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
#[cfg(feature = "serde-serialize")]
use serde;
use num_complex::Complex;
use std::ops::MulAssign;
use alga::general::Real;
use core::{Matrix, MatrixMN, VectorN, DefaultAllocator, Matrix2x3, Vector2};
use dimension::{Dim, DimMin, DimMinimum, DimSub, DimDiff, U1, U2};
use storage::Storage;
use allocator::Allocator;
use constraint::{ShapeConstraint, SameNumberOfRows};
use linalg::givens;
use linalg::symmetric_eigen;
use linalg::Bidiagonal;
use geometry::UnitComplex;
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde-serialize",
serde(bound(serialize =
"DefaultAllocator: Allocator<N, R, C> +
Allocator<N, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>>,
MatrixMN<N, R, DimMinimum<R, C>>: serde::Serialize,
MatrixMN<N, DimMinimum<R, C>, C>: serde::Serialize,
VectorN<N, DimMinimum<R, C>>: serde::Serialize")))]
#[cfg_attr(feature = "serde-serialize",
serde(bound(deserialize =
"DefaultAllocator: Allocator<N, R, C> +
Allocator<N, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>>,
MatrixMN<N, R, DimMinimum<R, C>>: serde::Deserialize<'de>,
MatrixMN<N, DimMinimum<R, C>, C>: serde::Deserialize<'de>,
VectorN<N, DimMinimum<R, C>>: serde::Deserialize<'de>")))]
#[derive(Clone, Debug)]
pub struct SVD<N: Real, R: DimMin<C>, C: Dim>
where DefaultAllocator: Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>> {
pub u: Option<MatrixMN<N, R, DimMinimum<R, C>>>,
pub v_t: Option<MatrixMN<N, DimMinimum<R, C>, C>>,
pub singular_values: VectorN<N, DimMinimum<R, C>>,
}
impl<N: Real, R: DimMin<C>, C: Dim> Copy for SVD<N, R, C>
where DefaultAllocator: Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>>,
MatrixMN<N, R, DimMinimum<R, C>>: Copy,
MatrixMN<N, DimMinimum<R, C>, C>: Copy,
VectorN<N, DimMinimum<R, C>>: Copy { }
impl<N: Real, R: DimMin<C>, C: Dim> SVD<N, R, C>
where DimMinimum<R, C>: DimSub<U1>,
DefaultAllocator: Allocator<N, R, C> +
Allocator<N, C> +
Allocator<N, R> +
Allocator<N, DimDiff<DimMinimum<R, C>, U1>> +
Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>> {
pub fn new(matrix: MatrixMN<N, R, C>, compute_u: bool, compute_v: bool) -> Self {
Self::try_new(matrix, compute_u, compute_v, N::default_epsilon(), 0).unwrap()
}
pub fn try_new(mut matrix: MatrixMN<N, R, C>,
compute_u: bool,
compute_v: bool,
eps: N,
max_niter: usize)
-> Option<Self> {
assert!(matrix.len() != 0, "Cannot compute the SVD of an empty matrix.");
let (nrows, ncols) = matrix.data.shape();
let min_nrows_ncols = nrows.min(ncols);
let dim = min_nrows_ncols.value();
let m_amax = matrix.amax();
if !m_amax.is_zero() {
matrix /= m_amax;
}
let mut b = Bidiagonal::new(matrix);
let mut u = if compute_u { Some(b.u()) } else { None };
let mut v_t = if compute_v { Some(b.v_t()) } else { None };
let mut niter = 0;
let (mut start, mut end) = Self::delimit_subproblem(&mut b, &mut u, &mut v_t, dim - 1, eps);
while end != start {
let subdim = end - start + 1;
if subdim > 2 {
let m = end - 1;
let n = end;
let mut vec;
{
let dm = b.diagonal[m];
let dn = b.diagonal[n];
let fm = b.off_diagonal[m];
let tmm = dm * dm + b.off_diagonal[m - 1] * b.off_diagonal[m - 1];
let tmn = dm * fm;
let tnn = dn * dn + fm * fm;
let shift = symmetric_eigen::wilkinson_shift(tmm, tnn, tmn);
vec = Vector2::new(b.diagonal[start] * b.diagonal[start] - shift,
b.diagonal[start] * b.off_diagonal[start]);
}
for k in start .. n {
let m12 = if k == n - 1 { N::zero() } else { b.off_diagonal[k + 1] };
let mut subm = Matrix2x3::new(
b.diagonal[k], b.off_diagonal[k], N::zero(),
N::zero(), b.diagonal[k + 1], m12);
if let Some((rot1, norm1)) = givens::cancel_y(&vec) {
rot1.conjugate().rotate_rows(&mut subm.fixed_columns_mut::<U2>(0));
if k > start {
b.off_diagonal[k - 1] = norm1;
}
let v = Vector2::new(subm[(0, 0)], subm[(1, 0)]);
let (rot2, norm2) = givens::cancel_y(&v).unwrap_or((UnitComplex::identity(), subm[(0, 0)]));
rot2.rotate(&mut subm.fixed_columns_mut::<U2>(1));
subm[(0, 0)] = norm2;
if let Some(ref mut v_t) = v_t {
if b.is_upper_diagonal() {
rot1.rotate(&mut v_t.fixed_rows_mut::<U2>(k));
}
else {
rot2.rotate(&mut v_t.fixed_rows_mut::<U2>(k));
}
}
if let Some(ref mut u) = u {
if b.is_upper_diagonal() {
rot2.inverse().rotate_rows(&mut u.fixed_columns_mut::<U2>(k));
}
else {
rot1.inverse().rotate_rows(&mut u.fixed_columns_mut::<U2>(k));
}
}
b.diagonal[k + 0] = subm[(0, 0)];
b.diagonal[k + 1] = subm[(1, 1)];
b.off_diagonal[k + 0] = subm[(0, 1)];
if k != n - 1 {
b.off_diagonal[k + 1] = subm[(1, 2)];
}
vec.x = subm[(0, 1)];
vec.y = subm[(0, 2)];
}
else {
break;
}
}
}
else if subdim == 2 {
let (u2, s, v2) = Self::compute_2x2_uptrig_svd(
b.diagonal[start], b.off_diagonal[start], b.diagonal[start + 1],
compute_u && b.is_upper_diagonal() || compute_v && !b.is_upper_diagonal(),
compute_v && b.is_upper_diagonal() || compute_u && !b.is_upper_diagonal());
b.diagonal[start + 0] = s[0];
b.diagonal[start + 1] = s[1];
b.off_diagonal[start] = N::zero();
if let Some(ref mut u) = u {
let rot = if b.is_upper_diagonal() { u2.unwrap() } else { v2.unwrap() };
rot.rotate_rows(&mut u.fixed_columns_mut::<U2>(start));
}
if let Some(ref mut v_t) = v_t {
let rot = if b.is_upper_diagonal() { v2.unwrap() } else { u2.unwrap() };
rot.inverse().rotate(&mut v_t.fixed_rows_mut::<U2>(start));
}
end -= 1;
}
let sub = Self::delimit_subproblem(&mut b, &mut u, &mut v_t, end, eps);
start = sub.0;
end = sub.1;
niter += 1;
if niter == max_niter {
return None;
}
}
b.diagonal *= m_amax;
for i in 0 .. dim {
let sval = b.diagonal[i];
if sval < N::zero() {
b.diagonal[i] = -sval;
if let Some(ref mut u) = u {
u.column_mut(i).neg_mut();
}
}
}
Some(SVD { u: u, v_t: v_t, singular_values: b.diagonal })
}
fn compute_2x2_uptrig_svd(m11: N, m12: N, m22: N, compute_u: bool, compute_v: bool)
-> (Option<UnitComplex<N>>, Vector2<N>, Option<UnitComplex<N>>) {
let two: N = ::convert(2.0f64);
let half: N = ::convert(0.5f64);
let denom = (m11 + m22).hypot(m12) + (m11 - m22).hypot(m12);
let v1 = two * m11 * m22 / denom;
let v2 = half * denom;
let mut u = None;
let mut v_t = None;
if compute_u || compute_v {
let csv = Vector2::new(m11 * m12, v1 * v1 - m11 * m11).normalize();
if compute_v {
v_t = Some(UnitComplex::new_unchecked(Complex::new(csv.x, csv.y)));
}
if compute_u {
let cu = (m11 * csv.x + m12 * csv.y) / v1;
let su = (m22 * csv.y) / v1;
u = Some(UnitComplex::new_unchecked(Complex::new(cu, su)));
}
}
(u, Vector2::new(v1, v2), v_t)
}
fn delimit_subproblem(b: &mut Bidiagonal<N, R, C>,
u: &mut Option<MatrixMN<N, R, DimMinimum<R, C>>>,
v_t: &mut Option<MatrixMN<N, DimMinimum<R, C>, C>>,
end: usize,
eps: N)
-> (usize, usize) {
let mut n = end;
while n > 0 {
let m = n - 1;
if b.off_diagonal[m].is_zero() ||
b.off_diagonal[m].abs() <= eps * (b.diagonal[n].abs() + b.diagonal[m].abs()) {
b.off_diagonal[m] = N::zero();
}
else if b.diagonal[m].abs() <= eps {
b.diagonal[m] = N::zero();
Self::cancel_horizontal_off_diagonal_elt(b, u, v_t, m, m + 1);
if m != 0 {
Self::cancel_vertical_off_diagonal_elt(b, u, v_t, m - 1);
}
}
else if b.diagonal[n].abs() <= eps {
b.diagonal[n] = N::zero();
Self::cancel_vertical_off_diagonal_elt(b, u, v_t, m);
}
else {
break;
}
n -= 1;
}
if n == 0 {
return (0, 0);
}
let mut new_start = n - 1;
while new_start > 0 {
let m = new_start - 1;
if b.off_diagonal[m].abs() <= eps * (b.diagonal[new_start].abs() + b.diagonal[m].abs()) {
b.off_diagonal[m] = N::zero();
break;
}
else if b.diagonal[m].abs() <= eps {
b.diagonal[m] = N::zero();
Self::cancel_horizontal_off_diagonal_elt(b, u, v_t, m, n);
if m != 0 {
Self::cancel_vertical_off_diagonal_elt(b, u, v_t, m - 1);
}
break;
}
new_start -= 1;
}
(new_start, n)
}
fn cancel_horizontal_off_diagonal_elt(b: &mut Bidiagonal<N, R, C>,
u: &mut Option<MatrixMN<N, R, DimMinimum<R, C>>>,
v_t: &mut Option<MatrixMN<N, DimMinimum<R, C>, C>>,
i: usize,
end: usize) {
let mut v = Vector2::new(b.off_diagonal[i], b.diagonal[i + 1]);
b.off_diagonal[i] = N::zero();
for k in i .. end {
if let Some((rot, norm)) = givens::cancel_x(&v) {
b.diagonal[k + 1] = norm;
if b.is_upper_diagonal() {
if let Some(ref mut u) = *u {
rot.inverse().rotate_rows(&mut u.fixed_columns_with_step_mut::<U2>(i, k - i));
}
}
else if let Some(ref mut v_t) = *v_t {
rot.rotate(&mut v_t.fixed_rows_with_step_mut::<U2>(i, k - i));
}
if k + 1 != end {
v.x = -rot.sin_angle() * b.off_diagonal[k + 1];
v.y = b.diagonal[k + 2];
b.off_diagonal[k + 1] *= rot.cos_angle();
}
}
else {
break;
}
}
}
fn cancel_vertical_off_diagonal_elt(b: &mut Bidiagonal<N, R, C>,
u: &mut Option<MatrixMN<N, R, DimMinimum<R, C>>>,
v_t: &mut Option<MatrixMN<N, DimMinimum<R, C>, C>>,
i: usize) {
let mut v = Vector2::new(b.diagonal[i], b.off_diagonal[i]);
b.off_diagonal[i] = N::zero();
for k in (0 .. i + 1).rev() {
if let Some((rot, norm)) = givens::cancel_y(&v) {
b.diagonal[k] = norm;
if b.is_upper_diagonal() {
if let Some(ref mut v_t) = *v_t {
rot.rotate(&mut v_t.fixed_rows_with_step_mut::<U2>(k, i - k));
}
}
else if let Some(ref mut u) = *u {
rot.inverse().rotate_rows(&mut u.fixed_columns_with_step_mut::<U2>(k, i - k));
}
if k > 0 {
v.x = b.diagonal[k - 1];
v.y = rot.sin_angle() * b.off_diagonal[k - 1];
b.off_diagonal[k - 1] *= rot.cos_angle();
}
}
else {
break;
}
}
}
pub fn rank(&self, eps: N) -> usize {
assert!(eps >= N::zero(), "SVD rank: the epsilon must be non-negative.");
self.singular_values.iter().filter(|e| **e > eps).count()
}
pub fn recompose(self) -> MatrixMN<N, R, C> {
let mut u = self.u.expect("SVD recomposition: U has not been computed.");
let v_t = self.v_t.expect("SVD recomposition: V^t has not been computed.");
for i in 0 .. self.singular_values.len() {
let val = self.singular_values[i];
u.column_mut(i).mul_assign(val);
}
u * v_t
}
pub fn pseudo_inverse(mut self, eps: N) -> MatrixMN<N, C, R>
where DefaultAllocator: Allocator<N, C, R> {
assert!(eps >= N::zero(), "SVD pseudo inverse: the epsilon must be non-negative.");
for i in 0 .. self.singular_values.len() {
let val = self.singular_values[i];
if val > eps {
self.singular_values[i] = N::one() / val;
}
else {
self.singular_values[i] = N::zero();
}
}
self.recompose().transpose()
}
pub fn solve<R2: Dim, C2: Dim, S2>(&self, b: &Matrix<N, R2, C2, S2>, eps: N) -> MatrixMN<N, C, C2>
where S2: Storage<N, R2, C2>,
DefaultAllocator: Allocator<N, C, C2> +
Allocator<N, DimMinimum<R, C>, C2>,
ShapeConstraint: SameNumberOfRows<R, R2> {
assert!(eps >= N::zero(), "SVD solve: the epsilon must be non-negative.");
let u = self.u.as_ref().expect("SVD solve: U has not been computed.");
let v_t = self.v_t.as_ref().expect("SVD solve: V^t has not been computed.");
let mut ut_b = u.tr_mul(b);
for j in 0 .. ut_b.ncols() {
let mut col = ut_b.column_mut(j);
for i in 0 .. self.singular_values.len() {
let val = self.singular_values[i];
if val > eps {
col[i] /= val;
}
else {
col[i] = N::zero();
}
}
}
v_t.tr_mul(&ut_b)
}
}
impl<N: Real, R: DimMin<C>, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S>
where DimMinimum<R, C>: DimSub<U1>,
DefaultAllocator: Allocator<N, R, C> +
Allocator<N, C> +
Allocator<N, R> +
Allocator<N, DimDiff<DimMinimum<R, C>, U1>> +
Allocator<N, DimMinimum<R, C>, C> +
Allocator<N, R, DimMinimum<R, C>> +
Allocator<N, DimMinimum<R, C>> {
pub fn svd(self, compute_u: bool, compute_v: bool) -> SVD<N, R, C> {
SVD::new(self.into_owned(), compute_u, compute_v)
}
pub fn try_svd(self, compute_u: bool, compute_v: bool, eps: N, max_niter: usize) -> Option<SVD<N, R, C>> {
SVD::try_new(self.into_owned(), compute_u, compute_v, eps, max_niter)
}
pub fn singular_values(&self) -> VectorN<N, DimMinimum<R, C>> {
SVD::new(self.clone_owned(), false, false).singular_values
}
pub fn rank(&self, eps: N) -> usize {
let svd = SVD::new(self.clone_owned(), false, false);
svd.rank(eps)
}
pub fn pseudo_inverse(self, eps: N) -> MatrixMN<N, C, R>
where DefaultAllocator: Allocator<N, C, R> {
SVD::new(self.clone_owned(), true, true).pseudo_inverse(eps)
}
}