1use alloc::collections::BTreeMap;
4use alloc::format;
5use alloc::string::String;
6use alloc::vec::Vec;
7
8use crate::{Coefficient, Qubo};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Var(usize);
13
14impl Var {
15 #[must_use]
17 pub fn index(self) -> usize {
18 self.0
19 }
20}
21
22#[derive(Debug, Clone, PartialEq)]
24pub struct Constraint<T> {
25 pub name: String,
27 pub kind: ConstraintKind<T>,
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub enum ConstraintKind<T> {
34 ExactlyOne(Vec<Var>),
36 AtMostOne(Vec<Var>),
38 Linear {
42 terms: Vec<(Var, T)>,
44 rhs: T,
46 slack_max: u32,
48 },
49}
50
51impl<T: Coefficient> Constraint<T> {
52 #[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
74fn count_set(vars: &[Var], x: &[bool]) -> usize {
76 vars.iter().filter(|v| x[v.index()]).count()
77}
78
79fn 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#[derive(Debug, Clone)]
93pub struct Builder<T> {
94 names: Vec<String>,
96 lookup: BTreeMap<String, Var>,
98 offset: T,
100 terms: Vec<(usize, usize, T)>,
102 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 #[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 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 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 pub fn add_offset(&mut self, value: T) {
152 self.offset = self.offset.plus(value);
153 }
154
155 pub fn add_linear(&mut self, x: Var, value: T) {
157 self.terms.push((x.index(), x.index(), value));
158 }
159
160 pub fn add_quadratic(&mut self, x: Var, y: Var, value: T) {
162 self.terms.push((x.index(), y.index(), value));
163 }
164
165 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 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 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 #[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 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 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
264fn 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#[derive(Debug, Clone, PartialEq)]
287pub struct Problem<T> {
288 qubo: Qubo<T>,
290 names: Vec<String>,
292 lookup: BTreeMap<String, Var>,
294 constraints: Vec<Constraint<T>>,
296}
297
298impl<T: Coefficient> Problem<T> {
299 #[must_use]
301 pub fn qubo(&self) -> &Qubo<T> {
302 &self.qubo
303 }
304
305 #[must_use]
307 pub fn variable(&self, name: &str) -> Option<Var> {
308 self.lookup.get(name).copied()
309 }
310
311 #[must_use]
317 pub fn name(&self, var: Var) -> &str {
318 &self.names[var.index()]
319 }
320
321 #[must_use]
323 pub fn constraints(&self) -> &[Constraint<T>] {
324 &self.constraints
325 }
326
327 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#[cfg(test)]
347mod tests {
348 use alloc::vec::Vec;
349
350 use super::{Builder, Var, slack_weights};
351
352 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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}