geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! OSM areas that are relations: named venue multipolygons and named
//! administrative boundaries.
//!
//! A venue multipolygon (Tokyo Tower) becomes a place with its outline. A
//! boundary gives its outline to the settlement it stands for, linked the
//! way Nominatim links them: the boundary's `label` member, else the same
//! Wikidata item, else the same name, at a matching admin level, with the
//! settlement inside the boundary.
//!
//! The PBF stores relations after ways and ways after nodes, so the ways'
//! points are kept on disk during the OSM pass and the outlines are built
//! after it.

use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};

use crate::error::{Result, SearchError};

use crate::record::GeocodingLayer;
use crate::rings::{self, Ring};

/// What an area relation is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AreaKind {
    /// A named multipolygon with a venue tag: becomes a place.
    Venue,
    /// A named administrative boundary at this `admin_level`: gives its
    /// outline to a settlement.
    Boundary(u8),
}

/// A named area relation: its tags, member ways and the nodes it names.
#[derive(Debug, Clone)]
pub struct AreaRelation {
    /// Relation id.
    pub id: i64,
    /// What it is.
    pub kind: AreaKind,
    /// Its tags.
    pub tags: HashMap<String, String>,
    /// Outer ways (role `outer`, or none as older multipolygons have).
    pub outer: Vec<i64>,
    /// Inner ways.
    pub inner: Vec<i64>,
    /// Its `label` member node, if any.
    pub label: Option<i64>,
    /// Its `admin_centre` member node, if any.
    pub admin_centre: Option<i64>,
}

/// Reads the named venue multipolygons and named administrative
/// boundaries of `pbf`.
///
/// # Errors
/// When the file cannot be read.
pub fn load_area_relations(pbf: &Path) -> Result<Vec<AreaRelation>> {
    use osmpbf::{Element, RelMemberType};
    let mut found: Vec<AreaRelation> = osmpbf::ElementReader::from_path(pbf)
        .map_err(|source| SearchError::ReadOsmPbf {
            path: pbf.to_path_buf(),
            source,
        })?
        .par_map_reduce(
            |element| {
                let Element::Relation(rel) = element else {
                    return Vec::new();
                };
                let tags: HashMap<String, String> = rel
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                let Some(kind) = area_kind(&tags) else {
                    return Vec::new();
                };
                let mut relation = AreaRelation {
                    id: rel.id(),
                    kind,
                    tags,
                    outer: Vec::new(),
                    inner: Vec::new(),
                    label: None,
                    admin_centre: None,
                };
                for member in rel.members() {
                    let role = member.role().unwrap_or("");
                    match (member.member_type, role) {
                        (RelMemberType::Way, "" | "outer") => relation.outer.push(member.member_id),
                        (RelMemberType::Way, "inner") => relation.inner.push(member.member_id),
                        (RelMemberType::Node, "label") => relation.label = Some(member.member_id),
                        (RelMemberType::Node, "admin_centre") => {
                            relation.admin_centre = Some(member.member_id);
                        }
                        _ => {}
                    }
                }
                vec![relation]
            },
            Vec::new,
            |mut a, mut b| {
                a.append(&mut b);
                a
            },
        )?;
    found.sort_unstable_by_key(|r| r.id);
    Ok(found)
}

/// The kind of a relation with these tags, or `None` when it is neither a
/// named venue multipolygon nor a named administrative boundary.
fn area_kind(tags: &HashMap<String, String>) -> Option<AreaKind> {
    tags.get("name")?;
    let kind = tags.get("type").map(String::as_str);
    if kind == Some("multipolygon")
        && crate::osm::VENUE_KEYS
            .iter()
            .any(|key| tags.contains_key(*key))
    {
        return Some(AreaKind::Venue);
    }
    if matches!(kind, Some("boundary" | "multipolygon"))
        && tags.get("boundary").is_some_and(|b| b == "administrative")
    {
        let level = tags.get("admin_level")?.trim().parse::<u8>().ok()?;
        return Some(AreaKind::Boundary(level));
    }
    None
}

/// The points of the member ways, kept on disk during the OSM pass: each
/// way's points as `f64` pairs, and in memory only where each way starts.
pub struct WayPoints {
    path: PathBuf,
    out: Option<BufWriter<File>>,
    at: u64,
    index: HashMap<i64, (u64, u32)>,
}

impl WayPoints {
    /// An empty store with its file in `dir`.
    ///
    /// # Errors
    /// When the file cannot be created.
    pub fn new(dir: &Path) -> io::Result<Self> {
        let path = dir.join("area-ways.bin");
        Ok(Self {
            out: Some(BufWriter::new(File::create(&path)?)),
            path,
            at: 0,
            index: HashMap::new(),
        })
    }

    /// Keeps the points of way `id`.
    ///
    /// # Errors
    /// When the file cannot be written or the way is too long.
    pub fn add(&mut self, id: i64, points: &[[f64; 2]]) -> io::Result<()> {
        let Some(out) = self.out.as_mut() else {
            return Err(io::Error::other("way points already finished"));
        };
        for p in points {
            out.write_all(&p[0].to_le_bytes())?;
            out.write_all(&p[1].to_le_bytes())?;
        }
        let count = u32::try_from(points.len()).map_err(io::Error::other)?;
        self.index.insert(id, (self.at, count));
        self.at += 16 * u64::from(count);
        Ok(())
    }

    /// Ends writing; the points can then be read.
    ///
    /// # Errors
    /// When the file cannot be flushed.
    pub fn finish(&mut self) -> io::Result<()> {
        if let Some(out) = self.out.take() {
            out.into_inner()
                .map_err(io::IntoInnerError::into_error)?
                .sync_all()?;
        }
        Ok(())
    }

    /// The points of the ways in `ids` the file held; missing ways are left
    /// out.
    ///
    /// # Errors
    /// When the file cannot be read.
    pub fn read(&self, file: &File, ids: &[i64]) -> io::Result<Vec<Ring>> {
        let mut ways = Vec::with_capacity(ids.len());
        for id in ids {
            let Some(&(offset, count)) = self.index.get(id) else {
                continue;
            };
            let mut bytes = vec![0_u8; 16 * count as usize];
            read_exact_at(file, &mut bytes, offset)?;
            ways.push(
                bytes
                    .as_chunks::<16>()
                    .0
                    .iter()
                    .map(|c| {
                        let (lon, lat) = c.split_at(8);
                        [
                            f64::from_le_bytes(lon.try_into().unwrap_or([0; 8])),
                            f64::from_le_bytes(lat.try_into().unwrap_or([0; 8])),
                        ]
                    })
                    .collect(),
            );
        }
        Ok(ways)
    }

    /// Opens the finished file for [`WayPoints::read`].
    ///
    /// # Errors
    /// When it cannot be opened.
    pub fn open(&self) -> io::Result<File> {
        File::open(&self.path)
    }
}

impl Drop for WayPoints {
    fn drop(&mut self) {
        drop(self.out.take());
        std::fs::remove_file(&self.path).ok();
    }
}

/// Reads exactly `buf.len()` bytes of `file` at `offset`.
#[cfg(unix)]
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
    std::os::unix::fs::FileExt::read_exact_at(file, buf, offset)
}

/// Reads exactly `buf.len()` bytes of `file` at `offset`.
#[cfg(windows)]
fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
    while !buf.is_empty() {
        let read = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;
        if read == 0 {
            return Err(io::ErrorKind::UnexpectedEof.into());
        }
        buf = &mut buf[read..];
        offset += read as u64;
    }
    Ok(())
}

/// A settlement that may take a boundary's outline.
#[derive(Debug, Clone)]
pub struct Settlement {
    /// Its record id.
    pub record: u64,
    /// Its OSM node id.
    pub node: i64,
    /// Its layer.
    pub layer: GeocodingLayer,
    /// Its point.
    pub point: [f64; 2],
    /// Its Wikidata item, if tagged.
    pub wikidata: Option<String>,
    /// Hashes of its names, folded.
    pub names: Vec<u64>,
    /// Whether it is a city, town or village: one of the settlements that
    /// make a boundary holding several of them a parent unit.
    pub counted: bool,
}

/// Words that name a place's own unit, folded: "Ülde küla" is the village
/// of Ülde, "Teferrüç Mahallesi" the quarter of Teferrüç, "Jaipur
/// Municipal Corporation" and "Puri (M)" the cities. Words for a parent
/// unit (tehsil, mandal, district) are not here, so they keep the names
/// apart.
const OWN_UNIT_WORDS: [&str; 11] = [
    "katastralgemeinde",
    "kula",
    "mahallesi",
    "vca",
    "phuong",
    "xa",
    "κοινοτητα",
    "municipal",
    "corporation",
    "m",
    "urban",
];

/// A name folded for comparison, hashed: its words with case and accents
/// folded, without the words in `OWN_UNIT_WORDS` unless nothing else
/// is left.
#[must_use]
pub fn name_hash(name: &str) -> u64 {
    let words = glx::tokenize::query_tokens(name);
    let kept: Vec<&str> = words
        .iter()
        .map(String::as_str)
        .filter(|word| !OWN_UNIT_WORDS.contains(word))
        .collect();
    let words: Vec<&str> = if kept.is_empty() {
        words.iter().map(String::as_str).collect()
    } else {
        kept
    };
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    words.join(" ").hash(&mut hasher);
    hasher.finish()
}

/// A name-matched boundary at admin level 6 or 7 larger than this, in
/// km2, that holds another city, town or village is a parent unit (an
/// Indian tehsil named after its headquarters town), not the place. Chosen
/// on 600 judged cases from 204 countries and 2,817 Indian cases.
const PARENT_AREA_KM2: f64 = 50.0;

/// Area of `polygons` in km2, from square degrees near latitude `lat`.
fn area_km2(polygons: &[Vec<Ring>], lat: f64) -> f64 {
    rings::polygons_area(polygons) * 111.32 * 111.32 * lat.to_radians().cos()
}

/// The admin level a settlement of `layer` is usually bounded at, and how
/// far a name-matched boundary may be from it.
const fn level_of(layer: GeocodingLayer) -> Option<(u8, u8)> {
    match layer {
        GeocodingLayer::Country => Some((2, 0)),
        GeocodingLayer::Region => Some((4, 1)),
        GeocodingLayer::County => Some((5, 2)),
        GeocodingLayer::Locality => Some((8, 2)),
        GeocodingLayer::Address | GeocodingLayer::Venue | GeocodingLayer::Street => None,
    }
}

/// The names of a boundary, hashed: its name, English name and other
/// names.
fn boundary_names(tags: &HashMap<String, String>) -> HashSet<u64> {
    ["name", "name:en", "official_name", "alt_name", "short_name"]
        .iter()
        .filter_map(|key| tags.get(*key))
        .flat_map(|value| value.split(';'))
        .map(name_hash)
        .collect()
}

/// How a boundary matched a settlement; a lower value is a stronger link.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Link {
    /// The settlement is the boundary's `label` member.
    Label,
    /// Same Wikidata item.
    Wikidata,
    /// Same name, at this distance from the expected admin level.
    Name(u8),
}

/// The outline each settlement takes, by record id: of the boundaries that
/// link to it, the strongest link wins, then the smallest area.
#[must_use]
pub fn link_boundaries(
    settlements: &[Settlement],
    boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> HashMap<u64, Vec<Vec<Ring>>> {
    linked(settlements, boundaries)
        .into_iter()
        .map(|(index, at, _)| (settlements[index].record, boundaries[at].1.clone()))
        .collect()
}

/// The point of each linked boundary, by relation id: the point of the
/// settlement it links to, as Nominatim places a boundary at its linked
/// place (Tokyo's prefecture at the 東京都 node in Chiyoda, not at a point on
/// its Izu islands). A boundary two settlements link to takes the one of
/// the stronger link, then the first.
#[must_use]
pub fn linked_points(
    settlements: &[Settlement],
    boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> HashMap<i64, [f64; 2]> {
    let mut best: HashMap<i64, (Link, usize)> = HashMap::new();
    for (index, at, link) in linked(settlements, boundaries) {
        let entry = best.entry(boundaries[at].0.id).or_insert((link, index));
        if (link, index) < *entry {
            *entry = (link, index);
        }
    }
    best.into_iter()
        .map(|(relation, (_, index))| (relation, settlements[index].point))
        .collect()
}

/// The boundary each settlement links to and how, as (settlement,
/// boundary) indices.
fn linked(
    settlements: &[Settlement],
    boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> Vec<(usize, usize, Link)> {
    let counted: rstar::RTree<rstar::primitives::GeomWithData<[f64; 2], usize>> =
        rstar::RTree::bulk_load(
            settlements
                .iter()
                .enumerate()
                .filter(|(_, s)| s.counted)
                .map(|(index, s)| rstar::primitives::GeomWithData::new(s.point, index))
                .collect(),
        );
    // Whether another counted settlement than `index` lies in `polygons`.
    let holds_another = |polygons: &[Vec<Ring>], index: usize| -> bool {
        let mut bbox: Option<([f64; 2], [f64; 2])> = None;
        for p in polygons.iter().filter_map(|p| p.first()).flatten() {
            bbox = Some(bbox.map_or((*p, *p), |(lo, hi)| {
                (
                    [lo[0].min(p[0]), lo[1].min(p[1])],
                    [hi[0].max(p[0]), hi[1].max(p[1])],
                )
            }));
        }
        let Some((lo, hi)) = bbox else {
            return false;
        };
        counted
            .locate_in_envelope(rstar::AABB::from_corners(lo, hi))
            .any(|other| other.data != index && rings::polygons_contain(polygons, *other.geom()))
    };
    let mut by_node: HashMap<i64, usize> = HashMap::with_capacity(settlements.len());
    let mut by_wikidata: HashMap<&str, Vec<usize>> = HashMap::new();
    let mut by_name: HashMap<u64, Vec<usize>> = HashMap::new();
    for (index, settlement) in settlements.iter().enumerate() {
        by_node.insert(settlement.node, index);
        if let Some(item) = &settlement.wikidata {
            by_wikidata.entry(item.as_str()).or_default().push(index);
        }
        for &name in &settlement.names {
            by_name.entry(name).or_default().push(index);
        }
    }
    // Per settlement: the best link so far, its area and its boundary.
    let mut best: HashMap<usize, (Link, f64, usize)> = HashMap::new();
    for (at, (relation, polygons)) in boundaries.iter().enumerate() {
        let AreaKind::Boundary(level) = relation.kind else {
            continue;
        };
        let area = rings::polygons_area(polygons);
        let mut offer = |index: usize, link: Link| {
            let entry = best.entry(index).or_insert((link, area, at));
            if (link, area) < (entry.0, entry.1) {
                *entry = (link, area, at);
            }
        };
        if let Some(&index) = relation.label.and_then(|node| by_node.get(&node)) {
            offer(index, Link::Label);
        }
        if let Some(found) = relation
            .tags
            .get("wikidata")
            .and_then(|item| by_wikidata.get(item.as_str()))
        {
            for &index in found {
                offer(index, Link::Wikidata);
            }
        }
        let mut named: Vec<usize> = boundary_names(&relation.tags)
            .iter()
            .filter_map(|name| by_name.get(name))
            .flatten()
            .copied()
            .collect();
        named.sort_unstable();
        named.dedup();
        for index in named {
            let settlement = &settlements[index];
            let Some((expected, slack)) = level_of(settlement.layer) else {
                continue;
            };
            let distance = expected.abs_diff(level);
            if distance > slack || !rings::polygons_contain(polygons, settlement.point) {
                continue;
            }
            let parent = matches!(level, 6 | 7)
                && area_km2(polygons, settlement.point[1]) > PARENT_AREA_KM2
                && holds_another(polygons, index);
            if !parent {
                offer(index, Link::Name(distance));
            }
        }
    }
    best.into_iter()
        .map(|(index, (link, _, at))| (index, at, link))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn square(x: f64, y: f64, side: f64) -> Vec<Vec<Ring>> {
        vec![vec![vec![
            [x, y],
            [x + side, y],
            [x + side, y + side],
            [x, y + side],
            [x, y],
        ]]]
    }

    fn boundary(
        id: i64,
        name: &str,
        level: u8,
        label: Option<i64>,
        wikidata: Option<&str>,
    ) -> AreaRelation {
        let mut tags = HashMap::from([("name".to_string(), name.to_string())]);
        if let Some(item) = wikidata {
            tags.insert("wikidata".into(), item.into());
        }
        AreaRelation {
            id,
            kind: AreaKind::Boundary(level),
            tags,
            outer: Vec::new(),
            inner: Vec::new(),
            label,
            admin_centre: None,
        }
    }

    fn city(
        record: u64,
        node: i64,
        name: &str,
        point: [f64; 2],
        wikidata: Option<&str>,
    ) -> Settlement {
        Settlement {
            record,
            node,
            layer: GeocodingLayer::Locality,
            point,
            wikidata: wikidata.map(str::to_owned),
            names: vec![name_hash(name)],
            counted: true,
        }
    }

    /// Tokyo: the prefecture boundary (relation 1543125, Q1490) links to
    /// the 東京都 city node (265018692, Q1490) by Wikidata, so the
    /// prefecture's point is the node's (35.6768601, 139.7638947, where
    /// Nominatim places the prefecture), and a boundary nothing links to
    /// has none.
    #[test]
    fn a_linked_boundary_takes_its_settlements_point() {
        let tokyo = boundary(1_543_125, "東京都", 4, None, Some("Q1490"));
        let other = boundary(2, "Nowhere", 4, None, Some("Q2"));
        let boundaries = vec![
            (&tokyo, square(138.9, 24.0, 12.0)),
            (&other, square(0.0, 0.0, 1.0)),
        ];
        let node = city(
            10,
            265_018_692,
            "東京都",
            [139.763_894_7, 35.676_860_1],
            Some("Q1490"),
        );
        let points = linked_points(&[node], &boundaries);
        assert_eq!(points.get(&1_543_125), Some(&[139.763_894_7, 35.676_860_1]));
        assert_eq!(points.len(), 1);
    }

    /// Radaur, India: the town node and its tehsil (admin level 6, about
    /// 276 km2) share the name, and the tehsil holds other villages. The
    /// tehsil is a parent unit, so the town takes no outline. A level-6
    /// unit of the same size that holds no other town or village (a rural
    /// commune that is the place itself) still links.
    #[test]
    fn a_large_level_six_unit_holding_other_villages_is_a_parent() {
        // 0.15 degrees square at latitude 30: 16.7 km x 14.5 km = 242 km2.
        let tehsil = boundary(1, "Radaur", 6, None, None);
        let boundaries = vec![(&tehsil, square(77.0, 30.0, 0.15))];
        let town = city(10, 100, "Radaur", [77.05, 30.05], None);
        let village = city(11, 101, "Topra", [77.10, 30.10], None);
        let links = link_boundaries(&[town.clone(), village], &boundaries);
        assert!(!links.contains_key(&10), "the tehsil is not the town");
        let links = link_boundaries(&[town], &boundaries);
        assert_eq!(links.get(&10), Some(&square(77.0, 30.0, 0.15)));
    }

    /// The parent test needs both signals: a small level-6 unit (Puri
    /// municipality, 14.5 km2) links even with a suburb or village inside,
    /// and a level-8 boundary is never treated as a parent, whatever it
    /// holds.
    #[test]
    fn small_or_level_eight_units_link_with_others_inside() {
        // 0.03 degrees square at latitude 20: 3.3 km x 3.1 km = 10.4 km2.
        let puri = boundary(1, "Puri", 6, None, None);
        let boundaries = vec![(&puri, square(85.8, 19.8, 0.03))];
        let settlements = [
            city(10, 100, "Puri", [85.81, 19.81], None),
            city(11, 101, "Penthakata", [85.82, 19.82], None),
        ];
        assert_eq!(
            link_boundaries(&settlements, &boundaries).get(&10),
            Some(&square(85.8, 19.8, 0.03))
        );
        let commune = boundary(2, "Chisindia", 8, None, None);
        let boundaries = vec![(&commune, square(22.0, 46.2, 0.15))];
        let settlements = [
            city(20, 200, "Chisindia", [22.05, 46.25], None),
            city(21, 201, "Vasoaia", [22.10, 46.30], None),
        ];
        assert!(link_boundaries(&settlements, &boundaries).contains_key(&20));
    }

    /// A suburb or neighbourhood inside a unit is not one of the towns or
    /// villages that make it a parent.
    #[test]
    fn suburbs_do_not_make_a_parent() {
        let tehsil = boundary(1, "Radaur", 6, None, None);
        let boundaries = vec![(&tehsil, square(77.0, 30.0, 0.15))];
        let mut suburb = city(11, 101, "Topra", [77.10, 30.10], None);
        suburb.counted = false;
        let town = city(10, 100, "Radaur", [77.05, 30.05], None);
        assert!(link_boundaries(&[town, suburb], &boundaries).contains_key(&10));
    }

    /// Names compare folded: case and accents ("Jhārgrām" is "Jhargram"),
    /// and a word that names the place's own unit ("Ülde küla" is the
    /// village of Ülde). A word that names a parent unit ("Pachpadra
    /// Tehsil") still tells the names apart.
    #[test]
    fn names_fold_accents_and_own_unit_words() {
        assert_eq!(name_hash("Jhārgrām"), name_hash("Jhargram"));
        assert_eq!(name_hash("Ülde küla"), name_hash("Ülde"));
        assert_eq!(name_hash("Teferrüç Mahallesi"), name_hash("Teferrüç"));
        assert_eq!(name_hash("Katastralgemeinde Gerweis"), name_hash("Gerweis"));
        assert_eq!(name_hash("Phường Quy Nhơn"), name_hash("Quy Nhơn"));
        assert_eq!(
            name_hash("Jaipur Municipal Corporation"),
            name_hash("Jaipur")
        );
        assert_eq!(name_hash("Puri (M)"), name_hash("Puri"));
        assert_ne!(name_hash("Pachpadra Tehsil"), name_hash("Pachpadra"));
        assert_ne!(name_hash("Pune City Subdistrict"), name_hash("Pune"));
        // A name that is only a unit word keeps it.
        assert_ne!(name_hash("VCA"), name_hash(""));
    }

    /// Pune in OSM: the district (admin level 5) is named "Pune" and holds
    /// the city; no city boundary has the name. The city must not take the
    /// district's outline. Chennai's level-8 boundary has its name and holds
    /// it, so it takes that outline.
    #[test]
    fn a_city_takes_a_same_named_boundary_only_at_a_city_level() {
        let district = boundary(1, "Pune", 5, None, None);
        let chennai = boundary(2, "Chennai", 8, None, None);
        let boundaries = vec![
            (&district, square(73.0, 18.0, 1.0)),
            (&chennai, square(80.0, 13.0, 0.5)),
        ];
        let settlements = vec![
            city(10, 100, "Pune", [73.86, 18.52], None),
            city(20, 200, "Chennai", [80.27, 13.08], None),
        ];
        let links = link_boundaries(&settlements, &boundaries);
        assert_eq!(links.len(), 1);
        assert_eq!(links.get(&20), Some(&square(80.0, 13.0, 0.5)));
    }

    /// A name match needs the settlement inside the boundary: a town named
    /// like a far boundary does not take it.
    #[test]
    fn a_name_match_must_hold_the_settlement() {
        let far = boundary(1, "Rampur", 8, None, None);
        let boundaries = vec![(&far, square(80.0, 25.0, 0.1))];
        let settlements = vec![city(10, 100, "Rampur", [77.0, 28.0], None)];
        assert!(link_boundaries(&settlements, &boundaries).is_empty());
    }

    /// The label member links whatever the name or level; a Wikidata match
    /// beats a name match, and of two name matches the one at the expected
    /// level wins, then the smaller.
    #[test]
    fn the_strongest_link_wins() {
        let labelled = boundary(1, "Other Name", 4, Some(100), None);
        let by_item = boundary(2, "Jaipur Subdistrict", 6, None, Some("Q66485"));
        let level9 = boundary(3, "Jaipur", 9, None, None);
        let level8_big = boundary(4, "Jaipur", 8, None, None);
        let level8_small = boundary(5, "Jaipur", 8, None, None);
        let boundaries = vec![
            (&labelled, square(0.0, 0.0, 1.0)),
            (&by_item, square(75.0, 26.0, 2.0)),
            (&level9, square(75.7, 26.8, 0.3)),
        ];
        let settlements = vec![
            city(10, 100, "Somewhere", [0.5, 0.5], None),
            city(20, 200, "Jaipur", [75.79, 26.91], Some("Q66485")),
        ];
        let links = link_boundaries(&settlements, &boundaries);
        assert_eq!(links.get(&10), Some(&square(0.0, 0.0, 1.0)));
        assert_eq!(links.get(&20), Some(&square(75.0, 26.0, 2.0)));
        // Without the Wikidata item: level 8 beats level 9; of the two at
        // level 8 the smaller wins.
        let boundaries = vec![
            (&level9, square(75.7, 26.8, 0.3)),
            (&level8_big, square(75.0, 26.0, 2.0)),
            (&level8_small, square(75.5, 26.5, 0.6)),
        ];
        let settlements = vec![city(20, 200, "Jaipur", [75.79, 26.91], None)];
        let links = link_boundaries(&settlements, &boundaries);
        assert_eq!(links.get(&20), Some(&square(75.5, 26.5, 0.6)));
    }

    #[test]
    fn area_kinds_need_a_name_and_a_kind() {
        let tags = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
            pairs
                .iter()
                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                .collect()
        };
        assert_eq!(
            area_kind(&tags(&[
                ("type", "boundary"),
                ("boundary", "administrative"),
                ("admin_level", "8"),
                ("name", "Chennai")
            ])),
            Some(AreaKind::Boundary(8))
        );
        assert_eq!(
            area_kind(&tags(&[
                ("type", "multipolygon"),
                ("tourism", "attraction"),
                ("name", "Tokyo Tower")
            ])),
            Some(AreaKind::Venue)
        );
        // No name, no level, or not administrative.
        assert_eq!(
            area_kind(&tags(&[
                ("type", "boundary"),
                ("boundary", "administrative"),
                ("admin_level", "8")
            ])),
            None
        );
        assert_eq!(
            area_kind(&tags(&[
                ("type", "boundary"),
                ("boundary", "administrative"),
                ("name", "X")
            ])),
            None
        );
        assert_eq!(
            area_kind(&tags(&[
                ("type", "boundary"),
                ("boundary", "postal_code"),
                ("admin_level", "8"),
                ("name", "X")
            ])),
            None
        );
    }

    #[test]
    fn way_points_come_back_from_disk() {
        let dir = tempfile::tempdir().expect("tmp");
        let mut store = WayPoints::new(dir.path()).expect("store");
        store.add(7, &[[1.5, 2.5], [3.0, 4.0]]).expect("add");
        store.add(9, &[[-180.0, -90.0]]).expect("add");
        store.finish().expect("finish");
        let file = store.open().expect("open");
        let ways = store.read(&file, &[9, 8, 7]).expect("read");
        assert_eq!(
            ways,
            vec![vec![[-180.0, -90.0]], vec![[1.5, 2.5], [3.0, 4.0]]]
        );
    }
}