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};
const KASHMIR: [f64; 4] = [72.0, 32.0, 81.0, 37.5];
const MIN_PIECE: f64 = 0.005;
#[derive(Debug, Clone)]
pub struct IndiaOutline {
soi: MultiPolygon<f64>,
rect: Rect<f64>,
}
impl IndiaOutline {
#[must_use]
pub fn new(soi: MultiPolygon<f64>) -> Option<Self> {
let rect = soi.bounding_rect()?;
Some(Self { soi, rect })
}
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)
}
#[must_use]
pub const fn polygons(&self) -> &MultiPolygon<f64> {
&self.soi
}
#[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]
}
}
fn claims_indian_land(code: &str) -> bool {
code == "PK" || code == "CN" || code.starts_with('X')
}
#[derive(Debug)]
pub struct IndiaView<'a> {
outline: &'a IndiaOutline,
country: Option<AdminDivision>,
ladakh: Option<AdminDivision>,
jammu_kashmir: Option<AdminDivision>,
azad_kashmir: MultiPolygon<f64>,
}
impl<'a> IndiaView<'a> {
#[must_use]
pub const fn new(outline: &'a IndiaOutline) -> Self {
Self {
outline,
country: None,
ladakh: None,
jammu_kashmir: None,
azad_kashmir: MultiPolygon(Vec::new()),
}
}
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),
};
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)
}
#[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(®ion.parts).union(&more));
out.push(region);
}
}
out
}
}
impl IndiaView<'_> {
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;
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![
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)],
),
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)],
),
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)],
),
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)],
),
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)],
),
div(
17,
Country,
"Nepal",
"NP",
None,
vec![rect(91.5, 27.0, 92.0, 27.5)],
),
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)],
),
]
}
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"));
}
#[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);
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"
);
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"));
}
#[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"));
let plain = index(None).resolve(91.7, 27.2);
assert_eq!(plain.country_code.as_deref(), Some("NP"), "{plain:?}");
}
#[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");
}
#[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}");
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}");
}
#[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);
}
}