Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`.
| `value_candidate_limit` | `Option<usize>` | `None`; valid: `>= 1` when set; scalar heuristics only, list heuristics reject it |
| `group_name` | `Option<String>` | `None` |
| `group_candidate_limit` | `Option<usize>` | `None`; valid: `>= 1` when set; requires `group_name`; list heuristics reject it |
| `savings_neighbors` | `Option<NonZeroU32>` | `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<TerminationConfig>` | `None` |

`target` is flattened in serde, so configuration files still use top-level
Expand Down
10 changes: 10 additions & 0 deletions crates/solverforge-config/src/phase.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::num::NonZeroU32;

use serde::{Deserialize, Serialize};

use crate::acceptor::AcceptorConfig;
Expand Down Expand Up @@ -61,6 +63,13 @@ pub struct ConstructionHeuristicConfig {
/// Requires `group_name`; a list heuristic rejects it.
pub group_candidate_limit: Option<usize>,

/// 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<NonZeroU32>,

/// Phase termination configuration.
pub termination: Option<TerminationConfig>,
}
Expand All @@ -75,6 +84,7 @@ impl Default for ConstructionHeuristicConfig {
value_candidate_limit: None,
group_name: None,
group_candidate_limit: None,
savings_neighbors: None,
termination: None,
}
}
Expand Down
9 changes: 7 additions & 2 deletions crates/solverforge-cvrp/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -61,6 +62,7 @@ per metric type.
| `distance` | `fn(&self, from: usize, to: usize) -> Option<i64>` | Leg distance; `None` outside the metric |
| `travel_time` | `fn(&self, from: usize, to: usize) -> Option<i64>` | 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<usize>)` | 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`

Expand All @@ -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)
Expand Down Expand Up @@ -117,6 +121,7 @@ All functions are generic over `S: VrpSolution`.
| `savings_metric_class` | `fn<S: VrpSolution>(plan: &S, entity_idx: usize) -> usize` | Clarke-Wright metric class for owners that share backing `ProblemData` |
| `savings_distance` | `fn<S: VrpSolution>(plan: &S, entity_idx: usize, from: usize, to: usize) -> i64` | Construction distance adapter for models that share exact CVRP route data |
| `savings_feasible` | `fn<S: VrpSolution>(plan: &S, entity_idx: usize, route: &[usize]) -> bool` | Construction admissibility adapter that rejects only non-evaluable stock CVRP routes |
| `savings_neighbors` | `fn<S: VrpSolution>(plan: &S, entity_idx: usize, values: &[usize], k: usize, out: &mut Vec<usize>)` | 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

Expand All @@ -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
Expand Down
152 changes: 152 additions & 0 deletions crates/solverforge-cvrp/src/euclidean_grid.rs
Original file line number Diff line number Diff line change
@@ -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<usize>,
) {
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::<Option<Vec<_>>>()
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<usize>,
members: Vec<usize>,
}

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<usize> = 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;
}
}
}
}
17 changes: 17 additions & 0 deletions crates/solverforge-cvrp/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,23 @@ pub fn savings_distance<S: VrpSolution>(
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<S: VrpSolution>(
plan: &S,
entity_idx: usize,
values: &[usize],
k: usize,
out: &mut Vec<usize>,
) {
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.
Expand Down
3 changes: 2 additions & 1 deletion crates/solverforge-cvrp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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};
Expand Down
54 changes: 54 additions & 0 deletions crates/solverforge-cvrp/src/metric.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<usize>) {
nearest_by_rank(self, locations, k, out);
}
}

/// `RouteMetric::nearest` by ranking every other location for each one.
pub(crate) fn nearest_by_rank<M: RouteMetric>(
metric: &M,
locations: &[usize],
k: usize,
out: &mut Vec<usize>,
) {
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>) -> i64 {
distance.and_then(finite_leg).unwrap_or(MAX_SAFE_LEG_COST)
}

/// Dense distance and travel-time tables, indexed `[from][to]`.
Expand Down Expand Up @@ -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<usize>) {
crate::euclidean_grid::nearest(self, locations, k, out);
}
}
Loading
Loading