Skip to main content

constraint_search/search/
walk.rs

1//! The resumable depth-first walk: an explicit stack of choice points kept in the [`Solver`],
2//! so a search can stop at a solution or on its budget and continue later.
3//!
4//! Every choice pushes a trail level, which the walk pops when it backs out of that choice.
5//! The values still to try sit on [`Solver::values`], one slice per open node.
6
7use search_core::Budget;
8
9use super::{Report, Solver, Stats};
10use crate::{Domain, Var};
11
12/// Where a resumable search stands.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Progress {
15    /// The domains hold a solution, one value per variable. Resuming continues after it.
16    Solution,
17    /// The budget stopped the search. Resuming continues where it stopped.
18    Paused,
19    /// The search space is exhausted, and the domains are as they were at
20    /// [`Solver::begin`]. Also returned when no search is in progress.
21    Complete,
22}
23
24/// The next step of the walk.
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub(super) enum Phase {
27    /// No search is in progress.
28    #[default]
29    Idle,
30    /// Propagate the starting domains.
31    Start,
32    /// Enter the node the current domains describe.
33    Expand,
34    /// Try the next value of the innermost open node.
35    Advance,
36    /// Back out of the current node into its parent.
37    Retreat,
38}
39
40/// An open search node: the variable it branches on and its values still to try.
41#[derive(Debug, Clone, Copy)]
42pub(super) struct Frame {
43    /// The variable this node branches on.
44    var: Var,
45    /// Where the node's values start on [`Solver::values`].
46    start: usize,
47    /// The position of the next value to try.
48    next: usize,
49    /// One past the node's last value.
50    end: usize,
51}
52
53impl<D: Domain> Solver<'_, D> {
54    /// Starts a resumable search from the current domains, abandoning any search in progress.
55    ///
56    /// Drive it with [`Solver::resume`]. Until it completes or is abandoned, the domains
57    /// belong to the search: [`Solver::domains_mut`], [`Solver::reset`] and
58    /// [`Solver::propagate`] abandon it, and [`Solver::solve`], [`Solver::count`] and
59    /// [`Solver::for_each_solution`] abandon it to run a search of their own.
60    ///
61    /// # Examples
62    ///
63    /// Enumerate solutions a few nodes at a time, as a game might spread work across frames:
64    ///
65    /// ```
66    /// use constraint_search::{AllDifferent, Domain, Model, Progress, Solver, Stats};
67    ///
68    /// let mut model = Model::<u16>::new();
69    /// let vars = model.add_vars(4, u16::range(4));
70    /// model.add(AllDifferent::new(vars));
71    ///
72    /// let mut solver = Solver::new(&model);
73    /// solver.begin();
74    /// let (mut solutions, mut slices) = (0, 0);
75    /// loop {
76    ///     slices += 1;
77    ///     match solver.resume(|stats: &Stats| stats.nodes >= 3).outcome {
78    ///         Progress::Solution => solutions += 1,
79    ///         Progress::Paused => {}
80    ///         Progress::Complete => break,
81    ///     }
82    /// }
83    ///
84    /// assert_eq!(solutions, 24);
85    /// assert!(slices > solutions);
86    /// ```
87    pub fn begin(&mut self) {
88        self.abandon();
89        self.base_level = self.domains.level();
90        // Everything the search changes, its root propagation included, sits above this level.
91        self.domains.push_level();
92        self.phase = Phase::Start;
93    }
94
95    /// Continues the search until the next solution, until `budget` stops it, or until the
96    /// search space is exhausted. The budget and the returned counters cover this call only.
97    pub fn resume(&mut self, mut budget: impl Budget<Stats>) -> Report<Progress> {
98        let mut stats = Stats::default();
99        let outcome = self.run(&mut budget, &mut stats);
100
101        Report { outcome, stats }
102    }
103
104    /// Stops the search in progress, if any, and restores the domains to how they were at
105    /// [`Solver::begin`].
106    pub fn abandon(&mut self) {
107        if self.phase == Phase::Idle {
108            return;
109        }
110
111        while self.domains.level() > self.base_level {
112            self.domains.pop_level();
113        }
114
115        self.frames.clear();
116        self.values.clear();
117        self.phase = Phase::Idle;
118    }
119
120    /// Returns `true` while a search started with [`Solver::begin`] has not completed or been
121    /// abandoned.
122    #[must_use]
123    pub fn is_searching(&self) -> bool {
124        self.phase != Phase::Idle
125    }
126
127    /// Walks until a solution, the budget or the end, adding the work done to `stats`.
128    pub(super) fn run(&mut self, budget: &mut impl Budget<Stats>, stats: &mut Stats) -> Progress {
129        loop {
130            let progress = match self.phase {
131                Phase::Idle => return Progress::Complete,
132                Phase::Start => self.start(stats),
133                Phase::Expand => self.expand(budget, stats),
134                Phase::Advance => self.advance(stats),
135                Phase::Retreat => self.retreat(),
136            };
137
138            if let Some(progress) = progress {
139                return progress;
140            }
141        }
142    }
143
144    /// Propagates the starting domains, on the level [`Solver::begin`] pushed.
145    fn start(&mut self, stats: &mut Stats) -> Option<Progress> {
146        if self.engine.fixpoint(self.model, &mut self.domains).is_err() {
147            stats.nodes += 1;
148            return Some(self.finish());
149        }
150
151        self.phase = Phase::Expand;
152        None
153    }
154
155    /// Enters the current node: reports a solution, or opens a frame over the values of the
156    /// variable to branch on.
157    fn expand(&mut self, budget: &mut impl Budget<Stats>, stats: &mut Stats) -> Option<Progress> {
158        // Consult the budget before charging the node, so `nodes` counts nodes examined.
159        if budget.exhausted(stats) {
160            return Some(Progress::Paused);
161        }
162
163        stats.nodes += 1;
164        let Some(var) = self.var_order.pick(&self.domains) else {
165            stats.solutions += 1;
166            self.phase = Phase::Retreat;
167            return Some(Progress::Solution);
168        };
169
170        let start = self.values.len();
171        stats.failures += self.value_order.order(
172            var,
173            self.model,
174            &mut self.domains,
175            &mut self.engine,
176            &mut self.values,
177            &mut self.ordering,
178        );
179        self.prefer_hint(var, start);
180        self.frames.push(Frame {
181            var,
182            start,
183            next: start,
184            end: self.values.len(),
185        });
186
187        self.phase = Phase::Advance;
188        None
189    }
190
191    /// Moves the hinted value of `var`, if it is among the values from `start` on, to the
192    /// front, keeping the others in order.
193    fn prefer_hint(&mut self, var: Var, start: usize) {
194        let Some(&hinted) = self.hint.get(var.index()) else {
195            return;
196        };
197
198        if let Some(offset) = self.values[start..].iter().position(|&v| v == hinted) {
199            self.values[start..=start + offset].rotate_right(1);
200        }
201    }
202
203    /// Tries the next value of the innermost node; a refuted value is undone at once.
204    fn advance(&mut self, stats: &mut Stats) -> Option<Progress> {
205        let frame = self.frames.last_mut().expect("advance needs an open node");
206        if frame.next == frame.end {
207            self.values.truncate(frame.start);
208            self.frames.pop();
209            self.phase = Phase::Retreat;
210            return None;
211        }
212
213        let (var, value) = (frame.var, self.values[frame.next]);
214        frame.next += 1;
215
216        self.domains.push_level();
217        let propagated = self
218            .domains
219            .assign(var, value)
220            .and_then(|_| self.engine.propagate_changes(self.model, &mut self.domains));
221        if propagated.is_ok() {
222            self.phase = Phase::Expand;
223        } else {
224            stats.failures += 1;
225            self.domains.pop_level();
226        }
227
228        None
229    }
230
231    /// Backs out of the current node: undoes the choice that led to it, or finishes the
232    /// search at the root.
233    fn retreat(&mut self) -> Option<Progress> {
234        if self.frames.is_empty() {
235            return Some(self.finish());
236        }
237
238        self.domains.pop_level();
239        self.phase = Phase::Advance;
240        None
241    }
242
243    /// Ends the search, restoring the domains to how they were at [`Solver::begin`].
244    fn finish(&mut self) -> Progress {
245        self.abandon();
246        Progress::Complete
247    }
248}