Skip to main content

differential_equations/problem/
function.rs

1use ndarray::{Array, ArrayView, Dimension};
2
3use crate::SolveError;
4
5/// A statically dispatched, fallible ODE right-hand side.
6///
7/// Existing in-place closures `Fn(&mut [f64], &[f64], &P, f64)` implement this
8/// automatically. Ndarray out-of-place constructors use this same interface
9/// to validate returned shapes before copying derivatives into solver storage.
10/// Custom implementations may return a [`SolveError`] without panicking.
11pub trait OdeFunction<P> {
12    /// Overwrites the entire derivative buffer at the supplied state and time.
13    ///
14    /// The derivative and state buffers have the same dimension. Implementations
15    /// must not mutate parameters that affect the equations during evaluation;
16    /// callbacks provide the supported mechanism for those changes.
17    fn evaluate(
18        &self,
19        derivative: &mut [f64],
20        state: &[f64],
21        parameters: &P,
22        time: f64,
23    ) -> Result<(), SolveError>;
24}
25
26impl<F, P> OdeFunction<P> for F
27where
28    F: Fn(&mut [f64], &[f64], &P, f64),
29{
30    fn evaluate(
31        &self,
32        derivative: &mut [f64],
33        state: &[f64],
34        parameters: &P,
35        time: f64,
36    ) -> Result<(), SolveError> {
37        self(derivative, state, parameters, time);
38        Ok(())
39    }
40}
41
42pub(super) struct ArrayFunction<F, D> {
43    pub(super) rhs: F,
44    pub(super) shape: D,
45}
46
47impl<F, P, D> OdeFunction<P> for ArrayFunction<F, D>
48where
49    D: Dimension,
50    F: for<'a> Fn(ArrayView<'a, f64, D>, &P, f64) -> Array<f64, D>,
51{
52    fn evaluate(
53        &self,
54        derivative: &mut [f64],
55        state: &[f64],
56        parameters: &P,
57        time: f64,
58    ) -> Result<(), SolveError> {
59        let state = ArrayView::from_shape(self.shape.clone(), state)
60            .map_err(|_| SolveError::DerivativeShapeMismatch)?;
61        let result = (self.rhs)(state, parameters, time);
62        if result.raw_dim() != self.shape || result.len() != derivative.len() {
63            return Err(SolveError::DerivativeShapeMismatch);
64        }
65        // Iteration follows logical axis order even for a non-contiguous or
66        // column-major result. Solvers always use contiguous row-major storage.
67        for (output, value) in derivative.iter_mut().zip(result.iter()) {
68            *output = *value;
69        }
70        Ok(())
71    }
72}
73
74/// Sequential adapter for a mutable, fallible in-place right-hand side.
75///
76/// Construct with [`OdeProblem::new_fallible`](crate::OdeProblem::new_fallible).
77/// The adapter owns the interior mutability required by the existing shared
78/// problem solve interface; callers can capture ordinary mutable references.
79/// It is `Send` when `F` is `Send`, but is deliberately not `Sync`.
80/// Use independent problems per worker, or the reusable stepper for direct
81/// exclusive closure access without interior mutability.
82pub struct MutableFunction<F>(std::cell::RefCell<F>);
83
84impl<F> MutableFunction<F> {
85    pub(crate) fn new(function: F) -> Self {
86        Self(std::cell::RefCell::new(function))
87    }
88    /// Returns the closure, including any accumulated mutable state.
89    pub fn into_inner(self) -> F {
90        self.0.into_inner()
91    }
92}
93
94impl<F, P> OdeFunction<P> for MutableFunction<F>
95where
96    F: FnMut(&mut [f64], &[f64], &P, f64) -> Result<(), SolveError>,
97{
98    fn evaluate(
99        &self,
100        derivative: &mut [f64],
101        state: &[f64],
102        parameters: &P,
103        time: f64,
104    ) -> Result<(), SolveError> {
105        (self.0.borrow_mut())(derivative, state, parameters, time)
106    }
107}