use std::rc::Rc;
use crate::RhsCallable;
use crate::error::OdeError;
use crate::sparse::JacobianPattern;
pub type Rhs = dyn Fn(f64, &[f64], &mut [f64]);
pub struct OdeProblemBuilder {
rhs: Rc<dyn RhsCallable>,
y0: Vec<f64>,
t0: f64,
rtol: f64,
atol: f64,
h0: Option<f64>,
jac_pattern: Option<JacobianPattern>,
}
impl OdeProblemBuilder {
pub fn new<F>(rhs: F, y0: Vec<f64>, t0: f64) -> Self
where
F: Fn(f64, &[f64], &mut [f64]) + 'static,
{
Self {
rhs: Rc::new(rhs),
y0,
t0,
rtol: 1e-6,
atol: 1e-6,
h0: None,
jac_pattern: None,
}
}
pub fn from_rhs<R: RhsCallable + 'static>(rhs: R, y0: Vec<f64>, t0: f64) -> Self {
Self {
rhs: Rc::new(rhs),
y0,
t0,
rtol: 1e-6,
atol: 1e-6,
h0: None,
jac_pattern: None,
}
}
pub fn rtol(mut self, rtol: f64) -> Self {
self.rtol = rtol;
self
}
pub fn atol(mut self, atol: f64) -> Self {
self.atol = atol;
self
}
#[must_use]
pub fn jacobian_pattern(mut self, pattern: JacobianPattern) -> Self {
self.jac_pattern = Some(pattern);
self
}
pub fn h0(mut self, h0: f64) -> Self {
self.h0 = Some(h0);
self
}
pub fn build(self) -> Result<OdeProblem, OdeError> {
let n = self.y0.len();
if n == 0 {
return Err(OdeError::Invalid(
"initial state y0 must be non-empty".to_string(),
));
}
if self.rtol <= 0.0 || self.atol <= 0.0 {
return Err(OdeError::Invalid(
"rtol and atol must be strictly positive".to_string(),
));
}
Ok(OdeProblem {
rhs: self.rhs,
y0: self.y0,
t0: self.t0,
rtol: self.rtol,
atol: self.atol,
h0: self.h0,
jac_pattern: self.jac_pattern,
nstates: n,
})
}
}
pub struct OdeProblem {
pub(crate) rhs: Rc<dyn RhsCallable>,
pub(crate) y0: Vec<f64>,
pub(crate) t0: f64,
pub(crate) rtol: f64,
pub(crate) atol: f64,
pub(crate) h0: Option<f64>,
pub(crate) jac_pattern: Option<JacobianPattern>,
pub(crate) nstates: usize,
}
impl OdeProblem {
pub fn new<F>(rhs: F, y0: Vec<f64>, t0: f64) -> Result<Self, OdeError>
where
F: Fn(f64, &[f64], &mut [f64]) + 'static,
{
OdeProblemBuilder::new(rhs, y0, t0).build()
}
pub fn from_rhs<R: RhsCallable + 'static>(
rhs: R,
y0: Vec<f64>,
t0: f64,
) -> Result<Self, OdeError> {
OdeProblemBuilder::from_rhs(rhs, y0, t0).build()
}
pub fn nstates(&self) -> usize {
self.nstates
}
pub fn t0(&self) -> f64 {
self.t0
}
pub fn y0(&self) -> &[f64] {
&self.y0
}
pub fn respawn(&self, y0: Vec<f64>, t0: f64) -> Result<Self, OdeError> {
if y0.is_empty() {
return Err(OdeError::Invalid(
"initial state y0 must be non-empty".to_string(),
));
}
Ok(Self {
rhs: self.rhs.clone(),
y0,
t0,
rtol: self.rtol,
atol: self.atol,
h0: self.h0,
jac_pattern: self.jac_pattern.clone(),
nstates: self.nstates,
})
}
}