Skip to main content

sampling_planning/
validity.rs

1//! Validity checking of states and motions with a three-valued result.
2
3use crate::StateSpace;
4
5/// The outcome of a validity check.
6///
7/// Planners accept only [`Validity::Valid`]. [`Validity::Unknown`] is rejected like
8/// [`Validity::Invalid`]: a check that fails to prove validity never yields a valid state or
9/// edge. This is the conservative default that reachable-set based edge checks rely on.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[must_use]
12pub enum Validity {
13    /// Proven valid: collision-free and within all constraints.
14    Valid,
15    /// Proven invalid.
16    Invalid,
17    /// The checker could not decide, for example because an over-approximation touches an
18    /// obstacle. Treated as invalid by planners.
19    Unknown,
20}
21
22impl Validity {
23    /// Whether a planner may accept this result. Only [`Validity::Valid`] is accepted.
24    #[must_use]
25    pub const fn is_valid(self) -> bool {
26        matches!(self, Self::Valid)
27    }
28
29    /// Combines two results for a compound check: [`Validity::Invalid`] dominates
30    /// [`Validity::Unknown`], which dominates [`Validity::Valid`].
31    pub const fn and(self, other: Self) -> Self {
32        match (self, other) {
33            (Self::Invalid, _) | (_, Self::Invalid) => Self::Invalid,
34            (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
35            (Self::Valid, Self::Valid) => Self::Valid,
36        }
37    }
38}
39
40/// Checks states and motions of a [`StateSpace`].
41pub trait ValidityChecker<Sp: StateSpace> {
42    /// Checks a single state.
43    fn check_state(&self, state: &Sp::State) -> Validity;
44
45    /// Checks the motion from `from` to `to`, including `to`.
46    ///
47    /// `from` is assumed to be valid already; planners only call this from tree or roadmap
48    /// nodes. Use [`discretized_motion`] when only a state check is available.
49    fn check_motion(&self, space: &Sp, from: &Sp::State, to: &Sp::State) -> Validity;
50}
51
52/// Checks a motion by checking interpolated states at most `resolution` apart.
53///
54/// Checks the states after `from` up to and including `to`. Stops at the first
55/// [`Validity::Invalid`]; otherwise returns [`Validity::Unknown`] if any state was unknown.
56/// This is a sampled check, not a proof: obstacles thinner than `resolution` can be missed.
57///
58/// # Panics
59///
60/// Panics if `resolution` is not positive and finite.
61pub fn discretized_motion<Sp, F>(
62    space: &Sp,
63    from: &Sp::State,
64    to: &Sp::State,
65    resolution: f64,
66    mut check_state: F,
67) -> Validity
68where
69    Sp: StateSpace,
70    F: FnMut(&Sp::State) -> Validity,
71{
72    assert!(
73        resolution.is_finite() && resolution > 0.0,
74        "resolution must be positive and finite"
75    );
76
77    let steps = step_count(space.distance(from, to), resolution);
78    let mut result = Validity::Valid;
79
80    for step in 1..=steps {
81        let t = f64::from(step) / f64::from(steps);
82        result = result.and(check_state(&space.interpolate(from, to, t)));
83
84        if result == Validity::Invalid {
85            break;
86        }
87    }
88
89    result
90}
91
92/// The number of interpolation steps so that consecutive states are at most `resolution`
93/// apart. At least one, so the end state is always checked.
94fn step_count(distance: f64, resolution: f64) -> u32 {
95    let steps = libm::ceil(distance / resolution);
96
97    if steps.is_nan() || steps < 1.0 {
98        1
99    } else if steps >= f64::from(u32::MAX) {
100        u32::MAX
101    } else {
102        #[expect(
103            clippy::cast_possible_truncation,
104            clippy::cast_sign_loss,
105            reason = "steps is an integer in [1, u32::MAX) after the guards above"
106        )]
107        let steps = steps as u32;
108        steps
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::Euclidean;
116
117    #[test]
118    fn invalid_dominates_unknown_dominates_valid() {
119        use Validity::{Invalid, Unknown, Valid};
120
121        assert_eq!(Valid.and(Valid), Valid);
122        assert_eq!(Valid.and(Unknown), Unknown);
123        assert_eq!(Unknown.and(Invalid), Invalid);
124        assert_eq!(Invalid.and(Valid), Invalid);
125        assert!(!Unknown.is_valid());
126    }
127
128    #[test]
129    fn discretized_motion_finds_wall_and_unknown() {
130        let wall = |s: &[f64; 1]| {
131            if (4.9..5.1).contains(&s[0]) {
132                Validity::Invalid
133            } else if s[0] > 8.0 {
134                Validity::Unknown
135            } else {
136                Validity::Valid
137            }
138        };
139
140        let space = Euclidean::<1>;
141        assert_eq!(
142            discretized_motion(&space, &[0.0], &[4.0], 0.1, wall),
143            Validity::Valid
144        );
145        assert_eq!(
146            discretized_motion(&space, &[0.0], &[6.0], 0.1, wall),
147            Validity::Invalid
148        );
149        assert_eq!(
150            discretized_motion(&space, &[6.0], &[9.0], 0.1, wall),
151            Validity::Unknown
152        );
153        assert_eq!(
154            discretized_motion(&space, &[1.0], &[1.0], 0.1, wall),
155            Validity::Valid
156        );
157    }
158}