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
//! Random sampling of matrices
//!
//! This module defines traits for the randomized sampling of the range of a linear operator
//! and the associated computation of randomized QR and Singular Value Decompositions.
//!
//! In many applications we want to complete an approximate low-rank approximation of a linear
//! operator but do not have access to the whole matrix, or computing the full QR or SVD of a
//! matrix is too expensive. In these cases techniques from randomized linear algebra can be used
//! to compute approximate low-rank decompositions.
//!
//! Assume we have an operator $A$. We have two conditions on $A$.
//!
//! 1. We need to be able to compute $y=Ax$ for a given vector $x$.
//! 2. We need to be able to compute $y=A^Hx$ for a given vector $x$.
//!
//! These abilities are implemented through the traits [MatVec](crate::types::MatVec) and [ConjMatVec](crate::types::ConjMatVec).
//! Implementing these traits also automatically implements the corresponding traits
//! [MatMat](crate::types::MatMat) and [ConjMatMat](crate::types::ConjMatMat), which
//! are the corresponding versions for multiplications with a matrix $X$ instead of a vector $x$.
//! The routines in this module use the latter traits. For performance reasons it may sometimes be
//! preferable to directly implement [MatMat](crate::types::MatMat) and [ConjMatMat](crate::types::ConjMatMat)
//! instead of relying on the corresponding vector versions.
//!
//! In the following we describe the traits in more detail.
//!
//! - [`SampleRange`]: This trait can be used to randomly sample the range of an operator by specifying a target
//! rank. It only requires the [MatMat](crate::types::MatMat) trait.
//! - [`SampleRangePowerIteration`]: This trait is an improved version of [`SampleRange']. It uses a power
//! iteration to give a more precise result but requires the [ConjMatMat](crate::types::ConjMatMat) trait
//! to be implemented.
//! - [`AdaptiveSampling`]: This trait samples the range of an operator adaptively through specifying
//! a target tolerance. The error tolerance is checked probabilistically.
//!
//! Once we have sampled the range of an operator we can use the method
//! [compute_from_range_estimate](crate::qr::QRTraits::compute_from_range_estimate) of the
//! [QRTraits](crate::qr::QRTraits) to obtain an approximate QR Decomposition of the operator, from
//! which we can for example compute an interpolative decomposition. Alternatively, we can use
//! the [corresponding method](crate::svd::SVDTraits::compute_from_range_estimate) to compute an
//! approximate Singular Value Decomposition of the operator.
use crate;
use crateRandomMatrix;
use crateCompressionType;
use ;
use Norm;
use ToPrimitive;
use Rng;
use crate;
/// Randomly sample the range of an operator
///
/// Let $A\in\mathbb{C}{m\times n}$ be a matrix. To sample the range of rank $k$ one can multiply
/// $A$ by a Gaussian random matrix $\Omega$ of dimension $n\times k + p$, where $p$ is a small oversampling
/// parameter. The result of this product is post-processed by a pivoted QR decomposition and the first $k$
/// columns of the $Q$ matrix in the pivoted QR decomposition returned.
/// Randomly sample the range of an operator through a power iteration
///
/// Let $A\in\mathbb{C}{m\times n}$ be a matrix. To sample the range of rank $k$ one can multiply
/// $A$ by a Gaussian random matrix $\Omega$ of dimension $n\times k + p$, where $p$ is a small oversampling
/// parameter. To improve the accuracy of the range computation this is then `it_count` times multiplied with the
/// operator $AA^H$. Each intermediate result is QR orthogonalized to stabilise this power iteration.
/// The result of the power iteration is post-processed by a pivoted QR decomposition and the first $k$
/// columns of the $Q$ matrix in the pivoted QR decomposition returned.
sample_range_impl!;
sample_range_impl!;
sample_range_impl!;
sample_range_impl!;
sample_range_power_impl!;
sample_range_power_impl!;
sample_range_power_impl!;
sample_range_power_impl!;
/// Trait defining the maximum column norm of an operator
///
/// If $A\in\mathbb{C}^{m\times n}$ the maximum column-norm is
/// computed by first taking the Euclidian norm of each column and then
/// returning the maximum of the column norms.
impl_max_col_norm!;
impl_max_col_norm!;
impl_max_col_norm!;
impl_max_col_norm!;
/// This trait defines the adaptive sampling of the range of an operator.
adaptive_sampling_impl!;
adaptive_sampling_impl!;
adaptive_sampling_impl!;
adaptive_sampling_impl!;
// fn qr_from_range_estimate<R: Rng>(
// &self,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<QR<$scalar>> {
// let (q, _) = self.sample_range_adaptive(rel_tol, sample_size, rng)?;
// let b = self.conj_matmat(q.view()).t().map(|item| item.conj());
// let qr = QR::<$scalar>::compute_from(b.view())?;
// Ok(QR {
// q: b.dot(&qr.get_q()),
// r: qr.get_r().into_owned(),
// ind: qr.get_ind().into_owned(),
// })
// }
// // Compute a QR decomposition via adaptive random range sampling.
// // # Arguments
// // * `op`: The operator for which to compute the QR decomposition.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size` Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// fn randomized_adaptive_qr<R: Rng>(
// &self,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<QR<A>>;
// // Compute a SVD decomposition via adaptive random range sampling.
// // # Arguments
// // * `op`: The operator for which to compute the QR decomposition.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size` Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// fn randomized_adaptive_svd<R: Rng>(
// &self,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<SVD<A>>;
// }
// // Compute a SVD decomposition via adaptive random range sampling.
// // # Arguments
// // * `op`: The operator for which to compute the QR decomposition.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size` Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// fn randomized_adaptive_svd<R: Rng>(
// &self,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<SVD<$scalar>> {
// let (q, _) = self.sample_range_adaptive(rel_tol, sample_size, rng)?;
// let b = self.conj_matmat(q.view()).t().map(|item| item.conj());
// let svd = SVD::<$scalar>::compute_from(b.view())?;
// Ok(SVD {
// u: b.dot(&svd.u),
// s: svd.get_s().into_owned(),
// vt: svd.get_vt().into_owned(),
// })
// }
// }
// // Adaptively randomly sample the range of an operator up to a given tolerance.
// // # Arguments
// // * `op`: The operator for which to sample the range.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size`: Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// //
// // Returns a tuple (q, residuals), where `q` is an ndarray containing the orthogonalized columns of
// // the range, and `residuals` is a vector of tuples of the form `(rank, rel_res)`, where `rel_res`
// // is the estimated relative residual for the first `rank` columns of `q`.
// pub fn sample_range_adaptive<Op: ConjRowMatMat, R: Rng>(
// op: &Op,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<(Array2<Op::A>, Vec<(usize, f64)>)> {
// // This is a sampling factor. See Section 4.3 in Halko, Martinsson, Tropp,
// // Finding Structure with Randomness, SIAM Review.
// let tol_factor = num::cast::<f64, <Op::A as Scalar>::Real>(
// 10.0 * <f64 as num::traits::FloatConst>::FRAC_2_PI().sqrt(),
// )
// .unwrap();
// let m = op.ncols();
// let rel_tol = num::cast::<f64, <Op::A as Scalar>::Real>(rel_tol).unwrap();
// let omega = Op::A::random_gaussian((m, sample_size), rng);
// let mut op_omega = op.matmat(omega.view());
// // Randomized estimate of the original operator norm.
// let operator_norm = max_col_norm(&op_omega) * tol_factor;
// let mut max_norm = operator_norm;
// let mut q = Array2::<Op::A>::zeros((op.nrows(), 0));
// let mut b = Array2::<Op::A>::zeros((0, op.ncols()));
// let mut residuals = Vec::<(usize, f64)>::new();
// while max_norm / operator_norm >= rel_tol {
// // Orthogonalize against existing basis
// if q.ncols() > 0 {
// op_omega -= &q.dot(&q.t().map(|item| item.conj()).dot(&op_omega));
// }
// // Now do the QR of the vectors
// let (qtemp, _) = op_omega.qr().unwrap();
// // Extend the b matrix
// b = concatenate![Axis(0), b, op.conj_row_matmat(qtemp.view())];
// // Extend the Q matrix
// q = concatenate![Axis(1), q, qtemp];
// // Now compute new vectors
// let omega = Op::A::random_gaussian((m, sample_size), rng);
// op_omega = op.matmat(omega.view()) - q.dot(&b.dot(&omega));
// // Update the error tolerance
// max_norm = max_col_norm(&op_omega) * tol_factor;
// residuals.push((q.ncols(), (max_norm / operator_norm).to_f64().unwrap()));
// }
// Ok((q, residuals))
// }
// // Compute a QR decomposition via adaptive random range sampling.
// // # Arguments
// // * `op`: The operator for which to compute the QR decomposition.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size` Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// pub fn randomized_adaptive_qr<Op: ConjRowMatMat, R: Rng>(
// op: &Op,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<QRContainer<Op::A>> {
// let (q, _) = sample_range_adaptive(op, rel_tol, sample_size, rng)?;
// let b = op.conj_row_matmat(q.view());
// let mut qr = b.pivoted_qr()?;
// qr.q = b.dot(&qr.q);
// Ok(qr)
// }
// // Compute a SVD decomposition via adaptive random range sampling.
// // # Arguments
// // * `op`: The operator for which to compute the QR decomposition.
// // * `rel_tol`: The relative error tolerance. The error is checked probabilistically.
// // * `sample_size` Number of samples drawn together in each iteration.
// // * `rng`: The random number generator.
// pub fn randomized_adaptive_svd<Op: ConjRowMatMat, R: Rng>(
// op: &Op,
// rel_tol: f64,
// sample_size: usize,
// rng: &mut R,
// ) -> Result<SVDContainer<Op::A>> {
// let (q, _) = sample_range_adaptive(op, rel_tol, sample_size, rng)?;
// let b = op.conj_row_matmat(q.view());
// let mut svd = b.compute_svd()?;
// svd.u = b.dot(&svd.u);
// Ok(svd)
// }