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
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
//! Random matrix generation utilities
//!
//! This module provides functions for generating various types of random matrices
//! commonly used in scientific computing, testing, and simulations.

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::Complex;
use scirs2_core::numeric::{Float, NumAssign};
use scirs2_core::random::{Distribution, Normal, Uniform};
use scirs2_core::random::{Rng, RngExt};
use std::fmt::Debug;
use std::iter::Sum;

use crate::decomposition::qr;
use crate::error::{LinalgError, LinalgResult};

/// Standard distributions for matrix elements
#[derive(Debug, Clone, Copy)]
pub enum Distribution1D {
    /// Uniform distribution on [a, b]
    Uniform { a: f64, b: f64 },
    /// Normal distribution with given mean and standard deviation
    Normal { mean: f64, std_dev: f64 },
    /// Standard normal distribution (mean=0, std=1)
    StandardNormal,
}

/// Types of random matrices
#[derive(Debug, Clone, Copy)]
pub enum MatrixType {
    /// General random matrix with given distribution
    General(Distribution1D),
    /// Symmetric matrix
    Symmetric(Distribution1D),
    /// Positive definite matrix
    PositiveDefinite {
        eigenvalue_min: f64,
        eigenvalue_max: f64,
    },
    /// Orthogonal matrix (O^T * O = I)
    Orthogonal,
    /// Correlation matrix (symmetric positive semi-definite with 1s on diagonal)
    Correlation,
    /// Sparse matrix with given density
    Sparse {
        density: f64,
        distribution: Distribution1D,
    },
    /// Diagonal matrix
    Diagonal(Distribution1D),
    /// Triangular matrix (upper or lower)
    Triangular {
        upper: bool,
        distribution: Distribution1D,
    },
}

/// Generate a random matrix of the specified type
#[allow(dead_code)]
pub fn randommatrix<F, R>(
    rows: usize,
    cols: usize,
    matrix_type: MatrixType,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float
        + Debug
        + NumAssign
        + Sum
        + Send
        + Sync
        + scirs2_core::ndarray::ScalarOperand
        + 'static,
    R: Rng + ?Sized,
{
    match matrix_type {
        MatrixType::General(dist) => random_general(rows, cols, dist, rng),
        MatrixType::Symmetric(dist) => random_symmetric(rows, dist, rng),
        MatrixType::PositiveDefinite {
            eigenvalue_min,
            eigenvalue_max,
        } => random_positive_definite(rows, eigenvalue_min, eigenvalue_max, rng),
        MatrixType::Orthogonal => random_orthogonal(rows, rng),
        MatrixType::Correlation => random_correlation(rows, rng),
        MatrixType::Sparse {
            density,
            distribution,
        } => random_sparse(rows, cols, density, distribution, rng),
        MatrixType::Diagonal(dist) => random_diagonal(rows, dist, rng),
        MatrixType::Triangular {
            upper,
            distribution,
        } => random_triangular(rows, cols, upper, distribution, rng),
    }
}

/// Generate a general random matrix
#[allow(dead_code)]
fn random_general<F, R>(
    rows: usize,
    cols: usize,
    distribution: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let mut matrix = Array2::zeros((rows, cols));

    match distribution {
        Distribution1D::Uniform { a, b } => {
            let uniform = Uniform::new(a, b).map_err(|_| {
                LinalgError::ValueError("Invalid uniform distribution range".to_string())
            })?;
            for elem in matrix.iter_mut() {
                *elem = F::from(uniform.sample(rng)).expect("Operation failed");
            }
        }
        Distribution1D::Normal { mean, std_dev } => {
            let normal = Normal::new(mean, std_dev).map_err(|_| {
                LinalgError::ValueError("Invalid normal distribution parameters".to_string())
            })?;
            for elem in matrix.iter_mut() {
                *elem = F::from(normal.sample(rng)).expect("Operation failed");
            }
        }
        Distribution1D::StandardNormal => {
            let normal = Normal::new(0.0, 1.0).expect("Operation failed");
            for elem in matrix.iter_mut() {
                *elem = F::from(normal.sample(rng)).expect("Operation failed");
            }
        }
    }

    Ok(matrix)
}

/// Generate a symmetric random matrix
#[allow(dead_code)]
fn random_symmetric<F, R>(
    size: usize,
    distribution: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let mut matrix = random_general(size, size, distribution, rng)?;

    // Make it symmetric: A = (A + A^T) / 2
    for i in 0..size {
        for j in i + 1..size {
            let avg = (matrix[[i, j]] + matrix[[j, i]]) / F::from(2.0).expect("Operation failed");
            matrix[[i, j]] = avg;
            matrix[[j, i]] = avg;
        }
    }

    Ok(matrix)
}

/// Generate a positive definite matrix
#[allow(dead_code)]
fn random_positive_definite<F, R>(
    size: usize,
    eigenvalue_min: f64,
    eigenvalue_max: f64,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float
        + Debug
        + NumAssign
        + Sum
        + Send
        + Sync
        + scirs2_core::ndarray::ScalarOperand
        + 'static,
    R: Rng + ?Sized,
{
    if eigenvalue_min <= 0.0 {
        return Err(LinalgError::ValueError(
            "Minimum eigenvalue must be positive".to_string(),
        ));
    }

    // Generate random orthogonal matrix using QR decomposition
    let a = random_general(size, size, Distribution1D::StandardNormal, rng)?;
    let qr_result = qr(&a.view(), None)?;
    let (q, _) = qr_result;

    // Generate random eigenvalues in the specified range
    let uniform = Uniform::new(eigenvalue_min, eigenvalue_max)
        .map_err(|_| LinalgError::ValueError("Invalid eigenvalue range".to_string()))?;
    let mut eigenvalues = Array1::zeros(size);
    for i in 0..size {
        eigenvalues[i] = F::from(uniform.sample(rng)).expect("Operation failed");
    }

    // Create diagonal matrix with eigenvalues
    let mut d = Array2::zeros((size, size));
    for i in 0..size {
        d[[i, i]] = eigenvalues[i];
    }

    // A = Q * D * Q^T
    let qd = q.dot(&d);
    let qt = q.t();
    let result = qd.dot(&qt);

    Ok(result)
}

/// Generate a random orthogonal matrix using QR decomposition
#[allow(dead_code)]
fn random_orthogonal<F, R>(size: usize, rng: &mut R) -> LinalgResult<Array2<F>>
where
    F: Float
        + Debug
        + NumAssign
        + Sum
        + Send
        + Sync
        + scirs2_core::ndarray::ScalarOperand
        + 'static,
    R: Rng + ?Sized,
{
    // Generate random matrix with normal distribution
    let a = random_general(size, size, Distribution1D::StandardNormal, rng)?;

    // Perform QR decomposition
    let qr_result = qr(&a.view(), None)?;

    // Q is orthogonal
    let (q, _) = qr_result;
    Ok(q)
}

/// Generate a random correlation matrix
#[allow(dead_code)]
fn random_correlation<F, R>(size: usize, rng: &mut R) -> LinalgResult<Array2<F>>
where
    F: Float
        + Debug
        + NumAssign
        + Sum
        + Send
        + Sync
        + scirs2_core::ndarray::ScalarOperand
        + 'static,
    R: Rng + ?Sized,
{
    // Start with a positive definite matrix
    let mut matrix = random_positive_definite(size, 0.1, 10.0, rng)?;

    // Normalize to get correlations
    let diag = matrix.diag().to_owned();
    for i in 0..size {
        for j in 0..size {
            let prod: F = diag[i] * diag[j];
            let denom = prod.sqrt();
            matrix[[i, j]] /= denom;
        }
    }

    // Ensure diagonal is exactly 1
    for i in 0..size {
        matrix[[i, i]] = F::one();
    }

    Ok(matrix)
}

/// Generate a sparse random matrix
#[allow(dead_code)]
fn random_sparse<F, R>(
    rows: usize,
    cols: usize,
    density: f64,
    distribution: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float,
    R: Rng + ?Sized,
{
    if !(0.0..=1.0).contains(&density) {
        return Err(LinalgError::ValueError(
            "Density must be between 0 and 1".to_string(),
        ));
    }

    let mut matrix = Array2::zeros((rows, cols));
    let uniform = Uniform::new(0.0, 1.0)
        .map_err(|_| LinalgError::ValueError("Invalid uniform distribution range".to_string()))?;

    for i in 0..rows {
        for j in 0..cols {
            if F::from(uniform.sample(rng)).expect("Operation failed")
                < F::from(density).expect("Operation failed")
            {
                matrix[[i, j]] = match distribution {
                    Distribution1D::Uniform { a, b } => {
                        F::from(Uniform::new(a, b).expect("Operation failed").sample(rng))
                            .expect("Operation failed")
                    }
                    Distribution1D::Normal { mean, std_dev } => F::from(
                        Normal::new(mean, std_dev)
                            .expect("Operation failed")
                            .sample(rng),
                    )
                    .expect("Operation failed"),
                    Distribution1D::StandardNormal => {
                        F::from(Normal::new(0.0, 1.0).expect("Operation failed").sample(rng))
                            .expect("Operation failed")
                    }
                };
            }
        }
    }

    Ok(matrix)
}

/// Generate a random diagonal matrix
#[allow(dead_code)]
fn random_diagonal<F, R>(
    size: usize,
    distribution: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let mut matrix = Array2::zeros((size, size));

    match distribution {
        Distribution1D::Uniform { a, b } => {
            let uniform = Uniform::new(a, b).map_err(|_| {
                LinalgError::ValueError("Invalid uniform distribution range".to_string())
            })?;
            for i in 0..size {
                matrix[[i, i]] = F::from(uniform.sample(rng)).expect("Operation failed");
            }
        }
        Distribution1D::Normal { mean, std_dev } => {
            let normal = Normal::new(mean, std_dev).map_err(|_| {
                LinalgError::ValueError("Invalid normal distribution parameters".to_string())
            })?;
            for i in 0..size {
                matrix[[i, i]] = F::from(normal.sample(rng)).expect("Operation failed");
            }
        }
        Distribution1D::StandardNormal => {
            let normal = Normal::new(0.0, 1.0).expect("Operation failed");
            for i in 0..size {
                matrix[[i, i]] = F::from(normal.sample(rng)).expect("Operation failed");
            }
        }
    }

    Ok(matrix)
}

/// Generate a random triangular matrix
#[allow(dead_code)]
fn random_triangular<F, R>(
    rows: usize,
    cols: usize,
    upper: bool,
    distribution: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<F>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let mut matrix = Array2::zeros((rows, cols));

    for i in 0..rows {
        for j in 0..cols {
            let should_fill = if upper { j >= i } else { j <= i };
            if should_fill {
                matrix[[i, j]] = match distribution {
                    Distribution1D::Uniform { a, b } => {
                        F::from(Uniform::new(a, b).expect("Operation failed").sample(rng))
                            .expect("Operation failed")
                    }
                    Distribution1D::Normal { mean, std_dev } => F::from(
                        Normal::new(mean, std_dev)
                            .expect("Operation failed")
                            .sample(rng),
                    )
                    .expect("Operation failed"),
                    Distribution1D::StandardNormal => {
                        F::from(Normal::new(0.0, 1.0).expect("Operation failed").sample(rng))
                            .expect("Operation failed")
                    }
                };
            }
        }
    }

    Ok(matrix)
}

/// Generate a random complex matrix
#[allow(dead_code)]
pub fn random_complexmatrix<F, R>(
    rows: usize,
    cols: usize,
    real_dist: Distribution1D,
    imag_dist: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<Complex<F>>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let real_part = random_general(rows, cols, real_dist, rng)?;
    let imag_part = random_general(rows, cols, imag_dist, rng)?;

    let mut matrix = Array2::zeros((rows, cols));
    for i in 0..rows {
        for j in 0..cols {
            matrix[[i, j]] = Complex::new(real_part[[i, j]], imag_part[[i, j]]);
        }
    }

    Ok(matrix)
}

/// Generate a random Hermitian matrix
#[allow(dead_code)]
pub fn random_hermitian<F, R>(
    size: usize,
    real_dist: Distribution1D,
    imag_dist: Distribution1D,
    rng: &mut R,
) -> LinalgResult<Array2<Complex<F>>>
where
    F: Float,
    R: Rng + ?Sized,
{
    let mut matrix = random_complexmatrix(size, size, real_dist, imag_dist, rng)?;

    // Make it Hermitian: A = (A + A^H) / 2
    for i in 0..size {
        for j in i + 1..size {
            let avg = (matrix[[i, j]] + matrix[[j, i]].conj())
                / Complex::from(F::from(2.0).expect("Operation failed"));
            matrix[[i, j]] = avg;
            matrix[[j, i]] = avg.conj();
        }
        // Diagonal elements must be real
        matrix[[i, i]] = Complex::new(matrix[[i, i]].re, F::zero());
    }

    Ok(matrix)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use scirs2_core::random::{ChaCha8Rng, SeedableRng};

    #[test]
    fn test_symmetricmatrix() {
        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let matrix = randommatrix::<f64, ChaCha8Rng>(
            5,
            5,
            MatrixType::Symmetric(Distribution1D::StandardNormal),
            &mut rng,
        )
        .expect("Operation failed");

        // Check symmetry
        for i in 0..5 {
            for j in 0..5 {
                assert_relative_eq!(matrix[[i, j]], matrix[[j, i]], epsilon = 1e-10);
            }
        }
    }

    #[test]
    fn test_orthogonalmatrix() {
        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let q = randommatrix::<f64, ChaCha8Rng>(4, 4, MatrixType::Orthogonal, &mut rng)
            .expect("Operation failed");

        // Check Q^T * Q = I
        let qt = q.t();
        let qtq = qt.dot(&q);

        for i in 0..4 {
            for j in 0..4 {
                let expected = if i == j { 1.0 } else { 0.0 };
                assert_relative_eq!(qtq[[i, j]], expected, epsilon = 1e-10);
            }
        }
    }

    #[test]
    fn test_positive_definite() {
        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let matrix = randommatrix::<f64, ChaCha8Rng>(
            3,
            3,
            MatrixType::PositiveDefinite {
                eigenvalue_min: 0.1,
                eigenvalue_max: 5.0,
            },
            &mut rng,
        )
        .expect("Operation failed");

        // A positive definite matrix should be symmetric
        for i in 0..3 {
            for j in 0..3 {
                assert_relative_eq!(matrix[[i, j]], matrix[[j, i]], epsilon = 1e-10);
            }
        }

        // Should have positive eigenvalues (we won't compute them here, just test Cholesky)
        use crate::cholesky;
        let result = cholesky(&matrix.view(), None);
        assert!(result.is_ok(), "Matrix should be positive definite");
    }

    #[test]
    fn test_correlationmatrix() {
        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let matrix = randommatrix::<f64, ChaCha8Rng>(4, 4, MatrixType::Correlation, &mut rng)
            .expect("Operation failed");

        // Check diagonal elements are 1
        for i in 0..4 {
            assert_relative_eq!(matrix[[i, i]], 1.0, epsilon = 1e-10);
        }

        // Check symmetry
        for i in 0..4 {
            for j in 0..4 {
                assert_relative_eq!(matrix[[i, j]], matrix[[j, i]], epsilon = 1e-10);
            }
        }

        // Check elements are in [-1, 1]
        for elem in matrix.iter() {
            assert!(*elem >= -1.0 && *elem <= 1.0);
        }
    }
}