use alloc::vec;
use alloc::vec::Vec;
use nalgebra::{DMatrix, DVector};
use polyzonotope::{Interval, SparsePolyZonotope, Zonotope};
use super::{Attempt, NonlinearReach, Terms, polynomialization, split};
use crate::{Dynamics, ReachError, ReachFailure, Step};
#[derive(Clone, Debug, PartialEq)]
pub struct Adaptive {
pub min_step: f64,
pub max_step: f64,
pub shrink: f64,
pub grow: f64,
pub easy_guesses: usize,
}
impl Adaptive {
#[must_use]
pub fn new(min_step: f64, max_step: f64) -> Self {
Self {
min_step,
max_step,
shrink: 0.5,
grow: 1.25,
easy_guesses: 3,
}
}
pub(super) fn check(&self, step: f64) {
assert!(
self.min_step > 0.0 && self.max_step.is_finite(),
"adaptive steps must be positive and finite"
);
assert!(
self.min_step <= step && step <= self.max_step,
"the initial step must lie in [min_step, max_step]"
);
assert!(
self.shrink > 0.0 && self.shrink < 1.0,
"shrink must lie in (0, 1)"
);
assert!(self.grow >= 1.0, "grow must be at least 1");
}
}
#[derive(Clone, Copy, Debug)]
enum Horizon {
Steps(usize),
Time(f64),
}
struct Run {
flowpipe: Vec<Vec<Step>>,
pieces: Vec<SparsePolyZonotope>,
diverged: f64,
step: f64,
elapsed: f64,
}
struct Advanced {
steps: Vec<Step>,
narrowest: f64,
guesses: usize,
}
impl<D: Dynamics> NonlinearReach<D> {
pub fn reach(
&self,
x0: &SparsePolyZonotope,
u: &Zonotope,
steps: usize,
) -> Result<Vec<Vec<Step>>, ReachFailure> {
self.run(x0, u, Horizon::Steps(steps))
}
pub fn reach_for(
&self,
x0: &SparsePolyZonotope,
u: &Zonotope,
duration: f64,
) -> Result<Vec<Vec<Step>>, ReachFailure> {
assert!(
duration >= 0.0 && duration.is_finite(),
"duration must be non-negative and finite"
);
self.run(x0, u, Horizon::Time(duration))
}
pub fn step_autonomous(&self, x: &SparsePolyZonotope) -> Result<Step, ReachError> {
self.step(x, &self.no_input())
}
pub fn reach_autonomous(
&self,
x0: &SparsePolyZonotope,
steps: usize,
) -> Result<Vec<Vec<Step>>, ReachFailure> {
self.reach(x0, &self.no_input(), steps)
}
fn no_input(&self) -> Zonotope {
assert_eq!(
self.dynamics.inputs(),
0,
"an autonomous step needs dynamics without inputs"
);
Zonotope::new(DVector::zeros(0), DMatrix::zeros(0, 0))
}
fn run(
&self,
x0: &SparsePolyZonotope,
u: &Zonotope,
horizon: Horizon,
) -> Result<Vec<Vec<Step>>, ReachFailure> {
let mut run = Run {
flowpipe: Vec::new(),
pieces: vec![x0.clone()],
diverged: f64::INFINITY,
step: self.settings.step,
elapsed: 0.0,
};
while let Some(length) = next_length(horizon, &run) {
if let Err(error) = self.time_step(&mut run, u, length) {
return Err(ReachFailure {
proven: run.flowpipe,
error,
});
}
}
Ok(run.flowpipe)
}
fn time_step(&self, run: &mut Run, u: &Zonotope, mut length: f64) -> Result<(), ReachError> {
let adaptive = self.settings.adaptive.as_ref();
loop {
let shrinkable = adaptive.is_some_and(|a| length > a.min_step);
match self.advance(run.pieces.clone(), u, length, !shrinkable) {
Ok(advanced) => {
run.step = grown(adaptive, run.step.min(length), advanced.guesses);
run.elapsed += length;
run.diverged = run.diverged.min(advanced.narrowest);
run.pieces = self.next_pieces(&advanced.steps, 0.5 * run.diverged);
run.flowpipe.push(advanced.steps);
return Ok(());
}
Err(ReachError::AbstractionDiverged | ReachError::StepTooLarge) if shrinkable => {
length = adaptive.map_or(length, |a| (length * a.shrink).max(a.min_step));
}
Err(e) => return Err(e),
}
}
}
fn advance(
&self,
mut todo: Vec<SparsePolyZonotope>,
u: &Zonotope,
length: f64,
may_split: bool,
) -> Result<Advanced, ReachError> {
let attempt = Attempt {
step: length,
terms: Terms::ALL,
};
let mut done = Advanced {
steps: Vec::with_capacity(todo.len()),
narrowest: f64::INFINITY,
guesses: 0,
};
while let Some(piece) = todo.pop() {
match self.step_with(&piece, u, attempt) {
Ok((step, guesses)) => {
done.guesses = done.guesses.max(guesses);
done.steps.push(step);
}
Err(ReachError::AbstractionDiverged)
if may_split
&& done.steps.len() + todo.len() + 2 <= self.settings.max_pieces =>
{
done.narrowest = done.narrowest.min(split::width(&piece));
let (lower, upper) =
split::halves(&piece, |p| self.curvature(p, u), self.settings.splitting)
.ok_or(ReachError::AbstractionDiverged)?;
todo.push(lower);
todo.push(upper);
}
Err(e) => return Err(e),
}
}
Ok(done)
}
fn curvature(&self, x: &SparsePolyZonotope, u: &Zonotope) -> f64 {
let region: Vec<Interval> = x
.interval_hull()
.0
.into_iter()
.chain(u.interval_hull().0)
.collect();
let radius: Vec<f64> = region.iter().map(|iv| 0.5 * iv.width()).collect();
let w = radius.len();
let bound: f64 = self
.dynamics
.hessians(®ion)
.iter()
.flat_map(|h| {
let radius = &radius;
(0..w).flat_map(move |a| {
(0..w).map(move |b| h.0[(a, b)].mag() * radius[a] * radius[b])
})
})
.sum();
if bound.is_nan() { f64::INFINITY } else { bound }
}
fn next_pieces(&self, steps: &[Step], cap: f64) -> Vec<SparsePolyZonotope> {
let pieces = steps.iter().map(|s| s.time_point.clone()).collect();
split::merge(pieces, self.settings.merge_tolerance, cap, |merged| {
self.restructure(&polynomialization::cap_degree(
merged,
self.settings.max_degree,
))
})
}
}
fn next_length(horizon: Horizon, run: &Run) -> Option<f64> {
match horizon {
Horizon::Steps(n) => (run.flowpipe.len() < n).then_some(run.step),
Horizon::Time(t) => {
let left = t - run.elapsed;
let length = if left <= run.step * (1.0 + 1e-9) {
left
} else {
run.step
};
(left > 0.0).then_some(length)
}
}
}
fn grown(adaptive: Option<&Adaptive>, step: f64, guesses: usize) -> f64 {
match adaptive {
Some(a) if guesses <= a.easy_guesses => (step * a.grow).min(a.max_step),
_ => step,
}
}