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
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,11 @@ runs:
- The descriptor-placement scalar construction placer
(`RuntimeScalarConstructionPlacer`) and the compiled runtime phase runner
that solves first-fit construction.
- Grouped-scalar required construction (`assignment_required`): the default
runtime's dense required batch over an assignment group with capacity,
sequence and rule keys, solved through the compiled runtime runner; and the
compiled grouped-scalar local-search neighborhood of the same group
(`assignment_neighborhood`), including its augmenting-path repairs.
- Route moves executed against a scored model: the score director's
cascading list-shadow row maintenance (`route_rows`), and grouped list
ruin-and-recreate with joint placement of each element group
Expand Down
23 changes: 16 additions & 7 deletions crates/solverforge-solver/benches/selector_cursor_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ use std::time::Instant;

use solverforge_config::{
CartesianProductConfig, ChangeMoveConfig, ConstructionHeuristicConfig,
ConstructionHeuristicType, KOptMoveSelectorConfig, ListChangeMoveConfig, ListSwapMoveConfig,
LocalSearchConfig, MoveSelectorConfig, NearbyListChangeMoveConfig, NearbyListSwapMoveConfig,
PhaseConfig, RuinRecreateMoveSelectorConfig, SelectionOrder, SolverConfig,
SublistChangeMoveConfig, SublistSwapMoveConfig, SwapMoveConfig, UnionMoveSelectorConfig,
VariableTargetConfig,
ConstructionHeuristicType, GroupedScalarMoveSelectorConfig, KOptMoveSelectorConfig,
ListChangeMoveConfig, ListSwapMoveConfig, LocalSearchConfig, MoveSelectorConfig,
NearbyListChangeMoveConfig, NearbyListSwapMoveConfig, PhaseConfig,
RuinRecreateMoveSelectorConfig, SelectionOrder, SolverConfig, SublistChangeMoveConfig,
SublistSwapMoveConfig, SwapMoveConfig, UnionMoveSelectorConfig, VariableTargetConfig,
};
use solverforge_core::domain::{
EntityCollectionExtractor, EntityDescriptor, PlanningSolution, SolutionDescriptor,
Expand All @@ -33,8 +33,9 @@ use solverforge_scoring::ScoreDirector;
use solverforge_solver::__bench::{CandidateVisitor, CompiledNeighborhood, CompiledRuntimeRunner};
use solverforge_solver::{
CandidateTraceCoordinate, CandidateTraceIdentity, CrossEntityDistanceMeter, ListVariableSlot,
Move, MoveCandidateRef, MoveStreamContext, Phase, RuntimeModel, ScalarVariableSlot,
SearchContext, SolverScope, ValueSource, VariableSlot,
Move, MoveCandidateRef, MoveStreamContext, Phase, RuntimeModel, ScalarGroup,
ScalarGroupBinding, ScalarTarget, ScalarVariableSlot, SearchContext, SolverScope, ValueSource,
VariableSlot,
};

struct MeasuringAllocator;
Expand Down Expand Up @@ -148,6 +149,7 @@ include!("selector_cursor_gate/neighborhood_driver.rs");
include!("selector_cursor_gate/list_cases.rs");
include!("selector_cursor_gate/scalar_cases.rs");
include!("selector_cursor_gate/construction_cases.rs");
include!("selector_cursor_gate/assignment_cases.rs");
include!("selector_cursor_gate/scoring_cases.rs");
include!("selector_cursor_gate/route_model.rs");
include!("selector_cursor_gate/route_cases.rs");
Expand Down Expand Up @@ -189,6 +191,13 @@ fn main() {
"construction_first_fit",
construction_first_fit
);
run_case!(case, matched, "assignment_required", assignment_required);
run_case!(
case,
matched,
"assignment_neighborhood",
assignment_neighborhood
);
run_case!(case, matched, "route_rows", route_rows);
run_case!(case, matched, "group_ruin", group_ruin);
run_case!(case, matched, "scoring", scoring);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/* Grouped-scalar required construction through the compiled runtime.

`assignment_required` solves a rostering-shaped assignment group with the
default runtime: every shift is a required row, a nurse holds one shift per
day (capacity key), the day is the sequence key, and a late shift may not
precede an early shift of the same nurse on the next day (assignment rule).
The default runtime commits the dense required batch first and finishes any
row the batch could not place with the required cursor, which is the work a
generated rostering model pays before local search.

`assignment_neighborhood` enumerates the compiled grouped-scalar
local-search neighborhood of the same group over the constructed roster:
every assignment family a grouped local-search step opens, including the
augmenting-path repairs that discover through the pending-assignment overlay. The configuration sets no
termination, so the default runtime ends the solve after construction. The
cross-tree order hash is the constructed roster. */

const ASSIGNMENT_DAYS: usize = 28;
const ASSIGNMENT_SHIFTS_PER_DAY: usize = 18;
const ASSIGNMENT_NURSES: usize = 24;
const ASSIGNMENT_ROWS: usize = ASSIGNMENT_DAYS * ASSIGNMENT_SHIFTS_PER_DAY;
const ASSIGNMENT_NEIGHBORHOOD_CANDIDATES: usize = 2_016;

fn assignment_day(entity: usize) -> usize {
entity / ASSIGNMENT_SHIFTS_PER_DAY
}

fn assignment_shift_type(entity: usize) -> usize {
entity % ASSIGNMENT_SHIFTS_PER_DAY % 3
}

fn assignment_row_required(_: &Plan, _: usize) -> bool {
true
}

fn assignment_capacity_key(_: &Plan, entity: usize, nurse: usize) -> Option<usize> {
Some(nurse * ASSIGNMENT_DAYS + assignment_day(entity))
}

fn assignment_sequence_key(_: &Plan, entity: usize, _: usize) -> Option<usize> {
Some(assignment_day(entity))
}

fn assignment_rule(
_: &Plan,
left: usize,
left_nurse: usize,
right: usize,
right_nurse: usize,
) -> bool {
left_nurse != right_nurse
|| assignment_day(left) + 1 != assignment_day(right)
|| !(assignment_shift_type(left) == 2 && assignment_shift_type(right) == 0)
}

fn assignment_nurse(entity: &dyn std::any::Any) -> Option<usize> {
entity
.downcast_ref::<Vehicle>()
.expect("an assignment row is a Vehicle")
.visits
.first()
.copied()
}

fn assign_nurse(entity: &mut dyn std::any::Any, nurse: Option<usize>) {
let visits = &mut entity
.downcast_mut::<Vehicle>()
.expect("an assignment row is a Vehicle")
.visits;
visits.clear();
visits.extend(nurse);
}

fn assignment_variables() -> [VariableDescriptor; 1] {
[VariableDescriptor::genuine("first")
.with_allows_unassigned(true)
.with_usize_accessors(assignment_nurse, assign_nurse)]
}

fn assignment_slot() -> ScalarVariableSlot<Plan> {
ScalarVariableSlot::new(
0,
0,
"Vehicle",
entity_count,
"first",
first_get,
first_set,
ValueSource::CountableRange {
from: 0,
to: ASSIGNMENT_NURSES,
},
true,
)
}

fn assignment_context() -> Context {
let slot = assignment_slot();
let group = ScalarGroupBinding::bind(
ScalarGroup::assignment(
"shift_assignment",
ScalarTarget::from_descriptor_index(0, "first"),
)
.with_required_entity(assignment_row_required)
.with_capacity_key(assignment_capacity_key)
.with_sequence_key(assignment_sequence_key)
.with_assignment_rule(assignment_rule),
&[slot],
);
SearchContext::new(
descriptor(&assignment_variables()),
RuntimeModel::new(vec![VariableSlot::Scalar(slot)]).with_scalar_groups(vec![group]),
Some(SEED),
)
.expect("the assignment gate model must bind to its descriptor")
}

fn assignment_config() -> SolverConfig {
SolverConfig {
random_seed: Some(SEED),
..SolverConfig::default()
}
}

fn assignment_runner() -> Runner {
Runner::compile(&assignment_config(), assignment_context())
.expect("the assignment gate configuration must compile")
}

fn assignment_required() {
let mut runners = (0..iterations())
.map(|_| assignment_runner())
.collect::<Vec<_>>();
let variables = assignment_variables();
emit("assignment_required", ASSIGNMENT_ROWS, || {
let mut count = 0;
let mut roster = FNV_OFFSET;
for runner in &mut runners {
let mut scope =
SolverScope::new(plan_director(unassigned_plan(ASSIGNMENT_ROWS), &variables));
scope.start_solving();
runner.solve(&mut scope);
for shift in &scope.working_solution().vehicles {
let nurse = *shift
.visits
.first()
.expect("required construction assigns every shift");
mix(&mut roster, nurse);
count += 1;
}
}
(count, roster, roster)
});
}

/* The roster the default runtime constructs; local search starts here. */
fn assignment_roster() -> Plan {
let variables = assignment_variables();
let mut scope = SolverScope::new(plan_director(unassigned_plan(ASSIGNMENT_ROWS), &variables));
scope.start_solving();
assignment_runner().solve(&mut scope);
scope.working_solution().clone()
}

fn assignment_neighborhood() {
neighborhood_case(
"assignment_neighborhood",
ASSIGNMENT_NEIGHBORHOOD_CANDIDATES,
plan_director(assignment_roster(), &assignment_variables()),
compile_neighborhood(
assignment_context(),
MoveSelectorConfig::GroupedScalarMoveSelector(GroupedScalarMoveSelectorConfig {
selection_order: CANONICAL,
selection_metric: None,
group_name: "shift_assignment".to_string(),
value_candidate_limit: None,
max_moves_per_step: None,
require_hard_improvement: false,
}),
),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ impl<S> AugmentingPathSearch<'_, S> {
if state.is_required(blocker) {
continue;
}
work.overlay.set_value(state, blocker, None);
work.overlay
.set_value(state, self.group, self.solution, blocker, None);
work.edits.push(self.group.edit(blocker, None));
}
// State changed after the displacements; re-derive both blockers
Expand Down Expand Up @@ -195,7 +196,8 @@ impl<S> AugmentingPathSearch<'_, S> {
}

if work.blockers.is_empty() {
work.overlay.set_value(state, entity_index, Some(value));
work.overlay
.set_value(state, self.group, self.solution, entity_index, Some(value));
work.edits.push(self.group.edit(entity_index, Some(value)));
return true;
}
Expand Down Expand Up @@ -257,16 +259,19 @@ impl<S> AugmentingPathSearch<'_, S> {
),
}
{
work.overlay.rollback(overlay_checkpoint);
work.overlay
.rollback(self.group, self.solution, overlay_checkpoint);
work.edits.truncate(edit_checkpoint);
continue;
}
work.overlay.set_value(state, entity_index, Some(value));
work.overlay
.set_value(state, self.group, self.solution, entity_index, Some(value));
work.edits.push(self.group.edit(entity_index, Some(value)));
work.visiting.remove(&entity_index);
return true;
}
work.overlay.rollback(overlay_checkpoint);
work.overlay
.rollback(self.group, self.solution, overlay_checkpoint);
work.edits.truncate(edit_checkpoint);
}

Expand Down
Loading
Loading