use alloc::vec::Vec;
use nalgebra::DMatrix;
use polyzonotope::{Interval, IntervalBox, IntervalMatrix, SparsePolyZonotope, Zonotope};
use super::{Linearization, Term, Terms, all_finite};
use crate::Dynamics;
pub(super) fn abstraction_error<D: Dynamics>(
dynamics: &D,
model: &Linearization,
(states, u): (&SparsePolyZonotope, &Zonotope),
terms: Terms,
) -> Option<Vec<Interval>> {
let deviation = deviation(states, u, &model.point);
let hull = deviation.interval_hull();
if !all_finite(hull.0.iter()) {
return None;
}
let hessians = dynamics.hessians(&segment_box(&hull, &model.point));
let magnitude: Vec<Interval> = hull.0.iter().map(|iv| Interval::point(iv.mag())).collect();
if !hessians.iter().all(|h| quadratic_fits(h, &magnitude)) {
return None;
}
let (quadratic, radii): (Vec<_>, Vec<_>) = hessians
.iter()
.map(|h| h.scale(Interval::point(0.5)).center_radius())
.unzip();
let polynomial = deviation.quadratic_map(&quadratic).interval_hull();
let error: Vec<Interval> = polynomial
.0
.iter()
.enumerate()
.map(|(i, &q)| {
let parts = [
(Term::Quadratic, q),
(
Term::HessianSpread,
symmetric(hessian_radius(&radii[i], &magnitude)),
),
(
Term::JacobianSpread,
symmetric(jacobian_radius(&model.jacobian_radius, i, &magnitude)),
),
];
parts
.iter()
.filter(|(term, _)| terms.has(*term))
.fold(Interval::point(0.0), |acc, &(_, v)| acc + v)
})
.collect();
all_finite(error.iter()).then_some(error)
}
pub(super) fn deviation(
states: &SparsePolyZonotope,
u: &Zonotope,
point: &[f64],
) -> SparsePolyZonotope {
let n = states.dim();
let shift = |v: &[f64]| -nalgebra::DVector::from_column_slice(v);
let dx = states.translate(&shift(&point[..n]));
if u.dim() == 0 {
return dx;
}
dx.cartesian_product(&SparsePolyZonotope::from_zonotope(u).translate(&shift(&point[n..])))
}
pub(super) fn segment_box(hull: &IntervalBox, point: &[f64]) -> Vec<Interval> {
hull.0
.iter()
.zip(point)
.map(|(iv, &z)| Interval::new(iv.lo.min(0.0), iv.hi.max(0.0)) + Interval::point(z))
.collect()
}
fn hessian_radius(hessian: &DMatrix<f64>, magnitude: &[Interval]) -> f64 {
(0..magnitude.len())
.fold(Interval::point(0.0), |acc, a| {
(0..magnitude.len()).fold(acc, |acc, b| {
acc + Interval::point(hessian[(a, b)]) * magnitude[a] * magnitude[b]
})
})
.hi
}
fn jacobian_radius(jacobian: &DMatrix<f64>, row: usize, magnitude: &[Interval]) -> f64 {
(0..magnitude.len())
.fold(Interval::point(0.0), |acc, j| {
acc + Interval::point(jacobian[(row, j)]) * magnitude[j]
})
.hi
}
fn symmetric(r: f64) -> Interval {
Interval::new(-r, r)
}
const ERROR_LIMIT: f64 = 1e100;
fn quadratic_fits(hessian: &IntervalMatrix, magnitude: &[Interval]) -> bool {
let bound: f64 = (0..magnitude.len())
.flat_map(|a| (0..magnitude.len()).map(move |b| (a, b)))
.map(|(a, b)| hessian.0[(a, b)].mag() * magnitude[a].hi * magnitude[b].hi)
.sum();
bound < ERROR_LIMIT
}