rustsat 0.7.5

This library aims to provide implementations of elements commonly used in the development on software in the area of satisfiability solving. The focus of the library is to provide as much ease of use without giving up on performance.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! # CNF Encodings for Cardinality Constraints
//!
//! The module contains implementations of CNF encodings for cardinality
//! constraints. It defines traits for (non-)incremental cardinality constraints
//! and encodings implementing these traits.
//!
//! ## Example Usage
//!
//! ```
//! # use rustsat::{
//! #     clause,
//! #     encodings::card::{BoundBoth, DefIncBothBounding, Encode},
//! #     instances::{BasicVarManager, Cnf, ManageVars},
//! #     lit, solvers, var,
//! # };
//! #
//! let mut var_manager = BasicVarManager::default();
//! var_manager.increase_next_free(var![4]);
//!
//! let mut enc = DefIncBothBounding::from(vec![lit![0], lit![1], lit![2], lit![3]]);
//! let mut encoding = Cnf::new();
//! enc.encode_both(3..=3, &mut encoding, &mut var_manager);
//! ```
//!
//! When using cardinality and pseudo-boolean encodings at the same time, it is
//! recommended to import only the modules or rename the traits, e.g., `use
//! card::Encode as EncodeCard`.

use std::{
    cmp,
    ops::{Bound, Range, RangeBounds},
};

use super::{CollectClauses, ConstraintEncodingError, EnforceError, NotEncoded};
use crate::{
    clause,
    instances::ManageVars,
    types::{
        constraints::{CardConstraint, CardEqConstr, CardLbConstr, CardUbConstr},
        Clause, Lit,
    },
    utils::unreachable_err,
};

pub mod totalizer;
pub use totalizer::Totalizer;

pub mod simulators;

#[cfg(feature = "proof-logging")]
pub mod cert;

/// Trait for all cardinality encodings of form `sum of lits <> rhs`
pub trait Encode {
    /// Gets the number of input literals in the encoding
    fn n_lits(&self) -> usize;
}

/// Trait for cardinality encodings that allow upper bounding of the form `sum
/// of lits <= ub`
pub trait BoundUpper: Encode {
    /// Lazily builds the 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.
    ///
    /// # Errors
    ///
    /// If the clause collector runs out of memory.
    fn encode_ub<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize>;
    /// Returns assumptions/units for enforcing an upper bound (`sum of lits <=
    /// ub`). Make sure that [`BoundUpper::encode_ub`] has been called
    /// adequately and nothing has been called afterwards.
    ///
    /// # Errors
    ///
    /// If [`BoundUpper::encode_ub`] has not been called adequately.
    fn enforce_ub(&self, ub: usize) -> Result<Vec<Lit>, NotEncoded>;
    /// Encodes an upper bound cardinality constraint to CNF
    ///
    /// # Errors
    ///
    /// If the the collector runs out of memory. Note that upper bound constraints can never be
    /// unsatisfiable because their bound is a [`usize`].
    fn encode_ub_constr<Col>(
        constr: CardUbConstr,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        Self: FromIterator<Lit> + Sized,
    {
        let (lits, ub) = constr.decompose();
        let mut enc = Self::from_iter(lits);
        enc.encode_ub(ub..=ub, collector, var_manager)?;
        collector.extend_clauses(
            enc.enforce_ub(ub)
                .unwrap()
                .into_iter()
                .map(|unit| clause![unit]),
        )?;
        Ok(())
    }
}

/// Trait for cardinality encodings that allow lower bounding of the form `sum
/// of lits >= lb`
pub trait BoundLower: Encode {
    /// Lazily builds the 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.
    ///
    /// # Errors
    ///
    /// If the collector runs out of memory.
    fn encode_lb<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize>;
    /// Returns assumptions/units for enforcing a lower bound (`sum of lits >=
    /// lb`). Make sure that [`BoundLower::encode_lb`] has been called
    /// adequately and nothing has been added afterwards.
    ///
    /// # Errors
    ///
    /// If [`BoundLower::encode_lb`] has not been called adequately, or `lb` is larger than the
    /// number literals in the encoding.
    fn enforce_lb(&self, lb: usize) -> Result<Vec<Lit>, EnforceError>;
    /// Encodes a lower bound cardinality constraint to CNF
    ///
    /// # Errors
    ///
    /// If the constraint is unsatisfiable or the collector runs out of memory.
    fn encode_lb_constr<Col>(
        constr: CardLbConstr,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), ConstraintEncodingError>
    where
        Col: CollectClauses,
        Self: FromIterator<Lit> + Sized,
    {
        let (lits, lb) = constr.decompose();
        if lb > lits.len() {
            return Err(ConstraintEncodingError::Unsat);
        }
        let mut enc = Self::from_iter(lits);
        enc.encode_lb(lb..=lb, collector, var_manager)?;
        collector.extend_clauses(
            enc.enforce_lb(lb)
                .unwrap()
                .into_iter()
                .map(|unit| clause![unit]),
        )?;
        Ok(())
    }
}

/// Trait for cardinality encodings that allow upper and lower bounding
pub trait BoundBoth: BoundUpper + BoundLower {
    /// Lazily builds the 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.
    ///
    /// # Errors
    ///
    /// If the clause collector runs out of memory.
    fn encode_both<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize> + Clone,
    {
        self.encode_ub(range.clone(), collector, var_manager)?;
        self.encode_lb(range, collector, var_manager)?;
        Ok(())
    }
    /// Returns assumptions for enforcing an equality (`sum of lits = b`) or an
    /// error if the encoding does not support one of the two required bound
    /// types. Make sure the adequate `encode_x` methods have been called before
    /// this method and nothing has been added afterwards.
    ///
    /// # Errors
    ///
    /// If not adequately encoded, or `b` is larger than the number literals in the encoding.
    fn enforce_eq(&self, b: usize) -> Result<Vec<Lit>, EnforceError> {
        let mut assumps = self.enforce_ub(b)?;
        assumps.extend(self.enforce_lb(b)?);
        Ok(assumps)
    }
    /// Encodes an equality cardinality constraint to CNF
    ///
    /// # Errors
    ///
    /// If the constraint is unsatisfiable or the collector runs out of memory.
    fn encode_eq_constr<Col>(
        constr: CardEqConstr,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), ConstraintEncodingError>
    where
        Col: CollectClauses,
        Self: FromIterator<Lit> + Sized,
    {
        let (lits, b) = constr.decompose();
        if b > lits.len() {
            return Err(ConstraintEncodingError::Unsat);
        }
        let mut enc = Self::from_iter(lits);
        enc.encode_both(b..=b, collector, var_manager)?;
        collector.extend_clauses(
            enc.enforce_eq(b)
                .unwrap()
                .into_iter()
                .map(|unit| clause![unit]),
        )?;
        Ok(())
    }
    /// Encodes any cardinality constraint to CNF
    ///
    /// # Errors
    ///
    /// If the constraint is unsatisfiable or the collector runs out of memory.
    fn encode_constr<Col>(
        constr: CardConstraint,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), ConstraintEncodingError>
    where
        Col: CollectClauses,
        Self: FromIterator<Lit> + Sized,
    {
        match constr {
            CardConstraint::Ub(constr) => {
                Self::encode_ub_constr(constr, collector, var_manager)?;
                Ok(())
            }
            CardConstraint::Lb(constr) => Self::encode_lb_constr(constr, collector, var_manager),
            CardConstraint::Eq(constr) => Self::encode_eq_constr(constr, collector, var_manager),
        }
    }
}

/// Trait for all cardinality encodings of form `sum of lits <> rhs`
pub trait EncodeIncremental: Encode {
    /// Reserves all variables this encoding might need
    fn reserve(&mut self, var_manager: &mut dyn ManageVars);
}

/// Trait for incremental cardinality encodings that allow upper bounding of the
/// form `sum of lits <= ub`
pub trait BoundUpperIncremental: BoundUpper + EncodeIncremental {
    /// Lazily builds the _change in_ 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.
    ///
    /// # Errors
    ///
    /// If the clause collector runs out of memory.
    fn encode_ub_change<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize>;
}

/// Trait for incremental cardinality encodings that allow lower bounding of the
/// form `sum of lits >= lb`
pub trait BoundLowerIncremental: BoundLower + EncodeIncremental {
    /// Lazily builds the _change in_ 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.
    ///
    /// # Errors
    ///
    /// If the clause collector runs out of memory.
    fn encode_lb_change<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize>;
}

/// Trait for incremental cardinality encodings that allow upper and lower bounding
pub trait BoundBothIncremental: BoundUpperIncremental + BoundLowerIncremental + BoundBoth {
    /// Lazily builds the _change in_ 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.
    ///
    /// # Errors
    ///
    /// If the clause collector runs out of memory.
    fn encode_both_change<Col, R>(
        &mut self,
        range: R,
        collector: &mut Col,
        var_manager: &mut dyn ManageVars,
    ) -> Result<(), crate::OutOfMemory>
    where
        Col: CollectClauses,
        R: RangeBounds<usize> + Clone,
    {
        self.encode_ub_change(range.clone(), collector, var_manager)?;
        self.encode_lb_change(range, collector, var_manager)
    }
}

/// 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.
pub fn default_encode_cardinality_constraint<Col: CollectClauses>(
    constr: CardConstraint,
    collector: &mut Col,
    var_manager: &mut dyn ManageVars,
) -> Result<(), crate::OutOfMemory> {
    encode_cardinality_constraint::<DefBothBounding, Col>(constr, collector, var_manager)
}

/// An encoder for any cardinality constraint with an encoding of choice
///
/// # Errors
///
/// If the clause collector runs out of memory.
pub fn encode_cardinality_constraint<CE: BoundBoth + FromIterator<Lit>, Col: CollectClauses>(
    constr: CardConstraint,
    collector: &mut Col,
    var_manager: &mut dyn ManageVars,
) -> Result<(), crate::OutOfMemory> {
    if constr.is_tautology() {
        return Ok(());
    }
    if constr.is_unsat() {
        return collector.add_clause(Clause::new());
    }
    if constr.is_positive_assignment() {
        return collector.extend_clauses(constr.into_lits().into_iter().map(|lit| clause![lit]));
    }
    if constr.is_negative_assignment() {
        return collector.extend_clauses(constr.into_lits().into_iter().map(|lit| clause![!lit]));
    }
    if constr.is_clause() {
        return collector.add_clause(unreachable_err!(constr.into_clause()));
    }
    match CE::encode_constr(constr, collector, var_manager) {
        Ok(()) => Ok(()),
        Err(ConstraintEncodingError::OutOfMemory(err)) => Err(err),
        Err(ConstraintEncodingError::Unsat) => unreachable!(),
    }
}

fn prepare_ub_range<Enc: Encode, R: RangeBounds<usize>>(enc: &Enc, range: R) -> Range<usize> {
    (match range.start_bound() {
        Bound::Included(b) => *b,
        Bound::Excluded(b) => b + 1,
        Bound::Unbounded => 0,
    })..match range.end_bound() {
        Bound::Included(b) => cmp::min(b + 1, enc.n_lits()),
        Bound::Excluded(b) => cmp::min(*b, enc.n_lits()),
        Bound::Unbounded => enc.n_lits(),
    }
}

fn prepare_lb_range<Enc: Encode, R: RangeBounds<usize>>(enc: &Enc, range: R) -> Range<usize> {
    (match range.start_bound() {
        Bound::Included(b) => cmp::max(*b, 1),
        Bound::Excluded(b) => cmp::max(b + 1, 1),
        Bound::Unbounded => 1,
    })..match range.end_bound() {
        Bound::Included(b) => cmp::min(b + 1, enc.n_lits() + 1),
        Bound::Excluded(b) => cmp::min(*b, enc.n_lits() + 1),
        Bound::Unbounded => enc.n_lits() + 1,
    }
}

fn prepare_both_range<Enc: Encode, R: RangeBounds<usize>>(enc: &Enc, range: R) -> Range<usize> {
    (match range.start_bound() {
        Bound::Included(b) => *b,
        Bound::Excluded(b) => b + 1,
        Bound::Unbounded => 1,
    })..match range.end_bound() {
        Bound::Included(b) => cmp::min(b + 1, enc.n_lits() + 1),
        Bound::Excluded(b) => cmp::min(*b, enc.n_lits() + 1),
        Bound::Unbounded => enc.n_lits() + 1,
    }
}