-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
dense.jl
1695 lines (1470 loc) · 49.9 KB
/
dense.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
# Linear algebra functions for dense matrices in column major format
## BLAS cutoff threshold constants
#TODO const DOT_CUTOFF = 128
const ASUM_CUTOFF = 32
const NRM2_CUTOFF = 32
# Generic cross-over constant based on benchmarking on a single thread with an i7 CPU @ 2.5GHz
# L1 cache: 32K, L2 cache: 256K, L3 cache: 6144K
# This constant should ideally be determined by the actual CPU cache size
const ISONE_CUTOFF = 2^21 # 2M
function isone(A::AbstractMatrix)
m, n = size(A)
m != n && return false # only square matrices can satisfy x == one(x)
if sizeof(A) < ISONE_CUTOFF
_isone_triacheck(A, m)
else
_isone_cachefriendly(A, m)
end
end
@inline function _isone_triacheck(A::AbstractMatrix, m::Int)
@inbounds for i in 1:m, j in i:m
if i == j
isone(A[i,i]) || return false
else
iszero(A[i,j]) && iszero(A[j,i]) || return false
end
end
return true
end
# Inner loop over rows to be friendly to the CPU cache
@inline function _isone_cachefriendly(A::AbstractMatrix, m::Int)
@inbounds for i in 1:m, j in 1:m
if i == j
isone(A[i,i]) || return false
else
iszero(A[j,i]) || return false
end
end
return true
end
"""
isposdef!(A) -> Bool
Test whether a matrix is positive definite (and Hermitian) by trying to perform a
Cholesky factorization of `A`, overwriting `A` in the process.
See also [`isposdef`](@ref).
# Examples
```jldoctest
julia> A = [1. 2.; 2. 50.];
julia> isposdef!(A)
true
julia> A
2×2 Matrix{Float64}:
1.0 2.0
2.0 6.78233
```
"""
isposdef!(A::AbstractMatrix) =
ishermitian(A) && isposdef(cholesky!(Hermitian(A); check = false))
"""
isposdef(A) -> Bool
Test whether a matrix is positive definite (and Hermitian) by trying to perform a
Cholesky factorization of `A`.
See also [`isposdef!`](@ref), [`cholesky`](@ref).
# Examples
```jldoctest
julia> A = [1 2; 2 50]
2×2 Matrix{Int64}:
1 2
2 50
julia> isposdef(A)
true
```
"""
isposdef(A::AbstractMatrix) =
ishermitian(A) && isposdef(cholesky(Hermitian(A); check = false))
isposdef(x::Number) = imag(x)==0 && real(x) > 0
function norm(x::StridedVector{T}, rx::Union{UnitRange{TI},AbstractRange{TI}}) where {T<:BlasFloat,TI<:Integer}
if minimum(rx) < 1 || maximum(rx) > length(x)
throw(BoundsError(x, rx))
end
GC.@preserve x BLAS.nrm2(length(rx), pointer(x)+(first(rx)-1)*sizeof(T), step(rx))
end
norm1(x::Union{Array{T},StridedVector{T}}) where {T<:BlasReal} =
length(x) < ASUM_CUTOFF ? generic_norm1(x) : BLAS.asum(x)
norm2(x::Union{Array{T},StridedVector{T}}) where {T<:BlasFloat} =
length(x) < NRM2_CUTOFF ? generic_norm2(x) : BLAS.nrm2(x)
"""
triu!(M, k::Integer)
Return the upper triangle of `M` starting from the `k`th superdiagonal,
overwriting `M` in the process.
# Examples
```jldoctest
julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
5×5 Matrix{Int64}:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
julia> triu!(M, 1)
5×5 Matrix{Int64}:
0 2 3 4 5
0 0 3 4 5
0 0 0 4 5
0 0 0 0 5
0 0 0 0 0
```
"""
function triu!(M::AbstractMatrix, k::Integer)
require_one_based_indexing(M)
m, n = size(M)
for j in 1:min(n, m + k)
for i in max(1, j - k + 1):m
M[i,j] = zero(M[i,j])
end
end
M
end
triu(M::Matrix, k::Integer) = triu!(copy(M), k)
"""
tril!(M, k::Integer)
Return the lower triangle of `M` starting from the `k`th superdiagonal, overwriting `M` in
the process.
# Examples
```jldoctest
julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
5×5 Matrix{Int64}:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
julia> tril!(M, 2)
5×5 Matrix{Int64}:
1 2 3 0 0
1 2 3 4 0
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
```
"""
function tril!(M::AbstractMatrix, k::Integer)
require_one_based_indexing(M)
m, n = size(M)
for j in max(1, k + 1):n
@inbounds for i in 1:min(j - k - 1, m)
M[i,j] = zero(M[i,j])
end
end
M
end
tril(M::Matrix, k::Integer) = tril!(copy(M), k)
"""
fillband!(A::AbstractMatrix, x, l, u)
Fill the band between diagonals `l` and `u` with the value `x`.
"""
function fillband!(A::AbstractMatrix{T}, x, l, u) where T
require_one_based_indexing(A)
m, n = size(A)
xT = convert(T, x)
for j in 1:n
for i in max(1,j-u):min(m,j-l)
@inbounds A[i, j] = xT
end
end
return A
end
diagind(m::Integer, n::Integer, k::Integer=0) =
k <= 0 ? range(1-k, step=m+1, length=min(m+k, n)) : range(k*m+1, step=m+1, length=min(m, n-k))
"""
diagind(M, k::Integer=0)
An `AbstractRange` giving the indices of the `k`th diagonal of the matrix `M`.
See also: [`diag`](@ref), [`diagm`](@ref), [`Diagonal`](@ref).
# Examples
```jldoctest
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> diagind(A,-1)
2:4:6
```
"""
function diagind(A::AbstractMatrix, k::Integer=0)
require_one_based_indexing(A)
diagind(size(A,1), size(A,2), k)
end
"""
diag(M, k::Integer=0)
The `k`th diagonal of a matrix, as a vector.
See also [`diagm`](@ref), [`diagind`](@ref), [`Diagonal`](@ref), [`isdiag`](@ref).
# Examples
```jldoctest
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> diag(A,1)
2-element Vector{Int64}:
2
6
```
"""
diag(A::AbstractMatrix, k::Integer=0) = A[diagind(A,k)]
"""
diagm(kv::Pair{<:Integer,<:AbstractVector}...)
diagm(m::Integer, n::Integer, kv::Pair{<:Integer,<:AbstractVector}...)
Construct a matrix from `Pair`s of diagonals and vectors.
Vector `kv.second` will be placed on the `kv.first` diagonal.
By default the matrix is square and its size is inferred
from `kv`, but a non-square size `m`×`n` (padded with zeros as needed)
can be specified by passing `m,n` as the first arguments.
For repeated diagonal indices `kv.first` the values in the corresponding
vectors `kv.second` will be added.
`diagm` constructs a full matrix; if you want storage-efficient
versions with fast arithmetic, see [`Diagonal`](@ref), [`Bidiagonal`](@ref)
[`Tridiagonal`](@ref) and [`SymTridiagonal`](@ref).
# Examples
```jldoctest
julia> diagm(1 => [1,2,3])
4×4 Matrix{Int64}:
0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0
julia> diagm(1 => [1,2,3], -1 => [4,5])
4×4 Matrix{Int64}:
0 1 0 0
4 0 2 0
0 5 0 3
0 0 0 0
julia> diagm(1 => [1,2,3], 1 => [1,2,3])
4×4 Matrix{Int64}:
0 2 0 0
0 0 4 0
0 0 0 6
0 0 0 0
```
"""
diagm(kv::Pair{<:Integer,<:AbstractVector}...) = _diagm(nothing, kv...)
diagm(m::Integer, n::Integer, kv::Pair{<:Integer,<:AbstractVector}...) = _diagm((Int(m),Int(n)), kv...)
function _diagm(size, kv::Pair{<:Integer,<:AbstractVector}...)
A = diagm_container(size, kv...)
for p in kv
inds = diagind(A, p.first)
for (i, val) in enumerate(p.second)
A[inds[i]] += val
end
end
return A
end
function diagm_size(size::Nothing, kv::Pair{<:Integer,<:AbstractVector}...)
mnmax = mapreduce(x -> length(x.second) + abs(Int(x.first)), max, kv; init=0)
return mnmax, mnmax
end
function diagm_size(size::Tuple{Int,Int}, kv::Pair{<:Integer,<:AbstractVector}...)
mmax = mapreduce(x -> length(x.second) - min(0,Int(x.first)), max, kv; init=0)
nmax = mapreduce(x -> length(x.second) + max(0,Int(x.first)), max, kv; init=0)
m, n = size
(m ≥ mmax && n ≥ nmax) || throw(DimensionMismatch("invalid size=$size"))
return m, n
end
function diagm_container(size, kv::Pair{<:Integer,<:AbstractVector}...)
T = promote_type(map(x -> eltype(x.second), kv)...)
# For some type `T`, `zero(T)` is not a `T` and `zeros(T, ...)` fails.
U = promote_type(T, typeof(zero(T)))
return zeros(U, diagm_size(size, kv...)...)
end
diagm_container(size, kv::Pair{<:Integer,<:BitVector}...) =
falses(diagm_size(size, kv...)...)
"""
diagm(v::AbstractVector)
diagm(m::Integer, n::Integer, v::AbstractVector)
Construct a matrix with elements of the vector as diagonal elements.
By default, the matrix is square and its size is given by
`length(v)`, but a non-square size `m`×`n` can be specified
by passing `m,n` as the first arguments.
# Examples
```jldoctest
julia> diagm([1,2,3])
3×3 Matrix{Int64}:
1 0 0
0 2 0
0 0 3
```
"""
diagm(v::AbstractVector) = diagm(0 => v)
diagm(m::Integer, n::Integer, v::AbstractVector) = diagm(m, n, 0 => v)
function tr(A::Matrix{T}) where T
n = checksquare(A)
t = zero(T)
@inbounds @simd for i in 1:n
t += A[i,i]
end
t
end
_kronsize(A::AbstractMatrix, B::AbstractMatrix) = map(*, size(A), size(B))
_kronsize(A::AbstractMatrix, B::AbstractVector) = (size(A, 1)*length(B), size(A, 2))
_kronsize(A::AbstractVector, B::AbstractMatrix) = (length(A)*size(B, 1), size(B, 2))
"""
kron!(C, A, B)
Computes the Kronecker product of `A` and `B` and stores the result in `C`,
overwriting the existing content of `C`. This is the in-place version of [`kron`](@ref).
!!! compat "Julia 1.6"
This function requires Julia 1.6 or later.
"""
function kron!(C::AbstractVecOrMat, A::AbstractVecOrMat, B::AbstractVecOrMat)
size(C) == _kronsize(A, B) || throw(DimensionMismatch("kron!"))
_kron!(C, A, B)
end
function kron!(c::AbstractVector, a::AbstractVector, b::AbstractVector)
length(c) == length(a) * length(b) || throw(DimensionMismatch("kron!"))
m = firstindex(c)
@inbounds for i in eachindex(a)
ai = a[i]
for k in eachindex(b)
c[m] = ai*b[k]
m += 1
end
end
return c
end
kron!(c::AbstractVecOrMat, a::AbstractVecOrMat, b::Number) = mul!(c, a, b)
kron!(c::AbstractVecOrMat, a::Number, b::AbstractVecOrMat) = mul!(c, a, b)
function _kron!(C, A::AbstractMatrix, B::AbstractMatrix)
m = firstindex(C)
@inbounds for j in axes(A,2), l in axes(B,2), i in axes(A,1)
Aij = A[i,j]
for k in axes(B,1)
C[m] = Aij*B[k,l]
m += 1
end
end
return C
end
function _kron!(C, A::AbstractMatrix, b::AbstractVector)
m = firstindex(C)
@inbounds for j in axes(A,2), i in axes(A,1)
Aij = A[i,j]
for k in eachindex(b)
C[m] = Aij*b[k]
m += 1
end
end
return C
end
function _kron!(C, a::AbstractVector, B::AbstractMatrix)
m = firstindex(C)
@inbounds for l in axes(B,2), i in eachindex(a)
ai = a[i]
for k in axes(B,1)
C[m] = ai*B[k,l]
m += 1
end
end
return C
end
"""
kron(A, B)
Computes the Kronecker product of two vectors, matrices or numbers.
For real vectors `v` and `w`, the Kronecker product is related to the outer product by
`kron(v,w) == vec(w * transpose(v))` or
`w * transpose(v) == reshape(kron(v,w), (length(w), length(v)))`.
Note how the ordering of `v` and `w` differs on the left and right
of these expressions (due to column-major storage).
For complex vectors, the outer product `w * v'` also differs by conjugation of `v`.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> B = [im 1; 1 -im]
2×2 Matrix{Complex{Int64}}:
0+1im 1+0im
1+0im 0-1im
julia> kron(A, B)
4×4 Matrix{Complex{Int64}}:
0+1im 1+0im 0+2im 2+0im
1+0im 0-1im 2+0im 0-2im
0+3im 3+0im 0+4im 4+0im
3+0im 0-3im 4+0im 0-4im
julia> v = [1, 2]; w = [3, 4, 5];
julia> w*transpose(v)
3×2 Matrix{Int64}:
3 6
4 8
5 10
julia> reshape(kron(v,w), (length(w), length(v)))
3×2 Matrix{Int64}:
3 6
4 8
5 10
```
"""
function kron(A::AbstractVecOrMat{T}, B::AbstractVecOrMat{S}) where {T,S}
R = Matrix{promote_op(*,T,S)}(undef, _kronsize(A, B))
return kron!(R, A, B)
end
function kron(a::AbstractVector{T}, b::AbstractVector{S}) where {T,S}
c = Vector{promote_op(*,T,S)}(undef, length(a)*length(b))
return kron!(c, a, b)
end
kron(a::Number, b::Union{Number, AbstractVecOrMat}) = a * b
kron(a::AbstractVecOrMat, b::Number) = a * b
kron(a::AdjointAbsVec, b::AdjointAbsVec) = adjoint(kron(adjoint(a), adjoint(b)))
kron(a::AdjOrTransAbsVec, b::AdjOrTransAbsVec) = transpose(kron(transpose(a), transpose(b)))
# Matrix power
(^)(A::AbstractMatrix, p::Integer) = p < 0 ? power_by_squaring(inv(A), -p) : power_by_squaring(A, p)
function (^)(A::AbstractMatrix{T}, p::Integer) where T<:Integer
# make sure that e.g. [1 1;1 0]^big(3)
# gets promotes in a similar way as 2^big(3)
TT = promote_op(^, T, typeof(p))
return power_by_squaring(convert(AbstractMatrix{TT}, A), p)
end
function integerpow(A::AbstractMatrix{T}, p) where T
TT = promote_op(^, T, typeof(p))
return (TT == T ? A : convert(AbstractMatrix{TT}, A))^Integer(p)
end
function schurpow(A::AbstractMatrix, p)
if istriu(A)
# Integer part
retmat = A ^ floor(p)
# Real part
if p - floor(p) == 0.5
# special case: A^0.5 === sqrt(A)
retmat = retmat * sqrt(A)
else
retmat = retmat * powm!(UpperTriangular(float.(A)), real(p - floor(p)))
end
else
S,Q,d = Schur{Complex}(schur(A))
# Integer part
R = S ^ floor(p)
# Real part
if p - floor(p) == 0.5
# special case: A^0.5 === sqrt(A)
R = R * sqrt(S)
else
R = R * powm!(UpperTriangular(float.(S)), real(p - floor(p)))
end
retmat = Q * R * Q'
end
# if A has nonpositive real eigenvalues, retmat is a nonprincipal matrix power.
if isreal(retmat)
return real(retmat)
else
return retmat
end
end
function (^)(A::AbstractMatrix{T}, p::Real) where T
n = checksquare(A)
# Quicker return if A is diagonal
if isdiag(A)
TT = promote_op(^, T, typeof(p))
retmat = copymutable_oftype(A, TT)
for i in 1:n
retmat[i, i] = retmat[i, i] ^ p
end
return retmat
end
# For integer powers, use power_by_squaring
isinteger(p) && return integerpow(A, p)
# If possible, use diagonalization
if issymmetric(A)
return (Symmetric(A)^p)
end
if ishermitian(A)
return (Hermitian(A)^p)
end
# Otherwise, use Schur decomposition
return schurpow(A, p)
end
"""
^(A::AbstractMatrix, p::Number)
Matrix power, equivalent to ``\\exp(p\\log(A))``
# Examples
```jldoctest
julia> [1 2; 0 3]^3
2×2 Matrix{Int64}:
1 26
0 27
```
"""
(^)(A::AbstractMatrix, p::Number) = exp(p*log(A))
# Matrix exponential
"""
exp(A::AbstractMatrix)
Compute the matrix exponential of `A`, defined by
```math
e^A = \\sum_{n=0}^{\\infty} \\frac{A^n}{n!}.
```
For symmetric or Hermitian `A`, an eigendecomposition ([`eigen`](@ref)) is
used, otherwise the scaling and squaring algorithm (see [^H05]) is chosen.
[^H05]: Nicholas J. Higham, "The squaring and scaling method for the matrix exponential revisited", SIAM Journal on Matrix Analysis and Applications, 26(4), 2005, 1179-1193. [doi:10.1137/090768539](https://doi.org/10.1137/090768539)
# Examples
```jldoctest
julia> A = Matrix(1.0I, 2, 2)
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
julia> exp(A)
2×2 Matrix{Float64}:
2.71828 0.0
0.0 2.71828
```
"""
exp(A::AbstractMatrix) = exp!(copy_similar(A, eigtype(eltype(A))))
exp(A::AdjointAbsMat) = adjoint(exp(parent(A)))
exp(A::TransposeAbsMat) = transpose(exp(parent(A)))
"""
cis(A::AbstractMatrix)
More efficient method for `exp(im*A)` of square matrix `A`
(especially if `A` is `Hermitian` or real-`Symmetric`).
See also [`cispi`](@ref), [`sincos`](@ref), [`exp`](@ref).
!!! compat "Julia 1.7"
Support for using `cis` with matrices was added in Julia 1.7.
# Examples
```jldoctest
julia> cis([π 0; 0 π]) ≈ -I
true
```
"""
cis(A::AbstractMatrix) = exp(im * A) # fallback
cis(A::AbstractMatrix{<:Base.HWNumber}) = exp_maybe_inplace(float.(im .* A))
exp_maybe_inplace(A::StridedMatrix{<:Union{ComplexF32, ComplexF64}}) = exp!(A)
exp_maybe_inplace(A) = exp(A)
"""
^(b::Number, A::AbstractMatrix)
Matrix exponential, equivalent to ``\\exp(\\log(b)A)``.
!!! compat "Julia 1.1"
Support for raising `Irrational` numbers (like `ℯ`)
to a matrix was added in Julia 1.1.
# Examples
```jldoctest
julia> 2^[1 2; 0 3]
2×2 Matrix{Float64}:
2.0 6.0
0.0 8.0
julia> ℯ^[1 2; 0 3]
2×2 Matrix{Float64}:
2.71828 17.3673
0.0 20.0855
```
"""
Base.:^(b::Number, A::AbstractMatrix) = exp!(log(b)*A)
# method for ℯ to explicitly elide the log(b) multiplication
Base.:^(::Irrational{:ℯ}, A::AbstractMatrix) = exp(A)
## Destructive matrix exponential using algorithm from Higham, 2008,
## "Functions of Matrices: Theory and Computation", SIAM
function exp!(A::StridedMatrix{T}) where T<:BlasFloat
n = checksquare(A)
if ishermitian(A)
return copytri!(parent(exp(Hermitian(A))), 'U', true)
end
ilo, ihi, scale = LAPACK.gebal!('B', A) # modifies A
nA = opnorm(A, 1)
## For sufficiently small nA, use lower order Padé-Approximations
if (nA <= 2.1)
if nA > 0.95
C = T[17643225600.,8821612800.,2075673600.,302702400.,
30270240., 2162160., 110880., 3960.,
90., 1.]
elseif nA > 0.25
C = T[17297280.,8648640.,1995840.,277200.,
25200., 1512., 56., 1.]
elseif nA > 0.015
C = T[30240.,15120.,3360.,
420., 30., 1.]
else
C = T[120.,60.,12.,1.]
end
A2 = A * A
# Compute U and V: Even/odd terms in Padé numerator & denom
# Expansion of k=1 in for loop
P = A2
U = mul!(C[4]*P, true, C[2]*I, true, true) #U = C[2]*I + C[4]*P
V = mul!(C[3]*P, true, C[1]*I, true, true) #V = C[1]*I + C[3]*P
for k in 2:(div(length(C), 2) - 1)
P *= A2
mul!(U, C[2k + 2], P, true, true) # U += C[2k+2]*P
mul!(V, C[2k + 1], P, true, true) # V += C[2k+1]*P
end
U = A * U
# Padé approximant: (V-U)\(V+U)
tmp1, tmp2 = A, A2 # Reuse already allocated arrays
tmp1 .= V .- U
tmp2 .= V .+ U
X = LAPACK.gesv!(tmp1, tmp2)[1]
else
s = log2(nA/5.4) # power of 2 later reversed by squaring
if s > 0
si = ceil(Int,s)
A ./= convert(T,2^si)
end
CC = T[64764752532480000.,32382376266240000.,7771770303897600.,
1187353796428800., 129060195264000., 10559470521600.,
670442572800., 33522128640., 1323241920.,
40840800., 960960., 16380.,
182., 1.]
A2 = A * A
A4 = A2 * A2
A6 = A2 * A4
tmp1, tmp2 = similar(A6), similar(A6)
# Allocation economical version of:
# U = A * (A6 * (CC[14].*A6 .+ CC[12].*A4 .+ CC[10].*A2) .+
# CC[8].*A6 .+ CC[6].*A4 .+ CC[4]*A2+CC[2]*I)
tmp1 .= CC[14].*A6 .+ CC[12].*A4 .+ CC[10].*A2
tmp2 .= CC[8].*A6 .+ CC[6].*A4 .+ CC[4].*A2
mul!(tmp2, true,CC[2]*I, true, true) # tmp2 .+= CC[2]*I
U = mul!(tmp2, A6, tmp1, true, true)
U, tmp1 = mul!(tmp1, A, U), A # U = A * U0
# Allocation economical version of:
# V = A6 * (CC[13].*A6 .+ CC[11].*A4 .+ CC[9].*A2) .+
# CC[7].*A6 .+ CC[5].*A4 .+ CC[3]*A2 .+ CC[1]*I
tmp1 .= CC[13].*A6 .+ CC[11].*A4 .+ CC[9].*A2
tmp2 .= CC[7].*A6 .+ CC[5].*A4 .+ CC[3].*A2
mul!(tmp2, true, CC[1]*I, true, true) # tmp2 .+= CC[1]*I
V = mul!(tmp2, A6, tmp1, true, true)
tmp1 .= V .+ U
tmp2 .= V .- U # tmp2 already contained V but this seems more readable
X = LAPACK.gesv!(tmp2, tmp1)[1] # X now contains r_13 in Higham 2008
if s > 0
# Repeated squaring to compute X = r_13^(2^si)
for t=1:si
mul!(tmp2, X, X)
X, tmp2 = tmp2, X
end
end
end
# Undo the balancing
for j = ilo:ihi
scj = scale[j]
for i = 1:n
X[j,i] *= scj
end
for i = 1:n
X[i,j] /= scj
end
end
if ilo > 1 # apply lower permutations in reverse order
for j in (ilo-1):-1:1; rcswap!(j, Int(scale[j]), X) end
end
if ihi < n # apply upper permutations in forward order
for j in (ihi+1):n; rcswap!(j, Int(scale[j]), X) end
end
X
end
## Swap rows i and j and columns i and j in X
function rcswap!(i::Integer, j::Integer, X::AbstractMatrix{<:Number})
for k = 1:size(X,1)
X[k,i], X[k,j] = X[k,j], X[k,i]
end
for k = 1:size(X,2)
X[i,k], X[j,k] = X[j,k], X[i,k]
end
end
"""
log(A::AbstractMatrix)
If `A` has no negative real eigenvalue, compute the principal matrix logarithm of `A`, i.e.
the unique matrix ``X`` such that ``e^X = A`` and ``-\\pi < Im(\\lambda) < \\pi`` for all
the eigenvalues ``\\lambda`` of ``X``. If `A` has nonpositive eigenvalues, a nonprincipal
matrix function is returned whenever possible.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](@ref)) is
used, if `A` is triangular an improved version of the inverse scaling and squaring method is
employed (see [^AH12] and [^AHR13]). If `A` is real with no negative eigenvalues, then
the real Schur form is computed. Otherwise, the complex Schur form is computed. Then
the upper (quasi-)triangular algorithm in [^AHR13] is used on the upper (quasi-)triangular
factor.
[^AH12]: Awad H. Al-Mohy and Nicholas J. Higham, "Improved inverse scaling and squaring algorithms for the matrix logarithm", SIAM Journal on Scientific Computing, 34(4), 2012, C153-C169. [doi:10.1137/110852553](https://doi.org/10.1137/110852553)
[^AHR13]: Awad H. Al-Mohy, Nicholas J. Higham and Samuel D. Relton, "Computing the Fréchet derivative of the matrix logarithm and estimating the condition number", SIAM Journal on Scientific Computing, 35(4), 2013, C394-C410. [doi:10.1137/120885991](https://doi.org/10.1137/120885991)
# Examples
```jldoctest
julia> A = Matrix(2.7182818*I, 2, 2)
2×2 Matrix{Float64}:
2.71828 0.0
0.0 2.71828
julia> log(A)
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
```
"""
function log(A::AbstractMatrix)
# If possible, use diagonalization
if ishermitian(A)
logHermA = log(Hermitian(A))
return ishermitian(logHermA) ? copytri!(parent(logHermA), 'U', true) : parent(logHermA)
elseif istriu(A)
return triu!(parent(log(UpperTriangular(A))))
elseif isreal(A)
SchurF = schur(real(A))
if istriu(SchurF.T)
logA = SchurF.Z * log(UpperTriangular(SchurF.T)) * SchurF.Z'
else
# real log exists whenever all eigenvalues are positive
is_log_real = !any(x -> isreal(x) && real(x) ≤ 0, SchurF.values)
if is_log_real
logA = SchurF.Z * log_quasitriu(SchurF.T) * SchurF.Z'
else
SchurS = Schur{Complex}(SchurF)
logA = SchurS.Z * log(UpperTriangular(SchurS.T)) * SchurS.Z'
end
end
return eltype(A) <: Complex ? complex(logA) : logA
else
SchurF = schur(A)
return SchurF.vectors * log(UpperTriangular(SchurF.T)) * SchurF.vectors'
end
end
log(A::AdjointAbsMat) = adjoint(log(parent(A)))
log(A::TransposeAbsMat) = transpose(log(parent(A)))
"""
sqrt(A::AbstractMatrix)
If `A` has no negative real eigenvalues, compute the principal matrix square root of `A`,
that is the unique matrix ``X`` with eigenvalues having positive real part such that
``X^2 = A``. Otherwise, a nonprincipal square root is returned.
If `A` is real-symmetric or Hermitian, its eigendecomposition ([`eigen`](@ref)) is
used to compute the square root. For such matrices, eigenvalues λ that
appear to be slightly negative due to roundoff errors are treated as if they were zero.
More precisely, matrices with all eigenvalues `≥ -rtol*(max |λ|)` are treated as semidefinite
(yielding a Hermitian square root), with negative eigenvalues taken to be zero.
`rtol` is a keyword argument to `sqrt` (in the Hermitian/real-symmetric case only) that
defaults to machine precision scaled by `size(A,1)`.
Otherwise, the square root is determined by means of the
Björck-Hammarling method [^BH83], which computes the complex Schur form ([`schur`](@ref))
and then the complex square root of the triangular factor.
If a real square root exists, then an extension of this method [^H87] that computes the real
Schur form and then the real square root of the quasi-triangular factor is instead used.
[^BH83]:
Åke Björck and Sven Hammarling, "A Schur method for the square root of a matrix",
Linear Algebra and its Applications, 52-53, 1983, 127-140.
[doi:10.1016/0024-3795(83)80010-X](https://doi.org/10.1016/0024-3795(83)80010-X)
[^H87]:
Nicholas J. Higham, "Computing real square roots of a real matrix",
Linear Algebra and its Applications, 88-89, 1987, 405-430.
[doi:10.1016/0024-3795(87)90118-2](https://doi.org/10.1016/0024-3795(87)90118-2)
# Examples
```jldoctest
julia> A = [4 0; 0 4]
2×2 Matrix{Int64}:
4 0
0 4
julia> sqrt(A)
2×2 Matrix{Float64}:
2.0 0.0
0.0 2.0
```
"""
sqrt(::AbstractMatrix)
function sqrt(A::AbstractMatrix{T}) where {T<:Union{Real,Complex}}
if ishermitian(A)
sqrtHermA = sqrt(Hermitian(A))
return ishermitian(sqrtHermA) ? copytri!(parent(sqrtHermA), 'U', true) : parent(sqrtHermA)
elseif istriu(A)
return triu!(parent(sqrt(UpperTriangular(A))))
elseif isreal(A)
SchurF = schur(real(A))
if istriu(SchurF.T)
sqrtA = SchurF.Z * sqrt(UpperTriangular(SchurF.T)) * SchurF.Z'
else
# real sqrt exists whenever no eigenvalues are negative
is_sqrt_real = !any(x -> isreal(x) && real(x) < 0, SchurF.values)
# sqrt_quasitriu uses LAPACK functions for non-triu inputs
if typeof(sqrt(zero(T))) <: BlasFloat && is_sqrt_real
sqrtA = SchurF.Z * sqrt_quasitriu(SchurF.T) * SchurF.Z'
else
SchurS = Schur{Complex}(SchurF)
sqrtA = SchurS.Z * sqrt(UpperTriangular(SchurS.T)) * SchurS.Z'
end
end
return eltype(A) <: Complex ? complex(sqrtA) : sqrtA
else
SchurF = schur(A)
return SchurF.vectors * sqrt(UpperTriangular(SchurF.T)) * SchurF.vectors'
end
end
sqrt(A::AdjointAbsMat) = adjoint(sqrt(parent(A)))
sqrt(A::TransposeAbsMat) = transpose(sqrt(parent(A)))
function inv(A::StridedMatrix{T}) where T
checksquare(A)
S = typeof((oneunit(T)*zero(T) + oneunit(T)*zero(T))/oneunit(T))
AA = convert(AbstractArray{S}, A)
if istriu(AA)
Ai = triu!(parent(inv(UpperTriangular(AA))))
elseif istril(AA)
Ai = tril!(parent(inv(LowerTriangular(AA))))
else
Ai = inv!(lu(AA))
Ai = convert(typeof(parent(Ai)), Ai)
end
return Ai
end
"""
cos(A::AbstractMatrix)
Compute the matrix cosine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](@ref)) is used to
compute the cosine. Otherwise, the cosine is determined by calling [`exp`](@ref).
# Examples
```jldoctest
julia> cos(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
0.291927 -0.708073
-0.708073 0.291927
```
"""
function cos(A::AbstractMatrix{<:Real})
if issymmetric(A)
return copytri!(parent(cos(Symmetric(A))), 'U')
end
T = complex(float(eltype(A)))
return real(exp!(T.(im .* A)))
end
function cos(A::AbstractMatrix{<:Complex})
if ishermitian(A)
return copytri!(parent(cos(Hermitian(A))), 'U', true)
end
T = complex(float(eltype(A)))
X = exp!(T.(im .* A))
@. X = (X + $exp!(T(-im*A))) / 2
return X
end
"""
sin(A::AbstractMatrix)
Compute the matrix sine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](@ref)) is used to
compute the sine. Otherwise, the sine is determined by calling [`exp`](@ref).
# Examples
```jldoctest
julia> sin(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
0.454649 0.454649
0.454649 0.454649
```
"""
function sin(A::AbstractMatrix{<:Real})
if issymmetric(A)
return copytri!(parent(sin(Symmetric(A))), 'U')
end
T = complex(float(eltype(A)))
return imag(exp!(T.(im .* A)))
end
function sin(A::AbstractMatrix{<:Complex})
if ishermitian(A)
return copytri!(parent(sin(Hermitian(A))), 'U', true)
end
T = complex(float(eltype(A)))
X = exp!(T.(im .* A))
Y = exp!(T.(.-im .* A))
@inbounds for i in eachindex(X)
x, y = X[i]/2, Y[i]/2
X[i] = Complex(imag(x)-imag(y), real(y)-real(x))
end
return X
end
"""
sincos(A::AbstractMatrix)
Compute the matrix sine and cosine of a square matrix `A`.
# Examples
```jldoctest
julia> S, C = sincos(fill(1.0, (2,2)));