Skip to main content

constraint_search/
search.rs

1//! Backtracking search: the [`Solver`] that finds, counts and enumerates solutions of a
2//! [`Model`].
3//!
4//! Each node picks an unfixed variable, tries its values in turn and propagates after each
5//! choice; a conflict undoes the choice through the trail.
6
7mod analysis;
8mod order;
9mod walk;
10
11use alloc::vec::Vec;
12use core::ops::ControlFlow;
13
14use search_core::Budget;
15
16use crate::propagator::Engine;
17use crate::{Domain, Domains, Inconsistent, Model};
18pub use analysis::Marginals;
19use order::OrderState;
20pub use order::{ValueOrder, VarOrder};
21pub use walk::Progress;
22use walk::{Frame, Phase};
23
24/// Counters collected during one search.
25///
26/// Non-exhaustive: later versions may add counters. Start from [`Stats::default`] where a
27/// value is needed.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct Stats {
31    /// Search nodes entered, the root included.
32    pub nodes: u64,
33    /// Value choices that propagation refuted.
34    pub failures: u64,
35    /// Full assignments found.
36    pub solutions: u64,
37}
38
39impl Stats {
40    /// The counters of `self` and `other` added up, for searches made of several parts.
41    pub(crate) fn plus(self, other: Self) -> Self {
42        Self {
43            nodes: self.nodes + other.nodes,
44            failures: self.failures + other.failures,
45            solutions: self.solutions + other.solutions,
46        }
47    }
48}
49
50/// How a search ended.
51///
52/// `T` is the solution: the value of every variable for a [`Solver`], the chosen rows for an
53/// [`ExactCover`](crate::ExactCover).
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Outcome<T = Vec<u32>> {
56    /// A solution: for a [`Solver`], the value of every variable in index order.
57    Solved(T),
58    /// The search space is exhausted: no solution exists.
59    Unsatisfiable,
60    /// The budget stopped the search first.
61    Exhausted,
62}
63
64/// How many solutions a count found.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Count {
67    /// The search space was exhausted: there are exactly this many solutions.
68    Exact(u64),
69    /// The count stopped at the limit or at the budget: there are at least this many.
70    AtLeast(u64),
71}
72
73/// Why [`Solver::for_each_solution`] returned.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Status {
76    /// The search space is exhausted: every solution was reported.
77    Complete,
78    /// The callback asked to stop.
79    Stopped,
80    /// The budget stopped the search first.
81    Exhausted,
82}
83
84/// What a search returns: its result and the counters that led to it.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Report<T> {
87    /// The result.
88    pub outcome: T,
89    /// The work the search did.
90    pub stats: Stats,
91}
92
93/// Backtracking search over a shared [`Model`], with reusable working state.
94///
95/// The solver owns the current domains, their trail, the propagation queue and every
96/// propagator's scratch memory, and keeps their allocations from one solve to the next:
97/// once warmed up, [`Solver::count`] and [`Solver::for_each_solution`] allocate nothing, and
98/// [`Solver::solve`] allocates only the solution it returns. [`Solver::reset`] returns to the model's
99/// initial domains without reallocating. Search leaves the domains as it found them, so a
100/// caller can fix some variables ([`Solver::domains_mut`]) and search many times from there.
101///
102/// [`Solver::solve`], [`Solver::count`] and [`Solver::for_each_solution`] run one search to
103/// its end or budget. For time slicing, [`Solver::begin`] starts a search that
104/// [`Solver::resume`] continues a little at a time, pausing at each solution or when its
105/// budget runs out.
106///
107/// The model is only borrowed and is `Sync`, so threads can each run a solver over one model.
108/// Fixing different variables per solver splits the search tree into independent subtrees,
109/// and differing [`VarOrder`]s and [`ValueOrder`]s make a portfolio. A shared stop flag goes
110/// into the budget, which every node consults.
111///
112/// Each search node picks an unfixed variable, tries its values in turn and propagates after
113/// each choice; a conflict undoes the choice through the trail.
114///
115/// ```mermaid
116/// flowchart LR
117///     node([node]) --> pick{unfixed variable?}
118///     pick -->|none| solution([solution])
119///     pick -->|"pick by VarOrder"| value[next value by ValueOrder]
120///     value --> propagate[assign and propagate]
121///     propagate -->|ok| node
122///     propagate -->|conflict| undo[undo] --> value
123/// ```
124///
125/// # Examples
126///
127/// The 3×3 Latin squares: each row and column holds 0, 1 and 2 once.
128///
129/// ```
130/// use constraint_search::{AllDifferent, Count, Domain, Model, Solver};
131///
132/// let mut model = Model::<u16>::new();
133/// let cells = model.add_vars(9, u16::range(3));
134/// for i in 0..3 {
135///     model.add(AllDifferent::new((0..3).map(|j| cells[3 * i + j])));
136///     model.add(AllDifferent::new((0..3).map(|j| cells[3 * j + i])));
137/// }
138///
139/// let mut solver = Solver::new(&model);
140/// let report = solver.count(u64::MAX, |_: &_| false);
141/// assert_eq!(report.outcome, Count::Exact(12));
142///
143/// // Fix the first row and the square is unique up to the remaining rows.
144/// for (j, value) in [0, 1, 2].into_iter().enumerate() {
145///     solver.domains_mut().assign(cells[j], value)?;
146/// }
147/// assert_eq!(solver.count(u64::MAX, |_: &_| false).outcome, Count::Exact(2));
148/// # Ok::<(), constraint_search::Inconsistent>(())
149/// ```
150pub struct Solver<'m, D> {
151    /// The problem being solved.
152    model: &'m Model<D>,
153    /// The current domains and their trail.
154    domains: Domains<D>,
155    /// The propagation queue and each propagator's scratch memory.
156    engine: Engine,
157    /// The values still to try at each open search node, stacked: a node's values sit above
158    /// its parent's and are popped when the node returns.
159    values: Vec<u32>,
160    /// Scratch and state of the value orderings.
161    ordering: OrderState,
162    /// The open nodes of the search in progress, root first.
163    frames: Vec<Frame>,
164    /// The next step of the search in progress.
165    phase: Phase,
166    /// The trail level of the domains when the search began.
167    base_level: usize,
168    /// A value per variable to try first when branching on it; empty for none.
169    hint: Vec<u32>,
170    /// How to pick the variable to branch on.
171    var_order: VarOrder,
172    /// How to order the values of that variable.
173    value_order: ValueOrder,
174}
175
176impl<'m, D: Domain> Solver<'m, D> {
177    /// A solver over `model`, starting from its initial domains, branching with
178    /// [`VarOrder::Mrv`] and [`ValueOrder::Ascending`].
179    #[must_use]
180    pub fn new(model: &'m Model<D>) -> Self {
181        let mut solver = Self {
182            model,
183            domains: Domains::new(),
184            engine: Engine::new(model),
185            values: Vec::new(),
186            ordering: OrderState::default(),
187            frames: Vec::new(),
188            phase: Phase::Idle,
189            base_level: 0,
190            hint: Vec::new(),
191            var_order: VarOrder::default(),
192            value_order: ValueOrder::default(),
193        };
194        solver.reset();
195
196        solver
197    }
198
199    /// Sets how to pick the variable to branch on.
200    #[must_use]
201    pub fn with_var_order(mut self, order: VarOrder) -> Self {
202        self.var_order = order;
203        self
204    }
205
206    /// Sets how to order the values of the branching variable.
207    #[must_use]
208    pub fn with_value_order(mut self, order: ValueOrder) -> Self {
209        self.value_order = order;
210        self
211    }
212
213    /// Tries `values[i]` first whenever the search branches on variable `i`, then the other
214    /// values in the [`ValueOrder`]. A hint value no longer in the domain is skipped.
215    ///
216    /// Give a known solution as the hint to find it first: a generator that digs clues out of
217    /// a solved puzzle checks uniqueness with [`Solver::count`] and a limit of 2, and the hint
218    /// turns finding the first solution into a straight walk, leaving only the search for a
219    /// second. The hint stays set across searches and [`Solver::reset`].
220    ///
221    /// # Panics
222    ///
223    /// Panics if `values` does not hold exactly one value per variable of the model.
224    pub fn set_hint(&mut self, values: &[u32]) {
225        assert_eq!(
226            values.len(),
227            self.model.num_vars(),
228            "a hint needs one value per variable"
229        );
230
231        self.hint.clear();
232        self.hint.extend_from_slice(values);
233    }
234
235    /// Removes the hint set by [`Solver::set_hint`].
236    pub fn clear_hint(&mut self) {
237        self.hint.clear();
238    }
239
240    /// Returns to the model's initial domains, keeping every allocation. Abandons a search in
241    /// progress.
242    pub fn reset(&mut self) {
243        self.abandon();
244        self.domains.reset_to(self.model.initial_domains());
245    }
246
247    /// The current domains.
248    #[must_use]
249    pub fn domains(&self) -> &Domains<D> {
250        &self.domains
251    }
252
253    /// The current domains, to fix or restrict variables before a search. Abandons a search
254    /// in progress, which owns the domains until it completes.
255    pub fn domains_mut(&mut self) -> &mut Domains<D> {
256        self.abandon();
257        &mut self.domains
258    }
259
260    /// Runs every propagator to a fixpoint on the current domains, keeping the result.
261    ///
262    /// # Errors
263    ///
264    /// Returns [`Inconsistent`] if the constraints cannot be satisfied. The domains are then
265    /// partly propagated; [`Solver::reset`] starts over.
266    ///
267    /// Abandons a search in progress first, since that search owns the domains.
268    pub fn propagate(&mut self) -> Result<(), Inconsistent> {
269        self.abandon();
270        self.engine.fixpoint(self.model, &mut self.domains)
271    }
272
273    /// Finds one solution.
274    ///
275    /// Like [`Solver::count`] and [`Solver::for_each_solution`], this runs a search of its own
276    /// from the current domains: it abandons a search in progress (see [`Solver::begin`]),
277    /// which restores the domains to where that search began, and leaves them as it found
278    /// them.
279    pub fn solve(&mut self, budget: impl Budget<Stats>) -> Report<Outcome> {
280        first_solution(|found| {
281            self.for_each_solution(budget, |domains| {
282                *found = domains.solution();
283                ControlFlow::Break(())
284            })
285        })
286    }
287
288    /// Counts solutions, stopping at `limit`.
289    ///
290    /// A limit of 2 decides uniqueness: `Count::Exact(1)` means exactly one solution, and
291    /// `Count::AtLeast(2)` more than one. A limit of 0 searches nothing and reports
292    /// `Count::AtLeast(0)`.
293    ///
294    /// Abandons a search in progress, as [`Solver::solve`] does.
295    pub fn count(&mut self, limit: u64, budget: impl Budget<Stats>) -> Report<Count> {
296        // Even a zero limit, which searches nothing, abandons the search in progress.
297        self.abandon();
298        count_up_to(limit, |tally| self.for_each_solution(budget, |_| tally()))
299    }
300
301    /// Calls `on_solution` with the domains of every solution, each holding one value per
302    /// variable, until it returns [`ControlFlow::Break`] or the search ends.
303    ///
304    /// Abandons a search in progress first, as [`Solver::solve`] does, which restores the
305    /// domains to where that search began. When this call returns, the domains are as they
306    /// were after that.
307    pub fn for_each_solution(
308        &mut self,
309        mut budget: impl Budget<Stats>,
310        mut on_solution: impl FnMut(&Domains<D>) -> ControlFlow<()>,
311    ) -> Report<Status> {
312        let mut stats = Stats::default();
313        self.begin();
314
315        let outcome = loop {
316            match self.run(&mut budget, &mut stats) {
317                Progress::Solution => {
318                    if on_solution(&self.domains).is_break() {
319                        break Status::Stopped;
320                    }
321                }
322                Progress::Paused => break Status::Exhausted,
323                Progress::Complete => break Status::Complete,
324            }
325        };
326
327        self.abandon();
328        Report { outcome, stats }
329    }
330}
331
332/// Runs `enumerate`, which stores the first solution it meets in `found` and stops there,
333/// and turns what it stored into an [`Outcome`]. Shared by [`Solver::solve`] and
334/// [`ExactCover::solve`](crate::ExactCover::solve).
335pub(crate) fn first_solution<T>(
336    enumerate: impl FnOnce(&mut Option<T>) -> Report<Status>,
337) -> Report<Outcome<T>> {
338    let mut found = None;
339    let report = enumerate(&mut found);
340
341    let outcome = match (report.outcome, found) {
342        (_, Some(solution)) => Outcome::Solved(solution),
343        (Status::Exhausted, None) => Outcome::Exhausted,
344        (_, None) => Outcome::Unsatisfiable,
345    };
346
347    Report {
348        outcome,
349        stats: report.stats,
350    }
351}
352
353/// Runs `enumerate`, which calls the tally it is given once per solution and stops when the
354/// tally breaks, and counts up to `limit` solutions. A zero limit does not run `enumerate`.
355/// Shared by [`Solver::count`] and [`ExactCover::count`](crate::ExactCover::count).
356pub(crate) fn count_up_to(
357    limit: u64,
358    enumerate: impl FnOnce(&mut dyn FnMut() -> ControlFlow<()>) -> Report<Status>,
359) -> Report<Count> {
360    if limit == 0 {
361        return Report {
362            outcome: Count::AtLeast(0),
363            stats: Stats::default(),
364        };
365    }
366
367    let mut solutions = 0;
368    let report = enumerate(&mut || {
369        solutions += 1;
370        if solutions >= limit {
371            ControlFlow::Break(())
372        } else {
373            ControlFlow::Continue(())
374        }
375    });
376
377    let outcome = match report.outcome {
378        Status::Complete => Count::Exact(solutions),
379        Status::Stopped | Status::Exhausted => Count::AtLeast(solutions),
380    };
381
382    Report {
383        outcome,
384        stats: report.stats,
385    }
386}
387
388/// Compile-time check that solvers can move to other threads.
389const _: () = {
390    /// Accepts only `Send` types.
391    const fn sendable<T: Send>() {}
392    sendable::<Solver<'static, u64>>();
393};
394
395/// Unit tests for the stopping paths of [`Solver`].
396#[cfg(test)]
397mod tests {
398    use core::ops::ControlFlow;
399
400    use super::{Count, Outcome, Progress, Solver, Stats, Status};
401    use crate::{AllDifferent, Domain, Model};
402
403    /// Three variables over three values, all different: six solutions.
404    fn permutations() -> Model<u16> {
405        let mut model = Model::new();
406        let vars = model.add_vars(3, u16::range(3));
407        model.add(AllDifferent::new(vars));
408
409        model
410    }
411
412    /// A budget that runs out before the first solution makes `solve` report exhaustion.
413    #[test]
414    fn solve_reports_exhausted_budget() {
415        let model = permutations();
416        let report = Solver::new(&model).solve(|stats: &Stats| stats.nodes >= 1);
417
418        assert_eq!(report.outcome, Outcome::Exhausted);
419        assert_eq!(report.stats.solutions, 0);
420    }
421
422    /// A one-node budget still examines that node, so an already solved problem is solved.
423    #[test]
424    fn budget_counts_examined_nodes() {
425        let mut model = Model::<u16>::new();
426        model.add_var(0b100);
427        let report = Solver::new(&model).solve(|stats: &Stats| stats.nodes >= 1);
428
429        assert_eq!(report.outcome, Outcome::Solved(alloc::vec![2]));
430        assert_eq!(report.stats.nodes, 1);
431    }
432
433    /// A zero limit searches nothing.
434    #[test]
435    fn zero_limit_searches_nothing() {
436        let model = permutations();
437        let report = Solver::new(&model).count(0, |_: &Stats| false);
438
439        assert_eq!(report.outcome, Count::AtLeast(0));
440        assert_eq!(report.stats.nodes, 0);
441    }
442
443    /// A count stops at its limit and reports a lower bound.
444    #[test]
445    fn count_stops_at_limit() {
446        let model = permutations();
447        let report = Solver::new(&model).count(4, |_: &Stats| false);
448
449        assert_eq!(report.outcome, Count::AtLeast(4));
450        assert_eq!(report.stats.solutions, 4);
451    }
452
453    /// Abandoning, resetting or editing the domains ends a search and restores the domains.
454    #[test]
455    fn abandoning_restores_domains() {
456        let model = permutations();
457        let mut solver = Solver::new(&model);
458        assert_eq!(solver.resume(|_: &Stats| false).outcome, Progress::Complete);
459
460        solver.begin();
461        assert_eq!(solver.resume(|_: &Stats| false).outcome, Progress::Solution);
462        assert!(solver.is_searching());
463        assert!(solver.domains().is_solved());
464
465        solver.abandon();
466        assert!(!solver.is_searching());
467        assert!(!solver.domains().is_solved());
468
469        solver.begin();
470        let _ = solver.resume(|_: &Stats| false);
471        let _ = solver.domains_mut();
472        assert!(!solver.is_searching());
473        assert_eq!(solver.domains().level(), 0);
474    }
475
476    /// A hint leads the search straight to the hinted solution, without changing counts.
477    #[test]
478    fn hint_is_tried_first() {
479        let model = permutations();
480        let mut solver = Solver::new(&model);
481        solver.set_hint(&[2, 0, 1]);
482
483        let report = solver.solve(|_: &Stats| false);
484        assert_eq!(report.outcome, Outcome::Solved(alloc::vec![2, 0, 1]));
485        assert_eq!(report.stats.failures, 0);
486        assert_eq!(
487            solver.count(u64::MAX, |_: &Stats| false).outcome,
488            Count::Exact(6)
489        );
490
491        solver.clear_hint();
492        assert_eq!(
493            solver.solve(|_: &Stats| false).outcome,
494            Outcome::Solved(alloc::vec![0, 1, 2])
495        );
496    }
497
498    /// A hint must cover every variable.
499    #[test]
500    #[should_panic(expected = "one value per variable")]
501    fn short_hint_panics() {
502        let model = permutations();
503        Solver::new(&model).set_hint(&[0]);
504    }
505
506    /// Changes the search makes, its root propagation included, are undone however it ends,
507    /// and one-shot searches start afresh.
508    #[test]
509    fn searches_never_leak_changes() {
510        let model = permutations();
511        let mut solver = Solver::new(&model);
512        let x = crate::Var::new(0);
513
514        solver.begin();
515        solver.domains_mut().assign(x, 1).unwrap();
516        solver.begin();
517        while solver.resume(|_: &Stats| false).outcome != Progress::Complete {}
518        assert_eq!(solver.domains()[x], 0b010);
519        assert_eq!(solver.domains().level(), 0);
520
521        solver.begin();
522        let _ = solver.resume(|_: &Stats| false);
523        solver.propagate().unwrap();
524        assert!(!solver.is_searching());
525
526        solver.begin();
527        let _ = solver.resume(|_: &Stats| false);
528        let report = solver.count(u64::MAX, |_: &Stats| false);
529        assert_eq!(report.outcome, Count::Exact(2));
530        assert!(!solver.is_searching());
531
532        solver.begin();
533        let _ = solver.count(0, |_: &Stats| false);
534        assert!(!solver.is_searching());
535    }
536
537    /// Enumeration reports whether the callback or the search space ended it.
538    #[test]
539    fn enumeration_status() {
540        let model = permutations();
541        let mut solver = Solver::new(&model);
542
543        let stopped = solver.for_each_solution(|_: &Stats| false, |_| ControlFlow::Break(()));
544        let complete = solver.for_each_solution(|_: &Stats| false, |_| ControlFlow::Continue(()));
545        assert_eq!(stopped.outcome, Status::Stopped);
546        assert_eq!(
547            (complete.outcome, complete.stats.solutions),
548            (Status::Complete, 6)
549        );
550    }
551}