tpt-sci-grid 0.1.0

Structured finite-difference grids/stencils for the tpt-science pillar
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
//! Feature-gated sparse-matrix backend for large PDE grids.
//!
//! Enabled by the `sparse` cargo feature. Provides a minimal
//! [compressed-sparse-row](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_(CSR,_CRS_or_Yale_format))
//! (`CsrMatrix`) alongside sparse Laplacian assemblers. This is additive: the
//! dense operators in [`crate::operator`] remain the default; the CSR variants
//! here let callers work with realistically-sized 1-D/2-D grids without the
//! O(n²) memory cost of a dense [`DMatrix`](tpt_math_linalg::tpt_math_linalg_dense::DMatrix).

use crate::grid::{Boundary, UniformGrid1D, UniformGrid2D, UniformGrid3D};
use crate::operator::laplacian_3d_rows;

/// A real, compressed-sparse-row (CSR) matrix.
///
/// `row_ptr` has length `nrows + 1`; the entries for row `i` are stored in
/// `col_ind[row_ptr[i]..row_ptr[i+1]]` with matching values in `values`.
#[derive(Debug, Clone)]
pub struct CsrMatrix {
    nrows: usize,
    ncols: usize,
    /// `row_ptr[i]` is the start offset of row `i` in the column/value arrays;
    /// `row_ptr[nrows]` is the total number of stored entries.
    pub row_ptr: Vec<usize>,
    /// Column indices, parallel to `values`.
    pub col_ind: Vec<usize>,
    /// Stored values, parallel to `col_ind`.
    pub values: Vec<f64>,
}

impl CsrMatrix {
    /// Number of rows.
    #[must_use]
    pub fn nrows(&self) -> usize {
        self.nrows
    }

    /// Number of columns.
    #[must_use]
    pub fn ncols(&self) -> usize {
        self.ncols
    }

    /// Build a CSR matrix from a dense [`DMatrix`](tpt_math_linalg::tpt_math_linalg_dense::DMatrix),
    /// dropping (near-)zero entries to keep it sparse.
    #[must_use]
    pub fn from_dense(m: &tpt_math_linalg::tpt_math_linalg_dense::DMatrix<f64>) -> Self {
        let nrows = m.nrows();
        let ncols = m.ncols();
        let mut row_ptr = Vec::with_capacity(nrows + 1);
        let mut col_ind = Vec::new();
        let mut values = Vec::new();
        let mut offset = 0;
        row_ptr.push(0);
        for i in 0..nrows {
            for j in 0..ncols {
                let v = m[(i, j)];
                if v != 0.0 {
                    col_ind.push(j);
                    values.push(v);
                    offset += 1;
                }
            }
            row_ptr.push(offset);
        }
        Self {
            nrows,
            ncols,
            row_ptr,
            col_ind,
            values,
        }
    }

    /// Build a CSR matrix from a list of `(column, value)` rows, one per matrix
    /// row. Duplicate column entries within a row are summed. Entries with a
    /// zero value are still stored (callers that need compression should drop
    /// them beforehand); this is intended for assembling PDE operators where
    /// boundary clamping can collapse distinct stencil offsets onto the same
    /// column.
    #[must_use]
    pub fn from_rows(nrows: usize, ncols: usize, rows: &[Vec<(usize, f64)>]) -> Self {
        pack_csr(nrows, ncols, rows)
    }

    /// Sparse matrix–vector product `y = A·x`.
    ///
    /// # Panics
    ///
    /// Panics if `x.len() != self.ncols()` (the dense `DMatrix` mat-vec would
    /// likewise panic on a dimension mismatch).
    #[must_use]
    pub fn mul_vec(&self, x: &[f64]) -> Vec<f64> {
        assert_eq!(x.len(), self.ncols(), "vector length must match ncols");
        let mut y = vec![0.0; self.nrows];
        for (i, slot) in y.iter_mut().enumerate() {
            let start = self.row_ptr[i];
            let end = self.row_ptr[i + 1];
            let mut acc = 0.0;
            for k in start..end {
                acc += self.values[k] * x[self.col_ind[k]];
            }
            *slot = acc;
        }
        y
    }
}

/// Assemble the discrete 1-D Laplacian as a [`CsrMatrix`] (mirrors
/// [`crate::laplacian_1d`]). See that function for the boundary-condition
/// treatment.
#[must_use]
pub fn laplacian_1d_sparse(grid: &UniformGrid1D, bc: Boundary) -> CsrMatrix {
    let n = grid.n();
    let dx2 = grid.dx() * grid.dx();
    let is_boundary = |k: usize| k == 0 || k == n - 1;

    // Collect the (col, value) entries per row first, then pack into CSR.
    let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
    for (i, row) in rows.iter_mut().enumerate() {
        if bc == Boundary::Dirichlet && is_boundary(i) {
            row.push((i, 1.0));
            continue;
        }
        if bc == Boundary::Neumann && i == 0 {
            row.push((0, -2.0 / dx2));
            row.push((1, 2.0 / dx2));
            continue;
        }
        if bc == Boundary::Neumann && i == n - 1 {
            row.push((n - 1, -2.0 / dx2));
            row.push((n - 2, 2.0 / dx2));
            continue;
        }
        if i > 0 {
            let left = i - 1;
            if !(bc == Boundary::Dirichlet && is_boundary(left)) {
                row.push((left, 1.0 / dx2));
            }
        }
        row.push((i, -2.0 / dx2));
        if i + 1 < n {
            let right = i + 1;
            if !(bc == Boundary::Dirichlet && is_boundary(right)) {
                row.push((right, 1.0 / dx2));
            }
        }
    }

    pack_csr(n, n, &rows)
}

/// Assemble the discrete 2-D Laplacian (`d²/dx² + d²/dy²`) on a tensor-product
/// grid as a [`CsrMatrix`], using node ordering `index = ix + iy * nx` and the
/// standard 5-point stencil. Mirrors [`crate::laplacian_2d`] but without forming
/// a dense `n² × n²` matrix.
#[must_use]
pub fn laplacian_2d_sparse(grid: &UniformGrid2D, bc: Boundary) -> CsrMatrix {
    let nx = grid.nx();
    let ny = grid.ny();
    let n = nx * ny;
    let dx2 = grid.dx() * grid.dx();
    let dy2 = grid.dy() * grid.dy();
    let idx = |ix: usize, iy: usize| ix + iy * nx;

    let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
    for iy in 0..ny {
        for ix in 0..nx {
            let i = idx(ix, iy);
            let on_boundary = ix == 0 || ix == nx - 1 || iy == 0 || iy == ny - 1;
            if bc == Boundary::Dirichlet && on_boundary {
                rows[i].push((i, 1.0));
                continue;
            }
            // x-direction neighbours (Neumann clamps off-boundary to the node).
            let xm = if ix > 0 { ix - 1 } else { ix };
            let xp = if ix + 1 < nx { ix + 1 } else { ix };
            if bc == Boundary::Neumann || ix > 0 {
                rows[i].push((idx(xm, iy), 1.0 / dx2));
            }
            rows[i].push((i, -2.0 / dx2));
            if bc == Boundary::Neumann || ix + 1 < nx {
                rows[i].push((idx(xp, iy), 1.0 / dx2));
            }
            // y-direction neighbours.
            let ym = if iy > 0 { iy - 1 } else { iy };
            let yp = if iy + 1 < ny { iy + 1 } else { iy };
            if bc == Boundary::Neumann || iy > 0 {
                rows[i].push((idx(ix, ym), 1.0 / dy2));
            }
            rows[i].push((i, -2.0 / dy2));
            if bc == Boundary::Neumann || iy + 1 < ny {
                rows[i].push((idx(ix, yp), 1.0 / dy2));
            }
        }
    }

    pack_csr(n, n, &rows)
}

/// Assemble the discrete 3-D Laplacian (`d²/dx² + d²/dy² + d²/dz²`) on a
/// tensor-product grid as a [`CsrMatrix`], using node ordering
/// `index = ix + iy·nx + iz·nx·ny` and the standard 7-point stencil. Mirrors
/// [`crate::laplacian_3d`] (it shares the same row assembly) but without forming
/// a dense `n³ × n³` matrix.
#[must_use]
pub fn laplacian_3d_sparse(grid: &UniformGrid3D, bc: Boundary) -> CsrMatrix {
    let rows = laplacian_3d_rows(grid, bc);
    let n = grid.len();
    pack_csr(n, n, &rows)
}

/// One explicit-Euler diffusion step `u_next = u + dt · D · (L · u)` for a field
/// `u` on a grid with diffusion coefficient `D` and Laplacian `L`.
///
/// The Laplacian is applied via the sparse mat-vec [`CsrMatrix::mul_vec`], so the
/// cost scales with the number of non-zeros rather than `n²`.
#[must_use]
pub fn diffuse_step(u: &[f64], laplacian: &CsrMatrix, dt: f64, diffusion: f64) -> Vec<f64> {
    let lap = laplacian.mul_vec(u);
    u.iter()
        .zip(&lap)
        .map(|(u_i, lap_i)| u_i + dt * diffusion * lap_i)
        .collect()
}

/// Solve `A·x = b` for a symmetric positive-definite [`CsrMatrix`] `A` with the
/// conjugate gradient (CG) method.
///
/// `x0` is an optional initial guess (zeros are used when `None`). Iteration
/// stops once the Euclidean residual norm drops below `tol · ‖b‖` (or below
/// `tol` when `b` is zero) or after `max_iter` iterations. The discrete
/// Laplacian assemblers ([`laplacian_1d_sparse`] etc.) produce SPD systems
/// under Dirichlet/Neumann boundaries, so this is the natural solver for the
/// Poisson/elliptic problems that arise in pressure-correction and
/// extracellular-potential solves.
#[must_use]
pub fn conjugate_gradient(
    a: &CsrMatrix,
    b: &[f64],
    x0: Option<&[f64]>,
    tol: f64,
    max_iter: usize,
) -> Vec<f64> {
    let n = a.nrows();
    let mut x = match x0 {
        Some(v) => v.to_vec(),
        None => vec![0.0; n],
    };
    let mut r = {
        let ax = a.mul_vec(&x);
        b.iter()
            .zip(&ax)
            .map(|(bi, axi)| bi - axi)
            .collect::<Vec<f64>>()
    };
    let mut p = r.clone();
    let mut rsold = r.iter().zip(&r).map(|(a, b)| a * b).sum::<f64>();
    let bnrm = b.iter().map(|v| v * v).sum::<f64>().sqrt();
    let threshold = if bnrm > 0.0 { tol * bnrm } else { tol };
    let rnorm = rsold.sqrt();
    if rnorm < threshold {
        return x;
    }
    for _ in 0..max_iter {
        let ap = a.mul_vec(&p);
        let p_ap = p.iter().zip(&ap).map(|(a, b)| a * b).sum::<f64>();
        let alpha = rsold / p_ap;
        for i in 0..n {
            x[i] += alpha * p[i];
        }
        for (ri, api) in r.iter_mut().zip(&ap) {
            *ri -= alpha * api;
        }
        let rsnew = r.iter().zip(&r).map(|(a, b)| a * b).sum::<f64>();
        if rsnew.sqrt() < threshold {
            return x;
        }
        let beta = rsnew / rsold;
        for (pi, ri) in p.iter_mut().zip(&r) {
            *pi = *ri + beta * *pi;
        }
        rsold = rsnew;
    }
    x
}

/// Pack per-row `(col, value)` lists into CSR storage.
///
/// Duplicate column entries within a row (e.g. the separate per-axis diagonal
/// contributions of a 3-D Laplacian) are merged by summing their values, so the
/// resulting matrix has at most one entry per `(row, column)` pair.
fn pack_csr(nrows: usize, ncols: usize, rows: &[Vec<(usize, f64)>]) -> CsrMatrix {
    let mut row_ptr = Vec::with_capacity(nrows + 1);
    let mut col_ind = Vec::new();
    let mut values = Vec::new();
    let mut offset = 0;
    row_ptr.push(0);
    for r in rows {
        // Sort by column, then coalesce equal columns.
        let mut entries = r.clone();
        entries.sort_by_key(|&(c, _)| c);
        let mut i = 0;
        while i < entries.len() {
            let (c, mut v) = entries[i];
            let mut j = i + 1;
            while j < entries.len() && entries[j].0 == c {
                v += entries[j].1;
                j += 1;
            }
            col_ind.push(c);
            values.push(v);
            offset += 1;
            i = j;
        }
        row_ptr.push(offset);
    }
    CsrMatrix {
        nrows,
        ncols,
        row_ptr,
        col_ind,
        values,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use tpt_math_linalg::tpt_math_linalg_dense::DVector;

    #[test]
    fn sparse_1d_matches_dense_laplacian() {
        let g = UniformGrid1D::new(21, 0.0, 1.0).unwrap();
        let sparse = laplacian_1d_sparse(&g, Boundary::Dirichlet);
        let dense = crate::laplacian_1d(&g, Boundary::Dirichlet);
        for i in 0..g.n() {
            let start = sparse.row_ptr[i];
            let end = sparse.row_ptr[i + 1];
            for k in start..end {
                assert_abs_diff_eq!(
                    sparse.values[k],
                    dense[(i, sparse.col_ind[k])],
                    epsilon = 1e-12
                );
            }
        }
    }

    #[test]
    fn sparse_mul_vec_matches_dense() {
        let g = UniformGrid1D::new(11, 0.0, 1.0).unwrap();
        let sparse = laplacian_1d_sparse(&g, Boundary::Dirichlet);
        let dense = crate::laplacian_1d(&g, Boundary::Dirichlet);
        let u: Vec<f64> = (0..g.n()).map(|i| i as f64 * 0.1).collect();
        let y_sparse = sparse.mul_vec(&u);
        let y_dense = dense * DVector::from_vec(u);
        for i in 0..g.n() {
            assert_abs_diff_eq!(y_sparse[i], y_dense[i], epsilon = 1e-12);
        }
    }

    #[test]
    fn sparse_2d_laplacian_of_quadratic() {
        // u = (x(1-x) + y(1-y))/4  ->  ∇²u = -1  ->  L·u ≈ -1 on the interior.
        let g = UniformGrid2D::new(41, 0.0, 1.0, 41, 0.0, 1.0).unwrap();
        let l = laplacian_2d_sparse(&g, Boundary::Dirichlet);
        let xs = g.x_coordinates();
        let ys = g.y_coordinates();
        let u: Vec<f64> = (0..g.len())
            .map(|k| {
                let ix = k % g.nx();
                let iy = k / g.nx();
                (xs[ix] * (1.0 - xs[ix]) + ys[iy] * (1.0 - ys[iy])) / 4.0
            })
            .collect();
        let lu = l.mul_vec(&u);
        let mid = g.len() / 2;
        assert_abs_diff_eq!(lu[mid], -1.0, epsilon = 2e-2);
    }

    #[test]
    fn diffuse_step_reduces_gradient() {
        let g = UniformGrid1D::new(51, 0.0, 1.0).unwrap();
        let l = laplacian_1d_sparse(&g, Boundary::Dirichlet);
        // A parabola pinned to zero at the boundaries: diffusion flattens it.
        let u: Vec<f64> = g.coordinates().iter().map(|&x| x * (1.0 - x)).collect();
        let u1 = diffuse_step(&u, &l, 0.0005, 1.0);
        let grad0: f64 = u.windows(2).map(|w| (w[1] - w[0]).abs()).sum();
        let grad1: f64 = u1.windows(2).map(|w| (w[1] - w[0]).abs()).sum();
        assert!(grad1 < grad0, "diffusion should smooth the parabola");
    }

    #[test]
    fn sparse_3d_matches_dense_laplacian() {
        let g = UniformGrid3D::new(9, 0.0, 1.0, 9, 0.0, 1.0, 9, 0.0, 1.0).unwrap();
        let sparse = laplacian_3d_sparse(&g, Boundary::Dirichlet);
        let dense = crate::laplacian_3d(&g, Boundary::Dirichlet);
        assert_eq!(sparse.nrows(), dense.nrows());
        assert_eq!(sparse.ncols(), dense.ncols());
        for i in 0..sparse.nrows() {
            let start = sparse.row_ptr[i];
            let end = sparse.row_ptr[i + 1];
            for k in start..end {
                assert_abs_diff_eq!(
                    sparse.values[k],
                    dense[(i, sparse.col_ind[k])],
                    epsilon = 1e-12
                );
            }
        }
    }

    #[test]
    fn sparse_3d_laplacian_of_quadratic() {
        // u = (x(1-x) + y(1-y) + z(1-z))/6  ->  ∇²u = -1.
        let g = UniformGrid3D::new(15, 0.0, 1.0, 15, 0.0, 1.0, 15, 0.0, 1.0).unwrap();
        let l = laplacian_3d_sparse(&g, Boundary::Dirichlet);
        let xs = g.x_coordinates();
        let ys = g.y_coordinates();
        let zs = g.z_coordinates();
        let u: Vec<f64> = (0..g.len())
            .map(|k| {
                let ix = k % g.nx();
                let iy = (k / g.nx()) % g.ny();
                let iz = k / (g.nx() * g.ny());
                (xs[ix] * (1.0 - xs[ix]) + ys[iy] * (1.0 - ys[iy]) + zs[iz] * (1.0 - zs[iz])) / 6.0
            })
            .collect();
        let lu = l.mul_vec(&u);
        let mid = g.len() / 2;
        assert_abs_diff_eq!(lu[mid], -1.0, epsilon = 5e-2);
    }

    #[test]
    fn conjugate_gradient_solves_poisson() {
        // u = sin(pi x) on [0,1] (Dirichlet) -> ∇²u = -π²·u, so A·u = f with
        // f = -π²·u. CG must recover u to high accuracy.
        let g = UniformGrid1D::new(81, 0.0, 1.0).unwrap();
        let a = laplacian_1d_sparse(&g, Boundary::Dirichlet);
        let xs = g.coordinates();
        let u: Vec<f64> = xs
            .iter()
            .map(|&x| (std::f64::consts::PI * x).sin())
            .collect();
        let f: Vec<f64> = a.mul_vec(&u);
        let x = conjugate_gradient(&a, &f, None, 1e-12, 1000);
        for i in 1..g.n() - 1 {
            assert_abs_diff_eq!(x[i], u[i], epsilon = 1e-6);
        }
    }
}