Skip to main content

section_properties/fea/solver/impls/
sparse_lu.rs

1//! Sparse LU solver wrapper
2use crate::fea::SparseMatrix;
3use crate::fea::solver::{LinearSolver, SolverCapabilities, SolverError};
4use crate::fea::solvers::SparseLu;
5
6/// Sparse LU solver wrapper
7pub struct SparseLuSolver {
8    lu: Option<SparseLu>,
9    n: usize,
10    scale: f64,
11}
12
13impl SparseLuSolver {
14    pub fn new() -> Self {
15        Self {
16            lu: None,
17            n: 0,
18            scale: 1.0,
19        }
20    }
21}
22
23impl LinearSolver for SparseLuSolver {
24    fn name(&self) -> &'static str {
25        "sparse_lu"
26    }
27
28    fn capabilities(&self) -> SolverCapabilities {
29        SolverCapabilities::sparse_lu()
30    }
31
32    fn factor(&mut self, matrix: &SparseMatrix) -> Result<(), SolverError> {
33        // Invalidate any previous factorization first, so a failed factor()
34        // cannot leave stale factors usable by a later solve().
35        self.lu = None;
36        self.n = 0;
37
38        let n = matrix.n;
39        if n == 0 {
40            return Err(SolverError::invalid_input("Empty matrix"));
41        }
42
43        let lu = SparseLu::factor(matrix).map_err(|e| SolverError::factorization_failed(e))?;
44
45        // Compute scale
46        let mut scale = 0.0f64;
47        for &val in &matrix.csr_vals {
48            scale = scale.max(val.abs());
49        }
50        self.scale = scale.max(1.0);
51
52        self.lu = Some(lu);
53        self.n = n;
54
55        Ok(())
56    }
57
58    fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError> {
59        let lu = self
60            .lu
61            .as_ref()
62            .ok_or_else(|| SolverError::not_factorized())?;
63
64        let n = self.n;
65        if rhs.len() != n {
66            return Err(SolverError::dimension_mismatch(n, rhs.len()));
67        }
68
69        // Check for NaN/Inf
70        for (i, &val) in rhs.iter().enumerate() {
71            if !val.is_finite() {
72                return Err(SolverError::non_finite(i));
73            }
74        }
75
76        lu.solve(rhs).map_err(|e| SolverError::solve_failed(e))
77    }
78}