heuristic_search/bidirectional/meet.rs
1//! When the two frontiers of a bidirectional search meet: the [`MeetRelation`] capability,
2//! the scanning relation [`MeetFn`], and the replay that turns a meet into a real path or
3//! a [`ReplayError`].
4//!
5//! By default a forward state meets a backward node when they are equal, found through the
6//! hash index both sides already keep. A [`MeetRelation`] replaces that with any relation,
7//! such as "the state satisfies the subgoal" for regression over partial states, and owns
8//! whatever index makes the relation fast (per-fact buckets, a trie, a plain list).
9
10use alloc::vec::Vec;
11use core::fmt;
12use core::marker::PhantomData;
13
14use crate::best_first::GraphResult;
15use crate::problem::Successors;
16
17/// A direction of a bidirectional search, and so a side of its frontier.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub(crate) enum Direction {
20 /// From the starts along successor edges.
21 Forward = 0,
22 /// From the goals along predecessor edges.
23 Backward = 1,
24}
25
26impl Direction {
27 /// The other direction.
28 pub(crate) const fn opposite(self) -> Self {
29 match self {
30 Self::Forward => Self::Backward,
31 Self::Backward => Self::Forward,
32 }
33 }
34
35 /// The index of this direction: `0` forward, `1` backward.
36 pub(crate) const fn index(self) -> usize {
37 self as usize
38 }
39}
40
41/// Which forward states (`S`) meet which backward nodes (`N`) in a bidirectional search.
42///
43/// A forward state `s` *meets* a backward node `n` when a path from `s` to a goal is known
44/// through `n`: the backward search reached `n` from a goal, so the actions along `n`'s
45/// backward links lead from `s` to a goal. With plain states that is `s == n`, the default
46/// of the searches without `_meet`. For regression over subgoals (partial states, possibly
47/// of another type than states) it is "`s` satisfies `n`".
48///
49/// The search reports every node it creates, with a dense id per side (`0, 1, 2, ...` in
50/// creation order), and asks for the opposite-side ids that meet a new or improved node.
51/// The relation keeps its own index of the inserted nodes (per-fact buckets, a trie, a
52/// list).
53///
54/// # Contract
55///
56/// The stopping rules of the searches assume every start-goal path has a point where a
57/// forward state meets a backward node: for regression, the subgoal obtained by regressing
58/// a goal along the rest of the path is satisfied by the state on the path. Then the
59/// returned solutions keep the guarantees of plain bidirectional search.
60///
61/// # Examples
62///
63/// Equality, indexed by the lowest bit:
64///
65/// ```
66/// use heuristic_search::MeetRelation;
67///
68/// /// `[side][bit]` lists `(id, state)`; side 0 is forward.
69/// #[derive(Default)]
70/// struct Buckets([[Vec<(usize, u32)>; 2]; 2]);
71///
72/// impl Buckets {
73/// /// The ids in `side`'s bucket of `state` that equal it.
74/// fn equal(&self, side: usize, state: u32, mut emit: impl FnMut(usize)) {
75/// for &(id, other) in &self.0[side][(state & 1) as usize] {
76/// if other == state {
77/// emit(id);
78/// }
79/// }
80/// }
81/// }
82///
83/// impl MeetRelation<u32> for Buckets {
84/// fn insert_forward(&mut self, id: usize, state: &u32) {
85/// self.0[0][(*state & 1) as usize].push((id, *state));
86/// }
87///
88/// fn insert_backward(&mut self, id: usize, node: &u32) {
89/// self.0[1][(*node & 1) as usize].push((id, *node));
90/// }
91///
92/// fn meets_forward(&self, state: &u32, emit: impl FnMut(usize)) {
93/// self.equal(1, *state, emit);
94/// }
95///
96/// fn meets_backward(&self, node: &u32, emit: impl FnMut(usize)) {
97/// self.equal(0, *node, emit);
98/// }
99/// }
100///
101/// let mut buckets = Buckets::default();
102/// buckets.insert_backward(0, &6);
103/// let mut met = Vec::new();
104/// buckets.meets_forward(&6, |id| met.push(id));
105/// assert_eq!(met, [0]);
106/// ```
107pub trait MeetRelation<S, N = S> {
108 /// Records the new forward node `id` with `state`.
109 fn insert_forward(&mut self, id: usize, state: &S);
110
111 /// Records the new backward node `id` with `node`.
112 fn insert_backward(&mut self, id: usize, node: &N);
113
114 /// Calls `emit(id)` for every backward node that `state` meets.
115 fn meets_forward(&self, state: &S, emit: impl FnMut(usize));
116
117 /// Calls `emit(id)` for every forward state that meets `node`.
118 fn meets_backward(&self, node: &N, emit: impl FnMut(usize));
119}
120
121impl<S, N, M: MeetRelation<S, N> + ?Sized> MeetRelation<S, N> for &mut M {
122 fn insert_forward(&mut self, id: usize, state: &S) {
123 (**self).insert_forward(id, state);
124 }
125
126 fn insert_backward(&mut self, id: usize, node: &N) {
127 (**self).insert_backward(id, node);
128 }
129
130 fn meets_forward(&self, state: &S, emit: impl FnMut(usize)) {
131 (**self).meets_forward(state, emit);
132 }
133
134 fn meets_backward(&self, node: &N, emit: impl FnMut(usize)) {
135 (**self).meets_backward(node, emit);
136 }
137}
138
139/// A [`MeetRelation`] from a closure `meets(forward_state, backward_node) -> bool`, checked
140/// against every node of the opposite side; created by [`meet_fn`].
141///
142/// Each check scans the whole opposite side, so a search costs time quadratic in the number
143/// of nodes. Fine for small problems and tests; implement [`MeetRelation`] with an index
144/// for large ones.
145#[derive(Debug, Clone)]
146pub struct MeetFn<F, S, N> {
147 /// The relation, forward state first.
148 relation: F,
149 /// The forward states as `(id, state)`.
150 forward: Vec<(usize, S)>,
151 /// The backward nodes as `(id, node)`.
152 backward: Vec<(usize, N)>,
153}
154
155/// Turns a closure `Fn(&S, &N) -> bool` (forward state, backward node) into a scanning
156/// [`MeetRelation`].
157///
158/// # Examples
159///
160/// ```
161/// use heuristic_search::{MeetRelation, meet_fn};
162///
163/// // A state (a bit set of facts) meets a subgoal it contains.
164/// let mut satisfies = meet_fn(|state: &u8, subgoal: &u8| state & subgoal == *subgoal);
165/// satisfies.insert_backward(0, &0b011);
166/// satisfies.insert_backward(1, &0b100);
167///
168/// let mut met = Vec::new();
169/// satisfies.meets_forward(&0b111, |id| met.push(id));
170/// assert_eq!(met, [0, 1]);
171/// ```
172pub fn meet_fn<S, N, F: Fn(&S, &N) -> bool>(relation: F) -> MeetFn<F, S, N> {
173 MeetFn {
174 relation,
175 forward: Vec::new(),
176 backward: Vec::new(),
177 }
178}
179
180impl<S: Clone, N: Clone, F: Fn(&S, &N) -> bool> MeetRelation<S, N> for MeetFn<F, S, N> {
181 fn insert_forward(&mut self, id: usize, state: &S) {
182 self.forward.push((id, state.clone()));
183 }
184
185 fn insert_backward(&mut self, id: usize, node: &N) {
186 self.backward.push((id, node.clone()));
187 }
188
189 fn meets_forward(&self, state: &S, mut emit: impl FnMut(usize)) {
190 for (id, node) in &self.backward {
191 if (self.relation)(state, node) {
192 emit(*id);
193 }
194 }
195 }
196
197 fn meets_backward(&self, node: &N, mut emit: impl FnMut(usize)) {
198 for (id, state) in &self.forward {
199 if (self.relation)(state, node) {
200 emit(*id);
201 }
202 }
203 }
204}
205
206/// A `_meet` search could not turn its meet into a path of real states: `state` has no
207/// successor edge labelled `action`, although the backward search used that action.
208///
209/// The meet relation or the [`Predecessors`](crate::Predecessors) disagree with the
210/// [`Successors`]: regression produced a subgoal that the forward model cannot follow.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct ReplayError<S, A> {
213 /// The real state the replay had reached.
214 pub state: S,
215 /// The backward action it could not apply to `state`.
216 pub action: A,
217}
218
219impl<S, A> fmt::Display for ReplayError<S, A> {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 f.write_str("a backward action has no matching successor edge from the meeting path")
222 }
223}
224
225impl<S: fmt::Debug, A: fmt::Debug> core::error::Error for ReplayError<S, A> {}
226
227/// What a `_meet` search returns: the search result, or the [`ReplayError`] if its
228/// solution could not be replayed as real states.
229pub type MeetResult<G> =
230 Result<GraphResult<G>, ReplayError<<G as Successors>::State, <G as Successors>::Action>>;
231
232/// The internal, direction-based meet the bidirectional core asks; one node type for both
233/// sides. [`MeetRelation`]s reach it through `Split` over mixed nodes.
234pub(crate) trait Meets<T> {
235 /// Records the new node `id` with `node` on `direction`'s side.
236 fn insert(&mut self, direction: Direction, id: usize, node: &T);
237
238 /// Calls `emit(id)` for every node on the opposite side that meets `node`.
239 fn meets(&self, direction: Direction, node: &T, emit: impl FnMut(usize));
240}
241
242/// The default meet: equality through the sides' own hash index. Never asked.
243pub(crate) struct Equality;
244
245impl<S> Meets<S> for Equality {
246 fn insert(&mut self, _: Direction, _: usize, _: &S) {}
247
248 fn meets(&self, _: Direction, _: &S, _: impl FnMut(usize)) {}
249}
250
251/// Applies `action` to `state` forwards: the successor reached by an edge with that label
252/// and its cost, or `None` if `state` has no such edge.
253pub(crate) type ReplayFn<G> = fn(
254 &G,
255 &<G as Successors>::State,
256 &<G as Successors>::Action,
257) -> Option<(<G as Successors>::State, <G as Successors>::Cost)>;
258
259/// A relation-based meet: the relation and the replay that rebuilds real states past the
260/// meeting point.
261pub(crate) struct Meeting<G: Successors, M> {
262 /// Decides which nodes meet.
263 pub(crate) relation: M,
264 /// Replays backward actions forwards from the meeting state.
265 pub(crate) replay: ReplayFn<G>,
266 /// Ties the replay's graph type to the meeting.
267 graph: PhantomData<fn(&G)>,
268}
269
270impl<G: Successors, M> Meeting<G, M> {
271 /// A meeting by `relation`, replaying actions through the first successor edge with an
272 /// equal label.
273 pub(crate) fn new(relation: M) -> Self
274 where
275 G::Action: PartialEq,
276 G::State: Clone,
277 {
278 Self {
279 relation,
280 replay: replay_step::<G>,
281 graph: PhantomData,
282 }
283 }
284}
285
286/// The successor of `state` along the first edge labelled `action`, and its cost.
287fn replay_step<G>(graph: &G, state: &G::State, action: &G::Action) -> Option<(G::State, G::Cost)>
288where
289 G: Successors,
290 G::Action: PartialEq,
291 G::State: Clone,
292{
293 let mut found = None;
294 graph.successors(state, |label, next, cost| {
295 if found.is_none() && label == *action {
296 found = Some((next, cost));
297 }
298 });
299
300 found
301}