vrp_parser 0.1.0

A library for parsing VRPLib-formatted files.
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use crate::EdgeWeightKind;
use crate::ProblemType;
use crate::common::edge_weight::edge_weight_by_euc2d;
use crate::common::matrix::expand_lower_row;
use crate::vrplib::parser::SectionData;

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct VRPInstanceBuilder<T> {
    name: String,
    problem_type: ProblemType,
    edge_weight_kind: EdgeWeightKind,
    dimension: usize,
    depots: Vec<usize>,
    capacity: Option<T>,
    demands: Option<Vec<T>>,
    node_coords: Option<Vec<(f64, f64)>>,
    edge_weights: Option<Vec<Vec<T>>>,
}

/// Represents a fully constructed Vehicle Routing Problem (VRP) instance
/// loaded from a VRPLib file.
///
/// A `VRPInstance<T>` contains all data required to describe a VRP, including
/// problem metadata, node information, distance or cost matrices, and
/// problem‑specific attributes such as vehicle capacity and customer demands.
/// The type parameter `T` determines the numeric representation used for values
/// such as edge weights and demands. Common choices include `u64` for standard
/// VRPLib instances.
///
/// This structure is created only after successful parsing and validation of
/// a VRPLib file. All fields therefore represent a semantically consistent
/// instance. Optional fields are present only for problem types that require
/// them (e.g., capacity and demands for [`ProblemType::CVRP`]).
///
/// Edge weights are stored as a fully expanded matrix, regardless of the
/// original VRPLib representation.
///
/// # Type Parameters
/// - `T`: The numeric type representing values such as edge weights and demands.
///   Typically:
///   - `u64`: The standard VRPLib-compliant integer representation.
///
/// # Fields
/// - `name`: The instance name as specified in the VRPLib file.
/// - `problem_type`: The VRP variant (see [`ProblemType`]).
/// - `dimension`: The number of nodes in the instance.
/// - `depots`: Indices of depot nodes.
/// - `edge_weights`: A fully expanded distance or cost matrix.
/// - `capacity`: Vehicle capacity (if applicable).
/// - `demands`: Customer demands for each node (if applicable).
/// - `node_coords`: Node coordinates (if provided in the VRPLib file).
///
/// A `VRPInstance` is immutable after construction and can be used directly
/// by solvers, heuristics, or analysis tools.
#[derive(Debug, Clone, PartialEq)]
pub struct VRPInstance<T> {
    name: String,
    problem_type: ProblemType,
    dimension: usize,
    depots: Vec<usize>,
    edge_weights: Vec<Vec<T>>,
    capacity: Option<T>,
    demands: Option<Vec<T>>,
    node_coords: Option<Vec<(f64, f64)>>,
}

#[derive(Debug, PartialEq, thiserror::Error)]
pub enum ValidationError {
    #[error("missing capacity")]
    MissingCapacity,
    #[error("missing demands")]
    MissingDemands,
    #[error("missing depots")]
    MissingDepots,
    #[error("missing edge weight")]
    MissingEdgeWeight,
    #[error("missing node coords")]
    MissingNodeCoords,
    #[error("invalid demands length")]
    InvalidDemandsLength,
}

impl VRPInstanceBuilder<u64> {
    pub fn new(
        name: String,
        problem_type: ProblemType,
        dimension: usize,
        edge_weight_kind: EdgeWeightKind,
    ) -> Self {
        Self {
            name,
            problem_type,
            edge_weight_kind,
            dimension,
            depots: vec![],
            capacity: None,
            demands: None,
            node_coords: None,
            edge_weights: None,
        }
    }

    pub fn depots(mut self, depots: Vec<usize>) -> Self {
        self.depots = depots;
        self
    }

    pub fn capacity(mut self, capacity: Option<u64>) -> Self {
        self.capacity = capacity;
        self
    }

    pub fn demands(mut self, demands: Option<Vec<u64>>) -> Self {
        self.demands = demands;
        self
    }

    pub fn node_coords(mut self, node_coords: Option<Vec<(f64, f64)>>) -> Self {
        self.node_coords = node_coords;
        self
    }
    pub fn edge_weights(mut self, edge_weights: Option<Vec<Vec<u64>>>) -> Self {
        self.edge_weights = edge_weights;
        self
    }

    pub fn build(self) -> Result<VRPInstance<u64>, ValidationError> {
        let edge_weights = match self.edge_weight_kind {
            EdgeWeightKind::LowerRow => {
                self.edge_weights
                    .as_ref()
                    .ok_or(ValidationError::MissingEdgeWeight)?;
                expand_lower_row(self.edge_weights.as_ref().unwrap())
            }
            EdgeWeightKind::Euc2D => self
                .node_coords
                .as_ref()
                .ok_or(ValidationError::MissingNodeCoords)?
                .iter()
                .map(|&p| {
                    self.node_coords
                        .as_ref()
                        .unwrap()
                        .iter()
                        .map(|&q| edge_weight_by_euc2d(p, q))
                        .collect()
                })
                .collect(),
        };

        if self.depots.is_empty() {
            return Err(ValidationError::MissingDepots);
        }

        match self.problem_type {
            ProblemType::CVRP => {
                self.capacity
                    .as_ref()
                    .ok_or(ValidationError::MissingCapacity)?;
                self.demands
                    .as_ref()
                    .ok_or(ValidationError::MissingDemands)?;

                self.validate_demands()?;

                Ok(VRPInstance::new(
                    self.name,
                    self.problem_type,
                    self.dimension,
                    self.depots,
                    edge_weights,
                    self.capacity,
                    self.demands,
                    self.node_coords,
                ))
            }
        }
    }

    fn validate_demands(&self) -> Result<(), ValidationError> {
        if let Some(demands) = &self.demands
            && demands.len() != self.dimension
        {
            return Err(ValidationError::InvalidDemandsLength);
        }
        Ok(())
    }

    pub(crate) fn make_from_vrplib(section_data: SectionData) -> Self {
        let name = section_data.name.unwrap();
        let edge_weight_kind = EdgeWeightKind::new(
            section_data.edge_weight_type.unwrap(),
            section_data.edge_weight_format,
        )
        .unwrap();
        let depots = section_data.depots.iter().map(|depot| depot[0]).collect();
        let demands = section_data
            .demands
            .iter()
            .map(|demand| demand[1])
            .collect();
        let node_coords = section_data
            .node_coords
            .iter()
            .map(|coords| (coords[0], coords[1]))
            .collect();

        Self::new(
            name,
            section_data.problem_type.unwrap(),
            section_data.dimension.unwrap(),
            edge_weight_kind,
        )
        .depots(depots)
        .capacity(section_data.capacity)
        .demands(Some(demands))
        .node_coords(Some(node_coords))
        .edge_weights(Some(section_data.edge_weights))
    }
}

impl<T> VRPInstance<T> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        name: String,
        problem_type: ProblemType,
        dimension: usize,
        depots: Vec<usize>,
        edge_weights: Vec<Vec<T>>,
        capacity: Option<T>,
        demands: Option<Vec<T>>,
        node_coords: Option<Vec<(f64, f64)>>,
    ) -> Self {
        Self {
            name,
            problem_type,
            dimension,
            depots,
            edge_weights,
            capacity,
            demands,
            node_coords,
        }
    }

    /// Returns the name of the instance as specified in the VRPLib file
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the problem type of this instance.
    ///
    /// See [`ProblemType`] for supported variants.
    pub fn problem_type(&self) -> ProblemType {
        self.problem_type
    }

    /// Returns the number of nodes in the instance (`DIMENSION` in VRPLib).
    pub fn dimension(&self) -> usize {
        self.dimension
    }
    /// Returns the list of node coordinates, if provided.
    ///
    /// Coordinate‑based VRPLib instances (e.g., `EUC_2D`, `GEO`) include
    /// coordinates for each node. For explicit edge‑weight matrices, this
    /// field is `None`.
    pub fn node_coords(&self) -> &Option<Vec<(f64, f64)>> {
        &self.node_coords
    }

    /// Returns the demand value for each node, if applicable.
    ///
    /// This field is present for problem types that require customer demands,
    /// such as [`ProblemType::CVRP`]. For other problem types, it is `None`.
    pub fn demands(&self) -> &Option<Vec<T>> {
        &self.demands
    }

    /// Returns the vehicle capacity, if defined for this instance.
    ///
    /// Capacity is required for capacitated VRP variants such as
    /// [`ProblemType::CVRP`]. For problem types without capacity constraints,
    /// this field is `None`.
    pub fn capacity(&self) -> &Option<T> {
        &self.capacity
    }

    /// Returns the indices of depot nodes.
    ///
    /// VRPLib allows multiple depots.
    /// The indices refer to node positions in the instance.
    pub fn depots(&self) -> &[usize] {
        &self.depots
    }

    /// Returns the fully expanded edge‑weight matrix.
    ///
    /// Regardless of the original VRPLib representation (explicit matrix,
    /// compressed format, or coordinate‑based type), this method returns a
    /// complete `dimension × dimension` matrix of edge weights.
    pub fn edge_weights(&self) -> &[Vec<T>] {
        &self.edge_weights
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::vrplib::edge_weight_format::EdgeWeightFormat;
    use crate::vrplib::edge_weight_type::EdgeWeightType;
    use crate::vrplib::node_coord_type::NodeCoordType;

    #[test]
    fn test_make_from_vrplib() {
        let sut = SectionData {
            name: Some("This is a name.".to_string()),
            problem_type: Some(ProblemType::CVRP),
            dimension: Some(3),
            edge_weight_type: Some(EdgeWeightType::Explicit),
            edge_weight_format: Some(EdgeWeightFormat::LowerRow),
            node_coord_type: Some(NodeCoordType::TwodCoords),
            capacity: Some(2),
            edge_weights: vec![vec![4], vec![5, 6]],
            node_coords: vec![vec![0.0, 0.0], vec![7.0, 8.0], vec![9.0, 10.0]],
            demands: vec![vec![1, 0], vec![2, 11], vec![3, 12]],
            depots: vec![vec![1]],
        };

        let value = VRPInstanceBuilder::make_from_vrplib(sut);

        let expected = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![1],
            capacity: Some(2),
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: Some(vec![vec![4], vec![5, 6]]),
        };
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_succeeds() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![1],
            capacity: Some(2),
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: Some(vec![vec![4], vec![5, 6]]),
        };

        let value = sut.build().unwrap();

        let expected = VRPInstance {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            depots: vec![1],
            capacity: Some(2),
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: vec![vec![0, 4, 5], vec![4, 0, 6], vec![5, 6, 0]],
        };
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_fails_if_missing_depots() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![], // is empty
            capacity: Some(2),
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: Some(vec![vec![4], vec![5, 6]]),
        };

        let value = sut.build().unwrap_err();

        let expected = ValidationError::MissingDepots;
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_fails_if_missing_demands() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![1],
            capacity: Some(2),
            demands: None, // not given
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: Some(vec![vec![4], vec![5, 6]]),
        };

        let value = sut.build().unwrap_err();

        let expected = ValidationError::MissingDemands;
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_fails_if_missing_capacity() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![1],
            capacity: None, // not given
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: Some(vec![vec![4], vec![5, 6]]),
        };

        let value = sut.build().unwrap_err();

        let expected = ValidationError::MissingCapacity;
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_fails_if_missing_edge_weights() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::LowerRow,
            depots: vec![1],
            capacity: None,
            demands: Some(vec![0, 11, 12]),
            node_coords: Some(vec![(0.0, 0.0), (7.0, 8.0), (9.0, 10.0)]),
            edge_weights: None, // not given
        };

        let value = sut.build().unwrap_err();

        let expected = ValidationError::MissingEdgeWeight;
        assert_eq!(value, expected);
    }

    #[test]
    fn test_build_fails_if_missing_node_coords() {
        let sut = VRPInstanceBuilder {
            name: "This is a name.".to_string(),
            problem_type: ProblemType::CVRP,
            dimension: 3,
            edge_weight_kind: EdgeWeightKind::Euc2D,
            depots: vec![1],
            capacity: None,
            demands: Some(vec![0, 11, 12]),
            node_coords: None, // not given
            edge_weights: None,
        };

        let value = sut.build().unwrap_err();

        let expected = ValidationError::MissingNodeCoords;
        assert_eq!(value, expected);
    }
}