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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/solverforge-cvrp/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# solverforge-cvrp

Capacitated vehicle routing helpers for SolverForge: problem data, matrix distance meters, the `VrpSolution` trait and the hooks behind `#[planning_list_variable(domain = "cvrp")]`.
Capacitated vehicle routing helpers for SolverForge: problem data with dense-matrix or on-demand Euclidean leg distances, distance meters, the `VrpSolution` trait and the hooks behind `#[planning_list_variable(domain = "cvrp")]`.

Applications depend on the [`solverforge`](https://crates.io/crates/solverforge) facade crate, which re-exports this crate's supported items; use this crate directly only to build an integration on it. API documentation is on [docs.rs](https://docs.rs/solverforge-cvrp), and the project guide is at [solverforge.org](https://solverforge.org) and in the [repository](https://github.com/SolverForge/solverforge).

Expand Down
50 changes: 42 additions & 8 deletions crates/solverforge-cvrp/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ src/
├── 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
├── metric.rs — `RouteMetric`, `DenseMatrix`, `EuclideanMetric`
├── metric_tests.rs — Metric semantics and on-demand vs tabulated equivalence tests
├── problem_data.rs — `ProblemData`
├── solution.rs — `VrpSolution`
└── tests.rs — CVRP helper and route-feasibility tests
```

## Types

### `ProblemData`
### `ProblemData<M = DenseMatrix>`

Immutable problem data shared by all vehicles. Derives: `Clone, Debug`.
Immutable problem data shared by all vehicles, generic over the source of leg
distances and travel times. Derives: `Clone, Debug`.

Fields:

Expand All @@ -35,25 +38,56 @@ Fields:
| `capacity` | `i64` | Vehicle capacity |
| `depot` | `usize` | Depot node index |
| `demands` | `Vec<i32>` | Demand per node |
| `distance_matrix` | `Vec<Vec<i64>>` | Distance matrix |
| `metric` | `M` | Leg distances and travel times (`RouteMetric`) |
| `time_windows` | `Vec<(i64, i64)>` | `(min_start, max_end)` per node |
| `service_durations` | `Vec<i64>` | Service duration per node |
| `travel_times` | `Vec<Vec<i64>>` | Travel time matrix |
| `vehicle_departure_time` | `i64` | Departure time from depot |

`UNREACHABLE` is exported as `i64::MAX` for non-traversable matrix entries.
`UNREACHABLE` is exported as `i64::MAX` for non-traversable legs; a negative
leg value is treated the same way.
`route_feasible` rejects routes that contain unreachable travel-time legs or
overflowing time arithmetic. Distance hooks convert unreachable or malformed
distance entries into a large finite cost so construction and local-search
distance arithmetic stays panic-free.

### `RouteMetric` (trait)

Source of leg values, bounded `Clone + Debug + Send + Sync + 'static`. The
stock helpers, meters and route checks read legs only through it, monomorphized
per metric type.

| Method | Signature | Description |
|--------|-----------|-------------|
| `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 |

### `DenseMatrix`

Dense tables indexed `[from][to]`, holding exactly the supplied values (rows
may differ in length; a leg outside a row is undefined). `DenseMatrix::new(distances, travel_times)`.
Public fields `distances: Vec<Vec<i64>>` and `travel_times: Vec<Vec<i64>>`.
Implements `RouteMetric`. Derives: `Clone, Debug`. Memory is quadratic in the
location count.

### `EuclideanMetric`

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`.
Derives: `Clone, Debug`. Memory is linear in the location count.

### `VrpSolution` (trait)

Trait implemented by a planning solution that holds a fleet of vehicles.

Associated type `Metric: RouteMetric` names the vehicles' leg source.

| Method | Signature |
|--------|-----------|
| `vehicle_data` | `fn(&self, entity_idx: usize) -> Option<&ProblemData>` |
| `vehicle_data` | `fn(&self, entity_idx: usize) -> Option<&ProblemData<Self::Metric>>` |
| `vehicle_visits` | `fn(&self, entity_idx: usize) -> &[usize]` |
| `vehicle_visits_mut` | `fn(&mut self, entity_idx: usize) -> &mut Vec<usize>` |
| `vehicle_count` | `fn(&self) -> usize` |
Expand All @@ -62,11 +96,11 @@ Vehicles that share one `ProblemData` return the same reference, so `savings_met

### `MatrixDistanceMeter`

Cross-entity distance meter backed by the solution's distance matrix. Implements `CrossEntityDistanceMeter<S: VrpSolution>`. `#[derive(Clone, Debug, Default)]`.
Cross-entity distance meter backed by the vehicles' `RouteMetric` distances. Implements `CrossEntityDistanceMeter<S: VrpSolution>`. `#[derive(Clone, Debug, Default)]`.

### `MatrixIntraDistanceMeter`

Intra-entity distance meter backed by the solution's distance matrix. Implements `CrossEntityDistanceMeter<S: VrpSolution>`. `#[derive(Clone, Debug, Default)]`.
Intra-entity distance meter backed by the vehicle's `RouteMetric` distances. Implements `CrossEntityDistanceMeter<S: VrpSolution>`. `#[derive(Clone, Debug, Default)]`.

## Free Functions

Expand Down
31 changes: 9 additions & 22 deletions crates/solverforge-cvrp/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::{ProblemData, VrpSolution};
use crate::{ProblemData, RouteMetric, VrpSolution};

#[inline]
pub(crate) fn problem_data_for_entity<S: VrpSolution>(
plan: &S,
entity_idx: usize,
) -> Option<&ProblemData> {
) -> Option<&ProblemData<S::Metric>> {
if entity_idx >= plan.vehicle_count() {
return None;
}
Expand All @@ -20,7 +20,7 @@ pub(crate) fn problem_data_for_entity<S: VrpSolution>(
fn optional_problem_data_for_entity<S: VrpSolution>(
plan: &S,
entity_idx: usize,
) -> Option<&ProblemData> {
) -> Option<&ProblemData<S::Metric>> {
if entity_idx >= plan.vehicle_count() {
return None;
}
Expand Down Expand Up @@ -124,7 +124,7 @@ pub mod savings_hooks {
pub use super::savings_feasible as feasible;
}

fn route_is_structurally_valid(route: &[usize], data: &ProblemData) -> bool {
fn route_is_structurally_valid<M: RouteMetric>(route: &[usize], data: &ProblemData<M>) -> bool {
let Some(max_visit) = route.iter().copied().max() else {
return true;
};
Expand All @@ -133,27 +133,14 @@ fn route_is_structurally_valid(route: &[usize], data: &ProblemData) -> bool {
if max_visit >= data.demands.len()
|| max_visit >= data.time_windows.len()
|| max_visit >= data.service_durations.len()
|| max_node >= data.distance_matrix.len()
|| max_node >= data.travel_times.len()
{
return false;
}

route
.iter()
.chain(std::iter::once(&data.depot))
.all(|&node| {
data.distance_matrix
.get(node)
.is_some_and(|row| row.len() > max_node)
&& data
.travel_times
.get(node)
.is_some_and(|row| row.len() > max_node)
})
}

fn route_is_capacity_feasible(route: &[usize], data: &ProblemData) -> bool {
data.metric.covers(route, data.depot, max_node)
}

fn route_is_capacity_feasible<M>(route: &[usize], data: &ProblemData<M>) -> bool {
let mut total = 0_i64;
for &visit in route {
let demand = i64::from(data.demands[visit]);
Expand All @@ -165,7 +152,7 @@ fn route_is_capacity_feasible(route: &[usize], data: &ProblemData) -> bool {
total <= data.capacity
}

fn route_is_time_feasible(route: &[usize], data: &ProblemData) -> bool {
fn route_is_time_feasible<M: RouteMetric>(route: &[usize], data: &ProblemData<M>) -> bool {
let mut current_time = data.vehicle_departure_time;
let mut previous = data.depot;

Expand Down
12 changes: 9 additions & 3 deletions crates/solverforge-cvrp/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
//! CVRP domain helpers for SolverForge.
//!
//! Provides `ProblemData`, `MatrixDistanceMeter`, `MatrixIntraDistanceMeter`,
//! the `VrpSolution` trait, and the stock helpers behind
//! `#[planning_list_variable(domain = "cvrp")]`.
//! Provides `ProblemData` with its `RouteMetric` distance sources
//! (`DenseMatrix`, `EuclideanMetric`), `MatrixDistanceMeter`,
//! `MatrixIntraDistanceMeter`, the `VrpSolution` trait, and the stock helpers
//! behind `#[planning_list_variable(domain = "cvrp")]`.

mod helpers;
mod meters;
mod metric;
mod problem_data;
mod solution;

Expand All @@ -15,8 +17,12 @@ pub use helpers::{
savings_metric_class,
};
pub use meters::{MatrixDistanceMeter, MatrixIntraDistanceMeter};
pub use metric::{DenseMatrix, EuclideanMetric, RouteMetric};
pub use problem_data::{ProblemData, UNREACHABLE};
pub use solution::VrpSolution;

#[cfg(test)]
mod tests;

#[cfg(test)]
mod metric_tests;
135 changes: 135 additions & 0 deletions crates/solverforge-cvrp/src/metric.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use std::fmt;

/// Source of leg distances and travel times between locations.
///
/// The stock CVRP helpers, meters and route checks read legs only through
/// this trait, so a [`ProblemData`](crate::ProblemData) can hold a dense
/// matrix or compute legs on demand. Values follow the matrix conventions:
/// [`UNREACHABLE`](crate::UNREACHABLE) or a negative value marks a leg that
/// cannot be traversed, and `None` marks a location outside the metric.
pub trait RouteMetric: Clone + fmt::Debug + Send + Sync + 'static {
/// Distance from `from` to `to`; `None` when either is outside the metric.
fn distance(&self, from: usize, to: usize) -> Option<i64>;

/// Travel time from `from` to `to`; `None` when either is outside the
/// metric.
fn travel_time(&self, from: usize, to: usize) -> Option<i64>;

/// 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;
}

/// Dense distance and travel-time tables, indexed `[from][to]`.
///
/// Holds exactly the values a caller supplies: rows may differ in length,
/// and a leg outside a row is undefined, so a route touching it is not
/// structurally valid.
#[derive(Clone, Debug)]
pub struct DenseMatrix {
/// Distance from location `[from][to]`.
pub distances: Vec<Vec<i64>>,
/// Travel time from location `[from][to]`.
pub travel_times: Vec<Vec<i64>>,
}

impl DenseMatrix {
/// Builds the metric from a distance table and a travel-time table.
pub fn new(distances: Vec<Vec<i64>>, travel_times: Vec<Vec<i64>>) -> Self {
Self {
distances,
travel_times,
}
}
}

impl RouteMetric for DenseMatrix {
#[inline]
fn distance(&self, from: usize, to: usize) -> Option<i64> {
self.distances.get(from)?.get(to).copied()
}

#[inline]
fn travel_time(&self, from: usize, to: usize) -> Option<i64> {
self.travel_times.get(from)?.get(to).copied()
}

fn covers(&self, route: &[usize], depot: usize, max_node: usize) -> bool {
if max_node >= self.distances.len() || max_node >= self.travel_times.len() {
return false;
}
route.iter().chain(std::iter::once(&depot)).all(|&node| {
self.distances[node].len() > max_node && self.travel_times[node].len() > max_node
})
}
}

/// Straight-line legs between planar coordinates, computed on demand.
///
/// Distance is the Euclidean length of the leg, `sqrt(dx² + dy²)`, rounded to
/// the nearest integer with halves away from zero (TSPLIB `EUC_2D`); travel
/// time is that length divided by `speed`, rounded the same way. Memory is
/// linear in the location count.
#[derive(Clone, Debug)]
pub struct EuclideanMetric {
coordinates: Vec<(f64, f64)>,
speed: f64,
}

impl EuclideanMetric {
/// Builds the metric from one `(x, y)` per location and a travel speed in
/// distance units per time unit.
///
/// # Panics
///
/// Panics when `speed` is not finite and positive, or a coordinate is not
/// finite.
pub fn new(coordinates: Vec<(f64, f64)>, speed: f64) -> Self {
assert!(
speed.is_finite() && speed > 0.0,
"EuclideanMetric speed must be finite and positive, got {speed}"
);
assert!(
coordinates
.iter()
.all(|(x, y)| x.is_finite() && y.is_finite()),
"EuclideanMetric coordinates must be finite"
);
Self { coordinates, speed }
}

/// The `(x, y)` coordinates, one per location.
pub fn coordinates(&self) -> &[(f64, f64)] {
&self.coordinates
}

/// The travel speed in distance units per time unit.
pub fn speed(&self) -> f64 {
self.speed
}

#[inline]
fn length(&self, from: usize, to: usize) -> Option<f64> {
let (from_x, from_y) = *self.coordinates.get(from)?;
let (to_x, to_y) = *self.coordinates.get(to)?;
let (dx, dy) = (to_x - from_x, to_y - from_y);
Some((dx * dx + dy * dy).sqrt())
}
}

impl RouteMetric for EuclideanMetric {
#[inline]
fn distance(&self, from: usize, to: usize) -> Option<i64> {
self.length(from, to).map(|length| length.round() as i64)
}

#[inline]
fn travel_time(&self, from: usize, to: usize) -> Option<i64> {
self.length(from, to)
.map(|length| (length / self.speed).round() as i64)
}

fn covers(&self, _route: &[usize], _depot: usize, max_node: usize) -> bool {
max_node < self.coordinates.len()
}
}
Loading
Loading