heuristic-search 0.2.1

Explicit-state heuristic graph search: A*, weighted and anytime, bounded-suboptimal, bidirectional, incremental and real-time search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Bidirectional best-first search with one open list per side:
//! [`bidirectional_dijkstra`], [`dibbs`] and [`bae_star`].

use core::cmp::Reverse;
use core::hash::Hash;

use alloc::vec::Vec;

use search_core::{Budget, Cost, Heuristic, Zero};

use crate::best_first::GraphResult;
use crate::bidirectional::mixed::{Both, Mixed, MixedGraph, Split, unmix};
use crate::bidirectional::{
    BidirectionalGraph, Core, Direction, Equality, MeetRelation, MeetResult, Meeting, Meets,
    RegressionGraph,
};
use crate::cost::CostExt;
use crate::keyed_set::KeyedSet;
use crate::outcome::Stats;
use crate::problem::Predecessors;
use crate::problem::Successors;
use crate::space::NodeId;

/// Bidirectional Dijkstra: uniform-cost search from both ends, cheapest path.
///
/// Expands the side whose cheapest open state has the smaller `g` and stops once
/// `g_min_F + g_min_B` reaches the cheapest meet. Optimal for non-negative costs.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, bidirectional_dijkstra};
///
/// /// A cycle of 10 nodes; going up costs 1, going down costs 3.
/// struct Ring;
///
/// impl Successors for Ring {
///     type State = u8;
///     type Action = bool;
///     type Cost = u32;
///
///     fn successors(&self, n: &u8, mut emit: impl FnMut(bool, u8, u32)) {
///         emit(true, (n + 1) % 10, 1);
///         emit(false, (n + 9) % 10, 3);
///     }
/// }
///
/// impl Predecessors for Ring {
///     type Node = u8;
///     type Action = bool;
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u8, mut emit: impl FnMut(bool, u8, u32)) {
///         emit(true, (n + 9) % 10, 1);
///         emit(false, (n + 1) % 10, 3);
///     }
/// }
///
/// let result = bidirectional_dijkstra(&Ring, 0, [8], Limits::NONE);
/// let solution = result.into_solution().expect("the ring is connected");
///
/// assert_eq!(solution.cost, 6);
/// assert_eq!(solution.actions, [false, false]);
/// ```
pub fn bidirectional_dijkstra<G>(
    graph: &G,
    start: G::State,
    goals: impl IntoIterator<Item = G::State>,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
{
    bidirectional_dijkstra_multi(graph, [start], goals, budget)
}

/// [`bidirectional_dijkstra`] from several start states at once.
///
/// Every start has path cost zero on the forward side, just as every goal has on the
/// backward side. Repeated starts count once, an empty set of starts finds nothing, and a
/// start that is a goal is returned as a zero-cost path.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, bidirectional_dijkstra_multi};
///
/// /// Counting up by one at cost 1, and back down for the backward search.
/// struct Up;
///
/// impl Successors for Up {
///     type State = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         emit((), n + 1, 1);
///     }
/// }
///
/// impl Predecessors for Up {
///     type Node = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         if let Some(previous) = n.checked_sub(1) {
///             emit((), previous, 1);
///         }
///     }
/// }
///
/// let result = bidirectional_dijkstra_multi(&Up, [0, 6, 3], [8], Limits::NONE);
///
/// assert_eq!(result.solution().map(|s| s.cost), Some(2));
/// ```
pub fn bidirectional_dijkstra_multi<G>(
    graph: &G,
    starts: impl IntoIterator<Item = G::State>,
    goals: impl IntoIterator<Item = G::State>,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
{
    let core = Core::new(
        graph,
        starts,
        goals,
        Zero,
        Zero,
        None::<Meeting<G, Equality>>,
    );

    Frontier::new(core, Rule::Dijkstra).run(budget)
}

/// Dynamically Improved Bounds Bidirectional Search (DIBBS, Sewell and Jacobson 2021).
///
/// Orders each side by `b = 2g + h - h_opposite`, where `h` estimates the distance to the
/// side's target and `h_opposite` the distance back to its own origin. It expands the side
/// with the smaller `b` and stops once `b_min_F + b_min_B >= 2 mu`. Optimal with
/// consistent heuristics; `forward` estimates the cost to the nearest goal, `backward` the
/// cost from the start.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, dibbs, heuristic_fn};
///
/// /// A line of integers; each step moves one to the left or right at cost 1.
/// struct Line;
///
/// impl Successors for Line {
///     type State = i32;
///     type Action = i32;
///     type Cost = u32;
///
///     fn successors(&self, state: &i32, mut emit: impl FnMut(i32, i32, u32)) {
///         emit(-1, state - 1, 1);
///         emit(1, state + 1, 1);
///     }
/// }
///
/// impl Predecessors for Line {
///     type Node = i32;
///     type Action = i32;
///     type Cost = u32;
///
///     fn predecessors(&self, state: &i32, mut emit: impl FnMut(i32, i32, u32)) {
///         emit(1, state - 1, 1);
///         emit(-1, state + 1, 1);
///     }
/// }
///
/// let to_goal = heuristic_fn(|s: &i32| Some(9_i32.abs_diff(*s)));
/// let from_start = heuristic_fn(|s: &i32| Some(0_i32.abs_diff(*s)));
/// let result = dibbs(&Line, 0, [9], to_goal, from_start, Limits::NONE);
///
/// assert_eq!(result.solution().map(|solution| solution.cost), Some(9));
/// ```
pub fn dibbs<G, HF, HB>(
    graph: &G,
    start: G::State,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    dibbs_multi(graph, [start], goals, forward, backward, budget)
}

/// [`dibbs`] from several start states at once.
///
/// Every start has path cost zero on the forward side, just as every goal has on the
/// backward side. Repeated starts count once, an empty set of starts finds nothing, and a
/// start that is a goal is returned as a zero-cost path. The backward heuristic must estimate
/// the cost back to the nearest start, which a heuristic towards one start overestimates.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, dibbs_multi, heuristic_fn};
///
/// /// Counting up by one at cost 1, and back down for the backward search.
/// struct Up;
///
/// impl Successors for Up {
///     type State = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         emit((), n + 1, 1);
///     }
/// }
///
/// impl Predecessors for Up {
///     type Node = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         if let Some(previous) = n.checked_sub(1) {
///             emit((), previous, 1);
///         }
///     }
/// }
///
/// let h = heuristic_fn(|n: &u32| 8_u32.checked_sub(*n));
/// let result = dibbs_multi(&Up, [0, 6, 3], [8], h, Zero, Limits::NONE);
///
/// assert_eq!(result.solution().map(|s| s.cost), Some(2));
/// ```
pub fn dibbs_multi<G, HF, HB>(
    graph: &G,
    starts: impl IntoIterator<Item = G::State>,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    let core = Core::new(
        graph,
        starts,
        goals,
        forward,
        backward,
        None::<Meeting<G, Equality>>,
    );

    Frontier::new(core, Rule::Dibbs).run(budget)
}

/// Bidirectional A* with error (BAE*, Sadhukhan 2013).
///
/// Uses the same `b = 2g + h - h_opposite` order and stopping rule as [`dibbs`] (`b` is
/// BAE*'s `f + d` with error term `d = g - h_opposite`) but picks the direction by the
/// cardinality criterion: the side with fewer open states expands. Optimal with consistent
/// heuristics.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, bae_star};
///
/// /// Counting up by one at cost 2; counting back down is not possible.
/// struct Up;
///
/// impl Successors for Up {
///     type State = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         emit((), n + 1, 2);
///     }
/// }
///
/// impl Predecessors for Up {
///     type Node = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         if let Some(previous) = n.checked_sub(1) {
///             emit((), previous, 2);
///         }
///     }
/// }
///
/// let result = bae_star(&Up, 3, [7], Zero, Zero, Limits::NONE);
///
/// assert_eq!(result.solution().map(|solution| solution.states.clone()), Some(vec![3, 4, 5, 6, 7]));
/// ```
pub fn bae_star<G, HF, HB>(
    graph: &G,
    start: G::State,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    bae_star_multi(graph, [start], goals, forward, backward, budget)
}

/// [`bae_star`] from several start states at once.
///
/// Every start has path cost zero on the forward side, just as every goal has on the
/// backward side. Repeated starts count once, an empty set of starts finds nothing, and a
/// start that is a goal is returned as a zero-cost path. The backward heuristic must estimate
/// the cost back to the nearest start, which a heuristic towards one start overestimates.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, bae_star_multi, heuristic_fn};
///
/// /// Counting up by one at cost 1, and back down for the backward search.
/// struct Up;
///
/// impl Successors for Up {
///     type State = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         emit((), n + 1, 1);
///     }
/// }
///
/// impl Predecessors for Up {
///     type Node = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         if let Some(previous) = n.checked_sub(1) {
///             emit((), previous, 1);
///         }
///     }
/// }
///
/// let h = heuristic_fn(|n: &u32| 8_u32.checked_sub(*n));
/// let result = bae_star_multi(&Up, [0, 6, 3], [8], h, Zero, Limits::NONE);
///
/// assert_eq!(result.solution().map(|s| s.cost), Some(2));
/// ```
pub fn bae_star_multi<G, HF, HB>(
    graph: &G,
    starts: impl IntoIterator<Item = G::State>,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    let core = Core::new(
        graph,
        starts,
        goals,
        forward,
        backward,
        None::<Meeting<G, Equality>>,
    );

    Frontier::new(core, Rule::Bae).run(budget)
}

/// How a [`Frontier`] search orders, picks a side and stops.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rule {
    /// Key `g`; smaller key expands; stop at `k_F + k_B >= mu`.
    Dijkstra,
    /// Key `b`; smaller key expands; stop at `k_F + k_B >= 2 mu`.
    Dibbs,
    /// Key `b`; the side with fewer open states expands; stop at `k_F + k_B >= 2 mu`.
    Bae,
}

/// Open-list order of one side: smallest key, then larger `g`, then node id.
type Key<C> = (C, Reverse<C>);

/// [`bidirectional_dijkstra`] that meets by a [`MeetRelation`] instead of state equality, from several
/// starts at once.
///
/// `goals` are backward nodes of the graph's [`Predecessors::Node`](crate::Predecessors)
/// type, such as subgoals (partial states), and `meet` decides which forward states meet
/// which backward nodes (see [`MeetRelation`] for the contract). The returned path is
/// rebuilt from the meeting state by replaying the backward actions forwards, through the
/// first successor edge with an equal label, so every state on it is a real state and its
/// cost the true cost.
///
/// Both heuristics are evaluated on states and on backward nodes, so they implement
/// [`Heuristic`] for both types ([`Zero`] does). On a backward node such as a subgoal,
/// each must keep its guarantee (admissible, and consistent where the search needs it)
/// when read as the cheapest value over the states that satisfy the node.
///
/// # Errors
///
/// [`ReplayError`](crate::ReplayError) if a replay step finds no successor edge with the backward action's
/// label: the relation or the predecessors disagree with the successors.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, bidirectional_dijkstra_meet, meet_fn};
///
/// /// Three facts as bits; action `k` makes fact `k` true at cost 1.
/// struct Facts;
///
/// impl Successors for Facts {
///     type State = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn successors(&self, state: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if state & (1 << k) == 0 {
///                 emit(k, state | (1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // Regression: a subgoal is a set of facts that must hold; action `k` achieves fact `k`.
/// impl Predecessors for Facts {
///     type Node = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn predecessors(&self, subgoal: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if subgoal & (1 << k) != 0 {
///                 emit(k, subgoal & !(1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // A state meets a subgoal it satisfies.
/// let satisfies = meet_fn(|state: &u8, subgoal: &u8| state & subgoal == *subgoal);
/// let result = bidirectional_dijkstra_meet(&Facts, [0], [0b110], satisfies, Limits::NONE);
///
/// let solution = result.expect("the model replays").into_solution().expect("facts 1 and 2 are reachable");
/// assert_eq!(solution.cost, 2);
/// assert_eq!(solution.states.len(), 3);
/// assert_eq!(solution.goal() & 0b110, 0b110);
/// ```
pub fn bidirectional_dijkstra_meet<G, M>(
    graph: &G,
    starts: impl IntoIterator<Item = <G as Successors>::State>,
    goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
    meet: M,
    budget: impl Budget<Stats>,
) -> MeetResult<G>
where
    G: RegressionGraph,
    <G as Successors>::State: Clone + Hash + Eq,
    <G as Predecessors>::Node: Clone + Hash + Eq,
    <G as Successors>::Action: Clone + PartialEq,
    <G as Successors>::Cost: CostExt,
    M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
    let mixed = MixedGraph(graph);
    let core = Core::new(
        &mixed,
        starts.into_iter().map(Mixed::State),
        goals.into_iter().map(Mixed::Node),
        Zero,
        Zero,
        Some(Meeting::new(Split(meet))),
    );

    unmix(Frontier::new(core, Rule::Dijkstra).run(budget))
}

/// [`dibbs`] that meets by a [`MeetRelation`] instead of state equality, from several
/// starts at once.
///
/// `goals` are backward nodes of the graph's [`Predecessors::Node`](crate::Predecessors)
/// type, such as subgoals (partial states), and `meet` decides which forward states meet
/// which backward nodes (see [`MeetRelation`] for the contract). The returned path is
/// rebuilt from the meeting state by replaying the backward actions forwards, through the
/// first successor edge with an equal label, so every state on it is a real state and its
/// cost the true cost.
///
/// Both heuristics are evaluated on states and on backward nodes, so they implement
/// [`Heuristic`] for both types ([`Zero`] does). On a backward node such as a subgoal,
/// each must keep its guarantee (admissible, and consistent where the search needs it)
/// when read as the cheapest value over the states that satisfy the node.
///
/// # Errors
///
/// [`ReplayError`](crate::ReplayError) if a replay step finds no successor edge with the backward action's
/// label: the relation or the predecessors disagree with the successors.
///
/// The backward heuristic estimates the cost from the starts to a backward node.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, dibbs_meet, meet_fn};
///
/// /// Three facts as bits; action `k` makes fact `k` true at cost 1.
/// struct Facts;
///
/// impl Successors for Facts {
///     type State = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn successors(&self, state: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if state & (1 << k) == 0 {
///                 emit(k, state | (1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // Regression: a subgoal is a set of facts that must hold; action `k` achieves fact `k`.
/// impl Predecessors for Facts {
///     type Node = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn predecessors(&self, subgoal: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if subgoal & (1 << k) != 0 {
///                 emit(k, subgoal & !(1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // A state meets a subgoal it satisfies.
/// let satisfies = meet_fn(|state: &u8, subgoal: &u8| state & subgoal == *subgoal);
/// let result = dibbs_meet(&Facts, [0], [0b110], Zero, Zero, satisfies, Limits::NONE);
///
/// let solution = result.expect("the model replays").into_solution().expect("facts 1 and 2 are reachable");
/// assert_eq!(solution.cost, 2);
/// assert_eq!(solution.states.len(), 3);
/// assert_eq!(solution.goal() & 0b110, 0b110);
/// ```
pub fn dibbs_meet<G, HF, HB, M>(
    graph: &G,
    starts: impl IntoIterator<Item = <G as Successors>::State>,
    goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
    forward: HF,
    backward: HB,
    meet: M,
    budget: impl Budget<Stats>,
) -> MeetResult<G>
where
    G: RegressionGraph,
    <G as Successors>::State: Clone + Hash + Eq,
    <G as Predecessors>::Node: Clone + Hash + Eq,
    <G as Successors>::Action: Clone + PartialEq,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    HB: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
    let mixed = MixedGraph(graph);
    let core = Core::new(
        &mixed,
        starts.into_iter().map(Mixed::State),
        goals.into_iter().map(Mixed::Node),
        Both(forward),
        Both(backward),
        Some(Meeting::new(Split(meet))),
    );

    unmix(Frontier::new(core, Rule::Dibbs).run(budget))
}

/// [`bae_star`] that meets by a [`MeetRelation`] instead of state equality, from several
/// starts at once.
///
/// `goals` are backward nodes of the graph's [`Predecessors::Node`](crate::Predecessors)
/// type, such as subgoals (partial states), and `meet` decides which forward states meet
/// which backward nodes (see [`MeetRelation`] for the contract). The returned path is
/// rebuilt from the meeting state by replaying the backward actions forwards, through the
/// first successor edge with an equal label, so every state on it is a real state and its
/// cost the true cost.
///
/// Both heuristics are evaluated on states and on backward nodes, so they implement
/// [`Heuristic`] for both types ([`Zero`] does). On a backward node such as a subgoal,
/// each must keep its guarantee (admissible, and consistent where the search needs it)
/// when read as the cheapest value over the states that satisfy the node.
///
/// # Errors
///
/// [`ReplayError`](crate::ReplayError) if a replay step finds no successor edge with the backward action's
/// label: the relation or the predecessors disagree with the successors.
///
/// The backward heuristic estimates the cost from the starts to a backward node.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, bae_star_meet, meet_fn};
///
/// /// Three facts as bits; action `k` makes fact `k` true at cost 1.
/// struct Facts;
///
/// impl Successors for Facts {
///     type State = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn successors(&self, state: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if state & (1 << k) == 0 {
///                 emit(k, state | (1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // Regression: a subgoal is a set of facts that must hold; action `k` achieves fact `k`.
/// impl Predecessors for Facts {
///     type Node = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn predecessors(&self, subgoal: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if subgoal & (1 << k) != 0 {
///                 emit(k, subgoal & !(1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // A state meets a subgoal it satisfies.
/// let satisfies = meet_fn(|state: &u8, subgoal: &u8| state & subgoal == *subgoal);
/// let result = bae_star_meet(&Facts, [0], [0b110], Zero, Zero, satisfies, Limits::NONE);
///
/// let solution = result.expect("the model replays").into_solution().expect("facts 1 and 2 are reachable");
/// assert_eq!(solution.cost, 2);
/// assert_eq!(solution.states.len(), 3);
/// assert_eq!(solution.goal() & 0b110, 0b110);
/// ```
pub fn bae_star_meet<G, HF, HB, M>(
    graph: &G,
    starts: impl IntoIterator<Item = <G as Successors>::State>,
    goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
    forward: HF,
    backward: HB,
    meet: M,
    budget: impl Budget<Stats>,
) -> MeetResult<G>
where
    G: RegressionGraph,
    <G as Successors>::State: Clone + Hash + Eq,
    <G as Predecessors>::Node: Clone + Hash + Eq,
    <G as Successors>::Action: Clone + PartialEq,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    HB: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
    let mixed = MixedGraph(graph);
    let core = Core::new(
        &mixed,
        starts.into_iter().map(Mixed::State),
        goals.into_iter().map(Mixed::Node),
        Both(forward),
        Both(backward),
        Some(Meeting::new(Split(meet))),
    );

    unmix(Frontier::new(core, Rule::Bae).run(budget))
}

/// A bidirectional search with one keyed open list per side.
struct Frontier<'a, G: BidirectionalGraph, HF, HB, M> {
    /// Both sides, the heuristics, the counters and the best meet.
    core: Core<'a, G, HF, HB, M>,
    /// The open lists, indexed by [`Direction::index`].
    open: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
    /// The ordering, side-selection and stopping rule.
    rule: Rule,
}

impl<'a, G, HF, HB, M> Frontier<'a, G, HF, HB, M>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    <G as Successors>::Cost: CostExt,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
    M: Meets<G::State>,
{
    /// Opens the live seeds of both sides.
    fn new(core: Core<'a, G, HF, HB, M>, rule: Rule) -> Self {
        let mut search = Self {
            core,
            open: [KeyedSet::new(), KeyedSet::new()],
            rule,
        };

        for direction in [Direction::Forward, Direction::Backward] {
            for id in 0..search.core.side(direction).space.len() {
                search.open(direction, id);
            }
        }

        search
    }

    /// Expands until the stopping rule holds, a side runs empty or the budget is used up.
    fn run(mut self, mut budget: impl Budget<Stats>) -> GraphResult<G> {
        let mut touched = Vec::new();
        loop {
            let (Some(forward), Some(backward)) = (
                self.min_key(Direction::Forward),
                self.min_key(Direction::Backward),
            ) else {
                return self.core.finish(true);
            };

            if self.stops(forward, backward) {
                return self.core.finish(true);
            }

            if budget.exhausted(&self.core.stats) {
                return self.core.finish(false);
            }

            let direction = self.pick(forward, backward);
            let (_, node) = self.open[direction.index()]
                .first()
                .expect("the side is not empty");
            self.open[direction.index()].remove(node);
            self.core.expand(direction, node, true, &mut touched);
            for id in touched.drain(..) {
                self.open(direction, id);
            }
        }
    }

    /// The smallest key open on `direction`'s side.
    fn min_key(&self, direction: Direction) -> Option<<G as Successors>::Cost> {
        self.open[direction.index()].first().map(|(key, _)| key.0)
    }

    /// Returns `true` if the keys `forward` and `backward` prove the best meet optimal.
    fn stops(&self, forward: <G as Successors>::Cost, backward: <G as Successors>::Cost) -> bool {
        let sum = forward.saturating_add(backward);

        match self.rule {
            Rule::Dijkstra => self.core.proven(sum),
            Rule::Dibbs | Rule::Bae => self
                .core
                .mu()
                .is_some_and(|mu| sum.cmp(&mu.saturating_times(2)).is_ge()),
        }
    }

    /// The direction to expand next.
    fn pick(
        &self,
        forward: <G as Successors>::Cost,
        backward: <G as Successors>::Cost,
    ) -> Direction {
        let forward_first = match self.rule {
            Rule::Dijkstra | Rule::Dibbs => forward.cmp(&backward).is_le(),
            Rule::Bae => self.open[0].len() <= self.open[1].len(),
        };

        if forward_first {
            Direction::Forward
        } else {
            Direction::Backward
        }
    }

    /// Opens (or re-keys) the live node `id` on `direction`'s side.
    fn open(&mut self, direction: Direction, id: NodeId) {
        let Some((h, h_opposite)) = self.core.h(direction, id) else {
            return;
        };

        let g = self.core.g(direction, id);
        let key = match self.rule {
            Rule::Dijkstra => g,
            Rule::Dibbs | Rule::Bae => (g + g + h).saturating_sub(h_opposite),
        };

        self.open[direction.index()].insert(id, (key, Reverse(g)));
    }
}