logicng 0.1.0-alpha.3

A Library for Creating, Manipulating, and Solving Boolean Formulas
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use crate::datastructures::{Assignment, Model};
use crate::formulas::{EncodedFormula, Formula, FormulaFactory, Variable};
use crate::solver::maxsat_config::{MaxSatConfig, PbEncoding};
use crate::solver::maxsat_ffi::{MaxSatError, OpenWboSolver};
use std::collections::BTreeSet;
use std::fmt::Debug;

/// Algorithms support for solving the MaxSAT problem with a [`MaxSatSolver`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Algorithm {
    /// Weighted Boolean Optimization
    Wbo,
    /// OLL
    Oll,
    /// Linear Sat-Unsat
    LinearSu,
    /// Partial Seminal-core guided algorithm
    PartMsu3,
    /// Seminal-core guided algorithm
    Msu3,
}

impl Algorithm {
    /// Returns `true` if this algorithm supports with the given configuration
    /// the weighted MaxSAT problem. Otherwise, it returns `false`.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// let config = MaxSatConfig::default();
    ///
    /// assert!(Algorithm::Wbo.weighted(&config));
    /// assert!(!Algorithm::Msu3.weighted(&config));
    /// ```
    pub fn weighted(&self, config: &MaxSatConfig) -> bool {
        match self {
            Self::Wbo | Self::Oll => true,
            Self::LinearSu => config.pb_encoding != PbEncoding::Adder,
            Self::PartMsu3 | Self::Msu3 => false,
        }
    }
}

/// Stores different metrics measured during the execution of the MaxSAT
/// algorithm.
#[derive(Debug, Clone, PartialEq)]
pub struct MaxSatStats {
    /// Upper bound cost.
    pub ub_cost: Option<u64>,
    /// Number of satisfiable calls.
    pub nb_satisfied: u64,
    /// Number of cores.
    pub nb_cores: u64,
    /// Average of the sizes of cores.
    pub avg_core_size: f64,
    /// Number of symmetry clauses.
    pub nb_sym_clauses: u64,
}

/// Result returned by an MaxSAT algorithm.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MaxSatResult {
    /// The hard clauses on the solver are already unsatisfiable, optimization
    /// could not be performed.
    Unsatisfiable,
    /// An optimal solution was found + the result as value.
    Optimum(u64),
    /// If no search has been executed yet or the search was aborted by the
    /// algorithm and yielded no result.
    Undef,
}

const SEL_PREFIX: &str = "@SEL_SOFT_";

/// A solver for the MaxSAT problem.
///
/// [`MaxSatSolver`] does not implement the algorithms itself, but makes use of
/// [OpenWBO](http://sat.inesc-id.pt/open-wbo/) as an library. `OpenWBO` allows
/// you to use different algorithms, depending on your MaxSAT flavor and your
/// specific use case.
///
/// For more information about the general MaxSAT problem read the documentation of the [`maxsat module`](crate::solver::maxsat)
///
/// # Usage
///
/// You can create a new instance by using
/// [`MaxSatSolver::new`](crate::solver::maxsat::MaxSatSolver::new) or
/// [`MaxSatSolver::from_config`](crate::solver::maxsat::MaxSatSolver::from_config).
/// Both constructors take an [`Algorithm`](crate::solver::maxsat::Algorithm) as
/// argument, which will be used by the solver. Additionally, `from_config`
/// takes a `MaxSatConfig`, which allows you to configure certain details
/// (encodings, strategies) of the algorithm. Solver created by `new` use a
/// default configuration. Once you have created a solver, you can no longer
/// modify the algorithm or the configuration.
///
/// ```
/// # use logicng::solver::maxsat::*;
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let solver1 = MaxSatSolver::new(Algorithm::Oll)?; //Solver with default configuration
///
/// let config = MaxSatConfig::default()
///                 .cardinal(CardinalEncoding::MTotalizer)
///                 .pb(PbEncoding::Gte);
/// let solver2 = MaxSatSolver::from_config(Algorithm::LinearSu, config)?; //With custom configuration
/// # Ok(())
/// # }
/// ```
///
/// Hard formulas are added with the method
/// [`MaxSatSolver::add_hard_formula`](crate::solver::maxsat::MaxSatSolver::add_hard_formula),
/// soft clauses are added with
/// [`MaxSatSolver::add_soft_formula`](crate::solver::maxsat::MaxSatSolver::add_soft_formula),
/// which takes a positive weight. For an unweighted clause, use the weight 1.
/// After you added all formulas, you can use the method `MaxSatSolver::solve`
/// to solve the problem.
pub struct MaxSatSolver {
    algorithm: Algorithm,
    config: MaxSatConfig,
    solver: OpenWboSolver,
    selector_variables: BTreeSet<Variable>,
}

impl MaxSatSolver {
    /// Creating a new [`MaxSatSolver`] instance with the given algorithm and the default configuration.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(algorithm: Algorithm) -> Result<Self, MaxSatError> {
        Self::from_config(algorithm, MaxSatConfig::default())
    }

    /// Creating a new [`MaxSatSolver`] instance with given algorithm and configuration.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;   
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let config = MaxSatConfig::default();
    ///
    /// let solver = MaxSatSolver::from_config(Algorithm::Oll, config);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_config(algorithm: Algorithm, config: MaxSatConfig) -> Result<Self, MaxSatError> {
        let solver = OpenWboSolver::new(&algorithm, &config)?;

        Ok(Self { algorithm, config, solver, selector_variables: BTreeSet::new() })
    }

    /// Returns `true` if this solver is capable of solving the weighted MaxSAT
    /// problem.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let solver1 = MaxSatSolver::new(Algorithm::Oll)?;
    /// let solver2 = MaxSatSolver::new(Algorithm::Msu3)?;
    ///
    /// assert!(solver1.is_weighted());
    /// assert!(!solver2.is_weighted());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_weighted(&self) -> bool {
        self.algorithm.weighted(&self.config)
    }

    /// Resets the solver.
    ///
    /// This will keep the algorithm and configuration, but will clear all
    /// results and formulas on the solver.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{FormulaFactory, ToFormula};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    ///
    /// solver.add_hard_formula("A".to_formula(&f), &f)?;
    /// solver.add_soft_formula(1, "~A".to_formula(&f), &f)?;
    /// let res = solver.solve()?;
    /// assert_eq!(res, MaxSatResult::Optimum(1));
    ///
    /// solver.reset();
    ///
    /// solver.add_hard_formula("A".to_formula(&f), &f)?;
    /// let res = solver.solve()?;
    /// assert_eq!(res, MaxSatResult::Optimum(0));
    /// # Ok(())
    /// # }
    /// ```
    pub fn reset(&mut self) {
        // Algorithm and Config can not be changed. Therefore, we can expect that we can create this solver,
        // because otherwise it would have failed in the constructor.
        self.solver = OpenWboSolver::new(&self.algorithm, &self.config).expect("Failed to reset the MaxSAT solver!");
        self.selector_variables.clear();
    }

    /// Adds a hard formula to the solver.
    ///
    /// Every result of a MaxSAT problem must fulfill all hard formulas on the solver.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{FormulaFactory, ToFormula};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    ///
    /// solver.add_hard_formula("A".to_formula(&f), &f)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_hard_formula(&mut self, formula: EncodedFormula, f: &FormulaFactory) -> Result<(), MaxSatError> {
        self.add_cnf(None, f.cnf_of(formula), f)
    }

    /// Adds a soft formula to the solver.
    ///
    /// A soft formula is associated with an weight. The MaxSAT solver minimizes
    /// the sum of weights of unsatisfied soft formula. If an algorithm does not
    /// support the weighted MaxSAT problem, the weight must be equals to 1.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{FormulaFactory, ToFormula};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    ///
    /// solver.add_soft_formula(1, "A".to_formula(&f), &f)?;
    /// solver.add_soft_formula(2, "~A".to_formula(&f), &f)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Adding a weighted formula to an non-weighted algorithm, will return a
    /// [`MaxSatError::IllegalWeightedClause`](`MaxSatError`) error:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{FormulaFactory, ToFormula};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Msu3)?;
    /// assert!(!solver.is_weighted());
    ///
    /// let res = solver.add_soft_formula(3, "A".to_formula(&f), &f);
    /// assert_eq!(res, Err(MaxSatError::IllegalWeightedClause));
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_soft_formula(&mut self, weight: u64, formula: EncodedFormula, f: &FormulaFactory) -> Result<(), MaxSatError> {
        if (formula.is_or() || formula.is_literal()) && formula.is_cnf(f) {
            self.add_clause(Some(weight), formula, f)
        } else {
            let sel_var_name = format!("{SEL_PREFIX}{}", self.selector_variables.len());
            let sel_var = f.var(&sel_var_name);
            self.selector_variables.insert(sel_var);
            let f1 = f.or(&[sel_var.negate().into(), formula]);
            let neg_f = f.negate(formula);
            let f2 = f.or(&[neg_f, sel_var.into()]);
            self.add_hard_formula(f1, f)?;
            self.add_hard_formula(f2, f)?;
            self.add_clause(Some(weight), sel_var.into(), f)
        }
    }

    /// Solves the MaxSAT problem on this solver and returns the result.
    ///
    /// The result of the search is cached. Every additional call to `solve`
    /// will return that cached value. Furthermore, you can also use [`MaxSatSolver::status`]
    /// to get the cached value once there is one.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{ToFormula, FormulaFactory};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// solver.add_hard_formula("A & B & (C | D)".to_formula(&f), &f)?;
    /// solver.add_soft_formula(2, "A => ~B".to_formula(&f), &f)?;
    /// solver.add_soft_formula(4, "~C".to_formula(&f), &f)?;
    /// solver.add_soft_formula(8, "~D".to_formula(&f), &f)?;
    ///
    /// let result = solver.solve()?;
    /// assert_eq!(result, MaxSatResult::Optimum(6));
    /// # Ok(())
    /// # }
    /// ```
    pub fn solve(&mut self) -> Result<MaxSatResult, MaxSatError> {
        let status = self.solver.status();
        if status == Ok(MaxSatResult::Undef) {
            self.solver.search()
        } else {
            status
        }
    }

    /// Returns the result of the last search.
    ///
    /// If there has not been a search yet, it will return
    /// [`MaxSatResult::Undef`](`MaxSatResult`).
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{ToFormula, FormulaFactory};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// solver.add_hard_formula("A & B & (C | D)".to_formula(&f), &f)?;
    /// solver.add_soft_formula(2, "A => ~B".to_formula(&f), &f)?;
    /// solver.add_soft_formula(4, "~C".to_formula(&f), &f)?;
    /// solver.add_soft_formula(8, "~D".to_formula(&f), &f)?;
    ///
    /// assert_eq!(solver.solve()?, MaxSatResult::Optimum(6));
    /// assert_eq!(solver.status()?, MaxSatResult::Optimum(6));
    /// # Ok(())
    /// # }
    /// ```
    pub fn status(&self) -> Result<MaxSatResult, MaxSatError> {
        self.solver.status()
    }

    /// Returns a model (as [`Model`]) which yields the optimal result, if there is one.
    ///
    /// If the search has not been executed yet or the result is not an optimum,
    /// this function returns a
    /// [`MaxSatError::IllegalModelRequest`](`MaxSatError`) error.
    ///
    /// If you need an [`Assignment`] you can use [`MaxSatSolver::assignment`].
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{ToFormula, FormulaFactory};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// solver.add_hard_formula("A & B & (C | D)".to_formula(&f), &f)?;
    /// solver.add_soft_formula(2, "A => ~B".to_formula(&f), &f)?;
    /// solver.add_soft_formula(4, "~C".to_formula(&f), &f)?;
    /// solver.add_soft_formula(8, "~D".to_formula(&f), &f)?;
    ///
    /// if let MaxSatResult::Optimum(_) = solver.solve()? {
    ///     let model = solver.model()?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn model(&mut self) -> Result<Model, MaxSatError> {
        self.solver.model(&self.selector_variables)
    }

    /// Returns a model (as [`Assignment`]) which yields the optimal result, if
    /// there is one.
    ///
    /// If the search has not been executed yet or the result is not an optimum,
    /// this function returns a
    /// [`MaxSatError::IllegalModelRequest`](`MaxSatError`) error.
    ///
    /// If you need a [`Model`] you can use [`MaxSatSolver::model`].
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use logicng::formulas::{ToFormula, FormulaFactory};
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let f = FormulaFactory::new();
    /// let mut solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// solver.add_hard_formula("A & B & (C | D)".to_formula(&f), &f)?;
    /// solver.add_soft_formula(2, "A => ~B".to_formula(&f), &f)?;
    /// solver.add_soft_formula(4, "~C".to_formula(&f), &f)?;
    /// solver.add_soft_formula(8, "~D".to_formula(&f), &f)?;
    ///
    /// if let MaxSatResult::Optimum(_) = solver.solve()? {
    ///     let model = solver.assignment()?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn assignment(&mut self) -> Result<Assignment, MaxSatError> {
        self.solver.assignment(&self.selector_variables)
    }

    /// Returns the algorithm used by this solver.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// assert_eq!(solver.algorithm(), Algorithm::Oll);
    /// # Ok(())
    /// # }
    pub fn algorithm(&self) -> Algorithm {
        self.algorithm.clone()
    }

    /// Returns stats measured during the search.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```
    /// # use logicng::solver::maxsat::*;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let solver = MaxSatSolver::new(Algorithm::Oll)?;
    /// // ...
    /// // solver.search()?;
    /// // ...
    /// solver.stats();
    /// # Ok(())
    /// # }
    pub fn stats(&self) -> MaxSatStats {
        self.solver.stats()
    }

    fn add_cnf(&mut self, weight: Option<u64>, formula: EncodedFormula, f: &FormulaFactory) -> Result<(), MaxSatError> {
        match formula.unpack(f) {
            Formula::True => Ok(()),
            Formula::False | Formula::Lit(_) | Formula::Or(_) => self.add_clause(weight, formula, f),
            Formula::And(ops) => {
                for op in ops {
                    self.add_clause(weight, op, f)?;
                }
                Ok(())
            }
            _ => panic!("Formula must be in cnf form!"),
        }
    }

    fn add_clause(&mut self, weight: Option<u64>, formula: EncodedFormula, f: &FormulaFactory) -> Result<(), MaxSatError> {
        match weight {
            Some(w) => self.solver.add_soft_clause(w, &formula, f),
            None => self.solver.add_hard_clause(&formula, f),
        }
    }
}