use alloc::vec;
use alloc::vec::Vec;
use nalgebra::{DMatrix, DVector};
use polyzonotope::{IntervalBox, SparsePolyZonotope, Zonotope};
use super::{Method, NonlinearReach, NonlinearSettings, Term, Terms};
use crate::Polynomial;
type Field = fn(&[f64; 2], f64) -> [f64; 2];
const TOL: f64 = 1e-9;
const SUBSTEPS: u32 = 40;
const SAMPLES: usize = 24;
struct Scenario {
dynamics: Polynomial,
field: Field,
center: [f64; 2],
radius: f64,
input: f64,
step: f64,
steps: usize,
}
impl Scenario {
fn escapes(&self, method: Method, terms: Terms) -> bool {
self.escapes_within(method, terms).0
}
fn escapes_within(&self, method: Method, terms: Terms) -> (bool, usize) {
let settings = NonlinearSettings {
taylor_terms: 12,
max_pieces: 1,
method,
..NonlinearSettings::new(self.step)
};
let reach = NonlinearReach::new(self.dynamics.clone(), settings);
let u = Zonotope::new(DVector::zeros(1), DMatrix::from_element(1, 1, self.input));
let mut x = start_box(self.center, self.radius);
let mut sets = Vec::with_capacity(self.steps);
for _ in 0..self.steps {
let Ok((step, _)) = reach.step_with(
&x,
&u,
super::Attempt {
step: self.step,
terms,
},
) else {
break;
};
sets.push((
Enclosure::of(&step.time_interval),
Enclosure::of(&step.time_point),
));
x = step.time_point;
}
let escaped = (0..SAMPLES).any(|s| self.sample_escapes(s, &sets));
(escaped, sets.len())
}
fn sample_escapes(&self, s: usize, sets: &[(Enclosure, Enclosure)]) -> bool {
let mut rng = Lcg(u64::try_from(s).expect("small") + 11);
let mut x = [0.0; 2];
for (i, xi) in x.iter_mut().enumerate() {
let corner = if (s >> i) & 1 == 0 { -1.0 } else { 1.0 };
*xi = self.center[i] + self.radius * if s < 4 { corner } else { rng.next() };
}
let h = self.step / f64::from(SUBSTEPS);
for (during, end) in sets {
for _ in 0..SUBSTEPS {
let u = match s % 3 {
0 => self.input,
1 => -self.input,
_ if rng.next() < 0.0 => -self.input,
_ => self.input,
};
x = rk4(self.field, &x, u, h);
if !during.holds(&x) {
return true;
}
}
if !end.holds(&x) {
return true;
}
}
false
}
fn shows(&self, method: Method, term: Term) {
let (escaped, converged) = self.escapes_within(method, Terms::ALL);
assert_eq!(converged, self.steps, "the full error must converge");
assert!(!escaped, "the full error must hold");
assert!(
self.escapes(method, Terms::ALL.without(term)),
"dropping {term:?} must let a trajectory escape"
);
}
}
struct Enclosure {
hull: IntervalBox,
zonotope: Zonotope,
}
impl Enclosure {
fn of(set: &SparsePolyZonotope) -> Self {
Self {
hull: set.interval_hull(),
zonotope: set.to_zonotope(),
}
}
fn holds(&self, x: &[f64; 2]) -> bool {
let p = DVector::from_column_slice(x);
let z = &self.zonotope;
self.hull.contains(&p, TOL)
&& (0..32).all(|k| {
let angle = core::f64::consts::TAU * f64::from(k) / 32.0;
let d = DVector::from_vec(vec![libm::cos(angle), libm::sin(angle)]);
let support = d.dot(z.center()) + (d.transpose() * z.generators()).abs().sum();
d.dot(&p) <= support + TOL
})
}
}
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> f64 {
self.0 = self
.0
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
#[expect(clippy::cast_precision_loss, reason = "the top 53 bits fit exactly")]
let unit = (self.0 >> 11) as f64 / (1u64 << 53) as f64;
2.0 * unit - 1.0
}
}
fn rk4(f: Field, x: &[f64; 2], u: f64, h: f64) -> [f64; 2] {
let at = |base: &[f64; 2], k: &[f64; 2], c: f64| [base[0] + c * k[0], base[1] + c * k[1]];
let k1 = f(x, u);
let k2 = f(&at(x, &k1, h / 2.0), u);
let k3 = f(&at(x, &k2, h / 2.0), u);
let k4 = f(&at(x, &k3, h), u);
[0, 1].map(|i| x[i] + h / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
}
fn start_box(center: [f64; 2], radius: f64) -> SparsePolyZonotope {
SparsePolyZonotope::from_zonotope(&Zonotope::new(
DVector::from_column_slice(¢er),
DMatrix::from_diagonal_element(2, 2, radius),
))
}
fn van_der_pol() -> Polynomial {
Polynomial::new(2, 1)
.term(0, 1.0, &[0, 1, 0])
.term(1, 1.0, &[0, 1, 0])
.term(1, -1.0, &[2, 1, 0])
.term(1, -1.0, &[1, 0, 0])
.term(1, 1.0, &[0, 0, 1])
}
fn van_der_pol_f64(x: &[f64; 2], u: f64) -> [f64; 2] {
[x[1], (1.0 - x[0] * x[0]) * x[1] - x[0] + u]
}
fn wide_van_der_pol() -> Scenario {
Scenario {
dynamics: van_der_pol(),
field: van_der_pol_f64,
center: [1.4, 2.4],
radius: 0.2,
input: 0.0,
step: 0.02,
steps: 20,
}
}
fn point_van_der_pol() -> Scenario {
Scenario {
radius: 0.0,
step: 0.05,
..wide_van_der_pol()
}
}
fn cubic() -> Scenario {
Scenario {
dynamics: Polynomial::new(2, 1)
.term(0, 1.0, &[3, 0, 0])
.term(1, -1.0, &[0, 1, 0]),
field: |x, _| [x[0] * x[0] * x[0], -x[1]],
center: [0.0, 0.0],
radius: 0.5,
input: 0.0,
step: 0.05,
steps: 10,
}
}
fn quartic() -> Scenario {
Scenario {
dynamics: Polynomial::new(2, 1)
.term(0, 1.0, &[4, 0, 0])
.term(1, -1.0, &[0, 1, 0]),
field: |x, _| [x[0] * x[0] * x[0] * x[0], -x[1]],
radius: 0.3,
..cubic()
}
}
fn shear() -> Scenario {
Scenario {
dynamics: Polynomial::new(2, 1)
.term(0, 1.0, &[1, 1, 0])
.term(1, 1.0, &[0, 0, 0])
.term(1, 1.0, &[1, 0, 0]),
field: |x, _| [x[0] * x[1], 1.0 + x[0]],
center: [0.0, 0.0],
radius: 0.2,
input: 0.0,
step: 0.05,
steps: 20,
}
}
fn modulated() -> Scenario {
Scenario {
dynamics: Polynomial::new(2, 1).term(1, 1.0, &[1, 0, 1]),
field: |x, u| [0.0, x[0] * u],
center: [1.0, 0.0],
radius: 0.5,
input: 0.5,
step: 0.05,
steps: 20,
}
}
#[test]
fn linearization_needs_the_quadratic_error() {
wide_van_der_pol().shows(Method::Linearization, Term::Quadratic);
}
#[test]
fn linearization_needs_the_hessian_spread() {
Scenario {
radius: 0.3,
..cubic()
}
.shows(Method::Linearization, Term::HessianSpread);
}
#[test]
fn polynomialization_needs_the_static_set() {
wide_van_der_pol().shows(Method::Polynomialization, Term::StaticSet);
}
#[test]
fn polynomialization_needs_the_cross_term() {
shear().shows(Method::Polynomialization, Term::Cross);
}
#[test]
fn polynomialization_needs_the_dynamic_quadratic() {
point_van_der_pol().shows(Method::Polynomialization, Term::DynamicQuadratic);
}
#[test]
fn polynomialization_needs_the_cubic_static_set() {
cubic().shows(Method::Polynomialization, Term::CubicStatic);
}
#[test]
fn polynomialization_needs_the_cubic_change() {
cubic().shows(Method::Polynomialization, Term::CubicCross);
}
#[test]
fn polynomialization_needs_the_remainder() {
quartic().shows(Method::Polynomialization, Term::Remainder);
}
#[test]
fn polynomialization_needs_the_input_deviation() {
modulated().shows(Method::Polynomialization, Term::InputDeviation);
}