use polyzonotope::{Polytope, SparsePolyZonotope};
use crate::{Obstacles, SafetyVerdict, Witness};
pub trait Reach<const N: usize> {
type Control: Clone;
fn propagate(
&self,
initial: &SparsePolyZonotope,
control: &Self::Control,
cover: &mut Vec<SparsePolyZonotope>,
) -> SparsePolyZonotope;
fn certify_collision(
&self,
initial: &SparsePolyZonotope,
control: &Self::Control,
set: &SparsePolyZonotope,
obstacle: &Polytope,
) -> Option<Vec<f64>> {
let _ = (initial, control, set, obstacle);
None
}
}
pub fn check_edge<R: Reach<N>, const N: usize>(
reach: &R,
obstacles: &Obstacles,
initial: &SparsePolyZonotope,
control: &R::Control,
cover: &mut Vec<SparsePolyZonotope>,
) -> (SafetyVerdict, SparsePolyZonotope) {
cover.clear();
let end = reach.propagate(initial, control, cover);
if cover.is_empty() {
return (SafetyVerdict::Indeterminate, end);
}
let verdict = match obstacles.check_sets(cover) {
SafetyVerdict::Safe => SafetyVerdict::Safe,
unproven => find_witness(reach, obstacles, initial, control, cover)
.map_or(unproven, SafetyVerdict::Unsafe),
};
(verdict, end)
}
fn find_witness<R: Reach<N>, const N: usize>(
reach: &R,
obstacles: &Obstacles,
initial: &SparsePolyZonotope,
control: &R::Control,
cover: &[SparsePolyZonotope],
) -> Option<Witness> {
cover.iter().enumerate().find_map(|(set_index, set)| {
obstacles
.polytopes()
.iter()
.enumerate()
.find_map(|(obstacle_index, obstacle)| {
let point = reach.certify_collision(initial, control, set, obstacle)?;
is_plausible(&point, set, obstacle).then_some(Witness {
point,
set: set_index,
obstacle: obstacle_index,
})
})
})
}
fn is_plausible(point: &[f64], set: &SparsePolyZonotope, obstacle: &Polytope) -> bool {
let hull = set.interval_hull();
let in_hull = point.len() == hull.dim()
&& point
.iter()
.zip(&hull.0)
.all(|(x, range)| range.contains(*x, 0.0));
let in_obstacle = obstacle.facets.iter().all(|h| {
h.normal.len() == point.len()
&& h.normal.iter().zip(point).map(|(a, x)| a * x).sum::<f64>() <= h.offset
});
in_hull && in_obstacle
}