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
102210
fn create_bool_aux(symbols: &mut SymbolTable) -> Expr {
15
102210
    let name = symbols.gensym(&Domain::bool());
16

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

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

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

            
48
252840
    Some(CnfClause::new(new_terms))
49
298596
}
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
32073
pub fn tseytin_and(
56
32073
    exprs: &Vec<Expr>,
57
32073
    clauses: &mut Vec<CnfClause>,
58
32073
    symbols: &mut SymbolTable,
59
32073
) -> Expr {
60
32073
    let new_expr = create_bool_aux(symbols);
61

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

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

            
73
32073
    new_expr
74
32073
}
75

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

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

            
86
21795
    new_expr
87
21795
}
88

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

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

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

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

            
109
34383
    new_expr
110
34383
}
111

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

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

            
138
10425
    new_expr
139
10425
}
140

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

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

            
161
780
    new_expr
162
780
}
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
240
pub fn tseytin_mux(
171
240
    cond: Expr,
172
240
    a: Expr,
173
240
    b: Expr,
174
240
    clauses: &mut Vec<CnfClause>,
175
240
    symbols: &mut SymbolTable,
176
240
) -> Expr {
177
240
    let new_expr = create_bool_aux(symbols);
178

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

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

            
211
240
    new_expr
212
240
}
213

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

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

            
245
2514
    new_expr
246
2514
}
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
59499
fn remove_single_atom(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
259
    // The single atom must not be within another expression
260
59499
    let Expr::Root(_, children) = expr else {
261
54060
        return Err(RuleNotApplicable);
262
    };
263

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

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

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

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

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

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

            
285
3441
    Ok(Reduction::cnf(new_expr, new_clauses, symbols.clone()))
286
59499
}
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
131187
fn apply_tseytin_and_or(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
323
131187
    let exprs = match expr {
324
375
        Expr::And(_, exprs) | Expr::Or(_, exprs) => exprs,
325
130812
        _ => return Err(RuleNotApplicable),
326
    };
327

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

            
332
819
    for x in exprs_list {
333
819
        if !is_literal(x) {
334
60
            return Err(RuleNotApplicable);
335
759
        };
336
    }
337

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

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

            
352
315
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
353
131187
}
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
266373
fn apply_tseytin_not(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
371
266373
    let Expr::Not(_, x) = expr else {
372
266043
        return Err(RuleNotApplicable);
373
    };
374

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

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

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

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

            
388
102
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
389
266373
}
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
131187
fn apply_tseytin_iff_eq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
410
    // Check for iff or eq
411
131187
    let (x, y) = match expr {
412
447
        Expr::Iff(_, x, y) | Expr::Eq(_, x, y) => (x, y),
413
130740
        _ => return Err(RuleNotApplicable),
414
    };
415

            
416
447
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
417
429
        return Err(RuleNotApplicable);
418
18
    };
419

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

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

            
430
18
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
431
131187
}
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
131187
fn apply_tseytin_imply(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
450
131187
    let Expr::Imply(_, x, y) = expr else {
451
131115
        return Err(RuleNotApplicable);
452
    };
453

            
454
72
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
455
18
        return Err(RuleNotApplicable);
456
54
    };
457

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

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

            
469
54
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
470
131187
}
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
131187
fn apply_tseytin_xor_neq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
491
131187
    let Expr::Neq(_, x, y) = expr else {
492
130479
        return Err(RuleNotApplicable);
493
    };
494

            
495
708
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
496
690
        return Err(RuleNotApplicable);
497
18
    };
498

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

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

            
509
18
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
510
131187
}