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("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
229pub trait FactoredSolver: Send + Sync {
231 fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
233
234 fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
236 rhs.iter().map(|rhs| self.solve(rhs)).collect()
237 }
238
239 fn capabilities(&self) -> SolverCapabilities;
241
242 fn name(&self) -> &'static str;
244}
245
246pub trait LinearSolver: Send + Sync {
248 fn name(&self) -> &'static str;
250
251 fn capabilities(&self) -> SolverCapabilities;
253
254 fn factor(&mut self, matrix: &SparseMatrix) -> Result<(), SolverError>;
256
257 fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
259
260 fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
262 rhs.iter().map(|rhs| self.solve(rhs)).collect()
263 }
264}
265
266pub trait LinearSolverWithConstraints: LinearSolver {
268 fn solve_lagrange(&self, c: &[f64], f: &[f64]) -> Result<(Vec<f64>, f64), SolverError>;
270}
271
272#[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
323pub enum SolverSelection {
324 #[default]
326 Auto,
327 Named(String),
329}
330
331impl SolverSelection {
332 pub fn named(name: impl Into<String>) -> Self {
334 Self::Named(name.into())
335 }
336 pub fn dense() -> Self {
338 Self::Named("dense".to_string())
339 }
340 pub fn skyline_ldlt() -> Self {
342 Self::Named("skyline_ldlt".to_string())
343 }
344 pub fn sparse_lu() -> Self {
346 Self::Named("sparse_lu".to_string())
347 }
348 pub fn cg() -> Self {
350 Self::Named("cg".to_string())
351 }
352 pub fn iccg() -> Self {
354 Self::Named("iccg".to_string())
355 }
356 pub fn pardiso() -> Self {
365 Self::Named("pardiso".to_string())
366 }
367 pub fn is_auto(&self) -> bool {
369 matches!(self, Self::Auto)
370 }
371 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum SelectionReason {
383 ExplicitlyRequested,
385 SmallSystem,
387 SymmetricPositiveDiagonal,
390 GeneralSystem,
392 LargeSystem,
394}
395
396#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct SolverSelectionInfo {
400 pub solver_name: String,
402 pub reason: SelectionReason,
404}
405
406fn 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
438pub 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 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 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 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 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 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 #[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 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 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
628fn 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 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 registry
669 }
670}
671
672struct 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
686struct 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
700struct 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
714struct 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
728struct 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#[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
763pub use self::LinearSolver as Solver;
765pub use self::SolverCapabilities as Capabilities;
766pub use self::SolverError as Error;
767pub use self::SolverRegistry as Registry;