pub const WGSL_CRANK_NICOLSON_F64: &str = include_str!("../shaders/pde/crank_nicolson_f64.wgsl");
use crate::error::{BarracudaError, Result};
use crate::ops::linalg::tridiagonal::tridiagonal_solve;
#[derive(Debug, Clone)]
pub struct CrankNicolsonConfig {
pub alpha: f64,
pub dx: f64,
pub dt: f64,
pub nx: usize,
pub left_bc: f64,
pub right_bc: f64,
}
impl CrankNicolsonConfig {
#[must_use]
pub fn new(alpha: f64, dx: f64, dt: f64, nx: usize) -> Self {
Self {
alpha,
dx,
dt,
nx,
left_bc: 0.0,
right_bc: 0.0,
}
}
#[must_use]
pub fn with_boundary_conditions(mut self, left: f64, right: f64) -> Self {
self.left_bc = left;
self.right_bc = right;
self
}
#[must_use]
pub fn courant_number(&self) -> f64 {
self.alpha * self.dt / (self.dx * self.dx)
}
pub fn validate(&self) -> Result<()> {
if self.alpha <= 0.0 {
return Err(BarracudaError::InvalidInput {
message: "alpha must be positive".to_string(),
});
}
if self.dx <= 0.0 {
return Err(BarracudaError::InvalidInput {
message: "dx must be positive".to_string(),
});
}
if self.dt <= 0.0 {
return Err(BarracudaError::InvalidInput {
message: "dt must be positive".to_string(),
});
}
if self.nx < 3 {
return Err(BarracudaError::InvalidInput {
message: "nx must be >= 3".to_string(),
});
}
Ok(())
}
}
pub struct HeatEquation1D {
config: CrankNicolsonConfig,
u: Vec<f64>,
a: Vec<f64>,
b: Vec<f64>,
c: Vec<f64>,
r: f64,
}
impl HeatEquation1D {
pub fn new(config: CrankNicolsonConfig, initial: &[f64]) -> Result<Self> {
config.validate()?;
if initial.len() != config.nx {
return Err(BarracudaError::InvalidInput {
message: format!(
"Initial condition length {} != nx {}",
initial.len(),
config.nx
),
});
}
let r = config.courant_number();
let n_interior = config.nx - 2;
let a = vec![-r / 2.0; n_interior - 1]; let b = vec![1.0 + r; n_interior]; let c = vec![-r / 2.0; n_interior - 1];
let u = initial[1..config.nx - 1].to_vec();
Ok(Self {
config,
u,
a,
b,
c,
r,
})
}
pub fn step(&mut self) -> Result<Vec<f64>> {
let n = self.u.len();
let mut rhs = vec![0.0; n];
for (i, rhs_i) in rhs.iter_mut().enumerate() {
let u_left = if i == 0 {
self.config.left_bc
} else {
self.u[i - 1]
};
let u_right = if i == n - 1 {
self.config.right_bc
} else {
self.u[i + 1]
};
*rhs_i = (1.0 - self.r).mul_add(self.u[i], (self.r / 2.0) * (u_left + u_right));
}
rhs[0] = (self.r / 2.0).mul_add(self.config.left_bc, rhs[0]);
rhs[n - 1] = (self.r / 2.0).mul_add(self.config.right_bc, rhs[n - 1]);
self.u = tridiagonal_solve(&self.a, &self.b, &self.c, &rhs)?;
Ok(self.solution())
}
pub fn advance(&mut self, n_steps: usize) -> Result<Vec<f64>> {
for _ in 0..n_steps {
self.step()?;
}
Ok(self.solution())
}
#[must_use]
pub fn solution(&self) -> Vec<f64> {
let mut full = Vec::with_capacity(self.config.nx);
full.push(self.config.left_bc);
full.extend_from_slice(&self.u);
full.push(self.config.right_bc);
full
}
#[must_use]
pub fn grid(&self) -> Vec<f64> {
(0..self.config.nx)
.map(|i| i as f64 * self.config.dx)
.collect()
}
#[must_use]
pub fn config(&self) -> &CrankNicolsonConfig {
&self.config
}
}
pub struct CrankNicolson1D {
heat: HeatEquation1D,
time: f64,
}
impl CrankNicolson1D {
pub fn new(config: CrankNicolsonConfig, initial: &[f64]) -> Result<Self> {
let heat = HeatEquation1D::new(config, initial)?;
Ok(Self { heat, time: 0.0 })
}
pub fn step_with_source(&mut self, source: Option<&[f64]>) -> Result<Vec<f64>> {
let result = self.heat.step()?;
self.time += self.heat.config.dt;
if let Some(src) = source
&& src.len() == self.heat.u.len()
{
for (u, s) in self.heat.u.iter_mut().zip(src.iter()) {
*u = self.heat.config.dt.mul_add(*s, *u);
}
}
Ok(result)
}
#[must_use]
pub fn time(&self) -> f64 {
self.time
}
#[must_use]
pub fn solution(&self) -> Vec<f64> {
self.heat.solution()
}
}
pub fn crank_nicolson_step(
u: &[f64],
alpha: f64,
dx: f64,
dt: f64,
left_bc: f64,
right_bc: f64,
) -> Result<Vec<f64>> {
let n = u.len();
if n == 0 {
return Err(BarracudaError::InvalidInput {
message: "u must have at least 1 interior point".to_string(),
});
}
let r = alpha * dt / (dx * dx);
let a = vec![-r / 2.0; n - 1];
let b = vec![1.0 + r; n];
let c = vec![-r / 2.0; n - 1];
let mut rhs = vec![0.0; n];
for i in 0..n {
let u_left = if i == 0 { left_bc } else { u[i - 1] };
let u_right = if i == n - 1 { right_bc } else { u[i + 1] };
rhs[i] = (1.0 - r).mul_add(u[i], (r / 2.0) * (u_left + u_right));
}
rhs[0] = (r / 2.0).mul_add(left_bc, rhs[0]);
rhs[n - 1] = (r / 2.0).mul_add(right_bc, rhs[n - 1]);
tridiagonal_solve(&a, &b, &c, &rhs)
}
#[cfg(test)]
mod tests {
use super::*;
use std::f64::consts::PI;
#[test]
fn test_config_validation() {
let config = CrankNicolsonConfig::new(1.0, 0.1, 0.01, 11);
assert!(config.validate().is_ok());
let bad = CrankNicolsonConfig::new(-1.0, 0.1, 0.01, 11);
assert!(bad.validate().is_err());
let bad2 = CrankNicolsonConfig::new(1.0, 0.1, 0.01, 2);
assert!(bad2.validate().is_err());
}
#[test]
fn test_courant_number() {
let config = CrankNicolsonConfig::new(1.0, 0.1, 0.005, 11);
let r = config.courant_number();
assert!((r - 0.5).abs() < 1e-14);
}
#[test]
fn test_heat_equation_steady_state() {
let config =
CrankNicolsonConfig::new(1.0, 0.1, 0.01, 11).with_boundary_conditions(0.0, 1.0);
let initial = vec![0.0; 11];
let mut solver = HeatEquation1D::new(config, &initial).unwrap();
let _ = solver.advance(1000).unwrap();
let sol = solver.solution();
let grid = solver.grid();
for (i, (x, u)) in grid.iter().zip(sol.iter()).enumerate() {
let expected = x / 1.0; if i > 0 && i < 10 {
assert!(
(u - expected).abs() < 0.1,
"At x={x}: u={u}, expected={expected}"
);
}
}
}
#[test]
fn test_heat_equation_decay() {
let nx = 101;
let dx = 1.0 / (nx - 1) as f64;
let dt = 0.0001;
let alpha = 1.0;
let config = CrankNicolsonConfig::new(alpha, dx, dt, nx).with_boundary_conditions(0.0, 0.0);
let initial: Vec<f64> = (0..nx)
.map(|i| (PI * i as f64 / (nx - 1) as f64).sin())
.collect();
let mut solver = HeatEquation1D::new(config, &initial).unwrap();
let n_steps = 1000;
let t_final = n_steps as f64 * dt;
let _ = solver.advance(n_steps).unwrap();
let sol = solver.solution();
let mid_idx = nx / 2;
let expected = (-PI * PI * t_final).exp() * 1.0;
assert!(
(sol[mid_idx] - expected).abs() < 0.05,
"At midpoint: got {}, expected {}",
sol[mid_idx],
expected
);
}
#[test]
fn test_crank_nicolson_step() {
let u = vec![0.0, 1.0, 0.0]; let result = crank_nicolson_step(&u, 1.0, 0.1, 0.005, 0.0, 0.0).unwrap();
assert_eq!(result.len(), 3);
assert!(result[1] < 1.0);
}
#[test]
fn test_solver_with_source() {
let config =
CrankNicolsonConfig::new(1.0, 0.1, 0.01, 11).with_boundary_conditions(0.0, 0.0);
let initial = vec![0.0; 11];
let mut solver = CrankNicolson1D::new(config, &initial).unwrap();
let source = vec![1.0; 9]; let _ = solver.step_with_source(Some(&source)).unwrap();
assert!(solver.time() > 0.0);
}
#[test]
fn test_conservation_with_no_flux() {
let nx = 11;
let config =
CrankNicolsonConfig::new(1.0, 0.1, 0.01, nx).with_boundary_conditions(0.0, 0.0);
let initial: Vec<f64> = (0..nx)
.map(|i| if i == nx / 2 { 1.0 } else { 0.0 })
.collect();
let initial_sum: f64 = initial.iter().sum();
let mut solver = HeatEquation1D::new(config, &initial).unwrap();
let _ = solver.advance(10).unwrap();
let final_sol = solver.solution();
let final_sum: f64 = final_sol.iter().sum();
assert!(final_sum < initial_sum);
}
}