Skip to main content

robust_planning/
goal.rs

1//! Goal regions over reachable sets: a node reaches the goal only when its whole set is
2//! proven inside.
3
4use polyzonotope::{Containment, IntervalBox, Polytope, SparsePolyZonotope};
5
6/// A goal region that whole reachable sets are tested against.
7///
8/// The set counterpart of `sampling-planning`'s
9/// [`GoalRegion`](sampling_planning::GoalRegion): a [`Goal::center`] for goal-biased
10/// samples, and a containment test that takes a set instead of a state.
11///
12/// # Contract
13///
14/// [`Goal::containment`] may answer [`Containment::Inside`] only if every point of the set
15/// is proven to lie in the goal. Planners accept nothing else as reaching the goal, so a
16/// wrong `Inside` makes their goal proofs void. When in doubt, answer
17/// [`Containment::Unknown`].
18pub trait Goal<const N: usize> {
19    /// The state drawn for goal-biased samples, usually inside the goal.
20    fn center(&self) -> [f64; N];
21
22    /// Whether every point of `set` lies in the goal.
23    ///
24    /// Only [`Containment::Inside`] is a proof; planners treat
25    /// [`Containment::NotInside`] and [`Containment::Unknown`] alike.
26    fn containment(&self, set: &SparsePolyZonotope) -> Containment;
27
28    /// An upper bound on the distance from [`Goal::center`] to any point of the goal, if
29    /// the goal knows one.
30    ///
31    /// [`ReachSearch`](crate::ReachSearch) derives its heuristic radius from it with
32    /// [`GoalRadius::FromGoal`](crate::search::GoalRadius::FromGoal). It affects only the
33    /// search order, never safety. The default is `None`.
34    fn radius(&self) -> Option<f64> {
35        None
36    }
37}
38
39/// A convex polytope goal in H-representation, `{ x | aᵢᵀ x <= dᵢ for every facet i }`.
40///
41/// Containment is decided by [`SparsePolyZonotope::containment`] with a split budget of
42/// [`PolytopeGoal::max_splits`]. It is a proof with the `sound` feature, and up to
43/// floating-point rounding without it.
44///
45/// # Examples
46///
47/// ```
48/// use robust_planning::{Goal, PolytopeGoal};
49/// use robust_planning::polyzonotope::{
50///     Containment, Interval, IntervalBox, SparsePolyZonotope, Zonotope,
51/// };
52///
53/// let square = |lo: f64, hi: f64| IntervalBox(vec![Interval::new(lo, hi); 2]);
54/// let goal = PolytopeGoal::<2>::from_box(&square(0.0, 4.0), 8);
55/// let set = |b| SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&b));
56///
57/// assert_eq!(goal.center(), [2.0, 2.0]);
58/// assert_eq!(goal.containment(&set(square(1.0, 2.0))), Containment::Inside);
59/// assert_ne!(goal.containment(&set(square(3.0, 5.0))), Containment::Inside);
60/// ```
61#[derive(Debug, Clone, PartialEq)]
62pub struct PolytopeGoal<const N: usize> {
63    /// The goal region. Every facet normal has `N` finite entries and every offset is finite.
64    polytope: Polytope,
65    /// The state drawn for goal-biased samples.
66    center: [f64; N],
67    /// Split budget for proving a set inside; `0` disables refinement.
68    max_splits: usize,
69}
70
71impl<const N: usize> PolytopeGoal<N> {
72    /// Creates a goal from its facets, the state for goal-biased samples and a split budget.
73    ///
74    /// # Panics
75    ///
76    /// Panics if a facet normal does not have `N` entries, or if a normal entry or an offset
77    /// is not finite. A NaN facet would never refute containment, so it is rejected here
78    /// instead of silently proving every set inside.
79    #[must_use]
80    pub fn new(polytope: Polytope, center: [f64; N], max_splits: usize) -> Self {
81        for facet in &polytope.facets {
82            assert_eq!(facet.normal.len(), N, "facet normals must have {N} entries");
83            assert!(
84                facet.normal.iter().all(|a| a.is_finite()) && facet.offset.is_finite(),
85                "facet normals and offsets must be finite"
86            );
87        }
88
89        Self {
90            polytope,
91            center,
92            max_splits,
93        }
94    }
95
96    /// Creates a box goal, centered for goal-biased samples at the box midpoint.
97    ///
98    /// # Panics
99    ///
100    /// Panics if the box does not have `N` dimensions or has an infinite bound.
101    #[must_use]
102    pub fn from_box(b: &IntervalBox, max_splits: usize) -> Self {
103        assert_eq!(b.dim(), N, "the box must have {N} dimensions");
104        let center = core::array::from_fn(|i| b.0[i].lo + b.0[i].width() / 2.0);
105
106        Self::new(Polytope::from_box(b), center, max_splits)
107    }
108
109    /// The goal region.
110    #[must_use]
111    pub const fn polytope(&self) -> &Polytope {
112        &self.polytope
113    }
114
115    /// Split budget for proving a set inside.
116    #[must_use]
117    pub const fn max_splits(&self) -> usize {
118        self.max_splits
119    }
120}
121
122impl<const N: usize> Goal<N> for PolytopeGoal<N> {
123    fn center(&self) -> [f64; N] {
124        self.center
125    }
126
127    /// The distance from the center to the farthest corner of the box that the polytope's
128    /// axis-aligned facets bound, or `None` if some axis is not bounded on both sides by
129    /// such a facet.
130    ///
131    /// Facets with other normals only cut the polytope further, so the box contains it and
132    /// the radius is an upper bound. It is widened by a few ULPs against rounding.
133    fn radius(&self) -> Option<f64> {
134        let (lower, upper) = axis_bounds::<N>(&self.polytope);
135        let squared: f64 = (0..N)
136            .map(|i| {
137                let reach = (self.center[i] - lower[i]).max(upper[i] - self.center[i]);
138
139                reach * reach
140            })
141            .sum();
142        let radius = squared.sqrt() * (1.0 + 8.0 * f64::EPSILON);
143
144        radius.is_finite().then_some(radius)
145    }
146
147    /// Delegates to [`SparsePolyZonotope::containment`] within the split budget.
148    ///
149    /// # Panics
150    ///
151    /// Panics if `set` does not have `N` dimensions.
152    fn containment(&self, set: &SparsePolyZonotope) -> Containment {
153        set.containment(&self.polytope, self.max_splits)
154    }
155}
156
157/// The tightest lower and upper bound per axis among the facets of `polytope` whose normal
158/// has exactly one non-zero entry; infinite where no such facet bounds that side.
159fn axis_bounds<const N: usize>(polytope: &Polytope) -> ([f64; N], [f64; N]) {
160    let mut lower = [f64::NEG_INFINITY; N];
161    let mut upper = [f64::INFINITY; N];
162
163    for facet in &polytope.facets {
164        let mut nonzero = facet.normal.iter().enumerate().filter(|(_, a)| **a != 0.0);
165        let (Some((axis, &a)), None) = (nonzero.next(), nonzero.next()) else {
166            continue;
167        };
168        let bound = facet.offset / a;
169
170        if a > 0.0 {
171            upper[axis] = upper[axis].min(bound);
172        } else {
173            lower[axis] = lower[axis].max(bound);
174        }
175    }
176
177    (lower, upper)
178}
179
180#[cfg(test)]
181mod tests {
182    use nalgebra::DVector;
183    use polyzonotope::{Halfspace, Interval, Zonotope};
184
185    use super::*;
186
187    /// The box `[lo, hi]` in every axis as a set.
188    fn square_set(lo: f64, hi: f64) -> SparsePolyZonotope {
189        SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&IntervalBox(vec![
190            Interval::new(
191                lo, hi
192            );
193            2
194        ])))
195    }
196
197    /// The unit box goal `[0, 1]²`.
198    fn unit_goal() -> PolytopeGoal<2> {
199        PolytopeGoal::from_box(&IntervalBox(vec![Interval::new(0.0, 1.0); 2]), 8)
200    }
201
202    /// The triangle `x >= 0, y >= 0, x + y <= 1`, a goal with a facet no box has.
203    fn triangle() -> PolytopeGoal<2> {
204        let facet = |a: f64, b: f64, offset: f64| Halfspace {
205            normal: DVector::from_column_slice(&[a, b]),
206            offset,
207        };
208        let polytope = Polytope {
209            facets: vec![
210                facet(-1.0, 0.0, 0.0),
211                facet(0.0, -1.0, 0.0),
212                facet(1.0, 1.0, 1.0),
213            ],
214        };
215
216        PolytopeGoal::new(polytope, [0.25, 0.25], 8)
217    }
218
219    #[test]
220    fn set_well_inside_is_contained() {
221        assert_eq!(unit_goal().center(), [0.5, 0.5]);
222        assert_eq!(
223            unit_goal().containment(&square_set(0.25, 0.75)),
224            Containment::Inside
225        );
226    }
227
228    #[test]
229    fn straddling_set_is_not_contained() {
230        assert_ne!(
231            unit_goal().containment(&square_set(0.5, 1.5)),
232            Containment::Inside
233        );
234    }
235
236    #[test]
237    fn set_one_ulp_outside_is_not_contained() {
238        assert_ne!(
239            unit_goal().containment(&square_set(0.5, 1.0_f64.next_up())),
240            Containment::Inside
241        );
242    }
243
244    #[test]
245    fn slanted_facet_decides_containment() {
246        let goal = triangle();
247
248        assert_eq!(goal.containment(&square_set(0.1, 0.3)), Containment::Inside);
249        assert_ne!(
250            goal.containment(&square_set(0.35, 0.55)),
251            Containment::Inside,
252            "the corner (0.55, 0.55) is beyond x + y <= 1"
253        );
254    }
255
256    #[test]
257    #[should_panic(expected = "finite")]
258    fn nan_offset_is_rejected() {
259        let mut polytope = unit_goal().polytope().clone();
260        polytope.facets[0].offset = f64::NAN;
261
262        let _ = PolytopeGoal::new(polytope, [0.5, 0.5], 8);
263    }
264
265    #[test]
266    #[should_panic(expected = "entries")]
267    fn wrong_normal_length_is_rejected() {
268        let polytope = Polytope::from_box(&IntervalBox(vec![Interval::new(0.0, 1.0); 3]));
269
270        let _ = PolytopeGoal::<2>::new(polytope, [0.5, 0.5], 8);
271    }
272
273    #[test]
274    fn radius_bounds_the_box_and_needs_axis_facets() {
275        let unit = unit_goal().radius().expect("a box bounds every axis");
276
277        assert!(unit >= 0.5f64.sqrt() && unit < 0.5f64.sqrt() + 1e-12);
278        assert_eq!(
279            triangle().radius(),
280            None,
281            "x + y <= 1 bounds no axis from above"
282        );
283
284        let mut cut = unit_goal();
285        cut.polytope.facets.extend(triangle().polytope.facets);
286        let radius = cut.radius().expect("the box facets are still there");
287        assert!(
288            radius >= 0.5f64.sqrt(),
289            "extra facets never shrink the bound below the box"
290        );
291    }
292}