use std::collections::HashMap;
use crate::importance::{Wikipedia, default_importance};
use crate::osm::record_id;
use crate::place_importance::{SettlementClass, division_signals, settlement_importance};
use crate::record::{GeocodingLayer, GeocodingRecord, RecordInit};
use geolith::admin::{AdminHierarchy, AdminHierarchyIndex};
use geolith::conflation::spatial::haversine_distance_m;
use geolith::source::input::{InputFeature, OsmElementType};
use geolith::source::reader::SOURCE_ID_PROP;
use geolith::tile::feature::PropValue;
pub const SAME_PLACE_M: f64 = 2_000.0;
pub const SEAT_KM: f64 = 60.0;
const CELL_DEG: f64 = 0.05;
fn prop<'a>(feature: &'a InputFeature, key: &str) -> Option<&'a str> {
match feature.properties.get(key) {
Some(PropValue::Str(s)) if !s.trim().is_empty() => Some(s.trim()),
_ => None,
}
}
#[must_use]
pub fn division_layer(subtype: &str, class: Option<&str>) -> Option<(GeocodingLayer, u8)> {
Some(match subtype {
"country" | "dependency" => (GeocodingLayer::Country, 4),
"region" => (GeocodingLayer::Region, 8),
"county" => (GeocodingLayer::County, 12),
"localadmin" => (GeocodingLayer::County, 14),
"locality" => (
GeocodingLayer::Locality,
match class {
Some("city") => 16,
Some("town") => 18,
Some("hamlet") => 20,
_ => 19,
},
),
"macrohood" => (GeocodingLayer::Locality, 19),
"neighborhood" => (GeocodingLayer::Locality, 20),
"microhood" => (GeocodingLayer::Locality, 24),
_ => return None,
})
}
#[must_use]
pub fn osm_record_id(feature: &InputFeature) -> Option<u64> {
if prop(feature, "sources.dataset")? != "OpenStreetMap" {
return None;
}
let source = prop(feature, "sources.record_id")?;
let element = match source.get(..1)? {
"n" => OsmElementType::Node,
"w" => OsmElementType::Way,
"r" => OsmElementType::Relation,
_ => return None,
};
let id = source.get(1..)?.split('@').next()?.parse::<u64>().ok()?;
Some(record_id(element, id))
}
fn fold(name: &str) -> String {
name.trim().to_lowercase()
}
fn folded_names(feature: &InputFeature) -> Vec<String> {
let mut names: Vec<String> = Vec::with_capacity(2);
for key in ["names.primary", "names.common.en"] {
if let Some(name) = prop(feature, key) {
let name = fold(name);
if !names.contains(&name) {
names.push(name);
}
}
}
names
}
fn point(feature: &InputFeature) -> Option<(f64, f64)> {
match feature.geometry.as_ref() {
geo::Geometry::Point(p) => Some((p.x(), p.y())),
_ => None,
}
}
fn cell(lon: f64, lat: f64) -> (i32, i32) {
let at = |v: f64| (v / CELL_DEG).floor() as i32;
(at(lon), at(lat))
}
pub(crate) fn above(mut admin: AdminHierarchy, layer: GeocodingLayer, rank: u8) -> AdminHierarchy {
match layer {
GeocodingLayer::Country => {
admin = AdminHierarchy {
country_code: admin.country_code,
..AdminHierarchy::default()
};
}
GeocodingLayer::Region => {
admin.region = None;
admin.county = None;
admin.locality = None;
admin.neighbourhood = None;
}
GeocodingLayer::County => {
admin.county = None;
admin.locality = None;
admin.neighbourhood = None;
}
GeocodingLayer::Locality if rank <= TOWN_RANK => {
admin.locality = None;
admin.neighbourhood = None;
}
GeocodingLayer::Locality => admin.neighbourhood = None,
_ => {}
}
admin
}
pub(crate) const TOWN_RANK: u8 = 18;
fn is_foreign_admin_area(feature: &InputFeature) -> bool {
prop(feature, "subtype").is_some_and(|subtype| {
geolith::admin::soi_area::is_foreign_admin_area(
subtype,
prop(feature, "country"),
prop(feature, "region"),
)
})
}
#[must_use]
pub fn division_record(
feature: &InputFeature,
at: Option<(f64, f64)>,
admin_index: &AdminHierarchyIndex,
wikipedia: &Wikipedia,
) -> Option<GeocodingRecord> {
let (layer, rank) = division_layer(prop(feature, "subtype")?, prop(feature, "class"))?;
let name = prop(feature, "names.primary")?.to_string();
let (lon, lat) = at.or_else(|| point(feature))?;
if is_foreign_admin_area(feature) && admin_index.in_soi(lon, lat) {
return None;
}
let mut names = HashMap::new();
for (key, value) in &feature.properties {
if let Some(lang) = key.strip_prefix("names.common.")
&& let PropValue::Str(v) = value
&& !v.trim().is_empty()
{
names.insert(lang.to_string(), v.trim().to_string());
}
}
let importance = (prop(feature, "subtype") == Some("locality"))
.then(|| prop(feature, "class").and_then(SettlementClass::from_overture))
.flatten()
.map(|class| {
settlement_importance(
wikipedia,
prop(feature, "wikidata"),
class,
&division_signals(feature),
)
})
.unwrap_or_else(|| {
prop(feature, "wikidata")
.and_then(|item| wikipedia.get(item))
.unwrap_or_else(|| default_importance(rank))
});
let mut record = GeocodingRecord::new(RecordInit {
id: feature.id,
source: feature.source.clone(),
layer,
name,
lon,
lat,
admin: above(admin_index.resolve(lon, lat), layer, rank),
address: None,
names,
importance,
});
if let Some(source_id) = prop(feature, SOURCE_ID_PROP) {
record = record.with_source_id(source_id);
}
record.prefer_english_name();
record.shape = crate::shape::admin_outline(admin_index, &record);
Some(record)
}
type Seat = (f64, f64, f32, Vec<String>);
fn name_words(feature: &InputFeature) -> Vec<String> {
let mut words: Vec<String> = Vec::new();
for name in folded_names(feature) {
for word in glx::tokenize::index_tokens(&name) {
if !words.contains(&word) {
words.push(word);
}
}
}
words
}
#[derive(Debug, Default)]
pub struct DivisionIndex {
osm: Vec<(u64, bool)>,
others: HashMap<String, (Vec<String>, f64, f64, bool)>,
grid: HashMap<(i32, i32), Vec<String>>,
seats: HashMap<String, Vec<Seat>>,
linked: HashMap<u64, (f64, f64)>,
}
impl DivisionIndex {
pub fn place_linked(&mut self, points: &HashMap<i64, [f64; 2]>) {
self.linked.reserve(points.len());
for (&relation, &[lon, lat]) in points {
self.linked.insert(
record_id(OsmElementType::Relation, relation.unsigned_abs()),
(lon, lat),
);
}
}
#[must_use]
pub fn located(&self, feature: &InputFeature) -> Option<(f64, f64)> {
osm_record_id(feature)
.and_then(|id| self.linked.get(&id).copied())
.or_else(|| point(feature))
}
pub fn add(&mut self, feature: &InputFeature) {
let Some((layer, _)) = division_layer(prop(feature, "subtype").unwrap_or(""), None) else {
return;
};
if matches!(layer, GeocodingLayer::County | GeocodingLayer::Region) {
for word in name_words(feature) {
self.seats.entry(word).or_default();
}
}
if let Some(id) = osm_record_id(feature) {
self.osm.push((id, false));
}
let (Some(source_id), Some((lon, lat))) = (prop(feature, SOURCE_ID_PROP), point(feature))
else {
return;
};
let names = folded_names(feature);
if names.is_empty() {
return;
}
self.grid
.entry(cell(lon, lat))
.or_default()
.push(source_id.to_string());
self.others
.insert(source_id.to_string(), (names, lon, lat, false));
}
pub fn seal(&mut self) {
self.osm.sort_unstable_by_key(|(id, _)| *id);
self.osm.dedup_by_key(|(id, _)| *id);
}
pub fn mark(&mut self, record: &GeocodingRecord) {
if let Ok(at) = self.osm.binary_search_by_key(&record.id, |(id, _)| *id) {
self.osm[at].1 = true;
}
if record.layer == GeocodingLayer::Locality && !self.seats.is_empty() {
for name in record.all_names() {
let words = glx::tokenize::index_tokens(name);
if let Some(towns) = words.first().and_then(|first| self.seats.get_mut(first)) {
towns.push((record.lon, record.lat, record.importance, words));
}
}
}
if self.others.is_empty() {
return;
}
let names: Vec<String> = record.all_names().into_iter().map(fold).collect();
let (cx, cy) = cell(record.lon, record.lat);
for dx in -1..=1 {
for dy in -1..=1 {
let Some(ids) = self.grid.get(&(cx + dx, cy + dy)) else {
continue;
};
for source_id in ids {
if let Some((own, lon, lat, seen)) = self.others.get_mut(source_id)
&& !*seen
&& own.iter().any(|name| names.contains(name))
&& haversine_distance_m(record.lon, record.lat, *lon, *lat) <= SAME_PLACE_M
{
*seen = true;
}
}
}
}
}
#[must_use]
pub fn seat_importance(&self, feature: &InputFeature) -> Option<f32> {
let (layer, _) = division_layer(prop(feature, "subtype")?, None)?;
if !matches!(layer, GeocodingLayer::County | GeocodingLayer::Region) {
return None;
}
let (lon, lat) = self.located(feature)?;
let words = name_words(feature);
words
.iter()
.filter_map(|word| self.seats.get(word))
.flatten()
.filter(|(_, _, _, town)| town.iter().all(|w| words.contains(w)))
.map(|&(x, y, importance, _)| (haversine_distance_m(lon, lat, x, y), importance))
.filter(|(m, _)| *m <= SEAT_KM * 1_000.0)
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, importance)| importance * 0.99)
}
#[must_use]
pub fn written(&self, feature: &InputFeature) -> bool {
let by_id = osm_record_id(feature).is_some_and(|id| {
self.osm
.binary_search_by_key(&id, |(id, _)| *id)
.is_ok_and(|at| self.osm[at].1)
});
by_id
|| prop(feature, SOURCE_ID_PROP)
.and_then(|source_id| self.others.get(source_id))
.is_some_and(|(_, _, _, seen)| *seen)
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use geolith::source::input::DataSource;
fn division(props: &[(&str, &str)], lon: f64, lat: f64) -> InputFeature {
InputFeature {
id: 7,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(lon, lat))),
properties: props
.iter()
.map(|(k, v)| ((*k).to_string(), PropValue::Str((*v).to_string())))
.collect(),
bbox: None,
source: DataSource::Overture {
theme: "divisions".into(),
otype: "division".into(),
},
}
}
fn osm(record: &str) -> InputFeature {
division(
&[
("subtype", "locality"),
("names.primary", "Agatti"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", record),
],
72.18,
10.86,
)
}
#[test]
fn an_osm_source_gives_the_osm_record_id() {
assert_eq!(osm_record_id(&osm("n982044205@6")), Some(982_044_205));
assert_eq!(osm_record_id(&osm("w42@1")), Some((1 << 62) | 42));
assert_eq!(
osm_record_id(&osm("r2027460@26")),
Some((2 << 62) | 2_027_460)
);
assert_eq!(osm_record_id(&osm("x42@1")), None);
assert_eq!(osm_record_id(&osm("n@1")), None);
let linz = division(
&[("sources.dataset", "Linz"), ("sources.record_id", "n42@1")],
0.0,
0.0,
);
assert_eq!(osm_record_id(&linz), None);
}
#[test]
fn subtypes_take_nominatim_ranks() {
assert_eq!(
division_layer("locality", Some("city")),
Some((GeocodingLayer::Locality, 16))
);
assert_eq!(
division_layer("locality", None),
Some((GeocodingLayer::Locality, 19))
);
assert_eq!(
division_layer("neighborhood", None),
Some((GeocodingLayer::Locality, 20))
);
assert_eq!(
division_layer("county", None),
Some((GeocodingLayer::County, 12))
);
assert_eq!(
division_layer("region", None),
Some((GeocodingLayer::Region, 8))
);
assert_eq!(division_layer("ocean", None), None);
}
#[test]
fn a_division_keeps_only_the_admin_levels_above_its_own() {
use geolith::admin::AdminHierarchy;
let admin = AdminHierarchy {
country_code: Some("IN".into()),
country: Some("India".into()),
region: Some("Manipur".into()),
county: Some("Senapati".into()),
locality: Some("Tungjoy".into()),
neighbourhood: Some("Ward 1".into()),
borough: None,
postcode: None,
city: None,
};
let county = above(admin.clone(), GeocodingLayer::County, 12);
assert_eq!(county.locality, None);
assert_eq!(county.neighbourhood, None);
assert_eq!(county.county, None);
assert_eq!(county.region.as_deref(), Some("Manipur"));
let region = above(admin.clone(), GeocodingLayer::Region, 8);
assert_eq!(region.region, None);
assert_eq!(region.country.as_deref(), Some("India"));
let country = above(admin.clone(), GeocodingLayer::Country, 4);
assert_eq!(country.country, None);
assert_eq!(country.country_code.as_deref(), Some("IN"));
let hood = above(admin.clone(), GeocodingLayer::Locality, 20);
assert_eq!(hood.locality.as_deref(), Some("Tungjoy"));
assert_eq!(hood.neighbourhood, None);
let town = above(admin, GeocodingLayer::Locality, 18);
assert_eq!(town.locality, None);
assert_eq!(town.county.as_deref(), Some("Senapati"));
}
#[test]
fn a_linked_boundary_stands_at_its_settlement() {
let prefecture = division(
&[
("subtype", "region"),
("names.primary", "東京都"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r1543125@384"),
],
139.294_774_5,
34.225_580_4,
);
let mut index = DivisionIndex::default();
index.add(&prefecture);
index.seal();
let mut city = written_osm_place(265_018_692, "東京都", 139.763_894_7, 35.676_860_1);
city.importance = 0.834;
index.mark(&city);
assert_eq!(
index.located(&prefecture),
Some((139.294_774_5, 34.225_580_4))
);
assert_eq!(
index.seat_importance(&prefecture),
None,
"the city is 165 km away"
);
index.place_linked(&HashMap::from([(1_543_125, [139.763_894_7, 35.676_860_1])]));
assert_eq!(
index.located(&prefecture),
Some((139.763_894_7, 35.676_860_1))
);
let below = index
.seat_importance(&prefecture)
.expect("the city is the seat");
assert!(below < 0.834, "{below}");
let admin = geolith::admin::AdminHierarchyBuilder::new()
.build()
.expect("admin");
let record = division_record(
&prefecture,
index.located(&prefecture),
&admin,
&Wikipedia::default(),
)
.expect("a region");
assert_eq!((record.lon, record.lat), (139.763_894_7, 35.676_860_1));
let other = osm("n2@1");
assert_eq!(index.located(&other), Some((72.18, 10.86)));
}
#[test]
fn an_overture_locality_takes_its_floor_from_its_own_signals() {
let admin = geolith::admin::AdminHierarchyBuilder::new()
.build()
.expect("admin");
let wikipedia =
Wikipedia::read("sv\ta\tDesa_Tawang\t0.21822785325192331\tQ12520130\n".as_bytes())
.expect("rows");
let importance = |class: Option<&str>, extra: &[(&str, PropValue)]| {
let mut props = vec![("subtype", "locality"), ("names.primary", "Tawang")];
if let Some(class) = class {
props.push(("class", class));
}
let mut feature = division(&props, 91.86, 27.59);
for (key, value) in extra {
feature.properties.insert((*key).to_string(), value.clone());
}
division_record(&feature, None, &admin, &wikipedia)
.expect("a locality")
.importance
};
let seat = [
("population", PropValue::I64(11_000)),
("cartography.prominence", PropValue::I64(58)),
("capital_of_divisions", PropValue::Str("county".into())),
];
assert!((importance(Some("town"), &seat) - 0.40).abs() < 1e-6);
let town = [("population", PropValue::I64(11_000))];
assert!((importance(Some("town"), &town) - 0.264_15).abs() < 1e-4);
assert!((importance(Some("town"), &[]) - 0.160_01).abs() < 1e-4);
assert!((importance(Some("hamlet"), &[]) - 0.133_34).abs() < 1e-4);
assert!((importance(None, &seat) - 0.146_68).abs() < 1e-4);
let mut hood = division(
&[("subtype", "neighborhood"), ("names.primary", "Tawang")],
91.86,
27.59,
);
hood.properties
.insert("population".into(), PropValue::I64(500_000));
let record = division_record(&hood, None, &admin, &wikipedia).expect("a neighbourhood");
assert!(
(record.importance - 0.133_34).abs() < 1e-4,
"{}",
record.importance
);
}
#[test]
fn a_district_named_after_its_seat_town_ranks_below_it() {
let district = division(
&[
("subtype", "county"),
("names.primary", "Dhamtari"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r1972719@21"),
],
81.7156,
20.5326,
);
let lonely = division(
&[
("subtype", "county"),
("names.primary", "Senapati"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r2027936@20"),
],
94.15,
25.39,
);
let far = division(
&[
("subtype", "county"),
("names.primary", "Kanker"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r1@1"),
],
81.0,
20.0,
);
let worded = division(
&[
("subtype", "county"),
("names.primary", "Ramban district"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r2@1"),
],
75.25,
33.30,
);
let mut index = DivisionIndex::default();
index.add(&district);
index.add(&lonely);
index.add(&far);
index.add(&worded);
index.seal();
let mut ramban = written_osm_place(9, "Ramban", 75.19, 33.24);
ramban.importance = 0.2;
index.mark(&ramban);
index.mark(&written_osm_place(8, "Kanker", 81.0, 21.0));
let mut town = written_osm_place(12_289_058_716, "Dhamtari", 81.5464, 20.7075);
town.importance = 0.4365;
index.mark(&town);
let mut other = written_osm_place(7, "Senapati", 94.16, 25.40);
other.layer = GeocodingLayer::County;
index.mark(&other);
index.mark(&written_osm_place(10, "Senapati Hills", 94.16, 25.40));
assert!(index.seat_importance(&district).is_some_and(|i| i < 0.4365));
assert_eq!(index.seat_importance(&lonely), None);
assert_eq!(index.seat_importance(&far), None);
assert!(index.seat_importance(&worded).is_some_and(|i| i < 0.2));
}
fn written_osm_place(id: u64, name: &str, lon: f64, lat: f64) -> GeocodingRecord {
GeocodingRecord::new(RecordInit {
id,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
},
layer: GeocodingLayer::Locality,
name: name.to_string(),
lon,
lat,
admin: geolith::admin::AdminHierarchy::default(),
address: None,
names: HashMap::new(),
importance: 0.1,
})
}
#[test]
fn written_places_are_told_by_osm_id_or_by_name_and_distance() {
let node = osm("n982044205@6");
let other = osm("n5@1");
let near = division(
&[
("subtype", "locality"),
("names.primary", "Wellington"),
(SOURCE_ID_PROP, "near"),
("sources.dataset", "Linz"),
],
174.7762,
-41.2865,
);
let far = division(
&[
("subtype", "locality"),
("names.primary", "Wellington"),
(SOURCE_ID_PROP, "far"),
],
174.7762,
-41.2815,
);
let mut index = DivisionIndex::default();
for f in [&node, &other, &near, &far] {
index.add(f);
}
index.seal();
index.mark(&written_osm_place(982_044_205, "Agatti", 72.18, 10.86));
index.mark(&written_osm_place(9, "wellington", 174.7762, -41.3015));
assert!(index.written(&node));
assert!(!index.written(&other));
assert!(index.written(&near), "1,668 m away");
assert!(!index.written(&far), "2,224 m away");
}
#[test]
fn an_osm_relation_point_is_written_by_a_same_name_place_nearby() {
let relation = division(
&[
("subtype", "locality"),
("names.primary", "Navi Mumbai"),
("sources.dataset", "OpenStreetMap"),
("sources.record_id", "r7888990@5"),
(SOURCE_ID_PROP, "r7888990@5"),
],
73.019_853_7,
19.030_826_2,
);
let mut index = DivisionIndex::default();
index.add(&relation);
index.seal();
index.mark(&written_osm_place(
619_091_882,
"Navi Mumbai",
73.019_853_7,
19.030_826_2,
));
assert!(index.written(&relation));
}
fn soi_index() -> AdminHierarchyIndex {
use geolith::admin::AdminHierarchyBuilder;
use geolith::admin::india::{IndiaOutline, IndiaView};
let square = |x0: f64, y0: f64, x1: f64, y1: f64| {
geo::Polygon::new(
geo::LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
vec![],
)
};
let outline = IndiaOutline::new(geo::MultiPolygon(vec![
square(91.0, 26.0, 97.5, 29.5),
square(73.0, 35.0, 77.0, 37.0),
]))
.expect("outline");
let mut builder = AdminHierarchyBuilder::new();
IndiaView::new(&outline)
.finish_into(&mut builder)
.expect("india");
builder.build().expect("index")
}
fn written(feature: &InputFeature, index: &AdminHierarchyIndex) -> bool {
division_record(feature, None, index, &Wikipedia::default()).is_some()
}
#[test]
fn foreign_admin_areas_inside_soi_land_are_not_indexed() {
let index = soi_index();
let at = |props: &[(&str, &str)], lon: f64, lat: f64| {
let mut all = vec![("names.primary", "X")];
all.extend_from_slice(props);
written(&division(&all, lon, lat), &index)
};
let claim = [("subtype", "region"), ("country", "IN")];
assert!(!at(&claim, 94.0, 28.1), "South Tibet: IN with no ISO code");
let tibet = [
("subtype", "region"),
("country", "CN"),
("region", "CN-XZ"),
];
assert!(!at(&tibet, 94.0, 28.1), "Chinese region over Arunachal");
let gb = [
("subtype", "region"),
("country", "PK"),
("region", "PK-GB"),
];
assert!(!at(&gb, 74.3, 35.9), "Gilgit-Baltistan");
let gilgit_division = [
("subtype", "county"),
("country", "PK"),
("region", "PK-GB"),
];
assert!(!at(&gilgit_division, 74.3, 35.9), "Gilgit division");
let prefecture = [
("subtype", "county"),
("country", "CN"),
("region", "CN-XZ"),
];
assert!(!at(&prefecture, 94.0, 28.1), "Chinese prefecture");
let pakistan = [("subtype", "country"), ("country", "PK")];
assert!(
!at(&pakistan, 74.3, 35.9),
"Pakistan label point on SOI land"
);
let arunachal = [
("subtype", "region"),
("country", "IN"),
("region", "IN-AR"),
];
assert!(at(&arunachal, 94.0, 28.1), "Arunachal Pradesh");
let tawang = [
("subtype", "county"),
("country", "IN"),
("region", "IN-AR"),
];
assert!(at(&tawang, 91.9, 27.6), "an Indian county");
assert!(at(&gb, 60.0, 30.0), "a Pakistani region outside SOI land");
assert!(at(&claim, 60.0, 30.0), "the rule is about SOI land");
let gilgit = [("subtype", "locality"), ("country", "PK")];
assert!(at(&gilgit, 74.3, 35.9), "Gilgit locality");
}
}