geolith 0.1.3

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
//! 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::fs::File;
use std::io::BufReader;
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::Context` over `Io` or `Json` when the file cannot be
    /// opened or parsed, and `GeolithError::GeoJson` when a geometry is bad or
    /// the file holds no polygon.
    pub fn load(path: &Path) -> Result<Self> {
        let file = File::open(path).map_err(|e| {
            GeolithError::from(e).context(format!("failed to open {}", path.display()))
        })?;
        let json: geojson::GeoJson =
            serde_json::from_reader(BufReader::new(file)).map_err(|e| {
                GeolithError::from(e).context(format!("failed to parse {}", path.display()))
            })?;
        let geometries: Vec<geojson::Geometry> = match json {
            geojson::GeoJson::FeatureCollection(fc) => {
                fc.features.into_iter().filter_map(|f| f.geometry).collect()
            }
            geojson::GeoJson::Feature(f) => f.geometry.into_iter().collect(),
            geojson::GeoJson::Geometry(g) => vec![g],
        };
        let mut polygons = Vec::new();
        for geometry in geometries {
            match geo::Geometry::<f64>::try_from(geometry).map_err(|e| {
                GeolithError::GeoJson(format!("bad geometry in {}: {e}", path.display()))
            })? {
                geo::Geometry::Polygon(p) => polygons.push(p),
                geo::Geometry::MultiPolygon(m) => polygons.extend(m.0),
                _ => {}
            }
        }
        let Some(outline) = Self::new(MultiPolygon(polygons)) 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
    }
}

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, 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)],
            ),
            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)],
            ),
            // 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)],
            ),
            // 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),
        ]))
        .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();
        }
        for d in view.map(IndiaView::finish).unwrap_or_default() {
            b.add(d).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"));
        // Gilgit keeps its locality.
        assert_eq!(
            idx.resolve(74.31, 35.92).locality.as_deref(),
            Some("Gilgit")
        );
    }

    #[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);
    }
}