pumpkin-propagators 0.5.0

The propagators of the Pumpkin constraint programming solver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use pumpkin_checking::AtomicConstraint;
use pumpkin_checking::CheckerVariable;
use pumpkin_checking::InferenceChecker;
use pumpkin_checking::IntExt;
use pumpkin_checking::VariableState;
use pumpkin_core::asserts::pumpkin_assert_simple;
use pumpkin_core::declare_inference_label;
use pumpkin_core::predicate;
use pumpkin_core::predicates::Predicate;
use pumpkin_core::predicates::PropositionalConjunction;
use pumpkin_core::proof::ConstraintTag;
use pumpkin_core::proof::InferenceCode;
use pumpkin_core::propagation::DomainEvents;
use pumpkin_core::propagation::Domains;
use pumpkin_core::propagation::EnqueueDecision;
use pumpkin_core::propagation::EventsToRegister;
use pumpkin_core::propagation::ExplanationContext;
use pumpkin_core::propagation::LazyExplanation;
use pumpkin_core::propagation::LocalId;
use pumpkin_core::propagation::NotificationContext;
use pumpkin_core::propagation::OpaqueDomainEvent;
use pumpkin_core::propagation::Priority;
use pumpkin_core::propagation::PropagationContext;
use pumpkin_core::propagation::Propagator;
use pumpkin_core::propagation::PropagatorConstructor;
use pumpkin_core::propagation::PropagatorConstructorContext;
use pumpkin_core::propagation::PropagatorSpec;
use pumpkin_core::propagation::ReadDomains;
use pumpkin_core::propagation::RuntimeCheckers;
use pumpkin_core::propagation::TrailedInteger;
use pumpkin_core::state::PropagationStatusCP;
use pumpkin_core::state::PropagatorConflict;
use pumpkin_core::variables::IntegerVariable;

declare_inference_label!(LinearBounds);

/// The [`PropagatorConstructor`] for the [`LinearLessOrEqualPropagator`].
#[derive(Clone, Debug)]
pub struct LinearLessOrEqualPropagatorArgs<Var> {
    pub x: Box<[Var]>,
    pub c: i32,
    pub constraint_tag: ConstraintTag,
}

impl<Var> PropagatorConstructor for LinearLessOrEqualPropagatorArgs<Var>
where
    Var: IntegerVariable + 'static,
{
    type PropagatorImpl = LinearLessOrEqualPropagator<Var>;

    fn create(
        self,
        mut context: PropagatorConstructorContext,
    ) -> PropagatorSpec<Self::PropagatorImpl> {
        let LinearLessOrEqualPropagatorArgs {
            x,
            c,
            constraint_tag,
        } = self;

        let mut lower_bound_left_hand_side = 0_i64;
        let mut current_bounds = vec![];

        let mut registration = EventsToRegister::builder();
        for (i, x_i) in x.iter().enumerate() {
            registration =
                registration.add(x_i, DomainEvents::LOWER_BOUND, LocalId::from(i as u32));
            lower_bound_left_hand_side += context.lower_bound(x_i) as i64;
            current_bounds.push(context.new_trailed_integer(context.lower_bound(x_i) as i64));
        }

        let lower_bound_left_hand_side = context.new_trailed_integer(lower_bound_left_hand_side);

        let mut checkers = RuntimeCheckers::builder();
        let inference_code = checkers.add_inference_checker(
            constraint_tag,
            LinearBounds,
            LinearLessOrEqualInferenceChecker::new(x.clone(), c),
        );

        let propagator = LinearLessOrEqualPropagator {
            x,
            c,
            lower_bound_left_hand_side,
            current_bounds: current_bounds.into(),
            inference_code,
            reason_buffer: Vec::default(),
        };

        PropagatorSpec {
            registration: registration.build(),
            checkers: checkers.build(),
            propagator,
        }
    }
}

/// Propagator for the constraint `\sum x_i <= c`.
#[derive(Clone, Debug)]
pub struct LinearLessOrEqualPropagator<Var> {
    x: Box<[Var]>,
    c: i32,

    /// The lower bound of the sum of the left-hand side. This is incremental state.
    lower_bound_left_hand_side: TrailedInteger,
    /// The value at index `i` is the bound for `x[i]`.
    current_bounds: Box<[TrailedInteger]>,
    /// A buffer for storing the reason for a propagation.
    reason_buffer: Vec<Predicate>,

    inference_code: InferenceCode,
}

impl<Var> LinearLessOrEqualPropagator<Var>
where
    Var: IntegerVariable,
{
    fn create_conflict(&self, context: Domains) -> PropagatorConflict {
        PropagatorConflict {
            conjunction: self
                .x
                .iter()
                .map(|var| predicate![var >= context.lower_bound(var)])
                .collect(),
            inference_code: self.inference_code.clone(),
        }
    }
}

impl<Var: 'static> Propagator for LinearLessOrEqualPropagator<Var>
where
    Var: IntegerVariable,
{
    fn detect_inconsistency(&self, domains: Domains) -> Option<PropagatorConflict> {
        if (self.c as i64) < domains.read_trailed_integer(self.lower_bound_left_hand_side) {
            Some(self.create_conflict(domains))
        } else {
            None
        }
    }

    fn notify(
        &mut self,
        mut context: NotificationContext,
        local_id: LocalId,
        _event: OpaqueDomainEvent,
    ) -> EnqueueDecision {
        let index = local_id.unpack() as usize;
        let x_i = &self.x[index];

        let old_bound = context.read_trailed_integer(self.current_bounds[index]);
        let new_bound = context.lower_bound(x_i) as i64;

        pumpkin_assert_simple!(
            old_bound < new_bound,
            "propagator should only be triggered when lower bounds are tightened, old_bound={old_bound}, new_bound={new_bound}"
        );

        context.write_trailed_integer(
            self.lower_bound_left_hand_side,
            context.read_trailed_integer(self.lower_bound_left_hand_side) + (new_bound - old_bound),
        );
        context.write_trailed_integer(self.current_bounds[index], new_bound);

        EnqueueDecision::Enqueue
    }

    fn priority(&self) -> Priority {
        Priority::High
    }

    fn name(&self) -> &str {
        "LinearLeq"
    }

    fn lazy_explanation(&mut self, code: u64, context: ExplanationContext) -> LazyExplanation<'_> {
        let i = code as usize;

        self.reason_buffer.clear();

        self.reason_buffer
            .extend(self.x.iter().enumerate().filter_map(|(j, x_j)| {
                if j != i {
                    Some(predicate![
                        x_j >= context
                            .lower_bound_at_trail_position(x_j, context.get_trail_position())
                    ])
                } else {
                    None
                }
            }));

        LazyExplanation {
            predicates: self.reason_buffer.as_slice(),
            inference_code: self.inference_code.clone(),
        }
    }

    fn propagate(&mut self, mut context: PropagationContext) -> PropagationStatusCP {
        if let Some(conflict) = self.detect_inconsistency(context.domains()) {
            return Err(conflict.into());
        }

        let lower_bound_left_hand_side = match TryInto::<i32>::try_into(
            context.read_trailed_integer(self.lower_bound_left_hand_side),
        ) {
            Ok(bound) => bound,
            Err(_)
                if context
                    .read_trailed_integer(self.lower_bound_left_hand_side)
                    .is_positive() =>
            {
                // We cannot fit the `lower_bound_left_hand_side` into an i32 due to an
                // overflow (hence the check that the lower-bound on the left-hand side is
                // positive)
                //
                // This means that the lower-bounds of the current variables will always be
                // higher than the right-hand side (with a maximum value of i32). We thus
                // return a conflict
                return Err(self.create_conflict(context.domains()).into());
            }
            Err(_) => {
                // We cannot fit the `lower_bound_left_hand_side` into an i32 due to an
                // underflow
                //
                // This means that the constraint is always satisfied
                return Ok(());
            }
        };

        for (i, x_i) in self.x.iter().enumerate() {
            let bound = self.c - (lower_bound_left_hand_side - context.lower_bound(x_i));

            if context.upper_bound(x_i) > bound {
                context.post(predicate![x_i <= bound], i)?;
            }
        }

        Ok(())
    }

    fn propagate_from_scratch(&self, mut context: PropagationContext) -> PropagationStatusCP {
        let lower_bound_left_hand_side = self
            .x
            .iter()
            .map(|var| context.lower_bound(var) as i64)
            .sum::<i64>();

        let lower_bound_left_hand_side = match TryInto::<i32>::try_into(lower_bound_left_hand_side)
        {
            Ok(bound) => bound,
            Err(_)
                if context
                    .read_trailed_integer(self.lower_bound_left_hand_side)
                    .is_positive() =>
            {
                // We cannot fit the `lower_bound_left_hand_side` into an i32 due to an
                // overflow (hence the check that the lower-bound on the left-hand side is
                // positive)
                //
                // This means that the lower-bounds of the current variables will always be
                // higher than the right-hand side (with a maximum value of i32). We thus
                // return a conflict
                return Err(self.create_conflict(context.domains()).into());
            }
            Err(_) => {
                // We cannot fit the `lower_bound_left_hand_side` into an i32 due to an
                // underflow
                //
                // This means that the constraint is always satisfied
                return Ok(());
            }
        };

        for (i, x_i) in self.x.iter().enumerate() {
            let bound = self.c - (lower_bound_left_hand_side - context.lower_bound(x_i));

            if context.upper_bound(x_i) > bound {
                let reason: PropositionalConjunction = self
                    .x
                    .iter()
                    .enumerate()
                    .filter_map(|(j, x_j)| {
                        if j != i {
                            Some(predicate![x_j >= context.lower_bound(x_j)])
                        } else {
                            None
                        }
                    })
                    .collect();

                context.post(predicate![x_i <= bound], (reason, &self.inference_code))?;
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct LinearLessOrEqualInferenceChecker<Var> {
    terms: Box<[Var]>,
    bound: i32,
}

impl<Var> LinearLessOrEqualInferenceChecker<Var> {
    pub fn new(terms: Box<[Var]>, bound: i32) -> Self {
        LinearLessOrEqualInferenceChecker { terms, bound }
    }
}

impl<Var, Atomic> InferenceChecker<Atomic> for LinearLessOrEqualInferenceChecker<Var>
where
    Var: CheckerVariable<Atomic>,
    Atomic: AtomicConstraint,
{
    fn check(
        &self,
        variable_state: VariableState<Atomic>,
        _: &[Atomic],
        _: Option<&Atomic>,
    ) -> bool {
        // Next, we evaluate the linear inequality. The lower bound of the
        // left-hand side must exceed the bound in the constraint. Note that the accumulator is an
        // IntExt, and if the lower bound of one of the terms is -infty, then the left-hand side
        // will be -infty regardless of the other terms.
        let left_hand_side: IntExt<i64> = self
            .terms
            .iter()
            .map(|variable| variable.induced_lower_bound(&variable_state).into())
            .sum();

        left_hand_side > i64::from(self.bound)
    }
}

#[cfg(test)]
mod tests {
    use pumpkin_core::conjunction;
    use pumpkin_core::predicate;
    use pumpkin_core::predicates::Predicate;
    use pumpkin_core::predicates::PropositionalConjunction;
    use pumpkin_core::propagation::CurrentNogood;
    use pumpkin_core::state::State;

    use super::*;
    use crate::StateExt;

    #[test]
    fn test_bounds_are_propagated() {
        let mut state = State::default();
        let x = state.new_interval_variable(1, 5, None);
        let y = state.new_interval_variable(0, 10, None);

        let constraint_tag = state.new_constraint_tag();

        let _ = state.add_propagator(LinearLessOrEqualPropagatorArgs {
            x: [x, y].into(),
            c: 7,
            constraint_tag,
        });
        state.propagate_to_fixed_point().expect("no empty domains");

        state.assert_bounds(x, 1, 5);
        state.assert_bounds(y, 0, 6);
    }

    #[test]
    fn test_explanations() {
        let mut state = State::default();
        let x = state.new_interval_variable(1, 5, None);
        let y = state.new_interval_variable(0, 10, None);
        let constraint_tag = state.new_constraint_tag();

        let _ = state.add_propagator(LinearLessOrEqualPropagatorArgs {
            x: [x, y].into(),
            c: 7,
            constraint_tag,
        });
        state.propagate_to_fixed_point().expect("no empty domains");

        let mut reason_buffer: Vec<Predicate> = vec![];
        let _ = state.get_propagation_reason(
            predicate![y <= 6],
            &mut reason_buffer,
            CurrentNogood::empty(),
        );
        let reason: PropositionalConjunction = reason_buffer.into();

        assert_eq!(conjunction!([x >= 1]), reason);
    }

    #[test]
    fn overflow_leads_to_conflict() {
        let mut state = State::default();

        let x = state.new_interval_variable(i32::MAX, i32::MAX, None);
        let y = state.new_interval_variable(1, 1, None);
        let constraint_tag = state.new_constraint_tag();

        let _ = state.add_propagator(LinearLessOrEqualPropagatorArgs {
            x: [x, y].into(),
            c: i32::MAX,
            constraint_tag,
        });
        let _ = state
            .propagate_to_fixed_point()
            .expect_err("Expected overflow to be detected");
    }

    #[test]
    fn underflow_leads_to_no_propagation() {
        let mut state = State::default();

        let x = state.new_interval_variable(i32::MIN, i32::MIN, None);
        let y = state.new_interval_variable(-1, -1, None);
        let constraint_tag = state.new_constraint_tag();

        let _ = state.add_propagator(LinearLessOrEqualPropagatorArgs {
            x: [x, y].into(),
            c: i32::MIN,
            constraint_tag,
        });
        state
            .propagate_to_fixed_point()
            .expect("Expected no error to be detected");
    }
}