Skip to main content

rmv_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//! Only the names count: a match whose name is the query (ignoring case,
6//! punctuation and spacing), else the only match that contains every word
7//! of the query. Matches with the same name count as one.
8
9use hafas::StopLocation;
10
11use crate::Error;
12use crate::model::StopMatch;
13
14/// The most candidates an [`Error::AmbiguousStop`] lists.
15pub const MAX_CANDIDATES: usize = 10;
16
17/// Whether the input is a stop ID rather than a name: an external ID like
18/// `3000010`, or a HAFAS ID like `A=1@O=Frankfurt (Main) Hbf@L=3000010@`.
19pub fn is_stop_id(input: &str) -> bool {
20    let input = input.trim();
21    (!input.is_empty() && input.chars().all(|c| c.is_ascii_digit()))
22        || input.starts_with("A=")
23        || input.contains("@L=")
24}
25
26/// Coordinates `LAT,LON`, which a trip search accepts as a place.
27pub fn coordinates(input: &str) -> Option<(f64, f64)> {
28    let (lat, lon) = input.split_once(',')?;
29    let lat: f64 = lat.trim().parse().ok()?;
30    let lon: f64 = lon.trim().parse().ok()?;
31    ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon)).then_some((lat, lon))
32}
33
34/// The stop `query` names among the `stops` found for it.
35pub fn choose<'a>(query: &str, stops: &[&'a StopLocation]) -> Result<&'a StopLocation, Error> {
36    if stops.is_empty() {
37        return Err(Error::StopNotFound {
38            query: query.to_owned(),
39        });
40    }
41    let wanted = normalize(query);
42    // Matches with the name of the query all have the same name.
43    if let Some(found) = stops.iter().find(|found| normalize(&found.name) == wanted) {
44        return Ok(found);
45    }
46    let words: Vec<&str> = wanted.split(' ').collect();
47    let containing: Vec<&StopLocation> = stops
48        .iter()
49        .copied()
50        .filter(|found| {
51            let name = normalize(&found.name);
52            let name: Vec<&str> = name.split(' ').collect();
53            words.iter().all(|word| name.contains(word))
54        })
55        .collect();
56    if let Some(found) = single(&containing) {
57        return Ok(found);
58    }
59    Err(Error::AmbiguousStop {
60        query: query.to_owned(),
61        candidates: stops
62            .iter()
63            .copied()
64            .take(MAX_CANDIDATES)
65            .map(StopMatch::from)
66            .collect(),
67    })
68}
69
70/// The first match, if all have the same name.
71fn single<'a>(matches: &[&'a StopLocation]) -> Option<&'a StopLocation> {
72    let first = *matches.first()?;
73    let key = normalize(&first.name);
74    matches
75        .iter()
76        .all(|found| normalize(&found.name) == key)
77        .then_some(first)
78}
79
80/// Lowercase letters and digits, words separated by one space.
81fn normalize(text: &str) -> String {
82    text.chars()
83        .map(|c| {
84            if c.is_alphanumeric() {
85                c.to_lowercase().next().unwrap_or(c)
86            } else {
87                ' '
88            }
89        })
90        .collect::<String>()
91        .split_whitespace()
92        .collect::<Vec<_>>()
93        .join(" ")
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    fn stop(id: &str, name: &str) -> StopLocation {
101        StopLocation {
102            id: format!("A=1@O={name}@L={id}@"),
103            ext_id: id.into(),
104            name: name.into(),
105            ..StopLocation::default()
106        }
107    }
108
109    fn chosen(query: &str, stops: &[StopLocation]) -> String {
110        let stops: Vec<&StopLocation> = stops.iter().collect();
111        choose(query, &stops).unwrap().ext_id.clone()
112    }
113
114    fn candidates(query: &str, stops: &[StopLocation]) -> Vec<String> {
115        let stops: Vec<&StopLocation> = stops.iter().collect();
116        let error = choose(query, &stops).unwrap_err();
117        assert_eq!(error.status(), "ambiguous_stop");
118        error.body().candidates.into_iter().map(|c| c.id).collect()
119    }
120
121    #[test]
122    fn tells_ids_from_names() {
123        assert!(is_stop_id("3000010"));
124        assert!(is_stop_id(" 3000010 "));
125        assert!(is_stop_id(
126            "A=1@O=Frankfurt (Main) Hbf@X=8662653@L=3000010@"
127        ));
128        assert!(is_stop_id("A=1@L=3000010@"));
129        assert!(!is_stop_id("Hauptwache"));
130        assert!(!is_stop_id("Frankfurt (Main) Hbf"));
131        assert!(!is_stop_id("Haltestelle 7"));
132        assert!(!is_stop_id(""));
133    }
134
135    #[test]
136    fn reads_coordinates() {
137        assert_eq!(coordinates("50.11, 8.68"), Some((50.11, 8.68)));
138        assert_eq!(coordinates("-33.9,151.2"), Some((-33.9, 151.2)));
139        assert_eq!(coordinates("91,0"), None);
140        assert_eq!(coordinates("0,181"), None);
141        assert_eq!(coordinates("Hauptwache"), None);
142        assert_eq!(coordinates("a,1"), None);
143        assert_eq!(coordinates("1,b"), None);
144    }
145
146    #[test]
147    fn takes_the_exact_name() {
148        let stops = [
149            stop("1", "Frankfurt (Main) Hauptwache"),
150            stop("2", "Frankfurt (Main) Freßgass/Hauptwache"),
151        ];
152        assert_eq!(chosen("frankfurt main  HAUPTWACHE", &stops), "1");
153    }
154
155    #[test]
156    fn the_same_name_twice_counts_as_one() {
157        let stops = [stop("1", "Hauptwache"), stop("2", "Hauptwache")];
158        assert_eq!(chosen("Hauptwache", &stops), "1");
159    }
160
161    #[test]
162    fn takes_the_only_match_with_every_word() {
163        let stops = [
164            stop("1", "Frankfurt (Main) Hauptbahnhof"),
165            stop("2", "Frankfurt (Oder) Bahnhof"),
166        ];
167        assert_eq!(chosen("Frankfurt Hauptbahnhof", &stops), "1");
168    }
169
170    #[test]
171    fn several_matches_with_every_word_are_ambiguous() {
172        let stops = [
173            stop("1", "Frankfurt (Main) Hauptwache"),
174            stop("2", "Frankfurt (Main) Freßgass/Hauptwache"),
175        ];
176        assert_eq!(candidates("Hauptwache", &stops), ["1", "2"]);
177    }
178
179    #[test]
180    fn a_single_fuzzy_match_is_not_taken() {
181        let stops = [stop("1", "Hauptbahnhof")];
182        assert_eq!(candidates("Hauptbanhof", &stops), ["1"]);
183    }
184
185    #[test]
186    fn lists_at_most_ten_candidates() {
187        let stops: Vec<StopLocation> = (0..15)
188            .map(|i| stop(&i.to_string(), &format!("Bahnhof {i}")))
189            .collect();
190        assert_eq!(candidates("Bahnhof", &stops).len(), MAX_CANDIDATES);
191    }
192
193    #[test]
194    fn nothing_found_is_not_found() {
195        assert!(matches!(
196            choose("Hauptwache", &[]),
197            Err(Error::StopNotFound { .. })
198        ));
199    }
200}