-
Notifications
You must be signed in to change notification settings - Fork 52
/
sparsematrix.jl
4354 lines (3838 loc) · 159 KB
/
sparsematrix.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
# Compressed sparse columns data structure
# No assumptions about stored zeros in the data structure
# Assumes that row values in rowval for each column are sorted
# issorted(rowval[colptr[i]:(colptr[i+1]-1)]) == true
# Assumes that 1 <= colptr[i] <= colptr[i+1] for i in 1..n
# Assumes that nnz <= length(rowval) < typemax(Ti)
# Assumes that 0 <= length(nzval) < typemax(Ti)
"""
SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
Matrix type for storing sparse matrices in the
[Compressed Sparse Column](@ref man-csc) format. The standard way
of constructing SparseMatrixCSC is through the [`sparse`](@ref) function.
See also [`spzeros`](@ref), [`spdiagm`](@ref) and [`sprand`](@ref).
"""
struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
m::Int # Number of rows
n::Int # Number of columns
colptr::Vector{Ti} # Column i is in colptr[i]:(colptr[i+1]-1)
rowval::Vector{Ti} # Row indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
function SparseMatrixCSC{Tv,Ti}(m::Integer, n::Integer, colptr::Vector{Ti},
rowval::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti<:Integer}
sparse_check_Ti(m, n, Ti)
_goodbuffers(Int(m), Int(n), colptr, rowval, nzval) ||
throw(ArgumentError("Invalid buffers for SparseMatrixCSC construction n=$n, colptr=$(summary(colptr)), rowval=$(summary(rowval)), nzval=$(summary(nzval))"))
new(Int(m), Int(n), colptr, rowval, nzval)
end
end
function SparseMatrixCSC(m::Integer, n::Integer, colptr::Vector, rowval::Vector, nzval::Vector)
Tv = eltype(nzval)
Ti = promote_type(eltype(colptr), eltype(rowval))
sparse_check_Ti(m, n, Ti)
sparse_check(n, colptr, rowval, nzval)
# silently shorten rowval and nzval to usable index positions.
maxlen = abs(widemul(m, n))
isbitstype(Ti) && (maxlen = min(maxlen, typemax(Ti) - 1))
length(rowval) > maxlen && resize!(rowval, maxlen)
length(nzval) > maxlen && resize!(nzval, maxlen)
SparseMatrixCSC{Tv,Ti}(m, n, colptr, rowval, nzval)
end
SparseMatrixCSC(m, n, colptr::ReadOnly, rowval::ReadOnly, nzval::Vector) =
SparseMatrixCSC(m, n, copy(parent(colptr)), copy(parent(rowval)), nzval)
"""
SparseMatrixCSC{Tv,Ti}(::UndefInitializer, m::Integer, n::Integer)
Creates an empty sparse matrix with element type `Tv` and integer type `Ti` of size `m × n`.
"""
SparseMatrixCSC{Tv,Ti}(::UndefInitializer, m::Integer, n::Integer) where {Tv, Ti} = spzeros(Tv, Ti, m, n)
"""
`FixedSparseCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}`
Experimental AbstractSparseMatrixCSC whose non-zero index are fixed.
"""
struct FixedSparseCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
m::Int # Number of rows
n::Int # Number of columns
colptr::ReadOnly{Ti,1,Vector{Ti}} # Column i is in colptr[i]:(colptr[i+1]-1)
rowval::ReadOnly{Ti,1,Vector{Ti}} # Row indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
function FixedSparseCSC{Tv,Ti}(m::Integer, n::Integer,
colptr::ReadOnly{Ti,1,Vector{Ti}},
rowval::ReadOnly{Ti,1,Vector{Ti}},
nzval::Vector{Tv}) where {Tv,Ti<:Integer}
sparse_check_Ti(m, n, Ti)
_goodbuffers(Int(m), Int(n), parent(colptr), parent(rowval), nzval) ||
throw(ArgumentError("Invalid buffers for FixedSparseCSC construction n=$n, colptr=$(summary(colptr)), rowval=$(summary(rowval)), nzval=$(summary(nzval))"))
new(Int(m), Int(n), colptr, rowval, nzval)
end
end
@inline _is_fixed(::FixedSparseCSC) = true
FixedSparseCSC(m::Integer, n::Integer,
colptr::ReadOnly{Ti,1,Vector{Ti}},
rowval::ReadOnly{Ti,1,Vector{Ti}},
nzval::Vector{Tv}) where {Tv,Ti<:Integer} =
FixedSparseCSC{Tv,Ti}(m, n, colptr, rowval, nzval)
FixedSparseCSC{Tv,Ti}(m::Integer, n::Integer, colptr::Vector{Ti}, rowval::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti} =
FixedSparseCSC{Tv,Ti}(m, n, ReadOnly(colptr), ReadOnly(rowval), nzval)
FixedSparseCSC(m::Integer, n::Integer, colptr::Vector{Ti}, rowval::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti} =
FixedSparseCSC{Tv,Ti}(m, n, ReadOnly(colptr), ReadOnly(rowval), nzval)
FixedSparseCSC(x::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv,Ti} =
FixedSparseCSC{Tv,Ti}(size(x, 1), size(x, 2),
getcolptr(x), rowvals(x), nonzeros(x))
FixedSparseCSC{Tv,Ti}(x::AbstractSparseMatrixCSC) where {Tv,Ti} =
FixedSparseCSC{Tv,Ti}(size(x, 1), size(x, 2),
getcolptr(x), rowvals(x), nonzeros(x))
"""
`fixed(x...)`
Experimental. Like `sparse` but returns a sparse array whose `_is_fixed` is `true`.
"""
fixed(x...) = move_fixed(sparse(x...))
fixed(x::AbstractSparseMatrixCSC) = FixedSparseCSC(x)
"""
`move_fixed(x::AbstractSparseMatrixCSC)`
Experimental, unsafe. Make a `FixedSparseCSC` by reusing the colptr, rowvals and nonzeros of `x`.
"""
move_fixed(x::AbstractSparseMatrixCSC) = FixedSparseCSC(size(x)..., getcolptr(x), rowvals(x), nonzeros(x))
"""
`_unsafe_unfix(x)`
Experimental, unsafe. Returns a modifyable version of `x` for compatibility with this codebase.
"""
_unsafe_unfix(x::FixedSparseCSC) = SparseMatrixCSC(size(x)..., parent(getcolptr(x)), parent(rowvals(x)), nonzeros(x))
_unsafe_unfix(x::SparseMatrixCSC) = x
const SorF = Union{<:SparseMatrixCSC, <:FixedSparseCSC}
"""
`SparseMatrixCSC(x::FixedSparseCSC)`
Get a writable copy of x. See `_unsafe_unfix(x)`
"""
SparseMatrixCSC(x::FixedSparseCSC) = SparseMatrixCSC(size(x, 1), size(x, 2),
copy(parent(getcolptr(x))),
copy(parent(rowval(x))),
copy(nonzeros(x)))
function sparse_check_Ti(m::Integer, n::Integer, Ti::Type)
@noinline throwTi(str, lbl, k) =
throw(ArgumentError("$str ($lbl = $k) does not fit in Ti = $(Ti)"))
0 ≤ m && (!isbitstype(Ti) || m ≤ typemax(Ti)) || throwTi("number of rows", "m", m)
0 ≤ n && (!isbitstype(Ti) || n ≤ typemax(Ti)) || throwTi("number of columns", "n", n)
end
function sparse_check(n::Integer, colptr::Vector{Ti}, rowval, nzval) where Ti
# String interpolation is a performance bottleneck when it's part of the same function,
# ensure we only do it once committed to the error.
throwstart(ckp) = throw(ArgumentError("$ckp == colptr[1] != 1"))
throwmonotonic(ckp, ck, k) = throw(ArgumentError("$ckp == colptr[$(k-1)] > colptr[$k] == $ck"))
sparse_check_length("colptr", colptr, n+1, String) # don't check upper bound
ckp = Ti(1)
ckp == colptr[1] || throwstart(ckp)
@inbounds for k = 2:n+1
ck = colptr[k]
ckp <= ck || throwmonotonic(ckp, ck, k)
ckp = ck
end
sparse_check_length("rowval", rowval, ckp-1, Ti)
sparse_check_length("nzval", nzval, 0, Ti) # we allow empty nzval !!!
end
function sparse_check_length(rowstr, rowval, minlen, Ti)
throwmin(len, minlen, rowstr) = throw(ArgumentError("$len == length($rowstr) < $minlen"))
throwmax(len, max, rowstr) = throw(ArgumentError("$len == length($rowstr) >= $max"))
len = length(rowval)
len >= minlen || throwmin(len, minlen, rowstr)
!isbitstype(Ti) || len < typemax(Ti) || throwmax(len, typemax(Ti), rowstr)
end
size(S::SorF) = (getfield(S, :m), getfield(S, :n))
_goodbuffers(S::AbstractSparseMatrixCSC) = _goodbuffers(size(S)..., getcolptr(S), getrowval(S), nonzeros(S))
_checkbuffers(S::AbstractSparseMatrixCSC) = (@assert _goodbuffers(S); S)
_checkbuffers(S::Union{Adjoint, Transpose}) = (_checkbuffers(parent(S)); S)
function _goodbuffers(m, n, colptr, rowval, nzval)
(length(colptr) == n + 1 && colptr[end] - 1 == length(rowval) == length(nzval))
# stronger check for debugging purposes
# && all(issorted(@view rowval[colptr[i]:colptr[i+1]-1]) for i=1:n)
end
# Define an alias for views of a SparseMatrixCSC which include all rows and a unit range of the columns.
# Also define a union of SparseMatrixCSC and this view since many methods can be defined efficiently for
# this union by extracting the fields via the get function: getcolptr, getrowval, and getnzval. The key
# insight is that getcolptr on a SparseMatrixCSCView returns an offset view of the colptr of the
# underlying SparseMatrixCSC
const SparseMatrixCSCView{Tv,Ti} =
SubArray{Tv,2,<:AbstractSparseMatrixCSC{Tv,Ti},
Tuple{Base.Slice{Base.OneTo{Int}},I}} where {I<:AbstractUnitRange}
const SparseMatrixCSCUnion{Tv,Ti} = Union{AbstractSparseMatrixCSC{Tv,Ti}, SparseMatrixCSCView{Tv,Ti}}
getcolptr(S::SorF) = getfield(S, :colptr)
getcolptr(S::SparseMatrixCSCView) = view(getcolptr(parent(S)), first(axes(S, 2)):(last(axes(S, 2)) + 1))
getrowval(S::AbstractSparseMatrixCSC) = rowvals(S)
getrowval(S::SparseMatrixCSCView) = rowvals(parent(S))
getnzval( S::AbstractSparseMatrixCSC) = nonzeros(S)
getnzval( S::SparseMatrixCSCView) = nonzeros(parent(S))
nzvalview(S::AbstractSparseMatrixCSC) = view(nonzeros(S), 1:nnz(S))
"""
nnz(A)
Returns the number of stored (filled) elements in a sparse array.
# Examples
```jldoctest
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> nnz(A)
3
```
"""
nnz(S::AbstractSparseMatrixCSC) = Int(getcolptr(S)[size(S, 2) + 1]) - 1
nnz(S::ReshapedArray{<:Any,1,<:AbstractSparseMatrixCSC}) = nnz(parent(S))
nnz(S::Adjoint{<:Any,<:AbstractSparseMatrixCSC}) = nnz(parent(S))
nnz(S::Transpose{<:Any,<:AbstractSparseMatrixCSC}) = nnz(parent(S))
nnz(S::UpperTriangular{<:Any,<:AbstractSparseMatrixCSC}) = nnz1(S)
nnz(S::LowerTriangular{<:Any,<:AbstractSparseMatrixCSC}) = nnz1(S)
nnz(S::SparseMatrixCSCView) = nnz1(S)
nnz1(S) = sum(length.(nzrange.(Ref(S), axes(S, 2))))
function Base._simple_count(pred, S::AbstractSparseMatrixCSC, init::T) where T
init + T(count(pred, nzvalview(S)) + pred(zero(eltype(S)))*(prod(size(S)) - nnz(S)))
end
"""
nonzeros(A)
Return a vector of the structural nonzero values in sparse array `A`. This
includes zeros that are explicitly stored in the sparse array. The returned
vector points directly to the internal nonzero storage of `A`, and any
modifications to the returned vector will mutate `A` as well. See
[`rowvals`](@ref) and [`nzrange`](@ref).
# Examples
```jldoctest
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> nonzeros(A)
3-element Vector{Int64}:
2
2
2
```
"""
nonzeros(S::SorF) = getfield(S, :nzval)
nonzeros(S::SparseMatrixCSCView) = nonzeros(S.parent)
nonzeros(S::UpperTriangular{<:Any,<:SparseMatrixCSCUnion}) = nonzeros(S.data)
nonzeros(S::LowerTriangular{<:Any,<:SparseMatrixCSCUnion}) = nonzeros(S.data)
"""
rowvals(A::AbstractSparseMatrixCSC)
Return a vector of the row indices of `A`. Any modifications to the returned
vector will mutate `A` as well. Providing access to how the row indices are
stored internally can be useful in conjunction with iterating over structural
nonzero values. See also [`nonzeros`](@ref) and [`nzrange`](@ref).
# Examples
```jldoctest
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> rowvals(A)
3-element Vector{Int64}:
1
2
3
```
"""
rowvals(S::SorF) = getfield(S, :rowval)
rowvals(S::SparseMatrixCSCView) = rowvals(S.parent)
rowvals(S::UpperTriangular{<:Any,<:SparseMatrixCSCUnion}) = rowvals(S.data)
rowvals(S::LowerTriangular{<:Any,<:SparseMatrixCSCUnion}) = rowvals(S.data)
"""
nzrange(A::AbstractSparseMatrixCSC, col::Integer)
Return the range of indices to the structural nonzero values of a sparse matrix
column. In conjunction with [`nonzeros`](@ref) and
[`rowvals`](@ref), this allows for convenient iterating over a sparse matrix :
A = sparse(I,J,V)
rows = rowvals(A)
vals = nonzeros(A)
m, n = size(A)
for j = 1:n
for i in nzrange(A, j)
row = rows[i]
val = vals[i]
# perform sparse wizardry...
end
end
"""
nzrange(S::AbstractSparseMatrixCSC, col::Integer) = getcolptr(S)[col]:(getcolptr(S)[col+1]-1)
nzrange(S::SparseMatrixCSCView, col::Integer) = nzrange(S.parent, S.indices[2][col])
nzrange(S::UpperTriangular{<:Any,<:SparseMatrixCSCUnion}, i::Integer) = nzrangeup(S.data, i)
nzrange(S::LowerTriangular{<:Any,<:SparseMatrixCSCUnion}, i::Integer) = nzrangelo(S.data, i)
const AbstractSparseMatrixCSCInclAdjointAndTranspose = Union{AbstractSparseMatrixCSC,Adjoint{<:Any,<:AbstractSparseMatrixCSC},Transpose{<:Any,<:AbstractSparseMatrixCSC}}
function Base.isstored(A::AbstractSparseMatrixCSC, i::Integer, j::Integer)
@boundscheck checkbounds(A, i, j)
rows = rowvals(A)
for istored in nzrange(A, j) # could do binary search if the row indices are sorted?
i == rows[istored] && return true
end
return false
end
function Base.isstored(A::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}, i::Integer, j::Integer)
@boundscheck checkbounds(A, i, j)
cols = rowvals(parent(A))
for istored in nzrange(parent(A), i)
j == cols[istored] && return true
end
return false
end
Base.replace_in_print_matrix(A::AbstractSparseMatrixCSCInclAdjointAndTranspose, i::Integer, j::Integer, s::AbstractString) =
Base.isstored(A, i, j) ? s : Base.replace_with_centered_mark(s)
function Base.array_summary(io::IO, S::AbstractSparseMatrixCSCInclAdjointAndTranspose, dims::Tuple{Vararg{Base.OneTo}})
_checkbuffers(S)
xnnz = nnz(S)
m, n = size(S)
print(io, m, "×", n, " ", typeof(S), " with ", xnnz, " stored ",
xnnz == 1 ? "entry" : "entries")
nothing
end
# called by `show(io, MIME("text/plain"), ::AbstractSparseMatrixCSCInclAdjointAndTranspose)`
function Base.print_array(io::IO, S::AbstractSparseMatrixCSCInclAdjointAndTranspose)
if max(size(S)...) < 16
Base.print_matrix(io, S)
else
_show_with_braille_patterns(io, S)
end
end
# always show matrices as `sparse(I, J, K)`
function Base.show(io::IO, _S::AbstractSparseMatrixCSCInclAdjointAndTranspose)
_checkbuffers(_S)
# can't use `findnz`, because that expects all values not to be #undef
S = _S isa Adjoint || _S isa Transpose ? _S.parent : _S
I = rowvals(S)
K = nonzeros(S)
m, n = size(S)
if _S isa Adjoint
print(io, "adjoint(")
elseif _S isa Transpose
print(io, "transpose(")
end
print(io, "sparse(", I, ", ")
if length(I) == 0
print(io, eltype(getcolptr(S)), "[]")
else
print(io, "[")
il = nnz(S) - 1
for col in 1:size(S, 2),
k in getcolptr(S)[col] : (getcolptr(S)[col+1]-1)
print(io, col)
if il > 0
print(io, ", ")
il -= 1
end
end
print(io, "]")
end
print(io, ", ", K, ", ", m, ", ", n, ")")
if _S isa Adjoint || _S isa Transpose
print(io, ")")
end
end
const brailleBlocks = UInt16['⠁', '⠂', '⠄', '⡀', '⠈', '⠐', '⠠', '⢀']
function _show_with_braille_patterns(io::IO, S::AbstractSparseMatrixCSCInclAdjointAndTranspose)
m, n = size(S)
(m == 0 || n == 0) && return show(io, MIME("text/plain"), S)
# The maximal number of characters we allow to display the matrix
local maxHeight::Int, maxWidth::Int
maxHeight = displaysize(io)[1] - 4 # -4 from [Prompt, header, newline after elements, new prompt]
maxWidth = displaysize(io)[2] ÷ 2
# In the process of generating the braille pattern to display the nonzero
# structure of `S`, we need to be able to scale the matrix `S` to a
# smaller matrix with the same aspect ratio as `S`, but fits on the
# available screen space. The size of that smaller matrix is stored
# in the variables `scaleHeight` and `scaleWidth`. If no scaling is needed,
# we can use the size `m × n` of `S` directly.
# We determine if scaling is needed and set the scaling factors
# `scaleHeight` and `scaleWidth` accordingly. Note that each available
# character can contain up to 4 braille dots in its height (⡇) and up to
# 2 braille dots in its width (⠉).
if get(io, :limit, true) && (m > 4maxHeight || n > 2maxWidth)
s = min(2maxWidth / n, 4maxHeight / m)
scaleHeight = floor(Int, s * m)
scaleWidth = floor(Int, s * n)
else
scaleHeight = m
scaleWidth = n
end
# Make sure that the matrix size is big enough to be able to display all
# the corner border characters
if scaleHeight < 8
scaleHeight = 8
end
if scaleWidth < 4
scaleWidth = 4
end
# `brailleGrid` is used to store the needed braille characters for
# the matrix `S`. Each row of the braille pattern to print is stored
# in a column of `brailleGrid`.
brailleGrid = fill(UInt16(10240), (scaleWidth - 1) ÷ 2 + 4, (scaleHeight - 1) ÷ 4 + 1)
brailleGrid[1,:] .= '⎢'
brailleGrid[end-1,:] .= '⎥'
brailleGrid[1,1] = '⎡'
brailleGrid[1,end] = '⎣'
brailleGrid[end-1,1] = '⎤'
brailleGrid[end-1,end] = '⎦'
brailleGrid[end, :] .= '\n'
rvals = rowvals(parent(S))
rowscale = max(1, scaleHeight - 1) / max(1, m - 1)
colscale = max(1, scaleWidth - 1) / max(1, n - 1)
if isa(S, AbstractSparseMatrixCSC)
@inbounds for j = 1:n
# Scale the column index `j` to the best matching column index
# of a matrix of size `scaleHeight × scaleWidth`
sj = round(Int, (j - 1) * colscale + 1)
for x in nzrange(S, j)
# Scale the row index `i` to the best matching row index
# of a matrix of size `scaleHeight × scaleWidth`
si = round(Int, (rvals[x] - 1) * rowscale + 1)
# Given the index pair `(si, sj)` of the scaled matrix,
# calculate the corresponding triple `(k, l, p)` such that the
# element at `(si, sj)` can be found at position `(k, l)` in the
# braille grid `brailleGrid` and corresponds to the 1-dot braille
# character `brailleBlocks[p]`
k = (sj - 1) ÷ 2 + 2
l = (si - 1) ÷ 4 + 1
p = ((sj - 1) % 2) * 4 + ((si - 1) % 4 + 1)
brailleGrid[k, l] |= brailleBlocks[p]
end
end
else
# If `S` is a adjoint or transpose of a sparse matrix we invert the
# roles of the indices `i` and `j`
@inbounds for i = 1:m
si = round(Int, (i - 1) * rowscale + 1)
for x in nzrange(parent(S), i)
sj = round(Int, (rvals[x] - 1) * colscale + 1)
k = (sj - 1) ÷ 2 + 2
l = (si - 1) ÷ 4 + 1
p = ((sj - 1) % 2) * 4 + ((si - 1) % 4 + 1)
brailleGrid[k, l] |= brailleBlocks[p]
end
end
end
foreach(c -> print(io, Char(c)), @view brailleGrid[1:end-1])
end
for QT in (:LinAlgLeftQs, :LQPackedQ)
@eval (*)(Q::$QT, B::AbstractSparseMatrixCSC) = Q * Matrix(B)
@eval (*)(Q::$QT, B::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}) = Q * copy(B)
@eval (*)(A::AbstractSparseMatrixCSC, Q::$QT) = Matrix(A) * Q
@eval (*)(A::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}, Q::$QT) = copy(A) * Q
@eval (*)(Q::AdjQType{<:Any,<:$QT}, B::AbstractSparseMatrixCSC) = Q * Matrix(B)
@eval (*)(Q::AdjQType{<:Any,<:$QT}, B::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}) = Q * copy(B)
@eval (*)(A::AbstractSparseMatrixCSC, Q::AdjQType{<:Any,<:$QT}) = Matrix(A) * Q
@eval (*)(A::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}, Q::AdjQType{<:Any,<:$QT}) = copy(A) * Q
end
## Reshape
function sparse_compute_reshaped_colptr_and_rowval!(colptrS::Vector{Ti}, rowvalS::Vector{Ti},
mS::Int, nS::Int, colptrA::Vector{Ti},
rowvalA::Vector{Ti}, mA::Int, nA::Int) where Ti
lrowvalA = length(rowvalA)
maxrowvalA = (lrowvalA > 0) ? maximum(rowvalA) : zero(Ti)
((length(colptrA) == (nA+1)) && (maximum(colptrA) <= (lrowvalA+1)) && (maxrowvalA <= mA)) || throw(BoundsError())
colptrS[1] = 1
colA = 1
colS = 1
ptr = 1
@inbounds while colA <= nA
offsetA = (colA - 1) * mA
while ptr <= colptrA[colA+1]-1
rowA = rowvalA[ptr]
i = offsetA + rowA - 1
colSn = div(i, mS) + 1
rowS = mod(i, mS) + 1
while colS < colSn
colptrS[colS+1] = ptr
colS += 1
end
rowvalS[ptr] = rowS
ptr += 1
end
colA += 1
end
@inbounds while colS <= nS
colptrS[colS+1] = ptr
colS += 1
end
end
function copy(ra::ReshapedArray{<:Any,2,<:AbstractSparseMatrixCSC})
mS,nS = size(ra)
a = parent(ra)
mA,nA = size(a)
numnz = nnz(a)
colptr = similar(getcolptr(a), nS+1)
rowval = similar(rowvals(a))
nzval = copy(nonzeros(a))
sparse_compute_reshaped_colptr_and_rowval!(colptr, rowval, mS, nS, getcolptr(a), rowvals(a), mA, nA)
return SparseMatrixCSC(mS, nS, colptr, rowval, nzval)
end
## Alias detection and prevention
using Base: dataids, unaliascopy
Base.dataids(S::AbstractSparseMatrixCSC) = _is_fixed(S) ? dataids(nonzeros(S)) : (dataids(getcolptr(S))..., dataids(rowvals(S))..., dataids(nonzeros(S))...)
Base.unaliascopy(S::AbstractSparseMatrixCSC) = typeof(S)(size(S, 1), size(S, 2),
_is_fixed(S) ? getcolptr(S) : unaliascopy(getcolptr(S)),
_is_fixed(S) ? rowvals(S) : unaliascopy(rowvals(S)),
unaliascopy(nonzeros(S)))
## Constructors
copy(S::AbstractSparseMatrixCSC) =
SparseMatrixCSC(size(S, 1), size(S, 2), copy(getcolptr(S)), copy(rowvals(S)), copy(nonzeros(S)))
copy(S::FixedSparseCSC) =
FixedSparseCSC(size(S, 1), size(S, 2), getcolptr(S), rowvals(S), copy(nonzeros(S)))
function copyto!(A::AbstractSparseMatrixCSC, B::AbstractSparseMatrixCSC)
# If the two matrices have the same length then all the
# elements in A will be overwritten.
if widelength(A) == widelength(B)
resize!(nonzeros(A), length(nonzeros(B)))
resize!(rowvals(A), length(rowvals(B)))
if size(A) == size(B)
# Simple case: we can simply copy the internal fields of B to A.
copyto!(getcolptr(A), getcolptr(B))
copyto!(rowvals(A), rowvals(B))
else
# This is like a "reshape B into A".
sparse_compute_reshaped_colptr_and_rowval!(getcolptr(A), rowvals(A), size(A, 1), size(A, 2), getcolptr(B), rowvals(B), size(B, 1), size(B, 2))
end
else
widelength(A) >= widelength(B) || throw(BoundsError())
lB = widelength(B)
nnzA = nnz(A)
nnzB = nnz(B)
# Up to which col, row, and ptr in rowval/nzval will A be overwritten?
lastmodcolA = Int(div(lB - 1, size(A, 1))) + 1
lastmodrowA = Int(mod(lB - 1, size(A, 1))) + 1
lastmodptrA = getcolptr(A)[lastmodcolA]
while lastmodptrA < getcolptr(A)[lastmodcolA+1] && rowvals(A)[lastmodptrA] <= lastmodrowA
lastmodptrA += 1
end
lastmodptrA -= 1
if lastmodptrA >= nnzB
# A will have fewer non-zero elements; unmodified elements are kept at the end.
deleteat!(rowvals(A), nnzB+1:lastmodptrA)
deleteat!(nonzeros(A), nnzB+1:lastmodptrA)
else
# A will have more non-zero elements; unmodified elements are kept at the end.
resize!(rowvals(A), nnzB + nnzA - lastmodptrA)
resize!(nonzeros(A), nnzB + nnzA - lastmodptrA)
copyto!(rowvals(A), nnzB+1, rowvals(A), lastmodptrA+1, nnzA-lastmodptrA)
copyto!(nonzeros(A), nnzB+1, nonzeros(A), lastmodptrA+1, nnzA-lastmodptrA)
end
# Adjust colptr accordingly.
@inbounds for i in 2:length(getcolptr(A))
getcolptr(A)[i] += nnzB - lastmodptrA
end
sparse_compute_reshaped_colptr_and_rowval!(getcolptr(A), rowvals(A), size(A, 1), lastmodcolA-1, getcolptr(B), rowvals(B), size(B, 1), size(B, 2))
end
copyto!(nonzeros(A), nonzeros(B))
return _checkbuffers(A)
end
copyto!(A::AbstractMatrix, B::AbstractSparseMatrixCSC) = _sparse_copyto!(A, B)
# Ambiguity resolution
copyto!(A::PermutedDimsArray, B::AbstractSparseMatrixCSC) = _sparse_copyto!(A, B)
function _sparse_copyto!(dest::AbstractMatrix, src::AbstractSparseMatrixCSC)
(dest === src || isempty(src)) && return dest
z = convert(eltype(dest), zero(eltype(src))) # should throw if not possible
isrc = LinearIndices(src)
checkbounds(dest, isrc)
# If src is not dense, zero out the portion of dest spanned by isrc
if widelength(src) > nnz(src)
for i in isrc
@inbounds dest[i] = z
end
end
@inbounds for col in axes(src, 2), ptr in nzrange(src, col)
row = rowvals(src)[ptr]
val = nonzeros(src)[ptr]
dest[isrc[row, col]] = val
end
return dest
end
function copyto!(dest::AbstractMatrix, Rdest::CartesianIndices{2},
src::AbstractSparseMatrixCSC{T}, Rsrc::CartesianIndices{2}) where {T}
isempty(Rdest) && return dest
if size(Rdest) != size(Rsrc)
throw(ArgumentError("source and destination must have same size (got $(size(Rsrc)) and $(size(Rdest)))"))
end
checkbounds(dest, Rdest)
checkbounds(src, Rsrc)
src′ = Base.unalias(dest, src)
for I in Rdest
@inbounds dest[I] = zero(T) # implicitly convert to eltype(dest), throw if not possible
end
rows, cols = Rsrc.indices
lin = LinearIndices(Base.IdentityUnitRange.(Rsrc.indices))
@inbounds for col in cols, ptr in nzrange(src′, col)
row = rowvals(src′)[ptr]
if row in rows
val = nonzeros(src′)[ptr]
I = Rdest[lin[row, col]]
dest[I] = val
end
end
return dest
end
# Faster version for non-abstract Array and SparseMatrixCSC
function Base.copyto!(A::Array{T}, S::SparseMatrixCSC{<:Number}) where {T<:Number}
isempty(S) && return A
length(A) < length(S) && throw(BoundsError())
# Zero elements that are also in S, don't change rest of A
@inbounds for i in 1:length(S)
A[i] = zero(T)
end
# Copy the structural nonzeros from S to A using
# the linear indices (to work when size(A)!=size(S))
num_rows = size(S,1)
rowval = getrowval(S)
nzval = getnzval(S)
linear_index_col0 = 0 # Linear index before column (linear index = linear_index_col0 + row)
for col in 1:size(S, 2)
for i in nzrange(S, col)
row = rowval[i]
val = nzval[i]
A[linear_index_col0+row] = val
end
linear_index_col0 += num_rows
end
return A
end
## similar
#
# parent method for similar that preserves stored-entry structure (for when new and old dims match)
function _sparsesimilar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}) where {TvNew,TiNew}
newcolptr = copyto!(similar(getcolptr(S), TiNew), getcolptr(S))
newrowval = copyto!(similar(rowvals(S), TiNew), rowvals(S))
return SparseMatrixCSC(size(S, 1), size(S, 2), newcolptr, newrowval, similar(nonzeros(S), TvNew))
end
# parent methods for similar that preserves only storage space (for when new dims are 2-d)
_sparsesimilar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}, dims::Dims{2}) where {TvNew,TiNew} =
sizehint!(spzeros(TvNew, TiNew, dims...), length(nonzeros(S)))
# parent method for similar that allocates an empty sparse vector (for when new dims are 1-d)
_sparsesimilar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}, dims::Dims{1}) where {TvNew,TiNew} =
SparseVector(dims..., similar(rowvals(S), TiNew, 0), similar(nonzeros(S), TvNew, 0))
# 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 partially preserve
# storage space when the shape calls for a two-dimensional result.
"""
similar(A::AbstractSparseMatrixCSC{Tv,Ti}, [::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer]) where {Tv,Ti}
Create an uninitialized mutable array with the given element type,
index type, and size, based upon the given source
`SparseMatrixCSC`. The new sparse matrix maintains the structure of
the original sparse matrix, except in the case where dimensions of the
output matrix are different from the output.
The output matrix has zeros in the same locations as the input, but
unititialized values for the nonzero locations.
"""
similar(S::AbstractSparseMatrixCSC{<:Any,Ti}, ::Type{TvNew}) where {Ti,TvNew} =
@if_move_fixed S _sparsesimilar(S, TvNew, Ti)
similar(S::AbstractSparseMatrixCSC{<:Any,Ti}, ::Type{TvNew}, dims::Union{Dims{1},Dims{2}}) where {Ti,TvNew} =
@if_move_fixed S _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 shape
# preserve storage space when the shape calls for a two-dimensional result.
similar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}) where{TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew)
similar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}, dims::Union{Dims{1},Dims{2}}) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, dims)
similar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}, m::Integer) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, (m,))
similar(S::AbstractSparseMatrixCSC, ::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer) where {TvNew,TiNew} =
_sparsesimilar(S, TvNew, TiNew, (m, n))
function Base.sizehint!(S::SparseMatrixCSC, n::Integer)
nhint = min(n, widelength(S))
sizehint!(getrowval(S), nhint)
sizehint!(nonzeros(S), nhint)
return S
end
# converting between SparseMatrixCSC types
SparseMatrixCSC(S::AbstractSparseMatrixCSC) = copy(S)
AbstractMatrix{Tv}(A::AbstractSparseMatrixCSC) where {Tv} = SparseMatrixCSC{Tv}(A)
SparseMatrixCSC{Tv}(S::AbstractSparseMatrixCSC{Tv}) where {Tv} = copy(S)
SparseMatrixCSC{Tv}(S::AbstractSparseMatrixCSC) where {Tv} = SparseMatrixCSC{Tv,eltype(getcolptr(S))}(S)
SparseMatrixCSC{Tv,Ti}(S::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = copy(S)
function SparseMatrixCSC{Tv,Ti}(S::AbstractSparseMatrixCSC) where {Tv,Ti}
eltypeTicolptr = Vector{Ti}(getcolptr(S))
eltypeTirowval = Vector{Ti}(rowvals(S))
eltypeTvnzval = Vector{Tv}(nonzeros(S))
return SparseMatrixCSC(size(S, 1), size(S, 2), eltypeTicolptr, eltypeTirowval, eltypeTvnzval)
end
# converting from other matrix types to SparseMatrixCSC (also see sparse())
SparseMatrixCSC(M::Matrix) = sparse(M)
SparseMatrixCSC(T::Tridiagonal{Tv}) where Tv = SparseMatrixCSC{Tv,Int}(T)
function SparseMatrixCSC{Tv,Ti}(T::Tridiagonal) where {Tv,Ti}
m = length(T.d)
m == 0 && return SparseMatrixCSC{Tv,Ti}(0, 0, ones(Ti, 1), Ti[], Tv[])
m == 1 && return SparseMatrixCSC{Tv,Ti}(1, 1, Ti[1, 2], Ti[1], Tv[T.d[1]])
colptr = Vector{Ti}(undef, m+1)
colptr[1] = 1
@inbounds for i=1:m-1
colptr[i+1] = 3i
end
colptr[end] = 3m-1
rowval = Vector{Ti}(undef, 3m-2)
rowval[1] = 1
rowval[2] = 2
@inbounds for i=2:m-1, j=-1:1
rowval[3i+j-2] = i+j
end
rowval[end-1] = m - 1
rowval[end] = m
nzval = Vector{Tv}(undef, 3m-2)
@inbounds for i=1:(m-1)
nzval[3i-2] = T.d[i]
nzval[3i-1] = T.dl[i]
nzval[3i] = T.du[i]
end
nzval[end] = T.d[end]
return SparseMatrixCSC(m, m, colptr, rowval, nzval)
end
SparseMatrixCSC(T::SymTridiagonal{Tv}) where Tv = SparseMatrixCSC{Tv,Int}(T)
function SparseMatrixCSC{Tv,Ti}(T::SymTridiagonal) where {Tv,Ti}
m = length(T.dv)
m == 0 && return SparseMatrixCSC{Tv,Ti}(0, 0, ones(Ti, 1), Ti[], Tv[])
m == 1 && return SparseMatrixCSC{Tv,Ti}(1, 1, Ti[1, 2], Ti[1], Tv[T.dv[1]])
colptr = Vector{Ti}(undef, m+1)
colptr[1] = 1
@inbounds for i=1:m-1
colptr[i+1] = 3i
end
colptr[end] = 3m-1
rowval = Vector{Ti}(undef, 3m-2)
rowval[1] = 1
rowval[2] = 2
@inbounds for i=2:m-1, j=-1:1
rowval[3i+j-2] = i+j
end
rowval[end-1] = m - 1
rowval[end] = m
nzval = Vector{Tv}(undef, 3m-2)
@inbounds for i=1:(m-1)
nzval[3i-2] = T.dv[i]
nzval[3i-1] = T.ev[i]
nzval[3i] = T.ev[i]
end
nzval[end] = T.dv[end]
return SparseMatrixCSC(m, m, colptr, rowval, nzval)
end
SparseMatrixCSC(B::Bidiagonal{Tv}) where Tv = SparseMatrixCSC{Tv,Int}(B)
function SparseMatrixCSC{Tv,Ti}(B::Bidiagonal) where {Tv,Ti}
m = length(B.dv)
m == 0 && return SparseMatrixCSC{Tv,Ti}(0, 0, ones(Ti, 1), Ti[], Tv[])
colptr = Vector{Ti}(undef, m+1)
colptr[1] = 1
@inbounds for i=1:m-1
colptr[i+1] = B.uplo == 'U' ? 2i : 2i+1
end
colptr[end] = 2m
rowval = Vector{Ti}(undef, 2m-1)
@inbounds for i=1:m-1
rowval[2i-1] = i
rowval[2i] = B.uplo == 'U' ? i : i+1
end
rowval[end] = m
nzval = Vector{Tv}(undef, 2m-1)
nzval[1] = B.dv[1]
@inbounds for i=1:m-1
nzval[2i-1] = B.dv[i]
nzval[2i] = B.ev[i]
end
nzval[end] = B.dv[end]
return SparseMatrixCSC(m, m, colptr, rowval, nzval)
end
SparseMatrixCSC(D::Diagonal{Tv}) where Tv = SparseMatrixCSC{Tv,Int}(D)
function SparseMatrixCSC{Tv,Ti}(D::Diagonal) where {Tv,Ti}
m = length(D.diag)
m == 0 && return SparseMatrixCSC{Tv,Ti}(zeros(Tv, 0, 0))
nz = count(_isnotzero, D.diag)
nz_counter = 1
rowval = Vector{Ti}(undef, nz)
nzval = Vector{Tv}(undef, nz)
nz == 0 && return SparseMatrixCSC{Tv,Ti}(m, m, ones(Ti, m+1), rowval, nzval)
colptr = Vector{Ti}(undef, m+1)
@inbounds for i=1:m
if _isnotzero(D.diag[i])
colptr[i] = nz_counter
rowval[nz_counter] = i
nzval[nz_counter] = D.diag[i]
nz_counter += 1
else
colptr[i] = nz_counter
end
end
colptr[end] = nz_counter
return SparseMatrixCSC{Tv,Ti}(m, m, colptr, rowval, nzval)
end
SparseMatrixCSC(M::AbstractMatrix{Tv}) where {Tv} = SparseMatrixCSC{Tv,Int}(M)
SparseMatrixCSC{Tv}(M::AbstractMatrix{Tv}) where {Tv} = SparseMatrixCSC{Tv,Int}(M)
function SparseMatrixCSC{Tv,Ti}(M::AbstractMatrix) where {Tv,Ti}
require_one_based_indexing(M)
I = Ti[]
V = Tv[]
i = 0
for v in M
i += 1
if _isnotzero(v)
push!(I, i)
push!(V, v)
end
end
return sparse_sortedlinearindices!(I, V, size(M)...)
end
function SparseMatrixCSC{Tv,Ti}(M::StridedMatrix) where {Tv,Ti}
nz = count(_isnotzero, M)
colptr = zeros(Ti, size(M, 2) + 1)
nzval = Vector{Tv}(undef, nz)
rowval = Vector{Ti}(undef, nz)
colptr[1] = 1
cnt = 1
@inbounds for j in 1:size(M, 2)
for i in 1:size(M, 1)
v = M[i, j]
if _isnotzero(v)
rowval[cnt] = i
nzval[cnt] = v
cnt += 1
end
end
colptr[j+1] = cnt
end
return SparseMatrixCSC(size(M, 1), size(M, 2), colptr, rowval, nzval)
end
SparseMatrixCSC(M::Adjoint{<:Any,<:AbstractSparseMatrixCSC}) = copy(M)
SparseMatrixCSC(M::Transpose{<:Any,<:AbstractSparseMatrixCSC}) = copy(M)
SparseMatrixCSC{Tv}(M::Adjoint{Tv,<:AbstractSparseMatrixCSC{Tv}}) where {Tv} = copy(M)
SparseMatrixCSC{Tv}(M::Transpose{Tv,<:AbstractSparseMatrixCSC{Tv}}) where {Tv} = copy(M)
SparseMatrixCSC{Tv,Ti}(M::Adjoint{Tv,<:AbstractSparseMatrixCSC{Tv,Ti}}) where {Tv,Ti} = copy(M)
SparseMatrixCSC{Tv,Ti}(M::Transpose{Tv,<:AbstractSparseMatrixCSC{Tv,Ti}}) where {Tv,Ti} = copy(M)
# converting from adjoint or transpose sparse matrices to sparse matrices with different eltype
SparseMatrixCSC{Tv}(M::Adjoint{<:Any,<:AbstractSparseMatrixCSC}) where {Tv} = SparseMatrixCSC{Tv}(copy(M))
SparseMatrixCSC{Tv}(M::Transpose{<:Any,<:AbstractSparseMatrixCSC}) where {Tv} = SparseMatrixCSC{Tv}(copy(M))
SparseMatrixCSC{Tv,Ti}(M::Adjoint{<:Any,<:AbstractSparseMatrixCSC}) where {Tv,Ti} = SparseMatrixCSC{Tv,Ti}(copy(M))
SparseMatrixCSC{Tv,Ti}(M::Transpose{<:Any,<:AbstractSparseMatrixCSC}) where {Tv,Ti} = SparseMatrixCSC{Tv,Ti}(copy(M))
# we can only view AbstractQs as columns
SparseMatrixCSC(Q::AbstractQ{Tv}) where {Tv} = SparseMatrixCSC{Tv,Int}(Q)
SparseMatrixCSC{Tv}(Q::AbstractQ{Tv}) where {Tv} = SparseMatrixCSC{Tv,Int}(Q)
SparseMatrixCSC{Tv,Ti}(Q::AbstractQ) where {Tv,Ti} = sparse_with_lmul(Tv, Ti, Q)
"""
sparse_with_lmul(Tv, Ti, Q) -> SparseMatrixCSC
Helper function that creates a `SparseMatrixCSC{Tv,Ti}` representation of `Q`, where `Q` is
supposed to not have fast `getindex` or not admit an iteration protocol at all, but instead
a fast `lmul!(Q, v)` for dense vectors `v`. The prime example for such `Q`s is the Q factor
of a (sparse) QR decomposition.
"""
function sparse_with_lmul(Tv, Ti, Q)
colptr = zeros(Ti, size(Q, 2) + 1)
nzval = Tv[]
rowval = Ti[]
col = zeros(eltype(Q), size(Q, 1))
colptr[1] = 1
ind = 1
for j in axes(Q, 2)
fill!(col, false)
col[j] = one(Tv)
lmul!(Q, col)
for (i, v) in enumerate(col)
if _isnotzero(v)
push!(nzval, v)
push!(rowval, i)
ind += 1
end
end
colptr[j + 1] = ind
end
return SparseMatrixCSC{Tv,Ti}(size(Q)..., colptr, rowval, nzval)
end
# converting from AbstractSparseMatrixCSC to other matrix types
function Matrix(S::AbstractSparseMatrixCSC{Tv}) where Tv
_checkbuffers(S)
A = Matrix{Tv}(undef, size(S, 1), size(S, 2))
copyto!(A, S)
return A
end
Array(S::AbstractSparseMatrixCSC) = Matrix(S)
convert(T::Type{<:AbstractSparseMatrixCSC}, m::AbstractMatrix) = m isa T ? m : T(m)
convert(T::Type{<:Diagonal}, m::AbstractSparseMatrixCSC) = m isa T ? m :
isdiag(m) ? T(m) : throw(ArgumentError("matrix cannot be represented as Diagonal"))
convert(T::Type{<:SymTridiagonal}, m::AbstractSparseMatrixCSC) = m isa T ? m :
issymmetric(m) && isbanded(m, -1, 1) ? T(m) : throw(ArgumentError("matrix cannot be represented as SymTridiagonal"))
convert(T::Type{<:Tridiagonal}, m::AbstractSparseMatrixCSC) = m isa T ? m :
isbanded(m, -1, 1) ? T(m) : throw(ArgumentError("matrix cannot be represented as Tridiagonal"))
convert(T::Type{<:LowerTriangular}, m::AbstractSparseMatrixCSC) = m isa T ? m :
istril(m) ? T(m) : throw(ArgumentError("matrix cannot be represented as LowerTriangular"))
convert(T::Type{<:UpperTriangular}, m::AbstractSparseMatrixCSC) = m isa T ? m :
istriu(m) ? T(m) : throw(ArgumentError("matrix cannot be represented as UpperTriangular"))
float(S::SparseMatrixCSC) = SparseMatrixCSC(size(S, 1), size(S, 2), getcolptr(S), rowvals(S), float(nonzeros(S)))
complex(S::SparseMatrixCSC) = SparseMatrixCSC(size(S, 1), size(S, 2), getcolptr(S), rowvals(S), complex(nonzeros(S)))
"""
sparse(A)
Convert an AbstractMatrix `A` into a sparse matrix.
# Examples
```jldoctest
julia> A = Matrix(1.0I, 3, 3)
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> sparse(A)
3×3 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
1.0 ⋅ ⋅
⋅ 1.0 ⋅
⋅ ⋅ 1.0
```
"""
sparse(A::AbstractMatrix{Tv}) where {Tv} = convert(SparseMatrixCSC{Tv}, A)
sparse(S::AbstractSparseMatrixCSC) = copy(S)