From 591b4eed4ecf5542c83435378e8040ca18d01ad3 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 13 Nov 2026 05:11:54 +0100 Subject: [PATCH 1/2] perf(solver): resolve Clarke-Wright owner restrictions once per route Clarke-Wright asked the element-owner hook for every element of a route once per candidate owner: in the singleton pass, in owner-set and has-owner checks, and in completion. That is routes x owners x route length hook calls, which dominated the phase once savings stopped doing: 87% of a 20k-stop, 500-vehicle construction went to owner restriction checks. Each loop now resolves the route's (or element's) restriction once through list_placement's OwnerRestriction, which gains from_hook_owner and and, and tests each owner against it. The feasibility hook is still asked in the same order, so every decision is unchanged. Raw owner-hook answers are now interpreted only in list_placement, as for the other list phases. Construction-only runs of all 100 X instances give identical routes (2.84 s -> 2.48 s in total), as do synthetic stock-profile instances at 1k-8k stops. --- .../solverforge-solver/src/list_placement.rs | 27 +++++++++++--- .../phase_factory/list_clarke_wright.rs | 30 +++++++++------- .../list_clarke_wright/completion.rs | 35 ++++++++++--------- .../list_clarke_wright/kernel.rs | 11 ++---- .../list_clarke_wright/owner_assignment.rs | 20 +++-------- .../tests/admission_oracle.rs | 4 +-- 6 files changed, 68 insertions(+), 59 deletions(-) diff --git a/crates/solverforge-solver/src/list_placement.rs b/crates/solverforge-solver/src/list_placement.rs index 7e2cbbdf..bd256dcc 100644 --- a/crates/solverforge-solver/src/list_placement.rs +++ b/crates/solverforge-solver/src/list_placement.rs @@ -20,6 +20,27 @@ impl OwnerRestriction { } } + /// The restriction an owner hook's answer imposes among `entity_count` + /// entities: `None` leaves the element unrestricted, an in-range owner + /// fixes it, and an out-of-range owner admits no entity. + pub(crate) fn from_hook_owner(owner: Option, entity_count: usize) -> Self { + match owner { + None => Self::Unrestricted, + Some(owner_idx) if owner_idx < entity_count => Self::Fixed(owner_idx), + Some(_) => Self::Invalid, + } + } + + /// The entities both restrictions admit: the restriction of a group of + /// elements that must share one entity. + pub(crate) fn and(self, other: Self) -> Self { + match (self, other) { + (Self::Unrestricted, restriction) | (restriction, Self::Unrestricted) => restriction, + (Self::Fixed(left), Self::Fixed(right)) if left == right => Self::Fixed(left), + _ => Self::Invalid, + } + } + pub(crate) fn candidates(self, entity_count: usize) -> CandidateEntityIter { match self { Self::Unrestricted => CandidateEntityIter::All(0..entity_count), @@ -67,11 +88,7 @@ pub(crate) fn owner_restriction( return OwnerRestriction::Unrestricted; }; - match owner_fn(solution, element) { - None => OwnerRestriction::Unrestricted, - Some(owner_idx) if owner_idx < entity_count => OwnerRestriction::Fixed(owner_idx), - Some(_) => OwnerRestriction::Invalid, - } + OwnerRestriction::from_hook_owner(owner_fn(solution, element), entity_count) } #[cfg(test)] diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs index e9018a7c..1c52a90d 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs @@ -12,6 +12,7 @@ use crate::builder::context::{ ListSourceAccess, RuntimeListElement, RuntimeListSlot, RuntimeListSourceIndex, SourceElement, }; use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; +use crate::list_placement::OwnerRestriction; mod commit; mod completion; @@ -111,35 +112,38 @@ where } } -pub(super) fn owner_allows( +/// The owners an element admits, resolved once so loops over owners test +/// each against it instead of calling the owner hook per owner. +pub(super) fn element_restriction( access: &A, solution: &S, entity_count: usize, - entity_index: usize, element: &A::Element, -) -> bool +) -> OwnerRestriction where A: ClarkeWrightAccess, { - match access.element_owner(solution, element) { - None => true, - Some(owner_index) => owner_index < entity_count && owner_index == entity_index, - } + OwnerRestriction::from_hook_owner(access.element_owner(solution, element), entity_count) } -pub(super) fn route_owner_allows( +/// The owners every element of a route admits. +pub(super) fn route_restriction( access: &A, solution: &S, entity_count: usize, - entity_index: usize, route: &[&A::Element], -) -> bool +) -> OwnerRestriction where A: ClarkeWrightAccess, { - route - .iter() - .all(|element| owner_allows(access, solution, entity_count, entity_index, element)) + let mut restriction = OwnerRestriction::Unrestricted; + for element in route { + restriction = restriction.and(element_restriction(access, solution, entity_count, element)); + if restriction == OwnerRestriction::Invalid { + break; + } + } + restriction } pub(super) struct CompletionAssignment { diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/completion.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/completion.rs index ea5a05d8..351c294e 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/completion.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/completion.rs @@ -5,7 +5,8 @@ use solverforge_scoring::Director; use super::route_state::{route_values, ConstructedRoute}; use super::{ - insertion_delta, owner_allows, ClarkeWrightAccess, CompletionAssignment, RuntimeListSourceIndex, + element_restriction, insertion_delta, ClarkeWrightAccess, CompletionAssignment, + RuntimeListSourceIndex, }; use crate::phase::construction::{record_construction_candidate, PendingConstructionMoveTelemetry}; use crate::scope::{PhaseScope, ProgressCallback, StepControlPolicy}; @@ -60,15 +61,17 @@ where let element = source_index.element(element_idx); let value = [route_values_by_source_index[element_idx]]; feasibility.begin_route(); + let restriction = element_restriction(access, solution, entity_count, element); let feasible_owner_count = (0..owner_slots.len()) .filter(|&slot_position| { - owner_allows( - access, - solution, - entity_count, - owner_slots[slot_position].owner_idx, - element, - ) && feasibility.feasible(access, solution, owner_slots, slot_position, &value) + restriction.allows(owner_slots[slot_position].owner_idx) + && feasibility.feasible( + access, + solution, + owner_slots, + slot_position, + &value, + ) }) .count(); if feasible_owner_count == 0 { @@ -85,16 +88,16 @@ where return None; } let mut best: Option<(i64, usize, usize, Option)> = None; + let element = source_index.element(element_idx); + let restriction = element_restriction( + access, + phase_scope.score_director().working_solution(), + entity_count, + element, + ); for (assignment_idx, assignment) in assignments.iter().enumerate() { let owner_idx = assignment.owner_idx; - let element = source_index.element(element_idx); - if !owner_allows( - access, - phase_scope.score_director().working_solution(), - entity_count, - owner_idx, - element, - ) { + if !restriction.allows(owner_idx) { continue; } diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs index e957bbe7..f22c9b25 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs @@ -14,7 +14,7 @@ use super::owner_assignment::{ }; use super::route_state::{route_elements_into, route_values, route_values_into, ConstructedRoute}; use super::savings::{generate_savings, sort_savings}; -use super::{owner_allows, ClarkeWrightAccess, RuntimeListSourceIndex, SourceElement}; +use super::{element_restriction, ClarkeWrightAccess, RuntimeListSourceIndex, SourceElement}; use crate::phase::construction::{ record_construction_candidate, run_construction_phase, PendingConstructionMoveTelemetry, }; @@ -126,15 +126,10 @@ fn run_clarke_wright_in_phase( for entry in &unassigned { let singleton = [access.route_value(&entry.element)]; feasibility.begin_route(); + let restriction = element_restriction(access, solution, n_entities, &entry.element); let feasible_for_all_owners = (0..owner_slots.len()).all(|slot_position| { feasibility.feasible(access, solution, &owner_slots, slot_position, &singleton) - && owner_allows( - access, - solution, - n_entities, - owner_slots[slot_position].owner_idx, - &entry.element, - ) + && restriction.allows(owner_slots[slot_position].owner_idx) }); routes.push(ConstructedRoute::singleton( entry.source_index, diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/owner_assignment.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/owner_assignment.rs index e7839e1d..1e445a70 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/owner_assignment.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/owner_assignment.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use solverforge_core::domain::PlanningSolution; use super::route_state::{route_values, ConstructedRoute}; -use super::{route_owner_allows, ClarkeWrightAccess, RuntimeListSourceIndex}; +use super::{route_restriction, ClarkeWrightAccess, RuntimeListSourceIndex}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct OwnerSlot { @@ -121,19 +121,14 @@ where A: ClarkeWrightAccess, { feasibility.begin_route(); + let restriction = route_restriction(access, solution, entity_count, route_elements); let mut owners = Vec::new(); for (slot_position, slot) in owner_slots.iter().enumerate() { if scored_metric_class.is_some_and(|class| slot.metric_class != class) { continue; } if feasibility.feasible(access, solution, owner_slots, slot_position, route_values) - && route_owner_allows( - access, - solution, - entity_count, - slot.owner_idx, - route_elements, - ) + && restriction.allows(slot.owner_idx) { owners.push(slot.owner_idx); } @@ -159,19 +154,14 @@ where A: ClarkeWrightAccess, { feasibility.begin_route(); + let restriction = route_restriction(access, solution, entity_count, route_elements); owner_slots .iter() .enumerate() .filter(|(_, slot)| scored_metric_class.is_none_or(|class| slot.metric_class == class)) .any(|(slot_position, slot)| { feasibility.feasible(access, solution, owner_slots, slot_position, route_values) - && route_owner_allows( - access, - solution, - entity_count, - slot.owner_idx, - route_elements, - ) + && restriction.allows(slot.owner_idx) }) } diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/admission_oracle.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/admission_oracle.rs index c1c93ff5..f14fa869 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/admission_oracle.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/admission_oracle.rs @@ -203,13 +203,13 @@ fn run_case(seed: u64, shared_by_class: bool) -> (usize, usize) { let singleton = [element]; let all = slots.iter().all(|slot| { feasible(&plan, slot.owner_idx, &singleton) - && super::super::owner_allows( + && super::super::element_restriction( &access, &plan, owner_count, - slot.owner_idx, source_index.element(element), ) + .allows(slot.owner_idx) }); ConstructedRoute::singleton(element, all) }) From b7e14ad01e27c574fe00f6fa72a79d62ea165805 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 13 Nov 2026 05:12:06 +0100 Subject: [PATCH 2/2] feat(solver): bound Clarke-Wright savings to nearest neighbours list_clarke_wright scores every pair of unassigned elements, so its savings list holds 32 bytes per pair: 1.6 GB at 10k stops, 40 GB at 50k. With the pluggable route metric that was the last structure quadratic in the stops. `savings_neighbors = K` on a list_clarke_wright phase scores a pair only when one element is among the other's K nearest, about K entries per element. The neighbours come from a new optional list hook, savings_neighbors_fn (ListVariableMetadata, ListVariableSlot and the savings_neighbors_fn macro attribute); the compiler rejects a bounded phase on a slot without one. Each pair is scored once, left before right in the unassigned order, so the bounded savings are an ordered subset of the full list and a bound of at least n - 1 reproduces unbounded construction. Without the setting nothing changes. The domain = "cvrp" profile supplies cvrp::savings_neighbors, which asks the vehicle's RouteMetric::nearest. Its provided method ranks every pair (quadratic time, linear memory), which DenseMatrix uses; EuclideanMetric answers from a uniform grid, visiting cell rings until no closer stop can remain, with exactly the provided method's result. The compiled list slot keeps its size: the route bindings read the metric-class hook from the slot instead of holding a copy, and the setting is an Option, which fits the construction config's existing padding: a larger config shifted the solver's heap layout and failed the cache-miss gate on unrelated cases. Synthetic stock-profile instances on EuclideanMetric, K = 40: stops unbounded K = 40 10k 13.2 s, 1.58 GB 0.30 s, 25 MB 20k 56.6 s, 6.29 GB 1.06 s, 52 MB 50k - 6.0 s, 164 MB 100k - 22.8 s, 389 MB Scores are equal at 20k and within 0.02% at 10k. On the 100 X instances K = 40 keeps the score of 90, improves the hard score of 2 and changes the soft score by -0.10% on average (median 0), in a fifth of the time. Closes #252 --- crates/solverforge-config/WIREFRAME.md | 1 + crates/solverforge-config/src/phase.rs | 10 + crates/solverforge-cvrp/WIREFRAME.md | 9 +- crates/solverforge-cvrp/src/euclidean_grid.rs | 152 ++++++++++ crates/solverforge-cvrp/src/helpers.rs | 17 ++ crates/solverforge-cvrp/src/lib.rs | 3 +- crates/solverforge-cvrp/src/metric.rs | 54 ++++ crates/solverforge-cvrp/src/metric_tests.rs | 113 ++++++++ crates/solverforge-cvrp/src/problem_data.rs | 7 +- crates/solverforge-macros/WIREFRAME.md | 7 +- .../solverforge-macros/src/attr_validation.rs | 1 + .../src/planning_entity/list_variable.rs | 6 + .../src/planning_entity_tests.rs | 54 +++- .../runtime/helpers/phase_support.rs | 1 + ...ning_list_variable_unknown_argument.stderr | 2 +- crates/solverforge-solver/WIREFRAME.md | 9 +- crates/solverforge-solver/public-api.txt | 6 +- .../src/builder/context/list.rs | 16 ++ .../builder/context/list_access/dynamic.rs | 7 +- .../src/builder/context/list_access/types.rs | 1 + .../builder/context/runtime_list_binding.rs | 13 + .../src/builder/context/runtime_list_route.rs | 8 +- .../context/runtime_list_route_policy.rs | 21 +- .../phase_factory/list_clarke_wright.rs | 27 ++ .../list_clarke_wright/facade.rs | 31 ++ .../list_clarke_wright/kernel.rs | 4 + .../list_clarke_wright/savings.rs | 264 +++++++++++++----- .../phase_factory/list_clarke_wright/tests.rs | 1 + .../tests/bounded_savings.rs | 213 ++++++++++++++ .../tests/compiled_parity.rs | 1 + .../tests/compiled_parity/refresh.rs | 2 + .../tests/public_compiled_parity.rs | 1 + crates/solverforge-solver/src/runtime.rs | 12 + .../src/runtime/compiler/construction.rs | 3 + .../src/runtime/compiler/executor/execute.rs | 15 +- .../list_construction/clarke_wright.rs | 10 +- .../src/runtime/compiler/selector_values.rs | 9 + .../src/runtime/compiler/slots.rs | 1 + .../src/runtime/compiler/tests.rs | 9 +- .../compiler/tests/savings_neighbors.rs | 96 +++++++ .../src/runtime/compiler/types.rs | 2 + crates/solverforge/WIREFRAME.md | 2 +- crates/solverforge/src/cvrp.rs | 2 +- .../tests/list_clarke_wright_bounded.rs | 46 +++ docs/configuration.md | 23 ++ docs/extend-domain.md | 6 +- docs/modeling.md | 9 +- 47 files changed, 1178 insertions(+), 129 deletions(-) create mode 100644 crates/solverforge-cvrp/src/euclidean_grid.rs create mode 100644 crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/bounded_savings.rs create mode 100644 crates/solverforge-solver/src/runtime/compiler/tests/savings_neighbors.rs create mode 100644 crates/solverforge/tests/list_clarke_wright_bounded.rs diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index 36909016..d490d0a3 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -143,6 +143,7 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`. | `value_candidate_limit` | `Option` | `None`; valid: `>= 1` when set; scalar heuristics only, list heuristics reject it | | `group_name` | `Option` | `None` | | `group_candidate_limit` | `Option` | `None`; valid: `>= 1` when set; requires `group_name`; list heuristics reject it | +| `savings_neighbors` | `Option` | `None` (every pair scored); `0` does not parse; `ListClarkeWright` only, which then scores a pair only when one element is among the other's `savings_neighbors` nearest; other heuristics reject it | | `termination` | `Option` | `None` | `target` is flattened in serde, so configuration files still use top-level diff --git a/crates/solverforge-config/src/phase.rs b/crates/solverforge-config/src/phase.rs index 5230bd2f..8ddd75f8 100644 --- a/crates/solverforge-config/src/phase.rs +++ b/crates/solverforge-config/src/phase.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU32; + use serde::{Deserialize, Serialize}; use crate::acceptor::AcceptorConfig; @@ -61,6 +63,13 @@ pub struct ConstructionHeuristicConfig { /// Requires `group_name`; a list heuristic rejects it. pub group_candidate_limit: Option, + /// Bounds `list_clarke_wright` savings to each element's nearest + /// neighbours: a pair is scored only when one element is among the other's + /// `savings_neighbors` nearest, so the savings list holds about + /// `savings_neighbors` entries per element instead of one per pair. Absent, + /// every pair is scored. Zero does not parse; other heuristics reject it. + pub savings_neighbors: Option, + /// Phase termination configuration. pub termination: Option, } @@ -75,6 +84,7 @@ impl Default for ConstructionHeuristicConfig { value_candidate_limit: None, group_name: None, group_candidate_limit: None, + savings_neighbors: None, termination: None, } } diff --git a/crates/solverforge-cvrp/WIREFRAME.md b/crates/solverforge-cvrp/WIREFRAME.md index 9b1b4880..e52f91a3 100644 --- a/crates/solverforge-cvrp/WIREFRAME.md +++ b/crates/solverforge-cvrp/WIREFRAME.md @@ -14,6 +14,7 @@ stock `domain = "cvrp"` list-variable profile internals. ``` src/ +├── euclidean_grid.rs — Grid-backed exact nearest-location queries for `EuclideanMetric` ├── helpers.rs — Public CVRP free functions, hook bundles, and private pointer helpers ├── lib.rs — Module exports and public re-exports ├── meters.rs — Distance meter implementations @@ -61,6 +62,7 @@ per metric type. | `distance` | `fn(&self, from: usize, to: usize) -> Option` | Leg distance; `None` outside the metric | | `travel_time` | `fn(&self, from: usize, to: usize) -> Option` | Leg travel time; `None` outside the metric | | `covers` | `fn(&self, route: &[usize], depot: usize, max_node: usize) -> bool` | Whether every leg among the route's visits and the depot is defined | +| `nearest` | `fn(&self, locations: &[usize], k: usize, out: &mut Vec)` | Appends for each location the indexes into `locations` of its `min(k, len - 1)` nearest others by leg distance (untraversable legs rank as the savings distance's large finite cost), nearest first, ties by lower index. Provided: ranks every pair, quadratic time, linear memory | ### `DenseMatrix` @@ -76,7 +78,9 @@ Straight-line legs between planar coordinates, computed on demand: distance is `sqrt(dx² + dy²)` rounded half away from zero (TSPLIB `EUC_2D`), travel time is that length divided by the speed, rounded the same way. `EuclideanMetric::new(coordinates, speed)` panics on a non-finite or non-positive speed or a non-finite coordinate; -`coordinates()` and `speed()` read them back. Implements `RouteMetric`. +`coordinates()` and `speed()` read them back. Implements `RouteMetric`; +its `nearest` answers from a uniform grid over the locations with exactly the +provided method's result, in time about linear in `locations.len() * k`. Derives: `Clone, Debug`. Memory is linear in the location count. ### `VrpSolution` (trait) @@ -117,6 +121,7 @@ All functions are generic over `S: VrpSolution`. | `savings_metric_class` | `fn(plan: &S, entity_idx: usize) -> usize` | Clarke-Wright metric class for owners that share backing `ProblemData` | | `savings_distance` | `fn(plan: &S, entity_idx: usize, from: usize, to: usize) -> i64` | Construction distance adapter for models that share exact CVRP route data | | `savings_feasible` | `fn(plan: &S, entity_idx: usize, route: &[usize]) -> bool` | Construction admissibility adapter that rejects only non-evaluable stock CVRP routes | +| `savings_neighbors` | `fn(plan: &S, entity_idx: usize, values: &[usize], k: usize, out: &mut Vec)` | Bounded Clarke-Wright neighbour hook: the vehicle's `RouteMetric::nearest` over the values; nothing for an out-of-range vehicle | ### Usage as a macro domain profile @@ -128,7 +133,7 @@ All functions are generic over `S: VrpSolution`. ``` The profile expands to the stock meters, `VrpSolution` bound, route hooks, -savings hooks, and savings metric class. Route-local phases use strict stock +savings hooks, savings metric class, and savings neighbour hook. Route-local phases use strict stock CVRP route feasibility. Clarke-Wright construction uses relaxed savings feasibility so assignment can stay broad while the score model compares capacity, lateness, and unreachable-leg violations against leaving work diff --git a/crates/solverforge-cvrp/src/euclidean_grid.rs b/crates/solverforge-cvrp/src/euclidean_grid.rs new file mode 100644 index 00000000..51935772 --- /dev/null +++ b/crates/solverforge-cvrp/src/euclidean_grid.rs @@ -0,0 +1,152 @@ +//! Exact k-nearest-location queries for `EuclideanMetric` over a uniform grid. + +use crate::metric::{leg_rank, nearest_by_rank}; +use crate::{EuclideanMetric, RouteMetric}; + +/// Writes what `RouteMetric::nearest` specifies, ranking by the same rounded +/// leg distance and index the provided method uses, so both agree exactly. +pub(crate) fn nearest( + metric: &EuclideanMetric, + locations: &[usize], + k: usize, + out: &mut Vec, +) { + let stride = k.min(locations.len().saturating_sub(1)); + if stride == 0 { + return; + } + let coordinates = metric.coordinates(); + let Some(points) = locations + .iter() + .map(|&location| coordinates.get(location).copied()) + .collect::>>() + else { + // A location outside the coordinates has no position to index; the + // provided ranking handles its undefined legs. + return nearest_by_rank(metric, locations, k, out); + }; + let grid = Grid::new(&points); + let mut best: Vec<(i64, usize)> = Vec::with_capacity(stride + 1); + for (index, &point) in points.iter().enumerate() { + best.clear(); + let (cell_x, cell_y) = grid.cell_of(point); + let mut ring = 0usize; + loop { + grid.visit_ring(cell_x, cell_y, ring, |other| { + if other == index { + return; + } + let key = ( + leg_rank(metric.distance(locations[index], locations[other])), + other, + ); + if best.len() < stride || key < best[stride - 1] { + let at = best.partition_point(|&held| held < key); + best.insert(at, key); + best.truncate(stride); + } + }); + // Every location outside rings 0..=ring lies at least + // `ring * cell` away, so its rounded distance exceeds the k-th + // best once that bound passes the k-th best by half a unit. + let settled = best.len() == stride && { + let bound = ring as f64 * grid.cell; + let kth = best[stride - 1].0 as f64; + bound > kth + 0.5 + 1e-9 * (1.0 + kth.abs()) + }; + if settled || ring > grid.width.max(grid.height) { + break; + } + ring += 1; + } + out.extend(best.iter().map(|&(_, other)| other)); + } +} + +/// Location indexes bucketed by cell, row-major, ascending within a cell. +struct Grid { + min_x: f64, + min_y: f64, + cell: f64, + width: usize, + height: usize, + cell_start: Vec, + members: Vec, +} + +impl Grid { + fn new(points: &[(f64, f64)]) -> Self { + let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY); + let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY); + for &(x, y) in points { + min_x = min_x.min(x); + min_y = min_y.min(y); + max_x = max_x.max(x); + max_y = max_y.max(y); + } + let span_x = max_x - min_x; + let span_y = max_y - min_y; + // About two locations per cell over the bounding box. + let area = (span_x.max(1.0)) * (span_y.max(1.0)); + let cell = (2.0 * area / points.len() as f64).sqrt().max(1e-9); + let width = (span_x / cell) as usize + 1; + let height = (span_y / cell) as usize + 1; + let mut grid = Self { + min_x, + min_y, + cell, + width, + height, + cell_start: vec![0; width * height + 1], + members: vec![0; points.len()], + }; + let cells: Vec = points + .iter() + .map(|&point| { + let (x, y) = grid.cell_of(point); + y * width + x + }) + .collect(); + for &cell_index in &cells { + grid.cell_start[cell_index + 1] += 1; + } + for cell_index in 0..width * height { + grid.cell_start[cell_index + 1] += grid.cell_start[cell_index]; + } + let mut next = grid.cell_start.clone(); + for (index, &cell_index) in cells.iter().enumerate() { + grid.members[next[cell_index]] = index; + next[cell_index] += 1; + } + grid + } + + fn cell_of(&self, (x, y): (f64, f64)) -> (usize, usize) { + let cell_x = (((x - self.min_x) / self.cell) as usize).min(self.width - 1); + let cell_y = (((y - self.min_y) / self.cell) as usize).min(self.height - 1); + (cell_x, cell_y) + } + + /// Visits the locations of the cells at Chebyshev distance `ring` from + /// `(cell_x, cell_y)` that lie inside the grid. + fn visit_ring(&self, cell_x: usize, cell_y: usize, ring: usize, mut visit: impl FnMut(usize)) { + let (cx, cy, r) = (cell_x as isize, cell_y as isize, ring as isize); + let (width, height) = (self.width as isize, self.height as isize); + for y in (cy - r).max(0)..=(cy + r).min(height - 1) { + let edge_row = y == cy - r || y == cy + r; + let step = if edge_row || r == 0 { 1 } else { 2 * r }; + let mut x = cx - r; + while x <= cx + r { + if (0..width).contains(&x) { + let cell_index = y as usize * self.width + x as usize; + for &member in + &self.members[self.cell_start[cell_index]..self.cell_start[cell_index + 1]] + { + visit(member); + } + } + x += step; + } + } + } +} diff --git a/crates/solverforge-cvrp/src/helpers.rs b/crates/solverforge-cvrp/src/helpers.rs index e86dfb07..94e8ba71 100644 --- a/crates/solverforge-cvrp/src/helpers.rs +++ b/crates/solverforge-cvrp/src/helpers.rs @@ -59,6 +59,23 @@ pub fn savings_distance( route_distance(plan, entity_idx, from, to) } +/// Nearest neighbours for bounded Clarke-Wright savings: for each of +/// `values` (locations) in order, the indexes into `values` of its +/// `min(k, values.len() - 1)` nearest other values by the vehicle's +/// `RouteMetric::nearest`, nearest first, ties by lower index. Nothing is +/// appended for an out-of-range vehicle. +pub fn savings_neighbors( + plan: &S, + entity_idx: usize, + values: &[usize], + k: usize, + out: &mut Vec, +) { + if let Some(data) = problem_data_for_entity(plan, entity_idx) { + data.metric.nearest(values, k, out); + } +} + /// Construction admissibility used by Clarke-Wright for stock CVRP route data. /// /// This intentionally rejects only routes that cannot be evaluated safely. diff --git a/crates/solverforge-cvrp/src/lib.rs b/crates/solverforge-cvrp/src/lib.rs index 1e6a4175..64d63d73 100644 --- a/crates/solverforge-cvrp/src/lib.rs +++ b/crates/solverforge-cvrp/src/lib.rs @@ -5,6 +5,7 @@ //! `MatrixIntraDistanceMeter`, the `VrpSolution` trait, and the stock helpers //! behind `#[planning_list_variable(domain = "cvrp")]`. +mod euclidean_grid; mod helpers; mod meters; mod metric; @@ -14,7 +15,7 @@ mod solution; pub use helpers::{ depot_for_entity, get_route, replace_route, route_distance, route_feasible, route_hooks, savings_depot_for_entity, savings_distance, savings_feasible, savings_hooks, - savings_metric_class, + savings_metric_class, savings_neighbors, }; pub use meters::{MatrixDistanceMeter, MatrixIntraDistanceMeter}; pub use metric::{DenseMatrix, EuclideanMetric, RouteMetric}; diff --git a/crates/solverforge-cvrp/src/metric.rs b/crates/solverforge-cvrp/src/metric.rs index 5eb030bf..c70569a3 100644 --- a/crates/solverforge-cvrp/src/metric.rs +++ b/crates/solverforge-cvrp/src/metric.rs @@ -1,5 +1,7 @@ use std::fmt; +use crate::problem_data::{finite_leg, MAX_SAFE_LEG_COST}; + /// Source of leg distances and travel times between locations. /// /// The stock CVRP helpers, meters and route checks read legs only through @@ -18,6 +20,51 @@ pub trait RouteMetric: Clone + fmt::Debug + Send + Sync + 'static { /// Whether every leg among `route`'s visits and `depot` is defined, given /// that `max_node` is the largest of them. fn covers(&self, route: &[usize], depot: usize, max_node: usize) -> bool; + + /// Appends, for each of `locations` in order, the indexes into + /// `locations` of its `min(k, locations.len() - 1)` nearest other + /// locations by leg distance, nearest first, ties by lower index. A leg + /// that is undefined or cannot be traversed ranks as the large finite cost + /// the stock savings distance gives it. + /// + /// The provided method ranks every other location for each one, in time + /// quadratic and memory linear in `locations.len()`. + fn nearest(&self, locations: &[usize], k: usize, out: &mut Vec) { + nearest_by_rank(self, locations, k, out); + } +} + +/// `RouteMetric::nearest` by ranking every other location for each one. +pub(crate) fn nearest_by_rank( + metric: &M, + locations: &[usize], + k: usize, + out: &mut Vec, +) { + let stride = k.min(locations.len().saturating_sub(1)); + if stride == 0 { + return; + } + let mut ranked = Vec::with_capacity(locations.len()); + for (index, &from) in locations.iter().enumerate() { + ranked.clear(); + ranked.extend( + locations + .iter() + .enumerate() + .filter(|&(other, _)| other != index) + .map(|(other, &to)| (leg_rank(metric.distance(from, to)), other)), + ); + ranked.select_nth_unstable(stride - 1); + ranked[..stride].sort_unstable(); + out.extend(ranked[..stride].iter().map(|&(_, other)| other)); + } +} + +/// The savings-distance rank of a metric leg. +#[inline] +pub(crate) fn leg_rank(distance: Option) -> i64 { + distance.and_then(finite_leg).unwrap_or(MAX_SAFE_LEG_COST) } /// Dense distance and travel-time tables, indexed `[from][to]`. @@ -132,4 +179,11 @@ impl RouteMetric for EuclideanMetric { fn covers(&self, _route: &[usize], _depot: usize, max_node: usize) -> bool { max_node < self.coordinates.len() } + + /// Answers from a uniform grid over the locations, visiting cells in rings + /// around each location until no closer location can remain, in time + /// about linear in `locations.len() * k` for spread-out coordinates. + fn nearest(&self, locations: &[usize], k: usize, out: &mut Vec) { + crate::euclidean_grid::nearest(self, locations, k, out); + } } diff --git a/crates/solverforge-cvrp/src/metric_tests.rs b/crates/solverforge-cvrp/src/metric_tests.rs index 8e22177b..222bf4e4 100644 --- a/crates/solverforge-cvrp/src/metric_tests.rs +++ b/crates/solverforge-cvrp/src/metric_tests.rs @@ -169,3 +169,116 @@ fn euclidean_metric_answers_every_stock_helper_like_its_tabulated_matrix() { ); } } + +struct Lcg(u64); + +impl Lcg { + fn next(&mut self, bound: u64) -> u64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) % bound + } +} + +/// Coordinates spread, clustered, duplicated, on a line, and on a fine +/// lattice where many legs round to the same distance. +fn shapes(seed: u64, count: usize) -> Vec> { + let mut rng = Lcg(seed); + let spread = (0..count) + .map(|_| (rng.next(10_000) as f64 / 7.0, rng.next(10_000) as f64 / 3.0)) + .collect(); + let clustered = (0..count) + .map(|i| { + let centre = (i % 3) as f64 * 5_000.0; + (centre + rng.next(20) as f64, centre + rng.next(20) as f64) + }) + .collect(); + let duplicated = (0..count) + .map(|_| (rng.next(4) as f64, rng.next(4) as f64)) + .collect(); + let line = (0..count) + .map(|_| (rng.next(1_000) as f64 * 0.5, 7.0)) + .collect(); + vec![spread, clustered, duplicated, line] +} + +#[test] +fn euclidean_grid_neighbours_match_the_ranked_scan_exactly() { + for seed in 0..12 { + for count in [1, 2, 3, 17, 160, 300] { + for coordinates in shapes(seed, count) { + let metric = EuclideanMetric::new(coordinates, 1.0); + let mut locations: Vec = (0..count).collect(); + // Permute so location order differs from index order. + locations.rotate_left(seed as usize % count); + for k in [1, 2, 5, 40, count + 2] { + let mut grid = Vec::new(); + metric.nearest(&locations, k, &mut grid); + let mut scan = Vec::new(); + crate::metric::nearest_by_rank(&metric, &locations, k, &mut scan); + assert_eq!(grid, scan, "seed {seed}, {count} locations, k = {k}"); + assert_eq!(grid.len(), count * k.min(count.saturating_sub(1))); + } + } + } + } +} + +#[test] +fn euclidean_grid_neighbours_match_where_many_legs_round_alike() { + for seed in 0..40 { + let mut rng = Lcg(seed); + let count = 50 + (seed as usize * 7) % 300; + let coordinates = (0..count) + .map(|_| { + ( + rng.next(1_000) as f64 * 0.0137, + rng.next(1_000) as f64 * 0.0113, + ) + }) + .collect(); + let metric = EuclideanMetric::new(coordinates, 1.0); + let locations: Vec = (0..count).collect(); + for k in [3, 10, 40] { + let (mut grid, mut scan) = (Vec::new(), Vec::new()); + metric.nearest(&locations, k, &mut grid); + crate::metric::nearest_by_rank(&metric, &locations, k, &mut scan); + assert_eq!(grid, scan, "seed {seed}, {count} locations, k = {k}"); + } + } +} + +#[test] +fn ranked_neighbours_order_by_savings_distance_then_index() { + let metric = DenseMatrix::new( + vec![ + vec![0, 4, 4, UNREACHABLE], + vec![4, 0, -1, 2], + vec![4, 1, 0, 9], + vec![1, 2, 3, 0], + ], + vec![vec![0; 4]; 4], + ); + let mut out = Vec::new(); + metric.nearest(&[0, 1, 2, 3], 3, &mut out); + assert_eq!(out, vec![1, 2, 3, 3, 0, 2, 1, 0, 3, 0, 1, 2]); + out.clear(); + metric.nearest(&[3, 0], 5, &mut out); + assert_eq!(out, vec![1, 0]); +} + +#[test] +fn savings_neighbors_reads_the_vehicles_metric() { + let fleet = Fleet { + data: problem_data(EuclideanMetric::new(coordinates(), 1.0)), + routes: vec![Vec::new(), Vec::new()], + }; + let mut out = Vec::new(); + savings_neighbors(&fleet, 1, &[1, 2, 3], 1, &mut out); + assert_eq!(out, vec![1, 0, 0]); + out.clear(); + savings_neighbors(&fleet, 2, &[1, 2, 3], 1, &mut out); + assert!(out.is_empty()); +} diff --git a/crates/solverforge-cvrp/src/problem_data.rs b/crates/solverforge-cvrp/src/problem_data.rs index ac4df69e..66d2bc43 100644 --- a/crates/solverforge-cvrp/src/problem_data.rs +++ b/crates/solverforge-cvrp/src/problem_data.rs @@ -43,16 +43,17 @@ impl ProblemData { #[inline] pub(crate) fn finite_distance(&self, from: usize, to: usize) -> Option { - finite(self.metric.distance(from, to)?) + finite_leg(self.metric.distance(from, to)?) } #[inline] pub(crate) fn travel_time(&self, from: usize, to: usize) -> Option { - finite(self.metric.travel_time(from, to)?) + finite_leg(self.metric.travel_time(from, to)?) } } +/// A leg value, or `None` when it marks a leg that cannot be traversed. #[inline] -fn finite(value: i64) -> Option { +pub(crate) fn finite_leg(value: i64) -> Option { (value >= 0 && value != UNREACHABLE).then_some(value) } diff --git a/crates/solverforge-macros/WIREFRAME.md b/crates/solverforge-macros/WIREFRAME.md index a3ec5831..5cf4f37b 100644 --- a/crates/solverforge-macros/WIREFRAME.md +++ b/crates/solverforge-macros/WIREFRAME.md @@ -241,12 +241,13 @@ arguments are compile errors. **`#[planning_list_variable]` parameters:** - `element_collection = "field"` — solution field with all list elements -- `domain = "cvrp"` — stock CVRP list-variable profile; supplies the CVRP solution trait, distance meters, strict route hooks with safe unreachable-leg rejection, relaxed Clarke-Wright savings hooks, and savings metric class +- `domain = "cvrp"` — stock CVRP list-variable profile; supplies the CVRP solution trait, distance meters, strict route hooks with safe unreachable-leg rejection, relaxed Clarke-Wright savings hooks, savings metric class, and savings neighbour hook - `distance_meter = "path"` — optional cross-entity distance meter type - `intra_distance_meter = "path"` — optional intra-entity distance meter type - `route_hooks = "path"` — optional route-local hook module with `get`, `set`, `depot`, `distance`, and `feasible`; k-opt uses these hooks and Clarke-Wright uses only `set` for assignment - `savings_hooks = "path"` — optional Clarke-Wright construction hook module with `depot`, `distance`, and `feasible` - `savings_metric_class_fn = "path"` — optional Clarke-Wright metric-class hook, `fn(&Solution, entity_idx) -> usize`; owners in the same class must share construction depot and distance behavior +- `savings_neighbors_fn = "path"` — optional nearest-neighbour hook for bounded Clarke-Wright savings (`savings_neighbors`), `fn(&Solution, entity_idx, values: &[usize], k, out: &mut Vec)`; appends for each value the indexes into `values` of its `min(k, len - 1)` nearest others by savings distance, nearest first, ties by lower index; `domain = "cvrp"` supplies `::solverforge::cvrp::savings_neighbors` - `solution_trait = "path"` — optional solution trait bound required by custom list helper hooks; `domain = "cvrp"` supplies `::solverforge::cvrp::VrpSolution` - `element_owner_fn = "path"` — optional partial fixed-owner hook, `fn(&Solution, element) -> Option`; `None` leaves that element unrestricted - `construction_element_order_key = "path"` — optional list-construction ordering hook, `fn(&Solution, element) -> i64`; it flows through existing generated list metadata and runtime list slots @@ -255,8 +256,8 @@ arguments are compile errors. When `domain = "cvrp"` is present, the profiled defaults above must be used as a coherent stock bundle. Overriding `distance_meter`, `intra_distance_meter`, -`solution_trait`, `route_hooks`, `savings_hooks`, or `savings_metric_class_fn` -is rejected unless the override repeats the exact stock path. Custom routing +`solution_trait`, `route_hooks`, `savings_hooks`, `savings_metric_class_fn`, or +`savings_neighbors_fn` is rejected unless the override repeats the exact stock path. Custom routing semantics should omit `domain = "cvrp"` and declare explicit hook paths instead. The profile also declares savings feasibility shared by metric class, so Clarke-Wright asks one owner per class; explicit hook paths keep asking every diff --git a/crates/solverforge-macros/src/attr_validation.rs b/crates/solverforge-macros/src/attr_validation.rs index 9f29c0e0..cf728539 100644 --- a/crates/solverforge-macros/src/attr_validation.rs +++ b/crates/solverforge-macros/src/attr_validation.rs @@ -91,6 +91,7 @@ const PLANNING_LIST_VARIABLE_ARGS: &[AttributeArgSpec] = &[ AttributeArgSpec::string("route_hooks"), AttributeArgSpec::string("savings_hooks"), AttributeArgSpec::string("savings_metric_class_fn"), + AttributeArgSpec::string("savings_neighbors_fn"), AttributeArgSpec::string("element_owner_fn"), AttributeArgSpec::string("construction_element_order_key"), AttributeArgSpec::string("precedence_duration_fn"), diff --git a/crates/solverforge-macros/src/planning_entity/list_variable.rs b/crates/solverforge-macros/src/planning_entity/list_variable.rs index 1fdc8f67..3087e6bf 100644 --- a/crates/solverforge-macros/src/planning_entity/list_variable.rs +++ b/crates/solverforge-macros/src/planning_entity/list_variable.rs @@ -35,6 +35,7 @@ pub(super) fn generate_list_metadata( let savings_hooks_attr = parse_profiled_attribute(attr, "savings_hooks", field)?; let savings_metric_class_attr = parse_profiled_attribute(attr, "savings_metric_class_fn", field)?; + let savings_neighbors_attr = parse_profiled_attribute(attr, "savings_neighbors_fn", field)?; let cross_dm_ty = parse_type_or_default( distance_meter.clone(), @@ -87,6 +88,8 @@ pub(super) fn generate_list_metadata( let savings_hooks = parse_optional_path(savings_hooks_attr, "savings_hooks", field)?; let savings_metric_class_path = parse_optional_path(savings_metric_class_attr, "savings_metric_class_fn", field)?; + let savings_neighbors_path = + parse_optional_path(savings_neighbors_attr, "savings_neighbors_fn", field)?; let route_get = hook_fn_expr(route_hooks.as_ref(), "get"); let route_set = hook_fn_expr(route_hooks.as_ref(), "set"); let route_depot = hook_fn_expr(route_hooks.as_ref(), "depot"); @@ -94,6 +97,7 @@ pub(super) fn generate_list_metadata( let route_feasible = hook_fn_expr(route_hooks.as_ref(), "feasible"); let savings_depot = hook_fn_expr(savings_hooks.as_ref(), "depot"); let savings_metric_class = optional_hook_fn_expr(savings_metric_class_path.as_ref()); + let savings_neighbors = optional_hook_fn_expr(savings_neighbors_path.as_ref()); let savings_distance = hook_fn_expr(savings_hooks.as_ref(), "distance"); let savings_feasible = hook_fn_expr(savings_hooks.as_ref(), "feasible"); let (element_owner_adapter, element_owner) = if element_owner_path.is_some() { @@ -166,6 +170,7 @@ pub(super) fn generate_list_metadata( ) .with_element_owner_fn(#element_owner) .with_savings_feasible_shared_by_metric_class(#savings_feasible_shared_by_metric_class) + .with_savings_neighbors_fn(#savings_neighbors) } }) @@ -435,6 +440,7 @@ impl ListVariableDomain { "route_hooks" => Some("::solverforge::cvrp::route_hooks"), "savings_hooks" => Some("::solverforge::cvrp::savings_hooks"), "savings_metric_class_fn" => Some("::solverforge::cvrp::savings_metric_class"), + "savings_neighbors_fn" => Some("::solverforge::cvrp::savings_neighbors"), _ => None, }, } diff --git a/crates/solverforge-macros/src/planning_entity_tests.rs b/crates/solverforge-macros/src/planning_entity_tests.rs index 2c2ae953..d46376dd 100644 --- a/crates/solverforge-macros/src/planning_entity_tests.rs +++ b/crates/solverforge-macros/src/planning_entity_tests.rs @@ -148,21 +148,47 @@ fn list_metadata_declares_shared_savings_feasibility_only_for_the_cvrp_profile() } #[test] -fn entity_descriptor_includes_index_shadow_metadata() { - let input = parse_quote! { - struct Visit { +fn list_metadata_takes_the_savings_neighbour_hook_from_the_profile_or_the_attribute() { + let expand = |input| { + expand_derive(input) + .expect("entity expansion should succeed") + .to_string() + .replace(' ', "") + }; + let cvrp = expand(parse_quote! { + struct Route { #[planning_id] - id: usize, - #[index_shadow_variable(source_variable_name = "visits")] - index: Option, + id: String, + #[planning_list_variable(element_collection = "visits", domain = "cvrp")] + visits: Vec, } - }; - - let expanded = expand_derive(input) - .expect("index shadow expansion should succeed") - .to_string(); + }); + let custom = expand(parse_quote! { + struct Route { + #[planning_id] + id: String, + #[planning_list_variable( + element_collection = "visits", + savings_hooks = "crate::hooks", + savings_neighbors_fn = "crate::hooks::neighbors" + )] + visits: Vec, + } + }); + let absent = expand(parse_quote! { + struct Route { + #[planning_id] + id: String, + #[planning_list_variable(element_collection = "visits", savings_hooks = "crate::hooks")] + visits: Vec, + } + }); - assert!(expanded.contains("VariableDescriptor :: shadow")); - assert!(expanded.contains("ShadowVariableKind :: Index")); - assert!(expanded.contains("with_source (\"Visit\" , \"visits\")")); + assert!(cvrp.contains( + ".with_savings_neighbors_fn(::core::option::Option::Some(::solverforge::cvrp::savings_neighbors))" + )); + assert!(custom.contains( + ".with_savings_neighbors_fn(::core::option::Option::Some(crate::hooks::neighbors))" + )); + assert!(absent.contains(".with_savings_neighbors_fn(::core::option::Option::None)")); } diff --git a/crates/solverforge-macros/src/planning_solution/runtime/helpers/phase_support.rs b/crates/solverforge-macros/src/planning_solution/runtime/helpers/phase_support.rs index 1a93bc00..cd929e85 100644 --- a/crates/solverforge-macros/src/planning_solution/runtime/helpers/phase_support.rs +++ b/crates/solverforge-macros/src/planning_solution/runtime/helpers/phase_support.rs @@ -180,6 +180,7 @@ pub(super) fn generate_runtime_phase_support( .with_savings_feasible_shared_by_metric_class( metadata.savings_feasible_shared_by_metric_class, ) + .with_savings_neighbors_fn(metadata.savings_neighbors_fn) ) ) ); diff --git a/crates/solverforge-macros/tests/ui/fail/planning_list_variable_unknown_argument.stderr b/crates/solverforge-macros/tests/ui/fail/planning_list_variable_unknown_argument.stderr index 032ce4e9..d5d1f129 100644 --- a/crates/solverforge-macros/tests/ui/fail/planning_list_variable_unknown_argument.stderr +++ b/crates/solverforge-macros/tests/ui/fail/planning_list_variable_unknown_argument.stderr @@ -1,4 +1,4 @@ -error: unsupported planning_list_variable argument `unexpected`; supported arguments are element_collection, domain, distance_meter, intra_distance_meter, route_hooks, savings_hooks, savings_metric_class_fn, element_owner_fn, construction_element_order_key, precedence_duration_fn, precedence_successors_fn, solution_trait +error: unsupported planning_list_variable argument `unexpected`; supported arguments are element_collection, domain, distance_meter, intra_distance_meter, route_hooks, savings_hooks, savings_metric_class_fn, savings_neighbors_fn, element_owner_fn, construction_element_order_key, precedence_duration_fn, precedence_successors_fn, solution_trait --> tests/ui/fail/planning_list_variable_unknown_argument.rs:8:61 | 8 | #[planning_list_variable(element_collection = "visits", unexpected = "value")] diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index dda072fb..14683504 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -350,8 +350,9 @@ src/ │ │ ├── list_clarke_wright/owner_admission.rs — Incremental merge admission: metric-class counts, per-route ownership and owner sets updated for the merged route only │ │ ├── list_clarke_wright/owner_assignment.rs — Owner-specific route assignment, class-shared savings feasibility, buffered-merge publication on interruption, and preservation helpers │ │ ├── list_clarke_wright/route_state.rs — Route state and reusable route-buffer helpers -│ │ ├── list_clarke_wright/savings.rs — Metric-class savings computation +│ │ ├── list_clarke_wright/savings.rs — Metric-class savings computation, all pairs or bounded to nearest neighbours │ │ ├── list_clarke_wright/tests/admission_oracle.rs — Incremental admission against whole-set recomputation on seeded instances +│ │ ├── list_clarke_wright/tests/bounded_savings.rs — Bounded savings: full-bound equivalence, scored pairs, hook row-length check │ │ ├── list_clarke_wright/tests/metric_class.rs — Shared metric-class and owner-feasibility tests │ │ ├── list_clarke_wright/tests/owner_binding.rs — Owner-specific hook binding tests │ │ ├── list_k_opt.rs — ListKOptPhase @@ -1029,7 +1030,11 @@ Runtime helpers: feasibility and reuses the answer for the class; the `domain = "cvrp"` profile declares it because the stock hook reads only the owner's `ProblemData`, which is what the stock metric class groups by. - `ListVariableSlot` carries the same field and builder. + `savings_neighbors_fn`, `Option)>`, + starts absent and is attached with `with_savings_neighbors_fn(...)`; it is + the nearest-neighbour source bounded Clarke-Wright (`savings_neighbors`) + requires, and the compiler rejects a bounded `ListClarkeWright` on a slot + without it. `ListVariableSlot` carries the same fields and builders. - `ListVariableEntity` — list-variable accessors plus `HAS_LIST_VARIABLE`, `LIST_VARIABLE_NAME`, and `LIST_ELEMENT_SOURCE` - `runtime/compiler/` — compiles one value-owned `RuntimeModel` into an immutable graph, prepares solve-owned sources, and runs every configured or default phase through `CompiledRuntimePhaseRunner` - `PlanningModelSupport` — `#[doc(hidden)]` support trait (and `#[doc(hidden)]` diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index 023ffa49..e4e96a98 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -76,13 +76,15 @@ struct ExhaustiveSearchPhase: pub struct ExhaustiveSearchPhase { /* private struct FunctionalPartitioner: pub struct FunctionalPartitioner where S: PlanningSolution, PF: Fn(&S) -> Vec + Send + Sync, MF: Fn(&S, Vec) -> S + Send + Sync,{ /* private fields */ } FunctionalPartitioner: pub fn new(partition_fn: PF, merge_fn: MF) -> Self FunctionalPartitioner: pub fn with_recommended_count(self, count: NonZeroUsize) -> Self -struct ListVariableMetadata: pub struct ListVariableMetadata {Show 13 fields pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub route_get_fn: Option Vec>, pub route_set_fn: Option)>, pub route_depot_fn: Option usize>, pub route_distance_fn: Option i64>, pub route_feasible_fn: Option bool>, pub savings_depot_fn: Option usize>, pub savings_metric_class_fn: Option usize>, pub savings_distance_fn: Option i64>, pub savings_feasible_fn: Option bool>, pub savings_feasible_shared_by_metric_class: bool, pub element_owner_fn: Option Option>, /* private fields */ } +struct ListVariableMetadata: pub struct ListVariableMetadata {Show 14 fields pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub route_get_fn: Option Vec>, pub route_set_fn: Option)>, pub route_depot_fn: Option usize>, pub route_distance_fn: Option i64>, pub route_feasible_fn: Option bool>, pub savings_depot_fn: Option usize>, pub savings_metric_class_fn: Option usize>, pub savings_distance_fn: Option i64>, pub savings_feasible_fn: Option bool>, pub savings_feasible_shared_by_metric_class: bool, pub savings_neighbors_fn: Option)>, pub element_owner_fn: Option Option>, /* private fields */ } ListVariableMetadata: pub fn new( cross_distance_meter: DM, intra_distance_meter: IDM, route_get_fn: Option Vec>, route_set_fn: Option)>, route_depot_fn: Option usize>, route_distance_fn: Option i64>, route_feasible_fn: Option bool>, savings_depot_fn: Option usize>, savings_metric_class_fn: Option usize>, savings_distance_fn: Option i64>, savings_feasible_fn: Option bool>, ) -> Self ListVariableMetadata: pub fn with_savings_feasible_shared_by_metric_class(self, shared: bool) -> Self + ListVariableMetadata: pub fn with_savings_neighbors_fn( self, savings_neighbors_fn: Option)>, ) -> Self ListVariableMetadata: pub fn with_element_owner_fn( self, element_owner_fn: Option Option>, ) -> Self -struct ListVariableSlot: pub struct ListVariableSlot {Show 34 fields pub entity_type_name: &'static str, pub element_count: fn(&S) -> usize, pub assigned_elements: fn(&S) -> Vec, pub list_len: fn(&S, usize) -> usize, pub list_remove: fn(&mut S, usize, usize) -> Option, pub list_insert: fn(&mut S, usize, usize, V), pub list_get: fn(&S, usize, usize) -> Option, pub list_set: fn(&mut S, usize, usize, V), pub list_reverse: fn(&mut S, usize, usize, usize), pub sublist_remove: fn(&mut S, usize, usize, usize) -> Vec, pub sublist_insert: fn(&mut S, usize, usize, Vec), pub ruin_remove: fn(&mut S, usize, usize) -> V, pub ruin_insert: fn(&mut S, usize, usize, V), pub index_to_element: fn(&S, usize) -> V, pub element_source_key: fn(&S, &V) -> usize, pub entity_count: fn(&S) -> usize, pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub variable_name: &'static str, pub descriptor_index: usize, pub route_get_fn: Option Vec>, pub route_set_fn: Option)>, pub route_depot_fn: Option usize>, pub route_distance_fn: Option i64>, pub route_feasible_fn: Option bool>, pub savings_depot_fn: Option usize>, pub savings_metric_class_fn: Option usize>, pub savings_distance_fn: Option i64>, pub savings_feasible_fn: Option bool>, pub savings_feasible_shared_by_metric_class: bool, pub element_owner_fn: Option Option>, pub construction_element_order_key: Option i64>, pub precedence_duration_fn: Option usize>, pub precedence_successors_fn: Option)>, /* private fields */ } +struct ListVariableSlot: pub struct ListVariableSlot {Show 35 fields pub entity_type_name: &'static str, pub element_count: fn(&S) -> usize, pub assigned_elements: fn(&S) -> Vec, pub list_len: fn(&S, usize) -> usize, pub list_remove: fn(&mut S, usize, usize) -> Option, pub list_insert: fn(&mut S, usize, usize, V), pub list_get: fn(&S, usize, usize) -> Option, pub list_set: fn(&mut S, usize, usize, V), pub list_reverse: fn(&mut S, usize, usize, usize), pub sublist_remove: fn(&mut S, usize, usize, usize) -> Vec, pub sublist_insert: fn(&mut S, usize, usize, Vec), pub ruin_remove: fn(&mut S, usize, usize) -> V, pub ruin_insert: fn(&mut S, usize, usize, V), pub index_to_element: fn(&S, usize) -> V, pub element_source_key: fn(&S, &V) -> usize, pub entity_count: fn(&S) -> usize, pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub variable_name: &'static str, pub descriptor_index: usize, pub route_get_fn: Option Vec>, pub route_set_fn: Option)>, pub route_depot_fn: Option usize>, pub route_distance_fn: Option i64>, pub route_feasible_fn: Option bool>, pub savings_depot_fn: Option usize>, pub savings_metric_class_fn: Option usize>, pub savings_distance_fn: Option i64>, pub savings_feasible_fn: Option bool>, pub savings_feasible_shared_by_metric_class: bool, pub savings_neighbors_fn: Option)>, pub element_owner_fn: Option Option>, pub construction_element_order_key: Option i64>, pub precedence_duration_fn: Option usize>, pub precedence_successors_fn: Option)>, /* private fields */ } ListVariableSlot: pub fn new( entity_type_name: &'static str, element_count: fn(&S) -> usize, assigned_elements: fn(&S) -> Vec, list_len: fn(&S, usize) -> usize, list_remove: fn(&mut S, usize, usize) -> Option, list_insert: fn(&mut S, usize, usize, V), list_get: fn(&S, usize, usize) -> Option, list_set: fn(&mut S, usize, usize, V), list_reverse: fn(&mut S, usize, usize, usize), sublist_remove: fn(&mut S, usize, usize, usize) -> Vec, sublist_insert: fn(&mut S, usize, usize, Vec), ruin_remove: fn(&mut S, usize, usize) -> V, ruin_insert: fn(&mut S, usize, usize, V), index_to_element: fn(&S, usize) -> V, element_source_key: fn(&S, &V) -> usize, entity_count: fn(&S) -> usize, cross_distance_meter: DM, intra_distance_meter: IDM, variable_name: &'static str, descriptor_index: usize, route_get_fn: Option Vec>, route_set_fn: Option)>, route_depot_fn: Option usize>, route_distance_fn: Option i64>, route_feasible_fn: Option bool>, savings_depot_fn: Option usize>, savings_metric_class_fn: Option usize>, savings_distance_fn: Option i64>, savings_feasible_fn: Option bool>, ) -> Self ListVariableSlot: pub fn with_savings_feasible_shared_by_metric_class(self, shared: bool) -> Self + ListVariableSlot: pub fn with_savings_neighbors_fn( self, savings_neighbors_fn: Option)>, ) -> Self ListVariableSlot: pub fn with_element_owner_fn( self, element_owner_fn: Option Option>, ) -> Self ListVariableSlot: pub fn with_construction_element_order_key( self, construction_element_order_key: Option i64>, ) -> Self ListVariableSlot: pub fn with_precedence_hooks( self, duration_fn: Option usize>, successors_fn: Option)>, ) -> Self diff --git a/crates/solverforge-solver/src/builder/context/list.rs b/crates/solverforge-solver/src/builder/context/list.rs index 8f36dd01..96d52aa0 100644 --- a/crates/solverforge-solver/src/builder/context/list.rs +++ b/crates/solverforge-solver/src/builder/context/list.rs @@ -86,6 +86,11 @@ pub struct ListVariableSlot { /// Whether `savings_feasible_fn` answers the same for every entity of one /// savings metric class; Clarke-Wright then asks one entity per class. pub savings_feasible_shared_by_metric_class: bool, + /// Nearest neighbours for bounded Clarke-Wright savings: given an entity, + /// element values and `k`, appends for each value, in order, the indexes + /// (into the values) of its `min(k, len - 1)` nearest other values by + /// savings distance, nearest first, ties by lower index. + pub savings_neighbors_fn: Option)>, /// The entity whose list must hold an element, when the model restricts /// ownership; `None` from the hook means any entity. pub element_owner_fn: Option Option>, @@ -131,6 +136,7 @@ impl Clone for ListVariableSlot { savings_distance_fn: self.savings_distance_fn, savings_feasible_fn: self.savings_feasible_fn, savings_feasible_shared_by_metric_class: self.savings_feasible_shared_by_metric_class, + savings_neighbors_fn: self.savings_neighbors_fn, element_owner_fn: self.element_owner_fn, construction_element_order_key: self.construction_element_order_key, precedence_duration_fn: self.precedence_duration_fn, @@ -207,6 +213,7 @@ impl ListVariableSlot { savings_distance_fn, savings_feasible_fn, savings_feasible_shared_by_metric_class: false, + savings_neighbors_fn: None, element_owner_fn: None, construction_element_order_key: None, precedence_duration_fn: None, @@ -222,6 +229,15 @@ impl ListVariableSlot { self } + /// Sets the nearest-neighbour hook bounded Clarke-Wright savings use. + pub fn with_savings_neighbors_fn( + mut self, + savings_neighbors_fn: Option)>, + ) -> Self { + self.savings_neighbors_fn = savings_neighbors_fn; + self + } + /// Sets the element ownership hook. pub fn with_element_owner_fn( mut self, diff --git a/crates/solverforge-solver/src/builder/context/list_access/dynamic.rs b/crates/solverforge-solver/src/builder/context/list_access/dynamic.rs index 7158be0a..3cfac330 100644 --- a/crates/solverforge-solver/src/builder/context/list_access/dynamic.rs +++ b/crates/solverforge-solver/src/builder/context/list_access/dynamic.rs @@ -30,7 +30,8 @@ pub(super) fn dynamic_access_has( | ListAccessCapability::CrossPositionDistance | ListAccessCapability::IntraPositionDistance | ListAccessCapability::Route - | ListAccessCapability::Savings => false, + | ListAccessCapability::Savings + | ListAccessCapability::SavingsNeighbors => false, } } @@ -51,7 +52,9 @@ pub(super) fn dynamic_metadata_has( ListAccessCapability::IntraPositionDistance => capabilities.intra_position_distance, ListAccessCapability::Route => capabilities.route, ListAccessCapability::Savings => capabilities.savings, - ListAccessCapability::Set + // Host-language metadata declares no savings neighbour source. + ListAccessCapability::SavingsNeighbors + | ListAccessCapability::Set | ListAccessCapability::Replace | ListAccessCapability::Reverse | ListAccessCapability::Sublist => false, diff --git a/crates/solverforge-solver/src/builder/context/list_access/types.rs b/crates/solverforge-solver/src/builder/context/list_access/types.rs index f3e66644..372a8a30 100644 --- a/crates/solverforge-solver/src/builder/context/list_access/types.rs +++ b/crates/solverforge-solver/src/builder/context/list_access/types.rs @@ -14,6 +14,7 @@ pub(crate) enum ListAccessCapability { IntraPositionDistance, Route, Savings, + SavingsNeighbors, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/solverforge-solver/src/builder/context/runtime_list_binding.rs b/crates/solverforge-solver/src/builder/context/runtime_list_binding.rs index cb53e8b8..ca17e494 100644 --- a/crates/solverforge-solver/src/builder/context/runtime_list_binding.rs +++ b/crates/solverforge-solver/src/builder/context/runtime_list_binding.rs @@ -56,6 +56,17 @@ impl RuntimeListSlot { } } + /// The nearest-neighbour hook bounded Clarke-Wright savings use. + /// Host-language metadata never declares one. + pub(crate) fn savings_neighbors_fn( + &self, + ) -> Option)> { + match self { + Self::Static { slot, .. } => slot.savings_neighbors_fn, + Self::Dynamic(_) => None, + } + } + pub(crate) fn route_read_policy(&self) -> RouteReadPolicy { match self { Self::Static { route_bindings, .. } => route_bindings.read_policy, @@ -154,6 +165,7 @@ impl RuntimeListSlot { } ListAccessCapability::Route => route_bindings.supports_route(), ListAccessCapability::Savings => route_bindings.supports_savings(), + ListAccessCapability::SavingsNeighbors => self.savings_neighbors_fn().is_some(), }, Self::Dynamic(slot) => { let access = slot.access_capabilities(); @@ -181,6 +193,7 @@ impl RuntimeListSlot { && metadata.savings && slot.savings_metric_class_policy().is_dynamic_explicit() } + ListAccessCapability::SavingsNeighbors => false, } } } diff --git a/crates/solverforge-solver/src/builder/context/runtime_list_route.rs b/crates/solverforge-solver/src/builder/context/runtime_list_route.rs index 2dd4ec88..6bf2ec9d 100644 --- a/crates/solverforge-solver/src/builder/context/runtime_list_route.rs +++ b/crates/solverforge-solver/src/builder/context/runtime_list_route.rs @@ -202,9 +202,13 @@ where fn savings_metric_class(&self, solution: &S, entity: usize) -> Result { match self { - Self::Static { route_bindings, .. } => { + // The policy frozen in the route bindings mirrors this hook: + // absent, the owner index is its own metric class. + Self::Static { slot, .. } => { self.validate_savings()?; - Ok((route_bindings.savings_metric_class)(solution, entity)) + Ok(slot + .savings_metric_class_fn + .map_or(entity, |metric_class| metric_class(solution, entity))) } Self::Dynamic(slot) => { as SavingsAccess>::savings_metric_class( diff --git a/crates/solverforge-solver/src/builder/context/runtime_list_route_policy.rs b/crates/solverforge-solver/src/builder/context/runtime_list_route_policy.rs index 3b791dbd..36d147e0 100644 --- a/crates/solverforge-solver/src/builder/context/runtime_list_route_policy.rs +++ b/crates/solverforge-solver/src/builder/context/runtime_list_route_policy.rs @@ -35,10 +35,6 @@ fn unavailable_savings_depot(_: &S, _: usize) -> usize { panic!("compiled savings depot was invoked without an available savings bundle") } -fn declared_entity_identity(_: &S, entity: usize) -> usize { - entity -} - fn unavailable_savings_distance(_: &S, _: usize, _: usize, _: usize) -> i64 { panic!("compiled savings distance was invoked without an available savings bundle") } @@ -65,7 +61,6 @@ pub(crate) struct StaticRouteBindings { pub(super) route_distance: fn(&S, usize, usize, usize) -> i64, pub(super) route_feasible: fn(&S, usize, &[usize]) -> bool, pub(super) savings_depot: fn(&S, usize) -> usize, - pub(super) savings_metric_class: fn(&S, usize) -> usize, pub(super) savings_distance: fn(&S, usize, usize, usize) -> i64, pub(super) savings_feasible: fn(&S, usize, &[usize]) -> bool, pub(super) savings_feasible_shared_by_metric_class: bool, @@ -121,18 +116,9 @@ impl StaticRouteBindings { declared_always_feasible::, ), }; - let (metric_class_policy, savings_metric_class): ( - SavingsMetricClassPolicy, - fn(&S, usize) -> usize, - ) = match slot.savings_metric_class_fn { - Some(metric_class) => ( - SavingsMetricClassPolicy::ExplicitStaticProvider, - metric_class, - ), - None => ( - SavingsMetricClassPolicy::DeclaredEntityIdentity, - declared_entity_identity::, - ), + let metric_class_policy = match slot.savings_metric_class_fn { + Some(_) => SavingsMetricClassPolicy::ExplicitStaticProvider, + None => SavingsMetricClassPolicy::DeclaredEntityIdentity, }; Self { read_policy, @@ -149,7 +135,6 @@ impl StaticRouteBindings { savings_depot: slot .savings_depot_fn .unwrap_or(unavailable_savings_depot::), - savings_metric_class, savings_distance: slot .savings_distance_fn .unwrap_or(unavailable_savings_distance::), diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs index 1c52a90d..8e511d9a 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright.rs @@ -48,6 +48,19 @@ pub(crate) trait ClarkeWrightAccess: ListSourceAccess { /// Whether `savings_feasible` answers the same for every owner of one /// savings metric class, so one owner per class may answer for it. fn savings_feasible_shared_by_metric_class(&self) -> bool; + /// Appends, for each of `values` in order, the indexes into `values` of + /// its `min(k, values.len() - 1)` nearest other values for + /// `entity_index`'s savings, nearest first, ties by lower index. Called + /// only when bounded savings are configured, which the compiler admits + /// only for slots that declare the hook. + fn savings_neighbors( + &self, + solution: &S, + entity_index: usize, + values: &[usize], + k: usize, + out: &mut Vec, + ); fn replace_route(&self, solution: &mut S, entity_index: usize, route: Vec); } @@ -106,6 +119,20 @@ where RuntimeListSlot::savings_feasible_shared_by_metric_class(self) } + fn savings_neighbors( + &self, + solution: &S, + entity_index: usize, + values: &[usize], + k: usize, + out: &mut Vec, + ) { + let neighbors = self + .savings_neighbors_fn() + .expect("compiled bounded Clarke-Wright requires a savings neighbour hook"); + neighbors(solution, entity_index, values, k, out); + } + fn replace_route(&self, solution: &mut S, entity_index: usize, route: Vec) { RouteSequenceAccess::replace_route(self, solution, entity_index, route) .expect("compiled Clarke-Wright route replacement must be callable"); diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/facade.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/facade.rs index b3c005a0..31daf271 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/facade.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/facade.rs @@ -34,6 +34,8 @@ where feasible_fn: fn(&S, usize, &[usize]) -> bool, element_owner_fn: Option Option>, savings_feasible_shared_by_metric_class: bool, + savings_neighbors_fn: Option)>, + savings_neighbors: Option, descriptor_index: usize, } @@ -80,6 +82,8 @@ where feasible_fn, element_owner_fn: None, savings_feasible_shared_by_metric_class: false, + savings_neighbors_fn: None, + savings_neighbors: None, descriptor_index, } } @@ -94,6 +98,18 @@ where self } + /// Bounds savings to each element's `k` nearest neighbours as answered by + /// `neighbors_fn`. + pub(crate) fn with_savings_neighbors( + mut self, + neighbors_fn: fn(&S, usize, &[usize], usize, &mut Vec), + k: usize, + ) -> Self { + self.savings_neighbors_fn = Some(neighbors_fn); + self.savings_neighbors = Some(k); + self + } + pub(crate) fn with_element_owner_fn( mut self, element_owner_fn: Option Option>, @@ -174,6 +190,20 @@ where self.savings_feasible_shared_by_metric_class } + fn savings_neighbors( + &self, + solution: &S, + entity_index: usize, + values: &[usize], + k: usize, + out: &mut Vec, + ) { + let neighbors = self + .savings_neighbors_fn + .expect("bounded savings are configured only with a neighbour hook"); + neighbors(solution, entity_index, values, k, out); + } + fn replace_route(&self, solution: &mut S, entity_index: usize, route: Vec) { (self.assign_route)(solution, entity_index, route); } @@ -204,6 +234,7 @@ where self, &source_index, &unassigned, + self.savings_neighbors, StepControlPolicy::ObserveConfigLimits, solver_scope, ); diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs index f22c9b25..5438fbe0 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/kernel.rs @@ -30,6 +30,7 @@ pub(crate) fn run_clarke_wright( access: &A, source_index: &RuntimeListSourceIndex, bound_unassigned: &[SourceElement], + savings_neighbors: Option, control_policy: StepControlPolicy, solver_scope: &mut SolverScope<'_, S, D, BestCb>, ) where @@ -47,6 +48,7 @@ pub(crate) fn run_clarke_wright( access, source_index, bound_unassigned, + savings_neighbors, control_policy, phase_scope, ); @@ -58,6 +60,7 @@ fn run_clarke_wright_in_phase( access: &A, source_index: &RuntimeListSourceIndex, bound_unassigned: &[SourceElement], + savings_neighbors: Option, control_policy: StepControlPolicy, phase_scope: &mut PhaseScope<'_, '_, S, D, BestCb>, ) where @@ -164,6 +167,7 @@ fn run_clarke_wright_in_phase( &unassigned, &representative_owner_slots, &trace_metric_class_by_value, + savings_neighbors, control_policy, ); sort_savings(&mut savings); diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/savings.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/savings.rs index 61c4a50f..fdbe4708 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/savings.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/savings.rs @@ -30,15 +30,20 @@ pub(crate) fn sort_savings(entries: &mut [SavingsEntry]) { }); } -/// Scores every pair of unassigned elements once per representative owner, -/// recording each pair as a construction candidate. Returns the savings and -/// whether configured termination interrupted the generation. +/// Scores pairs of unassigned elements once per representative owner, +/// recording each pair as a construction candidate: every pair when +/// `savings_neighbors` is `None`, otherwise only pairs where one element is +/// among the other's `savings_neighbors` nearest. Each pair is scored once, +/// left before right in `unassigned` order, so a bound of at least +/// `unassigned.len() - 1` yields exactly the unbounded savings. Returns the +/// savings and whether configured termination interrupted the generation. pub(super) fn generate_savings( phase_scope: &mut PhaseScope<'_, '_, S, D, BestCb>, access: &A, unassigned: &[SourceElement], representative_owner_slots: &[OwnerSlot], trace_metric_class_by_value: &HashMap, + savings_neighbors: Option, control_policy: StepControlPolicy, ) -> (Vec, bool) where @@ -47,77 +52,196 @@ where D: Director, BestCb: ProgressCallback, { - let n = unassigned.len(); - let mut savings = Vec::with_capacity( - n.saturating_mul(n.saturating_sub(1)) - .saturating_div(2) - .saturating_mul(representative_owner_slots.len()), - ); - for owner_slot in representative_owner_slots { - let owner_idx = owner_slot.owner_idx; - for a in 0..n { - if (a & 0x1F) == 0 - && control_policy.should_terminate_construction(phase_scope.solver_scope_mut()) - { - return (savings, true); - } - for b in (a + 1)..n { - let left = &unassigned[a]; - let right = &unassigned[b]; - let trace_token = phase_scope.record_candidate_operation( - CandidateTraceSource::ListClarkeWrightSavings, - None, - savings.len(), - Some(CandidateTraceConstructionTarget { - descriptor_index: access.descriptor_index(), - entity_index: owner_idx, - }), - access.descriptor_index(), - "clarke_wright_savings_pair", - [ - owner_idx as u64, - trace_metric_class_by_value[&owner_slot.metric_class], - left.source_index as u64, - right.source_index as u64, - ], - ); - let solution = phase_scope.score_director().working_solution(); - let depot = access.savings_depot(solution, owner_idx); - let left_value = access.route_value(&left.element); - let right_value = access.route_value(&right.element); - let saving = super::sum_two_minus_one( - access.savings_distance(solution, owner_idx, depot, left_value), - access.savings_distance(solution, owner_idx, depot, right_value), - access.savings_distance(solution, owner_idx, left_value, right_value), - ); - savings.push(SavingsEntry { - saving, - metric_class: owner_slot.metric_class, - left_idx: left.source_index, - right_idx: right.source_index, - }); - if let Some(token) = trace_token { - phase_scope.record_candidate_trace_disposition( - token, - CandidateTraceDisposition::Evaluated, - ); - phase_scope.record_candidate_trace_disposition( - token, - CandidateTraceDisposition::ForagerIgnored, - ); + let mut generator = SavingsGenerator { + access, + unassigned, + trace_metric_class_by_value, + control_policy, + savings: Vec::new(), + }; + let interrupted = match savings_neighbors { + None => generator.all_pairs(phase_scope, representative_owner_slots), + Some(k) => generator.neighbor_pairs(phase_scope, representative_owner_slots, k), + }; + (generator.savings, interrupted) +} + +struct SavingsGenerator<'a, A, E> { + access: &'a A, + unassigned: &'a [SourceElement], + trace_metric_class_by_value: &'a HashMap, + control_policy: StepControlPolicy, + savings: Vec, +} + +impl SavingsGenerator<'_, A, E> { + fn all_pairs( + &mut self, + phase_scope: &mut PhaseScope<'_, '_, S, D, BestCb>, + representative_owner_slots: &[OwnerSlot], + ) -> bool + where + S: PlanningSolution, + A: ClarkeWrightAccess, + D: Director, + BestCb: ProgressCallback, + { + let n = self.unassigned.len(); + self.savings.reserve( + n.saturating_mul(n.saturating_sub(1)) + .saturating_div(2) + .saturating_mul(representative_owner_slots.len()), + ); + for owner_slot in representative_owner_slots { + for a in 0..n { + if (a & 0x1F) == 0 + && self + .control_policy + .should_terminate_construction(phase_scope.solver_scope_mut()) + { + return true; + } + for b in (a + 1)..n { + if self.score_pair(phase_scope, owner_slot, a, b) { + return true; + } } - record_construction_candidate( - phase_scope, - std::time::Duration::ZERO, - std::time::Duration::ZERO, - ); - if (savings.len() & 0x3FF) == 0 - && control_policy.should_terminate_construction(phase_scope.solver_scope_mut()) + } + } + false + } + + fn neighbor_pairs( + &mut self, + phase_scope: &mut PhaseScope<'_, '_, S, D, BestCb>, + representative_owner_slots: &[OwnerSlot], + k: usize, + ) -> bool + where + S: PlanningSolution, + A: ClarkeWrightAccess, + D: Director, + BestCb: ProgressCallback, + { + let n = self.unassigned.len(); + let stride = k.min(n.saturating_sub(1)); + let values: Vec = self + .unassigned + .iter() + .map(|entry| self.access.route_value(&entry.element)) + .collect(); + let mut neighbors = Vec::with_capacity(n.saturating_mul(stride)); + self.savings.reserve( + n.saturating_mul(stride) + .saturating_mul(representative_owner_slots.len()), + ); + for owner_slot in representative_owner_slots { + neighbors.clear(); + self.access.savings_neighbors( + phase_scope.score_director().working_solution(), + owner_slot.owner_idx, + &values, + k, + &mut neighbors, + ); + assert_eq!( + neighbors.len(), + n * stride, + "savings_neighbors_fn must append min(k, len - 1) = {stride} neighbours for each of {n} values" + ); + for a in 0..n { + if (a & 0x1F) == 0 + && self + .control_policy + .should_terminate_construction(phase_scope.solver_scope_mut()) { - return (savings, true); + return true; + } + for &b in &neighbors[a * stride..(a + 1) * stride] { + assert!( + b < n && b != a, + "savings_neighbors_fn returned neighbour index {b} for value index {a} of {n}" + ); + // A pair both rows name is scored from the lower row. + if b < a && neighbors[b * stride..(b + 1) * stride].contains(&a) { + continue; + } + if self.score_pair(phase_scope, owner_slot, a.min(b), a.max(b)) { + return true; + } } } } + false + } + + /// Scores the pair of unassigned positions `left < right` for one + /// representative owner. Returns whether termination interrupted. + fn score_pair( + &mut self, + phase_scope: &mut PhaseScope<'_, '_, S, D, BestCb>, + owner_slot: &OwnerSlot, + left: usize, + right: usize, + ) -> bool + where + S: PlanningSolution, + A: ClarkeWrightAccess, + D: Director, + BestCb: ProgressCallback, + { + let access = self.access; + let owner_idx = owner_slot.owner_idx; + let left = &self.unassigned[left]; + let right = &self.unassigned[right]; + let trace_token = phase_scope.record_candidate_operation( + CandidateTraceSource::ListClarkeWrightSavings, + None, + self.savings.len(), + Some(CandidateTraceConstructionTarget { + descriptor_index: access.descriptor_index(), + entity_index: owner_idx, + }), + access.descriptor_index(), + "clarke_wright_savings_pair", + [ + owner_idx as u64, + self.trace_metric_class_by_value[&owner_slot.metric_class], + left.source_index as u64, + right.source_index as u64, + ], + ); + let solution = phase_scope.score_director().working_solution(); + let depot = access.savings_depot(solution, owner_idx); + let left_value = access.route_value(&left.element); + let right_value = access.route_value(&right.element); + let saving = super::sum_two_minus_one( + access.savings_distance(solution, owner_idx, depot, left_value), + access.savings_distance(solution, owner_idx, depot, right_value), + access.savings_distance(solution, owner_idx, left_value, right_value), + ); + self.savings.push(SavingsEntry { + saving, + metric_class: owner_slot.metric_class, + left_idx: left.source_index, + right_idx: right.source_index, + }); + if let Some(token) = trace_token { + phase_scope + .record_candidate_trace_disposition(token, CandidateTraceDisposition::Evaluated); + phase_scope.record_candidate_trace_disposition( + token, + CandidateTraceDisposition::ForagerIgnored, + ); + } + record_construction_candidate( + phase_scope, + std::time::Duration::ZERO, + std::time::Duration::ZERO, + ); + (self.savings.len() & 0x3FF) == 0 + && self + .control_policy + .should_terminate_construction(phase_scope.solver_scope_mut()) } - (savings, false) } diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests.rs index cf0c3989..a2c3998e 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests.rs @@ -9,6 +9,7 @@ use solverforge_core::score::SoftScore; use solverforge_scoring::ScoreDirector; mod admission_oracle; +mod bounded_savings; mod compiled_parity; mod interruption; mod metric_class; diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/bounded_savings.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/bounded_savings.rs new file mode 100644 index 00000000..ca057d02 --- /dev/null +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/bounded_savings.rs @@ -0,0 +1,213 @@ +use std::cell::{Cell, RefCell}; + +use crate::phase::Phase; +use crate::scope::solver::SolverScope; +use std::any::TypeId; + +use solverforge_core::domain::SolutionDescriptor; +use solverforge_scoring::ScoreDirector; + +use super::*; + +thread_local! { + static COORDINATES: RefCell> = const { RefCell::new(Vec::new()) }; + static CAPACITY: Cell = const { Cell::new(0) }; + /// Set by the neighbour hook, which runs right before savings scoring, + /// and cleared by the first feasibility check after it, in the merge loop. + static IN_SAVINGS: Cell = const { Cell::new(false) }; + static SCORED_PAIRS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn leg(from: usize, to: usize) -> i64 { + COORDINATES.with(|coordinates| { + let coordinates = coordinates.borrow(); + let (a, b) = (coordinates[from], coordinates[to]); + (a.0 - b.0).abs() + (a.1 - b.1).abs() + }) +} + +fn grid_distance(_: &Plan, _: usize, from: usize, to: usize) -> i64 { + if IN_SAVINGS.with(Cell::get) && from != 0 && to != 0 { + // Recorded as asked: a scored pair is measured left to right. + SCORED_PAIRS.with(|pairs| pairs.borrow_mut().push((from, to))); + } + leg(from, to) +} + +fn capacity_feasible(_: &Plan, _: usize, route: &[usize]) -> bool { + IN_SAVINGS.with(|flag| flag.set(false)); + route.len() <= CAPACITY.with(Cell::get) +} + +/// Brute-force nearest neighbours by leg, ties by lower index. +fn nearest(_: &Plan, _: usize, values: &[usize], k: usize, out: &mut Vec) { + IN_SAVINGS.with(|flag| flag.set(true)); + let stride = k.min(values.len().saturating_sub(1)); + for (index, &value) in values.iter().enumerate() { + let mut others: Vec = (0..values.len()).filter(|&o| o != index).collect(); + others.sort_by_key(|&other| (leg(value, values[other]), other)); + out.extend_from_slice(&others[..stride]); + } +} + +fn short_neighbors(_: &Plan, _: usize, _: &[usize], _: usize, out: &mut Vec) { + out.push(1); +} + +struct Lcg(u64); + +impl Lcg { + fn next(&mut self, bound: u64) -> u64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) % bound + } +} + +/// Seeds a random instance: `customers` values on a grid plus the depot 0. +fn seed_instance(seed: u64, customers: usize, vehicles: usize) -> Plan { + let mut rng = Lcg(seed); + COORDINATES.with(|coordinates| { + *coordinates.borrow_mut() = (0..=customers) + .map(|_| (rng.next(100) as i64, rng.next(100) as i64)) + .collect(); + }); + CAPACITY.with(|capacity| capacity.set(customers.div_ceil(vehicles) + 1)); + Plan { + customer_values: (1..=customers).collect(), + routes: (0..vehicles) + .map(|_| Route { visits: Vec::new() }) + .collect(), + score: None, + } +} + +/// Solves and returns the routes plus the customer pairs savings scored +/// (recorded for bounded runs only). +fn solve(plan: Plan, savings_neighbors: Option) -> (Vec>, Vec<(usize, usize)>) { + SCORED_PAIRS.with(|pairs| pairs.borrow_mut().clear()); + let director = ScoreDirector::simple( + plan, + SolutionDescriptor::new("Plan", TypeId::of::()), + |s, descriptor_index| { + if descriptor_index == 0 { + s.routes.len() + } else { + 0 + } + }, + ); + let mut solver_scope = SolverScope::new(director); + let phase = ListClarkeWrightPhase::new( + element_count, + get_assigned, + entity_count, + route_len, + assign_route, + index_to_element, + crate::builder::context::list::usize_element_source_key, + depot, + grid_distance, + capacity_feasible, + 0, + ); + let mut phase = match savings_neighbors { + Some(k) => phase.with_savings_neighbors(nearest, k), + None => phase, + }; + phase.solve(&mut solver_scope); + let routes = solver_scope + .working_solution() + .routes + .iter() + .map(|route| route.visits.clone()) + .collect(); + (routes, SCORED_PAIRS.with(|pairs| pairs.take())) +} + +#[test] +fn a_bound_covering_every_pair_reproduces_unbounded_clarke_wright() { + for seed in 0..40 { + let customers = 3 + (seed as usize % 23); + let vehicles = 1 + (seed as usize % 4); + let (unbounded, _) = solve(seed_instance(seed, customers, vehicles), None); + for k in [customers - 1, customers + 3] { + let (bounded, _) = solve(seed_instance(seed, customers, vehicles), Some(k)); + assert_eq!( + bounded, unbounded, + "seed {seed}, {customers} customers, k = {k}" + ); + } + } +} + +#[test] +fn bounded_savings_score_each_neighbouring_pair_once() { + for seed in 0..20 { + let customers = 12 + (seed as usize % 9); + let vehicles = 1 + (seed as usize % 3); + for k in [1, 2, 4] { + let plan = seed_instance(seed, customers, vehicles); + let mut rows = Vec::new(); + nearest(&plan, 0, &plan.customer_values, k, &mut rows); + let mut expected = std::collections::BTreeSet::new(); + for (a, row) in rows.chunks(k).enumerate() { + for &b in row { + // Values are customers 1..=n at positions 0..n. + expected.insert((a.min(b) + 1, a.max(b) + 1)); + } + } + let (routes, scored) = solve(plan, Some(k)); + // Every vehicle is its own metric class here; each scores the pairs. + assert_eq!( + scored.len(), + expected.len() * vehicles, + "each pair once per class: seed {seed}, k = {k}" + ); + let scored: std::collections::BTreeSet<_> = scored.into_iter().collect(); + assert_eq!(scored, expected, "seed {seed}, k = {k}"); + let mut assigned: Vec = routes.concat(); + assigned.sort_unstable(); + assert_eq!( + assigned, + (1..=customers).collect::>(), + "seed {seed}, k = {k}" + ); + } + } +} + +#[test] +#[should_panic(expected = "savings_neighbors_fn must append")] +fn a_neighbour_hook_with_the_wrong_row_length_is_rejected() { + let plan = seed_instance(7, 6, 2); + let director = ScoreDirector::simple( + plan, + SolutionDescriptor::new("Plan", TypeId::of::()), + |s, descriptor_index| { + if descriptor_index == 0 { + s.routes.len() + } else { + 0 + } + }, + ); + let mut solver_scope = SolverScope::new(director); + let mut phase = ListClarkeWrightPhase::new( + element_count, + get_assigned, + entity_count, + route_len, + assign_route, + index_to_element, + crate::builder::context::list::usize_element_source_key, + depot, + grid_distance, + capacity_feasible, + 0, + ) + .with_savings_neighbors(short_neighbors, 3); + phase.solve(&mut solver_scope); +} diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity.rs index f11046fb..babae954 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity.rs @@ -363,6 +363,7 @@ fn run(slot: Slot) -> (Vec>, CandidateTraceTelemetry) { &slot, &source_index, &unassigned, + None, crate::scope::StepControlPolicy::ObserveConfigLimits, &mut scope, ) diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity/refresh.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity/refresh.rs index 208bf34b..7e61d3c4 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity/refresh.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/compiled_parity/refresh.rs @@ -18,6 +18,7 @@ fn compiled_clarke_wright_refreshes_current_assignment_before_a_second_execution &slot, &source_index, &unassigned, + None, crate::scope::StepControlPolicy::ObserveConfigLimits, &mut scope, ) @@ -30,6 +31,7 @@ fn compiled_clarke_wright_refreshes_current_assignment_before_a_second_execution &slot, &source_index, &unassigned, + None, crate::scope::StepControlPolicy::ObserveConfigLimits, &mut scope, ) diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/public_compiled_parity.rs b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/public_compiled_parity.rs index d29adddb..7657ab66 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/public_compiled_parity.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_clarke_wright/tests/public_compiled_parity.rs @@ -353,6 +353,7 @@ fn run_runtime(slot: Slot) -> (Vec>, CandidateTraceTelemetry) { &slot, &source_index, &unassigned, + None, crate::scope::StepControlPolicy::ObserveConfigLimits, &mut scope, ) diff --git a/crates/solverforge-solver/src/runtime.rs b/crates/solverforge-solver/src/runtime.rs index 63eaacbe..2abfc5c9 100644 --- a/crates/solverforge-solver/src/runtime.rs +++ b/crates/solverforge-solver/src/runtime.rs @@ -50,6 +50,8 @@ pub struct ListVariableMetadata { /// Whether `savings_feasible_fn` answers the same for every entity of one /// savings metric class. pub savings_feasible_shared_by_metric_class: bool, + /// Nearest neighbours for bounded Clarke-Wright savings. + pub savings_neighbors_fn: Option)>, /// The entity whose list must hold an element; `None` means any. pub element_owner_fn: Option Option>, _phantom: PhantomData S>, @@ -108,6 +110,7 @@ impl ListVariableMetadata { savings_distance_fn, savings_feasible_fn, savings_feasible_shared_by_metric_class: false, + savings_neighbors_fn: None, element_owner_fn: None, _phantom: PhantomData, } @@ -120,6 +123,15 @@ impl ListVariableMetadata { self } + /// Sets the nearest-neighbour hook bounded Clarke-Wright savings use. + pub fn with_savings_neighbors_fn( + mut self, + savings_neighbors_fn: Option)>, + ) -> Self { + self.savings_neighbors_fn = savings_neighbors_fn; + self + } + /// Sets the element ownership hook. pub fn with_element_owner_fn( mut self, diff --git a/crates/solverforge-solver/src/runtime/compiler/construction.rs b/crates/solverforge-solver/src/runtime/compiler/construction.rs index 595a63c3..af9dd2bf 100644 --- a/crates/solverforge-solver/src/runtime/compiler/construction.rs +++ b/crates/solverforge-solver/src/runtime/compiler/construction.rs @@ -103,6 +103,9 @@ where match kind { ListConstructionKind::ClarkeWright => { require_list_capability(&slots, RuntimeCapability::ListSavings, path)?; + if config.savings_neighbors.is_some() { + require_list_capability(&slots, RuntimeCapability::ListSavingsNeighbors, path)?; + } } ListConstructionKind::KOpt => { require_list_capability(&slots, RuntimeCapability::ListRoute, path)?; diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs index 3fd8c691..a95b6154 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs @@ -184,7 +184,18 @@ where slots, control_policy, solver_scope, - execute_runtime_list_clarke_wright, + |slot, source_index, unassigned, control_policy, solver_scope| { + execute_runtime_list_clarke_wright( + slot, + source_index, + unassigned, + config + .savings_neighbors + .map(|k| usize::try_from(k.get()).unwrap_or(usize::MAX)), + control_policy, + solver_scope, + ) + }, ) }, ) @@ -381,7 +392,7 @@ fn execute_list_slots( slots: &[PreparedListSlot], control_policy: StepControlPolicy, solver_scope: &mut SolverScope<'_, S, D, ProgressCb>, - execute: fn( + execute: impl Fn( &crate::builder::context::RuntimeListSlot, &crate::builder::context::RuntimeListSourceIndex< crate::builder::context::RuntimeListElement, diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/list_construction/clarke_wright.rs b/crates/solverforge-solver/src/runtime/compiler/executor/list_construction/clarke_wright.rs index 5e8d67b9..6841277d 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/list_construction/clarke_wright.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/list_construction/clarke_wright.rs @@ -24,6 +24,7 @@ pub(crate) fn execute_runtime_list_clarke_wright( slot: &RuntimeListSlot, source_index: &RuntimeListSourceIndex>, unassigned: &[SourceElement>], + savings_neighbors: Option, control_policy: StepControlPolicy, solver_scope: &mut SolverScope<'_, S, D, ProgressCb>, ) -> Result<(), ListConstructionKernelError> @@ -35,6 +36,13 @@ where D: Director, ProgressCb: ProgressCallback, { - run_clarke_wright(slot, source_index, unassigned, control_policy, solver_scope); + run_clarke_wright( + slot, + source_index, + unassigned, + savings_neighbors, + control_policy, + solver_scope, + ); Ok(()) } diff --git a/crates/solverforge-solver/src/runtime/compiler/selector_values.rs b/crates/solverforge-solver/src/runtime/compiler/selector_values.rs index 584ec7fc..81451158 100644 --- a/crates/solverforge-solver/src/runtime/compiler/selector_values.rs +++ b/crates/solverforge-solver/src/runtime/compiler/selector_values.rs @@ -85,6 +85,15 @@ fn validate_construction( "caps grouped scalar candidates and needs `group_name`".to_string(), )); } + if config.savings_neighbors.is_some() + && config.construction_heuristic_type != ConstructionHeuristicType::ListClarkeWright + { + return Err(invalid( + path, + "savings_neighbors", + "applies only to `list_clarke_wright` construction".to_string(), + )); + } positive_limit(path, "value_candidate_limit", config.value_candidate_limit)?; positive_limit(path, "group_candidate_limit", config.group_candidate_limit) } diff --git a/crates/solverforge-solver/src/runtime/compiler/slots.rs b/crates/solverforge-solver/src/runtime/compiler/slots.rs index c82d9f3b..b982820c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/slots.rs +++ b/crates/solverforge-solver/src/runtime/compiler/slots.rs @@ -266,6 +266,7 @@ pub(super) fn require_list_capability( RuntimeCapability::ListIntraPositionDistance => ListAccessCapability::IntraPositionDistance, RuntimeCapability::ListRoute => ListAccessCapability::Route, RuntimeCapability::ListSavings => ListAccessCapability::Savings, + RuntimeCapability::ListSavingsNeighbors => ListAccessCapability::SavingsNeighbors, _ => unreachable!("list capability validation received a scalar capability"), }; if let Some(slot) = slots.iter().find(|slot| !slot.supports(access_capability)) { diff --git a/crates/solverforge-solver/src/runtime/compiler/tests.rs b/crates/solverforge-solver/src/runtime/compiler/tests.rs index ddd82469..b05d534c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/tests.rs @@ -25,6 +25,7 @@ use crate::heuristic::selector::nearby_list_change::DefaultCrossEntityDistanceMe mod invalid_config; mod invalid_selector_values; +mod savings_neighbors; type Meter = DefaultCrossEntityDistanceMeter; @@ -178,7 +179,11 @@ fn model(shape: PrecedenceShape) -> RuntimeModel { } fn savings_model() -> RuntimeModel { - RuntimeModel::new(vec![VariableSlot::List(ListVariableSlot::new( + RuntimeModel::new(vec![VariableSlot::List(savings_slot())]) +} + +fn savings_slot() -> ListVariableSlot { + ListVariableSlot::new( "Vehicle", element_count, assigned_elements, @@ -208,7 +213,7 @@ fn savings_model() -> RuntimeModel { None, Some(savings_distance), Some(route_feasible), - ))]) + ) } fn compile( diff --git a/crates/solverforge-solver/src/runtime/compiler/tests/savings_neighbors.rs b/crates/solverforge-solver/src/runtime/compiler/tests/savings_neighbors.rs new file mode 100644 index 00000000..7a12eb70 --- /dev/null +++ b/crates/solverforge-solver/src/runtime/compiler/tests/savings_neighbors.rs @@ -0,0 +1,96 @@ +use super::*; + +fn neighbors(_: &Plan, _: usize, values: &[usize], k: usize, out: &mut Vec) { + let stride = k.min(values.len().saturating_sub(1)); + for index in 0..values.len() { + out.extend( + (0..values.len()) + .filter(|&other| other != index) + .take(stride), + ); + } +} + +fn compile_bounded( + model: RuntimeModel, + construction_heuristic_type: ConstructionHeuristicType, + savings_neighbors: Option, +) -> Result<(), super::super::RuntimeCompileError> { + let config = SolverConfig { + phases: vec![PhaseConfig::ConstructionHeuristic( + ConstructionHeuristicConfig { + construction_heuristic_type, + savings_neighbors: savings_neighbors + .map(|k| std::num::NonZeroU32::new(k).expect("test bounds are positive")), + ..ConstructionHeuristicConfig::default() + }, + )], + ..SolverConfig::default() + }; + let context = SearchContext::new(descriptor(), model, config.resolved_random_seed()) + .expect("search context should bind"); + compile_runtime_graph( + &config, + RuntimeGraphInput::new(context, NoDynamicExtensions), + ) + .map(|_| ()) +} + +fn neighbor_model() -> RuntimeModel { + RuntimeModel::new(vec![VariableSlot::List( + savings_slot().with_savings_neighbors_fn(Some(neighbors)), + )]) +} + +#[test] +fn bounded_clarke_wright_requires_a_savings_neighbour_source() { + let error = compile_bounded( + savings_model(), + ConstructionHeuristicType::ListClarkeWright, + Some(8), + ) + .expect_err("bounded savings need a neighbour hook"); + assert!(matches!( + error.kind, + RuntimeCompileErrorKind::MissingCapability { + capability: RuntimeCapability::ListSavingsNeighbors, + .. + } + )); + compile_bounded( + savings_model(), + ConstructionHeuristicType::ListClarkeWright, + None, + ) + .expect("unbounded savings need no neighbour hook"); + compile_bounded( + neighbor_model(), + ConstructionHeuristicType::ListClarkeWright, + Some(8), + ) + .expect("a declared neighbour hook admits bounded savings"); +} + +#[test] +fn savings_neighbors_is_a_positive_clarke_wright_setting() { + for heuristic in [ + ConstructionHeuristicType::ListCheapestInsertion, + ConstructionHeuristicType::FirstFit, + ] { + let error = compile_bounded(neighbor_model(), heuristic, Some(8)) + .expect_err("savings_neighbors on another heuristic"); + assert_eq!( + error.path, "phases[0].construction.savings_neighbors", + "{error}" + ); + assert!( + matches!(error.kind, RuntimeCompileErrorKind::InvalidValue { .. }), + "{error}" + ); + } + let zero = SolverConfig::from_toml_str( + "[[phases]]\ntype = \"construction_heuristic\"\n\ + construction_heuristic_type = \"list_clarke_wright\"\nsavings_neighbors = 0\n", + ); + assert!(zero.is_err(), "zero savings_neighbors must not parse"); +} diff --git a/crates/solverforge-solver/src/runtime/compiler/types.rs b/crates/solverforge-solver/src/runtime/compiler/types.rs index b3514a59..cfd57337 100644 --- a/crates/solverforge-solver/src/runtime/compiler/types.rs +++ b/crates/solverforge-solver/src/runtime/compiler/types.rs @@ -49,6 +49,7 @@ pub(crate) enum RuntimeCapability { ListIntraPositionDistance, ListRoute, ListSavings, + ListSavingsNeighbors, } impl fmt::Display for RuntimeCapability { @@ -67,6 +68,7 @@ impl fmt::Display for RuntimeCapability { Self::ListIntraPositionDistance => "intra-position list distance", Self::ListRoute => "route bundle (read/replace/depot/distance/feasible)", Self::ListSavings => "savings bundle (replace/depot/metric_class/distance/feasible)", + Self::ListSavingsNeighbors => "savings neighbour source (savings_neighbors_fn)", }; f.write_str(name) } diff --git a/crates/solverforge/WIREFRAME.md b/crates/solverforge/WIREFRAME.md index d14b8c27..e1d42aff 100644 --- a/crates/solverforge/WIREFRAME.md +++ b/crates/solverforge/WIREFRAME.md @@ -257,7 +257,7 @@ Module: `solverforge::cvrp` - `replace_route`, `get_route` - hook modules: `route_hooks`, `savings_hooks` - route-local helpers: `depot_for_entity`, `route_distance`, `route_feasible` -- Clarke-Wright construction adapters: `savings_depot_for_entity`, `savings_metric_class`, `savings_distance`, `savings_feasible` +- Clarke-Wright construction adapters: `savings_depot_for_entity`, `savings_metric_class`, `savings_distance`, `savings_feasible`, `savings_neighbors` Stock CVRP route lists should normally use `#[planning_list_variable(element_collection = "...", domain = "cvrp")]`. The diff --git a/crates/solverforge/src/cvrp.rs b/crates/solverforge/src/cvrp.rs index c70e2038..4f4c4939 100644 --- a/crates/solverforge/src/cvrp.rs +++ b/crates/solverforge/src/cvrp.rs @@ -1,6 +1,6 @@ pub use solverforge_cvrp::{ depot_for_entity, get_route, replace_route, route_distance, route_feasible, route_hooks, savings_depot_for_entity, savings_distance, savings_feasible, savings_hooks, - savings_metric_class, DenseMatrix, EuclideanMetric, MatrixDistanceMeter, + savings_metric_class, savings_neighbors, DenseMatrix, EuclideanMetric, MatrixDistanceMeter, MatrixIntraDistanceMeter, ProblemData, RouteMetric, VrpSolution, UNREACHABLE, }; diff --git a/crates/solverforge/tests/list_clarke_wright_bounded.rs b/crates/solverforge/tests/list_clarke_wright_bounded.rs new file mode 100644 index 00000000..aa4d6b0e --- /dev/null +++ b/crates/solverforge/tests/list_clarke_wright_bounded.rs @@ -0,0 +1,46 @@ +//! Bounded Clarke-Wright savings through the stock `domain = "cvrp"` profile: +//! the configured bound reaches the profile's neighbour hook, a bound covering +//! every pair reproduces unbounded construction, and a small bound still +//! assigns every customer. + +use solverforge::SolverConfig; + +#[path = "list_clarke_wright_publication/domain/mod.rs"] +mod domain; + +use domain::{build_plan, PublicationPlan}; + +fn construct(customers: usize, savings_neighbors: Option) -> Vec> { + let bound = savings_neighbors + .map(|k| format!("savings_neighbors = {k}\n")) + .unwrap_or_default(); + let config = SolverConfig::from_toml_str(&format!( + "[[phases]]\ntype = \"construction_heuristic\"\n\ + construction_heuristic_type = \"list_clarke_wright\"\n{bound}" + )) + .expect("Clarke-Wright config parses"); + let plan: PublicationPlan = build_plan(customers, 1); + plan.solve_with_config(config) + .expect("construction solves") + .routes + .into_iter() + .map(|route| route.visits) + .collect() +} + +#[test] +fn a_bound_covering_every_pair_reproduces_unbounded_construction() { + let unbounded = construct(24, None); + assert_eq!(construct(24, Some(23)), unbounded); + assert_eq!(construct(24, Some(100)), unbounded); +} + +#[test] +fn a_small_bound_still_assigns_every_customer() { + let routes = construct(24, Some(3)); + let mut assigned: Vec = routes.concat(); + assigned.sort_unstable(); + let mut expected: Vec = build_plan(24, 1).customer_values; + expected.sort_unstable(); + assert_eq!(assigned, expected); +} diff --git a/docs/configuration.md b/docs/configuration.md index 5ad54176..c8c8cfef 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -187,6 +187,29 @@ type = "change_move_selector" | List selectors | `list_change_move_selector`, `nearby_list_change_move_selector`, `list_swap_move_selector`, `nearby_list_swap_move_selector`, `list_permute_move_selector`, `list_precedence_move_selector`, `sublist_change_move_selector`, `sublist_swap_move_selector`, `list_reverse_move_selector`, `k_opt_move_selector`, `list_ruin_move_selector` | | Composition | `union_move_selector`, `cartesian_product_move_selector`, `limited_neighborhood`; native and host-backed compound scalar moves; nearby selection for scalar and list neighborhoods | +### Bounded Clarke-Wright savings + +`list_clarke_wright` scores every pair of unassigned elements by default, so +its savings list grows with the square of the element count (32 bytes per +pair; 1.6 GB at 10k stops). `savings_neighbors` scores a pair only when one +element is among the other's nearest: + +```toml +[[phases]] +type = "construction_heuristic" +construction_heuristic_type = "list_clarke_wright" +savings_neighbors = 40 +``` + +The list then holds about `savings_neighbors` entries per element. The +variable must declare a savings neighbour hook (`savings_neighbors_fn`); the +`domain = "cvrp"` profile supplies one that asks the vehicles' `RouteMetric`. +With `EuclideanMetric` the neighbours come from a spatial grid, so memory +stays linear in the stops; see [Modeling](modeling.md#vehicle-routing-cvrp-profile). +Without the setting, savings, their order and the merges are unchanged, and a +bound of at least the element count minus one gives the same routes as no +bound. + The configuration surface also covers bounded candidate tracing, per-selector ordering and host metrics, weighted union scheduling, score tie-breaking, and grouped scalar and conflict-repair selectors. diff --git a/docs/extend-domain.md b/docs/extend-domain.md index 752af2b6..453e9127 100644 --- a/docs/extend-domain.md +++ b/docs/extend-domain.md @@ -81,7 +81,11 @@ Use the scaffold as a thin starter, then model the real problem in your app. construction depot and distance behavior. Clarke-Wright then computes savings once per class but still asks every owner whether a merged route is feasible; only the `domain = "cvrp"` profile, whose feasibility depends on - the class's shared data alone, asks one owner per class. + the class's shared data alone, asks one owner per class. Add + `savings_neighbors_fn = "path::neighbors"` to allow bounded savings + (`savings_neighbors` in `solver.toml`): for an owner, element values and + `k`, it appends each value's `min(k, len - 1)` nearest other values as + indexes into the values, nearest first, ties by lower index. - Add derived fields, validation helpers, and sample data beside the domain model, not in the scaffold templates. diff --git a/docs/modeling.md b/docs/modeling.md index e0e364bd..8cbad06c 100644 --- a/docs/modeling.md +++ b/docs/modeling.md @@ -170,7 +170,14 @@ times from its `metric`, named by `VrpSolution::Metric`: travel time = length / speed, rounded the same way); memory grows linearly, for models too large for a matrix. -`UNREACHABLE` or a negative leg value marks a leg that cannot be traversed. Custom routing domains omit `domain = "cvrp"` +`UNREACHABLE` or a negative leg value marks a leg that cannot be traversed. + +For models past roughly 10k stops, pair `EuclideanMetric` with bounded +Clarke-Wright savings (`savings_neighbors`, see +[Configuration](configuration.md#bounded-clarke-wright-savings)): the profile's +neighbour hook asks the metric for each stop's nearest stops, which +`EuclideanMetric` answers from a spatial grid, so construction memory stays +linear in the stops. Custom routing domains omit `domain = "cvrp"` and supply their own `route_hooks` and `savings_hooks`; see [Extend the domain](extend-domain.md).