Skip to main content

constraint_search/search/
analysis.rs

1//! Questions about problems with many solutions: which values are possible or certain
2//! ([`Solver::possible_values`], [`Solver::backbone`]), how likely each value is
3//! ([`Solver::marginals`]), and a random solution ([`Solver::sample`]).
4//!
5//! Propagation and every rule stay sound when a problem has many solutions; only rules with
6//! [`Rule::assumes_unique`](crate::Rule::assumes_unique) must stay off.
7
8use alloc::vec;
9use alloc::vec::Vec;
10use core::ops::ControlFlow;
11
12use search_core::Budget;
13
14use super::{Outcome, Report, Solver, Stats, Status, ValueOrder};
15use crate::{Domain, Domains, Var};
16
17/// How often each value occurs across the solutions a [`Solver::marginals`] call enumerated,
18/// optionally weighted.
19///
20/// With every solution enumerated ([`Marginals::is_exact`]), [`Marginals::probability`] is the
21/// exact probability under a uniform (or the given) weighting of the solutions; otherwise it
22/// estimates from the solutions seen.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Marginals {
25    /// Values per variable in [`Marginals::weights`]: one more than the largest value seen.
26    stride: usize,
27    /// `weights[var * stride + value]`: the summed weight of the solutions with that value.
28    weights: Vec<f64>,
29    /// The summed weight of all solutions seen.
30    total: f64,
31    /// The number of solutions seen.
32    solutions: u64,
33    /// `true` if the search space was exhausted, so every solution was seen.
34    exact: bool,
35}
36
37impl Marginals {
38    /// The weighted share of solutions in which `var` takes `value`, between 0 and 1; 0 when
39    /// no solution was seen.
40    #[must_use]
41    pub fn probability(&self, var: Var, value: u32) -> f64 {
42        let value = value as usize;
43        if self.total <= 0.0 || value >= self.stride {
44            return 0.0;
45        }
46
47        self.weights[var.index() * self.stride + value] / self.total
48    }
49
50    /// The number of solutions enumerated.
51    #[must_use]
52    pub fn solutions(&self) -> u64 {
53        self.solutions
54    }
55
56    /// The summed weight of the solutions enumerated.
57    #[must_use]
58    pub fn total_weight(&self) -> f64 {
59        self.total
60    }
61
62    /// Returns `true` if every solution was enumerated, so the probabilities are exact; `false`
63    /// if more solutions exist than the limit allowed, or the budget ran out.
64    #[must_use]
65    pub fn is_exact(&self) -> bool {
66        self.exact
67    }
68}
69
70impl<D: Domain> Solver<'_, D> {
71    /// Sets the seed of [`ValueOrder::Random`]. The same seed on the same problem gives the
72    /// same order.
73    pub fn set_seed(&mut self, seed: u64) {
74        self.ordering.seed(seed);
75    }
76
77    /// Draws a random solution: up to `restarts` searches in random value order, each under
78    /// its own copy of `budget`, until one finds a solution.
79    ///
80    /// Restarting with fresh random orders keeps a search from getting stuck in one hard
81    /// region, and spreads the solutions found. They are not drawn exactly uniformly: a
82    /// solution that many value choices lead to comes up more often. Successive calls continue
83    /// the random sequence; [`Solver::set_seed`] makes them reproducible. A sample is a
84    /// determinization of hidden information, e.g. a deal of the unseen cards for Perfect
85    /// Information Monte Carlo in game-tree search.
86    ///
87    /// Returns [`Outcome::Unsatisfiable`] as soon as one search exhausts its space without a
88    /// solution, and [`Outcome::Exhausted`] if every restart ran out of budget. With zero
89    /// restarts nothing is searched, and the outcome is [`Outcome::Exhausted`]: no attempt had
90    /// any budget. Like [`Solver::solve`], this abandons a search in progress. A hint set with
91    /// [`Solver::set_hint`] is ignored here and stays set afterwards.
92    pub fn sample<B: Budget<Stats> + Clone>(
93        &mut self,
94        restarts: u32,
95        budget: B,
96    ) -> Report<Outcome> {
97        self.abandon();
98        let order = core::mem::replace(&mut self.value_order, ValueOrder::Random);
99        // A hint would put its solution first on every restart and undo the shuffle.
100        let hint = core::mem::take(&mut self.hint);
101        let mut stats = Stats::default();
102        let mut outcome = Outcome::Exhausted;
103
104        // One budget per restart: clones for all but the last, which takes the original.
105        let budgets = core::iter::repeat_n(budget, usize::try_from(restarts).unwrap_or(usize::MAX));
106        for budget in budgets {
107            let report = self.solve(budget);
108            stats = stats.plus(report.stats);
109            outcome = report.outcome;
110            if outcome != Outcome::Exhausted {
111                break;
112            }
113        }
114
115        self.value_order = order;
116        self.hint = hint;
117        Report { outcome, stats }
118    }
119
120    /// The values each variable takes in at least one solution of the current domains, or
121    /// `None` if `budget` stopped the search first. Without solutions, every domain is empty.
122    ///
123    /// A value outside its variable's result is impossible: no solution uses it. This is exact,
124    /// unlike propagation, which may keep values that no solution uses. Each solution found
125    /// supports all its values at once, so only values not yet seen in a solution cost a
126    /// search of their own. The budget sees the counters of all those searches together.
127    ///
128    /// Like [`Solver::solve`], this abandons a search in progress and answers for the domains
129    /// that search began from.
130    pub fn possible_values(&mut self, budget: impl Budget<Stats>) -> Report<Option<Vec<D>>> {
131        // Abandon first, so the candidates and the searches see the same domains.
132        self.abandon();
133        let mut budget = budget;
134        let mut stats = Stats::default();
135        let mut possible = vec![D::empty(); self.domains.len()];
136        let candidates: Vec<D> = self.domains.vars().map(|var| self.domains[var]).collect();
137
138        let first = self.witness(None, &mut budget, &mut stats);
139        let outcome = match first {
140            Witness::Found(values) => {
141                support(&mut possible, &values);
142                self.test_candidates(&candidates, &mut possible, &mut budget, &mut stats)
143                    .then_some(possible)
144            }
145            Witness::None => Some(possible),
146            Witness::Exhausted => None,
147        };
148
149        Report { outcome, stats }
150    }
151
152    /// The value of each variable that is the same in every solution, `None` for the others:
153    /// the certain facts of an undetermined problem, such as the cards whose location is known
154    /// or the Minesweeper cells that are safe or mines for sure. The outer `None` means that
155    /// `budget` stopped the search first. Without solutions, no variable has a value.
156    ///
157    /// For belief tracking, record each observation as it arrives (restrict or fix variables
158    /// through [`Solver::domains_mut`]) and ask again: the solutions left are the belief
159    /// state, and the backbone is what is known for certain.
160    pub fn backbone(&mut self, budget: impl Budget<Stats>) -> Report<Option<Vec<Option<u32>>>> {
161        let report = self.possible_values(budget);
162        let outcome = report
163            .outcome
164            .map(|possible| possible.iter().map(Domain::value).collect());
165
166        Report {
167            outcome,
168            stats: report.stats,
169        }
170    }
171
172    /// How often each value occurs among the solutions, enumerating up to `limit` of them.
173    ///
174    /// [`Marginals::is_exact`] is `true` exactly when no solution beyond those counted exists;
175    /// telling that apart costs finding one solution past the limit. Like [`Solver::solve`],
176    /// this abandons a search in progress. A limit of 0 counts nothing and is never exact.
177    ///
178    /// For example the probability that a hidden card is in West's hand, or that a Minesweeper
179    /// cell is a mine. Choosing the probe whose outcome splits the solutions best (the safest
180    /// click, a Mastermind guess) is then an expectimax step over these counts.
181    pub fn marginals(&mut self, limit: u64, budget: impl Budget<Stats>) -> Report<Marginals> {
182        self.weighted_marginals(limit, budget, |_| 1.0)
183    }
184
185    /// Like [`Solver::marginals`], with each solution weighted by `weight`, for non-uniform
186    /// priors such as the hands that fit a Bridge bidding sequence best. Weights should be
187    /// non-negative.
188    pub fn weighted_marginals(
189        &mut self,
190        limit: u64,
191        budget: impl Budget<Stats>,
192        mut weight: impl FnMut(&Domains<D>) -> f64,
193    ) -> Report<Marginals> {
194        // Abandon first, so the value range covers every domain the search will see.
195        self.abandon();
196        let stride = self.value_stride();
197        let mut marginals = Marginals {
198            stride,
199            weights: vec![0.0; self.domains.len() * stride],
200            total: 0.0,
201            solutions: 0,
202            exact: false,
203        };
204
205        let report = if limit == 0 {
206            Report {
207                outcome: Status::Stopped,
208                stats: Stats::default(),
209            }
210        } else {
211            self.for_each_solution(budget, |domains| {
212                // A solution past the limit only proves the enumeration incomplete.
213                if marginals.solutions == limit {
214                    return ControlFlow::Break(());
215                }
216
217                add_solution(&mut marginals, domains, weight(domains));
218                ControlFlow::Continue(())
219            })
220        };
221
222        marginals.exact = report.outcome == Status::Complete;
223        Report {
224            outcome: marginals,
225            stats: report.stats,
226        }
227    }
228
229    /// One more than the largest value in any current domain.
230    fn value_stride(&self) -> usize {
231        self.domains
232            .vars()
233            .filter_map(|var| {
234                let domain = self.domains[var];
235                domain.values().last()
236            })
237            .max()
238            .map_or(0, |largest| largest as usize + 1)
239    }
240
241    /// Tests every candidate value not yet supported, adding the support of each solution it
242    /// finds; returns `false` if the budget stopped it.
243    fn test_candidates(
244        &mut self,
245        candidates: &[D],
246        possible: &mut [D],
247        budget: &mut impl Budget<Stats>,
248        stats: &mut Stats,
249    ) -> bool {
250        for (index, &domain) in candidates.iter().enumerate() {
251            let var = Var::new(u32::try_from(index).expect("fewer than u32::MAX variables"));
252            for value in domain.values() {
253                if possible[index].contains(value) {
254                    continue;
255                }
256
257                match self.witness(Some((var, value)), budget, stats) {
258                    Witness::Found(values) => support(possible, &values),
259                    Witness::None => {}
260                    Witness::Exhausted => return false,
261                }
262            }
263        }
264
265        true
266    }
267
268    /// Searches for one solution, with `fixed` assigned first if given.
269    fn witness(
270        &mut self,
271        fixed: Option<(Var, u32)>,
272        budget: &mut impl Budget<Stats>,
273        stats: &mut Stats,
274    ) -> Witness {
275        self.abandon();
276        self.domains.push_level();
277
278        let mut found = None;
279        let base = *stats;
280        let report = if fixed.is_none_or(|(var, value)| self.domains.assign(var, value).is_ok()) {
281            self.for_each_solution(
282                |current: &Stats| budget.exhausted(&base.plus(*current)),
283                |domains| {
284                    found = domains.solution();
285                    ControlFlow::Break(())
286                },
287            )
288        } else {
289            Report {
290                outcome: Status::Complete,
291                stats: Stats::default(),
292            }
293        };
294
295        self.domains.pop_level();
296        *stats = base.plus(report.stats);
297        match (found, report.outcome) {
298            (Some(values), _) => Witness::Found(values),
299            (None, Status::Exhausted) => Witness::Exhausted,
300            (None, _) => Witness::None,
301        }
302    }
303}
304
305/// The result of looking for one solution.
306enum Witness {
307    /// A solution: the value of every variable.
308    Found(Vec<u32>),
309    /// The search space holds no solution.
310    None,
311    /// The budget ran out first.
312    Exhausted,
313}
314
315/// Marks every value of `solution` as possible.
316fn support<D: Domain>(possible: &mut [D], solution: &[u32]) {
317    for (domain, &value) in possible.iter_mut().zip(solution) {
318        domain.insert(value);
319    }
320}
321
322/// Adds the solution in `domains`, with weight `weight`, to `marginals`.
323fn add_solution<D: Domain>(marginals: &mut Marginals, domains: &Domains<D>, weight: f64) {
324    for var in domains.vars() {
325        let value = domains.value(var).expect("a solution fixes every variable") as usize;
326        marginals.weights[var.index() * marginals.stride + value] += weight;
327    }
328
329    marginals.total += weight;
330    marginals.solutions += 1;
331}