-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcholmod.jl
2067 lines (1810 loc) · 77.6 KB
/
cholmod.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
# Theoretically CHOLMOD supports both Int32 and Int64 indices on 64-bit.
# However experience suggests that using both in the same session causes memory
# leaks, so we restrict indices to be Sys.WORD_SIZE
# Ref: https://github.com/JuliaLang/julia/issues/12664
# Additionally, only Float{32 | 64}/ComplexF{32 | 64} are supported in practice.
# Ref: https://github.com/JuliaLang/julia/issues/25986
module CHOLMOD
import Base: (*), convert, copy, eltype, getindex, getproperty, show, size,
IndexStyle, IndexLinear, IndexCartesian, adjoint, axes
using Base: require_one_based_indexing
using LinearAlgebra
using LinearAlgebra: RealHermSymComplexHerm, AdjOrTrans
import LinearAlgebra: (\), AdjointFactorization,
cholesky, cholesky!, det, diag, ishermitian, isposdef,
issuccess, issymmetric, ldlt, ldlt!, logdet,
lowrankdowndate, lowrankdowndate!, lowrankupdate, lowrankupdate!
using SparseArrays
using SparseArrays: getcolptr, AbstractSparseVecOrMat
import Libdl
export
Dense,
Factor,
Sparse
import SparseArrays: AbstractSparseMatrix, SparseMatrixCSC, indtype, sparse, spzeros, nnz,
sparsevec
import ..increment, ..increment!
using ..LibSuiteSparse
import ..LibSuiteSparse: TRUE, FALSE, CHOLMOD_INT, CHOLMOD_LONG
# # itype defines the types of integer used:
# CHOLMOD_INT, # all integer arrays are int
# CHOLMOD_LONG, # all integer arrays are Sys.WORD_SIZE
# # dtype defines what the numerical type is (double or float):
# CHOLMOD_DOUBLE, # all numerical values are double
# CHOLMOD_SINGLE, # all numerical values are float
# # xtype defines the kind of numerical values used:
# CHOLMOD_PATTERN, # pattern only, no numerical values
# CHOLMOD_REAL, # a real matrix
# CHOLMOD_COMPLEX, # a complex matrix (ANSI C99 compatible)
# CHOLMOD_ZOMPLEX, # a complex matrix (MATLAB compatible)
# # Scaling modes, selected by the scale input parameter:
# CHOLMOD_SCALAR, # A = s*A
# CHOLMOD_ROW, # A = diag(s)*A
# CHOLMOD_COL, # A = A*diag(s)
# CHOLMOD_SYM, # A = diag(s)*A*diag(s)
# # Types of systems to solve
# CHOLMOD_A, # solve Ax=b
# CHOLMOD_LDLt, # solve LDL'x=b
# CHOLMOD_LD, # solve LDx=b
# CHOLMOD_DLt, # solve DL'x=b
# CHOLMOD_L, # solve Lx=b
# CHOLMOD_Lt, # solve L'x=b
# CHOLMOD_D, # solve Dx=b
# CHOLMOD_P, # permute x=Px
# CHOLMOD_Pt, # permute x=P'x
# # Symmetry types
# CHOLMOD_MM_RECTANGULAR,
# CHOLMOD_MM_UNSYMMETRIC,
# CHOLMOD_MM_SYMMETRIC,
# CHOLMOD_MM_HERMITIAN,
# CHOLMOD_MM_SKEW_SYMMETRIC,
# CHOLMOD_MM_SYMMETRIC_POSDIAG,
# CHOLMOD_MM_HERMITIAN_POSDIAG
dtyp(::Type{Float32}) = CHOLMOD_SINGLE
dtyp(::Type{Float64}) = CHOLMOD_DOUBLE
dtyp(::Type{ComplexF32}) = CHOLMOD_SINGLE
dtyp(::Type{ComplexF64}) = CHOLMOD_DOUBLE
xtyp(::Type{Float32}) = CHOLMOD_REAL
xtyp(::Type{Float64}) = CHOLMOD_REAL
xtyp(::Type{ComplexF32}) = CHOLMOD_COMPLEX
xtyp(::Type{ComplexF64}) = CHOLMOD_COMPLEX
xdtyp(::Type{T}) where T = dtyp(T) + xtyp(T)
if Sys.WORD_SIZE == 64
const IndexTypes = (:Int32, :Int64)
const ITypes = Union{Int32, Int64}
else
const IndexTypes = (:Int32,)
const ITypes = Union{Int32}
end
ityp(::Type{Int32}) = CHOLMOD_INT
ityp(::Type{Int64}) = CHOLMOD_LONG
jlitype(t) = t == CHOLMOD_INT ? Int32 :
(t == CHOLMOD_LONG ? Int64 : throw(CHOLMODException("Unsupported itype $t")))
jlxtype(xtype, dtype) = (dtype == CHOLMOD_DOUBLE && xtype == CHOLMOD_REAL) ? Float64 :
(dtype == CHOLMOD_DOUBLE && xtype == CHOLMOD_COMPLEX) ? ComplexF64 :
(dtype == CHOLMOD_SINGLE && xtype == CHOLMOD_REAL) ? Float32 :
(dtype == CHOLMOD_SINGLE && xtype == CHOLMOD_COMPLEX) ? ComplexF32 :
throw(CHOLMODException("Unsupported dtype $dtype and xtype $xtype"))
cholname(name::Symbol, type) = type === :Int64 ? Symbol(:cholmod_l_, name) :
type === :Int32 ? Symbol(:cholmod_, name) : throw(ArgumentError("Unsupported type: $type"))
const VTypes = Union{ComplexF64, Float64, ComplexF32, Float32}
const VRealTypes = Union{Float64, Float32}
const VComplexTypes = Union{ComplexF64, ComplexF32}
const StridedVecOrMatInclAdjAndTrans{Tv} = Union{StridedVecOrMat{Tv}, Adjoint{Tv, <:StridedVecOrMat}, Transpose{Tv, <:StridedVecOrMat}}
# exception
struct CHOLMODException <: Exception
msg::String
end
function error_handler(status::Cint, file::Cstring, line::Cint, message::Cstring)::Cvoid
status < 0 && throw(CHOLMODException(unsafe_string(message)))
nothing
end
const CHOLMOD_MIN_VERSION = v"2.1.1"
# Set a `common` field, execute some code and then safely reset the field to
# its initial value
# Will set the field for both long and int common structs.
# This seems like the most obvious behavior, changing common parameters
# would be expected to change all cholmod calls within this block,
# and Int32 & Int64 probably shouldn't be mixed much anyway.
macro cholmod_param(kwarg, code)
@assert kwarg.head == :(=)
param = kwarg.args[1]
value = kwarg.args[2]
common_param = # Read `common.param`
Expr(:., :(getcommon(Int32)[]), QuoteNode(param))
common_param_l = # Read `common.param`
Expr(:., :(getcommon(Int64)[]), QuoteNode(param))
return quote
default_value = $common_param
default_value_l = $common_param_l
try
$common_param = $(esc(value))
$common_param_l = $(esc(value))
$(esc(code))
finally
$common_param = default_value
$common_param_l = default_value_l
end
end
end
function newcommon_l(; print = 0) # no printing from CHOLMOD by default
common = finalizer(cholmod_l_finish, Ref(cholmod_common()))
result = cholmod_l_start(common)
@assert result == TRUE "failed to run `cholmod_l_start`!"
common[].print = print
common[].error_handler = @cfunction(error_handler, Cvoid, (Cint, Cstring, Cint, Cstring))
return common
end
function newcommon(; print = 0) # no printing from CHOLMOD by default
common = finalizer(cholmod_finish, Ref(cholmod_common()))
result = cholmod_start(common)
@assert result == TRUE "failed to run `cholmod_start`!"
common[].print = print
common[].error_handler = @cfunction(error_handler, Cvoid, (Cint, Cstring, Cint, Cstring))
return common
end
function getcommon(::Type{Int32})
return get!(newcommon, task_local_storage(), :cholmod_common)::Ref{cholmod_common}
end
function getcommon(::Type{Int64})
return get!(newcommon_l, task_local_storage(), :cholmod_common_l)::Ref{cholmod_common}
end
getcommon() = getcommon(Int)
const BUILD_VERSION = VersionNumber(CHOLMOD_MAIN_VERSION, CHOLMOD_SUB_VERSION, CHOLMOD_SUBSUB_VERSION)
function __init__()
try
### Check if the linked library is compatible with the Julia code
if Libdl.dlsym_e(Libdl.dlopen("libcholmod"), :cholmod_version) != C_NULL
current_version_array = Vector{Cint}(undef, 3)
cholmod_version(current_version_array)
current_version = VersionNumber(current_version_array...)
else # CHOLMOD < 2.1.1 does not include cholmod_version()
current_version = v"0.0.0"
end
if current_version < CHOLMOD_MIN_VERSION
@warn """
CHOLMOD version incompatibility
Julia was compiled with CHOLMOD version $BUILD_VERSION. It is
currently linked with a version older than
$(CHOLMOD_MIN_VERSION). This might cause Julia to
terminate when working with sparse matrix factorizations,
e.g. solving systems of equations with \\.
It is recommended that you use Julia with a recent version
of CHOLMOD, or download the generic binaries
from www.julialang.org, which ship with the correct
versions of all dependencies.
"""
elseif BUILD_VERSION.major != current_version.major
@warn """
CHOLMOD version incompatibility
Julia was compiled with CHOLMOD version $BUILD_VERSION. It is
currently linked with version $current_version.
This might cause Julia to terminate when working with
sparse matrix factorizations, e.g. solving systems of
equations with \\.
It is recommended that you use Julia with the same major
version of CHOLMOD as the one used during the build, or
download the generic binaries from www.julialang.org,
which ship with the correct versions of all dependencies.
"""
end
# Register gc tracked allocator if CHOLMOD is new enough
if current_version >= v"4.0.3"
ccall((:SuiteSparse_config_malloc_func_set, :libsuitesparseconfig),
Cvoid, (Ptr{Cvoid},), cglobal(:jl_malloc, Ptr{Cvoid}))
ccall((:SuiteSparse_config_calloc_func_set, :libsuitesparseconfig),
Cvoid, (Ptr{Cvoid},), cglobal(:jl_calloc, Ptr{Cvoid}))
ccall((:SuiteSparse_config_realloc_func_set, :libsuitesparseconfig),
Cvoid, (Ptr{Cvoid},), cglobal(:jl_realloc, Ptr{Cvoid}))
ccall((:SuiteSparse_config_free_func_set, :libsuitesparseconfig),
Cvoid, (Ptr{Cvoid},), cglobal(:jl_free, Ptr{Cvoid}))
elseif current_version >= v"3.0.0"
cnfg = cglobal((:SuiteSparse_config, :libsuitesparseconfig), Ptr{Cvoid})
unsafe_store!(cnfg, cglobal(:jl_malloc, Ptr{Cvoid}), 1)
unsafe_store!(cnfg, cglobal(:jl_calloc, Ptr{Cvoid}), 2)
unsafe_store!(cnfg, cglobal(:jl_realloc, Ptr{Cvoid}), 3)
unsafe_store!(cnfg, cglobal(:jl_free, Ptr{Cvoid}), 4)
end
catch ex
@error "Error during initialization of module CHOLMOD" exception=ex,catch_backtrace()
end
end
####################
# Type definitions #
####################
# The three core data types for CHOLMOD: Dense, Sparse and Factor.
# CHOLMOD manages the memory, so the Julia versions only wrap a
# pointer to a struct. Therefore finalizers should be registered each
# time a pointer is returned from CHOLMOD.
mutable struct Dense{Tv<:VTypes} <: DenseMatrix{Tv}
ptr::Ptr{cholmod_dense}
function Dense{Tv}(ptr::Ptr{cholmod_dense}) where Tv<:VTypes
if ptr == C_NULL
throw(ArgumentError("dense matrix construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(ptr)
if s.xtype != xtyp(Tv)
free!(ptr)
throw(CHOLMODException("xtype=$(s.xtype) not supported"))
elseif s.dtype != dtyp(Tv)
free!(ptr)
throw(CHOLMODException("dtype=$(s.dtype) not supported"))
end
obj = new(ptr)
finalizer(free!, obj)
return obj
end
end
mutable struct Sparse{Tv<:VTypes, Ti<:ITypes} <: AbstractSparseMatrix{Tv,Ti}
ptr::Ptr{cholmod_sparse}
function Sparse{Tv, Ti}(ptr::Ptr{cholmod_sparse}) where {Tv<:VTypes, Ti<:ITypes}
if ptr == C_NULL
throw(ArgumentError("sparse matrix construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(ptr)
if s.itype != ityp(Ti)
free!(ptr, Ti)
throw(CHOLMODException("Ti=$Ti does not match s.itype=$(s.itype)"))
elseif s.xtype != xtyp(Tv)
free!(ptr, Ti)
throw(CHOLMODException("xtype=$(s.xtype) not supported"))
elseif s.dtype != dtyp(Tv)
free!(ptr, Ti)
throw(CHOLMODException("dtype=$(s.dtype) not supported"))
end
A = new(ptr)
finalizer(free!, A)
return A
end
end
function Sparse{Tv}(ptr::Ptr{cholmod_sparse}) where Tv
if ptr == C_NULL
throw(ArgumentError("sparse matrix construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(ptr)
return Sparse{Tv, jlitype(s.itype)}(ptr)
end
# Useful when reading in files, but not type stable
function Sparse(p::Ptr{cholmod_sparse})
if p == C_NULL
throw(ArgumentError("sparse matrix construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(p)
Sparse{jlxtype(s.xtype, s.dtype)}(p)
end
mutable struct Factor{Tv<:VTypes, Ti<:ITypes} <: Factorization{Tv}
ptr::Ptr{cholmod_factor}
function Factor{Tv, Ti}(ptr::Ptr{cholmod_factor}, register_finalizer = true) where {Tv, Ti}
if ptr == C_NULL
throw(ArgumentError("factorization construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(ptr)
if s.itype != ityp(Ti)
free!(ptr, Ti)
throw(CHOLMODException("Ti=$Ti does not match s.itype=$(s.itype)"))
elseif s.xtype != xtyp(Tv) && s.xtype != CHOLMOD_PATTERN
free!(ptr, Ti)
throw(CHOLMODException("xtype=$(s.xtype) not supported"))
elseif s.dtype != dtyp(Tv)
free!(ptr, Ti)
throw(CHOLMODException("dtype=$(s.dtype) not supported"))
end
F = new(ptr)
if register_finalizer
finalizer(free!, F)
end
return F
end
end
function Factor{Tv}(ptr::Ptr{cholmod_factor}) where Tv
if ptr == C_NULL
throw(ArgumentError("factorization construction failed for " *
"unknown reasons. Please submit a bug report."))
end
s = unsafe_load(ptr)
return Factor{Tv, jlitype(s.itype)}(ptr)
end
const SuiteSparseStruct = Union{cholmod_dense, cholmod_sparse, cholmod_factor}
# All pointer loads should be checked to make sure that SuiteSparse is not called with
# a C_NULL pointer which could cause a segfault. Pointers are set to null
# when serialized so this can happen when multiple processes are in use.
function Base.unsafe_convert(::Type{Ptr{T}}, x::Union{Dense,Sparse,Factor}) where T<:SuiteSparseStruct
xp = getfield(x, :ptr)
if xp == C_NULL
throw(ArgumentError("pointer to the $T object is null. This can " *
"happen if the object has been serialized."))
else
return xp
end
end
Base.pointer(x::Dense{Tv}) where {Tv} = Base.unsafe_convert(Ptr{cholmod_dense}, x)
Base.pointer(x::Sparse{Tv}) where {Tv} = Base.unsafe_convert(Ptr{cholmod_sparse}, x)
Base.pointer(x::Factor{Tv}) where {Tv} = Base.unsafe_convert(Ptr{cholmod_factor}, x)
# FactorComponent, for encoding particular factors from a factorization
mutable struct FactorComponent{Tv, S, Ti} <: AbstractMatrix{Tv}
F::Factor{Tv, Ti}
function FactorComponent{Tv, S, Ti}(F::Factor{Tv, Ti}) where {Tv, S, Ti}
s = unsafe_load(pointer(F))
if s.is_ll != 0
if !(S === :L || S === :U || S === :PtL || S === :UP)
throw(CHOLMODException(string(S, " not supported for sparse ",
"LLt matrices; try :L, :U, :PtL, or :UP")))
end
elseif !(S === :L || S === :U || S === :PtL || S === :UP ||
S === :D || S === :LD || S === :DU || S === :PtLD || S === :DUP)
throw(CHOLMODException(string(S, " not supported for sparse LDLt ",
"matrices; try :L, :U, :PtL, :UP, :D, :LD, :DU, :PtLD, or :DUP")))
end
new(F)
end
end
function FactorComponent{Tv, S}(F::Factor{Tv, Ti}) where {Tv, S, Ti}
return FactorComponent{Tv, S, Ti}(F)
end
function FactorComponent(F::Factor{Tv, Ti}, sym::Symbol) where {Tv, Ti}
FactorComponent{Tv, sym, Ti}(F)
end
Factor(FC::FactorComponent) = FC.F
#################
# Thin wrappers #
#################
# Dense wrappers
# The ifelse here may be unnecessary.
# nothing different actually occurs in cholmod_l_allocate vs cholmod_allocate AFAICT.
# And CHOLMOD has no way of tracking the difference internally (no internal itype field).
# This leads me to believe they can be mixed with long and int versions of sparse freely.
# Julia will take care of erroring on conversion from Integer -> size_t due to overflow.
@static if sizeof(Int) == 4
function allocate_dense(m::Integer, n::Integer, d::Integer, ::Type{Tv}) where {Tv<:VTypes}
Dense{Tv}(cholmod_allocate_dense(m, n, d, xdtyp(Tv), getcommon()))
end
function free!(p::Ptr{cholmod_dense})
cholmod_free_dense(Ref(p), getcommon()) == TRUE
end
function zeros(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_zeros(m, n, xdtyp(Tv), getcommon()))
end
function ones(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_ones(m, n, xdtyp(Tv), getcommon()))
end
function eye(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_eye(m, n, xdtyp(Tv), getcommon()))
end
function copy(A::Dense{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_copy_dense(A, getcommon()))
end
function check_dense(A::Dense{Tv}) where Tv<:VTypes
cholmod_check_dense(pointer(A), getcommon()) != 0
end
function norm_dense(D::Dense{Tv}, p::Integer) where Tv<:VTypes
s = unsafe_load(pointer(D))
if p == 2
if s.ncol > 1
throw(ArgumentError("2 norm only supported when matrix has one column"))
end
elseif p != 0 && p != 1
throw(ArgumentError("second argument must be either 0 (Inf norm), 1, or 2"))
end
cholmod_norm_dense(D, p, getcommon())
end
else
function allocate_dense(m::Integer, n::Integer, d::Integer, ::Type{Tv}) where {Tv<:VTypes}
Dense{Tv}(cholmod_l_allocate_dense(m, n, d, xdtyp(Tv), getcommon()))
end
function free!(p::Ptr{cholmod_dense})
cholmod_l_free_dense(Ref(p), getcommon()) == TRUE
end
function zeros(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_l_zeros(m, n, xdtyp(Tv), getcommon()))
end
function ones(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_l_ones(m, n, xdtyp(Tv), getcommon()))
end
function eye(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_l_eye(m, n, xdtyp(Tv), getcommon()))
end
function copy(A::Dense{Tv}) where Tv<:VTypes
Dense{Tv}(cholmod_l_copy_dense(A, getcommon()))
end
function check_dense(A::Dense{Tv}) where Tv<:VTypes
cholmod_l_check_dense(pointer(A), getcommon()) != 0
end
function norm_dense(D::Dense{Tv}, p::Integer) where Tv<:VTypes
s = unsafe_load(pointer(D))
if p == 2
if s.ncol > 1
throw(ArgumentError("2 norm only supported when matrix has one column"))
end
elseif p != 0 && p != 1
throw(ArgumentError("second argument must be either 0 (Inf norm), 1, or 2"))
end
cholmod_l_norm_dense(D, p, getcommon())
end
end
zeros(m::Integer, n::Integer) = zeros(m, n, Float64)
ones(m::Integer, n::Integer) = ones(m, n, Float64)
eye(m::Integer, n::Integer) = eye(m, n, Float64)
eye(n::Integer, ::Type{Tv}) where Tv = eye(n, n, Tv)
eye(n::Integer) = eye(n, Float64)
# Non-Dense wrappers
for TI ∈ IndexTypes
@eval begin
mutable struct $(cholname(:sparse_struct_typed, TI))
nrow::Csize_t
ncol::Csize_t
nzmax::Csize_t
p::Ptr{$TI}
i::Ptr{$TI}
nz::Ptr{$TI}
x::Ptr{Cvoid}
z::Ptr{Cvoid}
stype::Cint
itype::Cint
xtype::Cint
dtype::Cint
sorted::Cint
packed::Cint
cholmod_sparse_struct() = new()
end
typedpointer(x::Sparse{<:Any, $TI}) = Ptr{$(cholname(:sparse_struct_typed, TI))}(pointer(x))
mutable struct $(cholname(:factor_struct_typed, TI))
n::Csize_t
minor::Csize_t
Perm::Ptr{$TI}
ColCount::Ptr{$TI}
IPerm::Ptr{$TI}
nzmax::Csize_t
p::Ptr{$TI}
i::Ptr{$TI}
x::Ptr{Cvoid}
z::Ptr{Cvoid}
nz::Ptr{$TI}
next::Ptr{$TI}
prev::Ptr{$TI}
nsuper::Csize_t
ssize::Csize_t
xsize::Csize_t
maxcsize::Csize_t
maxesize::Csize_t
super::Ptr{$TI}
pi::Ptr{$TI}
px::Ptr{$TI}
s::Ptr{$TI}
ordering::Cint
is_ll::Cint
is_super::Cint
is_monotonic::Cint
itype::Cint
xtype::Cint
dtype::Cint
useGPU::Cint
cholmod_factor_struct() = new()
end
typedpointer(x::Factor{<:Any, $TI}) = Ptr{$(cholname(:factor_struct_typed, TI))}(pointer(x))
function sort!(S::Sparse{<:VTypes, $TI})
$(cholname(:sort, TI))(S, getcommon($TI))
return S
end
function allocate_sparse(nrow::Integer, ncol::Integer, nzmax::Integer,
sorted::Bool, packed::Bool, stype::Integer, ::Type{Tv}, ::Type{$TI}) where {Tv<:VTypes}
Sparse{Tv, $TI}($(cholname(:allocate_sparse, TI))(nrow, ncol, nzmax, sorted,
packed, stype, xdtyp(Tv), getcommon($TI)))
end
function free!(ptr::Ptr{cholmod_sparse}, ::Type{$TI})
$(cholname(:free_sparse, TI))(Ref(ptr), getcommon($TI)) == TRUE
end
function free!(ptr::Ptr{cholmod_factor}, ::Type{$TI})
# Warning! Important that finalizer doesn't modify the global Common struct.
$(cholname(:free_factor, TI))(Ref(ptr), getcommon($TI)) == TRUE
end
function aat(A::Sparse{Tv, $TI}, fset::Vector{<:Integer}, mode::Integer) where Tv<:VRealTypes
Sparse{Tv, $TI}($(cholname(:aat, TI))(A, convert(Vector{$TI}, fset), length(fset), mode, getcommon($TI)))
end
function sparse_to_dense(A::Sparse{Tv, $TI}) where Tv<:VTypes
Dense{Tv}($(cholname(:sparse_to_dense, TI))(A, getcommon($TI)))
end
function dense_to_sparse(D::Dense{Tv}, ::Type{$TI}) where Tv<:VTypes
Sparse{Tv, $TI}($(cholname(:dense_to_sparse, TI))(D, true, getcommon($TI)))
end
function factor_to_sparse!(F::Factor{Tv, $TI}) where Tv<:VTypes
ss = unsafe_load(pointer(F))
ss.xtype == CHOLMOD_PATTERN && throw(CHOLMODException("only numeric factors are supported"))
Sparse{Tv, $TI}($(cholname(:factor_to_sparse, TI))(F, getcommon($TI)))
end
# changing single <=> double precision is not supported
function change_factor!(F::Factor{Tv, $TI}, to_ll::Bool, to_super::Bool, to_packed::Bool,
to_monotonic::Bool) where Tv<:VTypes
$(cholname(:change_factor, TI))(xtyp(Tv), to_ll, to_super, to_packed, to_monotonic, F, getcommon($TI)) == TRUE
end
function check_sparse(A::Sparse{Tv, $TI}) where Tv<:VTypes
$(cholname(:check_sparse, TI))(A, getcommon($TI)) != 0
end
function check_factor(F::Factor{Tv, $TI}) where Tv<:VTypes
$(cholname(:check_factor, TI))(F, getcommon($TI)) != 0
end
nnz(A::Sparse{<:VTypes, $TI}) = $(cholname(:nnz, TI))(A, getcommon($TI))
function speye(m::Integer, n::Integer, ::Type{Tv}, ::Type{$TI}) where Tv<:VTypes
Sparse{Tv, $TI}($(cholname(:speye, TI))(m, n, xdtyp(Tv), getcommon($TI)))
end
function spzeros(m::Integer, n::Integer, nzmax::Integer, ::Type{Tv}, ::Type{$TI}) where Tv<:VTypes
Sparse{Tv, $TI}($(cholname(:spzeros, TI))(m, n, nzmax, xdtyp(Tv), getcommon($TI)))
end
function transpose_(A::Sparse{Tv, $TI}, values::Integer) where Tv<:VTypes
Sparse{Tv, $TI}($(cholname(:transpose, TI))(A, values, getcommon($TI)))
end
function copy(F::Factor{Tv, $TI}) where Tv<:VTypes
Factor{Tv, $TI}($(cholname(:copy_factor, TI))(F, getcommon($TI)))
end
function copy(A::Sparse{Tv, $TI}) where Tv<:VTypes
Sparse{Tv, $TI}($(cholname(:copy_sparse, TI))(A, getcommon($TI)))
end
function copy(A::Sparse{Tv, $TI}, stype::Integer, mode::Integer) where Tv<:VRealTypes
Sparse{Tv, $TI}($(cholname(:copy, TI))(A, stype, mode, getcommon($TI)))
end
function print_sparse(A::Sparse{Tv, $TI}, name::String) where Tv<:VTypes
isascii(name) || error("non-ASCII name: $name")
@cholmod_param print = 3 begin
$(cholname(:print_sparse, TI))(A, name, getcommon($TI))
end
nothing
end
function print_factor(F::Factor{Tv, $TI}, name::String) where Tv<:VTypes
@cholmod_param print = 3 begin
$(cholname(:print_factor, TI))(F, name, getcommon($TI))
end
nothing
end
function ssmult(A::Sparse{Tv, $TI}, B::Sparse{Tv, $TI}, stype::Integer,
values::Integer, sorted::Bool) where Tv<:VTypes
lA = unsafe_load(pointer(A))
lB = unsafe_load(pointer(B))
if lA.ncol != lB.nrow
throw(DimensionMismatch("inner matrix dimensions do not fit"))
end
return Sparse{Tv, $TI}($(cholname(:ssmult, TI))(A, B, stype, values, sorted, getcommon($TI)))
end
function norm_sparse(A::Sparse{Tv, $TI}, norm::Integer) where Tv<:VTypes
if norm != 0 && norm != 1
throw(ArgumentError("norm argument must be either 0 or 1"))
end
$(cholname(:norm_sparse, TI))(A, norm, getcommon($TI))
end
function horzcat(A::Sparse{Tv, $TI}, B::Sparse{Tv, $TI}, values::Bool) where Tv<:VRealTypes
Sparse{Tv, $TI}($(cholname(:horzcat, TI))(A, B, values, getcommon($TI)))
end
function scale!(S::Dense{Tv}, scale::Integer, A::Sparse{Tv, $TI}) where Tv<:VTypes
sS = unsafe_load(pointer(S))
sA = unsafe_load(pointer(A))
if sS.ncol != 1 && sS.nrow != 1
throw(DimensionMismatch("first argument must be a vector"))
end
if scale == CHOLMOD_SCALAR && sS.nrow != 1
throw(DimensionMismatch("scaling argument must have length one"))
elseif scale == CHOLMOD_ROW && sS.nrow*sS.ncol != sA.nrow
throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " *
"but matrix has $(sA.nrow) rows."))
elseif scale == CHOLMOD_COL && sS.nrow*sS.ncol != sA.ncol
throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " *
"but matrix has $(sA.ncol) columns"))
elseif scale == CHOLMOD_SYM
if sA.nrow != sA.ncol
throw(DimensionMismatch("matrix must be square"))
elseif sS.nrow*sS.ncol != sA.nrow
throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " *
"but matrix has $(sA.ncol) columns and rows"))
end
end
sA = unsafe_load(pointer(A))
$(cholname(:scale, TI))(S, scale, A, getcommon($TI))
return A
end
function sdmult!(A::Sparse{Tv, $TI}, transpose::Bool,
α::Number, β::Number, X::Dense{Tv}, Y::Dense{Tv}) where Tv<:VTypes
m, n = size(A)
nc = transpose ? m : n
nr = transpose ? n : m
if nc != size(X, 1)
throw(DimensionMismatch("incompatible dimensions, $nc and $(size(X,1))"))
end
$(cholname(:sdmult, TI))(A, transpose, [real(α), imag(α)], [real(β), imag(β)], X, Y, getcommon($TI))
Y
end
function vertcat(A::Sparse{Tv, $TI}, B::Sparse{Tv, $TI}, values::Bool) where Tv<:VRealTypes
Sparse{Tv, $TI}($(cholname(:vertcat, TI))(A, B, values, getcommon($TI)))
end
function symmetry(A::Sparse{Tv, $TI}, option::Integer) where Tv<:VTypes
xmatched = Ref{$TI}()
pmatched = Ref{$TI}()
nzoffdiag = Ref{$TI}()
nzdiag = Ref{$TI}()
rv = $(cholname(:symmetry, TI))(A, option, xmatched, pmatched,
nzoffdiag, nzdiag, getcommon($TI))
rv, xmatched[], pmatched[], nzoffdiag[], nzdiag[]
end
# For analyze, analyze_p, and factorize_p!, the Common argument must be
# supplied in order to control if the factorization is LLt or LDLt
function analyze(A::Sparse{Tv, $TI}) where Tv<:VTypes
return Factor{Tv, $TI}($(cholname(:analyze, TI))(A, getcommon($TI)))
end
function analyze_p(A::Sparse{Tv, $TI}, perm::Vector{$TI}) where Tv<:VTypes
length(perm) != size(A,1) && throw(BoundsError())
Factor{Tv, $TI}($(cholname(:analyze_p, TI))(A, perm, C_NULL, 0, getcommon($TI)))
end
function factorize!(A::Sparse{Tv, $TI}, F::Factor{Tv, $TI}) where Tv<:VTypes
$(cholname(:factorize, TI))(A, F, getcommon($TI))
return F
end
function factorize_p!(A::Sparse{Tv, $TI}, β::Real, F::Factor{Tv, $TI}) where Tv<:VTypes
# note that β is passed as a complex number (double beta[2]),
# but the CHOLMOD manual says that only beta[0] (real part) is used
$(cholname(:factorize_p, TI))(A, Float64[β, 0], C_NULL, 0, F, getcommon($TI))
return F
end
function solve(sys::Integer, F::Factor{Tv, $TI}, B::Dense{Tv}) where Tv<:VTypes
if size(F,1) != size(B,1)
throw(DimensionMismatch("LHS and RHS should have the same number of rows. " *
"LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows."))
end
if !issuccess(F)
s = unsafe_load(pointer(F))
if s.is_ll == 1
throw(LinearAlgebra.PosDefException(s.minor))
else
throw(LinearAlgebra.ZeroPivotException(s.minor))
end
end
Dense{Tv}($(cholname(:solve, TI))(sys, F, B, getcommon($TI)))
end
function spsolve(sys::Integer, F::Factor{Tv, $TI}, B::Sparse{Tv, $TI}) where Tv<:VTypes
if size(F,1) != size(B,1)
throw(DimensionMismatch("LHS and RHS should have the same number of rows. " *
"LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows."))
end
Sparse{Tv, $TI}($(cholname(:spsolve, TI))(sys, F, B, getcommon($TI)))
end
# Autodetects the types
# TODO: does this need another Sparse method to autodetect index type?
function read_sparse(file::Libc.FILE, ::Type{$TI})
Sparse($(cholname(:read_sparse, TI))(file.ptr, getcommon($TI)))
end
function read_sparse(file::Libc.FILE, ::Type{Tv}, ::Type{$TI}) where Tv
Sparse($(cholname(:read_sparse2, TI))(file.ptr, dtyp(Tv), getcommon($TI)))
end
function lowrankupdowndate!(F::Factor{Tv, $TI}, C::Sparse{Tv, $TI}, update::Cint) where Tv<:VTypes
lF = unsafe_load(pointer(F))
lC = unsafe_load(pointer(C))
if lF.n != lC.nrow
throw(DimensionMismatch("matrix dimensions do not fit"))
end
$(cholname(:updown, TI))(update, C, F, getcommon($TI))
return F
end
# TODO: Change these to new methods in CHOLMOD v5.2 when available.
# As this currently double copies.
function change_xdtype(A::Sparse{Tv, $TI}, ::Type{Tnew}) where {Tv<:VTypes, Tnew<:VTypes}
s = $(cholname(:copy_sparse, TI))(A, getcommon($TI))
$(cholname(:sparse_xtype, TI))(xdtyp(Tnew), s, getcommon($TI))
return Sparse{Tnew, $TI}(s)
end
function change_xdtype(F::Factor{Tv, $TI}, ::Type{Tnew}) where {Tv<:VTypes, Tnew<:VTypes}
c = $(cholname(:copy_factor, TI))(F, getcommon($TI))
$(cholname(:factor_xtype, TI))(xdtyp(Tnew), c, getcommon($TI))
return Factor{Tnew, $TI}(c)
end
end
end
# promotion functions for the strictly single typed functions above:
function ssmult(A::Sparse{Tv1, Ti1}, B::Sparse{Tv2, Ti2}, stype::Integer,
values::Integer, sorted::Bool) where {Tv1, Tv2, Ti1, Ti2}
if size(A, 2) != size(B, 1)
throw(DimensionMismatch("inner matrix dimensions do not fit"))
end
A, B = convert.(Sparse{promote_type(Tv1, Tv2), promote_type(Ti1, Ti2)}, (A, B))
return ssmult(A, B, stype, values, sorted)
end
function horzcat(A::Sparse{Tv1, Ti1}, B::Sparse{Tv2, Ti2}, values::Bool) where
{Tv1<:VRealTypes, Tv2<:VRealTypes, Ti1, Ti2}
A, B = convert.(Sparse{promote_type(Tv1, Tv2), promote_type(Ti1, Ti2)}, (A, B))
return horzcat(A, B, values)
end
function scale!(S::Dense, scale::Integer, A::Sparse{Tv}) where {Tv}
S = convert(Dense{Tv}, S)
return scale!(S, scale, A)
end
function sdmult!(A::Sparse{Tv1, Ti}, transpose::Bool,
α::Number, β::Number, X::Dense{Tv2}, Y::Dense{Tv3}) where {Tv1, Ti, Tv2, Tv3}
A, X = convert(Sparse{Tv3, Ti}, A), convert(Dense{Tv3}, X)
return sdmult!(A, transpose, α, β, X, Y)
end
function vertcat(A::Sparse{Tv1, Ti1}, B::Sparse{Tv2, Ti2}, values::Bool) where
{Tv1<:VRealTypes, Ti1, Tv2<:VRealTypes, Ti2}
A, B = convert.(Sparse{promote_type(Tv1, Tv2), promote_type(Ti1, Ti2)}, (A, B))
return vertcat(A, B, values)
end
function analyze_p(A::Sparse{Tv, Ti}, perm::Vector{<:Integer}) where {Tv, Ti}
length(perm) != size(A,1) && throw(BoundsError())
perm = convert(Vector{Ti}, perm)
analyze_p(A, perm)
end
function factorize!(A::Sparse, F::Factor{Tv, Ti}) where {Tv, Ti}
return factorize!(convert(Sparse{Tv, Ti}, A), F)
end
function factorize_p!(A::Sparse, β::Real, F::Factor{Tv, Ti}) where {Tv, Ti}
return factorize_p!(convert(Sparse{Tv, Ti}, A), β, F)
end
function solve(sys::Integer, F::Factor{Tv1}, B::Dense{Tv2}) where {Tv1, Tv2}
if size(F,1) != size(B,1)
throw(DimensionMismatch("LHS and RHS should have the same number of rows. " *
"LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows."))
end
if !issuccess(F)
s = unsafe_load(pointer(F))
if s.is_ll == 1
throw(LinearAlgebra.PosDefException(s.minor))
else
throw(LinearAlgebra.ZeroPivotException(s.minor))
end
end
T = promote_type(Tv1, Tv2)
return solve(sys, T === Tv1 ? F : change_xdtype(F, T), convert(Dense{T}, B))
end
# No method at this time to change the Ti type of a factorization.
function spsolve(sys::Integer, F::Factor{Tv1, Ti1}, B::Sparse{Tv2}) where {Tv1, Ti1, Tv2}
if size(F,1) != size(B,1)
throw(DimensionMismatch("LHS and RHS should have the same number of rows. " *
"LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows."))
end
T = promote_type(Tv1, Tv2)
return spsolve(sys, T === Tv1 ? F : change_xdtype(F, T), convert(Sparse{T, Ti1}, B))
end
function lowrankupdowndate!(F::Factor{Tv, Ti}, C::Sparse, update::Cint) where {Tv, Ti}
return lowrankupdowndate!(F, convert(Sparse{Tv, Ti}, C), update)
end
function speye(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes
speye(m, n, Tv, Int)
end
function spzeros(m::Integer, n::Integer, nzmax::Integer, ::Type{Tv}) where Tv<:VTypes
spzeros(m, n, nzmax, Tv, Int)
end
function read_sparse(file::IO, Tv, Ti)
cfile = Libc.FILE(file)
try return read_sparse(cfile, Tv, Ti)
finally close(cfile)
end
end
read_sparse(file::IO, Ti) = read_sparse(file, Float64, Ti)
function get_perm(F::Factor)
s = unsafe_load(typedpointer(F))
p = unsafe_wrap(Array, s.Perm, s.n, own = false)
p .+ 1
end
get_perm(FC::FactorComponent) = get_perm(Factor(FC))
#########################
# High level interfaces #
#########################
# Conversion/construction
function Dense{T}(A::StridedVecOrMatInclAdjAndTrans) where T<:VTypes
d = allocate_dense(size(A, 1), size(A, 2), A isa StridedVecOrMat ? stride(A, 2) : size(A, 1), T)
D = unsafe_wrap(Array, Ptr{eltype(d)}(unsafe_load(pointer(d)).x), size(A), own = false)
copyto!(D, A)
return d
end
function Dense(A::StridedVecOrMatInclAdjAndTrans)
T = promote_type(eltype(A), Float64)
return Dense{T}(A)
end
# Don't always promote to Float64 now that we have Float32 support.
Dense(A::StridedVecOrMatInclAdjAndTrans{T}) where
{T<:Union{Float16, ComplexF16, Float32, ComplexF32}} = Dense{promote_type(T, Float32)}(A)
Dense(A::Sparse) = sparse_to_dense(A)
function Base.convert(::Type{Dense{Tnew}}, A::Dense{T}) where {Tnew, T}
GC.@preserve A begin
Ap = unsafe_load(pointer(A))
d = allocate_dense(size(A)..., Ap.d, Tnew)
Ax = unsafe_wrap(Array, Ptr{eltype(A)}(Ap.x), size(A), own = false)
D = unsafe_wrap(Array, Ptr{eltype(d)}(unsafe_load(pointer(d)).x), size(A), own = false)
copyto!(D, Ax)
end
return d
end
Base.convert(::Type{Dense{T}}, A::Dense{T}) where T = A
# This constructor assumes zero based colptr and rowval
function Sparse(m::Integer, n::Integer,
colptr0::Vector{Ti}, rowval0::Vector{Ti},
nzval::Vector{Tv}, stype) where {Tv<:VTypes, Ti<:ITypes}
# checks
## length of input
if length(colptr0) <= n
throw(ArgumentError("length of colptr0 must be at least n + 1 = $(n + 1) but was $(length(colptr0))"))
end
if colptr0[n + 1] > length(rowval0)
throw(ArgumentError("length of rowval0 is $(length(rowval0)) but value of colptr0 requires length to be at least $(colptr0[n + 1])"))
end
if colptr0[n + 1] > length(nzval)
throw(ArgumentError("length of nzval is $(length(nzval)) but value of colptr0 requires length to be at least $(colptr0[n + 1])"))
end
## columns are sorted
iss = true
for i = 2:length(colptr0)
if !issorted(view(rowval0, colptr0[i - 1] + 1:colptr0[i]))
iss = false
break
end
end
o = allocate_sparse(m, n, colptr0[n + 1], iss, true, stype, Tv, Ti)
s = unsafe_load(typedpointer(o))
unsafe_copyto!(s.p, pointer(colptr0), n + 1)
unsafe_copyto!(s.i, pointer(rowval0), colptr0[n + 1])
unsafe_copyto!(Ptr{Tv}(s.x), pointer(nzval) , colptr0[n + 1])
check_sparse(o)
return o
end
function Sparse(m::Integer, n::Integer,
colptr0::Vector{Ti},
rowval0::Vector{Ti},
nzval::Vector{<:VTypes}) where {Ti<:ITypes}
o = Sparse(m, n, colptr0, rowval0, nzval, 0)
# sort indices
sort!(o)
# check if array is symmetric and change stype if it is
if ishermitian(o)
change_stype!(o, -1)
end
o
end
function Sparse{Tv, Ti}(A::SparseMatrixCSC{<:Any}, stype::Integer) where {Tv<:VTypes, Ti<:ITypes}
## Check length of input. This should never fail but see #20024
if length(getcolptr(A)) <= size(A, 2)
throw(ArgumentError("length of colptr must be at least size(A,2) + 1 = $(size(A, 2) + 1) but was $(length(getcolptr(A)))"))
end
if nnz(A) > length(rowvals(A))
throw(ArgumentError("length of rowval is $(length(rowvals(A))) but value of colptr requires length to be at least $(nnz(A))"))
end
if nnz(A) > length(nonzeros(A))
throw(ArgumentError("length of nzval is $(length(nonzeros(A))) but value of colptr requires length to be at least $(nnz(A))"))
end
o = allocate_sparse(size(A, 1), size(A, 2), nnz(A), true, true, stype, Tv, Ti)
s = unsafe_load(typedpointer(o))
for i = 1:(size(A, 2) + 1)
unsafe_store!(s.p, getcolptr(A)[i] - 1, i)
end
for i = 1:nnz(A)
unsafe_store!(s.i, rowvals(A)[i] - 1, i)
end
if Tv <: Complex && stype != 0
# Need to remove any non real elements in the diagonal because, in contrast to
# BLAS/LAPACK these are not ignored by CHOLMOD. If even tiny imaginary parts are
# present CHOLMOD will fail with a non-positive definite/zero pivot error.
for j = 1:size(A, 2)
for ip = getcolptr(A)[j]:getcolptr(A)[j + 1] - 1
v = nonzeros(A)[ip]
unsafe_store!(Ptr{Tv}(s.x), rowvals(A)[ip] == j ? Complex(real(v)) : v, ip)
end
end
elseif Tv == eltype(nonzeros(A))
unsafe_copyto!(Ptr{Tv}(s.x), pointer(nonzeros(A)), nnz(A))
else