Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -282,13 +282,26 @@ impl<S> ScalarAssignmentBinding<S> {
entity_index: usize,
value_candidate_limit: Option<usize>,
) -> Vec<usize> {
let mut values =
self.target
.candidate_values(solution, entity_index, value_candidate_limit);
values.sort_by_key(|value| (self.value_order_key(solution, entity_index, *value), *value));
let mut values = Vec::new();
self.candidate_values_into(solution, entity_index, value_candidate_limit, &mut values);
values
}

/// Refills `values` with the candidate values of `entity_index` in value
/// order, reusing its allocation.
pub(crate) fn candidate_values_into(
&self,
solution: &S,
entity_index: usize,
value_candidate_limit: Option<usize>,
values: &mut Vec<usize>,
) {
values.clear();
self.target
.extend_candidate_values(solution, entity_index, value_candidate_limit, values);
values.sort_by_key(|value| (self.value_order_key(solution, entity_index, *value), *value));
}

pub(crate) fn value_is_legal(
&self,
solution: &S,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,22 +162,28 @@ impl<S> ScalarGroupMemberBinding<S> {
}
}

pub(crate) fn candidate_values(
/// Appends the candidate values of `entity_index` to `values`, so a
/// caller refilling its own buffer allocates at most once.
pub(crate) fn extend_candidate_values(
&self,
solution: &S,
entity_index: usize,
value_candidate_limit: Option<usize>,
) -> Vec<usize> {
values: &mut Vec<usize>,
) {
match &self.access {
ScalarGroupMemberAccess::Static(slot) => {
slot.candidate_values_for_entity(solution, entity_index, value_candidate_limit)
}
ScalarGroupMemberAccess::Static(slot) => slot.extend_candidate_values_for_entity(
solution,
entity_index,
value_candidate_limit,
values,
),
ScalarGroupMemberAccess::Dynamic(slot) => {
let values = slot.candidate_values(solution, entity_index);
match value_candidate_limit {
Some(limit) => values.iter().copied().take(limit).collect(),
None => values.to_vec(),
}
let candidates = slot.candidate_values(solution, entity_index);
let limit = value_candidate_limit
.unwrap_or(usize::MAX)
.min(candidates.len());
values.extend_from_slice(&candidates[..limit]);
}
}
}
Expand Down
45 changes: 26 additions & 19 deletions crates/solverforge-solver/src/heuristic/move/compound_scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ pub(crate) struct CompoundScalarMove<S> {
variable_label: &'static str,
edits: Vec<CompoundScalarEdit<S>>,
entity_indices: Vec<usize>,
affected: Vec<(usize, usize)>,
require_hard_improvement: bool,
construction_value_order_key: Option<i64>,
}
Expand All @@ -176,13 +175,6 @@ impl<S> CompoundScalarMove<S> {
variable_label: &'static str,
edits: Vec<CompoundScalarEdit<S>>,
) -> Self {
let mut affected = Vec::new();
for edit in edits.iter() {
let key = (edit.descriptor_index, edit.entity_index);
if !affected.contains(&key) {
affected.push(key);
}
}
let mut entity_indices = edits
.iter()
.map(|edit| edit.entity_index)
Expand All @@ -194,7 +186,6 @@ impl<S> CompoundScalarMove<S> {
variable_label,
edits,
entity_indices,
affected,
require_hard_improvement: false,
construction_value_order_key: None,
}
Expand Down Expand Up @@ -237,6 +228,24 @@ impl<S> CompoundScalarMove<S> {
}
}

impl<S> CompoundScalarMove<S> {
/* The (descriptor, entity) rows the edits change, each once, in edit
order. A move holds a handful of edits, so a scan replaces a stored
list built per move. */
fn affected(&self) -> impl DoubleEndedIterator<Item = (usize, usize)> + '_ {
self.edits
.iter()
.enumerate()
.filter(|(position, edit)| {
!self.edits[..*position].iter().any(|earlier| {
earlier.descriptor_index == edit.descriptor_index
&& earlier.entity_index == edit.entity_index
})
})
.map(|(_, edit)| (edit.descriptor_index, edit.entity_index))
}
}

impl<S> Debug for CompoundScalarMove<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompoundScalarMove")
Expand Down Expand Up @@ -264,33 +273,31 @@ where

fn do_move<D: Director<S>>(&self, score_director: &mut D) -> Self::Undo {
let mut undo = SmallVec::<[Option<usize>; 8]>::with_capacity(self.edits.len());
let affected = &self.affected;
for edit in &self.edits {
let old_value = edit.current_value(score_director.working_solution());
undo.push(old_value);
}
for (descriptor_index, entity_index) in affected.iter() {
score_director.before_variable_changed(*descriptor_index, *entity_index);
for (descriptor_index, entity_index) in self.affected() {
score_director.before_variable_changed(descriptor_index, entity_index);
}
for edit in &self.edits {
edit.set_value(score_director.working_solution_mut(), edit.to_value);
}
for (descriptor_index, entity_index) in affected.iter().rev() {
score_director.after_variable_changed(*descriptor_index, *entity_index);
for (descriptor_index, entity_index) in self.affected().rev() {
score_director.after_variable_changed(descriptor_index, entity_index);
}
undo
}

fn undo_move<D: Director<S>>(&self, score_director: &mut D, undo: Self::Undo) {
let affected = &self.affected;
for (descriptor_index, entity_index) in affected.iter() {
score_director.before_variable_changed(*descriptor_index, *entity_index);
for (descriptor_index, entity_index) in self.affected() {
score_director.before_variable_changed(descriptor_index, entity_index);
}
for (edit, old_value) in self.edits.iter().zip(undo) {
edit.set_value(score_director.working_solution_mut(), old_value);
}
for (descriptor_index, entity_index) in affected.iter().rev() {
score_director.after_variable_changed(*descriptor_index, *entity_index);
for (descriptor_index, entity_index) in self.affected().rev() {
score_director.after_variable_changed(descriptor_index, entity_index);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use super::assignment_scarcity::sort_values_by_required_scarcity;
use super::assignment_state::{CapacityConflict, ScalarAssignmentState};
use crate::builder::ScalarAssignmentBinding;
use crate::heuristic::r#move::CompoundScalarMove;
use crate::planning::ScalarEdit;
use solverforge_core::fast_hash::{FastMap, FastSet};

pub(super) struct EntityValueCursor {
Expand All @@ -32,6 +33,7 @@ impl EntityValueCursor {
group: &ScalarAssignmentBinding<S>,
solution: &S,
state: &mut ScalarAssignmentState,
edits: &mut Vec<ScalarEdit<S>>,
should_stop: &mut ShouldStop,
) -> Option<CompoundScalarMove<S>>
where
Expand All @@ -54,10 +56,11 @@ impl EntityValueCursor {
continue;
}
if self.values.is_empty() {
self.values = group.candidate_values(
group.candidate_values_into(
solution,
entity_index,
self.options.value_candidate_limit,
&mut self.values,
);
if self.kind == AssignmentMoveKind::Required
&& self.options.required_scarcity_ordering
Expand Down Expand Up @@ -88,6 +91,7 @@ impl EntityValueCursor {
AssignmentRequest::root(entity_index, value, self.request_depth()),
self.options,
intent,
edits,
should_stop,
);
if should_stop() {
Expand Down Expand Up @@ -141,17 +145,22 @@ impl EntityValueCursor {
group: &ScalarAssignmentBinding<S>,
solution: &S,
entity_index: usize,
values: &mut Vec<usize>,
) {
if self.value_degrees.is_empty() {
return;
}
for value in
group.candidate_values(solution, entity_index, self.options.value_candidate_limit)
{
if let Some(degree) = self.value_degrees.get_mut(&value) {
group.candidate_values_into(
solution,
entity_index,
self.options.value_candidate_limit,
values,
);
for value in values.iter() {
if let Some(degree) = self.value_degrees.get_mut(value) {
*degree -= 1;
if *degree == 0 {
self.value_degrees.remove(&value);
self.value_degrees.remove(value);
}
}
}
Expand Down Expand Up @@ -208,6 +217,7 @@ impl CapacityCursor {
group: &ScalarAssignmentBinding<S>,
solution: &S,
state: &mut ScalarAssignmentState,
edits: &mut Vec<ScalarEdit<S>>,
should_stop: &mut ShouldStop,
) -> Option<CompoundScalarMove<S>>
where
Expand All @@ -219,7 +229,7 @@ impl CapacityCursor {
return None;
}
if let Some(cursor) = &mut self.repair_cursor {
if let Some(mov) = cursor.next(group, solution, state, should_stop) {
if let Some(mov) = cursor.next(group, solution, state, edits, should_stop) {
return Some(mov);
}
if should_stop() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ use crate::heuristic::r#move::CompoundScalarMove;
use crate::planning::ScalarEdit;
use solverforge_core::fast_hash::FastSet;

#[allow(clippy::too_many_arguments)]
pub(super) fn assignment_move_for_entity_value<S, ShouldStop>(
group: &ScalarAssignmentBinding<S>,
solution: &S,
state: &mut ScalarAssignmentState,
assignment: AssignmentRequest,
options: ScalarAssignmentMoveOptions,
intent: AssignmentMoveIntent,
edits: &mut Vec<ScalarEdit<S>>,
should_stop: &mut ShouldStop,
) -> Option<CompoundScalarMove<S>>
where
Expand All @@ -32,17 +34,22 @@ where
}
let mut overlay = state.take_path_overlay();
overlay.clear();
let mut edits = Vec::new();
let mut visiting = FastSet::default();
let mut blockers = Vec::new();
edits.clear();
let mut scratch = state.take_path_scratch();
let search = AugmentingPathSearch::new(group, solution, options, intent);
let mut work = AssignmentPathWork::new(&mut overlay, &mut visiting, &mut edits, &mut blockers);
let mut work = AssignmentPathWork::new(
&mut overlay,
&mut scratch.visiting,
edits,
&mut scratch.blockers,
);
let produced = search.discover(state, assignment, &mut work, should_stop);
let feasible = produced && state.refresh_trial_edits(group, solution, &edits);
state.restore_path_scratch(scratch);
let feasible = produced && state.refresh_trial_edits(group, solution, edits);
overlay.clear();
state.restore_path_overlay(overlay);
feasible
.then_some(move_from_edits(group, solution, &edits, intent.reason))
.then_some(move_from_edits(group, solution, edits, intent.reason))
.flatten()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ where
ShouldStop: FnMut() -> bool,
{
let mut entities = Vec::new();
let mut values = Vec::new();
for entity_index in 0..group.entity_count(solution) {
if should_stop() {
return None;
}
if !state.is_required(entity_index) || state.current_value(entity_index).is_some() {
continue;
}
let candidate_count = group
.candidate_values(solution, entity_index, value_candidate_limit)
.len();
group.candidate_values_into(solution, entity_index, value_candidate_limit, &mut values);
let candidate_count = values.len();
if should_stop() {
return None;
}
Expand Down Expand Up @@ -61,11 +61,13 @@ where
{
let mut degrees = FastMap::default();
let mut processed_edges = 0usize;
let mut values = Vec::new();
for entity_index in entities {
if should_stop() {
return None;
}
for value in group.candidate_values(solution, *entity_index, value_candidate_limit) {
group.candidate_values_into(solution, *entity_index, value_candidate_limit, &mut values);
for value in values.iter().copied() {
*degrees.entry(value).or_insert(0) += 1;
processed_edges += 1;
if processed_edges.is_multiple_of(GENERATION_POLL_INTERVAL) && should_stop() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod pressure;
use super::assignment_path_overlay::AssignmentPathOverlay;
use overlay::OverlayScratch;

use solverforge_core::fast_hash::FastMap;
use solverforge_core::fast_hash::{FastMap, FastSet};

mod membership;

Expand All @@ -28,6 +28,16 @@ pub(crate) struct ScalarAssignmentState {
serves one nesting level (take/restore, allocated once grown). */
overlay: OverlayScratch,
path_overlay: AssignmentPathOverlay,
path_scratch: PathScratch,
}

/* The visited set and blocker list one augmenting-path discovery uses,
kept across discoveries so a discovery allocates nothing once they have
grown. */
#[derive(Default)]
pub(super) struct PathScratch {
pub(super) visiting: FastSet<usize>,
pub(super) blockers: Vec<usize>,
}

pub(super) struct CapacityConflict {
Expand Down Expand Up @@ -83,6 +93,7 @@ impl ScalarAssignmentState {
assigned_by_sequence: FastMap::default(),
overlay: OverlayScratch::default(),
path_overlay: AssignmentPathOverlay::default(),
path_scratch: PathScratch::default(),
};
for entity in 0..entity_count {
state.refresh_rows(
Expand Down Expand Up @@ -125,6 +136,17 @@ impl ScalarAssignmentState {
self.path_overlay = overlay;
}

pub(super) fn take_path_scratch(&mut self) -> PathScratch {
let mut scratch = std::mem::take(&mut self.path_scratch);
scratch.visiting.clear();
scratch.blockers.clear();
scratch
}

pub(super) fn restore_path_scratch(&mut self, scratch: PathScratch) {
self.path_scratch = scratch;
}

pub(super) fn refresh_trial_edits<S>(
&mut self,
group: &ScalarAssignmentBinding<S>,
Expand Down
Loading
Loading