Skip to main content

mapf_search/
movingai.rs

1//! Parsers for the Moving AI benchmark formats (Stern et al. 2019,
2//! <https://movingai.com/benchmarks/mapf/>): grid maps ([`parse_map`]), scenarios
3//! ([`parse_scenario`]) and instances built from both ([`scenario_instance`]).
4//!
5//! The parsers read strings, so they stay `no_std`; reading files is the caller's job. Maps
6//! declare `type octile`, but MAPF benchmarks move agents 4-connected, as [`Grid`] does.
7//!
8//! # Examples
9//!
10//! ```
11//! use mapf_search::{Limits, Objective, cbs, parse_map, parse_scenario, scenario_instance};
12//!
13//! let map = "type octile\nheight 2\nwidth 3\nmap\n...\n@.@\n";
14//! let scen = "version 1\n\
15//!     0\ttiny.map\t3\t2\t0\t0\t2\t0\t2\n\
16//!     0\ttiny.map\t3\t2\t2\t0\t0\t0\t2\n";
17//!
18//! let grid = parse_map(map)?;
19//! let entries = parse_scenario(scen)?;
20//! let instance = scenario_instance(grid, &entries, 2)?;
21//!
22//! let result = cbs(&instance, Objective::SumOfCosts, Limits::expansions(1_000));
23//! assert_eq!(result.solution().map(|s| s.sum_of_costs), Some(7));
24//! # Ok::<(), Box<dyn std::error::Error>>(())
25//! ```
26
27use alloc::string::{String, ToString};
28use alloc::vec::Vec;
29use core::fmt;
30use core::str::FromStr;
31
32use crate::graph::Grid;
33use crate::instance::{Agent, Instance, InstanceError};
34
35/// Parses a Moving AI `.map` file into a [`Grid`].
36///
37/// The header lists `type`, `height` and `width` (one `key value` pair per line, in any
38/// order) and ends with the line `map`. Then follow `height` rows of `width` cells:
39/// `.`, `G` and `S` are free; `@`, `O`, `T` and `W` are blocked. Trailing empty lines are
40/// ignored, and so are carriage returns at line ends.
41///
42/// # Errors
43///
44/// Returns a [`ParseError`] with the 1-based line number and a [`ParseErrorKind`]:
45/// a missing or unknown header field or a bad number, a zero size, a row of the wrong
46/// length, an unknown cell, or too few or too many rows.
47pub fn parse_map(text: &str) -> Result<Grid, ParseError> {
48    let mut lines = numbered_lines(text);
49    let (width, height) = parse_map_header(&mut lines)?;
50
51    // Rows are checked before the grid is allocated, so a header cannot ask for more cells
52    // than the text holds.
53    let rows = read_map_rows(text, &mut lines, width, height)?;
54    let mut grid = Grid::new(width, height);
55    for (y, row) in rows.iter().enumerate() {
56        block_map_row(&mut grid, y, row);
57    }
58
59    Ok(grid)
60}
61
62/// One agent of a Moving AI `.scen` file.
63#[derive(Debug, Clone, PartialEq)]
64pub struct ScenarioEntry {
65    /// The bucket, which groups entries of similar difficulty.
66    pub bucket: u32,
67    /// The map file name, as written in the scenario.
68    pub map: String,
69    /// The width of the map the entry was made for.
70    pub map_width: usize,
71    /// The height of the map the entry was made for.
72    pub map_height: usize,
73    /// The start cell `(x, y)`; `(0, 0)` is the top left.
74    pub start: (usize, usize),
75    /// The goal cell `(x, y)`.
76    pub goal: (usize, usize),
77    /// The optimal single-agent path length the file reports. Computed with octile
78    /// (8-connected) moves, so on a 4-connected [`Grid`] it is only a lower bound.
79    pub optimal_length: f64,
80}
81
82/// Parses a Moving AI `.scen` file: a `version` line, then one entry per line with nine
83/// whitespace-separated fields (see [`ScenarioEntry`]). Empty lines are skipped.
84///
85/// # Errors
86///
87/// Returns a [`ParseError`] if the version line is missing, a line has the wrong number of
88/// fields or a field is not a number.
89pub fn parse_scenario(text: &str) -> Result<Vec<ScenarioEntry>, ParseError> {
90    let mut lines = numbered_lines(text).filter(|(_, line)| !line.is_empty());
91    match lines.next() {
92        Some((_, line)) if line.starts_with("version") => {}
93        other => {
94            return Err(ParseError {
95                line: other.map_or(1, |(line, _)| line),
96                kind: ParseErrorKind::MissingHeader("version"),
97            });
98        }
99    }
100
101    lines
102        .map(|(line, text)| parse_scenario_entry(line, text))
103        .collect()
104}
105
106/// Builds an instance from the first `agents` entries of a scenario on `grid`.
107///
108/// # Errors
109///
110/// - [`ScenarioError::MapSize`] if an entry was made for a map of another size;
111/// - [`ScenarioError::TooFewEntries`] if the scenario has fewer than `agents` entries;
112/// - [`ScenarioError::BlockedCell`] if an entry's start or goal is blocked;
113/// - [`ScenarioError::Instance`] if [`Instance::new`] rejects the agents, for example
114///   for a shared goal.
115pub fn scenario_instance(
116    grid: Grid,
117    entries: &[ScenarioEntry],
118    agents: usize,
119) -> Result<Instance<Grid>, ScenarioError> {
120    let chosen = entries.get(..agents).ok_or(ScenarioError::TooFewEntries {
121        available: entries.len(),
122    })?;
123    let agents = chosen
124        .iter()
125        .enumerate()
126        .map(|(index, entry)| entry_agent(&grid, index, entry))
127        .collect::<Result<Vec<_>, _>>()?;
128
129    Instance::new(grid, agents).map_err(ScenarioError::Instance)
130}
131
132/// The agent of scenario entry `index` on `grid`, after checking the map size and cells.
133fn entry_agent(grid: &Grid, index: usize, entry: &ScenarioEntry) -> Result<Agent, ScenarioError> {
134    if (entry.map_width, entry.map_height) != (grid.width(), grid.height()) {
135        return Err(ScenarioError::MapSize { entry: index });
136    }
137
138    let start = grid.vertex(entry.start.0, entry.start.1);
139    let goal = grid.vertex(entry.goal.0, entry.goal.1);
140    if grid.is_blocked(start) || grid.is_blocked(goal) {
141        return Err(ScenarioError::BlockedCell { entry: index });
142    }
143
144    Ok(Agent { start, goal })
145}
146
147/// The lines of `text`, numbered from 1, without trailing whitespace.
148fn numbered_lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
149    text.lines()
150        .enumerate()
151        .map(|(index, line)| (index + 1, line.trim_end()))
152}
153
154/// Reads the header of a `.map` file up to and including the `map` line and returns the
155/// `(width, height)` it declares.
156fn parse_map_header<'a>(
157    lines: &mut impl Iterator<Item = (usize, &'a str)>,
158) -> Result<(usize, usize), ParseError> {
159    let (mut width, mut height, mut kind) = (None, None, None);
160    let mut last = 0;
161
162    for (line, text) in lines.by_ref() {
163        last = line;
164        let mut words = text.split_whitespace();
165        match (words.next(), words.next()) {
166            (Some("map"), None) => return header_size(width, height, kind, line),
167            (Some("type"), Some(value)) => kind = Some(value),
168            (Some("height"), Some(value)) => height = Some(number(line, value)?),
169            (Some("width"), Some(value)) => width = Some(number(line, value)?),
170            (None, _) => {}
171            _ => return Err(ParseError::new(line, ParseErrorKind::UnknownHeader)),
172        }
173    }
174
175    Err(ParseError::new(
176        last + 1,
177        ParseErrorKind::MissingHeader("map"),
178    ))
179}
180
181/// Checks that the header declared a type and a non-zero size.
182fn header_size(
183    width: Option<usize>,
184    height: Option<usize>,
185    kind: Option<&str>,
186    line: usize,
187) -> Result<(usize, usize), ParseError> {
188    let missing = |field| ParseError::new(line, ParseErrorKind::MissingHeader(field));
189    kind.ok_or_else(|| missing("type"))?;
190    let width = width.ok_or_else(|| missing("width"))?;
191    let height = height.ok_or_else(|| missing("height"))?;
192
193    if width == 0 || height == 0 {
194        return Err(ParseError::new(line, ParseErrorKind::EmptyMap));
195    }
196
197    Ok((width, height))
198}
199
200/// Reads the `height` rows of `width` cells that follow the header from `lines` (numbered
201/// lines of `text`), checks each with [`check_map_row`], and checks that only empty lines
202/// follow them. Allocates no more than the rows of `text` occupy.
203fn read_map_rows<'a>(
204    text: &str,
205    lines: &mut impl Iterator<Item = (usize, &'a str)>,
206    width: usize,
207    height: usize,
208) -> Result<Vec<&'a str>, ParseError> {
209    let rows = (0..height)
210        .map(|_| {
211            let (line, row) = lines.next().ok_or_else(|| {
212                ParseError::new(text.lines().count() + 1, ParseErrorKind::MissingRows)
213            })?;
214            check_map_row(width, line, row)?;
215
216            Ok(row)
217        })
218        .collect::<Result<Vec<_>, _>>()?;
219
220    if let Some((line, _)) = lines.find(|(_, row)| !row.is_empty()) {
221        return Err(ParseError::new(line, ParseErrorKind::ExtraRows));
222    }
223
224    Ok(rows)
225}
226
227/// Checks that map row `row`, read from `line`, has `width` known cells.
228fn check_map_row(width: usize, line: usize, row: &str) -> Result<(), ParseError> {
229    let found = row.chars().count();
230    if found != width {
231        return Err(ParseError::new(
232            line,
233            ParseErrorKind::RowLength {
234                expected: width,
235                found,
236            },
237        ));
238    }
239
240    match row
241        .chars()
242        .find(|cell| !is_free_cell(*cell) && !is_blocked_cell(*cell))
243    {
244        Some(other) => Err(ParseError::new(line, ParseErrorKind::UnknownCell(other))),
245        None => Ok(()),
246    }
247}
248
249/// Blocks the obstacles of map row `y`, which [`check_map_row`] accepted.
250fn block_map_row(grid: &mut Grid, y: usize, row: &str) {
251    for (x, _) in row
252        .chars()
253        .enumerate()
254        .filter(|(_, cell)| is_blocked_cell(*cell))
255    {
256        grid.block(x, y);
257    }
258}
259
260/// Returns `true` for the free map cells `.`, `G` and `S`.
261fn is_free_cell(cell: char) -> bool {
262    matches!(cell, '.' | 'G' | 'S')
263}
264
265/// Returns `true` for the blocked map cells `@`, `O`, `T` and `W`.
266fn is_blocked_cell(cell: char) -> bool {
267    matches!(cell, '@' | 'O' | 'T' | 'W')
268}
269
270/// Parses one scenario entry from the text of line `line`.
271fn parse_scenario_entry(line: usize, text: &str) -> Result<ScenarioEntry, ParseError> {
272    let fields: Vec<&str> = text.split_whitespace().collect();
273    let [bucket, map, width, height, sx, sy, gx, gy, optimal] = fields[..] else {
274        return Err(ParseError::new(
275            line,
276            ParseErrorKind::FieldCount {
277                found: fields.len(),
278            },
279        ));
280    };
281
282    let entry = ScenarioEntry {
283        bucket: number(line, bucket)?,
284        map: map.to_string(),
285        map_width: number(line, width)?,
286        map_height: number(line, height)?,
287        start: (number(line, sx)?, number(line, sy)?),
288        goal: (number(line, gx)?, number(line, gy)?),
289        optimal_length: number(line, optimal)?,
290    };
291
292    let inside = |(x, y): (usize, usize)| x < entry.map_width && y < entry.map_height;
293    if !inside(entry.start) || !inside(entry.goal) {
294        return Err(ParseError::new(line, ParseErrorKind::OutsideMap));
295    }
296
297    Ok(entry)
298}
299
300/// Parses `text` as a number, reporting failures at `line`.
301fn number<T: FromStr>(line: usize, text: &str) -> Result<T, ParseError> {
302    text.parse()
303        .map_err(|_| ParseError::new(line, ParseErrorKind::BadNumber))
304}
305
306/// A syntax error in a Moving AI file.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct ParseError {
309    /// The 1-based line the error was found on.
310    pub line: usize,
311    /// What is wrong.
312    pub kind: ParseErrorKind,
313}
314
315impl ParseError {
316    /// An error of `kind` at `line`.
317    fn new(line: usize, kind: ParseErrorKind) -> Self {
318        Self { line, kind }
319    }
320}
321
322/// What is wrong in a [`ParseError`].
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324#[non_exhaustive]
325pub enum ParseErrorKind {
326    /// A required header line or field is missing: `type`, `height`, `width` or `map` in a
327    /// map, `version` in a scenario.
328    MissingHeader(&'static str),
329    /// A map header line is not one of `type`, `height`, `width` or `map`.
330    UnknownHeader,
331    /// The map declares a zero width or height.
332    EmptyMap,
333    /// A field that must be a number is not one.
334    BadNumber,
335    /// A map row has the wrong number of cells.
336    RowLength {
337        /// The declared width.
338        expected: usize,
339        /// The number of cells in the row.
340        found: usize,
341    },
342    /// A map cell is not one of `.`, `G`, `S`, `@`, `O`, `T`, `W`.
343    UnknownCell(char),
344    /// The map has fewer rows than its height.
345    MissingRows,
346    /// The map has non-empty lines after its last row.
347    ExtraRows,
348    /// A scenario line does not have nine fields.
349    FieldCount {
350        /// The number of fields on the line.
351        found: usize,
352    },
353    /// A scenario start or goal lies outside the map size the entry declares.
354    OutsideMap,
355}
356
357impl fmt::Display for ParseError {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        write!(f, "line {}: ", self.line)?;
360        match self.kind {
361            ParseErrorKind::MissingHeader(field) => write!(f, "missing `{field}` header"),
362            ParseErrorKind::UnknownHeader => f.write_str("unknown header line"),
363            ParseErrorKind::EmptyMap => f.write_str("map has no cells"),
364            ParseErrorKind::BadNumber => f.write_str("expected a number"),
365            ParseErrorKind::RowLength { expected, found } => {
366                write!(f, "row has {found} cells, expected {expected}")
367            }
368            ParseErrorKind::UnknownCell(cell) => write!(f, "unknown map cell {cell:?}"),
369            ParseErrorKind::MissingRows => f.write_str("map has too few rows"),
370            ParseErrorKind::ExtraRows => f.write_str("map has too many rows"),
371            ParseErrorKind::FieldCount { found } => {
372                write!(f, "scenario line has {found} fields, expected 9")
373            }
374            ParseErrorKind::OutsideMap => f.write_str("start or goal outside the map"),
375        }
376    }
377}
378
379impl core::error::Error for ParseError {}
380
381/// Why [`scenario_instance`] could not build an instance.
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383#[non_exhaustive]
384pub enum ScenarioError {
385    /// Entry `entry` was made for a map of another size.
386    MapSize {
387        /// The 0-based index of the entry.
388        entry: usize,
389    },
390    /// The scenario has fewer entries than agents were asked for.
391    TooFewEntries {
392        /// The number of entries in the scenario.
393        available: usize,
394    },
395    /// The start or goal of entry `entry` is a blocked cell.
396    BlockedCell {
397        /// The 0-based index of the entry.
398        entry: usize,
399    },
400    /// The agents do not form a valid instance.
401    Instance(InstanceError),
402}
403
404impl fmt::Display for ScenarioError {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        match self {
407            Self::MapSize { entry } => write!(f, "scenario entry {entry} is for another map size"),
408            Self::TooFewEntries { available } => {
409                write!(f, "the scenario has only {available} entries")
410            }
411            Self::BlockedCell { entry } => {
412                write!(f, "scenario entry {entry} starts or ends on a blocked cell")
413            }
414            Self::Instance(error) => write!(f, "invalid instance: {error}"),
415        }
416    }
417}
418
419impl core::error::Error for ScenarioError {
420    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
421        match self {
422            Self::Instance(error) => Some(error),
423            _ => None,
424        }
425    }
426}