1
//! Preserve linear constraints and numeric relations as semantic library decisions.
2
use conjure_cp::ast::sat_decision::{CardinalityRelation, PbTermGroup, PbTermStructure};
3
use conjure_cp::ast::{
4
    AbstractLiteral::Matrix, Atom, Expression as Expr, Literal, Metadata, SATIntEncoding,
5
    SatEncodingDecision, SymbolTable,
6
};
7
use conjure_cp::rule_engine::{
8
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
9
};
10

            
11
#[derive(Default)]
12
struct Linear {
13
    constant: i128,
14
    terms: Vec<(i128, Expr)>,
15
    groups: Vec<PbTermGroup>,
16
}
17
impl Linear {
18
63420536
    fn add(&mut self, expression: &Expr, scale: i128) -> Option<()> {
19
63420536
        match expression {
20
            Expr::Atomic(_, Atom::Literal(Literal::Int(value))) => {
21
4023169
                self.constant = self
22
4023169
                    .constant
23
4023169
                    .checked_add(scale.checked_mul(i128::from(*value))?)?
24
            }
25
            Expr::Atomic(_, Atom::Reference(reference)) => {
26
                use crate::types::int::{
27
                    IntBinaryOffset, IntBinaryRank, IntBinarySignMagnitude,
28
                    IntBinaryTwosComplement, IntDirect, IntOrder,
29
                };
30
8458352
                let represented = if let Some(state) = reference.get_repr_as::<IntDirect>() {
31
1959489
                    state.sat_int_expr()
32
6498863
                } else if let Some(state) = reference.get_repr_as::<IntOrder>() {
33
345642
                    state.sat_int_expr()
34
6153221
                } else if let Some(state) = reference.get_repr_as::<IntBinaryOffset>() {
35
523865
                    state.sat_int_expr()
36
5629356
                } else if let Some(state) = reference.get_repr_as::<IntBinaryRank>() {
37
227924
                    state.sat_int_expr()
38
5401432
                } else if let Some(state) = reference.get_repr_as::<IntBinarySignMagnitude>() {
39
280008
                    state.sat_int_expr()
40
                } else {
41
5121424
                    reference
42
5121424
                        .get_repr_as::<IntBinaryTwosComplement>()?
43
                        .sat_int_expr()
44
                };
45
3567463
                self.add(&represented, scale)?;
46
            }
47
            Expr::Minus(_, left, right) => {
48
322983
                self.add(left, scale)?;
49
67302
                self.add(right, scale.checked_neg()?)?;
50
            }
51
163593
            Expr::Neg(_, input) => self.add(input, scale.checked_neg()?)?,
52
            Expr::Sum(_, inputs) => {
53
9440454
                let Expr::AbstractLiteral(_, Matrix(inputs, _)) = inputs.as_ref() else {
54
471465
                    return None;
55
                };
56
8968989
                for input in inputs {
57
21909057
                    self.add(input, scale)?;
58
                }
59
            }
60
            Expr::Product(_, inputs) => {
61
1743276
                let Expr::AbstractLiteral(_, Matrix(inputs, _)) = inputs.as_ref() else {
62
18
                    return None;
63
                };
64
1743258
                let mut multiplier = scale;
65
1743258
                let mut variable = None;
66
1743258
                for input in inputs {
67
3498414
                    if let Some(value) = constant_int(input) {
68
891768
                        multiplier = multiplier.checked_mul(i128::from(value))?;
69
2606646
                    } else if variable.replace(input).is_some() {
70
863388
                        return None;
71
1743258
                    }
72
                }
73
879870
                if let Some(variable) = variable {
74
879870
                    self.add(variable, multiplier)?;
75
                } else {
76
                    self.constant = self.constant.checked_add(multiplier)?;
77
                }
78
            }
79
            Expr::ToInt(_, input)
80
5200855
                if crate::shared::utils::is_literal(input)
81
1612285
                    && input.domain_of().is_some_and(|domain| domain.is_bool()) =>
82
            {
83
1612285
                self.terms.push((scale, input.as_ref().clone()))
84
            }
85
            Expr::SATInt(_, encoding, inner, (low, high)) => {
86
18681742
                let bits = inner.unwrap_list_cow()?;
87
18681742
                let start = self.terms.len();
88
18681742
                let structure = match encoding {
89
                    SATIntEncoding::Direct => {
90
3338136
                        if bits.len() as i128 != i128::from(*high) - i128::from(*low) + 1 {
91
                            return None;
92
3338136
                        }
93
                        // Direct and Order retain the domain span; separate structural
94
                        // constraints exclude sparse-domain gaps.
95
3338136
                        for (index, bit) in bits.iter().enumerate() {
96
18662517
                            self.terms.push((
97
18662517
                                scale.checked_mul(i128::from(*low) + index as i128)?,
98
18662517
                                bit.clone(),
99
                            ));
100
                        }
101
3338136
                        Some(PbTermStructure::Choice)
102
                    }
103
                    SATIntEncoding::Order => {
104
699061
                        if bits.len() as i128 != i128::from(*high) - i128::from(*low) + 1 {
105
                            return None;
106
699061
                        }
107
699061
                        self.constant = self
108
699061
                            .constant
109
699061
                            .checked_add(scale.checked_mul(i128::from(*low))?)?;
110
699061
                        for bit in bits.iter().skip(1) {
111
4659064
                            self.terms.push((scale, bit.clone()));
112
                        }
113
699061
                        Some(PbTermStructure::Chain)
114
                    }
115
                    SATIntEncoding::Offset | SATIntEncoding::Rank(_) => {
116
1644947
                        if let SATIntEncoding::Rank(ranges) = encoding
117
698352
                            && ranges.as_slice() != [(*low, *high)]
118
                        {
119
310002
                            return None;
120
1334945
                        }
121
1334945
                        if bits.is_empty() || bits.len() > 32 {
122
                            return None;
123
1334945
                        }
124
1334945
                        self.constant = self
125
1334945
                            .constant
126
1334945
                            .checked_add(scale.checked_mul(i128::from(*low))?)?;
127
1334945
                        for (index, bit) in bits.iter().enumerate() {
128
3190083
                            self.terms
129
3190083
                                .push((scale.checked_mul(1i128 << index)?, bit.clone()));
130
                        }
131
1334945
                        binary_structure(scale, 0, i128::from(*high) - i128::from(*low))
132
                    }
133
                    SATIntEncoding::SignMagnitude => {
134
622161
                        if bits.len() < 2 || bits.len() > 33 {
135
                            return None;
136
622161
                        }
137
622161
                        let sign = bits.last()?;
138
622161
                        for (index, magnitude) in bits[..bits.len() - 1].iter().enumerate() {
139
1524852
                            let weight = scale.checked_mul(1i128 << index)?;
140
1524852
                            self.terms.push((weight, magnitude.clone()));
141
                            // x = magnitude - 2*(sign AND magnitude). The compiler
142
                            // reuses RustSAT gates and the selected library PB encoder.
143
1524852
                            let negative = match (sign, magnitude) {
144
                                (Expr::Atomic(_, Atom::Literal(Literal::Bool(false))), _)
145
                                | (_, Expr::Atomic(_, Atom::Literal(Literal::Bool(false)))) => {
146
6300
                                    false.into()
147
                                }
148
                                (Expr::Atomic(_, Atom::Literal(Literal::Bool(true))), _) => {
149
540
                                    magnitude.clone()
150
                                }
151
                                (_, Expr::Atomic(_, Atom::Literal(Literal::Bool(true)))) => {
152
                                    sign.clone()
153
                                }
154
1518012
                                _ => Expr::And(
155
1518012
                                    Metadata::new(),
156
1518012
                                    conjure_cp::ast::Moo::new(conjure_cp::into_matrix_expr!(vec![
157
1518012
                                        sign.clone(),
158
1518012
                                        magnitude.clone()
159
1518012
                                    ])),
160
1518012
                                ),
161
                            };
162
1524852
                            self.terms.push((weight.checked_mul(-2)?, negative));
163
                        }
164
                        // The conjunctions depend on the magnitude bits: this is
165
                        // not an independent bounded-binary input group.
166
622161
                        None
167
                    }
168
                    SATIntEncoding::Log => {
169
12377437
                        if bits.is_empty() || bits.len() > 32 {
170
                            return None;
171
12377437
                        }
172
12377437
                        for (index, bit) in bits.iter().enumerate() {
173
29853784
                            let weight = scale.checked_mul(1i128 << index)?;
174
29853784
                            self.terms.push((
175
29853784
                                if index + 1 == bits.len() {
176
12377437
                                    weight.checked_neg()?
177
                                } else {
178
17476347
                                    weight
179
                                },
180
29853784
                                bit.clone(),
181
                            ));
182
                        }
183
12377437
                        binary_structure(scale, i128::from(*low), i128::from(*high))
184
                    }
185
                };
186
18371740
                if self.terms.len() > start
187
18361660
                    && let Some(structure) = structure
188
                {
189
17739499
                    self.groups.push(PbTermGroup {
190
17739499
                        start,
191
17739499
                        end: self.terms.len(),
192
17739499
                        structure,
193
17739499
                    });
194
632241
                }
195
            }
196
18974682
            _ => return None,
197
        }
198
28421339
        Some(())
199
63420536
    }
200
}
201
/// Extract an actual-value view without folding representation bounds to constants.
202
4457273
pub(super) fn integer_view(
203
4457273
    expression: &Expr,
204
4457273
) -> Option<conjure_cp::ast::sat_decision::SatIntegerView> {
205
    use conjure_cp::ast::{Moo, sat_decision::SatIntegerView};
206
4457273
    if expression
207
4457273
        .domain_of()
208
4457255
        .is_some_and(|domain| domain.is_bool())
209
117225
        && crate::shared::utils::is_literal(expression)
210
    {
211
117198
        return Some(SatIntegerView {
212
117198
            constant: 0,
213
117198
            terms: vec![(1, expression.clone())],
214
117198
            groups: vec![],
215
117198
            choices: Some(vec![
216
117198
                (0, Expr::Not(Metadata::new(), Moo::new(expression.clone()))),
217
117198
                (1, expression.clone()),
218
117198
            ]),
219
117198
        });
220
4340075
    }
221
4340075
    let mut linear = Linear::default();
222
4340075
    linear.add(expression, 1)?;
223
2664597
    let constant = i64::try_from(linear.constant).ok()?;
224
2664597
    let terms = linear
225
2664597
        .terms
226
2664597
        .into_iter()
227
10332898
        .map(|(weight, input)| i64::try_from(weight).ok().map(|weight| (weight, input)))
228
        .collect::<Option<Vec<_>>>()?;
229
    // Literal code bits establish the actual value; singleton bounds alone do not.
230
2664597
    if terms
231
2664597
        .iter()
232
2227206
        .all(|(_, input)| matches!(input, Expr::Atomic(_, Atom::Literal(Literal::Bool(_)))))
233
    {
234
586728
        let value = terms
235
586728
            .iter()
236
586728
            .try_fold(i128::from(constant), |value, (weight, input)| {
237
149337
                let Expr::Atomic(_, Atom::Literal(Literal::Bool(bit))) = input else {
238
                    unreachable!()
239
                };
240
149337
                value.checked_add(i128::from(*weight) * i128::from(*bit))
241
149337
            })
242
586728
            .and_then(|value| i64::try_from(value).ok())?;
243
586728
        return Some(SatIntegerView {
244
586728
            constant: value,
245
586728
            terms: vec![],
246
586728
            groups: vec![],
247
586728
            choices: Some(vec![(value, true.into())]),
248
586728
        });
249
2077869
    }
250
2077869
    let choices = if terms.is_empty() {
251
        Some(vec![(constant, true.into())])
252
2077869
    } else if linear.groups.len() == 1
253
1874973
        && linear.groups[0].start == 0
254
1874973
        && linear.groups[0].end == terms.len()
255
1874973
        && linear.groups[0].structure == PbTermStructure::Choice
256
    {
257
        Some(
258
1052595
            terms
259
1052595
                .iter()
260
6517665
                .map(|(weight, input)| {
261
6517665
                    constant
262
6517665
                        .checked_add(*weight)
263
6517665
                        .map(|value| (value, input.clone()))
264
6517665
                })
265
                .collect::<Option<Vec<_>>>()?,
266
        )
267
    } else {
268
1025274
        None
269
    };
270
2077869
    Some(SatIntegerView {
271
2077869
        constant,
272
2077869
        terms,
273
2077869
        groups: linear.groups,
274
2077869
        choices,
275
2077869
    })
276
4457273
}
277

            
278
13712382
fn binary_structure(scale: i128, low: i128, high: i128) -> Option<PbTermStructure> {
279
13712382
    let a = scale.checked_mul(low)?;
280
13712382
    let b = scale.checked_mul(high)?;
281
    Some(PbTermStructure::BoundedBinary {
282
13712382
        lower: i64::try_from(a.min(b)).ok()?,
283
13712382
        upper: i64::try_from(a.max(b)).ok()?,
284
    })
285
13712382
}
286
4784325
fn constant_int(expression: &Expr) -> Option<i32> {
287
4784325
    match expression {
288
1882614
        Expr::Atomic(_, Atom::Literal(Literal::Int(value))) => Some(*value),
289
        Expr::SATInt(..) => {
290
            // Inspect literal code bits: singleton bounds alone do not make a value constant.
291
939987
            let view = integer_view(expression)?;
292
825642
            view.terms
293
825642
                .is_empty()
294
126027
                .then(|| i32::try_from(view.constant).ok())
295
                .flatten()
296
        }
297
1961724
        _ => None,
298
    }
299
4784325
}
300
17624647
fn has_linear_operation(expression: &Expr) -> bool {
301
17624647
    matches!(
302
17624647
        expression,
303
        Expr::Sum(..) | Expr::Product(..) | Expr::Minus(..) | Expr::Neg(..) | Expr::ToInt(..)
304
    )
305
17624647
}
306

            
307
/// Preserve products of Boolean indicators as an indicator of their conjunction.
308
#[register_rule("SAT", 18900, [Product])]
309
1243305
fn product_boolean_indicators(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
310
1243305
    let Expr::Product(_, factors) = expr else {
311
27
        return Err(RuleNotApplicable);
312
    };
313
1243278
    let inputs = super::boolean::count_inputs(factors).ok_or(RuleNotApplicable)?;
314
19728
    Ok(RuleEffect::pure(Expr::ToInt(
315
19728
        Metadata::new(),
316
19728
        conjure_cp::ast::Moo::new(Expr::And(
317
19728
            Metadata::new(),
318
19728
            conjure_cp::ast::Moo::new(conjure_cp::into_matrix_expr!(inputs)),
319
19728
        )),
320
19728
    )))
321
1243305
}
322

            
323
/// Extract ready, asserted linear comparisons before integer circuits consume them.
324
#[register_rule("SAT", 19000, [Root])]
325
9186294
fn select_pseudo_boolean(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
326
92327696
    super::asserted::select_asserted(expr, symbols, |child| {
327
92327696
        let (left, right, relation, strict) = match child {
328
2966173
            Expr::Leq(_, left, right) => (left, right, CardinalityRelation::AtMost, false),
329
149391
            Expr::Lt(_, left, right) => (left, right, CardinalityRelation::AtMost, true),
330
1060663
            Expr::Geq(_, left, right) => (left, right, CardinalityRelation::AtLeast, false),
331
17775
            Expr::Gt(_, left, right) => (left, right, CardinalityRelation::AtLeast, true),
332
7224602
            Expr::Eq(_, left, right) => (left, right, CardinalityRelation::Exactly, false),
333
80909092
            _ => return None,
334
        };
335
11418604
        if !has_linear_operation(left) && !has_linear_operation(right) {
336
5476296
            return None;
337
5942308
        }
338
5942308
        let mut linear = Linear::default();
339
5942308
        linear.add(left, 1)?;
340
677191
        linear.add(right, -1)?;
341
70870
        let mut bound = linear.constant.checked_neg()?;
342
70870
        if strict {
343
1269
            bound = bound.checked_add(if relation == CardinalityRelation::AtMost {
344
1260
                -1
345
            } else {
346
9
                1
347
            })?;
348
69601
        }
349
70870
        let bound = i64::try_from(bound).ok()?;
350
70870
        let terms = linear
351
70870
            .terms
352
70870
            .into_iter()
353
793794
            .map(|(weight, input)| i64::try_from(weight).map(|weight| (weight, input)))
354
            .collect::<Result<Vec<_>, _>>()
355
            .ok()?;
356
70870
        Some(SatEncodingDecision::PseudoBoolean {
357
70870
            terms,
358
70870
            groups: linear.groups,
359
70870
            relation,
360
70870
            bound,
361
70870
            encoding: None,
362
70870
        })
363
92327696
    })
364
9186294
}
365
330811743
fn ready_count_comparison(expr: &Expr) -> bool {
366
330811743
    let (left, right) = match expr {
367
        Expr::Eq(_, left, right)
368
        | Expr::Neq(_, left, right)
369
        | Expr::Lt(_, left, right)
370
        | Expr::Leq(_, left, right)
371
        | Expr::Gt(_, left, right)
372
73689125
        | Expr::Geq(_, left, right) => (left, right),
373
257122618
        _ => return false,
374
    };
375
146491066
    let count = |expression: &Expr| {
376
146491066
        matches!(expression, Expr::Sum(_, inputs)
377
8689014
        if super::boolean::count_inputs(inputs).is_some())
378
146491066
    };
379
73689125
    (count(left) && constant_int(right).is_some()) || (count(right) && constant_int(left).is_some())
380
330811743
}
381

            
382
/// Reify Boolean counts within ready Boolean contexts using cardinality and AMO providers.
383
#[register_rule("SAT", 18600, [Root])]
384
9114749
fn select_guarded_count(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
385
9114749
    if !matches!(expr, Expr::Root(..)) {
386
27
        return Err(RuleNotApplicable);
387
9114722
    }
388
9114722
    guarded_count(expr, true, symbols).ok_or(RuleNotApplicable)
389
9114749
}
390

            
391
386837198
fn guarded_count(expr: &Expr, asserted: bool, symbols: &SymbolTable) -> Option<RuleEffect> {
392
386837198
    if !asserted && ready_count_comparison(expr) {
393
139032
        return count_relation(expr, symbols).ok();
394
386698166
    }
395
    // Only traverse Boolean contexts and literal matrices, never a binder or undefined value.
396
386698166
    match expr {
397
9114722
        Expr::Root(_, entries) => guarded_children(expr, entries.iter(), true, symbols),
398
        Expr::AbstractLiteral(_, Matrix(entries, _)) => {
399
56931406
            guarded_children(expr, entries.iter(), asserted, symbols)
400
        }
401
        Expr::And(_, entries)
402
18050939
            if matches!(entries.as_ref(), Expr::AbstractLiteral(_, Matrix(..))) =>
403
        {
404
16837739
            guarded_children(expr, std::iter::once(entries.as_ref()), asserted, symbols)
405
        }
406
        Expr::Or(_, entries)
407
40358465
            if matches!(entries.as_ref(), Expr::AbstractLiteral(_, Matrix(..))) =>
408
        {
409
40093667
            guarded_children(expr, std::iter::once(entries.as_ref()), false, symbols)
410
        }
411
        Expr::Not(_, child) | Expr::ToInt(_, child) => {
412
21044394
            guarded_children(expr, std::iter::once(child.as_ref()), false, symbols)
413
        }
414
        Expr::Imply(_, left, right)
415
        | Expr::Iff(_, left, right)
416
        | Expr::Eq(_, left, right)
417
        | Expr::Neq(_, left, right)
418
        | Expr::Lt(_, left, right)
419
        | Expr::Leq(_, left, right)
420
        | Expr::Gt(_, left, right)
421
44280937
        | Expr::Geq(_, left, right) => guarded_children(
422
44280937
            expr,
423
44280937
            [left.as_ref(), right.as_ref()].into_iter(),
424
44280937
            false,
425
44280937
            symbols,
426
44280937
        ),
427
198395301
        _ => None,
428
    }
429
386837198
}
430

            
431
188302865
fn guarded_children<'a>(
432
188302865
    expr: &Expr,
433
188302865
    children: impl Iterator<Item = &'a Expr>,
434
188302865
    asserted: bool,
435
188302865
    symbols: &SymbolTable,
436
188302865
) -> Option<RuleEffect> {
437
    use uniplate::Uniplate;
438
188302865
    for (index, child) in children.enumerate() {
439
377722476
        if let Some(mut effect) = guarded_count(child, asserted, symbols) {
440
533988
            let mut replacements = expr.children();
441
533988
            replacements[index] = effect.new_expression;
442
533988
            effect.new_expression = expr.with_children(replacements);
443
533988
            return Some(effect);
444
377188488
        }
445
    }
446
187768877
    None
447
188302865
}
448

            
449
/// Preserve numeric equality and comparison, including nested Boolean uses, for library encoding.
450
#[register_rule("SAT", 18500, [Eq, Neq, Lt, Leq, Gt, Geq])]
451
24071975
fn select_integer_relation(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
452
    // Root chooses asserted bounds; disequality and guarded counts require equivalence decisions.
453
24071975
    if ready_count_comparison(expr) && !matches!(expr, Expr::Neq(..)) {
454
816669
        return Err(RuleNotApplicable);
455
23255306
    }
456
23255306
    if ready_count_comparison(expr) {
457
7380
        return count_relation(expr, symbols);
458
23247926
    }
459
23247926
    integer_relation(expr, symbols)
460
24071975
}
461

            
462
146412
fn count_relation(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
463
    use conjure_cp::ast::sat_decision::IntegerRelation;
464
146412
    let (left, right, mut relation) = match expr {
465
14976
        Expr::Eq(_, left, right) => (left, right, IntegerRelation::Equal),
466
12402
        Expr::Neq(_, left, right) => (left, right, IntegerRelation::NotEqual),
467
43578
        Expr::Lt(_, left, right) => (left, right, IntegerRelation::Less),
468
60390
        Expr::Leq(_, left, right) => (left, right, IntegerRelation::LessEqual),
469
5022
        Expr::Gt(_, left, right) => (left, right, IntegerRelation::Greater),
470
10044
        Expr::Geq(_, left, right) => (left, right, IntegerRelation::GreaterEqual),
471
        _ => return Err(RuleNotApplicable),
472
    };
473
146412
    let (sum, bound) = if let Expr::Sum(_, sum) = left.as_ref() {
474
64278
        (sum, constant_int(right).ok_or(RuleNotApplicable)?)
475
82134
    } else if let Expr::Sum(_, sum) = right.as_ref() {
476
82134
        relation = match relation {
477
38556
            IntegerRelation::Less => IntegerRelation::Greater,
478
38556
            IntegerRelation::LessEqual => IntegerRelation::GreaterEqual,
479
            IntegerRelation::Greater => IntegerRelation::Less,
480
5022
            IntegerRelation::GreaterEqual => IntegerRelation::LessEqual,
481
            other => other,
482
        };
483
82134
        (sum, constant_int(left).ok_or(RuleNotApplicable)?)
484
    } else {
485
        return Err(RuleNotApplicable);
486
    };
487
146412
    let inputs = super::boolean::count_inputs(sum).ok_or(RuleNotApplicable)?;
488
146412
    let bound = i64::from(bound);
489
146412
    let mut symbols = symbols.clone();
490
146412
    let output = super::boolean::create_bool_aux(&mut symbols);
491
146412
    Ok(RuleEffect::sat(
492
146412
        output.clone(),
493
146412
        vec![SatEncodingDecision::CountRelation {
494
146412
            output,
495
146412
            inputs,
496
146412
            relation,
497
146412
            bound,
498
146412
            encoding: None,
499
146412
            amo_encoding: None,
500
146412
        }],
501
146412
        symbols,
502
146412
    ))
503
146412
}
504

            
505
23247926
fn integer_relation(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
506
    use conjure_cp::ast::sat_decision::IntegerRelation;
507
23247926
    let (left, right, relation) = match expr {
508
14381596
        Expr::Eq(_, left, right) => (left, right, IntegerRelation::Equal),
509
1161599
        Expr::Neq(_, left, right) => (left, right, IntegerRelation::NotEqual),
510
2722019
        Expr::Lt(_, left, right) => (left, right, IntegerRelation::Less),
511
3537515
        Expr::Leq(_, left, right) => (left, right, IntegerRelation::LessEqual),
512
296896
        Expr::Gt(_, left, right) => (left, right, IntegerRelation::Greater),
513
1148274
        Expr::Geq(_, left, right) => (left, right, IntegerRelation::GreaterEqual),
514
27
        _ => return Err(RuleNotApplicable),
515
    };
516
    // Boolean equality stays in the Boolean family. Ready SATInt views are already numeric.
517
23247899
    if !matches!(left.as_ref(), Expr::SATInt(..))
518
21493075
        && !left.domain_of().is_some_and(|domain| domain.is_int())
519
    {
520
2525986
        return Err(RuleNotApplicable);
521
20721913
    }
522
20721913
    let mut linear = Linear::default();
523
20721913
    linear.add(left, 1).ok_or(RuleNotApplicable)?;
524
4828781
    linear.add(right, -1).ok_or(RuleNotApplicable)?;
525
2758385
    let bound = linear
526
2758385
        .constant
527
2758385
        .checked_neg()
528
2758385
        .and_then(|n| i64::try_from(n).ok())
529
2758385
        .ok_or(RuleNotApplicable)?;
530
2758385
    let terms = linear
531
2758385
        .terms
532
2758385
        .into_iter()
533
15707666
        .map(|(weight, input)| i64::try_from(weight).map(|weight| (weight, input)))
534
        .collect::<Result<Vec<_>, _>>()
535
        .map_err(|_| RuleNotApplicable)?;
536
2758385
    let mut symbols = symbols.clone();
537
2758385
    let output = super::boolean::create_bool_aux(&mut symbols);
538
2758385
    Ok(RuleEffect::sat(
539
2758385
        output.clone(),
540
2758385
        vec![SatEncodingDecision::IntegerRelation {
541
2758385
            output,
542
2758385
            terms,
543
2758385
            groups: linear.groups,
544
2758385
            relation,
545
2758385
            bound,
546
2758385
            encoding: None,
547
2758385
        }],
548
2758385
        symbols,
549
2758385
    ))
550
23247926
}
551

            
552
/// Preserve the objective's actual-value view and shared PB choice for solve-time tightening.
553
#[register_rule("SAT", 18400, [SatObjective])]
554
30722
fn select_sat_objective(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
555
30722
    let Expr::SatObjective(_, minimise, value) = expr else {
556
27
        return Err(RuleNotApplicable);
557
    };
558
30695
    let value = integer_view(value).ok_or(RuleNotApplicable)?;
559
6420
    Ok(RuleEffect::sat(
560
6420
        true.into(),
561
6420
        vec![SatEncodingDecision::Objective {
562
6420
            minimise: *minimise,
563
6420
            value,
564
6420
            encoding: None,
565
6420
        }],
566
6420
        symbols.clone(),
567
6420
    ))
568
30722
}