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..27606746e 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; @@ -10,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; @@ -88,9 +91,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 +117,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 +361,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 +396,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 +422,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,17 +466,20 @@ 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 (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 { @@ -473,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. @@ -500,6 +521,7 @@ impl WorkingNogood { self.add_predicate_current_checkpoint( predicate, + trail_position, context, predicate_id_generator, mode, @@ -746,21 +768,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/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/conflict_resolving/conflict_analysis_context.rs b/pumpkin-crates/core/src/conflict_resolving/conflict_analysis_context.rs index c27ea019e..aa161860a 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,13 +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_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 8fc4c45db..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; @@ -795,68 +794,83 @@ 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, - ); + // 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() { + 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); + } + + // 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 30db10012..999c5d544 100644 --- a/pumpkin-crates/core/src/engine/cp/assignments.rs +++ b/pumpkin-crates/core/src/engine/cp/assignments.rs @@ -1,5 +1,4 @@ use crate::basic_types::Trail; -use crate::containers::HashMap; use crate::containers::KeyedVec; use crate::engine::cp::reason::ReasonRef; use crate::engine::notifications::NotificationEngine; @@ -131,6 +130,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 { @@ -138,6 +138,7 @@ impl Assignments { old_lower_bound: lower_bound, old_upper_bound: upper_bound, reason: None, + range_end: None, }); let _ = self.domains.push(IntegerDomain::new( @@ -217,13 +218,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 } } @@ -325,17 +330,16 @@ impl Assignments { predicates.push(predicate![domain_id <= domain.upper_bound()]); } - // Add holes. - for hole in &self.domains[domain_id].holes { - // 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]); + // 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 piece in &self.domains[domain_id].holes { + if piece.update_info.checkpoint == 0 { + continue; + } + 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]); + } } } predicates @@ -352,6 +356,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, @@ -376,6 +386,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 { @@ -420,6 +441,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -460,6 +482,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -501,6 +524,7 @@ impl Assignments { old_lower_bound, old_upper_bound, reason, + range_end: None, }); let checkpoint = self.get_checkpoint(); @@ -534,7 +558,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); @@ -543,16 +590,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_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; @@ -560,13 +608,90 @@ 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 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 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 the number of removed values, 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().map(|_| 0); + } + + // 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 end_of_runs = if empties_domain { last - 1 } else { last }; + + 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); + + while let Some((run_start, run_end, index_after_run)) = + 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)?; + 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!( + { + 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" + ); + piece_index = index_after_run + 1; + next_run_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 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(), + true, + domain_id, + ); + } + + Ok(num_removed_values) } /// Apply the given [`Predicate`] to the integer domains. @@ -774,26 +899,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 entry.predicate.is_not_equal_predicate() - && add_on_lower_bound + add_on_upper_bound == 0 - { - self.pruned_values -= 1; - } - 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(); @@ -826,7 +940,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(); @@ -853,7 +967,7 @@ impl Assignments { self.trail .iter() .find_map(|entry| { - if entry.predicate == predicate { + if entry.covers(predicate) { entry.reason } else { None @@ -874,6 +988,52 @@ 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 + } + }) + } } #[derive(Clone, Copy, Debug)] @@ -882,6 +1042,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. +#[derive(Clone, Copy, Debug)] +struct HolePiece { + start: i32, + end: i32, + update_info: PairDecisionLevelTrailPosition, +} + #[derive(Clone, Debug)] struct BoundUpdateInfo { bound: i32, @@ -891,7 +1060,11 @@ struct BoundUpdateInfo { #[derive(Clone, Debug)] struct HoleUpdateInfo { - removed_value: i32, + /// 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`. + end: i32, checkpoint: usize, @@ -913,9 +1086,14 @@ 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 removed by one trail entry. + /// The pieces are disjoint. + /// Adjacent pieces are not merged, so that the time of removal stays known for every value. + /// + /// 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. @@ -1044,10 +1222,35 @@ 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| 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 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 = self.holes[index]; + (value <= piece.end).then_some(piece) + } + + fn is_hole(&self, value: i32) -> bool { + self.piece_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 +1265,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.piece_containing(value) + && piece.update_info.trail_position <= trail_position { return false; } @@ -1072,54 +1275,149 @@ 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.holes.contains_key(&removed_value) - { + if !self.contains(removed_value) { return false; } + 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_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!( + (start..=end).all(|value| !self.is_hole(value)), + "the removed values should not overlap with a hole" + ); + self.hole_updates.push(HoleUpdateInfo { - removed_value, + start, + end, checkpoint, triggered_lower_bound_update: false, triggered_upper_bound_update: false, }); // 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, - 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, + HolePiece { + start, + end, + update_info: PairDecisionLevelTrailPosition { + checkpoint, + trail_position, + }, }, ); - 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 whether any of the values `from..=to` is in the domain. + 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; + } + + // The bounds are always in the domain. + if first == self.lower_bound() || last == self.upper_bound() { + return true; + } + + // 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 in &self.holes[first_piece_to_check..] { + let contains_candidate = piece.start <= candidate && candidate <= piece.end; + if candidate > last || !contains_candidate { + break; + } + candidate = piece.end + 1; + } + + candidate <= last + } + + /// 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. + /// + /// 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`]). + /// + /// 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; + while let Some(piece) = self.holes.get(piece_index) + && piece.start <= run_start + { + run_start = piece.end + 1; + piece_index += 1; + } + + 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| to.min(piece.start - 1)); + Some((run_start, run_end, piece_index)) } fn debug_is_valid_upper_bound_domain_update( @@ -1156,10 +1454,12 @@ 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(piece) = self.piece_containing(self.upper_bound()) { - self.upper_bound_updates.last_mut().unwrap().bound -= 1; + self.upper_bound_updates.last_mut().unwrap().bound = piece.start - 1; } } @@ -1198,10 +1498,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.piece_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 +1514,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()) } } @@ -1225,8 +1527,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); @@ -1244,17 +1555,28 @@ 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.removed_value == not_equal_constant); + pumpkin_assert_moderate!( + hole_update.start == not_equal_constant && hole_update.end == range_end + ); - let _ = self - .holes - .remove(¬_equal_constant) - .expect("Must be present."); + let index = self.index_of_first_piece_after(hole_update.start) - 1; + let removed_piece = self.holes.remove(index); + pumpkin_assert_moderate!( + 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 + && !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(); @@ -1287,6 +1609,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 { @@ -1336,8 +1662,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.piece_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 +1724,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 +1736,13 @@ 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(|piece| piece.start..=piece.end) } } @@ -1456,11 +1782,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.piece_containing(self.current_value) { - self.current_value += 1; + self.current_value = piece.end + 1; } result } @@ -2245,4 +2571,184 @@ 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 num_removed_values = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + assert_eq!(num_removed_values, 3); + let hole_position = assignment.num_trail_entries() - 1; + + let num_removed_values = assignment + .remove_range_from_domain(x, 2, 8, None, &mut notification_engine) + .expect("non-empty domain"); + assert_eq!(num_removed_values, 4); + + 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 num_removed_values = assignment + .remove_range_from_domain(x, 4, 6, None, &mut notification_engine) + .expect("non-empty domain"); + 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_eq!(num_removed_values, 0); + + 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), + ] + ); + } + + #[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/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..81e11b915 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,15 +305,35 @@ 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.is_on_trail_at(predicate, trail_position)) } - /// Returns whether the trail position of the provided [`Predicate`]. + /// 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. + /// + /// # 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 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) } + + /// 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. @@ -754,11 +775,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); + } } } @@ -884,13 +905,40 @@ 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, 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 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, + 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 @@ -906,20 +954,19 @@ 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: - // 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( @@ -963,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) => { @@ -1034,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) => { @@ -1095,46 +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. - pumpkin_assert_simple!(input_upper_bound < not_equal_constant); - - // 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); - - reason_buffer.extend(std::iter::once(new_ub_predicate)); - reason_buffer.extend(std::iter::once(new_not_equals_predicate)); + // 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); + + // 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); + + // 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(); @@ -1170,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 { @@ -1193,11 +1290,14 @@ 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::propagation::PropagationContext; use crate::state::CurrentNogood; use crate::state::PropagatorId; use crate::state::State; + use crate::variables::TransformableVariable; declare_inference_label!(TestLabel); @@ -1241,4 +1341,140 @@ 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 constraint_tag = state.new_constraint_tag(); + let slot = state.reason_store.new_slot(); + let num_removed_values = state + .assignments + .remove_range_from_domain( + x, + 0, + 3, + Some(slot.reason_ref()), + &mut state.notification_engine, + ) + .expect("non-empty domain"); + assert_eq!(num_removed_values, 4); + let _ = slot.populate( + PropagatorId::create_from_index(0), + 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 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!(reason_buffer, vec![predicate!(y >= 5)]); + + // 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), + &mut reason_buffer, + CurrentNogood::empty(), + ); + assert!(inference_code.is_none()); + assert_eq!( + reason_buffer, + vec![ + predicate!(x >= 0), + predicate!(x != 0), + predicate!(x != 1), + predicate!(x != 2), + 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 constraint_tag = state.new_constraint_tag(); + let slot = state.reason_store.new_slot(); + let num_removed_values = state + .assignments + .remove_range_from_domain( + x, + 7, + 10, + Some(slot.reason_ref()), + &mut state.notification_engine, + ) + .expect("non-empty domain"); + assert_eq!(num_removed_values, 4); + let _ = slot.populate( + PropagatorId::create_from_index(0), + 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 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), + &mut reason_buffer, + CurrentNogood::empty(), + ); + assert!(inference_code.is_none()); + assert_eq!( + reason_buffer, + vec![predicate!(x <= 10), predicate!(x != 9), predicate!(x != 10)] + ); + } + + #[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 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( + &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. + 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. + 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::>(), + 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/engine/variables/affine_view.rs b/pumpkin-crates/core/src/engine/variables/affine_view.rs index 9142f0ba5..ea141b1d6 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 range_of_x = |start, end| RangeOfUnderlyingDomain::Domain { + domain_id: x, + start, + end, + }; + + assert_eq!( + x.scaled(2).offset(1).range_of_underlying_domain(4, 9), + range_of_x(2, 4) + ); + assert_eq!( + x.scaled(-1).range_of_underlying_domain(-8, -5), + range_of_x(5, 8) + ); + assert_eq!( + x.scaled(-3).offset(1).range_of_underlying_domain(-7, 5), + range_of_x(-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..1f3a703c9 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, + start, + 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..d21cc0e19 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,31 @@ 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 of the variable (see [`IntegerVariable::range_of_underlying_domain`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RangeOfUnderlyingDomain { + /// The range corresponds to the non-empty range `start..=end` of the domain `domain_id`. + Domain { + domain_id: DomainId, + start: i32, + end: i32, + }, + /// The variable is a constant, and its value lies in the range. + Constant(i32), + /// No value of the variable lies in the range. + 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/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..6325d10a0 100644 --- a/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs +++ b/pumpkin-crates/core/src/propagation/contexts/propagation_context.rs @@ -29,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. /// @@ -288,6 +289,144 @@ 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 var.range_of_underlying_domain(start, end) { + RangeOfUnderlyingDomain::Domain { + domain_id, + start, + end, + } => self + .assignments + .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` with the provided + /// `reason`. + /// + /// 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. + /// + /// - 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. + /// + /// Returns the number of removed values. + /// + /// # Examples + /// 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 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 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) + /// 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, + var: &Var, + start: i32, + end: i32, + reason: impl Into, + ) -> 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(); + + 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, + start, + end, + } => self.assignments.remove_range_from_domain( + domain_id, + start, + end, + Some(reason_slot.reason_ref()), + self.notification_engine, + ), + // 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, + ) + .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(0) => Ok(0), + Ok(num_removed_values) => { + let _ = reason_slot.populate( + self.propagator_id, + build_reason(reason, self.reification_literal), + ); + Ok(num_removed_values) + } + // 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 _ = reason_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( diff --git a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs index 9a80677d6..bbb5e833d 100644 --- a/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs +++ b/pumpkin-crates/core/src/propagators/nogoods/nogood_propagator.rs @@ -82,6 +82,9 @@ pub struct NogoodPropagator { bumped_nogoods: Vec, /// Used to return lazy reasons temp_nogood_reason: Vec, + /// 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. /// /// Used during nogood cleanup. A nogood can only be removed if it is not propagated in the @@ -191,6 +194,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 +324,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 +408,10 @@ impl Propagator for NogoodPropagator { // that once). let mut falsified_zeroth = None; + // 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 // reaching the end of the nogood to ensure that all possible watcher are // considered. @@ -412,6 +423,7 @@ impl Propagator for NogoodPropagator { &mut context, nogood_predicates, i, + &mut self.domain_description, ) { WatcherProcessingStatus::Continue => continue, WatcherProcessingStatus::FoundNewWatch => { @@ -485,13 +497,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,37 +721,66 @@ 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> { + // A nogood with a falsified predicate is satisfied, so nothing can be propagated. + if !domain_description.try_describe(context, nogood, propagated_domain) { + statistics + .extended_propagation_statistics + .num_extended_propagation_calls += 1; + 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, + let DomainDescription { + described_domain, + lower_bound_predicate, + upper_bound_predicate, + ref exceptions, + num_describing_predicates, last_describing_predicate_id, - is_falsified, - ) = get_domain_info(context, nogood, propagated_domain); + } = *domain_description; + let propagated_domain = + described_domain.expect("Expected the described domain to be known"); - if is_falsified { - // The nogood is already falsified - return Ok(()); - } - - if num_describing_domain == 0 { + 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. @@ -743,14 +803,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 = + 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 +843,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 // @@ -803,7 +855,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(), ); @@ -813,7 +865,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(), ); @@ -823,12 +875,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 @@ -900,7 +952,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 @@ -1005,49 +1057,78 @@ 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) + // 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. + // + // Since the exceptions are sorted and contain no duplicates (see + // `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() + .copied() + .take_while(|&exception| exception <= ub) + .chain(std::iter::once(ub + 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. + if gap_start > gap_end + || !context.contains_any_in_range(&propagated_domain, gap_start, gap_end) { - propagated = true; + continue; + } + + // 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); + + (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_extended_disequality_propagations += 1; - 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); - - (predicate.get_domain() != propagated_domain).then_some(predicate) - }) - .collect::(), - inference_code, - ) - .into() - }; - let result = context.post(predicate!(propagated_domain != value_in_domain), reason); - if result.is_err() { - statistics - .extended_propagation_statistics - .num_variables_propagated += 1; - } - result? + .num_variables_propagated += 1; } + let num_removed_values = result?; + + propagated = true; + statistics + .extended_propagation_statistics + .num_extended_disequality_propagations += num_removed_values; } if propagated { @@ -1076,7 +1157,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; @@ -1130,6 +1211,7 @@ impl NogoodPropagator { inference_code, nogood_id, &mut self.statistics, + &mut self.domain_description, ) .expect("Asserting nogood cannot fail"); @@ -1304,84 +1386,135 @@ 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. -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; - - for predicate_id in nogood.iter().copied() { - let predicate = context.get_predicate(predicate_id); - - is_falsified |= context.is_predicate_id_falsified(predicate_id); - - pumpkin_assert_moderate!( - predicate.get_domain() == propagated_domain - || context.is_predicate_id_satisfied(predicate_id), - "Expected {predicate} to be unassigned with {propagated_domain:?}", - ); +/// 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, 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, + num_describing_predicates: usize, + last_describing_predicate_id: Option, +} - // 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 - { - continue; +impl DomainDescription { + /// 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.described_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.described_domain { + Some(domain) => domain, + None => { + let domain = context.get_predicate(nogood[0]).get_domain(); + self.start(domain); + domain + } } + } - // Then we add the information of the predicates to our structures - num_describing_domain += 1; - last_describing_predicate_id = predicate_id; + /// Starts an empty description of the provided `domain`. + fn start(&mut self, domain: DomainId) { + self.described_domain = Some(domain); + self.lower_bound_predicate = None; + self.upper_bound_predicate = None; + self.exceptions.clear(); + self.num_describing_predicates = 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.described_domain); + + self.num_describing_predicates += 1; + self.last_describing_predicate_id = Some(predicate_id); match predicate.get_predicate_type() { PredicateType::UpperBound => { - pumpkin_assert_simple!(upper_bound.is_none()); - upper_bound = Some(predicate) + pumpkin_assert_simple!(self.upper_bound_predicate.is_none()); + self.upper_bound_predicate = 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()); + 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 => {} } } - ( - exceptions, - lower_bound, - upper_bound, - num_describing_domain, - last_describing_predicate_id, - is_falsified, - ) + + /// 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, + 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(); + } + + /// Describes the unassigned predicates of `nogood`, which should all be over `domain`. + /// + /// 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() { + match context.evaluate_predicate_id(predicate_id) { + Some(true) => continue, + Some(false) => return false, + None => {} + } + + 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); + } + + self.complete(); + + true + } + + /// 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 @@ -2043,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..766926e0d 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 truth_value = context.evaluate_predicate_id(nogood_predicates[index]); + + // A satisfied predicate can never be a new watcher, regardless of its domain. + if truth_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 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, so extended + // nogood propagation needs it in the description of the domain. + 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 => { 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..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 @@ -376,65 +376,90 @@ 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 => { + // Naive and big-step explanations are created by the same procedure, since + // `create_profile_explanation` takes the explanation type into account. + // + // 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, + 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); + pumpkin_assert_extreme!(explains_removed_start_times( + context, + propagating_task, + lower_bound_removed_time_points, + upper_bound_removed_time_points, + &explanation, + )); + let _ = 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 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 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); + + 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, - ) - } 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))?; + let chunk_end = min(explanation_point, upper_bound_removed_time_points); + + // 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, + ) { + 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, + )); + let _ = context.remove_range( + &propagating_task.start_variable, + chunk_start, + chunk_end, + (explanation, &self.inference_code), + )?; + } + + chunk_start = chunk_end + 1; } } } @@ -478,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 5b167fc34..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 @@ -427,6 +427,46 @@ 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 start_time in 7..=10 { + assert!(!state.contains(s2, start_time)); + assert_eq!( + conjunction!([s1 >= 6] & [s1 <= 10]), + reason_for(&mut state, predicate!(s2 != start_time)) + ); + } + 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, + reason_for(&mut state, predicate!(s2 != start_time)) + ); + } +} + 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 +698,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>()