use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use crate::error::{Result, SearchError};
use crate::record::GeocodingLayer;
use crate::rings::{self, Ring};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AreaKind {
Venue,
Boundary(u8),
}
#[derive(Debug, Clone)]
pub struct AreaRelation {
pub id: i64,
pub kind: AreaKind,
pub tags: HashMap<String, String>,
pub outer: Vec<i64>,
pub inner: Vec<i64>,
pub label: Option<i64>,
pub admin_centre: Option<i64>,
}
pub fn load_area_relations(pbf: &Path) -> Result<Vec<AreaRelation>> {
use osmpbf::{Element, RelMemberType};
let mut found: Vec<AreaRelation> = osmpbf::ElementReader::from_path(pbf)
.map_err(|source| SearchError::ReadOsmPbf {
path: pbf.to_path_buf(),
source,
})?
.par_map_reduce(
|element| {
let Element::Relation(rel) = element else {
return Vec::new();
};
let tags: HashMap<String, String> = rel
.tags()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let Some(kind) = area_kind(&tags) else {
return Vec::new();
};
let mut relation = AreaRelation {
id: rel.id(),
kind,
tags,
outer: Vec::new(),
inner: Vec::new(),
label: None,
admin_centre: None,
};
for member in rel.members() {
let role = member.role().unwrap_or("");
match (member.member_type, role) {
(RelMemberType::Way, "" | "outer") => relation.outer.push(member.member_id),
(RelMemberType::Way, "inner") => relation.inner.push(member.member_id),
(RelMemberType::Node, "label") => relation.label = Some(member.member_id),
(RelMemberType::Node, "admin_centre") => {
relation.admin_centre = Some(member.member_id);
}
_ => {}
}
}
vec![relation]
},
Vec::new,
|mut a, mut b| {
a.append(&mut b);
a
},
)?;
found.sort_unstable_by_key(|r| r.id);
Ok(found)
}
fn area_kind(tags: &HashMap<String, String>) -> Option<AreaKind> {
tags.get("name")?;
let kind = tags.get("type").map(String::as_str);
if kind == Some("multipolygon")
&& crate::osm::VENUE_KEYS
.iter()
.any(|key| tags.contains_key(*key))
{
return Some(AreaKind::Venue);
}
if matches!(kind, Some("boundary" | "multipolygon"))
&& tags.get("boundary").is_some_and(|b| b == "administrative")
{
let level = tags.get("admin_level")?.trim().parse::<u8>().ok()?;
return Some(AreaKind::Boundary(level));
}
None
}
pub struct WayPoints {
path: PathBuf,
out: Option<BufWriter<File>>,
at: u64,
index: HashMap<i64, (u64, u32)>,
}
impl WayPoints {
pub fn new(dir: &Path) -> io::Result<Self> {
let path = dir.join("area-ways.bin");
Ok(Self {
out: Some(BufWriter::new(File::create(&path)?)),
path,
at: 0,
index: HashMap::new(),
})
}
pub fn add(&mut self, id: i64, points: &[[f64; 2]]) -> io::Result<()> {
let Some(out) = self.out.as_mut() else {
return Err(io::Error::other("way points already finished"));
};
for p in points {
out.write_all(&p[0].to_le_bytes())?;
out.write_all(&p[1].to_le_bytes())?;
}
let count = u32::try_from(points.len()).map_err(io::Error::other)?;
self.index.insert(id, (self.at, count));
self.at += 16 * u64::from(count);
Ok(())
}
pub fn finish(&mut self) -> io::Result<()> {
if let Some(out) = self.out.take() {
out.into_inner()
.map_err(io::IntoInnerError::into_error)?
.sync_all()?;
}
Ok(())
}
pub fn read(&self, file: &File, ids: &[i64]) -> io::Result<Vec<Ring>> {
let mut ways = Vec::with_capacity(ids.len());
for id in ids {
let Some(&(offset, count)) = self.index.get(id) else {
continue;
};
let mut bytes = vec![0_u8; 16 * count as usize];
read_exact_at(file, &mut bytes, offset)?;
ways.push(
bytes
.as_chunks::<16>()
.0
.iter()
.map(|c| {
let (lon, lat) = c.split_at(8);
[
f64::from_le_bytes(lon.try_into().unwrap_or([0; 8])),
f64::from_le_bytes(lat.try_into().unwrap_or([0; 8])),
]
})
.collect(),
);
}
Ok(ways)
}
pub fn open(&self) -> io::Result<File> {
File::open(&self.path)
}
}
impl Drop for WayPoints {
fn drop(&mut self) {
drop(self.out.take());
std::fs::remove_file(&self.path).ok();
}
}
#[cfg(unix)]
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
std::os::unix::fs::FileExt::read_exact_at(file, buf, offset)
}
#[cfg(windows)]
fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
while !buf.is_empty() {
let read = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;
if read == 0 {
return Err(io::ErrorKind::UnexpectedEof.into());
}
buf = &mut buf[read..];
offset += read as u64;
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct Settlement {
pub record: u64,
pub node: i64,
pub layer: GeocodingLayer,
pub point: [f64; 2],
pub wikidata: Option<String>,
pub names: Vec<u64>,
pub counted: bool,
}
const OWN_UNIT_WORDS: [&str; 11] = [
"katastralgemeinde",
"kula",
"mahallesi",
"vca",
"phuong",
"xa",
"κοινοτητα",
"municipal",
"corporation",
"m",
"urban",
];
#[must_use]
pub fn name_hash(name: &str) -> u64 {
let words = glx::tokenize::query_tokens(name);
let kept: Vec<&str> = words
.iter()
.map(String::as_str)
.filter(|word| !OWN_UNIT_WORDS.contains(word))
.collect();
let words: Vec<&str> = if kept.is_empty() {
words.iter().map(String::as_str).collect()
} else {
kept
};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
words.join(" ").hash(&mut hasher);
hasher.finish()
}
const PARENT_AREA_KM2: f64 = 50.0;
fn area_km2(polygons: &[Vec<Ring>], lat: f64) -> f64 {
rings::polygons_area(polygons) * 111.32 * 111.32 * lat.to_radians().cos()
}
const fn level_of(layer: GeocodingLayer) -> Option<(u8, u8)> {
match layer {
GeocodingLayer::Country => Some((2, 0)),
GeocodingLayer::Region => Some((4, 1)),
GeocodingLayer::County => Some((5, 2)),
GeocodingLayer::Locality => Some((8, 2)),
GeocodingLayer::Address | GeocodingLayer::Venue | GeocodingLayer::Street => None,
}
}
fn boundary_names(tags: &HashMap<String, String>) -> HashSet<u64> {
["name", "name:en", "official_name", "alt_name", "short_name"]
.iter()
.filter_map(|key| tags.get(*key))
.flat_map(|value| value.split(';'))
.map(name_hash)
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Link {
Label,
Wikidata,
Name(u8),
}
#[must_use]
pub fn link_boundaries(
settlements: &[Settlement],
boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> HashMap<u64, Vec<Vec<Ring>>> {
linked(settlements, boundaries)
.into_iter()
.map(|(index, at, _)| (settlements[index].record, boundaries[at].1.clone()))
.collect()
}
#[must_use]
pub fn linked_points(
settlements: &[Settlement],
boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> HashMap<i64, [f64; 2]> {
let mut best: HashMap<i64, (Link, usize)> = HashMap::new();
for (index, at, link) in linked(settlements, boundaries) {
let entry = best.entry(boundaries[at].0.id).or_insert((link, index));
if (link, index) < *entry {
*entry = (link, index);
}
}
best.into_iter()
.map(|(relation, (_, index))| (relation, settlements[index].point))
.collect()
}
fn linked(
settlements: &[Settlement],
boundaries: &[(&AreaRelation, Vec<Vec<Ring>>)],
) -> Vec<(usize, usize, Link)> {
let counted: rstar::RTree<rstar::primitives::GeomWithData<[f64; 2], usize>> =
rstar::RTree::bulk_load(
settlements
.iter()
.enumerate()
.filter(|(_, s)| s.counted)
.map(|(index, s)| rstar::primitives::GeomWithData::new(s.point, index))
.collect(),
);
let holds_another = |polygons: &[Vec<Ring>], index: usize| -> bool {
let mut bbox: Option<([f64; 2], [f64; 2])> = None;
for p in polygons.iter().filter_map(|p| p.first()).flatten() {
bbox = Some(bbox.map_or((*p, *p), |(lo, hi)| {
(
[lo[0].min(p[0]), lo[1].min(p[1])],
[hi[0].max(p[0]), hi[1].max(p[1])],
)
}));
}
let Some((lo, hi)) = bbox else {
return false;
};
counted
.locate_in_envelope(rstar::AABB::from_corners(lo, hi))
.any(|other| other.data != index && rings::polygons_contain(polygons, *other.geom()))
};
let mut by_node: HashMap<i64, usize> = HashMap::with_capacity(settlements.len());
let mut by_wikidata: HashMap<&str, Vec<usize>> = HashMap::new();
let mut by_name: HashMap<u64, Vec<usize>> = HashMap::new();
for (index, settlement) in settlements.iter().enumerate() {
by_node.insert(settlement.node, index);
if let Some(item) = &settlement.wikidata {
by_wikidata.entry(item.as_str()).or_default().push(index);
}
for &name in &settlement.names {
by_name.entry(name).or_default().push(index);
}
}
let mut best: HashMap<usize, (Link, f64, usize)> = HashMap::new();
for (at, (relation, polygons)) in boundaries.iter().enumerate() {
let AreaKind::Boundary(level) = relation.kind else {
continue;
};
let area = rings::polygons_area(polygons);
let mut offer = |index: usize, link: Link| {
let entry = best.entry(index).or_insert((link, area, at));
if (link, area) < (entry.0, entry.1) {
*entry = (link, area, at);
}
};
if let Some(&index) = relation.label.and_then(|node| by_node.get(&node)) {
offer(index, Link::Label);
}
if let Some(found) = relation
.tags
.get("wikidata")
.and_then(|item| by_wikidata.get(item.as_str()))
{
for &index in found {
offer(index, Link::Wikidata);
}
}
let mut named: Vec<usize> = boundary_names(&relation.tags)
.iter()
.filter_map(|name| by_name.get(name))
.flatten()
.copied()
.collect();
named.sort_unstable();
named.dedup();
for index in named {
let settlement = &settlements[index];
let Some((expected, slack)) = level_of(settlement.layer) else {
continue;
};
let distance = expected.abs_diff(level);
if distance > slack || !rings::polygons_contain(polygons, settlement.point) {
continue;
}
let parent = matches!(level, 6 | 7)
&& area_km2(polygons, settlement.point[1]) > PARENT_AREA_KM2
&& holds_another(polygons, index);
if !parent {
offer(index, Link::Name(distance));
}
}
}
best.into_iter()
.map(|(index, (link, _, at))| (index, at, link))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn square(x: f64, y: f64, side: f64) -> Vec<Vec<Ring>> {
vec![vec![vec![
[x, y],
[x + side, y],
[x + side, y + side],
[x, y + side],
[x, y],
]]]
}
fn boundary(
id: i64,
name: &str,
level: u8,
label: Option<i64>,
wikidata: Option<&str>,
) -> AreaRelation {
let mut tags = HashMap::from([("name".to_string(), name.to_string())]);
if let Some(item) = wikidata {
tags.insert("wikidata".into(), item.into());
}
AreaRelation {
id,
kind: AreaKind::Boundary(level),
tags,
outer: Vec::new(),
inner: Vec::new(),
label,
admin_centre: None,
}
}
fn city(
record: u64,
node: i64,
name: &str,
point: [f64; 2],
wikidata: Option<&str>,
) -> Settlement {
Settlement {
record,
node,
layer: GeocodingLayer::Locality,
point,
wikidata: wikidata.map(str::to_owned),
names: vec![name_hash(name)],
counted: true,
}
}
#[test]
fn a_linked_boundary_takes_its_settlements_point() {
let tokyo = boundary(1_543_125, "東京都", 4, None, Some("Q1490"));
let other = boundary(2, "Nowhere", 4, None, Some("Q2"));
let boundaries = vec![
(&tokyo, square(138.9, 24.0, 12.0)),
(&other, square(0.0, 0.0, 1.0)),
];
let node = city(
10,
265_018_692,
"東京都",
[139.763_894_7, 35.676_860_1],
Some("Q1490"),
);
let points = linked_points(&[node], &boundaries);
assert_eq!(points.get(&1_543_125), Some(&[139.763_894_7, 35.676_860_1]));
assert_eq!(points.len(), 1);
}
#[test]
fn a_large_level_six_unit_holding_other_villages_is_a_parent() {
let tehsil = boundary(1, "Radaur", 6, None, None);
let boundaries = vec![(&tehsil, square(77.0, 30.0, 0.15))];
let town = city(10, 100, "Radaur", [77.05, 30.05], None);
let village = city(11, 101, "Topra", [77.10, 30.10], None);
let links = link_boundaries(&[town.clone(), village], &boundaries);
assert!(!links.contains_key(&10), "the tehsil is not the town");
let links = link_boundaries(&[town], &boundaries);
assert_eq!(links.get(&10), Some(&square(77.0, 30.0, 0.15)));
}
#[test]
fn small_or_level_eight_units_link_with_others_inside() {
let puri = boundary(1, "Puri", 6, None, None);
let boundaries = vec![(&puri, square(85.8, 19.8, 0.03))];
let settlements = [
city(10, 100, "Puri", [85.81, 19.81], None),
city(11, 101, "Penthakata", [85.82, 19.82], None),
];
assert_eq!(
link_boundaries(&settlements, &boundaries).get(&10),
Some(&square(85.8, 19.8, 0.03))
);
let commune = boundary(2, "Chisindia", 8, None, None);
let boundaries = vec![(&commune, square(22.0, 46.2, 0.15))];
let settlements = [
city(20, 200, "Chisindia", [22.05, 46.25], None),
city(21, 201, "Vasoaia", [22.10, 46.30], None),
];
assert!(link_boundaries(&settlements, &boundaries).contains_key(&20));
}
#[test]
fn suburbs_do_not_make_a_parent() {
let tehsil = boundary(1, "Radaur", 6, None, None);
let boundaries = vec![(&tehsil, square(77.0, 30.0, 0.15))];
let mut suburb = city(11, 101, "Topra", [77.10, 30.10], None);
suburb.counted = false;
let town = city(10, 100, "Radaur", [77.05, 30.05], None);
assert!(link_boundaries(&[town, suburb], &boundaries).contains_key(&10));
}
#[test]
fn names_fold_accents_and_own_unit_words() {
assert_eq!(name_hash("Jhārgrām"), name_hash("Jhargram"));
assert_eq!(name_hash("Ülde küla"), name_hash("Ülde"));
assert_eq!(name_hash("Teferrüç Mahallesi"), name_hash("Teferrüç"));
assert_eq!(name_hash("Katastralgemeinde Gerweis"), name_hash("Gerweis"));
assert_eq!(name_hash("Phường Quy Nhơn"), name_hash("Quy Nhơn"));
assert_eq!(
name_hash("Jaipur Municipal Corporation"),
name_hash("Jaipur")
);
assert_eq!(name_hash("Puri (M)"), name_hash("Puri"));
assert_ne!(name_hash("Pachpadra Tehsil"), name_hash("Pachpadra"));
assert_ne!(name_hash("Pune City Subdistrict"), name_hash("Pune"));
assert_ne!(name_hash("VCA"), name_hash(""));
}
#[test]
fn a_city_takes_a_same_named_boundary_only_at_a_city_level() {
let district = boundary(1, "Pune", 5, None, None);
let chennai = boundary(2, "Chennai", 8, None, None);
let boundaries = vec![
(&district, square(73.0, 18.0, 1.0)),
(&chennai, square(80.0, 13.0, 0.5)),
];
let settlements = vec![
city(10, 100, "Pune", [73.86, 18.52], None),
city(20, 200, "Chennai", [80.27, 13.08], None),
];
let links = link_boundaries(&settlements, &boundaries);
assert_eq!(links.len(), 1);
assert_eq!(links.get(&20), Some(&square(80.0, 13.0, 0.5)));
}
#[test]
fn a_name_match_must_hold_the_settlement() {
let far = boundary(1, "Rampur", 8, None, None);
let boundaries = vec![(&far, square(80.0, 25.0, 0.1))];
let settlements = vec![city(10, 100, "Rampur", [77.0, 28.0], None)];
assert!(link_boundaries(&settlements, &boundaries).is_empty());
}
#[test]
fn the_strongest_link_wins() {
let labelled = boundary(1, "Other Name", 4, Some(100), None);
let by_item = boundary(2, "Jaipur Subdistrict", 6, None, Some("Q66485"));
let level9 = boundary(3, "Jaipur", 9, None, None);
let level8_big = boundary(4, "Jaipur", 8, None, None);
let level8_small = boundary(5, "Jaipur", 8, None, None);
let boundaries = vec![
(&labelled, square(0.0, 0.0, 1.0)),
(&by_item, square(75.0, 26.0, 2.0)),
(&level9, square(75.7, 26.8, 0.3)),
];
let settlements = vec![
city(10, 100, "Somewhere", [0.5, 0.5], None),
city(20, 200, "Jaipur", [75.79, 26.91], Some("Q66485")),
];
let links = link_boundaries(&settlements, &boundaries);
assert_eq!(links.get(&10), Some(&square(0.0, 0.0, 1.0)));
assert_eq!(links.get(&20), Some(&square(75.0, 26.0, 2.0)));
let boundaries = vec![
(&level9, square(75.7, 26.8, 0.3)),
(&level8_big, square(75.0, 26.0, 2.0)),
(&level8_small, square(75.5, 26.5, 0.6)),
];
let settlements = vec![city(20, 200, "Jaipur", [75.79, 26.91], None)];
let links = link_boundaries(&settlements, &boundaries);
assert_eq!(links.get(&20), Some(&square(75.5, 26.5, 0.6)));
}
#[test]
fn area_kinds_need_a_name_and_a_kind() {
let tags = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
pairs
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect()
};
assert_eq!(
area_kind(&tags(&[
("type", "boundary"),
("boundary", "administrative"),
("admin_level", "8"),
("name", "Chennai")
])),
Some(AreaKind::Boundary(8))
);
assert_eq!(
area_kind(&tags(&[
("type", "multipolygon"),
("tourism", "attraction"),
("name", "Tokyo Tower")
])),
Some(AreaKind::Venue)
);
assert_eq!(
area_kind(&tags(&[
("type", "boundary"),
("boundary", "administrative"),
("admin_level", "8")
])),
None
);
assert_eq!(
area_kind(&tags(&[
("type", "boundary"),
("boundary", "administrative"),
("name", "X")
])),
None
);
assert_eq!(
area_kind(&tags(&[
("type", "boundary"),
("boundary", "postal_code"),
("admin_level", "8"),
("name", "X")
])),
None
);
}
#[test]
fn way_points_come_back_from_disk() {
let dir = tempfile::tempdir().expect("tmp");
let mut store = WayPoints::new(dir.path()).expect("store");
store.add(7, &[[1.5, 2.5], [3.0, 4.0]]).expect("add");
store.add(9, &[[-180.0, -90.0]]).expect("add");
store.finish().expect("finish");
let file = store.open().expect("open");
let ways = store.read(&file, &[9, 8, 7]).expect("read");
assert_eq!(
ways,
vec![vec![[-180.0, -90.0]], vec![[1.5, 2.5], [3.0, 4.0]]]
);
}
}