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
315645
fn literal_sat_direct_int(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
25
1254
    let value = {
26
12471
        if let Expr::Atomic(_, Atom::Literal(Literal::Int(value))) = expr {
27
1254
            *value
28
        } else {
29
314391
            return Err(RuleNotApplicable);
30
        }
31
    };
32

            
33
1254
    Ok(Reduction::pure(Expr::SATInt(
34
1254
        Metadata::new(),
35
1254
        SATIntEncoding::Direct,
36
1254
        Moo::new(into_matrix_expr!(vec![Expr::Atomic(
37
1254
            Metadata::new(),
38
1254
            Atom::Literal(Literal::Bool(true)),
39
1254
        )])),
40
1254
        (value, value),
41
1254
    )))
42
315645
}
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
25974
pub fn validate_direct_int_operands(
47
25974
    exprs: Vec<Expr>,
48
25974
) -> 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
25974
    let mut global_min: i32 = i32::MAX;
55
25974
    let mut global_max: i32 = i32::MIN;
56

            
57
28650
    for operand in &exprs {
58
26505
        let Expr::SATInt(_, SATIntEncoding::Direct, _, (local_min, local_max)) = operand else {
59
24201
            return Err(RuleNotApplicable);
60
        };
61
4449
        global_min = global_min.min(*local_min);
62
4449
        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
1773
    let out: Vec<Vec<Expr>> = exprs
68
1773
        .into_iter()
69
3489
        .map(|expr| {
70
3489
            let Expr::SATInt(_, SATIntEncoding::Direct, inner, (local_min, local_max)) = expr
71
            else {
72
                return Err(RuleNotApplicable);
73
            };
74

            
75
3489
            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
3489
            let prefix_len = (local_min - global_min) as usize;
81
3489
            let postfix_len = (global_max - local_max) as usize;
82

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

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

            
91
3489
            bits.extend(v);
92

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

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

            
103
1773
    Ok((out, global_min, global_max))
104
25974
}
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
62895
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
62895
    let Expr::Eq(_, lhs, rhs) = expr else {
117
62487
        return Err(RuleNotApplicable);
118
    };
119

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

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

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

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

            
147
357
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
148
62895
}
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
62895
fn neq_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
160
62895
    let Expr::Neq(_, lhs, rhs) = expr else {
161
62814
        return Err(RuleNotApplicable);
162
    };
163

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

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

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

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

            
191
72
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
192
62895
}
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
356598
fn ineq_sat_direct(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
203
356598
    let (lhs, rhs, negate) = match expr {
204
        // A < B -> sat_direct_lt(A, B)
205
426
        Expr::Lt(_, x, y) => (x, y, false),
206
        // A > B -> sat_direct_lt(B, A)
207
555
        Expr::Gt(_, x, y) => (y, x, false),
208
        // A <= B -> NOT (B < A)
209
13380
        Expr::Leq(_, x, y) => (y, x, true),
210
        // A >= B -> NOT (A < B)
211
11058
        Expr::Geq(_, x, y) => (x, y, true),
212
331179
        _ => return Err(RuleNotApplicable),
213
    };
214

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

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

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

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

            
235
1287
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
236
356598
}
237

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

            
248
10245
    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
10245
        b_or = tseytin_or(&vec![b_or, b_i.clone()], clauses, symbols);
251
10245

            
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
10245
        let not_b_or = tseytin_not(b_or.clone(), clauses, symbols);
255
10245
        let a_i_and_not_b_i = tseytin_and(&vec![a_i.clone(), not_b_or], clauses, symbols);
256
10245

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

            
260
1287
    cum_result
261
1287
}
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
62895
fn neg_sat_direct(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
271
62895
    let Expr::Neg(_, value) = expr else {
272
62829
        return Err(RuleNotApplicable);
273
    };
274

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

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

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

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