numra-linalg 0.1.4

Linear algebra abstractions for Numra: dense and sparse matrices, LU/QR/Cholesky/SVD, iterative solvers (CG, GMRES, BiCGSTAB).
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Matrix trait and implementations.
//!
//! Author: Moussa Leblouba
//! Date: 8 February 2026
//! Modified: 2 May 2026

use crate::Scalar;
use faer::prelude::*;
use faer::{ComplexField, Conjugate, Entity, Mat, MatMut, MatRef, SimpleEntity};
use numra_core::LinalgError;

/// Trait for matrix types.
///
/// Provides a backend-agnostic interface for matrix operations needed by ODE
/// solvers.
///
/// **Sparse storage**: [`crate::SparseMatrix`] is not currently in this trait.
/// Sparse-aware solvers (`crate::iterative`, `crate::preconditioner`) dispatch
/// on `&SparseMatrix<S>` concretely rather than through `dyn Matrix<S>`.
/// Whether sparse should join this trait is an open foundation question
/// coupled to sparse-Jacobian-return, deferred per Foundation Spec §7 #5
/// under the spec's named trigger ("when a sparse-aware solver path needs to
/// dispatch across both dense and sparse via a single trait"). The current
/// dense-only scope is the expedient state, not a deliberate design — see
/// F-MATRIX-SHAPE in `docs/internal-followups.md` for the operational
/// tracker, and Foundation Spec §3.2 + §7 #5 for the design context.
pub trait Matrix<S: Scalar>: Clone + Sized {
    /// Create a zero matrix with given dimensions.
    fn zeros(rows: usize, cols: usize) -> Self;

    /// Create an identity matrix.
    fn identity(n: usize) -> Self;

    /// Number of rows.
    fn nrows(&self) -> usize;

    /// Number of columns.
    fn ncols(&self) -> usize;

    /// Get element at (i, j).
    fn get(&self, i: usize, j: usize) -> S;

    /// Set element at (i, j).
    fn set(&mut self, i: usize, j: usize, value: S);

    /// Fill matrix with zeros.
    fn fill_zero(&mut self);

    /// Scale all elements by a constant.
    fn scale(&mut self, alpha: S);

    /// Compute y = self * x (matrix-vector product).
    fn mul_vec(&self, x: &[S], y: &mut [S]);

    /// Add another matrix: self += alpha * other.
    fn add_scaled(&mut self, alpha: S, other: &Self);

    /// Solve the linear system Ax = b, returning x.
    fn solve(&self, b: &[S]) -> Result<Vec<S>, LinalgError>;

    /// Check if matrix is square.
    fn is_square(&self) -> bool {
        self.nrows() == self.ncols()
    }
}

/// Dense matrix backed by faer.
#[derive(Clone, Debug)]
pub struct DenseMatrix<S: Scalar + Entity> {
    data: Mat<S>,
}

impl<S: Scalar + Entity> DenseMatrix<S> {
    /// Create from a faer Mat.
    pub fn from_faer(mat: Mat<S>) -> Self {
        Self { data: mat }
    }

    /// Get reference to underlying faer matrix.
    pub fn as_faer(&self) -> MatRef<'_, S> {
        self.data.as_ref()
    }

    /// Get mutable reference to underlying faer matrix.
    pub fn as_faer_mut(&mut self) -> MatMut<'_, S> {
        self.data.as_mut()
    }

    /// Create from row-major data.
    pub fn from_row_major(rows: usize, cols: usize, data: &[S]) -> Self {
        assert_eq!(data.len(), rows * cols);
        let mut mat = Mat::zeros(rows, cols);
        for i in 0..rows {
            for j in 0..cols {
                mat.write(i, j, data[i * cols + j]);
            }
        }
        Self { data: mat }
    }

    /// Create from column-major data.
    pub fn from_col_major(rows: usize, cols: usize, data: &[S]) -> Self {
        assert_eq!(data.len(), rows * cols);
        let mut mat = Mat::zeros(rows, cols);
        for j in 0..cols {
            for i in 0..rows {
                mat.write(i, j, data[j * rows + i]);
            }
        }
        Self { data: mat }
    }

    /// Convert to row-major vector.
    pub fn to_row_major(&self) -> Vec<S> {
        let (rows, cols) = (self.data.nrows(), self.data.ncols());
        let mut data = Vec::with_capacity(rows * cols);
        for i in 0..rows {
            for j in 0..cols {
                data.push(self.data.read(i, j));
            }
        }
        data
    }

    /// Frobenius norm.
    pub fn norm_frobenius(&self) -> S {
        let mut sum = S::ZERO;
        for i in 0..self.data.nrows() {
            for j in 0..self.data.ncols() {
                let v = self.data.read(i, j);
                sum += v * v;
            }
        }
        sum.sqrt()
    }

    /// Infinity norm (max row sum).
    pub fn norm_inf(&self) -> S {
        let mut max_sum = S::ZERO;
        for i in 0..self.data.nrows() {
            let mut row_sum = S::ZERO;
            for j in 0..self.data.ncols() {
                row_sum += self.data.read(i, j).abs();
            }
            max_sum = max_sum.max(row_sum);
        }
        max_sum
    }

    /// Number of rows (direct access without trait).
    pub fn rows(&self) -> usize {
        self.data.nrows()
    }

    /// Number of columns (direct access without trait).
    pub fn cols(&self) -> usize {
        self.data.ncols()
    }

    /// Check if square (direct access without trait).
    pub fn is_square(&self) -> bool {
        self.data.nrows() == self.data.ncols()
    }
}

impl<S: Scalar + SimpleEntity + Conjugate<Canonical = S> + ComplexField> Matrix<S>
    for DenseMatrix<S>
{
    fn zeros(rows: usize, cols: usize) -> Self {
        Self {
            data: Mat::zeros(rows, cols),
        }
    }

    fn identity(n: usize) -> Self {
        let mut mat = Mat::zeros(n, n);
        for i in 0..n {
            mat.write(i, i, S::ONE);
        }
        Self { data: mat }
    }

    fn nrows(&self) -> usize {
        self.data.nrows()
    }

    fn ncols(&self) -> usize {
        self.data.ncols()
    }

    fn get(&self, i: usize, j: usize) -> S {
        self.data.read(i, j)
    }

    fn set(&mut self, i: usize, j: usize, value: S) {
        self.data.write(i, j, value);
    }

    fn fill_zero(&mut self) {
        for i in 0..self.nrows() {
            for j in 0..self.ncols() {
                self.data.write(i, j, S::ZERO);
            }
        }
    }

    fn scale(&mut self, alpha: S) {
        for i in 0..self.nrows() {
            for j in 0..self.ncols() {
                let v = self.data.read(i, j);
                self.data.write(i, j, alpha * v);
            }
        }
    }

    fn mul_vec(&self, x: &[S], y: &mut [S]) {
        assert_eq!(x.len(), self.ncols());
        assert_eq!(y.len(), self.nrows());

        for (i, y_i) in y.iter_mut().enumerate().take(self.nrows()) {
            let mut sum = S::ZERO;
            for (j, &x_j) in x.iter().enumerate().take(self.ncols()) {
                sum += self.data.read(i, j) * x_j;
            }
            *y_i = sum;
        }
    }

    fn add_scaled(&mut self, alpha: S, other: &Self) {
        assert_eq!(self.nrows(), other.nrows());
        assert_eq!(self.ncols(), other.ncols());

        for i in 0..self.nrows() {
            for j in 0..self.ncols() {
                let v = self.data.read(i, j) + alpha * other.data.read(i, j);
                self.data.write(i, j, v);
            }
        }
    }

    fn solve(&self, b: &[S]) -> Result<Vec<S>, LinalgError> {
        if !self.is_square() {
            return Err(LinalgError::NotSquare {
                nrows: self.nrows(),
                ncols: self.ncols(),
            });
        }
        if b.len() != self.nrows() {
            return Err(LinalgError::DimensionMismatch {
                expected: (self.nrows(), 1),
                actual: (b.len(), 1),
            });
        }

        // Use faer's LU solver
        let lu = self.data.as_ref().partial_piv_lu();

        // Create column vector from b
        let mut b_mat = Mat::zeros(b.len(), 1);
        for (i, &val) in b.iter().enumerate() {
            b_mat.write(i, 0, val);
        }

        // Solve
        let x_mat = lu.solve(&b_mat);

        // Extract result
        let mut x = Vec::with_capacity(b.len());
        for i in 0..b.len() {
            x.push(x_mat.read(i, 0));
        }

        Ok(x)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zeros() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(3, 4);
        assert_eq!(m.nrows(), 3);
        assert_eq!(m.ncols(), 4);
        for i in 0..3 {
            for j in 0..4 {
                assert!((m.get(i, j) - 0.0).abs() < 1e-15);
            }
        }
    }

    #[test]
    fn test_identity() {
        let m: DenseMatrix<f64> = DenseMatrix::identity(3);
        assert_eq!(m.nrows(), 3);
        assert_eq!(m.ncols(), 3);
        for i in 0..3 {
            for j in 0..3 {
                let expected = if i == j { 1.0 } else { 0.0 };
                assert!((m.get(i, j) - expected).abs() < 1e-15);
            }
        }
    }

    #[test]
    fn test_set_get() {
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, 4.0);

        assert!((m.get(0, 0) - 1.0).abs() < 1e-15);
        assert!((m.get(0, 1) - 2.0).abs() < 1e-15);
        assert!((m.get(1, 0) - 3.0).abs() < 1e-15);
        assert!((m.get(1, 1) - 4.0).abs() < 1e-15);
    }

    #[test]
    fn test_mul_vec() {
        // [1 2] * [1]   [5]
        // [3 4]   [2] = [11]
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, 4.0);

        let x = [1.0, 2.0];
        let mut y = [0.0, 0.0];
        m.mul_vec(&x, &mut y);

        assert!((y[0] - 5.0).abs() < 1e-10);
        assert!((y[1] - 11.0).abs() < 1e-10);
    }

    #[test]
    fn test_scale() {
        let mut m: DenseMatrix<f64> = DenseMatrix::identity(2);
        m.scale(3.0);
        assert!((m.get(0, 0) - 3.0).abs() < 1e-15);
        assert!((m.get(1, 1) - 3.0).abs() < 1e-15);
    }

    #[test]
    fn test_add_scaled() {
        let mut a: DenseMatrix<f64> = DenseMatrix::identity(2);
        let b: DenseMatrix<f64> = DenseMatrix::identity(2);
        a.add_scaled(2.0, &b);

        // a should now be 3*I
        assert!((a.get(0, 0) - 3.0).abs() < 1e-15);
        assert!((a.get(1, 1) - 3.0).abs() < 1e-15);
    }

    #[test]
    fn test_solve_diagonal() {
        // Solve diag(2, 3, 4) * x = [1, 2, 3]
        // x = [0.5, 2/3, 0.75]
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(3, 3);
        m.set(0, 0, 2.0);
        m.set(1, 1, 3.0);
        m.set(2, 2, 4.0);

        let b = vec![1.0, 2.0, 3.0];
        let x = m.solve(&b).unwrap();

        assert!((x[0] - 0.5).abs() < 1e-10);
        assert!((x[1] - 2.0 / 3.0).abs() < 1e-10);
        assert!((x[2] - 0.75).abs() < 1e-10);
    }

    #[test]
    fn test_solve_general() {
        // Solve [1 2; 3 4] * x = [5; 11]
        // x = [1; 2]
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, 4.0);

        let b = vec![5.0, 11.0];
        let x = m.solve(&b).unwrap();

        assert!((x[0] - 1.0).abs() < 1e-10);
        assert!((x[1] - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_from_row_major() {
        let data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let m: DenseMatrix<f64> = DenseMatrix::from_row_major(2, 3, &data);

        assert_eq!(m.nrows(), 2);
        assert_eq!(m.ncols(), 3);
        assert!((m.get(0, 0) - 1.0).abs() < 1e-15);
        assert!((m.get(0, 2) - 3.0).abs() < 1e-15);
        assert!((m.get(1, 0) - 4.0).abs() < 1e-15);
        assert!((m.get(1, 2) - 6.0).abs() < 1e-15);
    }

    #[test]
    fn test_norm_frobenius() {
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, 4.0);

        // sqrt(1 + 4 + 9 + 16) = sqrt(30)
        let norm = m.norm_frobenius();
        assert!((norm - 30.0_f64.sqrt()).abs() < 1e-10);
    }

    // ============================================================================
    // Edge Case Tests
    // ============================================================================

    #[test]
    fn test_1x1_matrix() {
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(1, 1);
        m.set(0, 0, 5.0);
        assert!(m.is_square());
        assert!((m.get(0, 0) - 5.0).abs() < 1e-15);

        let b = vec![10.0];
        let x = m.solve(&b).unwrap();
        assert!((x[0] - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_identity_1x1() {
        let m: DenseMatrix<f64> = DenseMatrix::identity(1);
        assert!((m.get(0, 0) - 1.0).abs() < 1e-15);
    }

    #[test]
    fn test_rectangular_not_square() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 3);
        assert!(!m.is_square());
    }

    #[test]
    fn test_solve_non_square_error() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 3);
        let b = vec![1.0, 2.0];
        let result = m.solve(&b);
        assert!(result.is_err());
    }

    #[test]
    fn test_solve_dimension_mismatch() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        let b = vec![1.0, 2.0, 3.0]; // Wrong size
        let result = m.solve(&b);
        assert!(result.is_err());
    }

    #[test]
    fn test_fill_zero() {
        let mut m: DenseMatrix<f64> = DenseMatrix::identity(3);
        m.fill_zero();
        for i in 0..3 {
            for j in 0..3 {
                assert!(m.get(i, j).abs() < 1e-15);
            }
        }
    }

    #[test]
    fn test_scale_by_zero() {
        let mut m: DenseMatrix<f64> = DenseMatrix::identity(2);
        m.scale(0.0);
        for i in 0..2 {
            for j in 0..2 {
                assert!(m.get(i, j).abs() < 1e-15);
            }
        }
    }

    #[test]
    fn test_scale_by_negative() {
        let mut m: DenseMatrix<f64> = DenseMatrix::identity(2);
        m.scale(-1.0);
        assert!((m.get(0, 0) + 1.0).abs() < 1e-15);
        assert!((m.get(1, 1) + 1.0).abs() < 1e-15);
    }

    #[test]
    fn test_mul_vec_with_zeros() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        let x = [100.0, 200.0];
        let mut y = [999.0, 999.0];
        m.mul_vec(&x, &mut y);
        assert!(y[0].abs() < 1e-15);
        assert!(y[1].abs() < 1e-15);
    }

    #[test]
    fn test_norm_inf() {
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, -1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, -4.0);

        // Row 0: |−1| + |2| = 3
        // Row 1: |3| + |−4| = 7
        // Max = 7
        assert!((m.norm_inf() - 7.0).abs() < 1e-10);
    }

    #[test]
    fn test_zeros_large() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(100, 100);
        assert_eq!(m.nrows(), 100);
        assert_eq!(m.ncols(), 100);
    }

    #[test]
    fn test_from_col_major() {
        // Column-major: col0 = [1, 3], col1 = [2, 4]
        let data = [1.0, 3.0, 2.0, 4.0];
        let m: DenseMatrix<f64> = DenseMatrix::from_col_major(2, 2, &data);

        assert!((m.get(0, 0) - 1.0).abs() < 1e-15);
        assert!((m.get(1, 0) - 3.0).abs() < 1e-15);
        assert!((m.get(0, 1) - 2.0).abs() < 1e-15);
        assert!((m.get(1, 1) - 4.0).abs() < 1e-15);
    }

    #[test]
    fn test_to_row_major() {
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 3);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(0, 2, 3.0);
        m.set(1, 0, 4.0);
        m.set(1, 1, 5.0);
        m.set(1, 2, 6.0);

        let data = m.to_row_major();
        assert_eq!(data, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
    }

    #[test]
    fn test_solve_ill_conditioned() {
        // Near-singular matrix (Hilbert-like)
        let mut m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 0.5);
        m.set(1, 0, 0.5);
        m.set(1, 1, 0.333333333333);

        let b = vec![1.5, 0.833333333333];
        let result = m.solve(&b);
        // Should still produce a result (may be less accurate)
        assert!(result.is_ok());
    }

    // ============================================================================
    // f32 Scalar Tests
    // ============================================================================

    #[test]
    fn test_f32_solve() {
        let mut m: DenseMatrix<f32> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 2.0);
        m.set(0, 1, 0.0);
        m.set(1, 0, 0.0);
        m.set(1, 1, 3.0);

        let b = vec![4.0f32, 9.0f32];
        let x = m.solve(&b).unwrap();

        assert!((x[0] - 2.0).abs() < 1e-5);
        assert!((x[1] - 3.0).abs() < 1e-5);
    }

    #[test]
    fn test_f32_identity() {
        let m: DenseMatrix<f32> = DenseMatrix::identity(3);
        for i in 0..3 {
            for j in 0..3 {
                let expected = if i == j { 1.0f32 } else { 0.0f32 };
                assert!((m.get(i, j) - expected).abs() < 1e-7);
            }
        }
    }

    #[test]
    fn test_f32_mul_vec() {
        let mut m: DenseMatrix<f32> = DenseMatrix::zeros(2, 2);
        m.set(0, 0, 1.0);
        m.set(0, 1, 2.0);
        m.set(1, 0, 3.0);
        m.set(1, 1, 4.0);

        let x = [1.0f32, 2.0f32];
        let mut y = [0.0f32, 0.0f32];
        m.mul_vec(&x, &mut y);

        assert!((y[0] - 5.0).abs() < 1e-5);
        assert!((y[1] - 11.0).abs() < 1e-5);
    }

    // ============================================================================
    // Error Type Tests
    // ============================================================================

    #[test]
    fn test_solve_non_square_returns_not_square_error() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 3);
        let b = vec![1.0, 2.0];
        match m.solve(&b) {
            Err(LinalgError::NotSquare { nrows: 2, ncols: 3 }) => {}
            other => panic!("Expected NotSquare error, got {:?}", other),
        }
    }

    #[test]
    fn test_solve_dimension_mismatch_returns_typed_error() {
        let m: DenseMatrix<f64> = DenseMatrix::zeros(2, 2);
        let b = vec![1.0, 2.0, 3.0];
        match m.solve(&b) {
            Err(LinalgError::DimensionMismatch { .. }) => {}
            other => panic!("Expected DimensionMismatch error, got {:?}", other),
        }
    }
}