huub 100.0.0

CP+SAT solver framework built to be reliable, performant, and extensible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Definitions for Propositional Logic expressions and constraints that can be
//! used in [`Model`].

use pindakaas::{
	Lit as RawLit,
	propositional_logic::{Formula, TseitinEncoder},
};

use crate::{
	actions::{
		BoolInitActions, BoolInspectionActions, BoolPropagationActions, InitActions,
		PropagationActions, ReasoningEngine, SimplificationActions,
	},
	constraints::{
		BoolModelActions, BoolSolverActions, Constraint, Propagator, SimplificationStatus,
	},
	lower::{LoweringContext, LoweringError},
	model::view::View,
	solver::view::boolean::BoolView,
};

/// Type alias for the type used to represent propositional logic formulas that
/// can be used in [`Model`](crate::model::Model).
pub type BoolFormula = Formula<View<bool>>;

impl<E> Constraint<E> for BoolFormula
where
	E: ReasoningEngine,
	for<'a> E::PropagationContext<'a>: SimplificationActions<Target = E>,
	View<bool>: BoolModelActions<E>,
{
	fn simplify(
		&mut self,
		ctx: &mut E::PropagationContext<'_>,
	) -> Result<SimplificationStatus, E::Conflict> {
		let mut resolver = |bv: View<bool>| {
			if let Some(b) = bv.val(ctx) {
				return Err(b);
			};
			Ok(bv)
		};
		let result = self.clone().simplify_with(&mut resolver);
		let mut f = match result {
			Ok(f) => f,
			Err(true) => return Ok(SimplificationStatus::Subsumed),
			Err(false) => return Err(ctx.declare_conflict([])),
		};

		let negate = |f: BoolFormula| match f {
			Formula::Atom(x) => Formula::Atom(!x),
			Formula::Not(x) if matches!(*x, Formula::Atom(_)) => {
				let Formula::Atom(x) = *x else { unreachable!() };
				Formula::Atom(x)
			}
			f => Formula::Not(Box::new(f)),
		};

		while let Formula::Not(neg_f) = f {
			f = match *neg_f {
				// Demorgan's Law transformation
				Formula::And(v) => Formula::Or(v.into_iter().map(negate).collect()),
				Formula::Atom(x) => Formula::Atom(!x),
				Formula::IfThenElse { cond, then, els } => Formula::IfThenElse {
					cond,
					then: Box::new(!*then),
					els: Box::new(!*els),
				},
				Formula::Implies(x, y) => {
					// Demorgan's Law transformation
					// ¬(x → y) ≡ ¬(¬x v y) ≡ x ∧ ¬y
					Formula::And(vec![*x, !*y])
				}
				// Double not elimination
				Formula::Not(f) => *f,
				// Demorgan's Law transformation
				Formula::Or(v) => Formula::And(v.into_iter().map(negate).collect()),
				Formula::Equiv(f) => Formula::And(vec![
					Formula::Or(f.iter().map(|f| !(f.clone())).collect()),
					Formula::Or(f),
				]),
				Formula::Xor(f) if f.len() < 2 => unreachable!(),
				Formula::Xor(f) if f.len() == 2 => Formula::Equiv(f),
				Formula::Xor(mut f) => {
					f[0] = negate(f[0].clone());
					Formula::Xor(f)
				}
			};
		}

		*self = match f {
			Formula::And(v) => {
				for f in v {
					match f {
						Formula::Atom(x) => {
							x.require(ctx, [])?;
						}
						Formula::Not(x) if matches!(*x, Formula::Atom(_)) => {
							let Formula::Atom(x) = *x else { unreachable!() };
							x.fix(ctx, false, [])?;
						}
						f => {
							ctx.post_constraint(f);
						}
					}
				}
				return Ok(SimplificationStatus::Subsumed);
			}
			Formula::Atom(b) => {
				b.require(ctx, [])?;
				return Ok(SimplificationStatus::Subsumed);
			}
			Formula::Not(_) => unreachable!(),
			f => f,
		};
		Ok(SimplificationStatus::NoFixpoint)
	}

	fn to_solver(&self, slv: &mut LoweringContext<'_>) -> Result<(), LoweringError> {
		let mut resolver = |bv: View<bool>| {
			let inner = slv.solver_view(bv);
			match inner.0 {
				BoolView::Const(b) => Err(b),
				BoolView::Lit(l) => Ok(l.0),
			}
		};
		let result: Result<Formula<RawLit>, _> = self.clone().simplify_with(&mut resolver);
		match result {
			Err(false) => Err(slv.declare_conflict([]).into()),
			Err(true) => Ok(()),
			Ok(f) => slv.cnf_encode(&f, &TseitinEncoder),
		}
	}
}

impl From<View<bool>> for BoolFormula {
	fn from(v: View<bool>) -> Self {
		Self::Atom(v)
	}
}

impl<E> Propagator<E> for BoolFormula
where
	E: ReasoningEngine,
	View<bool>: BoolSolverActions<E>,
{
	fn initialize(&mut self, ctx: &mut E::InitializationContext<'_>) {
		ctx.enqueue_now(true);
		match self {
			Formula::And(v) => v.iter_mut().for_each(|f| f.initialize(ctx)),
			Formula::Atom(a) => a.enqueue_when_fixed(ctx),
			Formula::Equiv(v) => v.iter_mut().for_each(|f| f.initialize(ctx)),
			Formula::IfThenElse { cond, then, els } => {
				cond.initialize(ctx);
				then.initialize(ctx);
				els.initialize(ctx);
			}
			Formula::Implies(f1, f2) => {
				f1.initialize(ctx);
				f2.initialize(ctx);
			}
			Formula::Not(f) => f.initialize(ctx),
			Formula::Or(v) => v.iter_mut().for_each(|f| f.initialize(ctx)),
			Formula::Xor(v) => v.iter_mut().for_each(|f| f.initialize(ctx)),
		}
	}

	fn propagate(
		&mut self,
		_: &mut <E as ReasoningEngine>::PropagationContext<'_>,
	) -> Result<(), <E as ReasoningEngine>::Conflict> {
		unreachable!()
	}
}

#[cfg(test)]
mod tests {
	use pindakaas::propositional_logic::Formula;

	use crate::{
		actions::BoolInspectionActions,
		constraints::{Constraint, SimplificationStatus},
		model::{Model, expressions::bool_formula::BoolFormula},
	};

	#[test]
	fn simplify_and_formula() {
		use Formula::*;

		// Test case for And with a true literal
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = And(vec![Atom(x), Atom(true.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));

		// Test case for And with a false literal
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = And(vec![Atom(x), Atom(false.into())]);
		assert!(<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb).is_err());
	}

	#[test]
	fn simplify_equiv_formula() {
		use Formula::*;

		// Test case for Equiv(x, true) -> x
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Equiv(vec![Atom(x), Atom(true.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));

		// Test case for Equiv(x, false) -> !x
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Equiv(vec![Atom(x), Atom(false.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(false));
	}

	#[test]
	fn simplify_ifthenelse_formula() {
		use Formula::*;

		// Test case for IfThenElse(true, t, e) -> t
		let mut prb = Model::default();
		let t = prb.new_bool_decision();
		let e = prb.new_bool_decision();
		let mut f: BoolFormula = IfThenElse {
			cond: Box::new(Atom(true.into())),
			then: Box::new(Atom(t)),
			els: Box::new(Atom(e)),
		};
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(t.val(&prb), Some(true));
		assert_eq!(e.val(&prb), None);

		// Test case for IfThenElse(false, t, e) -> e
		let mut prb = Model::default();
		let t = prb.new_bool_decision();
		let e = prb.new_bool_decision();
		let mut f: BoolFormula = IfThenElse {
			cond: Box::new(Atom(false.into())),
			then: Box::new(Atom(t)),
			els: Box::new(Atom(e)),
		};
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(t.val(&prb), None);
		assert_eq!(e.val(&prb), Some(true));
	}

	#[test]
	fn simplify_implies_formula() {
		use Formula::*;

		// Test case for Implies(true, y) -> y
		let mut prb = Model::default();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Implies(Box::new(Atom(true.into())), Box::new(Atom(y)));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(y.val(&prb), Some(true));

		// Test case for Implies(x, false) -> !x
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Implies(Box::new(Atom(x)), Box::new(Atom(false.into())));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(false));
	}

	#[test]
	fn simplify_not_formula() {
		use Formula::*;

		// Test case for Not(Not(x))
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Not(Box::new(Atom(x)))));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));

		// Test case for De Morgan's law with And
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(And(vec![Atom(x), Atom(y)])));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::NoFixpoint)
		);
		assert_eq!(f, Or(vec![Atom(!x), Atom(!y)]));

		// Test case for De Morgan's law with Or
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Or(vec![Atom(x), Atom(y)])));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(false));
		assert_eq!(y.val(&prb), Some(false));

		// Test case for Not(Implies)
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Implies(Box::new(Atom(x)), Box::new(Atom(y)))));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));
		assert_eq!(y.val(&prb), Some(false));

		// Test case for Not(IfThenElse)
		let mut prb = Model::default();
		let c = prb.new_bool_decision();
		let t = prb.new_bool_decision();
		let e = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(IfThenElse {
			cond: Box::new(Atom(c)),
			then: Box::new(Atom(t)),
			els: Box::new(Atom(e)),
		}));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::NoFixpoint)
		);
		assert_eq!(
			f,
			IfThenElse {
				cond: Box::new(Atom(c)),
				then: Box::new(Not(Box::new(Atom(t)))),
				els: Box::new(Not(Box::new(Atom(e)))),
			}
		);

		// Test case for Not(Equiv(x,y))
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Equiv(vec![Atom(x), Atom(y)])));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed) // rewritten to two clauses
		);
		assert_eq!(x.val(&prb), None);
		assert_eq!(y.val(&prb), None);

		// Test case for Not(Xor(x, y))
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Xor(vec![Atom(x), Atom(y)])));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::NoFixpoint)
		);
		assert_eq!(f, Equiv(vec![Atom(x), Atom(y)]));

		// Test case for Not(Xor(x, y, z))
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let y = prb.new_bool_decision();
		let z = prb.new_bool_decision();
		let mut f: BoolFormula = Not(Box::new(Xor(vec![Atom(x), Atom(y), Atom(z)])));
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::NoFixpoint)
		);
		assert_eq!(f, Xor(vec![Atom(!x), Atom(y), Atom(z)]));
	}

	#[test]
	fn simplify_or_formula() {
		use Formula::*;

		// Test case for Or with a true literal
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Or(vec![Atom(x), Atom(true.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), None);

		// Test case for Or with a false literal
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Or(vec![Atom(x), Atom(false.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));
	}

	#[test]
	fn simplify_xor_formula() {
		use Formula::*;

		// Test case for Xor(x, false) -> x
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Xor(vec![Atom(x), Atom(false.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(true));

		// Test case for Xor(x, true) -> !x
		let mut prb = Model::default();
		let x = prb.new_bool_decision();
		let mut f: BoolFormula = Xor(vec![Atom(x), Atom(true.into())]);
		assert_eq!(
			<BoolFormula as Constraint<Model>>::simplify(&mut f, &mut prb),
			Ok(SimplificationStatus::Subsumed)
		);
		assert_eq!(x.val(&prb), Some(false));
	}
}