1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub struct SolverCapabilities {
21 pub symmetric: bool,
23 pub spd: bool,
25 pub symmetric_indefinite: bool,
27 pub general: bool,
29 pub multiple_rhs: bool,
31 pub complex: bool,
33 pub max_size: Option<usize>,
35}
36
37impl SolverCapabilities {
38 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 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 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 #[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 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 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#[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
236pub trait FactoredSolver: Send + Sync {
238 fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
240
241 fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
243 rhs.iter().map(|rhs| self.solve(rhs)).collect()
244 }
245
246 fn capabilities(&self) -> SolverCapabilities;
248
249 fn name(&self) -> &'static str;
251}
252
253pub trait LinearSolver: Send + Sync {
255 fn name(&self) -> &'static str;
257
258 fn capabilities(&self) -> SolverCapabilities;
260
261 fn factor(&mut self, matrix: &SparseMatrix) -> Result<(), SolverError>;
263
264 fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
266
267 fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
269 rhs.iter().map(|rhs| self.solve(rhs)).collect()
270 }
271}
272
273pub trait LinearSolverWithConstraints: LinearSolver {
275 fn solve_lagrange(&self, c: &[f64], f: &[f64]) -> Result<(Vec<f64>, f64), SolverError>;
277}
278
279#[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
330pub enum SolverSelection {
331 #[default]
333 Auto,
334 Named(String),
336}
337
338impl SolverSelection {
339 pub fn named(name: impl Into<String>) -> Self {
341 Self::Named(name.into())
342 }
343 pub fn dense() -> Self {
345 Self::Named("dense".to_string())
346 }
347 pub fn skyline_ldlt() -> Self {
349 Self::Named("skyline_ldlt".to_string())
350 }
351 pub fn sparse_lu() -> Self {
353 Self::Named("sparse_lu".to_string())
354 }
355 pub fn cg() -> Self {
357 Self::Named("cg".to_string())
358 }
359 pub fn iccg() -> Self {
361 Self::Named("iccg".to_string())
362 }
363 pub fn pardiso() -> Self {
372 Self::Named("pardiso".to_string())
373 }
374 pub fn is_auto(&self) -> bool {
376 matches!(self, Self::Auto)
377 }
378 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub enum SelectionReason {
390 ExplicitlyRequested,
392 SmallSystem,
394 SymmetricPositiveDiagonal,
397 GeneralSystem,
399 LargeSystem,
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct SolverSelectionInfo {
407 pub solver_name: String,
409 pub reason: SelectionReason,
411}
412
413fn 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
445pub 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 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 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 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 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 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 #[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 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 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
635fn 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 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 registry
676 }
677}
678
679struct 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
693struct 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
707struct 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
721struct 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
735struct 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#[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
770pub use self::LinearSolver as Solver;
772pub use self::SolverCapabilities as Capabilities;
773pub use self::SolverError as Error;
774pub use self::SolverRegistry as Registry;