Skip to main content

evolutionary_planning/problems/
intersection.rs

1//! A multi-robot intersection benchmark after Parque (2024): every robot crosses a four-way
2//! intersection on a lattice roadmap built around its reference path, the lattice of robot
3//! `i` is parameterised by its base `b_i` and height `h_i`, and the cost of a parameter
4//! vector `x = (b_1, h_1, …, b_N, h_N)` is the total length of the coordinated, collision-free
5//! paths (equation (1) of the paper) plus a price per time step (see below), so any
6//! gradient-free optimiser (RADES, DE, CMA-ES) can search the roadmap configurations.
7//!
8//! The paper coordinates the robots with dRRT* in the composite roadmap. This benchmark uses
9//! prioritised space-time search instead: robots plan in index order on their own roadmaps,
10//! each avoiding the already planned ones (positions at every time step and edge midpoint
11//! at least `safety` apart; a robot leaves the scene at its goal). One roadmap edge takes one
12//! time step and waiting in place is allowed. Every step, moving or waiting, also costs
13//! [`Intersection::time_cost`]: with length alone the straight middle row plus waits would
14//! make nearly every configuration cost the same, whereas with a price on time a coarse
15//! lattice (large `b_i`, fewer and faster steps) pays off unless it causes conflicts that
16//! need waits or detours.
17//! A robot that finds no plan adds a penalty of `1000` plus its straight-line distance, so
18//! infeasible configurations still compare.
19//!
20//! In the [`Intersection::crossing`] scene the robots drive straight, and the coarsest
21//! lattice (`b_i = 6` for all) happens to be conflict-free, so the optimum sits at that corner
22//! of the box (cost 412 for eight robots) and the heights `h_i` only matter for
23//! configurations that need detours. It is a smoke benchmark for the optimisers rather than
24//! a hard coordination problem; scenes with turning robots are an open extension.
25//!
26//! ```
27//! use evolutionary_planning::de::rades::{Config, Rades};
28//! use evolutionary_planning::problems::intersection::Intersection;
29//! use evolutionary_planning::{Limits, SplitMix64};
30//!
31//! let mut scene = Intersection::crossing(4);
32//! let mut rades = Rades::new(Config::default(), scene.bounds());
33//! // The paper's budget: 300 function evaluations.
34//! let outcome = rades.run(&mut scene, &mut Limits::evaluations(300), &mut (), &mut SplitMix64::new(1));
35//! let plan = scene.plan(outcome.best_genome().expect("evaluated")).expect("feasible");
36//! assert_eq!(scene.collisions(&plan), 0);
37//! ```
38
39use alloc::collections::BinaryHeap;
40use alloc::vec::Vec;
41use core::cmp::Ordering;
42
43use crate::Objective;
44use crate::operators::real::Bounds;
45
46/// A point in the plane.
47pub type Point = (f64, f64);
48
49/// One robot: where it enters and where it leaves, and its reference path (a polyline from
50/// start to goal through the intersection).
51#[derive(Debug, Clone, PartialEq)]
52pub struct Robot {
53    /// The reference polyline; its first point is the start, its last the goal.
54    pub reference: Vec<Point>,
55}
56
57/// An axis-aligned rectangular obstacle `[x0, x1] × [y0, y1]`.
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct Block {
60    /// The lower-left corner.
61    pub min: Point,
62    /// The upper-right corner.
63    pub max: Point,
64}
65
66impl Block {
67    /// Whether the segment `a → b` touches the block (sampled densely; the blocks are large
68    /// compared to the sampling step).
69    fn hits(&self, from: Point, to: Point) -> bool {
70        (0..=32).any(|k| {
71            let t = f64::from(k) / 32.0;
72            let (x, y) = (from.0 + t * (to.0 - from.0), from.1 + t * (to.1 - from.1));
73            (self.min.0..=self.max.0).contains(&x) && (self.min.1..=self.max.1).contains(&y)
74        })
75    }
76}
77
78/// The intersection scene.
79#[derive(Debug, Clone, PartialEq)]
80pub struct Intersection {
81    /// The robots, in planning priority order.
82    pub robots: Vec<Robot>,
83    /// The buildings at the corners.
84    pub blocks: Vec<Block>,
85    /// The minimum distance between two robots.
86    pub safety: f64,
87    /// The bounds of each `(b_i, h_i)` pair: the paper's `b ∈ [1, 6]`, `h ∈ [0.5, 5]`.
88    pub parameter_bounds: [(f64, f64); 2],
89    /// The cost of one time step, moving or waiting, in length units. Default `1`.
90    pub time_cost: f64,
91}
92
93/// A roadmap: vertex positions and forward edges.
94struct Roadmap {
95    /// The vertex positions; vertex `0` is the start, vertex `1` the goal.
96    points: Vec<Point>,
97    /// The out-edges of every vertex: `(target, length)`.
98    edges: Vec<Vec<(usize, f64)>>,
99}
100
101impl Intersection {
102    /// A four-way crossing of roads 8 wide with buildings at the corners and up to eight
103    /// robots driving straight across on the right-hand lanes: robots 0–3 come from the west,
104    /// east, south and north; robots 4–7 follow them on the same lanes, 8 units behind.
105    ///
106    /// # Panics
107    ///
108    /// Panics if `robots` is not in `1..=8`.
109    #[must_use]
110    pub fn crossing(robots: usize) -> Self {
111        assert!(
112            (1..=8).contains(&robots),
113            "the crossing scene has one to eight robots"
114        );
115
116        let lanes: [(Point, Point); 4] = [
117            ((-18.0, -2.0), (18.0, -2.0)),
118            ((18.0, 2.0), (-18.0, 2.0)),
119            ((2.0, -18.0), (2.0, 18.0)),
120            ((-2.0, 18.0), (-2.0, -18.0)),
121        ];
122        let robots = (0..robots)
123            .map(|i| {
124                let (start, goal) = lanes[i % 4];
125                let behind = if i < 4 { 0.0 } else { 8.0 };
126                let direction = unit((goal.0 - start.0, goal.1 - start.1));
127                let shift = |p: Point, d: f64| (p.0 - d * direction.0, p.1 - d * direction.1);
128                Robot {
129                    reference: alloc::vec![shift(start, behind), shift(goal, -behind)],
130                }
131            })
132            .collect();
133        let corner = |sx: f64, sy: f64| Block {
134            min: (
135                if sx > 0.0 { 4.0 } else { -40.0 },
136                if sy > 0.0 { 4.0 } else { -40.0 },
137            ),
138            max: (
139                if sx > 0.0 { 40.0 } else { -4.0 },
140                if sy > 0.0 { 40.0 } else { -4.0 },
141            ),
142        };
143
144        Self {
145            robots,
146            blocks: alloc::vec![
147                corner(1.0, 1.0),
148                corner(-1.0, 1.0),
149                corner(1.0, -1.0),
150                corner(-1.0, -1.0)
151            ],
152            safety: 1.5,
153            parameter_bounds: [(1.0, 6.0), (0.5, 5.0)],
154            time_cost: 1.0,
155        }
156    }
157
158    /// The search box of the parameter vector `(b_1, h_1, …, b_N, h_N)`.
159    #[must_use]
160    pub fn bounds(&self) -> Bounds {
161        let [(b0, b1), (h0, h1)] = self.parameter_bounds;
162        let lower = self.robots.iter().flat_map(|_| [b0, h0]).collect();
163        let upper = self.robots.iter().flat_map(|_| [b1, h1]).collect();
164
165        Bounds::new(lower, upper)
166    }
167
168    /// The coordinated trajectories (one position per time step, until each robot's goal)
169    /// for parameters `x`, or `None` if some robot found no collision-free plan.
170    #[must_use]
171    pub fn plan(&self, x: &[f64]) -> Option<Vec<Vec<Point>>> {
172        let mut planned: Vec<Vec<Point>> = Vec::with_capacity(self.robots.len());
173        for (i, robot) in self.robots.iter().enumerate() {
174            let roadmap = self.roadmap(
175                robot,
176                self.parameter(x, 2 * i, 0),
177                self.parameter(x, 2 * i + 1, 1),
178            );
179            planned.push(self.space_time(&roadmap, &planned)?);
180        }
181
182        Some(planned)
183    }
184
185    /// The cost of one trajectory: its length plus [`Intersection::time_cost`] per step.
186    #[must_use]
187    pub fn trajectory_cost(&self, trajectory: &[Point]) -> f64 {
188        trajectory
189            .windows(2)
190            .map(|w| distance(w[0], w[1]) + self.time_cost)
191            .sum()
192    }
193
194    /// The number of time steps (and midpoints) at which two robots are closer than `safety`.
195    #[must_use]
196    pub fn collisions(&self, trajectories: &[Vec<Point>]) -> usize {
197        let horizon = trajectories.iter().map(Vec::len).max().unwrap_or(0);
198        let mut count = 0;
199        for t in 0..horizon {
200            for (i, a) in trajectories.iter().enumerate() {
201                for b in &trajectories[i + 1..] {
202                    count += usize::from(conflict(a, b, t, self.safety));
203                }
204            }
205        }
206
207        count
208    }
209
210    /// Reads parameter `index` of `x`, clamped to its bounds (`kind` 0: base, 1: height).
211    fn parameter(&self, x: &[f64], index: usize, kind: usize) -> f64 {
212        let (low, high) = self.parameter_bounds[kind];
213
214        x.get(index).copied().unwrap_or(low).clamp(low, high)
215    }
216
217    /// The lattice roadmap of `robot` with base `base` and height `height`: points on the
218    /// reference path every `base` units and offset by `±height`, with the forward edges of
219    /// the paper's equation (4) that avoid the buildings.
220    fn roadmap(&self, robot: &Robot, base: f64, height: f64) -> Roadmap {
221        let middle = resample(&robot.reference, base);
222        let r = middle.len();
223        let mut points = Vec::with_capacity(3 * r);
224        // Vertex 0 is the start and 1 the goal; then the interior middle points and both rows.
225        points.push(middle[0]);
226        points.push(middle[r - 1]);
227        let mut index = alloc::vec![[usize::MAX; 3]; r];
228        index[0][0] = 0;
229        index[r - 1][0] = 1;
230        for j in 0..r {
231            let normal = normal_at(&middle, j);
232            for (row, offset) in [(0, 0.0), (1, height), (2, -height)] {
233                if index[j][row] != usize::MAX || ((j == 0 || j == r - 1) && row != 0) {
234                    continue;
235                }
236                index[j][row] = points.len();
237                points.push((
238                    middle[j].0 + offset * normal.0,
239                    middle[j].1 + offset * normal.1,
240                ));
241            }
242        }
243
244        let mut edges = alloc::vec![Vec::new(); points.len()];
245        let mut connect = |from: usize, to: usize, points: &[Point]| {
246            if from == usize::MAX || to == usize::MAX {
247                return;
248            }
249            let (a, b) = (points[from], points[to]);
250            if !self.blocks.iter().any(|block| block.hits(a, b)) {
251                edges[from].push((to, distance(a, b)));
252            }
253        };
254        for j in 0..r {
255            let [q, p, s] = index[j];
256            connect(q, p, &points);
257            connect(q, s, &points);
258            if j + 1 < r {
259                let [q1, p1, s1] = index[j + 1];
260                for (from, to) in [
261                    (q, q1),
262                    (p, q1),
263                    (s, q1),
264                    (p, p1),
265                    (s, s1),
266                    (q, p1),
267                    (q, s1),
268                ] {
269                    connect(from, to, &points);
270                }
271            }
272        }
273
274        Roadmap { points, edges }
275    }
276
277    /// Prioritised space-time Dijkstra on `roadmap` avoiding the `planned` trajectories;
278    /// minimises path length plus [`Intersection::time_cost`] per step.
279    fn space_time(&self, roadmap: &Roadmap, planned: &[Vec<Point>]) -> Option<Vec<Point>> {
280        /// A search entry ordered by smallest cost first.
281        #[derive(PartialEq)]
282        struct Entry(f64, usize, usize);
283        impl Eq for Entry {}
284        impl PartialOrd for Entry {
285            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
286                Some(self.cmp(other))
287            }
288        }
289        impl Ord for Entry {
290            fn cmp(&self, other: &Self) -> Ordering {
291                other
292                    .0
293                    .total_cmp(&self.0)
294                    .then(other.2.cmp(&self.2))
295                    .then(other.1.cmp(&self.1))
296            }
297        }
298
299        let horizon = 2 * roadmap.points.len() + planned.iter().map(Vec::len).max().unwrap_or(0);
300        let n = roadmap.points.len();
301        let mut best = alloc::vec![f64::INFINITY; n * (horizon + 1)];
302        let mut parent = alloc::vec![usize::MAX; n * (horizon + 1)];
303        let mut heap = BinaryHeap::new();
304        if !self.free(roadmap.points[0], roadmap.points[0], 0, planned) {
305            return None;
306        }
307
308        best[0] = 0.0;
309        heap.push(Entry(0.0, 0, 0));
310        while let Some(Entry(cost, v, t)) = heap.pop() {
311            if v == 1 {
312                return Some(trace(&roadmap.points, &parent, n, v, t));
313            }
314            if cost > best[t * n + v] || t == horizon {
315                continue;
316            }
317
318            let wait = core::iter::once((v, 0.0));
319            for (w, length) in wait.chain(roadmap.edges[v].iter().copied()) {
320                let next = (t + 1) * n + w;
321                let total = cost + length + self.time_cost;
322                if total < best[next]
323                    && self.free(roadmap.points[v], roadmap.points[w], t + 1, planned)
324                {
325                    best[next] = total;
326                    parent[next] = t * n + v;
327                    heap.push(Entry(total, w, t + 1));
328                }
329            }
330        }
331
332        None
333    }
334
335    /// Whether moving `from → to` arriving at time `t` keeps the safety distance to every planned
336    /// robot still in the scene (at `t` and at the midpoint of the move).
337    fn free(&self, from: Point, to: Point, t: usize, planned: &[Vec<Point>]) -> bool {
338        let middle = midpoint(from, to);
339        planned.iter().all(|other| {
340            let at = |time: usize| other.get(time).copied();
341            let clear =
342                |p: Point, q: Option<Point>| q.is_none_or(|q| distance(p, q) >= self.safety);
343            let previous = t.checked_sub(1).and_then(at);
344            let midpoint = match (previous, at(t)) {
345                (Some(before), Some(now)) => Some(midpoint(before, now)),
346                _ => None,
347            };
348            clear(to, at(t)) && clear(middle, midpoint)
349        })
350    }
351}
352
353impl Objective<Vec<f64>> for Intersection {
354    /// The total cost of the coordinated plan: path length plus [`Intersection::time_cost`]
355    /// per step; failed robots add `1000` plus their straight-line distance.
356    fn evaluate(&mut self, x: &Vec<f64>) -> f64 {
357        let mut planned: Vec<Vec<Point>> = Vec::with_capacity(self.robots.len());
358        let mut cost = 0.0;
359        for (i, robot) in self.robots.iter().enumerate() {
360            let roadmap = self.roadmap(
361                robot,
362                self.parameter(x, 2 * i, 0),
363                self.parameter(x, 2 * i + 1, 1),
364            );
365            if let Some(path) = self.space_time(&roadmap, &planned) {
366                cost += self.trajectory_cost(&path);
367                planned.push(path);
368            } else {
369                let (start, goal) = (
370                    robot.reference[0],
371                    robot.reference[robot.reference.len() - 1],
372                );
373                cost += 1000.0 + distance(start, goal);
374            }
375        }
376
377        cost
378    }
379}
380
381/// Whether trajectories `a` and `b` are closer than `safety` at time `t` or at the midpoint of
382/// the step into `t`.
383fn conflict(a: &[Point], b: &[Point], t: usize, safety: f64) -> bool {
384    let (Some(&pa), Some(&pb)) = (a.get(t), b.get(t)) else {
385        return false;
386    };
387    if distance(pa, pb) < safety {
388        return true;
389    }
390
391    match (
392        t.checked_sub(1).and_then(|s| a.get(s)),
393        t.checked_sub(1).and_then(|s| b.get(s)),
394    ) {
395        (Some(&qa), Some(&qb)) => distance(midpoint(pa, qa), midpoint(pb, qb)) < safety,
396        _ => false,
397    }
398}
399
400/// The midpoint of two points.
401fn midpoint(a: Point, b: Point) -> Point {
402    (f64::midpoint(a.0, b.0), f64::midpoint(a.1, b.1))
403}
404
405/// Follows the parent pointers back from `(v, t)`.
406fn trace(points: &[Point], parent: &[usize], n: usize, v: usize, t: usize) -> Vec<Point> {
407    let mut states = alloc::vec![t * n + v];
408    while parent[*states.last().expect("non-empty")] != usize::MAX {
409        states.push(parent[*states.last().expect("non-empty")]);
410    }
411    states.reverse();
412
413    states.into_iter().map(|s| points[s % n]).collect()
414}
415
416/// Points along `polyline` every `step` units of arc length, both ends included (the last
417/// interval may be shorter): `R = 1 + ⌈L / b⌉` points, the paper's (2) rounded up.
418fn resample(polyline: &[Point], step: f64) -> Vec<Point> {
419    let mut points = alloc::vec![polyline[0]];
420    let mut carried = 0.0;
421    for w in polyline.windows(2) {
422        let length = distance(w[0], w[1]);
423        let mut s = step - carried;
424        while s < length - 1e-9 {
425            let t = s / length;
426            points.push((
427                w[0].0 + t * (w[1].0 - w[0].0),
428                w[0].1 + t * (w[1].1 - w[0].1),
429            ));
430            s += step;
431        }
432        carried = length - (s - step);
433    }
434
435    points.push(polyline[polyline.len() - 1]);
436    points
437}
438
439/// The left normal of the path at point `j` (from the neighbouring points).
440fn normal_at(points: &[Point], j: usize) -> Point {
441    let a = points[j.saturating_sub(1)];
442    let b = points[(j + 1).min(points.len() - 1)];
443    let (dx, dy) = unit((b.0 - a.0, b.1 - a.1));
444
445    (-dy, dx)
446}
447
448/// The unit vector of `v` (zero stays zero).
449fn unit(v: Point) -> Point {
450    let length = libm::hypot(v.0, v.1);
451    if length > 0.0 {
452        (v.0 / length, v.1 / length)
453    } else {
454        (0.0, 0.0)
455    }
456}
457
458/// The Euclidean distance.
459fn distance(a: Point, b: Point) -> f64 {
460    libm::hypot(a.0 - b.0, a.1 - b.1)
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466    use crate::cmaes::{CmaEs, Config as CmaConfig};
467    use crate::de::rades::{Config, Rades};
468    use crate::de::{Config as DeConfig, De};
469    use crate::{Limits, SplitMix64};
470
471    /// Every optimiser finds a collision-free coordinated plan for four robots (RADES also
472    /// for eight), and the reported cost equals the cost of the planned trajectories.
473    #[test]
474    fn coordinated_plans_are_collision_free() {
475        for robots in [4, 8] {
476            let mut scene = Intersection::crossing(robots);
477            let bounds = scene.bounds();
478            let mut rng = SplitMix64::new(3);
479            let budget = if robots == 4 { 300 } else { 100 };
480            let mut outcomes = alloc::vec![Rades::new(Config::default(), bounds.clone()).run(
481                &mut scene,
482                &mut Limits::evaluations(budget),
483                &mut (),
484                &mut rng
485            )];
486            if robots == 4 {
487                outcomes.push(
488                    De::new(
489                        DeConfig {
490                            population_size: 10,
491                            ..DeConfig::default()
492                        },
493                        bounds.clone(),
494                    )
495                    .run(
496                        &mut scene,
497                        &mut Limits::evaluations(300),
498                        &mut (),
499                        &mut rng,
500                    ),
501                );
502                outcomes.push(
503                    CmaEs::new(
504                        bounds.center(),
505                        1.0,
506                        CmaConfig {
507                            bounds: Some(bounds.clone()),
508                            ..CmaConfig::default()
509                        },
510                    )
511                    .minimize(
512                        &mut scene,
513                        &mut Limits::evaluations(300),
514                        &mut (),
515                        &mut rng,
516                    ),
517                );
518            }
519            for outcome in outcomes {
520                let x = outcome.best_genome().expect("evaluated");
521                let plan = scene.plan(x).expect("feasible");
522                let cost: f64 = plan.iter().map(|p| scene.trajectory_cost(p)).sum();
523                assert_eq!(scene.collisions(&plan), 0, "{robots} robots");
524                assert!((cost - outcome.best_cost()).abs() < 1e-9);
525                assert!(
526                    plan.iter()
527                        .zip(&scene.robots)
528                        .all(|(p, r)| p[p.len() - 1] == r.reference[r.reference.len() - 1])
529                );
530            }
531        }
532    }
533
534    /// The objective is not flat: random configurations differ, and RADES with the paper's
535    /// 300 evaluations beats the median random configuration.
536    #[test]
537    fn configurations_matter() {
538        let mut scene = Intersection::crossing(4);
539        let mut bounds = scene.bounds();
540        let mut rng = SplitMix64::new(11);
541        let mut costs: alloc::vec::Vec<f64> = (0..40)
542            .map(|_| {
543                let x = crate::operators::Initializer::initialize(&mut bounds, &mut rng);
544                scene.evaluate(&x)
545            })
546            .collect();
547        costs.sort_by(f64::total_cmp);
548        let outcome = Rades::new(Config::default(), scene.bounds()).run(
549            &mut scene,
550            &mut Limits::evaluations(300),
551            &mut (),
552            &mut rng,
553        );
554
555        assert!(costs[39] - costs[0] > 1.0, "flat objective: {costs:?}");
556        assert!(
557            outcome.best_cost() < costs[20],
558            "{} vs median {}",
559            outcome.best_cost(),
560            costs[20]
561        );
562    }
563
564    /// In the straight-crossing scene the coarsest lattice is conflict-free and optimal
565    /// (documented in the module docs): `b_i = 6` costs 412 for eight robots whatever `h_i`.
566    #[test]
567    fn coarsest_lattice_is_optimal_in_the_crossing() {
568        let mut scene = Intersection::crossing(8);
569        let bounds = scene.bounds();
570        let upper = bounds.upper().to_vec();
571        let mut low_heights = upper.clone();
572        for k in (1..low_heights.len()).step_by(2) {
573            low_heights[k] = bounds.lower()[k];
574        }
575
576        assert!((scene.evaluate(&upper) - 412.0).abs() < 1e-9);
577        assert!((scene.evaluate(&low_heights) - 412.0).abs() < 1e-9);
578        assert!(scene.evaluate(&bounds.lower().to_vec()) > 412.0);
579    }
580
581    /// Lattice resampling and roadmap structure.
582    #[test]
583    fn lattice_structure() {
584        let points = resample(&[(0.0, 0.0), (10.0, 0.0)], 3.0);
585        assert_eq!(
586            points,
587            [(0.0, 0.0), (3.0, 0.0), (6.0, 0.0), (9.0, 0.0), (10.0, 0.0)]
588        );
589
590        let scene = Intersection::crossing(1);
591        let roadmap = scene.roadmap(&scene.robots[0], 4.0, 1.0);
592        // The straight middle row is always available: the start reaches the goal.
593        assert!(roadmap.edges[0].iter().any(|&(w, _)| w >= 2));
594        assert!(roadmap.edges.iter().flatten().all(|&(_, l)| l > 0.0));
595    }
596}