use std::collections::{BTreeMap, BTreeSet, HashMap, hash_map};
use std::fs::File;
use std::io::{BufWriter, Write as _};
use std::path::Path;
use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};
use geo::orient::{Direction, Orient as _};
use geo::{
Area as _, BooleanOps, BoundingRect, Centroid, Coord, Intersects as _, LineString,
MultiPolygon, Point, Polygon,
};
use serde_json::{Value, json};
use super::country::{BoundarySource, CountryConfig};
use super::exact_json::parse_feature_collection;
use crate::cli::AreasArgs;
use geolith::admin::india::{IndiaOutline, IndiaView};
use geolith::admin::{AdminDivision, AdminLevel, division_from_feature};
use geolith::source::bbox_filter::Bbox;
use geolith::source::overture_files;
use geolith::source::reader::{SOURCE_ID_PROP, read_parquet_file_with_source_id};
use geolith::source::schema::OvertureType;
pub const BOUNDARIES_ATTRIBUTION: &str = "Boundaries: Overture Maps Foundation, \
© OpenStreetMap contributors, ODbL. India boundaries by DataMeet India community (CC BY 4.0)";
pub const GAP_MIN_PIECE_SQ_DEG: f64 = 0.005;
pub const GAP_LABEL: &str = "District data not available";
#[derive(Debug, Clone, PartialEq)]
pub struct Area {
pub id: String,
pub code: Option<String>,
pub name: String,
pub country: String,
pub level: String,
pub parent_id: Option<String>,
pub parent_name: Option<String>,
pub region_code: Option<String>,
pub shape: MultiPolygon<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GapPiece {
pub id: String,
pub area_sq_deg: f64,
pub centroid: (f64, f64),
pub region_id: Option<String>,
pub region_name: Option<String>,
pub region_code: Option<String>,
pub shape: MultiPolygon<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AreasFile {
pub areas: Vec<Area>,
pub boundary_release: String,
pub attribution: String,
}
#[must_use]
pub fn soi_gaps(
outline: &MultiPolygon<f64>,
districts: &[&MultiPolygon<f64>],
) -> Vec<Polygon<f64>> {
let districts: Vec<MultiPolygon<f64>> = districts.iter().map(|d| oriented(d)).collect();
let covered = geo::unary_union(&districts);
let mut pieces: Vec<Polygon<f64>> = oriented(outline)
.difference(&covered)
.0
.into_iter()
.filter(|p| p.unsigned_area() >= GAP_MIN_PIECE_SQ_DEG)
.collect();
pieces.sort_by(|a, b| {
let (a, b) = (centroid_of(a), centroid_of(b));
a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
});
pieces
}
fn oriented(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
shape.orient(Direction::Default)
}
fn centroid_of<T: Centroid<Output = Option<Point<f64>>>>(shape: &T) -> (f64, f64) {
shape.centroid().map_or((0.0, 0.0), |c| (c.x(), c.y()))
}
pub fn read_areas_geojson(path: &Path) -> Result<AreasFile> {
let bytes = std::fs::read(path).io_at(IoOp::Open, path)?;
let collection =
parse_feature_collection(&bytes).within(format!("failed to parse {}", path.display()))?;
let member = |key: &str| {
collection
.foreign_members
.as_ref()
.and_then(|m| m.get(key))
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| DatasetError::data(format!("{} has no {key}", path.display())))
};
let boundary_release = member("boundary_release")?;
let attribution = member("attribution")?;
let mut areas = Vec::with_capacity(collection.features.len());
for feature in &collection.features {
let props = feature.properties.clone().unwrap_or_default();
let text = |key: &str| props.get(key).and_then(Value::as_str).map(str::to_string);
let required = |key: &str| {
text(key).ok_or_else(|| {
DatasetError::data(format!("a feature of {} has no {key}", path.display()))
})
};
let id = required("id")?;
let geometry = feature.geometry.clone().ok_or_else(|| {
DatasetError::data(format!("area {id} in {} has no geometry", path.display()))
})?;
let shape = match geo::Geometry::<f64>::try_from(geometry).map_err(|source| {
DatasetError::Geometry {
what: format!("bad geometry of area {id} in {}", path.display()),
source: Box::new(source),
}
})? {
geo::Geometry::Polygon(p) => MultiPolygon(vec![p]),
geo::Geometry::MultiPolygon(m) => m,
_ => {
return Err(DatasetError::data(format!(
"area {id} in {} is not a polygon",
path.display()
)));
}
};
areas.push(Area {
name: required("name")?,
country: required("country")?,
level: required("level")?,
parent_id: text("parent_id"),
parent_name: text("parent_name"),
region_code: text("region_code"),
shape,
id,
code: text("code"),
});
}
areas.sort_by(|a, b| a.id.cmp(&b.id));
Ok(AreasFile {
areas,
boundary_release,
attribution,
})
}
pub fn write_areas_geojson(path: &Path, file: &AreasFile) -> Result<()> {
let features = file.areas.iter().map(|area| {
let mut props = json!({
"id": area.id,
"name": area.name,
"country": area.country,
"level": area.level,
"parent_id": area.parent_id,
"parent_name": area.parent_name,
"region_code": area.region_code,
});
if let (Some(code), Value::Object(map)) = (&area.code, &mut props) {
map.insert("code".into(), json!(code));
}
feature(geojson::GeometryValue::from(&area.shape), props)
});
write_collection(path, features, &file.boundary_release, &file.attribution)
}
pub(super) fn feature(geometry: geojson::GeometryValue, properties: Value) -> geojson::Feature {
geojson::Feature {
bbox: None,
geometry: Some(geojson::Geometry::new(geometry)),
id: None,
properties: match properties {
Value::Object(map) => Some(map),
_ => None,
},
foreign_members: None,
}
}
pub(super) fn write_collection(
path: &Path,
features: impl Iterator<Item = geojson::Feature>,
boundary_release: &str,
attribution: &str,
) -> Result<()> {
let mut members = geojson::JsonObject::new();
members.insert("boundary_release".into(), boundary_release.into());
members.insert("attribution".into(), attribution.into());
let collection = geojson::FeatureCollection {
bbox: None,
features: features.collect(),
foreign_members: Some(members),
};
write_json(path, &collection)
}
pub(super) fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
let file = File::create(path).io_at(IoOp::Create, path)?;
let mut out = BufWriter::new(file);
serde_json::to_writer(&mut out, value).io_at(IoOp::Write, path)?;
out.flush().io_at(IoOp::Write, path)
}
struct Row {
division_id: String,
division: AdminDivision,
}
pub fn run(args: &AreasArgs) -> Result<()> {
let config = args
.country_config
.as_deref()
.map(CountryConfig::load)
.transpose()?;
if let Some(config) = &config
&& config.boundaries.source == BoundarySource::Shapefile
{
let dir = args.boundaries_dir.as_deref().ok_or_else(|| {
DatasetError::data(
"the country config has a shapefile source: pass --boundaries-dir <dir>",
)
})?;
return super::official_areas::run(config, dir, &args.out, args.max_zoom);
}
run_overture(args, config.as_ref())
}
fn run_overture(args: &AreasArgs, config: Option<&CountryConfig>) -> Result<()> {
let overture = args.overture.as_deref().ok_or_else(|| {
DatasetError::data({
"dataset areas reads Overture: pass --overture <release dir>, or a --country-config \
whose boundaries.source is shapefile"
})
})?;
let listed = args
.countries
.clone()
.or_else(|| config.map(|c| c.code.to_uppercase()))
.unwrap_or_default();
let countries: BTreeSet<String> = listed
.split(',')
.map(|c| c.trim().to_uppercase())
.filter(|c| !c.is_empty())
.collect();
if countries.is_empty() {
return Err(DatasetError::usage("--countries lists no country"));
}
let india = countries.contains("IN");
let needs_outline = match config {
Some(config) => config.boundaries.holds_soi_land,
None => india || countries.iter().any(|c| holds_soi_land(c)),
};
let allowed: Vec<String> = args
.allow_districtless
.as_deref()
.unwrap_or_default()
.split(',')
.map(|c| c.trim().to_uppercase())
.filter(|c| !c.is_empty())
.collect();
if args.india_outline.is_none() && needs_outline {
if india {
return Err(DatasetError::data(
"dataset areas covers India: pass --india-outline <Survey of India GeoJSON>",
));
}
if let Some(code) = countries.iter().find(|c| holds_soi_land(c)) {
return Err(DatasetError::data(format!(
"dataset areas covers {code}, which holds land of India's Survey of India map: \
pass --india-outline <Survey of India GeoJSON>"
)));
}
return Err(DatasetError::data(
"the country config holds Survey of India land: pass --india-outline",
));
}
let level = match AdminLevel::from_overture_subtype(&args.subtype) {
Some(level @ (AdminLevel::County | AdminLevel::Region)) => level,
_ => {
return Err(DatasetError::usage(format!(
"--subtype {}: areas must be an Overture county or region subtype",
args.subtype
)));
}
};
let outline = args
.india_outline
.as_deref()
.map(IndiaOutline::load)
.transpose()?;
let india_only = countries.len() == 1 && needs_outline;
let bbox = match (&outline, india_only) {
(Some(o), true) => o.polygons().bounding_rect().map(|r| Bbox {
min_lon: r.min().x - 1.0,
min_lat: r.min().y - 1.0,
max_lon: r.max().x + 1.0,
max_lat: r.max().y + 1.0,
}),
_ => None,
};
let boundary_release = match &args.release {
Some(release) => release.clone(),
None => overture
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.ok_or_else(|| {
DatasetError::data(format!(
"{} has no file name: pass --release",
overture.display()
))
})?,
};
let Rows {
regions: raw_regions,
units,
view_only,
} = read_rows(
overture,
bbox.as_ref(),
&countries,
level,
outline.is_some(),
)?;
let raw_regions: Vec<Row> = raw_regions
.into_iter()
.filter(|r| !is_uncoded_indian_region(&r.division))
.collect();
let regions = india_view_regions(raw_regions, view_only, outline.as_ref());
let region_groups = union_by_id(®ions, None);
let parents = region_parents(®ion_groups);
let unit_rows = if level == AdminLevel::Region {
®ions
} else {
&units
};
let soi = outline.as_ref().map(|o| oriented(o.polygons()));
let mut areas: Vec<Area> = Vec::new();
let mut by_overlap: Vec<Value> = Vec::new();
for (id, g) in union_by_id(unit_rows, soi.as_ref()) {
let parent = if level == AdminLevel::Region {
None
} else {
resolve_parent(&g, &parents)?
};
if let Some(p) = parent
&& p.region_code != g.region_code
{
let area = g.shape.unsigned_area();
let share = if area > 0.0 {
g.shape.intersection(&p.shape).unsigned_area() / area
} else {
0.0
};
tracing::info!(
district = id.as_str(),
name = g.name.as_str(),
region_code = p.region_code.as_deref().unwrap_or_default(),
share,
"district without a coded region placed in the region it overlaps most"
);
by_overlap.push(json!({
"id": id,
"name": g.name,
"region_code": p.region_code,
"overlap_share": share,
}));
}
let region_code = match parent {
Some(p) if level != AdminLevel::Region => p.region_code.clone(),
_ => g.region_code,
};
areas.push(Area {
id,
code: None,
parent_id: parent.map(|p| p.id.clone()),
parent_name: parent.map(|p| p.name.clone()),
level: args.subtype.clone(),
name: g.name,
country: g.country,
region_code,
shape: g.shape,
});
}
if areas.is_empty() {
return Err(DatasetError::data(format!(
"dataset areas read no {} row of {} from {}: is that the release directory?",
args.subtype,
countries.iter().cloned().collect::<Vec<_>>().join(","),
overture.display()
)));
}
let india_regions = if india && level != AdminLevel::Region {
check_india_regions(&areas, &parents, &allowed)?
} else {
BTreeMap::new()
};
let gaps = match (&outline, india) {
(Some(o), true) => gap_pieces(o, &areas, ®ion_groups),
_ => Vec::new(),
};
std::fs::create_dir_all(&args.out).io_at(IoOp::Create, &args.out)?;
let attribution = config.map_or_else(
|| BOUNDARIES_ATTRIBUTION.to_string(),
|c| c.boundaries.attribution.clone(),
);
let file = AreasFile {
areas,
boundary_release,
attribution,
};
write_areas_geojson(&args.out.join("areas.geojson"), &file)?;
let gap_features = gaps.iter().map(|g| {
let geometry = match g.shape.0.as_slice() {
[polygon] => geojson::GeometryValue::from(polygon),
_ => geojson::GeometryValue::from(&g.shape),
};
feature(
geometry,
json!({
"id": g.id,
"area_sq_deg": g.area_sq_deg,
"region_id": g.region_id,
"region_name": g.region_name,
"region_code": g.region_code,
"label": GAP_LABEL,
"attribution": file.attribution,
}),
)
});
write_collection(
&args.out.join("gaps.geojson"),
gap_features,
&file.boundary_release,
&file.attribution,
)?;
let mut report = json!({
"areas": file.areas.len(),
"gaps": gaps
.iter()
.map(|g| json!({
"id": g.id,
"area_sq_deg": g.area_sq_deg,
"centroid": [g.centroid.0, g.centroid.1],
"region_name": g.region_name,
}))
.collect::<Vec<_>>(),
"countries": countries,
"india_regions": india_regions,
"india_districtless_allowed": allowed,
"india_assigned_by_overlap": by_overlap,
"subtype": args.subtype,
"boundary_release": file.boundary_release,
"attribution": file.attribution,
});
if let (Some(config), Some(map)) = (config, report.as_object_mut()) {
map.insert(
"invariants".to_owned(),
serde_json::to_value(&config.boundaries.invariants)?,
);
}
write_json(&args.out.join("areas-report.json"), &report)?;
crate::areas_tiles::write_areas_pmtiles(
&args.out.join("areas.pmtiles"),
&file.areas,
&gaps,
args.max_zoom,
&file.attribution,
None,
)?;
tracing::info!(
areas = file.areas.len(),
gaps = gaps.len(),
out = %args.out.display(),
"dataset areas written"
);
Ok(())
}
struct Rows {
regions: Vec<Row>,
units: Vec<Row>,
view_only: Vec<AdminDivision>,
}
fn needed_by_india_view(division: &AdminDivision) -> bool {
match division.level {
AdminLevel::Country => division.country_code.as_deref() == Some("IN"),
AdminLevel::Region => division.region_code.as_deref() == Some("PK-JK"),
_ => false,
}
}
fn read_rows(
overture: &Path,
bbox: Option<&Bbox>,
countries: &BTreeSet<String>,
level: AdminLevel,
india_view: bool,
) -> Result<Rows> {
let otype = OvertureType::new("divisions", "division_area");
let files =
overture_files(overture, otype).within(format!("failed to list {}", overture.display()))?;
let mut rows = Rows {
regions: Vec::new(),
units: Vec::new(),
view_only: Vec::new(),
};
for path in &files {
let mut failed: Option<DatasetError> = None;
read_parquet_file_with_source_id(path, otype, bbox, |feature| {
if failed.is_some() {
return;
}
let Some(division) = division_from_feature(&feature) else {
return;
};
let listed = division
.country_code
.as_deref()
.is_some_and(|c| countries.contains(c));
let is_region = division.level == AdminLevel::Region;
if !listed || !(is_region || division.level == level) {
if india_view && needed_by_india_view(&division) {
rows.view_only.push(division);
}
return;
}
let Some(division_id) = feature.get_str("division_id").filter(|s| !s.is_empty()) else {
failed = Some(DatasetError::data(format!(
"land row {} of {} has no division_id",
feature.get_str(SOURCE_ID_PROP).unwrap_or("(no id)"),
path.display()
)));
return;
};
let row = Row {
division_id: division_id.to_string(),
division,
};
if is_region {
rows.regions.push(row);
} else {
rows.units.push(row);
}
})
.io_at(IoOp::Read, path)?;
if let Some(e) = failed {
return Err(e);
}
}
Ok(rows)
}
fn is_uncoded_indian_region(division: &AdminDivision) -> bool {
division.level == AdminLevel::Region
&& division
.country_code
.as_deref()
.is_some_and(|c| c.eq_ignore_ascii_case("IN"))
&& division.region_code.as_deref().is_none_or(str::is_empty)
}
fn india_view_regions(
rows: Vec<Row>,
view_only: Vec<AdminDivision>,
outline: Option<&IndiaOutline>,
) -> Vec<Row> {
let Some(outline) = outline else {
return rows;
};
let ids: HashMap<u64, String> = rows
.iter()
.map(|r| (r.division.id, r.division_id.clone()))
.collect();
let mut view = IndiaView::new(outline);
let mut admitted: Vec<AdminDivision> = rows
.into_iter()
.map(|r| r.division)
.chain(view_only)
.filter_map(|d| view.admit(d))
.collect();
admitted.extend(view.finish());
admitted
.into_iter()
.filter(|d| d.level == AdminLevel::Region)
.filter_map(|division| {
Some(Row {
division_id: ids.get(&division.id)?.clone(),
division,
})
})
.collect()
}
fn region_parents(groups: &BTreeMap<String, Group>) -> HashMap<(&str, &str), &Group> {
let mut parents: HashMap<(&str, &str), &Group> = HashMap::with_capacity(groups.len());
for group in groups.values() {
let Some(code) = group.region_code.as_deref() else {
continue;
};
match parents.entry((group.country.as_str(), code)) {
hash_map::Entry::Vacant(slot) => {
slot.insert(group);
}
hash_map::Entry::Occupied(mut slot) => {
let held = *slot.get();
let (kept, dropped) = if group.shape.unsigned_area() > held.shape.unsigned_area() {
(group, held)
} else {
(held, group)
};
tracing::warn!(
region_code = code,
kept = kept.id.as_str(),
dropped = dropped.id.as_str(),
"two regions share a region code; the larger keeps it"
);
slot.insert(kept);
}
}
}
parents
}
fn resolve_parent<'a>(
g: &Group,
parents: &HashMap<(&str, &str), &'a Group>,
) -> Result<Option<&'a Group>> {
if let Some(parent) = g
.region_code
.as_deref()
.and_then(|code| parents.get(&(g.country.as_str(), code)))
{
return Ok(Some(*parent));
}
if g.country != "IN" {
return Ok(None);
}
let rect = g.shape.bounding_rect();
let mut best: Option<(f64, &str, &'a Group)> = None;
for (&(country, code), ®ion) in parents {
if country != "IN" {
continue;
}
let meets = match (rect, region.shape.bounding_rect()) {
(Some(a), Some(b)) => a.intersects(&b),
_ => false,
};
if !meets {
continue;
}
let overlap = g.shape.intersection(®ion.shape).unsigned_area();
if overlap <= 0.0 {
continue;
}
let better =
best.is_none_or(|(area, held, _)| overlap > area || (overlap == area && code < held));
if better {
best = Some((overlap, code, region));
}
}
match best {
Some((_, _, region)) => Ok(Some(region)),
None => Err(DatasetError::data(format!(
"Indian district {} ({}) has no coded region and overlaps no coded Indian region",
g.id, g.name
))),
}
}
fn check_india_regions(
areas: &[Area],
parents: &HashMap<(&str, &str), &Group>,
allowed: &[String],
) -> Result<BTreeMap<String, usize>> {
let indian: Vec<&Area> = areas.iter().filter(|a| a.country == "IN").collect();
let stateless: Vec<String> = indian
.iter()
.filter(|a| a.region_code.is_none() || a.parent_name.is_none())
.map(|a| format!("{} ({})", a.id, a.name))
.collect();
if !stateless.is_empty() {
return Err(DatasetError::data(format!(
"{} Indian districts have no state: {}",
stateless.len(),
stateless.join(", ")
)));
}
let mut counts: BTreeMap<String, usize> = parents
.keys()
.filter(|(country, _)| *country == "IN")
.map(|(_, code)| ((*code).to_string(), 0))
.collect();
for area in &indian {
if let Some(count) = area.region_code.as_ref().and_then(|c| counts.get_mut(c)) {
*count += 1;
}
}
let empty: Vec<&str> = counts
.iter()
.filter(|(code, n)| **n == 0 && !allowed.contains(code))
.map(|(code, _)| code.as_str())
.collect();
if !indian.is_empty() && !empty.is_empty() {
return Err(DatasetError::data(format!(
"coded Indian regions without a district: {}",
empty.join(", ")
)));
}
Ok(counts)
}
struct Group {
id: String,
name: String,
country: String,
region_code: Option<String>,
shape: MultiPolygon<f64>,
}
fn union_by_id(rows: &[Row], soi: Option<&MultiPolygon<f64>>) -> BTreeMap<String, Group> {
let mut groups: BTreeMap<String, Group> = BTreeMap::new();
for row in rows {
let country = row.division.country_code.clone().unwrap_or_default();
let mut shape = to_multi(&row.division.parts);
if let Some(soi) = soi {
shape = soi_recut(&country, shape, soi);
}
match groups.get_mut(&row.division_id) {
Some(group) => group.shape = group.shape.union(&shape),
None => {
groups.insert(
row.division_id.clone(),
Group {
id: row.division_id.clone(),
name: row.division.name.clone(),
country,
region_code: row.division.region_code.clone(),
shape,
},
);
}
}
}
groups.retain(|_, g| !g.shape.0.is_empty());
groups
}
fn holds_soi_land(country: &str) -> bool {
country == "PK" || country == "CN" || country.starts_with('X')
}
fn soi_recut(
country: &str,
shape: MultiPolygon<f64>,
soi: &MultiPolygon<f64>,
) -> MultiPolygon<f64> {
if country == "IN" {
shape.intersection(soi)
} else if holds_soi_land(country) {
shape.difference(soi)
} else {
shape
}
}
fn gap_pieces(
outline: &IndiaOutline,
areas: &[Area],
regions: &BTreeMap<String, Group>,
) -> Vec<GapPiece> {
let districts: Vec<&MultiPolygon<f64>> = areas
.iter()
.filter(|a| a.country == "IN")
.map(|a| &a.shape)
.collect();
let indian: Vec<&Group> = regions.values().filter(|g| g.country == "IN").collect();
let mut parts: Vec<(MultiPolygon<f64>, Option<&Group>)> = Vec::new();
for piece in soi_gaps(outline.polygons(), &districts) {
parts.extend(split_gap_piece(piece, &indian));
}
let mut gaps: Vec<GapPiece> = parts
.into_iter()
.map(|(shape, region)| GapPiece {
id: String::new(),
area_sq_deg: shape.unsigned_area(),
centroid: centroid_of(&shape),
region_id: region.map(|g| g.id.clone()),
region_name: region.map(|g| g.name.clone()),
region_code: region.and_then(|g| g.region_code.clone()),
shape,
})
.collect();
gaps.sort_by(|a, b| {
a.centroid
.0
.total_cmp(&b.centroid.0)
.then(a.centroid.1.total_cmp(&b.centroid.1))
});
for (i, gap) in gaps.iter_mut().enumerate() {
gap.id = format!("gap-{}", i + 1);
}
gaps
}
fn split_gap_piece<'a>(
piece: Polygon<f64>,
indian: &[&'a Group],
) -> Vec<(MultiPolygon<f64>, Option<&'a Group>)> {
let whole = MultiPolygon(vec![piece]);
let mut rest = whole.clone();
let mut inside: Vec<(Polygon<f64>, &Group)> = Vec::new();
let mut most: Option<(f64, &Group)> = None;
for ®ion in indian {
let touches = match (whole.bounding_rect(), region.shape.bounding_rect()) {
(Some(a), Some(b)) => a.intersects(&b),
_ => false,
};
if !touches {
continue;
}
let overlap = rest.intersection(®ion.shape);
let area = overlap.unsigned_area();
if area <= 0.0 {
continue;
}
if most.is_none_or(|(a, _)| area > a) {
most = Some((area, region));
}
inside.extend(overlap.0.into_iter().map(|p| (p, region)));
rest = rest.difference(®ion.shape);
}
let regions: BTreeSet<&str> = inside
.iter()
.filter(|(p, _)| p.unsigned_area() >= GAP_MIN_PIECE_SQ_DEG)
.map(|(_, g)| g.id.as_str())
.collect();
if regions.len() < 2 {
return vec![(whole, most.map(|(_, g)| g))];
}
let mut kept: Vec<(MultiPolygon<f64>, Option<&Group>)> = Vec::with_capacity(inside.len());
let mut slivers: Vec<Polygon<f64>> = Vec::new();
let labelled = inside.into_iter().map(|(p, g)| (p, Some(g)));
for (part, region) in labelled.chain(rest.0.into_iter().map(|p| (p, None))) {
let area = part.unsigned_area();
if area >= GAP_MIN_PIECE_SQ_DEG {
kept.push((MultiPolygon(vec![part]), region));
} else if area >= GAP_NOISE_SQ_DEG {
slivers.push(part);
}
}
merge_slivers(&mut kept, slivers);
kept
}
const GAP_NOISE_SQ_DEG: f64 = 1e-9;
fn merge_slivers<T>(kept: &mut [(MultiPolygon<f64>, T)], slivers: Vec<Polygon<f64>>) {
let mut joined: Vec<Vec<Polygon<f64>>> = vec![Vec::new(); kept.len()];
let mut pending = slivers;
loop {
let before = pending.len();
let mut waiting = Vec::with_capacity(before);
for sliver in pending {
let best = kept
.iter()
.zip(&joined)
.enumerate()
.map(|(i, ((part, _), extra))| {
let length =
shared_edge_length(&sliver, &part.0) + shared_edge_length(&sliver, extra);
(i, length)
})
.filter(|&(_, length)| length > 0.0)
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i);
match best.and_then(|i| joined.get_mut(i)) {
Some(extra) => extra.push(sliver),
None => waiting.push(sliver),
}
}
pending = waiting;
if pending.is_empty() || pending.len() == before {
break;
}
}
let largest = kept
.iter()
.enumerate()
.max_by(|a, b| a.1.0.unsigned_area().total_cmp(&b.1.0.unsigned_area()))
.map(|(i, _)| i);
if let Some(extra) = largest.and_then(|i| joined.get_mut(i)) {
extra.extend(pending);
}
for ((part, _), extra) in kept.iter_mut().zip(joined) {
if !extra.is_empty() {
*part = part.union(&MultiPolygon(extra));
}
}
}
const EDGE_TOLERANCE: f64 = 1e-9;
fn shared_edge_length(sliver: &Polygon<f64>, part: &[Polygon<f64>]) -> f64 {
let Some(bounds) = sliver.bounding_rect() else {
return 0.0;
};
let near: Vec<&Polygon<f64>> = part
.iter()
.filter(|p| p.bounding_rect().is_some_and(|r| r.intersects(&bounds)))
.collect();
if near.is_empty() {
return 0.0;
}
let segments = |p: &Polygon<f64>| -> Vec<(Coord<f64>, Coord<f64>)> {
std::iter::once(p.exterior())
.chain(p.interiors())
.flat_map(|r| r.lines().map(|l| (l.start, l.end)))
.collect()
};
let theirs: Vec<(Coord<f64>, Coord<f64>)> = near.into_iter().flat_map(segments).collect();
segments(sliver)
.into_iter()
.map(|(p, q)| {
theirs
.iter()
.map(|&(r, s)| collinear_overlap(p, q, r, s))
.sum::<f64>()
})
.sum()
}
fn collinear_overlap(p: Coord<f64>, q: Coord<f64>, r: Coord<f64>, s: Coord<f64>) -> f64 {
let d = q - p;
let length = d.x.hypot(d.y);
if length == 0.0 {
return 0.0;
}
let off_line = |c: Coord<f64>| ((c.x - p.x) * d.y - (c.y - p.y) * d.x).abs() / length;
if off_line(r) > EDGE_TOLERANCE || off_line(s) > EDGE_TOLERANCE {
return 0.0;
}
let along = |c: Coord<f64>| ((c.x - p.x) * d.x + (c.y - p.y) * d.y) / length;
let (a, b) = (along(r), along(s));
(a.max(b).min(length) - a.min(b).max(0.0)).max(0.0)
}
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<_>>());
oriented(&MultiPolygon(
parts
.iter()
.filter_map(|rings| {
let (outer, holes) = rings.split_first()?;
Some(Polygon::new(ring(outer), holes.iter().map(ring).collect()))
})
.collect(),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> LineString<f64> {
LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)])
}
fn group(id: &str, code: &str, shape: Polygon<f64>) -> Group {
Group {
id: id.to_string(),
name: format!("{id} name"),
country: "IN".to_string(),
region_code: Some(code.to_string()),
shape: MultiPolygon(vec![shape]),
}
}
const MISROUNDED: &str = "21.546982095478498";
fn one_area_text(x: &str) -> String {
format!(
r#"{{"type":"FeatureCollection","boundary_release":"r","attribution":"a","features":[
{{"type":"Feature","properties":{{"id":"d","name":"D","country":"IN","level":"county"}},
"geometry":{{"type":"Polygon","coordinates":[[[{x},1.0],[22,1.0],[22,2.5e0],[{x},2.5E0],[{x},1.0]]]}}}}]}}"#
)
}
#[test]
fn areas_geojson_coordinates_are_correctly_rounded() {
let exact: f64 = MISROUNDED.parse().unwrap();
let naive: f64 = serde_json::from_str(MISROUNDED).unwrap();
assert_ne!(
exact.to_bits(),
naive.to_bits(),
"fixture must be misrounded by default"
);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("areas.geojson");
std::fs::write(&path, one_area_text(MISROUNDED)).unwrap();
let file = read_areas_geojson(&path).unwrap();
let ring = &file.areas[0].shape.0[0].exterior().0;
assert_eq!(ring[0].x.to_bits(), exact.to_bits());
assert_eq!(ring[3].x.to_bits(), exact.to_bits());
assert_eq!(ring[2], Coord { x: 22.0, y: 2.5 });
}
#[test]
fn areas_geojson_write_read_write_is_byte_stable() {
let exact: f64 = MISROUNDED.parse().unwrap();
let file = AreasFile {
areas: vec![Area {
code: None,
id: "d".into(),
name: "D".into(),
country: "IN".into(),
level: "county".into(),
parent_id: None,
parent_name: None,
region_code: None,
shape: MultiPolygon(vec![Polygon::new(rect(exact, 1.0, 22.0, 2.5), vec![])]),
}],
boundary_release: "r".into(),
attribution: "a".into(),
};
let dir = tempfile::tempdir().unwrap();
let first = dir.path().join("first.geojson");
let second = dir.path().join("second.geojson");
write_areas_geojson(&first, &file).unwrap();
let read = read_areas_geojson(&first).unwrap();
assert_eq!(read, file);
write_areas_geojson(&second, &read).unwrap();
let bytes = std::fs::read(&first).unwrap();
assert_eq!(bytes, std::fs::read(&second).unwrap());
assert!(String::from_utf8(bytes).unwrap().contains(MISROUNDED));
}
#[test]
fn shared_edge_length_counts_collinear_overlap_only() {
let a = Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]);
let b = MultiPolygon(vec![Polygon::new(rect(1.0, 0.25, 2.0, 0.75), vec![])]);
assert!((shared_edge_length(&a, &b.0) - 0.5).abs() <= 1e-12);
let c = MultiPolygon(vec![Polygon::new(rect(1.0, 1.0, 2.0, 2.0), vec![])]);
assert_eq!(shared_edge_length(&a, &c.0), 0.0);
}
#[test]
fn a_sliver_joins_the_part_it_shares_the_longest_edge_with() {
let p = group(
"div-p",
"IN-PP",
Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]),
);
let q_ring = LineString::from(vec![
(1.0, 0.0),
(3.0, 0.0),
(3.0, 0.94),
(2.95, 0.94),
(2.95, 1.0),
(1.0, 1.0),
(1.0, 0.0),
]);
let q = group("div-q", "IN-QQ", Polygon::new(q_ring, vec![]));
let piece = Polygon::new(rect(0.0, 0.0, 3.0, 1.0), vec![]);
let parts = split_gap_piece(piece, &[&p, &q]);
assert_eq!(parts.len(), 2, "one part per region");
let total: f64 = parts.iter().map(|(s, _)| s.unsigned_area()).sum();
assert!((total - 3.0).abs() <= 1e-9, "parts add up to {total}");
let (q_part, _) = parts
.iter()
.find(|(_, g)| g.is_some_and(|g| g.id == "div-q"))
.expect("Q's part");
assert!((q_part.unsigned_area() - 2.0).abs() <= 1e-9);
}
#[test]
fn a_sliver_bordering_no_part_joins_the_largest() {
let mut kept = vec![
(
MultiPolygon(vec![Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![])]),
"small",
),
(
MultiPolygon(vec![Polygon::new(rect(2.0, 0.0, 4.0, 1.0), vec![])]),
"large",
),
];
let sliver = Polygon::new(rect(10.0, 10.0, 10.05, 10.06), vec![]);
merge_slivers(&mut kept, vec![sliver]);
let (large, _) = kept
.iter()
.find(|(_, tag)| *tag == "large")
.expect("the large part");
assert!((large.unsigned_area() - 2.003).abs() <= 1e-9);
let (small, _) = kept
.iter()
.find(|(_, tag)| *tag == "small")
.expect("the small part");
assert!((small.unsigned_area() - 1.0).abs() <= 1e-9);
}
fn district(id: &str, code: Option<&str>, shape: Polygon<f64>) -> Group {
Group {
id: id.to_string(),
name: format!("{id} name"),
country: "IN".to_string(),
region_code: code.map(str::to_string),
shape: MultiPolygon(vec![shape]),
}
}
fn two_states() -> BTreeMap<String, Group> {
let mut groups = BTreeMap::new();
for g in [
group(
"div-ar",
"IN-AR",
Polygon::new(rect(0.0, 0.0, 2.0, 1.0), vec![]),
),
group(
"div-as",
"IN-AS",
Polygon::new(rect(2.0, 0.0, 4.0, 1.0), vec![]),
),
] {
groups.insert(g.id.clone(), g);
}
groups
}
#[test]
fn a_district_without_a_coded_parent_gets_the_state_it_overlaps_most() {
let groups = two_states();
let parents = region_parents(&groups);
let tawang = district("d1", None, Polygon::new(rect(1.0, 0.0, 2.1, 1.0), vec![]));
let parent = resolve_parent(&tawang, &parents)
.expect("resolves")
.expect("a parent");
assert_eq!(parent.region_code.as_deref(), Some("IN-AR"));
let coded = district(
"d2",
Some("IN-AS"),
Polygon::new(rect(1.0, 0.0, 2.1, 1.0), vec![]),
);
let parent = resolve_parent(&coded, &parents)
.expect("resolves")
.expect("a parent");
assert_eq!(parent.region_code.as_deref(), Some("IN-AS"));
let unknown = district(
"d3",
Some("IN-ZZ"),
Polygon::new(rect(3.0, 0.0, 3.5, 1.0), vec![]),
);
let parent = resolve_parent(&unknown, &parents)
.expect("resolves")
.expect("a parent");
assert_eq!(parent.region_code.as_deref(), Some("IN-AS"));
}
#[test]
fn an_indian_district_overlapping_no_coded_state_fails() {
let groups = two_states();
let parents = region_parents(&groups);
let lost = district(
"d9",
None,
Polygon::new(rect(10.0, 10.0, 11.0, 11.0), vec![]),
);
let Err(err) = resolve_parent(&lost, &parents) else {
panic!("a district overlapping no coded region must fail");
};
assert!(geolith::error::report(&err).contains("d9"), "{err:#}");
let mut abroad = lost;
abroad.country = "NP".to_string();
assert!(
resolve_parent(&abroad, &parents)
.expect("no error")
.is_none()
);
}
fn area_in(id: &str, code: Option<&str>, parent: Option<&str>) -> Area {
Area {
code: None,
id: id.to_string(),
name: id.to_string(),
country: "IN".to_string(),
level: "county".to_string(),
parent_id: parent.map(|p| format!("{p}-id")),
parent_name: parent.map(str::to_string),
region_code: code.map(str::to_string),
shape: MultiPolygon(vec![]),
}
}
#[test]
fn every_indian_district_has_a_state_and_every_state_a_district() {
let groups = two_states();
let parents = region_parents(&groups);
let ok = [
area_in("a", Some("IN-AR"), Some("Arunachal Pradesh")),
area_in("b", Some("IN-AS"), Some("Assam")),
area_in("c", Some("IN-AS"), Some("Assam")),
];
let counts = check_india_regions(&ok, &parents, &[]).expect("complete");
assert_eq!(counts.get("IN-AR"), Some(&1));
assert_eq!(counts.get("IN-AS"), Some(&2));
let orphan = [
area_in("a", Some("IN-AR"), Some("Arunachal Pradesh")),
area_in("b", None, None),
];
let err = check_india_regions(&orphan, &parents, &[]).expect_err("null state");
assert!(
geolith::error::report(&err).contains("1 Indian districts have no state"),
"{err:#}"
);
let empty_state = [area_in("a", Some("IN-AR"), Some("Arunachal Pradesh"))];
let err = check_india_regions(&empty_state, &parents, &[]).expect_err("IN-AS empty");
assert!(geolith::error::report(&err).contains("IN-AS"), "{err:#}");
let counts = check_india_regions(&empty_state, &parents, &["IN-AS".to_string()])
.expect("IN-AS allowlisted");
assert_eq!(counts.get("IN-AS"), Some(&0));
}
#[test]
fn duplicate_region_codes_keep_the_larger_group() {
let mut groups = BTreeMap::new();
for g in [
group(
"div-a",
"IN-XX",
Polygon::new(rect(0.0, 0.0, 1.0, 1.0), vec![]),
),
group(
"div-b",
"IN-XX",
Polygon::new(rect(0.0, 0.0, 3.0, 1.0), vec![]),
),
group(
"div-c",
"IN-XX",
Polygon::new(rect(0.0, 0.0, 2.0, 1.0), vec![]),
),
] {
groups.insert(g.id.clone(), g);
}
let parents = region_parents(&groups);
assert_eq!(parents.len(), 1);
let kept = parents.get(&("IN", "IN-XX")).expect("IN-XX");
assert_eq!(kept.id, "div-b");
}
#[test]
fn soi_gaps_drops_pieces_below_the_threshold() {
let outline = MultiPolygon(vec![Polygon::new(rect(0.0, 0.0, 10.0, 10.0), vec![])]);
let east = MultiPolygon(vec![Polygon::new(
rect(0.05, 0.0, 10.0, 10.0),
vec![rect(8.0, 8.0, 9.0, 9.0)],
)]);
let west = MultiPolygon(vec![Polygon::new(rect(0.0, 0.05, 0.05, 10.0), vec![])]);
let gaps = soi_gaps(&outline, &[&east, &west]);
assert_eq!(gaps.len(), 1);
let area: f64 = gaps.iter().map(Polygon::unsigned_area).sum();
assert!((area - 1.0).abs() <= 1e-9, "gap area {area}");
}
}