scirs2-linalg 0.4.2

Linear algebra module for SciRS2 (scirs2-linalg)
Documentation
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
//! Matrix analysis functions including decompositions and matrix norms

use scirs2_core::ndarray::{Array2, ArrayView2};
use scirs2_core::numeric::{Float, NumAssign, One};
use std::iter::Sum;

use crate::eigen::eig;
use crate::error::{LinalgError, LinalgResult};
use crate::solve::solve_multiple;
use crate::validation::validate_decomposition;

/// Compute the spectral radius of a matrix.
///
/// The spectral radius is the largest absolute value of the eigenvalues.
///
/// # Arguments
///
/// * `a` - Input square matrix
/// * `workers` - Number of worker threads (None = use default)
///
/// # Returns
///
/// * Spectral radius (largest eigenvalue magnitude)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::spectral_radius;
///
/// let a = array![[2.0_f64, 0.0], [0.0, 3.0]];
/// let rho = spectral_radius(&a.view(), None).expect("Operation failed");
/// // rho should be 3.0
/// ```
#[allow(dead_code)]
pub fn spectral_radius<F>(a: &ArrayView2<F>, workers: Option<usize>) -> LinalgResult<F>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    use crate::parallel;

    // Configure workers for parallel operations
    parallel::configure_workers(workers);

    validate_decomposition(a, "Spectral radius computation", true)?;

    // Compute eigenvalues
    let (eigenvals, _) = eig(a, None)?;

    // Find the maximum absolute value
    let mut max_abs = F::zero();
    for &val in eigenvals.iter() {
        let abs_val = (val.re * val.re + val.im * val.im).sqrt();
        if abs_val > max_abs {
            max_abs = abs_val;
        }
    }

    Ok(max_abs)
}

/// Compute the spectral condition number of a matrix.
///
/// The spectral condition number is the ratio of the largest to smallest
/// singular values (or eigenvalues for symmetric matrices).
///
/// # Arguments
///
/// * `a` - Input square matrix
/// * `workers` - Number of worker threads (None = use default)
///
/// # Returns
///
/// * Spectral condition number
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::spectral_condition_number;
///
/// let a = array![[2.0_f64, 0.0], [0.0, 1.0]];
/// let cond = spectral_condition_number(&a.view(), None).expect("Operation failed");
/// // cond should be 2.0
/// ```
#[allow(dead_code)]
pub fn spectral_condition_number<F>(a: &ArrayView2<F>, workers: Option<usize>) -> LinalgResult<F>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    use crate::parallel;

    // Configure workers for parallel operations
    parallel::configure_workers(workers);

    validate_decomposition(a, "Spectral condition number computation", true)?;

    // Compute eigenvalues
    let (eigenvals, _) = eig(a, None)?;

    // Find the maximum and minimum absolute values
    let mut max_abs = F::zero();
    let mut min_abs = F::infinity();

    for &val in eigenvals.iter() {
        let abs_val = (val.re * val.re + val.im * val.im).sqrt();
        if abs_val > max_abs {
            max_abs = abs_val;
        }
        if abs_val < min_abs && abs_val > F::epsilon() {
            min_abs = abs_val;
        }
    }

    // Check for singular matrix
    if min_abs < F::epsilon() {
        return Ok(F::infinity());
    }

    Ok(max_abs / min_abs)
}

/// Compute the polar decomposition of a matrix.
///
/// The polar decomposition factorizes a matrix A as A = UP where U is unitary
/// and P is positive semidefinite.
///
/// # Arguments
///
/// * `a` - Input matrix
/// * `side` - Which factor to return ("left" for A = UP, "right" for A = PU)
///
/// # Returns
///
/// * (U, P) - Unitary and positive semidefinite factors
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::polar_decomposition;
///
/// let a = array![[2.0_f64, 1.0], [0.0, 1.0]];
/// let (u, p) = polar_decomposition(&a.view(), "right").expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn polar_decomposition<F>(a: &ArrayView2<F>, side: &str) -> LinalgResult<(Array2<F>, Array2<F>)>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    use super::exponential::sqrtm;

    validate_decomposition(a, "Polar decomposition", false)?;

    let (m, n) = a.dim();

    match side {
        "right" => {
            // Right polar decomposition: A = UP
            // P = sqrt(A^H * A), U = A * P^{-1}

            // Compute A^H * A
            let mut aha = Array2::<F>::zeros((n, n));
            for i in 0..n {
                for j in 0..n {
                    for k in 0..m {
                        aha[[i, j]] += a[[k, i]] * a[[k, j]]; // A^H * A
                    }
                }
            }

            // Compute P = sqrt(A^H * A)
            let p = sqrtm(&aha.view(), 50, F::from(1e-12).expect("Operation failed"))?;

            // Compute U = A * P^{-1}
            let p_inv = solve_multiple(&p.view(), &Array2::eye(n).view(), None)?;

            let mut u = Array2::<F>::zeros((m, n));
            for i in 0..m {
                for j in 0..n {
                    for k in 0..n {
                        u[[i, j]] += a[[i, k]] * p_inv[[k, j]];
                    }
                }
            }

            Ok((u, p))
        }
        "left" => {
            // Left polar decomposition: A = PU
            // P = sqrt(A * A^H), U = P^{-1} * A

            // Compute A * A^H
            let mut aah = Array2::<F>::zeros((m, m));
            for i in 0..m {
                for j in 0..m {
                    for k in 0..n {
                        aah[[i, j]] += a[[i, k]] * a[[j, k]]; // A * A^H
                    }
                }
            }

            // Compute P = sqrt(A * A^H)
            let p = sqrtm(&aah.view(), 50, F::from(1e-12).expect("Operation failed"))?;

            // Compute U = P^{-1} * A
            let p_inv = solve_multiple(&p.view(), &Array2::eye(m).view(), None)?;

            let mut u = Array2::<F>::zeros((m, n));
            for i in 0..m {
                for j in 0..n {
                    for k in 0..m {
                        u[[i, j]] += p_inv[[i, k]] * a[[k, j]];
                    }
                }
            }

            Ok((p, u))
        }
        _ => Err(LinalgError::InvalidInputError(format!(
            "Invalid side '{}'. Must be 'left' or 'right'",
            side
        ))),
    }
}

/// Compute the geometric mean of symmetric positive definite matrices.
///
/// For two SPD matrices A and B, the geometric mean is:
/// A #_t B = A^{1/2} * (A^{-1/2} * B * A^{-1/2})^t * A^{1/2}
///
/// For t = 1/2, this gives the standard geometric mean.
///
/// # Arguments
///
/// * `a` - First SPD matrix
/// * `b` - Second SPD matrix
/// * `t` - Parameter (0.5 for standard geometric mean)
///
/// # Returns
///
/// * Geometric mean of A and B
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::geometric_mean_spd;
///
/// let a = array![[4.0_f64, 0.0], [0.0, 1.0]];
/// let b = array![[1.0_f64, 0.0], [0.0, 4.0]];
/// let mean = geometric_mean_spd(&a.view(), &b.view(), 0.5).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn geometric_mean_spd<F>(a: &ArrayView2<F>, b: &ArrayView2<F>, t: F) -> LinalgResult<Array2<F>>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    use super::exponential::sqrtm;
    use super::fractional::spdmatrix_function;

    validate_decomposition(a, "Geometric mean computation (matrix A)", true)?;
    validate_decomposition(b, "Geometric mean computation (matrix B)", true)?;

    if a.dim() != b.dim() {
        return Err(LinalgError::ShapeError(
            "Matrices must have the same dimensions".to_string(),
        ));
    }

    let n = a.nrows();

    // Check if matrices are symmetric
    for i in 0..n {
        for j in 0..n {
            if (a[[i, j]] - a[[j, i]]).abs() > F::epsilon() {
                return Err(LinalgError::InvalidInputError(
                    "Matrix A must be symmetric".to_string(),
                ));
            }
            if (b[[i, j]] - b[[j, i]]).abs() > F::epsilon() {
                return Err(LinalgError::InvalidInputError(
                    "Matrix B must be symmetric".to_string(),
                ));
            }
        }
    }

    // Compute A^{1/2}
    let a_half = spdmatrix_function(a, |x| x.sqrt(), true)?;

    // Compute A^{-1/2}
    let a_neg_half = spdmatrix_function(a, |x| F::one() / x.sqrt(), true)?;

    // Compute A^{-1/2} * B * A^{-1/2}
    let mut temp1 = Array2::<F>::zeros((n, n));
    for i in 0..n {
        for j in 0..n {
            for k in 0..n {
                temp1[[i, j]] += a_neg_half[[i, k]] * b[[k, j]];
            }
        }
    }

    let mut similarity = Array2::<F>::zeros((n, n));
    for i in 0..n {
        for j in 0..n {
            for k in 0..n {
                similarity[[i, j]] += temp1[[i, k]] * a_neg_half[[k, j]];
            }
        }
    }

    // Compute (A^{-1/2} * B * A^{-1/2})^t
    let powered_similarity = spdmatrix_function(&similarity.view(), |x| x.powf(t), true)?;

    // Compute A^{1/2} * (A^{-1/2} * B * A^{-1/2})^t * A^{1/2}
    let mut temp2 = Array2::<F>::zeros((n, n));
    for i in 0..n {
        for j in 0..n {
            for k in 0..n {
                temp2[[i, j]] += a_half[[i, k]] * powered_similarity[[k, j]];
            }
        }
    }

    let mut result = Array2::<F>::zeros((n, n));
    for i in 0..n {
        for j in 0..n {
            for k in 0..n {
                result[[i, j]] += temp2[[i, k]] * a_half[[k, j]];
            }
        }
    }

    Ok(result)
}

/// Compute Tikhonov regularization of a matrix.
///
/// Tikhonov regularization adds a ridge term to improve conditioning:
/// A_reg = A + λI
///
/// # Arguments
///
/// * `a` - Input matrix
/// * `lambda` - Regularization parameter
/// * `identity_like` - Whether to add λI (true) or λ times identity-like term
///
/// # Returns
///
/// * Regularized matrix
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::tikhonov_regularization;
///
/// let a = array![[1.0_f64, 0.5], [0.5, 1.0]];
/// let reg_a = tikhonov_regularization(&a.view(), 0.1, true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn tikhonov_regularization<F>(
    a: &ArrayView2<F>,
    lambda: F,
    identity_like: bool,
) -> LinalgResult<Array2<F>>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    let (m, n) = a.dim();

    if identity_like && m != n {
        return Err(LinalgError::ShapeError(
            "Matrix must be square for identity-like regularization".to_string(),
        ));
    }

    let mut result = a.to_owned();

    if identity_like {
        // Add λI to the diagonal
        for i in 0..n {
            result[[i, i]] += lambda;
        }
    } else {
        // Add λ to all elements (different regularization scheme)
        for i in 0..m {
            for j in 0..n {
                result[[i, j]] += lambda;
            }
        }
    }

    Ok(result)
}

/// Compute the nuclear norm (trace norm) of a matrix.
///
/// The nuclear norm is the sum of singular values, which for symmetric matrices
/// is the sum of absolute eigenvalues.
///
/// # Arguments
///
/// * `a` - Input matrix
/// * `workers` - Number of worker threads (None = use default)
///
/// # Returns
///
/// * Nuclear norm of the matrix
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_linalg::matrix_functions::nuclear_norm;
///
/// let a = array![[2.0_f64, 0.0], [0.0, 3.0]];
/// let norm = nuclear_norm(&a.view(), None).expect("Operation failed");
/// // norm should be 5.0
/// ```
#[allow(dead_code)]
pub fn nuclear_norm<F>(a: &ArrayView2<F>, workers: Option<usize>) -> LinalgResult<F>
where
    F: Float + NumAssign + Sum + One + Send + Sync + scirs2_core::ndarray::ScalarOperand + 'static,
{
    use crate::parallel;

    // Configure workers for parallel operations
    parallel::configure_workers(workers);

    validate_decomposition(a, "Nuclear norm computation", false)?;

    let (m, n) = a.dim();

    if m == n {
        // For square matrices, use eigendecomposition
        // This gives us the singular values for symmetric matrices
        let (eigenvals, _) = eig(a, None)?;

        let mut sum = F::zero();
        for &val in eigenvals.iter() {
            sum += (val.re * val.re + val.im * val.im).sqrt();
        }

        Ok(sum)
    } else {
        // For non-square matrices, we'd need SVD
        // For now, return an error
        Err(LinalgError::ImplementationError(
            "Nuclear norm for non-square matrices requires SVD (not yet implemented)".to_string(),
        ))
    }
}