Skip to main content

constraint_search/search/
order.rs

1//! Branching heuristics: [`VarOrder`] picks the variable, [`ValueOrder`] orders its values.
2
3use alloc::vec::Vec;
4
5use crate::propagator::Engine;
6use crate::{Domain, Domains, Model, Var};
7
8/// How search picks the variable to branch on.
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum VarOrder {
12    /// The unfixed variable with the fewest values left ("minimum remaining values",
13    /// fail-first); ties go to the lowest index.
14    #[default]
15    Mrv,
16    /// The unfixed variable with the lowest index.
17    Input,
18}
19
20impl VarOrder {
21    /// The variable to branch on, or `None` if every variable is fixed.
22    pub(crate) fn pick<D: Domain>(self, domains: &Domains<D>) -> Option<Var> {
23        let mut unfixed = domains.vars().filter(|&var| domains[var].len() > 1);
24        match self {
25            Self::Mrv => unfixed.min_by_key(|&var| domains[var].len()),
26            Self::Input => unfixed.next(),
27        }
28    }
29}
30
31/// How search orders the values of the branching variable.
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum ValueOrder {
35    /// Smallest value first.
36    #[default]
37    Ascending,
38    /// Largest value first.
39    Descending,
40    /// The value that leaves the most values in all domains after propagation first
41    /// ("least constraining value"). Values that propagation refutes are skipped and count as
42    /// [`Stats::failures`](super::Stats::failures). Costs one propagation per value, so it pays
43    /// off when wrong choices are expensive.
44    Lcv,
45    /// A random order, from the solver's seed ([`Solver::set_seed`](super::Solver::set_seed)).
46    /// Repeated searches with different seeds sample different solutions; see
47    /// [`Solver::sample`](super::Solver::sample).
48    Random,
49}
50
51/// Scratch and state of the value orderings, owned by the solver and reused.
52#[derive(Debug, Clone)]
53pub(super) struct OrderState {
54    /// For [`ValueOrder::Lcv`]: how many values each candidate leaves, and the value.
55    pub(super) scores: Vec<(u64, u32)>,
56    /// For [`ValueOrder::Random`]: the xorshift64 state. Never zero.
57    pub(super) rng: u64,
58}
59
60impl Default for OrderState {
61    fn default() -> Self {
62        Self {
63            scores: Vec::new(),
64            rng: 0x9e37_79b9_7f4a_7c15,
65        }
66    }
67}
68
69impl OrderState {
70    /// Seeds the random ordering; a zero seed is replaced, since xorshift sticks at zero.
71    pub(super) fn seed(&mut self, seed: u64) {
72        self.rng = seed.max(1);
73    }
74
75    /// The next 64 random bits.
76    fn next(&mut self) -> u64 {
77        self.rng ^= self.rng << 13;
78        self.rng ^= self.rng >> 7;
79        self.rng ^= self.rng << 17;
80        self.rng
81    }
82
83    /// Shuffles `values` uniformly (Fisher–Yates).
84    fn shuffle(&mut self, values: &mut [u32]) {
85        for i in (1..values.len()).rev() {
86            let bound = u64::try_from(i + 1).expect("a domain has fewer than 2^64 values");
87            let j = usize::try_from(self.next() % bound).expect("below a usize bound");
88            values.swap(i, j);
89        }
90    }
91}
92
93impl ValueOrder {
94    /// Pushes the values of `var` to try onto `values`, in order, and returns how many values
95    /// the ordering itself refuted.
96    pub(super) fn order<D: Domain>(
97        self,
98        var: Var,
99        model: &Model<D>,
100        domains: &mut Domains<D>,
101        engine: &mut Engine,
102        values: &mut Vec<u32>,
103        state: &mut OrderState,
104    ) -> u64 {
105        let start = values.len();
106        match self {
107            Self::Ascending => values.extend(domains[var].values()),
108            Self::Descending => {
109                values.extend(domains[var].values());
110                values[start..].reverse();
111            }
112            Self::Lcv => {
113                let refuted = score(var, model, domains, engine, &mut state.scores);
114                values.extend(state.scores.iter().map(|&(_, value)| value));
115                return refuted;
116            }
117            Self::Random => {
118                values.extend(domains[var].values());
119                state.shuffle(&mut values[start..]);
120            }
121        }
122
123        0
124    }
125}
126
127/// Scores each value of `var` that survives propagation by the values it leaves, most first
128/// (ties by ascending value), and returns how many values propagation refuted.
129fn score<D: Domain>(
130    var: Var,
131    model: &Model<D>,
132    domains: &mut Domains<D>,
133    engine: &mut Engine,
134    scores: &mut Vec<(u64, u32)>,
135) -> u64 {
136    let candidates = domains[var];
137    scores.clear();
138    for value in candidates.values() {
139        domains.push_level();
140        let survives = domains
141            .assign(var, value)
142            .and_then(|_| engine.propagate_changes(model, domains));
143        if survives.is_ok() {
144            let left = domains
145                .vars()
146                .map(|other| u64::from(domains[other].len()))
147                .sum();
148            scores.push((left, value));
149        }
150
151        domains.pop_level();
152    }
153
154    // Unstable sort: it never allocates, and the value breaks ties deterministically.
155    scores.sort_unstable_by_key(|&(left, value)| (core::cmp::Reverse(left), value));
156    u64::from(candidates.len()) - u64::try_from(scores.len()).expect("fewer than 2^64 values")
157}