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
4 changes: 2 additions & 2 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -977,8 +977,8 @@ carry a `reason` attribute naming the model declaration that selected them
`required_assignments_remain`, `only_optional_assignments_remain`,
`scalar_slot_outside_assignment_groups`, `route_hooks_declared_and_route_non_empty`,
`element_groups_declared`, `list_elements_remain_unassigned`). The optional
assignment step of a time-limited solve also carries `time_budget_seconds`,
the share of the time limit it was allowed.
assignment step of a time-limited solve also carries `time_budget_ms`,
the share of the time limit it was allowed, in milliseconds.
The default local-search node carries acceptor, forager,
`forager_accepted_count_limit`, `selection_order`, `weighting` (`equal`, or
`fixed:[...]` with one cost weight per selector) and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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_scarcity::{required_value_degrees, sort_values_by_required_scarcity};
use super::assignment_state::{CapacityConflict, ScalarAssignmentState};
use crate::builder::ScalarAssignmentBinding;
use crate::heuristic::r#move::CompoundScalarMove;
Expand All @@ -21,9 +21,14 @@ 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. */
/* Required rows are placed in two passes over the scarcity order. The
direct pass gives each row its first value that is free (search depth
0), with the value degrees of every row the pass started with; the
augmenting pass then places the rows left over with rematches, its
degrees counting only the rows that still need a value. A row with a
free value never pays for a rematch search, and one row's rematch never
takes the value a later row would have had free. False during the direct
pass. */
pub(super) augmenting: bool,
}

Expand All @@ -41,7 +46,13 @@ impl EntityValueCursor {
ShouldStop: FnMut() -> bool,
{
let intent = self.kind.intent();
while self.entity_pos < self.entities.len() {
loop {
if self.entity_pos == self.entities.len() {
if !self.begin_augmenting_pass(group, solution, state, should_stop)? {
return None;
}
continue;
}
if should_stop() {
return None;
}
Expand All @@ -52,7 +63,6 @@ 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 @@ -102,20 +112,52 @@ 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
}

/* Ends the direct pass of a required cursor: generation restarts at the
first row with rematches allowed, and the value degrees are recounted
over the rows still unassigned. `Some(false)` when there is no
augmenting pass to run, `None` when stopped while recounting. */
fn begin_augmenting_pass<S, ShouldStop>(
&mut self,
group: &ScalarAssignmentBinding<S>,
solution: &S,
state: &ScalarAssignmentState,
should_stop: &mut ShouldStop,
) -> Option<bool>
where
S: PlanningSolution,
ShouldStop: FnMut() -> bool,
{
if self.kind != AssignmentMoveKind::Required
|| self.augmenting
|| self.options.max_depth == 0
{
return Some(false);
}
self.entities
.retain(|entity_index| state.current_value(*entity_index).is_none());
if self.entities.is_empty() {
return Some(false);
}
if self.options.required_scarcity_ordering {
self.value_degrees = required_value_degrees(
group,
solution,
&self.entities,
self.options.value_candidate_limit,
should_stop,
)?;
}
self.augmenting = true;
self.entity_pos = 0;
self.values.clear();
self.value_pos = 0;
Some(true)
}

fn request_depth(&self) -> usize {
Expand All @@ -135,19 +177,19 @@ impl EntityValueCursor {
}
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. */
/* Drops a required row the augmenting pass assigned from the value
degrees, so they keep counting only the rows that still need a value.
The direct pass keeps the degrees it started with. */
pub(super) fn retire_required_row<S>(
&mut self,
group: &ScalarAssignmentBinding<S>,
solution: &S,
entity_index: usize,
values: &mut Vec<usize>,
) {
if self.value_degrees.is_empty() {
if !self.augmenting || self.value_degrees.is_empty() {
return;
}
group.candidate_values_into(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

The placement cursor keeps its assignment state and row order from one
placement to the next, so a construction reads each row's domain a bounded
number of times instead of once per placement, and a required row takes a
free value before any value that needs an augmenting rematch. */
number of times instead of once per placement. Required rows take free
values in a direct pass, with the value degrees that pass started with,
before an augmenting pass rematches rows for the rest. */

use std::cell::Cell;

Expand Down Expand Up @@ -80,3 +81,22 @@ fn required_rows_take_a_free_value_before_a_rematch() {
);
assert_eq!(solved.assignments, vec![Some(0), Some(1)]);
}

#[test]
fn direct_pass_orders_values_by_the_degrees_it_started_with() {
let group = assignment_group(&descriptor(), ScalarGroupLimits::new());
let solved = construct(
group,
AssignmentPlan {
score: None,
// Values 0 and 1 are listed once, value 2 three times and values
// 3 and 4 twice. Rows 0 and 1 take their scarcer value, so row 2
// ranks value 3 (two rows) before value 2 (three rows) and row 3
// then takes value 4. Recounting value 2 once rows 0 and 1 hold
// values would hand row 2 value 2 and row 3 value 3.
assignments: vec![None; 4],
candidates: vec![vec![0, 2], vec![1, 2], vec![2, 3], vec![3, 4]],
},
);
assert_eq!(solved.assignments, vec![Some(0), Some(1), Some(3), Some(4)]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! and run through the same prepared dispatcher as explicit construction.

use std::fmt;
use std::time::Duration;

use solverforge_core::domain::PlanningSolution;
use solverforge_core::score::{ParseableScore, Score};
Expand Down Expand Up @@ -142,14 +143,13 @@ where
/// Optional rows stay reachable to local search's optional-assignment moves.
const OPTIONAL_CONSTRUCTION_BUDGET_PERCENT: u32 = 20;

/// The optional pass's remaining share of the scope's time span, rounded up
/// to whole seconds, or `None` when no time limit applies. The span is the
/// solver-active time so far plus the remaining time, so a top-level solve
/// shares its time limit and a partition shares the time its inherited
/// deadline leaves it.
pub(super) fn optional_construction_termination<S, D, ProgressCb>(
/// The optional pass's remaining share of the scope's time span, or `None`
/// when no time limit applies. The span is the solver-active time so far plus
/// the remaining time, so a top-level solve shares its time limit and a
/// partition shares the time its inherited deadline leaves it.
pub(super) fn optional_construction_budget<S, D, ProgressCb>(
solver_scope: &SolverScope<'_, S, D, ProgressCb>,
) -> Option<solverforge_config::TerminationConfig>
) -> Option<Duration>
where
S: PlanningSolution,
D: Director<S>,
Expand All @@ -158,11 +158,7 @@ where
let elapsed = solver_scope.elapsed().unwrap_or_default();
let span = elapsed + solver_scope.remaining_time()?;
let share = span * OPTIONAL_CONSTRUCTION_BUDGET_PERCENT / 100;
let remaining = share.saturating_sub(elapsed);
Some(solverforge_config::TerminationConfig {
seconds_spent_limit: Some(remaining.as_millis().div_ceil(1000) as u64),
..solverforge_config::TerminationConfig::default()
})
Some(share.saturating_sub(elapsed))
}

fn execute_resolved_default_construction_plan<S, V, DM, IDM, Extension, D, ProgressCb>(
Expand All @@ -182,22 +178,17 @@ where
{
let mut steps = Vec::with_capacity(resolved.steps.len());
for step in &resolved.steps {
let mut construction =
let construction =
execution.prepare_resolved_construction(default.phase_index, &step.construction)?;
let mut time_budget_seconds = None;
if step.kind == DefaultConstructionStepKind::AssignmentOptional {
if let PreparedConstruction::GroupedScalar { config, .. } = &mut construction {
config.termination = optional_construction_termination(solver_scope);
time_budget_seconds = config
.termination
.as_ref()
.and_then(|termination| termination.seconds_spent_limit);
}
}
let time_budget = (step.kind == DefaultConstructionStepKind::AssignmentOptional
&& matches!(construction, PreparedConstruction::GroupedScalar { .. }))
.then(|| optional_construction_budget(solver_scope))
.flatten();
let execution = execute_prepared_construction(
execution,
&construction,
step.required_only,
time_budget,
solver_scope,
)?;
steps.push(ResolvedConstructionExecutionStep {
Expand All @@ -206,7 +197,7 @@ where
required_only: step.required_only,
target: step.target.clone(),
list_policies: step.list_policies.clone(),
time_budget_seconds,
time_budget_ms: time_budget.map(|budget| budget.as_millis() as u64),
outcome: execution.outcome,
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! savings/merge/completion path.

use std::fmt;
use std::time::Duration;

use solverforge_config::ConstructionHeuristicConfig;
use solverforge_core::domain::PlanningSolution;
Expand Down Expand Up @@ -48,6 +49,7 @@ pub(crate) fn execute_prepared_construction<S, V, DM, IDM, Extension, D, Progres
execution: &mut PreparedRuntimeExecution<S, V, DM, IDM, Extension>,
construction: &PreparedConstruction<S, V, DM, IDM>,
required_only: bool,
time_budget: Option<Duration>,
solver_scope: &mut SolverScope<'_, S, D, ProgressCb>,
) -> Result<ConstructionExecution, RuntimeInstantiationError>
where
Expand All @@ -70,6 +72,7 @@ where
} => execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
if control_policy.should_terminate_construction(solver_scope) {
Expand Down Expand Up @@ -128,6 +131,7 @@ where
execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
execute_list_slots(
Expand All @@ -144,6 +148,7 @@ where
execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
execute_list_slots(
Expand All @@ -169,6 +174,7 @@ where
execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
execute_list_slots(
Expand All @@ -194,6 +200,7 @@ where
execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
execute_list_slots(
Expand All @@ -220,6 +227,7 @@ where
PreparedConstruction::KOpt { config, slots } => execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
for slot in slots {
Expand All @@ -239,6 +247,7 @@ where
} => execute_with_construction_termination(
config,
control_policy,
time_budget,
solver_scope,
|solver_scope| {
if control_policy.should_terminate_construction(solver_scope) {
Expand Down Expand Up @@ -270,6 +279,7 @@ where
fn execute_with_construction_termination<S, D, ProgressCb>(
config: &ConstructionHeuristicConfig,
control_policy: StepControlPolicy,
time_budget: Option<Duration>,
solver_scope: &mut SolverScope<'_, S, D, ProgressCb>,
work: impl FnOnce(&mut SolverScope<'_, S, D, ProgressCb>) -> Result<bool, RuntimeInstantiationError>,
) -> Result<ConstructionExecution, RuntimeInstantiationError>
Expand All @@ -279,7 +289,7 @@ where
D: Director<S>,
ProgressCb: ProgressCallback<S>,
{
solver_scope.with_phase_termination(config.termination.as_ref(), |solver_scope| {
solver_scope.with_phase_termination(config.termination.as_ref(), time_budget, |solver_scope| {
if control_policy.should_terminate_construction(solver_scope) {
return Ok(ConstructionExecution::skipped_terminated());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ pub(crate) struct ResolvedConstructionExecutionStep {
pub(crate) required_only: bool,
pub(crate) target: Option<RuntimeScalarSlotId>,
pub(crate) list_policies: Option<DefaultListPolicyProvenance>,
/// Whole seconds of the solve's time limit this step was allowed, when
/// Milliseconds of the solve's time limit this step was allowed, when
/// the default policy bounded it.
pub(crate) time_budget_seconds: Option<u64>,
pub(crate) time_budget_ms: Option<u64>,
pub(crate) outcome: ResolvedConstructionExecutionOutcome,
}

Expand Down
Loading
Loading