Skip to main content

multiobjective_search/
dimacs.rs

1//! A loader for road networks in the format of the 9th DIMACS
2//! Implementation Challenge on shortest paths.
3//!
4//! The challenge distributes each road network as a distance graph
5//! (`USA-road-d.*.gr`), a travel-time graph (`USA-road-t.*.gr`) with the same
6//! arcs in the same order, and node coordinates (`USA-road-*.co`). The
7//! bi-objective search literature (BOA*, BOBA*, PP-A*) uses distance and time
8//! as its two objectives. [`RoadGraph`] zips the two `.gr` files into one
9//! graph with `[distance, time]` edge costs.
10//!
11//! The format, line by line (`c` lines are comments everywhere):
12//!
13//! - `.gr`: one problem line `p sp <nodes> <arcs>`, then `<arcs>` arc lines
14//!   `a <from> <to> <weight>`, nodes numbered `1..=<nodes>`;
15//! - `.co`: one problem line `p aux sp co <nodes>`, then node lines
16//!   `v <id> <x> <y>`, coordinates as signed integers (micro-degrees in the
17//!   USA files).
18//!
19//! The loader parses from `&str`, so it works without `std`; read the files
20//! with `std::fs::read_to_string` or decompress them first.
21
22use alloc::vec;
23use alloc::vec::Vec;
24use core::fmt;
25use core::str::FromStr;
26
27use crate::graph::{Graph, ReverseGraph};
28
29/// A road network with `[distance, time]` arc costs, loaded from DIMACS
30/// files.
31///
32/// States are the DIMACS node ids, `1..=node_count()`. Arcs are stored in
33/// compressed sparse rows in both directions, so [`Graph::successors`] and
34/// [`ReverseGraph::predecessors`] are a slice copy each.
35///
36/// # Examples
37///
38/// ```
39/// use multiobjective_search::{RoadGraph, boa_star, ZeroHeuristic};
40///
41/// let distance = "c tiny\np sp 3 3\na 1 2 10\na 2 3 10\na 1 3 25\n";
42/// let time = "p sp 3 3\na 1 2 5\na 2 3 5\na 1 3 6\n";
43/// let graph = RoadGraph::from_dimacs(distance, time)?;
44/// assert_eq!(graph.node_count(), 3);
45///
46/// let out = boa_star(&graph, ZeroHeuristic, 1, |s| *s == 3);
47/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
48/// assert_eq!(costs, [[20, 10], [25, 6]]);
49/// # Ok::<(), multiobjective_search::DimacsError>(())
50/// ```
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct RoadGraph {
53    /// Number of nodes; ids run from 1 to this.
54    nodes: u32,
55    /// Forward adjacency: arcs of node `v` are
56    /// `out_arcs[out_start[v - 1]..out_start[v]]`. Length `nodes + 1`.
57    out_start: Vec<usize>,
58    /// Forward arcs as `(to, [distance, time])`, grouped by source.
59    out_arcs: Vec<(u32, [u32; 2])>,
60    /// Reverse adjacency offsets, as [`RoadGraph::out_start`].
61    in_start: Vec<usize>,
62    /// Reverse arcs as `(from, [distance, time])`, grouped by target.
63    in_arcs: Vec<(u32, [u32; 2])>,
64    /// Coordinates by node id minus one; empty until
65    /// [`RoadGraph::with_coordinates`]. `None` for nodes without a `v` line.
66    coordinates: Vec<Option<[i32; 2]>>,
67}
68
69/// An error while parsing a DIMACS file, with the 1-based line where it
70/// occurred (the line after the last one for errors found at the end).
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct DimacsError {
73    /// 1-based line number in the file being parsed.
74    pub line: usize,
75    /// What went wrong.
76    pub kind: DimacsErrorKind,
77}
78
79/// The kinds of [`DimacsError`].
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum DimacsErrorKind {
83    /// No problem line before the first data line or the end of the file.
84    MissingProblemLine,
85    /// A second problem line.
86    DuplicateProblemLine,
87    /// A line that does not have the expected fields or numbers.
88    Malformed,
89    /// A node id outside `1..=nodes`.
90    NodeOutOfRange(u32),
91    /// The file has a different number of arcs than its problem line says,
92    /// or the time file a different number than the distance file (line 0).
93    ArcCount {
94        /// The count on the problem line.
95        expected: usize,
96        /// The number of arc lines.
97        found: usize,
98    },
99    /// The distance and time files disagree on the node count, or the
100    /// coordinate file on the graph's node count.
101    NodeCount {
102        /// The graph's node count.
103        expected: u32,
104        /// The count in the second file.
105        found: u32,
106    },
107    /// The time file's arc on this line connects other nodes than the
108    /// distance file's arc at the same position.
109    ArcMismatch,
110    /// A second `v` line for the same node.
111    DuplicateNode(u32),
112}
113
114impl fmt::Display for DimacsError {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "line {}: ", self.line)?;
117
118        match &self.kind {
119            DimacsErrorKind::MissingProblemLine => f.write_str("missing problem line"),
120            DimacsErrorKind::DuplicateProblemLine => f.write_str("second problem line"),
121            DimacsErrorKind::Malformed => f.write_str("malformed line"),
122            DimacsErrorKind::NodeOutOfRange(id) => write!(f, "node {id} out of range"),
123            DimacsErrorKind::ArcCount { expected, found } => {
124                write!(f, "expected {expected} arcs, found {found}")
125            }
126            DimacsErrorKind::NodeCount { expected, found } => {
127                write!(f, "expected {expected} nodes, found {found}")
128            }
129            DimacsErrorKind::ArcMismatch => {
130                f.write_str("arc differs from the distance file's arc at this position")
131            }
132            DimacsErrorKind::DuplicateNode(id) => write!(f, "node {id} listed twice"),
133        }
134    }
135}
136
137impl core::error::Error for DimacsError {}
138
139impl RoadGraph {
140    /// Parses a distance `.gr` file and a time `.gr` file with the same
141    /// arcs in the same order.
142    ///
143    /// # Errors
144    ///
145    /// Returns a [`DimacsError`] for a malformed or inconsistent file:
146    /// a missing or second problem line, a malformed line, a node id out of
147    /// range, an arc count that differs from the problem line, or two files
148    /// that differ in node count ([`DimacsErrorKind::NodeCount`], line 0),
149    /// in arc count ([`DimacsErrorKind::ArcCount`], line 0) or in an arc's
150    /// endpoints ([`DimacsErrorKind::ArcMismatch`], at the time
151    /// file's line).
152    pub fn from_dimacs(distance: &str, time: &str) -> Result<Self, DimacsError> {
153        let distance = parse_gr(distance)?;
154        let time = parse_gr(time)?;
155
156        if distance.nodes != time.nodes {
157            return Err(DimacsError {
158                line: 0,
159                kind: DimacsErrorKind::NodeCount {
160                    expected: distance.nodes,
161                    found: time.nodes,
162                },
163            });
164        }
165
166        if distance.arcs.len() != time.arcs.len() {
167            return Err(DimacsError {
168                line: 0,
169                kind: DimacsErrorKind::ArcCount {
170                    expected: distance.arcs.len(),
171                    found: time.arcs.len(),
172                },
173            });
174        }
175
176        let mut arcs = Vec::with_capacity(distance.arcs.len());
177        for (d, t) in distance.arcs.iter().zip(&time.arcs) {
178            if (d.from, d.to) != (t.from, t.to) {
179                return Err(DimacsError {
180                    line: t.line,
181                    kind: DimacsErrorKind::ArcMismatch,
182                });
183            }
184
185            arcs.push((d.from, d.to, [d.weight, t.weight]));
186        }
187
188        Ok(Self::from_arcs(distance.nodes, &arcs))
189    }
190
191    /// Builds a graph over nodes `1..=nodes` from `(from, to, [distance,
192    /// time])` arcs.
193    ///
194    /// # Panics
195    ///
196    /// Panics if an arc endpoint is outside `1..=nodes`.
197    #[must_use]
198    pub fn from_arcs(nodes: u32, arcs: &[(u32, u32, [u32; 2])]) -> Self {
199        let (out_start, out_arcs) = compressed_rows(nodes, arcs.iter().map(|a| (a.0, a.1, a.2)));
200        let (in_start, in_arcs) = compressed_rows(nodes, arcs.iter().map(|a| (a.1, a.0, a.2)));
201
202        Self {
203            nodes,
204            out_start,
205            out_arcs,
206            in_start,
207            in_arcs,
208            coordinates: Vec::new(),
209        }
210    }
211
212    /// Adds the node coordinates from a `.co` file.
213    ///
214    /// # Errors
215    ///
216    /// Returns a [`DimacsError`] for a missing or second problem line, a
217    /// malformed line, a node count that differs from the graph's, a node id
218    /// out of range or listed twice.
219    pub fn with_coordinates(mut self, co: &str) -> Result<Self, DimacsError> {
220        let mut coordinates = vec![None; self.nodes as usize];
221        let mut header = false;
222        let mut line_number = 0;
223
224        for (index, line) in co.lines().enumerate() {
225            line_number = index + 1;
226            let error = |kind| DimacsError {
227                line: line_number,
228                kind,
229            };
230            let mut fields = line.split_whitespace();
231
232            match fields.next() {
233                None | Some("c") => {}
234                Some("p") => {
235                    if header {
236                        return Err(error(DimacsErrorKind::DuplicateProblemLine));
237                    }
238
239                    let found = parse_co_header(fields).ok_or(error(DimacsErrorKind::Malformed))?;
240                    if found != self.nodes {
241                        return Err(error(DimacsErrorKind::NodeCount {
242                            expected: self.nodes,
243                            found,
244                        }));
245                    }
246
247                    header = true;
248                }
249                Some("v") if header => {
250                    let (id, x, y) =
251                        parse_fields(fields).ok_or(error(DimacsErrorKind::Malformed))?;
252                    let slot = node_slot(&mut coordinates, id)
253                        .ok_or(error(DimacsErrorKind::NodeOutOfRange(id)))?;
254                    if slot.replace([x, y]).is_some() {
255                        return Err(error(DimacsErrorKind::DuplicateNode(id)));
256                    }
257                }
258                Some("v") => return Err(error(DimacsErrorKind::MissingProblemLine)),
259                Some(_) => return Err(error(DimacsErrorKind::Malformed)),
260            }
261        }
262
263        if !header {
264            return Err(DimacsError {
265                line: line_number + 1,
266                kind: DimacsErrorKind::MissingProblemLine,
267            });
268        }
269
270        self.coordinates = coordinates;
271
272        Ok(self)
273    }
274
275    /// Number of nodes; the node ids are `1..=node_count()`.
276    #[must_use]
277    pub fn node_count(&self) -> u32 {
278        self.nodes
279    }
280
281    /// Number of arcs.
282    #[must_use]
283    pub fn arc_count(&self) -> usize {
284        self.out_arcs.len()
285    }
286
287    /// The coordinates of `node` as `[x, y]`, or `None` if no coordinates
288    /// were loaded for it.
289    #[must_use]
290    pub fn coordinates(&self, node: u32) -> Option<[i32; 2]> {
291        let index = usize::try_from(node.checked_sub(1)?).ok()?;
292        self.coordinates.get(index).copied().flatten()
293    }
294
295    /// The arcs of `node` in the compressed rows `start` and `arcs`, or an
296    /// empty slice for an id out of range.
297    fn row<'a>(start: &[usize], arcs: &'a [(u32, [u32; 2])], node: u32) -> &'a [(u32, [u32; 2])] {
298        let Some(index) = node.checked_sub(1).map(|i| i as usize) else {
299            return &[];
300        };
301
302        match (start.get(index), start.get(index + 1)) {
303            (Some(&from), Some(&to)) => &arcs[from..to],
304            _ => &[],
305        }
306    }
307}
308
309impl Graph for RoadGraph {
310    type State = u32;
311    type Weight = [u32; 2];
312
313    fn successors(&self, state: &u32, out: &mut Vec<(u32, [u32; 2])>) {
314        out.extend_from_slice(Self::row(&self.out_start, &self.out_arcs, *state));
315    }
316}
317
318impl ReverseGraph for RoadGraph {
319    fn predecessors(&self, state: &u32, out: &mut Vec<(u32, [u32; 2])>) {
320        out.extend_from_slice(Self::row(&self.in_start, &self.in_arcs, *state));
321    }
322}
323
324/// One parsed `.gr` file.
325struct GrFile {
326    /// Node count from the problem line.
327    nodes: u32,
328    /// Arcs in file order.
329    arcs: Vec<Arc>,
330}
331
332/// One arc line of a `.gr` file.
333struct Arc {
334    /// 1-based line number, for error messages.
335    line: usize,
336    /// Source node id.
337    from: u32,
338    /// Target node id.
339    to: u32,
340    /// Arc weight.
341    weight: u32,
342}
343
344/// Parses one `.gr` file.
345fn parse_gr(text: &str) -> Result<GrFile, DimacsError> {
346    let mut header: Option<(u32, usize)> = None;
347    let mut arcs = Vec::new();
348    let mut line_number = 0;
349
350    for (index, line) in text.lines().enumerate() {
351        line_number = index + 1;
352        let error = |kind| DimacsError {
353            line: line_number,
354            kind,
355        };
356        let mut fields = line.split_whitespace();
357
358        match fields.next() {
359            None | Some("c") => {}
360            Some("p") => {
361                if header.is_some() {
362                    return Err(error(DimacsErrorKind::DuplicateProblemLine));
363                }
364
365                let parsed = parse_gr_header(fields).ok_or(error(DimacsErrorKind::Malformed))?;
366                arcs.reserve(parsed.1.min(max_arc_lines(text)));
367                header = Some(parsed);
368            }
369            Some("a") => {
370                let (nodes, _) = header.ok_or(error(DimacsErrorKind::MissingProblemLine))?;
371                let (from, to, weight): (u32, u32, u32) =
372                    parse_fields(fields).ok_or(error(DimacsErrorKind::Malformed))?;
373
374                for id in [from, to] {
375                    if id == 0 || id > nodes {
376                        return Err(error(DimacsErrorKind::NodeOutOfRange(id)));
377                    }
378                }
379
380                arcs.push(Arc {
381                    line: line_number,
382                    from,
383                    to,
384                    weight,
385                });
386            }
387            Some(_) => return Err(error(DimacsErrorKind::Malformed)),
388        }
389    }
390
391    let end = |kind| DimacsError {
392        line: line_number + 1,
393        kind,
394    };
395    let (nodes, expected) = header.ok_or(end(DimacsErrorKind::MissingProblemLine))?;
396    if arcs.len() != expected {
397        return Err(end(DimacsErrorKind::ArcCount {
398            expected,
399            found: arcs.len(),
400        }));
401    }
402
403    Ok(GrFile { nodes, arcs })
404}
405
406/// An upper bound on the arc lines `text` can hold, so a problem line that
407/// declares billions of arcs cannot reserve more memory than the file
408/// could fill. The shortest arc line, `a 1 1 0` plus its newline, has 8
409/// bytes.
410fn max_arc_lines(text: &str) -> usize {
411    text.len() / 8 + 1
412}
413
414/// Parses the fields after `p` of a `.gr` problem line: `sp <nodes> <arcs>`.
415fn parse_gr_header<'a>(mut fields: impl Iterator<Item = &'a str>) -> Option<(u32, usize)> {
416    if fields.next()? != "sp" {
417        return None;
418    }
419
420    let (nodes, arcs) = parse_fields(fields)?;
421    Some((nodes, arcs))
422}
423
424/// Parses the fields after `p` of a `.co` problem line:
425/// `aux sp co <nodes>`.
426fn parse_co_header<'a>(mut fields: impl Iterator<Item = &'a str>) -> Option<u32> {
427    for expected in ["aux", "sp", "co"] {
428        if fields.next()? != expected {
429            return None;
430        }
431    }
432
433    let (nodes,) = parse_fields(fields)?;
434    Some(nodes)
435}
436
437/// Parses exactly the fields of a tuple of numbers, rejecting extra fields.
438fn parse_fields<'a, T: Fields>(mut fields: impl Iterator<Item = &'a str>) -> Option<T> {
439    let parsed = T::parse(&mut fields)?;
440    fields.next().is_none().then_some(parsed)
441}
442
443/// A tuple of whitespace-separated numbers.
444trait Fields: Sized {
445    /// Parses the tuple's fields from the front of `fields`.
446    fn parse<'a>(fields: &mut impl Iterator<Item = &'a str>) -> Option<Self>;
447}
448
449/// Parses the next field as a number.
450fn next<'a, T: FromStr>(fields: &mut impl Iterator<Item = &'a str>) -> Option<T> {
451    fields.next()?.parse().ok()
452}
453
454impl<A: FromStr> Fields for (A,) {
455    fn parse<'a>(fields: &mut impl Iterator<Item = &'a str>) -> Option<Self> {
456        Some((next(fields)?,))
457    }
458}
459
460impl<A: FromStr, B: FromStr> Fields for (A, B) {
461    fn parse<'a>(fields: &mut impl Iterator<Item = &'a str>) -> Option<Self> {
462        Some((next(fields)?, next(fields)?))
463    }
464}
465
466impl<A: FromStr, B: FromStr, C: FromStr> Fields for (A, B, C) {
467    fn parse<'a>(fields: &mut impl Iterator<Item = &'a str>) -> Option<Self> {
468        Some((next(fields)?, next(fields)?, next(fields)?))
469    }
470}
471
472/// The coordinate slot of node `id`, or `None` if it is out of range.
473fn node_slot(coordinates: &mut [Option<[i32; 2]>], id: u32) -> Option<&mut Option<[i32; 2]>> {
474    let index = usize::try_from(id.checked_sub(1)?).ok()?;
475    coordinates.get_mut(index)
476}
477
478/// Groups `(row, column, weight)` triples by row into compressed sparse rows
479/// over rows `1..=nodes`, keeping the input order within a row.
480///
481/// # Panics
482///
483/// Panics if a row is outside `1..=nodes`.
484fn compressed_rows(
485    nodes: u32,
486    entries: impl Iterator<Item = (u32, u32, [u32; 2])> + Clone,
487) -> (Vec<usize>, Vec<(u32, [u32; 2])>) {
488    let rows = nodes as usize;
489    let row = |id: u32| {
490        assert!(
491            (1..=nodes).contains(&id),
492            "node {id} out of range 1..={nodes}"
493        );
494        id as usize - 1
495    };
496
497    let mut start = vec![0; rows + 1];
498    for (from, _, _) in entries.clone() {
499        start[row(from) + 1] += 1;
500    }
501
502    for i in 0..rows {
503        start[i + 1] += start[i];
504    }
505
506    let mut next = start.clone();
507    let mut arcs = vec![(0, [0, 0]); start[rows]];
508    for (from, to, weight) in entries {
509        let slot = &mut next[row(from)];
510        arcs[*slot] = (to, weight);
511        *slot += 1;
512    }
513
514    (start, arcs)
515}
516
517#[cfg(test)]
518mod tests {
519    //! Unit tests for the DIMACS loader.
520
521    use alloc::vec::Vec;
522
523    use super::{DimacsErrorKind, RoadGraph};
524    use crate::graph::{Graph, ReverseGraph};
525
526    /// A distance file with comments and blank lines.
527    const DISTANCE: &str = "c 9th DIMACS style\n\np sp 3 3\nc arcs\na 1 2 10\na 2 3 10\na 1 3 25\n";
528
529    /// The matching time file.
530    const TIME: &str = "p sp 3 3\na 1 2 5\na 2 3 5\na 1 3 6\n";
531
532    /// Successors and predecessors mirror the arcs.
533    #[test]
534    fn adjacency_in_both_directions() {
535        let graph = RoadGraph::from_dimacs(DISTANCE, TIME).expect("valid");
536        let mut out = Vec::new();
537
538        graph.successors(&1, &mut out);
539        assert_eq!(out, [(2, [10, 5]), (3, [25, 6])]);
540
541        out.clear();
542        graph.predecessors(&3, &mut out);
543        assert_eq!(out, [(2, [10, 5]), (1, [25, 6])]);
544
545        out.clear();
546        graph.successors(&0, &mut out);
547        graph.successors(&4, &mut out);
548        assert_eq!(out, []);
549        assert_eq!(graph.arc_count(), 3);
550    }
551
552    /// Coordinates load by node id.
553    #[test]
554    fn coordinates() {
555        let co = "c coords\np aux sp co 3\nv 1 -73530767 41085396\nv 3 10 -20\n";
556        let graph = RoadGraph::from_dimacs(DISTANCE, TIME)
557            .and_then(|g| g.with_coordinates(co))
558            .expect("valid");
559
560        assert_eq!(graph.coordinates(1), Some([-73_530_767, 41_085_396]));
561        assert_eq!(graph.coordinates(2), None);
562        assert_eq!(graph.coordinates(3), Some([10, -20]));
563        assert_eq!(graph.coordinates(0), None);
564    }
565
566    /// Every `.gr` error kind is reported with its line.
567    #[test]
568    fn errors() {
569        let kind = |d: &str, t: &str| RoadGraph::from_dimacs(d, t).map(|_| ()).unwrap_err();
570
571        let e = kind("a 1 2 3\n", TIME);
572        assert_eq!((e.line, e.kind), (1, DimacsErrorKind::MissingProblemLine));
573        let e = kind("p sp 3 1\np sp 3 1\n", TIME);
574        assert_eq!((e.line, e.kind), (2, DimacsErrorKind::DuplicateProblemLine));
575        let e = kind("p sp 3 1\na 1 x 3\n", TIME);
576        assert_eq!((e.line, e.kind), (2, DimacsErrorKind::Malformed));
577        let e = kind("p sp 3 1\na 1 4 3\n", TIME);
578        assert_eq!((e.line, e.kind), (2, DimacsErrorKind::NodeOutOfRange(4)));
579        let e = kind("p sp 3 2\na 1 2 3\n", TIME);
580        assert_eq!(
581            e.kind,
582            DimacsErrorKind::ArcCount {
583                expected: 2,
584                found: 1
585            }
586        );
587        let e = kind("p sp 4 3\na 1 2 10\na 2 3 10\na 1 3 25\n", TIME);
588        assert_eq!(
589            e.kind,
590            DimacsErrorKind::NodeCount {
591                expected: 4,
592                found: 3
593            }
594        );
595        let e = kind(DISTANCE, "p sp 3 2\na 1 2 5\na 2 3 5\n");
596        assert_eq!(
597            (e.line, e.kind),
598            (
599                0,
600                DimacsErrorKind::ArcCount {
601                    expected: 3,
602                    found: 2
603                }
604            )
605        );
606        let e = kind(DISTANCE, "p sp 3 3\na 1 2 5\na 3 2 5\na 1 3 6\n");
607        assert_eq!((e.line, e.kind), (3, DimacsErrorKind::ArcMismatch));
608    }
609
610    /// Every `.co` error kind is reported.
611    #[test]
612    fn coordinate_errors() {
613        let graph = RoadGraph::from_dimacs(DISTANCE, TIME).expect("valid");
614        let co = |text: &str| {
615            graph
616                .clone()
617                .with_coordinates(text)
618                .map(|_| ())
619                .unwrap_err()
620        };
621        assert_eq!(co("v 1 2 3\n").kind, DimacsErrorKind::MissingProblemLine);
622        assert_eq!(
623            co("p aux sp co 2\n").kind,
624            DimacsErrorKind::NodeCount {
625                expected: 3,
626                found: 2
627            }
628        );
629        assert_eq!(
630            co("p aux sp co 3\nv 1 2 3\nv 1 2 3\n").kind,
631            DimacsErrorKind::DuplicateNode(1)
632        );
633        assert_eq!(
634            co("p aux sp co 3\nv 9 2 3\n").kind,
635            DimacsErrorKind::NodeOutOfRange(9)
636        );
637        assert_eq!(
638            co("p aux sp co 3\nv 1 2\n").kind,
639            DimacsErrorKind::Malformed
640        );
641    }
642
643    /// A problem line that declares more arcs than the file holds is an
644    /// arc-count error, not an allocation of the declared size (found by the
645    /// `dimacs_parse` fuzz target).
646    #[test]
647    fn huge_declared_arc_count() {
648        let e = RoadGraph::from_dimacs("p sp 6 4000000000\n", TIME).unwrap_err();
649        assert_eq!(
650            e.kind,
651            DimacsErrorKind::ArcCount {
652                expected: 4_000_000_000,
653                found: 0
654            }
655        );
656    }
657
658    /// Error messages name the line.
659    #[test]
660    fn display() {
661        let e = RoadGraph::from_dimacs("p sp 3 1\na 1 4 3\n", TIME).unwrap_err();
662        assert_eq!(alloc::format!("{e}"), "line 2: node 4 out of range");
663    }
664}