Skip to main content

constraint_search/
model.rs

1//! The [`Model`]: variables with their initial domains, and the propagators over them.
2
3use alloc::boxed::Box;
4use alloc::vec::Vec;
5
6use crate::propagator::Erased;
7use crate::{Domain, Propagator, Var};
8
9/// A constraint problem: variables, their initial domains and the propagators over them.
10///
11/// A model is built once and then only read. It is `Send + Sync`, so one model can serve
12/// any number of [`Solver`](crate::Solver)s, on one thread or several.
13///
14/// # Examples
15///
16/// ```
17/// use constraint_search::{AllDifferent, Domain, Model};
18///
19/// let mut model = Model::<u16>::new();
20/// let vars = model.add_vars(3, u16::range(3));
21/// model.add(AllDifferent::new(vars));
22/// assert_eq!(model.num_vars(), 3);
23/// ```
24pub struct Model<D> {
25    /// The domain each variable starts with, indexed by [`Var::index`]. Never empty.
26    initial: Vec<D>,
27    /// The constraints, in the order they were added.
28    propagators: Vec<Box<dyn Erased<D>>>,
29    /// For each variable, the indices of the propagators whose scope holds it.
30    watchers: Vec<Vec<usize>>,
31}
32
33impl<D: Domain> Model<D> {
34    /// A model without variables or constraints.
35    #[must_use]
36    pub const fn new() -> Self {
37        Self {
38            initial: Vec::new(),
39            propagators: Vec::new(),
40            watchers: Vec::new(),
41        }
42    }
43
44    /// Adds a variable that may take any value of `domain`.
45    ///
46    /// # Panics
47    ///
48    /// Panics if `domain` is empty or if the model already has `u32::MAX` variables.
49    pub fn add_var(&mut self, domain: D) -> Var {
50        assert!(!domain.is_empty(), "a variable needs at least one value");
51
52        let var =
53            Var::new(u32::try_from(self.initial.len()).expect("fewer than u32::MAX variables"));
54        self.initial.push(domain);
55        self.watchers.push(Vec::new());
56
57        var
58    }
59
60    /// Adds `count` variables that may each take any value of `domain`.
61    ///
62    /// # Panics
63    ///
64    /// Panics if `domain` is empty or if the model would exceed `u32::MAX` variables.
65    pub fn add_vars(&mut self, count: usize, domain: D) -> Vec<Var> {
66        (0..count).map(|_| self.add_var(domain)).collect()
67    }
68
69    /// Adds a constraint.
70    ///
71    /// # Panics
72    ///
73    /// Panics if the scope of `propagator` holds a variable that is not in the model.
74    pub fn add(&mut self, propagator: impl Propagator<D> + 'static) -> &mut Self {
75        let index = self.propagators.len();
76        for var in Propagator::scope(&propagator) {
77            let watchers = self
78                .watchers
79                .get_mut(var.index())
80                .expect("the propagator's scope only holds variables of this model");
81            if watchers.last() != Some(&index) {
82                watchers.push(index);
83            }
84        }
85
86        self.propagators.push(Box::new(propagator));
87        self
88    }
89
90    /// The number of variables.
91    #[must_use]
92    pub fn num_vars(&self) -> usize {
93        self.initial.len()
94    }
95
96    /// The domain each variable starts with, indexed by [`Var::index`].
97    #[must_use]
98    pub fn initial_domains(&self) -> &[D] {
99        &self.initial
100    }
101
102    /// The number of constraints.
103    #[must_use]
104    pub fn num_propagators(&self) -> usize {
105        self.propagators.len()
106    }
107
108    /// The constraints with their scratch types erased, in the order they were added.
109    pub(crate) fn erased(&self) -> &[Box<dyn Erased<D>>] {
110        &self.propagators
111    }
112
113    /// The indices of the propagators whose scope holds `var`.
114    pub(crate) fn watchers(&self, var: Var) -> &[usize] {
115        &self.watchers[var.index()]
116    }
117}
118
119impl<D: Domain> Default for Model<D> {
120    fn default() -> Self {
121        Self::new()
122    }
123}
124
125/// Compile-time check that a model can be shared between threads.
126const _: () = {
127    /// Accepts only `Send + Sync` types.
128    const fn shareable<T: Send + Sync>() {}
129    shareable::<Model<u64>>();
130};
131
132/// Unit tests for [`Model`].
133#[cfg(test)]
134mod tests {
135    use alloc::vec::Vec;
136
137    use super::Model;
138    use crate::{Domains, Inconsistent, Propagator, Var};
139
140    /// Lists its one variable twice, to check that the watch list holds it once.
141    struct Twice([Var; 2]);
142
143    impl Propagator<u16> for Twice {
144        type Scratch = ();
145
146        fn scope(&self) -> &[Var] {
147            &self.0
148        }
149
150        fn propagate(&self, _: &mut Domains<u16>, (): &mut ()) -> Result<(), Inconsistent> {
151            Ok(())
152        }
153    }
154
155    /// A variable repeated in a scope wakes its propagator once.
156    #[test]
157    fn repeated_scope_var_is_watched_once() {
158        let mut model = Model::<u16>::default();
159        let x = model.add_var(0b11);
160        model.add(Twice([x, x]));
161
162        assert_eq!(model.watchers(x), [0]);
163        assert_eq!(model.num_vars(), 1);
164        assert_eq!(model.num_propagators(), 1);
165        assert_eq!(
166            Twice([x, x]).propagate(&mut Domains::new(), &mut ()),
167            Ok(())
168        );
169    }
170
171    /// A scope naming a variable from elsewhere is rejected when the constraint is added.
172    #[test]
173    #[should_panic(expected = "only holds variables of this model")]
174    fn foreign_var_panics() {
175        let mut model = Model::<u16>::new();
176        let vars: Vec<Var> = model.add_vars(1, 0b1);
177        model.add(Twice([vars[0], Var::new(5)]));
178    }
179}