Skip to main content

geocoder_core/search/
results.rs

1//! addok 1.1's `SEARCH_RESULT_PROCESSORS` as configured by the Géoplateforme:
2//! `match_housenumber`, `make_labels`, `score_by_importance`,
3//! `score_by_autocomplete_distance`, `score_by_ngram_distance`,
4//! `score_by_geo_distance`. (`adjust_scores` is not part of it.)
5
6use serde_json::Value;
7
8use crate::doc::{Document, first_f64};
9use crate::profile::Profile;
10use crate::settings::{IMPORTANCE_WEIGHT, MATCH_THRESHOLD};
11use crate::text::{ascii, compare_ngrams};
12use crate::types::DocId;
13
14/// What the result processors need from the query.
15pub struct Context<'a> {
16    pub profile: &'a dyn Profile,
17    /// ASCII folded raw query (not cleaned by the query processors).
18    pub query: &'a str,
19    pub autocomplete: bool,
20    pub lat: Option<f64>,
21    pub lon: Option<f64>,
22    pub check_housenumber: bool,
23    /// `type=housenumber` filter: results without a matching housenumber
24    /// are dropped.
25    pub only_housenumber: bool,
26    /// Housenumber tokens joined in query order.
27    pub housenumber: &'a str,
28}
29
30/// A scored candidate, `addok.core.Result`.
31#[derive(Debug, Clone)]
32pub struct Scored {
33    pub id: DocId,
34    pub doc: Document,
35    pub labels: Vec<String>,
36    /// Shown instead of the first label (`Profile::display_label`).
37    pub display: Option<String>,
38    pub housenumber: Option<String>,
39    pub distance_km: Option<f64>,
40    importance: Option<(f64, f64)>,
41    str_distance: Option<(f64, f64)>,
42    geo_distance: Option<(f64, f64)>,
43}
44
45/// `Result.add_score`: keep the best value seen.
46fn add_score(slot: &mut Option<(f64, f64)>, score: f64, ceiling: f64) {
47    if score >= slot.map_or(0.0, |s| s.0) {
48        *slot = Some((score, ceiling));
49    }
50}
51
52impl Scored {
53    pub fn score(&self) -> f64 {
54        let (mut sum, mut max) = (0.0, 0.0);
55        for (score, ceiling) in [self.importance, self.str_distance, self.geo_distance]
56            .into_iter()
57            .flatten()
58        {
59            sum += score;
60            max += ceiling;
61        }
62        if max == 0.0 { 0.0 } else { sum / max }
63    }
64
65    pub fn str_distance(&self) -> f64 {
66        self.str_distance.map_or(0.0, |s| s.0)
67    }
68
69    /// `str(result)`: first label, else the name.
70    pub fn label(&self) -> String {
71        if let Some(display) = &self.display {
72            return display.clone();
73        }
74        self.labels.first().cloned().unwrap_or_else(|| {
75            crate::doc::str_values(&self.doc, "name")
76                .into_iter()
77                .next()
78                .unwrap_or_default()
79        })
80    }
81
82    pub fn lat(&self) -> f64 {
83        first_f64(&self.doc, "lat").unwrap_or_default()
84    }
85
86    pub fn lon(&self) -> f64 {
87        first_f64(&self.doc, "lon").unwrap_or_default()
88    }
89}
90
91/// Run the processors on one document; `None` when one of them rejects it.
92pub fn process(ctx: &Context, id: DocId, mut doc: Document) -> Option<Scored> {
93    // match_housenumber
94    let mut housenumber = None;
95    if ctx.check_housenumber {
96        if !ctx.housenumber.is_empty()
97            && let Some(Value::Object(data)) = doc
98                .get("housenumbers")
99                .and_then(|h| h.get(ctx.housenumber))
100                .cloned()
101        {
102            let mut data = data;
103            housenumber = data.remove("raw").map(|v| crate::doc::py_str(&v));
104            doc.insert("type".into(), Value::String("housenumber".into()));
105            doc.extend(data);
106        }
107        if ctx.only_housenumber && housenumber.is_none() {
108            return None;
109        }
110    }
111
112    let labels = ctx.profile.make_labels(&doc, housenumber.as_deref());
113    let display = ctx
114        .profile
115        .display_label(&doc, housenumber.as_deref(), ctx.query);
116    let mut result = Scored {
117        id,
118        doc,
119        labels,
120        display,
121        housenumber,
122        distance_km: None,
123        importance: None,
124        str_distance: None,
125        geo_distance: None,
126    };
127
128    // score_by_importance
129    let importance = first_f64(&result.doc, "importance").unwrap_or(0.0);
130    add_score(
131        &mut result.importance,
132        importance * IMPORTANCE_WEIGHT,
133        IMPORTANCE_WEIGHT,
134    );
135
136    let labels: Vec<String> = result.labels.iter().map(|l| ascii(l)).collect();
137    if ctx.autocomplete {
138        // score_by_autocomplete_distance: every label is tried (addok 1.1
139        // dropped the early exit of 1.0), the best one wins.
140        let query = ascii(ctx.query);
141        let mut score = 0.0;
142        for label in &labels {
143            if *label == query {
144                score = 1.0;
145            } else if label.starts_with(query.as_str()) {
146                score = 0.9;
147            } else if label.contains(query.as_str()) {
148                score = 0.7;
149            }
150            if score > 0.0 {
151                add_score(&mut result.str_distance, score, 1.0);
152            }
153        }
154        if score == 0.0 {
155            score_by_ngram_distance(&mut result, &labels, ctx.query, 0.9);
156        }
157    } else {
158        score_by_ngram_distance(&mut result, &labels, ctx.query, 1.0);
159    }
160
161    // score_by_geo_distance
162    if let (Some(lat), Some(lon)) = (ctx.lat, ctx.lon) {
163        let km = haversine_km(result.lat(), result.lon(), lat, lon);
164        result.distance_km = Some(km);
165        add_score(&mut result.geo_distance, km_to_score(km), 0.1);
166    }
167    Some(result)
168}
169
170fn score_by_ngram_distance(result: &mut Scored, labels: &[String], query: &str, scale: f64) {
171    for label in labels {
172        let score = compare_ngrams(label, query) * scale;
173        add_score(&mut result.str_distance, score, 1.0);
174        if score >= MATCH_THRESHOLD {
175            break;
176        }
177    }
178}
179
180/// Reverse geocoding processors: `load_closer`, `make_labels`,
181/// `score_by_geo_distance`.
182pub fn process_reverse(
183    profile: &dyn Profile,
184    id: DocId,
185    mut doc: Document,
186    lat: f64,
187    lon: f64,
188    check_housenumber: bool,
189    only_housenumber: bool,
190) -> Option<Scored> {
191    let mut housenumber = None;
192    if check_housenumber {
193        let center = (
194            first_f64(&doc, "lat").unwrap_or_default(),
195            first_f64(&doc, "lon").unwrap_or_default(),
196        );
197        let mut best: Option<(f64, &serde_json::Map<String, Value>)> = None;
198        if let Some(Value::Object(hns)) = doc.get("housenumbers") {
199            for data in hns.values().filter_map(|v| v.as_object()) {
200                let (Some(hlat), Some(hlon)) = (first_f64(data, "lat"), first_f64(data, "lon"))
201                else {
202                    continue;
203                };
204                let d = haversine_km(hlat, hlon, lat, lon);
205                if best.is_none_or(|(b, _)| d < b) {
206                    best = Some((d, data));
207                }
208            }
209        }
210        // addok sorts the housenumbers then the street center (left out when
211        // only housenumbers are wanted), stably.
212        let street = if only_housenumber {
213            f64::INFINITY
214        } else {
215            haversine_km(center.0, center.1, lat, lon)
216        };
217        if let Some((d, data)) = best
218            && d <= street
219        {
220            let mut data = data.clone();
221            housenumber = data.remove("raw").map(|v| crate::doc::py_str(&v));
222            doc.insert("type".into(), Value::String("housenumber".into()));
223            doc.extend(data);
224        }
225        if only_housenumber && housenumber.is_none() {
226            return None;
227        }
228    }
229    let labels = profile.make_labels(&doc, housenumber.as_deref());
230    let display = profile.display_label(&doc, housenumber.as_deref(), "");
231    let mut result = Scored {
232        id,
233        doc,
234        labels,
235        display,
236        housenumber,
237        distance_km: None,
238        importance: None,
239        str_distance: None,
240        geo_distance: None,
241    };
242    let km = haversine_km(result.lat(), result.lon(), lat, lon);
243    result.distance_km = Some(km);
244    add_score(&mut result.geo_distance, km_to_score(km), 0.1);
245    Some(result)
246}
247
248/// Between 0 and 0.1: 0.1 close to 0 km, 0 at 100 km and beyond.
249pub fn km_to_score(km: f64) -> f64 {
250    if km > 100.0 {
251        0.0
252    } else {
253        0.1 * (-(km / 50.0).powi(2)).exp()
254    }
255}
256
257/// Great circle distance, with addok's 6367 km Earth radius.
258pub fn haversine_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
259    let (lat1, lon1, lat2, lon2) = (
260        lat1.to_radians(),
261        lon1.to_radians(),
262        lat2.to_radians(),
263        lon2.to_radians(),
264    );
265    let a = ((lat2 - lat1) / 2.0).sin().powi(2)
266        + lat1.cos() * lat2.cos() * ((lon2 - lon1) / 2.0).sin().powi(2);
267    2.0 * a.sqrt().asin() * 6367.0
268}