From f598c721974f93b7ef70b22eaee503c1a3443035 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 09:41:57 +0100 Subject: [PATCH 01/18] refactor: use btree map to store removed ranges --- .../core/src/engine/cp/assignments.rs | 128 ++++++++++++------ 1 file changed, 88 insertions(+), 40 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index 30db10012..ace6a0a22 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -1,5 +1,6 @@ +use std::collections::BTreeMap; + use crate::basic_types::Trail; -use crate::containers::HashMap; use crate::containers::KeyedVec; use crate::engine::cp::reason::ReasonRef; use crate::engine::notifications::NotificationEngine; @@ -326,16 +327,18 @@ impl Assignments { } // Add holes. - for hole in &self.domains[domain_id].holes { + for (&start, piece) in &self.domains[domain_id].holes { + if piece.update_info.checkpoint == 0 { + continue; + } // Only record holes that are within the lower and upper bound, // that are not root assignments. // Since bound values cannot be in the holes, // we can use '<' or '>'. - if hole.1.checkpoint > 0 - && domain.lower_bound() < *hole.0 - && *hole.0 < domain.upper_bound() - { - predicates.push(predicate![domain_id != *hole.0]); + for hole in start..=piece.end { + if domain.lower_bound() < hole && hole < domain.upper_bound() { + predicates.push(predicate![domain_id != hole]); + } } } predicates @@ -882,6 +885,15 @@ struct PairDecisionLevelTrailPosition { trail_position: usize, } +/// A piece of consecutive values `[start, end]` (both inclusive) which were removed from a domain +/// at the same time; the start of the piece is the key in [`IntegerDomain::holes`]. +#[derive(Clone, Copy, Debug)] +struct HolePiece { + /// The last value of the removed piece (inclusive). + end: i32, + update_info: PairDecisionLevelTrailPosition, +} + #[derive(Clone, Debug)] struct BoundUpdateInfo { bound: i32, @@ -891,7 +903,12 @@ struct BoundUpdateInfo { #[derive(Clone, Debug)] struct HoleUpdateInfo { - removed_value: i32, + /// The first value of the removed piece (inclusive); this is the key of the piece in + /// [`IntegerDomain::holes`]. + start: i32, + /// The last value of the removed piece (inclusive), i.e., the removed values are + /// `start..=end`. + end: i32, checkpoint: usize, @@ -913,9 +930,12 @@ struct IntegerDomain { hole_updates: Vec, /// Auxiliary data structure to make it easy to check if a value is present or not. /// This is done to avoid going through 'hole_updates'. - /// It maps a removed value with its decision level and trail position. - /// In the future we could consider using direct hashing if the domain is small. - holes: HashMap, + /// + /// Each entry is a piece of consecutive values which were removed by a single removal; it maps + /// the first value of the piece to the last value of the piece and the decision level and + /// trail position of the removal. The pieces are disjoint, but pieces are not merged when they + /// are adjacent, so that the time of removal is known for every value. + holes: BTreeMap, // Records the trail entry at which all of the root bounds are true initial_bounds_below_trail: usize, /// The holes that exist in the input problem. @@ -1044,10 +1064,20 @@ impl IntegerDomain { IntegerDomainIterator::new(self) } + /// Returns the removed piece which contains `value`, if any. + fn hole_containing(&self, value: i32) -> Option { + self.holes + .range(..=value) + .next_back() + .and_then(|(_, piece)| (value <= piece.end).then_some(*piece)) + } + + fn is_hole(&self, value: i32) -> bool { + self.hole_containing(value).is_some() + } + fn contains(&self, value: i32) -> bool { - self.lower_bound() <= value - && value <= self.upper_bound() - && !self.holes.contains_key(&value) + self.lower_bound() <= value && value <= self.upper_bound() && !self.is_hole(value) } fn contains_at_trail_position(&self, value: i32, trail_position: usize) -> bool { @@ -1062,8 +1092,8 @@ impl IntegerDomain { // In case the hole is made at the given trail position or earlier, // the value is not in the domain. - if let Some(hole_info) = self.holes.get(&value) - && hole_info.trail_position <= trail_position + if let Some(piece) = self.hole_containing(value) + && piece.update_info.trail_position <= trail_position { return false; } @@ -1080,13 +1110,14 @@ impl IntegerDomain { ) -> bool { if removed_value < self.lower_bound() || removed_value > self.upper_bound() - || self.holes.contains_key(&removed_value) + || self.is_hole(removed_value) { return false; } self.hole_updates.push(HoleUpdateInfo { - removed_value, + start: removed_value, + end: removed_value, checkpoint, triggered_lower_bound_update: false, triggered_upper_bound_update: false, @@ -1095,9 +1126,12 @@ impl IntegerDomain { // because the later if statements may use the holes. let old_none_entry = self.holes.insert( removed_value, - PairDecisionLevelTrailPosition { - checkpoint, - trail_position, + HolePiece { + end: removed_value, + update_info: PairDecisionLevelTrailPosition { + checkpoint, + trail_position, + }, }, ); pumpkin_assert_moderate!(old_none_entry.is_none()); @@ -1156,10 +1190,16 @@ impl IntegerDomain { } fn update_upper_bound_with_respect_to_holes(&mut self) { - while self.holes.contains_key(&self.upper_bound()) - && self.lower_bound() <= self.upper_bound() + // Jump over the removed pieces which contain the upper bound; note that pieces can be + // adjacent, so this may jump over several pieces. + while self.lower_bound() <= self.upper_bound() + && let Some((&start, _)) = self + .holes + .range(..=self.upper_bound()) + .next_back() + .filter(|(_, piece)| self.upper_bound() <= piece.end) { - self.upper_bound_updates.last_mut().unwrap().bound -= 1; + self.upper_bound_updates.last_mut().unwrap().bound = start - 1; } } @@ -1198,10 +1238,12 @@ impl IntegerDomain { } fn update_lower_bound_with_respect_to_holes(&mut self) { - while self.holes.contains_key(&self.lower_bound()) - && self.lower_bound() <= self.upper_bound() + // Jump over the removed pieces which contain the lower bound; note that pieces can be + // adjacent, so this may jump over several pieces. + while self.lower_bound() <= self.upper_bound() + && let Some(piece) = self.hole_containing(self.lower_bound()) { - self.lower_bound_updates.last_mut().unwrap().bound += 1; + self.lower_bound_updates.last_mut().unwrap().bound = piece.end + 1; } } @@ -1212,8 +1254,8 @@ impl IntegerDomain { } else { self.lower_bound() >= self.initial_lower_bound() && self.upper_bound() <= self.initial_upper_bound() - && !self.holes.contains_key(&self.lower_bound()) - && !self.holes.contains_key(&self.upper_bound()) + && !self.is_hole(self.lower_bound()) + && !self.is_hole(self.upper_bound()) } } @@ -1249,12 +1291,16 @@ impl IntegerDomain { .hole_updates .pop() .expect("Must have record of domain removal."); - pumpkin_assert_moderate!(hole_update.removed_value == not_equal_constant); + pumpkin_assert_moderate!( + hole_update.start == not_equal_constant + && hole_update.end == not_equal_constant + ); - let _ = self + let removed_piece = self .holes - .remove(¬_equal_constant) + .remove(&hole_update.start) .expect("Must be present."); + pumpkin_assert_moderate!(removed_piece.end == hole_update.end); if hole_update.triggered_lower_bound_update { let _ = self.lower_bound_updates.pop(); @@ -1336,8 +1382,8 @@ impl IntegerDomain { // Check the explictly stored holes. // If the value has been removed explicitly, // then the stored time is the first time the value was removed. - if let Some(hole_info) = self.holes.get(&value) { - Some(*hole_info) + if let Some(piece) = self.hole_containing(value) { + Some(piece.update_info) } else { // Otherwise, check the case when the lower/upper bound surpassed the value. // If this never happened, then report that the predicate is not true. @@ -1398,7 +1444,7 @@ impl IntegerDomain { self.hole_updates .iter() .filter(move |entry| entry.checkpoint == checkpoint) - .map(|entry| entry.removed_value) + .flat_map(|entry| entry.start..=entry.end) } /// Returns the holes which were created on the current decision level. @@ -1410,13 +1456,15 @@ impl IntegerDomain { .iter() .rev() .take_while(move |entry| entry.checkpoint == current_checkpoint) - .map(|entry| entry.removed_value) + .flat_map(|entry| entry.start..=entry.end) } /// Returns all of the holes (currently) in the domain of `var` (including ones which were /// created at previous decision levels). pub(crate) fn get_holes(&self) -> impl Iterator + '_ { - self.holes.keys().copied() + self.holes + .iter() + .flat_map(|(&start, piece)| start..=piece.end) } } @@ -1456,11 +1504,11 @@ impl Iterator for IntegerDomainIterator<'_> { self.current_value += 1; // If the current value is within the bounds, but is not in the domain, - // linearly look for the next non-hole value. + // jump over the removed pieces to the next non-hole value. while self.current_value <= self.domain.upper_bound() - && !self.domain.contains(self.current_value) + && let Some(piece) = self.domain.hole_containing(self.current_value) { - self.current_value += 1; + self.current_value = piece.end + 1; } result } From 3b6df306860763c42708c3fa7a16bd00d826eb1d Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 10:08:41 +0100 Subject: [PATCH 02/18] feat: remove range from domain --- .../engine/constraint_satisfaction_solver.rs | 111 ++--- .../core/src/engine/cp/assignments.rs | 396 ++++++++++++++++-- .../core/src/engine/debug_helper.rs | 22 +- pumpkin-crates/core/src/engine/state.rs | 62 ++- .../contexts/explanation_context.rs | 6 + .../contexts/propagation_context.rs | 52 +++ 6 files changed, 551 insertions(+), 98 deletions(-) diff --git a/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs b/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs index 8fc4c45db..30f217075 100644 --- a/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs +++ b/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs @@ -795,67 +795,74 @@ impl ConstraintSatisfactionSolver { // In case we are not logging inferences, we only need to keep track // of the root-level inferences to allow us to correctly finalize the // proof. - let _ = self - .unit_nogood_inference_codes - .insert(entry.predicate, inference_code); + // + // A trail entry which removes a range of values propagates a disequality + // predicate for every removed value. + for propagated in entry.propagated_predicates() { + let _ = self + .unit_nogood_inference_codes + .insert(propagated, inference_code.clone()); + } continue; } - let propagated = entry.predicate; - - // The proof inference for the propagation `R -> l` is `R /\ ~l -> false`. - let inference_premises = reason.iter().copied().chain(std::iter::once(!propagated)); - let _ = self.internal_parameters.proof_log.log_inference( - &mut self.state.constraint_tags, - inference_code, - inference_premises, - None, - &self.state.variable_names, - &self.state.assignments, - ); - - // Since inference steps are only related to the nogood they directly precede, - // facts derived at the root are also logged as nogoods so they can be used in the - // derivation of other nogoods. - // - // In case we are logging hints, we must therefore identify what proof steps contribute - // to the derivation of the current nogood, and therefore are in the premise of the - // previously logged inference. These proof steps are necessarily unit nogoods, and - // therefore we recursively look up which unit nogoods are involved in the premise of - // the inference. - - let mut to_explain: VecDeque = reason.iter().copied().collect(); - - while let Some(premise) = to_explain.pop_front() { - pumpkin_assert_simple!( - self.state - .truth_value(premise) - .expect("Expected predicate to hold") + // A trail entry which removes a range of values propagates a disequality predicate for + // every removed value; each of these is logged separately. + for propagated in entry.propagated_predicates() { + // The proof inference for the propagation `R -> l` is `R /\ ~l -> false`. + let inference_premises = reason.iter().copied().chain(std::iter::once(!propagated)); + let _ = self.internal_parameters.proof_log.log_inference( + &mut self.state.constraint_tags, + inference_code.clone(), + inference_premises, + None, + &self.state.variable_names, + &self.state.assignments, ); - let mut context = RootExplanationContext { - proof_log: &mut self.internal_parameters.proof_log, - unit_nogood_inference_codes: &self.unit_nogood_inference_codes, - state: &mut self.state, - }; + // Since inference steps are only related to the nogood they directly precede, + // facts derived at the root are also logged as nogoods so they can be used in the + // derivation of other nogoods. + // + // In case we are logging hints, we must therefore identify what proof steps + // contribute to the derivation of the current nogood, and therefore are in the + // premise of the previously logged inference. These proof steps are necessarily + // unit nogoods, and therefore we recursively look up which unit nogoods are + // involved in the premise of the inference. + + let mut to_explain: VecDeque = reason.iter().copied().collect(); + + while let Some(premise) = to_explain.pop_front() { + pumpkin_assert_simple!( + self.state + .truth_value(premise) + .expect("Expected predicate to hold") + ); - explain_root_assignment(&mut context, premise); - } + let mut context = RootExplanationContext { + proof_log: &mut self.internal_parameters.proof_log, + unit_nogood_inference_codes: &self.unit_nogood_inference_codes, + state: &mut self.state, + }; - // Log the nogood which adds the root-level knowledge to the proof. - let constraint_tag = self.internal_parameters.proof_log.log_deduction( - [!propagated], - &self.state.variable_names, - &mut self.state.constraint_tags, - &self.state.assignments, - ); + explain_root_assignment(&mut context, premise); + } + + // Log the nogood which adds the root-level knowledge to the proof. + let constraint_tag = self.internal_parameters.proof_log.log_deduction( + [!propagated], + &self.state.variable_names, + &mut self.state.constraint_tags, + &self.state.assignments, + ); - if let Ok(constraint_tag) = constraint_tag { - let inference_code = InferenceCode::new(constraint_tag, NogoodLabel); + if let Ok(constraint_tag) = constraint_tag { + let inference_code = InferenceCode::new(constraint_tag, NogoodLabel); - let _ = self - .unit_nogood_inference_codes - .insert(propagated, inference_code); + let _ = self + .unit_nogood_inference_codes + .insert(propagated, inference_code); + } } } } diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index ace6a0a22..cc92a0a21 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -132,6 +132,7 @@ impl Assignments { old_lower_bound: lower_bound, old_upper_bound: upper_bound, reason: None, + range_end: None, }); let upper_bound_position = self.trail.len(); self.trail.push(ConstraintProgrammingTrailEntry { @@ -139,6 +140,7 @@ impl Assignments { old_lower_bound: lower_bound, old_upper_bound: upper_bound, reason: None, + range_end: None, }); let _ = self.domains.push(IntegerDomain::new( @@ -423,6 +425,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -463,6 +466,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -504,6 +508,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -537,7 +542,30 @@ impl Assignments { return self.domains[domain_id].verify_consistency(); } - let predicate = predicate!(domain_id != removed_value_from_domain); + self.remove_run( + domain_id, + removed_value_from_domain, + removed_value_from_domain, + reason, + )?; + + Ok(true) + } + + /// Removes the values `start..=end` from the domain using a single trail entry. + /// + /// All of these values should be in the domain. + fn remove_run( + &mut self, + domain_id: DomainId, + start: i32, + end: i32, + reason: Option, + ) -> Result<(), EmptyDomain> { + pumpkin_assert_moderate!( + (start..=end).all(|value| self.domains[domain_id].contains(value)), + "all values of a run should be in the domain" + ); let old_lower_bound = self.get_lower_bound(domain_id); let old_upper_bound = self.get_upper_bound(domain_id); @@ -546,16 +574,17 @@ impl Assignments { let trail_position = self.trail.len(); self.trail.push(ConstraintProgrammingTrailEntry { - predicate, + predicate: predicate!(domain_id != start), old_lower_bound, old_upper_bound, reason, + range_end: (start != end).then_some(end), }); let checkpoint = self.get_checkpoint(); let domain = &mut self.domains[domain_id]; - let _ = domain.remove_value(removed_value_from_domain, checkpoint, trail_position); + domain.remove_range(start, end, checkpoint, trail_position); let changed_lower_bound = domain.lower_bound().abs_diff(old_lower_bound) as u64; let changed_upper_bound = old_upper_bound.abs_diff(domain.upper_bound()) as u64; @@ -563,13 +592,75 @@ impl Assignments { if changed_lower_bound + changed_upper_bound > 0 { self.pruned_values += changed_upper_bound + changed_lower_bound; } else { - self.pruned_values += 1; + self.pruned_values += end.abs_diff(start) as u64 + 1; } self.update_bounds_snapshot(domain_id); let _ = self.domains[domain_id].verify_consistency()?; - Ok(true) + Ok(()) + } + + /// Removes the values `start..=end` from the domain of `domain_id`. + /// + /// Values which are not in the domain are skipped: the remaining values are split into + /// maximal runs of consecutive values in the domain, and each run is removed using a single + /// trail entry, all sharing the provided `reason`. For example, if the domain is `[0, 10]` + /// with the hole `[4, 6]`, then removing `[2, 8]` removes the runs `[2, 3]` and `[7, 8]`. + /// + /// If the removal results in an empty domain, then the last removed value is removed using + /// its own trail entry, such that the last trail entry is a disequality predicate for the last + /// value in the domain (as is the case when removing a single value). + /// + /// Returns whether any value was removed, or [`EmptyDomain`] if the domain became empty. + pub(crate) fn remove_range_from_domain( + &mut self, + domain_id: DomainId, + start: i32, + end: i32, + reason: Option, + notification_engine: &mut NotificationEngine, + ) -> Result { + let (lower_bound_before, upper_bound_before) = self.bounds[domain_id]; + + let first = start.max(lower_bound_before); + let last = end.min(upper_bound_before); + if first > last { + return self.domains[domain_id].verify_consistency(); + } + + // If all values in the domain are removed, then we remove the upper-bound separately + // (see the documentation of this method). + let empties_domain = first == lower_bound_before && last == upper_bound_before; + let last_of_runs = if empties_domain { last - 1 } else { last }; + + let mut removal_took_place = false; + let mut from = first; + while let Some((run_start, run_end)) = + self.domains[domain_id].next_run_in_domain(from, last_of_runs) + { + self.remove_run(domain_id, run_start, run_end, reason)?; + removal_took_place = true; + from = run_end + 1; + } + + if empties_domain { + self.remove_run(domain_id, last, last, reason)?; + unreachable!("removing all values from the domain results in an empty domain"); + } + + if removal_took_place { + notification_engine.event_occurred( + lower_bound_before, + upper_bound_before, + self.domains[domain_id].lower_bound(), + self.domains[domain_id].upper_bound(), + removal_took_place, + domain_id, + ); + } + + Ok(removal_took_place) } /// Apply the given [`Predicate`] to the integer domains. @@ -788,10 +879,8 @@ impl Assignments { let add_on_lower_bound = entry.old_lower_bound.abs_diff(lower_bound_before) as u64; self.pruned_values -= add_on_upper_bound + add_on_lower_bound; - if entry.predicate.is_not_equal_predicate() - && add_on_lower_bound + add_on_upper_bound == 0 - { - self.pruned_values -= 1; + if add_on_lower_bound + add_on_upper_bound == 0 { + self.pruned_values -= entry.num_removed_values(); } let fixed_before = @@ -856,7 +945,7 @@ impl Assignments { self.trail .iter() .find_map(|entry| { - if entry.predicate == predicate { + if entry.covers(predicate) { entry.reason } else { None @@ -877,6 +966,63 @@ pub(crate) struct ConstraintProgrammingTrailEntry { /// propagation took place, e.g., does _not_ make sense in the case of a decision or if /// the update was due to synchronisation from the propositional trail. pub(crate) reason: Option, + /// For a [`PredicateType::NotEqual`] entry which removed several consecutive values at once, + /// the last removed value (inclusive); the removed values are then `rhs..=range_end`, where + /// `rhs` is the right-hand side of [`ConstraintProgrammingTrailEntry::predicate`]. + /// + /// This is `None` for all other entries (including the removal of a single value). + pub(crate) range_end: Option, +} + +impl ConstraintProgrammingTrailEntry { + /// Returns whether `predicate` was explicitly set to true by this trail entry. + /// + /// This is the case if it is the [`ConstraintProgrammingTrailEntry::predicate`], or if it is a + /// disequality predicate for one of the values removed by this entry. + pub(crate) fn covers(&self, predicate: Predicate) -> bool { + if self.predicate == predicate { + return true; + } + + let Some(range_end) = self.range_end else { + return false; + }; + + predicate.is_not_equal_predicate() + && predicate.get_domain() == self.predicate.get_domain() + && (self.predicate.get_right_hand_side()..=range_end) + .contains(&predicate.get_right_hand_side()) + } + + /// Returns the predicates which were explicitly set to true by this trail entry; this is + /// [`ConstraintProgrammingTrailEntry::predicate`], or a disequality predicate for every + /// removed value if this entry removed several values at once. + pub(crate) fn propagated_predicates(&self) -> impl Iterator + use<> { + let predicate = self.predicate; + let domain_id = predicate.get_domain(); + let start = predicate.get_right_hand_side(); + let range_end = self.range_end; + + // Without a range, the iterator yields `predicate` exactly once. + (start..=range_end.unwrap_or(start)).map(move |value| { + if range_end.is_some() { + predicate!(domain_id != value) + } else { + predicate + } + }) + } + + /// Returns the number of values removed by this entry if it is a disequality entry, and 0 + /// otherwise. + fn num_removed_values(&self) -> u64 { + if !self.predicate.is_not_equal_predicate() { + return 0; + } + + let start = self.predicate.get_right_hand_side(); + self.range_end.unwrap_or(start).abs_diff(start) as u64 + 1 + } } #[derive(Clone, Copy, Debug)] @@ -1102,22 +1248,38 @@ impl IntegerDomain { true } + #[cfg(test)] fn remove_value( &mut self, removed_value: i32, checkpoint: usize, trail_position: usize, ) -> bool { - if removed_value < self.lower_bound() - || removed_value > self.upper_bound() - || self.is_hole(removed_value) - { + if !self.contains(removed_value) { return false; } + self.remove_range(removed_value, removed_value, checkpoint, trail_position); + true + } + + /// Removes the values `start..=end` from the domain as a single piece. + /// + /// All of these values should be in the domain. + fn remove_range(&mut self, start: i32, end: i32, checkpoint: usize, trail_position: usize) { + pumpkin_assert_moderate!(start <= end); + pumpkin_assert_moderate!(self.lower_bound() <= start && end <= self.upper_bound()); + pumpkin_assert_moderate!( + self.holes + .range(..=end) + .next_back() + .is_none_or(|(_, piece)| piece.end < start), + "the removed values should not overlap with a hole" + ); + self.hole_updates.push(HoleUpdateInfo { - start: removed_value, - end: removed_value, + start, + end, checkpoint, triggered_lower_bound_update: false, triggered_upper_bound_update: false, @@ -1125,9 +1287,9 @@ impl IntegerDomain { // Note that it is important to remove the hole now, // because the later if statements may use the holes. let old_none_entry = self.holes.insert( - removed_value, + start, HolePiece { - end: removed_value, + end, update_info: PairDecisionLevelTrailPosition { checkpoint, trail_position, @@ -1136,24 +1298,48 @@ impl IntegerDomain { ); pumpkin_assert_moderate!(old_none_entry.is_none()); - // Check if removing a value triggers a lower bound update. - if self.lower_bound() == removed_value { - let _ = self.set_lower_bound(removed_value + 1, checkpoint, trail_position); + // Check if removing the values triggers a lower bound update. + if self.lower_bound() == start { + let _ = self.set_lower_bound(end + 1, checkpoint, trail_position); self.hole_updates .last_mut() .expect("we just pushed a value, so must be present") .triggered_lower_bound_update = true; } - // Check if removing the value triggers an upper bound update. - if self.upper_bound() == removed_value { - let _ = self.set_upper_bound(removed_value - 1, checkpoint, trail_position); + // Check if removing the values triggers an upper bound update. + if self.upper_bound() == end { + let _ = self.set_upper_bound(start - 1, checkpoint, trail_position); self.hole_updates .last_mut() .expect("we just pushed a value, so must be present") .triggered_upper_bound_update = true; } + } - true + /// Returns the first maximal run `[run_start, run_end]` of consecutive values in the domain + /// with `from <= run_start` and `run_end <= to`, if there is any. + /// + /// Both `from` and `to` should be within the bounds of the domain. + fn next_run_in_domain(&self, from: i32, to: i32) -> Option<(i32, i32)> { + // Skip the removed piece containing `from`; pieces can be adjacent, so this may skip + // several pieces. + let mut run_start = from; + while let Some(piece) = self.hole_containing(run_start) { + run_start = piece.end + 1; + } + + if run_start > to { + return None; + } + + // The run ends right before the next removed piece (or at `to`). + let run_end = self + .holes + .range(run_start..=to) + .next() + .map_or(to, |(&next_piece_start, _)| next_piece_start - 1); + + Some((run_start, run_end)) } fn debug_is_valid_upper_bound_domain_update( @@ -1286,14 +1472,14 @@ impl IntegerDomain { pumpkin_assert_moderate!(domain_id == self.id); let not_equal_constant = entry.predicate.get_right_hand_side(); + let range_end = entry.range_end.unwrap_or(not_equal_constant); let hole_update = self .hole_updates .pop() .expect("Must have record of domain removal."); pumpkin_assert_moderate!( - hole_update.start == not_equal_constant - && hole_update.end == not_equal_constant + hole_update.start == not_equal_constant && hole_update.end == range_end ); let removed_piece = self @@ -2293,4 +2479,160 @@ mod tests { .is_some_and(|x| x) ); } + + #[test] + fn remove_range_is_split_around_existing_hole() { + let mut notification_engine = NotificationEngine::test_default(); + let mut assignment = Assignments::default(); + let x = assignment.grow(0, 10); + notification_engine.grow(); + + assignment.new_checkpoint(); + let removed = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + assert!(removed); + let hole_position = assignment.num_trail_entries() - 1; + + let removed = assignment + .remove_range_from_domain(x, 2, 8, None, &mut notification_engine) + .expect("non-empty domain"); + assert!(removed); + + assert_eq!( + assignment.get_domain_iterator(x).collect::>(), + vec![0, 1, 9, 10] + ); + assert_eq!(assignment.get_pruned_value_count(), 7); + + // The existing hole is kept, and the range is split into the runs [2, 3] and [7, 8]. + let entries = (hole_position..assignment.num_trail_entries()) + .map(|index| { + let entry = assignment.get_trail_entry(index); + (entry.predicate, entry.range_end) + }) + .collect::>(); + assert_eq!( + entries, + vec![ + (predicate!(x != 4), Some(6)), + (predicate!(x != 2), Some(3)), + (predicate!(x != 7), Some(8)), + ] + ); + + // Each removed value is attributed to the entry which removed it. + assert_eq!( + assignment.get_trail_position(&predicate!(x != 5)), + Some(hole_position) + ); + assert_eq!( + assignment.get_trail_position(&predicate!(x != 3)), + Some(hole_position + 1) + ); + assert_eq!( + assignment.get_trail_position(&predicate!(x != 7)), + Some(hole_position + 2) + ); + assert!(!assignment.is_value_in_domain_at_trail_position(x, 7, hole_position + 2)); + assert!(assignment.is_value_in_domain_at_trail_position(x, 7, hole_position + 1)); + + let _ = assignment.synchronise(0, &mut notification_engine); + + assert_eq!( + assignment.get_domain_iterator(x).collect::>(), + (0..=10).collect::>() + ); + assert_eq!(assignment.get_pruned_value_count(), 0); + } + + #[test] + fn remove_range_at_bounds_jumps_over_adjacent_holes() { + let mut notification_engine = NotificationEngine::test_default(); + let mut assignment = Assignments::default(); + let x = assignment.grow(0, 10); + notification_engine.grow(); + + assignment.new_checkpoint(); + let _ = assignment + .remove_range_from_domain(x, 3, 4, None, &mut notification_engine) + .expect("non-empty domain"); + let _ = assignment + .remove_range_from_domain(x, 6, 7, None, &mut notification_engine) + .expect("non-empty domain"); + + let _ = assignment + .remove_range_from_domain(x, -5, 2, None, &mut notification_engine) + .expect("non-empty domain"); + assert_eq!(assignment.get_lower_bound(x), 5); + + let _ = assignment + .remove_range_from_domain(x, 8, 15, None, &mut notification_engine) + .expect("non-empty domain"); + assert_eq!(assignment.get_upper_bound(x), 5); + + let _ = assignment.synchronise(0, &mut notification_engine); + + assert_eq!(assignment.get_lower_bound(x), 0); + assert_eq!(assignment.get_upper_bound(x), 10); + assert_eq!(assignment.get_domain_iterator(x).count(), 11); + assert_eq!(assignment.get_pruned_value_count(), 0); + } + + #[test] + fn remove_range_of_removed_values_does_nothing() { + let mut notification_engine = NotificationEngine::test_default(); + let mut assignment = Assignments::default(); + let x = assignment.grow(0, 10); + notification_engine.grow(); + + assignment.new_checkpoint(); + let _ = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + let num_trail_entries = assignment.num_trail_entries(); + + let removed = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + assert!(!removed); + let removed = assignment + .remove_range_from_domain(x, 11, 20, None, &mut notification_engine) + .expect("non-empty domain"); + assert!(!removed); + + assert_eq!(assignment.num_trail_entries(), num_trail_entries); + } + + #[test] + fn remove_range_emptying_domain_ends_with_single_value_removal() { + let mut notification_engine = NotificationEngine::test_default(); + let mut assignment = Assignments::default(); + let x = assignment.grow(0, 10); + notification_engine.grow(); + + assignment.new_checkpoint(); + let _ = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + let num_trail_entries = assignment.num_trail_entries(); + + let result = assignment.remove_range_from_domain(x, -5, 20, None, &mut notification_engine); + assert!(result.is_err()); + + let entries = (num_trail_entries..assignment.num_trail_entries()) + .map(|index| { + let entry = assignment.get_trail_entry(index); + (entry.predicate, entry.range_end) + }) + .collect::>(); + assert_eq!( + entries, + vec![ + (predicate!(x != 0), Some(3)), + (predicate!(x != 7), Some(9)), + (predicate!(x != 10), None), + ] + ); + } } diff --git a/pumpkin-crates/core/src/engine/debug_helper.rs b/pumpkin-crates/core/src/engine/debug_helper.rs index 6704a156d..b14c35dcf 100644 --- a/pumpkin-crates/core/src/engine/debug_helper.rs +++ b/pumpkin-crates/core/src/engine/debug_helper.rs @@ -179,15 +179,19 @@ impl DebugHelper { &mut reason, ); - result &= Self::debug_propagator_reason( - trail_entry.predicate, - &reason, - trailed_values, - assignments, - &propagators[propagator_id], - propagator_id, - notification_engine, - ); + // A trail entry which removes a range of values propagates a disequality predicate + // for every removed value. + for propagated in trail_entry.propagated_predicates() { + result &= Self::debug_propagator_reason( + propagated, + &reason, + trailed_values, + assignments, + &propagators[propagator_id], + propagator_id, + notification_engine, + ); + } } result } diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index 68eb8d186..8e413ec1f 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -304,9 +304,8 @@ impl State { pub fn is_on_trail(&self, predicate: Predicate) -> bool { let trail_position = self.trail_position(predicate); - trail_position.is_some_and(|trail_position| { - self.assignments.trail[trail_position].predicate == predicate - }) + trail_position + .is_some_and(|trail_position| self.assignments.trail[trail_position].covers(predicate)) } /// Returns whether the trail position of the provided [`Predicate`]. @@ -754,11 +753,11 @@ impl State { &mut reason_buffer, ); - self.run_checker( - std::mem::take(&mut reason_buffer), - Some(entry.predicate), - &inference_code, - ); + // A trail entry which removes a range of values propagates a disequality predicate + // for every removed value. + for propagated in entry.propagated_predicates() { + self.run_checker(reason_buffer.clone(), Some(propagated), &inference_code); + } } } @@ -918,8 +917,9 @@ impl State { let trail_entry = self.assignments.get_trail_entry(trail_position); // We distinguish between three cases: - // 1) The predicate is explicitly present on the trail. - if trail_entry.predicate == predicate { + // 1) The predicate is explicitly present on the trail (possibly as one of the values + // removed by a trail entry which removes a range of values). + if trail_entry.covers(predicate) { let reason_ref = trail_entry.reason?; let explanation_context = ExplanationContext::new( @@ -1193,6 +1193,7 @@ mod tests { use crate::conjunction; use crate::containers::StorageKey; use crate::declare_inference_label; + use crate::engine::cp::reason::StoredReason; use crate::predicate; use crate::proof::InferenceCode; use crate::state::CurrentNogood; @@ -1241,4 +1242,45 @@ mod tests { assert_eq!(state.statistics.sum_of_backjumps, 0); assert_eq!(state.statistics.num_backjumps, 0); } + + #[test] + fn values_removed_by_range_are_explained_by_its_reason() { + let mut state = State::default(); + let y = state.new_interval_variable(0, 10, None); + let x = state.new_interval_variable(0, 10, None); + + let tag = state.new_constraint_tag(); + let slot = state.reason_store.new_slot(); + let removed = state + .assignments + .remove_range_from_domain( + x, + 0, + 3, + Some(slot.reason_ref()), + &mut state.notification_engine, + ) + .expect("non-empty domain"); + assert!(removed); + let _ = slot.populate( + PropagatorId::create_from_index(0), + StoredReason::Eager(conjunction!([y >= 5]), InferenceCode::new(tag, TestLabel)), + ); + + // A value inside the range is explicitly on the trail, with the reason of the range. + assert!(state.is_on_trail(predicate!(x != 2))); + let mut buffer = vec![]; + let inference_code = + state.get_propagation_reason(predicate!(x != 2), &mut buffer, CurrentNogood::empty()); + assert!(inference_code.is_some()); + assert_eq!(buffer, vec![predicate!(y >= 5)]); + + // The lower-bound which was raised by the range is explained using the last removed + // value. + let mut buffer = vec![]; + let inference_code = + state.get_propagation_reason(predicate!(x >= 4), &mut buffer, CurrentNogood::empty()); + assert!(inference_code.is_none()); + assert_eq!(buffer, vec![predicate!(x >= 3), predicate!(x != 3)]); + } } diff --git a/pumpkin-crates/core/src/propagation/contexts/explanation_context.rs b/pumpkin-crates/core/src/propagation/contexts/explanation_context.rs index 419825f89..40de7c24a 100644 --- a/pumpkin-crates/core/src/propagation/contexts/explanation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/explanation_context.rs @@ -85,6 +85,12 @@ impl<'a> ExplanationContext<'a> { } /// Returns the [`Predicate`] which is being explained. + /// + /// If the propagation removed a range of values (see [`PropagationContext::remove_range`]), + /// then this is the disequality predicate for the first removed value; the explanation should + /// explain the removal of the whole range. + /// + /// [`PropagationContext::remove_range`]: crate::propagation::PropagationContext::remove_range pub fn get_predicate_to_be_explained(&self) -> Predicate { self.assignments .get_trail_entry(self.trail_position) diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index 7294b99fe..d1d7f025a 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -288,6 +288,58 @@ impl PropagationContext<'_> { } } } + + /// Removes the values `start..=end` (both inclusive) from the domain of `domain_id`, i.e., + /// it sets the predicates `[domain_id != v]` for all `start <= v <= end` to true, with the + /// provided reason. + /// + /// The values which are not in the domain are skipped, and every maximal run of consecutive + /// values which are in the domain is removed using a single trail entry; all of these share + /// the provided reason, which should thus explain the removal of the whole range. + /// + /// If the domain becomes empty, then the [`EmptyDomainConflict`] error is returned. At that + /// point, no-more propagation should happen. + pub fn remove_range( + &mut self, + domain_id: DomainId, + start: i32, + end: i32, + reason: impl Into, + ) -> Result<(), EmptyDomainConflict> { + let slot = self.reason_store.new_slot(); + + let modification_result = self.assignments.remove_range_from_domain( + domain_id, + start, + end, + Some(slot.reason_ref()), + self.notification_engine, + ); + + match modification_result { + Ok(false) => Ok(()), + Ok(true) => { + let _ = slot.populate( + self.propagator_id, + build_reason(reason, self.reification_literal), + ); + Ok(()) + } + Err(EmptyDomain) => { + let _ = slot.populate( + self.propagator_id, + build_reason(reason, self.reification_literal), + ); + let (trigger_predicate, trigger_reason) = + self.assignments.remove_last_trail_element(); + + Err(EmptyDomainConflict { + trigger_predicate, + trigger_reason: Some(trigger_reason), + }) + } + } + } } pub(crate) fn build_reason( From cb7359e550c8702fb7abf4a646245407b6ed9bc3 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 10:56:29 +0100 Subject: [PATCH 03/18] fix: small assertion error + adding more docs --- pumpkin-crates/core/src/engine/state.rs | 74 ++++++++- .../contexts/propagation_context.rs | 155 ++++++++++++++++-- .../propagators/nogoods/nogood_propagator.rs | 50 ++++-- .../time_table/propagation_handler.rs | 146 ++++++++++------- .../cumulative/time_table/test_suite.rs | 40 +++++ 5 files changed, 376 insertions(+), 89 deletions(-) diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index 8e413ec1f..ce23da96b 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -1124,7 +1124,12 @@ impl State { // creating a hole cannot result in the upper bound being lower to the // hole, there must be some other reason for that to happen, which we would // find earlier. - pumpkin_assert_simple!(input_upper_bound < not_equal_constant); + // + // If the trail entry removed a range of values `not_equal_constant..=end`, + // then the upper bound was lowered below `not_equal_constant`, so any + // upper-bound smaller than `end` became true at this trail entry. + let last_removed_value = trail_entry.range_end.unwrap_or(not_equal_constant); + pumpkin_assert_simple!(input_upper_bound < last_removed_value); // The reason for the input predicate [x <= a] is computed recursively as // the reason for [x <= a + 1] & [x != a + 1]. @@ -1196,9 +1201,11 @@ mod tests { use crate::engine::cp::reason::StoredReason; use crate::predicate; use crate::proof::InferenceCode; + use crate::propagation::PropagationContext; use crate::state::CurrentNogood; use crate::state::PropagatorId; use crate::state::State; + use crate::variables::TransformableVariable; declare_inference_label!(TestLabel); @@ -1283,4 +1290,69 @@ mod tests { assert!(inference_code.is_none()); assert_eq!(buffer, vec![predicate!(x >= 3), predicate!(x != 3)]); } + + #[test] + fn upper_bound_lowered_by_range_is_explained_by_removed_values() { + let mut state = State::default(); + let x = state.new_interval_variable(0, 10, None); + + let tag = state.new_constraint_tag(); + let slot = state.reason_store.new_slot(); + let removed = state + .assignments + .remove_range_from_domain( + x, + 7, + 10, + Some(slot.reason_ref()), + &mut state.notification_engine, + ) + .expect("non-empty domain"); + assert!(removed); + let _ = slot.populate( + PropagatorId::create_from_index(0), + StoredReason::Eager(conjunction!(), InferenceCode::new(tag, TestLabel)), + ); + + // The range [7, 10] lowered the upper-bound to 6; an upper-bound within the range is + // explained using the next removed value. + let mut buffer = vec![]; + let inference_code = + state.get_propagation_reason(predicate!(x <= 8), &mut buffer, CurrentNogood::empty()); + assert!(inference_code.is_none()); + assert_eq!(buffer, vec![predicate!(x <= 9), predicate!(x != 9)]); + } + + #[test] + fn remove_range_of_view_removes_range_of_underlying_domain() { + let mut state = State::default(); + let x = state.new_interval_variable(0, 10, None); + let tag = state.new_constraint_tag(); + let inference_code = InferenceCode::new(tag, TestLabel); + let num_trail_entries = state.assignments.num_trail_entries(); + + let mut context = PropagationContext::new( + &mut state.trailed_values, + &mut state.assignments, + &mut state.reason_store, + &mut state.notification_engine, + PropagatorId::create_from_index(0), + ); + // The values -9..=-3 of -2 * x correspond to the values 2..=4 of x. + context + .remove_range(&x.scaled(-2), -9, -3, (conjunction!(), &inference_code)) + .expect("non-empty domain"); + // A constant is not a view over a domain; removing values other than the constant has no + // effect. + context + .remove_range(&5, 6, 10, (conjunction!(), &inference_code)) + .expect("non-empty domain"); + + assert_eq!( + state.assignments.get_domain_iterator(x).collect::>(), + vec![0, 1, 5, 6, 7, 8, 9, 10] + ); + // The range is removed using a single trail entry. + assert_eq!(state.assignments.num_trail_entries(), num_trail_entries + 1); + } } diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index d1d7f025a..b11dc21c6 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -8,6 +8,7 @@ use crate::engine::TrailedValues; use crate::engine::notifications::NotificationEngine; use crate::engine::notifications::Watchers; use crate::engine::predicates::predicate::Predicate; +use crate::engine::predicates::predicate::PredicateType; use crate::engine::reason::Reason; use crate::engine::reason::ReasonStore; use crate::engine::reason::StoredReason; @@ -289,35 +290,153 @@ impl PropagationContext<'_> { } } - /// Removes the values `start..=end` (both inclusive) from the domain of `domain_id`, i.e., - /// it sets the predicates `[domain_id != v]` for all `start <= v <= end` to true, with the - /// provided reason. + /// Removes the values `start..=end` (both inclusive) from the domain of `var`, i.e., it sets + /// the predicates `[var != v]` for all `start <= v <= end` to true, with the provided reason. /// - /// The values which are not in the domain are skipped, and every maximal run of consecutive - /// values which are in the domain is removed using a single trail entry; all of these share - /// the provided reason, which should thus explain the removal of the whole range. + /// This is equivalent to calling [`PropagationContext::post`] with `[var != v]` for every + /// value `v` in the range (with the same reason), but it is cheaper: the removed values are + /// stored as a range, rather than one value at a time. /// + /// # Reason + /// A single reason is stored for the whole range, and it is used to explain every removed + /// value. Hence, the reason should imply `[var != v]` for *every* `start <= v <= end`, not just + /// for some of them. During conflict analysis, the explanation of `[var != v]` for any value + /// `v` in the range is this reason. + /// + /// # Values outside of the domain + /// The range does not need to be within the domain of `var`: + /// - Values outside of the bounds of `var` are ignored. + /// - Values which have already been removed (holes) are skipped; these keep their original + /// reason. + /// + /// If none of the values are in the domain, then this method does nothing. + /// + /// # Trail entries + /// If `var` is a domain or an affine view over a domain, then the range is translated to a + /// range of the underlying domain, and every maximal run of consecutive values of the + /// underlying domain which are removed uses a single trail entry (see the examples below). + /// Otherwise (e.g., for constants), the values are removed one by one. All of the trail + /// entries share the provided reason. + /// + /// # Empty domains /// If the domain becomes empty, then the [`EmptyDomainConflict`] error is returned. At that - /// point, no-more propagation should happen. - pub fn remove_range( + /// point, no-more propagation should happen. The trigger of the conflict is the removal of + /// the last value in the domain (i.e., the predicate `[x != v]` where `v` is the largest value + /// in the domain of the underlying domain `x`), as is the case when posting a disequality + /// predicate which empties the domain. + /// + /// # Examples + /// Removing a range which contains an existing hole; the range is split into the runs of + /// values which are still in the domain: + /// ```text + /// x in {0, 1, 2, 3, 7, 8, 9, 10} (i.e., [0, 10] with the hole [4, 6]) + /// remove_range(&x, 2, 8, reason) + /// x in {0, 1, 9, 10} (trail entries: [2, 3] and [7, 8]) + /// ``` + /// + /// Removing a range which partially lies outside of the bounds; this moves the lower-bound: + /// ```text + /// x in [0, 10] + /// remove_range(&x, -5, 3, reason) + /// x in [4, 10] (trail entry: [0, 3]) + /// ``` + /// + /// Removing a range of an affine view; the values of the view `y = 2x + 1` in `[4, 9]` (i.e., + /// 5, 7, and 9) correspond to the values `[2, 4]` of `x`: + /// ```text + /// x in [0, 10], y = 2x + 1 + /// remove_range(&y, 4, 9, reason) + /// x in {0, 1, 5, 6, 7, 8, 9, 10} (trail entry: [2, 4] of x) + /// ``` + /// + /// Removing a range which contains all values in the domain: + /// ```text + /// x in [3, 5] + /// remove_range(&x, 0, 10, reason) (returns an `EmptyDomainConflict` triggered by + /// [x != 5]; the values [3, 4] are removed with the + /// provided reason) + /// ``` + pub fn remove_range( &mut self, - domain_id: DomainId, + var: &Var, start: i32, end: i32, reason: impl Into, ) -> Result<(), EmptyDomainConflict> { + // For a domain (or an affine view over a domain), the values `start..=end` of `var` + // correspond to the values of the underlying domain which satisfy both of these + // predicates; one is a lower-bound and the other is an upper-bound predicate over the + // underlying domain (which are swapped if the view has a negative scale). + // + // For example: + // - For the domain `x`, these are `[x >= start]` and `[x <= end]`. + // - For the view `y = 2x + 1` with `start = 4` and `end = 9`, these are `[x >= 2]` (since + // `2x + 1 >= 4` iff `x >= 1.5`) and `[x <= 4]`. + // - For the view `y = -x` with `start = -8` and `end = -5`, these are `[x <= 8]` and `[x >= + // 5]`; note that the lower-bound of `y` becomes an upper-bound of `x`. + // - For a constant, these are trivially true or false predicates, which are neither + // lower-bound nor upper-bound predicates; there is no underlying domain in that case. + let lower = var.lower_bound_predicate(start); + let upper = var.upper_bound_predicate(end); + let range_of_underlying_domain = + match (lower.get_predicate_type(), upper.get_predicate_type()) { + (PredicateType::LowerBound, PredicateType::UpperBound) => { + Some((lower.get_right_hand_side(), upper.get_right_hand_side())) + } + (PredicateType::UpperBound, PredicateType::LowerBound) => { + Some((upper.get_right_hand_side(), lower.get_right_hand_side())) + } + _ => None, + } + .filter(|_| lower.get_domain() == upper.get_domain()); + + // We reserve a slot for the reason up front, since the trail entries need to refer to it; + // the reason itself is only stored if a value was actually removed (see below). let slot = self.reason_store.new_slot(); - let modification_result = self.assignments.remove_range_from_domain( - domain_id, - start, - end, - Some(slot.reason_ref()), - self.notification_engine, - ); + let modification_result = if let Some((range_start, range_end)) = range_of_underlying_domain + { + // The values of the underlying domain are removed as runs of consecutive values, + // skipping the values which are not in the domain. + self.assignments.remove_range_from_domain( + lower.get_domain(), + range_start, + range_end, + Some(slot.reason_ref()), + self.notification_engine, + ) + } else { + // Otherwise (e.g., for constants), we remove the values within the bounds one by one, + // all sharing the same reason. We only go over the values within the bounds of `var` + // to avoid iterating over a (potentially large) range of values which are not in the + // domain anyway. + let first_value = start.max(var.lower_bound(self.assignments)); + let last_value = end.min(var.upper_bound(self.assignments)); + + let mut modification_result = Ok(false); + for value in first_value..=last_value { + match self.assignments.post_predicate( + var.disequality_predicate(value), + Some(slot.reason_ref()), + self.notification_engine, + ) { + Ok(true) => modification_result = Ok(true), + Ok(false) => {} + Err(empty_domain) => { + modification_result = Err(empty_domain); + break; + } + } + } + modification_result + }; match modification_result { + // None of the values were in the domain, so no trail entry refers to the slot and the + // reason does not need to be stored. Ok(false) => Ok(()), + // At least one value was removed; the trail entries refer to the slot, so we store + // the reason. Ok(true) => { let _ = slot.populate( self.propagator_id, @@ -325,6 +444,10 @@ impl PropagationContext<'_> { ); Ok(()) } + // The domain became empty. The values removed before the last one stay on the trail + // (they are valid propagations with the provided reason), while the removal of the + // last value is undone and reported as the trigger of the conflict, as is done in + // `PropagationContext::post`. Err(EmptyDomain) => { let _ = slot.populate( self.propagator_id, diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index 9a80677d6..bd2dd7742 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -1005,20 +1005,26 @@ impl NogoodPropagator { // upper-bound of the range to start iterating over. // // - // Hence, we iterate over the range that we have created, removing the values while *not* - // removing the values for which there is an inequality predicate. - - // The reason consists of: - // 1) All predicates which reason over a different domain than the propagated predicate - // (which are all guaranteed to be satisfied) - for value_in_domain in lb..=ub { - if !exceptions.contains(&value_in_domain) - && context.contains(&propagated_domain, value_in_domain) - { - propagated = true; - statistics - .extended_propagation_statistics - .num_extended_disequality_propagations += 1; + // Hence, we remove the values in the range that we have created, while *not* removing the + // values for which there is an inequality predicate (the exceptions). Every gap between + // two consecutive exceptions is removed as a single range; the values in a gap which are + // not in the domain anymore are skipped. + let mut sorted_exceptions = exceptions + .into_iter() + .filter(|&exception| lb <= exception && exception <= ub) + .collect::>(); + sorted_exceptions.sort_unstable(); + + let mut gap_start = lb; + for gap_end in sorted_exceptions + .iter() + .map(|exception| exception - 1) + .chain(std::iter::once(ub)) + { + if gap_start <= gap_end { + // The reason consists of: + // 1) All predicates which reason over a different domain than the propagated + // predicate (which are all guaranteed to be satisfied) let reason = if let Some(nogood_id) = nogood_id { Reason::DynamicLazy( LazyNogoodExplanation::new() @@ -1040,14 +1046,26 @@ impl NogoodPropagator { ) .into() }; - let result = context.post(predicate!(propagated_domain != value_in_domain), reason); + + let num_trail_entries_before = context.trail_position(); + let result = context.remove_range(&propagated_domain, gap_start, gap_end, reason); if result.is_err() { statistics .extended_propagation_statistics .num_variables_propagated += 1; } - result? + result?; + + if context.trail_position() > num_trail_entries_before { + propagated = true; + statistics + .extended_propagation_statistics + .num_extended_disequality_propagations += 1; + } } + + // The next gap starts after the exception. + gap_start = gap_end + 2; } if propagated { diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs index deed41bc3..48d26ccb5 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs @@ -376,65 +376,99 @@ impl CumulativePropagationHandler { profile.end, ); - for time_point in lower_bound_removed_time_points..=upper_bound_removed_time_points { - if !context.contains(&propagating_task.start_variable, time_point) { - continue; - } + match self.explanation_type { + CumulativeExplanationType::Naive | CumulativeExplanationType::BigStep => { + // We use the same procedure for the explanation using naive and bigstep, note + // that `create_profile_explanation` uses the explanation type to create the + // explanations. + // + // This explanation does not depend on the removed time-point, so all of the + // time-points are removed at once using the same explanation. + if lower_bound_removed_time_points > upper_bound_removed_time_points { + return Ok(()); + } - match self.explanation_type { - CumulativeExplanationType::Naive | CumulativeExplanationType::BigStep => { - // We use the same procedure for the explanation using naive and bigstep, note - // that `create_profile_explanation` uses the - // explanation type to create the explanations. - let explanation = self.create_profile_explanation( - context, - profile, - capacity, - propagating_task, + let explanation = + self.create_profile_explanation(context, profile, capacity, propagating_task); + // The explanation is checked for every time-point which is removed (i.e., which is + // still in the domain). + pumpkin_assert_extreme!({ + let mut explanation_is_valid = true; + for time_point in + lower_bound_removed_time_points..=upper_bound_removed_time_points + { + if context.contains(&propagating_task.start_variable, time_point) { + explanation_is_valid &= check_explanation( + predicate![propagating_task.start_variable != time_point], + &explanation, + context.domains(), + ); + } + } + explanation_is_valid + }); + context.remove_range( + &propagating_task.start_variable, + lower_bound_removed_time_points, + upper_bound_removed_time_points, + (explanation, &self.inference_code), + )?; + } + CumulativeExplanationType::Pointwise => { + // A pointwise explanation explains that `propagating_task` cannot overlap with a + // single time-point `t` of the profile; this means that it explains the removal + // of all start times in `[t - processing_time + 1, t]`. + // + // We therefore split the time-points to remove into chunks of at most + // `processing_time` consecutive time-points, which are each removed at once using + // a single explanation point. Going from left to right, for a chunk starting at + // `chunk_start`, we pick the latest explanation point which still explains + // `chunk_start` (i.e., `chunk_start + processing_time - 1`), unless this is after + // the end of the profile. + // + // Note that the explanation point is always in the profile, since + // `chunk_start >= profile.start - processing_time + 1`. + pumpkin_assert_simple!(propagating_task.processing_time > 0); + + let mut chunk_start = lower_bound_removed_time_points; + while chunk_start <= upper_bound_removed_time_points { + let explanation_point = min( + chunk_start + propagating_task.processing_time - 1, + profile.end, ); - let predicate = predicate![propagating_task.start_variable != time_point]; - pumpkin_assert_extreme!(check_explanation( - predicate, - &explanation, - context.domains() - )); - context.post(predicate, (explanation, &self.inference_code))?; - } - CumulativeExplanationType::Pointwise => { - // We split into two cases when determining the explanation of the profile - // - Either the time-point is before the start of the profile; in which case the - // explanation for the removal of this time-point is that there is a profile - // point at the point `profile.start..time_point + - // propagating_task.processing_time - 1`. In this case, we pick the time point - // plus the processing time value until we reach the middle point of the - // profile in which case we always pick the middle point (this is an untested - // heuristic in terms of performance). - // - Or the time-point is after the start of the profile in which case the - // explanation is simply that there is a profile at this time-point (which - // together with the propagating task would overflow the capacity) - let corresponding_profile_explanation_point = if time_point < profile.start { - min( - time_point + propagating_task.processing_time - 1, - (profile.end - profile.start) / 2 + profile.start, + let chunk_end = min(explanation_point, upper_bound_removed_time_points); + + let explanation: PropositionalConjunction = + create_pointwise_propagation_explanation( + explanation_point, + profile, + capacity, + propagating_task.resource_usage, ) - } else { - time_point - }; - - let explanation = create_pointwise_propagation_explanation( - corresponding_profile_explanation_point, - profile, - capacity, - propagating_task.resource_usage, - ) - .collect(); - let predicate = predicate![propagating_task.start_variable != time_point]; - pumpkin_assert_extreme!(check_explanation( - predicate, - &explanation, - context.domains() - )); - context.post(predicate, (explanation, &self.inference_code))?; + .collect(); + // The explanation is checked for every time-point which is removed (i.e., + // which is still in the domain). + pumpkin_assert_extreme!({ + let mut explanation_is_valid = true; + for time_point in chunk_start..=chunk_end { + if context.contains(&propagating_task.start_variable, time_point) { + explanation_is_valid &= check_explanation( + predicate![propagating_task.start_variable != time_point], + &explanation, + context.domains(), + ); + } + } + explanation_is_valid + }); + context.remove_range( + &propagating_task.start_variable, + chunk_start, + chunk_end, + (explanation, &self.inference_code), + )?; + + chunk_start = chunk_end + 1; } } } diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs index 5b167fc34..ae12b0c67 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs @@ -427,6 +427,41 @@ fn propagator_propagates_with_holes() { } } +fn propagator_propagates_holes_in_chunks_with_pointwise_explanations() { + let mut state = State::default(); + let s1 = state.new_interval_variable(10, 10, None); + let s2 = state.new_interval_variable(0, 20, None); + + let options = CumulativePropagatorOptions { + allow_holes_in_domain: true, + explanation_type: CumulativeExplanationType::Pointwise, + ..Default::default() + }; + add_propagator::

(&mut state, &[(s1, 5, 1), (s2, 4, 1)], 1, options).expect("No conflict"); + state.assert_bounds(s2, 0, 20); + + // The profile [10, 14] removes the start times [7, 14] of s2; the chunk [7, 10] is explained + // by the time-point 10 of the profile. + for removed in 7..=10 { + assert!(!state.contains(s2, removed)); + assert_eq!( + conjunction!([s1 >= 6] & [s1 <= 10]), + reason_for(&mut state, predicate!(s2 != removed)) + ); + } + for removed in 11..=14 { + assert!(!state.contains(s2, removed)); + let expected = match P::STRATEGY { + // Every time-point is a separate profile, and the start time `removed` is first removed + // by the profile at the time-point `removed` + TimeTableStrategy::PerPoint => conjunction!([s1 >= removed - 4] & [s1 <= removed]), + // The chunk [11, 14] is explained by the time-point 14 of the profile + TimeTableStrategy::OverInterval => conjunction!([s1 >= 10] & [s1 <= 14]), + }; + assert_eq!(expected, reason_for(&mut state, predicate!(s2 != removed))); + } +} + fn propagator_propagates_sequence_with_gap_equal_to_processing_time() { let mut state = State::default(); let s1 = state.new_interval_variable(5, 5, None); @@ -658,6 +693,11 @@ macro_rules! time_table_tests { super::propagator_propagates_with_holes::<$propagator>() } + #[test] + fn propagator_propagates_holes_in_chunks_with_pointwise_explanations() { + super::propagator_propagates_holes_in_chunks_with_pointwise_explanations::<$propagator>() + } + #[test] fn propagator_propagates_sequence_with_gap_equal_to_processing_time() { super::propagator_propagates_sequence_with_gap_equal_to_processing_time::<$propagator>() From 13802c00d53a440ae2a75487088d258f22927289 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 11:45:13 +0100 Subject: [PATCH 04/18] refactor: small optimisations - reuse structure + checking whether any value exists in range + switching to vec view --- .../core/src/engine/cp/assignments.rs | 210 +++++++++++++----- .../contexts/propagation_context.rs | 146 +++++++----- .../time_table/propagation_handler.rs | 20 +- 3 files changed, 256 insertions(+), 120 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index cc92a0a21..a6006da0e 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -1,5 +1,3 @@ -use std::collections::BTreeMap; - use crate::basic_types::Trail; use crate::containers::KeyedVec; use crate::engine::cp::reason::ReasonRef; @@ -24,6 +22,9 @@ pub struct Assignments { domains: KeyedVec, /// The number of values that have been pruned from the domain. pruned_values: u64, + /// A buffer for the runs of values which are removed by + /// [`Assignments::remove_range_from_domain`], to avoid allocating a new vector every time. + runs_buffer: Vec<(i32, i32)>, } impl Default for Assignments { @@ -33,6 +34,7 @@ impl Default for Assignments { bounds: Default::default(), domains: Default::default(), pruned_values: 0, + runs_buffer: Vec::default(), }; // As a convention, we allocate a dummy domain_id=0, which represents a 0-1 variable that is @@ -329,7 +331,7 @@ impl Assignments { } // Add holes. - for (&start, piece) in &self.domains[domain_id].holes { + for &(start, piece) in &self.domains[domain_id].holes { if piece.update_info.checkpoint == 0 { continue; } @@ -357,6 +359,12 @@ impl Assignments { domain.contains(value) } + /// Returns whether any of the values `start..=end` (both inclusive) is in the domain of + /// `domain_id`. + pub(crate) fn contains_any_in_range(&self, domain_id: DomainId, start: i32, end: i32) -> bool { + self.domains[domain_id].contains_any_in_range(start, end) + } + pub(crate) fn is_value_in_domain_at_trail_position( &self, domain_id: DomainId, @@ -634,15 +642,17 @@ impl Assignments { let empties_domain = first == lower_bound_before && last == upper_bound_before; let last_of_runs = if empties_domain { last - 1 } else { last }; - let mut removal_took_place = false; - let mut from = first; - while let Some((run_start, run_end)) = - self.domains[domain_id].next_run_in_domain(from, last_of_runs) - { + // We first determine all of the runs (since the domain cannot be updated while going over + // its holes), and then remove them. + let mut runs = std::mem::take(&mut self.runs_buffer); + runs.clear(); + self.domains[domain_id].runs_in_domain(first, last_of_runs, &mut runs); + + let removal_took_place = !runs.is_empty(); + for &(run_start, run_end) in &runs { self.remove_run(domain_id, run_start, run_end, reason)?; - removal_took_place = true; - from = run_end + 1; } + self.runs_buffer = runs; if empties_domain { self.remove_run(domain_id, last, last, reason)?; @@ -1077,11 +1087,15 @@ struct IntegerDomain { /// Auxiliary data structure to make it easy to check if a value is present or not. /// This is done to avoid going through 'hole_updates'. /// - /// Each entry is a piece of consecutive values which were removed by a single removal; it maps - /// the first value of the piece to the last value of the piece and the decision level and - /// trail position of the removal. The pieces are disjoint, but pieces are not merged when they - /// are adjacent, so that the time of removal is known for every value. - holes: BTreeMap, + /// Each entry is a piece of consecutive values which were removed by a single removal; it + /// consists of the first value of the piece and the [`HolePiece`] (containing the last value + /// of the piece and the decision level and trail position of the removal). The pieces are + /// disjoint, but pieces are not merged when they are adjacent, so that the time of removal is + /// known for every value. + /// + /// The entries are sorted by their first value, such that the piece containing a value can be + /// found using binary search. + holes: Vec<(i32, HolePiece)>, // Records the trail entry at which all of the root bounds are true initial_bounds_below_trail: usize, /// The holes that exist in the input problem. @@ -1210,12 +1224,23 @@ impl IntegerDomain { IntegerDomainIterator::new(self) } + /// Returns the index (in [`IntegerDomain::holes`]) of the first piece which starts after + /// `value`; the piece before it (if any) is the last piece which starts at or before `value`. + fn index_of_first_piece_after(&self, value: i32) -> usize { + self.holes + .partition_point(|&(piece_start, _)| piece_start <= value) + } + + /// Returns the start and the removed piece which contains `value`, if any. + fn piece_containing(&self, value: i32) -> Option<(i32, HolePiece)> { + let index = self.index_of_first_piece_after(value).checked_sub(1)?; + let (piece_start, piece) = self.holes[index]; + (value <= piece.end).then_some((piece_start, piece)) + } + /// Returns the removed piece which contains `value`, if any. fn hole_containing(&self, value: i32) -> Option { - self.holes - .range(..=value) - .next_back() - .and_then(|(_, piece)| (value <= piece.end).then_some(*piece)) + self.piece_containing(value).map(|(_, piece)| piece) } fn is_hole(&self, value: i32) -> bool { @@ -1270,10 +1295,7 @@ impl IntegerDomain { pumpkin_assert_moderate!(start <= end); pumpkin_assert_moderate!(self.lower_bound() <= start && end <= self.upper_bound()); pumpkin_assert_moderate!( - self.holes - .range(..=end) - .next_back() - .is_none_or(|(_, piece)| piece.end < start), + (start..=end).all(|value| !self.is_hole(value)), "the removed values should not overlap with a hole" ); @@ -1286,17 +1308,22 @@ impl IntegerDomain { }); // Note that it is important to remove the hole now, // because the later if statements may use the holes. - let old_none_entry = self.holes.insert( - start, - HolePiece { - end, - update_info: PairDecisionLevelTrailPosition { - checkpoint, - trail_position, + // The piece is inserted at its sorted position; since it does not overlap with any other + // piece, all pieces before this position end before `start`. + let index = self.index_of_first_piece_after(start); + self.holes.insert( + index, + ( + start, + HolePiece { + end, + update_info: PairDecisionLevelTrailPosition { + checkpoint, + trail_position, + }, }, - }, + ), ); - pumpkin_assert_moderate!(old_none_entry.is_none()); // Check if removing the values triggers a lower bound update. if self.lower_bound() == start { @@ -1316,30 +1343,71 @@ impl IntegerDomain { } } - /// Returns the first maximal run `[run_start, run_end]` of consecutive values in the domain - /// with `from <= run_start` and `run_end <= to`, if there is any. + /// Returns whether any of the values `from..=to` is in the domain. /// - /// Both `from` and `to` should be within the bounds of the domain. - fn next_run_in_domain(&self, from: i32, to: i32) -> Option<(i32, i32)> { - // Skip the removed piece containing `from`; pieces can be adjacent, so this may skip - // several pieces. - let mut run_start = from; - while let Some(piece) = self.hole_containing(run_start) { - run_start = piece.end + 1; + /// The first value within the bounds is in the domain unless it is in a removed piece; in + /// that case, we go over the pieces which follow it until we find a gap between two pieces + /// (or reach the end of the range). Typically, this only requires a single binary search. + fn contains_any_in_range(&self, from: i32, to: i32) -> bool { + let first = from.max(self.lower_bound()); + let last = to.min(self.upper_bound()); + if first > last { + return false; } - if run_start > to { - return None; + let index_after_first = self.index_of_first_piece_after(first); + let Some(first_piece_index) = index_after_first.checked_sub(1) else { + // There is no piece which starts at or before `first`, so `first` is not a hole. + return true; + }; + + // The value after the pieces which we have visited so far; the values before it (and + // starting from `first`) are all removed. + let mut next_value = first; + for &(piece_start, piece) in &self.holes[first_piece_index..] { + if piece_start > next_value { + // There is a gap before this piece, which contains a value in the domain. + break; + } + next_value = next_value.max(piece.end + 1); + if next_value > last { + return false; + } } - // The run ends right before the next removed piece (or at `to`). - let run_end = self - .holes - .range(run_start..=to) - .next() - .map_or(to, |(&next_piece_start, _)| next_piece_start - 1); + next_value <= last + } - Some((run_start, run_end)) + /// Adds all maximal runs `[run_start, run_end]` of consecutive values in the domain with + /// `from <= run_start` and `run_end <= to` to `runs`, in increasing order. + /// + /// This goes over the removed pieces which overlap with `from..=to` only once (in order of + /// their values), rather than looking up the pieces one by one. + fn runs_in_domain(&self, from: i32, to: i32, runs: &mut Vec<(i32, i32)>) { + // We start from the piece containing `from` (if there is one), since it determines where + // the first run starts; otherwise, we start from the first piece after `from`. + let index_after_from = self.index_of_first_piece_after(from); + let first_piece_index = match self.piece_containing(from) { + Some(_) => index_after_from - 1, + None => index_after_from, + }; + + // The start of the current run; the values in `run_start..` are not part of any piece + // which we have visited so far. + let mut run_start = from; + for &(piece_start, piece) in self.holes[first_piece_index..] + .iter() + .take_while(|&&(piece_start, _)| piece_start <= to) + { + if piece_start > run_start { + runs.push((run_start, piece_start - 1)); + } + run_start = run_start.max(piece.end + 1); + } + + if run_start <= to { + runs.push((run_start, to)); + } } fn debug_is_valid_upper_bound_domain_update( @@ -1379,11 +1447,7 @@ impl IntegerDomain { // Jump over the removed pieces which contain the upper bound; note that pieces can be // adjacent, so this may jump over several pieces. while self.lower_bound() <= self.upper_bound() - && let Some((&start, _)) = self - .holes - .range(..=self.upper_bound()) - .next_back() - .filter(|(_, piece)| self.upper_bound() <= piece.end) + && let Some((start, _)) = self.piece_containing(self.upper_bound()) { self.upper_bound_updates.last_mut().unwrap().bound = start - 1; } @@ -1482,11 +1546,11 @@ impl IntegerDomain { hole_update.start == not_equal_constant && hole_update.end == range_end ); - let removed_piece = self - .holes - .remove(&hole_update.start) - .expect("Must be present."); - pumpkin_assert_moderate!(removed_piece.end == hole_update.end); + let index = self.index_of_first_piece_after(hole_update.start) - 1; + let (removed_start, removed_piece) = self.holes.remove(index); + pumpkin_assert_moderate!( + removed_start == hole_update.start && removed_piece.end == hole_update.end + ); if hole_update.triggered_lower_bound_update { let _ = self.lower_bound_updates.pop(); @@ -1650,7 +1714,7 @@ impl IntegerDomain { pub(crate) fn get_holes(&self) -> impl Iterator + '_ { self.holes .iter() - .flat_map(|(&start, piece)| start..=piece.end) + .flat_map(|&(start, piece)| start..=piece.end) } } @@ -2635,4 +2699,28 @@ mod tests { ] ); } + + #[test] + fn contains_any_in_range_skips_adjacent_holes() { + let mut notification_engine = NotificationEngine::test_default(); + let mut assignment = Assignments::default(); + let x = assignment.grow(0, 10); + notification_engine.grow(); + + assignment.new_checkpoint(); + // The pieces [2, 3] and [4, 6] are adjacent, and [8, 8] is separated from them by 7. + for (start, end) in [(2, 3), (4, 6), (8, 8)] { + let _ = assignment + .remove_range_from_domain(x, start, end, None, &mut notification_engine) + .expect("non-empty domain"); + } + + assert!(!assignment.contains_any_in_range(x, 2, 6)); + assert!(!assignment.contains_any_in_range(x, 4, 5)); + assert!(assignment.contains_any_in_range(x, 2, 7)); + assert!(assignment.contains_any_in_range(x, 7, 8)); + assert!(!assignment.contains_any_in_range(x, 8, 8)); + assert!(assignment.contains_any_in_range(x, -5, 1)); + assert!(!assignment.contains_any_in_range(x, 11, 20)); + } } diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index b11dc21c6..4424d5d4e 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -290,6 +290,28 @@ impl PropagationContext<'_> { } } + /// Returns whether any of the values `start..=end` (both inclusive) is in the domain of `var`. + /// + /// This can be used to avoid creating a reason for [`PropagationContext::remove_range`] when + /// all of the values have already been removed. + pub fn contains_any_in_range( + &self, + var: &Var, + start: i32, + end: i32, + ) -> bool { + match range_of_underlying_domain(var, start, end) { + Some((domain_id, range_start, range_end)) => { + self.assignments + .contains_any_in_range(domain_id, range_start, range_end) + } + // Otherwise (e.g., for constants), we check the values within the bounds one by one. + None => (start.max(var.lower_bound(self.assignments)) + ..=end.min(var.upper_bound(self.assignments))) + .any(|value| var.contains(self.assignments, value)), + } + } + /// Removes the values `start..=end` (both inclusive) from the domain of `var`, i.e., it sets /// the predicates `[var != v]` for all `start <= v <= end` to true, with the provided reason. /// @@ -363,73 +385,48 @@ impl PropagationContext<'_> { end: i32, reason: impl Into, ) -> Result<(), EmptyDomainConflict> { - // For a domain (or an affine view over a domain), the values `start..=end` of `var` - // correspond to the values of the underlying domain which satisfy both of these - // predicates; one is a lower-bound and the other is an upper-bound predicate over the - // underlying domain (which are swapped if the view has a negative scale). - // - // For example: - // - For the domain `x`, these are `[x >= start]` and `[x <= end]`. - // - For the view `y = 2x + 1` with `start = 4` and `end = 9`, these are `[x >= 2]` (since - // `2x + 1 >= 4` iff `x >= 1.5`) and `[x <= 4]`. - // - For the view `y = -x` with `start = -8` and `end = -5`, these are `[x <= 8]` and `[x >= - // 5]`; note that the lower-bound of `y` becomes an upper-bound of `x`. - // - For a constant, these are trivially true or false predicates, which are neither - // lower-bound nor upper-bound predicates; there is no underlying domain in that case. - let lower = var.lower_bound_predicate(start); - let upper = var.upper_bound_predicate(end); - let range_of_underlying_domain = - match (lower.get_predicate_type(), upper.get_predicate_type()) { - (PredicateType::LowerBound, PredicateType::UpperBound) => { - Some((lower.get_right_hand_side(), upper.get_right_hand_side())) - } - (PredicateType::UpperBound, PredicateType::LowerBound) => { - Some((upper.get_right_hand_side(), lower.get_right_hand_side())) - } - _ => None, - } - .filter(|_| lower.get_domain() == upper.get_domain()); + let range_of_underlying_domain = range_of_underlying_domain(var, start, end); // We reserve a slot for the reason up front, since the trail entries need to refer to it; // the reason itself is only stored if a value was actually removed (see below). let slot = self.reason_store.new_slot(); - let modification_result = if let Some((range_start, range_end)) = range_of_underlying_domain - { - // The values of the underlying domain are removed as runs of consecutive values, - // skipping the values which are not in the domain. - self.assignments.remove_range_from_domain( - lower.get_domain(), - range_start, - range_end, - Some(slot.reason_ref()), - self.notification_engine, - ) - } else { - // Otherwise (e.g., for constants), we remove the values within the bounds one by one, - // all sharing the same reason. We only go over the values within the bounds of `var` - // to avoid iterating over a (potentially large) range of values which are not in the - // domain anyway. - let first_value = start.max(var.lower_bound(self.assignments)); - let last_value = end.min(var.upper_bound(self.assignments)); - - let mut modification_result = Ok(false); - for value in first_value..=last_value { - match self.assignments.post_predicate( - var.disequality_predicate(value), + let modification_result = + if let Some((domain_id, range_start, range_end)) = range_of_underlying_domain { + // The values of the underlying domain are removed as runs of consecutive values, + // skipping the values which are not in the domain. + self.assignments.remove_range_from_domain( + domain_id, + range_start, + range_end, Some(slot.reason_ref()), self.notification_engine, - ) { - Ok(true) => modification_result = Ok(true), - Ok(false) => {} - Err(empty_domain) => { - modification_result = Err(empty_domain); - break; + ) + } else { + // Otherwise (e.g., for constants), we remove the values within the bounds one by + // one, all sharing the same reason. We only go over the values within the bounds of + // `var` to avoid iterating over a (potentially large) range of values which are not + // in the domain anyway. + let first_value = start.max(var.lower_bound(self.assignments)); + let last_value = end.min(var.upper_bound(self.assignments)); + + let mut modification_result = Ok(false); + for value in first_value..=last_value { + match self.assignments.post_predicate( + var.disequality_predicate(value), + Some(slot.reason_ref()), + self.notification_engine, + ) { + Ok(true) => modification_result = Ok(true), + Ok(false) => {} + Err(empty_domain) => { + modification_result = Err(empty_domain); + break; + } } } - } - modification_result - }; + modification_result + }; match modification_result { // None of the values were in the domain, so no trail entry refers to the slot and the @@ -465,6 +462,39 @@ impl PropagationContext<'_> { } } +/// Returns the underlying domain of `var` and the range of its values which corresponds to the +/// values `start..=end` of `var`, if `var` is a domain or an affine view over a domain; otherwise +/// (e.g., for constants), `None` is returned. +fn range_of_underlying_domain( + var: &Var, + start: i32, + end: i32, +) -> Option<(DomainId, i32, i32)> { + // For a domain (or an affine view over a domain), the values `start..=end` of `var` + // correspond to the values of the underlying domain which satisfy both of these + // predicates; one is a lower-bound and the other is an upper-bound predicate over the + // underlying domain (which are swapped if the view has a negative scale). + // + // For example: + // - For the domain `x`, these are `[x >= start]` and `[x <= end]`. + // - For `y = 2x + 1`, `start = 4`, and `end = 9`, these are `[x >= 2]` and `[x <= 4]`. + // - For `y = -x`, `start = -8`, and `end = -5`, these are `[x <= 8]` and `[x >= 5]`. + // - For a constant, these are trivially true or false predicates (i.e., no underlying domain). + let lower = var.lower_bound_predicate(start); + let upper = var.upper_bound_predicate(end); + match (lower.get_predicate_type(), upper.get_predicate_type()) { + (PredicateType::LowerBound, PredicateType::UpperBound) => { + Some((lower.get_right_hand_side(), upper.get_right_hand_side())) + } + (PredicateType::UpperBound, PredicateType::LowerBound) => { + Some((upper.get_right_hand_side(), lower.get_right_hand_side())) + } + _ => None, + } + .filter(|_| lower.get_domain() == upper.get_domain()) + .map(|(range_start, range_end)| (lower.get_domain(), range_start, range_end)) +} + pub(crate) fn build_reason( reason: impl Into, reification_literal: Option, diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs index 48d26ccb5..b1f3d6836 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs @@ -384,7 +384,14 @@ impl CumulativePropagationHandler { // // This explanation does not depend on the removed time-point, so all of the // time-points are removed at once using the same explanation. - if lower_bound_removed_time_points > upper_bound_removed_time_points { + // + // If all of the time-points have already been removed, then we do not need to + // create the explanation. + if !context.contains_any_in_range( + &propagating_task.start_variable, + lower_bound_removed_time_points, + upper_bound_removed_time_points, + ) { return Ok(()); } @@ -438,6 +445,17 @@ impl CumulativePropagationHandler { ); let chunk_end = min(explanation_point, upper_bound_removed_time_points); + // If all of the time-points in this chunk have already been removed, then we + // do not need to create the explanation. + if !context.contains_any_in_range( + &propagating_task.start_variable, + chunk_start, + chunk_end, + ) { + chunk_start = chunk_end + 1; + continue; + } + let explanation: PropositionalConjunction = create_pointwise_propagation_explanation( explanation_point, From 99af471ce7857c80135b82139d2ffeff53ab27c1 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 11:59:17 +0100 Subject: [PATCH 05/18] refactor: build domain description during watcher scan --- .../propagators/nogoods/nogood_propagator.rs | 332 ++++++++++++------ .../propagators/nogoods/propagation_buffer.rs | 3 + .../propagators/nogoods/propagation_mode.rs | 60 ++-- 3 files changed, 263 insertions(+), 132 deletions(-) diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index bd2dd7742..089bfb1f8 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -82,6 +82,8 @@ pub struct NogoodPropagator { bumped_nogoods: Vec, /// Used to return lazy reasons temp_nogood_reason: Vec, + /// Describes the domain of the nogood which is propagated by extended nogood propagation. + domain_description: DomainDescription, /// The handle of this instance inside the solver. /// /// Used during nogood cleanup. A nogood can only be removed if it is not propagated in the @@ -191,6 +193,7 @@ impl PropagatorConstructor for NogoodPropagatorConstructor { lbd_helper: Default::default(), bumped_nogoods: Default::default(), temp_nogood_reason: Default::default(), + domain_description: Default::default(), propagation_mode: self.propagation_mode, semantic_minimiser: Default::default(), priority: self.priority, @@ -320,8 +323,11 @@ impl Propagator for NogoodPropagator { pumpkin_assert_moderate!(self.debug_is_properly_watched()); pumpkin_assert_moderate!(self.debug_is_properly_registered(&context)); - self.propagation_buffer - .propagate_buffer(&mut context, &mut self.statistics)?; + self.propagation_buffer.propagate_buffer( + &mut context, + &mut self.statistics, + &mut self.domain_description, + )?; // First we perform nogood management to ensure that the database does not grow excessively // large with "bad" nogoods @@ -401,6 +407,10 @@ impl Propagator for NogoodPropagator { // that once). let mut falsified_zeroth = None; + // The description of the domain of the 0-th predicate, which is filled in by the + // extended nogood propagation while looking for a new watcher. + self.domain_description.reset(); + // We start from the index of the last-traversed watcher and circle around after // reaching the end of the nogood to ensure that all possible watcher are // considered. @@ -412,6 +422,7 @@ impl Propagator for NogoodPropagator { &mut context, nogood_predicates, i, + &mut self.domain_description, ) { WatcherProcessingStatus::Continue => continue, WatcherProcessingStatus::FoundNewWatch => { @@ -485,13 +496,32 @@ impl Propagator for NogoodPropagator { } // Now we perform the propagation - self.propagation_mode.perform_propagation( - &mut context, - nogood_predicates, - &self.inference_codes[nogood_index], - watcher.nogood_id, - &mut self.statistics, - )?; + match self.propagation_mode { + PropagationMode::ExtendedNogoodPropagation => { + // The search for a new watcher has visited all predicates except the + // watched ones; hence, we only need to add those to the description. + self.domain_description + .complete_with_watched_predicates(&mut context, nogood_predicates); + Self::propagate_domain_description( + &mut context, + nogood_predicates, + &self.inference_codes[nogood_index], + &mut self.statistics, + Some(watcher.nogood_id), + &self.domain_description, + )?; + } + PropagationMode::UnitPropagation => { + self.propagation_mode.perform_propagation( + &mut context, + nogood_predicates, + &self.inference_codes[nogood_index], + watcher.nogood_id, + &mut self.statistics, + &mut self.domain_description, + )?; + } + } index += 1; } @@ -690,35 +720,63 @@ impl NogoodPropagator { /// For this nogood to be satisfied, we can see that [x <= 5] \/ [x >= 16] \/ [x == 12]. /// Based on this reasoning, we can remove the values {6, 7, 8, 9, 10, 11, 13, 14, 15} from the /// domain of `x`. + pub(crate) fn extended_nogood_propagation( + context: &mut PropagationContext, + nogood: &[PredicateId], + propagated_domain: DomainId, + inference_code: &InferenceCode, + statistics: &mut NogoodPropagatorStatistics, + nogood_id: Option, + domain_description: &mut DomainDescription, + ) -> Result<(), Conflict> { + let is_falsified = get_domain_info(context, nogood, propagated_domain, domain_description); + + if is_falsified { + statistics + .extended_propagation_statistics + .num_extended_propagation_calls += 1; + // The nogood is already falsified + return Ok(()); + } + + Self::propagate_domain_description( + context, + nogood, + inference_code, + statistics, + nogood_id, + domain_description, + ) + } + + /// Performs extended nogood propagation based on the provided [`DomainDescription`] of the + /// unassigned predicates in the nogood; see [`NogoodPropagator::extended_nogood_propagation`]. + /// + /// It is assumed that no predicate in the nogood is falsified, that all predicates over other + /// domains than the described one are satisfied, and that the description is complete. #[allow( clippy::filter_map_bool_then, reason = "Otherwise leads to borrow issues." )] - pub(crate) fn extended_nogood_propagation( + fn propagate_domain_description( context: &mut PropagationContext, nogood: &[PredicateId], - propagated_domain: DomainId, inference_code: &InferenceCode, statistics: &mut NogoodPropagatorStatistics, nogood_id: Option, + domain_description: &DomainDescription, ) -> Result<(), Conflict> { statistics .extended_propagation_statistics .num_extended_propagation_calls += 1; - let ( - exceptions, - lower_bound, - upper_bound, - num_describing_domain, - last_describing_predicate_id, - is_falsified, - ) = get_domain_info(context, nogood, propagated_domain); - - if is_falsified { - // The nogood is already falsified - return Ok(()); - } + let propagated_domain = domain_description + .domain + .expect("Expected the described domain to be known"); + let lower_bound = domain_description.lower_bound; + let upper_bound = domain_description.upper_bound; + let num_describing_domain = domain_description.num_describing_domain; + let exceptions = &domain_description.exceptions; if num_describing_domain == 0 { // We could not find another watcher (i.e., all predicats over other variables are @@ -751,6 +809,9 @@ impl NogoodPropagator { if num_describing_domain == 1 { statistics.num_unit_propagations += 1; + let last_describing_predicate_id = domain_description + .last_describing_predicate_id + .expect("Expected a predicate describing the domain"); let last_describing_predicate = context.get_predicate(last_describing_predicate_id); let reason = if let Some(nogood_id) = nogood_id { @@ -781,20 +842,10 @@ impl NogoodPropagator { .map_err(|e| e.into()); } - // Now we get the minimum and maximum exception values for propagation - let (min_exception, max_exception) = - exceptions - .iter() - .fold((None, None), |(min_exception, max_exception), exception| { - ( - min_exception.map_or(Some(*exception), |min_exception: i32| { - Some(min_exception.min(*exception)) - }), - max_exception.map_or(Some(*exception), |max_exception: i32| { - Some(max_exception.max(*exception)) - }), - ) - }); + // Now we get the minimum and maximum exception values for propagation; note that the + // exceptions are sorted. + let min_exception = exceptions.first().copied(); + let max_exception = exceptions.last().copied(); // Now we propagate our nogood // @@ -1009,15 +1060,15 @@ impl NogoodPropagator { // values for which there is an inequality predicate (the exceptions). Every gap between // two consecutive exceptions is removed as a single range; the values in a gap which are // not in the domain anymore are skipped. - let mut sorted_exceptions = exceptions - .into_iter() - .filter(|&exception| lb <= exception && exception <= ub) - .collect::>(); - sorted_exceptions.sort_unstable(); - + // + // Since the exceptions are sorted and contain no duplicates (see + // `DomainDescription::complete`), we start from the first exception in the range rather + // than going over all of them. + let first_exception_index = exceptions.partition_point(|&exception| exception < lb); let mut gap_start = lb; - for gap_end in sorted_exceptions + for gap_end in exceptions[first_exception_index..] .iter() + .take_while(|&&exception| exception <= ub) .map(|exception| exception - 1) .chain(std::iter::once(ub)) { @@ -1094,7 +1145,7 @@ impl NogoodPropagator { self.add_permanent_nogood(nogood, inference_code, context); self.propagation_buffer - .propagate_buffer(context, &mut self.statistics) + .propagate_buffer(context, &mut self.statistics, &mut self.domain_description) .expect("Adding asserting nogood should not lead to conflict"); return; @@ -1148,6 +1199,7 @@ impl NogoodPropagator { inference_code, nogood_id, &mut self.statistics, + &mut self.domain_description, ) .expect("Asserting nogood cannot fail"); @@ -1322,84 +1374,147 @@ impl NogoodPropagator { } } -/// Returns the following information about the unsatisfied predicates concerning the provided -/// domain: -/// 1. The values disequality values which are present in the nogood. -/// 2. The lower-bound predicate, if present. -/// 3. The upper-bound predicate, if present -/// 4. The number of elements describing the domain. -/// 5. The index of the last processed predicate of the domain. -/// 6. Whether any predicates in the nogood are satisfied. +/// Describes the unassigned predicates of a nogood which reason over a single domain; this is the +/// information required by extended nogood propagation. +#[derive(Clone, Debug, Default)] +pub(crate) struct DomainDescription { + /// The described domain; `None` if no description has been started. + domain: Option, + /// The unassigned lower-bound predicate, if present. + lower_bound: Option, + /// The unassigned upper-bound predicate, if present. + upper_bound: Option, + /// The values of the unassigned disequality predicates; these are strictly increasing once + /// the description is complete. + exceptions: Vec, + /// The number of unassigned predicates describing the domain. + num_describing_domain: usize, + /// The last added unassigned predicate describing the domain. + last_describing_predicate_id: Option, +} + +impl DomainDescription { + /// Marks the description as not started; the remaining fields are only cleared once a new + /// description is started using [`DomainDescription::start`]. + pub(crate) fn reset(&mut self) { + self.domain = None; + } + + /// Returns the described domain, starting an empty description of the domain of + /// `nogood[0]` if no description has been started. + pub(crate) fn get_or_start( + &mut self, + context: &mut PropagationContext, + nogood: &[PredicateId], + ) -> DomainId { + match self.domain { + Some(domain) => domain, + None => { + let domain = context.get_predicate(nogood[0]).get_domain(); + self.start(domain); + domain + } + } + } + + /// Starts an empty description of the provided `domain`. + fn start(&mut self, domain: DomainId) { + self.domain = Some(domain); + self.lower_bound = None; + self.upper_bound = None; + self.exceptions.clear(); + self.num_describing_domain = 0; + self.last_describing_predicate_id = None; + } + + /// Adds the provided unassigned predicate over the described domain to the description. + pub(crate) fn add_unassigned_predicate( + &mut self, + predicate_id: PredicateId, + predicate: Predicate, + ) { + pumpkin_assert_moderate!(Some(predicate.get_domain()) == self.domain); + + self.num_describing_domain += 1; + self.last_describing_predicate_id = Some(predicate_id); + match predicate.get_predicate_type() { + PredicateType::UpperBound => { + pumpkin_assert_simple!(self.upper_bound.is_none()); + self.upper_bound = Some(predicate) + } + PredicateType::LowerBound => { + pumpkin_assert_simple!(self.lower_bound.is_none()); + self.lower_bound = Some(predicate) + } + PredicateType::NotEqual => self.exceptions.push(predicate.get_right_hand_side()), + PredicateType::Equal => {} + } + } + + /// Completes a description which was created while looking for a new watcher for the watched + /// predicate at index 1, which is satisfied; all predicates except the watched ones have been + /// processed, so only the predicate at index 0 still needs to be added. + fn complete_with_watched_predicates( + &mut self, + context: &mut PropagationContext, + nogood: &[PredicateId], + ) { + pumpkin_assert_moderate!(context.is_predicate_id_satisfied(nogood[1])); + + let _ = self.get_or_start(context, nogood); + if context.evaluate_predicate_id(nogood[0]).is_none() { + let predicate = context.get_predicate(nogood[0]); + self.add_unassigned_predicate(nogood[0], predicate); + } + self.complete(); + } + + /// Completes the description by sorting the exceptions and removing duplicates. + fn complete(&mut self) { + self.exceptions.sort_unstable(); + self.exceptions.dedup(); + } +} + +/// Fills `domain_description` with the unassigned predicates concerning the provided domain and +/// returns whether any predicate in the nogood is falsified; if this is the case, then the +/// description is incomplete. fn get_domain_info( context: &mut PropagationContext<'_>, nogood: &[PredicateId], propagated_domain: DomainId, -) -> ( - HashSet, - Option, - Option, - usize, - PredicateId, - bool, -) { - // We keep track of the holes in the domains which are posted; these can be seen as - // "exceptions" to the removals of the domain - let mut exceptions: HashSet = Default::default(); - - // We need to keep track of whether there is a lower-bound and/or upper-bound predicate in - // the nogood. - let mut lower_bound = None; - let mut upper_bound = None; - - let mut num_describing_domain = 0; - let mut last_describing_predicate_id = PredicateId::create_from_index(u32::MAX as usize); - let mut is_falsified = false; + domain_description: &mut DomainDescription, +) -> bool { + domain_description.start(propagated_domain); for predicate_id in nogood.iter().copied() { - let predicate = context.get_predicate(predicate_id); + // First, we filter out all of the predicates which are currently satisfied; if a + // predicate is falsified, then no propagation can take place. + match context.evaluate_predicate_id(predicate_id) { + Some(true) => continue, + Some(false) => return true, + None => {} + } - is_falsified |= context.is_predicate_id_falsified(predicate_id); + let predicate = context.get_predicate(predicate_id); pumpkin_assert_moderate!( - predicate.get_domain() == propagated_domain - || context.is_predicate_id_satisfied(predicate_id), + predicate.get_domain() == propagated_domain, "Expected {predicate} to be unassigned with {propagated_domain:?}", ); - // First, we filter out all of the predicates which are currently satisfied and - // which are not concerning the propagated domain id - if context.is_predicate_id_satisfied(predicate_id) - || predicate.get_domain() != propagated_domain - { + // Then we filter out all of the predicates which are not concerning the propagated + // domain id + if predicate.get_domain() != propagated_domain { continue; } - // Then we add the information of the predicates to our structures - num_describing_domain += 1; - last_describing_predicate_id = predicate_id; - match predicate.get_predicate_type() { - PredicateType::UpperBound => { - pumpkin_assert_simple!(upper_bound.is_none()); - upper_bound = Some(predicate) - } - PredicateType::LowerBound => { - pumpkin_assert_simple!(lower_bound.is_none()); - lower_bound = Some(predicate) - } - PredicateType::NotEqual => { - let _ = exceptions.insert(predicate.get_right_hand_side()); - } - PredicateType::Equal => {} - } + domain_description.add_unassigned_predicate(predicate_id, predicate); } - ( - exceptions, - lower_bound, - upper_bound, - num_describing_domain, - last_describing_predicate_id, - is_falsified, - ) + + domain_description.complete(); + + false } /// Methods concerning the watchers and watch lists @@ -2061,6 +2176,7 @@ impl NogoodPropagator { inference_code, &mut NogoodPropagatorStatistics::default(), Some(nogood_id), + &mut DomainDescription::default(), )?; } } diff --git a/pumpkin-crates/core/src/propagators/nogoods/propagation_buffer.rs b/pumpkin-crates/core/src/propagators/nogoods/propagation_buffer.rs index 07ee479c0..ae380d22d 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/propagation_buffer.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/propagation_buffer.rs @@ -3,6 +3,7 @@ use crate::engine::Reason; use crate::predicates::Predicate; use crate::proof::InferenceCode; use crate::propagation::PropagationContext; +use crate::propagators::nogoods::DomainDescription; use crate::propagators::nogoods::NogoodPropagator; use crate::propagators::nogoods::NogoodPropagatorStatistics; use crate::state::Conflict; @@ -37,6 +38,7 @@ impl PropagationBuffer { &mut self, context: &mut PropagationContext, statistics: &mut NogoodPropagatorStatistics, + domain_description: &mut DomainDescription, ) -> Result<(), Conflict> { let result_unit = self .to_propagate @@ -60,6 +62,7 @@ impl PropagationBuffer { &inference_code, statistics, None, + domain_description, ) }) } diff --git a/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs b/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs index 3af210f6f..5a29a7994 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs @@ -10,6 +10,7 @@ use crate::predicates::Predicate; use crate::proof::InferenceCode; use crate::propagation::PropagationContext; use crate::propagation::ReadDomains; +use crate::propagators::nogoods::DomainDescription; use crate::propagators::nogoods::NogoodId; use crate::propagators::nogoods::NogoodInfo; use crate::propagators::nogoods::NogoodPropagator; @@ -60,38 +61,47 @@ pub enum PropagationMode { impl PropagationMode { /// Returns a [`WatcherProcessingStatus`] based on the [`Predicate`] pointed to by `index` in /// `nogood_predicates`. + /// + /// When using extended nogood propagation, the unassigned predicates over the domain of the + /// 0-th predicate are added to `domain_description`; it should be reset at the start of the + /// search for a new watcher. Note that the 0-th predicate is only replaced by a predicate over + /// the same domain, so the description remains valid. pub(crate) fn process_potential_watcher( &self, context: &mut PropagationContext, nogood_predicates: &[PredicateId], index: usize, + domain_description: &mut DomainDescription, ) -> WatcherProcessingStatus { match self { PropagationMode::ExtendedNogoodPropagation => { - // In the case of CPIP nogoods, we split into cases dependent on whether the - // predicate which we are processing reasons over the same domain. - // - // First, we store whether the current predicate reasons over the same domain as - // the predicate for which we are finding a new watcher. - let reasons_over_same_domain = - context.get_predicate(nogood_predicates[index]).get_domain() - == context.get_predicate(nogood_predicates[0]).get_domain(); - - // Next we split into several cases depending on the states of the to process - // predicate. - match context.evaluate_predicate_id(nogood_predicates[index]) { - None | Some(false) if !reasons_over_same_domain => { - // If the predicate is unassigned and does not reason over the same - // domain as the 0-th predicate, then we have found a new watch. - WatcherProcessingStatus::FoundNewWatch - } - Some(false) => { - assert!(reasons_over_same_domain); - // Otherwise, we have found a falsified predicate, and we need to - // update the zero-th predicate with this predicate. - WatcherProcessingStatus::FalsifiedZeroth - } - _ => WatcherProcessingStatus::Continue, + // In the case of CPIP nogoods, we split into cases dependent on the state of the + // predicate which we are processing and on whether it reasons over the same domain + // as the predicate for which we are finding a new watcher. + let value = context.evaluate_predicate_id(nogood_predicates[index]); + + // A satisfied predicate can never be a new watcher, regardless of its domain. + if value == Some(true) { + return WatcherProcessingStatus::Continue; + } + + let zeroth_domain = domain_description.get_or_start(context, nogood_predicates); + let predicate = context.get_predicate(nogood_predicates[index]); + + if predicate.get_domain() != zeroth_domain { + // If the predicate is unassigned or falsified and does not reason over the + // same domain as the 0-th predicate, then we have found a new watch. + WatcherProcessingStatus::FoundNewWatch + } else if value == Some(false) { + // Otherwise, we have found a falsified predicate over the same domain, and we + // need to update the zero-th predicate with this predicate. + WatcherProcessingStatus::FalsifiedZeroth + } else { + // The predicate is unassigned and reasons over the same domain, which is + // required in case extended nogood propagation takes place. + domain_description + .add_unassigned_predicate(nogood_predicates[index], predicate); + WatcherProcessingStatus::Continue } } PropagationMode::UnitPropagation => { @@ -149,6 +159,7 @@ impl PropagationMode { inference_code: &InferenceCode, nogood_id: NogoodId, statistics: &mut NogoodPropagatorStatistics, + domain_description: &mut DomainDescription, ) -> PropagationStatusCP { match self { PropagationMode::ExtendedNogoodPropagation => { @@ -160,6 +171,7 @@ impl PropagationMode { inference_code, statistics, Some(nogood_id), + domain_description, )?; } PropagationMode::UnitPropagation => { From 0a5bc584dd98c75103b290df123ced7fae991924 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Mon, 30 Nov 2026 13:16:59 +0100 Subject: [PATCH 06/18] refactor: avoid recomputation --- .../src/resolvers/analysis_mode.rs | 6 +- .../src/resolvers/resolution_resolver.rs | 14 +++-- .../src/resolvers/working_nogood.rs | 63 ++++++++++++------- .../conflict_analysis_context.rs | 58 +++++++++++++++-- .../core/src/engine/cp/assignments.rs | 21 ++++++- pumpkin-crates/core/src/engine/state.rs | 55 +++++++++++++--- 6 files changed, 175 insertions(+), 42 deletions(-) diff --git a/pumpkin-crates/conflict-resolvers/src/resolvers/analysis_mode.rs b/pumpkin-crates/conflict-resolvers/src/resolvers/analysis_mode.rs index 1593ea968..7863ff93b 100644 --- a/pumpkin-crates/conflict-resolvers/src/resolvers/analysis_mode.rs +++ b/pumpkin-crates/conflict-resolvers/src/resolvers/analysis_mode.rs @@ -133,7 +133,11 @@ impl AnalysisMode { // We first calculate the value in the heap of the new_predicate, and retrieve the // predicate which is currently the next to be resolved upon (i.e., the maximum in the // heap). - let heap_value = get_heap_value(new_predicate, context); + let trail_position = context + .get_state() + .trail_position(new_predicate) + .expect("Predicate should be true during conflict analysis"); + let heap_value = get_heap_value(new_predicate, trail_position, context); let max = working_nogood.peek_max_current_checkpoint(); // Then we check whether `new_predicate` would *not* be the next predicate to be resolved diff --git a/pumpkin-crates/conflict-resolvers/src/resolvers/resolution_resolver.rs b/pumpkin-crates/conflict-resolvers/src/resolvers/resolution_resolver.rs index 3405d18bc..eb9bbd39a 100644 --- a/pumpkin-crates/conflict-resolvers/src/resolvers/resolution_resolver.rs +++ b/pumpkin-crates/conflict-resolvers/src/resolvers/resolution_resolver.rs @@ -206,15 +206,17 @@ impl ResolutionResolver { // // This is done in two steps: // 1) Pop the predicate last assigned on the trail from the nogood. - let next_predicate = self + let (next_predicate, trail_position) = self .working_nogood .pop_max_predicate(&self.predicate_id_generator, self.mode); - // 2) Get the reason for the predicate and add it to the nogood. + // 2) Get the reason for the predicate and add it to the nogood; the trail position is + // already known from the heap, so it does not need to be looked up again. self.reason_buffer.clear(); - let _ = context.get_propagation_reason( + let _ = context.get_propagation_reason_at( next_predicate, + trail_position, self.working_nogood .get_current_nogood(&self.predicate_id_generator), &mut self.reason_buffer, @@ -546,7 +548,8 @@ mod tests { assert_eq!( resolver .working_nogood - .pop_max_predicate(&resolver.predicate_id_generator, mode), + .pop_max_predicate(&resolver.predicate_id_generator, mode) + .0, predicate!(z >= 5) ); @@ -620,7 +623,8 @@ mod tests { assert_eq!( resolver .working_nogood - .pop_max_predicate(&resolver.predicate_id_generator, mode), + .pop_max_predicate(&resolver.predicate_id_generator, mode) + .0, predicate!(z >= 5) ); assert!(!mode.should_continue_resolving( diff --git a/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs b/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs index f20658756..485c3eee1 100644 --- a/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs +++ b/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs @@ -1,4 +1,5 @@ use pumpkin_core::asserts::pumpkin_assert_eq_simple; +use pumpkin_core::asserts::pumpkin_assert_moderate; use pumpkin_core::asserts::pumpkin_assert_simple; use pumpkin_core::conflict_resolving::ConflictAnalysisContext; use pumpkin_core::containers::HashMap; @@ -88,9 +89,13 @@ impl WorkingNogood { } /// Adds a predicate to the current working nogood which is from the current checkpoint. + /// + /// The `trail_position` is the trail position of the `predicate` (see + /// `State::trail_position`). fn add_predicate_current_checkpoint( &mut self, predicate: Predicate, + trail_position: usize, context: &mut ConflictAnalysisContext<'_>, predicate_id_generator: &mut PredicateIdGenerator, mode: AnalysisMode, @@ -110,7 +115,7 @@ impl WorkingNogood { } // We first retrieve the value that the predicate will get in the heap - let heap_value = get_heap_value(predicate, context); + let heap_value = get_heap_value(predicate, trail_position, context); // Next, we restore the key in the heap self.to_process_heap.restore_key(predicate_id); @@ -354,7 +359,7 @@ impl WorkingNogood { // which the extended UIP is calculated, this could be multiple elements. let mut previous_predicate: Option = None; while self.num_current_checkpoint() > 0 { - let predicate = self.pop_max_predicate(predicate_id_generator, mode); + let (predicate, _) = self.pop_max_predicate(predicate_id_generator, mode); pumpkin_assert_eq_simple!( previous_predicate.unwrap_or(predicate).get_domain(), @@ -389,14 +394,25 @@ impl WorkingNogood { } } - /// Returns the next [`Predicate`] to resolve upon based on the trail. + /// Returns the next [`Predicate`] to resolve upon based on the trail, together with its trail + /// position. + /// + /// The trail position is derived from the value of the predicate in the heap (see + /// [`get_heap_value`]), so that it does not need to be looked up again. pub(crate) fn pop_max_predicate( &mut self, predicate_id_generator: &PredicateIdGenerator, mode: AnalysisMode, - ) -> Predicate { + ) -> (Predicate, usize) { + let (_, &heap_value) = self + .to_process_heap + .peek_max() + .expect("there should be a predicate to resolve upon"); let next_predicate_id = self.to_process_heap.pop_max().unwrap(); let predicate = predicate_id_generator.get_predicate(next_predicate_id); + // The heap value is twice the trail position, plus one if the predicate is not + // explicitly on the trail. + let trail_position = (heap_value / 2) as usize; mode.predicate_removed_from_nogood(predicate, &mut self.unique_variable_helper); @@ -404,7 +420,7 @@ impl WorkingNogood { self.iterative_minimiser.remove_predicate(predicate); } - predicate + (predicate, trail_position) } /// Add the predicate to the current conflict nogood if we know it needs to be added. @@ -448,8 +464,11 @@ impl WorkingNogood { context: &mut ConflictAnalysisContext, predicate_id_generator: &mut PredicateIdGenerator, ) { - let dec_level = context - .get_checkpoint_for_predicate(predicate) + // We look up the checkpoint and the trail position of the predicate once, since both are + // used below. + let (dec_level, trail_position) = context + .get_state() + .checkpoint_and_trail_position(predicate) .unwrap_or_else(|| { panic!( "Expected predicate {predicate} to be assigned but bounds were ({}, {})", @@ -500,6 +519,7 @@ impl WorkingNogood { self.add_predicate_current_checkpoint( predicate, + trail_position, context, predicate_id_generator, mode, @@ -746,21 +766,22 @@ impl WorkingNogood { /// The idea is that implied predicates (i.e., predicates which are not explicitly on the trail) /// should be resolved upon before the predicates which are explicitly on the trail. /// -/// Panics if the provided [`Predicate`] is not currently true on the trail. -pub(crate) fn get_heap_value(predicate: Predicate, context: &ConflictAnalysisContext<'_>) -> u32 { - if context.get_state().is_on_trail(predicate) { - context - .get_state() - .trail_position(predicate) - .expect("Predicate should be true during conflict analysis") as u32 - * 2 +/// The `trail_position` should be the trail position of the provided [`Predicate`] (see +/// `State::trail_position`); it is passed in to avoid looking it up again. +pub(crate) fn get_heap_value( + predicate: Predicate, + trail_position: usize, + context: &ConflictAnalysisContext<'_>, +) -> u32 { + pumpkin_assert_moderate!(context.get_state().trail_position(predicate) == Some(trail_position)); + + if context + .get_state() + .is_on_trail_at(predicate, trail_position) + { + trail_position as u32 * 2 } else { - context - .get_state() - .trail_position(predicate) - .expect("Predicate should be true during conflict analysis") as u32 - * 2 - + 1 + trail_position as u32 * 2 + 1 } } diff --git a/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs b/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs index c27ea019e..d2d2af7dd 100644 --- a/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs +++ b/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs @@ -176,6 +176,27 @@ impl ConflictAnalysisContext<'_> { ) } + /// The same as [`ConflictAnalysisContext::get_propagation_reason`], given that + /// `trail_position` is the trail position of the provided [`Predicate`]; this avoids looking + /// up the trail position again if it is already known. + pub fn get_propagation_reason_at( + &mut self, + predicate: Predicate, + trail_position: usize, + current_nogood: CurrentNogood<'_>, + reason_buffer: &mut (impl Extend + AsRef<[Predicate]>), + ) -> Option { + Self::get_propagation_reason_inner_at( + predicate, + trail_position, + current_nogood, + self.proof_log, + self.unit_nogood_inference_codes, + reason_buffer, + self.state, + ) + } + /// Returns the last decision which was made by the solver (if such a decision exists). pub fn find_last_decision(&mut self) -> Option { self.state.assignments.find_last_decision() @@ -355,12 +376,41 @@ impl ConflictAnalysisContext<'_> { reason_buffer: &mut (impl Extend + AsRef<[Predicate]>), state: &mut State, ) -> Option { - let inference_code = state.get_propagation_reason(predicate, reason_buffer, current_nogood); + let trail_position = state + .trail_position(predicate) + .unwrap_or_else(|| panic!("The predicate {predicate:?} must be true")); + + Self::get_propagation_reason_inner_at( + predicate, + trail_position, + current_nogood, + proof_log, + unit_nogood_inference_codes, + reason_buffer, + state, + ) + } + + /// The same as [`ConflictAnalysisContext::get_propagation_reason_inner`], given that + /// `trail_position` is the trail position of the provided [`Predicate`]. + pub(crate) fn get_propagation_reason_inner_at( + predicate: Predicate, + trail_position: usize, + current_nogood: CurrentNogood<'_>, + proof_log: &mut ProofLog, + unit_nogood_inference_codes: &HashMap, + reason_buffer: &mut (impl Extend + AsRef<[Predicate]>), + state: &mut State, + ) -> Option { + let inference_code = state.get_propagation_reason_at( + predicate, + trail_position, + reason_buffer, + current_nogood, + ); if let Some(ref ic) = inference_code { - let trail_index = state.trail_position(predicate).expect( - "an inference code is only present if the propagated predicate is on the trail", - ); + let trail_index = trail_position; let trail_entry = state.assignments.get_trail_entry(trail_index); let Some(reason_ref) = trail_entry.reason else { return inference_code; diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index a6006da0e..bb035c523 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -222,13 +222,17 @@ impl Assignments { } pub(crate) fn is_initial_bound(&self, predicate: Predicate) -> bool { - let domain_id = predicate.get_domain(); - let Some(trail_position) = self.get_trail_position(&predicate) else { return false; }; - trail_position <= self.domains[domain_id].initial_bounds_below_trail + self.is_initial_bound_at(predicate, trail_position) + } + + /// The same as [`Assignments::is_initial_bound`], given that `trail_position` is the trail + /// position of the (true) `predicate`; this avoids looking up the trail position again. + pub(crate) fn is_initial_bound_at(&self, predicate: Predicate, trail_position: usize) -> bool { + trail_position <= self.domains[predicate.get_domain()].initial_bounds_below_trail } } @@ -389,6 +393,17 @@ impl Assignments { .map(|u| u.trail_position) } + /// If the predicate is assigned true, returns the decision level and the trail position at + /// which it became true (using a single lookup). Otherwise returns None. + pub(crate) fn get_checkpoint_and_trail_position( + &self, + predicate: &Predicate, + ) -> Option<(usize, usize)> { + self.domains[predicate.get_domain()] + .get_update_info(predicate) + .map(|u| (u.checkpoint, u.trail_position)) + } + /// If the predicate is assigned true, returns the decision level of the predicate. /// Otherwise returns None. pub(crate) fn get_checkpoint_for_predicate(&self, predicate: &Predicate) -> Option { diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index ce23da96b..7dd9ebb0b 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -41,6 +41,7 @@ use crate::propagation::store::PropagatorStore; use crate::pumpkin_assert_advanced; use crate::pumpkin_assert_eq_simple; use crate::pumpkin_assert_extreme; +use crate::pumpkin_assert_moderate; use crate::pumpkin_assert_simple; use crate::results::SolutionReference; use crate::state::Conflict; @@ -304,14 +305,32 @@ impl State { pub fn is_on_trail(&self, predicate: Predicate) -> bool { let trail_position = self.trail_position(predicate); - trail_position - .is_some_and(|trail_position| self.assignments.trail[trail_position].covers(predicate)) + trail_position.is_some_and(|trail_position| self.is_on_trail_at(predicate, trail_position)) + } + + /// Returns whether the provided [`Predicate`] is explicitly on the trail, given that + /// `trail_position` is its trail position (see [`State::trail_position`]). + /// + /// This is the same as [`State::is_on_trail`], but it avoids looking up the trail position + /// again if it is already known. + pub fn is_on_trail_at(&self, predicate: Predicate, trail_position: usize) -> bool { + self.assignments.trail[trail_position].covers(predicate) } /// Returns whether the trail position of the provided [`Predicate`]. pub fn trail_position(&self, predicate: Predicate) -> Option { self.assignments.get_trail_position(&predicate) } + + /// Returns the checkpoint and the trail position at which the provided [`Predicate`] became + /// true, or [`None`] if it is not true. + /// + /// This is the same as calling [`State::get_checkpoint_for_predicate`] and + /// [`State::trail_position`], but it only looks up the predicate once. + pub fn checkpoint_and_trail_position(&self, predicate: Predicate) -> Option<(usize, usize)> { + self.assignments + .get_checkpoint_and_trail_position(&predicate) + } } /// Operations for adding constraints. @@ -890,6 +909,28 @@ impl State { reason_buffer: &mut (impl Extend + AsRef<[Predicate]>), current_nogood: CurrentNogood<'_>, ) -> Option { + let trail_position = self + .assignments + .get_trail_position(&predicate) + .unwrap_or_else(|| panic!("The predicate {predicate:?} must be true during conflict analysis. Bounds were {},{}", self.lower_bound(predicate.get_domain()), self.upper_bound(predicate.get_domain()))); + + self.get_propagation_reason_at(predicate, trail_position, reason_buffer, current_nogood) + } + + /// The same as [`State::get_propagation_reason`], given that `trail_position` is the trail + /// position of the provided [`Predicate`] (see [`State::trail_position`]); this avoids looking + /// up the trail position again if it is already known (e.g., during conflict analysis). + pub fn get_propagation_reason_at( + &mut self, + predicate: Predicate, + trail_position: usize, + reason_buffer: &mut (impl Extend + AsRef<[Predicate]>), + current_nogood: CurrentNogood<'_>, + ) -> Option { + pumpkin_assert_moderate!( + self.assignments.get_trail_position(&predicate) == Some(trail_position) + ); + // TODO: this function could be put into the reason store // Note that this function can only be called with propagations, and never decision @@ -905,15 +946,13 @@ impl State { // there would be only one predicate from the current checkpoint. For this // reason, it is safe to assume that in the following, that any input predicate is // indeed a propagated predicate. - if self.assignments.is_initial_bound(predicate) { + if self + .assignments + .is_initial_bound_at(predicate, trail_position) + { return None; } - let trail_position = self - .assignments - .get_trail_position(&predicate) - .unwrap_or_else(|| panic!("The predicate {predicate:?} must be true during conflict analysis. Bounds were {},{}", self.lower_bound(predicate.get_domain()), self.upper_bound(predicate.get_domain()))); - let trail_entry = self.assignments.get_trail_entry(trail_position); // We distinguish between three cases: From 3ac2aa7e5d4352c49f036986fd283986580760ab Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 11:36:49 +0100 Subject: [PATCH 07/18] refactor: make removed values uniform --- .../core/src/engine/cp/assignments.rs | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index bb035c523..615a623f1 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -893,24 +893,15 @@ impl Assignments { .synchronise(new_checkpoint) .enumerate() .for_each(|(index, entry)| { - // Calculate how many values are re-introduced into the domain. let domain_id = entry.predicate.get_domain(); let lower_bound_before = self.domains[domain_id].lower_bound(); let upper_bound_before = self.domains[domain_id].upper_bound(); let trail_index = num_trail_entries_before_synchronisation - index - 1; - let add_on_upper_bound = entry.old_upper_bound.abs_diff(upper_bound_before) as u64; - let add_on_lower_bound = entry.old_lower_bound.abs_diff(lower_bound_before) as u64; - self.pruned_values -= add_on_upper_bound + add_on_lower_bound; - - if add_on_lower_bound + add_on_upper_bound == 0 { - self.pruned_values -= entry.num_removed_values(); - } - let fixed_before = self.domains[domain_id].lower_bound() == self.domains[domain_id].upper_bound(); - self.domains[domain_id].undo_trail_entry(&entry); + self.pruned_values -= self.domains[domain_id].undo_trail_entry(&entry); let new_lower_bound = self.domains[domain_id].lower_bound(); let new_upper_bound = self.domains[domain_id].upper_bound(); @@ -943,7 +934,7 @@ impl Assignments { pub(crate) fn remove_last_trail_element(&mut self) -> (Predicate, ReasonRef) { let entry = self.trail.pop().unwrap(); let domain_id = entry.predicate.get_domain(); - self.domains[domain_id].undo_trail_entry(&entry); + let _ = self.domains[domain_id].undo_trail_entry(&entry); self.update_bounds_snapshot(domain_id); let reason_ref = entry.reason.unwrap(); @@ -1037,17 +1028,6 @@ impl ConstraintProgrammingTrailEntry { } }) } - - /// Returns the number of values removed by this entry if it is a disequality entry, and 0 - /// otherwise. - fn num_removed_values(&self) -> u64 { - if !self.predicate.is_not_equal_predicate() { - return 0; - } - - let start = self.predicate.get_right_hand_side(); - self.range_end.unwrap_or(start).abs_diff(start) as u64 + 1 - } } #[derive(Clone, Copy, Debug)] @@ -1532,8 +1512,17 @@ impl IntegerDomain { } } - fn undo_trail_entry(&mut self, entry: &ConstraintProgrammingTrailEntry) { + /// Undoes the given trail entry, and returns the number of values which are re-introduced + /// into the domain (mirroring how [`Assignments::pruned_values`] is increased). + /// + /// This is the distance by which the bounds move, plus the size of the removed hole if it did + /// not move a bound. Note that this is an over-approximation, since the values between the old + /// and new bound may include values which are still removed by other holes. + fn undo_trail_entry(&mut self, entry: &ConstraintProgrammingTrailEntry) -> u64 { let domain_id = entry.predicate.get_domain(); + let lower_bound_before = self.lower_bound(); + let upper_bound_before = self.upper_bound(); + let mut num_values_in_hole = 0; match entry.predicate.get_predicate_type() { PredicateType::LowerBound => { pumpkin_assert_moderate!(domain_id == self.id); @@ -1566,6 +1555,12 @@ impl IntegerDomain { pumpkin_assert_moderate!( removed_start == hole_update.start && removed_piece.end == hole_update.end ); + // If the hole moved a bound, then its values are counted by the bound change. + if !hole_update.triggered_lower_bound_update + && !hole_update.triggered_upper_bound_update + { + num_values_in_hole = hole_update.end.abs_diff(hole_update.start) as u64 + 1; + } if hole_update.triggered_lower_bound_update { let _ = self.lower_bound_updates.pop(); @@ -1598,6 +1593,10 @@ impl IntegerDomain { pumpkin_assert_eq_simple!(self.upper_bound(), entry.old_upper_bound); pumpkin_assert_moderate!(self.debug_bounds_check()); + + lower_bound_before.abs_diff(self.lower_bound()) as u64 + + self.upper_bound().abs_diff(upper_bound_before) as u64 + + num_values_in_hole } fn get_update_info(&self, predicate: &Predicate) -> Option { From 8a62fd0e9de0444ac1f044e28e146925bf01ae40 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 11:45:03 +0100 Subject: [PATCH 08/18] refactor: shortcut when equal to bounds --- pumpkin-crates/core/src/engine/cp/assignments.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index 615a623f1..b52e9b527 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -1350,6 +1350,11 @@ impl IntegerDomain { return false; } + // The bounds are always in the domain. + if first == self.lower_bound() || last == self.upper_bound() { + return true; + } + let index_after_first = self.index_of_first_piece_after(first); let Some(first_piece_index) = index_after_first.checked_sub(1) else { // There is no piece which starts at or before `first`, so `first` is not a hole. From 79e411fbb5ca5dcc562907c48a7b263bc3e22517 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 11:50:27 +0100 Subject: [PATCH 09/18] refactor: clarify contains_any_in_range --- .../core/src/engine/cp/assignments.rs | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index b52e9b527..591d0203d 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -1341,8 +1341,8 @@ impl IntegerDomain { /// Returns whether any of the values `from..=to` is in the domain. /// /// The first value within the bounds is in the domain unless it is in a removed piece; in - /// that case, we go over the pieces which follow it until we find a gap between two pieces - /// (or reach the end of the range). Typically, this only requires a single binary search. + /// that case, we go over the adjacent pieces which follow it until we find a gap between two + /// pieces (or pass the end of the range). Typically, this only requires a single binary search. fn contains_any_in_range(&self, from: i32, to: i32) -> bool { let first = from.max(self.lower_bound()); let last = to.min(self.upper_bound()); @@ -1355,27 +1355,22 @@ impl IntegerDomain { return true; } - let index_after_first = self.index_of_first_piece_after(first); - let Some(first_piece_index) = index_after_first.checked_sub(1) else { - // There is no piece which starts at or before `first`, so `first` is not a hole. - return true; - }; - - // The value after the pieces which we have visited so far; the values before it (and - // starting from `first`) are all removed. - let mut next_value = first; - for &(piece_start, piece) in &self.holes[first_piece_index..] { - if piece_start > next_value { - // There is a gap before this piece, which contains a value in the domain. + // The pieces are sorted and disjoint, so the only piece which can contain `first` is the + // last piece which starts at or before it. Starting from that piece, we skip over the + // pieces as long as they contain `candidate`, which is the smallest value from `first` + // onwards that is not in any of the pieces visited so far; each such piece directly + // follows the previous one. + let first_piece_to_check = self.index_of_first_piece_after(first).saturating_sub(1); + let mut candidate = first; + for &(piece_start, piece) in &self.holes[first_piece_to_check..] { + let contains_candidate = piece_start <= candidate && candidate <= piece.end; + if candidate > last || !contains_candidate { break; } - next_value = next_value.max(piece.end + 1); - if next_value > last { - return false; - } + candidate = piece.end + 1; } - next_value <= last + candidate <= last } /// Adds all maximal runs `[run_start, run_end]` of consecutive values in the domain with From 31bc5d44baee6c22c01f8c43ec92ec3c586d34ac Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 12:09:03 +0100 Subject: [PATCH 10/18] refactor: clarify the removing of ranges --- .../core/src/engine/cp/assignments.rs | 103 ++++++++++++------ 1 file changed, 67 insertions(+), 36 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index 591d0203d..3143959cc 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -22,9 +22,6 @@ pub struct Assignments { domains: KeyedVec, /// The number of values that have been pruned from the domain. pruned_values: u64, - /// A buffer for the runs of values which are removed by - /// [`Assignments::remove_range_from_domain`], to avoid allocating a new vector every time. - runs_buffer: Vec<(i32, i32)>, } impl Default for Assignments { @@ -34,7 +31,6 @@ impl Default for Assignments { bounds: Default::default(), domains: Default::default(), pruned_values: 0, - runs_buffer: Vec::default(), }; // As a convention, we allocate a dummy domain_id=0, which represents a 0-1 variable that is @@ -648,6 +644,7 @@ impl Assignments { let first = start.max(lower_bound_before); let last = end.min(upper_bound_before); + if first > last { return self.domains[domain_id].verify_consistency(); } @@ -657,17 +654,29 @@ impl Assignments { let empties_domain = first == lower_bound_before && last == upper_bound_before; let last_of_runs = if empties_domain { last - 1 } else { last }; - // We first determine all of the runs (since the domain cannot be updated while going over - // its holes), and then remove them. - let mut runs = std::mem::take(&mut self.runs_buffer); - runs.clear(); - self.domains[domain_id].runs_in_domain(first, last_of_runs, &mut runs); + let mut removal_took_place = false; + let mut from = first; + let mut piece_index = + self.domains[domain_id].index_of_first_piece_ending_at_or_after(first); - let removal_took_place = !runs.is_empty(); - for &(run_start, run_end) in &runs { + // Next, we iteratively find the next runs that will be removed by the range. + while let Some((run_start, run_end, index_after_run)) = + self.domains[domain_id].next_run_in_domain(from, last_of_runs, piece_index) + { self.remove_run(domain_id, run_start, run_end, reason)?; + removal_took_place = true; + + // The removed run is inserted as a piece directly before the piece following the run. + pumpkin_assert_moderate!( + { + let (piece_start, piece) = self.domains[domain_id].holes[index_after_run]; + piece_start == run_start && piece.end == run_end + }, + "the removed run should be stored at the tracked index" + ); + piece_index = index_after_run + 1; + from = run_end + 1; } - self.runs_buffer = runs; if empties_domain { self.remove_run(domain_id, last, last, reason)?; @@ -1226,6 +1235,16 @@ impl IntegerDomain { .partition_point(|&(piece_start, _)| piece_start <= value) } + /// Returns the index (in [`IntegerDomain::holes`]) of the first piece which ends at or after + /// `value`; this is the piece containing `value` if there is one, and otherwise the first + /// piece which starts after `value` (or `self.holes.len()` if there is none). + /// + /// For example, with the pieces `[[2, 3], [4, 6], [9, 9]]`, this returns 1 for `value = 5` + /// (the piece `[4, 6]` contains it), 2 for `value = 7`, and 3 for `value = 10`. + fn index_of_first_piece_ending_at_or_after(&self, value: i32) -> usize { + self.holes.partition_point(|&(_, piece)| piece.end < value) + } + /// Returns the start and the removed piece which contains `value`, if any. fn piece_containing(&self, value: i32) -> Option<(i32, HolePiece)> { let index = self.index_of_first_piece_after(value).checked_sub(1)?; @@ -1373,36 +1392,48 @@ impl IntegerDomain { candidate <= last } - /// Adds all maximal runs `[run_start, run_end]` of consecutive values in the domain with - /// `from <= run_start` and `run_end <= to` to `runs`, in increasing order. + /// Returns the first run `[run_start, run_end]` of consecutive values in the domain within + /// `from..=to` (i.e., the values in `from..run_start` are all removed, and `run_end` is either + /// `to` or directly followed by a removed value), or `None` if there is no value of `from..=to` + /// in the domain. /// - /// This goes over the removed pieces which overlap with `from..=to` only once (in order of - /// their values), rather than looking up the pieces one by one. - fn runs_in_domain(&self, from: i32, to: i32, runs: &mut Vec<(i32, i32)>) { - // We start from the piece containing `from` (if there is one), since it determines where - // the first run starts; otherwise, we start from the first piece after `from`. - let index_after_from = self.index_of_first_piece_after(from); - let first_piece_index = match self.piece_containing(from) { - Some(_) => index_after_from - 1, - None => index_after_from, - }; - - // The start of the current run; the values in `run_start..` are not part of any piece - // which we have visited so far. + /// Alongside the run, it returns the index of the first piece after the run (or + /// `self.holes.len()` if there is none). Removing the run inserts its piece at exactly this + /// index, so the next run can be found by calling this method with `from = run_end + 1` and + /// `piece_index` set to this index plus one, without looking up the pieces again. + /// + /// The `piece_index` should be the index of the first piece which ends at or after `from` (see + /// [`IntegerDomain::index_of_first_piece_ending_at_or_after`]). + /// + /// For example, with the domain `[0, 12]` and the pieces `[[2, 3], [4, 6], [9, 9]]`: + /// - `next_run_in_domain(2, 10, 0)` skips `[2, 3]` and `[4, 6]`, and returns `(7, 8, 2)`. + /// - After removing `[7, 8]`, the pieces are `[[2, 3], [4, 6], [7, 8], [9, 9]]`, and + /// `next_run_in_domain(9, 10, 3)` skips `[9, 9]` and returns `(10, 10, 4)`. + fn next_run_in_domain( + &self, + from: i32, + to: i32, + mut piece_index: usize, + ) -> Option<(i32, i32, usize)> { + // The run starts after the (adjacent) pieces which contain `from`. let mut run_start = from; - for &(piece_start, piece) in self.holes[first_piece_index..] - .iter() - .take_while(|&&(piece_start, _)| piece_start <= to) + while let Some(&(piece_start, piece)) = self.holes.get(piece_index) + && piece_start <= run_start { - if piece_start > run_start { - runs.push((run_start, piece_start - 1)); - } - run_start = run_start.max(piece.end + 1); + run_start = piece.end + 1; + piece_index += 1; } - if run_start <= to { - runs.push((run_start, to)); + if run_start > to { + return None; } + + // The run ends directly before the next piece, or at `to`. + let run_end = self + .holes + .get(piece_index) + .map_or(to, |&(piece_start, _)| to.min(piece_start - 1)); + Some((run_start, run_end, piece_index)) } fn debug_is_valid_upper_bound_domain_update( From 62e219aec5a28284b61fb46f5bd55ab7caf3d973 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 12:22:11 +0100 Subject: [PATCH 11/18] docs: simplify remove_range documentation --- .../contexts/propagation_context.rs | 33 ++++--------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index 4424d5d4e..090c3d386 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -319,33 +319,12 @@ impl PropagationContext<'_> { /// value `v` in the range (with the same reason), but it is cheaper: the removed values are /// stored as a range, rather than one value at a time. /// - /// # Reason - /// A single reason is stored for the whole range, and it is used to explain every removed - /// value. Hence, the reason should imply `[var != v]` for *every* `start <= v <= end`, not just - /// for some of them. During conflict analysis, the explanation of `[var != v]` for any value - /// `v` in the range is this reason. - /// - /// # Values outside of the domain - /// The range does not need to be within the domain of `var`: - /// - Values outside of the bounds of `var` are ignored. - /// - Values which have already been removed (holes) are skipped; these keep their original - /// reason. - /// - /// If none of the values are in the domain, then this method does nothing. - /// - /// # Trail entries - /// If `var` is a domain or an affine view over a domain, then the range is translated to a - /// range of the underlying domain, and every maximal run of consecutive values of the - /// underlying domain which are removed uses a single trail entry (see the examples below). - /// Otherwise (e.g., for constants), the values are removed one by one. All of the trail - /// entries share the provided reason. - /// - /// # Empty domains - /// If the domain becomes empty, then the [`EmptyDomainConflict`] error is returned. At that - /// point, no-more propagation should happen. The trigger of the conflict is the removal of - /// the last value in the domain (i.e., the predicate `[x != v]` where `v` is the largest value - /// in the domain of the underlying domain `x`), as is the case when posting a disequality - /// predicate which empties the domain. + /// # Notes + /// - The reason should be valid for *every* removed value. + /// - Any values which are already outside of the domain are ignored. + /// - For views, the holes are translated and every maximal run of consecutive values of the + /// underlying domain are removed. + /// - The trigger of the conflict is removal of the last value in the domain. /// /// # Examples /// Removing a range which contains an existing hole; the range is split into the runs of From b3af6d64658ac8535fec23d7ba7ea9faac575081 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 13:15:16 +0100 Subject: [PATCH 12/18] refactor: move method for getting range to trait --- pumpkin-crates/core/src/api/mod.rs | 1 + .../core/src/engine/variables/affine_view.rs | 71 +++++++++++ .../core/src/engine/variables/constant.rs | 9 ++ .../core/src/engine/variables/domain_id.rs | 13 ++ .../src/engine/variables/integer_variable.rs | 29 +++++ .../core/src/engine/variables/literal.rs | 5 + .../core/src/engine/variables/mod.rs | 1 + .../contexts/propagation_context.rs | 115 ++++++------------ 8 files changed, 163 insertions(+), 81 deletions(-) diff --git a/pumpkin-crates/core/src/api/mod.rs b/pumpkin-crates/core/src/api/mod.rs index 5c3ce584d..e31ba057e 100644 --- a/pumpkin-crates/core/src/api/mod.rs +++ b/pumpkin-crates/core/src/api/mod.rs @@ -55,6 +55,7 @@ pub mod variables { pub use crate::engine::variables::DomainId; pub use crate::engine::variables::IntegerVariable; pub use crate::engine::variables::Literal; + pub use crate::engine::variables::RangeOfUnderlyingDomain; pub use crate::engine::variables::TransformableVariable; } diff --git a/pumpkin-crates/core/src/engine/variables/affine_view.rs b/pumpkin-crates/core/src/engine/variables/affine_view.rs index 9142f0ba5..710f9b51e 100644 --- a/pumpkin-crates/core/src/engine/variables/affine_view.rs +++ b/pumpkin-crates/core/src/engine/variables/affine_view.rs @@ -13,6 +13,7 @@ use crate::engine::predicates::predicate::Predicate; use crate::engine::predicates::predicate_constructor::PredicateConstructor; use crate::engine::variables::DomainId; use crate::engine::variables::IntegerVariable; +use crate::engine::variables::RangeOfUnderlyingDomain; use crate::math::num_ext::NumExt; use crate::propagation::EventDispatcher; use crate::propagation::EventTarget; @@ -323,6 +324,33 @@ where .get_holes(assignments) .map(|value| self.map(value)) } + + fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain { + // The values of `inner` which are mapped into `start..=end`; the rounding is inwards, and + // a negative scale swaps the order of the range (as for the bound predicates). + let (inner_start, inner_end) = if self.scale < 0 { + ( + self.invert(end, Rounding::Up), + self.invert(start, Rounding::Down), + ) + } else { + ( + self.invert(start, Rounding::Up), + self.invert(end, Rounding::Down), + ) + }; + + match self + .inner + .range_of_underlying_domain(inner_start, inner_end) + { + // The value of a constant is mapped to the value of this view. + RangeOfUnderlyingDomain::Constant(value) => { + RangeOfUnderlyingDomain::Constant(self.map(value)) + } + range => range, + } + } } impl TransformableVariable> for AffineView @@ -421,6 +449,49 @@ mod tests { use super::*; use crate::predicate; + #[test] + fn range_of_underlying_domain_maps_range_back_to_inner_domain() { + let x = DomainId::new(0); + let domain = |range_start, range_end| RangeOfUnderlyingDomain::Domain { + domain_id: x, + range_start, + range_end, + }; + + assert_eq!( + x.scaled(2).offset(1).range_of_underlying_domain(4, 9), + domain(2, 4) + ); + assert_eq!( + x.scaled(-1).range_of_underlying_domain(-8, -5), + domain(5, 8) + ); + assert_eq!( + x.scaled(-3).offset(1).range_of_underlying_domain(-7, 5), + domain(-1, 2) + ); + // No multiple of 2 is in [3, 3]. + assert_eq!( + x.scaled(2).range_of_underlying_domain(3, 3), + RangeOfUnderlyingDomain::Empty + ); + + // The value of a constant is returned if it is in the range. + assert_eq!( + 4.range_of_underlying_domain(2, 5), + RangeOfUnderlyingDomain::Constant(4) + ); + assert_eq!( + 4.range_of_underlying_domain(5, 8), + RangeOfUnderlyingDomain::Empty + ); + // The value of a view over a constant is mapped to the value of the view. + assert_eq!( + AffineView::new(4, -2, 1).range_of_underlying_domain(-8, 0), + RangeOfUnderlyingDomain::Constant(-7) + ); + } + #[test] fn scaling_an_affine_view() { let view = AffineView::new(DomainId::new(0), 3, 4); diff --git a/pumpkin-crates/core/src/engine/variables/constant.rs b/pumpkin-crates/core/src/engine/variables/constant.rs index af328ba3b..f079c0eb6 100644 --- a/pumpkin-crates/core/src/engine/variables/constant.rs +++ b/pumpkin-crates/core/src/engine/variables/constant.rs @@ -3,6 +3,7 @@ use pumpkin_checking::CheckerVariable; use pumpkin_checking::IntExt; use crate::engine::Assignments; +use crate::engine::variables::RangeOfUnderlyingDomain; use crate::predicates::Predicate; use crate::predicates::PredicateConstructor; use crate::propagation::DomainEvent; @@ -83,6 +84,14 @@ impl IntegerVariable for i32 { fn get_holes(&self, _assignments: &Assignments) -> impl Iterator { std::iter::empty() } + + fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain { + if (start..=end).contains(self) { + RangeOfUnderlyingDomain::Constant(*self) + } else { + RangeOfUnderlyingDomain::Empty + } + } } impl TransformableVariable for i32 { diff --git a/pumpkin-crates/core/src/engine/variables/domain_id.rs b/pumpkin-crates/core/src/engine/variables/domain_id.rs index 0d1c42b62..ef00c14c1 100644 --- a/pumpkin-crates/core/src/engine/variables/domain_id.rs +++ b/pumpkin-crates/core/src/engine/variables/domain_id.rs @@ -9,6 +9,7 @@ use crate::engine::notifications::OpaqueDomainEvent; use crate::engine::notifications::Watchers; use crate::engine::variables::AffineView; use crate::engine::variables::IntegerVariable; +use crate::engine::variables::RangeOfUnderlyingDomain; use crate::predicates::Predicate; use crate::predicates::PredicateConstructor; use crate::predicates::PredicateType; @@ -191,6 +192,18 @@ impl IntegerVariable for DomainId { fn get_holes(&self, assignments: &Assignments) -> impl Iterator { assignments.get_holes(*self) } + + fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain { + if start <= end { + RangeOfUnderlyingDomain::Domain { + domain_id: *self, + range_start: start, + range_end: end, + } + } else { + RangeOfUnderlyingDomain::Empty + } + } } impl TransformableVariable> for DomainId { diff --git a/pumpkin-crates/core/src/engine/variables/integer_variable.rs b/pumpkin-crates/core/src/engine/variables/integer_variable.rs index 34083bbd5..e295a17c4 100644 --- a/pumpkin-crates/core/src/engine/variables/integer_variable.rs +++ b/pumpkin-crates/core/src/engine/variables/integer_variable.rs @@ -9,6 +9,7 @@ use crate::engine::notifications::DomainEvent; use crate::engine::notifications::OpaqueDomainEvent; use crate::engine::notifications::Watchers; use crate::engine::predicates::predicate_constructor::PredicateConstructor; +use crate::engine::variables::DomainId; use crate::predicates::Predicate; use crate::propagation::EventTarget; @@ -68,4 +69,32 @@ pub trait IntegerVariable: /// Returns all of the holes in the domain fn get_holes(&self, assignments: &Assignments) -> impl Iterator; + + /// Returns which values of the underlying domain of this variable correspond to the values + /// `start..=end` of this variable; see [`RangeOfUnderlyingDomain`]. + /// + /// For example: + /// - For the domain `x`, `start = 2`, and `end = 5`, this returns `Domain(x, 2, 5)`. + /// - For `y = 2x + 1`, `start = 4`, and `end = 9`, this returns `Domain(x, 2, 4)`. + /// - For `y = -x`, `start = -8`, and `end = -5`, this returns `Domain(x, 5, 8)`. + /// - For `y = 2x`, `start = 3`, and `end = 3`, this returns `Empty`. + /// - For the constant `4`, `start = 2`, and `end = 5`, this returns `Constant(4)`. + fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain; +} + +/// The values of the underlying domain of an [`IntegerVariable`] which correspond to a range of +/// values `start..=end` of the variable (see [`IntegerVariable::range_of_underlying_domain`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RangeOfUnderlyingDomain { + /// The values `start..=end` of the variable correspond to the (non-empty) range + /// `range_start..=range_end` of the domain `domain_id`. + Domain { + domain_id: DomainId, + range_start: i32, + range_end: i32, + }, + /// The variable is the constant `value`, which is in `start..=end`. + Constant(i32), + /// No value of the variable can be in `start..=end`. + Empty, } diff --git a/pumpkin-crates/core/src/engine/variables/literal.rs b/pumpkin-crates/core/src/engine/variables/literal.rs index 3b358031f..279a7bf4f 100644 --- a/pumpkin-crates/core/src/engine/variables/literal.rs +++ b/pumpkin-crates/core/src/engine/variables/literal.rs @@ -7,6 +7,7 @@ use pumpkin_checking::VariableState; use super::DomainId; use super::IntegerVariable; +use super::RangeOfUnderlyingDomain; use super::TransformableVariable; use crate::engine::Assignments; use crate::engine::notifications::DomainEvent; @@ -202,6 +203,10 @@ impl IntegerVariable for Literal { fn get_holes(&self, assignments: &Assignments) -> impl Iterator { self.integer_variable.get_holes(assignments) } + + fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain { + self.integer_variable.range_of_underlying_domain(start, end) + } } impl PredicateConstructor for Literal { diff --git a/pumpkin-crates/core/src/engine/variables/mod.rs b/pumpkin-crates/core/src/engine/variables/mod.rs index ce9e1b650..b8b44be15 100644 --- a/pumpkin-crates/core/src/engine/variables/mod.rs +++ b/pumpkin-crates/core/src/engine/variables/mod.rs @@ -14,5 +14,6 @@ pub use affine_view::AffineView; pub use domain_generator_iterator::DomainGeneratorIterator; pub use domain_id::DomainId; pub use integer_variable::IntegerVariable; +pub use integer_variable::RangeOfUnderlyingDomain; pub use literal::Literal; pub use transformable_variable::TransformableVariable; diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index 090c3d386..5bfbbc1c3 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -8,7 +8,6 @@ use crate::engine::TrailedValues; use crate::engine::notifications::NotificationEngine; use crate::engine::notifications::Watchers; use crate::engine::predicates::predicate::Predicate; -use crate::engine::predicates::predicate::PredicateType; use crate::engine::reason::Reason; use crate::engine::reason::ReasonStore; use crate::engine::reason::StoredReason; @@ -30,6 +29,7 @@ use crate::propagation::ReadDomains; use crate::pumpkin_assert_simple; use crate::variables::DomainId; use crate::variables::IntegerVariable; +use crate::variables::RangeOfUnderlyingDomain; /// Provided to the propagator when it is notified of a domain event. /// @@ -300,15 +300,16 @@ impl PropagationContext<'_> { start: i32, end: i32, ) -> bool { - match range_of_underlying_domain(var, start, end) { - Some((domain_id, range_start, range_end)) => { - self.assignments - .contains_any_in_range(domain_id, range_start, range_end) - } - // Otherwise (e.g., for constants), we check the values within the bounds one by one. - None => (start.max(var.lower_bound(self.assignments)) - ..=end.min(var.upper_bound(self.assignments))) - .any(|value| var.contains(self.assignments, value)), + match var.range_of_underlying_domain(start, end) { + RangeOfUnderlyingDomain::Domain { + domain_id, + range_start, + range_end, + } => self + .assignments + .contains_any_in_range(domain_id, range_start, range_end), + RangeOfUnderlyingDomain::Constant(_) => true, + RangeOfUnderlyingDomain::Empty => false, } } @@ -364,48 +365,33 @@ impl PropagationContext<'_> { end: i32, reason: impl Into, ) -> Result<(), EmptyDomainConflict> { - let range_of_underlying_domain = range_of_underlying_domain(var, start, end); - // We reserve a slot for the reason up front, since the trail entries need to refer to it; // the reason itself is only stored if a value was actually removed (see below). let slot = self.reason_store.new_slot(); - let modification_result = - if let Some((domain_id, range_start, range_end)) = range_of_underlying_domain { - // The values of the underlying domain are removed as runs of consecutive values, - // skipping the values which are not in the domain. - self.assignments.remove_range_from_domain( - domain_id, - range_start, - range_end, - Some(slot.reason_ref()), - self.notification_engine, - ) - } else { - // Otherwise (e.g., for constants), we remove the values within the bounds one by - // one, all sharing the same reason. We only go over the values within the bounds of - // `var` to avoid iterating over a (potentially large) range of values which are not - // in the domain anyway. - let first_value = start.max(var.lower_bound(self.assignments)); - let last_value = end.min(var.upper_bound(self.assignments)); - - let mut modification_result = Ok(false); - for value in first_value..=last_value { - match self.assignments.post_predicate( - var.disequality_predicate(value), - Some(slot.reason_ref()), - self.notification_engine, - ) { - Ok(true) => modification_result = Ok(true), - Ok(false) => {} - Err(empty_domain) => { - modification_result = Err(empty_domain); - break; - } - } - } - modification_result - }; + let modification_result = match var.range_of_underlying_domain(start, end) { + // The values of the underlying domain are removed as runs of consecutive values, + // skipping the values which are not in the domain. + RangeOfUnderlyingDomain::Domain { + domain_id, + range_start, + range_end, + } => self.assignments.remove_range_from_domain( + domain_id, + range_start, + range_end, + Some(slot.reason_ref()), + self.notification_engine, + ), + // Removing the value of a constant results in an empty domain (since the disequality + // predicate is trivially false). + RangeOfUnderlyingDomain::Constant(value) => self.assignments.post_predicate( + var.disequality_predicate(value), + Some(slot.reason_ref()), + self.notification_engine, + ), + RangeOfUnderlyingDomain::Empty => Ok(false), + }; match modification_result { // None of the values were in the domain, so no trail entry refers to the slot and the @@ -441,39 +427,6 @@ impl PropagationContext<'_> { } } -/// Returns the underlying domain of `var` and the range of its values which corresponds to the -/// values `start..=end` of `var`, if `var` is a domain or an affine view over a domain; otherwise -/// (e.g., for constants), `None` is returned. -fn range_of_underlying_domain( - var: &Var, - start: i32, - end: i32, -) -> Option<(DomainId, i32, i32)> { - // For a domain (or an affine view over a domain), the values `start..=end` of `var` - // correspond to the values of the underlying domain which satisfy both of these - // predicates; one is a lower-bound and the other is an upper-bound predicate over the - // underlying domain (which are swapped if the view has a negative scale). - // - // For example: - // - For the domain `x`, these are `[x >= start]` and `[x <= end]`. - // - For `y = 2x + 1`, `start = 4`, and `end = 9`, these are `[x >= 2]` and `[x <= 4]`. - // - For `y = -x`, `start = -8`, and `end = -5`, these are `[x <= 8]` and `[x >= 5]`. - // - For a constant, these are trivially true or false predicates (i.e., no underlying domain). - let lower = var.lower_bound_predicate(start); - let upper = var.upper_bound_predicate(end); - match (lower.get_predicate_type(), upper.get_predicate_type()) { - (PredicateType::LowerBound, PredicateType::UpperBound) => { - Some((lower.get_right_hand_side(), upper.get_right_hand_side())) - } - (PredicateType::UpperBound, PredicateType::LowerBound) => { - Some((upper.get_right_hand_side(), lower.get_right_hand_side())) - } - _ => None, - } - .filter(|_| lower.get_domain() == upper.get_domain()) - .map(|(range_start, range_end)| (lower.get_domain(), range_start, range_end)) -} - pub(crate) fn build_reason( reason: impl Into, reification_literal: Option, From bdc577e9bc27706375ce92ce74ed0df0c4f45956 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 13:34:17 +0100 Subject: [PATCH 13/18] refactor: clarify extended nogood propagation loop --- .../propagators/nogoods/nogood_propagator.rs | 106 ++++++++++-------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index 089bfb1f8..f58008f9f 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -1062,61 +1062,71 @@ impl NogoodPropagator { // not in the domain anymore are skipped. // // Since the exceptions are sorted and contain no duplicates (see - // `DomainDescription::complete`), we start from the first exception in the range rather - // than going over all of them. - let first_exception_index = exceptions.partition_point(|&exception| exception < lb); - let mut gap_start = lb; - for gap_end in exceptions[first_exception_index..] + // `DomainDescription::complete`), we go over the exceptions within `lb..=ub` in order, + // starting from the first one. The exceptions should stay in the domain, so a gap ends + // directly before an exception (at `exception - 1`), and the next gap starts directly after + // it (at `exception + 1`). The first gap starts at `lb`, and the last gap ends at `ub`, + // which is handled by treating `ub + 1` as an additional exception. + // + // For example, with the range [5, 15] and the exceptions [8, 9, 12], the gaps are [5, 7], + // [9, 8] (which is empty, since 8 and 9 are adjacent), [10, 11], and [13, 15]. + + let mut next_gap_start = lb; + + let first_exception_in_range = exceptions.partition_point(|&exception| exception < lb); + for exception in exceptions[first_exception_in_range..] .iter() - .take_while(|&&exception| exception <= ub) - .map(|exception| exception - 1) - .chain(std::iter::once(ub)) + .copied() + .take_while(|&exception| exception <= ub) + .chain(std::iter::once(ub + 1)) { - if gap_start <= gap_end { - // The reason consists of: - // 1) All predicates which reason over a different domain than the propagated - // predicate (which are all guaranteed to be satisfied) - let reason = if let Some(nogood_id) = nogood_id { - Reason::DynamicLazy( - LazyNogoodExplanation::new() - .with_nogood_id(nogood_id) - .with_explains_extended_propagation(true) - .into(), - ) - } else { - ( - nogood - .iter() - .filter_map(|predicate_id| { - let predicate = context.get_predicate(*predicate_id); + let gap_start = std::mem::replace(&mut next_gap_start, exception + 1); + let gap_end = exception - 1; - (predicate.get_domain() != propagated_domain).then_some(predicate) - }) - .collect::(), - inference_code, - ) - .into() - }; + // We skip the gaps which are empty or which have already been removed, to avoid + // creating a reason for them. + if gap_start > gap_end + || !context.contains_any_in_range(&propagated_domain, gap_start, gap_end) + { + continue; + } - let num_trail_entries_before = context.trail_position(); - let result = context.remove_range(&propagated_domain, gap_start, gap_end, reason); - if result.is_err() { - statistics - .extended_propagation_statistics - .num_variables_propagated += 1; - } - result?; + // The reason consists of all predicates which reason over a different domain than the + // propagated predicate (which are all guaranteed to be satisfied). + let reason = if let Some(nogood_id) = nogood_id { + Reason::DynamicLazy( + LazyNogoodExplanation::new() + .with_nogood_id(nogood_id) + .with_explains_extended_propagation(true) + .into(), + ) + } else { + ( + nogood + .iter() + .filter_map(|predicate_id| { + let predicate = context.get_predicate(*predicate_id); - if context.trail_position() > num_trail_entries_before { - propagated = true; - statistics - .extended_propagation_statistics - .num_extended_disequality_propagations += 1; - } + (predicate.get_domain() != propagated_domain).then_some(predicate) + }) + .collect::(), + inference_code, + ) + .into() + }; + + let result = context.remove_range(&propagated_domain, gap_start, gap_end, reason); + if result.is_err() { + statistics + .extended_propagation_statistics + .num_variables_propagated += 1; } + result?; - // The next gap starts after the exception. - gap_start = gap_end + 2; + propagated = true; + statistics + .extended_propagation_statistics + .num_extended_disequality_propagations += 1; } if propagated { From 5965a4b0bfd154a036d46afd15d1dc0eb8bab42d Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 15:02:06 +0100 Subject: [PATCH 14/18] refactor: applying checklist --- .../src/resolvers/working_nogood.rs | 14 +- .../conflict_analysis_context.rs | 3 +- .../engine/constraint_satisfaction_solver.rs | 107 ++++++----- .../core/src/engine/cp/assignments.rs | 115 +++++------ pumpkin-crates/core/src/engine/state.rs | 75 +++++--- .../core/src/engine/variables/affine_view.rs | 12 +- .../core/src/engine/variables/domain_id.rs | 4 +- .../src/engine/variables/integer_variable.rs | 23 ++- .../contexts/propagation_context.rs | 77 ++++---- .../propagators/nogoods/nogood_propagator.rs | 179 ++++++++---------- .../propagators/nogoods/propagation_mode.rs | 10 +- .../time_table/propagation_handler.rs | 134 ++++++------- .../cumulative/time_table/test_suite.rs | 27 +-- 13 files changed, 391 insertions(+), 389 deletions(-) diff --git a/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs b/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs index 485c3eee1..27606746e 100644 --- a/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs +++ b/pumpkin-crates/conflict-resolvers/src/resolvers/working_nogood.rs @@ -11,6 +11,8 @@ use pumpkin_core::predicates::PredicateIdGenerator; use pumpkin_core::propagation::PredicateId; use pumpkin_core::propagation::ReadDomains; use pumpkin_core::state::CurrentNogood; +#[cfg(doc)] +use pumpkin_core::state::State; use pumpkin_core::statistics::Statistic; use pumpkin_core::statistics::StatisticLogger; use pumpkin_core::statistics::moving_averages::MovingAverage; @@ -91,7 +93,7 @@ impl WorkingNogood { /// Adds a predicate to the current working nogood which is from the current checkpoint. /// /// The `trail_position` is the trail position of the `predicate` (see - /// `State::trail_position`). + /// [`State::trail_position`]). fn add_predicate_current_checkpoint( &mut self, predicate: Predicate, @@ -466,18 +468,18 @@ impl WorkingNogood { ) { // We look up the checkpoint and the trail position of the predicate once, since both are // used below. - let (dec_level, trail_position) = context + let (checkpoint, trail_position) = context .get_state() .checkpoint_and_trail_position(predicate) .unwrap_or_else(|| { panic!( "Expected predicate {predicate} to be assigned but bounds were ({}, {})", context.lower_bound(&predicate.get_domain()), - context.lower_bound(&predicate.get_domain()), + context.upper_bound(&predicate.get_domain()), ) }); // Ignore root level predicates. - if dec_level == 0 { + if checkpoint == 0 { context.explain_root_assignment(predicate); if self.iterative_minimisation { @@ -492,7 +494,7 @@ impl WorkingNogood { // All-decision Learning // If the variables are not decisions then we want to potentially add them to the heap, // otherwise we add it to the decision predicates which have been discovered previously - else if mode.predicate_should_be_processed(predicate, dec_level, context) { + else if mode.predicate_should_be_processed(predicate, checkpoint, context) { let predicate_id = predicate_id_generator.get_id(predicate); // The first time we encounter the predicate, we initialise its value in the // heap. @@ -767,7 +769,7 @@ impl WorkingNogood { /// should be resolved upon before the predicates which are explicitly on the trail. /// /// The `trail_position` should be the trail position of the provided [`Predicate`] (see -/// `State::trail_position`); it is passed in to avoid looking it up again. +/// [`State::trail_position`]); it is passed in to avoid looking it up again. pub(crate) fn get_heap_value( predicate: Predicate, trail_position: usize, diff --git a/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs b/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs index d2d2af7dd..aa161860a 100644 --- a/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs +++ b/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs @@ -410,8 +410,7 @@ impl ConflictAnalysisContext<'_> { ); if let Some(ref ic) = inference_code { - let trail_index = trail_position; - let trail_entry = state.assignments.get_trail_entry(trail_index); + let trail_entry = state.assignments.get_trail_entry(trail_position); let Some(reason_ref) = trail_entry.reason else { return inference_code; }; diff --git a/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs b/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs index 30f217075..727fc59a4 100644 --- a/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs +++ b/pumpkin-crates/core/src/engine/constraint_satisfaction_solver.rs @@ -1,7 +1,6 @@ //! Houses the solver which attempts to find a solution to a Constraint Satisfaction Problem (CSP) //! using a Lazy Clause Generation approach. use std::cmp::max; -use std::collections::VecDeque; use std::fmt::Debug; use std::sync::Arc; @@ -809,61 +808,69 @@ impl ConstraintSatisfactionSolver { // A trail entry which removes a range of values propagates a disequality predicate for // every removed value; each of these is logged separately. for propagated in entry.propagated_predicates() { - // The proof inference for the propagation `R -> l` is `R /\ ~l -> false`. - let inference_premises = reason.iter().copied().chain(std::iter::once(!propagated)); - let _ = self.internal_parameters.proof_log.log_inference( - &mut self.state.constraint_tags, - inference_code.clone(), - inference_premises, - None, - &self.state.variable_names, - &self.state.assignments, - ); + self.log_root_propagation(propagated, &reason, &inference_code); + } + } + } - // Since inference steps are only related to the nogood they directly precede, - // facts derived at the root are also logged as nogoods so they can be used in the - // derivation of other nogoods. - // - // In case we are logging hints, we must therefore identify what proof steps - // contribute to the derivation of the current nogood, and therefore are in the - // premise of the previously logged inference. These proof steps are necessarily - // unit nogoods, and therefore we recursively look up which unit nogoods are - // involved in the premise of the inference. - - let mut to_explain: VecDeque = reason.iter().copied().collect(); - - while let Some(premise) = to_explain.pop_front() { - pumpkin_assert_simple!( - self.state - .truth_value(premise) - .expect("Expected predicate to hold") - ); + /// Logs the root-level propagation `reason -> propagated` to the proof, followed by the unit + /// nogood `propagated` (see [`ConstraintSatisfactionSolver::handle_root_propagation`]). + fn log_root_propagation( + &mut self, + propagated: Predicate, + reason: &[Predicate], + inference_code: &InferenceCode, + ) { + // The proof inference for the propagation `R -> l` is `R /\ ~l -> false`. + let inference_premises = reason.iter().copied().chain(std::iter::once(!propagated)); + let _ = self.internal_parameters.proof_log.log_inference( + &mut self.state.constraint_tags, + inference_code.clone(), + inference_premises, + None, + &self.state.variable_names, + &self.state.assignments, + ); - let mut context = RootExplanationContext { - proof_log: &mut self.internal_parameters.proof_log, - unit_nogood_inference_codes: &self.unit_nogood_inference_codes, - state: &mut self.state, - }; + // Since inference steps are only related to the nogood they directly precede, + // facts derived at the root are also logged as nogoods so they can be used in the + // derivation of other nogoods. + // + // In case we are logging hints, we must therefore identify what proof steps + // contribute to the derivation of the current nogood, and therefore are in the + // premise of the previously logged inference. These proof steps are necessarily + // unit nogoods, and therefore we recursively look up which unit nogoods are + // involved in the premise of the inference. + for &premise in reason { + pumpkin_assert_simple!( + self.state + .truth_value(premise) + .expect("Expected predicate to hold") + ); - explain_root_assignment(&mut context, premise); - } + let mut context = RootExplanationContext { + proof_log: &mut self.internal_parameters.proof_log, + unit_nogood_inference_codes: &self.unit_nogood_inference_codes, + state: &mut self.state, + }; - // Log the nogood which adds the root-level knowledge to the proof. - let constraint_tag = self.internal_parameters.proof_log.log_deduction( - [!propagated], - &self.state.variable_names, - &mut self.state.constraint_tags, - &self.state.assignments, - ); + explain_root_assignment(&mut context, premise); + } - if let Ok(constraint_tag) = constraint_tag { - let inference_code = InferenceCode::new(constraint_tag, NogoodLabel); + // Log the nogood which adds the root-level knowledge to the proof. + let constraint_tag = self.internal_parameters.proof_log.log_deduction( + [!propagated], + &self.state.variable_names, + &mut self.state.constraint_tags, + &self.state.assignments, + ); - let _ = self - .unit_nogood_inference_codes - .insert(propagated, inference_code); - } - } + if let Ok(constraint_tag) = constraint_tag { + let inference_code = InferenceCode::new(constraint_tag, NogoodLabel); + + let _ = self + .unit_nogood_inference_codes + .insert(propagated, inference_code); } } diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index 3143959cc..f1350bc52 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -330,18 +330,15 @@ impl Assignments { predicates.push(predicate![domain_id <= domain.upper_bound()]); } - // Add holes. + // Add holes, except the ones made at the root and the ones outside the bounds. + // Since a bound value cannot be in a hole, we can use '<' and '>'. for &(start, piece) in &self.domains[domain_id].holes { if piece.update_info.checkpoint == 0 { continue; } - // Only record holes that are within the lower and upper bound, - // that are not root assignments. - // Since bound values cannot be in the holes, - // we can use '<' or '>'. - for hole in start..=piece.end { - if domain.lower_bound() < hole && hole < domain.upper_bound() { - predicates.push(predicate![domain_id != hole]); + for removed_value in start..=piece.end { + if domain.lower_bound() < removed_value && removed_value < domain.upper_bound() { + predicates.push(predicate![domain_id != removed_value]); } } } @@ -390,7 +387,7 @@ impl Assignments { } /// If the predicate is assigned true, returns the decision level and the trail position at - /// which it became true (using a single lookup). Otherwise returns None. + /// which it became true (using a single lookup); otherwise returns [`None`]. pub(crate) fn get_checkpoint_and_trail_position( &self, predicate: &Predicate, @@ -603,7 +600,7 @@ impl Assignments { let checkpoint = self.get_checkpoint(); let domain = &mut self.domains[domain_id]; - domain.remove_range(start, end, checkpoint, trail_position); + domain.remove_run(start, end, checkpoint, trail_position); let changed_lower_bound = domain.lower_bound().abs_diff(old_lower_bound) as u64; let changed_upper_bound = old_upper_bound.abs_diff(domain.upper_bound()) as u64; @@ -622,14 +619,15 @@ impl Assignments { /// Removes the values `start..=end` from the domain of `domain_id`. /// - /// Values which are not in the domain are skipped: the remaining values are split into - /// maximal runs of consecutive values in the domain, and each run is removed using a single - /// trail entry, all sharing the provided `reason`. For example, if the domain is `[0, 10]` - /// with the hole `[4, 6]`, then removing `[2, 8]` removes the runs `[2, 3]` and `[7, 8]`. + /// Values which are not in the domain are skipped. + /// The other values form maximal runs of consecutive values in the domain. + /// Each run is removed with one trail entry, and all runs share the provided `reason`. + /// For example, if the domain is `[0, 10]` with the hole `[4, 6]`, then removing `[2, 8]` + /// removes the runs `[2, 3]` and `[7, 8]`. /// - /// If the removal results in an empty domain, then the last removed value is removed using - /// its own trail entry, such that the last trail entry is a disequality predicate for the last - /// value in the domain (as is the case when removing a single value). + /// If the domain becomes empty, then its last value is removed with a trail entry of its own. + /// The last trail entry is then the disequality predicate for that value, as when a single + /// value is removed. /// /// Returns whether any value was removed, or [`EmptyDomain`] if the domain became empty. pub(crate) fn remove_range_from_domain( @@ -649,19 +647,18 @@ impl Assignments { return self.domains[domain_id].verify_consistency(); } - // If all values in the domain are removed, then we remove the upper-bound separately + // If all values in the domain are removed, then the upper-bound is removed separately // (see the documentation of this method). let empties_domain = first == lower_bound_before && last == upper_bound_before; - let last_of_runs = if empties_domain { last - 1 } else { last }; + let end_of_runs = if empties_domain { last - 1 } else { last }; let mut removal_took_place = false; - let mut from = first; + let mut next_run_from = first; let mut piece_index = self.domains[domain_id].index_of_first_piece_ending_at_or_after(first); - // Next, we iteratively find the next runs that will be removed by the range. while let Some((run_start, run_end, index_after_run)) = - self.domains[domain_id].next_run_in_domain(from, last_of_runs, piece_index) + self.domains[domain_id].next_run_in_domain(next_run_from, end_of_runs, piece_index) { self.remove_run(domain_id, run_start, run_end, reason)?; removal_took_place = true; @@ -675,7 +672,7 @@ impl Assignments { "the removed run should be stored at the tracked index" ); piece_index = index_after_run + 1; - from = run_end + 1; + next_run_from = run_end + 1; } if empties_domain { @@ -1046,7 +1043,8 @@ struct PairDecisionLevelTrailPosition { } /// A piece of consecutive values `[start, end]` (both inclusive) which were removed from a domain -/// at the same time; the start of the piece is the key in [`IntegerDomain::holes`]. +/// at the same time. +/// The piece is stored in [`IntegerDomain::holes`] next to its first value `start`. #[derive(Clone, Copy, Debug)] struct HolePiece { /// The last value of the removed piece (inclusive). @@ -1063,8 +1061,7 @@ struct BoundUpdateInfo { #[derive(Clone, Debug)] struct HoleUpdateInfo { - /// The first value of the removed piece (inclusive); this is the key of the piece in - /// [`IntegerDomain::holes`]. + /// The first value of the removed piece (inclusive). start: i32, /// The last value of the removed piece (inclusive), i.e., the removed values are /// `start..=end`. @@ -1091,14 +1088,13 @@ struct IntegerDomain { /// Auxiliary data structure to make it easy to check if a value is present or not. /// This is done to avoid going through 'hole_updates'. /// - /// Each entry is a piece of consecutive values which were removed by a single removal; it - /// consists of the first value of the piece and the [`HolePiece`] (containing the last value - /// of the piece and the decision level and trail position of the removal). The pieces are - /// disjoint, but pieces are not merged when they are adjacent, so that the time of removal is - /// known for every value. + /// Each entry is a piece of consecutive values removed by one trail entry. + /// It consists of the first value of the piece and the [`HolePiece`] with the rest. + /// The pieces are disjoint. + /// Adjacent pieces are not merged, so that the time of removal stays known for every value. /// - /// The entries are sorted by their first value, such that the piece containing a value can be - /// found using binary search. + /// The entries are sorted by their first value, so a binary search finds the piece containing + /// a value. holes: Vec<(i32, HolePiece)>, // Records the trail entry at which all of the root bounds are true initial_bounds_below_trail: usize, @@ -1245,20 +1241,15 @@ impl IntegerDomain { self.holes.partition_point(|&(_, piece)| piece.end < value) } - /// Returns the start and the removed piece which contains `value`, if any. + /// Returns the removed piece which contains `value` together with its first value, if any. fn piece_containing(&self, value: i32) -> Option<(i32, HolePiece)> { let index = self.index_of_first_piece_after(value).checked_sub(1)?; let (piece_start, piece) = self.holes[index]; (value <= piece.end).then_some((piece_start, piece)) } - /// Returns the removed piece which contains `value`, if any. - fn hole_containing(&self, value: i32) -> Option { - self.piece_containing(value).map(|(_, piece)| piece) - } - fn is_hole(&self, value: i32) -> bool { - self.hole_containing(value).is_some() + self.piece_containing(value).is_some() } fn contains(&self, value: i32) -> bool { @@ -1277,7 +1268,7 @@ impl IntegerDomain { // In case the hole is made at the given trail position or earlier, // the value is not in the domain. - if let Some(piece) = self.hole_containing(value) + if let Some((_, piece)) = self.piece_containing(value) && piece.update_info.trail_position <= trail_position { return false; @@ -1298,14 +1289,14 @@ impl IntegerDomain { return false; } - self.remove_range(removed_value, removed_value, checkpoint, trail_position); + self.remove_run(removed_value, removed_value, checkpoint, trail_position); true } /// Removes the values `start..=end` from the domain as a single piece. /// /// All of these values should be in the domain. - fn remove_range(&mut self, start: i32, end: i32, checkpoint: usize, trail_position: usize) { + fn remove_run(&mut self, start: i32, end: i32, checkpoint: usize, trail_position: usize) { pumpkin_assert_moderate!(start <= end); pumpkin_assert_moderate!(self.lower_bound() <= start && end <= self.upper_bound()); pumpkin_assert_moderate!( @@ -1358,10 +1349,6 @@ impl IntegerDomain { } /// Returns whether any of the values `from..=to` is in the domain. - /// - /// The first value within the bounds is in the domain unless it is in a removed piece; in - /// that case, we go over the adjacent pieces which follow it until we find a gap between two - /// pieces (or pass the end of the range). Typically, this only requires a single binary search. fn contains_any_in_range(&self, from: i32, to: i32) -> bool { let first = from.max(self.lower_bound()); let last = to.min(self.upper_bound()); @@ -1374,11 +1361,12 @@ impl IntegerDomain { return true; } - // The pieces are sorted and disjoint, so the only piece which can contain `first` is the - // last piece which starts at or before it. Starting from that piece, we skip over the - // pieces as long as they contain `candidate`, which is the smallest value from `first` - // onwards that is not in any of the pieces visited so far; each such piece directly - // follows the previous one. + // The value `first` is in the domain unless a removed piece contains it. + // The only piece which can contain `first` is the last piece starting at or before it, + // since the pieces are sorted and disjoint. + // From that piece on, we skip the adjacent pieces which contain `candidate`. + // After each skipped piece, `candidate` is the value directly after it. + // Typically, this needs a single binary search. let first_piece_to_check = self.index_of_first_piece_after(first).saturating_sub(1); let mut candidate = first; for &(piece_start, piece) in &self.holes[first_piece_to_check..] { @@ -1392,15 +1380,16 @@ impl IntegerDomain { candidate <= last } - /// Returns the first run `[run_start, run_end]` of consecutive values in the domain within - /// `from..=to` (i.e., the values in `from..run_start` are all removed, and `run_end` is either - /// `to` or directly followed by a removed value), or `None` if there is no value of `from..=to` - /// in the domain. + /// Returns the first run `[run_start, run_end]` of consecutive values of the domain within + /// `from..=to`, or [`None`] if no value of `from..=to` is in the domain. + /// The values in `from..run_start` are removed, and `run_end` is `to` or directly precedes a + /// removed value. /// - /// Alongside the run, it returns the index of the first piece after the run (or - /// `self.holes.len()` if there is none). Removing the run inserts its piece at exactly this - /// index, so the next run can be found by calling this method with `from = run_end + 1` and - /// `piece_index` set to this index plus one, without looking up the pieces again. + /// With the run, it returns the index of the first piece after the run, or `self.holes.len()` + /// if there is none. + /// Removing the run inserts its piece at this index. + /// The next run is then found by passing `from = run_end + 1` and this index plus one as + /// `piece_index`, without a new binary search. /// /// The `piece_index` should be the index of the first piece which ends at or after `from` (see /// [`IntegerDomain::index_of_first_piece_ending_at_or_after`]). @@ -1517,7 +1506,7 @@ impl IntegerDomain { // Jump over the removed pieces which contain the lower bound; note that pieces can be // adjacent, so this may jump over several pieces. while self.lower_bound() <= self.upper_bound() - && let Some(piece) = self.hole_containing(self.lower_bound()) + && let Some((_, piece)) = self.piece_containing(self.lower_bound()) { self.lower_bound_updates.last_mut().unwrap().bound = piece.end + 1; } @@ -1677,7 +1666,7 @@ impl IntegerDomain { // Check the explictly stored holes. // If the value has been removed explicitly, // then the stored time is the first time the value was removed. - if let Some(piece) = self.hole_containing(value) { + if let Some((_, piece)) = self.piece_containing(value) { Some(piece.update_info) } else { // Otherwise, check the case when the lower/upper bound surpassed the value. @@ -1801,7 +1790,7 @@ impl Iterator for IntegerDomainIterator<'_> { // If the current value is within the bounds, but is not in the domain, // jump over the removed pieces to the next non-hole value. while self.current_value <= self.domain.upper_bound() - && let Some(piece) = self.domain.hole_containing(self.current_value) + && let Some((_, piece)) = self.domain.piece_containing(self.current_value) { self.current_value = piece.end + 1; } diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index 7dd9ebb0b..51e593c60 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -313,11 +313,14 @@ impl State { /// /// This is the same as [`State::is_on_trail`], but it avoids looking up the trail position /// again if it is already known. + /// + /// # Panics + /// If `trail_position` is not a position on the trail. pub fn is_on_trail_at(&self, predicate: Predicate, trail_position: usize) -> bool { self.assignments.trail[trail_position].covers(predicate) } - /// Returns whether the trail position of the provided [`Predicate`]. + /// Returns the trail position of the provided [`Predicate`], or [`None`] if it is not true. pub fn trail_position(&self, predicate: Predicate) -> Option { self.assignments.get_trail_position(&predicate) } @@ -902,7 +905,8 @@ impl State { /// All the predicates appended to the `reason_buffer` will evaluate to `true`. The buffer /// is _not_ cleared before predicates are appended. /// - /// If the provided predicate is not true, then this method will panic. + /// # Panics + /// If the provided predicate is not true. pub fn get_propagation_reason( &mut self, predicate: Predicate, @@ -918,8 +922,12 @@ impl State { } /// The same as [`State::get_propagation_reason`], given that `trail_position` is the trail - /// position of the provided [`Predicate`] (see [`State::trail_position`]); this avoids looking - /// up the trail position again if it is already known (e.g., during conflict analysis). + /// position of the provided [`Predicate`] (see [`State::trail_position`]). + /// This avoids looking up a trail position that is already known, e.g., during conflict + /// analysis. + /// + /// # Panics + /// If `trail_position` is not a position on the trail. pub fn get_propagation_reason_at( &mut self, predicate: Predicate, @@ -1164,9 +1172,11 @@ impl State { // hole, there must be some other reason for that to happen, which we would // find earlier. // - // If the trail entry removed a range of values `not_equal_constant..=end`, - // then the upper bound was lowered below `not_equal_constant`, so any - // upper-bound smaller than `end` became true at this trail entry. + // If the trail entry removed the values + // `not_equal_constant..=last_removed_value`, then it lowered the upper bound + // below `not_equal_constant`. + // Any upper-bound below `last_removed_value` then became true at this trail + // entry. let last_removed_value = trail_entry.range_end.unwrap_or(not_equal_constant); pumpkin_assert_simple!(input_upper_bound < last_removed_value); @@ -1295,7 +1305,7 @@ mod tests { let y = state.new_interval_variable(0, 10, None); let x = state.new_interval_variable(0, 10, None); - let tag = state.new_constraint_tag(); + let constraint_tag = state.new_constraint_tag(); let slot = state.reason_store.new_slot(); let removed = state .assignments @@ -1310,24 +1320,33 @@ mod tests { assert!(removed); let _ = slot.populate( PropagatorId::create_from_index(0), - StoredReason::Eager(conjunction!([y >= 5]), InferenceCode::new(tag, TestLabel)), + StoredReason::Eager( + conjunction!([y >= 5]), + InferenceCode::new(constraint_tag, TestLabel), + ), ); // A value inside the range is explicitly on the trail, with the reason of the range. assert!(state.is_on_trail(predicate!(x != 2))); - let mut buffer = vec![]; - let inference_code = - state.get_propagation_reason(predicate!(x != 2), &mut buffer, CurrentNogood::empty()); + let mut reason_buffer = vec![]; + let inference_code = state.get_propagation_reason( + predicate!(x != 2), + &mut reason_buffer, + CurrentNogood::empty(), + ); assert!(inference_code.is_some()); - assert_eq!(buffer, vec![predicate!(y >= 5)]); + assert_eq!(reason_buffer, vec![predicate!(y >= 5)]); // The lower-bound which was raised by the range is explained using the last removed // value. - let mut buffer = vec![]; - let inference_code = - state.get_propagation_reason(predicate!(x >= 4), &mut buffer, CurrentNogood::empty()); + let mut reason_buffer = vec![]; + let inference_code = state.get_propagation_reason( + predicate!(x >= 4), + &mut reason_buffer, + CurrentNogood::empty(), + ); assert!(inference_code.is_none()); - assert_eq!(buffer, vec![predicate!(x >= 3), predicate!(x != 3)]); + assert_eq!(reason_buffer, vec![predicate!(x >= 3), predicate!(x != 3)]); } #[test] @@ -1335,7 +1354,7 @@ mod tests { let mut state = State::default(); let x = state.new_interval_variable(0, 10, None); - let tag = state.new_constraint_tag(); + let constraint_tag = state.new_constraint_tag(); let slot = state.reason_store.new_slot(); let removed = state .assignments @@ -1350,24 +1369,30 @@ mod tests { assert!(removed); let _ = slot.populate( PropagatorId::create_from_index(0), - StoredReason::Eager(conjunction!(), InferenceCode::new(tag, TestLabel)), + StoredReason::Eager( + conjunction!(), + InferenceCode::new(constraint_tag, TestLabel), + ), ); // The range [7, 10] lowered the upper-bound to 6; an upper-bound within the range is // explained using the next removed value. - let mut buffer = vec![]; - let inference_code = - state.get_propagation_reason(predicate!(x <= 8), &mut buffer, CurrentNogood::empty()); + let mut reason_buffer = vec![]; + let inference_code = state.get_propagation_reason( + predicate!(x <= 8), + &mut reason_buffer, + CurrentNogood::empty(), + ); assert!(inference_code.is_none()); - assert_eq!(buffer, vec![predicate!(x <= 9), predicate!(x != 9)]); + assert_eq!(reason_buffer, vec![predicate!(x <= 9), predicate!(x != 9)]); } #[test] fn remove_range_of_view_removes_range_of_underlying_domain() { let mut state = State::default(); let x = state.new_interval_variable(0, 10, None); - let tag = state.new_constraint_tag(); - let inference_code = InferenceCode::new(tag, TestLabel); + let constraint_tag = state.new_constraint_tag(); + let inference_code = InferenceCode::new(constraint_tag, TestLabel); let num_trail_entries = state.assignments.num_trail_entries(); let mut context = PropagationContext::new( diff --git a/pumpkin-crates/core/src/engine/variables/affine_view.rs b/pumpkin-crates/core/src/engine/variables/affine_view.rs index 710f9b51e..ea141b1d6 100644 --- a/pumpkin-crates/core/src/engine/variables/affine_view.rs +++ b/pumpkin-crates/core/src/engine/variables/affine_view.rs @@ -452,23 +452,23 @@ mod tests { #[test] fn range_of_underlying_domain_maps_range_back_to_inner_domain() { let x = DomainId::new(0); - let domain = |range_start, range_end| RangeOfUnderlyingDomain::Domain { + let range_of_x = |start, end| RangeOfUnderlyingDomain::Domain { domain_id: x, - range_start, - range_end, + start, + end, }; assert_eq!( x.scaled(2).offset(1).range_of_underlying_domain(4, 9), - domain(2, 4) + range_of_x(2, 4) ); assert_eq!( x.scaled(-1).range_of_underlying_domain(-8, -5), - domain(5, 8) + range_of_x(5, 8) ); assert_eq!( x.scaled(-3).offset(1).range_of_underlying_domain(-7, 5), - domain(-1, 2) + range_of_x(-1, 2) ); // No multiple of 2 is in [3, 3]. assert_eq!( diff --git a/pumpkin-crates/core/src/engine/variables/domain_id.rs b/pumpkin-crates/core/src/engine/variables/domain_id.rs index ef00c14c1..1f3a703c9 100644 --- a/pumpkin-crates/core/src/engine/variables/domain_id.rs +++ b/pumpkin-crates/core/src/engine/variables/domain_id.rs @@ -197,8 +197,8 @@ impl IntegerVariable for DomainId { if start <= end { RangeOfUnderlyingDomain::Domain { domain_id: *self, - range_start: start, - range_end: end, + start, + end, } } else { RangeOfUnderlyingDomain::Empty diff --git a/pumpkin-crates/core/src/engine/variables/integer_variable.rs b/pumpkin-crates/core/src/engine/variables/integer_variable.rs index e295a17c4..d21cc0e19 100644 --- a/pumpkin-crates/core/src/engine/variables/integer_variable.rs +++ b/pumpkin-crates/core/src/engine/variables/integer_variable.rs @@ -74,27 +74,26 @@ pub trait IntegerVariable: /// `start..=end` of this variable; see [`RangeOfUnderlyingDomain`]. /// /// For example: - /// - For the domain `x`, `start = 2`, and `end = 5`, this returns `Domain(x, 2, 5)`. - /// - For `y = 2x + 1`, `start = 4`, and `end = 9`, this returns `Domain(x, 2, 4)`. - /// - For `y = -x`, `start = -8`, and `end = -5`, this returns `Domain(x, 5, 8)`. - /// - For `y = 2x`, `start = 3`, and `end = 3`, this returns `Empty`. - /// - For the constant `4`, `start = 2`, and `end = 5`, this returns `Constant(4)`. + /// - for the domain `x`, `start = 2`, and `end = 5`, this returns `Domain(x, 2, 5)`; + /// - for `y = 2x + 1`, `start = 4`, and `end = 9`, this returns `Domain(x, 2, 4)`; + /// - for `y = -x`, `start = -8`, and `end = -5`, this returns `Domain(x, 5, 8)`; + /// - for `y = 2x`, `start = 3`, and `end = 3`, this returns `Empty`; + /// - for the constant `4`, `start = 2`, and `end = 5`, this returns `Constant(4)`. fn range_of_underlying_domain(&self, start: i32, end: i32) -> RangeOfUnderlyingDomain; } /// The values of the underlying domain of an [`IntegerVariable`] which correspond to a range of -/// values `start..=end` of the variable (see [`IntegerVariable::range_of_underlying_domain`]). +/// values of the variable (see [`IntegerVariable::range_of_underlying_domain`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RangeOfUnderlyingDomain { - /// The values `start..=end` of the variable correspond to the (non-empty) range - /// `range_start..=range_end` of the domain `domain_id`. + /// The range corresponds to the non-empty range `start..=end` of the domain `domain_id`. Domain { domain_id: DomainId, - range_start: i32, - range_end: i32, + start: i32, + end: i32, }, - /// The variable is the constant `value`, which is in `start..=end`. + /// The variable is a constant, and its value lies in the range. Constant(i32), - /// No value of the variable can be in `start..=end`. + /// No value of the variable lies in the range. Empty, } diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index 5bfbbc1c3..cc99ccc1d 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -303,48 +303,47 @@ impl PropagationContext<'_> { match var.range_of_underlying_domain(start, end) { RangeOfUnderlyingDomain::Domain { domain_id, - range_start, - range_end, + start, + end, } => self .assignments - .contains_any_in_range(domain_id, range_start, range_end), + .contains_any_in_range(domain_id, start, end), RangeOfUnderlyingDomain::Constant(_) => true, RangeOfUnderlyingDomain::Empty => false, } } - /// Removes the values `start..=end` (both inclusive) from the domain of `var`, i.e., it sets - /// the predicates `[var != v]` for all `start <= v <= end` to true, with the provided reason. + /// Removes the values `start..=end` (both inclusive) from the domain of `var` with the provided + /// `reason`. /// - /// This is equivalent to calling [`PropagationContext::post`] with `[var != v]` for every - /// value `v` in the range (with the same reason), but it is cheaper: the removed values are - /// stored as a range, rather than one value at a time. + /// This has the same effect as calling [`PropagationContext::post`] with `[var != v]` and the + /// same `reason` for every value `v` in the range. + /// It is cheaper, since it removes each run of consecutive values with one trail entry. /// - /// # Notes - /// - The reason should be valid for *every* removed value. - /// - Any values which are already outside of the domain are ignored. - /// - For views, the holes are translated and every maximal run of consecutive values of the - /// underlying domain are removed. - /// - The trigger of the conflict is removal of the last value in the domain. + /// - The `reason` should explain the removal of *every* value in the range. + /// - Values which are not in the domain are skipped. + /// - For a view, the range is mapped to a range of the underlying domain (see + /// [`IntegerVariable::range_of_underlying_domain`]). + /// - If the domain becomes empty, then the removal of its last value triggers the conflict. /// /// # Examples - /// Removing a range which contains an existing hole; the range is split into the runs of - /// values which are still in the domain: + /// Removing a range which contains a hole removes the runs of values around the hole: /// ```text /// x in {0, 1, 2, 3, 7, 8, 9, 10} (i.e., [0, 10] with the hole [4, 6]) /// remove_range(&x, 2, 8, reason) /// x in {0, 1, 9, 10} (trail entries: [2, 3] and [7, 8]) /// ``` /// - /// Removing a range which partially lies outside of the bounds; this moves the lower-bound: + /// Removing a range which starts below the lower-bound moves the lower-bound: /// ```text /// x in [0, 10] /// remove_range(&x, -5, 3, reason) /// x in [4, 10] (trail entry: [0, 3]) /// ``` /// - /// Removing a range of an affine view; the values of the view `y = 2x + 1` in `[4, 9]` (i.e., - /// 5, 7, and 9) correspond to the values `[2, 4]` of `x`: + /// Removing a range of an affine view removes the corresponding range of its underlying domain. + /// The values 5, 7, and 9 of the view `y = 2x + 1` in `[4, 9]` correspond to the values + /// `[2, 4]` of `x`: /// ```text /// x in [0, 10], y = 2x + 1 /// remove_range(&y, 4, 9, reason) @@ -365,53 +364,51 @@ impl PropagationContext<'_> { end: i32, reason: impl Into, ) -> Result<(), EmptyDomainConflict> { - // We reserve a slot for the reason up front, since the trail entries need to refer to it; - // the reason itself is only stored if a value was actually removed (see below). - let slot = self.reason_store.new_slot(); + // The trail entries refer to the reason slot, so the slot is reserved before the removal. + // The reason itself is only stored if a value is removed. + let reason_slot = self.reason_store.new_slot(); let modification_result = match var.range_of_underlying_domain(start, end) { // The values of the underlying domain are removed as runs of consecutive values, // skipping the values which are not in the domain. RangeOfUnderlyingDomain::Domain { domain_id, - range_start, - range_end, + start, + end, } => self.assignments.remove_range_from_domain( domain_id, - range_start, - range_end, - Some(slot.reason_ref()), + start, + end, + Some(reason_slot.reason_ref()), self.notification_engine, ), - // Removing the value of a constant results in an empty domain (since the disequality - // predicate is trivially false). + // Removing the value of a constant empties its domain, since the disequality predicate + // is trivially false. RangeOfUnderlyingDomain::Constant(value) => self.assignments.post_predicate( var.disequality_predicate(value), - Some(slot.reason_ref()), + Some(reason_slot.reason_ref()), self.notification_engine, ), RangeOfUnderlyingDomain::Empty => Ok(false), }; match modification_result { - // None of the values were in the domain, so no trail entry refers to the slot and the - // reason does not need to be stored. + // No value was in the domain, so no trail entry refers to the reason slot. Ok(false) => Ok(()), - // At least one value was removed; the trail entries refer to the slot, so we store - // the reason. Ok(true) => { - let _ = slot.populate( + let _ = reason_slot.populate( self.propagator_id, build_reason(reason, self.reification_literal), ); Ok(()) } - // The domain became empty. The values removed before the last one stay on the trail - // (they are valid propagations with the provided reason), while the removal of the - // last value is undone and reported as the trigger of the conflict, as is done in - // `PropagationContext::post`. + // The domain became empty. + // The values removed before the last value stay on the trail, since the reason + // explains their removal. + // As in `PropagationContext::post`, the removal of the last value is undone and + // reported as the trigger of the conflict. Err(EmptyDomain) => { - let _ = slot.populate( + let _ = reason_slot.populate( self.propagator_id, build_reason(reason, self.reification_literal), ); diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index f58008f9f..8d146d3d9 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -82,7 +82,8 @@ pub struct NogoodPropagator { bumped_nogoods: Vec, /// Used to return lazy reasons temp_nogood_reason: Vec, - /// Describes the domain of the nogood which is propagated by extended nogood propagation. + /// The unassigned predicates over the domain of the 0-th predicate of the nogood that is being + /// propagated by extended nogood propagation; the buffer is reused for every nogood. domain_description: DomainDescription, /// The handle of this instance inside the solver. /// @@ -407,8 +408,8 @@ impl Propagator for NogoodPropagator { // that once). let mut falsified_zeroth = None; - // The description of the domain of the 0-th predicate, which is filled in by the - // extended nogood propagation while looking for a new watcher. + // Extended nogood propagation describes the domain of the 0-th predicate while it + // looks for a new watcher. self.domain_description.reset(); // We start from the index of the last-traversed watcher and circle around after @@ -729,16 +730,18 @@ impl NogoodPropagator { nogood_id: Option, domain_description: &mut DomainDescription, ) -> Result<(), Conflict> { - let is_falsified = get_domain_info(context, nogood, propagated_domain, domain_description); - - if is_falsified { + // A nogood with a falsified predicate is satisfied, so nothing can be propagated. + if nogood + .iter() + .any(|&predicate_id| context.is_predicate_id_falsified(predicate_id)) + { statistics .extended_propagation_statistics .num_extended_propagation_calls += 1; - // The nogood is already falsified return Ok(()); } + domain_description.describe(context, nogood, propagated_domain); Self::propagate_domain_description( context, nogood, @@ -770,15 +773,18 @@ impl NogoodPropagator { .extended_propagation_statistics .num_extended_propagation_calls += 1; - let propagated_domain = domain_description - .domain - .expect("Expected the described domain to be known"); - let lower_bound = domain_description.lower_bound; - let upper_bound = domain_description.upper_bound; - let num_describing_domain = domain_description.num_describing_domain; - let exceptions = &domain_description.exceptions; - - if num_describing_domain == 0 { + let DomainDescription { + described_domain, + lower_bound_predicate, + upper_bound_predicate, + ref exceptions, + num_describing_predicates, + last_describing_predicate_id, + } = *domain_description; + let propagated_domain = + described_domain.expect("Expected the described domain to be known"); + + if num_describing_predicates == 0 { // We could not find another watcher (i.e., all predicats over other variables are // satisfied). However, we could not find a predicate in the nogood which is over // `propgating_domain` *and* unsatisfied. @@ -801,17 +807,16 @@ impl NogoodPropagator { statistics .extended_propagation_statistics .average_num_predicates_describing_domain_when_propagating_extended - .add_term(num_describing_domain); + .add_term(num_describing_predicates); // We perform the standard unit propagation if possible // // TODO: Could use a lazy explanation here - if num_describing_domain == 1 { + if num_describing_predicates == 1 { statistics.num_unit_propagations += 1; - let last_describing_predicate_id = domain_description - .last_describing_predicate_id - .expect("Expected a predicate describing the domain"); + let last_describing_predicate_id = + last_describing_predicate_id.expect("Expected a predicate describing the domain"); let last_describing_predicate = context.get_predicate(last_describing_predicate_id); let reason = if let Some(nogood_id) = nogood_id { @@ -854,7 +859,7 @@ impl NogoodPropagator { // // If there is no such predicate in the nogood then there must be one or more holes, and we // store the minimum value of this. - let lb = lower_bound.map_or_else( + let lb = lower_bound_predicate.map_or_else( || min_exception.unwrap(), |predicate| predicate.get_right_hand_side(), ); @@ -864,7 +869,7 @@ impl NogoodPropagator { // // If there is no such predicate in the nogood then there must be one or more holes, and we // store the maximum value of this. - let ub = upper_bound.map_or_else( + let ub = upper_bound_predicate.map_or_else( || max_exception.unwrap(), |predicate| predicate.get_right_hand_side(), ); @@ -874,12 +879,12 @@ impl NogoodPropagator { let mut propagated = false; // Now we check whether we can do any bound propagation - if upper_bound.is_none() { + if upper_bound_predicate.is_none() { pumpkin_assert_simple!( exceptions.len() > 1 || (!exceptions.is_empty() - && lower_bound.is_some() - && ub > lower_bound.unwrap().get_right_hand_side()), + && lower_bound_predicate.is_some() + && ub > lower_bound_predicate.unwrap().get_right_hand_side()), ); // First, if there is no upper-bound predicate ([x <= v]), then we can propagate the // upper-bound based on the lower-bound predicate and/or the inequality predicates (note @@ -951,7 +956,7 @@ impl NogoodPropagator { } } - if lower_bound.is_none() { + if lower_bound_predicate.is_none() { // First, if there is no lower-bound predicate ([x >= v]), then we can propagate the // lower-bound based on the upper-bound predicate and/or the inequality predicates (note // that there must be one or more holes due to semantic minimisation and unit @@ -1080,8 +1085,9 @@ impl NogoodPropagator { .take_while(|&exception| exception <= ub) .chain(std::iter::once(ub + 1)) { - let gap_start = std::mem::replace(&mut next_gap_start, exception + 1); + let gap_start = next_gap_start; let gap_end = exception - 1; + next_gap_start = exception + 1; // We skip the gaps which are empty or which have already been removed, to avoid // creating a reason for them. @@ -1388,26 +1394,22 @@ impl NogoodPropagator { /// information required by extended nogood propagation. #[derive(Clone, Debug, Default)] pub(crate) struct DomainDescription { - /// The described domain; `None` if no description has been started. - domain: Option, - /// The unassigned lower-bound predicate, if present. - lower_bound: Option, - /// The unassigned upper-bound predicate, if present. - upper_bound: Option, - /// The values of the unassigned disequality predicates; these are strictly increasing once - /// the description is complete. + /// The described domain, or `None` if no description has been started. + described_domain: Option, + lower_bound_predicate: Option, + upper_bound_predicate: Option, + /// The values of the disequality predicates. + /// They are strictly increasing once the description is complete. exceptions: Vec, - /// The number of unassigned predicates describing the domain. - num_describing_domain: usize, - /// The last added unassigned predicate describing the domain. + num_describing_predicates: usize, last_describing_predicate_id: Option, } impl DomainDescription { - /// Marks the description as not started; the remaining fields are only cleared once a new - /// description is started using [`DomainDescription::start`]. + /// Marks the description as not started. + /// The other fields are cleared by the next call to [`DomainDescription::start`]. pub(crate) fn reset(&mut self) { - self.domain = None; + self.described_domain = None; } /// Returns the described domain, starting an empty description of the domain of @@ -1417,7 +1419,7 @@ impl DomainDescription { context: &mut PropagationContext, nogood: &[PredicateId], ) -> DomainId { - match self.domain { + match self.described_domain { Some(domain) => domain, None => { let domain = context.get_predicate(nogood[0]).get_domain(); @@ -1429,11 +1431,11 @@ impl DomainDescription { /// Starts an empty description of the provided `domain`. fn start(&mut self, domain: DomainId) { - self.domain = Some(domain); - self.lower_bound = None; - self.upper_bound = None; + self.described_domain = Some(domain); + self.lower_bound_predicate = None; + self.upper_bound_predicate = None; self.exceptions.clear(); - self.num_describing_domain = 0; + self.num_describing_predicates = 0; self.last_describing_predicate_id = None; } @@ -1443,27 +1445,28 @@ impl DomainDescription { predicate_id: PredicateId, predicate: Predicate, ) { - pumpkin_assert_moderate!(Some(predicate.get_domain()) == self.domain); + pumpkin_assert_moderate!(Some(predicate.get_domain()) == self.described_domain); - self.num_describing_domain += 1; + self.num_describing_predicates += 1; self.last_describing_predicate_id = Some(predicate_id); match predicate.get_predicate_type() { PredicateType::UpperBound => { - pumpkin_assert_simple!(self.upper_bound.is_none()); - self.upper_bound = Some(predicate) + pumpkin_assert_simple!(self.upper_bound_predicate.is_none()); + self.upper_bound_predicate = Some(predicate) } PredicateType::LowerBound => { - pumpkin_assert_simple!(self.lower_bound.is_none()); - self.lower_bound = Some(predicate) + pumpkin_assert_simple!(self.lower_bound_predicate.is_none()); + self.lower_bound_predicate = Some(predicate) } PredicateType::NotEqual => self.exceptions.push(predicate.get_right_hand_side()), PredicateType::Equal => {} } } - /// Completes a description which was created while looking for a new watcher for the watched - /// predicate at index 1, which is satisfied; all predicates except the watched ones have been - /// processed, so only the predicate at index 0 still needs to be added. + /// Completes the description that the search for a new watcher of `nogood[1]` has built. + /// + /// That search visits every predicate except the two watched ones, and `nogood[1]` is + /// satisfied, so only `nogood[0]` remains to be added. fn complete_with_watched_predicates( &mut self, context: &mut PropagationContext, @@ -1479,52 +1482,36 @@ impl DomainDescription { self.complete(); } - /// Completes the description by sorting the exceptions and removing duplicates. - fn complete(&mut self) { - self.exceptions.sort_unstable(); - self.exceptions.dedup(); - } -} - -/// Fills `domain_description` with the unassigned predicates concerning the provided domain and -/// returns whether any predicate in the nogood is falsified; if this is the case, then the -/// description is incomplete. -fn get_domain_info( - context: &mut PropagationContext<'_>, - nogood: &[PredicateId], - propagated_domain: DomainId, - domain_description: &mut DomainDescription, -) -> bool { - domain_description.start(propagated_domain); - - for predicate_id in nogood.iter().copied() { - // First, we filter out all of the predicates which are currently satisfied; if a - // predicate is falsified, then no propagation can take place. - match context.evaluate_predicate_id(predicate_id) { - Some(true) => continue, - Some(false) => return true, - None => {} - } - - let predicate = context.get_predicate(predicate_id); + /// Describes the unassigned predicates of `nogood`, which should all be over `domain`. + fn describe( + &mut self, + context: &mut PropagationContext, + nogood: &[PredicateId], + domain: DomainId, + ) { + self.start(domain); - pumpkin_assert_moderate!( - predicate.get_domain() == propagated_domain, - "Expected {predicate} to be unassigned with {propagated_domain:?}", - ); + for predicate_id in nogood.iter().copied() { + if context.evaluate_predicate_id(predicate_id).is_some() { + continue; + } - // Then we filter out all of the predicates which are not concerning the propagated - // domain id - if predicate.get_domain() != propagated_domain { - continue; + let predicate = context.get_predicate(predicate_id); + pumpkin_assert_moderate!( + predicate.get_domain() == domain, + "Expected the unassigned {predicate} to be over {domain:?}", + ); + self.add_unassigned_predicate(predicate_id, predicate); } - domain_description.add_unassigned_predicate(predicate_id, predicate); + self.complete(); } - domain_description.complete(); - - false + /// Completes the description by sorting the exceptions and removing duplicates. + fn complete(&mut self) { + self.exceptions.sort_unstable(); + self.exceptions.dedup(); + } } /// Methods concerning the watchers and watch lists diff --git a/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs b/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs index 5a29a7994..766926e0d 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/propagation_mode.rs @@ -78,10 +78,10 @@ impl PropagationMode { // In the case of CPIP nogoods, we split into cases dependent on the state of the // predicate which we are processing and on whether it reasons over the same domain // as the predicate for which we are finding a new watcher. - let value = context.evaluate_predicate_id(nogood_predicates[index]); + let truth_value = context.evaluate_predicate_id(nogood_predicates[index]); // A satisfied predicate can never be a new watcher, regardless of its domain. - if value == Some(true) { + if truth_value == Some(true) { return WatcherProcessingStatus::Continue; } @@ -92,13 +92,13 @@ impl PropagationMode { // If the predicate is unassigned or falsified and does not reason over the // same domain as the 0-th predicate, then we have found a new watch. WatcherProcessingStatus::FoundNewWatch - } else if value == Some(false) { + } else if truth_value == Some(false) { // Otherwise, we have found a falsified predicate over the same domain, and we // need to update the zero-th predicate with this predicate. WatcherProcessingStatus::FalsifiedZeroth } else { - // The predicate is unassigned and reasons over the same domain, which is - // required in case extended nogood propagation takes place. + // The predicate is unassigned and reasons over the same domain, so extended + // nogood propagation needs it in the description of the domain. domain_description .add_unassigned_predicate(nogood_predicates[index], predicate); WatcherProcessingStatus::Continue diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs index b1f3d6836..7d80f0e36 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs @@ -378,15 +378,12 @@ impl CumulativePropagationHandler { match self.explanation_type { CumulativeExplanationType::Naive | CumulativeExplanationType::BigStep => { - // We use the same procedure for the explanation using naive and bigstep, note - // that `create_profile_explanation` uses the explanation type to create the - // explanations. + // Naive and big-step explanations are created by the same procedure, since + // `create_profile_explanation` takes the explanation type into account. // - // This explanation does not depend on the removed time-point, so all of the - // time-points are removed at once using the same explanation. - // - // If all of the time-points have already been removed, then we do not need to - // create the explanation. + // Such an explanation does not depend on the removed time-point. + // All time-points are therefore removed at once, with one explanation, which is + // not created when the time-points have already been removed. if !context.contains_any_in_range( &propagating_task.start_variable, lower_bound_removed_time_points, @@ -397,23 +394,13 @@ impl CumulativePropagationHandler { let explanation = self.create_profile_explanation(context, profile, capacity, propagating_task); - // The explanation is checked for every time-point which is removed (i.e., which is - // still in the domain). - pumpkin_assert_extreme!({ - let mut explanation_is_valid = true; - for time_point in - lower_bound_removed_time_points..=upper_bound_removed_time_points - { - if context.contains(&propagating_task.start_variable, time_point) { - explanation_is_valid &= check_explanation( - predicate![propagating_task.start_variable != time_point], - &explanation, - context.domains(), - ); - } - } - explanation_is_valid - }); + pumpkin_assert_extreme!(explains_removed_start_times( + context, + propagating_task, + lower_bound_removed_time_points, + upper_bound_removed_time_points, + &explanation, + )); context.remove_range( &propagating_task.start_variable, lower_bound_removed_time_points, @@ -422,18 +409,16 @@ impl CumulativePropagationHandler { )?; } CumulativeExplanationType::Pointwise => { - // A pointwise explanation explains that `propagating_task` cannot overlap with a - // single time-point `t` of the profile; this means that it explains the removal - // of all start times in `[t - processing_time + 1, t]`. + // A pointwise explanation states that the profile overloads the resource at one + // time-point `t` together with `propagating_task`. + // It therefore explains the removal of every start time in + // `[t - processing_time + 1, t]`. // - // We therefore split the time-points to remove into chunks of at most - // `processing_time` consecutive time-points, which are each removed at once using - // a single explanation point. Going from left to right, for a chunk starting at - // `chunk_start`, we pick the latest explanation point which still explains - // `chunk_start` (i.e., `chunk_start + processing_time - 1`), unless this is after - // the end of the profile. - // - // Note that the explanation point is always in the profile, since + // We split the removed time-points into chunks of at most `processing_time` + // time-points, from left to right, and remove each chunk with one explanation. + // The explanation point of a chunk is its last start time + // `chunk_start + processing_time - 1`, or `profile.end` if that comes first. + // This point lies in the profile, since // `chunk_start >= profile.start - processing_time + 1`. pumpkin_assert_simple!(propagating_task.processing_time > 0); @@ -445,47 +430,35 @@ impl CumulativePropagationHandler { ); let chunk_end = min(explanation_point, upper_bound_removed_time_points); - // If all of the time-points in this chunk have already been removed, then we - // do not need to create the explanation. - if !context.contains_any_in_range( + // A chunk whose time-points have all been removed needs no explanation. + if context.contains_any_in_range( &propagating_task.start_variable, chunk_start, chunk_end, ) { - chunk_start = chunk_end + 1; - continue; + let explanation: PropositionalConjunction = + create_pointwise_propagation_explanation( + explanation_point, + profile, + capacity, + propagating_task.resource_usage, + ) + .collect(); + pumpkin_assert_extreme!(explains_removed_start_times( + context, + propagating_task, + chunk_start, + chunk_end, + &explanation, + )); + context.remove_range( + &propagating_task.start_variable, + chunk_start, + chunk_end, + (explanation, &self.inference_code), + )?; } - let explanation: PropositionalConjunction = - create_pointwise_propagation_explanation( - explanation_point, - profile, - capacity, - propagating_task.resource_usage, - ) - .collect(); - // The explanation is checked for every time-point which is removed (i.e., - // which is still in the domain). - pumpkin_assert_extreme!({ - let mut explanation_is_valid = true; - for time_point in chunk_start..=chunk_end { - if context.contains(&propagating_task.start_variable, time_point) { - explanation_is_valid &= check_explanation( - predicate![propagating_task.start_variable != time_point], - &explanation, - context.domains(), - ); - } - } - explanation_is_valid - }); - context.remove_range( - &propagating_task.start_variable, - chunk_start, - chunk_end, - (explanation, &self.inference_code), - )?; - chunk_start = chunk_end + 1; } } @@ -530,6 +503,25 @@ impl CumulativePropagationHandler { } } +/// Returns whether `explanation` explains the removal of each start time of `task` in +/// `start..=end` which is still in the domain. +fn explains_removed_start_times( + context: &mut PropagationContext, + task: &Rc>, + start: i32, + end: i32, + explanation: &PropositionalConjunction, +) -> bool { + (start..=end).all(|start_time| { + !context.contains(&task.start_variable, start_time) + || check_explanation( + predicate![task.start_variable != start_time], + explanation, + context.domains(), + ) + }) +} + /// Creates an explanation of the conflict caused by `conflict_profile` based on the provided /// `explanation_type`. pub(crate) fn create_conflict_explanation( diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs index ae12b0c67..27611f580 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/test_suite.rs @@ -442,23 +442,28 @@ fn propagator_propagates_holes_in_chunks_with_pointwise_explanations= 6] & [s1 <= 10]), - reason_for(&mut state, predicate!(s2 != removed)) + reason_for(&mut state, predicate!(s2 != start_time)) ); } - for removed in 11..=14 { - assert!(!state.contains(s2, removed)); - let expected = match P::STRATEGY { - // Every time-point is a separate profile, and the start time `removed` is first removed - // by the profile at the time-point `removed` - TimeTableStrategy::PerPoint => conjunction!([s1 >= removed - 4] & [s1 <= removed]), - // The chunk [11, 14] is explained by the time-point 14 of the profile + for start_time in 11..=14 { + assert!(!state.contains(s2, start_time)); + let expected_reason = match P::STRATEGY { + // Every time-point is a separate profile, and the profile at the time-point + // `start_time` is the first to remove the start time `start_time`. + TimeTableStrategy::PerPoint => { + conjunction!([s1 >= start_time - 4] & [s1 <= start_time]) + } + // The chunk [11, 14] is explained by the time-point 14 of the profile. TimeTableStrategy::OverInterval => conjunction!([s1 >= 10] & [s1 <= 14]), }; - assert_eq!(expected, reason_for(&mut state, predicate!(s2 != removed))); + assert_eq!( + expected_reason, + reason_for(&mut state, predicate!(s2 != start_time)) + ); } } From dca09fd72965491cfe26450508aeb8de155f9111 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 15:06:16 +0100 Subject: [PATCH 15/18] refactor: remove extra pass + shortcut in describe domain --- .../propagators/nogoods/nogood_propagator.rs | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index 8d146d3d9..2b8d9457a 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -731,17 +731,13 @@ impl NogoodPropagator { domain_description: &mut DomainDescription, ) -> Result<(), Conflict> { // A nogood with a falsified predicate is satisfied, so nothing can be propagated. - if nogood - .iter() - .any(|&predicate_id| context.is_predicate_id_falsified(predicate_id)) - { + if !domain_description.try_describe(context, nogood, propagated_domain) { statistics .extended_propagation_statistics .num_extended_propagation_calls += 1; return Ok(()); } - domain_description.describe(context, nogood, propagated_domain); Self::propagate_domain_description( context, nogood, @@ -1483,17 +1479,22 @@ impl DomainDescription { } /// Describes the unassigned predicates of `nogood`, which should all be over `domain`. - fn describe( + /// + /// Returns `false` if a predicate of `nogood` is falsified; the description is then + /// incomplete. + fn try_describe( &mut self, context: &mut PropagationContext, nogood: &[PredicateId], domain: DomainId, - ) { + ) -> bool { self.start(domain); for predicate_id in nogood.iter().copied() { - if context.evaluate_predicate_id(predicate_id).is_some() { - continue; + match context.evaluate_predicate_id(predicate_id) { + Some(true) => continue, + Some(false) => return false, + None => {} } let predicate = context.get_predicate(predicate_id); @@ -1505,6 +1506,8 @@ impl DomainDescription { } self.complete(); + + true } /// Completes the description by sorting the exceptions and removing duplicates. From 0555c9d84e5d1f641960f9afcb3e02d979433b24 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 15:12:39 +0100 Subject: [PATCH 16/18] refactor: count removed values instead of removed ranges --- .../core/src/engine/cp/assignments.rs | 32 +++++++++---------- pumpkin-crates/core/src/engine/state.rs | 14 ++++---- .../contexts/propagation_context.rs | 25 +++++++++------ .../propagators/nogoods/nogood_propagator.rs | 4 +-- .../time_table/propagation_handler.rs | 4 +-- 5 files changed, 43 insertions(+), 36 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index f1350bc52..224bc5183 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -629,7 +629,7 @@ impl Assignments { /// The last trail entry is then the disequality predicate for that value, as when a single /// value is removed. /// - /// Returns whether any value was removed, or [`EmptyDomain`] if the domain became empty. + /// Returns the number of removed values, or [`EmptyDomain`] if the domain became empty. pub(crate) fn remove_range_from_domain( &mut self, domain_id: DomainId, @@ -637,14 +637,14 @@ impl Assignments { end: i32, reason: Option, notification_engine: &mut NotificationEngine, - ) -> Result { + ) -> Result { let (lower_bound_before, upper_bound_before) = self.bounds[domain_id]; let first = start.max(lower_bound_before); let last = end.min(upper_bound_before); if first > last { - return self.domains[domain_id].verify_consistency(); + return self.domains[domain_id].verify_consistency().map(|_| 0); } // If all values in the domain are removed, then the upper-bound is removed separately @@ -652,7 +652,7 @@ impl Assignments { let empties_domain = first == lower_bound_before && last == upper_bound_before; let end_of_runs = if empties_domain { last - 1 } else { last }; - let mut removal_took_place = false; + let mut num_removed_values = 0; let mut next_run_from = first; let mut piece_index = self.domains[domain_id].index_of_first_piece_ending_at_or_after(first); @@ -661,7 +661,7 @@ impl Assignments { self.domains[domain_id].next_run_in_domain(next_run_from, end_of_runs, piece_index) { self.remove_run(domain_id, run_start, run_end, reason)?; - removal_took_place = true; + num_removed_values += run_end.abs_diff(run_start) as usize + 1; // The removed run is inserted as a piece directly before the piece following the run. pumpkin_assert_moderate!( @@ -680,18 +680,18 @@ impl Assignments { unreachable!("removing all values from the domain results in an empty domain"); } - if removal_took_place { + if num_removed_values > 0 { notification_engine.event_occurred( lower_bound_before, upper_bound_before, self.domains[domain_id].lower_bound(), self.domains[domain_id].upper_bound(), - removal_took_place, + true, domain_id, ); } - Ok(removal_took_place) + Ok(num_removed_values) } /// Apply the given [`Predicate`] to the integer domains. @@ -2586,16 +2586,16 @@ mod tests { notification_engine.grow(); assignment.new_checkpoint(); - let removed = assignment + let num_removed_values = assignment .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) .expect("non-empty domain"); - assert!(removed); + assert_eq!(num_removed_values, 3); let hole_position = assignment.num_trail_entries() - 1; - let removed = assignment + let num_removed_values = assignment .remove_range_from_domain(x, 2, 8, None, &mut notification_engine) .expect("non-empty domain"); - assert!(removed); + assert_eq!(num_removed_values, 4); assert_eq!( assignment.get_domain_iterator(x).collect::>(), @@ -2690,14 +2690,14 @@ mod tests { .expect("non-empty domain"); let num_trail_entries = assignment.num_trail_entries(); - let removed = assignment + let num_removed_values = assignment .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) .expect("non-empty domain"); - assert!(!removed); - let removed = assignment + assert_eq!(num_removed_values, 0); + let num_removed_values = assignment .remove_range_from_domain(x, 11, 20, None, &mut notification_engine) .expect("non-empty domain"); - assert!(!removed); + assert_eq!(num_removed_values, 0); assert_eq!(assignment.num_trail_entries(), num_trail_entries); } diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index 51e593c60..5fb255709 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -1307,7 +1307,7 @@ mod tests { let constraint_tag = state.new_constraint_tag(); let slot = state.reason_store.new_slot(); - let removed = state + let num_removed_values = state .assignments .remove_range_from_domain( x, @@ -1317,7 +1317,7 @@ mod tests { &mut state.notification_engine, ) .expect("non-empty domain"); - assert!(removed); + assert_eq!(num_removed_values, 4); let _ = slot.populate( PropagatorId::create_from_index(0), StoredReason::Eager( @@ -1356,7 +1356,7 @@ mod tests { let constraint_tag = state.new_constraint_tag(); let slot = state.reason_store.new_slot(); - let removed = state + let num_removed_values = state .assignments .remove_range_from_domain( x, @@ -1366,7 +1366,7 @@ mod tests { &mut state.notification_engine, ) .expect("non-empty domain"); - assert!(removed); + assert_eq!(num_removed_values, 4); let _ = slot.populate( PropagatorId::create_from_index(0), StoredReason::Eager( @@ -1403,14 +1403,16 @@ mod tests { PropagatorId::create_from_index(0), ); // The values -9..=-3 of -2 * x correspond to the values 2..=4 of x. - context + let num_removed_values = context .remove_range(&x.scaled(-2), -9, -3, (conjunction!(), &inference_code)) .expect("non-empty domain"); + assert_eq!(num_removed_values, 3); // A constant is not a view over a domain; removing values other than the constant has no // effect. - context + let num_removed_values = context .remove_range(&5, 6, 10, (conjunction!(), &inference_code)) .expect("non-empty domain"); + assert_eq!(num_removed_values, 0); assert_eq!( state.assignments.get_domain_iterator(x).collect::>(), diff --git a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs index cc99ccc1d..6325d10a0 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -326,6 +326,8 @@ impl PropagationContext<'_> { /// [`IntegerVariable::range_of_underlying_domain`]). /// - If the domain becomes empty, then the removal of its last value triggers the conflict. /// + /// Returns the number of removed values. + /// /// # Examples /// Removing a range which contains a hole removes the runs of values around the hole: /// ```text @@ -363,7 +365,7 @@ impl PropagationContext<'_> { start: i32, end: i32, reason: impl Into, - ) -> Result<(), EmptyDomainConflict> { + ) -> Result { // The trail entries refer to the reason slot, so the slot is reserved before the removal. // The reason itself is only stored if a value is removed. let reason_slot = self.reason_store.new_slot(); @@ -384,23 +386,26 @@ impl PropagationContext<'_> { ), // Removing the value of a constant empties its domain, since the disequality predicate // is trivially false. - RangeOfUnderlyingDomain::Constant(value) => self.assignments.post_predicate( - var.disequality_predicate(value), - Some(reason_slot.reason_ref()), - self.notification_engine, - ), - RangeOfUnderlyingDomain::Empty => Ok(false), + RangeOfUnderlyingDomain::Constant(value) => self + .assignments + .post_predicate( + var.disequality_predicate(value), + Some(reason_slot.reason_ref()), + self.notification_engine, + ) + .map(usize::from), + RangeOfUnderlyingDomain::Empty => Ok(0), }; match modification_result { // No value was in the domain, so no trail entry refers to the reason slot. - Ok(false) => Ok(()), - Ok(true) => { + Ok(0) => Ok(0), + Ok(num_removed_values) => { let _ = reason_slot.populate( self.propagator_id, build_reason(reason, self.reification_literal), ); - Ok(()) + Ok(num_removed_values) } // The domain became empty. // The values removed before the last value stay on the trail, since the reason diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index 2b8d9457a..bbb5e833d 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -1123,12 +1123,12 @@ impl NogoodPropagator { .extended_propagation_statistics .num_variables_propagated += 1; } - result?; + let num_removed_values = result?; propagated = true; statistics .extended_propagation_statistics - .num_extended_disequality_propagations += 1; + .num_extended_disequality_propagations += num_removed_values; } if propagated { diff --git a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs index 7d80f0e36..8f7064c7d 100644 --- a/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs +++ b/pumpkin-crates/propagators/src/propagators/cumulative/time_table/propagation_handler.rs @@ -401,7 +401,7 @@ impl CumulativePropagationHandler { upper_bound_removed_time_points, &explanation, )); - context.remove_range( + let _ = context.remove_range( &propagating_task.start_variable, lower_bound_removed_time_points, upper_bound_removed_time_points, @@ -451,7 +451,7 @@ impl CumulativePropagationHandler { chunk_end, &explanation, )); - context.remove_range( + let _ = context.remove_range( &propagating_task.start_variable, chunk_start, chunk_end, From 42989078a47a5235d44987d5b1eb0b27aae06f53 Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Tue, 1 Dec 2026 15:17:38 +0100 Subject: [PATCH 17/18] refactor: store the start in the piece --- .../core/src/engine/cp/assignments.rs | 76 +++++++++---------- 1 file changed, 35 insertions(+), 41 deletions(-) diff --git a/pumpkin-crates/core/src/engine/cp/assignments.rs b/pumpkin-crates/core/src/engine/cp/assignments.rs index 224bc5183..999c5d544 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -332,11 +332,11 @@ impl Assignments { // Add holes, except the ones made at the root and the ones outside the bounds. // Since a bound value cannot be in a hole, we can use '<' and '>'. - for &(start, piece) in &self.domains[domain_id].holes { + for piece in &self.domains[domain_id].holes { if piece.update_info.checkpoint == 0 { continue; } - for removed_value in start..=piece.end { + for removed_value in piece.start..=piece.end { if domain.lower_bound() < removed_value && removed_value < domain.upper_bound() { predicates.push(predicate![domain_id != removed_value]); } @@ -666,8 +666,8 @@ impl Assignments { // The removed run is inserted as a piece directly before the piece following the run. pumpkin_assert_moderate!( { - let (piece_start, piece) = self.domains[domain_id].holes[index_after_run]; - piece_start == run_start && piece.end == run_end + let piece = self.domains[domain_id].holes[index_after_run]; + piece.start == run_start && piece.end == run_end }, "the removed run should be stored at the tracked index" ); @@ -1044,10 +1044,9 @@ struct PairDecisionLevelTrailPosition { /// A piece of consecutive values `[start, end]` (both inclusive) which were removed from a domain /// at the same time. -/// The piece is stored in [`IntegerDomain::holes`] next to its first value `start`. #[derive(Clone, Copy, Debug)] struct HolePiece { - /// The last value of the removed piece (inclusive). + start: i32, end: i32, update_info: PairDecisionLevelTrailPosition, } @@ -1089,13 +1088,12 @@ struct IntegerDomain { /// This is done to avoid going through 'hole_updates'. /// /// Each entry is a piece of consecutive values removed by one trail entry. - /// It consists of the first value of the piece and the [`HolePiece`] with the rest. /// The pieces are disjoint. /// Adjacent pieces are not merged, so that the time of removal stays known for every value. /// - /// The entries are sorted by their first value, so a binary search finds the piece containing - /// a value. - holes: Vec<(i32, HolePiece)>, + /// The pieces are sorted by their start, so a binary search finds the piece containing a + /// value. + holes: Vec, // Records the trail entry at which all of the root bounds are true initial_bounds_below_trail: usize, /// The holes that exist in the input problem. @@ -1227,8 +1225,7 @@ impl IntegerDomain { /// Returns the index (in [`IntegerDomain::holes`]) of the first piece which starts after /// `value`; the piece before it (if any) is the last piece which starts at or before `value`. fn index_of_first_piece_after(&self, value: i32) -> usize { - self.holes - .partition_point(|&(piece_start, _)| piece_start <= value) + self.holes.partition_point(|piece| piece.start <= value) } /// Returns the index (in [`IntegerDomain::holes`]) of the first piece which ends at or after @@ -1238,14 +1235,14 @@ impl IntegerDomain { /// For example, with the pieces `[[2, 3], [4, 6], [9, 9]]`, this returns 1 for `value = 5` /// (the piece `[4, 6]` contains it), 2 for `value = 7`, and 3 for `value = 10`. fn index_of_first_piece_ending_at_or_after(&self, value: i32) -> usize { - self.holes.partition_point(|&(_, piece)| piece.end < value) + self.holes.partition_point(|piece| piece.end < value) } - /// Returns the removed piece which contains `value` together with its first value, if any. - fn piece_containing(&self, value: i32) -> Option<(i32, HolePiece)> { + /// Returns the removed piece which contains `value`, if any. + fn piece_containing(&self, value: i32) -> Option { let index = self.index_of_first_piece_after(value).checked_sub(1)?; - let (piece_start, piece) = self.holes[index]; - (value <= piece.end).then_some((piece_start, piece)) + let piece = self.holes[index]; + (value <= piece.end).then_some(piece) } fn is_hole(&self, value: i32) -> bool { @@ -1268,7 +1265,7 @@ impl IntegerDomain { // In case the hole is made at the given trail position or earlier, // the value is not in the domain. - if let Some((_, piece)) = self.piece_containing(value) + if let Some(piece) = self.piece_containing(value) && piece.update_info.trail_position <= trail_position { return false; @@ -1318,16 +1315,14 @@ impl IntegerDomain { let index = self.index_of_first_piece_after(start); self.holes.insert( index, - ( + HolePiece { start, - HolePiece { - end, - update_info: PairDecisionLevelTrailPosition { - checkpoint, - trail_position, - }, + end, + update_info: PairDecisionLevelTrailPosition { + checkpoint, + trail_position, }, - ), + }, ); // Check if removing the values triggers a lower bound update. @@ -1369,8 +1364,8 @@ impl IntegerDomain { // Typically, this needs a single binary search. let first_piece_to_check = self.index_of_first_piece_after(first).saturating_sub(1); let mut candidate = first; - for &(piece_start, piece) in &self.holes[first_piece_to_check..] { - let contains_candidate = piece_start <= candidate && candidate <= piece.end; + for piece in &self.holes[first_piece_to_check..] { + let contains_candidate = piece.start <= candidate && candidate <= piece.end; if candidate > last || !contains_candidate { break; } @@ -1406,8 +1401,8 @@ impl IntegerDomain { ) -> Option<(i32, i32, usize)> { // The run starts after the (adjacent) pieces which contain `from`. let mut run_start = from; - while let Some(&(piece_start, piece)) = self.holes.get(piece_index) - && piece_start <= run_start + while let Some(piece) = self.holes.get(piece_index) + && piece.start <= run_start { run_start = piece.end + 1; piece_index += 1; @@ -1421,7 +1416,7 @@ impl IntegerDomain { let run_end = self .holes .get(piece_index) - .map_or(to, |&(piece_start, _)| to.min(piece_start - 1)); + .map_or(to, |piece| to.min(piece.start - 1)); Some((run_start, run_end, piece_index)) } @@ -1462,9 +1457,9 @@ impl IntegerDomain { // Jump over the removed pieces which contain the upper bound; note that pieces can be // adjacent, so this may jump over several pieces. while self.lower_bound() <= self.upper_bound() - && let Some((start, _)) = self.piece_containing(self.upper_bound()) + && let Some(piece) = self.piece_containing(self.upper_bound()) { - self.upper_bound_updates.last_mut().unwrap().bound = start - 1; + self.upper_bound_updates.last_mut().unwrap().bound = piece.start - 1; } } @@ -1506,7 +1501,7 @@ impl IntegerDomain { // Jump over the removed pieces which contain the lower bound; note that pieces can be // adjacent, so this may jump over several pieces. while self.lower_bound() <= self.upper_bound() - && let Some((_, piece)) = self.piece_containing(self.lower_bound()) + && let Some(piece) = self.piece_containing(self.lower_bound()) { self.lower_bound_updates.last_mut().unwrap().bound = piece.end + 1; } @@ -1571,9 +1566,10 @@ impl IntegerDomain { ); let index = self.index_of_first_piece_after(hole_update.start) - 1; - let (removed_start, removed_piece) = self.holes.remove(index); + let removed_piece = self.holes.remove(index); pumpkin_assert_moderate!( - removed_start == hole_update.start && removed_piece.end == hole_update.end + removed_piece.start == hole_update.start + && removed_piece.end == hole_update.end ); // If the hole moved a bound, then its values are counted by the bound change. if !hole_update.triggered_lower_bound_update @@ -1666,7 +1662,7 @@ impl IntegerDomain { // Check the explictly stored holes. // If the value has been removed explicitly, // then the stored time is the first time the value was removed. - if let Some((_, piece)) = self.piece_containing(value) { + if let Some(piece) = self.piece_containing(value) { Some(piece.update_info) } else { // Otherwise, check the case when the lower/upper bound surpassed the value. @@ -1746,9 +1742,7 @@ impl IntegerDomain { /// Returns all of the holes (currently) in the domain of `var` (including ones which were /// created at previous decision levels). pub(crate) fn get_holes(&self) -> impl Iterator + '_ { - self.holes - .iter() - .flat_map(|&(start, piece)| start..=piece.end) + self.holes.iter().flat_map(|piece| piece.start..=piece.end) } } @@ -1790,7 +1784,7 @@ impl Iterator for IntegerDomainIterator<'_> { // If the current value is within the bounds, but is not in the domain, // jump over the removed pieces to the next non-hole value. while self.current_value <= self.domain.upper_bound() - && let Some((_, piece)) = self.domain.piece_containing(self.current_value) + && let Some(piece) = self.domain.piece_containing(self.current_value) { self.current_value = piece.end + 1; } From 84f7b375f544d2f207b0128a1cccead8f1db98ae Mon Sep 17 00:00:00 2001 From: Imko Marijnissen Date: Wed, 2 Dec 2026 15:17:14 +0100 Subject: [PATCH 18/18] refactor: prevent individual resolutions based on each individual disequality predicate --- pumpkin-crates/core/src/engine/state.rs | 206 +++++++++++++++--------- 1 file changed, 131 insertions(+), 75 deletions(-) diff --git a/pumpkin-crates/core/src/engine/state.rs b/pumpkin-crates/core/src/engine/state.rs index 5fb255709..81e11b915 100644 --- a/pumpkin-crates/core/src/engine/state.rs +++ b/pumpkin-crates/core/src/engine/state.rs @@ -1010,31 +1010,31 @@ impl State { if trail_lower_bound > input_lower_bound { reason_buffer.extend(std::iter::once(trail_entry.predicate)); } - // Otherwise, the input bound is strictly greater than the trailed - // bound. This means the reason is due to holes in the domain. + // Otherwise, the input lower bound is strictly greater than the trail lower + // bound. + // This means that the lower bound skipped over removed values. else { // Note that the bounds cannot be equal. // If the bound were equal, the predicate would be explicitly on the // trail, so we would have detected this case earlier. pumpkin_assert_simple!(trail_lower_bound < input_lower_bound); - // The reason for the propagation of the input predicate [x >= a] is - // because [x >= a-1] & [x != a]. Conflict analysis will then - // recursively decompose these further. - - // Note that we do not need to worry about decreasing the lower - // bounds so much so that it reaches its root lower bound, for which - // there is no reason since it is given as input to the problem. - // We cannot reach the original lower bound since in the 1uip, we - // only look for reasons for predicates from the current decision - // level, and we never look for reasons at the root level. - - let one_less_bound_predicate = - predicate!(domain_id >= input_lower_bound - 1); - - let not_equals_predicate = predicate!(domain_id != input_lower_bound - 1); - reason_buffer.extend(std::iter::once(one_less_bound_predicate)); - reason_buffer.extend(std::iter::once(not_equals_predicate)); + // The values `trail_lower_bound..input_lower_bound` were removed before + // this trail entry, so the lower bound skipped over them. + // The reason for the input predicate [x >= a] is therefore + // [x >= t] & [x != t] & ... & [x != a - 1], with t the trail lower bound. + // + // Listing the removed values directly saves conflict analysis one + // resolution step per value, compared to explaining [x >= a] by + // [x >= a - 1] & [x != a - 1]. + reason_buffer.extend(std::iter::once(trail_entry.predicate)); + self.add_removed_values_to_reason( + domain_id, + trail_lower_bound, + input_lower_bound - 1, + trail_position, + reason_buffer, + ); } } (PredicateType::LowerBound, PredicateType::NotEqual) => { @@ -1081,23 +1081,22 @@ impl State { if trail_upper_bound < input_upper_bound { reason_buffer.extend(std::iter::once(trail_entry.predicate)); } else { - // I think it cannot be that the bounds are equal, since otherwise we - // would have found the predicate explicitly on the trail. + // The bounds cannot be equal, since then the input predicate would be + // explicitly on the trail. pumpkin_assert_simple!(trail_upper_bound > input_upper_bound); - // The input upper bound is greater than the trail predicate, meaning - // that holes in the domain also played a rule in lowering the upper - // bound. - - // The reason of the input predicate [x <= a] is computed recursively as - // the reason for [x <= a + 1] & [x != a + 1]. - - let new_ub_predicate = - predicate!(predicate.get_domain() <= input_upper_bound + 1); - let not_equal_predicate = - predicate!(predicate.get_domain() != input_upper_bound + 1); - reason_buffer.extend(std::iter::once(new_ub_predicate)); - reason_buffer.extend(std::iter::once(not_equal_predicate)); + // The values `input_upper_bound + 1..=trail_upper_bound` were removed + // before this trail entry, so the upper bound skipped over them. + // The reason for the input predicate [x <= a] is therefore + // [x <= t] & [x != a + 1] & ... & [x != t], with t the trail upper bound. + reason_buffer.extend(std::iter::once(trail_entry.predicate)); + self.add_removed_values_to_reason( + predicate.get_domain(), + input_upper_bound + 1, + trail_upper_bound, + trail_position, + reason_buffer, + ); } } (PredicateType::UpperBound, PredicateType::NotEqual) => { @@ -1142,53 +1141,71 @@ impl State { // bound predicate. This means that creating the hole in the domain resulted // in raising the lower bound. - // I think this holds. The not_equals_constant cannot be greater, since that - // would not impact the lower bound. It can also not be the same, since - // creating a hole cannot result in the lower bound being raised to the - // hole, there must be some other reason for that to happen, which we would - // find earlier. - pumpkin_assert_simple!(input_lower_bound > not_equal_constant); + let domain_id = predicate.get_domain(); - // The reason for the input predicate [x >= a] is computed recursively as - // the reason for [x >= a - 1] & [x != a - 1]. - let new_lb_predicate = - predicate!(predicate.get_domain() >= input_lower_bound - 1); - let new_not_equals_predicate = - predicate!(predicate.get_domain() != input_lower_bound - 1); + // Removing values raises the lower bound only if the first removed value is + // the lower bound. + // So the lower bound before this trail entry was `not_equal_constant`. + pumpkin_assert_eq_simple!( + self.assignments + .get_lower_bound_at_trail_position(domain_id, trail_position - 1), + not_equal_constant + ); + // The input predicate became true at this trail entry, so the input lower + // bound is above `not_equal_constant`. + pumpkin_assert_simple!(input_lower_bound > not_equal_constant); - reason_buffer.extend(std::iter::once(new_lb_predicate)); - reason_buffer.extend(std::iter::once(new_not_equals_predicate)); + // The lower bound skipped over the values + // `not_equal_constant..input_lower_bound`, which were removed by this trail + // entry or before it. + // The reason for the input predicate [x >= a] is therefore + // [x >= c] & [x != c] & ... & [x != a - 1], with c the not-equal constant. + reason_buffer + .extend(std::iter::once(predicate!(domain_id >= not_equal_constant))); + self.add_removed_values_to_reason( + domain_id, + not_equal_constant, + input_lower_bound - 1, + trail_position, + reason_buffer, + ); } (PredicateType::NotEqual, PredicateType::UpperBound) => { let not_equal_constant = trail_entry.predicate.get_right_hand_side(); let input_upper_bound = predicate.get_right_hand_side(); // The trail predicate is not equals, but the input predicate is an upper // bound predicate. This means that creating the hole in the domain resulted - // in lower the upper bound. - - // I think this holds. The not_equals_constant cannot be smaller, since that - // would not impact the upper bound. It can also not be the same, since - // creating a hole cannot result in the upper bound being lower to the - // hole, there must be some other reason for that to happen, which we would - // find earlier. - // - // If the trail entry removed the values - // `not_equal_constant..=last_removed_value`, then it lowered the upper bound - // below `not_equal_constant`. - // Any upper-bound below `last_removed_value` then became true at this trail - // entry. + // in lowering the upper bound. + let domain_id = predicate.get_domain(); + // The trail entry removed the values `not_equal_constant..=last_removed_value`. let last_removed_value = trail_entry.range_end.unwrap_or(not_equal_constant); - pumpkin_assert_simple!(input_upper_bound < last_removed_value); - // The reason for the input predicate [x <= a] is computed recursively as - // the reason for [x <= a + 1] & [x != a + 1]. - let new_ub_predicate = - predicate!(predicate.get_domain() <= input_upper_bound + 1); - let new_not_equals_predicate = - predicate!(predicate.get_domain() != input_upper_bound + 1); + // Removing values lowers the upper bound only if the last removed value is + // the upper bound. + // So the upper bound before this trail entry was `last_removed_value`. + pumpkin_assert_eq_simple!( + self.assignments + .get_upper_bound_at_trail_position(domain_id, trail_position - 1), + last_removed_value + ); + // The input predicate became true at this trail entry, so the input upper + // bound is below `last_removed_value`. + pumpkin_assert_simple!(input_upper_bound < last_removed_value); - reason_buffer.extend(std::iter::once(new_ub_predicate)); - reason_buffer.extend(std::iter::once(new_not_equals_predicate)); + // The upper bound skipped over the values + // `input_upper_bound + 1..=last_removed_value`, which were removed by this + // trail entry or before it. + // The reason for the input predicate [x <= a] is therefore + // [x <= e] & [x != a + 1] & ... & [x != e], with e the last removed value. + reason_buffer + .extend(std::iter::once(predicate!(domain_id <= last_removed_value))); + self.add_removed_values_to_reason( + domain_id, + input_upper_bound + 1, + last_removed_value, + trail_position, + reason_buffer, + ); } (PredicateType::NotEqual, PredicateType::Equal) => { let equality_constant = predicate.get_right_hand_side(); @@ -1224,6 +1241,32 @@ impl State { None } } + + /// Adds `[domain_id != value]` to `reason_buffer` for every value in `from..=to`. + /// + /// Each of these values should be removed from the domain at or before `trail_position`. + fn add_removed_values_to_reason( + &self, + domain_id: DomainId, + from: i32, + to: i32, + trail_position: usize, + reason_buffer: &mut impl Extend, + ) { + pumpkin_assert_moderate!( + (from..=to).all( + |value| !self.assignments.is_value_in_domain_at_trail_position( + domain_id, + value, + trail_position + ) + ), + "the values {from}..={to} of {domain_id} should be removed at or before trail \ + position {trail_position}" + ); + + reason_buffer.extend((from..=to).map(|value| predicate!(domain_id != value))); + } } impl State { @@ -1337,8 +1380,8 @@ mod tests { assert!(inference_code.is_some()); assert_eq!(reason_buffer, vec![predicate!(y >= 5)]); - // The lower-bound which was raised by the range is explained using the last removed - // value. + // Removing the range raised the lower bound to 4. + // The reason for [x >= 4] is the previous lower bound [x >= 0] and the removed values. let mut reason_buffer = vec![]; let inference_code = state.get_propagation_reason( predicate!(x >= 4), @@ -1346,7 +1389,16 @@ mod tests { CurrentNogood::empty(), ); assert!(inference_code.is_none()); - assert_eq!(reason_buffer, vec![predicate!(x >= 3), predicate!(x != 3)]); + assert_eq!( + reason_buffer, + vec![ + predicate!(x >= 0), + predicate!(x != 0), + predicate!(x != 1), + predicate!(x != 2), + predicate!(x != 3) + ] + ); } #[test] @@ -1376,7 +1428,8 @@ mod tests { ); // The range [7, 10] lowered the upper-bound to 6; an upper-bound within the range is - // explained using the next removed value. + // explained by the upper-bound before the range was removed together with the removed + // values above it. let mut reason_buffer = vec![]; let inference_code = state.get_propagation_reason( predicate!(x <= 8), @@ -1384,7 +1437,10 @@ mod tests { CurrentNogood::empty(), ); assert!(inference_code.is_none()); - assert_eq!(reason_buffer, vec![predicate!(x <= 9), predicate!(x != 9)]); + assert_eq!( + reason_buffer, + vec![predicate!(x <= 10), predicate!(x != 9), predicate!(x != 10)] + ); } #[test]