-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
generic.jl
2032 lines (1692 loc) · 49.9 KB
/
generic.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
## linalg.jl: Some generic Linear Algebra definitions
# Elements of `out` may not be defined (e.g., for `BigFloat`). To make
# `mul!(out, A, B)` work for such cases, `out .*ₛ beta` short-circuits
# `out * beta`. Using `broadcasted` to avoid the multiplication
# inside this function.
function *ₛ end
Broadcast.broadcasted(::typeof(*ₛ), out, beta) =
iszero(beta::Number) ? false : broadcasted(*, out, beta)
"""
MulAddMul(alpha, beta)
A callable for operating short-circuiting version of `x * alpha + y * beta`.
# Examples
```jldoctest
julia> using LinearAlgebra: MulAddMul
julia> _add = MulAddMul(1, 0);
julia> _add(123, nothing)
123
julia> MulAddMul(12, 34)(56, 78) == 56 * 12 + 78 * 34
true
```
"""
struct MulAddMul{ais1, bis0, TA, TB}
alpha::TA
beta::TB
end
@inline function MulAddMul(alpha::TA, beta::TB) where {TA,TB}
if isone(alpha)
if iszero(beta)
return MulAddMul{true,true,TA,TB}(alpha, beta)
else
return MulAddMul{true,false,TA,TB}(alpha, beta)
end
else
if iszero(beta)
return MulAddMul{false,true,TA,TB}(alpha, beta)
else
return MulAddMul{false,false,TA,TB}(alpha, beta)
end
end
end
"""
@stable_muladdmul
Replaces a function call, that has a `MulAddMul(alpha, beta)` constructor as an
argument, with a branch over possible values of `isone(alpha)` and `iszero(beta)`
and constructs `MulAddMul{isone(alpha), iszero(beta)}` explicitly in each branch.
For example, 'f(x, y, MulAddMul(alpha, beta))` is transformed into
```
if isone(alpha)
if iszero(beta)
f(x, y, MulAddMul{true, true, typeof(alpha), typeof(beta)}(alpha, beta))
else
f(x, y, MulAddMul{true, false, typeof(alpha), typeof(beta)}(alpha, beta))
end
else
if iszero(beta)
f(x, y, MulAddMul{false, true, typeof(alpha), typeof(beta)}(alpha, beta))
else
f(x, y, MulAddMul{false, false, typeof(alpha), typeof(beta)}(alpha, beta))
end
end
```
This avoids the type instability of the `MulAddMul(alpha, beta)` constructor,
which causes runtime dispatch in case alpha and zero are not constants.
"""
macro stable_muladdmul(expr)
expr.head == :call || throw(ArgumentError("Can only handle function calls."))
for (i, e) in enumerate(expr.args)
e isa Expr || continue
if e.head == :call && e.args[1] == :MulAddMul && length(e.args) == 3
local asym = e.args[2]
local bsym = e.args[3]
local e_sub11 = copy(expr)
e_sub11.args[i] = :(MulAddMul{true, true, typeof($asym), typeof($bsym)}($asym, $bsym))
local e_sub10 = copy(expr)
e_sub10.args[i] = :(MulAddMul{true, false, typeof($asym), typeof($bsym)}($asym, $bsym))
local e_sub01 = copy(expr)
e_sub01.args[i] = :(MulAddMul{false, true, typeof($asym), typeof($bsym)}($asym, $bsym))
local e_sub00 = copy(expr)
e_sub00.args[i] = :(MulAddMul{false, false, typeof($asym), typeof($bsym)}($asym, $bsym))
local e_out = quote
if isone($asym)
if iszero($bsym)
$e_sub11
else
$e_sub10
end
else
if iszero($bsym)
$e_sub01
else
$e_sub00
end
end
end
return esc(e_out)
end
end
throw(ArgumentError("No valid MulAddMul expression found."))
end
MulAddMul() = MulAddMul{true,true,Bool,Bool}(true, false)
@inline (::MulAddMul{true})(x) = x
@inline (p::MulAddMul{false})(x) = x * p.alpha
@inline (::MulAddMul{true, true})(x, _) = x
@inline (p::MulAddMul{false, true})(x, _) = x * p.alpha
@inline (p::MulAddMul{true, false})(x, y) = x + y * p.beta
@inline (p::MulAddMul{false, false})(x, y) = x * p.alpha + y * p.beta
"""
_modify!(_add::MulAddMul, x, C, idx)
Short-circuiting version of `C[idx] = _add(x, C[idx])`.
Short-circuiting the indexing `C[idx]` is necessary for avoiding `UndefRefError`
when mutating an array of non-primitive numbers such as `BigFloat`.
# Examples
```jldoctest
julia> using LinearAlgebra: MulAddMul, _modify!
julia> _add = MulAddMul(1, 0);
C = Vector{BigFloat}(undef, 1);
julia> _modify!(_add, 123, C, 1)
julia> C
1-element Vector{BigFloat}:
123.0
```
"""
@inline @propagate_inbounds function _modify!(p::MulAddMul{ais1, bis0},
x, C, idx′) where {ais1, bis0}
# `idx′` may be an integer, a tuple of integer, or a `CartesianIndex`.
# Let `CartesianIndex` constructor normalize them so that it can be
# used uniformly. It also acts as a workaround for performance penalty
# of splatting a number (#29114):
idx = CartesianIndex(idx′)
if bis0
C[idx] = p(x)
else
C[idx] = p(x, C[idx])
end
return
end
@inline function _rmul_or_fill!(C::AbstractArray, beta::Number)
if isempty(C)
return C
end
if iszero(beta)
fill!(C, zero(eltype(C)))
else
rmul!(C, beta)
end
return C
end
function generic_mul!(C::AbstractArray, X::AbstractArray, s::Number, _add::MulAddMul)
if length(C) != length(X)
throw(DimensionMismatch(lazy"first array has length $(length(C)) which does not match the length of the second, $(length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds _modify!(_add, X[IX] * s, C, IC)
end
C
end
function generic_mul!(C::AbstractArray, s::Number, X::AbstractArray, _add::MulAddMul)
if length(C) != length(X)
throw(DimensionMismatch(lazy"first array has length $(length(C)) which does not
match the length of the second, $(length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds _modify!(_add, s * X[IX], C, IC)
end
C
end
@inline mul!(C::AbstractArray, s::Number, X::AbstractArray, alpha::Number, beta::Number) =
_lscale_add!(C, s, X, alpha, beta)
@inline function _lscale_add!(C::AbstractArray, s::Number, X::AbstractArray, alpha::Number, beta::Number)
if axes(C) == axes(X)
C .= (s .* X) .*ₛ alpha .+ C .*ₛ beta
else
generic_mul!(C, s, X, MulAddMul(alpha, beta))
end
return C
end
@inline mul!(C::AbstractArray, X::AbstractArray, s::Number, alpha::Number, beta::Number) =
_rscale_add!(C, X, s, alpha, beta)
@inline function _rscale_add!(C::AbstractArray, X::AbstractArray, s::Number, alpha::Number, beta::Number)
if axes(C) == axes(X)
C .= (X .* s) .*ₛ alpha .+ C .*ₛ beta
else
generic_mul!(C, X, s, MulAddMul(alpha, beta))
end
return C
end
# For better performance when input and output are the same array
# See https://github.com/JuliaLang/julia/issues/8415#issuecomment-56608729
"""
rmul!(A::AbstractArray, b::Number)
Scale an array `A` by a scalar `b` overwriting `A` in-place. Use
[`lmul!`](@ref) to multiply scalar from left. The scaling operation
respects the semantics of the multiplication [`*`](@ref) between an
element of `A` and `b`. In particular, this also applies to
multiplication involving non-finite numbers such as `NaN` and `±Inf`.
!!! compat "Julia 1.1"
Prior to Julia 1.1, `NaN` and `±Inf` entries in `A` were treated
inconsistently.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rmul!(A, 2)
2×2 Matrix{Int64}:
2 4
6 8
julia> rmul!([NaN], 0.0)
1-element Vector{Float64}:
NaN
```
"""
function rmul!(X::AbstractArray, s::Number)
@simd for I in eachindex(X)
@inbounds X[I] *= s
end
X
end
"""
lmul!(a::Number, B::AbstractArray)
Scale an array `B` by a scalar `a` overwriting `B` in-place. Use
[`rmul!`](@ref) to multiply scalar from right. The scaling operation
respects the semantics of the multiplication [`*`](@ref) between `a`
and an element of `B`. In particular, this also applies to
multiplication involving non-finite numbers such as `NaN` and `±Inf`.
!!! compat "Julia 1.1"
Prior to Julia 1.1, `NaN` and `±Inf` entries in `B` were treated
inconsistently.
# Examples
```jldoctest
julia> B = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> lmul!(2, B)
2×2 Matrix{Int64}:
2 4
6 8
julia> lmul!(0.0, [Inf])
1-element Vector{Float64}:
NaN
```
"""
function lmul!(s::Number, X::AbstractArray)
@simd for I in eachindex(X)
@inbounds X[I] = s*X[I]
end
X
end
"""
rdiv!(A::AbstractArray, b::Number)
Divide each entry in an array `A` by a scalar `b` overwriting `A`
in-place. Use [`ldiv!`](@ref) to divide scalar from left.
# Examples
```jldoctest
julia> A = [1.0 2.0; 3.0 4.0]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> rdiv!(A, 2.0)
2×2 Matrix{Float64}:
0.5 1.0
1.5 2.0
```
"""
function rdiv!(X::AbstractArray, s::Number)
@simd for I in eachindex(X)
@inbounds X[I] /= s
end
X
end
"""
ldiv!(a::Number, B::AbstractArray)
Divide each entry in an array `B` by a scalar `a` overwriting `B`
in-place. Use [`rdiv!`](@ref) to divide scalar from right.
# Examples
```jldoctest
julia> B = [1.0 2.0; 3.0 4.0]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> ldiv!(2.0, B)
2×2 Matrix{Float64}:
0.5 1.0
1.5 2.0
```
"""
function ldiv!(s::Number, X::AbstractArray)
@simd for I in eachindex(X)
@inbounds X[I] = s\X[I]
end
X
end
ldiv!(Y::AbstractArray, s::Number, X::AbstractArray) = Y .= s .\ X
# Generic fallback. This assumes that B and Y have the same sizes.
ldiv!(Y::AbstractArray, A::AbstractMatrix, B::AbstractArray) = ldiv!(A, copyto!(Y, B))
"""
cross(x, y)
×(x,y)
Compute the cross product of two 3-vectors.
# Examples
```jldoctest
julia> a = [0;1;0]
3-element Vector{Int64}:
0
1
0
julia> b = [0;0;1]
3-element Vector{Int64}:
0
0
1
julia> cross(a,b)
3-element Vector{Int64}:
1
0
0
```
"""
function cross(a::AbstractVector, b::AbstractVector)
if !(length(a) == length(b) == 3)
throw(DimensionMismatch("cross product is only defined for vectors of length 3"))
end
a1, a2, a3 = a
b1, b2, b3 = b
[a2*b3-a3*b2, a3*b1-a1*b3, a1*b2-a2*b1]
end
"""
triu(M)
Upper triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
0.0 1.0 1.0 1.0
0.0 0.0 1.0 1.0
0.0 0.0 0.0 1.0
```
"""
triu(M::AbstractMatrix) = triu!(copymutable(M))
"""
tril(M)
Lower triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a)
4×4 Matrix{Float64}:
1.0 0.0 0.0 0.0
1.0 1.0 0.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
```
"""
tril(M::AbstractMatrix) = tril!(copymutable(M))
"""
triu(M, k::Integer)
Return the upper triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a,3)
4×4 Matrix{Float64}:
0.0 0.0 0.0 1.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
julia> triu(a,-3)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
```
"""
triu(M::AbstractMatrix,k::Integer) = triu!(copymutable(M),k)
"""
tril(M, k::Integer)
Return the lower triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,3)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,-3)
4×4 Matrix{Float64}:
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0
```
"""
tril(M::AbstractMatrix,k::Integer) = tril!(copymutable(M),k)
"""
triu!(M)
Upper triangle of a matrix, overwriting `M` in the process.
See also [`triu`](@ref).
"""
triu!(M::AbstractMatrix) = triu!(M,0)
"""
tril!(M)
Lower triangle of a matrix, overwriting `M` in the process.
See also [`tril`](@ref).
"""
tril!(M::AbstractMatrix) = tril!(M,0)
diag(A::AbstractVector) = throw(ArgumentError("use diagm instead of diag to construct a diagonal matrix"))
###########################################################################################
# Dot products and norms
# special cases of norm; note that they don't need to handle isempty(x)
generic_normMinusInf(x) = float(mapreduce(norm, min, x))
generic_normInf(x) = float(mapreduce(norm, max, x))
generic_norm1(x) = mapreduce(float ∘ norm, +, x)
# faster computation of norm(x)^2, avoiding overflow for integers
norm_sqr(x) = norm(x)^2
norm_sqr(x::Number) = abs2(x)
norm_sqr(x::Union{T,Complex{T},Rational{T}}) where {T<:Integer} = abs2(float(x))
function generic_norm2(x)
maxabs = normInf(x)
(ismissing(maxabs) || iszero(maxabs) || isinf(maxabs)) && return maxabs
(v, s) = iterate(x)::Tuple
T = typeof(maxabs)
if isfinite(length(x)*maxabs*maxabs) && !iszero(maxabs*maxabs) # Scaling not necessary
sum::promote_type(Float64, T) = norm_sqr(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm_sqr(v)
end
ismissing(sum) && return missing
return convert(T, sqrt(sum))
else
sum = abs2(norm(v)/maxabs)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += (norm(v)/maxabs)^2
end
ismissing(sum) && return missing
return convert(T, maxabs*sqrt(sum))
end
end
# Compute L_p norm ‖x‖ₚ = sum(abs(x).^p)^(1/p)
# (Not technically a "norm" for p < 1.)
function generic_normp(x, p)
(v, s) = iterate(x)::Tuple
if p > 1 || p < -1 # might need to rescale to avoid overflow
maxabs = p > 1 ? normInf(x) : normMinusInf(x)
(ismissing(maxabs) || iszero(maxabs) || isinf(maxabs)) && return maxabs
T = typeof(maxabs)
else
T = typeof(float(norm(v)))
end
spp::promote_type(Float64, T) = p
if -1 <= p <= 1 || (isfinite(length(x)*maxabs^spp) && !iszero(maxabs^spp)) # scaling not necessary
sum::promote_type(Float64, T) = norm(v)^spp
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
ismissing(v) && return missing
sum += norm(v)^spp
end
return convert(T, sum^inv(spp))
else # rescaling
sum = (norm(v)/maxabs)^spp
ismissing(sum) && return missing
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
ismissing(v) && return missing
sum += (norm(v)/maxabs)^spp
end
return convert(T, maxabs*sum^inv(spp))
end
end
normMinusInf(x) = generic_normMinusInf(x)
normInf(x) = generic_normInf(x)
norm1(x) = generic_norm1(x)
norm2(x) = generic_norm2(x)
normp(x, p) = generic_normp(x, p)
"""
norm(A, p::Real=2)
For any iterable container `A` (including arrays of any dimension) of numbers (or any
element type for which `norm` is defined), compute the `p`-norm (defaulting to `p=2`) as if
`A` were a vector of the corresponding length.
The `p`-norm is defined as
```math
\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p}
```
with ``a_i`` the entries of ``A``, ``| a_i |`` the [`norm`](@ref) of ``a_i``, and
``n`` the length of ``A``. Since the `p`-norm is computed using the [`norm`](@ref)s
of the entries of `A`, the `p`-norm of a vector of vectors is not compatible with
the interpretation of it as a block vector in general if `p != 2`.
`p` can assume any numeric value (even though not all values produce a
mathematically valid vector norm). In particular, `norm(A, Inf)` returns the largest value
in `abs.(A)`, whereas `norm(A, -Inf)` returns the smallest. If `A` is a matrix and `p=2`,
then this is equivalent to the Frobenius norm.
The second argument `p` is not necessarily a part of the interface for `norm`, i.e. a custom
type may only implement `norm(A)` without second argument.
Use [`opnorm`](@ref) to compute the operator norm of a matrix.
# Examples
```jldoctest
julia> v = [3, -2, 6]
3-element Vector{Int64}:
3
-2
6
julia> norm(v)
7.0
julia> norm(v, 1)
11.0
julia> norm(v, Inf)
6.0
julia> norm([1 2 3; 4 5 6; 7 8 9])
16.881943016134134
julia> norm([1 2 3 4 5 6 7 8 9])
16.881943016134134
julia> norm(1:9)
16.881943016134134
julia> norm(hcat(v,v), 1) == norm(vcat(v,v), 1) != norm([v,v], 1)
true
julia> norm(hcat(v,v), 2) == norm(vcat(v,v), 2) == norm([v,v], 2)
true
julia> norm(hcat(v,v), Inf) == norm(vcat(v,v), Inf) != norm([v,v], Inf)
true
```
"""
Base.@constprop :aggressive function norm(itr, p::Real=2)
isempty(itr) && return float(norm(zero(eltype(itr))))
v, s = iterate(itr)
!isnothing(s) && !ismissing(v) && v == itr && throw(ArgumentError(
"cannot evaluate norm recursively if the type of the initial element is identical to that of the container"))
if p == 2
return norm2(itr)
elseif p == 1
return norm1(itr)
elseif p == Inf
return normInf(itr)
elseif p == 0
return typeof(float(norm(first(itr))))(count(!iszero, itr))
elseif p == -Inf
return normMinusInf(itr)
else
normp(itr, p)
end
end
"""
norm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
# Examples
```jldoctest
julia> norm(2, 1)
2.0
julia> norm(-2, 1)
2.0
julia> norm(2, 2)
2.0
julia> norm(-2, 2)
2.0
julia> norm(2, Inf)
2.0
julia> norm(-2, Inf)
2.0
```
"""
@inline function norm(x::Number, p::Real=2)
afx = abs(float(x))
if p == 0
if iszero(x)
return zero(afx)
elseif !isnan(x)
return oneunit(afx)
else
return afx
end
else
return afx
end
end
norm(::Missing, p::Real=2) = missing
# special cases of opnorm
function opnorm1(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m, n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for j = 1:n
nrmj::Tsum = 0
for i = 1:m
nrmj += norm(A[i,j])
end
nrm = max(nrm,nrmj)
end
end
return convert(Tnorm, nrm)
end
function opnorm2(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m,n = size(A)
Tnorm = typeof(float(real(zero(T))))
if m == 0 || n == 0 return zero(Tnorm) end
if m == 1 || n == 1 return norm2(A) end
return svdvals(A)[1]
end
function opnormInf(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m,n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for i = 1:m
nrmi::Tsum = 0
for j = 1:n
nrmi += norm(A[i,j])
end
nrm = max(nrm,nrmi)
end
end
return convert(Tnorm, nrm)
end
"""
opnorm(A::AbstractMatrix, p::Real=2)
Compute the operator norm (or matrix norm) induced by the vector `p`-norm,
where valid values of `p` are `1`, `2`, or `Inf`. (Note that for sparse matrices,
`p=2` is currently not implemented.) Use [`norm`](@ref) to compute the Frobenius
norm.
When `p=1`, the operator norm is the maximum absolute column sum of `A`:
```math
\\|A\\|_1 = \\max_{1 ≤ j ≤ n} \\sum_{i=1}^m | a_{ij} |
```
with ``a_{ij}`` the entries of ``A``, and ``m`` and ``n`` its dimensions.
When `p=2`, the operator norm is the spectral norm, equal to the largest
singular value of `A`.
When `p=Inf`, the operator norm is the maximum absolute row sum of `A`:
```math
\\|A\\|_\\infty = \\max_{1 ≤ i ≤ m} \\sum _{j=1}^n | a_{ij} |
```
# Examples
```jldoctest
julia> A = [1 -2 -3; 2 3 -1]
2×3 Matrix{Int64}:
1 -2 -3
2 3 -1
julia> opnorm(A, Inf)
6.0
julia> opnorm(A, 1)
5.0
```
"""
Base.@constprop :aggressive function opnorm(A::AbstractMatrix, p::Real=2)
if p == 2
return opnorm2(A)
elseif p == 1
return opnorm1(A)
elseif p == Inf
return opnormInf(A)
else
throw(ArgumentError(lazy"invalid p-norm p=$p. Valid: 1, 2, Inf"))
end
end
"""
opnorm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
This is equivalent to [`norm`](@ref).
"""
@inline opnorm(x::Number, p::Real=2) = norm(x, p)
"""
opnorm(A::Adjoint{<:Any,<:AbstractVector}, q::Real=2)
opnorm(A::Transpose{<:Any,<:AbstractVector}, q::Real=2)
For Adjoint/Transpose-wrapped vectors, return the operator ``q``-norm of `A`, which is
equivalent to the `p`-norm with value `p = q/(q-1)`. They coincide at `p = q = 2`.
Use [`norm`](@ref) to compute the `p` norm of `A` as a vector.
The difference in norm between a vector space and its dual arises to preserve
the relationship between duality and the dot product, and the result is
consistent with the operator `p`-norm of a `1 × n` matrix.
# Examples
```jldoctest
julia> v = [1; im];
julia> vc = v';
julia> opnorm(vc, 1)
1.0
julia> norm(vc, 1)
2.0
julia> norm(v, 1)
2.0
julia> opnorm(vc, 2)
1.4142135623730951
julia> norm(vc, 2)
1.4142135623730951
julia> norm(v, 2)
1.4142135623730951
julia> opnorm(vc, Inf)
2.0
julia> norm(vc, Inf)
1.0
julia> norm(v, Inf)
1.0
```
"""
opnorm(v::TransposeAbsVec, q::Real) = q == Inf ? norm(v.parent, 1) : norm(v.parent, q/(q-1))
opnorm(v::AdjointAbsVec, q::Real) = q == Inf ? norm(conj(v.parent), 1) : norm(conj(v.parent), q/(q-1))
opnorm(v::AdjointAbsVec) = norm(conj(v.parent))
opnorm(v::TransposeAbsVec) = norm(v.parent)
norm(v::AdjOrTrans, p::Real) = norm(v.parent, p)
"""
dot(x, y)
x ⋅ y
Compute the dot product between two vectors. For complex vectors, the first
vector is conjugated.
`dot` also works on arbitrary iterable objects, including arrays of any dimension,
as long as `dot` is defined on the elements.
`dot` is semantically equivalent to `sum(dot(vx,vy) for (vx,vy) in zip(x, y))`,
with the added restriction that the arguments must have equal lengths.
`x ⋅ y` (where `⋅` can be typed by tab-completing `\\cdot` in the REPL) is a synonym for
`dot(x, y)`.
# Examples
```jldoctest
julia> dot([1; 1], [2; 3])
5
julia> dot([im; im], [1; 1])
0 - 2im
julia> dot(1:5, 2:6)
70
julia> x = fill(2., (5,5));
julia> y = fill(3., (5,5));
julia> dot(x, y)
150.0
```
"""
function dot end
function dot(x, y) # arbitrary iterables
ix = iterate(x)
iy = iterate(y)
if ix === nothing
if iy !== nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
return dot(zero(eltype(x)), zero(eltype(y)))
end
if iy === nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
(vx, xs) = ix
(vy, ys) = iy
typeof(vx) == typeof(x) && typeof(vy) == typeof(y) && throw(ArgumentError(
"cannot evaluate dot recursively if the type of an element is identical to that of the container"))
s = dot(vx, vy)
while true
ix = iterate(x, xs)
iy = iterate(y, ys)
ix === nothing && break
iy === nothing && break
(vx, xs), (vy, ys) = ix, iy
s += dot(vx, vy)
end
if !(iy === nothing && ix === nothing)
throw(DimensionMismatch("x and y are of different lengths!"))
end
return s
end
dot(x::Number, y::Number) = conj(x) * y
function dot(x::AbstractArray, y::AbstractArray)
lx = length(x)
if lx != length(y)
throw(DimensionMismatch(lazy"first array has length $(lx) which does not match the length of the second, $(length(y))."))
end
if lx == 0
return dot(zero(eltype(x)), zero(eltype(y)))
end
s = zero(dot(first(x), first(y)))
for (Ix, Iy) in zip(eachindex(x), eachindex(y))
@inbounds s += dot(x[Ix], y[Iy])
end
s
end
function dot(x::Adjoint{<:Union{Real,Complex}}, y::Adjoint{<:Union{Real,Complex}})
return conj(dot(parent(x), parent(y)))
end
dot(x::Transpose, y::Transpose) = dot(parent(x), parent(y))
"""
dot(x, A, y)
Compute the generalized dot product `dot(x, A*y)` between two vectors `x` and `y`,
without storing the intermediate result of `A*y`. As for the two-argument
[`dot(_,_)`](@ref), this acts recursively. Moreover, for complex vectors, the
first vector is conjugated.
!!! compat "Julia 1.4"
Three-argument `dot` requires at least Julia 1.4.
# Examples
```jldoctest
julia> dot([1; 1], [1 2; 3 4], [2; 3])
26
julia> dot(1:5, reshape(1:25, 5, 5), 2:6)
4850
julia> ⋅(1:5, reshape(1:25, 5, 5), 2:6) == dot(1:5, reshape(1:25, 5, 5), 2:6)
true
```
"""
dot(x, A, y) = dot(x, A*y) # generic fallback for cases that are not covered by specialized methods
function dot(x::AbstractVector, A::AbstractMatrix, y::AbstractVector)