sampling_planning/
validity.rs1use crate::StateSpace;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[must_use]
12pub enum Validity {
13 Valid,
15 Invalid,
17 Unknown,
20}
21
22impl Validity {
23 #[must_use]
25 pub const fn is_valid(self) -> bool {
26 matches!(self, Self::Valid)
27 }
28
29 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
40pub trait ValidityChecker<Sp: StateSpace> {
42 fn check_state(&self, state: &Sp::State) -> Validity;
44
45 fn check_motion(&self, space: &Sp, from: &Sp::State, to: &Sp::State) -> Validity;
50}
51
52pub 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
92fn 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}