Skip to main content

multiobjective_search/
benchmarks.rs

1//! Generators and loaders for the standardized multi-objective search
2//! benchmark suite of Peer, Hernández, Koenig, Felner, Salzman ("Bridging
3//! the Evaluation Gap: Standardized Benchmarks for Multi-Objective
4//! Search", arXiv 2603.24084).
5//!
6//! The suite's data (github.com/CRL-Technion/Multi-Objective-Search-Benchmarks)
7//! is not bundled: its graphs are large and their licence is not stated.
8//! Instead this module builds instances by the paper's definitions, from a
9//! seed, and converts the inputs the paper builds on (DIMACS road arcs,
10//! Moving AI maps with guards) into its objectives:
11//!
12//! - [`random_grid`]: the random-cost grids `Grid_d` (Section 4.3);
13//! - [`netmaker`] and [`netmaker_queries`]: `NetMaker` graphs (Section 4.3);
14//! - [`guards_grid`]: GUARDS-based bi-objective grids (Section 4.4);
15//! - [`road_extended`]: the DIMACS-Extended objectives (Section 4.2).
16//!
17//! `GER_10` and the robot motion-planning roadmaps need data that only the
18//! suite provides; [`BenchmarkGraph::from_arcs`] loads any such arc list.
19
20use alloc::vec::Vec;
21
22use crate::graph::{Graph, ReverseGraph};
23
24/// A directed graph with `N` integer objectives per edge, over states
25/// `0..nodes`, as the suite's instances are.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct BenchmarkGraph<const N: usize> {
28    /// Outgoing edges per state.
29    out: Vec<Vec<(u32, [u32; N])>>,
30    /// Incoming edges per state.
31    into: Vec<Vec<(u32, [u32; N])>>,
32}
33
34/// A start–goal query.
35pub type Query = (u32, u32);
36
37impl<const N: usize> BenchmarkGraph<N> {
38    /// A graph over `nodes` states with the arcs `(from, to, costs)`.
39    ///
40    /// # Panics
41    ///
42    /// Panics if an arc names a state `>= nodes`.
43    #[must_use]
44    pub fn from_arcs(nodes: u32, arcs: &[(u32, u32, [u32; N])]) -> Self {
45        let n = usize::try_from(nodes).expect("node counts fit in usize");
46        let mut graph = Self {
47            out: alloc::vec![Vec::new(); n],
48            into: alloc::vec![Vec::new(); n],
49        };
50        for &(from, to, cost) in arcs {
51            graph.out[index(from)].push((to, cost));
52            graph.into[index(to)].push((from, cost));
53        }
54
55        graph
56    }
57
58    /// The number of states.
59    ///
60    /// # Panics
61    ///
62    /// Never: the graph was built from a `u32` count.
63    #[must_use]
64    pub fn node_count(&self) -> u32 {
65        u32::try_from(self.out.len()).expect("built from a u32 count")
66    }
67
68    /// The number of arcs.
69    #[must_use]
70    pub fn arc_count(&self) -> usize {
71        self.out.iter().map(Vec::len).sum()
72    }
73
74    /// Every arc as `(from, to, costs)`.
75    ///
76    /// # Panics
77    ///
78    /// Never: the graph was built from a `u32` count.
79    pub fn arcs(&self) -> impl Iterator<Item = (u32, u32, [u32; N])> + '_ {
80        self.out.iter().enumerate().flat_map(|(u, edges)| {
81            let u = u32::try_from(u).expect("built from a u32 count");
82            edges.iter().map(move |&(v, c)| (u, v, c))
83        })
84    }
85
86    /// The same graph with only the objectives `objectives`, in that order
87    /// (for example the three-, four- and five-objective DIMACS-Extended
88    /// variants of one five-objective graph).
89    ///
90    /// # Panics
91    ///
92    /// Panics if an objective index is `>= N`.
93    #[must_use]
94    pub fn project<const M: usize>(&self, objectives: [usize; M]) -> BenchmarkGraph<M> {
95        let pick = |c: [u32; N]| objectives.map(|i| c[i]);
96        let arcs: Vec<_> = self.arcs().map(|(u, v, c)| (u, v, pick(c))).collect();
97        BenchmarkGraph::from_arcs(self.node_count(), &arcs)
98    }
99}
100
101impl<const N: usize> Graph for BenchmarkGraph<N> {
102    type State = u32;
103    type Weight = [u32; N];
104
105    fn successors(&self, state: &u32, out: &mut Vec<(u32, [u32; N])>) {
106        out.extend_from_slice(&self.out[index(*state)]);
107    }
108}
109
110impl<const N: usize> ReverseGraph for BenchmarkGraph<N> {
111    fn predecessors(&self, state: &u32, out: &mut Vec<(u32, [u32; N])>) {
112        out.extend_from_slice(&self.into[index(*state)]);
113    }
114}
115
116/// `state` as an index.
117fn index(state: u32) -> usize {
118    usize::try_from(state).expect("u32 fits in usize")
119}
120
121/// A splitmix64 generator: deterministic from its seed, no dependencies.
122#[derive(Debug, Clone)]
123struct Rng(u64);
124
125impl Rng {
126    /// The next 64 random bits.
127    fn next(&mut self) -> u64 {
128        self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
129        let mut z = self.0;
130        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
131        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
132        z ^ (z >> 31)
133    }
134
135    /// A uniform value in `low..=high`.
136    fn range(&mut self, low: u32, high: u32) -> u32 {
137        let span = u64::from(high - low) + 1;
138        low + u32::try_from(self.next() % span).expect("below the span")
139    }
140}
141
142/// A random-cost grid `Grid_N` (Section 4.3): a four-connected
143/// `width × height` grid, every directed edge with `N` independent costs
144/// uniform in `1..=10`, plus a source joined to every cell of the leftmost
145/// column and a target joined from every cell of the rightmost one, with
146/// costs from the same distribution. Cell `(x, y)` is state `y · width +
147/// x`; the source and target are the last two states, and the query is
148/// theirs. The paper uses widths and heights in `{300, 350, ..., 600}`.
149///
150/// # Panics
151///
152/// Panics if `width` or `height` is zero, or the grid does not fit `u32`
153/// states.
154#[must_use]
155pub fn random_grid<const N: usize>(
156    width: u32,
157    height: u32,
158    seed: u64,
159) -> (BenchmarkGraph<N>, Query) {
160    assert!(width > 0 && height > 0, "a grid needs at least one cell");
161    let cells = width.checked_mul(height).expect("the grid fits u32 states");
162    let (source, target) = (cells, cells + 1);
163    let mut rng = Rng(seed);
164    let mut cost = || core::array::from_fn(|_| rng.range(1, 10));
165    let mut arcs = Vec::new();
166
167    for y in 0..height {
168        for x in 0..width {
169            let cell = y * width + x;
170            if x + 1 < width {
171                arcs.push((cell, cell + 1, cost()));
172                arcs.push((cell + 1, cell, cost()));
173            }
174
175            if y + 1 < height {
176                arcs.push((cell, cell + width, cost()));
177                arcs.push((cell + width, cell, cost()));
178            }
179        }
180
181        arcs.push((source, y * width, cost()));
182        arcs.push((y * width + width - 1, target, cost()));
183    }
184
185    (
186        BenchmarkGraph::from_arcs(cells + 2, &arcs),
187        (source, target),
188    )
189}
190
191/// A `NetMaker` graph (Section 4.3) over states `0..nodes` with three
192/// objectives: a random directed Hamiltonian cycle whose edges get one cost
193/// from each of `1..=333`, `334..=666` and `667..=1000` in random order, and
194/// per state a random extra out-degree from `out_min + 1..=out_max` (the
195/// cycle edge counts as one) filled with edges to states within the
196/// locality window `[u - locality / 2, u + locality / 2]` of its identifier,
197/// with costs uniform in `1..=99`; no self-loops or duplicates. The paper
198/// uses `nodes` in `{10000, 20000, 30000}`, `out_min = 1`, `out_max = 10`
199/// and `locality` in `{20, 50}`.
200///
201/// # Panics
202///
203/// Panics if `nodes < 2` or `out_min >= out_max`.
204#[must_use]
205pub fn netmaker(
206    nodes: u32,
207    out_min: u32,
208    out_max: u32,
209    locality: u32,
210    seed: u64,
211) -> BenchmarkGraph<3> {
212    assert!(
213        nodes >= 2 && out_min < out_max,
214        "`NetMaker` needs two states and out_min < out_max"
215    );
216    let mut rng = Rng(seed);
217
218    // A uniform permutation by Fisher-Yates.
219    let mut order: Vec<u32> = (0..nodes).collect();
220    for i in (1..order.len()).rev() {
221        let j = index(rng.range(0, u32::try_from(i).expect("below nodes")));
222        order.swap(i, j);
223    }
224
225    let mut out: Vec<Vec<(u32, [u32; 3])>> = alloc::vec![Vec::new(); index(nodes)];
226    for k in 0..order.len() {
227        let (u, v) = (order[k], order[(k + 1) % order.len()]);
228        let mut bands = [(1, 333), (334, 666), (667, 1000)];
229        for i in (1..3).rev() {
230            let j = index(rng.range(0, u32::try_from(i).expect("below 3")));
231            bands.swap(i, j);
232        }
233
234        out[index(u)].push((v, bands.map(|(low, high)| rng.range(low, high))));
235    }
236
237    for u in 0..nodes {
238        let degree = rng.range(out_min + 1, out_max);
239        let low = u.saturating_sub(locality / 2);
240        let high = (u + locality / 2).min(nodes - 1);
241        let mut free: Vec<u32> = (low..=high)
242            .filter(|&v| v != u && out[index(u)].iter().all(|e| e.0 != v))
243            .collect();
244
245        while out[index(u)].len() < index(degree) && !free.is_empty() {
246            let pick = index(rng.range(0, u32::try_from(free.len() - 1).expect("small")));
247            let v = free.swap_remove(pick);
248            out[index(u)].push((v, core::array::from_fn(|_| rng.range(1, 99))));
249        }
250    }
251
252    let arcs: Vec<_> = out
253        .iter()
254        .enumerate()
255        .flat_map(|(u, edges)| {
256            edges
257                .iter()
258                .map(move |&(v, c)| (u32::try_from(u).expect("below nodes"), v, c))
259        })
260        .collect();
261    BenchmarkGraph::from_arcs(nodes, &arcs)
262}
263
264/// `count` `NetMaker` queries (Section 4.3): sources uniform among the first
265/// tenth of the identifiers, targets among the last tenth.
266///
267/// # Panics
268///
269/// Panics if `nodes < 10`.
270#[must_use]
271pub fn netmaker_queries(nodes: u32, count: usize, seed: u64) -> Vec<Query> {
272    assert!(nodes >= 10, "queries need at least ten states");
273    let tenth = nodes / 10;
274    let mut rng = Rng(seed);
275    (0..count)
276        .map(|_| (rng.range(0, tenth - 1), rng.range(nodes - tenth, nodes - 1)))
277        .collect()
278}
279
280/// A GUARDS-based bi-objective grid (Section 4.4) from a Moving AI map and
281/// guard cells: an eight-connected directed graph over the passable cells,
282/// objectives path length (10 per orthogonal, 14 per diagonal move) and
283/// guard exposure. A cell's exposure is the number of guards that see it
284/// (Bresenham line of sight through passable cells); an orthogonal move
285/// costs the destination's exposure, a diagonal one the largest of the
286/// destination and the two side cells, and is allowed only when both side
287/// cells are passable. Cell `(x, y)` is state `y · width + x`; blocked cells
288/// have no edges.
289///
290/// The map format is Moving AI's: a header with `height` and `width`
291/// lines, a `map` line, then one row per line, `.`, `G` and `S` passable.
292///
293/// Returns `None` if the header or a row is malformed, or the map has more
294/// cells than `u32` states.
295///
296/// # Panics
297///
298/// Never: cell indices are checked against the map size.
299#[must_use]
300pub fn guards_grid(map: &str, guards: &[(u32, u32)]) -> Option<BenchmarkGraph<2>> {
301    let (width, height, open) = parse_map(map)?;
302    let passable = |x: i64, y: i64| {
303        x >= 0 && y >= 0 && x < i64::from(width) && y < i64::from(height) && open[cell(width, x, y)]
304    };
305    let exposure: Vec<u32> = (0..height)
306        .flat_map(|y| (0..width).map(move |x| (x, y)))
307        .map(|(x, y)| {
308            let seen = guards
309                .iter()
310                .filter(|&&(gx, gy)| {
311                    sees(
312                        &passable,
313                        (i64::from(gx), i64::from(gy)),
314                        (i64::from(x), i64::from(y)),
315                    )
316                })
317                .count();
318            u32::try_from(seen).expect("guard counts fit")
319        })
320        .collect();
321
322    let mut arcs = Vec::new();
323    for y in 0..i64::from(height) {
324        for x in 0..i64::from(width) {
325            if !passable(x, y) {
326                continue;
327            }
328
329            for (dx, dy) in [
330                (1, 0),
331                (-1, 0),
332                (0, 1),
333                (0, -1),
334                (1, 1),
335                (1, -1),
336                (-1, 1),
337                (-1, -1),
338            ] {
339                let (tx, ty) = (x + dx, y + dy);
340                if !passable(tx, ty) {
341                    continue;
342                }
343
344                let diagonal = dx != 0 && dy != 0;
345                let risk = if diagonal {
346                    if !passable(x + dx, y) || !passable(x, y + dy) {
347                        continue;
348                    }
349
350                    exposure[cell(width, tx, ty)]
351                        .max(exposure[cell(width, x + dx, y)])
352                        .max(exposure[cell(width, x, y + dy)])
353                } else {
354                    exposure[cell(width, tx, ty)]
355                };
356
357                let id = |x: i64, y: i64| u32::try_from(cell(width, x, y)).expect("cells fit u32");
358                arcs.push((id(x, y), id(tx, ty), [if diagonal { 14 } else { 10 }, risk]));
359            }
360        }
361    }
362
363    Some(BenchmarkGraph::from_arcs(width.checked_mul(height)?, &arcs))
364}
365
366/// The index of cell `(x, y)`.
367fn cell(width: u32, x: i64, y: i64) -> usize {
368    usize::try_from(y * i64::from(width) + x).expect("a cell on the map")
369}
370
371/// Parses a Moving AI map into its width, height and passability.
372fn parse_map(map: &str) -> Option<(u32, u32, Vec<bool>)> {
373    let mut lines = map.lines();
374    let (mut width, mut height) = (None, None);
375    for line in lines.by_ref() {
376        let mut words = line.split_whitespace();
377        match (words.next(), words.next()) {
378            (Some("height"), Some(h)) => height = h.parse().ok(),
379            (Some("width"), Some(w)) => width = w.parse().ok(),
380            (Some("map"), None) => break,
381            _ => {}
382        }
383    }
384
385    let (width, height): (u32, u32) = (width?, height?);
386    let mut open = Vec::new();
387    for _ in 0..height {
388        let row = lines.next()?;
389        if row.chars().count() != index(width) {
390            return None;
391        }
392
393        open.extend(row.chars().map(|c| matches!(c, '.' | 'G' | 'S')));
394    }
395
396    Some((width, height, open))
397}
398
399/// Returns `true` if `from` sees `to`: every cell on the Bresenham line
400/// between them is passable.
401fn sees(passable: &impl Fn(i64, i64) -> bool, from: (i64, i64), to: (i64, i64)) -> bool {
402    let (mut x, mut y) = from;
403    let (dx, dy) = ((to.0 - x).abs(), -(to.1 - y).abs());
404    let (sx, sy) = (if x < to.0 { 1 } else { -1 }, if y < to.1 { 1 } else { -1 });
405    let mut err = dx + dy;
406
407    loop {
408        if !passable(x, y) {
409            return false;
410        }
411
412        if (x, y) == to {
413            return true;
414        }
415
416        let e2 = 2 * err;
417        if e2 >= dy {
418            err += dy;
419            x += sx;
420        }
421
422        if e2 <= dx {
423            err += dx;
424            y += sy;
425        }
426    }
427}
428
429/// The DIMACS-Extended objectives (Section 4.2, after Ahmadi et al. 2024)
430/// on a road network given as arcs with `[distance, time]`: distance,
431/// time, the absolute elevation difference of the endpoints, the sum of
432/// the endpoints' out-degrees (twice their average, to stay integral), and
433/// one hop. `elevation[v]` is the elevation of state `v`; the paper takes
434/// it from external elevation data. Project with
435/// [`BenchmarkGraph::project`] for the three- and four-objective variants.
436///
437/// # Panics
438///
439/// Panics if an arc names a state without an elevation.
440#[must_use]
441pub fn road_extended(
442    nodes: u32,
443    arcs: &[(u32, u32, [u32; 2])],
444    elevation: &[i32],
445) -> BenchmarkGraph<5> {
446    let mut degree = alloc::vec![0_u32; index(nodes)];
447    for &(u, _, _) in arcs {
448        degree[index(u)] += 1;
449    }
450
451    let extended: Vec<_> = arcs
452        .iter()
453        .map(|&(u, v, [d, t])| {
454            let rise = elevation[index(u)].abs_diff(elevation[index(v)]);
455            (u, v, [d, t, rise, degree[index(u)] + degree[index(v)], 1])
456        })
457        .collect();
458
459    BenchmarkGraph::from_arcs(nodes, &extended)
460}