Skip to main content

planning_qubo/
builder.rs

1//! A builder for QUBO models over named variables, with penalty terms for constraints.
2
3use alloc::collections::BTreeMap;
4use alloc::format;
5use alloc::string::String;
6use alloc::vec::Vec;
7
8use crate::{Coefficient, Qubo};
9
10/// A binary variable of a [`Builder`] or [`Problem`]: the index into the QUBO model.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Var(usize);
13
14impl Var {
15    /// The index of the variable in the QUBO model and in samples.
16    #[must_use]
17    pub fn index(self) -> usize {
18        self.0
19    }
20}
21
22/// A named constraint, kept next to the model so that decoders can check samples.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Constraint<T> {
25    /// The name that [`Problem::violations`] reports.
26    pub name: String,
27    /// What the constraint requires.
28    pub kind: ConstraintKind<T>,
29}
30
31/// What a [`Constraint`] requires of the original variables. Slack variables are not part of it.
32#[derive(Debug, Clone, PartialEq)]
33pub enum ConstraintKind<T> {
34    /// Exactly one of the variables is 1. A variable that occurs twice counts twice.
35    ExactlyOne(Vec<Var>),
36    /// At most one of the variables is 1. A variable that occurs twice counts twice.
37    AtMostOne(Vec<Var>),
38    /// `rhs − slack_max ≤ Σ aᵢ·xᵢ ≤ rhs`, with the terms `(xᵢ, aᵢ)`.
39    ///
40    /// With `slack_max == 0` this is the equality `Σ aᵢ·xᵢ = rhs`.
41    Linear {
42        /// The terms `(xᵢ, aᵢ)` of the left side.
43        terms: Vec<(Var, T)>,
44        /// The right side.
45        rhs: T,
46        /// The largest value of the slack, which the slack bits encode.
47        slack_max: u32,
48    },
49}
50
51impl<T: Coefficient> Constraint<T> {
52    /// Returns `true` if the assignment `x` satisfies the constraint.
53    ///
54    /// # Panics
55    ///
56    /// Panics if a variable of the constraint is not in `x`.
57    #[must_use]
58    pub fn is_satisfied(&self, x: &[bool]) -> bool {
59        match &self.kind {
60            ConstraintKind::ExactlyOne(vars) => count_set(vars, x) == 1,
61            ConstraintKind::AtMostOne(vars) => count_set(vars, x) <= 1,
62            ConstraintKind::Linear {
63                terms,
64                rhs,
65                slack_max,
66            } => {
67                let lhs = linear_sum(terms, x);
68                *rhs >= lhs && lhs >= rhs.minus(T::from_u32(*slack_max))
69            }
70        }
71    }
72}
73
74/// The number of variables in `vars` that are 1 in `x`.
75fn count_set(vars: &[Var], x: &[bool]) -> usize {
76    vars.iter().filter(|v| x[v.index()]).count()
77}
78
79/// The sum `Σ aᵢ·xᵢ` over `terms`.
80fn linear_sum<T: Coefficient>(terms: &[(Var, T)], x: &[bool]) -> T {
81    terms
82        .iter()
83        .filter(|(v, _)| x[v.index()])
84        .fold(T::ZERO, |sum, &(_, a)| sum.plus(a))
85}
86
87/// Builds a QUBO model over named variables from objective terms and penalized constraints.
88///
89/// Each constraint adds a penalty with a caller-chosen weight `P`. The penalty is 0 when
90/// the constraint holds (for the best slack value) and at least `P` otherwise, if all
91/// coefficients are integers. The builder does not tune the weights.
92#[derive(Debug, Clone)]
93pub struct Builder<T> {
94    /// The variable names, in index order.
95    names: Vec<String>,
96    /// The variable of each name.
97    lookup: BTreeMap<String, Var>,
98    /// The constant energy term.
99    offset: T,
100    /// The terms `(i, j, value)`; `i == j` is a linear term.
101    terms: Vec<(usize, usize, T)>,
102    /// The constraints, in the order they were added.
103    constraints: Vec<Constraint<T>>,
104}
105
106impl<T: Coefficient> Default for Builder<T> {
107    fn default() -> Self {
108        Self::new()
109    }
110}
111
112impl<T: Coefficient> Builder<T> {
113    /// Creates a builder with no variables.
114    #[must_use]
115    pub fn new() -> Self {
116        Self {
117            names: Vec::new(),
118            lookup: BTreeMap::new(),
119            offset: T::ZERO,
120            terms: Vec::new(),
121            constraints: Vec::new(),
122        }
123    }
124
125    /// Returns the variable called `name`, and creates it if it does not exist.
126    pub fn variable(&mut self, name: &str) -> Var {
127        if let Some(&var) = self.lookup.get(name) {
128            return var;
129        }
130
131        let var = Var(self.names.len());
132        self.names.push(String::from(name));
133        self.lookup.insert(String::from(name), var);
134
135        var
136    }
137
138    /// Creates a new variable called `name`, also if the name exists.
139    ///
140    /// [`Builder::variable`] and [`Problem::variable`] find the first variable of a name.
141    /// Slack bits use this, so constraints with the same name never share slack bits.
142    fn fresh_variable(&mut self, name: &str) -> Var {
143        let var = Var(self.names.len());
144        self.names.push(String::from(name));
145        self.lookup.entry(String::from(name)).or_insert(var);
146
147        var
148    }
149
150    /// Adds `value` to the constant objective term.
151    pub fn add_offset(&mut self, value: T) {
152        self.offset = self.offset.plus(value);
153    }
154
155    /// Adds the objective term `value·x`.
156    pub fn add_linear(&mut self, x: Var, value: T) {
157        self.terms.push((x.index(), x.index(), value));
158    }
159
160    /// Adds the objective term `value·x·y`. For `x == y` this is `value·x`.
161    pub fn add_quadratic(&mut self, x: Var, y: Var, value: T) {
162        self.terms.push((x.index(), y.index(), value));
163    }
164
165    /// Adds the constraint "exactly one of `vars` is 1" with the penalty `P·(1 − Σ xᵢ)²`.
166    pub fn exactly_one(&mut self, name: &str, vars: &[Var], penalty: T) {
167        let terms: Vec<(Var, T)> = vars.iter().map(|&v| (v, T::ONE)).collect();
168        self.add_squared_penalty(&terms, T::ONE, penalty);
169        self.push_constraint(name, ConstraintKind::ExactlyOne(vars.to_vec()));
170    }
171
172    /// Adds the constraint "at most one of `vars` is 1" with the penalty `P·Σ_{i<j} xᵢ·xⱼ`.
173    pub fn at_most_one(&mut self, name: &str, vars: &[Var], penalty: T) {
174        for (k, &x) in vars.iter().enumerate() {
175            for &y in &vars[k + 1..] {
176                self.add_quadratic(x, y, penalty);
177            }
178        }
179
180        self.push_constraint(name, ConstraintKind::AtMostOne(vars.to_vec()));
181    }
182
183    /// Adds the constraint `rhs − slack_max ≤ Σ aᵢ·xᵢ ≤ rhs` over `terms = [(xᵢ, aᵢ)]`.
184    ///
185    /// The constraint becomes the equality `Σ aᵢ·xᵢ + s = rhs` with a slack
186    /// `s ∈ [0, slack_max]`, and the penalty `P·(Σ aᵢ·xᵢ + s − rhs)²`. The slack has
187    /// binary digits with the weights 1, 2, 4, … and a last weight that makes the total
188    /// exactly `slack_max`, so no slack value above `slack_max` exists. The slack variables
189    /// are called `"{name}.slack{k}"`, and are always new variables: two constraints with
190    /// the same name do not share slack bits. With `slack_max == 0` there is no slack.
191    ///
192    /// For an upper bound `Σ aᵢ·xᵢ ≤ rhs` with non-negative `aᵢ`, use `slack_max = rhs`.
193    pub fn linear_equality(
194        &mut self,
195        name: &str,
196        terms: &[(Var, T)],
197        rhs: T,
198        slack_max: u32,
199        penalty: T,
200    ) {
201        let mut with_slack = terms.to_vec();
202
203        for (k, weight) in slack_weights(slack_max).enumerate() {
204            let slack = self.fresh_variable(&format!("{name}.slack{k}"));
205            with_slack.push((slack, T::from_u32(weight)));
206        }
207
208        self.add_squared_penalty(&with_slack, rhs, penalty);
209        self.push_constraint(
210            name,
211            ConstraintKind::Linear {
212                terms: terms.to_vec(),
213                rhs,
214                slack_max,
215            },
216        );
217    }
218
219    /// Builds the QUBO model and keeps the names and constraints next to it.
220    #[must_use]
221    pub fn build(self) -> Problem<T> {
222        let mut qubo = Qubo::new(self.names.len());
223        qubo.add_offset(self.offset);
224
225        for (i, j, value) in self.terms {
226            qubo.add_quadratic(i, j, value);
227        }
228
229        Problem {
230            qubo,
231            names: self.names,
232            lookup: self.lookup,
233            constraints: self.constraints,
234        }
235    }
236
237    /// Adds `P·(Σ aᵢ·yᵢ − rhs)²` over `terms = [(yᵢ, aᵢ)]`, with `yᵢ·yᵢ = yᵢ`.
238    ///
239    /// The expansion is `P·(Σᵢ aᵢ²·yᵢ + 2·Σ_{i<j} aᵢ·aⱼ·yᵢ·yⱼ − 2·rhs·Σᵢ aᵢ·yᵢ + rhs²)`.
240    /// A variable that occurs twice gets its pair term on the diagonal.
241    fn add_squared_penalty(&mut self, terms: &[(Var, T)], rhs: T, penalty: T) {
242        self.add_offset(penalty.times(rhs).times(rhs));
243
244        for (k, &(y, a)) in terms.iter().enumerate() {
245            let diagonal = a.minus(rhs.plus(rhs)).times(a);
246            self.add_linear(y, penalty.times(diagonal));
247
248            for &(z, b) in &terms[k + 1..] {
249                let pair = a.times(b);
250                self.add_quadratic(y, z, penalty.times(pair.plus(pair)));
251            }
252        }
253    }
254
255    /// Records a constraint for the decoder.
256    fn push_constraint(&mut self, name: &str, kind: ConstraintKind<T>) {
257        self.constraints.push(Constraint {
258            name: String::from(name),
259            kind,
260        });
261    }
262}
263
264/// The slack digit weights for a slack in `[0, max]`: 1, 2, 4, …, then the remainder.
265///
266/// The weights sum to `max`, and each value in `[0, max]` is a subset sum. The number of
267/// weights is `⌊log₂ max⌋ + 1` for `max > 0`, and 0 for `max == 0`.
268fn slack_weights(max: u32) -> impl Iterator<Item = u32> {
269    let mut remaining = max;
270    let mut next = 1_u32;
271
272    core::iter::from_fn(move || {
273        if remaining == 0 {
274            return None;
275        }
276
277        let weight = next.min(remaining);
278        remaining -= weight;
279        next = next.saturating_mul(2);
280
281        Some(weight)
282    })
283}
284
285/// A QUBO model built by a [`Builder`], with its variable names and constraints.
286#[derive(Debug, Clone, PartialEq)]
287pub struct Problem<T> {
288    /// The model: objective plus penalties.
289    qubo: Qubo<T>,
290    /// The variable names, in index order.
291    names: Vec<String>,
292    /// The variable of each name.
293    lookup: BTreeMap<String, Var>,
294    /// The constraints, in the order they were added.
295    constraints: Vec<Constraint<T>>,
296}
297
298impl<T: Coefficient> Problem<T> {
299    /// The QUBO model: objective plus penalties.
300    #[must_use]
301    pub fn qubo(&self) -> &Qubo<T> {
302        &self.qubo
303    }
304
305    /// The variable called `name`, if it exists.
306    #[must_use]
307    pub fn variable(&self, name: &str) -> Option<Var> {
308        self.lookup.get(name).copied()
309    }
310
311    /// The name of the variable `var`.
312    ///
313    /// # Panics
314    ///
315    /// Panics if `var` is not from the builder of this problem.
316    #[must_use]
317    pub fn name(&self, var: Var) -> &str {
318        &self.names[var.index()]
319    }
320
321    /// The constraints, in the order they were added.
322    #[must_use]
323    pub fn constraints(&self) -> &[Constraint<T>] {
324        &self.constraints
325    }
326
327    /// The constraints that the assignment `x` does not satisfy, in the order they were added.
328    ///
329    /// The check uses the original variables only, not the penalty energy or slack bits.
330    ///
331    /// # Panics
332    ///
333    /// Panics if `x.len()` is not the number of variables.
334    pub fn violations<'a>(&'a self, x: &'a [bool]) -> impl Iterator<Item = &'a Constraint<T>> {
335        assert_eq!(
336            x.len(),
337            self.qubo.num_variables(),
338            "the assignment length must equal the number of variables"
339        );
340
341        self.constraints.iter().filter(|c| !c.is_satisfied(x))
342    }
343}
344
345/// Unit tests for the penalty terms of each constraint type.
346#[cfg(test)]
347mod tests {
348    use alloc::vec::Vec;
349
350    use super::{Builder, Var, slack_weights};
351
352    /// All assignments of `n` variables, as bit vectors.
353    fn assignments(n: usize) -> impl Iterator<Item = Vec<bool>> {
354        (0..1_u32 << n).map(move |bits| (0..n).map(|i| bits >> i & 1 == 1).collect())
355    }
356
357    /// Checks the penalty contract over all assignments of the first `original` variables.
358    ///
359    /// For each assignment, the minimum energy over the slack bits must be 0 if all
360    /// constraints hold, and at least `penalty` otherwise.
361    fn assert_penalty_contract(builder: Builder<i64>, original: usize, penalty: i64) {
362        let problem = builder.build();
363        let n = problem.qubo().num_variables();
364
365        for x in assignments(original) {
366            let best = assignments(n - original)
367                .map(|slack| problem.qubo().energy(&[x.clone(), slack].concat()))
368                .min()
369                .expect("there is at least one slack assignment");
370
371            let padded = [x.clone(), alloc::vec![false; n - original]].concat();
372            let feasible = problem.violations(&padded).next().is_none();
373
374            if feasible {
375                assert_eq!(best, 0, "a feasible assignment {x:?} has a penalty");
376            } else {
377                assert!(
378                    best >= penalty,
379                    "an infeasible assignment {x:?} is too cheap"
380                );
381            }
382        }
383    }
384
385    /// Creates a builder with the variables `x0` to `x{n-1}`.
386    fn builder_with(n: usize) -> (Builder<i64>, Vec<Var>) {
387        let mut builder = Builder::new();
388        let vars = (0..n)
389            .map(|i| builder.variable(&alloc::format!("x{i}")))
390            .collect();
391
392        (builder, vars)
393    }
394
395    /// Exactly-one penalizes zero and two or more set variables.
396    #[test]
397    fn exactly_one_contract() {
398        let (mut builder, vars) = builder_with(4);
399        builder.exactly_one("one", &vars, 3);
400
401        assert_penalty_contract(builder, 4, 3);
402    }
403
404    /// At-most-one penalizes two or more set variables.
405    #[test]
406    fn at_most_one_contract() {
407        let (mut builder, vars) = builder_with(4);
408        builder.at_most_one("most", &vars, 3);
409
410        assert_penalty_contract(builder, 4, 3);
411    }
412
413    /// A linear constraint with slack and a repeated variable keeps the contract.
414    #[test]
415    fn linear_with_slack_contract() {
416        for slack_max in 0..=6 {
417            let (mut builder, vars) = builder_with(3);
418            let terms = [(vars[0], 2), (vars[1], 3), (vars[2], 1), (vars[0], 1)];
419            builder.linear_equality("cap", &terms, 5, slack_max, 2);
420
421            assert_penalty_contract(builder, 3, 2);
422        }
423    }
424
425    /// Slack weights sum to the maximum and never exceed the next power of two.
426    #[test]
427    fn slack_weights_cover_the_range() {
428        for max in 0..100 {
429            let weights: Vec<u32> = slack_weights(max).collect();
430            assert_eq!(weights.iter().sum::<u32>(), max);
431            assert!(weights.iter().all(|&w| w > 0));
432        }
433
434        assert_eq!(slack_weights(5).collect::<Vec<_>>(), [1, 2, 2]);
435    }
436
437    /// Two constraints with the same name get separate slack bits.
438    #[test]
439    fn same_name_constraints_do_not_share_slack() {
440        let (mut builder, vars) = builder_with(2);
441        builder.linear_equality("cap", &[(vars[0], 1)], 1, 1, 2);
442        builder.linear_equality("cap", &[(vars[1], 1)], 1, 1, 2);
443
444        let problem = builder.build();
445
446        assert_eq!(problem.qubo().num_variables(), 4);
447        assert_eq!(problem.variable("cap.slack0").map(Var::index), Some(2));
448    }
449
450    /// The same name returns the same variable.
451    #[test]
452    fn variables_are_named_once() {
453        let mut builder = Builder::<i64>::new();
454        let a = builder.variable("a");
455        let b = builder.variable("b");
456
457        assert_eq!(builder.variable("a"), a);
458        assert_ne!(a, b);
459
460        let problem = builder.build();
461        assert_eq!(problem.name(b), "b");
462        assert_eq!(problem.variable("b"), Some(b));
463        assert_eq!(problem.variable("c"), None);
464    }
465}