1
use conjure_cp::essence_expr;
2

            
3
use conjure_cp::ast::Metadata;
4
use conjure_cp::ast::{Atom, CnfClause, Expression as Expr, Literal, Moo};
5
use conjure_cp::rule_engine::{
6
    ApplicationError::RuleNotApplicable, ApplicationResult, Reduction, register_rule,
7
};
8

            
9
use conjure_cp::ast::AbstractLiteral::Matrix;
10
use conjure_cp::ast::{Domain, SymbolTable};
11

            
12
use crate::utils::is_literal;
13

            
14
108810
fn create_bool_aux(symbols: &mut SymbolTable) -> Expr {
15
108810
    let name = symbols.gensym(&Domain::bool());
16

            
17
108810
    symbols.insert(name.clone());
18

            
19
108810
    Expr::Atomic(
20
108810
        Metadata::new(),
21
108810
        Atom::Reference(conjure_cp::ast::Reference::new(name)),
22
108810
    )
23
108810
}
24

            
25
320376
fn create_clause(exprs: Vec<Expr>) -> Option<CnfClause> {
26
320376
    let mut new_terms = vec![];
27
727764
    for expr in exprs {
28
50985
        if let Expr::Atomic(_, Atom::Literal(Literal::Bool(x))) = expr {
29
            // true ~~> entire or is true
30
            // false ~~> remove false from the or
31
50985
            if x {
32
11838
                return None;
33
39147
            }
34
676779
        } else if let Expr::Not(_, ref inner) = expr {
35
365379
            if let Expr::Atomic(_, Atom::Literal(Literal::Bool(x))) = inner.as_ref() {
36
                // check for nested literal
37
50985
                if !x {
38
39147
                    return None;
39
11838
                }
40
314394
            } else {
41
314394
                new_terms.push(expr);
42
314394
            }
43
311400
        } else {
44
311400
            new_terms.push(expr);
45
311400
        }
46
    }
47

            
48
269391
    Some(CnfClause::new(new_terms))
49
320376
}
50

            
51
// TODO: Optimize all logic operators for constants
52
// TODO: If a clause simplifies to false, it should skip the solver and give no solutions
53

            
54
/// Applies the Tseytin and transformation to series of variables, returns the new expression, symbol table and clauses
55
36063
pub fn tseytin_and(
56
36063
    exprs: &Vec<Expr>,
57
36063
    clauses: &mut Vec<CnfClause>,
58
36063
    symbols: &mut SymbolTable,
59
36063
) -> Expr {
60
36063
    let new_expr = create_bool_aux(symbols);
61

            
62
36063
    let mut full_conj: Vec<Expr> = vec![new_expr.clone()];
63

            
64
72126
    for x in exprs {
65
72126
        clauses.extend(create_clause(vec![
66
72126
            Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
67
72126
            x.clone(),
68
72126
        ]));
69
72126
        full_conj.push(Expr::Not(Metadata::new(), Moo::new(x.clone())));
70
72126
    }
71
36063
    clauses.extend(create_clause(full_conj));
72

            
73
36063
    new_expr
74
36063
}
75

            
76
/// Applies the Tseytin not transformation to a variable, returns the new expression, symbol table and clauses
77
22839
pub fn tseytin_not(x: Expr, clauses: &mut Vec<CnfClause>, symbols: &mut SymbolTable) -> Expr {
78
22839
    let new_expr = create_bool_aux(symbols);
79

            
80
22839
    clauses.extend(create_clause(vec![
81
22839
        Expr::Not(Metadata::new(), Moo::new(x.clone())),
82
22839
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
83
    ]));
84
22839
    clauses.extend(create_clause(vec![x, new_expr.clone()]));
85

            
86
22839
    new_expr
87
22839
}
88

            
89
/// Applies the Tseytin or transformation to series of variables, returns the new expression, symbol table and clauses
90
32817
pub fn tseytin_or(
91
32817
    exprs: &Vec<Expr>,
92
32817
    clauses: &mut Vec<CnfClause>,
93
32817
    symbols: &mut SymbolTable,
94
32817
) -> Expr {
95
32817
    let new_expr = create_bool_aux(symbols);
96

            
97
32817
    let mut full_conj: Vec<Expr> = vec![Expr::Not(Metadata::new(), Moo::new(new_expr.clone()))];
98

            
99
65778
    for x in exprs {
100
65778
        clauses.extend(create_clause(vec![
101
65778
            Expr::Not(Metadata::new(), Moo::new(x.clone())),
102
65778
            new_expr.clone(),
103
65778
        ]));
104
65778
        full_conj.push(x.clone());
105
65778
    }
106

            
107
32817
    clauses.extend(create_clause(full_conj));
108

            
109
32817
    new_expr
110
32817
}
111

            
112
/// Applies the Tseytin iff transformation to two variables, returns the new expression, symbol table and clauses
113
12870
pub fn tseytin_iff(
114
12870
    x: Expr,
115
12870
    y: Expr,
116
12870
    clauses: &mut Vec<CnfClause>,
117
12870
    symbols: &mut SymbolTable,
118
12870
) -> Expr {
119
12870
    let new_expr = create_bool_aux(symbols);
120

            
121
12870
    clauses.extend(create_clause(vec![
122
12870
        Expr::Not(Metadata::new(), Moo::new(x.clone())),
123
12870
        Expr::Not(Metadata::new(), Moo::new(y.clone())),
124
12870
        new_expr.clone(),
125
    ]));
126
12870
    clauses.extend(create_clause(vec![x.clone(), y.clone(), new_expr.clone()]));
127
12870
    clauses.extend(create_clause(vec![
128
12870
        x.clone(),
129
12870
        Expr::Not(Metadata::new(), Moo::new(y.clone())),
130
12870
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
131
    ]));
132
12870
    clauses.extend(create_clause(vec![
133
12870
        Expr::Not(Metadata::new(), Moo::new(x)),
134
12870
        y,
135
12870
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
136
    ]));
137

            
138
12870
    new_expr
139
12870
}
140

            
141
/// Applies the Tseytin imply transformation to two variables, returns the new expression, symbol table and clauses
142
1170
pub fn tseytin_imply(
143
1170
    x: Expr,
144
1170
    y: Expr,
145
1170
    clauses: &mut Vec<CnfClause>,
146
1170
    symbols: &mut SymbolTable,
147
1170
) -> Expr {
148
1170
    let new_expr = create_bool_aux(symbols);
149

            
150
1170
    clauses.extend(create_clause(vec![
151
1170
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
152
1170
        Expr::Not(Metadata::new(), Moo::new(x.clone())),
153
1170
        y.clone(),
154
    ]));
155
1170
    clauses.extend(create_clause(vec![new_expr.clone(), x]));
156
1170
    clauses.extend(create_clause(vec![
157
1170
        new_expr.clone(),
158
1170
        Expr::Not(Metadata::new(), Moo::new(y)),
159
    ]));
160

            
161
1170
    new_expr
162
1170
}
163

            
164
/// Applies the Tseytin multiplex transformation
165
/// cond ? b : a
166
///
167
/// cond = 1 => b
168
/// cond = 0 => a
169
#[allow(dead_code)]
170
360
pub fn tseytin_mux(
171
360
    cond: Expr,
172
360
    a: Expr,
173
360
    b: Expr,
174
360
    clauses: &mut Vec<CnfClause>,
175
360
    symbols: &mut SymbolTable,
176
360
) -> Expr {
177
360
    let new_expr = create_bool_aux(symbols);
178

            
179
360
    clauses.extend(create_clause(vec![
180
360
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
181
360
        cond.clone(),
182
360
        a.clone(),
183
    ]));
184
360
    clauses.extend(create_clause(vec![
185
360
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
186
360
        Expr::Not(Metadata::new(), Moo::new(cond.clone())),
187
360
        b.clone(),
188
    ]));
189
360
    clauses.extend(create_clause(vec![
190
360
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
191
360
        a.clone(),
192
360
        b.clone(),
193
    ]));
194

            
195
360
    clauses.extend(create_clause(vec![
196
360
        new_expr.clone(),
197
360
        cond.clone(),
198
360
        Expr::Not(Metadata::new(), Moo::new(a.clone())),
199
    ]));
200
360
    clauses.extend(create_clause(vec![
201
360
        new_expr.clone(),
202
360
        Expr::Not(Metadata::new(), Moo::new(cond)),
203
360
        Expr::Not(Metadata::new(), Moo::new(b.clone())),
204
    ]));
205
360
    clauses.extend(create_clause(vec![
206
360
        new_expr.clone(),
207
360
        Expr::Not(Metadata::new(), Moo::new(a)),
208
360
        Expr::Not(Metadata::new(), Moo::new(b)),
209
    ]));
210

            
211
360
    new_expr
212
360
}
213

            
214
/// Applies the Tseytin xor transformation to two variables, returns the new expression, symbol table and clauses
215
#[allow(dead_code)]
216
2691
pub fn tseytin_xor(
217
2691
    x: Expr,
218
2691
    y: Expr,
219
2691
    clauses: &mut Vec<CnfClause>,
220
2691
    symbols: &mut SymbolTable,
221
2691
) -> Expr {
222
2691
    let new_expr = create_bool_aux(symbols);
223

            
224
2691
    clauses.extend(create_clause(vec![
225
2691
        Expr::Not(Metadata::new(), Moo::new(x.clone())),
226
2691
        Expr::Not(Metadata::new(), Moo::new(y.clone())),
227
2691
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
228
    ]));
229
2691
    clauses.extend(create_clause(vec![
230
2691
        x.clone(),
231
2691
        y.clone(),
232
2691
        Expr::Not(Metadata::new(), Moo::new(new_expr.clone())),
233
    ]));
234
2691
    clauses.extend(create_clause(vec![
235
2691
        x.clone(),
236
2691
        Expr::Not(Metadata::new(), Moo::new(y.clone())),
237
2691
        new_expr.clone(),
238
    ]));
239
2691
    clauses.extend(create_clause(vec![
240
2691
        Expr::Not(Metadata::new(), Moo::new(x)),
241
2691
        y,
242
2691
        new_expr.clone(),
243
    ]));
244

            
245
2691
    new_expr
246
2691
}
247

            
248
/// Converts a single boolean atom to a clause
249
///
250
/// ```text
251
///  a
252
///  ~~>
253
///  
254
///  new clauses:
255
///  clause(a)
256
/// ```
257
#[register_rule(("SAT", 8400))]
258
84201
fn remove_single_atom(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
259
    // The single atom must not be within another expression
260
84201
    let Expr::Root(_, children) = expr else {
261
77208
        return Err(RuleNotApplicable);
262
    };
263

            
264
    // Find the position of the first reference atom with boolean domain
265
6993
    let Some(pos) = children.iter().position(
266
4224
        |e| matches!(e, Expr::Atomic(_, Atom::Reference(x)) if x.domain().is_some_and(|d| d.is_bool())),
267
    ) else {
268
2769
        return Err(RuleNotApplicable);
269
    };
270

            
271
    // Clone the children since expr is borrowed immutably
272
4224
    let mut new_children = children.clone();
273

            
274
4224
    let removed = new_children.remove(pos);
275

            
276
4224
    let new_clauses = vec![CnfClause::new(vec![removed])];
277

            
278
    // If now empty, replace with `true`
279
4224
    if new_children.is_empty() {
280
780
        new_children.push(essence_expr!(true));
281
3444
    }
282

            
283
4224
    let new_expr = Expr::Root(Metadata::new(), new_children);
284

            
285
4224
    Ok(Reduction::cnf(new_expr, new_clauses, symbols.clone()))
286
84201
}
287

            
288
/// Converts an and/or expression to an aux variable, using the tseytin transformation
289
///
290
/// ```text
291
///  and(a, b, c, ...)
292
///  ~~>
293
///  __0
294
///
295
///  new variables:
296
///  find __0: bool
297
///
298
///  new clauses:
299
///  clause(__0, not(a), not(b), not(c), ...)
300
///  clause(not(__0), a)
301
///  clause(not(__0), b)
302
///  clause(not(__0), c)
303
///  ...
304
///
305
///  ---------------------------------------
306
///
307
///  clause(a, b, c, ...)
308
///  ~~>
309
///  __0
310
///
311
///  new variables:
312
///  find __0: bool
313
///
314
///  new clauses:
315
///  clause(not(__0), a, b, c, ...)
316
///  clause(__0, not(a))
317
///  clause(__0, not(b))
318
///  clause(__0, not(c))
319
///  ...
320
/// ```
321
#[register_rule(("SAT", 8500))]
322
160374
fn apply_tseytin_and_or(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
323
160374
    let exprs = match expr {
324
657
        Expr::And(_, exprs) | Expr::Or(_, exprs) => exprs,
325
159717
        _ => return Err(RuleNotApplicable),
326
    };
327

            
328
657
    let Expr::AbstractLiteral(_, Matrix(exprs_list, _)) = exprs.as_ref() else {
329
        return Err(RuleNotApplicable);
330
    };
331

            
332
1377
    for x in exprs_list {
333
1377
        if !is_literal(x) {
334
162
            return Err(RuleNotApplicable);
335
1215
        };
336
    }
337

            
338
    let new_expr;
339
495
    let mut new_clauses = vec![];
340
495
    let mut new_symbols = symbols.clone();
341

            
342
495
    match expr {
343
81
        Expr::And(_, _) => {
344
81
            new_expr = tseytin_and(exprs_list, &mut new_clauses, &mut new_symbols);
345
81
        }
346
414
        Expr::Or(_, _) => {
347
414
            new_expr = tseytin_or(exprs_list, &mut new_clauses, &mut new_symbols);
348
414
        }
349
        _ => return Err(RuleNotApplicable),
350
    };
351

            
352
495
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
353
160374
}
354

            
355
/// Converts a not expression to an aux variable, using the tseytin transformation
356
///
357
/// ```text
358
///  not(a)
359
///  ~~>
360
///  __0
361
///
362
///  new variables:
363
///  find __0: bool
364
///
365
///  new clauses:
366
///  clause(__0, a)
367
///  clause(not(__0), not(a))
368
/// ```
369
#[register_rule(("SAT", 9005))]
370
315654
fn apply_tseytin_not(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
371
315654
    let Expr::Not(_, x) = expr else {
372
315519
        return Err(RuleNotApplicable);
373
    };
374

            
375
135
    let Expr::Atomic(_, _) = x.as_ref() else {
376
        return Err(RuleNotApplicable);
377
    };
378

            
379
135
    if !is_literal(x.as_ref()) {
380
        return Err(RuleNotApplicable);
381
135
    };
382

            
383
135
    let mut new_clauses = vec![];
384
135
    let mut new_symbols = symbols.clone();
385

            
386
135
    let new_expr = tseytin_not(x.as_ref().clone(), &mut new_clauses, &mut new_symbols);
387

            
388
135
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
389
315654
}
390

            
391
/// Converts an iff/boolean equality expression to an aux variable, using the tseytin transformation
392
///
393
/// ```text
394
/// find a, b : bool
395
///  a <-> b OR a = b
396
///  ~~>
397
///  __0
398
///
399
///  new clauses:
400
///  find __0: bool
401
///
402
///  new clauses:
403
///  clause(not(a), not(b), __0)
404
///  clause(a, b, __0)
405
///  clause(a, not(b), not(__0))
406
///  clause(not(a), b, not(__0))
407
/// ```
408
#[register_rule(("SAT", 8500))]
409
160374
fn apply_tseytin_iff_eq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
410
    // Check for iff or eq
411
160374
    let (x, y) = match expr {
412
135
        Expr::Iff(_, x, y) | Expr::Eq(_, x, y) => (x, y),
413
160239
        _ => return Err(RuleNotApplicable),
414
    };
415

            
416
135
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
417
108
        return Err(RuleNotApplicable);
418
27
    };
419

            
420
27
    let mut new_clauses = vec![];
421
27
    let mut new_symbols = symbols.clone();
422

            
423
27
    let new_expr = tseytin_iff(
424
27
        x.as_ref().clone(),
425
27
        y.as_ref().clone(),
426
27
        &mut new_clauses,
427
27
        &mut new_symbols,
428
    );
429

            
430
27
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
431
160374
}
432

            
433
/// Converts an implication expression to an aux variable, using the tseytin transformation
434
///
435
/// ```text
436
///  a -> b
437
///  ~~>
438
///  __0
439
///
440
///  new variables:
441
///  find __0: bool
442
///
443
///  new clauses:
444
///  clause(not(__0), not(a), b)
445
///  clause(__0, a)
446
///  clause(__0, not(b))
447
/// ```
448
#[register_rule(("SAT", 8500))]
449
160374
fn apply_tseytin_imply(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
450
160374
    let Expr::Imply(_, x, y) = expr else {
451
160266
        return Err(RuleNotApplicable);
452
    };
453

            
454
108
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
455
27
        return Err(RuleNotApplicable);
456
81
    };
457

            
458
    let new_expr;
459
81
    let mut new_clauses = vec![];
460
81
    let mut new_symbols = symbols.clone();
461

            
462
81
    new_expr = tseytin_imply(
463
81
        x.as_ref().clone(),
464
81
        y.as_ref().clone(),
465
81
        &mut new_clauses,
466
81
        &mut new_symbols,
467
    );
468

            
469
81
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
470
160374
}
471

            
472
/// Converts a boolean != expression to an aux variable, using the tseytin transformation
473
///
474
/// ```text
475
///  find a, b : bool
476
///  a != b
477
///  ~~>
478
///  __0
479
///
480
///  new clauses:
481
///  find __0: bool
482
///
483
///  new clauses:
484
///  clause(not(a), not(b), not(__0))
485
///  clause(a, b, not(__0))
486
///  clause(a, not(b), __0)
487
///  clause(not(a), b, __0)
488
/// ```
489
#[register_rule(("SAT", 8500))]
490
160374
fn apply_tseytin_xor_neq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
491
160374
    let Expr::Neq(_, x, y) = expr else {
492
159456
        return Err(RuleNotApplicable);
493
    };
494

            
495
918
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
496
891
        return Err(RuleNotApplicable);
497
27
    };
498

            
499
27
    let mut new_clauses = vec![];
500
27
    let mut new_symbols = symbols.clone();
501

            
502
27
    let new_expr = tseytin_xor(
503
27
        x.as_ref().clone(),
504
27
        y.as_ref().clone(),
505
27
        &mut new_clauses,
506
27
        &mut new_symbols,
507
    );
508

            
509
27
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
510
160374
}