1use alloc::collections::BinaryHeap;
40use alloc::vec::Vec;
41use core::cmp::Ordering;
42
43use crate::Objective;
44use crate::operators::real::Bounds;
45
46pub type Point = (f64, f64);
48
49#[derive(Debug, Clone, PartialEq)]
52pub struct Robot {
53 pub reference: Vec<Point>,
55}
56
57#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct Block {
60 pub min: Point,
62 pub max: Point,
64}
65
66impl Block {
67 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#[derive(Debug, Clone, PartialEq)]
80pub struct Intersection {
81 pub robots: Vec<Robot>,
83 pub blocks: Vec<Block>,
85 pub safety: f64,
87 pub parameter_bounds: [(f64, f64); 2],
89 pub time_cost: f64,
91}
92
93struct Roadmap {
95 points: Vec<Point>,
97 edges: Vec<Vec<(usize, f64)>>,
99}
100
101impl Intersection {
102 #[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 #[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 #[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 #[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 #[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 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 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 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 fn space_time(&self, roadmap: &Roadmap, planned: &[Vec<Point>]) -> Option<Vec<Point>> {
280 #[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 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 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
381fn 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
400fn midpoint(a: Point, b: Point) -> Point {
402 (f64::midpoint(a.0, b.0), f64::midpoint(a.1, b.1))
403}
404
405fn 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
416fn 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
439fn 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
448fn 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
458fn 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 #[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 #[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 #[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 #[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 assert!(roadmap.edges[0].iter().any(|&(w, _)| w >= 2));
594 assert!(roadmap.edges.iter().flatten().all(|&(_, l)| l > 0.0));
595 }
596}