1use alloc::vec::Vec;
4
5use crate::{Domain, Domains, Inconsistent, Propagator, Var};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Relation {
10 AtMost,
12 Equal,
14 AtLeast,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Linear {
51 vars: Vec<Var>,
53 coefficients: Vec<i64>,
55 relation: Relation,
57 rhs: i64,
59}
60
61impl Linear {
62 #[must_use]
67 pub fn new(terms: impl IntoIterator<Item = (i64, Var)>, relation: Relation, rhs: i64) -> Self {
68 let (coefficients, vars) = terms.into_iter().unzip();
69
70 Self {
71 vars,
72 coefficients,
73 relation,
74 rhs,
75 }
76 }
77
78 #[must_use]
80 pub fn sum(vars: impl IntoIterator<Item = Var>, relation: Relation, rhs: i64) -> Self {
81 Self::new(vars.into_iter().map(|var| (1, var)), relation, rhs)
82 }
83
84 pub fn terms(&self) -> impl Iterator<Item = (i64, Var)> + '_ {
86 self.coefficients
87 .iter()
88 .copied()
89 .zip(self.vars.iter().copied())
90 }
91
92 #[must_use]
94 pub fn relation(&self) -> Relation {
95 self.relation
96 }
97
98 #[must_use]
100 pub fn rhs(&self) -> i64 {
101 self.rhs
102 }
103
104 fn caps(&self) -> bool {
106 matches!(self.relation, Relation::AtMost | Relation::Equal)
107 }
108
109 fn floors(&self) -> bool {
111 matches!(self.relation, Relation::AtLeast | Relation::Equal)
112 }
113}
114
115impl<D: Domain> Propagator<D> for Linear {
116 type Scratch = Vec<(i128, i128)>;
118
119 fn scope(&self) -> &[Var] {
120 &self.vars
121 }
122
123 fn propagate(
124 &self,
125 domains: &mut Domains<D>,
126 bounds: &mut Vec<(i128, i128)>,
127 ) -> Result<(), Inconsistent> {
128 let rhs = i128::from(self.rhs);
129 let (low, high) = self.term_bounds(domains, bounds);
130 if (self.caps() && low > rhs) || (self.floors() && high < rhs) {
131 return Err(Inconsistent);
132 }
133
134 for (term, (&var, &coefficient)) in self.vars.iter().zip(&self.coefficients).enumerate() {
135 let (term_low, term_high) = bounds[term];
136 let (rest_low, rest_high) = (low - term_low, high - term_high);
137 let mut allowed = domains[var];
138 for value in domains[var].values() {
139 let contribution = i128::from(coefficient) * i128::from(value);
140 let over = self.caps() && contribution + rest_low > rhs;
141 let under = self.floors() && contribution + rest_high < rhs;
142 if over || under {
143 allowed.remove(value);
144 }
145 }
146
147 domains.restrict(var, allowed)?;
148 }
149
150 Ok(())
151 }
152}
153
154impl Linear {
155 fn term_bounds<D: Domain>(
158 &self,
159 domains: &Domains<D>,
160 bounds: &mut Vec<(i128, i128)>,
161 ) -> (i128, i128) {
162 bounds.clear();
163 let (mut low, mut high) = (0, 0);
164 for (&var, &coefficient) in self.vars.iter().zip(&self.coefficients) {
165 let contributions = domains[var]
166 .values()
167 .map(|value| i128::from(coefficient) * i128::from(value));
168 let (term_low, term_high) =
169 contributions.fold((i128::MAX, i128::MIN), |(lo, hi), c| (lo.min(c), hi.max(c)));
170 bounds.push((term_low, term_high));
171 low += term_low;
172 high += term_high;
173 }
174
175 (low, high)
176 }
177}
178
179#[cfg(test)]
181mod tests {
182 use alloc::vec::Vec;
183
184 use super::{Linear, Relation};
185 use crate::testing::{Rng, check_sound_against_brute_force};
186 use crate::{Domains, Inconsistent, Propagator, Var};
187
188 #[test]
191 fn sound_against_brute_force() {
192 let mut rng = Rng::new(23);
193 for _ in 0..3000 {
194 let vars = 1 + rng.below(4);
195 let coefficients: Vec<i64> = (0..vars)
196 .map(|_| i64::try_from(rng.below(7)).unwrap() - 3)
197 .collect();
198 let relation = [Relation::AtMost, Relation::Equal, Relation::AtLeast][rng.below(3)];
199 let rhs = i64::try_from(rng.below(25)).unwrap() - 8;
200 let holds = |assignment: &[u32]| {
201 let sum: i64 = coefficients
202 .iter()
203 .zip(assignment)
204 .map(|(&a, &x)| a * i64::from(x))
205 .sum();
206 match relation {
207 Relation::AtMost => sum <= rhs,
208 Relation::Equal => sum == rhs,
209 Relation::AtLeast => sum >= rhs,
210 }
211 };
212
213 check_sound_against_brute_force(&mut rng, vars, 6, holds, |scope: Vec<Var>| {
214 Linear::new(coefficients.iter().copied().zip(scope), relation, rhs)
215 });
216 }
217 }
218
219 #[test]
221 fn infeasible_bounds_fail() {
222 let mut domains = Domains::<u16>::new();
223 let x = domains.add(0b11);
224 let y = domains.add(0b11);
225
226 let too_big = Linear::sum([x, y], Relation::AtLeast, 3);
227 assert_eq!(
228 too_big.propagate(&mut domains, &mut Vec::new()),
229 Err(Inconsistent)
230 );
231 let negative = Linear::new([(-1, x), (2, y)], Relation::Equal, 2);
232 negative.propagate(&mut domains, &mut Vec::new()).unwrap();
233 assert_eq!((domains[x], domains[y]), (0b01, 0b10));
234 }
235}