Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add method for retrieving relevant brancher events #138

Merged
merged 5 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pumpkin-solver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ clap = { version = "4.5.17", features = ["derive"] }
env_logger = "0.10.0"
bitfield-struct = "0.9.2"
num = "0.4.3"
enum-map = "2.7.3"

[dev-dependencies]
clap = { version = "4.5.17", features = ["derive"] }
Expand Down
43 changes: 43 additions & 0 deletions pumpkin-solver/src/branching/brancher.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use enum_map::Enum;

#[cfg(doc)]
use crate::basic_types::Random;
use crate::basic_types::SolutionReference;
#[cfg(doc)]
use crate::branching;
#[cfg(doc)]
use crate::branching::branchers::dynamic_brancher::DynamicBrancher;
#[cfg(doc)]
use crate::branching::value_selection::ValueSelector;
#[cfg(doc)]
use crate::branching::variable_selection::VariableSelector;
Expand Down Expand Up @@ -81,4 +85,43 @@ pub trait Brancher {
fn is_restart_pointless(&mut self) -> bool {
true
}

/// Indicates which [`BrancherEvents`] are relevant for this particular [`Brancher`].
///
/// This can be used by [`Brancher`]s such as the [`DynamicBrancher`] to determine upon which
/// events which [`Brancher`] should be called.
///
/// By default, a [`Brancher`] is subscribed to all events.
fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
vec![
BrancherEvents::Conflict,
BrancherEvents::Backtrack,
BrancherEvents::Solution,
BrancherEvents::UnassignInteger,
BrancherEvents::AppearanceInConflictPredicate,
BrancherEvents::Restart,
BrancherEvents::Synchronise,
]
}
}

/// The events which can occur for a [`Brancher`]. Used for returning which events are relevant in
/// [`Brancher::get_relevant_brancher_events`], [`VariableSelector::get_relevant_brancher_events`],
/// and [`ValueSelector::get_relevant_brancher_events`].
#[derive(Debug, Clone, Copy, Enum, Hash, PartialEq, Eq)]
pub enum BrancherEvents {
/// Event for when a conflict is detected
Conflict,
/// Event for when a backtrack is performed
Backtrack,
/// Event for when a solution has been found
Solution,
/// Event for when an integer variable has become unassigned
UnassignInteger,
/// Event for when a predicate appears during conflict analysis
AppearanceInConflictPredicate,
/// Event for when a restart occurs
Restart,
/// Event which is called with the new state after a backtrack has occurred
Synchronise,
}
11 changes: 11 additions & 0 deletions pumpkin-solver/src/branching/branchers/alternating_brancher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! on the strategy specified in [`AlternatingStrategy`].

use crate::basic_types::SolutionReference;
use crate::branching::brancher::BrancherEvents;
use crate::branching::Brancher;
use crate::branching::SelectionContext;
use crate::engine::predicates::predicate::Predicate;
Expand Down Expand Up @@ -208,6 +209,16 @@ impl<OtherBrancher: Brancher> Brancher for AlternatingBrancher<OtherBrancher> {
self.other_brancher.synchronise(assignments);
}
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
// We require the restart event and on solution event for the alternating brancher itself;
// additionally, it will be interested in the events of its sub-branchers
[BrancherEvents::Restart, BrancherEvents::Solution]
.into_iter()
.chain(self.default_brancher.get_relevant_brancher_events())
.chain(self.other_brancher.get_relevant_brancher_events())
.collect()
}
}

#[cfg(test)]
Expand Down
14 changes: 14 additions & 0 deletions pumpkin-solver/src/branching/branchers/autonomous_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::independent_variable_value_brancher::IndependentVariableValueBrancher
use crate::basic_types::PredicateId;
use crate::basic_types::PredicateIdGenerator;
use crate::basic_types::SolutionReference;
use crate::branching::brancher::BrancherEvents;
use crate::branching::value_selection::InDomainMin;
use crate::branching::variable_selection::Smallest;
use crate::branching::Brancher;
Expand Down Expand Up @@ -297,6 +298,19 @@ impl<BackupBrancher: Brancher> Brancher for AutonomousSearch<BackupBrancher> {
fn is_restart_pointless(&mut self) -> bool {
false
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
[
BrancherEvents::Solution,
BrancherEvents::Conflict,
BrancherEvents::Backtrack,
BrancherEvents::Synchronise,
BrancherEvents::AppearanceInConflictPredicate,
]
.into_iter()
.chain(self.backup_brancher.get_relevant_brancher_events())
.collect()
}
}

#[cfg(test)]
Expand Down
81 changes: 59 additions & 22 deletions pumpkin-solver/src/branching/branchers/dynamic_brancher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
use std::cmp::min;
use std::fmt::Debug;

use enum_map::EnumMap;

use crate::basic_types::HashSet;
use crate::basic_types::SolutionReference;
use crate::branching::brancher::BrancherEvents;
use crate::branching::Brancher;
use crate::branching::SelectionContext;
use crate::engine::predicates::predicate::Predicate;
Expand All @@ -28,6 +32,9 @@ use crate::engine::Assignments;
pub struct DynamicBrancher {
branchers: Vec<Box<dyn Brancher>>,
brancher_index: usize,

relevant_event_to_index: EnumMap<BrancherEvents, Vec<usize>>,
relevant_events: Vec<BrancherEvents>,
}

impl Debug for DynamicBrancher {
Expand All @@ -40,14 +47,36 @@ impl DynamicBrancher {
/// Creates a new [`DynamicBrancher`] with the provided `branchers`. It will attempt to use the
/// `branchers` in the order in which they were provided.
pub fn new(branchers: Vec<Box<dyn Brancher>>) -> Self {
let mut relevant_event_to_index: EnumMap<BrancherEvents, Vec<usize>> = EnumMap::default();
let mut relevant_events = HashSet::new();

// The dynamic brancher will reset the indices upon these events so they should be called
let _ = relevant_events.insert(BrancherEvents::Solution);
let _ = relevant_events.insert(BrancherEvents::Conflict);

branchers.iter().enumerate().for_each(|(index, brancher)| {
for event in brancher.get_relevant_brancher_events() {
relevant_event_to_index[event].push(index);
let _ = relevant_events.insert(event);
}
});
Self {
branchers,
brancher_index: 0,

relevant_event_to_index,
relevant_events: relevant_events.into_iter().collect(),
}
}

pub fn add_brancher(&mut self, brancher: Box<dyn Brancher>) {
self.branchers.push(brancher)
for event in brancher.get_relevant_brancher_events() {
self.relevant_event_to_index[event].push(self.branchers.len());
if !self.relevant_events.contains(&event) {
self.relevant_events.push(event);
}
}
self.branchers.push(brancher);
}
}

Expand All @@ -70,46 +99,50 @@ impl Brancher for DynamicBrancher {
// A conflict has occurred, we do not know which brancher now can select a variable, reset
// to the first one
self.brancher_index = 0;
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_conflict());
self.relevant_event_to_index[BrancherEvents::Conflict]
.iter()
.for_each(|&brancher_index| self.branchers[brancher_index].on_conflict());
}

fn on_backtrack(&mut self) {
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_backtrack());
self.relevant_event_to_index[BrancherEvents::Backtrack]
.iter()
.for_each(|&brancher_index| self.branchers[brancher_index].on_backtrack());
}

fn on_unassign_integer(&mut self, variable: DomainId, value: i32) {
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_unassign_integer(variable, value));
self.relevant_event_to_index[BrancherEvents::UnassignInteger]
.iter()
.for_each(|&brancher_index| {
self.branchers[brancher_index].on_unassign_integer(variable, value)
});
}

fn on_appearance_in_conflict_predicate(&mut self, predicate: Predicate) {
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_appearance_in_conflict_predicate(predicate));
self.relevant_event_to_index[BrancherEvents::AppearanceInConflictPredicate]
.iter()
.for_each(|&brancher_index| {
self.branchers[brancher_index].on_appearance_in_conflict_predicate(predicate)
});
}

fn on_solution(&mut self, solution: SolutionReference) {
self.brancher_index = 0;
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_solution(solution));
self.relevant_event_to_index[BrancherEvents::Solution]
.iter()
.for_each(|&brancher_index| self.branchers[brancher_index].on_solution(solution));
}

fn on_restart(&mut self) {
self.branchers
.iter_mut()
.for_each(|brancher| brancher.on_restart());
self.relevant_event_to_index[BrancherEvents::Restart]
.iter()
.for_each(|&brancher_index| self.branchers[brancher_index].on_restart());
}

fn synchronise(&mut self, assignments: &Assignments) {
self.branchers
.iter_mut()
.for_each(|brancher| brancher.synchronise(assignments));
self.relevant_event_to_index[BrancherEvents::Synchronise]
.iter()
.for_each(|&brancher_index| self.branchers[brancher_index].synchronise(assignments));
}

fn is_restart_pointless(&mut self) -> bool {
Expand All @@ -120,4 +153,8 @@ impl Brancher for DynamicBrancher {
.iter_mut()
.all(|brancher| brancher.is_restart_pointless())
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
self.relevant_events.clone()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use std::marker::PhantomData;

use crate::basic_types::SolutionReference;
use crate::branching::brancher::BrancherEvents;
use crate::branching::value_selection::ValueSelector;
use crate::branching::variable_selection::VariableSelector;
use crate::branching::Brancher;
Expand Down Expand Up @@ -89,4 +90,12 @@ where
fn is_restart_pointless(&mut self) -> bool {
self.variable_selector.is_restart_pointless() && self.value_selector.is_restart_pointless()
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
self.variable_selector
.get_relevant_brancher_events()
.into_iter()
.chain(self.value_selector.get_relevant_brancher_events())
.collect()
}
}
2 changes: 1 addition & 1 deletion pumpkin-solver/src/branching/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub mod tie_breaking;
pub mod value_selection;
pub mod variable_selection;

pub use brancher::Brancher;
pub use brancher::*;
pub use selection_context::SelectionContext;

#[cfg(doc)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt::Debug;

use super::ValueSelector;
use crate::basic_types::SolutionReference;
use crate::branching::brancher::BrancherEvents;
#[cfg(doc)]
use crate::branching::branchers::dynamic_brancher::DynamicBrancher;
use crate::branching::SelectionContext;
Expand Down Expand Up @@ -46,4 +47,8 @@ impl<Var> ValueSelector<Var> for DynamicValueSelector<Var> {
fn is_restart_pointless(&mut self) -> bool {
self.selector.is_restart_pointless()
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
self.selector.get_relevant_brancher_events()
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::InDomainSplit;
use crate::branching::brancher::BrancherEvents;
use crate::branching::value_selection::ValueSelector;
use crate::branching::SelectionContext;
use crate::engine::predicates::predicate::Predicate;
Expand Down Expand Up @@ -38,6 +39,10 @@ impl ValueSelector<DomainId> for InDomainInterval {
InDomainSplit::get_predicate_excluding_upper_half(context, decision_variable)
}
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
vec![]
}
}

#[cfg(test)]
Expand Down
5 changes: 5 additions & 0 deletions pumpkin-solver/src/branching/value_selection/in_domain_max.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::branching::brancher::BrancherEvents;
use crate::branching::value_selection::ValueSelector;
use crate::branching::SelectionContext;
use crate::engine::predicates::predicate::Predicate;
Expand All @@ -16,6 +17,10 @@ impl<Var: IntegerVariable + Copy> ValueSelector<Var> for InDomainMax {
) -> Predicate {
predicate!(decision_variable >= context.upper_bound(decision_variable))
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
vec![]
}
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::branching::brancher::BrancherEvents;
use crate::branching::value_selection::ValueSelector;
use crate::branching::SelectionContext;
use crate::engine::predicates::predicate::Predicate;
Expand All @@ -21,6 +22,10 @@ impl<Var: IntegerVariable + Copy> ValueSelector<Var> for InDomainMedian {
.collect::<Vec<_>>();
predicate!(decision_variable == values_in_domain[values_in_domain.len() / 2])
}

fn get_relevant_brancher_events(&self) -> Vec<BrancherEvents> {
vec![]
}
}

#[cfg(test)]
Expand Down
Loading
Loading