use super::csr::CsrMatrix;
use crate::error::{BarracudaError, Result};
#[derive(Debug, Clone)]
pub struct SolverConfig {
pub tolerance: f64,
pub max_iterations: usize,
pub use_preconditioner: bool,
pub verbose: bool,
}
impl Default for SolverConfig {
fn default() -> Self {
Self {
tolerance: 1e-10,
max_iterations: 1000,
use_preconditioner: true,
verbose: false,
}
}
}
impl SolverConfig {
#[must_use]
pub fn with_tolerance(mut self, tol: f64) -> Self {
self.tolerance = tol;
self
}
#[must_use]
pub fn with_max_iterations(mut self, max: usize) -> Self {
self.max_iterations = max;
self
}
#[must_use]
pub fn no_preconditioner(mut self) -> Self {
self.use_preconditioner = false;
self
}
}
#[derive(Debug, Clone)]
pub struct SolverResult {
pub x: Vec<f64>,
pub iterations: usize,
pub residual: f64,
pub converged: bool,
}
impl SolverResult {
#[must_use]
pub fn is_ok(&self) -> bool {
self.converged
}
}
fn dot(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b.iter()).map(|(&x, &y)| x * y).sum()
}
fn norm(v: &[f64]) -> f64 {
dot(v, v).sqrt()
}
fn axpy(a: f64, x: &[f64], y: &mut [f64]) {
for (yi, &xi) in y.iter_mut().zip(x.iter()) {
*yi = a.mul_add(xi, *yi);
}
}
fn sub_into(x: &[f64], y: &mut [f64]) {
for (yi, &xi) in y.iter_mut().zip(x.iter()) {
*yi = xi - *yi;
}
}
fn apply_preconditioner(diag: &[f64], r: &[f64], z: &mut [f64]) {
for (i, (&ri, &di)) in r.iter().zip(diag.iter()).enumerate() {
z[i] = if di.abs() > 1e-12 { ri / di } else { ri };
}
}
pub fn cg_solve(a: &CsrMatrix, b: &[f64], tol: f64, max_iter: usize) -> Result<SolverResult> {
let config = SolverConfig::default()
.with_tolerance(tol)
.with_max_iterations(max_iter);
cg_solve_with_config(a, b, &config)
}
pub fn cg_solve_with_config(
a: &CsrMatrix,
b: &[f64],
config: &SolverConfig,
) -> Result<SolverResult> {
let n = a.n_rows;
if a.n_cols != n {
return Err(BarracudaError::InvalidInput {
message: "CG requires square matrix".to_string(),
});
}
if b.len() != n {
return Err(BarracudaError::InvalidInput {
message: format!("Vector length {} doesn't match matrix size {}", b.len(), n),
});
}
let mut x = vec![0.0; n];
let mut r = b.to_vec();
let b_norm = norm(b);
if b_norm < 1e-14 {
return Ok(SolverResult {
x,
iterations: 0,
residual: 0.0,
converged: true,
});
}
let diag = if config.use_preconditioner {
a.diagonal()
} else {
vec![1.0; n]
};
let mut z = vec![0.0; n];
apply_preconditioner(&diag, &r, &mut z);
let mut p = z.clone();
let mut rz = dot(&r, &z);
for iter in 0..config.max_iterations {
let ap = a.matvec(&p)?;
let pap = dot(&p, &ap);
if pap.abs() < 1e-30 {
let residual = norm(&r) / b_norm;
return Ok(SolverResult {
x,
iterations: iter + 1,
residual,
converged: residual < config.tolerance,
});
}
let alpha = rz / pap;
axpy(alpha, &p, &mut x);
axpy(-alpha, &ap, &mut r);
let residual = norm(&r) / b_norm;
if residual < config.tolerance {
return Ok(SolverResult {
x,
iterations: iter + 1,
residual,
converged: true,
});
}
apply_preconditioner(&diag, &r, &mut z);
let rz_new = dot(&r, &z);
let beta = rz_new / rz;
rz = rz_new;
for (pi, &zi) in p.iter_mut().zip(z.iter()) {
*pi = zi + beta * *pi;
}
}
Ok(SolverResult {
x,
iterations: config.max_iterations,
residual: norm(&r) / b_norm,
converged: false,
})
}
pub fn bicgstab_solve(a: &CsrMatrix, b: &[f64], tol: f64, max_iter: usize) -> Result<SolverResult> {
let config = SolverConfig::default()
.with_tolerance(tol)
.with_max_iterations(max_iter);
bicgstab_solve_with_config(a, b, &config)
}
pub fn bicgstab_solve_with_config(
a: &CsrMatrix,
b: &[f64],
config: &SolverConfig,
) -> Result<SolverResult> {
let n = a.n_rows;
if a.n_cols != n {
return Err(BarracudaError::InvalidInput {
message: "BiCGSTAB requires square matrix".to_string(),
});
}
if b.len() != n {
return Err(BarracudaError::InvalidInput {
message: format!("Vector length {} doesn't match matrix size {}", b.len(), n),
});
}
let mut x = vec![0.0; n];
let mut r = b.to_vec();
let b_norm = norm(b);
if b_norm < 1e-14 {
return Ok(SolverResult {
x,
iterations: 0,
residual: 0.0,
converged: true,
});
}
let r_hat = r.clone();
let mut rho = 1.0;
let mut alpha = 1.0;
let mut omega = 1.0;
let mut v = vec![0.0; n];
let mut p = vec![0.0; n];
let mut s = vec![0.0; n];
let mut t = vec![0.0; n];
let diag = if config.use_preconditioner {
a.diagonal()
} else {
vec![1.0; n]
};
for iter in 0..config.max_iterations {
let rho_new = dot(&r_hat, &r);
if rho_new.abs() < 1e-14 {
return Err(BarracudaError::Internal(
"BiCGSTAB breakdown: rho = 0".to_string(),
));
}
let beta = (rho_new / rho) * (alpha / omega);
rho = rho_new;
for i in 0..n {
p[i] = r[i] + beta * (p[i] - omega * v[i]);
}
let mut p_hat = vec![0.0; n];
apply_preconditioner(&diag, &p, &mut p_hat);
v = a.matvec(&p_hat)?;
let rv = dot(&r_hat, &v);
if rv.abs() < 1e-14 {
return Err(BarracudaError::Internal(
"BiCGSTAB breakdown: r_hat·v = 0".to_string(),
));
}
alpha = rho / rv;
for i in 0..n {
s[i] = r[i] - alpha * v[i];
}
let s_norm = norm(&s);
if s_norm / b_norm < config.tolerance {
axpy(alpha, &p_hat, &mut x);
return Ok(SolverResult {
x,
iterations: iter + 1,
residual: s_norm / b_norm,
converged: true,
});
}
let mut s_hat = vec![0.0; n];
apply_preconditioner(&diag, &s, &mut s_hat);
t = a.matvec(&s_hat)?;
let tt = dot(&t, &t);
if tt.abs() < 1e-14 {
omega = 0.0;
} else {
omega = dot(&t, &s) / tt;
}
axpy(alpha, &p_hat, &mut x);
axpy(omega, &s_hat, &mut x);
for i in 0..n {
r[i] = s[i] - omega * t[i];
}
let residual = norm(&r) / b_norm;
if residual < config.tolerance {
return Ok(SolverResult {
x,
iterations: iter + 1,
residual,
converged: true,
});
}
if omega.abs() < 1e-14 {
return Err(BarracudaError::Internal(
"BiCGSTAB breakdown: omega = 0".to_string(),
));
}
}
Ok(SolverResult {
x,
iterations: config.max_iterations,
residual: norm(&r) / b_norm,
converged: false,
})
}
pub fn jacobi_solve(a: &CsrMatrix, b: &[f64], tol: f64, max_iter: usize) -> Result<SolverResult> {
let n = a.n_rows;
if a.n_cols != n || b.len() != n {
return Err(BarracudaError::InvalidInput {
message: "Dimension mismatch".to_string(),
});
}
let b_norm = norm(b);
if b_norm < 1e-14 {
return Ok(SolverResult {
x: vec![0.0; n],
iterations: 0,
residual: 0.0,
converged: true,
});
}
let diag = a.diagonal();
for (i, d) in diag.iter().enumerate() {
if d.abs() < 1e-14 {
return Err(BarracudaError::InvalidInput {
message: format!("Zero diagonal at row {i}"),
});
}
}
let mut x = vec![0.0; n];
let mut x_new = vec![0.0; n];
for iter in 0..max_iter {
for i in 0..n {
let row_start = a.row_ptr[i];
let row_end = a.row_ptr[i + 1];
let mut sum = b[i];
for k in row_start..row_end {
let j = a.col_indices[k];
if j != i {
sum = a.values[k].mul_add(-x[j], sum);
}
}
x_new[i] = sum / diag[i];
}
let ax = a.matvec(&x_new)?;
let mut r = ax;
sub_into(b, &mut r);
let residual = norm(&r) / b_norm;
if residual < tol {
return Ok(SolverResult {
x: x_new,
iterations: iter + 1,
residual,
converged: true,
});
}
std::mem::swap(&mut x, &mut x_new);
}
let ax = a.matvec(&x)?;
let mut r = ax;
sub_into(b, &mut r);
Ok(SolverResult {
x,
iterations: max_iter,
residual: norm(&r) / b_norm,
converged: false,
})
}
#[cfg(test)]
#[path = "solvers_tests.rs"]
mod tests;