1use crate::math_expr::{MathExpr, ParseError};
8use crate::{OdeSystem, SystemKind};
9use std::collections::HashMap;
10use std::ffi::c_int;
11use std::fmt::{Display, Formatter};
12mod ffi;
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum Method {
16 #[default]
17 England,
18 Lawson,
19 LawsonLinear,
20 LawsonSplit,
21 Rosenbrock,
22 RosenbrockAutonomous,
23}
24
25impl Method {
26 pub fn supports(self, kind: SystemKind) -> bool {
27 match self {
28 Self::LawsonLinear => kind == SystemKind::TimeLinear,
29 Self::LawsonSplit => kind == SystemKind::ConstantLinear,
30 Self::RosenbrockAutonomous => kind == SystemKind::Autonomous,
31 _ => true,
32 }
33 }
34
35 fn workspace_len(self, dimension: usize) -> Result<usize, SolverError> {
36 let (quadratic, linear) = match self {
37 Self::England => (0, 7),
38 Self::Lawson | Self::Rosenbrock => (6, 6),
39 Self::LawsonLinear => (7, 5),
40 Self::LawsonSplit => (5, 6),
41 Self::RosenbrockAutonomous => (6, 4),
42 };
43 let len = dimension
44 .checked_mul(dimension)
45 .and_then(|square| square.checked_mul(quadratic))
46 .and_then(|square| {
47 dimension
48 .checked_mul(linear)
49 .and_then(|v| square.checked_add(v))
50 })
51 .filter(|&len| c_int::try_from(len).is_ok());
52 if dimension
54 .checked_mul(64)
55 .is_none_or(|v| c_int::try_from(v).is_err())
56 {
57 return Err(SolverError::InvalidInput(
58 "system is too large for the Fortran integer ABI",
59 ));
60 }
61 len.ok_or(SolverError::InvalidInput(
62 "system is too large for the Fortran integer ABI",
63 ))
64 }
65}
66
67#[derive(Clone, Debug)]
70pub struct Solver {
71 pub method: Method,
72 pub initial_step: f64,
73 pub min_step: f64,
74 pub max_step: f64,
75 pub tolerance: f64,
77 pub relative_threshold: f64,
80 pub max_steps: usize,
82}
83
84impl Default for Solver {
85 fn default() -> Self {
86 Self {
87 method: Method::England,
88 initial_step: 0.01,
89 min_step: 1e-12,
90 max_step: 0.1,
91 tolerance: 1e-9,
92 relative_threshold: 1.0,
93 max_steps: 10_000_000,
94 }
95 }
96}
97
98#[derive(Clone, Debug, PartialEq)]
101pub struct Solution {
102 pub times: Vec<f64>,
103 pub states: Vec<Vec<f64>>,
104 pub recommended_steps: Vec<f64>,
107}
108
109#[derive(Clone, Debug, PartialEq)]
110pub enum SolverError {
111 InvalidInput(&'static str),
112 IncompatibleMethod { method: Method, system: SystemKind },
113 Parse { equation: usize, source: ParseError },
114 Evaluation { equation: usize, message: String },
115 NonFiniteDerivative { equation: usize, time: f64 },
116 NonFiniteState { time: f64 },
117 StepSizeTooSmall { time: f64 },
118 StepLimitExceeded { time: f64 },
119 NoProgress { time: f64 },
120 CallbackPanicked,
121 FortranFailure { info: c_int },
122}
123
124impl Display for SolverError {
125 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
126 match self {
127 Self::InvalidInput(message) => f.write_str(message),
128 Self::IncompatibleMethod { method, system } => {
129 write!(f, "{method:?} does not support {system:?} systems")
130 }
131 Self::Parse { equation, source } => write!(f, "equation {equation}: {source}"),
132 Self::Evaluation { equation, message } => {
133 write!(f, "equation {equation}: {message}")
134 }
135 Self::NonFiniteDerivative { equation, time } => {
136 write!(
137 f,
138 "equation {equation} has a non-finite derivative at t={time}"
139 )
140 }
141 Self::NonFiniteState { time } => write!(f, "non-finite time or state at t={time}"),
142 Self::StepSizeTooSmall { time } => {
143 write!(
144 f,
145 "solver cannot meet the tolerance at the minimum step at t={time}"
146 )
147 }
148 Self::StepLimitExceeded { time } => write!(f, "step limit reached at t={time}"),
149 Self::NoProgress { time } => {
150 write!(f, "step cannot advance floating-point time at t={time}")
151 }
152 Self::CallbackPanicked => f.write_str("expression evaluation panicked"),
153 Self::FortranFailure { info } => write!(f, "Fortran solver failed with IERR={info}"),
154 }
155 }
156}
157
158impl std::error::Error for SolverError {
159 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
160 match self {
161 Self::Parse { source, .. } => Some(source),
162 _ => None,
163 }
164 }
165}
166
167impl Solver {
168 pub fn solve(
179 &self,
180 rhs: &str,
181 start_time: f64,
182 initial_x: f64,
183 end_time: f64,
184 ) -> Result<Solution, SolverError> {
185 self.solve_system(&[rhs], start_time, &[initial_x], end_time)
186 }
187
188 pub fn solve_system(
196 &self,
197 rhs: &[&str],
198 start_time: f64,
199 initial_state: &[f64],
200 end_time: f64,
201 ) -> Result<Solution, SolverError> {
202 let names: Vec<_> = (0..rhs.len()).map(|i| format!("x{i}")).collect();
203 let names: Vec<_> = names.iter().map(String::as_str).collect();
204 let expressions = rhs
205 .iter()
206 .enumerate()
207 .map(|(equation, source)| {
208 let expression = MathExpr::parse(source)
209 .map_err(|source| SolverError::Parse { equation, source })?;
210 Ok(if names.len() == 1 {
213 expression.substitute("x", &MathExpr::new_var("x0"))
214 } else {
215 expression
216 })
217 })
218 .collect::<Result<Vec<_>, SolverError>>()?;
219 let (time, kind) = if self.method == Method::RosenbrockAutonomous {
220 (None, SystemKind::Autonomous)
221 } else {
222 (Some("t"), SystemKind::General)
223 };
224 let system = OdeSystem::from_expressions(time, &names, expressions, kind)?;
225 self.solve_problem(&system, start_time, initial_state, end_time)
226 }
227
228 pub fn solve_problem(
231 &self,
232 system: &OdeSystem<'_>,
233 start_time: f64,
234 initial_state: &[f64],
235 end_time: f64,
236 ) -> Result<Solution, SolverError> {
237 self.validate(system.dimension(), start_time, initial_state, end_time)?;
238 if !self.method.supports(system.kind()) {
239 return Err(SolverError::IncompatibleMethod {
240 method: self.method,
241 system: system.kind(),
242 });
243 }
244 let work_len = self.method.workspace_len(system.dimension())?;
245 let mut context = CallbackContext::new(system, self.method);
246 let direction = (end_time - start_time).signum();
247 let mut solution = Solution {
248 times: vec![start_time],
249 states: vec![initial_state.to_vec()],
250 recommended_steps: vec![direction * self.initial_step],
251 };
252 let mut time = start_time;
253 let mut state = initial_state.to_vec();
254 let mut work = vec![0.0; work_len];
255 let mut step = direction * self.initial_step;
256 let mut steps = 0;
257
258 while direction * (end_time - time) > 0.0 {
259 if steps == self.max_steps {
260 return Err(SolverError::StepLimitExceeded { time });
261 }
262 let remaining = (end_time - time).abs();
263 step = direction
264 * step
265 .abs()
266 .clamp(self.min_step, self.max_step)
267 .min(remaining);
268 let min_step = self.min_step.min(remaining);
269 if time + step == time {
270 return Err(SolverError::NoProgress { time });
271 }
272 let previous_time = time;
273 let info = ffi::step(
274 self,
275 &mut context,
276 min_step,
277 &mut state,
278 &mut time,
279 &mut step,
280 &mut work,
281 );
282 if let Some(error) = context.error.take() {
283 return Err(error);
284 }
285 match info {
286 0 => {}
287 65 => return Err(SolverError::StepSizeTooSmall { time }),
288 info => return Err(SolverError::FortranFailure { info }),
289 }
290 if !time.is_finite() || !state.iter().all(|x| x.is_finite()) {
291 return Err(SolverError::NonFiniteState { time });
292 }
293 if direction * (time - previous_time) <= 0.0 {
294 return Err(SolverError::NoProgress { time });
295 }
296 solution.times.push(time);
297 solution.states.push(state.clone());
298 solution.recommended_steps.push(step);
299 steps += 1;
300 }
301 Ok(solution)
302 }
303
304 fn validate(
305 &self,
306 dimension: usize,
307 start_time: f64,
308 initial_state: &[f64],
309 end_time: f64,
310 ) -> Result<(), SolverError> {
311 if dimension == 0 || dimension != initial_state.len() {
312 return Err(SolverError::InvalidInput(
313 "provide one RHS per state component and at least one component",
314 ));
315 }
316 if !start_time.is_finite() || !end_time.is_finite() || !(end_time - start_time).is_finite()
317 {
318 return Err(SolverError::InvalidInput(
319 "times and their difference must be finite",
320 ));
321 }
322 if !initial_state.iter().all(|x| x.is_finite()) {
323 return Err(SolverError::InvalidInput("initial state must be finite"));
324 }
325 if ![
326 self.initial_step,
327 self.min_step,
328 self.max_step,
329 self.tolerance,
330 self.relative_threshold,
331 ]
332 .iter()
333 .all(|v| v.is_finite() && *v > 0.0)
334 {
335 return Err(SolverError::InvalidInput(
336 "step sizes, tolerance, and relative threshold must be finite and positive",
337 ));
338 }
339 if self.min_step > self.initial_step || self.initial_step > self.max_step {
340 return Err(SolverError::InvalidInput(
341 "require min_step <= initial_step <= max_step",
342 ));
343 }
344 if self.max_steps == 0 {
345 return Err(SolverError::InvalidInput("max_steps must be positive"));
346 }
347 Ok(())
348 }
349}
350
351#[derive(Clone, Copy)]
352enum CallbackKind {
353 Rhs,
354 Jacobian,
355 TimeDerivative,
356 Matrix,
357 Forcing,
358}
359
360struct CallbackContext<'s, 'a> {
361 system: &'s OdeSystem<'a>,
362 jacobian: Vec<MathExpr<'a, f64>>,
363 time_derivative: Vec<MathExpr<'a, f64>>,
364 variables: HashMap<&'a str, f64>,
365 current_time: f64,
366 error: Option<SolverError>,
367}
368
369impl<'s, 'a> CallbackContext<'s, 'a> {
370 fn new(system: &'s OdeSystem<'a>, method: Method) -> Self {
371 let mut jacobian = Vec::new();
372 if matches!(
373 method,
374 Method::Lawson | Method::Rosenbrock | Method::RosenbrockAutonomous
375 ) {
376 for name in &system.names {
378 for expression in &system.rhs {
379 jacobian.push(expression.derive(name).simplify());
380 }
381 }
382 }
383 let time_derivative = if method == Method::Rosenbrock {
384 system
385 .rhs
386 .iter()
387 .map(|expression| match system.time {
388 Some(time) => expression.derive(time).simplify(),
389 None => MathExpr::new_const(0.0),
390 })
391 .collect()
392 } else {
393 Vec::new()
394 };
395 let variables = system
396 .names
397 .iter()
398 .copied()
399 .chain(system.time)
400 .map(|name| (name, 0.0))
401 .collect();
402 Self {
403 system,
404 jacobian,
405 time_derivative,
406 variables,
407 current_time: 0.0,
408 error: None,
409 }
410 }
411
412 fn evaluate(
413 &mut self,
414 time: f64,
415 state: &[f64],
416 derivative: &mut [f64],
417 kind: CallbackKind,
418 ) -> Result<(), SolverError> {
419 if !time.is_finite() || !state.iter().all(|x| x.is_finite()) {
420 return Err(SolverError::NonFiniteState { time });
421 }
422 for (&name, &value) in self.system.names.iter().zip(state) {
423 self.variables.insert(name, value);
424 }
425 if let Some(name) = self.system.time {
426 self.variables.insert(name, time);
427 }
428 let expressions = match kind {
429 CallbackKind::Rhs => &self.system.rhs,
430 CallbackKind::Jacobian => &self.jacobian,
431 CallbackKind::TimeDerivative => &self.time_derivative,
432 CallbackKind::Matrix => &self.system.matrix,
433 CallbackKind::Forcing => &self.system.forcing,
434 };
435 assert_eq!(expressions.len(), derivative.len());
436 for (equation, (expression, output)) in expressions.iter().zip(derivative).enumerate() {
437 let value =
438 expression
439 .evaluate(&self.variables)
440 .map_err(|error| SolverError::Evaluation {
441 equation,
442 message: format!("{error:?}"),
443 })?;
444 if !value.is_finite() {
445 return Err(SolverError::NonFiniteDerivative { equation, time });
446 }
447 *output = value;
448 }
449 Ok(())
450 }
451}