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
15 changes: 10 additions & 5 deletions crates/solverforge-solver/src/builder/selector/grouped_scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ where
activation: Option<GroupedScalarActivation<'a, S>>,
assignment_cursor:
Option<crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor<S>>,
pooled_assignment: Option<crate::phase::construction::grouped_scalar::ScalarAssignmentState>,
/* The solve-owned assignment base, kept boxed until activation moves it
into the assignment cursor, so every leaf cursor carries one pointer for
it instead of the whole state. */
pooled_assignment:
Option<Box<crate::phase::construction::grouped_scalar::ScalarAssignmentState>>,
require_hard_improvement: bool,
}

Expand Down Expand Up @@ -169,7 +173,7 @@ where
pooled.refresh_rows(assignment, solution, rows);
}
crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::with_pooled_state(
assignment, solution, options, pooled,
assignment, solution, options, *pooled,
)
}
// Structural change (entity count moved): the sparse
Expand Down Expand Up @@ -234,11 +238,12 @@ impl<S: PlanningSolution + 'static> GroupedScalarCursor<'_, S> {
/// Hands the assignment base back to the solve-owned slot when the step
/// closes. Steps that never activated keep the returned pool as retained
/// state; steps after activation move the maintained base back.
pub(crate) fn into_pooled_assignment(mut self) -> Option<ScalarAssignmentState> {
pub(crate) fn into_pooled_assignment(mut self) -> Option<Box<ScalarAssignmentState>> {
let returned = self
.assignment_cursor
.take()
.map(crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::into_state);
.map(crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::into_state)
.map(Box::new);
let pooled = returned.or_else(|| self.pooled_assignment.take());
drop(self);
pooled
Expand Down Expand Up @@ -350,7 +355,7 @@ impl<S: PlanningSolution + 'static> GroupedScalarSelector<S> {
context: MoveStreamContext,
) -> GroupedScalarCursor<'a, S> {
let mut cursor = self.open_cursor_with_context(score_director, context);
cursor.pooled_assignment = state.take().map(|boxed| *boxed);
cursor.pooled_assignment = state.take();
cursor
}
}
32 changes: 25 additions & 7 deletions crates/solverforge-solver/src/heuristic/move/compound_scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ pub(crate) struct CompoundScalarMove<S> {
reason: &'static str,
variable_label: &'static str,
edits: Vec<CompoundScalarEdit<S>>,
/* The sorted, distinct entities of a move that edits more than one;
empty when every edit names the first edit's entity, which
`entity_indices` then lends from that edit, so a single-entity move
allocates no index list. */
entity_indices: Vec<usize>,
require_hard_improvement: bool,
construction_value_order_key: Option<i64>,
Expand All @@ -175,12 +179,21 @@ impl<S> CompoundScalarMove<S> {
variable_label: &'static str,
edits: Vec<CompoundScalarEdit<S>>,
) -> Self {
let mut entity_indices = edits
.iter()
.map(|edit| edit.entity_index)
.collect::<Vec<_>>();
entity_indices.sort_unstable();
entity_indices.dedup();
let single_entity = edits.split_first().is_none_or(|(first, rest)| {
rest.iter()
.all(|edit| edit.entity_index == first.entity_index)
});
let entity_indices = if single_entity {
Vec::new()
} else {
let mut entity_indices = edits
.iter()
.map(|edit| edit.entity_index)
.collect::<Vec<_>>();
entity_indices.sort_unstable();
entity_indices.dedup();
entity_indices
};
Self {
reason,
variable_label,
Expand Down Expand Up @@ -309,7 +322,12 @@ where
}

fn entity_indices(&self) -> &[usize] {
&self.entity_indices
match self.edits.first() {
Some(first) if self.entity_indices.is_empty() => {
std::slice::from_ref(&first.entity_index)
}
_ => &self.entity_indices,
}
}

fn variable_name(&self) -> &str {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,28 @@ fn compound_scalar_rejects_noop_and_illegal_edits() {
let illegal = CompoundScalarMove::new("illegal", vec![illegal_edit]);
assert!(!illegal.is_doable(&director));
}

#[test]
fn compound_move_lists_each_edited_entity_once_in_order() {
let single = CompoundScalarMove::new(
"test",
vec![
compound_edit(0, 4, 0, "left", Some(3), get_left, set_left),
compound_edit(0, 4, 1, "right", Some(3), get_right, set_right),
],
);
assert_eq!(single.entity_indices(), &[4]);

let several = CompoundScalarMove::new(
"test",
vec![
compound_edit(0, 2, 0, "left", Some(3), get_left, set_left),
compound_edit(0, 0, 0, "left", Some(3), get_left, set_left),
compound_edit(0, 2, 1, "right", Some(3), get_right, set_right),
],
);
assert_eq!(several.entity_indices(), &[0, 2]);

let empty = CompoundScalarMove::<CompoundSolution>::new("test", Vec::new());
assert!(empty.entity_indices().is_empty());
}
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ impl OverlayScratch {
value: usize,
) -> bool {
if let Some(key) = group.capacity_key(solution, entity, value) {
let count = state.occupancy.get(&key).map_or(0, Vec::len);
let count = state.occupancy.get(&key).map_or(0, |members| members.len());
let delta = self.capacity_deltas.get(&key).copied().unwrap_or(0);
if !count.checked_add_signed(delta).is_some_and(|n| n <= 1) {
return false;
Expand Down Expand Up @@ -164,7 +164,7 @@ impl OverlayScratch {

fn capacity_feasible(&self, state: &ScalarAssignmentState) -> bool {
self.capacity_deltas.iter().all(|(key, delta)| {
let count = state.occupancy.get(key).map_or(0, Vec::len);
let count = state.occupancy.get(key).map_or(0, |members| members.len());
count.checked_add_signed(*delta).is_some_and(|n| n <= 1)
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod pressure;
use super::assignment_path_overlay::AssignmentPathOverlay;
use overlay::OverlayScratch;

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

mod membership;
Expand All @@ -16,14 +17,19 @@ mod membership;
#[path = "tests/membership_keys.rs"]
mod membership_keys;

/* The sorted rows of one index key. A capacity or sequence key holds one row
in a feasible plan, so its members stay inline and placing a row allocates
no member list. */
type Members = SmallVec<[usize; 2]>;

pub(crate) struct ScalarAssignmentState {
values: Vec<Option<usize>>,
capacity_keys: Vec<Option<usize>>,
sequence_keys: Vec<Option<usize>>,
required: Vec<bool>,
occupancy: FastMap<usize, Vec<usize>>,
assigned_by_value: FastMap<usize, Vec<usize>>,
assigned_by_sequence: FastMap<(usize, usize), Vec<usize>>,
occupancy: FastMap<usize, Members>,
assigned_by_value: FastMap<usize, Members>,
assigned_by_sequence: FastMap<(usize, usize), Members>,
/* Pooled scratch for the hot per-candidate feasibility path; each field
serves one nesting level (take/restore, allocated once grown). */
overlay: OverlayScratch,
Expand Down Expand Up @@ -59,19 +65,19 @@ impl ScalarAssignmentState {
let mut occupancy = self
.occupancy
.iter()
.map(|(key, entities)| (*key, entities.clone()))
.map(|(key, entities)| (*key, entities.to_vec()))
.collect::<Vec<_>>();
occupancy.sort_by_key(|(key, _)| *key);
let mut assigned_by_value = self
.assigned_by_value
.iter()
.map(|(key, entities)| (*key, entities.clone()))
.map(|(key, entities)| (*key, entities.to_vec()))
.collect::<Vec<_>>();
assigned_by_value.sort_by_key(|(key, _)| *key);
let mut assigned_by_sequence = self
.assigned_by_sequence
.iter()
.map(|(key, entities)| (*key, entities.clone()))
.map(|(key, entities)| (*key, entities.to_vec()))
.collect::<Vec<_>>();
assigned_by_sequence.sort_by_key(|(key, _)| *key);
AssignmentIndexSnapshot {
Expand Down Expand Up @@ -124,7 +130,7 @@ impl ScalarAssignmentState {
pub(super) fn assigned_count(&self, value: usize) -> usize {
self.assigned_by_value
.get(&value)
.map(Vec::len)
.map(Members::len)
.unwrap_or(0)
}

Expand Down Expand Up @@ -161,13 +167,16 @@ impl ScalarAssignmentState {
}

pub(super) fn capacity_occupants(&self, key: usize) -> &[usize] {
self.occupancy.get(&key).map(Vec::as_slice).unwrap_or(&[])
self.occupancy
.get(&key)
.map(Members::as_slice)
.unwrap_or(&[])
}

pub(super) fn sequence_members(&self, value: usize, sequence: usize) -> &[usize] {
self.assigned_by_sequence
.get(&(value, sequence))
.map(Vec::as_slice)
.map(Members::as_slice)
.unwrap_or(&[])
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl ScalarAssignmentState {
}
}

fn remove_member<K: Eq + std::hash::Hash>(map: &mut FastMap<K, Vec<usize>>, key: K, entity: usize) {
fn remove_member<K: Eq + std::hash::Hash>(map: &mut FastMap<K, Members>, key: K, entity: usize) {
let Some(members) = map.get_mut(&key) else {
return;
};
Expand All @@ -71,7 +71,7 @@ fn remove_member<K: Eq + std::hash::Hash>(map: &mut FastMap<K, Vec<usize>>, key:
}
}

fn insert_member<K: Eq + std::hash::Hash>(map: &mut FastMap<K, Vec<usize>>, key: K, entity: usize) {
fn insert_member<K: Eq + std::hash::Hash>(map: &mut FastMap<K, Members>, key: K, entity: usize) {
let members = map.entry(key).or_default();
if let Err(position) = members.binary_search(&entity) {
members.insert(position, entity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ fn pooled_assignment_base_matches_rebuild_across_random_sequences() {
let pooled_rows = pooled_stream(&mut pooled_cursor, director.working_solution());
pool = pooled_cursor
.into_pooled_assignment()
.filter(|state| state.row_count() == director.working_solution().values.len())
.map(Box::new);
.filter(|state| state.row_count() == director.working_solution().values.len());

let rebuilt = ScalarAssignmentState::new(binding, director.working_solution());
if let Some(state) = &pool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ where
) = (&mut leaf_cursor.inner, slot)
{
if let Some(grouped) = grouped.take() {
*pooled = grouped.into_pooled_assignment().map(Box::new);
*pooled = grouped.into_pooled_assignment();
}
}
}
Expand Down
Loading