use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Direction {
Rising,
Falling,
Both,
}
type EventFn = dyn Fn(f64, &[f64]) -> f64;
pub struct Event {
g: Box<EventFn>,
direction: Direction,
terminal: bool,
}
impl fmt::Debug for Event {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Event")
.field("direction", &self.direction)
.field("terminal", &self.terminal)
.finish_non_exhaustive()
}
}
impl Event {
pub fn new<G>(g: G) -> Self
where
G: Fn(f64, &[f64]) -> f64 + 'static,
{
Self {
g: Box::new(g),
direction: Direction::Both,
terminal: false,
}
}
#[must_use]
pub fn direction(mut self, direction: Direction) -> Self {
self.direction = direction;
self
}
#[must_use]
pub fn terminal(mut self) -> Self {
self.terminal = true;
self
}
pub(crate) fn eval(&self, t: f64, y: &[f64]) -> f64 {
(self.g)(t, y)
}
pub(crate) fn is_terminal(&self) -> bool {
self.terminal
}
pub(crate) fn crossing(&self, g_old: f64, g_new: f64) -> Option<Direction> {
let rising = g_old < 0.0 && g_new >= 0.0;
let falling = g_old > 0.0 && g_new <= 0.0;
let dir = if rising {
Direction::Rising
} else if falling {
Direction::Falling
} else {
return None;
};
match self.direction {
Direction::Both => Some(dir),
wanted if wanted == dir => Some(dir),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EventHit {
pub index: usize,
pub t: f64,
pub y: Vec<f64>,
pub direction: Direction,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EventSolution {
pub t_end: f64,
pub y_end: Vec<f64>,
pub hits: Vec<EventHit>,
}
pub(crate) fn bisect_root(mut a: f64, mut ha: f64, mut b: f64, h: impl Fn(f64) -> f64) -> f64 {
for _ in 0..200 {
let tol = 4.0 * f64::EPSILON * a.abs().max(b.abs()).max(f64::MIN_POSITIVE);
if (b - a).abs() <= tol {
break;
}
let m = 0.5 * (a + b);
let hm = h(m);
if hm == 0.0 {
return m;
}
if (hm < 0.0) == (ha < 0.0) {
a = m;
ha = hm;
} else {
b = m;
}
}
let hb = h(b);
if hb.abs() <= ha.abs() { b } else { a }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crossing_respects_direction() {
let rising = Event::new(|_, _| 0.0).direction(Direction::Rising);
assert_eq!(rising.crossing(-1.0, 1.0), Some(Direction::Rising));
assert_eq!(rising.crossing(1.0, -1.0), None);
assert_eq!(rising.crossing(1.0, 1.0), None);
let any = Event::new(|_, _| 0.0);
assert_eq!(any.crossing(1.0, -1.0), Some(Direction::Falling));
assert_eq!(any.crossing(0.0, 1.0), None);
}
#[test]
fn bisection_locates_sqrt2() {
let root = bisect_root(1.0, -1.0, 2.0, |t| t * t - 2.0);
assert!((root - 2f64.sqrt()).abs() < 1e-12);
}
}