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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ runs:
(`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,
runtime's required cursor 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.
Expand Down
5 changes: 3 additions & 2 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ src/
│ │ ├── grouped_scalar/assignment_family.rs — Shared assignment candidate-family deduplication
│ │ ├── grouped_scalar/assignment_pair.rs — Deterministic bounded pair, rematch, and sequence-window move generation
│ │ ├── grouped_scalar/assignment_path.rs — Bounded augmenting-path move construction for required and optional scalar assignments
│ │ ├── grouped_scalar/assignment_path_overlay.rs — Sparse reversible augmenting-path and required-batch discovery state
│ │ ├── grouped_scalar/assignment_required_batch.rs — Dense hard-first required assignment allocation
│ │ ├── grouped_scalar/assignment_path_overlay.rs — Sparse reversible augmenting-path discovery state
│ │ ├── grouped_scalar/assignment_scarcity.rs — Required-row scarcity order and value degrees
│ │ ├── grouped_scalar/assignment_state.rs — Committed assignment occupancy, capacity, and conflict bookkeeping
│ │ ├── grouped_scalar/assignment_overlay.rs — Sparse final-edit capacity and sequence-rule validation without mutating assignment indexes
│ │ ├── grouped_scalar/assignment_pressure.rs — Current-value and sequence-pressure candidate ordering
Expand All @@ -255,6 +255,7 @@ src/
│ │ ├── grouped_scalar/placement.rs — Grouped scalar construction-target and move-strength helpers
│ │ ├── grouped_scalar/phase.rs — ScalarGroupConstruction builder that feeds grouped scalar placements into stock ConstructionHeuristicPhase
│ │ ├── grouped_scalar/placer.rs — ScalarGroupPlacer adapter that opens one cursor-backed placement at a time for provider and assignment groups
│ │ ├── grouped_scalar/placer_resume.rs — Assignment placement generator carried across committed placements
│ │ └── grouped_scalar/placer_stream.rs — Concrete candidate and assignment placement stream helpers
│ ├── localsearch/
│ │ ├── mod.rs — Acceptor, local-search acceptor/forager, and LocalSearchPhase re-exports
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
/* Grouped-scalar required construction through the compiled runtime.
/* Grouped-scalar assignment cases over a rostering-shaped assignment group:
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).

`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_required` solves the group with the default runtime, whose
required cursor places every row one move at a time: the work a generated
rostering model pays before local search. The configuration sets no termination, so the default
runtime ends the solve after construction. The cross-tree order hash is the
constructed roster.

`assignment_neighborhood` enumerates the compiled grouped-scalar
local-search neighborhood of the same group over the constructed roster:
local-search neighborhood of the same group over a fixed feasible 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. */
augmenting-path repairs. The roster is built directly, so the case measures
only the neighborhood. */

const ASSIGNMENT_DAYS: usize = 28;
const ASSIGNMENT_SHIFTS_PER_DAY: usize = 18;
Expand Down Expand Up @@ -153,13 +153,21 @@ fn assignment_required() {
});
}

/* The roster the default runtime constructs; local search starts here. */
/* A feasible roster: shift `s` of day `d` goes to nurse `(s + 6d) mod 24`,
so a nurse works at most one shift a day and keeps its shift type from one
day to the next, which never puts a late shift before an early one. */
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()
Plan {
vehicles: (0..ASSIGNMENT_ROWS)
.map(|entity| Vehicle {
visits: vec![
(entity % ASSIGNMENT_SHIFTS_PER_DAY + 6 * assignment_day(entity))
% ASSIGNMENT_NURSES,
],
})
.collect(),
score: None,
}
}

fn assignment_neighborhood() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use super::assignment_candidate::{
use super::assignment_path::{
assignment_move_for_entity_value, move_from_edits, AssignmentRequest,
};
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::phase::control::GENERATION_POLL_INTERVAL;
use solverforge_core::fast_hash::{FastMap, FastSet};

pub(super) struct EntityValueCursor {
Expand All @@ -20,6 +20,10 @@ pub(super) struct EntityValueCursor {
pub(super) value_degrees: FastMap<usize, usize>,
pub(super) options: ScalarAssignmentMoveOptions,
pub(super) kind: AssignmentMoveKind,
/* Required rows try every value directly (search depth 0) before any
value with augmenting rematches, so a row with a free value never pays
for a rematch search. False during the direct pass. */
pub(super) augmenting: bool,
}

impl EntityValueCursor {
Expand All @@ -46,6 +50,7 @@ impl EntityValueCursor {
self.entity_pos += 1;
self.values.clear();
self.value_pos = 0;
self.augmenting = false;
continue;
}
if self.values.is_empty() {
Expand Down Expand Up @@ -80,7 +85,7 @@ impl EntityValueCursor {
group,
solution,
state,
AssignmentRequest::root(entity_index, value, self.options.max_depth),
AssignmentRequest::root(entity_index, value, self.request_depth()),
self.options,
intent,
should_stop,
Expand All @@ -93,12 +98,64 @@ impl EntityValueCursor {
return Some(mov);
}
}
if self.kind == AssignmentMoveKind::Required
&& !self.augmenting
&& self.options.max_depth > 0
{
self.augmenting = true;
self.value_pos = 0;
continue;
}
self.entity_pos += 1;
self.values.clear();
self.value_pos = 0;
self.augmenting = false;
}
None
}

fn request_depth(&self) -> usize {
if self.kind == AssignmentMoveKind::Required && !self.augmenting {
0
} else {
self.options.max_depth
}
}

/* Carries the cursor past a finished placement: generation moves past
`placed` and restarts the value list of the row it stands on, whose
candidates were built before the placement was committed. */
pub(super) fn resume_after_placement(&mut self, placed: usize) {
if self.entities.get(self.entity_pos) == Some(&placed) {
self.entity_pos += 1;
}
self.values.clear();
self.value_pos = 0;
self.augmenting = false;
}

/* Drops a newly assigned required row from the value degrees, so the
degrees keep counting only the rows that still need a value. */
pub(super) fn retire_required_row<S>(
&mut self,
group: &ScalarAssignmentBinding<S>,
solution: &S,
entity_index: 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) {
*degree -= 1;
if *degree == 0 {
self.value_degrees.remove(&value);
}
}
}
}
}

#[derive(Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -209,6 +266,7 @@ impl CapacityCursor {
value_degrees: FastMap::default(),
options: self.options,
kind: AssignmentMoveKind::CapacityRepair,
augmenting: false,
});
}
}
Expand Down Expand Up @@ -372,93 +430,3 @@ pub(super) fn assigned_entities_by_position<S>(
});
entities
}

pub(super) fn required_entities_by_scarcity<S, ShouldStop>(
group: &ScalarAssignmentBinding<S>,
solution: &S,
state: &ScalarAssignmentState,
value_candidate_limit: Option<usize>,
should_stop: &mut ShouldStop,
) -> Option<Vec<usize>>
where
S: PlanningSolution,
ShouldStop: FnMut() -> bool,
{
let mut entities = 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();
if should_stop() {
return None;
}
entities.push((
candidate_count,
group.entity_order_key(solution, entity_index),
entity_index,
));
}
entities.sort_unstable();
if should_stop() {
return None;
}
Some(
entities
.into_iter()
.map(|(_, _, entity_index)| entity_index)
.collect(),
)
}

pub(super) fn required_value_degrees<S, ShouldStop>(
group: &ScalarAssignmentBinding<S>,
solution: &S,
entities: &[usize],
value_candidate_limit: Option<usize>,
should_stop: &mut ShouldStop,
) -> Option<FastMap<usize, usize>>
where
S: PlanningSolution,
ShouldStop: FnMut() -> bool,
{
let mut degrees = FastMap::default();
let mut processed_edges = 0usize;
for entity_index in entities {
if should_stop() {
return None;
}
for value in group.candidate_values(solution, *entity_index, value_candidate_limit) {
*degrees.entry(value).or_insert(0) += 1;
processed_edges += 1;
if processed_edges.is_multiple_of(GENERATION_POLL_INTERVAL) && should_stop() {
return None;
}
}
}
if should_stop() {
return None;
}
Some(degrees)
}

pub(super) fn sort_values_by_required_scarcity<S>(
group: &ScalarAssignmentBinding<S>,
solution: &S,
entity_index: usize,
degrees: &FastMap<usize, usize>,
values: &mut [usize],
) {
values.sort_by_key(|value| {
(
degrees.get(value).copied().unwrap_or(usize::MAX),
group.value_order_key(solution, entity_index, *value),
*value,
)
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use super::assignment_block::{
use super::assignment_candidate::{order_candidates, ScalarAssignmentMoveOptions};
use super::assignment_cycle::CycleWindowCursor;
use super::assignment_entity::{
required_entities_by_scarcity, required_value_degrees, AssignmentMoveKind, CapacityCursor,
EntityValueCursor, OptionalAdjustmentCursor,
AssignmentMoveKind, CapacityCursor, EntityValueCursor, OptionalAdjustmentCursor,
};
use super::assignment_pair::PairWindowCursor;
use super::assignment_scarcity::{required_entities_by_scarcity, required_value_degrees};
use super::assignment_state::ScalarAssignmentState;
use super::assignment_value_cycle::ValueWindowCycleCursor;
use super::assignment_value_release::ValueRunReleaseCursor;
Expand Down Expand Up @@ -98,9 +98,20 @@ impl AssignmentFamilyCursor {
value_degrees,
options,
kind: AssignmentMoveKind::Required,
augmenting: false,
}))
}

/* Carries an entity-value cursor past a finished placement; any other
family reopens against the committed state. */
pub(super) fn resume_after_placement(&mut self, placed: usize) {
match self {
Self::EntityValues(cursor) => cursor.resume_after_placement(placed),
Self::Empty => {}
_ => *self = Self::Empty,
}
}

pub(super) fn entity_values(
mut entities: Vec<usize>,
options: ScalarAssignmentMoveOptions,
Expand All @@ -115,6 +126,7 @@ impl AssignmentFamilyCursor {
value_degrees: FastMap::default(),
options,
kind,
augmenting: false,
})
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ impl<S> AugmentingPathSearch<'_, S> {
if state.is_required(blocker) {
continue;
}
work.overlay
.set_value(state, self.group, self.solution, blocker, None);
work.overlay.set_value(state, blocker, None);
work.edits.push(self.group.edit(blocker, None));
}
// State changed after the displacements; re-derive both blockers
Expand Down Expand Up @@ -196,8 +195,7 @@ impl<S> AugmentingPathSearch<'_, S> {
}

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

Expand Down
Loading
Loading