use alloc::vec;
use alloc::vec::Vec;
use nalgebra::{DMatrix, DVector};
use polyzonotope::{Interval, IntervalBox, Reduction, SparsePolyZonotope, Zonotope};
use crate::{Dynamics, LinearReach, LinearSystem, ReachError, Step};
mod driver;
mod error;
mod polynomialization;
mod split;
pub use driver::Adaptive;
#[cfg(test)]
mod ablation;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Method {
#[default]
Linearization,
Polynomialization,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Splitting {
#[default]
Cheapest,
Factors,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Restructure {
#[default]
Off,
Lift,
}
#[derive(Clone, Debug, PartialEq)]
pub struct NonlinearSettings {
pub step: f64,
pub taylor_terms: usize,
pub order: f64,
pub max_iterations: usize,
pub enlarge: f64,
pub max_pieces: usize,
pub splitting: Splitting,
pub method: Method,
pub merge_tolerance: f64,
pub max_degree: u32,
pub restructure: Restructure,
pub adaptive: Option<Adaptive>,
}
impl NonlinearSettings {
#[must_use]
pub fn new(step: f64) -> Self {
Self {
step,
taylor_terms: 4,
order: 20.0,
max_iterations: 10,
enlarge: 0.1,
max_pieces: 8,
splitting: Splitting::Cheapest,
method: Method::Linearization,
merge_tolerance: 0.1,
max_degree: 4,
restructure: Restructure::Off,
adaptive: None,
}
}
}
pub struct NonlinearReach<D> {
dynamics: D,
settings: NonlinearSettings,
}
pub(crate) struct Linearization {
point: Vec<f64>,
middle: Vec<f64>,
a: DMatrix<f64>,
b: DMatrix<f64>,
offset: Vec<Interval>,
jacobian_radius: DMatrix<f64>,
}
impl<D: Dynamics> NonlinearReach<D> {
#[must_use]
pub fn new(dynamics: D, settings: NonlinearSettings) -> Self {
assert!(
settings.step > 0.0 && settings.step.is_finite(),
"step must be positive"
);
assert!(settings.order >= 1.0, "order must be at least 1");
assert!(settings.enlarge >= 0.0, "enlarge must not be negative");
assert!(
settings.merge_tolerance >= 0.0,
"merge_tolerance must not be negative"
);
assert!(
settings.max_iterations >= 1,
"max_iterations must be at least 1"
);
assert!(settings.max_pieces >= 1, "max_pieces must be at least 1");
assert!(settings.max_degree >= 1, "max_degree must be at least 1");
if let Some(adaptive) = &settings.adaptive {
adaptive.check(settings.step);
}
Self { dynamics, settings }
}
pub fn step(&self, x: &SparsePolyZonotope, u: &Zonotope) -> Result<Step, ReachError> {
let attempt = Attempt {
step: self.settings.step,
terms: Terms::ALL,
};
self.step_with(x, u, attempt).map(|(step, _)| step)
}
fn step_with(
&self,
x: &SparsePolyZonotope,
u: &Zonotope,
attempt: Attempt,
) -> Result<(Step, usize), ReachError> {
assert_eq!(x.dim(), self.dynamics.states(), "x needs one row per state");
assert_eq!(u.dim(), self.dynamics.inputs(), "u needs one row per input");
let model = self
.linearize(x, u, attempt.step)
.ok_or(ReachError::AbstractionDiverged)?;
match self.settings.method {
Method::Linearization => self.step_linearized(x, u, &model, attempt),
Method::Polynomialization => self.step_polynomialized(x, u, &model, attempt),
}
}
fn step_linearized(
&self,
x: &SparsePolyZonotope,
u: &Zonotope,
model: &Linearization,
attempt: Attempt,
) -> Result<(Step, usize), ReachError> {
let n = self.dynamics.states();
let system = LinearSystem {
a: model.a.clone(),
b: DMatrix::identity(n, n),
};
let linear = LinearReach::new(system, attempt.step, self.settings.taylor_terms)?;
let known = u.linear_map(&model.b);
self.confirm(n, attempt.step, |assumed| {
let step = linear.step(x, &with_error(&known, &model.offset, assumed));
let states = step
.time_interval
.reduce(self.settings.order, Reduction::Girard);
let actual =
error::abstraction_error(&self.dynamics, model, (&states, u), attempt.terms)
.ok_or(ReachError::AbstractionDiverged)?;
Ok((step.time_point, states, actual))
})
}
fn step_polynomialized(
&self,
x: &SparsePolyZonotope,
u: &Zonotope,
model: &Linearization,
attempt: Attempt,
) -> Result<(Step, usize), ReachError> {
let n = self.dynamics.states();
let limits = (self.settings.max_degree, self.settings.order);
let expansion =
polynomialization::static_error(&self.dynamics, model, x, limits, attempt.terms)?;
let start = if attempt.terms.has(Term::StaticSet) {
polynomialization::augmented_start(x, &expansion.static_set)
} else {
polynomialization::augmented_start(
x,
&SparsePolyZonotope::from_zonotope(&Zonotope::new(
DVector::zeros(n),
DMatrix::zeros(n, 0),
)),
)
};
let system = polynomialization::augmented_system(&model.a);
let linear = LinearReach::new(system, attempt.step, self.settings.taylor_terms)?;
let known = u.linear_map(&model.b);
self.confirm(n, attempt.step, |assumed| {
let step = linear.step(&start, &with_error(&known, &model.offset, assumed));
let states = polynomialization::project(&step.time_interval, n)
.reduce(self.settings.order, Reduction::Girard);
let drift = polynomialization::drift(&step.time_interval, n);
let actual = polynomialization::dynamic_error(
&self.dynamics,
(model, &expansion),
(&states, &drift, u),
attempt.step,
attempt.terms,
)?;
Ok((
polynomialization::project(&step.time_point, n),
states,
actual,
))
})
}
fn restructure(&self, set: &SparsePolyZonotope) -> SparsePolyZonotope {
let reduced = set.reduce(self.settings.order, Reduction::Girard);
match self.settings.restructure {
Restructure::Off => reduced,
Restructure::Lift => split::lift_independent(&reduced),
}
}
fn confirm(
&self,
n: usize,
step: f64,
mut attempt: impl FnMut(
&[Interval],
) -> Result<
(SparsePolyZonotope, SparsePolyZonotope, Vec<Interval>),
ReachError,
>,
) -> Result<(Step, usize), ReachError> {
let mut assumed = vec![Interval::point(0.0); n];
for guesses in 1..=self.settings.max_iterations {
let (time_point, time_interval, actual) = attempt(&assumed)?;
if encloses(&assumed, &actual) {
let step = Step {
time_point: self.restructure(&time_point),
time_interval,
duration: step,
};
return Ok((step, guesses));
}
assumed = widen(&assumed, &actual, self.settings.enlarge);
if !all_finite(assumed.iter()) {
break;
}
}
Err(ReachError::AbstractionDiverged)
}
fn linearize(&self, x: &SparsePolyZonotope, u: &Zonotope, step: f64) -> Option<Linearization> {
let n = self.dynamics.states();
let middle: Vec<f64> = x
.interval_hull()
.0
.iter()
.map(|iv| f64::midpoint(iv.lo, iv.hi))
.collect();
let inputs = u.center().iter().copied();
let drift = self
.dynamics
.flow(&points(middle.iter().copied().chain(inputs.clone())));
let point: Vec<f64> = middle
.iter()
.zip(&drift)
.map(|(&m, d)| m + 0.5 * step * f64::midpoint(d.lo, d.hi))
.chain(inputs)
.collect();
if !point.iter().all(|v| v.is_finite()) {
return None;
}
let at = points(point.iter().copied());
let jacobian = self.dynamics.jacobian(&at);
let flow = self.dynamics.flow(&at);
if !all_finite(jacobian.0.iter()) || !all_finite(flow.iter()) {
return None;
}
let (jacobian, jacobian_radius) = jacobian.center_radius();
let offset = model_offset(&flow, &jacobian, &point)?;
if !all_finite(offset.iter()) {
return None;
}
Some(Linearization {
a: jacobian.columns(0, n).into_owned(),
b: jacobian.columns(n, point.len() - n).into_owned(),
point,
middle,
offset,
jacobian_radius,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Attempt {
pub(crate) step: f64,
pub(crate) terms: Terms,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Term {
Quadratic,
HessianSpread,
JacobianSpread,
StaticSet,
StaticRadius,
Cross,
DynamicQuadratic,
CubicStatic,
CubicCross,
Remainder,
InputDeviation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Terms(u16);
impl Terms {
pub(crate) const ALL: Self = Self(u16::MAX);
pub(crate) fn has(self, term: Term) -> bool {
self.0 & Self::bit(term) != 0
}
#[cfg(test)]
pub(crate) fn without(self, term: Term) -> Self {
Self(self.0 & !Self::bit(term))
}
fn bit(term: Term) -> u16 {
1 << term as u16
}
}
fn all_finite<'a>(mut intervals: impl Iterator<Item = &'a Interval>) -> bool {
intervals.all(|iv| iv.lo.is_finite() && iv.hi.is_finite())
}
fn points(values: impl Iterator<Item = f64>) -> Vec<Interval> {
values.map(Interval::point).collect()
}
fn model_offset(
flow: &[Interval],
jacobian: &DMatrix<f64>,
point: &[f64],
) -> Option<Vec<Interval>> {
flow.iter()
.enumerate()
.map(|(i, &f)| {
point.iter().enumerate().try_fold(f, |acc, (j, &z)| {
let term = Interval::point(jacobian[(i, j)]) * Interval::point(z);
all_finite([acc, term].iter()).then(|| acc - term)
})
})
.collect()
}
fn with_error(known: &Zonotope, offset: &[Interval], assumed: &[Interval]) -> Zonotope {
let total = offset.iter().zip(assumed).map(|(&w, &e)| w + e).collect();
known.minkowski_sum(&Zonotope::from_box(&IntervalBox(total)))
}
fn encloses(assumed: &[Interval], actual: &[Interval]) -> bool {
assumed
.iter()
.zip(actual)
.all(|(a, e)| a.lo <= e.lo && e.hi <= a.hi)
}
fn widen(assumed: &[Interval], actual: &[Interval], enlarge: f64) -> Vec<Interval> {
assumed
.iter()
.zip(actual)
.map(|(a, e)| {
let hull = Interval::new(a.lo.min(e.lo), a.hi.max(e.hi));
let margin = enlarge * hull.mag();
Interval::new(hull.lo - margin, hull.hi + margin)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overflowing_offset_is_refused() {
let jacobian = DMatrix::from_row_slice(1, 2, &[1e300, 1.0]);
let flow = [Interval::point(1.0)];
assert_eq!(model_offset(&flow, &jacobian, &[1e10, 1.0]), None);
assert_eq!(
model_offset(&flow, &jacobian, &[1.0, 1.0]),
Some(vec![
Interval::point(1.0) - Interval::point(1e300) - Interval::point(1.0)
])
);
}
#[test]
fn widening_covers_both() {
let w = widen(&[Interval::new(-1.0, 1.0)], &[Interval::new(0.0, 2.0)], 0.5);
assert_eq!(w, vec![Interval::new(-2.0, 3.0)]);
assert!(encloses(&w, &[Interval::new(-1.0, 2.0)]));
assert!(!encloses(&w, &[Interval::new(-1.0, 3.5)]));
}
}