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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Overture `divisions/division` points → geocoding records.
//!
//! The OSM pass writes named `place=*` nodes; Overture's division points
//! hold more: neighbourhoods and wards mapped as OSM boundary relations,
//! `place=locality` nodes, and places from other sources (LINZ, geoBoundaries
//! and the like). A division point is written unless the OSM pass already
//! wrote the same place: an OSM-sourced point by its OSM element id, any
//! other by the same name within [`SAME_PLACE_M`].

use std::collections::HashMap;

use crate::importance::{Wikipedia, default_importance};
use crate::osm::record_id;
use crate::place_importance::{SettlementClass, division_signals, settlement_importance};
use crate::record::{GeocodingLayer, GeocodingRecord, RecordInit};
use geolith::admin::{AdminHierarchy, AdminHierarchyIndex};
use geolith::conflation::spatial::haversine_distance_m;
use geolith::source::input::{InputFeature, OsmElementType};
use geolith::source::reader::SOURCE_ID_PROP;
use geolith::tile::feature::PropValue;

/// How close a non-OSM division point must be to an OSM place of the same
/// name to be the same place.
pub const SAME_PLACE_M: f64 = 2_000.0;

/// How far a district's label point may lie from its seat town, the town
/// of the same name it ranks below (Uttar Bastar Kanker: 55 km).
pub const SEAT_KM: f64 = 60.0;

/// Grid cell of the same-place check, in degrees: wider than
/// [`SAME_PLACE_M`] away from the poles, so the 3 × 3 cells around a point
/// hold every place within it.
const CELL_DEG: f64 = 0.05;

fn prop<'a>(feature: &'a InputFeature, key: &str) -> Option<&'a str> {
    match feature.properties.get(key) {
        Some(PropValue::Str(s)) if !s.trim().is_empty() => Some(s.trim()),
        _ => None,
    }
}

/// The layer and Nominatim search rank of a division subtype
/// (`settings/address-levels.json`), as [`crate::osm::place_layer`]
/// ranks the OSM place values: a city 16 down to a neighbourhood 24.
#[must_use]
pub fn division_layer(subtype: &str, class: Option<&str>) -> Option<(GeocodingLayer, u8)> {
    Some(match subtype {
        "country" | "dependency" => (GeocodingLayer::Country, 4),
        "region" => (GeocodingLayer::Region, 8),
        "county" => (GeocodingLayer::County, 12),
        "localadmin" => (GeocodingLayer::County, 14),
        "locality" => (
            GeocodingLayer::Locality,
            match class {
                Some("city") => 16,
                Some("town") => 18,
                Some("hamlet") => 20,
                _ => 19,
            },
        ),
        "macrohood" => (GeocodingLayer::Locality, 19),
        "neighborhood" => (GeocodingLayer::Locality, 20),
        "microhood" => (GeocodingLayer::Locality, 24),
        _ => return None,
    })
}

/// The OSM record id of a point Overture took from OSM: `sources.record_id`
/// is the element type letter, its id and its version (`n240109189@20`).
#[must_use]
pub fn osm_record_id(feature: &InputFeature) -> Option<u64> {
    if prop(feature, "sources.dataset")? != "OpenStreetMap" {
        return None;
    }
    let source = prop(feature, "sources.record_id")?;
    let element = match source.get(..1)? {
        "n" => OsmElementType::Node,
        "w" => OsmElementType::Way,
        "r" => OsmElementType::Relation,
        _ => return None,
    };
    let id = source.get(1..)?.split('@').next()?.parse::<u64>().ok()?;
    Some(record_id(element, id))
}

/// Lower case, for the same-name check.
fn fold(name: &str) -> String {
    name.trim().to_lowercase()
}

/// The point's primary and English names, folded.
fn folded_names(feature: &InputFeature) -> Vec<String> {
    let mut names: Vec<String> = Vec::with_capacity(2);
    for key in ["names.primary", "names.common.en"] {
        if let Some(name) = prop(feature, key) {
            let name = fold(name);
            if !names.contains(&name) {
                names.push(name);
            }
        }
    }
    names
}

fn point(feature: &InputFeature) -> Option<(f64, f64)> {
    match feature.geometry.as_ref() {
        geo::Geometry::Point(p) => Some((p.x(), p.y())),
        _ => None,
    }
}

fn cell(lon: f64, lat: f64) -> (i32, i32) {
    // Degrees divided by the cell size stay far inside the i32 range.
    let at = |v: f64| (v / CELL_DEG).floor() as i32;
    (at(lon), at(lat))
}

/// The admin levels above `layer`: a district's label point lies in one of
/// its towns, but the district is not part of that town, so its search text
/// must not hold the town's name; a town keeps no locality or
/// neighbourhood, as a city is not in one of its wards.
pub(crate) fn above(mut admin: AdminHierarchy, layer: GeocodingLayer, rank: u8) -> AdminHierarchy {
    match layer {
        GeocodingLayer::Country => {
            admin = AdminHierarchy {
                country_code: admin.country_code,
                ..AdminHierarchy::default()
            };
        }
        GeocodingLayer::Region => {
            admin.region = None;
            admin.county = None;
            admin.locality = None;
            admin.neighbourhood = None;
        }
        GeocodingLayer::County => {
            admin.county = None;
            admin.locality = None;
            admin.neighbourhood = None;
        }
        // A city or town (Nominatim rank 18 or less); a suburb or
        // neighbourhood keeps its town.
        GeocodingLayer::Locality if rank <= TOWN_RANK => {
            admin.locality = None;
            admin.neighbourhood = None;
        }
        GeocodingLayer::Locality => admin.neighbourhood = None,
        _ => {}
    }
    admin
}

/// The highest Nominatim search rank of a town: a place of this rank or
/// lower is in no locality of its own.
pub(crate) const TOWN_RANK: u8 = 18;

/// Whether a division point is an admin area that does not belong to India
/// (see [`geolith::admin::soi_area::is_foreign_admin_area`]).
fn is_foreign_admin_area(feature: &InputFeature) -> bool {
    prop(feature, "subtype").is_some_and(|subtype| {
        geolith::admin::soi_area::is_foreign_admin_area(
            subtype,
            prop(feature, "country"),
            prop(feature, "region"),
        )
    })
}

/// A geocoding record for a division point, at `at` when set (see
/// [`DivisionIndex::located`]), or `None` for a subtype that is not a place
/// to search (or a point with no name).
#[must_use]
pub fn division_record(
    feature: &InputFeature,
    at: Option<(f64, f64)>,
    admin_index: &AdminHierarchyIndex,
    wikipedia: &Wikipedia,
) -> Option<GeocodingRecord> {
    let (layer, rank) = division_layer(prop(feature, "subtype")?, prop(feature, "class"))?;
    let name = prop(feature, "names.primary")?.to_string();
    let (lon, lat) = at.or_else(|| point(feature))?;
    // Inside Survey of India land only India's own admin areas are indexed.
    if is_foreign_admin_area(feature) && admin_index.in_soi(lon, lat) {
        return None;
    }
    let mut names = HashMap::new();
    for (key, value) in &feature.properties {
        if let Some(lang) = key.strip_prefix("names.common.")
            && let PropValue::Str(v) = value
            && !v.trim().is_empty()
        {
            names.insert(lang.to_string(), v.trim().to_string());
        }
    }
    let importance = (prop(feature, "subtype") == Some("locality"))
        .then(|| prop(feature, "class").and_then(SettlementClass::from_overture))
        .flatten()
        .map(|class| {
            settlement_importance(
                wikipedia,
                prop(feature, "wikidata"),
                class,
                &division_signals(feature),
            )
        })
        .unwrap_or_else(|| {
            prop(feature, "wikidata")
                .and_then(|item| wikipedia.get(item))
                .unwrap_or_else(|| default_importance(rank))
        });
    let mut record = GeocodingRecord::new(RecordInit {
        id: feature.id,
        source: feature.source.clone(),
        layer,
        name,
        lon,
        lat,
        admin: above(admin_index.resolve(lon, lat), layer, rank),
        address: None,
        names,
        importance,
    });
    if let Some(source_id) = prop(feature, SOURCE_ID_PROP) {
        record = record.with_source_id(source_id);
    }
    record.prefer_english_name();
    record.shape = crate::shape::admin_outline(admin_index, &record);
    Some(record)
}

/// A written OSM town that may be a district's seat: position, importance
/// and the words of its name.
type Seat = (f64, f64, f32, Vec<String>);

/// The words of the point's primary and English names, folded as the index
/// folds them.
fn name_words(feature: &InputFeature) -> Vec<String> {
    let mut words: Vec<String> = Vec::new();
    for name in folded_names(feature) {
        for word in glx::tokenize::index_tokens(&name) {
            if !words.contains(&word) {
                words.push(word);
            }
        }
    }
    words
}

/// The division points the OSM pass may already write, to tell which are
/// new: the OSM ids of the OSM-sourced points, and the names and positions
/// of all.
#[derive(Debug, Default)]
pub struct DivisionIndex {
    /// OSM record ids of OSM-sourced points, sorted, each with whether the
    /// OSM pass wrote it.
    osm: Vec<(u64, bool)>,
    /// Points by source id: their folded names, position and whether
    /// an OSM place of the same name lies within [`SAME_PLACE_M`].
    others: HashMap<String, (Vec<String>, f64, f64, bool)>,
    /// Source ids of the points per grid cell.
    grid: HashMap<(i32, i32), Vec<String>>,
    /// Each word of the district and state names, with the written OSM
    /// towns whose name starts with it: position, importance and words.
    seats: HashMap<String, Vec<Seat>>,
    /// The points of the OSM boundaries the OSM pass linked to a
    /// settlement, by OSM record id: the settlement's point.
    linked: HashMap<u64, (f64, f64)>,
}

impl DivisionIndex {
    /// Notes the boundaries the OSM pass linked to a settlement, by relation
    /// id, with the settlement's point.
    pub fn place_linked(&mut self, points: &HashMap<i64, [f64; 2]>) {
        self.linked.reserve(points.len());
        for (&relation, &[lon, lat]) in points {
            self.linked.insert(
                record_id(OsmElementType::Relation, relation.unsigned_abs()),
                (lon, lat),
            );
        }
    }

    /// Where a division point is placed: an OSM boundary linked to a
    /// settlement at the settlement, as Nominatim places a boundary at its
    /// linked place; any other at its own point. Overture's point for a
    /// boundary can lie far from the place it names (Tokyo's prefecture on
    /// its Izu islands, 165 km south of the city).
    #[must_use]
    pub fn located(&self, feature: &InputFeature) -> Option<(f64, f64)> {
        osm_record_id(feature)
            .and_then(|id| self.linked.get(&id).copied())
            .or_else(|| point(feature))
    }

    /// Adds one division point.
    pub fn add(&mut self, feature: &InputFeature) {
        let Some((layer, _)) = division_layer(prop(feature, "subtype").unwrap_or(""), None) else {
            return;
        };
        if matches!(layer, GeocodingLayer::County | GeocodingLayer::Region) {
            for word in name_words(feature) {
                self.seats.entry(word).or_default();
            }
        }
        if let Some(id) = osm_record_id(feature) {
            self.osm.push((id, false));
        }
        // Every point is also told by name and position: an OSM relation
        // the OSM pass skipped often has its place node written instead.
        let (Some(source_id), Some((lon, lat))) = (prop(feature, SOURCE_ID_PROP), point(feature))
        else {
            return;
        };
        let names = folded_names(feature);
        if names.is_empty() {
            return;
        }
        self.grid
            .entry(cell(lon, lat))
            .or_default()
            .push(source_id.to_string());
        self.others
            .insert(source_id.to_string(), (names, lon, lat, false));
    }

    /// Sorts the OSM ids; call once after the last [`Self::add`].
    pub fn seal(&mut self) {
        self.osm.sort_unstable_by_key(|(id, _)| *id);
        self.osm.dedup_by_key(|(id, _)| *id);
    }

    /// Notes a record the OSM pass wrote.
    pub fn mark(&mut self, record: &GeocodingRecord) {
        if let Ok(at) = self.osm.binary_search_by_key(&record.id, |(id, _)| *id) {
            self.osm[at].1 = true;
        }
        if record.layer == GeocodingLayer::Locality && !self.seats.is_empty() {
            for name in record.all_names() {
                let words = glx::tokenize::index_tokens(name);
                if let Some(towns) = words.first().and_then(|first| self.seats.get_mut(first)) {
                    towns.push((record.lon, record.lat, record.importance, words));
                }
            }
        }
        if self.others.is_empty() {
            return;
        }
        let names: Vec<String> = record.all_names().into_iter().map(fold).collect();
        let (cx, cy) = cell(record.lon, record.lat);
        for dx in -1..=1 {
            for dy in -1..=1 {
                let Some(ids) = self.grid.get(&(cx + dx, cy + dy)) else {
                    continue;
                };
                for source_id in ids {
                    if let Some((own, lon, lat, seen)) = self.others.get_mut(source_id)
                        && !*seen
                        && own.iter().any(|name| names.contains(name))
                        && haversine_distance_m(record.lon, record.lat, *lon, *lat) <= SAME_PLACE_M
                    {
                        *seen = true;
                    }
                }
            }
        }
    }

    /// For a district or state named after its seat town, an importance just
    /// below the town's, so the town ranks first, as Nominatim links a
    /// boundary to its own town. The seat is the nearest written OSM town
    /// within [`SEAT_KM`] whose name's words are all in the district's name
    /// ("Kanker" for "Uttar Bastar Kanker"); `None` when there is none.
    #[must_use]
    pub fn seat_importance(&self, feature: &InputFeature) -> Option<f32> {
        let (layer, _) = division_layer(prop(feature, "subtype")?, None)?;
        if !matches!(layer, GeocodingLayer::County | GeocodingLayer::Region) {
            return None;
        }
        let (lon, lat) = self.located(feature)?;
        let words = name_words(feature);
        words
            .iter()
            .filter_map(|word| self.seats.get(word))
            .flatten()
            .filter(|(_, _, _, town)| town.iter().all(|w| words.contains(w)))
            .map(|&(x, y, importance, _)| (haversine_distance_m(lon, lat, x, y), importance))
            .filter(|(m, _)| *m <= SEAT_KM * 1_000.0)
            .min_by(|a, b| a.0.total_cmp(&b.0))
            .map(|(_, importance)| importance * 0.99)
    }

    /// Whether the OSM pass already wrote the place of this division point:
    /// its own OSM element, or a place of the same name within
    /// [`SAME_PLACE_M`].
    #[must_use]
    pub fn written(&self, feature: &InputFeature) -> bool {
        let by_id = osm_record_id(feature).is_some_and(|id| {
            self.osm
                .binary_search_by_key(&id, |(id, _)| *id)
                .is_ok_and(|at| self.osm[at].1)
        });
        by_id
            || prop(feature, SOURCE_ID_PROP)
                .and_then(|source_id| self.others.get(source_id))
                .is_some_and(|(_, _, _, seen)| *seen)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use geolith::source::input::DataSource;

    fn division(props: &[(&str, &str)], lon: f64, lat: f64) -> InputFeature {
        InputFeature {
            id: 7,
            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(lon, lat))),
            properties: props
                .iter()
                .map(|(k, v)| ((*k).to_string(), PropValue::Str((*v).to_string())))
                .collect(),
            bbox: None,
            source: DataSource::Overture {
                theme: "divisions".into(),
                otype: "division".into(),
            },
        }
    }

    fn osm(record: &str) -> InputFeature {
        division(
            &[
                ("subtype", "locality"),
                ("names.primary", "Agatti"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", record),
            ],
            72.18,
            10.86,
        )
    }

    #[test]
    fn an_osm_source_gives_the_osm_record_id() {
        assert_eq!(osm_record_id(&osm("n982044205@6")), Some(982_044_205));
        assert_eq!(osm_record_id(&osm("w42@1")), Some((1 << 62) | 42));
        assert_eq!(
            osm_record_id(&osm("r2027460@26")),
            Some((2 << 62) | 2_027_460)
        );
        assert_eq!(osm_record_id(&osm("x42@1")), None);
        assert_eq!(osm_record_id(&osm("n@1")), None);
        let linz = division(
            &[("sources.dataset", "Linz"), ("sources.record_id", "n42@1")],
            0.0,
            0.0,
        );
        assert_eq!(osm_record_id(&linz), None);
    }

    #[test]
    fn subtypes_take_nominatim_ranks() {
        assert_eq!(
            division_layer("locality", Some("city")),
            Some((GeocodingLayer::Locality, 16))
        );
        assert_eq!(
            division_layer("locality", None),
            Some((GeocodingLayer::Locality, 19))
        );
        assert_eq!(
            division_layer("neighborhood", None),
            Some((GeocodingLayer::Locality, 20))
        );
        assert_eq!(
            division_layer("county", None),
            Some((GeocodingLayer::County, 12))
        );
        assert_eq!(
            division_layer("region", None),
            Some((GeocodingLayer::Region, 8))
        );
        assert_eq!(division_layer("ocean", None), None);
    }

    /// A district's label point lies in one of its towns, but the district
    /// is not in that town: "Tungjoy" must not find Senapati district. A
    /// record keeps only the admin levels above its own, as Pelias's
    /// hierarchy does.
    #[test]
    fn a_division_keeps_only_the_admin_levels_above_its_own() {
        use geolith::admin::AdminHierarchy;
        let admin = AdminHierarchy {
            country_code: Some("IN".into()),
            country: Some("India".into()),
            region: Some("Manipur".into()),
            county: Some("Senapati".into()),
            locality: Some("Tungjoy".into()),
            neighbourhood: Some("Ward 1".into()),
            borough: None,
            postcode: None,
            city: None,
        };
        let county = above(admin.clone(), GeocodingLayer::County, 12);
        assert_eq!(county.locality, None);
        assert_eq!(county.neighbourhood, None);
        assert_eq!(county.county, None);
        assert_eq!(county.region.as_deref(), Some("Manipur"));
        let region = above(admin.clone(), GeocodingLayer::Region, 8);
        assert_eq!(region.region, None);
        assert_eq!(region.country.as_deref(), Some("India"));
        let country = above(admin.clone(), GeocodingLayer::Country, 4);
        assert_eq!(country.country, None);
        assert_eq!(country.country_code.as_deref(), Some("IN"));
        // A neighbourhood keeps its town.
        let hood = above(admin.clone(), GeocodingLayer::Locality, 20);
        assert_eq!(hood.locality.as_deref(), Some("Tungjoy"));
        assert_eq!(hood.neighbourhood, None);
        // A town is in no locality.
        let town = above(admin, GeocodingLayer::Locality, 18);
        assert_eq!(town.locality, None);
        assert_eq!(town.county.as_deref(), Some("Senapati"));
    }

    /// Overture places Tokyo's prefecture (from OSM relation 1543125) at
    /// 34.2256, 139.2948 on the Izu islands. The OSM pass linked the
    /// boundary to the 東京都 city node, so the prefecture stands at the
    /// node (35.6768601, 139.7638947, Nominatim's point), and the city there
    /// is its seat: the prefecture ranks just below it. A point the pass did
    /// not link keeps its own position.
    #[test]
    fn a_linked_boundary_stands_at_its_settlement() {
        let prefecture = division(
            &[
                ("subtype", "region"),
                ("names.primary", "東京都"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r1543125@384"),
            ],
            139.294_774_5,
            34.225_580_4,
        );
        let mut index = DivisionIndex::default();
        index.add(&prefecture);
        index.seal();
        let mut city = written_osm_place(265_018_692, "東京都", 139.763_894_7, 35.676_860_1);
        city.importance = 0.834;
        index.mark(&city);
        assert_eq!(
            index.located(&prefecture),
            Some((139.294_774_5, 34.225_580_4))
        );
        assert_eq!(
            index.seat_importance(&prefecture),
            None,
            "the city is 165 km away"
        );
        index.place_linked(&HashMap::from([(1_543_125, [139.763_894_7, 35.676_860_1])]));
        assert_eq!(
            index.located(&prefecture),
            Some((139.763_894_7, 35.676_860_1))
        );
        let below = index
            .seat_importance(&prefecture)
            .expect("the city is the seat");
        assert!(below < 0.834, "{below}");
        let admin = geolith::admin::AdminHierarchyBuilder::new()
            .build()
            .expect("admin");
        let record = division_record(
            &prefecture,
            index.located(&prefecture),
            &admin,
            &Wikipedia::default(),
        )
        .expect("a region");
        assert_eq!((record.lon, record.lat), (139.763_894_7, 35.676_860_1));
        let other = osm("n2@1");
        assert_eq!(index.located(&other), Some((72.18, 10.86)));
    }

    /// A division point of Overture's own (no OSM node behind it) takes the
    /// same floor from its own `population`, `cartography.prominence` and
    /// `capital_of_divisions`, and the default of its class without them.
    #[test]
    fn an_overture_locality_takes_its_floor_from_its_own_signals() {
        let admin = geolith::admin::AdminHierarchyBuilder::new()
            .build()
            .expect("admin");
        let wikipedia =
            Wikipedia::read("sv\ta\tDesa_Tawang\t0.21822785325192331\tQ12520130\n".as_bytes())
                .expect("rows");
        let importance = |class: Option<&str>, extra: &[(&str, PropValue)]| {
            let mut props = vec![("subtype", "locality"), ("names.primary", "Tawang")];
            if let Some(class) = class {
                props.push(("class", class));
            }
            let mut feature = division(&props, 91.86, 27.59);
            for (key, value) in extra {
                feature.properties.insert((*key).to_string(), value.clone());
            }
            division_record(&feature, None, &admin, &wikipedia)
                .expect("a locality")
                .importance
        };
        let seat = [
            ("population", PropValue::I64(11_000)),
            ("cartography.prominence", PropValue::I64(58)),
            ("capital_of_divisions", PropValue::Str("county".into())),
        ];
        assert!((importance(Some("town"), &seat) - 0.40).abs() < 1e-6);
        // a town of 11 000 and nothing else: 0.16001 + 0.10 * log10(11)
        let town = [("population", PropValue::I64(11_000))];
        assert!((importance(Some("town"), &town) - 0.264_15).abs() < 1e-4);
        assert!((importance(Some("town"), &[]) - 0.160_01).abs() < 1e-4);
        assert!((importance(Some("hamlet"), &[]) - 0.133_34).abs() < 1e-4);
        // no class: the default of rank 19, and no floor
        assert!((importance(None, &seat) - 0.146_68).abs() < 1e-4);
        // a neighbourhood keeps its default whatever it says
        let mut hood = division(
            &[("subtype", "neighborhood"), ("names.primary", "Tawang")],
            91.86,
            27.59,
        );
        hood.properties
            .insert("population".into(), PropValue::I64(500_000));
        let record = division_record(&hood, None, &admin, &wikipedia).expect("a neighbourhood");
        assert!(
            (record.importance - 0.133_34).abs() < 1e-4,
            "{}",
            record.importance
        );
    }

    /// A district named after its seat town ranks below that town, as
    /// Nominatim links a boundary to its own town: "Dhamtari" is the town
    /// first, then Dhamtari district, whose Wikipedia article (0.4978) has a
    /// higher importance than the town's (0.4365). The seat is a written
    /// OSM town of the same name within [`SEAT_KM`]: Dhamtari town is 26 km
    /// from the district's label point. A district with no such town keeps
    /// its importance.
    #[test]
    fn a_district_named_after_its_seat_town_ranks_below_it() {
        let district = division(
            &[
                ("subtype", "county"),
                ("names.primary", "Dhamtari"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r1972719@21"),
            ],
            81.7156,
            20.5326,
        );
        let lonely = division(
            &[
                ("subtype", "county"),
                ("names.primary", "Senapati"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r2027936@20"),
            ],
            94.15,
            25.39,
        );
        // A town of the same name 1 degree of latitude (111 km) away is not
        // the seat.
        let far = division(
            &[
                ("subtype", "county"),
                ("names.primary", "Kanker"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r1@1"),
            ],
            81.0,
            20.0,
        );
        // A district named for its seat with more words: "Ramban district",
        // "Uttar Bastar Kanker". Its seat is 11 km from its label point.
        let worded = division(
            &[
                ("subtype", "county"),
                ("names.primary", "Ramban district"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r2@1"),
            ],
            75.25,
            33.30,
        );
        let mut index = DivisionIndex::default();
        index.add(&district);
        index.add(&lonely);
        index.add(&far);
        index.add(&worded);
        index.seal();
        let mut ramban = written_osm_place(9, "Ramban", 75.19, 33.24);
        ramban.importance = 0.2;
        index.mark(&ramban);
        index.mark(&written_osm_place(8, "Kanker", 81.0, 21.0));
        let mut town = written_osm_place(12_289_058_716, "Dhamtari", 81.5464, 20.7075);
        town.importance = 0.4365;
        index.mark(&town);
        // Same name, but a district: not a seat.
        let mut other = written_osm_place(7, "Senapati", 94.16, 25.40);
        other.layer = GeocodingLayer::County;
        index.mark(&other);
        // A town whose name has a word the district's lacks is not its seat.
        index.mark(&written_osm_place(10, "Senapati Hills", 94.16, 25.40));
        assert!(index.seat_importance(&district).is_some_and(|i| i < 0.4365));
        assert_eq!(index.seat_importance(&lonely), None);
        assert_eq!(index.seat_importance(&far), None);
        assert!(index.seat_importance(&worded).is_some_and(|i| i < 0.2));
    }

    fn written_osm_place(id: u64, name: &str, lon: f64, lat: f64) -> GeocodingRecord {
        GeocodingRecord::new(RecordInit {
            id,
            source: DataSource::Osm {
                element_type: OsmElementType::Node,
                relations: Vec::new(),
            },
            layer: GeocodingLayer::Locality,
            name: name.to_string(),
            lon,
            lat,
            admin: geolith::admin::AdminHierarchy::default(),
            address: None,
            names: HashMap::new(),
            importance: 0.1,
        })
    }

    /// An OSM-sourced point is the place the OSM pass wrote with the same
    /// element id; others are the same place by name within 2 km. Wellington
    /// to a point 0.015 degrees north: 0.015 * 111,195 m = 1,668 m; 0.02
    /// degrees north: 2,224 m.
    #[test]
    fn written_places_are_told_by_osm_id_or_by_name_and_distance() {
        let node = osm("n982044205@6");
        let other = osm("n5@1");
        let near = division(
            &[
                ("subtype", "locality"),
                ("names.primary", "Wellington"),
                (SOURCE_ID_PROP, "near"),
                ("sources.dataset", "Linz"),
            ],
            174.7762,
            -41.2865,
        );
        let far = division(
            &[
                ("subtype", "locality"),
                ("names.primary", "Wellington"),
                (SOURCE_ID_PROP, "far"),
            ],
            174.7762,
            -41.2815,
        );
        let mut index = DivisionIndex::default();
        for f in [&node, &other, &near, &far] {
            index.add(f);
        }
        index.seal();
        index.mark(&written_osm_place(982_044_205, "Agatti", 72.18, 10.86));
        index.mark(&written_osm_place(9, "wellington", 174.7762, -41.3015));
        assert!(index.written(&node));
        assert!(!index.written(&other));
        assert!(index.written(&near), "1,668 m away");
        assert!(!index.written(&far), "2,224 m away");
    }

    /// An OSM-sourced point of a relation the OSM pass did not write is the
    /// same place as a written OSM town of the same name nearby: Navi
    /// Mumbai's boundary relation and its place node, at one position, were
    /// both written on the planet.
    #[test]
    fn an_osm_relation_point_is_written_by_a_same_name_place_nearby() {
        let relation = division(
            &[
                ("subtype", "locality"),
                ("names.primary", "Navi Mumbai"),
                ("sources.dataset", "OpenStreetMap"),
                ("sources.record_id", "r7888990@5"),
                (SOURCE_ID_PROP, "r7888990@5"),
            ],
            73.019_853_7,
            19.030_826_2,
        );
        let mut index = DivisionIndex::default();
        index.add(&relation);
        index.seal();
        index.mark(&written_osm_place(
            619_091_882,
            "Navi Mumbai",
            73.019_853_7,
            19.030_826_2,
        ));
        assert!(index.written(&relation));
    }

    /// An index whose only data is the Survey of India outline: a square
    /// around Arunachal Pradesh (91..97.5 E, 26..29.5 N) and one around Gilgit.
    fn soi_index() -> AdminHierarchyIndex {
        use geolith::admin::AdminHierarchyBuilder;
        use geolith::admin::india::{IndiaOutline, IndiaView};
        let square = |x0: f64, y0: f64, x1: f64, y1: f64| {
            geo::Polygon::new(
                geo::LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
                vec![],
            )
        };
        let outline = IndiaOutline::new(geo::MultiPolygon(vec![
            square(91.0, 26.0, 97.5, 29.5),
            square(73.0, 35.0, 77.0, 37.0),
        ]))
        .expect("outline");
        let mut builder = AdminHierarchyBuilder::new();
        IndiaView::new(&outline)
            .finish_into(&mut builder)
            .expect("india");
        builder.build().expect("index")
    }

    fn written(feature: &InputFeature, index: &AdminHierarchyIndex) -> bool {
        division_record(feature, None, index, &Wikipedia::default()).is_some()
    }

    /// Overture's claim record is a region of country IN with no ISO code;
    /// Pakistani and Chinese units over SOI land are foreign. None of them
    /// is a record inside the SOI; India's own units, and the same names
    /// outside the SOI, are.
    #[test]
    fn foreign_admin_areas_inside_soi_land_are_not_indexed() {
        let index = soi_index();
        let at = |props: &[(&str, &str)], lon: f64, lat: f64| {
            let mut all = vec![("names.primary", "X")];
            all.extend_from_slice(props);
            written(&division(&all, lon, lat), &index)
        };
        let claim = [("subtype", "region"), ("country", "IN")];
        assert!(!at(&claim, 94.0, 28.1), "South Tibet: IN with no ISO code");
        let tibet = [
            ("subtype", "region"),
            ("country", "CN"),
            ("region", "CN-XZ"),
        ];
        assert!(!at(&tibet, 94.0, 28.1), "Chinese region over Arunachal");
        let gb = [
            ("subtype", "region"),
            ("country", "PK"),
            ("region", "PK-GB"),
        ];
        assert!(!at(&gb, 74.3, 35.9), "Gilgit-Baltistan");
        let gilgit_division = [
            ("subtype", "county"),
            ("country", "PK"),
            ("region", "PK-GB"),
        ];
        assert!(!at(&gilgit_division, 74.3, 35.9), "Gilgit division");
        let prefecture = [
            ("subtype", "county"),
            ("country", "CN"),
            ("region", "CN-XZ"),
        ];
        assert!(!at(&prefecture, 94.0, 28.1), "Chinese prefecture");
        let pakistan = [("subtype", "country"), ("country", "PK")];
        assert!(
            !at(&pakistan, 74.3, 35.9),
            "Pakistan label point on SOI land"
        );

        let arunachal = [
            ("subtype", "region"),
            ("country", "IN"),
            ("region", "IN-AR"),
        ];
        assert!(at(&arunachal, 94.0, 28.1), "Arunachal Pradesh");
        let tawang = [
            ("subtype", "county"),
            ("country", "IN"),
            ("region", "IN-AR"),
        ];
        assert!(at(&tawang, 91.9, 27.6), "an Indian county");
        // Outside the SOI nothing changes.
        assert!(at(&gb, 60.0, 30.0), "a Pakistani region outside SOI land");
        assert!(at(&claim, 60.0, 30.0), "the rule is about SOI land");
        // Localities are places, not admin areas: Gilgit stays searchable.
        let gilgit = [("subtype", "locality"), ("country", "PK")];
        assert!(at(&gilgit, 74.3, 35.9), "Gilgit locality");
    }
}