Skip to main content

constraint_search/
lib.rs

1//! # Constraint search
2//!
3//! Finite-domain constraint satisfaction: variables with small domains, constraints that
4//! prune them, and search for the assignments that remain.
5//!
6//! ## Scope
7//!
8//! - Finite-domain variables with bitset domains ([`Domain`]) and a trail for undoing changes
9//!   on backtrack ([`Domains`])
10//! - Propagators run to a fixpoint ([`Propagator`]), including all-different with complete
11//!   Hall-set reasoning ([`AllDifferent`]), constraints given by their allowed tuples
12//!   ([`Table`]), weighted sums ([`Linear`]) and nonogram lines ([`Line`])
13//! - Pluggable inference rules ordered by cost, for human-style solving, hints, explanations
14//!   ("why can `x` not be `v`?") and difficulty grading ([`Rules`]), for all-different groups,
15//!   sums and any propagator ([`PropagatorRule`])
16//! - Backtracking search with variable and value ordering heuristics under a
17//!   [`search_core::Budget`], resumable so the work can be spread over time ([`Solver`],
18//!   [`Solver::resume`])
19//! - Solution counting with early stop, for checking that a puzzle has a unique solution
20//!   ([`Solver::count`])
21//! - Problems with many solutions, as with hidden information: the values certain in every
22//!   solution ([`Solver::backbone`]), each value's probability ([`Solver::marginals`]), and
23//!   random solutions to determinize hidden state for game-tree search ([`Solver::sample`])
24//! - Exact cover with dancing links ([`ExactCover`])
25//!
26//! ## Overview
27//!
28//! ```mermaid
29//! flowchart LR
30//!     model[Model: variables, propagators] --> solver[Solver: domains, trail, queue]
31//!     solver -->|solve, count| search[backtracking + propagation]
32//!     domains[Domains] --> rules[Rules: costed deductions]
33//!     rules --> trace[Trace: steps, grade]
34//! ```
35//!
36//! A [`Model`] holds the variables and constraints and is shared read-only; it is
37//! `Send + Sync`. A [`Solver`] borrows it, owns the working state and reuses it across
38//! solves, which suits generators that check uniqueness thousands of times. [`Rules`] work on
39//! any [`Domains`] and explain a solve step by step instead.
40//!
41//! Domains are bitsets: `u16`, `u32`, `u64` and `u128` hold up to their bit width in values,
42//! and [`BitSet`] holds more.
43//!
44//! ## Example
45//!
46//! Colour a map of four regions with three colours, so that neighbours differ:
47//!
48//! ```
49//! use constraint_search::{AllDifferent, Domain, Model, Outcome, Solver, Stats};
50//!
51//! let mut model = Model::<u16>::new();
52//! let [a, b, c, d] = [(); 4].map(|()| model.add_var(u16::range(3)));
53//! for pair in [[a, b], [a, c], [b, c], [b, d], [c, d]] {
54//!     model.add(AllDifferent::new(pair));
55//! }
56//!
57//! let report = Solver::new(&model).solve(|_: &Stats| false);
58//! let Outcome::Solved(colours) = report.outcome else { panic!("three colours suffice") };
59//! assert_eq!(colours[0], colours[3]); // a and d must share a colour
60//! ```
61//!
62//! The crate is `no_std` and needs `alloc`. The `parallel` feature adds `ParallelSolver`
63//! (it needs `std` for threads): the search tree split across a pool of threads, or a
64//! portfolio of branching heuristics racing each other, with a shared stop.
65//!
66//! Repository: <https://github.com/sunsided/constraint-search>
67
68#![no_std]
69#![forbid(unsafe_code)]
70
71extern crate alloc;
72
73mod all_different;
74mod domain;
75mod exact_cover;
76mod line;
77mod linear;
78mod model;
79#[cfg(feature = "parallel")]
80mod parallel;
81mod propagator;
82mod rule;
83mod search;
84mod store;
85mod table;
86#[cfg(test)]
87mod testing;
88
89pub use all_different::{AllDifferent, MatchingScratch};
90pub use domain::{BitSet, Domain, Values};
91pub use exact_cover::ExactCover;
92pub use line::{EMPTY, FILLED, Line, LineScratch};
93pub use linear::{Linear, Relation};
94pub use model::Model;
95#[cfg(feature = "parallel")]
96pub use parallel::ParallelSolver;
97pub use propagator::Propagator;
98pub use rule::{
99    GroupIntersection, PropagatorRule, Rule, Rules, Step, SumDifference, Trace, ValueSubset,
100    VariableSubset,
101};
102pub use search::{
103    Count, Marginals, Outcome, Progress, Report, Solver, Stats, Status, ValueOrder, VarOrder,
104};
105pub use store::{Domains, Inconsistent, Var};
106pub use table::Table;
107
108/// Panics with `message` if `items` holds an element twice. Constructors use it to reject
109/// scopes that list a variable, cell or column more than once.
110#[track_caller]
111pub(crate) fn assert_distinct<T: Ord + Clone>(items: &[T], message: &str) {
112    let mut sorted = items.to_vec();
113    sorted.sort_unstable();
114    assert!(
115        sorted.windows(2).all(|pair| pair[0] != pair[1]),
116        "{message}"
117    );
118}
119
120/// Doctests for the code examples in README.md (not part of the API).
121#[cfg(doctest)]
122#[doc = include_str!("../README.md")]
123mod readme_doctests {}