1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use crate::instance::Instance;
use crate::solution::{Solution, route_distance};
use highs::{Col, HighsModelStatus, RowProblem, Sense};
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
/// Maximum routes in the pool.
const MAX_POOL_SIZE: usize = 100_000;
/// Vehicle cost in objective (hierarchical: minimize vehicles >> minimize distance).
/// Must dominate any realistic route distance.
const VEHICLE_COST: f64 = 1e6;
/// MIP time limit in seconds.
const MIP_TIME_LIMIT: f64 = 5.0;
/// Pool of feasible routes found during the search.
/// Used to solve a Set Covering MIP (Goeke 2019, Section 3.6, equations 32–36).
pub struct RoutePool {
/// Stored routes with depot endpoints [0, ..., 0].
routes: Vec<Vec<usize>>,
/// Distance of each route.
distances: Vec<f64>,
/// Sorted pickup signature per route (used for fast dominance pruning).
pickup_signatures: Vec<Vec<usize>>,
/// Hash of sorted pickup signature per route (for fast grouping).
pickup_signature_hashes: Vec<u64>,
/// Deduplication: set of route interiors (customers without depots).
seen: HashSet<Vec<usize>>,
/// For each pickup node p, list of pool indices of routes containing p.
pickup_routes: Vec<Vec<usize>>,
/// Number of customer nodes (inst.n).
n: usize,
/// List of pickup node IDs.
pickups: Vec<usize>,
/// True if new routes were added since the last SC solve.
dirty: bool,
/// Number of newly added routes since the last SC solve.
new_since_solve: usize,
}
impl RoutePool {
pub fn new(inst: &Instance) -> Self {
RoutePool {
routes: Vec::new(),
distances: Vec::new(),
pickup_signatures: Vec::new(),
pickup_signature_hashes: Vec::new(),
seen: HashSet::new(),
pickup_routes: vec![Vec::new(); inst.n + 1],
n: inst.n,
pickups: inst.pickups.clone(),
dirty: false,
new_since_solve: 0,
}
}
/// Add all routes from a solution to the pool.
pub fn add_solution(&mut self, inst: &Instance, sol: &Solution) {
for route in &sol.routes {
self.add_route(inst, route);
}
}
fn add_route(&mut self, inst: &Instance, route: &[usize]) {
if route.len() <= 2 || self.routes.len() >= MAX_POOL_SIZE {
return;
}
let interior = &route[1..route.len() - 1];
if self.seen.contains(interior) {
return; // duplicate
}
self.seen.insert(interior.to_vec());
let dist = route_distance(inst, route);
let idx = self.routes.len();
// Index by pickup nodes only (delivery is always in the same route)
let mut pickup_signature: Vec<usize> = Vec::new();
for &v in &route[1..route.len() - 1] {
if inst.is_pickup(v) {
self.pickup_routes[v].push(idx);
pickup_signature.push(v);
}
}
pickup_signature.sort_unstable();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
pickup_signature.hash(&mut hasher);
let pickup_signature_hash = hasher.finish();
self.routes.push(route.to_vec());
self.distances.push(dist);
self.pickup_signatures.push(pickup_signature);
self.pickup_signature_hashes.push(pickup_signature_hash);
self.dirty = true;
self.new_since_solve += 1;
}
pub fn len(&self) -> usize {
self.routes.len()
}
pub fn is_empty(&self) -> bool {
self.routes.is_empty()
}
/// Returns true if new routes were added since the last SC solve.
pub fn has_new_routes(&self) -> bool {
self.dirty
}
/// Number of routes added since the last SC solve.
pub fn new_routes_since_solve(&self) -> usize {
self.new_since_solve
}
/// Solve the set partitioning MIP with the default time limit.
/// `best` is the current best solution, used as objective cutoff.
pub fn solve(&mut self, inst: &Instance, best: &Solution) -> Option<Solution> {
self.dirty = false;
self.new_since_solve = 0;
let cutoff = Self::sc_cost(best, inst);
self.solve_with_limit(inst, MIP_TIME_LIMIT, cutoff)
}
/// Solve the set partitioning MIP with an extended time limit (for final solve).
/// `best` is the current best solution, used as objective cutoff.
pub fn solve_final(&mut self, inst: &Instance, best: &Solution) -> Option<Solution> {
self.dirty = false;
self.new_since_solve = 0;
let cutoff = Self::sc_cost(best, inst);
self.solve_with_limit(inst, 10.0, cutoff)
}
/// Compute which routes are non-dominated ("active") for the MIP.
/// Two routes with the same pickup set → keep only the shortest.
fn compute_active_routes(&self) -> Vec<bool> {
let num_routes = self.routes.len();
let mut active = vec![true; num_routes];
// Single pass: keep only the shortest route for each signature.
// Group first by precomputed signature hash; on hash collisions compare actual signatures.
let mut best_by_hash: HashMap<u64, Vec<usize>> = HashMap::new();
for r in 0..num_routes {
let sig_hash = self.pickup_signature_hashes[r];
let sig = &self.pickup_signatures[r];
let bucket = best_by_hash.entry(sig_hash).or_default();
let mut matched_pos: Option<usize> = None;
for (pos, &best_r) in bucket.iter().enumerate() {
if self.pickup_signatures[best_r] == *sig {
matched_pos = Some(pos);
break;
}
}
if let Some(pos) = matched_pos {
let best_r = bucket[pos];
if self.distances[r] < self.distances[best_r] {
active[best_r] = false;
bucket[pos] = r;
} else {
active[r] = false;
}
} else {
bucket.push(r);
}
}
active
}
/// Solve the LP relaxation of the Set Cover problem and return per-node
/// shadow prices (dual values). Routes use distance-only cost (no VEHICLE_COST)
/// so that duals give meaningful differentiation between pickups.
///
/// Returns a vector of length `inst.n + 1` indexed by node ID.
/// `result[p]` = shadow price for pickup `p`; 0.0 for non-pickup nodes.
#[allow(clippy::cast_precision_loss)]
pub fn solve_lp_duals(&self, inst: &Instance) -> Option<Vec<f64>> {
if self.routes.is_empty() {
return None;
}
// Check that all pickups are covered by at least one route in the pool
for &p in &self.pickups {
if self.pickup_routes[p].is_empty() {
return None;
}
}
let num_routes = self.routes.len();
let active = self.compute_active_routes();
let mut pb = RowProblem::default();
// Map pool index → LP column (only for active routes)
let mut pool_to_col: Vec<Option<Col>> = vec![None; num_routes];
for r in 0..num_routes {
if !active[r] {
continue;
}
// Distance-only cost: no VEHICLE_COST so duals differentiate meaningfully
let cost = self.distances[r];
let col = pb.add_column(cost, 0.0..=1.0); // continuous variable
pool_to_col[r] = Some(col);
}
// Covering constraints: for each pickup p, Σ_{r: p∈r} y_r >= 1
let mut coeffs: Vec<(Col, f64)> = Vec::new();
let mut constraint_to_pickup: Vec<usize> = Vec::new();
for &p in &self.pickups {
coeffs.clear();
coeffs.extend(
self.pickup_routes[p]
.iter()
.filter_map(|&r_idx| pool_to_col[r_idx].map(|col| (col, 1.0))),
);
if coeffs.is_empty() {
continue; // should not happen given the check above
}
pb.add_row(1.0..=f64::INFINITY, &coeffs);
constraint_to_pickup.push(p);
}
let mut model = pb.optimise(Sense::Minimise);
model.set_option("time_limit", 2.0);
model.set_option("threads", 4);
model.set_option("output_flag", false);
let Ok(solved) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| model.solve()))
else {
return None;
};
if solved.status() != HighsModelStatus::Optimal {
return None;
}
let solution = solved.get_solution();
let dual_rows = solution.dual_rows();
// Map constraint duals to per-node vector
let mut result = vec![0.0_f64; inst.n + 1];
for (constraint_idx, &pickup) in constraint_to_pickup.iter().enumerate() {
if constraint_idx < dual_rows.len() {
// LP duals for >= constraints are non-negative in a minimization;
// take absolute value for robustness against solver sign conventions.
result[pickup] = dual_rows[constraint_idx].abs();
}
}
Some(result)
}
/// Compute the SC objective value for a solution.
#[allow(clippy::cast_precision_loss)]
fn sc_cost(sol: &Solution, inst: &Instance) -> f64 {
sol.num_vehicles() as f64 * VEHICLE_COST + sol.total_distance(inst)
}
/// Solve the set partitioning MIP and return a solution if one is found.
///
/// Formulation (Goeke 2019, equations 32–36, with = instead of >=):
/// min Σ (VEHICLE_COST + c_r) · y_r (hierarchical objective)
/// s.t. Σ_{r: p∈r} y_r = 1 ∀ pickup p (each PD pair covered exactly once)
/// y_r ∈ {0, 1} (binary selection)
///
/// `cutoff` is an upper bound — only solutions strictly better are accepted.
fn solve_with_limit(&self, inst: &Instance, time_limit: f64, cutoff: f64) -> Option<Solution> {
if self.routes.is_empty() {
return None;
}
// Check that all pickups are covered by at least one route in the pool
for &p in &self.pickups {
if self.pickup_routes[p].is_empty() {
return None;
}
}
let num_routes = self.routes.len();
// Prune dominated routes: for routes with identical pickup sets,
// keep only the one with minimum distance.
let active = self.compute_active_routes();
let active_count = active.iter().filter(|&&a| a).count();
let mut pb = RowProblem::default();
// Map pool index → MIP column (only for active routes)
let mut pool_to_col: Vec<Option<Col>> = vec![None; num_routes];
let mut col_to_pool: Vec<usize> = Vec::with_capacity(active_count);
for r in 0..num_routes {
if !active[r] {
continue;
}
let cost = VEHICLE_COST + self.distances[r];
let col = pb.add_integer_column(cost, 0..=1);
pool_to_col[r] = Some(col);
col_to_pool.push(r);
}
// Partitioning constraints: for each pickup p, Σ_{r: p∈r} y_r = 1
let mut coeffs: Vec<(Col, f64)> = Vec::new();
for &p in &self.pickups {
coeffs.clear();
coeffs.extend(
self.pickup_routes[p]
.iter()
.filter_map(|&r_idx| pool_to_col[r_idx].map(|col| (col, 1.0))),
);
pb.add_row(1.0..=1.0, &coeffs);
}
// Solve MIP with time limit and objective cutoff
let mut model = pb.optimise(Sense::Minimise);
model.set_option("time_limit", time_limit);
model.set_option("objective_target", cutoff - 1e-6);
model.set_option("output_flag", false); // suppress HiGHS logs
model.set_option("threads", 4);
model.set_option("presolve", "on");
model.set_option("mip_rel_gap", 0.001); // 0.1% optimality gap is good enough
let Ok(solved) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| model.solve()))
else {
eprintln!(" SC: HiGHS panicked, skipping");
return None;
};
let status = solved.status();
// Accept optimal or time-limit-with-incumbent
if status != HighsModelStatus::Optimal && status != HighsModelStatus::ReachedTimeLimit {
return None;
}
let solution = solved.get_solution();
let primal = solution.columns();
// When ReachedTimeLimit, HiGHS may return LP relaxation values rather than
// an integer incumbent. Verify all selected variables are binary (0 or 1).
if status == HighsModelStatus::ReachedTimeLimit {
let all_binary = primal.iter().all(|&v| !(0.01..=0.99).contains(&v));
if !all_binary {
return None; // fractional LP solution, not a valid integer incumbent
}
}
// Extract selected pool indices (map MIP columns back to pool indices)
let mut selected_pool_indices: Vec<usize> = Vec::new();
for (col_idx, &pool_idx) in col_to_pool.iter().enumerate() {
if primal[col_idx] > 0.5 {
selected_pool_indices.push(pool_idx);
}
}
if selected_pool_indices.is_empty() {
return None;
}
// Verify all pickups are covered exactly once (partitioning).
let mut covered_pickups = vec![false; self.n + 1];
for &pool_idx in &selected_pool_indices {
for &p in &self.pickup_signatures[pool_idx] {
if covered_pickups[p] {
return None; // duplicate coverage — not a valid partition
}
covered_pickups[p] = true;
}
}
for &p in &self.pickups {
if !covered_pickups[p] {
return None; // incomplete solution
}
}
let selected_routes: Vec<Vec<usize>> = selected_pool_indices
.iter()
.map(|&pool_idx| self.routes[pool_idx].clone())
.collect();
let sc_sol = Solution {
routes: selected_routes,
unassigned: Vec::new(),
};
let nv = sc_sol.num_vehicles();
let dist = sc_sol.total_distance(inst);
eprintln!(
" SC: {active_count}/{num_routes} routes → {nv} vehicles, dist={dist:.2} ({status:?})",
);
Some(sc_sol)
}
}