connector_routing/search.rs
1//! Single-connector routing: A* over `(vertex, heading)` in a routing graph (Wybrow,
2//! Marriott and Stuckey 2009, section 4).
3//!
4//! The state is a graph vertex and the direction of the last move (or "not moved yet"
5//! at the source). Moves never reverse. A move costs its length times the length
6//! weight, plus the bend weight when it changes the heading, plus whatever extra cost
7//! the caller charges ([`EdgeCosts`]). The heuristic is the Manhattan distance times
8//! the length weight plus the exact free-space bend estimate ([`min_bends`]) times the
9//! bend weight, which is consistent.
10
11mod bends;
12pub(crate) mod one_bend;
13
14use alloc::vec::Vec;
15
16use heuristic_search::{Limits, Successors, a_star, heuristic_fn};
17
18use crate::error::Error;
19use crate::geom::{DirSet, Direction};
20use crate::graph::{RoutingGraph, VertexId};
21use crate::route::Route;
22use crate::scene::{PortId, Scene};
23
24pub use bends::min_bends;
25
26/// What a route minimises.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
28pub enum Objective {
29 /// The shortest route, and among those one with the fewest bends (exact).
30 #[default]
31 ShortestThenFewestBends,
32 /// The route with the fewest bends, and among those the shortest (exact).
33 FewestBendsThenShortest,
34 /// `length * length_weight + bends * bend_weight`.
35 Weighted {
36 /// The cost of one unit of length.
37 length: u64,
38 /// The cost of one bend.
39 bend: u64,
40 },
41}
42
43/// The length and bend weights of an [`Objective`] on a given graph.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct Weights {
46 /// The cost of one unit of length.
47 pub length: u64,
48 /// The cost of one bend.
49 pub bend: u64,
50}
51
52impl Objective {
53 /// The weights that realise this objective exactly on `graph`.
54 ///
55 /// The lexicographic objectives weight the secondary term by one and the primary
56 /// term by one more than a bound on the secondary term of any optimal route: the
57 /// number of vertices for bends (a shortest route never revisits a vertex), twice
58 /// the total edge length plus one for length (a route visits every
59 /// `(vertex, heading)` state at most once).
60 ///
61 /// # Errors
62 ///
63 /// [`Error::CostOverflow`] if the bound does not fit into `u64`.
64 pub fn weights(self, graph: &RoutingGraph) -> Result<Weights, Error> {
65 match self {
66 Self::Weighted { length, bend } => Ok(Weights { length, bend }),
67 Self::ShortestThenFewestBends => Ok(Weights {
68 length: u64::try_from(graph.len()).map_err(|_| Error::CostOverflow)? + 1,
69 bend: 1,
70 }),
71 Self::FewestBendsThenShortest => {
72 let total = graph.edges().try_fold(0_u64, |sum, (a, b)| {
73 sum.checked_add(graph.point(a).manhattan(graph.point(b)))
74 });
75 let bound = total
76 .and_then(|t| t.checked_mul(2))
77 .and_then(|t| t.checked_add(1))
78 .ok_or(Error::CostOverflow)?;
79
80 Ok(Weights {
81 length: 1,
82 bend: bound,
83 })
84 }
85 }
86 }
87}
88
89/// Extra costs a caller charges on top of length and bends, such as congestion.
90///
91/// The extra costs must be non-negative (they are `u64`), which keeps the free-space
92/// heuristic admissible.
93pub trait EdgeCosts {
94 /// The cost of moving from `from` in direction `dir` to its neighbour `to`, which
95 /// replaces `weights.length * length` for that edge. Must be at least
96 /// `length_weight * length` for the heuristic to stay admissible.
97 fn edge(&self, from: VertexId, dir: Direction, to: VertexId, length_cost: u64) -> u64 {
98 let _ = (from, dir, to);
99 length_cost
100 }
101
102 /// An extra cost for passing through `at`, entering with heading `entry` and leaving
103 /// with heading `exit`. `entry` is `None` at the source.
104 fn pass(&self, at: VertexId, entry: Option<Direction>, exit: Direction) -> u64 {
105 let _ = (at, entry, exit);
106 0
107 }
108}
109
110/// No extra cost: plain length and bends.
111#[derive(Debug, Clone, Copy, Default)]
112pub struct PlainCosts;
113
114impl EdgeCosts for PlainCosts {}
115
116/// A routing request between two graph vertices.
117#[derive(Debug, Clone, Copy)]
118pub struct Endpoints {
119 /// The source vertex.
120 pub source: VertexId,
121 /// The directions the route may leave the source in.
122 pub source_directions: DirSet,
123 /// The target vertex.
124 pub target: VertexId,
125 /// The directions the target port may be left in; the route arrives moving opposite
126 /// to one of them.
127 pub target_directions: DirSet,
128}
129
130/// A search state: a vertex slot and the heading index, or [`NOT_MOVED`].
131type State = (u32, u8);
132
133/// The heading of the start state, before the first move.
134const NOT_MOVED: u8 = 4;
135
136/// The `(vertex, heading)` state graph of a routing graph.
137struct StateGraph<'a, E> {
138 /// The routing graph.
139 graph: &'a RoutingGraph,
140 /// The source vertex and its allowed directions.
141 endpoints: Endpoints,
142 /// The objective weights.
143 weights: Weights,
144 /// Extra costs.
145 costs: &'a E,
146}
147
148impl<E: EdgeCosts> Successors for StateGraph<'_, E> {
149 type State = State;
150 type Action = Direction;
151 type Cost = u64;
152
153 fn successors(&self, state: &State, mut emit: impl FnMut(Direction, State, u64)) {
154 let v = VertexId(state.0);
155 let entry = (state.1 != NOT_MOVED).then(|| Direction::from_index(usize::from(state.1)));
156 // Straight first, then right, then left, as in the paper.
157 let options: [Option<Direction>; 4] = if let Some(h) = entry {
158 [Some(h), Some(h.right()), Some(h.left()), None]
159 } else {
160 let mut options = [None; 4];
161 for (slot, d) in options
162 .iter_mut()
163 .zip(self.endpoints.source_directions.iter())
164 {
165 *slot = Some(d);
166 }
167
168 options
169 };
170
171 let here = self.graph.point(v);
172 for dir in options.into_iter().flatten() {
173 let Some(w) = self.graph.neighbor(v, dir) else {
174 continue;
175 };
176
177 let length = here.manhattan(self.graph.point(w));
178 let length_cost = self.weights.length.saturating_mul(length);
179 let bend = if entry.is_some_and(|h| h != dir) {
180 self.weights.bend
181 } else {
182 0
183 };
184 let cost = self
185 .costs
186 .edge(v, dir, w, length_cost)
187 .saturating_add(bend)
188 .saturating_add(self.costs.pass(v, entry, dir));
189 let index = u8::try_from(dir.index()).expect("four directions");
190 emit(dir, (w.0, index), cost);
191 }
192 }
193}
194
195/// The admissible, consistent estimate of the remaining cost from `state`.
196fn estimate(
197 graph: &RoutingGraph,
198 endpoints: &Endpoints,
199 weights: Weights,
200 state: State,
201) -> Option<u64> {
202 let here = graph.point(VertexId(state.0));
203 let target = graph.point(endpoints.target);
204 let arrivals = endpoints.target_directions.reversed();
205 let bends = if state.1 == NOT_MOVED {
206 if state.0 == endpoints.target.0 {
207 0
208 } else {
209 endpoints
210 .source_directions
211 .iter()
212 .filter_map(|d| min_bends(here, d, target, arrivals))
213 .min()?
214 }
215 } else {
216 min_bends(
217 here,
218 Direction::from_index(usize::from(state.1)),
219 target,
220 arrivals,
221 )?
222 };
223
224 Some(
225 weights
226 .length
227 .saturating_mul(here.manhattan(target))
228 .saturating_add(weights.bend.saturating_mul(u64::from(bends))),
229 )
230}
231
232/// The cheapest route between two vertices of `graph`, or `None` if there is none.
233///
234/// A route between equal vertices is the single vertex, whatever the directions.
235#[must_use]
236pub fn route_vertices<E: EdgeCosts>(
237 graph: &RoutingGraph,
238 endpoints: Endpoints,
239 weights: Weights,
240 costs: &E,
241) -> Option<Route> {
242 let states = StateGraph {
243 graph,
244 endpoints,
245 weights,
246 costs,
247 };
248 let arrivals = endpoints.target_directions.reversed();
249 let target = endpoints.target.0;
250 let goal = move |s: &State| {
251 s.0 == target
252 && (s.1 == NOT_MOVED || arrivals.contains(Direction::from_index(usize::from(s.1))))
253 };
254 let heuristic = heuristic_fn(|s: &State| estimate(graph, &endpoints, weights, *s));
255 let result = a_star(
256 &states,
257 (endpoints.source.0, NOT_MOVED),
258 &goal,
259 heuristic,
260 Limits::NONE,
261 );
262 let solution = result.into_solution()?;
263 let vertices: Vec<VertexId> = solution.states.iter().map(|s| VertexId(s.0)).collect();
264
265 Some(Route::from_vertices(graph, vertices, solution.cost))
266}
267
268/// The endpoints of a connector between two ports of `scene`.
269///
270/// # Errors
271///
272/// [`Error::UnknownPort`] if a port does not exist, [`Error::PortBlocked`] if it lies
273/// inside an obstacle.
274pub fn endpoints(scene: &Scene, source: PortId, target: PortId) -> Result<Endpoints, Error> {
275 let vertex = |id: PortId| -> Result<(VertexId, DirSet), Error> {
276 let port = scene.port(id).ok_or(Error::UnknownPort)?;
277 let v = scene
278 .port_vertex(id)
279 .ok_or(Error::PortBlocked(port.point))?;
280
281 Ok((v, port.directions))
282 };
283 let (source, source_directions) = vertex(source)?;
284 let (target, target_directions) = vertex(target)?;
285
286 Ok(Endpoints {
287 source,
288 source_directions,
289 target,
290 target_directions,
291 })
292}
293
294/// Which single-connector search to use.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
296pub enum Search {
297 /// A* over the orthogonal visibility graph (Wybrow et al. 2009). Optimal on the
298 /// graph, which with the routing frame and port stubs matched brute force on the
299 /// unit grid for inputs spaced at least a few units apart (see `docs/design.md`).
300 #[default]
301 Ovg,
302 /// A* over the lazily generated 1-bend visibility graph (Marriott et al. 2014),
303 /// exploring only obstacle-hugging routes, with [`Search::Ovg`] as the fallback when
304 /// it finds nothing.
305 ///
306 /// Not exact in general: on a slit between touching boxes it returns length 38 with
307 /// 4 bends where the optimum is 20 with 6. Routes are always valid and never cheaper
308 /// than the optimum. In this lazy form it is also slower than [`Search::Ovg`].
309 OneBend,
310}
311
312/// The optimal route for one connector between two ports of `scene`.
313///
314/// # Errors
315///
316/// [`Error::UnknownPort`] or [`Error::PortBlocked`] for a bad port,
317/// [`Error::CostOverflow`] if the objective's weights overflow, and
318/// [`Error::NoRoute`] (with connector index 0) if the ports are not connected.
319///
320/// # Examples
321///
322/// ```
323/// use connector_routing::{DirSet, Objective, Point, Port, Rect, Scene, Search, route};
324///
325/// let mut scene = Scene::new();
326/// scene.add_obstacle(Rect::new(0, 0, 10, 10))?;
327/// let a = scene.add_port(Port::new(Point::new(-5, 5), DirSet::RIGHT))?;
328/// let b = scene.add_port(Port::new(Point::new(15, 5), DirSet::LEFT))?;
329///
330/// let r = route(&scene, a, b, Objective::default(), Search::default())?;
331/// assert_eq!(r.length, 30); // around the box: 5 + 5 + 10 + 5 + 5
332/// assert_eq!(r.bends, 4);
333/// # Ok::<(), connector_routing::Error>(())
334/// ```
335pub fn route(
336 scene: &Scene,
337 source: PortId,
338 target: PortId,
339 objective: Objective,
340 search: Search,
341) -> Result<Route, Error> {
342 let endpoints = endpoints(scene, source, target)?;
343 let weights = objective.weights(scene.graph())?;
344 let found = match search {
345 Search::Ovg => route_vertices(scene.graph(), endpoints, weights, &PlainCosts),
346 Search::OneBend => one_bend::route(scene, endpoints, weights)
347 .or_else(|| route_vertices(scene.graph(), endpoints, weights, &PlainCosts)),
348 };
349
350 found.ok_or(Error::NoRoute { connector: 0 })
351}
352
353/// The cost of a route of `length` and `bends` under `weights`, saturating.
354#[must_use]
355pub fn cost_of(weights: Weights, length: u64, bends: u32) -> u64 {
356 weights
357 .length
358 .saturating_mul(length)
359 .saturating_add(weights.bend.saturating_mul(u64::from(bends)))
360}