Skip to main content

transitous_core/
resolve.rs

1//! From what the caller typed to a stop ID: an ID is used as it is, a name
2//! only if it names one stop. A wrong stop gives wrong connections that look
3//! right, so a doubtful name is an error with the candidates, never a guess.
4//!
5//! The scores of the geocoder do not tell a good match from a bad one, so
6//! only the names count: a match whose name is the query (ignoring case,
7//! punctuation and spacing), else the only match that contains every word
8//! of the query. Matches with the same name in the same area, like the
9//! platforms of a station, count as one.
10
11use motis::{LocationType, Match};
12
13use crate::Error;
14use crate::model::{StopMatch, area};
15
16/// The most candidates an [`Error::AmbiguousStop`] lists.
17pub const MAX_CANDIDATES: usize = 10;
18
19/// Whether the input is a stop ID, like `de-DELFI_de:06412:1_G`, rather
20/// than a name.
21pub fn is_stop_id(input: &str) -> bool {
22    !input.is_empty() && !input.chars().any(char::is_whitespace) && input.contains(['_', ':'])
23}
24
25/// Coordinates `LAT,LON`, which the routing accepts as a place.
26pub fn coordinates(input: &str) -> Option<(f64, f64)> {
27    let (lat, lon) = input.split_once(',')?;
28    let lat: f64 = lat.trim().parse().ok()?;
29    let lon: f64 = lon.trim().parse().ok()?;
30    ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon)).then_some((lat, lon))
31}
32
33/// The stop `query` names among the geocoding `matches`.
34pub fn choose<'a>(query: &str, matches: &'a [Match]) -> Result<&'a Match, Error> {
35    let stops: Vec<&Match> = matches
36        .iter()
37        .filter(|found| found.kind == LocationType::Stop)
38        .collect();
39    if stops.is_empty() {
40        return Err(Error::StopNotFound {
41            query: query.to_owned(),
42        });
43    }
44    let wanted = normalize(query);
45    let exact: Vec<&Match> = stops
46        .iter()
47        .copied()
48        .filter(|found| normalize(&found.name) == wanted)
49        .collect();
50    if let Some(found) = single(&exact) {
51        return Ok(found);
52    }
53    if exact.is_empty() {
54        let words: Vec<&str> = wanted.split(' ').collect();
55        let containing: Vec<&Match> = stops
56            .iter()
57            .copied()
58            .filter(|found| {
59                let name = normalize(&found.name);
60                let name: Vec<&str> = name.split(' ').collect();
61                words.iter().all(|word| name.contains(word))
62            })
63            .collect();
64        if let Some(found) = single(&containing) {
65            return Ok(found);
66        }
67    }
68    let candidates = if exact.is_empty() { stops } else { exact };
69    Err(Error::AmbiguousStop {
70        query: query.to_owned(),
71        candidates: candidates
72            .into_iter()
73            .take(MAX_CANDIDATES)
74            .map(StopMatch::from)
75            .collect(),
76    })
77}
78
79/// The first match, if all have the same name and area.
80fn single<'a>(matches: &[&'a Match]) -> Option<&'a Match> {
81    let first = *matches.first()?;
82    let key = |found: &Match| (normalize(&found.name), area(found));
83    let same = matches.iter().all(|found| key(found) == key(first));
84    same.then_some(first)
85}
86
87/// Lowercase letters and digits, words separated by one space.
88fn normalize(text: &str) -> String {
89    text.chars()
90        .map(|c| {
91            if c.is_alphanumeric() {
92                c.to_lowercase().next().unwrap_or(c)
93            } else {
94                ' '
95            }
96        })
97        .collect::<String>()
98        .split_whitespace()
99        .collect::<Vec<_>>()
100        .join(" ")
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use motis::Area;
107
108    fn stop(id: &str, name: &str, area: &str) -> Match {
109        Match {
110            kind: LocationType::Stop,
111            id: id.into(),
112            name: name.into(),
113            areas: vec![Area {
114                name: area.into(),
115                default: Some(true),
116                ..Area::default()
117            }],
118            ..Match::default()
119        }
120    }
121
122    fn chosen(query: &str, matches: &[Match]) -> String {
123        choose(query, matches).unwrap().id.clone()
124    }
125
126    fn candidates(query: &str, matches: &[Match]) -> Vec<String> {
127        let error = choose(query, matches).unwrap_err();
128        assert_eq!(error.status(), "ambiguous_stop");
129        error.body().candidates.into_iter().map(|c| c.id).collect()
130    }
131
132    #[test]
133    fn tells_ids_from_names() {
134        assert!(is_stop_id("de-DELFI_de:06412:1_G"));
135        assert!(is_stop_id("de:06412:1"));
136        assert!(!is_stop_id("Hauptwache"));
137        assert!(!is_stop_id("Frankfurt (Main) Hbf"));
138        assert!(!is_stop_id("a_b c"));
139        assert!(!is_stop_id(""));
140    }
141
142    #[test]
143    fn reads_coordinates() {
144        assert_eq!(coordinates("50.11, 8.68"), Some((50.11, 8.68)));
145        assert_eq!(coordinates("-33.9,151.2"), Some((-33.9, 151.2)));
146        assert_eq!(coordinates("91,0"), None);
147        assert_eq!(coordinates("0,181"), None);
148        assert_eq!(coordinates("Hauptwache"), None);
149        assert_eq!(coordinates("a,1"), None);
150        assert_eq!(coordinates("1,b"), None);
151    }
152
153    #[test]
154    fn takes_the_exact_name() {
155        let matches = [
156            stop("1", "Frankfurt (Main) Hauptwache", "Frankfurt"),
157            stop("2", "Frankfurt (Main) Freßgass/Hauptwache", "Frankfurt"),
158        ];
159        assert_eq!(chosen("frankfurt main  HAUPTWACHE", &matches), "1");
160    }
161
162    #[test]
163    fn platforms_of_a_station_count_as_one() {
164        let matches = [
165            stop("1", "Hauptwache", "Frankfurt"),
166            stop("2", "Hauptwache", "Frankfurt"),
167        ];
168        assert_eq!(chosen("Hauptwache", &matches), "1");
169    }
170
171    #[test]
172    fn the_same_name_in_two_towns_is_ambiguous() {
173        let matches = [
174            stop("1", "Bahnhof", "Neustadt"),
175            stop("2", "Bahnhof", "Altstadt"),
176            stop("3", "Bahnhofstraße", "Neustadt"),
177        ];
178        assert_eq!(candidates("Bahnhof", &matches), ["1", "2"]);
179    }
180
181    #[test]
182    fn takes_the_only_match_with_every_word() {
183        let matches = [
184            stop("1", "Frankfurt (Main) Hauptbahnhof", "Frankfurt"),
185            stop("2", "Frankfurt (Oder) Bahnhof", "Frankfurt (Oder)"),
186        ];
187        assert_eq!(chosen("Frankfurt Hauptbahnhof", &matches), "1");
188    }
189
190    #[test]
191    fn several_matches_with_every_word_are_ambiguous() {
192        let matches = [
193            stop("1", "Frankfurt (Main) Hauptwache", "Frankfurt"),
194            stop("2", "Frankfurt (Main) Freßgass/Hauptwache", "Frankfurt"),
195        ];
196        assert_eq!(candidates("Hauptwache", &matches), ["1", "2"]);
197    }
198
199    #[test]
200    fn a_single_fuzzy_match_is_not_taken() {
201        let matches = [stop("1", "Hauptbahnhof", "Frankfurt")];
202        assert_eq!(candidates("Hauptbanhof", &matches), ["1"]);
203    }
204
205    #[test]
206    fn lists_at_most_ten_candidates() {
207        let matches: Vec<Match> = (0..15)
208            .map(|i| stop(&i.to_string(), "Bahnhof", &format!("Town {i}")))
209            .collect();
210        assert_eq!(candidates("Bahnhof", &matches).len(), MAX_CANDIDATES);
211    }
212
213    #[test]
214    fn only_stops_count() {
215        let address = Match {
216            kind: LocationType::Address,
217            ..stop("x", "Hauptwache", "Frankfurt")
218        };
219        assert!(matches!(
220            choose("Hauptwache", &[address]),
221            Err(Error::StopNotFound { .. })
222        ));
223        assert!(matches!(
224            choose("Hauptwache", &[]),
225            Err(Error::StopNotFound { .. })
226        ));
227    }
228}