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
//! # Certified CNF Encodings for Cardinality Constraints
use std::ops::RangeBounds;
use pigeons::AbsConstraintId;
use crate::{
clause,
encodings::cert::{CollectClauses, ConstraintEncodingError, EncodingError},
instances::ManageVars,
types::{
constraints::{CardConstraint, CardEqConstr, CardLbConstr, CardUbConstr},
Lit,
},
utils::unreachable_err,
};
use super::Totalizer;
/// Trait for certified cardinality encodings that allow upper bounding of the form `sum of lits <=
/// ub`
pub trait BoundUpper: super::Encode + super::BoundUpper {
/// Lazily builds the certified cardinality encoding to enable upper bounds in a given range.
/// `var_manager` is the variable manager to use for tracking new variables. A specific
/// encoding might ignore the lower or upper end of the range. The derivation of the encoding
/// is written to the given `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_ub_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize>,
W: std::io::Write;
/// Encodes an upper bound cardinality constraint to CNF with proof logging
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_ub_constr_cert<Col, W>(
constr: (CardUbConstr, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
W: std::io::Write,
Self: FromIterator<Lit> + Sized;
}
/// Trait for certified cardinality encodings that allow lower bounding of the form `sum of lits >=
/// lb`
pub trait BoundLower: super::Encode + super::BoundLower {
/// Lazily builds the certified cardinality encoding to enable lower bounds in a given range.
/// `var_manager` is the variable manager to use for tracking new variables. A specific
/// encoding might ignore the lower or upper end of the range. The derivation of the encoding
/// is written to the given `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_lb_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize>,
W: std::io::Write;
/// Encodes a lower bound cardinality constraint to CNF with proof logging
///
/// # Errors
///
/// If the clause collector runs out of memory, writing the proof fails, or the constraint is
/// unsatisfiable
fn encode_lb_constr_cert<Col, W>(
constr: (CardLbConstr, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), ConstraintEncodingError>
where
Col: CollectClauses,
W: std::io::Write,
Self: FromIterator<Lit> + Sized;
}
/// Trait for certified cardinality encodings that allow upper and lower bounding
pub trait BoundBoth: BoundUpper + BoundLower + super::BoundBoth {
/// Lazily builds the certified cardinality encoding to enable both bounds in a given range.
/// `var_manager` is the variable manager to use for tracking new variables. A specific
/// encoding might ignore the lower or upper end of the range. The derivation of the encoding
/// is written to the given `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_both_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize> + Clone,
W: std::io::Write,
{
self.encode_ub_cert(range.clone(), collector, var_manager, proof)?;
self.encode_lb_cert(range, collector, var_manager, proof)?;
Ok(())
}
/// Encodes an equality cardinality constraint to CNF with proof logging
///
/// # Errors
///
/// If the clause collector runs out of memory, writing the proof fails, or the constraint is
/// unsatisfiable
fn encode_eq_constr_cert<Col, W>(
constr: (CardEqConstr, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), ConstraintEncodingError>
where
Col: CollectClauses,
W: std::io::Write,
Self: FromIterator<Lit> + Sized,
{
// Assume the two constraints have ID as given and +1
let (constr, id) = constr;
let (lb_c, ub_c) = constr.split();
Self::encode_ub_constr_cert((ub_c, id + 1), collector, var_manager, proof)?;
Self::encode_lb_constr_cert((lb_c, id), collector, var_manager, proof)?;
Ok(())
}
/// Encodes any cardinality constraint to CNF with proof logging
///
/// # Errors
///
/// If the clause collector runs out of memory, writing the proof fails, or the constraint is
/// unsatisfiable
fn encode_constr_cert<Col, W>(
constr: (CardConstraint, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), ConstraintEncodingError>
where
Col: CollectClauses,
W: std::io::Write,
Self: FromIterator<Lit> + Sized,
{
let (constr, id) = constr;
match constr {
CardConstraint::Ub(constr) => {
Self::encode_ub_constr_cert((constr, id), collector, var_manager, proof)?;
Ok(())
}
CardConstraint::Lb(constr) => {
Self::encode_lb_constr_cert((constr, id), collector, var_manager, proof)
}
CardConstraint::Eq(constr) => {
Self::encode_eq_constr_cert((constr, id), collector, var_manager, proof)
}
}
}
}
/// Trait for incremental certified cardinality encodings that allow upper bounding of the form
/// `sum of lits <= ub`
pub trait BoundUpperIncremental: BoundUpper + super::EncodeIncremental {
/// Lazily builds the _change in_ the certified cardinality encoding to enable upper bounds in
/// a given range. A change might be added literals or changed bounds. `var_manager` is the
/// variable manager to use for tracking new variables. A specific encoding might ignore the
/// lower or upper end of the range. The derivation of the encoding is written to the given
/// `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_ub_change_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize>,
W: std::io::Write;
}
/// Trait for incremental certified cardinality encodings that allow lower bounding of the form
/// `sum of lits >= lb`
pub trait BoundLowerIncremental: BoundLower + super::EncodeIncremental {
/// Lazily builds the _change in_ the certified cardinality encoding to enable upper bounds in
/// a given range. A change might be added literals or changed bounds. `var_manager` is the
/// variable manager to use for tracking new variables. A specific encoding might ignore the
/// lower or upper end of the range. The derivation of the encoding is written to the given
/// `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_lb_change_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize>,
W: std::io::Write;
}
/// Trait for incremental cardinality encodings that allow upper and lower bounding
pub trait BoundBothIncremental: BoundUpperIncremental + BoundLowerIncremental + BoundBoth {
/// Lazily builds the _change in_ the certified cardinality encoding to enable both bounds in a
/// given range. `var_manager` is the variable manager to use for tracking new variables. A
/// specific encoding might ignore the lower or upper end of the range. The derivation of the
/// encoding is written to the given `proof`.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
fn encode_both_change_cert<Col, R, W>(
&mut self,
range: R,
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError>
where
Col: CollectClauses,
R: RangeBounds<usize> + Clone,
W: std::io::Write,
{
self.encode_ub_change_cert(range.clone(), collector, var_manager, proof)?;
self.encode_lb_change_cert(range, collector, var_manager, proof)?;
Ok(())
}
}
/// The default upper bound encoding. For now this is a [`Totalizer`].
pub type DefUpperBounding = Totalizer;
/// The default lower bound encoding. For now this is a [`Totalizer`].
pub type DefLowerBounding = Totalizer;
/// The default encoding for both bounds. For now this is a [`Totalizer`].
pub type DefBothBounding = Totalizer;
/// The default incremental upper bound encoding. For now this is a [`Totalizer`].
pub type DefIncUpperBounding = Totalizer;
/// The default incremental lower bound encoding. For now this is a [`Totalizer`].
pub type DefIncLowerBounding = Totalizer;
/// The default incremental encoding for both bounds. For now this is a [`Totalizer`].
pub type DefIncBothBounding = Totalizer;
/// Constructs a default upper bounding cardinality encoding.
#[must_use]
pub fn new_default_ub() -> impl BoundUpper {
DefUpperBounding::default()
}
/// Constructs a default lower bounding cardinality encoding.
#[must_use]
pub fn new_default_lb() -> impl BoundLower {
DefLowerBounding::default()
}
/// Constructs a default double bounding cardinality encoding.
#[must_use]
pub fn new_default_both() -> impl BoundBoth {
DefBothBounding::default()
}
/// Constructs a default incremental upper bounding cardinality encoding.
#[must_use]
pub fn new_default_inc_ub() -> impl BoundUpperIncremental {
DefIncUpperBounding::default()
}
/// Constructs a default incremental lower bounding cardinality encoding.
#[must_use]
pub fn new_default_inc_lb() -> impl BoundLower {
DefIncLowerBounding::default()
}
/// Constructs a default incremental double bounding cardinality encoding.
#[must_use]
pub fn new_default_inc_both() -> impl BoundBoth {
DefIncBothBounding::default()
}
/// A default encoder for any cardinality constraint. This uses a
/// [`DefBothBounding`] to encode non-trivial constraints.
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
pub fn default_encode_cardinality_constraint<Col: CollectClauses, W: std::io::Write>(
constr: (CardConstraint, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError> {
encode_cardinality_constraint::<DefBothBounding, Col, W>(constr, collector, var_manager, proof)
}
/// An encoder for any cardinality constraint with an encoding of choice
///
/// # Errors
///
/// If the clause collector runs out of memory, or writing the proof fails
pub fn encode_cardinality_constraint<
CE: BoundBoth + FromIterator<Lit>,
Col: CollectClauses,
W: std::io::Write,
>(
constr: (CardConstraint, AbsConstraintId),
collector: &mut Col,
var_manager: &mut dyn ManageVars,
proof: &mut pigeons::Proof<W>,
) -> Result<(), EncodingError> {
let (constr, mut id) = constr;
if constr.is_tautology() {
return Ok(());
}
if constr.is_unsat() {
let empty = clause![];
let unsat_id = proof.reverse_unit_prop(&empty, [id.into()])?;
collector.add_cert_clause(empty, unsat_id)?;
return Ok(());
}
if constr.is_positive_assignment() {
for lit in constr.into_lits() {
let unit = clause![lit];
let unit_id = proof.reverse_unit_prop(&unit, [id.into()])?;
collector.add_cert_clause(unit, unit_id)?;
}
return Ok(());
}
if constr.is_negative_assignment() {
if matches!(constr, CardConstraint::Eq(_)) {
id += 1;
}
for lit in constr.into_lits() {
let unit = clause![!lit];
let unit_id = proof.reverse_unit_prop(&unit, [id.into()])?;
collector.add_cert_clause(unit, unit_id)?;
}
return Ok(());
}
if constr.is_clause() {
let clause = unreachable_err!(constr.into_clause());
let cl_id = proof.reverse_unit_prop(&clause, [id.into()])?;
collector.add_cert_clause(clause, cl_id)?;
return Ok(());
}
match CE::encode_constr_cert((constr, id), collector, var_manager, proof) {
Ok(()) => Ok(()),
Err(ConstraintEncodingError::OutOfMemory(err)) => Err(err.into()),
Err(ConstraintEncodingError::Proof(err)) => Err(err.into()),
Err(ConstraintEncodingError::Unsat) => unreachable!(),
}
}