pub struct Solver<'m, D> { /* private fields */ }Expand description
Backtracking search over a shared Model, with reusable working state.
The solver owns the current domains, their trail, the propagation queue and every
propagator’s scratch memory, and keeps their allocations from one solve to the next:
once warmed up, Solver::count and Solver::for_each_solution allocate nothing, and
Solver::solve allocates only the solution it returns. Solver::reset returns to the model’s
initial domains without reallocating. Search leaves the domains as it found them, so a
caller can fix some variables (Solver::domains_mut) and search many times from there.
Solver::solve, Solver::count and Solver::for_each_solution run one search to
its end or budget. For time slicing, Solver::begin starts a search that
Solver::resume continues a little at a time, pausing at each solution or when its
budget runs out.
The model is only borrowed and is Sync, so threads can each run a solver over one model.
Fixing different variables per solver splits the search tree into independent subtrees,
and differing VarOrders and ValueOrders make a portfolio. A shared stop flag goes
into the budget, which every node consults.
Each search node picks an unfixed variable, tries its values in turn and propagates after each choice; a conflict undoes the choice through the trail.
flowchart LR
node([node]) --> pick{unfixed variable?}
pick -->|none| solution([solution])
pick -->|"pick by VarOrder"| value[next value by ValueOrder]
value --> propagate[assign and propagate]
propagate -->|ok| node
propagate -->|conflict| undo[undo] --> value§Examples
The 3×3 Latin squares: each row and column holds 0, 1 and 2 once.
use constraint_search::{AllDifferent, Count, Domain, Model, Solver};
let mut model = Model::<u16>::new();
let cells = model.add_vars(9, u16::range(3));
for i in 0..3 {
model.add(AllDifferent::new((0..3).map(|j| cells[3 * i + j])));
model.add(AllDifferent::new((0..3).map(|j| cells[3 * j + i])));
}
let mut solver = Solver::new(&model);
let report = solver.count(u64::MAX, |_: &_| false);
assert_eq!(report.outcome, Count::Exact(12));
// Fix the first row and the square is unique up to the remaining rows.
for (j, value) in [0, 1, 2].into_iter().enumerate() {
solver.domains_mut().assign(cells[j], value)?;
}
assert_eq!(solver.count(u64::MAX, |_: &_| false).outcome, Count::Exact(2));Implementations§
Source§impl<D: Domain> Solver<'_, D>
impl<D: Domain> Solver<'_, D>
Sourcepub fn set_seed(&mut self, seed: u64)
pub fn set_seed(&mut self, seed: u64)
Sets the seed of ValueOrder::Random. The same seed on the same problem gives the
same order.
Sourcepub fn sample<B: Budget<Stats> + Clone>(
&mut self,
restarts: u32,
budget: B,
) -> Report<Outcome>
pub fn sample<B: Budget<Stats> + Clone>( &mut self, restarts: u32, budget: B, ) -> Report<Outcome>
Draws a random solution: up to restarts searches in random value order, each under
its own copy of budget, until one finds a solution.
Restarting with fresh random orders keeps a search from getting stuck in one hard
region, and spreads the solutions found. They are not drawn exactly uniformly: a
solution that many value choices lead to comes up more often. Successive calls continue
the random sequence; Solver::set_seed makes them reproducible. A sample is a
determinization of hidden information, e.g. a deal of the unseen cards for Perfect
Information Monte Carlo in game-tree search.
Returns Outcome::Unsatisfiable as soon as one search exhausts its space without a
solution, and Outcome::Exhausted if every restart ran out of budget. With zero
restarts nothing is searched, and the outcome is Outcome::Exhausted: no attempt had
any budget. Like Solver::solve, this abandons a search in progress. A hint set with
Solver::set_hint is ignored here and stays set afterwards.
Sourcepub fn possible_values(
&mut self,
budget: impl Budget<Stats>,
) -> Report<Option<Vec<D>>>
pub fn possible_values( &mut self, budget: impl Budget<Stats>, ) -> Report<Option<Vec<D>>>
The values each variable takes in at least one solution of the current domains, or
None if budget stopped the search first. Without solutions, every domain is empty.
A value outside its variable’s result is impossible: no solution uses it. This is exact, unlike propagation, which may keep values that no solution uses. Each solution found supports all its values at once, so only values not yet seen in a solution cost a search of their own. The budget sees the counters of all those searches together.
Like Solver::solve, this abandons a search in progress and answers for the domains
that search began from.
Sourcepub fn backbone(
&mut self,
budget: impl Budget<Stats>,
) -> Report<Option<Vec<Option<u32>>>>
pub fn backbone( &mut self, budget: impl Budget<Stats>, ) -> Report<Option<Vec<Option<u32>>>>
The value of each variable that is the same in every solution, None for the others:
the certain facts of an undetermined problem, such as the cards whose location is known
or the Minesweeper cells that are safe or mines for sure. The outer None means that
budget stopped the search first. Without solutions, no variable has a value.
For belief tracking, record each observation as it arrives (restrict or fix variables
through Solver::domains_mut) and ask again: the solutions left are the belief
state, and the backbone is what is known for certain.
Sourcepub fn marginals(
&mut self,
limit: u64,
budget: impl Budget<Stats>,
) -> Report<Marginals>
pub fn marginals( &mut self, limit: u64, budget: impl Budget<Stats>, ) -> Report<Marginals>
How often each value occurs among the solutions, enumerating up to limit of them.
Marginals::is_exact is true exactly when no solution beyond those counted exists;
telling that apart costs finding one solution past the limit. Like Solver::solve,
this abandons a search in progress. A limit of 0 counts nothing and is never exact.
For example the probability that a hidden card is in West’s hand, or that a Minesweeper cell is a mine. Choosing the probe whose outcome splits the solutions best (the safest click, a Mastermind guess) is then an expectimax step over these counts.
Sourcepub fn weighted_marginals(
&mut self,
limit: u64,
budget: impl Budget<Stats>,
weight: impl FnMut(&Domains<D>) -> f64,
) -> Report<Marginals>
pub fn weighted_marginals( &mut self, limit: u64, budget: impl Budget<Stats>, weight: impl FnMut(&Domains<D>) -> f64, ) -> Report<Marginals>
Like Solver::marginals, with each solution weighted by weight, for non-uniform
priors such as the hands that fit a Bridge bidding sequence best. Weights should be
non-negative.
Source§impl<D: Domain> Solver<'_, D>
impl<D: Domain> Solver<'_, D>
Sourcepub fn begin(&mut self)
pub fn begin(&mut self)
Starts a resumable search from the current domains, abandoning any search in progress.
Drive it with Solver::resume. Until it completes or is abandoned, the domains
belong to the search: Solver::domains_mut, Solver::reset and
Solver::propagate abandon it, and Solver::solve, Solver::count and
Solver::for_each_solution abandon it to run a search of their own.
§Examples
Enumerate solutions a few nodes at a time, as a game might spread work across frames:
use constraint_search::{AllDifferent, Domain, Model, Progress, Solver, Stats};
let mut model = Model::<u16>::new();
let vars = model.add_vars(4, u16::range(4));
model.add(AllDifferent::new(vars));
let mut solver = Solver::new(&model);
solver.begin();
let (mut solutions, mut slices) = (0, 0);
loop {
slices += 1;
match solver.resume(|stats: &Stats| stats.nodes >= 3).outcome {
Progress::Solution => solutions += 1,
Progress::Paused => {}
Progress::Complete => break,
}
}
assert_eq!(solutions, 24);
assert!(slices > solutions);Sourcepub fn resume(&mut self, budget: impl Budget<Stats>) -> Report<Progress>
pub fn resume(&mut self, budget: impl Budget<Stats>) -> Report<Progress>
Continues the search until the next solution, until budget stops it, or until the
search space is exhausted. The budget and the returned counters cover this call only.
Sourcepub fn abandon(&mut self)
pub fn abandon(&mut self)
Stops the search in progress, if any, and restores the domains to how they were at
Solver::begin.
Sourcepub fn is_searching(&self) -> bool
pub fn is_searching(&self) -> bool
Returns true while a search started with Solver::begin has not completed or been
abandoned.
Source§impl<'m, D: Domain> Solver<'m, D>
impl<'m, D: Domain> Solver<'m, D>
Sourcepub fn new(model: &'m Model<D>) -> Self
pub fn new(model: &'m Model<D>) -> Self
A solver over model, starting from its initial domains, branching with
VarOrder::Mrv and ValueOrder::Ascending.
Sourcepub fn with_var_order(self, order: VarOrder) -> Self
pub fn with_var_order(self, order: VarOrder) -> Self
Sets how to pick the variable to branch on.
Sourcepub fn with_value_order(self, order: ValueOrder) -> Self
pub fn with_value_order(self, order: ValueOrder) -> Self
Sets how to order the values of the branching variable.
Sourcepub fn set_hint(&mut self, values: &[u32])
pub fn set_hint(&mut self, values: &[u32])
Tries values[i] first whenever the search branches on variable i, then the other
values in the ValueOrder. A hint value no longer in the domain is skipped.
Give a known solution as the hint to find it first: a generator that digs clues out of
a solved puzzle checks uniqueness with Solver::count and a limit of 2, and the hint
turns finding the first solution into a straight walk, leaving only the search for a
second. The hint stays set across searches and Solver::reset.
§Panics
Panics if values does not hold exactly one value per variable of the model.
Sourcepub fn clear_hint(&mut self)
pub fn clear_hint(&mut self)
Removes the hint set by Solver::set_hint.
Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Returns to the model’s initial domains, keeping every allocation. Abandons a search in progress.
Sourcepub fn domains_mut(&mut self) -> &mut Domains<D>
pub fn domains_mut(&mut self) -> &mut Domains<D>
The current domains, to fix or restrict variables before a search. Abandons a search in progress, which owns the domains until it completes.
Sourcepub fn propagate(&mut self) -> Result<(), Inconsistent>
pub fn propagate(&mut self) -> Result<(), Inconsistent>
Runs every propagator to a fixpoint on the current domains, keeping the result.
§Errors
Returns Inconsistent if the constraints cannot be satisfied. The domains are then
partly propagated; Solver::reset starts over.
Abandons a search in progress first, since that search owns the domains.
Sourcepub fn solve(&mut self, budget: impl Budget<Stats>) -> Report<Outcome>
pub fn solve(&mut self, budget: impl Budget<Stats>) -> Report<Outcome>
Finds one solution.
Like Solver::count and Solver::for_each_solution, this runs a search of its own
from the current domains: it abandons a search in progress (see Solver::begin),
which restores the domains to where that search began, and leaves them as it found
them.
Sourcepub fn count(&mut self, limit: u64, budget: impl Budget<Stats>) -> Report<Count>
pub fn count(&mut self, limit: u64, budget: impl Budget<Stats>) -> Report<Count>
Counts solutions, stopping at limit.
A limit of 2 decides uniqueness: Count::Exact(1) means exactly one solution, and
Count::AtLeast(2) more than one. A limit of 0 searches nothing and reports
Count::AtLeast(0).
Abandons a search in progress, as Solver::solve does.
Sourcepub fn for_each_solution(
&mut self,
budget: impl Budget<Stats>,
on_solution: impl FnMut(&Domains<D>) -> ControlFlow<()>,
) -> Report<Status>
pub fn for_each_solution( &mut self, budget: impl Budget<Stats>, on_solution: impl FnMut(&Domains<D>) -> ControlFlow<()>, ) -> Report<Status>
Calls on_solution with the domains of every solution, each holding one value per
variable, until it returns ControlFlow::Break or the search ends.
Abandons a search in progress first, as Solver::solve does, which restores the
domains to where that search began. When this call returns, the domains are as they
were after that.