-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
sparsevector.jl
1896 lines (1628 loc) · 58.2 KB
/
sparsevector.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: http://julialang.org/license
### Common definitions
import Base: scalarmax, scalarmin, sort, find, findnz
### The SparseVector
### Types
immutable SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
n::Int # the number of elements
nzind::Vector{Ti} # the indices of nonzeros
nzval::Vector{Tv} # the values of nonzeros
function SparseVector(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv})
n >= 0 || throw(ArgumentError("The number of elements must be non-negative."))
length(nzind) == length(nzval) ||
throw(ArgumentError("index and value vectors must be the same length"))
new(convert(Int, n), nzind, nzval)
end
end
SparseVector{Tv,Ti}(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv}) =
SparseVector{Tv,Ti}(n, nzind, nzval)
### Basic properties
length(x::SparseVector) = x.n
size(x::SparseVector) = (x.n,)
nnz(x::SparseVector) = length(x.nzval)
countnz(x::SparseVector) = countnz(x.nzval)
nonzeros(x::SparseVector) = x.nzval
nonzeroinds(x::SparseVector) = x.nzind
similar{T}(x::SparseVector, ::Type{T}, D::Dims) = spzeros(T, D...)
### Construct empty sparse vector
spzeros(len::Integer) = spzeros(Float64, len)
spzeros{T}(::Type{T}, len::Integer) = SparseVector(len, Int[], T[])
# Construction of same structure, but with all ones
spones{T}(x::SparseVector{T}) = SparseVector(x.n, copy(x.nzind), ones(T, length(x.nzval)))
### Construction from lists of indices and values
function _sparsevector!{Ti<:Integer}(I::Vector{Ti}, V::Vector, len::Integer)
# pre-condition: no duplicate indexes in I
if !isempty(I)
p = sortperm(I)
permute!(I, p)
permute!(V, p)
end
SparseVector(len, I, V)
end
function _sparsevector!{Tv,Ti<:Integer}(I::Vector{Ti}, V::Vector{Tv}, len::Integer, combine::Function)
if !isempty(I)
p = sortperm(I)
permute!(I, p)
permute!(V, p)
m = length(I)
r = 1
l = 1 # length of processed part
i = I[r] # row-index of current element
# main loop
while r < m
r += 1
i2 = I[r]
if i2 == i # accumulate r-th to the l-th entry
V[l] = combine(V[l], V[r])
else # advance l, and move r-th to l-th
pv = V[l]
l += 1
i = i2
if l < r
I[l] = i; V[l] = V[r]
end
end
end
if l < m
resize!(I, l)
resize!(V, l)
end
end
SparseVector(len, I, V)
end
"""
sparsevec(I, V, [m, combine])
Create a sparse vector `S` of length `m` such that `S[I[k]] = V[k]`.
Duplicates are combined using the `combine` function, which defaults to
`+` if no `combine` argument is provided, unless the elements of `V` are Booleans
in which case `combine` defaults to `|`.
"""
function sparsevec{Ti<:Integer}(I::AbstractVector{Ti}, V::AbstractVector, combine::Function)
length(I) == length(V) ||
throw(ArgumentError("index and value vectors must be the same length"))
len = 0
for i in I
i >= 1 || error("Index must be positive.")
if i > len
len = i
end
end
_sparsevector!(collect(I), collect(V), len, combine)
end
function sparsevec{Ti<:Integer}(I::AbstractVector{Ti}, V::AbstractVector, len::Integer, combine::Function)
length(I) == length(V) ||
throw(ArgumentError("index and value vectors must be the same length"))
for i in I
1 <= i <= len || throw(ArgumentError("An index is out of bound."))
end
_sparsevector!(collect(I), collect(V), len, combine)
end
sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}, args...) =
sparsevec(Vector{Int}(I), V, args...)
sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}) =
sparsevec(I, V, +)
sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}, len::Integer) =
sparsevec(I, V, len, +)
sparsevec(I::AbstractVector, V::Union{Bool, AbstractVector{Bool}}) =
sparsevec(I, V, |)
sparsevec(I::AbstractVector, V::Union{Bool, AbstractVector{Bool}}, len::Integer) =
sparsevec(I, V, len, |)
sparsevec(I::AbstractVector, v::Number, combine::Function) =
sparsevec(I, fill(v, length(I)), combine)
sparsevec(I::AbstractVector, v::Number, len::Integer, combine::Function) =
sparsevec(I, fill(v, length(I)), len, combine)
### Construction from dictionary
"""
sparsevec(D::Dict, [m])
Create a sparse vector of length `m` where the nonzero indices are keys from
the dictionary, and the nonzero values are the values from the dictionary.
"""
function sparsevec{Tv,Ti<:Integer}(dict::Associative{Ti,Tv})
m = length(dict)
nzind = Array{Ti}(m)
nzval = Array{Tv}(m)
cnt = 0
len = zero(Ti)
for (k, v) in dict
k >= 1 || throw(ArgumentError("index must be positive."))
if k > len
len = k
end
cnt += 1
@inbounds nzind[cnt] = k
@inbounds nzval[cnt] = v
end
resize!(nzind, cnt)
resize!(nzval, cnt)
_sparsevector!(nzind, nzval, len)
end
function sparsevec{Tv,Ti<:Integer}(dict::Associative{Ti,Tv}, len::Integer)
m = length(dict)
nzind = Array{Ti}(m)
nzval = Array{Tv}(m)
cnt = 0
maxk = convert(Ti, len)
for (k, v) in dict
1 <= k <= maxk || throw(ArgumentError("an index (key) is out of bound."))
cnt += 1
@inbounds nzind[cnt] = k
@inbounds nzval[cnt] = v
end
resize!(nzind, cnt)
resize!(nzval, cnt)
_sparsevector!(nzind, nzval, len)
end
### Element access
function setindex!{Tv,Ti<:Integer}(x::SparseVector{Tv,Ti}, v::Tv, i::Ti)
checkbounds(x, i)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
m = length(nzind)
k = searchsortedfirst(nzind, i)
if 1 <= k <= m && nzind[k] == i # i found
nzval[k] = v
else # i not found
if v != 0
insert!(nzind, k, i)
insert!(nzval, k, v)
end
end
x
end
setindex!{Tv, Ti<:Integer}(x::SparseVector{Tv,Ti}, v, i::Integer) =
setindex!(x, convert(Tv, v), convert(Ti, i))
### dropstored!
"""
dropstored!(x::SparseVector, i::Integer)
Drop entry `x[i]` from `x` if `x[i]` is stored and otherwise do nothing.
"""
function dropstored!(x::SparseVector, i::Integer)
if !(1 <= i <= x.n)
throw(BoundsError(x, i))
end
searchk = searchsortedfirst(x.nzind, i)
if searchk <= length(x.nzind) && x.nzind[searchk] == i
# Entry x[i] is stored. Drop and return.
deleteat!(x.nzind, searchk)
deleteat!(x.nzval, searchk)
end
return x
end
# TODO: Implement linear collection indexing methods for dropstored! ?
# TODO: Implement logical indexing methods for dropstored! ?
### Conversion
# convert SparseMatrixCSC to SparseVector
function convert{Tv,Ti<:Integer}(::Type{SparseVector{Tv,Ti}}, s::SparseMatrixCSC{Tv,Ti})
size(s, 2) == 1 || throw(ArgumentError("The input argument must have a single-column."))
SparseVector(s.m, s.rowval, s.nzval)
end
convert{Tv,Ti}(::Type{SparseVector{Tv}}, s::SparseMatrixCSC{Tv,Ti}) =
convert(SparseVector{Tv,Ti}, s)
convert{Tv,Ti}(::Type{SparseVector}, s::SparseMatrixCSC{Tv,Ti}) =
convert(SparseVector{Tv,Ti}, s)
# convert Vector to SparseVector
"""
sparsevec(A)
Convert a vector `A` into a sparse vector of length `m`.
"""
sparsevec{T}(a::AbstractVector{T}) = convert(SparseVector{T, Int}, a)
sparsevec(a::AbstractArray) = sparsevec(vec(a))
sparsevec(a::AbstractSparseArray) = vec(a)
sparse(a::AbstractVector) = sparsevec(a)
function _dense2sparsevec{Tv,Ti}(s::AbstractArray{Tv}, initcap::Ti)
# pre-condition: initcap > 0; the initcap determines the index type
n = length(s)
cap = initcap
nzind = Array{Ti}(cap)
nzval = Array{Tv}(cap)
c = 0
@inbounds for i = 1:n
v = s[i]
if v != 0
if c >= cap
cap *= 2
resize!(nzind, cap)
resize!(nzval, cap)
end
c += 1
nzind[c] = i
nzval[c] = v
end
end
if c < cap
resize!(nzind, c)
resize!(nzval, c)
end
SparseVector(n, nzind, nzval)
end
convert{Tv,Ti}(::Type{SparseVector{Tv,Ti}}, s::AbstractVector{Tv}) =
_dense2sparsevec(s, convert(Ti, max(8, div(length(s), 8))))
convert{Tv}(::Type{SparseVector{Tv}}, s::AbstractVector{Tv}) =
convert(SparseVector{Tv,Int}, s)
convert{Tv}(::Type{SparseVector}, s::AbstractVector{Tv}) =
convert(SparseVector{Tv,Int}, s)
# convert between different types of SparseVector
convert{Tv,Ti,TvS,TiS}(::Type{SparseVector{Tv,Ti}}, s::SparseVector{TvS,TiS}) =
SparseVector{Tv,Ti}(s.n, convert(Vector{Ti}, s.nzind), convert(Vector{Tv}, s.nzval))
convert{Tv,TvS,TiS}(::Type{SparseVector{Tv}}, s::SparseVector{TvS,TiS}) =
SparseVector{Tv,TiS}(s.n, s.nzind, convert(Vector{Tv}, s.nzval))
### copying
function prep_sparsevec_copy_dest!(A::SparseVector, lB, nnzB)
lA = length(A)
lA >= lB || throw(BoundsError())
# If the two vectors have the same length then all the elements in A will be overwritten.
if length(A) == lB
resize!(A.nzval, nnzB)
resize!(A.nzind, nnzB)
else
nnzA = nnz(A)
lastmodindA = searchsortedlast(A.nzind, lB)
if lastmodindA >= nnzB
# A will have fewer non-zero elements; unmodified elements are kept at the end.
deleteat!(A.nzind, nnzB+1:lastmodindA)
deleteat!(A.nzval, nnzB+1:lastmodindA)
else
# A will have more non-zero elements; unmodified elements are kept at the end.
resize!(A.nzind, nnzB + nnzA - lastmodindA)
resize!(A.nzval, nnzB + nnzA - lastmodindA)
copy!(A.nzind, nnzB+1, A.nzind, lastmodindA+1, nnzA-lastmodindA)
copy!(A.nzval, nnzB+1, A.nzval, lastmodindA+1, nnzA-lastmodindA)
end
end
end
function copy!(A::SparseVector, B::SparseVector)
prep_sparsevec_copy_dest!(A, length(B), nnz(B))
copy!(A.nzind, B.nzind)
copy!(A.nzval, B.nzval)
return A
end
function copy!(A::SparseVector, B::SparseMatrixCSC)
prep_sparsevec_copy_dest!(A, length(B), nnz(B))
ptr = 1
@assert length(A.nzind) >= length(B.rowval)
maximum(B.colptr)-1 <= length(B.rowval) || throw(BoundsError())
@inbounds for col=1:length(B.colptr)-1
offsetA = (col - 1) * B.m
while ptr <= B.colptr[col+1]-1
A.nzind[ptr] = B.rowval[ptr] + offsetA
ptr += 1
end
end
copy!(A.nzval, B.nzval)
return A
end
copy!{TvB, TiB}(A::SparseMatrixCSC, B::SparseVector{TvB,TiB}) =
copy!(A, SparseMatrixCSC{TvB,TiB}(B.n, 1, TiB[1, length(B.nzind)+1], B.nzind, B.nzval))
### Rand Construction
sprand{T}(n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) = sprand(GLOBAL_RNG, n, p, rfn, T)
function sprand{T}(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function, ::Type{T})
I = randsubseq(r, 1:convert(Int, n), p)
V = rfn(r, T, length(I))
SparseVector(n, I, V)
end
sprand(n::Integer, p::AbstractFloat, rfn::Function) = sprand(GLOBAL_RNG, n, p, rfn)
function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function)
I = randsubseq(r, 1:convert(Int, n), p)
V = rfn(r, length(I))
SparseVector(n, I, V)
end
sprand(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, rand)
sprand(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, rand)
sprand{T}(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) = sprand(r, n, p, (r, i) -> rand(r, T, i))
sprand(r::AbstractRNG, ::Type{Bool}, n::Integer, p::AbstractFloat) = sprand(r, n, p, truebools)
sprand{T}(::Type{T}, n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, T, n, p)
sprandn(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, randn)
sprandn(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, randn)
## Indexing into Matrices can return SparseVectors
# Column slices
function getindex(x::SparseMatrixCSC, ::Colon, j::Integer)
checkbounds(x, :, j)
r1 = convert(Int, x.colptr[j])
r2 = convert(Int, x.colptr[j+1]) - 1
SparseVector(x.m, x.rowval[r1:r2], x.nzval[r1:r2])
end
function getindex(x::SparseMatrixCSC, I::UnitRange, j::Integer)
checkbounds(x, I, j)
# Get the selected column
c1 = convert(Int, x.colptr[j])
c2 = convert(Int, x.colptr[j+1]) - 1
# Restrict to the selected rows
r1 = searchsortedfirst(x.rowval, first(I), c1, c2, Forward)
r2 = searchsortedlast(x.rowval, last(I), c1, c2, Forward)
SparseVector(length(I), x.rowval[r1:r2] - first(I) + 1, x.nzval[r1:r2])
end
# In the general case, we piggy back upon SparseMatrixCSC's optimized solution
@inline function getindex{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::Integer)
M = A[I, [J]]
SparseVector(M.m, M.rowval, M.nzval)
end
# Row slices
getindex(A::SparseMatrixCSC, i::Integer, ::Colon) = A[i, 1:end]
getindex{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, i::Integer, J::AbstractVector{Bool}) = A[i, find(J)]
function Base.getindex{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, i::Integer, J::AbstractVector)
checkbounds(A, i, J)
nJ = length(J)
colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval
nzinds = Array{Ti}(0)
nzvals = Array{Tv}(0)
# adapted from SparseMatrixCSC's sorted_bsearch_A
ptrI = 1
@inbounds for j = 1:nJ
col = J[j]
rowI = i
ptrA = Int(colptrA[col])
stopA = Int(colptrA[col+1]-1)
if ptrA <= stopA
if rowvalA[ptrA] <= rowI
ptrA = searchsortedfirst(rowvalA, rowI, ptrA, stopA, Base.Order.Forward)
if ptrA <= stopA && rowvalA[ptrA] == rowI
push!(nzinds, j)
push!(nzvals, nzvalA[ptrA])
end
end
ptrI += 1
end
end
return SparseVector(nJ, nzinds, nzvals)
end
# Logical and linear indexing into SparseMatrices
getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractVector{Bool}) = _logical_index(A, I) # Ambiguities
getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractArray{Bool}) = _logical_index(A, I)
function _logical_index{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractArray{Bool})
checkbounds(A, I)
n = sum(I)
nnzB = min(n, nnz(A))
colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval
rowvalB = Array{Int}(nnzB)
nzvalB = Array{Tv}(nnzB)
c = 1
rowB = 1
@inbounds for col in 1:A.n
r1 = colptrA[col]
r2 = colptrA[col+1]-1
for row in 1:A.m
if I[row, col]
while (r1 <= r2) && (rowvalA[r1] < row)
r1 += 1
end
if (r1 <= r2) && (rowvalA[r1] == row)
nzvalB[c] = nzvalA[r1]
rowvalB[c] = rowB
c += 1
end
rowB += 1
(rowB > n) && break
end
end
(rowB > n) && break
end
if nnzB > (c-1)
deleteat!(nzvalB, c:nnzB)
deleteat!(rowvalB, c:nnzB)
end
SparseVector(n, rowvalB, nzvalB)
end
# TODO: further optimizations are available for ::Colon and other types of Range
getindex(A::SparseMatrixCSC, ::Colon) = A[1:end]
function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::UnitRange)
checkbounds(A, I)
szA = size(A)
nA = szA[1]*szA[2]
colptrA = A.colptr
rowvalA = A.rowval
nzvalA = A.nzval
n = length(I)
nnzB = min(n, nnz(A))
rowvalB = Array{Int}(nnzB)
nzvalB = Array{Tv}(nnzB)
rowstart,colstart = ind2sub(szA, first(I))
rowend,colend = ind2sub(szA, last(I))
idxB = 1
@inbounds for col in colstart:colend
minrow = (col == colstart ? rowstart : 1)
maxrow = (col == colend ? rowend : szA[1])
for r in colptrA[col]:(colptrA[col+1]-1)
rowA = rowvalA[r]
if minrow <= rowA <= maxrow
rowvalB[idxB] = sub2ind(szA, rowA, col) - first(I) + 1
nzvalB[idxB] = nzvalA[r]
idxB += 1
end
end
end
if nnzB > (idxB-1)
deleteat!(nzvalB, idxB:nnzB)
deleteat!(rowvalB, idxB:nnzB)
end
SparseVector(n, rowvalB, nzvalB)
end
function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractVector)
szA = size(A)
nA = szA[1]*szA[2]
colptrA = A.colptr
rowvalA = A.rowval
nzvalA = A.nzval
n = length(I)
nnzB = min(n, nnz(A))
rowvalB = Array{Int}(nnzB)
nzvalB = Array{Tv}(nnzB)
idxB = 1
for i in 1:n
((I[i] < 1) | (I[i] > nA)) && throw(BoundsError(A, I))
row,col = ind2sub(szA, I[i])
for r in colptrA[col]:(colptrA[col+1]-1)
@inbounds if rowvalA[r] == row
if idxB <= nnzB
rowvalB[idxB] = i
nzvalB[idxB] = nzvalA[r]
idxB += 1
else # this can happen if there are repeated indices in I
push!(rowvalB, i)
push!(nzvalB, nzvalA[r])
end
break
end
end
end
if nnzB > (idxB-1)
deleteat!(nzvalB, idxB:nnzB)
deleteat!(rowvalB, idxB:nnzB)
end
SparseVector(n, rowvalB, nzvalB)
end
function find{Tv,Ti}(x::SparseVector{Tv,Ti})
numnz = nnz(x)
I = Array(Ti, numnz)
nzind = x.nzind
nzval = x.nzval
count = 1
@inbounds for i = 1 : numnz
if nzval[i] != 0
I[count] = nzind[i]
count += 1
end
end
count -= 1
if numnz != count
deleteat!(I, (count+1):numnz)
end
return I
end
function findnz{Tv,Ti}(x::SparseVector{Tv,Ti})
numnz = nnz(x)
I = Array(Ti, numnz)
V = Array(Tv, numnz)
nzind = x.nzind
nzval = x.nzval
count = 1
@inbounds for i = 1 : numnz
if nzval[i] != 0
I[count] = nzind[i]
V[count] = nzval[i]
count += 1
end
end
count -= 1
if numnz != count
deleteat!(I, (count+1):numnz)
deleteat!(V, (count+1):numnz)
end
return (I, V)
end
### Generic functions operating on AbstractSparseVector
### getindex
function _spgetindex{Tv,Ti}(m::Int, nzind::AbstractVector{Ti}, nzval::AbstractVector{Tv}, i::Integer)
ii = searchsortedfirst(nzind, convert(Ti, i))
(ii <= m && nzind[ii] == i) ? nzval[ii] : zero(Tv)
end
function getindex{Tv}(x::AbstractSparseVector{Tv}, i::Integer)
checkbounds(x, i)
_spgetindex(nnz(x), nonzeroinds(x), nonzeros(x), i)
end
function getindex{Tv,Ti}(x::AbstractSparseVector{Tv,Ti}, I::UnitRange)
checkbounds(x, I)
xlen = length(x)
i0 = first(I)
i1 = last(I)
xnzind = nonzeroinds(x)
xnzval = nonzeros(x)
m = length(xnzind)
# locate the first j0, s.t. xnzind[j0] >= i0
j0 = searchsortedfirst(xnzind, i0)
# locate the last j1, s.t. xnzind[j1] <= i1
j1 = searchsortedlast(xnzind, i1, j0, m, Forward)
# compute the number of non-zeros
jrgn = j0:j1
mr = length(jrgn)
rind = Array{Ti}(mr)
rval = Array{Tv}(mr)
if mr > 0
c = 0
for j in jrgn
c += 1
rind[c] = convert(Ti, xnzind[j] - i0 + 1)
rval[c] = xnzval[j]
end
end
SparseVector(length(I), rind, rval)
end
getindex{Tv,Ti}(x::AbstractSparseVector{Tv,Ti}, I::AbstractVector{Bool}) = x[find(I)]
getindex{Tv,Ti}(x::AbstractSparseVector{Tv,Ti}, I::AbstractArray{Bool}) = x[find(I)]
@inline function getindex{Tv,Ti}(x::AbstractSparseVector{Tv,Ti}, I::AbstractVector)
# SparseMatrixCSC has a nicely optimized routine for this; punt
S = SparseMatrixCSC(x.n, 1, [1,length(x.nzind)+1], x.nzind, x.nzval)
S[I, 1]
end
function getindex{Tv,Ti}(x::AbstractSparseVector{Tv,Ti}, I::AbstractArray)
# punt to SparseMatrixCSC
S = SparseMatrixCSC(x.n, 1, [1,length(x.nzind)+1], x.nzind, x.nzval)
S[I]
end
getindex(x::AbstractSparseVector, ::Colon) = copy(x)
### show and friends
function show(io::IO, ::MIME"text/plain", x::AbstractSparseVector)
println(io, summary(x))
show(io, x)
end
function show(io::IO, x::AbstractSparseVector)
# TODO: make this a one-line form
n = length(x)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
xnnz = length(nzind)
limit::Bool = get(io, :limit, false)
half_screen_rows = limit ? div(displaysize(io)[1] - 8, 2) : typemax(Int)
pad = ndigits(n)
sep = "\n\t"
io = IOContext(io)
if !haskey(io, :compact)
io = IOContext(io, :compact => true)
end
for k = 1:length(nzind)
if k < half_screen_rows || k > xnnz - half_screen_rows
print(io, " ", '[', rpad(nzind[k], pad), "] = ")
Base.show(io, nzval[k])
println(io)
elseif k == half_screen_rows
println(io, " ", " "^pad, " \u22ee")
end
end
end
function summary(x::AbstractSparseVector)
string("Sparse vector of length ", length(x), " with ", length(nonzeros(x)),
" ", eltype(x), " nonzero entries:")
end
### Conversion to matrix
function convert{TvD,TiD,Tv,Ti}(::Type{SparseMatrixCSC{TvD,TiD}}, x::AbstractSparseVector{Tv,Ti})
n = length(x)
xnzind = nonzeroinds(x)
xnzval = nonzeros(x)
m = length(xnzind)
colptr = TiD[1, m+1]
# Note that this *cannot* share data like normal array conversions, since
# modifying one would put the other in an inconsistent state
rowval = collect(TiD, xnzind)
nzval = collect(TvD, xnzval)
SparseMatrixCSC(n, 1, colptr, rowval, nzval)
end
convert{TvD,Tv,Ti}(::Type{SparseMatrixCSC{TvD}}, x::AbstractSparseVector{Tv,Ti}) =
convert(SparseMatrixCSC{TvD,Ti}, x)
convert{Tv,Ti}(::Type{SparseMatrixCSC}, x::AbstractSparseVector{Tv,Ti}) =
convert(SparseMatrixCSC{Tv,Ti}, x)
function convert{Tv}(::Type{Vector}, x::AbstractSparseVector{Tv})
n = length(x)
n == 0 && return Vector{Tv}(0)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
r = zeros(Tv, n)
for k in 1:nnz(x)
i = nzind[k]
v = nzval[k]
r[i] = v
end
return r
end
convert(::Type{Array}, x::AbstractSparseVector) = convert(Vector, x)
full(x::AbstractSparseVector) = convert(Array, x)
### Array manipulation
vec(x::AbstractSparseVector) = x
copy(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), copy(nonzeros(x)))
function reinterpret{T,Tv}(::Type{T}, x::AbstractSparseVector{Tv})
sizeof(T) == sizeof(Tv) ||
throw(ArgumentError("reinterpret of sparse vectors only supports element types of the same size."))
SparseVector(length(x), copy(nonzeroinds(x)), reinterpret(T, nonzeros(x)))
end
float{Tv<:AbstractFloat}(x::AbstractSparseVector{Tv}) = x
float(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), float(nonzeros(x)))
complex{Tv<:Complex}(x::AbstractSparseVector{Tv}) = x
complex(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), complex(nonzeros(x)))
### Concatenation
# Without the first of these methods, horizontal concatenations of SparseVectors fall
# back to the horizontal concatenation method that ensures that combinations of
# sparse/special/dense matrix/vector types concatenate to SparseMatrixCSCs, instead
# of _absspvec_hcat below. The <:Integer qualifications are necessary for correct dispatch.
hcat{Tv,Ti<:Integer}(X::SparseVector{Tv,Ti}...) = _absspvec_hcat(X...)
hcat{Tv,Ti<:Integer}(X::AbstractSparseVector{Tv,Ti}...) = _absspvec_hcat(X...)
function _absspvec_hcat{Tv,Ti}(X::AbstractSparseVector{Tv,Ti}...)
# check sizes
n = length(X)
m = length(X[1])
tnnz = nnz(X[1])
for j = 2:n
length(X[j]) == m ||
throw(DimensionMismatch("Inconsistent column lengths."))
tnnz += nnz(X[j])
end
# construction
colptr = Array{Ti}(n+1)
nzrow = Array{Ti}(tnnz)
nzval = Array{Tv}(tnnz)
roff = 1
@inbounds for j = 1:n
xj = X[j]
xnzind = nonzeroinds(xj)
xnzval = nonzeros(xj)
colptr[j] = roff
copy!(nzrow, roff, xnzind)
copy!(nzval, roff, xnzval)
roff += length(xnzind)
end
colptr[n+1] = roff
SparseMatrixCSC{Tv,Ti}(m, n, colptr, nzrow, nzval)
end
# Without the first of these methods, vertical concatenations of SparseVectors fall
# back to the vertical concatenation method that ensures that combinations of
# sparse/special/dense matrix/vector types concatenate to SparseMatrixCSCs, instead
# of _absspvec_vcat below. The <:Integer qualifications are necessary for correct dispatch.
vcat{Tv,Ti<:Integer}(X::SparseVector{Tv,Ti}...) = _absspvec_vcat(X...)
vcat{Tv,Ti<:Integer}(X::AbstractSparseVector{Tv,Ti}...) = _absspvec_vcat(X...)
function _absspvec_vcat{Tv,Ti}(X::AbstractSparseVector{Tv,Ti}...)
# check sizes
n = length(X)
tnnz = 0
for j = 1:n
tnnz += nnz(X[j])
end
# construction
rnzind = Array{Ti}(tnnz)
rnzval = Array{Tv}(tnnz)
ir = 0
len = 0
@inbounds for j = 1:n
xj = X[j]
xnzind = nonzeroinds(xj)
xnzval = nonzeros(xj)
xnnz = length(xnzind)
for i = 1:xnnz
rnzind[ir + i] = xnzind[i] + len
end
copy!(rnzval, ir+1, xnzval)
ir += xnnz
len += length(xj)
end
SparseVector(len, rnzind, rnzval)
end
hcat(Xin::Union{Vector, AbstractSparseVector}...) = hcat(map(sparse, Xin)...)
vcat(Xin::Union{Vector, AbstractSparseVector}...) = vcat(map(sparse, Xin)...)
### Concatenation of un/annotated sparse/special/dense vectors/matrices
# TODO: These methods and definitions should be moved to a more appropriate location,
# particularly some future equivalent of base/linalg/special.jl dedicated to interactions
# between a broader set of matrix types.
# TODO: A definition similar to the third exists in base/linalg/bidiag.jl. These definitions
# should be consolidated in a more appropriate location, e.g. base/linalg/special.jl.
typealias _SparseArrays Union{SparseVector, SparseMatrixCSC}
typealias _SpecialArrays Union{Diagonal, Bidiagonal, Tridiagonal, SymTridiagonal}
typealias _SparseConcatArrays Union{_SpecialArrays, _SparseArrays}
typealias _Symmetric_SparseConcatArrays{T,A<:_SparseConcatArrays} Symmetric{T,A}
typealias _Hermitian_SparseConcatArrays{T,A<:_SparseConcatArrays} Hermitian{T,A}
typealias _Triangular_SparseConcatArrays{T,A<:_SparseConcatArrays} Base.LinAlg.AbstractTriangular{T,A}
typealias _Annotated_SparseConcatArrays Union{_Triangular_SparseConcatArrays, _Symmetric_SparseConcatArrays, _Hermitian_SparseConcatArrays}
typealias _Symmetric_DenseArrays{T,A<:Matrix} Symmetric{T,A}
typealias _Hermitian_DenseArrays{T,A<:Matrix} Hermitian{T,A}
typealias _Triangular_DenseArrays{T,A<:Matrix} Base.LinAlg.AbstractTriangular{T,A}
typealias _Annotated_DenseArrays Union{_Triangular_DenseArrays, _Symmetric_DenseArrays, _Hermitian_DenseArrays}
typealias _Annotated_Typed_DenseArrays{T} Union{_Triangular_DenseArrays{T}, _Symmetric_DenseArrays{T}, _Hermitian_DenseArrays{T}}
typealias _SparseConcatGroup Union{Vector, Matrix, _SparseConcatArrays, _Annotated_SparseConcatArrays, _Annotated_DenseArrays}
typealias _DenseConcatGroup Union{Vector, Matrix, _Annotated_DenseArrays}
typealias _TypedDenseConcatGroup{T} Union{Vector{T}, Matrix{T}, _Annotated_Typed_DenseArrays{T}}
# Concatenations involving un/annotated sparse/special matrices/vectors should yield sparse arrays
function cat(catdims, Xin::_SparseConcatGroup...)
X = SparseMatrixCSC[issparse(x) ? x : sparse(x) for x in Xin]
T = promote_eltype(Xin...)
Base.cat_t(catdims, T, X...)
end
function hcat(Xin::_SparseConcatGroup...)
X = SparseMatrixCSC[issparse(x) ? x : sparse(x) for x in Xin]
hcat(X...)
end
function vcat(Xin::_SparseConcatGroup...)
X = SparseMatrixCSC[issparse(x) ? x : sparse(x) for x in Xin]
vcat(X...)
end
function hvcat(rows::Tuple{Vararg{Int}}, X::_SparseConcatGroup...)
nbr = length(rows) # number of block rows
tmp_rows = Array{SparseMatrixCSC}(nbr)
k = 0
@inbounds for i = 1 : nbr
tmp_rows[i] = hcat(X[(1 : rows[i]) + k]...)
k += rows[i]
end
vcat(tmp_rows...)
end
# Concatenations strictly involving un/annotated dense matrices/vectors should yield dense arrays
cat(catdims, xs::_DenseConcatGroup...) = Base.cat_t(catdims, promote_eltype(xs...), xs...)
vcat(A::_DenseConcatGroup...) = Base.typed_vcat(promote_eltype(A...), A...)
hcat(A::_DenseConcatGroup...) = Base.typed_hcat(promote_eltype(A...), A...)
hvcat(rows::Tuple{Vararg{Int}}, xs::_DenseConcatGroup...) = Base.typed_hvcat(promote_eltype(xs...), rows, xs...)
# For performance, specially handle the case where the matrices/vectors have homogeneous eltype
cat{T}(catdims, xs::_TypedDenseConcatGroup{T}...) = Base.cat_t(catdims, T, xs...)
vcat{T}(A::_TypedDenseConcatGroup{T}...) = Base.typed_vcat(T, A...)
hcat{T}(A::_TypedDenseConcatGroup{T}...) = Base.typed_hcat(T, A...)
hvcat{T}(rows::Tuple{Vararg{Int}}, xs::_TypedDenseConcatGroup{T}...) = Base.typed_hvcat(T, rows, xs...)
### math functions
### Unary Map
# zero-preserving functions (z->z, nz->nz)
broadcast(::typeof(abs), x::AbstractSparseVector) = SparseVector(length(x), copy(nonzeroinds(x)), abs.(nonzeros(x)))
for op in [:abs2, :conj]
@eval begin
$(op)(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), $(op).(nonzeros(x)))
end
end
-(x::AbstractSparseVector) = SparseVector(length(x), copy(nonzeroinds(x)), -(nonzeros(x)))
# functions f, such that
# f(x) can be zero or non-zero when x != 0
# f(x) = 0 when x == 0
#
macro unarymap_nz2z_z2z(op, TF)
esc(quote
function $(op){Tv<:$(TF),Ti<:Integer}(x::AbstractSparseVector{Tv,Ti})
R = typeof($(op)(zero(Tv)))
xnzind = nonzeroinds(x)
xnzval = nonzeros(x)
m = length(xnzind)
ynzind = Array{Ti}(m)
ynzval = Array{R}(m)
ir = 0
@inbounds for j = 1:m
i = xnzind[j]
v = $(op)(xnzval[j])
if v != zero(v)
ir += 1
ynzind[ir] = i
ynzval[ir] = v
end
end
resize!(ynzind, ir)
resize!(ynzval, ir)
SparseVector(length(x), ynzind, ynzval)
end
end)
end
real{T<:Real}(x::AbstractSparseVector{T}) = x
@unarymap_nz2z_z2z real Complex
imag{Tv<:Real,Ti<:Integer}(x::AbstractSparseVector{Tv,Ti}) = SparseVector(length(x), Ti[], Tv[])
@unarymap_nz2z_z2z imag Complex
for op in [:floor, :ceil, :trunc, :round]
@eval @unarymap_nz2z_z2z $(op) Real
end
for op in [:log1p, :expm1,
:sin, :tan, :sinpi, :sind, :tand,
:asin, :atan, :asind, :atand,
:sinh, :tanh, :asinh, :atanh]
@eval @unarymap_nz2z_z2z $(op) Number
end
# function that does not preserve zeros
macro unarymap_z2nz(op, TF)
esc(quote
function $(op){Tv<:$(TF),Ti<:Integer}(x::AbstractSparseVector{Tv,Ti})
v0 = $(op)(zero(Tv))
R = typeof(v0)
xnzind = nonzeroinds(x)
xnzval = nonzeros(x)
n = length(x)
m = length(xnzind)
y = fill(v0, n)
@inbounds for j = 1:m
y[xnzind[j]] = $(op)(xnzval[j])
end
y
end
end)
end
for op in [:exp, :exp2, :exp10, :log, :log2, :log10,
:cos, :csc, :cot, :sec, :cospi,
:cosd, :cscd, :cotd, :secd,
:acos, :acot, :acosd, :acotd,
:cosh, :csch, :coth, :sech,
:acsch, :asech]
@eval @unarymap_z2nz $(op) Number
end