Skip to main content

robust_planning/
reach.rs

1//! Reachable sets along one edge: the seam to the dynamics model.
2
3use polyzonotope::{Polytope, SparsePolyZonotope};
4
5use crate::{Obstacles, SafetyVerdict, Witness};
6
7/// Over-approximates the reachable set of a system along one edge.
8///
9/// Implement it for your dynamics model, for example on top of `polyzonotope-reach`, whose
10/// time-interval sets are cover sets and whose time-point sets are end sets. States are points in `N` dimensions; the reachable sets live in the
11/// same space. Planners also need a [`Steer`](crate::Steer) implementation for
12/// [`Reach::Control`]: implement it on the model, or pair the model with a steering function
13/// through [`WithSteering`](crate::WithSteering).
14///
15/// # Contract
16///
17/// [`Reach::propagate`] must over-approximate: every state the real system can occupy while
18/// it executes the control, including between time steps, must lie in one of the cover sets,
19/// and every state it can end in must lie in the returned end set. Planners prove safety from
20/// these sets only, so an under-approximation makes their proofs void. A model that cannot
21/// enclose an edge, for example because its integrator refuses a step, returns `None`
22/// instead of a set it has not proven.
23pub trait Reach<const N: usize> {
24    /// What drives the system along one edge, for example a sequence of nominal inputs.
25    type Control: Clone;
26
27    /// Propagates `initial` under `control`.
28    ///
29    /// Appends sets to `cover` that together contain every state on the way, from the start
30    /// of the edge to its end, in time order. Returns the set of states at the end of the
31    /// edge, which becomes the next edge's `initial`.
32    ///
33    /// Returns `None` if the model cannot enclose the whole edge. The sets it appended before
34    /// giving up stay in `cover` and are still sound, but they do not reach the end of the
35    /// edge, so [`check_edge`] answers [`SafetyVerdict::Indeterminate`].
36    fn propagate(
37        &self,
38        initial: &SparsePolyZonotope,
39        control: &Self::Control,
40        cover: &mut Vec<SparsePolyZonotope>,
41    ) -> Option<SparsePolyZonotope>;
42
43    /// Certifies a state the real system reaches in `set` that lies inside `obstacle`.
44    ///
45    /// `set` is one of the cover sets [`Reach::propagate`] produced from `initial` under
46    /// `control`, which identify the edge.
47    /// The hook behind [`SafetyVerdict::Unsafe`]. Edge checks call it only for edges that
48    /// are not proven safe, once per cover set and obstacle, and turn the first point it
49    /// returns into a [`Witness`]. The default returns `None`, so such edges stay
50    /// [`SafetyVerdict::Indeterminate`].
51    ///
52    /// Return `Some(point)` only if `point` is proven to be a state the real system can
53    /// actually reach on the edge, and proven to lie in `obstacle`. Cover sets are
54    /// over-approximations, so a point of `set` is in general *not* such a state; only a
55    /// model whose cover set is exact or under-approximated can certify one. polyzonotope
56    /// has no certified witness, so this is for models that prove it themselves.
57    ///
58    /// The returned point is sanity-checked in plain `f64` (inside `obstacle` and inside the
59    /// interval hull of `set`) and dropped if it fails, which keeps the verdict
60    /// `Indeterminate`. That check is a guard against hook bugs, not a proof.
61    fn certify_collision(
62        &self,
63        initial: &SparsePolyZonotope,
64        control: &Self::Control,
65        set: &SparsePolyZonotope,
66        obstacle: &Polytope,
67    ) -> Option<Vec<f64>> {
68        let _ = (initial, control, set, obstacle);
69
70        None
71    }
72}
73
74/// Propagates `initial` under `control` and checks the cover against `obstacles`.
75///
76/// Clears `cover` first and leaves the edge's cover sets in it. Returns the verdict and the
77/// end set, which is `None` exactly when [`Reach::propagate`] could not enclose the edge.
78/// The verdict is [`SafetyVerdict::Safe`] only if the model enclosed the edge and every
79/// cover set is proven disjoint from every obstacle, so a `Safe` verdict always comes with
80/// an end set. An edge that is not proven safe is [`SafetyVerdict::Unsafe`] if
81/// [`Reach::certify_collision`] certifies a collision, and [`SafetyVerdict::Indeterminate`]
82/// otherwise. An edge the model could not enclose, and an empty cover, are `Indeterminate`
83/// without asking for a witness: a model that reports no sets, or not all of them, has not
84/// shown where the system goes.
85///
86/// # Panics
87///
88/// Panics if the model's sets do not have the obstacles' dimension.
89pub fn check_edge<R: Reach<N>, const N: usize>(
90    reach: &R,
91    obstacles: &Obstacles,
92    initial: &SparsePolyZonotope,
93    control: &R::Control,
94    cover: &mut Vec<SparsePolyZonotope>,
95) -> (SafetyVerdict, Option<SparsePolyZonotope>) {
96    cover.clear();
97    let end = reach.propagate(initial, control, cover);
98
99    if end.is_none() || cover.is_empty() {
100        return (SafetyVerdict::Indeterminate, end);
101    }
102
103    let verdict = match obstacles.check_sets(cover) {
104        SafetyVerdict::Safe => SafetyVerdict::Safe,
105        unproven => find_witness(reach, obstacles, initial, control, cover)
106            .map_or(unproven, SafetyVerdict::Unsafe),
107    };
108
109    (verdict, end)
110}
111
112/// The first collision [`Reach::certify_collision`] certifies over every cover set and
113/// obstacle, in time order, if it passes [`is_plausible`].
114fn find_witness<R: Reach<N>, const N: usize>(
115    reach: &R,
116    obstacles: &Obstacles,
117    initial: &SparsePolyZonotope,
118    control: &R::Control,
119    cover: &[SparsePolyZonotope],
120) -> Option<Witness> {
121    cover.iter().enumerate().find_map(|(set_index, set)| {
122        obstacles
123            .polytopes()
124            .iter()
125            .enumerate()
126            .find_map(|(obstacle_index, obstacle)| {
127                let point = reach.certify_collision(initial, control, set, obstacle)?;
128
129                is_plausible(&point, set, obstacle).then_some(Witness {
130                    point,
131                    set: set_index,
132                    obstacle: obstacle_index,
133                })
134            })
135    })
136}
137
138/// Whether `point` has the set's dimension and lies, in plain `f64`, inside `obstacle` and
139/// inside the interval hull of `set`.
140///
141/// A guard against hooks that return garbage, not a proof: near a boundary it may reject a
142/// correctly certified point, which only costs the witness.
143fn is_plausible(point: &[f64], set: &SparsePolyZonotope, obstacle: &Polytope) -> bool {
144    let hull = set.interval_hull();
145    let in_hull = point.len() == hull.dim()
146        && point
147            .iter()
148            .zip(&hull.0)
149            .all(|(x, range)| range.contains(*x, 0.0));
150    let in_obstacle = obstacle.facets.iter().all(|h| {
151        h.normal.len() == point.len()
152            && h.normal.iter().zip(point).map(|(a, x)| a * x).sum::<f64>() <= h.offset
153    });
154
155    in_hull && in_obstacle
156}