1
use conjure_cp::ast::{Atom, Expression as Expr, Literal};
2
use conjure_cp::ast::{SATIntEncoding, SymbolTable};
3
use conjure_cp::rule_engine::ApplicationError;
4
use conjure_cp::rule_engine::{
5
    ApplicationError::RuleNotApplicable, ApplicationResult, Reduction, register_rule,
6
};
7

            
8
use conjure_cp::ast::Metadata;
9
use conjure_cp::ast::Moo;
10
use conjure_cp::into_matrix_expr;
11

            
12
use super::boolean::{tseytin_and, tseytin_iff, tseytin_not, tseytin_or, tseytin_xor};
13

            
14
use conjure_cp::ast::CnfClause;
15
/// Converts an integer literal to SATInt form
16
///
17
/// ```text
18
///  3
19
///  ~~>
20
///  SATInt([true;int(1..), (3, 3)])
21
///
22
/// ```
23
#[register_rule(("SAT_Direct", 9500))]
24
419196
fn literal_sat_direct_int(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
25
1410
    let value = {
26
13266
        if let Expr::Atomic(_, Atom::Literal(Literal::Int(value))) = expr {
27
1410
            *value
28
        } else {
29
417786
            return Err(RuleNotApplicable);
30
        }
31
    };
32

            
33
1410
    Ok(Reduction::pure(Expr::SATInt(
34
1410
        Metadata::new(),
35
1410
        SATIntEncoding::Direct,
36
1410
        Moo::new(into_matrix_expr!(vec![Expr::Atomic(
37
1410
            Metadata::new(),
38
1410
            Atom::Literal(Literal::Bool(true)),
39
1410
        )])),
40
1410
        (value, value),
41
1410
    )))
42
419196
}
43

            
44
/// This function confirms that all of the input expressions are direct SATInts, and returns vectors for each input of their bits
45
/// This function also normalizes direct SATInt operands to a common value range by zero-padding.
46
20202
pub fn validate_direct_int_operands(
47
20202
    exprs: Vec<Expr>,
48
20202
) -> Result<(Vec<Vec<Expr>>, i32, i32), ApplicationError> {
49
    // TODO: In the future it may be possible to optimize operations between integers with different bit sizes
50
    // Collect inner bit vectors from each SATInt
51

            
52
    // Iterate over all inputs
53
    // Check they are direct and calulate a lower and upper bound
54
20202
    let mut global_min: i32 = i32::MAX;
55
20202
    let mut global_max: i32 = i32::MIN;
56

            
57
22866
    for operand in &exprs {
58
19842
        let Expr::SATInt(_, SATIntEncoding::Direct, _, (local_min, local_max)) = operand else {
59
18390
            return Err(RuleNotApplicable);
60
        };
61
4476
        global_min = global_min.min(*local_min);
62
4476
        global_max = global_max.max(*local_max);
63
    }
64

            
65
    // build out by iterating over each operand and expanding it to match the new bounds
66

            
67
1812
    let out: Vec<Vec<Expr>> = exprs
68
1812
        .into_iter()
69
3564
        .map(|expr| {
70
3564
            let Expr::SATInt(_, SATIntEncoding::Direct, inner, (local_min, local_max)) = expr
71
            else {
72
                return Err(RuleNotApplicable);
73
            };
74

            
75
3564
            let Some(v) = inner.as_ref().clone().unwrap_list() else {
76
                return Err(RuleNotApplicable);
77
            };
78

            
79
            // calulcate how many zeroes to prepend/append
80
3564
            let prefix_len = (local_min - global_min) as usize;
81
3564
            let postfix_len = (global_max - local_max) as usize;
82

            
83
3564
            let mut bits = Vec::with_capacity(v.len() + prefix_len + postfix_len);
84

            
85
            // add 0s to start
86
3564
            bits.extend(std::iter::repeat_n(
87
3564
                Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false))),
88
3564
                prefix_len,
89
            ));
90

            
91
3564
            bits.extend(v);
92

            
93
            // add 0s to end
94
3564
            bits.extend(std::iter::repeat_n(
95
3564
                Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false))),
96
3564
                postfix_len,
97
            ));
98

            
99
3564
            Ok(bits)
100
3564
        })
101
1812
        .collect::<Result<_, _>>()?;
102

            
103
1812
    Ok((out, global_min, global_max))
104
20202
}
105

            
106
/// Converts a = expression between two direct SATInts to a boolean expression in cnf
107
///
108
/// ```text
109
/// SATInt(a) = SATInt(b) ~> Bool
110
/// ```
111
/// NOTE: This rule reduces to AND_i (a[i] ≡ b[i]) and does not enforce one-hotness.
112
#[register_rule(("SAT_Direct", 9100))]
113
135000
fn eq_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
114
    // TODO: this could be optimized by just going over the sections of both vectors where the ranges intersect
115
    // this does require enforcing structure separately
116
135000
    let Expr::Eq(_, lhs, rhs) = expr else {
117
133326
        return Err(RuleNotApplicable);
118
    };
119

            
120
318
    let (binding, _, _) =
121
1674
        validate_direct_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
122
318
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
123
        return Err(RuleNotApplicable);
124
    };
125

            
126
318
    let bit_count = lhs_bits.len();
127

            
128
318
    let mut output = true.into();
129
318
    let mut new_symbols = symbols.clone();
130
318
    let mut new_clauses = vec![];
131
    let mut comparison;
132

            
133
6612
    for i in 0..bit_count {
134
6612
        comparison = tseytin_iff(
135
6612
            lhs_bits[i].clone(),
136
6612
            rhs_bits[i].clone(),
137
6612
            &mut new_clauses,
138
6612
            &mut new_symbols,
139
6612
        );
140
6612
        output = tseytin_and(
141
6612
            &vec![comparison, output],
142
6612
            &mut new_clauses,
143
6612
            &mut new_symbols,
144
6612
        );
145
6612
    }
146

            
147
318
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
148
135000
}
149

            
150
/// Converts a != expression between two direct SATInts to a boolean expression in cnf
151
///
152
/// ```text
153
/// SATInt(a) != SATInt(b) ~> Bool
154
///
155
/// ```
156
///
157
/// True iff at least one value position differs.
158
#[register_rule(("SAT_Direct", 9100))]
159
135000
fn neq_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
160
135000
    let Expr::Neq(_, lhs, rhs) = expr else {
161
134526
        return Err(RuleNotApplicable);
162
    };
163

            
164
150
    let (binding, _, _) =
165
474
        validate_direct_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
166
150
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
167
        return Err(RuleNotApplicable);
168
    };
169

            
170
150
    let bit_count = lhs_bits.len();
171

            
172
150
    let mut output = false.into();
173
150
    let mut new_symbols = symbols.clone();
174
150
    let mut new_clauses = vec![];
175
    let mut comparison;
176

            
177
1158
    for i in 0..bit_count {
178
1158
        comparison = tseytin_xor(
179
1158
            lhs_bits[i].clone(),
180
1158
            rhs_bits[i].clone(),
181
1158
            &mut new_clauses,
182
1158
            &mut new_symbols,
183
1158
        );
184
1158
        output = tseytin_or(
185
1158
            &vec![comparison, output],
186
1158
            &mut new_clauses,
187
1158
            &mut new_symbols,
188
1158
        );
189
1158
    }
190

            
191
150
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
192
135000
}
193

            
194
/// Converts a </>/<=/>= expression between two direct SATInts to a boolean expression in cnf
195
///
196
/// ```text
197
/// SATInt(a) </>/<=/>= SATInt(b) ~> Bool
198
///
199
/// ```
200
/// Note: < and <= are rewritten by swapping operands to reuse lt logic.
201
#[register_rule(("SAT", 9100))]
202
342342
fn ineq_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
203
342342
    let (lhs, rhs, negate) = match expr {
204
        // A < B -> sat_direct_lt(A, B)
205
249
        Expr::Lt(_, x, y) => (x, y, false),
206
        // A > B -> sat_direct_lt(B, A)
207
333
        Expr::Gt(_, x, y) => (y, x, false),
208
        // A <= B -> NOT (B < A)
209
9492
        Expr::Leq(_, x, y) => (y, x, true),
210
        // A >= B -> NOT (A < B)
211
7908
        Expr::Geq(_, x, y) => (x, y, true),
212
324360
        _ => return Err(RuleNotApplicable),
213
    };
214

            
215
1284
    let (binding, _, _) =
216
17982
        validate_direct_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
217
1284
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
218
        return Err(RuleNotApplicable);
219
    };
220

            
221
1284
    let mut new_symbols = symbols.clone();
222
1284
    let mut new_clauses = vec![];
223

            
224
1284
    let mut output = sat_direct_lt(
225
1284
        lhs_bits.clone(),
226
1284
        rhs_bits.clone(),
227
1284
        &mut new_clauses,
228
1284
        &mut new_symbols,
229
    );
230

            
231
1284
    if negate {
232
1236
        output = tseytin_not(output, &mut new_clauses, &mut new_symbols);
233
1236
    }
234

            
235
1284
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
236
342342
}
237

            
238
/// Encodes a < b for one-hot direct integers using prefix OR logic.
239
1284
fn sat_direct_lt(
240
1284
    a: Vec<Expr>,
241
1284
    b: Vec<Expr>,
242
1284
    clauses: &mut Vec<CnfClause>,
243
1284
    symbols: &mut SymbolTable,
244
1284
) -> Expr {
245
1284
    let mut b_or = Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false)));
246
1284
    let mut cum_result = Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false)));
247

            
248
13248
    for (a_i, b_i) in a.iter().zip(b.iter()) {
249
        // b_or is prefix_or of b up to index i: B_i = b_0 | ... | b_i
250
13248
        b_or = tseytin_or(&vec![b_or, b_i.clone()], clauses, symbols);
251
13248

            
252
        // a < b if there exists i such that a=i and b > i.
253
        // b > i is equivalent to NOT(B_i) assuming one-hotness.
254
13248
        let not_b_or = tseytin_not(b_or.clone(), clauses, symbols);
255
13248
        let a_i_and_not_b_i = tseytin_and(&vec![a_i.clone(), not_b_or], clauses, symbols);
256
13248

            
257
13248
        cum_result = tseytin_or(&vec![cum_result, a_i_and_not_b_i], clauses, symbols);
258
13248
    }
259

            
260
1284
    cum_result
261
1284
}
262

            
263
/// Converts a - expression for a SATInt to a new SATInt
264
///
265
/// ```text
266
/// -SATInt(a) ~> SATInt(b)
267
///
268
/// ```
269
#[register_rule(("SAT_Direct", 9100))]
270
135000
fn neg_sat_direct(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
271
135000
    let Expr::Neg(_, value) = expr else {
272
134928
        return Err(RuleNotApplicable);
273
    };
274

            
275
72
    let (binding, old_min, old_max) = validate_direct_int_operands(vec![value.as_ref().clone()])?;
276
60
    let [val_bits] = binding.as_slice() else {
277
        return Err(RuleNotApplicable);
278
    };
279

            
280
60
    let new_min = -old_max;
281
60
    let new_max = -old_min;
282

            
283
60
    let mut out = val_bits.clone();
284
60
    out.reverse();
285

            
286
60
    Ok(Reduction::pure(Expr::SATInt(
287
60
        Metadata::new(),
288
60
        SATIntEncoding::Direct,
289
60
        Moo::new(into_matrix_expr!(out)),
290
60
        (new_min, new_max),
291
60
    )))
292
135000
}
293

            
294
13176
fn floor_div(a: i32, b: i32) -> i32 {
295
13176
    let (q, r) = (a / b, a % b);
296
13176
    if (r > 0 && b < 0) || (r < 0 && b > 0) {
297
4008
        q - 1
298
    } else {
299
9168
        q
300
    }
301
13176
}
302

            
303
/// Converts a / expression between two direct SATInts to a new direct SATInt
304
/// using the "lookup table" method.
305
///
306
/// ```text
307
/// SafeDiv(SATInt(a), SATInt(b)) ~> SATInt(c)
308
///
309
/// ```
310
#[register_rule(("SAT_Direct", 9100))]
311
135000
fn safediv_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
312
135000
    let Expr::SafeDiv(_, numer_expr, denom_expr) = expr else {
313
134910
        return Err(RuleNotApplicable);
314
    };
315

            
316
90
    let Expr::SATInt(_, SATIntEncoding::Direct, numer_inner, (numer_min, numer_max)) =
317
90
        numer_expr.as_ref()
318
    else {
319
        return Err(RuleNotApplicable);
320
    };
321
90
    let Some(numer_bits) = numer_inner.as_ref().clone().unwrap_list() else {
322
        return Err(RuleNotApplicable);
323
    };
324

            
325
90
    let Expr::SATInt(_, SATIntEncoding::Direct, denom_inner, (denom_min, denom_max)) =
326
90
        denom_expr.as_ref()
327
    else {
328
        return Err(RuleNotApplicable);
329
    };
330

            
331
90
    let Some(denom_bits) = denom_inner.as_ref().clone().unwrap_list() else {
332
        return Err(RuleNotApplicable);
333
    };
334

            
335
90
    let mut quot_min = i32::MAX;
336
90
    let mut quot_max = i32::MIN;
337

            
338
912
    for i in *numer_min..=*numer_max {
339
13956
        for j in *denom_min..=*denom_max {
340
13956
            let k = if j == 0 { 0 } else { i / j };
341
13956
            quot_min = quot_min.min(k);
342
13956
            quot_max = quot_max.max(k);
343
        }
344
    }
345

            
346
90
    let mut new_symbols = symbols.clone();
347
90
    let mut quot_bits = Vec::new();
348

            
349
    // generate boolean variables for all possible quotients
350
1002
    for _ in quot_min..=quot_max {
351
1002
        let decl = new_symbols.gensym(&conjure_cp::ast::Domain::bool());
352
1002
        quot_bits.push(Expr::Atomic(
353
1002
            Metadata::new(),
354
1002
            Atom::Reference(conjure_cp::ast::Reference::new(decl)),
355
1002
        ));
356
1002
    }
357

            
358
90
    let mut new_clauses = vec![];
359

            
360
    // generate the lookup table clauses: (n_i AND d_j) => q_k
361
912
    for i in *numer_min..=*numer_max {
362
912
        let numer_bit = &numer_bits[(i - numer_min) as usize];
363
13956
        for j in *denom_min..=*denom_max {
364
13956
            let denom_bit = &denom_bits[(j - denom_min) as usize];
365

            
366
13956
            let k = if j == 0 { 0 } else { floor_div(i, j) };
367

            
368
13956
            let quot_bit = &quot_bits[(k - quot_min) as usize];
369

            
370
13956
            new_clauses.push(CnfClause::new(vec![
371
13956
                Expr::Not(Metadata::new(), Moo::new(numer_bit.clone())),
372
13956
                Expr::Not(Metadata::new(), Moo::new(denom_bit.clone())),
373
13956
                quot_bit.clone(),
374
            ]));
375
        }
376
    }
377

            
378
    // the quotient cannot take more than one value simultaneously.
379
1002
    for a in 0..quot_bits.len() {
380
9708
        for b in (a + 1)..quot_bits.len() {
381
9708
            new_clauses.push(CnfClause::new(vec![
382
9708
                Expr::Not(Metadata::new(), Moo::new(quot_bits[a].clone())),
383
9708
                Expr::Not(Metadata::new(), Moo::new(quot_bits[b].clone())),
384
9708
            ]));
385
9708
        }
386
    }
387

            
388
90
    let quot_int = Expr::SATInt(
389
90
        Metadata::new(),
390
90
        SATIntEncoding::Direct,
391
90
        Moo::new(into_matrix_expr!(quot_bits)),
392
90
        (quot_min, quot_max),
393
90
    );
394

            
395
90
    Ok(Reduction::cnf(quot_int, new_clauses, new_symbols))
396
135000
}