1use std::collections::HashMap;
21
22use serde_json::{Map, Value, json};
23
24use crate::doc::Document;
25
26#[derive(Debug, Clone, Default)]
28pub struct AddressRow {
29 pub id: String,
31 pub street_id: String,
32 pub street_names: Vec<String>,
34 pub housenumber: String,
36 pub postcode: String,
37 pub city_names: Vec<String>,
40 pub municipality_id: String,
41 pub municipality_names: Vec<String>,
42 pub context: String,
44 pub lat: f64,
45 pub lon: f64,
46}
47
48#[derive(Default)]
49struct Area {
50 names: Vec<String>,
51 municipality_id: String,
52 municipality_names: Vec<String>,
53 postcodes: Vec<String>,
54 context: String,
55 points: Vec<(f64, f64)>,
56}
57
58impl Area {
59 fn add(&mut self, row: &AddressRow) {
60 if !self.postcodes.contains(&row.postcode) {
61 self.postcodes.push(row.postcode.clone());
62 }
63 self.points.push((row.lat, row.lon));
64 }
65}
66
67#[derive(Default)]
68struct Street {
69 id: String,
70 names: Vec<String>,
71 postcodes: Vec<String>,
73 cities: Vec<String>,
74 municipality_id: String,
75 context: String,
76 housenumbers: Vec<Housenumber>,
79}
80
81struct Housenumber {
82 number: String,
83 id: String,
84 lat: f64,
85 lon: f64,
86 postcode: Option<String>,
88 cities: Option<Vec<String>>,
89}
90
91pub fn documents(rows: impl IntoIterator<Item = AddressRow>, id_prefix: &str) -> Vec<Document> {
94 let mut grouper = Grouper::new(id_prefix);
95 for row in rows {
96 grouper.add(row);
97 }
98 grouper.finish()
99}
100
101pub struct Grouper {
104 id_prefix: String,
105 streets: HashMap<String, Street>,
106 street_order: Vec<String>,
107 municipalities: HashMap<String, Area>,
108 localities: HashMap<(String, String), Area>,
109}
110
111impl Grouper {
112 pub fn new(id_prefix: &str) -> Self {
113 Self {
114 id_prefix: id_prefix.to_string(),
115 streets: HashMap::new(),
116 street_order: Vec::new(),
117 municipalities: HashMap::new(),
118 localities: HashMap::new(),
119 }
120 }
121
122 pub fn add(&mut self, row: AddressRow) {
123 let Self {
124 streets,
125 street_order,
126 municipalities,
127 localities,
128 ..
129 } = self;
130 if row.street_names.is_empty() || row.housenumber.is_empty() {
131 return;
132 }
133 let street = streets.entry(row.street_id.clone()).or_insert_with(|| {
134 street_order.push(row.street_id.clone());
135 Street {
136 id: row.street_id.clone(),
137 names: row.street_names.clone(),
138 postcodes: Vec::new(),
139 cities: row.city_names.clone(),
140 municipality_id: row.municipality_id.clone(),
141 context: row.context.clone(),
142 housenumbers: Vec::new(),
143 }
144 });
145 if !street.postcodes.contains(&row.postcode) {
146 street.postcodes.push(row.postcode.clone());
147 }
148 if !street
149 .housenumbers
150 .iter()
151 .any(|h| h.number.eq_ignore_ascii_case(&row.housenumber))
152 {
153 let postcode = (row.postcode != street.postcodes[0]).then(|| row.postcode.clone());
154 let cities = (row.city_names != street.cities).then(|| row.city_names.clone());
155 street.housenumbers.push(Housenumber {
156 number: row.housenumber.clone(),
157 id: row.id.clone(),
158 lat: row.lat,
159 lon: row.lon,
160 postcode,
161 cities,
162 });
163 }
164
165 municipalities
166 .entry(row.municipality_id.clone())
167 .or_insert_with(|| Area {
168 names: row.municipality_names.clone(),
169 municipality_id: row.municipality_id.clone(),
170 municipality_names: row.municipality_names.clone(),
171 context: row.context.clone(),
172 ..Default::default()
173 })
174 .add(&row);
175
176 let is_municipality = row
177 .city_names
178 .first()
179 .is_none_or(|c| row.municipality_names.contains(c));
180 if !is_municipality {
181 localities
182 .entry((row.municipality_id.clone(), row.city_names[0].clone()))
183 .or_insert_with(|| Area {
184 names: row.city_names.clone(),
185 municipality_id: row.municipality_id.clone(),
186 municipality_names: row.municipality_names.clone(),
187 context: row.context.clone(),
188 ..Default::default()
189 })
190 .add(&row);
191 }
192 }
193
194 pub fn finish(self) -> Vec<Document> {
195 let Self {
196 id_prefix,
197 streets,
198 street_order,
199 municipalities,
200 localities,
201 } = self;
202 let id_prefix = id_prefix.as_str();
203 let max_area = municipalities
204 .values()
205 .map(|a| a.points.len())
206 .max()
207 .unwrap_or(1);
208 let max_street = streets
209 .values()
210 .map(|s| s.housenumbers.len())
211 .max()
212 .unwrap_or(1);
213 let municipality_size: HashMap<&str, usize> = municipalities
214 .iter()
215 .map(|(id, a)| (id.as_str(), a.points.len()))
216 .collect();
217
218 let mut docs = Vec::with_capacity(streets.len() + municipalities.len() + localities.len());
219
220 let mut municipality_ids: Vec<&String> = municipalities.keys().collect();
221 municipality_ids.sort();
222 for id in municipality_ids {
223 let area = &municipalities[id];
224 let (lat, lon) = central(&area.points);
225 let mut doc = Map::new();
226 doc.insert("id".into(), json!(format!("{id_prefix}_{id}")));
227 doc.insert("type".into(), json!("municipality"));
228 doc.insert("name".into(), names(&area.names));
229 doc.insert("postcode".into(), names(&area.postcodes));
230 doc.insert("citycode".into(), json!(area.municipality_id));
231 doc.insert("city".into(), names(&area.municipality_names));
232 doc.insert("context".into(), json!(area.context));
233 doc.insert(
234 "importance".into(),
235 json!(round(log_ratio(area.points.len(), max_area))),
236 );
237 doc.insert("lat".into(), json!(lat));
238 doc.insert("lon".into(), json!(lon));
239 docs.push(doc);
240 }
241
242 let mut locality_keys: Vec<&(String, String)> = localities.keys().collect();
243 locality_keys.sort();
244 for key in locality_keys {
245 let area = &localities[key];
246 let (lat, lon) = central(&area.points);
247 let mut doc = Map::new();
248 doc.insert(
249 "id".into(),
250 json!(format!(
251 "{id_prefix}_{}_{}",
252 area.municipality_id,
253 slug(&key.1)
254 )),
255 );
256 doc.insert("type".into(), json!("locality"));
257 doc.insert("name".into(), names(&area.names));
258 doc.insert("postcode".into(), names(&area.postcodes));
259 doc.insert("citycode".into(), json!(area.municipality_id));
260 doc.insert("city".into(), names(&area.municipality_names));
261 doc.insert("context".into(), json!(area.context));
262 doc.insert(
263 "importance".into(),
264 json!(round(0.8 * log_ratio(area.points.len(), max_area))),
265 );
266 doc.insert("lat".into(), json!(lat));
267 doc.insert("lon".into(), json!(lon));
268 docs.push(doc);
269 }
270
271 for key in street_order {
272 let street = &streets[&key];
273 let points: Vec<(f64, f64)> =
274 street.housenumbers.iter().map(|h| (h.lat, h.lon)).collect();
275 let (lat, lon) = central(&points);
276 let municipality = municipality_size
277 .get(street.municipality_id.as_str())
278 .copied()
279 .unwrap_or(1);
280 let importance = 0.7 * log_ratio(municipality, max_area)
282 + 0.3 * log_ratio(street.housenumbers.len(), max_street);
283 let housenumbers: Map<String, Value> = street
284 .housenumbers
285 .iter()
286 .map(|h| {
287 let mut data = Map::new();
288 data.insert("id".into(), json!(format!("{id_prefix}_{}", h.id)));
289 data.insert("lat".into(), json!(h.lat));
290 data.insert("lon".into(), json!(h.lon));
291 if let Some(postcode) = &h.postcode {
292 data.insert("postcode".into(), json!(postcode));
293 }
294 if let Some(cities) = &h.cities {
295 data.insert("city".into(), names(cities));
296 }
297 (h.number.clone(), Value::Object(data))
298 })
299 .collect();
300 let mut doc = Map::new();
301 doc.insert("id".into(), json!(format!("{id_prefix}_{}", street.id)));
302 doc.insert("type".into(), json!("street"));
303 doc.insert("name".into(), names(&street.names));
304 doc.insert("postcode".into(), names(&street.postcodes));
305 doc.insert("citycode".into(), json!(street.municipality_id));
306 doc.insert("city".into(), names(&street.cities));
307 doc.insert("context".into(), json!(street.context));
308 doc.insert("importance".into(), json!(round(importance)));
309 doc.insert("lat".into(), json!(lat));
310 doc.insert("lon".into(), json!(lon));
311 doc.insert("housenumbers".into(), Value::Object(housenumbers));
312 docs.push(doc);
313 }
314 docs
315 }
316}
317
318fn names(values: &[String]) -> Value {
320 match values {
321 [one] => json!(one),
322 _ => json!(values),
323 }
324}
325
326fn central(points: &[(f64, f64)]) -> (f64, f64) {
328 let n = points.len().max(1) as f64;
329 let (clat, clon) = points
330 .iter()
331 .fold((0.0, 0.0), |(a, b), (lat, lon)| (a + lat / n, b + lon / n));
332 points
333 .iter()
334 .copied()
335 .min_by(|a, b| {
336 let da = (a.0 - clat).powi(2) + (a.1 - clon).powi(2);
337 let db = (b.0 - clat).powi(2) + (b.1 - clon).powi(2);
338 da.total_cmp(&db)
339 })
340 .unwrap_or((clat, clon))
341}
342
343fn log_ratio(n: usize, max: usize) -> f64 {
345 if max == 0 {
346 return 0.0;
347 }
348 ((1 + n) as f64).ln() / ((1 + max) as f64).ln()
349}
350
351fn round(v: f64) -> f64 {
352 (v * 10_000.0).round() / 10_000.0
353}
354
355fn slug(value: &str) -> String {
356 crate::text::ascii(value).replace(' ', "-")
357}
358
359pub fn distinct(values: impl IntoIterator<Item = String>) -> Vec<String> {
361 let mut out: Vec<String> = Vec::new();
362 for v in values {
363 let v = v.trim().to_string();
364 if !v.is_empty() && !out.contains(&v) {
365 out.push(v);
366 }
367 }
368 out
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374
375 fn row(street: &str, number: &str, postcode: &str, city: &str, lat: f64) -> AddressRow {
376 AddressRow {
377 id: format!("{street}{number}"),
378 street_id: street.into(),
379 street_names: vec![format!("Rue {street}")],
380 housenumber: number.into(),
381 postcode: postcode.into(),
382 city_names: vec![city.into()],
383 municipality_id: "0501".into(),
384 municipality_names: vec!["Clervaux".into()],
385 context: "Clervaux".into(),
386 lat,
387 lon: 6.0,
388 }
389 }
390
391 #[test]
392 fn groups_streets_municipalities_and_localities() {
393 let docs = documents(
394 [
395 row("A", "1", "9755", "Hupperdange", 50.0),
396 row("A", "3", "9755", "Hupperdange", 50.002),
397 row("A", "3", "9755", "Hupperdange", 50.003),
398 row("A", "5", "9756", "Hupperdange", 50.004),
399 row("B", "2", "9701", "Clervaux", 50.1),
400 ],
401 "lu",
402 );
403 let kinds: Vec<(&str, &str)> = docs
404 .iter()
405 .map(|d| (d["type"].as_str().unwrap(), d["id"].as_str().unwrap()))
406 .collect();
407 assert_eq!(
408 kinds,
409 [
410 ("municipality", "lu_0501"),
411 ("locality", "lu_0501_hupperdange"),
412 ("street", "lu_A"),
413 ("street", "lu_B"),
414 ]
415 );
416 let a = &docs[2];
418 assert_eq!(a["housenumbers"].as_object().unwrap().len(), 3);
419 assert_eq!(a["housenumbers"]["3"]["lat"], 50.002);
420 assert_eq!(a["city"], "Hupperdange");
421 assert_eq!(a["postcode"], json!(["9755", "9756"]));
423 assert!(a["housenumbers"]["3"].get("postcode").is_none());
424 assert_eq!(a["housenumbers"]["5"]["postcode"], "9756");
425 assert_eq!(docs[0]["postcode"], json!(["9755", "9756", "9701"]));
426 assert_eq!(docs[0]["importance"], 1.0);
427 }
428}