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

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

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

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

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

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

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

            
73
12039
    new_expr
74
12039
}
75

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

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

            
86
7626
    new_expr
87
7626
}
88

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

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

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

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

            
109
11103
    new_expr
110
11103
}
111

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

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

            
138
4266
    new_expr
139
4266
}
140

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

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

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

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

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

            
211
120
    new_expr
212
120
}
213

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

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

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

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

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

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

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

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

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

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

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

            
332
459
    for x in exprs_list {
333
459
        if !is_literal(x) {
334
54
            return Err(RuleNotApplicable);
335
405
        };
336
    }
337

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

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

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

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

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

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

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

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

            
416
45
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
417
36
        return Err(RuleNotApplicable);
418
9
    };
419

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

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

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

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

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

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

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

            
495
306
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
496
297
        return Err(RuleNotApplicable);
497
9
    };
498

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

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

            
509
9
    Ok(Reduction::cnf(new_expr, new_clauses, new_symbols))
510
53457
}