/
givens.jl
400 lines (368 loc) · 12.2 KB
/
givens.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
# This file is a part of Julia. License is MIT: https://julialang.org/license
# givensAlgorithm functions are derived from LAPACK, see below
abstract type AbstractRotation{T} end
transpose(R::AbstractRotation) = error("transpose not implemented for $(typeof(R)). Consider using adjoint instead of transpose.")
function (*)(R::AbstractRotation{T}, A::AbstractVecOrMat{S}) where {T,S}
TS = typeof(zero(T)*zero(S) + zero(T)*zero(S))
lmul!(convert(AbstractRotation{TS}, R), TS == S ? copy(A) : convert(AbstractArray{TS}, A))
end
(*)(A::AbstractVector, adjR::Adjoint{<:Any,<:AbstractRotation}) = _absvecormat_mul_adjrot(A, adjR)
(*)(A::AbstractMatrix, adjR::Adjoint{<:Any,<:AbstractRotation}) = _absvecormat_mul_adjrot(A, adjR)
function _absvecormat_mul_adjrot(A::AbstractVecOrMat{T}, adjR::Adjoint{<:Any,<:AbstractRotation{S}}) where {T,S}
R = adjR.parent
TS = typeof(zero(T)*zero(S) + zero(T)*zero(S))
rmul!(TS.(A), convert(AbstractRotation{TS}, R)')
end
function(*)(A::AbstractMatrix{T}, R::AbstractRotation{S}) where {T,S}
TS = typeof(zero(T)*zero(S) + zero(T)*zero(S))
rmul!(TS.(A), convert(AbstractRotation{TS}, R))
end
"""
LinearAlgebra.Givens(i1,i2,c,s) -> G
A Givens rotation linear operator. The fields `c` and `s` represent the cosine and sine of
the rotation angle, respectively. The `Givens` type supports left multiplication `G*A` and
conjugated transpose right multiplication `A*G'`. The type doesn't have a `size` and can
therefore be multiplied with matrices of arbitrary size as long as `i2<=size(A,2)` for
`G*A` or `i2<=size(A,1)` for `A*G'`.
See also: [`givens`](@ref)
"""
struct Givens{T} <: AbstractRotation{T}
i1::Int
i2::Int
c::T
s::T
end
struct Rotation{T} <: AbstractRotation{T}
rotations::Vector{Givens{T}}
end
convert(::Type{T}, r::T) where {T<:AbstractRotation} = r
convert(::Type{T}, r::AbstractRotation) where {T<:AbstractRotation} = T(r)
Givens{T}(G::Givens{T}) where {T} = G
Givens{T}(G::Givens) where {T} = Givens(G.i1, G.i2, convert(T, G.c), convert(T, G.s))
Rotation{T}(R::Rotation{T}) where {T} = R
Rotation{T}(R::Rotation) where {T} = Rotation{T}([Givens{T}(g) for g in R.rotations])
AbstractRotation{T}(G::Givens) where {T} = Givens{T}(G)
AbstractRotation{T}(R::Rotation) where {T} = Rotation{T}(R)
adjoint(G::Givens) = Givens(G.i1, G.i2, G.c', -G.s)
adjoint(R::Rotation) = Adjoint(R)
function Base.copy(aG::Adjoint{<:Any,<:Givens})
G = aG.parent
return Givens(G.i1, G.i2, conj(G.c), -G.s)
end
Base.copy(aR::Adjoint{<:Any,Rotation{T}}) where {T} = Rotation{T}(reverse!([r' for r in aR.parent.rotations]))
floatmin2(::Type{Float32}) = reinterpret(Float32, 0x26000000)
floatmin2(::Type{Float64}) = reinterpret(Float64, 0x21a0000000000000)
floatmin2(::Type{T}) where {T} = (twopar = 2one(T); twopar^trunc(Integer,log(floatmin(T)/eps(T))/log(twopar)/twopar))
# derived from LAPACK's dlartg
# Copyright:
# Univ. of Tennessee
# Univ. of California Berkeley
# Univ. of Colorado Denver
# NAG Ltd.
function givensAlgorithm(f::T, g::T) where T<:AbstractFloat
onepar = one(T)
twopar = 2one(T)
T0 = typeof(onepar) # dimensionless
zeropar = T0(zero(T)) # must be dimensionless
# need both dimensionful and dimensionless versions of these:
safmn2 = floatmin2(T0)
safmn2u = floatmin2(T)
safmx2 = one(T)/safmn2
safmx2u = oneunit(T)/safmn2
if g == 0
cs = onepar
sn = zeropar
r = f
elseif f == 0
cs = zeropar
sn = onepar
r = g
else
f1 = f
g1 = g
scalepar = max(abs(f1), abs(g1))
if scalepar >= safmx2u
count = 0
while true
count += 1
f1 *= safmn2
g1 *= safmn2
scalepar = max(abs(f1), abs(g1))
if scalepar < safmx2u break end
end
r = sqrt(f1*f1 + g1*g1)
cs = f1/r
sn = g1/r
for i = 1:count
r *= safmx2
end
elseif scalepar <= safmn2u
count = 0
while true
count += 1
f1 *= safmx2
g1 *= safmx2
scalepar = max(abs(f1), abs(g1))
if scalepar > safmn2u break end
end
r = sqrt(f1*f1 + g1*g1)
cs = f1/r
sn = g1/r
for i = 1:count
r *= safmn2
end
else
r = sqrt(f1*f1 + g1*g1)
cs = f1/r
sn = g1/r
end
if abs(f) > abs(g) && cs < 0
cs = -cs
sn = -sn
r = -r
end
end
return cs, sn, r
end
# derived from LAPACK's zlartg
# Copyright:
# Univ. of Tennessee
# Univ. of California Berkeley
# Univ. of Colorado Denver
# NAG Ltd.
function givensAlgorithm(f::Complex{T}, g::Complex{T}) where T<:AbstractFloat
twopar, onepar = 2one(T), one(T)
T0 = typeof(onepar) # dimensionless
zeropar = T0(zero(T)) # must be dimensionless
czero = complex(zeropar)
abs1(ff) = max(abs(real(ff)), abs(imag(ff)))
safmin = floatmin(T0)
safmn2 = floatmin2(T0)
safmn2u = floatmin2(T)
safmx2 = one(T)/safmn2
safmx2u = oneunit(T)/safmn2
scalepar = max(abs1(f), abs1(g))
fs = f
gs = g
count = 0
if scalepar >= safmx2u
while true
count += 1
fs *= safmn2
gs *= safmn2
scalepar *= safmn2
if scalepar < safmx2u break end
end
elseif scalepar <= safmn2u
if g == 0
cs = onepar
sn = czero
r = f
return cs, sn, r
end
while true
count -= 1
fs *= safmx2
gs *= safmx2
scalepar *= safmx2
if scalepar > safmn2u break end
end
end
f2 = abs2(fs)
g2 = abs2(gs)
if f2 <= max(g2, oneunit(T))*safmin
# This is a rare case: F is very small.
if f == 0
cs = zero(T)
r = complex(hypot(real(g), imag(g)))
# do complex/real division explicitly with two real divisions
d = hypot(real(gs), imag(gs))
sn = complex(real(gs)/d, -imag(gs)/d)
return cs, sn, r
end
f2s = hypot(real(fs), imag(fs))
# g2 and g2s are accurate
# g2 is at least safmin, and g2s is at least safmn2
g2s = sqrt(g2)
# error in cs from underflow in f2s is at most
# unfl / safmn2 .lt. sqrt(unfl*eps) .lt. eps
# if max(g2,one)=g2, then f2 .lt. g2*safmin,
# and so cs .lt. sqrt(safmin)
# if max(g2,one)=one, then f2 .lt. safmin
# and so cs .lt. sqrt(safmin)/safmn2 = sqrt(eps)
# therefore, cs = f2s/g2s / sqrt( 1 + (f2s/g2s)**2 ) = f2s/g2s
cs = f2s/g2s
# make sure abs(ff) = 1
# do complex/real division explicitly with 2 real divisions
if abs1(f) > 1
d = hypot(real(f), imag(f))
ff = complex(real(f)/d, imag(f)/d)
else
dr = safmx2*real(f)
di = safmx2*imag(f)
d = hypot(dr, di)
ff = complex(dr/d, di/d)
end
sn = ff*complex(real(gs)/g2s, -imag(gs)/g2s)
r = cs*f + sn*g
else
# This is the most common case.
# Neither F2 nor F2/G2 are less than SAFMIN
# F2S cannot overflow, and it is accurate
f2s = sqrt(onepar + g2/f2)
# do the f2s(real)*fs(complex) multiply with two real multiplies
r = complex(f2s*real(fs), f2s*imag(fs))
cs = onepar/f2s
d = f2 + g2
# do complex/real division explicitly with two real divisions
sn = complex(real(r)/d, imag(r)/d)
sn *= conj(gs)
if count != 0
if count > 0
for i = 1:count
r *= safmx2
end
else
for i = 1:-count
r *= safmn2
end
end
end
end
return cs, sn, r
end
givensAlgorithm(f, g) = givensAlgorithm(promote(float(f), float(g))...)
"""
givens(f::T, g::T, i1::Integer, i2::Integer) where {T} -> (G::Givens, r::T)
Computes the Givens rotation `G` and scalar `r` such that for any vector `x` where
```
x[i1] = f
x[i2] = g
```
the result of the multiplication
```
y = G*x
```
has the property that
```
y[i1] = r
y[i2] = 0
```
See also: [`LinearAlgebra.Givens`](@ref)
"""
function givens(f::T, g::T, i1::Integer, i2::Integer) where T
if i1 == i2
throw(ArgumentError("Indices must be distinct."))
end
c, s, r = givensAlgorithm(f, g)
if i1 > i2
s = -conj(s)
i1,i2 = i2,i1
end
Givens(i1, i2, convert(T, c), convert(T, s)), r
end
"""
givens(A::AbstractArray, i1::Integer, i2::Integer, j::Integer) -> (G::Givens, r)
Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication
```
B = G*A
```
has the property that
```
B[i1,j] = r
B[i2,j] = 0
```
See also: [`LinearAlgebra.Givens`](@ref)
"""
givens(A::AbstractMatrix, i1::Integer, i2::Integer, j::Integer) =
givens(A[i1,j], A[i2,j],i1,i2)
"""
givens(x::AbstractVector, i1::Integer, i2::Integer) -> (G::Givens, r)
Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication
```
B = G*x
```
has the property that
```
B[i1] = r
B[i2] = 0
```
See also: [`LinearAlgebra.Givens`](@ref)
"""
givens(x::AbstractVector, i1::Integer, i2::Integer) =
givens(x[i1], x[i2], i1, i2)
function getindex(G::Givens, i::Integer, j::Integer)
if i == j
if i == G.i1 || i == G.i2
G.c
else
oneunit(G.c)
end
elseif i == G.i1 && j == G.i2
G.s
elseif i == G.i2 && j == G.i1
-conj(G.s)
else
zero(G.s)
end
end
@inline function lmul!(G::Givens, A::AbstractVecOrMat)
require_one_based_indexing(A)
m, n = size(A, 1), size(A, 2)
if G.i2 > m
throw(DimensionMismatch("column indices for rotation are outside the matrix"))
end
@inbounds for i = 1:n
a1, a2 = A[G.i1,i], A[G.i2,i]
A[G.i1,i] = G.c *a1 + G.s*a2
A[G.i2,i] = -conj(G.s)*a1 + G.c*a2
end
return A
end
@inline function rmul!(A::AbstractMatrix, G::Givens)
require_one_based_indexing(A)
m, n = size(A, 1), size(A, 2)
if G.i2 > n
throw(DimensionMismatch("column indices for rotation are outside the matrix"))
end
@inbounds for i = 1:m
a1, a2 = A[i,G.i1], A[i,G.i2]
A[i,G.i1] = a1*G.c - a2*G.s'
A[i,G.i2] = a1*G.s + a2*G.c
end
return A
end
function lmul!(G::Givens, R::Rotation)
push!(R.rotations, G)
return R
end
function lmul!(R::Rotation, A::AbstractMatrix)
@inbounds for i = 1:length(R.rotations)
lmul!(R.rotations[i], A)
end
return A
end
function rmul!(A::AbstractMatrix, adjR::Adjoint{<:Any,<:Rotation})
R = adjR.parent
@inbounds for i = 1:length(R.rotations)
rmul!(A, adjoint(R.rotations[i]))
end
return A
end
*(G1::Givens{T}, G2::Givens{T}) where {T} = Rotation(push!(push!(Givens{T}[], G2), G1))
# TODO: None of the following disambiguation methods are great. They should perhaps
# instead be MethodErrors, or revised.
#
# disambiguation methods: *(Adj/Trans of AbsVec or AbsMat, Adj of AbstractRotation)
*(A::Adjoint{<:Any,<:AbstractVector}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Adjoint{<:Any,<:AbstractMatrix}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Transpose{<:Any,<:AbstractVector}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Transpose{<:Any,<:AbstractMatrix}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
# disambiguation methods: *(Adj/Trans of AbsTri or RealHermSymComplex{Herm|Sym}, Adj of AbstractRotation)
*(A::Adjoint{<:Any,<:AbstractTriangular}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Transpose{<:Any,<:AbstractTriangular}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Adjoint{<:Any,<:RealHermSymComplexHerm}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
*(A::Transpose{<:Any,<:RealHermSymComplexSym}, B::Adjoint{<:Any,<:AbstractRotation}) = copy(A) * B
# disambiguation methods: *(Diag/AbsTri, Adj of AbstractRotation)
*(A::Diagonal, B::Adjoint{<:Any,<:AbstractRotation}) = A * copy(B)
*(A::AbstractTriangular, B::Adjoint{<:Any,<:AbstractRotation}) = A * copy(B)