geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! India's legal boundary (Survey of India) in the admin index.
//!
//! Overture draws India's country and its Ladakh and Jammu and Kashmir
//! regions along the lines of control: Pakistan-administered Kashmir
//! (Gilgit-Baltistan and "Azad Kashmir"), Aksai Chin and the Shaksgam
//! valley sit in Pakistan's and China's divisions. geolith always draws
//! and resolves India with its legal boundary, the Survey of India map:
//!
//! - the India country division takes the SOI outline;
//! - the land the SOI outline adds to Overture's India goes to the Indian
//!   region that holds it on the SOI map: Pakistan's "Azad Kashmir" to
//!   Jammu and Kashmir, the rest of Kashmir (Gilgit-Baltistan, Aksai Chin,
//!   Shaksgam) to Ladakh;
//! - Pakistan's and China's countries and regions, and Overture's disputed
//!   areas (codes `X*`), lose the land inside the SOI outline, so a point
//!   there resolves to India.
//!
//! Counties, localities and neighbourhoods keep their Overture outlines;
//! other neighbours (Nepal, Bangladesh, ...) are not changed.

use std::path::Path;

use geo::{
    Area, BooleanOps, BoundingRect, Centroid, Intersects, LineString, MultiPolygon, Polygon, Rect,
};

use super::{AdminDivision, AdminLevel};
use crate::error::{GeolithError, Result};

/// Kashmir on the SOI map, `[min_lon, min_lat, max_lon, max_lat]`: the
/// added land outside it (thin strips where the SOI and Overture lines
/// differ along a border) goes to no region.
const KASHMIR: [f64; 4] = [72.0, 32.0, 81.0, 37.5];

/// Smallest added piece, in square degrees (about 50 km² in Kashmir), that
/// joins Ladakh; smaller ones are strips along a border.
const MIN_PIECE: f64 = 0.005;

/// India's outline on the Survey of India map.
#[derive(Debug, Clone)]
pub struct IndiaOutline {
    soi: MultiPolygon<f64>,
    rect: Rect<f64>,
}

impl IndiaOutline {
    /// Build from the outline's polygons; `None` when there are none.
    #[must_use]
    pub fn new(soi: MultiPolygon<f64>) -> Option<Self> {
        let rect = soi.bounding_rect()?;
        Some(Self { soi, rect })
    }

    /// Read the polygons of a `GeoJSON` file (for example `DataMeet`'s
    /// `india-composite.geojson`).
    ///
    /// # Errors
    ///
    /// `GeolithError::IndiaFile` when the file is empty, is not `GeoJSON` in
    /// WGS 84, holds lines instead of polygons, or does not reach India (see
    /// [`crate::source::india_file`]); `GeolithError::Context` over `Io` when it
    /// cannot be read.
    pub fn load(path: &Path) -> Result<Self> {
        let Some(outline) = Self::new(crate::source::india_file::read_outline(path)?) else {
            return Err(GeolithError::GeoJson(format!(
                "{} holds no polygon",
                path.display()
            )));
        };
        tracing::info!(
            path = %path.display(),
            polygons = outline.soi.0.len(),
            "India outline (Survey of India) loaded"
        );
        Ok(outline)
    }

    /// The outline's polygons.
    #[must_use]
    pub const fn polygons(&self) -> &MultiPolygon<f64> {
        &self.soi
    }

    /// Whether the outline reaches into `[min_lon, min_lat, max_lon, max_lat]`.
    #[must_use]
    pub fn touches(&self, bbox: [f64; 4]) -> bool {
        let (min, max) = (self.rect.min(), self.rect.max());
        min.x <= bbox[2] && max.x >= bbox[0] && min.y <= bbox[3] && max.y >= bbox[1]
    }
}

/// Whether a country's Overture divisions cover land India holds on the
/// SOI map: Pakistan, China and Overture's disputed areas.
fn claims_indian_land(code: &str) -> bool {
    code == "PK" || code == "CN" || code.starts_with('X')
}

/// One pass of divisions turned to India's view: [`Self::admit`] each, then
/// add [`Self::finish`]'s.
#[derive(Debug)]
pub struct IndiaView<'a> {
    outline: &'a IndiaOutline,
    country: Option<AdminDivision>,
    ladakh: Option<AdminDivision>,
    jammu_kashmir: Option<AdminDivision>,
    /// Pakistan's "Azad Kashmir" region (`PK-JK`) as Overture draws it.
    azad_kashmir: MultiPolygon<f64>,
}

impl<'a> IndiaView<'a> {
    /// Start a pass with India's SOI outline.
    #[must_use]
    pub const fn new(outline: &'a IndiaOutline) -> Self {
        Self {
            outline,
            country: None,
            ladakh: None,
            jammu_kashmir: None,
            azad_kashmir: MultiPolygon(Vec::new()),
        }
    }

    /// The division to index now, in India's view; `None` when it is held
    /// for [`Self::finish`] or no land is left of it.
    pub fn admit(&mut self, mut division: AdminDivision) -> Option<AdminDivision> {
        if !matches!(
            division.level,
            AdminLevel::Country | AdminLevel::Dependency | AdminLevel::Region
        ) {
            return Some(division);
        }
        let code = division.country_code.as_deref().unwrap_or_default();
        if code == "IN" {
            let slot = match (division.level, division.region_code.as_deref()) {
                (AdminLevel::Country, _) => &mut self.country,
                (AdminLevel::Region, Some("IN-LA")) => &mut self.ladakh,
                (AdminLevel::Region, Some("IN-JK")) => &mut self.jammu_kashmir,
                _ => return Some(division),
            };
            // The lowest id, so the result does not depend on the load order.
            if slot.as_ref().is_none_or(|held| division.id < held.id) {
                *slot = Some(division);
            }
            return None;
        }
        if !claims_indian_land(code) {
            return Some(division);
        }
        let shape = to_multi(&division.parts);
        if !shape
            .bounding_rect()
            .is_some_and(|r| r.intersects(&self.outline.rect))
        {
            return Some(division);
        }
        if division.region_code.as_deref() == Some("PK-JK") {
            self.azad_kashmir.0.extend(shape.0.iter().cloned());
        }
        let left = shape.difference(&self.outline.soi);
        if left.0.is_empty() {
            return None;
        }
        division.parts = from_multi(&left);
        Some(division)
    }

    /// The held Indian divisions on the SOI map: India with the SOI outline,
    /// Ladakh and Jammu and Kashmir with the Kashmir land Overture left out.
    #[must_use]
    pub fn finish(self) -> Vec<AdminDivision> {
        let mut out = Vec::with_capacity(3);
        let soi = &self.outline.soi;
        let added = match self.country {
            Some(mut country) => {
                let added = soi.difference(&to_multi(&country.parts));
                country.parts = from_multi(soi);
                out.push(country);
                added
            }
            None => MultiPolygon(Vec::new()),
        };
        let to_jammu_kashmir = added.intersection(&self.azad_kashmir);
        let to_ladakh = MultiPolygon(
            added
                .difference(&self.azad_kashmir)
                .0
                .into_iter()
                .filter(in_kashmir)
                .collect(),
        );
        for (held, more) in [
            (self.ladakh, to_ladakh),
            (self.jammu_kashmir, to_jammu_kashmir),
        ] {
            if let Some(mut region) = held {
                region.parts = from_multi(&to_multi(&region.parts).union(&more));
                out.push(region);
            }
        }
        out
    }
}

impl IndiaView<'_> {
    /// Add the held Indian divisions to `builder`: India as the legal
    /// division, the regions as they are. When no India country division
    /// was admitted (a `--bbox` build whose box meets no row group of it),
    /// India still comes from the outline alone, so a point on SOI land
    /// never resolves to a neighbour.
    ///
    /// # Errors
    ///
    /// The error of the builder's scratch file.
    pub fn finish_into(self, builder: &mut super::AdminHierarchyBuilder) -> std::io::Result<()> {
        let outline = self.outline;
        let had_country = self.country.is_some();
        for division in self.finish() {
            if division.level == AdminLevel::Country {
                builder.add_legal_india(division)?;
            } else {
                builder.add(division)?;
            }
        }
        if !had_country {
            builder.add_legal_india(AdminDivision {
                id: u64::MAX,
                level: AdminLevel::Country,
                name: "India".to_owned(),
                country_code: Some("IN".to_owned()),
                region_code: None,
                parts: from_multi(&outline.soi),
            })?;
        }
        Ok(())
    }
}

fn in_kashmir(piece: &Polygon<f64>) -> bool {
    piece.unsigned_area() >= MIN_PIECE
        && piece.centroid().is_some_and(|c| {
            (KASHMIR[0]..=KASHMIR[2]).contains(&c.x()) && (KASHMIR[1]..=KASHMIR[3]).contains(&c.y())
        })
}

fn to_multi(parts: &[Vec<Vec<[f64; 2]>>]) -> MultiPolygon<f64> {
    let ring =
        |r: &Vec<[f64; 2]>| LineString::from(r.iter().map(|&[x, y]| (x, y)).collect::<Vec<_>>());
    MultiPolygon(
        parts
            .iter()
            .filter_map(|rings| {
                let (outer, holes) = rings.split_first()?;
                Some(Polygon::new(ring(outer), holes.iter().map(ring).collect()))
            })
            .collect(),
    )
}

fn from_multi(shape: &MultiPolygon<f64>) -> Vec<Vec<Vec<[f64; 2]>>> {
    let ring = |r: &LineString<f64>| r.coords().map(|c| [c.x, c.y]).collect::<Vec<_>>();
    shape
        .iter()
        .map(|p| {
            std::iter::once(ring(p.exterior()))
                .chain(p.interiors().iter().map(ring))
                .collect()
        })
        .collect()
}

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

    /// Rough stand-ins, at real coordinates, for the Overture divisions
    /// around Kashmir and the SOI outline. Expected answers are the SOI
    /// map's: Gilgit and Aksai Chin in Ladakh, Muzaffarabad in Jammu and
    /// Kashmir, all three in India; Lahore in Pakistan.
    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Vec<[f64; 2]>> {
        vec![vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]]
    }

    fn div(
        id: u64,
        level: AdminLevel,
        name: &str,
        code: &str,
        region: Option<&str>,
        parts: Vec<Vec<Vec<[f64; 2]>>>,
    ) -> AdminDivision {
        AdminDivision {
            id,
            level,
            name: name.into(),
            country_code: Some(code.into()),
            region_code: region.map(Into::into),
            parts,
        }
    }

    fn divisions() -> Vec<AdminDivision> {
        use AdminLevel::{Country, County, Locality, Region};
        vec![
            // Overture's India stops at the lines of control (x = 74 and 78.5).
            div(
                1,
                Country,
                "India",
                "IN",
                None,
                vec![
                    rect(74.6, 8.0, 78.5, 32.5),
                    rect(74.0, 32.5, 78.5, 34.5),
                    rect(91.0, 26.0, 97.5, 29.5),
                ],
            ),
            div(
                2,
                Region,
                "Jammu and Kashmir",
                "IN",
                Some("IN-JK"),
                vec![rect(74.0, 32.5, 76.0, 34.5)],
            ),
            div(
                3,
                Region,
                "Ladakh",
                "IN",
                Some("IN-LA"),
                vec![rect(76.0, 32.5, 78.5, 34.5)],
            ),
            div(
                4,
                Region,
                "Maharashtra",
                "IN",
                Some("IN-MH"),
                vec![rect(74.0, 16.0, 78.5, 20.0)],
            ),
            // Arunachal Pradesh, and Overture's claim record "South Tibet":
            // country IN, no ISO subdivision code, a smaller area on top.
            div(
                5,
                Region,
                "Arunachal Pradesh",
                "IN",
                Some("IN-AR"),
                vec![rect(91.0, 26.0, 97.5, 29.5)],
            ),
            div(
                6,
                Region,
                "South Tibet",
                "IN",
                None,
                vec![rect(92.0, 27.0, 96.0, 28.8)],
            ),
            div(
                7,
                County,
                "Tawang",
                "IN",
                Some("IN-AR"),
                vec![rect(91.5, 27.4, 92.5, 27.9)],
            ),
            // Chinese units over the same land (Tibetan region and prefecture).
            div(
                8,
                Region,
                "Tibetan claim region",
                "CN",
                Some("CN-XZ"),
                vec![rect(91.4, 27.3, 92.6, 28.0)],
            ),
            div(
                9,
                County,
                "Shannan prefecture",
                "CN",
                Some("CN-XZ"),
                vec![rect(91.4, 27.3, 92.6, 28.0)],
            ),
            // Pakistan reaches over Gilgit-Baltistan and Azad Kashmir.
            div(
                10,
                Country,
                "Pakistan",
                "PK",
                None,
                vec![
                    rect(66.0, 24.0, 74.6, 32.5),
                    rect(66.0, 32.5, 74.0, 37.0),
                    rect(74.0, 34.5, 77.0, 37.0),
                ],
            ),
            div(
                11,
                Region,
                "Punjab",
                "PK",
                Some("PK-PB"),
                vec![rect(70.0, 28.0, 74.6, 32.5)],
            ),
            div(
                12,
                Region,
                "Azad Kashmir",
                "PK",
                Some("PK-JK"),
                vec![rect(73.0, 33.0, 74.0, 35.0)],
            ),
            div(
                13,
                Region,
                "Gilgit-Baltistan",
                "PK",
                Some("PK-GB"),
                vec![rect(73.0, 35.0, 74.0, 37.0), rect(74.0, 34.5, 77.0, 37.0)],
            ),
            div(
                14,
                Locality,
                "Gilgit",
                "PK",
                None,
                vec![rect(74.2, 35.8, 74.4, 36.0)],
            ),
            // Pakistani county-level divisions: one over Gilgit (SOI land),
            // one over Lahore (Pakistan).
            div(
                15,
                County,
                "Gilgit division",
                "PK",
                Some("PK-GB"),
                vec![rect(73.5, 35.0, 77.0, 37.0)],
            ),
            div(
                16,
                County,
                "Lahore division",
                "PK",
                Some("PK-PB"),
                vec![rect(74.0, 31.0, 74.6, 32.0)],
            ),
            // A small Nepali country polygon over a sliver of Survey of India land
            // (OSM's Nepal reaches 22 m past the SOI line at Manebhanjan). Its
            // area is smaller than India's, so the smallest-area rule alone
            // would make it the country of every place in the sliver.
            div(
                17,
                Country,
                "Nepal",
                "NP",
                None,
                vec![rect(91.5, 27.0, 92.0, 27.5)],
            ),
            // China reaches over Aksai Chin.
            div(
                20,
                Country,
                "China",
                "CN",
                None,
                vec![rect(78.5, 30.0, 120.0, 45.0)],
            ),
            div(
                21,
                Region,
                "Aksai Chin",
                "CN",
                None,
                vec![rect(78.5, 34.5, 80.5, 36.0)],
            ),
        ]
    }

    /// SOI India: Overture's India plus Kashmir up to x = 73 (west), 37
    /// (north) and 80.5 (east, through Aksai Chin).
    fn soi() -> IndiaOutline {
        IndiaOutline::new(to_multi(&[
            rect(74.6, 8.0, 78.5, 32.5),
            rect(73.0, 32.5, 80.5, 37.0),
            rect(91.0, 26.0, 97.5, 29.5),
        ]))
        .unwrap()
    }

    fn index(india: Option<&IndiaOutline>) -> crate::admin::AdminHierarchyIndex {
        let mut b = AdminHierarchyBuilder::new();
        let mut view = india.map(IndiaView::new);
        for d in divisions() {
            let d = match view.as_mut() {
                Some(v) => match v.admit(d) {
                    Some(d) => d,
                    None => continue,
                },
                None => d,
            };
            b.add(d).unwrap();
        }
        if let Some(view) = view {
            view.finish_into(&mut b).unwrap();
        }
        b.build().unwrap()
    }

    fn at(index: &crate::admin::AdminHierarchyIndex, lat: f64, lon: f64) -> (String, String) {
        let h = index.resolve(lon, lat);
        (h.country.unwrap_or_default(), h.region.unwrap_or_default())
    }

    #[test]
    fn kashmir_resolves_to_india_on_the_soi_map() {
        let soi = soi();
        let idx = index(Some(&soi));
        let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
        assert_eq!(at(&idx, 35.92, 74.31), pair("India", "Ladakh"), "Gilgit");
        assert_eq!(
            at(&idx, 34.37, 73.47),
            pair("India", "Jammu and Kashmir"),
            "Muzaffarabad"
        );
        assert_eq!(at(&idx, 35.2, 79.0), pair("India", "Ladakh"), "Aksai Chin");
        assert_eq!(at(&idx, 31.55, 74.34), pair("Pakistan", "Punjab"), "Lahore");
        assert_eq!(at(&idx, 19.0, 75.0), pair("India", "Maharashtra"));
    }

    /// Pakistani and Chinese units inside SOI land are never parents: the
    /// county and the locality stay empty (no Indian record holds the point).
    /// The expected values are the legal rule's, not read from the code.
    #[test]
    fn foreign_counties_and_localities_inside_the_soi_are_never_parents() {
        let soi = soi();
        let idx = index(Some(&soi));
        let gilgit = idx.resolve(74.31, 35.92);
        assert_eq!(gilgit.country_code.as_deref(), Some("IN"));
        assert_eq!(gilgit.region.as_deref(), Some("Ladakh"));
        assert_eq!(gilgit.county, None, "Gilgit division is Pakistani");
        assert_eq!(gilgit.locality, None, "Pakistani locality");
        assert_eq!(gilgit.city, None);
        // Over the Chinese units in Arunachal Pradesh.
        let tawang = idx.resolve(91.9, 27.6);
        assert_eq!(tawang.region.as_deref(), Some("Arunachal Pradesh"));
        assert_eq!(
            tawang.county.as_deref(),
            Some("Tawang"),
            "the Indian county"
        );
        // Pakistan keeps its own units outside SOI land.
        let lahore = idx.resolve(74.3, 31.5);
        assert_eq!(lahore.country.as_deref(), Some("Pakistan"));
        assert_eq!(lahore.county.as_deref(), Some("Lahore division"));
    }

    /// On SOI land the country is India, whatever smaller country polygon
    /// also holds the point: a place in a Nepali sliver of Indian land is in
    /// India, and a point in the same Nepali polygon off SOI land is Nepal.
    #[test]
    fn a_smaller_foreign_country_never_wins_on_soi_land() {
        let soi = soi();
        let idx = index(Some(&soi));
        let sliver = idx.resolve(91.7, 27.2);
        assert_eq!(sliver.country_code.as_deref(), Some("IN"), "{sliver:?}");
        assert_eq!(sliver.country.as_deref(), Some("India"));
        // The same polygon where no SOI land lies: Nepal keeps it.
        let plain = index(None).resolve(91.7, 27.2);
        assert_eq!(plain.country_code.as_deref(), Some("NP"), "{plain:?}");
    }

    /// Overture's claim record is a region of country `IN` with no ISO
    /// subdivision code. It never names a place inside India.
    #[test]
    fn a_claim_name_region_never_replaces_the_indian_state() {
        let soi = soi();
        let idx = index(Some(&soi));
        let h = idx.resolve(94.0, 28.1);
        assert_eq!(h.country.as_deref(), Some("India"));
        assert_eq!(h.region.as_deref(), Some("Arunachal Pradesh"), "{h:?}");
        let outline = idx.outline(94.0, 28.1, &[AdminLevel::Region], &["South Tibet"]);
        assert!(outline.is_none(), "the claim record has no outline");
    }

    #[test]
    fn no_foreign_outline_is_given_for_a_point_inside_the_soi() {
        let soi = soi();
        let idx = index(Some(&soi));
        let foreign = idx.outline(74.31, 35.92, &[AdminLevel::County], &["Gilgit division"]);
        assert!(foreign.is_none());
        let lahore = idx.outline(74.3, 31.5, &[AdminLevel::County], &["Lahore division"]);
        assert!(lahore.is_some(), "outside the SOI the outline is given");
    }

    #[test]
    fn the_index_says_whether_a_point_is_on_soi_land() {
        let soi = soi();
        let idx = index(Some(&soi));
        assert!(idx.in_soi(74.31, 35.92), "Gilgit");
        assert!(idx.in_soi(94.0, 28.1), "Arunachal");
        assert!(!idx.in_soi(74.34, 31.55), "Lahore");
        assert!(!index(None).in_soi(74.31, 35.92), "no outline, no SOI land");
    }

    /// A `--bbox` build over Gilgit may load no Indian division at all (the
    /// row groups of India's divisions need not meet the box): the outline
    /// itself still makes the point Indian.
    #[test]
    fn the_outline_alone_makes_a_point_indian_when_no_india_division_is_loaded() {
        let soi = soi();
        let mut b = AdminHierarchyBuilder::new();
        let mut view = IndiaView::new(&soi);
        for d in divisions()
            .into_iter()
            .filter(|d| d.country_code.as_deref() != Some("IN"))
        {
            if let Some(d) = view.admit(d) {
                b.add(d).unwrap();
            }
        }
        view.finish_into(&mut b).unwrap();
        let idx = b.build().unwrap();
        let h = idx.resolve(74.31, 35.92);
        assert_eq!(h.country_code.as_deref(), Some("IN"), "{h:?}");
        assert_eq!(h.country.as_deref(), Some("India"));
        assert!(idx.in_soi(74.31, 35.92));
    }

    #[test]
    fn without_the_outline_kashmir_follows_overture() {
        let idx = index(None);
        assert_eq!(at(&idx, 35.92, 74.31).0, "Pakistan");
        assert_eq!(at(&idx, 35.2, 79.0).0, "China");
    }

    #[test]
    fn india_takes_the_soi_outline() {
        let soi = soi();
        let idx = index(Some(&soi));
        let names = ["India"];
        let outline = idx
            .outline(78.0, 20.0, &[AdminLevel::Country], &names)
            .unwrap();
        let area = to_multi(&outline).unsigned_area();
        assert!((area - soi.soi.unsigned_area()).abs() < 1e-6, "{area}");
        // Pakistan lost Gilgit-Baltistan and Azad Kashmir (x 73..74).
        let pk = idx
            .outline(70.0, 30.0, &[AdminLevel::Country], &["Pakistan"])
            .unwrap();
        let area = to_multi(&pk).unsigned_area();
        assert!((area - (8.6 * 8.5 + 7.0 * 4.5)).abs() < 1e-6, "{area}");
    }

    /// On real data: `GEOLITH_INDIA_OUTLINE` (`DataMeet` `india-composite.geojson`)
    /// and `GEOLITH_OVERTURE` (an Overture release directory with
    /// `divisions/division_area` over India). Expected values are the SOI map's.
    #[test]
    #[ignore = "needs the SOI outline and Overture divisions on disk"]
    fn real_divisions_on_the_soi_map() {
        let (Some(outline), Some(data)) = (
            std::env::var_os("GEOLITH_INDIA_OUTLINE"),
            std::env::var_os("GEOLITH_OVERTURE"),
        ) else {
            panic!("set GEOLITH_INDIA_OUTLINE and GEOLITH_OVERTURE");
        };
        let soi = IndiaOutline::load(Path::new(&outline)).unwrap();
        let idx = crate::admin::load_admin_index(Path::new(&data), None, None, Some(&soi)).unwrap();
        let in_india = |lat: f64, lon: f64, region: &str, place: &str| {
            let h = idx.resolve(lon, lat);
            assert_eq!(h.country_code.as_deref(), Some("IN"), "{place}: {h:?}");
            assert_eq!(h.region.as_deref(), Some(region), "{place}: {h:?}");
        };
        in_india(35.92, 74.31, "Ladakh", "Gilgit");
        in_india(34.37, 73.47, "Jammu and Kashmir", "Muzaffarabad");
        in_india(35.2, 79.0, "Ladakh", "Aksai Chin");
        in_india(34.16, 77.58, "Ladakh", "Leh");
        in_india(34.08, 74.80, "Jammu and Kashmir", "Srinagar");
        let lahore = idx.resolve(74.34, 31.55);
        assert_eq!(
            lahore.country_code.as_deref(),
            Some("PK"),
            "Lahore: {lahore:?}"
        );
        let outline = idx
            .outline(78.96, 20.59, &[AdminLevel::Country], &["India"])
            .unwrap();
        let area = to_multi(&outline).unsigned_area();
        let expected = soi.soi.unsigned_area();
        assert!(
            (area - expected).abs() < 1e-9 * expected,
            "{area} vs {expected}"
        );
        let rect = to_multi(&outline).bounding_rect().unwrap();
        eprintln!("India outline area {area:.4} deg², bbox {rect:?}");
    }

    #[test]
    fn neighbours_away_from_the_outline_are_unchanged() {
        let soi = soi();
        let mut view = IndiaView::new(&soi);
        let nepal = div(
            30,
            AdminLevel::Country,
            "Nepal",
            "NP",
            None,
            vec![rect(80.0, 26.0, 88.0, 30.5)],
        );
        assert_eq!(view.admit(nepal.clone()).unwrap().parts, nepal.parts);
    }
}