pub mod india;
use std::collections::HashMap;
use std::path::Path;
use rstar::{AABB, RTree, RTreeObject};
use serde::{Deserialize, Serialize};
use crate::admin::india::{IndiaOutline, IndiaView};
use crate::error::GeolithError;
use crate::source::bbox_filter::Bbox;
use crate::source::input::InputFeature;
use crate::source::overture_files;
use crate::source::reader::read_parquet_file_with_source_id;
use crate::source::schema::OvertureType;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AdminLevel {
Country,
Dependency,
Region,
County,
Locality,
Neighbourhood,
}
impl AdminLevel {
#[must_use]
pub fn from_overture_subtype(subtype: &str) -> Option<Self> {
match subtype {
"country" => Some(Self::Country),
"dependency" => Some(Self::Dependency),
"region" => Some(Self::Region),
"county" => Some(Self::County),
"locality" => Some(Self::Locality),
"neighborhood" => Some(Self::Neighbourhood),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AdminHierarchy {
pub country_code: Option<String>,
pub country: Option<String>,
pub region: Option<String>,
pub county: Option<String>,
pub locality: Option<String>,
pub neighbourhood: Option<String>,
#[serde(default)]
pub borough: Option<String>,
#[serde(default)]
pub postcode: Option<String>,
#[serde(default)]
pub city: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AdminDivision {
pub id: u64,
pub level: AdminLevel,
pub name: String,
pub country_code: Option<String>,
pub region_code: Option<String>,
pub parts: Vec<Vec<Vec<[f64; 2]>>>,
}
#[derive(Debug)]
struct DivisionMeta {
id: u64,
level: AdminLevel,
name: String,
country_code: Option<String>,
}
struct Prepared {
bbox: [f64; 4],
area: f64,
pts: Vec<[f64; 2]>,
band_height: f64,
band_offsets: Vec<u32>,
band_edges: Vec<u32>,
}
const EDGES_PER_BAND: usize = 8;
impl Prepared {
fn new(rings: &[Vec<[f64; 2]>]) -> Option<Self> {
let total: usize = rings.iter().map(|r| r.len() + 2).sum();
let mut pts: Vec<[f64; 2]> = Vec::with_capacity(total);
let mut area = 0.0;
for (i, ring) in rings.iter().enumerate() {
if ring.len() < 3 {
continue;
}
if !pts.is_empty() {
pts.push([f64::NAN, f64::NAN]);
}
pts.extend_from_slice(ring);
if ring.first() != ring.last() {
pts.push(ring[0]);
}
let ring_area = shoelace(ring).abs();
area += if i == 0 { ring_area } else { -ring_area };
}
if pts.len() < 4 {
return None;
}
let mut bbox = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
for p in pts.iter().filter(|p| !p[0].is_nan()) {
bbox[0] = bbox[0].min(p[0]);
bbox[1] = bbox[1].min(p[1]);
bbox[2] = bbox[2].max(p[0]);
bbox[3] = bbox[3].max(p[1]);
}
let edges = pts.len() - 1;
let bands = (edges / EDGES_PER_BAND).max(1);
let height = (bbox[3] - bbox[1]) / bands as f64;
let band_height = if height > 0.0 { height } else { 1.0 };
let band_of = |y: f64| -> usize { (((y - bbox[1]) / band_height) as usize).min(bands - 1) };
let edge_bands = |i: usize| -> Option<(usize, usize)> {
let (a, b) = (pts[i], pts[i + 1]);
if a[0].is_nan() || b[0].is_nan() {
return None;
}
Some((band_of(a[1].min(b[1])), band_of(a[1].max(b[1]))))
};
let mut counts = vec![0u32; bands + 1];
for i in 0..edges {
if let Some((lo, hi)) = edge_bands(i) {
for c in &mut counts[lo + 1..=hi + 1] {
*c += 1;
}
}
}
for b in 0..bands {
counts[b + 1] += counts[b];
}
let band_offsets = counts;
let mut cursor: Vec<u32> = band_offsets[..bands].to_vec();
let mut band_edges = vec![0u32; band_offsets[bands] as usize];
for i in 0..edges {
if let Some((lo, hi)) = edge_bands(i) {
for c in &mut cursor[lo..=hi] {
band_edges[*c as usize] = i as u32;
*c += 1;
}
}
}
Some(Self {
bbox,
area,
pts,
band_height,
band_offsets,
band_edges,
})
}
fn store(
&self,
meta: std::sync::Arc<DivisionMeta>,
out: &mut impl std::io::Write,
at: &mut u64,
) -> std::io::Result<PartRef> {
let pts_at = *at;
for p in &self.pts {
out.write_all(&p[0].to_le_bytes())?;
out.write_all(&p[1].to_le_bytes())?;
}
let offsets_at = pts_at + 16 * self.pts.len() as u64;
for o in &self.band_offsets {
out.write_all(&o.to_le_bytes())?;
}
let edges_at = offsets_at + 4 * self.band_offsets.len() as u64;
for e in &self.band_edges {
out.write_all(&e.to_le_bytes())?;
}
*at = edges_at + 4 * self.band_edges.len() as u64;
Ok(PartRef {
meta,
bbox: self.bbox,
area: self.area,
band_height: self.band_height,
bands: u32::try_from(self.band_offsets.len() - 1).unwrap_or(u32::MAX),
pts_at,
offsets_at,
edges_at,
})
}
}
#[derive(Debug)]
struct PartRef {
meta: std::sync::Arc<DivisionMeta>,
bbox: [f64; 4],
area: f64,
band_height: f64,
bands: u32,
pts_at: u64,
offsets_at: u64,
edges_at: u64,
}
fn u32_at(data: &[u8], at: u64) -> u32 {
let at = at as usize;
let mut raw = [0_u8; 4];
raw.copy_from_slice(&data[at..at + 4]);
u32::from_le_bytes(raw)
}
fn f64_at(data: &[u8], at: u64) -> f64 {
let at = at as usize;
let mut raw = [0_u8; 8];
raw.copy_from_slice(&data[at..at + 8]);
f64::from_le_bytes(raw)
}
impl PartRef {
fn contains(&self, data: &[u8], lon: f64, lat: f64) -> bool {
let bands = self.bands as usize;
let band = (((lat - self.bbox[1]) / self.band_height) as usize).min(bands - 1);
let first = u64::from(u32_at(data, self.offsets_at + 4 * band as u64));
let last = u64::from(u32_at(data, self.offsets_at + 4 * (band as u64 + 1)));
let vertex = |i: u64| {
let at = self.pts_at + 16 * i;
(f64_at(data, at), f64_at(data, at + 8))
};
let mut inside = false;
for k in first..last {
let i = u64::from(u32_at(data, self.edges_at + 4 * k));
let (a, b) = (vertex(i), vertex(i + 1));
if (a.1 > lat) != (b.1 > lat) && lon < (b.0 - a.0) * (lat - a.1) / (b.1 - a.1) + a.0 {
inside = !inside;
}
}
inside
}
}
impl RTreeObject for PartRef {
type Envelope = AABB<[f64; 2]>;
fn envelope(&self) -> Self::Envelope {
AABB::from_corners([self.bbox[0], self.bbox[1]], [self.bbox[2], self.bbox[3]])
}
}
fn shoelace(ring: &[[f64; 2]]) -> f64 {
let mut sum = 0.0;
for (i, a) in ring.iter().enumerate() {
let b = ring[(i + 1) % ring.len()];
sum += a[0] * b[1] - b[0] * a[1];
}
sum / 2.0
}
#[derive(Default)]
pub struct AdminHierarchyBuilder {
parts: Vec<PartRef>,
outlines: HashMap<u64, Vec<(u64, u64)>>,
countries: HashMap<String, ((usize, u64), String)>,
scratch_dir: Option<std::path::PathBuf>,
scratch: Option<std::io::BufWriter<std::fs::File>>,
written: u64,
}
impl AdminHierarchyBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn in_dir(dir: &Path) -> Self {
Self {
scratch_dir: Some(dir.to_path_buf()),
..Self::default()
}
}
pub fn add(&mut self, division: AdminDivision) -> std::io::Result<()> {
if let (AdminLevel::Country | AdminLevel::Dependency, Some(code)) =
(division.level, &division.country_code)
{
let key = (level_slot(division.level), division.id);
let entry = self
.countries
.entry(code.clone())
.or_insert_with(|| (key, division.name.clone()));
if key < entry.0 {
*entry = (key, division.name.clone());
}
}
let meta = std::sync::Arc::new(DivisionMeta {
id: division.id,
level: division.level,
name: division.name,
country_code: division.country_code,
});
for rings in &division.parts {
let Some(part) = Prepared::new(rings) else {
continue;
};
let out = match &mut self.scratch {
Some(out) => out,
none => {
let file = match &self.scratch_dir {
Some(dir) => tempfile::tempfile_in(dir)?,
None => tempfile::tempfile()?,
};
none.insert(std::io::BufWriter::with_capacity(1 << 20, file))
}
};
let stored = part.store(meta.clone(), out, &mut self.written)?;
self.outlines
.entry(meta.id)
.or_default()
.push((stored.pts_at, part.pts.len() as u64));
self.parts.push(stored);
}
Ok(())
}
#[allow(
unsafe_code,
reason = "memmap2::Mmap::map of the private scratch file; the SAFETY comment below states why it is sound"
)]
pub fn build(self) -> std::io::Result<AdminHierarchyIndex> {
let data = match self.scratch {
Some(out) => {
let file = out
.into_inner()
.map_err(std::io::IntoInnerError::into_error)?;
Some(unsafe { memmap2::Mmap::map(&file)? })
}
None => None,
};
Ok(AdminHierarchyIndex {
tree: RTree::bulk_load(self.parts),
countries: self
.countries
.into_iter()
.map(|(code, (_, name))| (code, name))
.collect(),
outlines: self.outlines,
data,
})
}
}
pub struct AdminHierarchyIndex {
tree: RTree<PartRef>,
countries: HashMap<String, String>,
outlines: HashMap<u64, Vec<(u64, u64)>>,
data: Option<memmap2::Mmap>,
}
impl AdminHierarchyIndex {
#[must_use]
pub fn resolve(&self, lon: f64, lat: f64) -> AdminHierarchy {
let point = [lon, lat];
let data: &[u8] = self.data.as_deref().unwrap_or(&[]);
let mut best: [Option<&PartRef>; 6] = [None; 6];
let mut largest: Option<&PartRef> = None;
for part in self
.tree
.locate_in_envelope_intersecting(AABB::from_point(point))
{
if !part.contains(data, lon, lat) {
continue;
}
if part.meta.level == AdminLevel::Locality
&& largest.is_none_or(|cur| (part.area, cur.meta.id) > (cur.area, part.meta.id))
{
largest = Some(part);
}
let slot = &mut best[level_slot(part.meta.level)];
let better = match slot {
None => true,
Some(cur) => (part.area, part.meta.id) < (cur.area, cur.meta.id),
};
if better {
*slot = Some(part);
}
}
let name = |slot: usize| best[slot].map(|p| p.meta.name.clone());
let (country_code, country) = match best[0].or(best[1]) {
Some(part) => (part.meta.country_code.clone(), Some(part.meta.name.clone())),
None => {
let code = best[2..]
.iter()
.flatten()
.find_map(|part| part.meta.country_code.clone());
let country = code
.as_ref()
.and_then(|code| self.countries.get(code).cloned());
(code, country)
}
};
let locality = name(4);
let city = largest.map(|p| p.meta.name.clone()).filter(|city| {
locality
.as_ref()
.is_some_and(|l| !l.eq_ignore_ascii_case(city))
});
AdminHierarchy {
country_code,
country,
region: name(2),
county: name(3),
locality,
neighbourhood: name(5),
borough: None,
postcode: None,
city,
}
}
#[must_use]
pub fn outline(
&self,
lon: f64,
lat: f64,
levels: &[AdminLevel],
names: &[&str],
) -> Option<Vec<Vec<Vec<[f64; 2]>>>> {
let data: &[u8] = self.data.as_deref()?;
let names: Vec<String> = names
.iter()
.map(|name| name.trim().to_lowercase())
.collect();
let best = self
.tree
.locate_in_envelope_intersecting(AABB::from_point([lon, lat]))
.filter(|part| levels.contains(&part.meta.level))
.filter(|part| names.contains(&part.meta.name.trim().to_lowercase()))
.filter(|part| part.contains(data, lon, lat))
.min_by(|a, b| a.area.total_cmp(&b.area).then(a.meta.id.cmp(&b.meta.id)))?;
let parts = self.outlines.get(&best.meta.id)?;
let mut polygons = Vec::with_capacity(parts.len());
for &(at, count) in parts {
let mut rings: Vec<Vec<[f64; 2]>> = vec![Vec::new()];
for i in 0..count {
let x = f64_at(data, at + 16 * i);
let y = f64_at(data, at + 16 * i + 8);
if x.is_nan() {
rings.push(Vec::new());
} else if let Some(ring) = rings.last_mut() {
ring.push([x, y]);
}
}
polygons.push(rings);
}
Some(polygons)
}
#[must_use]
pub fn has_country(&self, code: &str) -> bool {
self.countries.contains_key(code)
}
#[must_use]
pub fn backing_bytes(&self) -> u64 {
self.data.as_ref().map_or(0, |data| data.len() as u64)
}
#[must_use]
pub fn len(&self) -> usize {
self.tree.size()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.tree.size() == 0
}
}
const fn level_slot(level: AdminLevel) -> usize {
match level {
AdminLevel::Country => 0,
AdminLevel::Dependency => 1,
AdminLevel::Region => 2,
AdminLevel::County => 3,
AdminLevel::Locality => 4,
AdminLevel::Neighbourhood => 5,
}
}
#[must_use]
pub fn division_from_feature(feature: &InputFeature) -> Option<AdminDivision> {
let text = |key: &str| {
feature
.get_str(key)
.filter(|s| !s.is_empty())
.map(str::to_string)
};
if text("class")? != "land" {
return None;
}
let level = AdminLevel::from_overture_subtype(&text("subtype")?)?;
let name = text("names.primary")?;
let ring = |r: &geo::LineString<f64>| r.coords().map(|c| [c.x, c.y]).collect::<Vec<_>>();
let part = |p: &geo::Polygon<f64>| {
std::iter::once(ring(p.exterior()))
.chain(p.interiors().iter().map(ring))
.collect::<Vec<_>>()
};
let parts = match feature.geometry.as_ref() {
geo::Geometry::Polygon(p) => vec![part(p)],
geo::Geometry::MultiPolygon(mp) => mp.iter().map(part).collect(),
_ => return None,
};
Some(AdminDivision {
id: feature.id,
level,
name,
country_code: text("country").map(|c| c.to_uppercase()),
region_code: text("region").map(|c| c.to_uppercase()),
parts,
})
}
pub fn load_admin_index(
data_dir: &Path,
bbox: Option<&Bbox>,
scratch_dir: Option<&Path>,
india: Option<&IndiaOutline>,
) -> crate::error::Result<AdminHierarchyIndex> {
let mut view = india.map(IndiaView::new);
let otype = OvertureType::new("divisions", "division_area");
let files = overture_files(data_dir, otype)?;
let mut builder = match scratch_dir {
Some(dir) => AdminHierarchyBuilder::in_dir(dir),
None => AdminHierarchyBuilder::new(),
};
let mut failed: Option<std::io::Error> = None;
for path in &files {
read_parquet_file_with_source_id(path, otype, bbox, |feature| {
if failed.is_some() {
return;
}
let division = match (division_from_feature(&feature), view.as_mut()) {
(Some(d), Some(view)) => view.admit(d),
(d, None) => d,
(None, Some(_)) => None,
};
if let Some(division) = division
&& let Err(e) = builder.add(division)
{
failed = Some(e);
}
})
.map_err(|e| e.context(format!("failed to read {}", path.display())))?;
if let Some(e) = failed.take() {
return Err(GeolithError::from(e).context(SCRATCH_WRITE));
}
}
for division in view.map(IndiaView::finish).unwrap_or_default() {
builder
.add(division)
.map_err(|e| GeolithError::from(e).context(SCRATCH_WRITE))?;
}
let (file_count, part_count) = (files.len(), builder.parts.len());
tracing::info!(
files = file_count,
parts = part_count,
"division_area loaded"
);
builder
.build()
.map_err(|e| GeolithError::from(e).context("failed to map the admin polygon scratch file"))
}
const SCRATCH_WRITE: &str = "failed to write the admin polygon scratch file";
#[cfg(test)]
mod tests {
use super::*;
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<[f64; 2]> {
vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
}
fn division(
id: u64,
level: AdminLevel,
name: &str,
parts: Vec<Vec<Vec<[f64; 2]>>>,
) -> AdminDivision {
AdminDivision {
id,
level,
name: name.to_string(),
country_code: None,
region_code: None,
parts,
}
}
fn index(divisions: Vec<AdminDivision>) -> AdminHierarchyIndex {
let mut b = AdminHierarchyBuilder::new();
for d in divisions {
b.add(d).unwrap();
}
b.build().unwrap()
}
fn index_in(dir: &Path, divisions: Vec<AdminDivision>) -> AdminHierarchyIndex {
let mut b = AdminHierarchyBuilder::in_dir(dir);
for d in divisions {
b.add(d).unwrap();
}
b.build().unwrap()
}
#[test]
fn polygon_vertices_live_in_a_scratch_file() {
let vertices = 20_000_usize;
let ring: Vec<[f64; 2]> = (0..vertices)
.map(|i| {
let angle = std::f64::consts::TAU * i as f64 / vertices as f64;
[10.0 + angle.cos(), 10.0 + angle.sin()]
})
.collect();
let tmp = tempfile::tempdir().unwrap();
let idx = index_in(
tmp.path(),
vec![division(1, AdminLevel::Locality, "Round", vec![vec![ring]])],
);
assert!(
idx.backing_bytes() >= vertices as u64 * 16,
"{} bytes",
idx.backing_bytes()
);
assert_eq!(idx.resolve(10.0, 10.0).locality.as_deref(), Some("Round"));
assert_eq!(idx.resolve(10.9, 10.0).locality.as_deref(), Some("Round"));
assert!(idx.resolve(11.1, 10.0).locality.is_none());
}
#[test]
fn empty_index_resolves_nothing() {
let idx = index(vec![]);
assert!(idx.is_empty());
assert!(idx.resolve(77.0, 28.0).country.is_none());
}
#[test]
fn country_fields_come_from_the_containing_country() {
let mut india = division(
1,
AdminLevel::Country,
"India",
vec![vec![square(68.0, 6.5, 97.5, 37.2)]],
);
india.country_code = Some("IN".into());
let idx = index(vec![india]);
let h = idx.resolve(77.0, 28.0);
assert_eq!(h.country.as_deref(), Some("India"));
assert_eq!(h.country_code.as_deref(), Some("IN"));
assert!(idx.resolve(0.0, 0.0).country.is_none());
}
#[test]
fn a_point_in_a_hole_is_outside_the_surrounding_country() {
let south_africa = division(
1,
AdminLevel::Country,
"South Africa",
vec![vec![
square(16.0, -35.0, 33.0, -22.0),
square(27.0, -30.7, 29.5, -28.5),
]],
);
let lesotho = division(
2,
AdminLevel::Country,
"Lesotho",
vec![vec![square(27.0, -30.7, 29.5, -28.5)]],
);
let idx = index(vec![south_africa, lesotho]);
assert_eq!(idx.resolve(28.2, -29.6).country.as_deref(), Some("Lesotho"));
assert_eq!(
idx.resolve(18.4, -33.9).country.as_deref(),
Some("South Africa")
);
}
#[test]
fn every_part_of_a_multipolygon_resolves() {
let islands = division(
1,
AdminLevel::Region,
"Islands",
vec![
vec![square(0.0, 0.0, 1.0, 1.0)],
vec![square(10.0, 10.0, 11.0, 11.0)],
],
);
let idx = index(vec![islands]);
assert_eq!(idx.len(), 2);
assert_eq!(idx.resolve(0.5, 0.5).region.as_deref(), Some("Islands"));
assert_eq!(idx.resolve(10.5, 10.5).region.as_deref(), Some("Islands"));
assert!(idx.resolve(5.0, 5.0).region.is_none());
}
#[test]
fn a_detailed_concave_ring_is_tested_exactly() {
let mut ring = Vec::new();
let steps = 50;
let side = |ring: &mut Vec<[f64; 2]>, a: [f64; 2], b: [f64; 2]| {
for k in 0..steps {
let t = k as f64 / steps as f64;
ring.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
}
};
for w in [
[[0.0, 0.0], [10.0, 0.0]],
[[10.0, 0.0], [10.0, 4.0]],
[[10.0, 4.0], [3.0, 4.0]],
[[3.0, 4.0], [3.0, 6.0]],
[[3.0, 6.0], [10.0, 6.0]],
[[10.0, 6.0], [10.0, 10.0]],
[[10.0, 10.0], [0.0, 10.0]],
[[0.0, 10.0], [0.0, 0.0]],
] {
side(&mut ring, w[0], w[1]);
}
let idx = index(vec![division(
1,
AdminLevel::Locality,
"C",
vec![vec![ring]],
)]);
for (x, y, inside) in [
(1.0, 1.0, true),
(9.0, 9.0, true),
(2.0, 5.0, true),
(5.0, 5.0, false),
(9.9, 5.0, false),
(11.0, 5.0, false),
(5.0, 3.9, true),
(5.0, 6.1, true),
] {
assert_eq!(idx.resolve(x, y).locality.is_some(), inside, "({x}, {y})");
}
}
#[test]
fn the_smallest_containing_division_of_a_level_wins() {
let big = division(
1,
AdminLevel::Locality,
"Big",
vec![vec![square(0.0, 0.0, 10.0, 10.0)]],
);
let small = division(
9,
AdminLevel::Locality,
"Small",
vec![vec![square(4.0, 4.0, 6.0, 6.0)]],
);
let idx = index(vec![small, big]);
assert_eq!(idx.resolve(5.0, 5.0).locality.as_deref(), Some("Small"));
assert_eq!(idx.resolve(1.0, 1.0).locality.as_deref(), Some("Big"));
}
#[test]
fn the_largest_containing_locality_is_the_city() {
let city = division(
1,
AdminLevel::Locality,
"Bengaluru",
vec![vec![square(0.0, 0.0, 10.0, 10.0)]],
);
let ward = division(
9,
AdminLevel::Locality,
"Chikka Devasandra",
vec![vec![square(4.0, 4.0, 6.0, 6.0)]],
);
let mid = division(
5,
AdminLevel::Locality,
"Bangalore East",
vec![vec![square(3.0, 3.0, 7.0, 7.0)]],
);
let idx = index(vec![ward, city, mid]);
let inner = idx.resolve(5.0, 5.0);
assert_eq!(inner.locality.as_deref(), Some("Chikka Devasandra"));
assert_eq!(inner.city.as_deref(), Some("Bengaluru"));
assert_eq!(idx.resolve(1.0, 1.0).city, None);
}
#[test]
fn equal_areas_tie_break_on_the_lower_id() {
let a = division(
7,
AdminLevel::County,
"Seven",
vec![vec![square(0.0, 0.0, 1.0, 1.0)]],
);
let b = division(
3,
AdminLevel::County,
"Three",
vec![vec![square(0.0, 0.0, 1.0, 1.0)]],
);
assert_eq!(
index(vec![a, b]).resolve(0.5, 0.5).county.as_deref(),
Some("Three")
);
}
#[test]
fn a_dependency_fills_country_only_when_no_country_contains_the_point() {
let mut us = division(
1,
AdminLevel::Country,
"United States",
vec![vec![square(-125.0, 24.0, -66.0, 49.0)]],
);
us.country_code = Some("US".into());
let mut pr = division(
2,
AdminLevel::Dependency,
"Puerto Rico",
vec![vec![square(-67.3, 17.9, -65.6, 18.6)]],
);
pr.country_code = Some("PR".into());
let mut inside_us = division(
3,
AdminLevel::Dependency,
"Overlap",
vec![vec![square(-100.0, 30.0, -99.0, 31.0)]],
);
inside_us.country_code = Some("XX".into());
let idx = index(vec![us, pr, inside_us]);
let h = idx.resolve(-66.1, 18.4);
assert_eq!(
(h.country.as_deref(), h.country_code.as_deref()),
(Some("Puerto Rico"), Some("PR"))
);
let h = idx.resolve(-99.5, 30.5);
assert_eq!(
(h.country.as_deref(), h.country_code.as_deref()),
(Some("United States"), Some("US"))
);
}
#[test]
fn a_point_outside_every_country_takes_the_country_of_its_region() {
let mut india = division(
1,
AdminLevel::Country,
"India",
vec![vec![square(72.9, 8.0, 97.5, 37.2)]],
);
india.country_code = Some("IN".into());
let mut maharashtra = division(
2,
AdminLevel::Region,
"Maharashtra",
vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
);
maharashtra.country_code = Some("IN".into());
let h = index(vec![india, maharashtra]).resolve(72.8346, 18.9220);
assert_eq!(
(
h.country.as_deref(),
h.country_code.as_deref(),
h.region.as_deref()
),
(Some("India"), Some("IN"), Some("Maharashtra"))
);
}
#[test]
fn a_region_whose_country_is_not_loaded_gives_the_code_alone() {
let mut maharashtra = division(
2,
AdminLevel::Region,
"Maharashtra",
vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
);
maharashtra.country_code = Some("IN".into());
let h = index(vec![maharashtra]).resolve(72.8346, 18.9220);
assert_eq!(
(h.country.as_deref(), h.country_code.as_deref()),
(None, Some("IN"))
);
}
#[test]
fn the_country_name_for_a_region_code_prefers_the_country_to_a_dependency() {
let mut dependency = division(
1,
AdminLevel::Dependency,
"Island Territory",
vec![vec![square(92.0, 6.0, 94.0, 14.0)]],
);
dependency.country_code = Some("IN".into());
let mut india = division(
2,
AdminLevel::Country,
"India",
vec![vec![square(72.9, 8.0, 91.0, 37.2)]],
);
india.country_code = Some("IN".into());
let mut maharashtra = division(
3,
AdminLevel::Region,
"Maharashtra",
vec![vec![square(72.6, 15.6, 80.9, 22.1)]],
);
maharashtra.country_code = Some("IN".into());
let h = index(vec![dependency, india, maharashtra]).resolve(72.8346, 18.9220);
assert_eq!(h.country.as_deref(), Some("India"));
}
#[test]
fn all_levels_resolve_together() {
let idx = index(vec![
division(
1,
AdminLevel::Country,
"France",
vec![vec![square(-5.0, 42.0, 8.0, 51.0)]],
),
division(
2,
AdminLevel::Region,
"ÃŽle-de-France",
vec![vec![square(1.4, 48.1, 3.6, 49.3)]],
),
division(
3,
AdminLevel::County,
"Paris",
vec![vec![square(2.2, 48.8, 2.5, 48.9)]],
),
division(
4,
AdminLevel::Locality,
"Paris",
vec![vec![square(2.2, 48.8, 2.5, 48.9)]],
),
division(
5,
AdminLevel::Neighbourhood,
"Le Marais",
vec![vec![square(2.35, 48.85, 2.37, 48.87)]],
),
]);
let h = idx.resolve(2.36, 48.86);
assert_eq!(h.country.as_deref(), Some("France"));
assert_eq!(h.region.as_deref(), Some("ÃŽle-de-France"));
assert_eq!(h.county.as_deref(), Some("Paris"));
assert_eq!(h.locality.as_deref(), Some("Paris"));
assert_eq!(h.neighbourhood.as_deref(), Some("Le Marais"));
}
#[test]
fn degenerate_rings_are_skipped() {
let idx = index(vec![division(
1,
AdminLevel::Region,
"Line",
vec![vec![vec![[0.0, 0.0], [1.0, 1.0]]]],
)]);
assert!(idx.is_empty());
}
fn division_feature(props: &[(&str, &str)], geometry: geo::Geometry<f64>) -> InputFeature {
InputFeature {
id: 11,
geometry: std::sync::Arc::new(geometry),
properties: props
.iter()
.map(|(k, v)| {
(
k.to_string(),
crate::tile::feature::PropValue::Str(v.to_string()),
)
})
.collect(),
bbox: None,
source: crate::source::input::DataSource::Overture {
theme: "divisions".into(),
otype: "division_area".into(),
},
}
}
fn unit_polygon() -> geo::Polygon<f64> {
geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 0.0),
(1.0, 1.0),
(0.0, 1.0),
(0.0, 0.0),
]),
vec![],
)
}
const LAND_REGION: [(&str, &str); 4] = [
("class", "land"),
("subtype", "region"),
("names.primary", "Bavaria"),
("country", "de"),
];
#[test]
fn a_land_polygon_becomes_a_division() {
let f = division_feature(&LAND_REGION, geo::Geometry::Polygon(unit_polygon()));
let d = division_from_feature(&f).expect("division");
assert_eq!(
(d.id, d.level, d.name.as_str()),
(11, AdminLevel::Region, "Bavaria")
);
assert_eq!(d.country_code.as_deref(), Some("DE"));
assert_eq!(d.parts.len(), 1);
assert_eq!(d.parts[0][0].len(), 5);
}
#[test]
fn a_multipolygon_keeps_every_part() {
let mut far = unit_polygon();
far.exterior_mut(|r| r.0.iter_mut().for_each(|c| c.x += 10.0));
let mp = geo::MultiPolygon::new(vec![unit_polygon(), far]);
let d = division_from_feature(&division_feature(
&LAND_REGION,
geo::Geometry::MultiPolygon(mp),
))
.expect("division");
assert_eq!(d.parts.len(), 2);
assert_eq!(d.parts[1][0][0], [10.0, 0.0]);
}
#[test]
fn unusable_features_are_rejected() {
let polygon = || geo::Geometry::Polygon(unit_polygon());
fn with(
key: &'static str,
value: Option<&'static str>,
) -> Vec<(&'static str, &'static str)> {
let mut props: Vec<_> = LAND_REGION
.iter()
.copied()
.filter(|(k, _)| *k != key)
.collect();
props.extend(value.map(|v| (key, v)));
props
}
for (reason, props, geometry) in [
("maritime", with("class", Some("maritime")), polygon()),
("no class", with("class", None), polygon()),
("empty class", with("class", Some("")), polygon()),
(
"unmapped subtype",
with("subtype", Some("macrohood")),
polygon(),
),
("no subtype", with("subtype", None), polygon()),
("no name", with("names.primary", None), polygon()),
(
"point geometry",
with("class", Some("land")),
geo::Geometry::Point(geo::Point::new(0.5, 0.5)),
),
] {
assert!(
division_from_feature(&division_feature(&props, geometry)).is_none(),
"{reason}"
);
}
}
#[test]
fn a_zero_height_ring_contains_nothing() {
let flat = division(
1,
AdminLevel::Locality,
"Flat",
vec![vec![vec![[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]]],
);
let idx = index(vec![flat]);
assert_eq!(idx.len(), 1);
assert!(idx.resolve(1.0, 1.0).locality.is_none());
}
#[test]
fn a_missing_division_area_directory_loads_an_empty_index() {
let tmp = tempfile::tempdir().unwrap();
assert!(
load_admin_index(tmp.path(), None, None, None)
.unwrap()
.is_empty()
);
}
#[test]
fn a_corrupt_division_file_is_an_error_naming_the_file() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("theme=divisions/type=division_area");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("part-0.parquet"), b"not parquet").unwrap();
let err = load_admin_index(tmp.path(), None, None, None)
.err()
.expect("error");
assert!(
crate::error::report(&err).contains("part-0.parquet"),
"{err:#}"
);
}
#[cfg(unix)]
#[test]
fn an_unreadable_division_area_directory_is_an_error() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("theme=divisions/type=division_area");
std::fs::create_dir_all(&dir).unwrap();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).unwrap();
let result = load_admin_index(tmp.path(), None, None, None);
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(result.is_err());
}
#[test]
fn subtypes_map_to_levels() {
for (subtype, level) in [
("country", Some(AdminLevel::Country)),
("dependency", Some(AdminLevel::Dependency)),
("region", Some(AdminLevel::Region)),
("county", Some(AdminLevel::County)),
("locality", Some(AdminLevel::Locality)),
("neighborhood", Some(AdminLevel::Neighbourhood)),
("localadmin", None),
("macrohood", None),
("microhood", None),
] {
assert_eq!(
AdminLevel::from_overture_subtype(subtype),
level,
"{subtype}"
);
}
}
}