1
//! Channelling between the SAT integer encodings.
2
//!
3
//! Which encoding an integer gets is a per-declaration representation choice, so one constraint
4
//! can end up comparing a one-hot variable with a bit-vector one. The encoding-specific rules all
5
//! decline in that case -- each only knows how to read its own layout -- so a mixed operation is
6
//! first rewritten to put every operand in the same encoding.
7
//!
8
//! Fallback operations use actual-value binary circuits. Direct and Order supply value
9
//! indicators; Offset adds the domain minimum and Rank maps canonical intervals to their
10
//! numeric values. These temporary circuit operands do not create additional representations.
11

            
12
use std::collections::{HashSet, VecDeque};
13

            
14
use conjure_cp::ast::{
15
    AbstractLiteral, Atom, DomainPtr, Expression as Expr, Literal, Metadata, Moo, SATIntEncoding,
16
    SatEncodingDecision, SymbolTable,
17
};
18
use conjure_cp::into_matrix_expr;
19
use conjure_cp::rule_engine::{
20
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
21
};
22

            
23
use crate::backends::sat::boolean::{
24
    tseytin_and, tseytin_mux, tseytin_not, tseytin_or, tseytin_xor,
25
};
26
use crate::backends::sat::int::log::bit_magnitude;
27
use uniplate::Uniplate;
28

            
29
/// Put every `SATInt` operand of an operation into the logarithmic encoding.
30
///
31
/// This is a fallback, and sits below every encoding-specific operation rule on purpose. An
32
/// operation whose operands share an encoding that knows how to encode it is handled there and
33
/// never reaches this rule. Remaining operands may have different encodings, use an encoding with
34
/// no rule for the operation, or include Boolean indicators needing an actual-value circuit view.
35
#[register_rule("SAT", 4000, [Eq, Neq, Lt, Gt, Leq, Geq, AllDiff, AllDifferentExcept, Table, NegativeTable, SatElement, SatObjective, Sum, Product, Min, Max, Abs, Neg, SafeDiv, SafeMod, SafePow])]
36
987155
fn unify_sat_int_encodings(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
37
987155
    let mut encodings = HashSet::new();
38
987155
    let mut has_indicator = false;
39
987155
    let mut operands_ready = true;
40
987155
    let table = matches!(expr, Expr::Table(..) | Expr::NegativeTable(..));
41
987155
    let inputs = if table {
42
10710
        expr.children()
43
10710
            .into_iter()
44
21420
            .flat_map(|child| {
45
21420
                crate::shared::utils::table_operand(&child)
46
21420
                    .universe()
47
21420
                    .into_iter()
48
262440
                    .filter(|input| matches!(input, Expr::SATInt(..)))
49
                    .collect::<Vec<_>>()
50
21420
            })
51
            .collect::<Vec<_>>()
52
    } else {
53
976445
        operands(expr).collect()
54
    };
55
987155
    for operand in inputs {
56
2266774
        let indicator = ready_indicator(&operand);
57
2266774
        has_indicator |= indicator;
58
2266774
        operands_ready &= indicator
59
2207914
            || matches!(
60
2207914
                operand,
61
                Expr::SATInt(..) | Expr::Atomic(_, Atom::Literal(Literal::Int(_)))
62
            );
63
2266774
        if let Expr::SATInt(_, encoding, _, _) = operand {
64
886570
            encodings.insert(encoding);
65
1380204
        }
66
    }
67

            
68
    // Semantic allDifferent/table/element operands retain their ready value views.
69
    // Sparse rank still needs interval decoding; other numeric views are native.
70
987155
    let retains_views = matches!(
71
987155
        expr,
72
        Expr::AllDiff(..)
73
            | Expr::AllDifferentExcept(..)
74
            | Expr::Table(..)
75
            | Expr::NegativeTable(..)
76
            | Expr::SatElement(..)
77
            | Expr::SatObjective(..)
78
    );
79
987155
    if retains_views && !encodings.iter().any(needs_actual_value_circuit) {
80
41697
        return Err(RuleNotApplicable);
81
945458
    }
82
    // Ready indicators need an actual-value view only when a circuit is required.
83
    // Linear and count decisions run earlier and retain their original inputs.
84
945458
    let has_indicator = !retains_views && has_indicator && operands_ready;
85
945458
    if !has_indicator
86
928889
        && encodings
87
928889
            .iter()
88
411929
            .all(|encoding| matches!(encoding, SATIntEncoding::Log))
89
    {
90
663219
        return Err(RuleNotApplicable);
91
282239
    }
92

            
93
282239
    let mut decisions = Vec::new();
94
282239
    let mut new_symbols = symbols.clone();
95

            
96
623599
    let mut convert = |input: Expr| {
97
623599
        if (retains_views
98
8118
            && !matches!(&input, Expr::SATInt(_, encoding, _, _) if needs_actual_value_circuit(encoding)))
99
621493
            || (!has_indicator && ready_indicator(&input))
100
        {
101
2106
            input
102
        } else {
103
621493
            to_log(input, &mut decisions, &mut new_symbols)
104
        }
105
623599
    };
106
282239
    let children: VecDeque<Expr> = expr
107
282239
        .children()
108
282239
        .into_iter()
109
507076
        .map(|child| {
110
507076
            if table {
111
2160
                map_table_cells(crate::shared::utils::table_operand(&child), &mut convert)
112
            } else {
113
504916
                match matrix_child(&child) {
114
                    Some((elements, index_domain)) => {
115
56223
                        let converted: Vec<Expr> = elements.into_iter().map(&mut convert).collect();
116
56223
                        rebuild_matrix_child(converted, index_domain)
117
                    }
118
448693
                    None => convert(child),
119
                }
120
            }
121
507076
        })
122
        .collect();
123

            
124
282239
    let new_expression = expr.with_children(children);
125
282239
    if new_expression == *expr && decisions.is_empty() {
126
        return Err(RuleNotApplicable);
127
282239
    }
128
282239
    Ok(RuleEffect::sat(new_expression, decisions, new_symbols))
129
987155
}
130

            
131
/// Whether semantic numeric decisions need a decoded actual-value circuit.
132
31761
fn needs_actual_value_circuit(encoding: &SATIntEncoding) -> bool {
133
31761
    matches!(encoding, SATIntEncoding::Rank(ranges) if ranges.len() != 1)
134
31761
}
135

            
136
7020
fn map_table_cells(expression: Expr, convert: &mut impl FnMut(Expr) -> Expr) -> Expr {
137
7020
    if matches!(expression, Expr::SATInt(..)) {
138
3780
        return convert(expression);
139
3240
    }
140
    // Cells can contain packed-sequence arithmetic as well as collection wrappers.
141
3240
    let children = expression
142
3240
        .children()
143
3240
        .into_iter()
144
4860
        .map(|child| map_table_cells(crate::shared::utils::table_operand(&child), convert))
145
        .collect();
146
3240
    expression.with_children(children)
147
7020
}
148

            
149
/// The elements of a matrix-literal child, with the index domain to rebuild it under.
150
///
151
/// `unwrap_list` only recognises the implied `int(1..)` index domain, but a matrix rebuilt from its
152
/// components keeps the one it was declared with. These rules look through a child to reach the
153
/// operands underneath, and an operand is no less an operand for being indexed from zero.
154
20234474
fn matrix_child(expr: &Expr) -> Option<(Vec<Expr>, DomainPtr)> {
155
20234474
    match expr {
156
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(elements, index_domain)) => {
157
2216934
            Some((elements.clone(), index_domain.clone()))
158
        }
159
18017540
        _ => None,
160
    }
161
20234474
}
162

            
163
/// Rebuild a matrix-literal child from new elements, keeping its index domain.
164
72990
fn rebuild_matrix_child(elements: Vec<Expr>, index_domain: DomainPtr) -> Expr {
165
72990
    Expr::AbstractLiteral(
166
72990
        Metadata::new(),
167
72990
        AbstractLiteral::Matrix(elements, index_domain),
168
72990
    )
169
72990
}
170

            
171
/// The operand expressions of `expr`, looking one level into list children.
172
///
173
/// `Sum` and friends hold their operands in a matrix child rather than directly, so a mixed
174
/// summation would otherwise look uniform from the outside.
175
10576662
fn operands(expr: &Expr) -> impl Iterator<Item = Expr> {
176
10576662
    expr.children()
177
10576662
        .into_iter()
178
18939639
        .flat_map(|child| match matrix_child(&child) {
179
2143944
            Some((elements, _)) => elements,
180
16795695
            None => vec![child],
181
18939639
        })
182
10576662
}
183

            
184
/// Re-encode one operand into the logarithmic encoding, leaving anything else alone.
185
621493
fn to_log(expr: Expr, decisions: &mut Vec<SatEncodingDecision>, symbols: &mut SymbolTable) -> Expr {
186
621493
    if ready_indicator(&expr) {
187
40590
        let Expr::ToInt(_, input) = expr else {
188
            unreachable!()
189
        };
190
40590
        return Expr::SATInt(
191
40590
            Metadata::new(),
192
40590
            SATIntEncoding::Log,
193
40590
            Moo::new(into_matrix_expr!(vec![
194
40590
                input.as_ref().clone(),
195
40590
                false.into()
196
40590
            ])),
197
40590
            (0, 1),
198
40590
        );
199
580903
    }
200
580903
    let Expr::SATInt(_, encoding, bits, bounds) = &expr else {
201
20358
        return expr;
202
    };
203
560545
    if matches!(encoding, SATIntEncoding::Log) {
204
990
        return expr;
205
559555
    }
206
559555
    let Some(bits) = bits.as_ref().clone().into_list() else {
207
        return expr;
208
    };
209

            
210
559555
    let (low, high) = *bounds;
211
559555
    let width = bit_magnitude(low).max(bit_magnitude(high));
212
559555
    if matches!(encoding, SATIntEncoding::Offset | SATIntEncoding::Rank(_)) {
213
128410
        let mut decoded = add_unsigned_constant(&bits, i64::from(low), width, decisions, symbols);
214
128410
        if let SATIntEncoding::Rank(ranges) = encoding {
215
82114
            let mut start = 0u64;
216
82114
            for (index, &(range_low, range_high)) in ranges.iter().enumerate() {
217
127644
                if index > 0 {
218
45530
                    let selector = unsigned_at_least(&bits, start, decisions, symbols);
219
45530
                    let candidate = add_unsigned_constant(
220
45530
                        &bits,
221
45530
                        i64::from(range_low) - start as i64,
222
45530
                        width,
223
45530
                        decisions,
224
45530
                        symbols,
225
45530
                    );
226
45530
                    decoded = decoded
227
45530
                        .into_iter()
228
45530
                        .zip(candidate)
229
168521
                        .map(|(old, new)| {
230
168521
                            tseytin_mux(selector.clone(), old, new, decisions, symbols)
231
168521
                        })
232
                        .collect();
233
82114
                }
234
127644
                start += (i64::from(range_high) - i64::from(range_low) + 1) as u64;
235
            }
236
46296
        }
237
128410
        return Expr::SATInt(
238
128410
            Metadata::new(),
239
128410
            SATIntEncoding::Log,
240
128410
            Moo::new(into_matrix_expr!(decoded)),
241
128410
            (low, high),
242
128410
        );
243
431145
    }
244

            
245
431145
    if matches!(encoding, SATIntEncoding::SignMagnitude) {
246
45855
        return Expr::SATInt(
247
45855
            Metadata::new(),
248
45855
            SATIntEncoding::Log,
249
45855
            Moo::new(into_matrix_expr!(sign_magnitude_to_twos_complement(
250
45855
                &bits, width, decisions, symbols
251
45855
            ))),
252
45855
            (low, high),
253
45855
        );
254
385290
    }
255

            
256
    // Both remaining encodings lay out one bit per value; order does so cumulatively, so take the
257
    // difference between neighbouring thresholds to recover "x is exactly this value".
258
385290
    let value_bits = match encoding {
259
339390
        SATIntEncoding::Direct => bits,
260
45900
        SATIntEncoding::Order => order_to_value_bits(&bits, decisions, symbols),
261
        SATIntEncoding::Log
262
        | SATIntEncoding::Offset
263
        | SATIntEncoding::Rank(_)
264
        | SATIntEncoding::SignMagnitude => return expr,
265
    };
266

            
267
385290
    let log_bits: Vec<Expr> = (0..width)
268
1227420
        .map(|index| {
269
            // Bit `index` of `x` is set exactly when `x` takes one of the values whose two's
270
            // complement has that bit set.
271
1227420
            let terms: Vec<Expr> = value_bits
272
1227420
                .iter()
273
1227420
                .enumerate()
274
6845670
                .filter(|(offset, _)| ((low + *offset as i32) as u32) >> index & 1 == 1)
275
2556990
                .map(|(_, bit)| bit.clone())
276
                .collect();
277
1227420
            match terms.len() {
278
498825
                0 => Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false))),
279
287010
                1 => terms.into_iter().next().expect("just checked the length"),
280
441585
                _ => tseytin_or(&terms, decisions, symbols),
281
            }
282
1227420
        })
283
        .collect();
284

            
285
385290
    Expr::SATInt(
286
385290
        Metadata::new(),
287
385290
        SATIntEncoding::Log,
288
385290
        Moo::new(into_matrix_expr!(log_bits)),
289
385290
        (low, high),
290
385290
    )
291
621493
}
292

            
293
3459090
fn ready_indicator(expr: &Expr) -> bool {
294
3459090
    matches!(expr, Expr::ToInt(_, input)
295
107883
        if crate::shared::utils::is_literal(input)
296
99450
            && input.domain_of().is_some_and(|domain| domain.is_bool()))
297
3459090
}
298

            
299
/// Turn order-encoded thresholds into one bit per value.
300
///
301
/// `x = low + i` exactly when `x >= low + i` holds and `x >= low + i + 1` does not; past the top
302
/// threshold there is nothing left to exclude.
303
45900
fn order_to_value_bits(
304
45900
    thresholds: &[Expr],
305
45900
    decisions: &mut Vec<SatEncodingDecision>,
306
45900
    symbols: &mut SymbolTable,
307
45900
) -> Vec<Expr> {
308
45900
    thresholds
309
45900
        .iter()
310
45900
        .enumerate()
311
271935
        .map(|(index, threshold)| match thresholds.get(index + 1) {
312
            Some(next) => {
313
226035
                let not_next = tseytin_not(next.clone(), decisions, symbols);
314
226035
                tseytin_and(&[threshold.clone(), not_next], decisions, symbols)
315
            }
316
45900
            None => threshold.clone(),
317
271935
        })
318
        .collect()
319
45900
}
320

            
321
/// A constant in a given SAT integer encoding, with its value range pinned to the constant.
322
///
323
/// The direct and order encodings both need only a single set bit here: the padding in their
324
/// operand validators widens it to the range the operation works over.
325
403343
pub(super) fn sat_int_literal(encoding: &SATIntEncoding, value: i32) -> Expr {
326
403343
    let bits = match encoding {
327
76455
        SATIntEncoding::Log => log_literal_bits(value),
328
42173
        SATIntEncoding::Offset | SATIntEncoding::Rank(_) => vec![false.into()],
329
16200
        SATIntEncoding::SignMagnitude => sign_magnitude_literal_bits(value),
330
        SATIntEncoding::Direct | SATIntEncoding::Order => {
331
268515
            vec![Expr::Atomic(
332
268515
                Metadata::new(),
333
268515
                Atom::Literal(Literal::Bool(true)),
334
268515
            )]
335
        }
336
    };
337

            
338
    Expr::SATInt(
339
403343
        Metadata::new(),
340
403343
        match encoding {
341
25901
            SATIntEncoding::Rank(_) => SATIntEncoding::Rank(vec![(value, value)]),
342
377442
            other => other.clone(),
343
        },
344
403343
        Moo::new(into_matrix_expr!(bits)),
345
403343
        (value, value),
346
    )
347
403343
}
348

            
349
/// The sign-and-magnitude bits of a constant: its magnitude, least significant first, then the sign.
350
16200
fn sign_magnitude_literal_bits(value: i32) -> Vec<Expr> {
351
16200
    let magnitude = i64::from(value).unsigned_abs();
352
16200
    let width = (64 - magnitude.leading_zeros()).max(1);
353
49545
    let bit = |set: bool| Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(set)));
354
16200
    (0..width)
355
33345
        .map(|index| bit((magnitude >> index) & 1 == 1))
356
16200
        .chain(std::iter::once(bit(value < 0)))
357
        .collect()
358
16200
}
359

            
360
/// Two's complement of a sign-and-magnitude code, in `width` bits.
361
///
362
/// The magnitude is inverted and incremented when the sign is set: with the sign as the carry in,
363
/// bit `i` is `(m_i xor s) xor carry_i` and the carry on is `(m_i xor s) and carry_i`. Bits past
364
/// the magnitude's are zero, so they are just the sign.
365
45855
fn sign_magnitude_to_twos_complement(
366
45855
    bits: &[Expr],
367
45855
    width: usize,
368
45855
    decisions: &mut Vec<SatEncodingDecision>,
369
45855
    symbols: &mut SymbolTable,
370
45855
) -> Vec<Expr> {
371
45855
    let (sign, magnitude) = bits.split_last().expect("a sign bit");
372
45855
    let mut carry = sign.clone();
373
45855
    let mut out = Vec::with_capacity(width);
374
45855
    for index in 0..width {
375
158445
        let flipped = match magnitude.get(index) {
376
112950
            Some(bit) => tseytin_xor(bit.clone(), sign.clone(), decisions, symbols),
377
45495
            None => sign.clone(),
378
        };
379
158445
        out.push(tseytin_xor(
380
158445
            flipped.clone(),
381
158445
            carry.clone(),
382
158445
            decisions,
383
158445
            symbols,
384
158445
        ));
385
158445
        carry = tseytin_and(&[flipped, carry], decisions, symbols);
386
    }
387
45855
    out
388
45855
}
389

            
390
/// The two's-complement bits of a constant, least significant first.
391
76455
fn log_literal_bits(value: i32) -> Vec<Expr> {
392
76455
    let mut remaining = value as u32;
393
76455
    (0..bit_magnitude(value))
394
229905
        .map(|_| {
395
229905
            let bit = Expr::Atomic(
396
229905
                Metadata::new(),
397
229905
                Atom::Literal(Literal::Bool(remaining & 1 != 0)),
398
229905
            );
399
229905
            remaining >>= 1;
400
229905
            bit
401
229905
        })
402
        .collect()
403
76455
}
404

            
405
/// Encode integer constants into whichever encoding the operation's variables are in.
406
///
407
/// Constants have no representation of their own to follow, and encoding one eagerly would mean
408
/// guessing: the same `2` belongs in a bit vector next to a log-encoded variable and in a one-hot
409
/// vector next to a direct-encoded one. Deferring until the operation is known keeps the encodings
410
/// separate, and leaves every operation rule below with the invariant it relies on -- that its
411
/// integer operands are all `SATInt`s.
412
#[register_rule("SAT", 9400, [Eq, Neq, Lt, Gt, Leq, Geq, Sum, Product, Min, Max, SafeDiv, SafeMod, SafePow])]
413
9600217
fn encode_sat_int_literals(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
414
9600217
    let mut encoding = None;
415
9600217
    let mut has_literal = false;
416
9600217
    for operand in operands(expr) {
417
26095253
        match operand {
418
6490860
            Expr::SATInt(_, found, _, _) => encoding = encoding.or(Some(found)),
419
4770620
            Expr::Atomic(_, Atom::Literal(Literal::Int(_))) => has_literal = true,
420
14833773
            _ => {}
421
        }
422
    }
423

            
424
    // Without a variable to follow there is nothing to match, and without a constant there is
425
    // nothing to do.
426
9600217
    let (Some(encoding), true) = (encoding, has_literal) else {
427
9196874
        return Err(RuleNotApplicable);
428
    };
429

            
430
808639
    let encode = |expr: Expr| match expr {
431
403343
        Expr::Atomic(_, Atom::Literal(Literal::Int(value))) => sat_int_literal(&encoding, value),
432
405296
        other => other,
433
808639
    };
434

            
435
403343
    let children: VecDeque<Expr> = expr
436
403343
        .children()
437
403343
        .into_iter()
438
789919
        .map(|child| match matrix_child(&child) {
439
            Some((elements, index_domain)) => {
440
16767
                rebuild_matrix_child(elements.into_iter().map(encode).collect(), index_domain)
441
            }
442
773152
            None => encode(child),
443
789919
        })
444
        .collect();
445

            
446
403343
    Ok(RuleEffect::pure(expr.with_children(children)))
447
9600217
}
448

            
449
/// Add a constant modulo the semantic width; structural constraints exclude unused codes.
450
173940
fn add_unsigned_constant(
451
173940
    bits: &[Expr],
452
173940
    constant: i64,
453
173940
    width: usize,
454
173940
    decisions: &mut Vec<SatEncodingDecision>,
455
173940
    symbols: &mut SymbolTable,
456
173940
) -> Vec<Expr> {
457
173940
    let mut carry: Expr = false.into();
458
173940
    let mut out = Vec::with_capacity(width);
459
173940
    for index in 0..width {
460
612528
        let bit = bits.get(index).cloned().unwrap_or_else(|| false.into());
461
612528
        let sum = tseytin_xor(bit.clone(), carry.clone(), decisions, symbols);
462
612528
        if (constant as u32 >> index) & 1 == 1 {
463
208487
            out.push(tseytin_not(sum, decisions, symbols));
464
208487
            carry = tseytin_or(&[bit, carry], decisions, symbols);
465
        } else {
466
404041
            out.push(sum);
467
404041
            carry = tseytin_and(&[bit, carry], decisions, symbols);
468
        }
469
    }
470
173940
    out
471
173940
}
472
/// Compare an unsigned code with an interval's starting rank.
473
45530
fn unsigned_at_least(
474
45530
    bits: &[Expr],
475
45530
    minimum: u64,
476
45530
    decisions: &mut Vec<SatEncodingDecision>,
477
45530
    symbols: &mut SymbolTable,
478
45530
) -> Expr {
479
45530
    let maximum = minimum - 1;
480
45530
    let mut leq: Expr = true.into();
481
45530
    for (index, bit) in bits.iter().enumerate() {
482
88469
        let not = tseytin_not(bit.clone(), decisions, symbols);
483
88469
        leq = if (maximum >> index) & 1 == 1 {
484
22437
            tseytin_or(&[not, leq], decisions, symbols)
485
        } else {
486
66032
            tseytin_and(&[not, leq], decisions, symbols)
487
        };
488
    }
489
45530
    tseytin_not(leq, decisions, symbols)
490
45530
}