use crate::fea::SparseMatrix;
use crate::fea::solver::impls::cg::CgSolver;
use crate::fea::solver::impls::dense_gaussian::DenseGaussianSolver;
use crate::fea::solver::impls::iccg::IccgSolver;
use crate::fea::solver::impls::skyline_ldlt::SkylineLdltSolver;
use crate::fea::solver::impls::sparse_lu::SparseLuSolver;
pub mod impls;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SolverCapabilities {
pub symmetric: bool,
pub spd: bool,
pub symmetric_indefinite: bool,
pub general: bool,
pub multiple_rhs: bool,
pub complex: bool,
pub max_size: Option<usize>,
}
impl SolverCapabilities {
pub fn dense() -> Self {
Self {
symmetric: true,
spd: true,
symmetric_indefinite: true,
general: true,
multiple_rhs: true,
complex: false,
max_size: Some(500),
}
}
pub fn skyline_ldlt() -> Self {
Self {
symmetric: true,
spd: true,
symmetric_indefinite: false,
general: false,
multiple_rhs: true,
complex: false,
max_size: Some(10000),
}
}
pub fn sparse_lu() -> Self {
Self {
symmetric: true,
spd: true,
symmetric_indefinite: true,
general: true,
multiple_rhs: true,
complex: false,
max_size: Some(3000),
}
}
pub fn cg() -> Self {
Self {
symmetric: true,
spd: true,
symmetric_indefinite: false,
general: false,
multiple_rhs: false,
complex: false,
max_size: None,
}
}
pub fn iccg() -> Self {
Self {
symmetric: true,
spd: true,
symmetric_indefinite: false,
general: false,
multiple_rhs: false,
complex: false,
max_size: None,
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum SolverError {
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("non-finite input at index {index}")]
NonFiniteInput { index: usize },
#[error("dimension mismatch: expected {expected}, got {actual}")]
DimensionMismatch { expected: usize, actual: usize },
#[error("singular matrix: {0}")]
SingularMatrix(String),
#[error("near-singular matrix: {0}")]
NearSingularMatrix(String),
#[error("factorization failed: {0}")]
FactorizationFailed(String),
#[error("solve failed: {0}")]
SolveFailed(String),
#[error("backend unavailable: {0}")]
BackendUnavailable(String),
#[error("backend error: {0}")]
BackendError(String),
#[error("unsupported operation: {0}")]
Unsupported(String),
#[error("convergence failed: {0}")]
ConvergenceFailed(String),
#[error("not implemented: {0}")]
NotImplemented(String),
#[error("matrix is not symmetric")]
NotSymmetric,
#[error("solver not factorized")]
NotFactorized,
#[error("solver did not converge")]
NotConverged,
}
impl SolverError {
pub fn invalid_input(msg: impl Into<String>) -> Self {
Self::InvalidInput(msg.into())
}
pub fn non_finite(index: usize) -> Self {
Self::NonFiniteInput { index }
}
pub fn dimension_mismatch(expected: usize, actual: usize) -> Self {
Self::DimensionMismatch { expected, actual }
}
pub fn singular(msg: impl Into<String>) -> Self {
Self::SingularMatrix(msg.into())
}
pub fn near_singular(msg: impl Into<String>) -> Self {
Self::NearSingularMatrix(msg.into())
}
pub fn factorization_failed(msg: impl Into<String>) -> Self {
Self::FactorizationFailed(msg.into())
}
pub fn solve_failed(msg: impl Into<String>) -> Self {
Self::SolveFailed(msg.into())
}
pub fn backend_unavailable(msg: impl Into<String>) -> Self {
Self::BackendUnavailable(msg.into())
}
pub fn backend_error(msg: impl Into<String>) -> Self {
Self::BackendError(msg.into())
}
pub fn unsupported(msg: impl Into<String>) -> Self {
Self::Unsupported(msg.into())
}
pub fn convergence_failed(msg: impl Into<String>) -> Self {
Self::ConvergenceFailed(msg.into())
}
pub fn not_implemented(msg: impl Into<String>) -> Self {
Self::NotImplemented(msg.into())
}
pub fn not_symmetric() -> Self {
Self::NotSymmetric
}
pub fn not_factorized() -> Self {
Self::NotFactorized
}
pub fn not_converged() -> Self {
Self::NotConverged
}
}
pub trait LinearSolver: Send + Sync {
fn name(&self) -> &'static str;
fn capabilities(&self) -> SolverCapabilities;
fn factor(&mut self, matrix: &SparseMatrix) -> Result<(), SolverError>;
fn solve(&self, rhs: &[f64]) -> Result<Vec<f64>, SolverError>;
fn solve_many(&self, rhs: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, SolverError> {
rhs.iter().map(|rhs| self.solve(rhs)).collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SolverSelection {
#[default]
Auto,
Named(String),
}
impl SolverSelection {
pub fn named(name: impl Into<String>) -> Self {
Self::Named(name.into())
}
pub fn dense() -> Self {
Self::Named("dense".to_string())
}
pub fn skyline_ldlt() -> Self {
Self::Named("skyline_ldlt".to_string())
}
pub fn sparse_lu() -> Self {
Self::Named("sparse_lu".to_string())
}
pub fn cg() -> Self {
Self::Named("cg".to_string())
}
pub fn iccg() -> Self {
Self::Named("iccg".to_string())
}
pub fn is_auto(&self) -> bool {
matches!(self, Self::Auto)
}
pub fn requested_name(&self) -> Option<&str> {
match self {
Self::Auto => None,
Self::Named(n) => Some(n.as_str()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionReason {
ExplicitlyRequested,
SmallSystem,
SymmetricPositiveDiagonal,
GeneralSystem,
LargeSystem,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SolverSelectionInfo {
pub solver_name: String,
pub reason: SelectionReason,
}
fn validate_solver_for_matrix(
name: &str,
caps: &SolverCapabilities,
matrix: &SparseMatrix,
) -> Result<(), SolverError> {
if matrix.n == 0 {
return Err(SolverError::invalid_input("Empty matrix"));
}
if let Some(max_size) = caps.max_size.filter(|&m| matrix.n > m) {
return Err(SolverError::unsupported(format!(
"solver '{}' supports at most {} DOFs, but matrix has {}",
name, max_size, matrix.n
)));
}
let symmetric = matrix.is_symmetric(1e-12);
if !symmetric && !caps.general {
return Err(SolverError::unsupported(format!(
"solver '{}' requires a symmetric matrix, but the matrix is not symmetric; \
use 'dense' or 'sparse_lu'",
name
)));
}
Ok(())
}
pub struct SolverRegistry {
backends: std::collections::HashMap<String, Box<dyn LinearSolverFactory>>,
}
pub trait LinearSolverFactory: Send + Sync {
fn create(&self) -> Box<dyn LinearSolver>;
fn name(&self) -> &'static str;
fn capabilities(&self) -> SolverCapabilities;
}
impl SolverRegistry {
pub fn new() -> Self {
Self {
backends: std::collections::HashMap::new(),
}
}
pub fn register(&mut self, factory: Box<dyn LinearSolverFactory>) {
self.backends.insert(factory.name().to_string(), factory);
}
pub fn get(&self, name: &str) -> Option<&dyn LinearSolverFactory> {
self.backends.get(name).map(|b| b.as_ref())
}
pub fn list(&self) -> Vec<String> {
self.backends.keys().cloned().collect()
}
pub fn list_sorted(&self) -> Vec<String> {
let mut v = self.list();
v.sort();
v
}
pub fn create(&self, name: &str) -> Option<Box<dyn LinearSolver>> {
self.backends.get(name).map(|f| f.create())
}
pub fn validate_selection(
&self,
name: &str,
matrix: &SparseMatrix,
) -> Result<SolverCapabilities, SolverError> {
let factory = self
.get(name)
.ok_or_else(|| SolverError::unsupported(format!("unknown solver '{}'", name)))?;
let caps = factory.capabilities();
validate_solver_for_matrix(name, &caps, matrix)?;
Ok(caps)
}
pub fn select(
&self,
matrix: &SparseMatrix,
selection: &SolverSelection,
) -> Result<SolverSelectionInfo, SolverError> {
match selection {
SolverSelection::Named(name) => {
self.validate_selection(name, matrix)?;
Ok(SolverSelectionInfo {
solver_name: name.clone(),
reason: SelectionReason::ExplicitlyRequested,
})
}
SolverSelection::Auto => self.auto_select_info(matrix),
}
}
pub fn auto_select_info(
&self,
matrix: &SparseMatrix,
) -> Result<SolverSelectionInfo, SolverError> {
if matrix.n == 0 {
return Err(SolverError::invalid_input("Empty matrix"));
}
if matrix.n <= 500 && self.get("dense").is_some() {
return Ok(SolverSelectionInfo {
solver_name: "dense".to_string(),
reason: SelectionReason::SmallSystem,
});
}
if matrix.is_symmetric(1e-12) && has_positive_diagonal(matrix) {
let skyline_fits = self
.get("skyline_ldlt")
.is_some_and(|f| f.capabilities().max_size.is_none_or(|m| matrix.n <= m));
if skyline_fits {
return Ok(SolverSelectionInfo {
solver_name: "skyline_ldlt".to_string(),
reason: SelectionReason::SymmetricPositiveDiagonal,
});
}
}
if self.get("sparse_lu").is_some() {
return Ok(SolverSelectionInfo {
solver_name: "sparse_lu".to_string(),
reason: SelectionReason::GeneralSystem,
});
}
Err(SolverError::unsupported(
"no suitable solver is registered for this matrix",
))
}
pub fn create_selected(
&self,
matrix: &SparseMatrix,
selection: &SolverSelection,
) -> Result<Box<dyn LinearSolver>, SolverError> {
let info = self.select(matrix, selection)?;
self.create(&info.solver_name).ok_or_else(|| {
SolverError::backend_unavailable(format!(
"solver '{}' was selected but cannot be constructed",
info.solver_name
))
})
}
pub fn auto_select(&self, matrix: &SparseMatrix) -> Option<Box<dyn LinearSolver>> {
let info = self.auto_select_info(matrix).ok()?;
self.create(&info.solver_name)
}
}
fn has_positive_diagonal(matrix: &SparseMatrix) -> bool {
let n = matrix.n;
let mut diag = vec![0.0f64; n];
if matrix.compressed {
for (i, d) in diag.iter_mut().enumerate() {
for k in matrix.row_ptr[i]..matrix.row_ptr[i + 1] {
if matrix.csr_cols[k] == i {
*d = matrix.csr_vals[k];
}
}
}
} else {
for k in 0..matrix.rows.len() {
if matrix.rows[k] == matrix.cols[k] {
diag[matrix.rows[k]] = matrix.vals[k];
}
}
}
diag.iter().all(|&d| d > 0.0)
}
impl Default for SolverRegistry {
fn default() -> Self {
let mut registry = Self::new();
registry.register(Box::new(DenseSolverFactory));
registry.register(Box::new(SkylineLdltFactory));
registry.register(Box::new(SparseLuFactory));
registry.register(Box::new(CgSolverFactory));
registry.register(Box::new(IccgSolverFactory));
registry
}
}
struct DenseSolverFactory;
impl LinearSolverFactory for DenseSolverFactory {
fn create(&self) -> Box<dyn LinearSolver> {
Box::new(DenseGaussianSolver::new())
}
fn name(&self) -> &'static str {
"dense"
}
fn capabilities(&self) -> SolverCapabilities {
SolverCapabilities::dense()
}
}
struct SkylineLdltFactory;
impl LinearSolverFactory for SkylineLdltFactory {
fn create(&self) -> Box<dyn LinearSolver> {
Box::new(SkylineLdltSolver::new())
}
fn name(&self) -> &'static str {
"skyline_ldlt"
}
fn capabilities(&self) -> SolverCapabilities {
SolverCapabilities::skyline_ldlt()
}
}
struct SparseLuFactory;
impl LinearSolverFactory for SparseLuFactory {
fn create(&self) -> Box<dyn LinearSolver> {
Box::new(SparseLuSolver::new())
}
fn name(&self) -> &'static str {
"sparse_lu"
}
fn capabilities(&self) -> SolverCapabilities {
SolverCapabilities::sparse_lu()
}
}
struct CgSolverFactory;
impl LinearSolverFactory for CgSolverFactory {
fn create(&self) -> Box<dyn LinearSolver> {
Box::new(CgSolver::new())
}
fn name(&self) -> &'static str {
"cg"
}
fn capabilities(&self) -> SolverCapabilities {
SolverCapabilities::cg()
}
}
struct IccgSolverFactory;
impl LinearSolverFactory for IccgSolverFactory {
fn create(&self) -> Box<dyn LinearSolver> {
Box::new(IccgSolver::new())
}
fn name(&self) -> &'static str {
"iccg"
}
fn capabilities(&self) -> SolverCapabilities {
SolverCapabilities::iccg()
}
}
pub use self::LinearSolver as Solver;
pub use self::SolverCapabilities as Capabilities;
pub use self::SolverError as Error;
pub use self::SolverRegistry as Registry;