From 3758d7c2e2bc9aa522ed3e650c0f78450cbd9fdc Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 13 Nov 2026 04:12:08 +0100 Subject: [PATCH] feat(cvrp)!: read leg distances through a pluggable route metric ProblemData required two dense tables, distance_matrix and travel_times, so the stock domain = "cvrp" profile needed 16 bytes per stop pair: 1.6 GB at 10k stops and 40 GB at 50k, before any solving. ProblemData now holds a `metric: M` whose RouteMetric implementation answers distance, travel_time and whether a route's legs are all defined. VrpSolution names it with `type Metric`. The stock helpers, both meters and the route checks read legs only through it, monomorphized per metric, with the same UNREACHABLE and negative-value semantics. - DenseMatrix holds the supplied [from][to] tables unchanged, rows of any length included; existing models migrate to it. - EuclideanMetric computes legs on demand from coordinates and a speed (TSPLIB EUC_2D: sqrt(dx^2 + dy^2) rounded half away from zero, travel time = length / speed rounded the same way), in memory linear in the stops. The facade re-exports RouteMetric, DenseMatrix and EuclideanMetric. Routes and scores are unchanged: Clarke-Wright construction on all 100 X instances and Clarke-Wright plus 200 local-search steps on X-n101, X-n181 and X-n228 give identical routes and scores against main, with DenseMatrix and with EuclideanMetric. Local-search instruction counts change by -0.19%, -0.05% and -0.04%. Refs #252 BREAKING CHANGE: ProblemData's distance_matrix and travel_times fields are replaced by `metric`, and VrpSolution gains `type Metric: RouteMetric`. Migrate with `metric: DenseMatrix::new(distance_matrix, travel_times)` and `type Metric = DenseMatrix;`. --- crates/solverforge-cvrp/README.md | 2 +- crates/solverforge-cvrp/WIREFRAME.md | 50 ++++- crates/solverforge-cvrp/src/helpers.rs | 31 +--- crates/solverforge-cvrp/src/lib.rs | 12 +- crates/solverforge-cvrp/src/metric.rs | 135 ++++++++++++++ crates/solverforge-cvrp/src/metric_tests.rs | 171 ++++++++++++++++++ crates/solverforge-cvrp/src/problem_data.rs | 35 ++-- crates/solverforge-cvrp/src/solution.rs | 7 +- crates/solverforge-cvrp/src/tests.rs | 56 +++--- .../tests/ui/pass/list_cvrp_domain.rs | 4 +- .../ui/pass/list_cvrp_euclidean_domain.rs | 55 ++++++ crates/solverforge/WIREFRAME.md | 1 + crates/solverforge/src/cvrp.rs | 4 +- .../domain/publication_plan.rs | 7 +- .../domain/plan.rs | 7 +- .../list_k_opt_construction/domain/plan.rs | 7 +- docs/modeling.md | 13 +- 17 files changed, 506 insertions(+), 91 deletions(-) create mode 100644 crates/solverforge-cvrp/src/metric.rs create mode 100644 crates/solverforge-cvrp/src/metric_tests.rs create mode 100644 crates/solverforge-macros/tests/ui/pass/list_cvrp_euclidean_domain.rs diff --git a/crates/solverforge-cvrp/README.md b/crates/solverforge-cvrp/README.md index 6e07d322d..f0dce7e0e 100644 --- a/crates/solverforge-cvrp/README.md +++ b/crates/solverforge-cvrp/README.md @@ -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). diff --git a/crates/solverforge-cvrp/WIREFRAME.md b/crates/solverforge-cvrp/WIREFRAME.md index 1820e95dd..9b1b4880f 100644 --- a/crates/solverforge-cvrp/WIREFRAME.md +++ b/crates/solverforge-cvrp/WIREFRAME.md @@ -17,6 +17,8 @@ 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 @@ -24,9 +26,10 @@ src/ ## Types -### `ProblemData` +### `ProblemData` -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: @@ -35,25 +38,56 @@ Fields: | `capacity` | `i64` | Vehicle capacity | | `depot` | `usize` | Depot node index | | `demands` | `Vec` | Demand per node | -| `distance_matrix` | `Vec>` | Distance matrix | +| `metric` | `M` | Leg distances and travel times (`RouteMetric`) | | `time_windows` | `Vec<(i64, i64)>` | `(min_start, max_end)` per node | | `service_durations` | `Vec` | Service duration per node | -| `travel_times` | `Vec>` | 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` | 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 | + +### `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>` and `travel_times: Vec>`. +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>` | | `vehicle_visits` | `fn(&self, entity_idx: usize) -> &[usize]` | | `vehicle_visits_mut` | `fn(&mut self, entity_idx: usize) -> &mut Vec` | | `vehicle_count` | `fn(&self) -> usize` | @@ -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`. `#[derive(Clone, Debug, Default)]`. +Cross-entity distance meter backed by the vehicles' `RouteMetric` distances. Implements `CrossEntityDistanceMeter`. `#[derive(Clone, Debug, Default)]`. ### `MatrixIntraDistanceMeter` -Intra-entity distance meter backed by the solution's distance matrix. Implements `CrossEntityDistanceMeter`. `#[derive(Clone, Debug, Default)]`. +Intra-entity distance meter backed by the vehicle's `RouteMetric` distances. Implements `CrossEntityDistanceMeter`. `#[derive(Clone, Debug, Default)]`. ## Free Functions diff --git a/crates/solverforge-cvrp/src/helpers.rs b/crates/solverforge-cvrp/src/helpers.rs index 3e93d2997..e86dfb070 100644 --- a/crates/solverforge-cvrp/src/helpers.rs +++ b/crates/solverforge-cvrp/src/helpers.rs @@ -1,10 +1,10 @@ -use crate::{ProblemData, VrpSolution}; +use crate::{ProblemData, RouteMetric, VrpSolution}; #[inline] pub(crate) fn problem_data_for_entity( plan: &S, entity_idx: usize, -) -> Option<&ProblemData> { +) -> Option<&ProblemData> { if entity_idx >= plan.vehicle_count() { return None; } @@ -20,7 +20,7 @@ pub(crate) fn problem_data_for_entity( fn optional_problem_data_for_entity( plan: &S, entity_idx: usize, -) -> Option<&ProblemData> { +) -> Option<&ProblemData> { if entity_idx >= plan.vehicle_count() { return None; } @@ -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(route: &[usize], data: &ProblemData) -> bool { let Some(max_visit) = route.iter().copied().max() else { return true; }; @@ -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(route: &[usize], data: &ProblemData) -> bool { let mut total = 0_i64; for &visit in route { let demand = i64::from(data.demands[visit]); @@ -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(route: &[usize], data: &ProblemData) -> bool { let mut current_time = data.vehicle_departure_time; let mut previous = data.depot; diff --git a/crates/solverforge-cvrp/src/lib.rs b/crates/solverforge-cvrp/src/lib.rs index c8525466a..1e6a4175e 100644 --- a/crates/solverforge-cvrp/src/lib.rs +++ b/crates/solverforge-cvrp/src/lib.rs @@ -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; @@ -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; diff --git a/crates/solverforge-cvrp/src/metric.rs b/crates/solverforge-cvrp/src/metric.rs new file mode 100644 index 000000000..5eb030bfe --- /dev/null +++ b/crates/solverforge-cvrp/src/metric.rs @@ -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; + + /// Travel time from `from` to `to`; `None` when either is outside the + /// metric. + fn travel_time(&self, from: usize, to: usize) -> Option; + + /// 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>, + /// Travel time from location `[from][to]`. + pub travel_times: Vec>, +} + +impl DenseMatrix { + /// Builds the metric from a distance table and a travel-time table. + pub fn new(distances: Vec>, travel_times: Vec>) -> Self { + Self { + distances, + travel_times, + } + } +} + +impl RouteMetric for DenseMatrix { + #[inline] + fn distance(&self, from: usize, to: usize) -> Option { + self.distances.get(from)?.get(to).copied() + } + + #[inline] + fn travel_time(&self, from: usize, to: usize) -> Option { + 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 { + 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 { + self.length(from, to).map(|length| length.round() as i64) + } + + #[inline] + fn travel_time(&self, from: usize, to: usize) -> Option { + 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() + } +} diff --git a/crates/solverforge-cvrp/src/metric_tests.rs b/crates/solverforge-cvrp/src/metric_tests.rs new file mode 100644 index 000000000..8e22177bb --- /dev/null +++ b/crates/solverforge-cvrp/src/metric_tests.rs @@ -0,0 +1,171 @@ +use super::*; +use solverforge_solver::CrossEntityDistanceMeter; + +struct Fleet { + data: ProblemData, + routes: Vec>, +} + +impl VrpSolution for Fleet { + type Metric = M; + + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { + Some(&self.data) + } + + fn vehicle_visits(&self, entity_idx: usize) -> &[usize] { + &self.routes[entity_idx] + } + + fn vehicle_visits_mut(&mut self, entity_idx: usize) -> &mut Vec { + &mut self.routes[entity_idx] + } + + fn vehicle_count(&self) -> usize { + self.routes.len() + } +} + +fn coordinates() -> Vec<(f64, f64)> { + vec![ + (0.0, 0.0), + (3.0, 4.0), + (6.0, 8.0), + (0.5, 0.0), + (-2.5, 0.0), + (1.0, 1.0), + ] +} + +fn problem_data(metric: M) -> ProblemData { + ProblemData { + capacity: 9, + depot: 0, + demands: vec![0, 2, 3, 4, 1, 2], + metric, + time_windows: vec![(0, 100), (0, 40), (5, 60), (0, 30), (0, 50), (0, 70)], + service_durations: vec![0, 2, 2, 3, 1, 1], + vehicle_departure_time: 0, + } +} + +/// The dense tables an `EuclideanMetric` stands for, built from its own legs. +fn tabulated(metric: &EuclideanMetric) -> DenseMatrix { + let n = metric.coordinates().len(); + let table = |leg: &dyn Fn(usize, usize) -> Option| -> Vec> { + (0..n) + .map(|from| (0..n).map(|to| leg(from, to).unwrap()).collect()) + .collect() + }; + DenseMatrix::new( + table(&|from, to| metric.distance(from, to)), + table(&|from, to| metric.travel_time(from, to)), + ) +} + +#[test] +fn euclidean_legs_round_half_away_from_zero() { + let metric = EuclideanMetric::new(coordinates(), 2.0); + + assert_eq!(metric.distance(0, 1), Some(5)); + assert_eq!(metric.distance(1, 2), Some(5)); + assert_eq!(metric.distance(0, 2), Some(10)); + assert_eq!(metric.distance(0, 3), Some(1)); + assert_eq!(metric.distance(0, 4), Some(3)); + assert_eq!(metric.distance(0, 5), Some(1)); + assert_eq!(metric.travel_time(0, 1), Some(3)); + assert_eq!(metric.travel_time(0, 2), Some(5)); + assert_eq!(metric.travel_time(0, 3), Some(0)); + assert_eq!(metric.distance(3, 3), Some(0)); +} + +#[test] +fn euclidean_legs_outside_the_coordinates_are_undefined() { + let metric = EuclideanMetric::new(coordinates(), 1.0); + + assert_eq!(metric.distance(0, 6), None); + assert_eq!(metric.travel_time(6, 0), None); + assert!(metric.covers(&[1, 5], 0, 5)); + assert!(!metric.covers(&[1, 6], 0, 6)); +} + +#[test] +#[should_panic(expected = "speed must be finite and positive")] +fn euclidean_metric_rejects_a_non_positive_speed() { + EuclideanMetric::new(coordinates(), 0.0); +} + +#[test] +#[should_panic(expected = "coordinates must be finite")] +fn euclidean_metric_rejects_non_finite_coordinates() { + EuclideanMetric::new(vec![(0.0, f64::NAN)], 1.0); +} + +#[test] +fn dense_matrix_covers_exactly_the_supplied_rows() { + let metric = DenseMatrix::new( + vec![vec![0, 1, 2], vec![1, 0, 3], vec![2, 3]], + vec![vec![0, 1, 2], vec![1, 0, 3], vec![2, 3, 0]], + ); + + assert!(metric.covers(&[1], 0, 2)); + assert!(!metric.covers(&[2], 0, 2)); + assert!(!metric.covers(&[3], 0, 3)); + assert_eq!(metric.distance(2, 2), None); + assert_eq!(metric.travel_time(2, 2), Some(0)); +} + +#[test] +fn euclidean_metric_answers_every_stock_helper_like_its_tabulated_matrix() { + let euclidean = EuclideanMetric::new(coordinates(), 2.0); + let dense = tabulated(&euclidean); + let routes = vec![vec![1, 2], vec![3, 4, 5], vec![2, 5, 1, 3], vec![]]; + let on_demand = Fleet { + data: problem_data(euclidean), + routes: routes.clone(), + }; + let tabled = Fleet { + data: problem_data(dense), + routes, + }; + let candidates: [&[usize]; 6] = [&[], &[1], &[1, 2], &[3, 4, 5], &[2, 5, 1, 3], &[5, 4, 3, 2]]; + + for entity in 0..on_demand.vehicle_count() { + assert_eq!( + route_distance(&on_demand, entity, 0, 0), + route_distance(&tabled, entity, 0, 0) + ); + for &route in &candidates { + assert_eq!( + route_feasible(&on_demand, entity, route), + route_feasible(&tabled, entity, route) + ); + assert_eq!( + savings_feasible(&on_demand, entity, route), + savings_feasible(&tabled, entity, route) + ); + } + for from in 0..6 { + for to in 0..6 { + assert_eq!( + route_distance(&on_demand, entity, from, to), + route_distance(&tabled, entity, from, to) + ); + assert_eq!( + savings_distance(&on_demand, entity, from, to), + savings_distance(&tabled, entity, from, to) + ); + } + } + } + for (src_entity, src_pos, dst_entity, dst_pos) in [(0, 0, 1, 2), (2, 3, 2, 0), (1, 1, 0, 1)] { + assert_eq!( + MatrixDistanceMeter.distance(&on_demand, src_entity, src_pos, dst_entity, dst_pos), + MatrixDistanceMeter.distance(&tabled, src_entity, src_pos, dst_entity, dst_pos) + ); + assert_eq!( + MatrixIntraDistanceMeter.distance(&on_demand, src_entity, src_pos, src_entity, dst_pos), + MatrixIntraDistanceMeter.distance(&tabled, src_entity, src_pos, src_entity, dst_pos) + ); + } +} diff --git a/crates/solverforge-cvrp/src/problem_data.rs b/crates/solverforge-cvrp/src/problem_data.rs index 7b229aaf0..ac4df69e0 100644 --- a/crates/solverforge-cvrp/src/problem_data.rs +++ b/crates/solverforge-cvrp/src/problem_data.rs @@ -1,3 +1,5 @@ +use crate::{DenseMatrix, RouteMetric}; + /// Matrix sentinel for a leg that cannot be traversed. /// /// Stock CVRP helpers treat this as non-evaluable route-local travel and as a @@ -11,49 +13,46 @@ pub(crate) const MAX_SAFE_LEG_COST: i64 = i64::MAX / 4; /// /// A solution typically holds it once (for example behind an `Arc`) and /// returns a reference from [`VrpSolution::vehicle_data`](crate::VrpSolution::vehicle_data), -/// so cloning vehicles during local search never copies the matrices. +/// so cloning vehicles during local search never copies the metric. Leg +/// distances and travel times come from `metric`: a [`DenseMatrix`] holds +/// supplied tables, an [`EuclideanMetric`](crate::EuclideanMetric) computes +/// legs from coordinates. #[derive(Clone, Debug)] -pub struct ProblemData { +pub struct ProblemData { /// Vehicle capacity, in the units of `demands`. pub capacity: i64, /// Location index of the depot every route starts and ends at. pub depot: usize, /// Demand of each location, indexed by location. pub demands: Vec, - /// Distance from location `[from][to]`; [`UNREACHABLE`] marks a leg that - /// cannot be traversed. - pub distance_matrix: Vec>, + /// Leg distances and travel times between locations. + pub metric: M, /// `(earliest, latest)` service start of each location. pub time_windows: Vec<(i64, i64)>, /// Service time spent at each location. pub service_durations: Vec, - /// Travel time from location `[from][to]`; [`UNREACHABLE`] marks a leg that - /// cannot be traversed. - pub travel_times: Vec>, /// Time each vehicle leaves the depot. pub vehicle_departure_time: i64, } -impl ProblemData { +impl ProblemData { #[inline] pub(crate) fn distance_cost(&self, from: usize, to: usize) -> i64 { - self.finite_matrix_value(&self.distance_matrix, from, to) - .unwrap_or(MAX_SAFE_LEG_COST) + self.finite_distance(from, to).unwrap_or(MAX_SAFE_LEG_COST) } #[inline] pub(crate) fn finite_distance(&self, from: usize, to: usize) -> Option { - self.finite_matrix_value(&self.distance_matrix, from, to) + finite(self.metric.distance(from, to)?) } #[inline] pub(crate) fn travel_time(&self, from: usize, to: usize) -> Option { - self.finite_matrix_value(&self.travel_times, from, to) + finite(self.metric.travel_time(from, to)?) } +} - #[inline] - fn finite_matrix_value(&self, matrix: &[Vec], from: usize, to: usize) -> Option { - let value = matrix.get(from)?.get(to).copied()?; - (value >= 0 && value != UNREACHABLE).then_some(value) - } +#[inline] +fn finite(value: i64) -> Option { + (value >= 0 && value != UNREACHABLE).then_some(value) } diff --git a/crates/solverforge-cvrp/src/solution.rs b/crates/solverforge-cvrp/src/solution.rs index 94b6f3860..cee8378ca 100644 --- a/crates/solverforge-cvrp/src/solution.rs +++ b/crates/solverforge-cvrp/src/solution.rs @@ -1,15 +1,18 @@ -use crate::ProblemData; +use crate::{ProblemData, RouteMetric}; /// Trait implemented by a planning solution that holds a fleet of vehicles, /// each with its `ProblemData` and a list of visited stops. pub trait VrpSolution { + /// Where the vehicles' leg distances and travel times come from. + type Metric: RouteMetric; + /// The problem data of vehicle `entity_idx`. /// /// Vehicles that share one `ProblemData` should return the same reference; /// Clarke-Wright then computes their savings once. `None` for an in-range /// vehicle is an initialization bug: the route and savings helpers panic /// on it, and the feasibility gates reject the route. - fn vehicle_data(&self, entity_idx: usize) -> Option<&ProblemData>; + fn vehicle_data(&self, entity_idx: usize) -> Option<&ProblemData>; /// The visit (element) indexes of vehicle `entity_idx`'s route, in order. fn vehicle_visits(&self, entity_idx: usize) -> &[usize]; /// Mutable access to vehicle `entity_idx`'s route. diff --git a/crates/solverforge-cvrp/src/tests.rs b/crates/solverforge-cvrp/src/tests.rs index e7d2b410c..850e42a98 100644 --- a/crates/solverforge-cvrp/src/tests.rs +++ b/crates/solverforge-cvrp/src/tests.rs @@ -32,25 +32,29 @@ fn base_problem_data() -> ProblemData { capacity: 10, depot: 0, demands: vec![0, 2, 3, 4], - distance_matrix: vec![ - vec![0, 5, 7, 9], - vec![5, 0, 4, 6], - vec![7, 4, 0, 3], - vec![9, 6, 3, 0], - ], + metric: DenseMatrix::new( + vec![ + vec![0, 5, 7, 9], + vec![5, 0, 4, 6], + vec![7, 4, 0, 3], + vec![9, 6, 3, 0], + ], + vec![ + vec![0, 5, 7, 9], + vec![5, 0, 4, 6], + vec![7, 4, 0, 3], + vec![9, 6, 3, 0], + ], + ), time_windows: vec![(0, 100), (0, 10), (7, 14), (0, 12)], service_durations: vec![0, 2, 2, 3], - travel_times: vec![ - vec![0, 5, 7, 9], - vec![5, 0, 4, 6], - vec![7, 4, 0, 3], - vec![9, 6, 3, 0], - ], vehicle_departure_time: 0, } } impl VrpSolution for TestSolution { + type Metric = DenseMatrix; + fn vehicle_data(&self, entity_idx: usize) -> Option<&ProblemData> { self.data.get(entity_idx) } @@ -69,6 +73,8 @@ impl VrpSolution for TestSolution { } impl VrpSolution for SharedDataSolution { + type Metric = DenseMatrix; + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { Some(&self.data) } @@ -91,6 +97,8 @@ struct NullDataSolution { } impl VrpSolution for NullDataSolution { + type Metric = DenseMatrix; + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { None } @@ -112,7 +120,7 @@ impl VrpSolution for NullDataSolution { fn helpers_use_problem_data_for_route_owner() { let mut owner_one_data = base_problem_data(); owner_one_data.depot = 3; - owner_one_data.distance_matrix[1][3] = 42; + owner_one_data.metric.distances[1][3] = 42; let solution = TestSolution::with_data( vec![vec![1, 2], vec![3]], vec![base_problem_data(), owner_one_data], @@ -183,8 +191,8 @@ fn clarke_wright_adapters_share_exact_cvrp_data_when_requested() { #[test] fn route_feasibility_rejects_unreachable_depot_leg_without_panic() { let mut data = base_problem_data(); - data.distance_matrix[0][1] = UNREACHABLE; - data.travel_times[0][1] = UNREACHABLE; + data.metric.distances[0][1] = UNREACHABLE; + data.metric.travel_times[0][1] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1]], vec![data]); let outcome = std::panic::catch_unwind(|| route_feasible(&solution, 0, &[1])); @@ -195,8 +203,8 @@ fn route_feasibility_rejects_unreachable_depot_leg_without_panic() { #[test] fn route_feasibility_rejects_unreachable_inter_visit_leg_without_panic() { let mut data = base_problem_data(); - data.distance_matrix[1][2] = UNREACHABLE; - data.travel_times[1][2] = UNREACHABLE; + data.metric.distances[1][2] = UNREACHABLE; + data.metric.travel_times[1][2] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1, 2]], vec![data]); let outcome = std::panic::catch_unwind(|| route_feasible(&solution, 0, &[1, 2])); @@ -207,8 +215,8 @@ fn route_feasibility_rejects_unreachable_inter_visit_leg_without_panic() { #[test] fn route_feasibility_rejects_unreachable_return_depot_leg_without_panic() { let mut data = base_problem_data(); - data.distance_matrix[1][0] = UNREACHABLE; - data.travel_times[1][0] = UNREACHABLE; + data.metric.distances[1][0] = UNREACHABLE; + data.metric.travel_times[1][0] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1]], vec![data]); let outcome = std::panic::catch_unwind(|| route_feasible(&solution, 0, &[1])); @@ -220,7 +228,7 @@ fn route_feasibility_rejects_unreachable_return_depot_leg_without_panic() { fn route_feasibility_rejects_time_overflow_without_wrapping() { let mut data = base_problem_data(); data.vehicle_departure_time = 20; - data.travel_times[0][1] = i64::MAX - 10; + data.metric.travel_times[0][1] = i64::MAX - 10; let solution = TestSolution::with_data(vec![vec![1]], vec![data]); assert!( @@ -245,8 +253,8 @@ fn route_feasibility_rejects_service_overflow_without_wrapping() { #[test] fn stock_savings_feasibility_stays_structural_for_unreachable_routes() { let mut data = base_problem_data(); - data.distance_matrix[0][1] = UNREACHABLE; - data.travel_times[0][1] = UNREACHABLE; + data.metric.distances[0][1] = UNREACHABLE; + data.metric.travel_times[0][1] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1]], vec![data]); assert!(savings_feasible(&solution, 0, &[1])); @@ -256,7 +264,7 @@ fn stock_savings_feasibility_stays_structural_for_unreachable_routes() { #[test] fn stock_distances_convert_unreachable_or_malformed_legs_to_finite_costs() { let mut data = base_problem_data(); - data.distance_matrix[0][1] = UNREACHABLE; + data.metric.distances[0][1] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1]], vec![data]); let unreachable_cost = route_distance(&solution, 0, 0, 1); @@ -398,7 +406,7 @@ fn distance_meters_cover_invalid_positions() { #[test] fn distance_meters_treat_unreachable_legs_as_infinite() { let mut data = base_problem_data(); - data.distance_matrix[1][2] = UNREACHABLE; + data.metric.distances[1][2] = UNREACHABLE; let solution = TestSolution::with_data(vec![vec![1, 2], vec![2]], vec![data.clone(), data]); assert!(MatrixDistanceMeter diff --git a/crates/solverforge-macros/tests/ui/pass/list_cvrp_domain.rs b/crates/solverforge-macros/tests/ui/pass/list_cvrp_domain.rs index e476ca7a8..35b487bcd 100644 --- a/crates/solverforge-macros/tests/ui/pass/list_cvrp_domain.rs +++ b/crates/solverforge-macros/tests/ui/pass/list_cvrp_domain.rs @@ -1,4 +1,4 @@ -use solverforge::cvrp::{ProblemData, VrpSolution}; +use solverforge::cvrp::{DenseMatrix, ProblemData, VrpSolution}; use solverforge::prelude::*; #[planning_entity] @@ -30,6 +30,8 @@ impl solverforge::__internal::PlanningSolution for Plan { } impl VrpSolution for Plan { + type Metric = DenseMatrix; + fn vehicle_data(&self, entity_idx: usize) -> Option<&ProblemData> { (entity_idx < self.vehicles.len()).then_some(&self.data) } diff --git a/crates/solverforge-macros/tests/ui/pass/list_cvrp_euclidean_domain.rs b/crates/solverforge-macros/tests/ui/pass/list_cvrp_euclidean_domain.rs new file mode 100644 index 000000000..c785c6ee0 --- /dev/null +++ b/crates/solverforge-macros/tests/ui/pass/list_cvrp_euclidean_domain.rs @@ -0,0 +1,55 @@ +use solverforge::cvrp::{EuclideanMetric, ProblemData, VrpSolution}; +use solverforge::prelude::*; + +#[planning_entity] +pub struct Vehicle { + #[planning_id] + pub id: usize, + + #[planning_list_variable(element_collection = "deliveries", domain = "cvrp")] + pub visits: Vec, +} + +#[derive(Clone)] +struct Plan { + vehicles: Vec, + data: ProblemData, + score: Option, +} + +impl solverforge::__internal::PlanningSolution for Plan { + type Score = HardSoftScore; + + fn score(&self) -> Option { + self.score + } + + fn set_score(&mut self, score: Option) { + self.score = score; + } +} + +impl VrpSolution for Plan { + type Metric = EuclideanMetric; + + fn vehicle_data(&self, entity_idx: usize) -> Option<&ProblemData> { + (entity_idx < self.vehicles.len()).then_some(&self.data) + } + + fn vehicle_visits(&self, entity_idx: usize) -> &[usize] { + &self.vehicles[entity_idx].visits + } + + fn vehicle_visits_mut(&mut self, entity_idx: usize) -> &mut Vec { + &mut self.vehicles[entity_idx].visits + } + + fn vehicle_count(&self) -> usize { + self.vehicles.len() + } +} + +fn main() { + let _metadata = + >::list_metadata(); +} diff --git a/crates/solverforge/WIREFRAME.md b/crates/solverforge/WIREFRAME.md index a5ab2230f..d14b8c27f 100644 --- a/crates/solverforge/WIREFRAME.md +++ b/crates/solverforge/WIREFRAME.md @@ -250,6 +250,7 @@ Module: `solverforge::cvrp` - `VrpSolution` (trait) - `ProblemData` +- `RouteMetric` (trait), `DenseMatrix`, `EuclideanMetric` - `UNREACHABLE` - `MatrixDistanceMeter` - `MatrixIntraDistanceMeter` diff --git a/crates/solverforge/src/cvrp.rs b/crates/solverforge/src/cvrp.rs index f24595146..c70e20383 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, MatrixDistanceMeter, MatrixIntraDistanceMeter, ProblemData, VrpSolution, - UNREACHABLE, + savings_metric_class, DenseMatrix, EuclideanMetric, MatrixDistanceMeter, + MatrixIntraDistanceMeter, ProblemData, RouteMetric, VrpSolution, UNREACHABLE, }; diff --git a/crates/solverforge/tests/list_clarke_wright_publication/domain/publication_plan.rs b/crates/solverforge/tests/list_clarke_wright_publication/domain/publication_plan.rs index c2e9b42ea..83eafeb65 100644 --- a/crates/solverforge/tests/list_clarke_wright_publication/domain/publication_plan.rs +++ b/crates/solverforge/tests/list_clarke_wright_publication/domain/publication_plan.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use solverforge::cvrp::ProblemData; +use solverforge::cvrp::{DenseMatrix, ProblemData}; use solverforge::prelude::*; use solverforge::stream::joiner::equal_bi; use solverforge::stream::ConstraintFactory; @@ -31,6 +31,8 @@ pub struct PublicationPlan { } impl solverforge::cvrp::VrpSolution for PublicationPlan { + type Metric = DenseMatrix; + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { Some(&self.shared) } @@ -85,10 +87,9 @@ pub fn build_plan(customer_count: usize, time_limit_secs: u64) -> PublicationPla demands: std::iter::once(0) .chain(std::iter::repeat_n(1, customer_count)) .collect(), - distance_matrix, + metric: DenseMatrix::new(distance_matrix, travel_times), time_windows: vec![(0, i64::MAX); dimension], service_durations: vec![0; dimension], - travel_times, vehicle_departure_time: 0, }); let data_addr = Arc::as_ptr(&shared) as usize; diff --git a/crates/solverforge/tests/list_cvrp_k_opt_time_window/domain/plan.rs b/crates/solverforge/tests/list_cvrp_k_opt_time_window/domain/plan.rs index 895d89d93..d354a32f2 100644 --- a/crates/solverforge/tests/list_cvrp_k_opt_time_window/domain/plan.rs +++ b/crates/solverforge/tests/list_cvrp_k_opt_time_window/domain/plan.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use solverforge::cvrp::ProblemData; +use solverforge::cvrp::{DenseMatrix, ProblemData}; use solverforge::prelude::*; use solverforge::SolverConfig; use solverforge::stream::ConstraintFactory; @@ -33,6 +33,8 @@ fn solver_config(solution: &Plan, _base: SolverConfig) -> SolverConfig { } impl solverforge::cvrp::VrpSolution for Plan { + type Metric = DenseMatrix; + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { Some(&self.shared) } @@ -93,10 +95,9 @@ pub fn build_plan() -> Plan { capacity: 100, depot: 0, demands: vec![0, 1, 1, 1, 1], - distance_matrix, + metric: DenseMatrix::new(distance_matrix, travel_times), time_windows: vec![(0, 100), (0, 100), (0, 100), (0, 5), (0, 100)], service_durations: vec![0; 5], - travel_times, vehicle_departure_time: 0, }); diff --git a/crates/solverforge/tests/list_k_opt_construction/domain/plan.rs b/crates/solverforge/tests/list_k_opt_construction/domain/plan.rs index 5b158b7f1..8a3e09ce0 100644 --- a/crates/solverforge/tests/list_k_opt_construction/domain/plan.rs +++ b/crates/solverforge/tests/list_k_opt_construction/domain/plan.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use solverforge::cvrp::ProblemData; +use solverforge::cvrp::{DenseMatrix, ProblemData}; use solverforge::prelude::*; use solverforge::stream::ConstraintFactory; @@ -21,6 +21,8 @@ pub struct Plan { } impl solverforge::cvrp::VrpSolution for Plan { + type Metric = DenseMatrix; + fn vehicle_data(&self, _entity_idx: usize) -> Option<&ProblemData> { Some(&self.shared) } @@ -75,10 +77,9 @@ pub fn sorting_plan() -> Plan { capacity: 100, depot: 0, demands: vec![0, 1, 1, 1, 1, 1, 1], - distance_matrix, + metric: DenseMatrix::new(distance_matrix, travel_times), time_windows, service_durations: vec![0; size], - travel_times, vehicle_departure_time: 0, }); Plan { diff --git a/docs/modeling.md b/docs/modeling.md index 5cf44ceed..e0e364bda 100644 --- a/docs/modeling.md +++ b/docs/modeling.md @@ -159,7 +159,18 @@ meters and two separate hook bundles: stay scoreable, so assignment remains score-comparable. The `solverforge-cvrp` crate holds `VrpSolution`, `ProblemData`, the distance -meters and those hook bundles. Custom routing domains omit `domain = "cvrp"` +meters and those hook bundles. `ProblemData` reads leg distances and travel +times from its `metric`, named by `VrpSolution::Metric`: + +- `DenseMatrix::new(distances, travel_times)` holds supplied `[from][to]` + tables, such as road-network matrices; memory grows with the square of the + location count. +- `EuclideanMetric::new(coordinates, speed)` computes straight-line legs on + demand (TSPLIB `EUC_2D`: `sqrt(dx² + dy²)` rounded half away from zero, + 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"` and supply their own `route_hooks` and `savings_hooks`; see [Extend the domain](extend-domain.md).