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