-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
sparsevector.jl
2089 lines (1800 loc) · 69.7 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: https://julialang.org/license
### Common definitions
import Base: sort, findall, copy!
import LinearAlgebra: promote_to_array_type, promote_to_arrays_
### The SparseVector
### Types
"""
SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
Vector type for storing sparse vectors.
"""
struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
n::Int # Length of the sparse vector
nzind::Vector{Ti} # Indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
function SparseVector{Tv,Ti}(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti<:Integer}
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(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti} =
SparseVector{Tv,Ti}(n, nzind, nzval)
# Define an alias for a view of a whole column of a SparseMatrixCSC. Many methods can be written for the
# union of such a view and a SparseVector so we define an alias for such a union as well
const SparseColumnView{T} = SubArray{T,1,<:AbstractSparseMatrixCSC,Tuple{Base.Slice{Base.OneTo{Int}},Int},false}
const SparseVectorUnion{T} = Union{SparseVector{T}, SparseColumnView{T}}
const AdjOrTransSparseVectorUnion{T} = LinearAlgebra.AdjOrTrans{T, <:SparseVectorUnion{T}}
### Basic properties
size(x::SparseVector) = (getfield(x, :n),)
nnz(x::SparseVector) = length(nonzeros(x))
count(f, x::SparseVector) = count(f, nonzeros(x)) + f(zero(eltype(x)))*(length(x) - nnz(x))
nonzeros(x::SparseVector) = getfield(x, :nzval)
function nonzeros(x::SparseColumnView)
rowidx, colidx = parentindices(x)
A = parent(x)
@inbounds y = view(nonzeros(A), nzrange(A, colidx))
return y
end
nonzeroinds(x::SparseVector) = getfield(x, :nzind)
function nonzeroinds(x::SparseColumnView)
rowidx, colidx = parentindices(x)
A = parent(x)
@inbounds y = view(rowvals(A), nzrange(A, colidx))
return y
end
indtype(x::SparseColumnView) = indtype(parent(x))
function nnz(x::SparseColumnView)
rowidx, colidx = parentindices(x)
return length(nzrange(parent(x), colidx))
end
## similar
#
# parent method for similar that preserves stored-entry structure (for when new and old dims match)
_sparsesimilar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}) where {TvNew,TiNew} =
SparseVector(length(S), copyto!(similar(nonzeroinds(S), TiNew), nonzeroinds(S)), similar(nonzeros(S), TvNew))
# parent method for similar that preserves nothing (for when old and new dims differ, and new is 1d)
_sparsesimilar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}, dims::Dims{1}) where {TvNew,TiNew} =
SparseVector(dims..., similar(nonzeroinds(S), TiNew, 0), similar(nonzeros(S), TvNew, 0))
# parent method for similar that preserves storage space (for old and new dims differ, and new is 2d)
_sparsesimilar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}, dims::Dims{2}) where {TvNew,TiNew} =
SparseMatrixCSC(dims..., fill(one(TiNew), last(dims)+1), similar(nonzeroinds(S), TiNew), similar(nonzeros(S), TvNew))
# The following methods hook into the AbstractArray similar hierarchy. The first method
# covers similar(A[, Tv]) calls, which preserve stored-entry structure, and the latter
# methods cover similar(A[, Tv], shape...) calls, which preserve nothing if the dims
# specify a SparseVector result and storage space if the dims specify a SparseMatrixCSC result.
similar(S::SparseVector{<:Any,Ti}, ::Type{TvNew}) where {Ti,TvNew} =
_sparsesimilar(S, TvNew, Ti)
similar(S::SparseVector{<:Any,Ti}, ::Type{TvNew}, dims::Union{Dims{1},Dims{2}}) where {Ti,TvNew} =
_sparsesimilar(S, TvNew, Ti, dims)
# The following methods cover similar(A, Tv, Ti[, shape...]) calls, which specify the
# result's index type in addition to its entry type, and aren't covered by the hooks above.
# The calls without shape again preserve stored-entry structure, whereas those with
# one-dimensional shape preserve nothing, and those with two-dimensional shape
# preserve storage space.
similar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}) where{TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew)
similar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}, dims::Union{Dims{1},Dims{2}}) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, dims)
similar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}, m::Integer) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, (m,))
similar(S::SparseVector, ::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, (m, n))
## Alias detection and prevention
using Base: dataids, unaliascopy
Base.dataids(S::SparseVector) = (dataids(nonzeroinds(S))..., dataids(nonzeros(S))...)
Base.unaliascopy(S::SparseVector) = typeof(S)(length(S), unaliascopy(nonzeroinds(S)), unaliascopy(nonzeros(S)))
### Construct empty sparse vector
spzeros(len::Integer) = spzeros(Float64, len)
spzeros(::Type{T}, len::Integer) where {T} = SparseVector(len, Int[], T[])
spzeros(::Type{Tv}, ::Type{Ti}, len::Integer) where {Tv,Ti<:Integer} = SparseVector(len, Ti[], Tv[])
LinearAlgebra.fillstored!(x::SparseVector, y) = (fill!(nonzeros(x), y); x)
### Construction from lists of indices and values
function _sparsevector!(I::Vector{<:Integer}, V::Vector, len::Integer)
# pre-condition: no duplicate indices in I
if !isempty(I)
p = sortperm(I)
permute!(I, p)
permute!(V, p)
end
SparseVector(len, I, V)
end
function _sparsevector!(I::Vector{<:Integer}, V::Vector, 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 `|`.
# Examples
```jldoctest
julia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2];
julia> sparsevec(II, V)
5-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 0.1
[3] = 0.5
[5] = 0.2
julia> sparsevec(II, V, 8, -)
8-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 0.1
[3] = -0.1
[5] = 0.2
julia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false])
3-element SparseVector{Bool,Int64} with 3 stored entries:
[1] = 1
[2] = 0
[3] = 1
```
"""
function sparsevec(I::AbstractVector{<:Integer}, V::AbstractVector, combine::Function)
require_one_based_indexing(I, V)
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!(Vector(I), Vector(V), len, combine)
end
function sparsevec(I::AbstractVector{<:Integer}, V::AbstractVector, len::Integer, combine::Function)
require_one_based_indexing(I, V)
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!(Vector(I), Vector(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.
# Examples
```jldoctest
julia> sparsevec(Dict(1 => 3, 2 => 2))
2-element SparseVector{Int64,Int64} with 2 stored entries:
[1] = 3
[2] = 2
```
"""
function sparsevec(dict::AbstractDict{Ti,Tv}) where {Tv,Ti<:Integer}
m = length(dict)
nzind = Vector{Ti}(undef, m)
nzval = Vector{Tv}(undef, 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(dict::AbstractDict{Ti,Tv}, len::Integer) where {Tv,Ti<:Integer}
m = length(dict)
nzind = Vector{Ti}(undef, m)
nzval = Vector{Tv}(undef, 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!(x::SparseVector{Tv,Ti}, v::Tv, i::Ti) where {Tv,Ti<:Integer}
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 !iszero(v)
insert!(nzind, k, i)
insert!(nzval, k, v)
end
end
x
end
setindex!(x::SparseVector{Tv,Ti}, v, i::Integer) where {Tv,Ti<: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.
# Examples
```jldoctest
julia> x = sparsevec([1, 3], [1.0, 2.0])
3-element SparseVector{Float64,Int64} with 2 stored entries:
[1] = 1.0
[3] = 2.0
julia> SparseArrays.dropstored!(x, 3)
3-element SparseVector{Float64,Int64} with 1 stored entry:
[1] = 1.0
julia> SparseArrays.dropstored!(x, 2)
3-element SparseVector{Float64,Int64} with 1 stored entry:
[1] = 1.0
```
"""
function dropstored!(x::SparseVector, i::Integer)
if !(1 <= i <= length(x::SparseVector))
throw(BoundsError(x, i))
end
searchk = searchsortedfirst(nonzeroinds(x), i)
if searchk <= length(nonzeroinds(x)) && nonzeroinds(x)[searchk] == i
# Entry x[i] is stored. Drop and return.
deleteat!(nonzeroinds(x), searchk)
deleteat!(nonzeros(x), 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 SparseVector{Tv,Ti}(s::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv,Ti<:Integer}
size(s, 2) == 1 || throw(ArgumentError("The input argument must have a single-column."))
SparseVector(size(s, 1), rowvals(s), nonzeros(s))
end
SparseVector{Tv}(s::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = SparseVector{Tv,Ti}(s)
SparseVector(s::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = SparseVector{Tv,Ti}(s)
# convert Vector to SparseVector
"""
sparsevec(A)
Convert a vector `A` into a sparse vector of length `m`.
# Examples
```jldoctest
julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0])
6-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 1.0
[2] = 2.0
[5] = 3.0
```
"""
sparsevec(a::AbstractVector{T}) where {T} = SparseVector{T, Int}(a)
sparsevec(a::AbstractArray) = sparsevec(vec(a))
sparsevec(a::AbstractSparseArray) = vec(a)
sparsevec(a::AbstractSparseVector) = vec(a)
sparse(a::AbstractVector) = sparsevec(a)
function _dense2indval!(nzind::Vector{Ti}, nzval::Vector{Tv}, s::AbstractArray{Tv}) where {Tv,Ti}
require_one_based_indexing(s)
cap = length(nzind);
@assert cap == length(nzval)
n = length(s)
c = 0
@inbounds for i = 1:n
v = s[i]
if !iszero(v)
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
return (nzind, nzval)
end
function _dense2sparsevec(s::AbstractArray{Tv}, initcap::Ti) where {Tv,Ti}
nzind, nzval = _dense2indval!(Vector{Ti}(undef, initcap), Vector{Tv}(undef, initcap), s)
SparseVector(length(s), nzind, nzval)
end
SparseVector{Tv,Ti}(s::AbstractVector{Tv}) where {Tv,Ti} =
_dense2sparsevec(s, convert(Ti, max(8, div(length(s), 8))))
SparseVector{Tv}(s::AbstractVector{Tv}) where {Tv} = SparseVector{Tv,Int}(s)
SparseVector(s::AbstractVector{Tv}) where {Tv} = SparseVector{Tv,Int}(s)
# convert between different types of SparseVector
SparseVector{Tv}(s::SparseVector{Tv}) where {Tv} = s
SparseVector{Tv,Ti}(s::SparseVector{Tv,Ti}) where {Tv,Ti} = s
SparseVector{Tv,Ti}(s::SparseVector) where {Tv,Ti} =
SparseVector{Tv,Ti}(length(s::SparseVector), convert(Vector{Ti}, nonzeroinds(s)), convert(Vector{Tv}, nonzeros(s)))
SparseVector{Tv}(s::SparseVector{<:Any,Ti}) where {Tv,Ti} =
SparseVector{Tv,Ti}(length(s::SparseVector), nonzeroinds(s), convert(Vector{Tv}, nonzeros(s)))
convert(T::Type{<:SparseVector}, m::AbstractVector) = m isa T ? m : T(m)
convert(T::Type{<:SparseVector}, m::AbstractSparseMatrixCSC) = T(m)
convert(T::Type{<:AbstractSparseMatrixCSC}, v::SparseVector) = T(v)
### 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!(nonzeros(A), nnzB)
resize!(nonzeroinds(A), nnzB)
else
nnzA = nnz(A)
lastmodindA = searchsortedlast(nonzeroinds(A), lB)
if lastmodindA >= nnzB
# A will have fewer non-zero elements; unmodified elements are kept at the end.
deleteat!(nonzeroinds(A), nnzB+1:lastmodindA)
deleteat!(nonzeros(A), nnzB+1:lastmodindA)
else
# A will have more non-zero elements; unmodified elements are kept at the end.
resize!(nonzeroinds(A), nnzB + nnzA - lastmodindA)
resize!(nonzeros(A), nnzB + nnzA - lastmodindA)
copyto!(nonzeroinds(A), nnzB+1, nonzeroinds(A), lastmodindA+1, nnzA-lastmodindA)
copyto!(nonzeros(A), nnzB+1, nonzeros(A), lastmodindA+1, nnzA-lastmodindA)
end
end
end
function copyto!(A::SparseVector, B::SparseVector)
prep_sparsevec_copy_dest!(A, length(B), nnz(B))
copyto!(nonzeroinds(A), nonzeroinds(B))
copyto!(nonzeros(A), nonzeros(B))
return A
end
copyto!(A::SparseVector, B::AbstractVector) = copyto!(A, sparsevec(B))
function copyto!(A::SparseVector, B::AbstractSparseMatrixCSC)
prep_sparsevec_copy_dest!(A, length(B), nnz(B))
ptr = 1
@assert length(nonzeroinds(A)) >= length(rowvals(B))
maximum(getcolptr(B))-1 <= length(rowvals(B)) || throw(BoundsError())
@inbounds for col=1:length(getcolptr(B))-1
offsetA = (col - 1) * size(B, 1)
while ptr <= getcolptr(B)[col+1]-1
nonzeroinds(A)[ptr] = rowvals(B)[ptr] + offsetA
ptr += 1
end
end
copyto!(nonzeros(A), nonzeros(B))
return A
end
copyto!(A::AbstractSparseMatrixCSC, B::SparseVector{TvB,TiB}) where {TvB,TiB} =
copyto!(A, SparseMatrixCSC{TvB,TiB}(length(B), 1, TiB[1, length(nonzeroinds(B))+1], nonzeroinds(B), nonzeros(B)))
### Rand Construction
sprand(n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where {T} = sprand(default_rng(), n, p, rfn, T)
function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where 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(default_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(default_rng(), n, p, rand)
sprand(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, rand)
sprand(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) where {T} = 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(::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(default_rng(), T, n, p)
sprandn(n::Integer, p::AbstractFloat) = sprand(default_rng(), n, p, randn)
sprandn(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, randn)
sprandn(::Type{T}, n::Integer, p::AbstractFloat) where T = sprand(default_rng(), n, p, (r, i) -> randn(r, T, i))
sprandn(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) where T = sprand(r, n, p, (r, i) -> randn(r, T, i))
## Indexing into Matrices can return SparseVectors
# Column slices
function getindex(x::AbstractSparseMatrixCSC, ::Colon, j::Integer)
checkbounds(x, :, j)
r1 = convert(Int, getcolptr(x)[j])
r2 = convert(Int, getcolptr(x)[j+1]) - 1
SparseVector(size(x, 1), rowvals(x)[r1:r2], nonzeros(x)[r1:r2])
end
function getindex(x::AbstractSparseMatrixCSC, I::AbstractUnitRange, j::Integer)
checkbounds(x, I, j)
# Get the selected column
c1 = convert(Int, getcolptr(x)[j])
c2 = convert(Int, getcolptr(x)[j+1]) - 1
# Restrict to the selected rows
r1 = searchsortedfirst(rowvals(x), first(I), c1, c2, Forward)
r2 = searchsortedlast(rowvals(x), last(I), c1, c2, Forward)
SparseVector(length(I), [rowvals(x)[i] - first(I) + 1 for i = r1:r2], nonzeros(x)[r1:r2])
end
# In the general case, we piggy back upon SparseMatrixCSC's optimized solution
@inline function getindex(A::AbstractSparseMatrixCSC, I::AbstractVector, J::Integer)
M = A[I, [J]]
SparseVector(size(M, 1), rowvals(M), nonzeros(M))
end
# Row slices
getindex(A::AbstractSparseMatrixCSC, i::Integer, ::Colon) = A[i, 1:end]
function Base.getindex(A::AbstractSparseMatrixCSC{Tv,Ti}, i::Integer, J::AbstractVector) where {Tv,Ti}
require_one_based_indexing(A, J)
checkbounds(A, i, J)
nJ = length(J)
colptrA = getcolptr(A); rowvalA = rowvals(A); nzvalA = nonzeros(A)
nzinds = Vector{Ti}()
nzvals = Vector{Tv}()
# 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(A::AbstractSparseMatrixCSC, I::AbstractVector{Bool}) = _logical_index(A, I) # Ambiguities
getindex(A::AbstractSparseMatrixCSC, I::AbstractArray{Bool}) = _logical_index(A, I)
function _logical_index(A::AbstractSparseMatrixCSC{Tv}, I::AbstractArray{Bool}) where Tv
require_one_based_indexing(A, I)
checkbounds(A, I)
n = sum(I)
nnzB = min(n, nnz(A))
colptrA = getcolptr(A); rowvalA = rowvals(A); nzvalA = nonzeros(A)
rowvalB = Vector{Int}(undef, nnzB)
nzvalB = Vector{Tv}(undef, nnzB)
c = 1
rowB = 1
@inbounds for col in 1:size(A, 2)
r1 = colptrA[col]
r2 = colptrA[col+1]-1
for row in 1:size(A, 1)
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 AbstractRange
getindex(A::AbstractSparseMatrixCSC, ::Colon) = A[1:end]
function getindex(A::AbstractSparseMatrixCSC{Tv}, I::AbstractUnitRange) where Tv
require_one_based_indexing(A, I)
checkbounds(A, I)
szA = size(A)
nA = szA[1]*szA[2]
colptrA = getcolptr(A)
rowvalA = rowvals(A)
nzvalA = nonzeros(A)
n = length(I)
nnzB = min(n, nnz(A))
rowvalB = Vector{Int}(undef, nnzB)
nzvalB = Vector{Tv}(undef, nnzB)
rowstart,colstart = Base._ind2sub(szA, first(I))
rowend,colend = Base._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] = Base._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(A::AbstractSparseMatrixCSC{Tv,Ti}, I::AbstractVector) where {Tv,Ti}
require_one_based_indexing(A, I)
@boundscheck checkbounds(A, I)
szA = size(A)
nA = szA[1]*szA[2]
colptrA = getcolptr(A)
rowvalA = rowvals(A)
nzvalA = nonzeros(A)
n = length(I)
nnzB = min(n, nnz(A))
rowvalB = Vector{Ti}(undef, nnzB)
nzvalB = Vector{Tv}(undef, nnzB)
idxB = 1
for i in 1:n
row,col = Base._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
Base.copy(a::SubArray{<:Any,<:Any,<:Union{SparseVector, AbstractSparseMatrixCSC}}) = a.parent[a.indices...]
function findall(x::SparseVector)
return findall(identity, x)
end
function findall(p::Function, x::SparseVector{<:Any,Ti}) where Ti
if p(zero(eltype(x)))
return invoke(findall, Tuple{Function, Any}, p, x)
end
numnz = nnz(x)
I = Vector{Ti}(undef, numnz)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
count = 1
@inbounds for i = 1 : numnz
if p(nzval[i])
I[count] = nzind[i]
count += 1
end
end
count -= 1
if numnz != count
deleteat!(I, (count+1):numnz)
end
return I
end
findall(p::Base.Fix2{typeof(in)}, x::SparseVector{<:Any,Ti}) where {Ti} =
invoke(findall, Tuple{Base.Fix2{typeof(in)}, AbstractArray}, p, x)
function findnz(x::SparseVector{Tv,Ti}) where {Tv,Ti}
numnz = nnz(x)
I = Vector{Ti}(undef, numnz)
V = Vector{Tv}(undef, numnz)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
@inbounds for i = 1 : numnz
I[i] = nzind[i]
V[i] = nzval[i]
end
return (I, V)
end
function _sparse_findnextnz(v::SparseVector, i::Integer)
n = searchsortedfirst(nonzeroinds(v), i)
if n > length(nonzeroinds(v))
return nothing
else
return nonzeroinds(v)[n]
end
end
function _sparse_findprevnz(v::SparseVector, i::Integer)
n = searchsortedlast(nonzeroinds(v), i)
if iszero(n)
return nothing
else
return nonzeroinds(v)[n]
end
end
### Generic functions operating on AbstractSparseVector
### getindex
function _spgetindex(m::Int, nzind::AbstractVector{Ti}, nzval::AbstractVector{Tv}, i::Integer) where {Tv,Ti}
ii = searchsortedfirst(nzind, convert(Ti, i))
(ii <= m && nzind[ii] == i) ? nzval[ii] : zero(Tv)
end
function getindex(x::AbstractSparseVector, i::Integer)
checkbounds(x, i)
_spgetindex(nnz(x), nonzeroinds(x), nonzeros(x), i)
end
function getindex(x::AbstractSparseVector{Tv,Ti}, I::AbstractUnitRange) where {Tv,Ti}
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 = Vector{Ti}(undef, mr)
rval = Vector{Tv}(undef, 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(x::AbstractSparseVector, I::AbstractVector{Bool}) = x[findall(I)]
getindex(x::AbstractSparseVector, I::AbstractArray{Bool}) = x[findall(I)]
@inline function getindex(x::AbstractSparseVector{Tv,Ti}, I::AbstractVector) where {Tv,Ti}
# SparseMatrixCSC has a nicely optimized routine for this; punt
S = SparseMatrixCSC(length(x::SparseVector), 1, Ti[1,length(nonzeroinds(x))+1], nonzeroinds(x), nonzeros(x))
S[I, 1]
end
function getindex(x::AbstractSparseVector{Tv,Ti}, I::AbstractArray) where {Tv,Ti}
# punt to SparseMatrixCSC
S = SparseMatrixCSC(length(x::SparseVector), 1, Ti[1,length(nonzeroinds(x))+1], nonzeroinds(x), nonzeros(x))
S[I]
end
getindex(x::AbstractSparseVector, ::Colon) = copy(x)
### show and friends
function show(io::IO, ::MIME"text/plain", x::AbstractSparseVector)
xnnz = length(nonzeros(x))
print(io, length(x), "-element ", typeof(x), " with ", xnnz,
" stored ", xnnz == 1 ? "entry" : "entries")
if xnnz != 0
println(io, ":")
show(IOContext(io, :typeinfo => eltype(x)), x)
end
end
show(io::IO, x::AbstractSparseVector) = show(convert(IOContext, io), x)
function show(io::IOContext, x::AbstractSparseVector)
# TODO: make this a one-line form
n = length(x)
nzind = nonzeroinds(x)
nzval = nonzeros(x)
if isempty(nzind)
return show(io, MIME("text/plain"), x)
end
limit::Bool = get(io, :limit, false)
half_screen_rows = limit ? div(displaysize(io)[1] - 8, 2) : typemax(Int)
pad = ndigits(n)
if !haskey(io, :compact)
io = IOContext(io, :compact => true)
end
for k = eachindex(nzind)
if k < half_screen_rows || k > length(nzind) - half_screen_rows
print(io, " ", '[', rpad(nzind[k], pad), "] = ")
if isassigned(nzval, Int(k))
show(io, nzval[k])
else
print(io, Base.undef_ref_str)
end
k != length(nzind) && println(io)
elseif k == half_screen_rows
println(io, " ", " "^pad, " \u22ee")
end
end
end
### Conversion to matrix
function SparseMatrixCSC{Tv,Ti}(x::AbstractSparseVector) where {Tv,Ti}
require_one_based_indexing(x)
n = length(x)
xnzind = nonzeroinds(x)
xnzval = nonzeros(x)
m = length(xnzind)
colptr = Ti[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 = Vector{Ti}(xnzind)
nzval = Vector{Tv}(xnzval)
SparseMatrixCSC(n, 1, colptr, rowval, nzval)
end
SparseMatrixCSC{Tv}(x::AbstractSparseVector{<:Any,Ti}) where {Tv,Ti} = SparseMatrixCSC{Tv,Ti}(x)
SparseMatrixCSC(x::AbstractSparseVector{Tv,Ti}) where {Tv,Ti} = SparseMatrixCSC{Tv,Ti}(x)
function Vector(x::AbstractSparseVector{Tv}) where Tv
require_one_based_indexing(x)
n = length(x)
n == 0 && return Vector{Tv}()
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
Array(x::AbstractSparseVector) = Vector(x)
### Array manipulation
vec(x::AbstractSparseVector) = x
copy(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), copy(nonzeros(x)))
float(x::AbstractSparseVector{<:AbstractFloat}) = x
float(x::AbstractSparseVector) =
SparseVector(length(x), copy(nonzeroinds(x)), float(nonzeros(x)))
complex(x::AbstractSparseVector{<:Complex}) = 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(X::SparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_hcat(X...)
hcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_hcat(X...)
function _absspvec_hcat(X::AbstractSparseVector{Tv,Ti}...) where {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 = Vector{Ti}(undef, n+1)
nzrow = Vector{Ti}(undef, tnnz)
nzval = Vector{Tv}(undef, tnnz)
roff = 1
@inbounds for j = 1:n
xj = X[j]
xnzind = nonzeroinds(xj)
xnzval = nonzeros(xj)
colptr[j] = roff
copyto!(nzrow, roff, xnzind)
copyto!(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(X::SparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_vcat(X...)
vcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_vcat(X...)
function vcat(X::SparseVector...)
commeltype = promote_type(map(eltype, X)...)
commindtype = promote_type(map(indtype, X)...)
vcat(map(x -> SparseVector{commeltype,commindtype}(x), X)...)
end
function _absspvec_vcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti}
# check sizes
n = length(X)
tnnz = 0
for j = 1:n
tnnz += nnz(X[j])
end
# construction
rnzind = Vector{Ti}(undef, tnnz)
rnzval = Vector{Tv}(undef, 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
copyto!(rnzval, ir+1, xnzval)
ir += xnnz
len += length(xj)
end
SparseVector(len, rnzind, rnzval)
end