Skip to main content

section_properties/fea/
solver.rs

1//! Unified linear solver abstraction for the FEM framework.
2//!
3//! Provides a common interface for different linear solvers (direct, iterative, external)
4//! enabling a plugin-based architecture for the FEM framework.
5
6use crate::fea::SparseMatrix;
7use crate::fea::solver::impls::cg::CgSolver;
8use crate::fea::solver::impls::dense_gaussian::DenseGaussianSolver;
9use crate::fea::solver::impls::iccg::IccgSolver;
10use crate::fea::solver::impls::skyline_ldlt::SkylineLdltSolver;
11use crate::fea::solver::impls::sparse_lu::SparseLuSolver;
12
13#[cfg(feature = "pardiso")]
14use crate::fea::solver::impls::pardiso_wrapper::PardisoSolverWrapper;
15
16pub mod impls;
17
18/// Capabilities of a linear solver
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub struct SolverCapabilities {
21    /// Supports symmetric matrices
22    pub symmetric: bool,
23    /// Supports symmetric positive definite matrices
24    pub spd: bool,
25    /// Supports indefinite symmetric matrices
26    pub symmetric_indefinite: bool,
27    /// Supports general non-symmetric matrices
28    pub general: bool,
29    /// Supports multiple right-hand sides efficiently
30    pub multiple_rhs: bool,
31    /// Supports complex numbers
32    pub complex: bool,
33    /// Maximum problem size (None = unlimited)
34    pub max_size: Option<usize>,
35}
36
37impl SolverCapabilities {
38    /// Capabilities for dense Gaussian elimination
39    pub fn dense() -> Self {
40        Self {
41            symmetric: true,
42            spd: true,
43            symmetric_indefinite: true,
44            general: true,
45            multiple_rhs: true,
46            complex: false,
47            max_size: Some(500),
48        }
49    }
50
51    /// Capabilities for Skyline LDL^T
52    pub fn skyline_ldlt() -> Self {
53        Self {
54            symmetric: true,
55            spd: true,
56            symmetric_indefinite: false,
57            general: false,
58            multiple_rhs: true,
59            complex: false,
60            max_size: Some(10000),
61        }
62    }
63
64    /// Capabilities for SparseLU
65    pub fn sparse_lu() -> Self {
66        Self {
67            symmetric: true,
68            spd: true,
69            symmetric_indefinite: true,
70            general: true,
71            multiple_rhs: true,
72            complex: false,
73            max_size: Some(3000),
74        }
75    }
76
77    /// Capabilities for PARDISO
78    #[cfg(feature = "pardiso")]
79    pub fn pardiso() -> Self {
80        Self {
81            symmetric: true,
82            spd: true,
83            symmetric_indefinite: true,
84            general: true,
85            multiple_rhs: true,
86            complex: false,
87            max_size: None,
88        }
89    }
90
91    /// Capabilities for CG
92    pub fn cg() -> Self {
93        Self {
94            symmetric: true,
95            spd: true,
96            symmetric_indefinite: false,
97            general: false,
98            multiple_rhs: false,
99            complex: false,
100            max_size: None,
101        }
102    }
103
104    /// Capabilities for ICCG
105    pub fn iccg() -> Self {
106        Self {
107            symmetric: true,
108            spd: true,
109            symmetric_indefinite: false,
110            general: false,
111            multiple_rhs: false,
112            complex: false,
113            max_size: None,
114        }
115    }
116}
117
118/// Unified error type for all linear solvers
119#[derive(Debug, Clone, thiserror::Error)]
120pub enum SolverError {
121    #[error("invalid input: {0}")]
122    InvalidInput(String),
123
124    #[error("non-finite input at index {index}")]
125    NonFiniteInput { index: usize },
126
127    #[error("dimension mismatch: expected {expected}, got {actual}")]
128    DimensionMismatch { expected: usize, actual: usize },
129
130    #[error("singular matrix: {0}")]
131    SingularMatrix(String),
132
133    #[error("near-singular matrix: {0}")]
134    NearSingularMatrix(String),
135
136    #[error("factorization failed: {0}")]
137    FactorizationFailed(String),
138
139    #[error("solve failed: {0}")]
140    SolveFailed(String),
141
142    #[error("backend unavailable: {0}")]
143    BackendUnavailable(String),
144
145    #[error("backend error: {0}")]
146    BackendError(String),
147
148    #[error("unsupported operation: {0}")]
149    Unsupported(String),
150
151    #[error("convergence failed: {0}")]
152    ConvergenceFailed(String),
153
154    #[error("not implemented: {0}")]
155    NotImplemented(String),
156
157    #[error("matrix is not symmetric")]
158    NotSymmetric,
159
160    #[error("solver not factorized")]
161    NotFactorized,
162
163    #[error("solver did not converge")]
164    NotConverged,
165}
166
167impl SolverError {
168    pub fn invalid_input(msg: impl Into<String>) -> Self {
169        Self::InvalidInput(msg.into())
170    }
171
172    pub fn non_finite(index: usize) -> Self {
173        Self::NonFiniteInput { index }
174    }
175
176    pub fn dimension_mismatch(expected: usize, actual: usize) -> Self {
177        Self::DimensionMismatch { expected, actual }
178    }
179
180    pub fn singular(msg: impl Into<String>) -> Self {
181        Self::SingularMatrix(msg.into())
182    }
183
184    pub fn near_singular(msg: impl Into<String>) -> Self {
185        Self::NearSingularMatrix(msg.into())
186    }
187
188    pub fn factorization_failed(msg: impl Into<String>) -> Self {
189        Self::FactorizationFailed(msg.into())
190    }
191
192    pub fn solve_failed(msg: impl Into<String>) -> Self {
193        Self::SolveFailed(msg.into())
194    }
195
196    pub fn backend_unavailable(msg: impl Into<String>) -> Self {
197        Self::BackendUnavailable(msg.into())
198    }
199
200    pub fn backend_error(msg: impl Into<String>) -> Self {
201        Self::BackendError(msg.into())
202    }
203
204    pub fn unsupported(msg: impl Into<String>) -> Self {
205        Self::Unsupported(msg.into())
206    }
207
208    pub fn convergence_failed(msg: impl Into<String>) -> Self {
209        Self::ConvergenceFailed(msg.into())
210    }
211
212    pub fn not_implemented(msg: impl Into<String>) -> Self {
213        Self::NotImplemented(msg.into())
214    }
215
216    pub fn not_symmetric() -> Self {
217        Self::NotSymmetric
218    }
219
220    pub fn not_factorized() -> Self {
221        Self::NotFactorized
222    }
223
224    pub fn not_converged() -> Self {
225        Self::NotConverged
226    }
227}
228
229/// Trait for a factored solver that can solve multiple RHS
230pub trait FactoredSolver: Send + Sync {
231    /// Solve for a single RHS
232    fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
233
234    /// Solve for multiple RHS efficiently
235    fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
236        rhs.iter().map(|rhs| self.solve(rhs)).collect()
237    }
238
239    /// Get solver capabilities
240    fn capabilities(&self) -> SolverCapabilities;
241
242    /// Get solver name
243    fn name(&self) -> &'static str;
244}
245
246/// Trait for linear solvers that can factorize and solve
247pub trait LinearSolver: Send + Sync {
248    /// Get solver name
249    fn name(&self) -> &'static str;
250
251    /// Get solver capabilities
252    fn capabilities(&self) -> SolverCapabilities;
253
254    /// Factorize the matrix
255    fn factor(&mut self, matrix: &SparseMatrix) -> Result<(), SolverError>;
256
257    /// Solve for a single RHS (requires prior factorization)
258    fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
259
260    /// Solve for multiple RHS (requires prior factorization)
261    fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
262        rhs.iter().map(|rhs| self.solve(rhs)).collect()
263    }
264}
265
266/// Combined trait for solvers that support both factor+solve and Lagrange systems
267pub trait LinearSolverWithConstraints: LinearSolver {
268    /// Solve a Lagrange system [K C^T; C 0] [u; lambda] = [f; 0]
269    fn solve_lagrange(&self, c: &[f64], f: &[f64]) -> Result<(Vec<f64>, f64), SolverError>;
270}
271
272/// Solver backend type
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
274pub enum SolverBackend {
275    Dense,
276    SkylineLdlt,
277    SparseLu,
278    #[cfg(feature = "pardiso")]
279    Pardiso,
280    Cg,
281    Iccg,
282}
283
284/// How a linear solver is chosen for a system.
285///
286/// # Canonical solver names
287///
288/// `Named` carries one of the registered backend names below. Unknown names are
289/// rejected with a structured [`SolverError`] — they never fall back.
290///
291/// | name             | symmetry        | definiteness        | intended size | registered by default |
292/// |------------------|-----------------|---------------------|---------------|-----------------------|
293/// | `dense`          | any (general)   | any                 | small         | yes                   |
294/// | `skyline_ldlt`   | symmetric only  | SPD (verified)      | medium/large  | yes                   |
295/// | `sparse_lu`      | any (general)   | any                 | medium/large  | yes                   |
296/// | `cg`             | symmetric only  | SPD (assumed)       | large         | yes                   |
297/// | `iccg`           | symmetric only  | SPD (assumed)       | large         | yes                   |
298/// | `pardiso`        | any (general)   | any                 | very large    | **no** — feature-gated stub |
299///
300/// # PARDISO availability
301///
302/// `pardiso` is **not** registered by [`SolverRegistry::default()`], even when
303/// the `pardiso` feature is compiled in: the unified PARDISO wrapper is a stub
304/// whose `factor()` always returns an error. Selecting it through the default
305/// registry therefore returns [`SolverError::Unsupported`] ("unknown solver"),
306/// and auto-selection never claims it is available unless a PARDISO factory is
307/// explicitly registered on the registry.
308///
309/// # Semantics
310///
311/// - [`Auto`](Self::Auto): the registry analyses the matrix and picks a backend.
312///   It may substitute a different backend than any the caller had in mind.
313/// - [`Named`](Self::Named): the request is **authoritative**. The registry
314///   validates capabilities and returns an error if the backend cannot legally
315///   handle the matrix. It never substitutes another backend.
316///
317/// `skyline_ldlt`, `cg` and `iccg` require positive definiteness but perform
318/// their own definiteness check during [`LinearSolver::factor`] (skyline rejects
319/// a non-positive pivot; CG/ICCG report failure). They are therefore safe to
320/// select on a symmetric matrix, but are **never** chosen by `Auto` for a matrix
321/// whose SPD property is not established.
322#[derive(Debug, Clone, PartialEq, Eq, Default)]
323pub enum SolverSelection {
324    /// Registry-based automatic selection (default).
325    #[default]
326    Auto,
327    /// Explicit backend request (canonical name, see type docs).
328    Named(String),
329}
330
331impl SolverSelection {
332    /// Explicit selection by canonical name.
333    pub fn named(name: impl Into<String>) -> Self {
334        Self::Named(name.into())
335    }
336    /// Select the dense Gaussian backend.
337    pub fn dense() -> Self {
338        Self::Named("dense".to_string())
339    }
340    /// Select the skyline LDL^T backend (symmetric SPD).
341    pub fn skyline_ldlt() -> Self {
342        Self::Named("skyline_ldlt".to_string())
343    }
344    /// Select the sparse LU backend.
345    pub fn sparse_lu() -> Self {
346        Self::Named("sparse_lu".to_string())
347    }
348    /// Select the conjugate-gradient backend (symmetric SPD).
349    pub fn cg() -> Self {
350        Self::Named("cg".to_string())
351    }
352    /// Select the incomplete-Cholesky CG backend (symmetric SPD).
353    pub fn iccg() -> Self {
354        Self::Named("iccg".to_string())
355    }
356    /// Select the PARDISO backend.
357    ///
358    /// **Not available through [`SolverRegistry::default()`]** — PARDISO is a
359    /// feature-gated stub that is deliberately left unregistered, so this
360    /// selection resolves only if a PARDISO factory is explicitly registered
361    /// via [`SolverRegistry::register`]. Otherwise
362    /// [`SolverRegistry::create_selected`] returns
363    /// [`SolverError::Unsupported`] rather than silently falling back.
364    pub fn pardiso() -> Self {
365        Self::Named("pardiso".to_string())
366    }
367    /// Whether this is automatic selection.
368    pub fn is_auto(&self) -> bool {
369        matches!(self, Self::Auto)
370    }
371    /// The explicitly requested name, or `None` for [`SolverSelection::Auto`].
372    pub fn requested_name(&self) -> Option<&str> {
373        match self {
374            Self::Auto => None,
375            Self::Named(n) => Some(n.as_str()),
376        }
377    }
378}
379
380/// Why a particular solver was selected.
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum SelectionReason {
383    /// The caller requested this backend explicitly.
384    ExplicitlyRequested,
385    /// Small system: dense is used for any matrix class.
386    SmallSystem,
387    /// Symmetric matrix whose diagonal is positive (necessary condition for
388    /// SPD): skyline is chosen; it verifies definiteness during factorization.
389    SymmetricPositiveDiagonal,
390    /// General (possibly non-symmetric) system: sparse LU.
391    GeneralSystem,
392    /// Very large system with PARDISO available.
393    LargeSystem,
394}
395
396/// The outcome of a solver-selection query. No solver is constructed and no
397/// factorization is performed, so this is cheap and side-effect free.
398#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct SolverSelectionInfo {
400    /// Canonical name of the chosen backend.
401    pub solver_name: String,
402    /// Why it was chosen.
403    pub reason: SelectionReason,
404}
405
406/// Validate that a solver with `caps` may legally handle `matrix`.
407///
408/// This is a **class** check (symmetry / generality). It deliberately does not
409/// attempt to prove positive definiteness: a symmetric indefinite matrix is a
410/// legal input to every backend that claims `general` support, and backends that
411/// require SPD (`skyline_ldlt`, `cg`, `iccg`) verify that themselves during
412/// [`LinearSolver::factor`], returning an error rather than a wrong answer.
413fn validate_solver_for_matrix(
414    name: &str,
415    caps: &SolverCapabilities,
416    matrix: &SparseMatrix,
417) -> Result<(), SolverError> {
418    if matrix.n == 0 {
419        return Err(SolverError::invalid_input("Empty matrix"));
420    }
421    if let Some(max_size) = caps.max_size.filter(|&m| matrix.n > m) {
422        return Err(SolverError::unsupported(format!(
423            "solver '{}' supports at most {} DOFs, but matrix has {}",
424            name, max_size, matrix.n
425        )));
426    }
427    let symmetric = matrix.is_symmetric(1e-12);
428    if !symmetric && !caps.general {
429        return Err(SolverError::unsupported(format!(
430            "solver '{}' requires a symmetric matrix, but the matrix is not symmetric; \
431             use 'dense' or 'sparse_lu'",
432            name
433        )));
434    }
435    Ok(())
436}
437
438/// Registry for solver backends
439pub struct SolverRegistry {
440    backends: std::collections::HashMap<String, Box<dyn LinearSolverFactory>>,
441}
442
443pub trait LinearSolverFactory: Send + Sync {
444    fn create(&self) -> Box<dyn LinearSolver>;
445    fn name(&self) -> &'static str;
446    fn capabilities(&self) -> SolverCapabilities;
447}
448
449impl SolverRegistry {
450    pub fn new() -> Self {
451        Self {
452            backends: std::collections::HashMap::new(),
453        }
454    }
455
456    pub fn register(&mut self, factory: Box<dyn LinearSolverFactory>) {
457        self.backends.insert(factory.name().to_string(), factory);
458    }
459
460    pub fn get(&self, name: &str) -> Option<&dyn LinearSolverFactory> {
461        self.backends.get(name).map(|b| b.as_ref())
462    }
463
464    pub fn list(&self) -> Vec<String> {
465        self.backends.keys().cloned().collect()
466    }
467
468    /// Registered solver names, sorted (deterministic).
469    pub fn list_sorted(&self) -> Vec<String> {
470        let mut v = self.list();
471        v.sort();
472        v
473    }
474
475    pub fn create(&self, name: &str) -> Option<Box<dyn LinearSolver>> {
476        self.backends.get(name).map(|f| f.create())
477    }
478
479    /// Validate that the named backend can legally handle `matrix`, returning
480    /// its capabilities on success. Performs **no** factorization.
481    ///
482    /// # Errors
483    ///
484    /// - [`SolverError::Unsupported`] if the name is unknown or the matrix class
485    ///   is incompatible with the backend.
486    /// - [`SolverError::InvalidInput`] for an empty matrix.
487    pub fn validate_selection(
488        &self,
489        name: &str,
490        matrix: &SparseMatrix,
491    ) -> Result<SolverCapabilities, SolverError> {
492        let factory = self
493            .get(name)
494            .ok_or_else(|| SolverError::unsupported(format!("unknown solver '{}'", name)))?;
495        let caps = factory.capabilities();
496        validate_solver_for_matrix(name, &caps, matrix)?;
497        Ok(caps)
498    }
499
500    /// Decide which backend would be used, **without** constructing or
501    /// factorizing anything. Answers "which solver, and why?".
502    ///
503    /// # Errors
504    ///
505    /// Returns an error for an unknown explicit name, an incompatible matrix
506    /// class, an empty matrix, or (for `Auto`) when no suitable backend exists.
507    pub fn select(
508        &self,
509        matrix: &SparseMatrix,
510        selection: &SolverSelection,
511    ) -> Result<SolverSelectionInfo, SolverError> {
512        match selection {
513            SolverSelection::Named(name) => {
514                self.validate_selection(name, matrix)?;
515                Ok(SolverSelectionInfo {
516                    solver_name: name.clone(),
517                    reason: SelectionReason::ExplicitlyRequested,
518                })
519            }
520            SolverSelection::Auto => self.auto_select_info(matrix),
521        }
522    }
523
524    /// The auto-selection policy, exposed as a decision (name + reason).
525    ///
526    /// Policy (conservative; never selects a solver that cannot handle the
527    /// detected matrix class):
528    ///
529    /// 1. `n <= 500` → `dense` (general, any class).
530    /// 2. symmetric with a positive diagonal (necessary condition for SPD) and
531    ///    within skyline's size limit → `skyline_ldlt` (it verifies definiteness
532    ///    at factorization).
533    /// 3. `pardiso` **only if a PARDISO factory is actually registered**
534    ///    (never for the default registry, even with the feature enabled).
535    /// 4. otherwise → `sparse_lu` (general; handles symmetric or not).
536    ///
537    /// Auto never selects `cg`/`iccg`. Unlike explicit selection, auto does not
538    /// hard-reject on `max_size`: it treats the limit as a preference and still
539    /// returns the only class-legal backend for very large systems.
540    ///
541    /// `cg`/`iccg` are never auto-selected: their SPD requirement cannot be
542    /// established reliably from the matrix alone.
543    pub fn auto_select_info(
544        &self,
545        matrix: &SparseMatrix,
546    ) -> Result<SolverSelectionInfo, SolverError> {
547        if matrix.n == 0 {
548            return Err(SolverError::invalid_input("Empty matrix"));
549        }
550
551        if matrix.n <= 500 && self.get("dense").is_some() {
552            return Ok(SolverSelectionInfo {
553                solver_name: "dense".to_string(),
554                reason: SelectionReason::SmallSystem,
555            });
556        }
557
558        // Symmetric with a positive diagonal: skyline is preferred, but only
559        // within its configured size limit (it requires SPD and verifies it at
560        // factorization).
561        if matrix.is_symmetric(1e-12) && has_positive_diagonal(matrix) {
562            let skyline_fits = self
563                .get("skyline_ldlt")
564                .is_some_and(|f| f.capabilities().max_size.is_none_or(|m| matrix.n <= m));
565            if skyline_fits {
566                return Ok(SolverSelectionInfo {
567                    solver_name: "skyline_ldlt".to_string(),
568                    reason: SelectionReason::SymmetricPositiveDiagonal,
569                });
570            }
571        }
572
573        // PARDISO is used only if a PARDISO factory is actually registered. It
574        // is NOT part of `SolverRegistry::default()`, so this never fires for
575        // the default registry even when the feature is compiled in.
576        #[cfg(feature = "pardiso")]
577        if self.get("pardiso").is_some() {
578            return Ok(SolverSelectionInfo {
579                solver_name: "pardiso".to_string(),
580                reason: SelectionReason::LargeSystem,
581            });
582        }
583
584        if self.get("sparse_lu").is_some() {
585            return Ok(SolverSelectionInfo {
586                solver_name: "sparse_lu".to_string(),
587                reason: SelectionReason::GeneralSystem,
588            });
589        }
590
591        Err(SolverError::unsupported(
592            "no suitable solver is registered for this matrix",
593        ))
594    }
595
596    /// Construct a solver for `selection`, after capability validation.
597    ///
598    /// Explicit selections are authoritative: if the requested backend cannot
599    /// legally handle the matrix (or is unknown / uncreatable), an error is
600    /// returned and **no** other backend is substituted. `Auto` may pick any
601    /// backend that can handle the matrix class.
602    ///
603    /// The solver is returned **unfactored** — the caller calls
604    /// [`LinearSolver::factor`] then [`LinearSolver::solve`].
605    pub fn create_selected(
606        &self,
607        matrix: &SparseMatrix,
608        selection: &SolverSelection,
609    ) -> Result<Box<dyn LinearSolver>, SolverError> {
610        let info = self.select(matrix, selection)?;
611        self.create(&info.solver_name).ok_or_else(|| {
612            SolverError::backend_unavailable(format!(
613                "solver '{}' was selected but cannot be constructed",
614                info.solver_name
615            ))
616        })
617    }
618
619    /// Backwards-compatible automatic selection: returns the chosen solver, or
620    /// `None` if none is registered. Prefer [`Self::select`] /
621    /// [`Self::create_selected`] for new code.
622    pub fn auto_select(&self, matrix: &SparseMatrix) -> Option<Box<dyn LinearSolver>> {
623        let info = self.auto_select_info(matrix).ok()?;
624        self.create(&info.solver_name)
625    }
626}
627
628/// True if every diagonal entry of `matrix` is strictly positive.
629///
630/// This is a *necessary* (not sufficient) condition for SPD and is used only as
631/// a conservative screen for auto-selection. It never asserts definiteness.
632fn has_positive_diagonal(matrix: &SparseMatrix) -> bool {
633    let n = matrix.n;
634    let mut diag = vec![0.0f64; n];
635    if matrix.compressed {
636        for (i, d) in diag.iter_mut().enumerate() {
637            for k in matrix.row_ptr[i]..matrix.row_ptr[i + 1] {
638                if matrix.csr_cols[k] == i {
639                    *d = matrix.csr_vals[k];
640                }
641            }
642        }
643    } else {
644        for k in 0..matrix.rows.len() {
645            if matrix.rows[k] == matrix.cols[k] {
646                diag[matrix.rows[k]] = matrix.vals[k];
647            }
648        }
649    }
650    diag.iter().all(|&d| d > 0.0)
651}
652
653impl Default for SolverRegistry {
654    fn default() -> Self {
655        let mut registry = Self::new();
656
657        // Register built-in backends
658        registry.register(Box::new(DenseSolverFactory));
659        registry.register(Box::new(SkylineLdltFactory));
660        registry.register(Box::new(SparseLuFactory));
661        registry.register(Box::new(CgSolverFactory));
662        registry.register(Box::new(IccgSolverFactory));
663
664        // PARDISO is NOT registered by default - it's a stub for the unified interface.
665        // The real PARDISO implementation in solvers.rs is for augmented Lagrange systems.
666        // Users must explicitly create it if needed.
667
668        registry
669    }
670}
671
672/// Factory for Dense Gaussian elimination
673struct DenseSolverFactory;
674impl LinearSolverFactory for DenseSolverFactory {
675    fn create(&self) -> Box<dyn LinearSolver> {
676        Box::new(DenseGaussianSolver::new())
677    }
678    fn name(&self) -> &'static str {
679        "dense"
680    }
681    fn capabilities(&self) -> SolverCapabilities {
682        SolverCapabilities::dense()
683    }
684}
685
686/// Factory for Skyline LDL^T
687struct SkylineLdltFactory;
688impl LinearSolverFactory for SkylineLdltFactory {
689    fn create(&self) -> Box<dyn LinearSolver> {
690        Box::new(SkylineLdltSolver::new())
691    }
692    fn name(&self) -> &'static str {
693        "skyline_ldlt"
694    }
695    fn capabilities(&self) -> SolverCapabilities {
696        SolverCapabilities::skyline_ldlt()
697    }
698}
699
700/// Factory for SparseLU
701struct SparseLuFactory;
702impl LinearSolverFactory for SparseLuFactory {
703    fn create(&self) -> Box<dyn LinearSolver> {
704        Box::new(SparseLuSolver::new())
705    }
706    fn name(&self) -> &'static str {
707        "sparse_lu"
708    }
709    fn capabilities(&self) -> SolverCapabilities {
710        SolverCapabilities::sparse_lu()
711    }
712}
713
714/// Factory for CG
715struct CgSolverFactory;
716impl LinearSolverFactory for CgSolverFactory {
717    fn create(&self) -> Box<dyn LinearSolver> {
718        Box::new(CgSolver::new())
719    }
720    fn name(&self) -> &'static str {
721        "cg"
722    }
723    fn capabilities(&self) -> SolverCapabilities {
724        SolverCapabilities::cg()
725    }
726}
727
728/// Factory for ICCG
729struct IccgSolverFactory;
730impl LinearSolverFactory for IccgSolverFactory {
731    fn create(&self) -> Box<dyn LinearSolver> {
732        Box::new(IccgSolver::new())
733    }
734    fn name(&self) -> &'static str {
735        "iccg"
736    }
737    fn capabilities(&self) -> SolverCapabilities {
738        SolverCapabilities::iccg()
739    }
740}
741
742// PARDISO is deliberately NOT registered by `SolverRegistry::default()`: the
743// unified wrapper (`PardisoSolverWrapper`) is a stub whose `factor()` always
744// returns an error, so it is not a usable general-purpose `LinearSolver` yet.
745// The factory is kept for callers that want to register it explicitly once a
746// real implementation exists; it is therefore never constructed in-tree.
747#[cfg(feature = "pardiso")]
748#[allow(dead_code)]
749struct PardisoSolverFactory;
750#[cfg(feature = "pardiso")]
751impl LinearSolverFactory for PardisoSolverFactory {
752    fn create(&self) -> Box<dyn LinearSolver> {
753        Box::new(PardisoSolverWrapper::new())
754    }
755    fn name(&self) -> &'static str {
756        "pardiso"
757    }
758    fn capabilities(&self) -> SolverCapabilities {
759        SolverCapabilities::pardiso()
760    }
761}
762
763// Re-export for public API
764pub use self::LinearSolver as Solver;
765pub use self::SolverCapabilities as Capabilities;
766pub use self::SolverError as Error;
767pub use self::SolverRegistry as Registry;