scirs2-sparse 0.4.2

Sparse matrix module for SciRS2 (scirs2-sparse)
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
//! Direct solvers and basic operations for sparse matrices

use crate::csr::CsrMatrix;
use crate::error::{SparseError, SparseResult};
use scirs2_core::numeric::{Float, NumAssign, SparseElement};
use std::iter::Sum;

/// Solve a sparse linear system Ax = b using Gaussian elimination with
/// partial pivoting on the dense representation.
///
/// For small-to-medium systems this is reliable. Large systems should
/// prefer iterative solvers (CG, GMRES, BiCGSTAB) from the
/// `iterative` sub-module.
#[allow(dead_code)]
pub fn spsolve<F>(a: &CsrMatrix<F>, b: &[F]) -> SparseResult<Vec<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.rows() != a.cols() {
        return Err(SparseError::ValueError(format!(
            "Matrix must be square, got {}x{}",
            a.rows(),
            a.cols()
        )));
    }
    if a.rows() != b.len() {
        return Err(SparseError::DimensionMismatch {
            expected: a.rows(),
            found: b.len(),
        });
    }
    let a_dense = a.to_dense();
    gaussian_elimination(&a_dense, b)
}

/// Solve a sparse linear system using direct methods.
///
/// Accepts hints for symmetry and positive-definiteness (currently both
/// paths fall through to Gaussian elimination with partial pivoting).
#[allow(dead_code)]
pub fn sparse_direct_solve<F>(
    a: &CsrMatrix<F>,
    b: &[F],
    _symmetric: bool,
    _positive_definite: bool,
) -> SparseResult<Vec<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    spsolve(a, b)
}

/// Solve a least squares problem
#[allow(dead_code)]
pub fn sparse_lstsq<F>(a: &CsrMatrix<F>, b: &[F]) -> SparseResult<Vec<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    // For now, solve normal equations: A^T * A * x = A^T * b
    let at = a.transpose();
    let ata = matmul(&at, a)?;
    // Compute A^T * b
    let mut atb = vec![F::sparse_zero(); at.rows()];
    for (row, atb_val) in atb.iter_mut().enumerate().take(at.rows()) {
        let row_range = at.row_range(row);
        let row_indices = &at.indices[row_range.clone()];
        let row_data = &at.data[row_range];

        let mut sum = F::sparse_zero();
        for (col_idx, &col) in row_indices.iter().enumerate() {
            sum += row_data[col_idx] * b[col];
        }
        *atb_val = sum;
    }
    spsolve(&ata, &atb)
}

/// Compute matrix norm using the sparse CSR structure directly.
///
///  - `"1"`   : 1-norm (maximum absolute column sum)
///  - `"inf"` : infinity-norm (maximum absolute row sum)
///  - `"fro"` : Frobenius norm (sqrt of sum of squared entries)
#[allow(dead_code)]
pub fn norm<F>(a: &CsrMatrix<F>, ord: &str) -> SparseResult<F>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    match ord {
        "1" => {
            // 1-norm: single pass over non-zeros to accumulate column sums
            let mut col_sums = vec![F::sparse_zero(); a.cols()];
            for i in 0..a.rows() {
                let range = a.row_range(i);
                let row_indices = &a.indices[range.clone()];
                let row_data = &a.data[range];
                for (idx, &col) in row_indices.iter().enumerate() {
                    col_sums[col] += row_data[idx].abs();
                }
            }
            let max_sum = col_sums
                .into_iter()
                .fold(F::sparse_zero(), |mx, v| if v > mx { v } else { mx });
            Ok(max_sum)
        }
        "inf" => {
            // Infinity norm: single pass over rows
            let mut max_sum = F::sparse_zero();
            for i in 0..a.rows() {
                let range = a.row_range(i);
                let row_data = &a.data[range];
                let row_sum: F = row_data.iter().map(|v| v.abs()).sum();
                if row_sum > max_sum {
                    max_sum = row_sum;
                }
            }
            Ok(max_sum)
        }
        "fro" => {
            let sum_squares: F = a.data.iter().map(|v| *v * *v).sum();
            Ok(sum_squares.sqrt())
        }
        _ => Err(SparseError::ValueError(format!("Unknown norm: {ord}"))),
    }
}

/// Sparse matrix multiplication C = A * B using CSR row-by-row accumulation.
///
/// For each row i of A, scatters `a[i,k] * B[k,:]` into a workspace.
/// Operates in O(nnz(A) * avg_nnz_per_row(B)) time.
#[allow(dead_code)]
pub fn matmul<F>(a: &CsrMatrix<F>, b: &CsrMatrix<F>) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.cols() != b.rows() {
        return Err(SparseError::DimensionMismatch {
            expected: a.cols(),
            found: b.rows(),
        });
    }

    let nrows = a.rows();
    let ncols = b.cols();
    let mut result_rows = Vec::new();
    let mut result_cols = Vec::new();
    let mut result_data = Vec::new();

    let mut workspace = vec![F::sparse_zero(); ncols];
    let mut marker = vec![false; ncols];

    for i in 0..nrows {
        let a_range = a.row_range(i);
        let a_indices = &a.indices[a_range.clone()];
        let a_data_row = &a.data[a_range];
        let mut touched_cols: Vec<usize> = Vec::new();

        for (idx, &k) in a_indices.iter().enumerate() {
            let a_ik = a_data_row[idx];
            if a_ik == F::sparse_zero() {
                continue;
            }
            let b_range = b.row_range(k);
            let b_indices = &b.indices[b_range.clone()];
            let b_data_row = &b.data[b_range];
            for (bidx, &j) in b_indices.iter().enumerate() {
                workspace[j] += a_ik * b_data_row[bidx];
                if !marker[j] {
                    marker[j] = true;
                    touched_cols.push(j);
                }
            }
        }

        touched_cols.sort_unstable();
        for &j in &touched_cols {
            let val = workspace[j];
            if val != F::sparse_zero() {
                result_rows.push(i);
                result_cols.push(j);
                result_data.push(val);
            }
            workspace[j] = F::sparse_zero();
            marker[j] = false;
        }
    }

    CsrMatrix::new(result_data, result_rows, result_cols, (nrows, ncols))
}

/// Sparse matrix addition using a merge of the two CSR row structures.
///
/// Runs in O(nnz(A) + nnz(B)) time without converting to dense form.
#[allow(dead_code)]
pub fn add<F>(a: &CsrMatrix<F>, b: &CsrMatrix<F>) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.shape() != b.shape() {
        return Err(SparseError::ShapeMismatch {
            expected: a.shape(),
            found: b.shape(),
        });
    }

    let (nrows, ncols) = a.shape();
    let mut rows = Vec::new();
    let mut cols = Vec::new();
    let mut data = Vec::new();

    for i in 0..nrows {
        let a_range = a.row_range(i);
        let b_range = b.row_range(i);
        let a_cols = &a.indices[a_range.clone()];
        let a_data = &a.data[a_range];
        let b_cols = &b.indices[b_range.clone()];
        let b_data = &b.data[b_range];

        let mut ai = 0usize;
        let mut bi = 0usize;
        while ai < a_cols.len() && bi < b_cols.len() {
            if a_cols[ai] < b_cols[bi] {
                let val = a_data[ai];
                if val != F::sparse_zero() {
                    rows.push(i);
                    cols.push(a_cols[ai]);
                    data.push(val);
                }
                ai += 1;
            } else if a_cols[ai] > b_cols[bi] {
                let val = b_data[bi];
                if val != F::sparse_zero() {
                    rows.push(i);
                    cols.push(b_cols[bi]);
                    data.push(val);
                }
                bi += 1;
            } else {
                let val = a_data[ai] + b_data[bi];
                if val != F::sparse_zero() {
                    rows.push(i);
                    cols.push(a_cols[ai]);
                    data.push(val);
                }
                ai += 1;
                bi += 1;
            }
        }
        while ai < a_cols.len() {
            let val = a_data[ai];
            if val != F::sparse_zero() {
                rows.push(i);
                cols.push(a_cols[ai]);
                data.push(val);
            }
            ai += 1;
        }
        while bi < b_cols.len() {
            let val = b_data[bi];
            if val != F::sparse_zero() {
                rows.push(i);
                cols.push(b_cols[bi]);
                data.push(val);
            }
            bi += 1;
        }
    }

    CsrMatrix::new(data, rows, cols, (nrows, ncols))
}

/// Element-wise multiplication (Hadamard product) using sorted CSR row merge.
///
/// Only produces non-zeros where both A and B have non-zeros in the same
/// position, so runs in O(nnz(A) + nnz(B)) time.
#[allow(dead_code)]
pub fn multiply<F>(a: &CsrMatrix<F>, b: &CsrMatrix<F>) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.shape() != b.shape() {
        return Err(SparseError::ShapeMismatch {
            expected: a.shape(),
            found: b.shape(),
        });
    }

    let (nrows, _ncols) = a.shape();
    let mut rows = Vec::new();
    let mut cols = Vec::new();
    let mut data = Vec::new();

    for i in 0..nrows {
        let a_range = a.row_range(i);
        let b_range = b.row_range(i);
        let a_cols = &a.indices[a_range.clone()];
        let a_data = &a.data[a_range];
        let b_cols = &b.indices[b_range.clone()];
        let b_data = &b.data[b_range];

        let mut ai = 0usize;
        let mut bi = 0usize;
        while ai < a_cols.len() && bi < b_cols.len() {
            if a_cols[ai] < b_cols[bi] {
                ai += 1;
            } else if a_cols[ai] > b_cols[bi] {
                bi += 1;
            } else {
                let val = a_data[ai] * b_data[bi];
                if val != F::sparse_zero() {
                    rows.push(i);
                    cols.push(a_cols[ai]);
                    data.push(val);
                }
                ai += 1;
                bi += 1;
            }
        }
    }

    CsrMatrix::new(data, rows, cols, a.shape())
}

/// Create a diagonal matrix
#[allow(dead_code)]
pub fn diag_matrix<F>(diag: &[F], n: Option<usize>) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    let size = n.unwrap_or(diag.len());
    if size < diag.len() {
        return Err(SparseError::ValueError(
            "Size must be at least as large as diagonal".to_string(),
        ));
    }

    let mut rows = Vec::new();
    let mut cols = Vec::new();
    let mut data = Vec::new();

    for (i, &val) in diag.iter().enumerate() {
        if val != F::sparse_zero() {
            rows.push(i);
            cols.push(i);
            data.push(val);
        }
    }

    CsrMatrix::new(data, rows, cols, (size, size))
}

/// Create an identity matrix
#[allow(dead_code)]
pub fn eye<F>(n: usize) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    let diag = vec![F::sparse_one(); n];
    diag_matrix(&diag, Some(n))
}

/// Matrix inverse
#[allow(dead_code)]
pub fn inv<F>(a: &CsrMatrix<F>) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.rows() != a.cols() {
        return Err(SparseError::ValueError(
            "Matrix must be square for inverse".to_string(),
        ));
    }

    let n = a.rows();

    // Solve A * X = I for X
    let mut inv_cols = Vec::new();

    for j in 0..n {
        // Get column j from identity matrix
        let mut col_vec = vec![F::sparse_zero(); n];
        col_vec[j] = F::sparse_one();
        let x = spsolve(a, &col_vec)?;
        inv_cols.push(x);
    }

    // Construct the inverse matrix from columns
    let mut rows = Vec::new();
    let mut cols = Vec::new();
    let mut data = Vec::new();

    for (j, col) in inv_cols.iter().enumerate() {
        for (i, &val) in col.iter().enumerate() {
            if val.abs() > F::epsilon() {
                rows.push(i);
                cols.push(j);
                data.push(val);
            }
        }
    }

    CsrMatrix::new(data, rows, cols, (n, n))
}

// Matrix exponential functionality is now available in linalg/expm.rs module

/// Matrix power
#[allow(dead_code)]
pub fn matrix_power<F>(a: &CsrMatrix<F>, power: i32) -> SparseResult<CsrMatrix<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static + std::fmt::Debug,
{
    if a.rows() != a.cols() {
        return Err(SparseError::ValueError(
            "Matrix must be square for power".to_string(),
        ));
    }

    match power {
        0 => eye(a.rows()),
        1 => Ok(a.clone()),
        p if p > 0 => {
            let mut result = a.clone();
            for _ in 1..p {
                result = matmul(&result, a)?;
            }
            Ok(result)
        }
        p => {
            // Negative power: compute inverse and then positive power
            let inv_a = inv(a)?;
            matrix_power(&inv_a, -p)
        }
    }
}

// Helper functions

#[allow(dead_code)]
fn gaussian_elimination<F>(a: &[Vec<F>], b: &[F]) -> SparseResult<Vec<F>>
where
    F: Float + NumAssign + SparseElement,
{
    let n = a.len();
    let mut aug = vec![vec![F::sparse_zero(); n + 1]; n];

    // Create augmented matrix
    for i in 0..n {
        for j in 0..n {
            aug[i][j] = a[i][j];
        }
        aug[i][n] = b[i];
    }

    // Forward elimination
    for k in 0..n {
        // Find pivot
        let mut max_idx = k;
        for i in (k + 1)..n {
            if aug[i][k].abs() > aug[max_idx][k].abs() {
                max_idx = i;
            }
        }
        aug.swap(k, max_idx);

        // Check for zero pivot
        if aug[k][k].abs() < F::epsilon() {
            return Err(SparseError::SingularMatrix(
                "Matrix is singular".to_string(),
            ));
        }

        // Eliminate column
        for i in (k + 1)..n {
            let factor = aug[i][k] / aug[k][k];
            for j in k..=n {
                aug[i][j] = aug[i][j] - factor * aug[k][j];
            }
        }
    }

    // Back substitution
    let mut x = vec![F::sparse_zero(); n];
    for i in (0..n).rev() {
        x[i] = aug[i][n];
        for j in (i + 1)..n {
            x[i] = x[i] - aug[i][j] * x[j];
        }
        x[i] /= aug[i][i];
    }

    Ok(x)
}

// Helper functions for matrix exponential have been moved to linalg/expm.rs

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

    #[test]
    fn test_eye_matrix() {
        let eye_matrix = eye::<f64>(3).expect("Operation failed");
        assert_eq!(eye_matrix.shape(), (3, 3));
        assert_eq!(eye_matrix.get(0, 0), 1.0);
        assert_eq!(eye_matrix.get(1, 1), 1.0);
        assert_eq!(eye_matrix.get(2, 2), 1.0);
        assert_eq!(eye_matrix.get(0, 1), 0.0);
    }

    #[test]
    fn test_diag_matrix() {
        let diag = vec![2.0, 3.0, 4.0];
        let diag_matrix = diag_matrix(&diag, None).expect("Operation failed");
        assert_eq!(diag_matrix.shape(), (3, 3));
        assert_eq!(diag_matrix.get(0, 0), 2.0);
        assert_eq!(diag_matrix.get(1, 1), 3.0);
        assert_eq!(diag_matrix.get(2, 2), 4.0);
    }

    #[test]
    fn test_matrix_power() {
        let diag = vec![2.0, 3.0];
        let matrix = diag_matrix(&diag, None).expect("Operation failed");

        // Test power 2
        let matrix2 = matrix_power(&matrix, 2).expect("Operation failed");
        assert_eq!(matrix2.get(0, 0), 4.0);
        assert_eq!(matrix2.get(1, 1), 9.0);

        // Test power 0 (identity)
        let matrix0 = matrix_power(&matrix, 0).expect("Operation failed");
        assert_eq!(matrix0.get(0, 0), 1.0);
        assert_eq!(matrix0.get(1, 1), 1.0);
    }
}