use std::collections::HashMap;
use geo::Centroid;
use rayon::prelude::*;
use rstar::primitives::GeomWithData;
use rstar::{AABB, RTree};
use crate::importance::{POI_RANK, Wikipedia, default_importance};
use crate::place_importance::{self, PlaceSignalIndex, SettlementClass, settlement_importance};
use crate::record::{AddressFields, GeocodingLayer, GeocodingRecord, RecordInit};
use geolith::admin::AdminHierarchyIndex;
use geolith::conflation::spatial::{SpatialCandidate, SpatialDedupConfig, haversine_distance_m};
use geolith::source::input::{DataSource, InputFeature, OsmElementType};
use geolith::tile::feature::PropValue;
pub const DUPLICATE_NAME_SIMILARITY: f64 = 0.9;
pub(crate) const VENUE_KEYS: [&str; 10] = [
"amenity",
"shop",
"tourism",
"leisure",
"historic",
"office",
"craft",
"healthcare",
"aeroway",
"railway",
];
const TYPE_SHIFT: u32 = 62;
pub const TWIN_BIT: u64 = 1 << (TYPE_SHIFT - 1);
const ID_MASK: u64 = TWIN_BIT - 1;
#[must_use]
pub const fn record_id(element_type: OsmElementType, osm_id: u64) -> u64 {
let code: u64 = match element_type {
OsmElementType::Node => 0,
OsmElementType::Way => 1,
OsmElementType::Relation => 2,
};
(code << TYPE_SHIFT) | (osm_id & ID_MASK)
}
#[must_use]
pub const fn element_id(record_id: u64) -> u64 {
record_id & ID_MASK
}
#[must_use]
pub fn place_layer(place: &str) -> Option<(GeocodingLayer, u8)> {
Some(match place {
"country" => (GeocodingLayer::Country, 4),
"state" | "province" => (GeocodingLayer::Region, 8),
"region" => (GeocodingLayer::Region, 18),
"county" | "district" => (GeocodingLayer::County, 12),
"city" => (GeocodingLayer::Locality, 16),
"town" => (GeocodingLayer::Locality, 18),
"village" | "suburb" => (GeocodingLayer::Locality, 19),
"hamlet" | "quarter" => (GeocodingLayer::Locality, 20),
"neighbourhood" => (GeocodingLayer::Locality, 24),
_ => return None,
})
}
fn tag(feature: &InputFeature, key: &str) -> Option<String> {
match feature.properties.get(key)? {
PropValue::Str(s) if !s.trim().is_empty() => Some(s.trim().to_string()),
PropValue::Str(_) => None,
PropValue::I64(v) => Some(v.to_string()),
PropValue::U64(v) => Some(v.to_string()),
PropValue::F64(v) => Some(v.to_string()),
PropValue::Bool(v) => Some(v.to_string()),
_ => None,
}
}
fn venue_category(feature: &InputFeature) -> Option<String> {
VENUE_KEYS.iter().find_map(|key| {
let value = tag(feature, key)?;
let qualifies = match *key {
"tourism" => !matches!(value.as_str(), "yes" | "no"),
"railway" => matches!(value.as_str(), "station" | "halt"),
"aeroway" => value == "aerodrome",
_ => value != "no",
};
qualifies.then_some(value)
})
}
fn names(feature: &InputFeature) -> HashMap<String, String> {
let mut out = HashMap::new();
for (key, value) in &feature.properties {
if let Some(lang) = key.strip_prefix("name:")
&& let PropValue::Str(v) = value
&& !v.trim().is_empty()
{
out.insert(lang.to_string(), v.trim().to_string());
}
}
out
}
const OTHER_NAME_KEYS: [&str; 6] = [
"alt_name",
"old_name",
"short_name",
"official_name",
"int_name",
"loc_name",
];
fn other_names(feature: &InputFeature, known: &[&str]) -> Vec<String> {
let mut seen: Vec<String> = known.iter().map(|name| name.to_lowercase()).collect();
let mut out = Vec::new();
for key in OTHER_NAME_KEYS {
for value in tag(feature, key).iter().flat_map(|v| v.split(';')) {
let value = value.trim();
let folded = value.to_lowercase();
if !value.is_empty() && !seen.contains(&folded) {
seen.push(folded);
out.push(value.to_string());
}
}
}
out
}
fn title_name(title: &str) -> Option<String> {
let title = title.split('#').next()?.replace('_', " ");
let mut title = title.trim();
if title.ends_with(')')
&& let Some(open) = title.rfind(" (")
{
title = title[..open].trim_end();
}
(!title.is_empty()).then(|| title.to_string())
}
fn article_names(
feature: &InputFeature,
wikipedia: &Wikipedia,
names: &HashMap<String, String>,
known: &[&str],
) -> Vec<String> {
let tagged = tag(feature, "wikipedia").and_then(|value| {
let (lang, title) = value.split_once(':')?;
(2..=3)
.contains(&lang.trim().len())
.then(|| title.to_string())
});
let english =
tag(feature, "wikidata").and_then(|item| wikipedia.english_title(&item).map(str::to_owned));
let mut seen: Vec<String> = known
.iter()
.copied()
.chain(names.values().map(String::as_str))
.map(str::to_lowercase)
.collect();
let mut out = Vec::new();
for title in [tagged, english].into_iter().flatten() {
if let Some(name) = title_name(&title)
&& !seen
.iter()
.any(|known| qualifies(&name.to_lowercase(), known))
{
seen.push(name.to_lowercase());
out.push(name);
}
}
out
}
fn qualifies(title: &str, name: &str) -> bool {
if name.is_empty() {
return false;
}
if title.contains(name) || name.contains(title) {
return true;
}
let words = |text: &str| -> Vec<String> {
text.split(|c: char| !c.is_alphanumeric())
.filter(|word| !word.is_empty())
.map(str::to_owned)
.collect()
};
let name_words = words(name);
words(title).iter().any(|word| name_words.contains(word))
}
fn address(feature: &InputFeature) -> Option<AddressFields> {
let number = tag(feature, "addr:housenumber");
let street = tag(feature, "addr:street").or_else(|| tag(feature, "addr:place"));
if number.is_none() && street.is_none() {
return None;
}
Some(AddressFields {
number,
street,
unit: tag(feature, "addr:unit"),
postcode: tag(feature, "addr:postcode"),
city: tag(feature, "addr:city"),
})
}
pub fn may_be_record<'a>(tags: impl IntoIterator<Item = (&'a str, &'a str)>) -> bool {
let (mut named, mut kind) = (false, false);
for (key, _) in tags {
match key {
"addr:housenumber" | "addr:street" | "addr:place" => return true,
"name" => named = true,
"place" => kind = true,
key if VENUE_KEYS.contains(&key) => kind = true,
_ => {}
}
if named && kind {
return true;
}
}
false
}
#[must_use]
pub fn osm_record(
feature: &InputFeature,
admin_index: &AdminHierarchyIndex,
wikipedia: &Wikipedia,
) -> Option<GeocodingRecord> {
osm_record_with(
feature,
admin_index,
wikipedia,
&PlaceSignalIndex::default(),
)
}
#[must_use]
pub fn osm_record_with(
feature: &InputFeature,
admin_index: &AdminHierarchyIndex,
wikipedia: &Wikipedia,
places: &PlaceSignalIndex,
) -> Option<GeocodingRecord> {
let DataSource::Osm { element_type, .. } = &feature.source else {
return None;
};
let element_type = *element_type;
let name = tag(feature, "name");
let address = address(feature);
let (layer, name, rank, category) = if let (Some(name), Some((layer, rank))) = (
name.clone(),
tag(feature, "place").and_then(|p| place_layer(&p)),
) {
(layer, name, rank, None)
} else if let (Some(name), Some(category)) = (name, venue_category(feature)) {
(GeocodingLayer::Venue, name, POI_RANK, Some(category))
} else {
let a = address.as_ref()?;
let label = match (&a.number, &a.street) {
(Some(n), Some(s)) => format!("{n} {s}"),
(Some(n), None) => n.clone(),
(None, Some(s)) => s.clone(),
(None, None) => return None,
};
(GeocodingLayer::Address, label, POI_RANK, None)
};
let wikidata = tag(feature, "wikidata");
let class = (layer == GeocodingLayer::Locality)
.then(|| tag(feature, "place").and_then(|p| SettlementClass::from_place(&p)))
.flatten();
let importance = if let Some(class) = class {
let signals = place_importance::osm_signals(
tag(feature, "population").as_deref(),
tag(feature, "capital").as_deref(),
)
.or(places.get(record_id(element_type, feature.id)));
settlement_importance(wikipedia, wikidata.as_deref(), class, &signals)
} else {
wikidata
.and_then(|item| wikipedia.get(&item))
.unwrap_or_else(|| default_importance(rank))
};
let point = match feature.geometry.as_ref() {
geo::Geometry::Point(p) => *p,
other => other.centroid()?,
};
let (lon, lat) = (point.x(), point.y());
if !crate::record::valid_point(lon, lat) {
crate::record::count_bad_point();
return None;
}
let address = if layer == GeocodingLayer::Venue || layer == GeocodingLayer::Address {
address
} else {
None
};
let mut admin = admin_index.resolve(lon, lat);
if admin.locality.is_none() {
admin.locality = tag(feature, "addr:city");
}
let admin = crate::division::above(admin, layer, rank);
let kind = match element_type {
OsmElementType::Node => "node",
OsmElementType::Way => "way",
OsmElementType::Relation => "relation",
};
let mut record = GeocodingRecord::new(RecordInit {
id: record_id(element_type, feature.id),
source: feature.source.clone(),
layer,
name,
lon,
lat,
admin,
address,
names: names(feature),
importance,
})
.with_source_id(format!("{kind}/{}", feature.id));
if layer != GeocodingLayer::Address {
let others = other_names(feature, &record.all_names());
let known: Vec<&str> = record
.all_names()
.into_iter()
.chain(others.iter().map(String::as_str))
.collect();
record.article_names = article_names(feature, wikipedia, &record.names, &known);
record.other_names = others;
record.rebuild_search_text();
record.prefer_english_name();
record.shape = crate::shape::from_geometry(
&feature.geometry,
if layer == GeocodingLayer::Venue {
crate::shape::VENUE_TOLERANCE
} else {
crate::shape::AREA_TOLERANCE
},
);
if record.shape.is_empty() {
record.shape = crate::shape::admin_outline(admin_index, &record);
}
}
Some(match category {
Some(c) => record.with_categories(vec![c]),
None => record,
})
}
#[must_use]
pub fn address_twin(venue: &GeocodingRecord) -> Option<GeocodingRecord> {
if venue.layer != GeocodingLayer::Venue {
return None;
}
let address = venue.address.as_ref()?;
let label = format!("{} {}", address.number.as_ref()?, address.street.as_ref()?);
let twin = GeocodingRecord::new(RecordInit {
id: venue.id | TWIN_BIT,
source: venue.source.clone(),
layer: GeocodingLayer::Address,
name: label,
lon: venue.lon,
lat: venue.lat,
admin: venue.admin.clone(),
address: venue.address.clone(),
names: HashMap::new(),
importance: default_importance(POI_RANK),
});
Some(match &venue.source_id {
Some(source_id) => twin.with_source_id(format!("{source_id}/address")),
None => twin,
})
}
fn candidate(record: &GeocodingRecord) -> SpatialCandidate {
SpatialCandidate {
id: record.id,
centroid_lon: record.lon,
centroid_lat: record.lat,
area_m2: None,
name: Some(record.name.clone()),
}
}
pub const SETTLEMENT_RADIUS_M: f64 = 30_000.0;
const SETTLEMENT_CELL_DEG: f64 = 0.25;
type Settlement = (f64, f64, String, f64, Locale);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Locale {
country: [u8; 2],
region: u32,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedPlaces {
pub places: usize,
pub without_country: usize,
pub without_region: usize,
}
const NO_REGION: u32 = u32::MAX;
impl Locale {
const UNKNOWN: Self = Self {
country: [0, 0],
region: NO_REGION,
};
fn country_of(code: Option<&str>) -> [u8; 2] {
match code.map(str::as_bytes) {
Some([a, b]) => [a.to_ascii_uppercase(), b.to_ascii_uppercase()],
_ => [0, 0],
}
}
}
struct Wanted<'a> {
country: [u8; 2],
region: Option<&'a str>,
regions: &'a [String],
}
impl Wanted<'_> {
fn admits(&self, place: &Locale) -> bool {
if self.country != [0, 0] && place.country != [0, 0] && place.country != self.country {
return false;
}
match (self.region, place.region) {
(Some(wanted), id) if id != NO_REGION => self
.regions
.get(id as usize)
.is_some_and(|name| name.eq_ignore_ascii_case(wanted)),
_ => true,
}
}
}
const CITY_AREA_M: f64 = 15_000.0;
const TOWN_AREA_M: f64 = 4_000.0;
const AREA_CELL_DEG: f64 = 0.05;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AreaKind {
Fine,
Suburb,
Borough,
}
#[derive(Debug, Clone)]
struct Area {
lon: f64,
lat: f64,
name: String,
kind: AreaKind,
radius_m: f64,
locale: Locale,
}
fn area_kind(place: &str) -> Option<(AreaKind, f64)> {
match place {
"neighbourhood" => Some((AreaKind::Fine, 500.0)),
"quarter" => Some((AreaKind::Fine, 1000.0)),
"suburb" => Some((AreaKind::Suburb, 2000.0)),
"borough" | "city_district" => Some((AreaKind::Borough, 4000.0)),
_ => None,
}
}
#[derive(Default)]
pub struct SettlementIndex {
cells: HashMap<(i32, i32), Vec<Settlement>>,
areas: HashMap<(i32, i32), Vec<Area>>,
regions: Vec<String>,
postcode_sums: HashMap<String, (f64, f64, u32)>,
postcodes: std::sync::OnceLock<PostcodeCells>,
}
type PostcodeCells = HashMap<(i32, i32), Vec<(f64, f64, String)>>;
const POSTCODE_EXTENT_M: f64 = 5000.0;
const POSTCODE_CELL_DEG: f64 = 0.1;
fn normal_postcode(value: &str) -> Option<String> {
let code: String = value.chars().filter(|c| !c.is_whitespace()).collect();
(!code.is_empty() && code.chars().count() <= 10).then_some(code)
}
impl SettlementIndex {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, place: &str, name: &str, lon: f64, lat: f64) {
if name.trim().is_empty() {
return;
}
if let Some((kind, radius_m)) = area_kind(place) {
self.areas
.entry(area_cell(lon, lat))
.or_default()
.push(Area {
lon,
lat,
name: name.trim().to_string(),
kind,
radius_m,
locale: Locale::UNKNOWN,
});
return;
}
let radius_m = match place {
"city" => CITY_AREA_M,
"town" => TOWN_AREA_M,
_ => return,
};
self.cells
.entry(settlement_cell(lon, lat))
.or_default()
.push((lon, lat, name.trim().to_string(), radius_m, Locale::UNKNOWN));
}
pub fn resolve_admin(&mut self, admin: &AdminHierarchyIndex) -> ResolvedPlaces {
let mut ids: HashMap<String, u32> = HashMap::new();
let mut counts = ResolvedPlaces::default();
let mut regions = Vec::new();
let mut locale = |lon: f64, lat: f64| {
let h = admin.resolve(lon, lat);
let region = h.region.map_or(NO_REGION, |name| {
*ids.entry(name.to_lowercase()).or_insert_with(|| {
regions.push(name);
u32::try_from(regions.len() - 1).unwrap_or(NO_REGION)
})
});
let country = Locale::country_of(h.country_code.as_deref());
counts.places += 1;
counts.without_country += usize::from(country == [0, 0]);
counts.without_region += usize::from(region == NO_REGION);
Locale { country, region }
};
for list in self.cells.values_mut() {
for place in list {
place.4 = locale(place.0, place.1);
}
}
for list in self.areas.values_mut() {
for area in list {
area.locale = locale(area.lon, area.lat);
}
}
self.regions = regions;
counts
}
#[must_use]
pub fn len(&self) -> usize {
self.cells.values().map(Vec::len).sum()
}
#[must_use]
pub fn area_count(&self) -> usize {
self.areas.values().map(Vec::len).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.cells.is_empty()
}
#[must_use]
pub fn nearest(&self, lon: f64, lat: f64) -> Option<&str> {
self.nearest_where(lon, lat, &|_| true)
}
fn nearest_where(&self, lon: f64, lat: f64, allowed: &dyn Fn(&Locale) -> bool) -> Option<&str> {
let (cx, cy) = settlement_cell(lon, lat);
let mut best: Option<(f64, &str)> = None;
for dx in -2..=2 {
for dy in -2..=2 {
let Some(list) = self.cells.get(&(cx + dx, cy + dy)) else {
continue;
};
for (slon, slat, name, _, locale) in list {
let d =
geolith::conflation::spatial::haversine_distance_m(lon, lat, *slon, *slat);
if d <= SETTLEMENT_RADIUS_M
&& best.is_none_or(|(bd, _)| d < bd)
&& allowed(locale)
{
best = Some((d, name.as_str()));
}
}
}
}
best.map(|(_, name)| name)
}
fn town_around(
&self,
lon: f64,
lat: f64,
skip: &[&str],
allowed: &dyn Fn(&Locale) -> bool,
) -> Option<&str> {
let (cx, cy) = settlement_cell(lon, lat);
let mut best: Option<(f64, &str)> = None;
for dx in -1..=1 {
for dy in -1..=1 {
let Some(list) = self.cells.get(&(cx + dx, cy + dy)) else {
continue;
};
for (slon, slat, name, radius_m, locale) in list {
if skip.iter().any(|other| other.eq_ignore_ascii_case(name)) {
continue;
}
let d =
geolith::conflation::spatial::haversine_distance_m(lon, lat, *slon, *slat);
if d <= *radius_m && best.is_none_or(|(bd, _)| d < bd) && allowed(locale) {
best = Some((d, name.as_str()));
}
}
}
}
best.map(|(_, name)| name)
}
pub fn add_postcode(&mut self, value: &str, lon: f64, lat: f64) {
let Some(code) = normal_postcode(value) else {
return;
};
let sums = self.postcode_sums.entry(code).or_insert((0.0, 0.0, 0));
sums.0 += lon;
sums.1 += lat;
sums.2 += 1;
self.postcodes = std::sync::OnceLock::new();
}
fn postcode_of(&self, lon: f64, lat: f64) -> Option<&str> {
let cells = self.postcodes.get_or_init(|| {
let mut cells = PostcodeCells::new();
for (code, (sum_lon, sum_lat, n)) in &self.postcode_sums {
let (clon, clat) = (sum_lon / f64::from(*n), sum_lat / f64::from(*n));
cells.entry(postcode_cell(clon, clat)).or_default().push((
clon,
clat,
code.clone(),
));
}
cells
});
let (cx, cy) = postcode_cell(lon, lat);
let mut best: Option<(f64, &str)> = None;
for dx in -2..=2 {
for dy in -1..=1 {
for (clon, clat, code) in cells.get(&(cx + dx, cy + dy)).into_iter().flatten() {
let ns =
geolith::conflation::spatial::haversine_distance_m(lon, lat, lon, *clat);
let ew = geolith::conflation::spatial::haversine_distance_m(
lon, *clat, *clon, *clat,
);
if ns > POSTCODE_EXTENT_M || ew > POSTCODE_EXTENT_M {
continue;
}
let d =
geolith::conflation::spatial::haversine_distance_m(lon, lat, *clon, *clat);
if best.is_none_or(|(bd, _)| d < bd) {
best = Some((d, code.as_str()));
}
}
}
}
best.map(|(_, code)| code)
}
fn nearest_area(
&self,
lon: f64,
lat: f64,
kind: AreaKind,
allowed: &dyn Fn(&Locale) -> bool,
) -> Option<&str> {
let (cx, cy) = area_cell(lon, lat);
let mut best: Option<(f64, &str)> = None;
for dx in -2..=2 {
for dy in -1..=1 {
let Some(list) = self.areas.get(&(cx + dx, cy + dy)) else {
continue;
};
for area in list.iter().filter(|area| area.kind == kind) {
let d = geolith::conflation::spatial::haversine_distance_m(
lon, lat, area.lon, area.lat,
);
if d <= area.radius_m
&& best.is_none_or(|(bd, _)| d < bd)
&& allowed(&area.locale)
{
best = Some((d, area.name.as_str()));
}
}
}
}
best.map(|(_, name)| name)
}
fn areas_of(
&self,
lon: f64,
lat: f64,
allowed: &dyn Fn(&Locale) -> bool,
) -> (Option<&str>, Option<&str>) {
let fine = self.nearest_area(lon, lat, AreaKind::Fine, allowed);
let suburb = self.nearest_area(lon, lat, AreaKind::Suburb, allowed);
let borough = self.nearest_area(lon, lat, AreaKind::Borough, allowed);
match fine {
Some(fine) => (Some(fine), suburb.or(borough)),
None => (suburb, if suburb.is_some() { None } else { borough }),
}
}
}
fn postcode_cell(lon: f64, lat: f64) -> (i32, i32) {
(
(lon / POSTCODE_CELL_DEG).floor() as i32,
(lat / POSTCODE_CELL_DEG).floor() as i32,
)
}
fn area_cell(lon: f64, lat: f64) -> (i32, i32) {
(
(lon / AREA_CELL_DEG).floor() as i32,
(lat / AREA_CELL_DEG).floor() as i32,
)
}
pub fn fill_locality(record: &mut GeocodingRecord, settlements: &SettlementIndex) {
let above_town = matches!(
record.layer,
GeocodingLayer::County | GeocodingLayer::Region | GeocodingLayer::Country
);
let wanted = Wanted {
country: Locale::country_of(record.admin.country_code.as_deref()),
region: record.admin.region.as_deref(),
regions: &settlements.regions,
};
let same_place = |place: &Locale| wanted.admits(place);
let mut changed = false;
if record.admin.locality.is_none()
&& !above_town
&& let Some(name) = settlements.nearest_where(record.lon, record.lat, &same_place)
{
record.admin.locality = Some(name.to_string());
changed = true;
}
let in_areas = matches!(
record.layer,
GeocodingLayer::Venue | GeocodingLayer::Address | GeocodingLayer::Street
);
if in_areas && record.admin.neighbourhood.is_none() && record.admin.borough.is_none() {
let (neighbourhood, borough) = settlements.areas_of(record.lon, record.lat, &same_place);
if neighbourhood.is_some() || borough.is_some() {
record.admin.neighbourhood = neighbourhood.map(str::to_owned);
record.admin.borough = borough.map(str::to_owned);
changed = true;
}
}
if in_areas && record.admin.city.is_none() {
let admin = &record.admin;
let skip: Vec<&str> = [
&admin.locality,
&admin.county,
&admin.neighbourhood,
&admin.borough,
]
.into_iter()
.flatten()
.map(String::as_str)
.collect();
if let Some(town) = settlements.town_around(record.lon, record.lat, &skip, &same_place) {
record.admin.city = Some(town.to_owned());
changed = true;
}
}
let tagged = record
.address
.as_ref()
.is_some_and(|address| address.postcode.is_some());
if in_areas && !tagged && record.admin.postcode.is_none() {
record.admin.postcode = settlements
.postcode_of(record.lon, record.lat)
.map(str::to_owned);
}
if changed {
record.rebuild_search_text();
}
}
#[must_use]
pub fn is_notable(record: &GeocodingRecord) -> bool {
record.importance > default_importance(POI_RANK)
}
fn settlement_cell(lon: f64, lat: f64) -> (i32, i32) {
(
(lon / SETTLEMENT_CELL_DEG).floor() as i32,
(lat / SETTLEMENT_CELL_DEG).floor() as i32,
)
}
const EARTH_RADIUS_M: f64 = 6_371_000.0;
type Place = GeomWithData<[f64; 2], String>;
#[derive(Default)]
pub struct OvertureIndexBuilder {
venues: Vec<Place>,
addresses: Vec<Place>,
}
impl OvertureIndexBuilder {
pub fn add(&mut self, record: &GeocodingRecord) {
self.add_candidate(record.layer, candidate(record));
}
pub fn add_candidate(&mut self, layer: GeocodingLayer, candidate: SpatialCandidate) {
let places = match layer {
GeocodingLayer::Venue => &mut self.venues,
GeocodingLayer::Address => &mut self.addresses,
_ => return,
};
let (lon, lat) = (candidate.centroid_lon, candidate.centroid_lat);
if let Some(name) = candidate.name
&& on_globe(lon, lat)
{
places.push(GeomWithData::new([lon, lat], name));
}
}
#[must_use]
pub fn build(self) -> OvertureIndex {
fn tree(mut places: Vec<Place>) -> RTree<Place> {
places
.par_iter_mut()
.for_each(|place| place.data = place.data.to_lowercase());
RTree::bulk_load(places)
}
let (venues, addresses) = rayon::join(|| tree(self.venues), || tree(self.addresses));
OvertureIndex {
venues,
addresses,
radius_m: SpatialDedupConfig::default().max_distance_m,
}
}
}
pub struct OvertureIndex {
venues: RTree<Place>,
addresses: RTree<Place>,
radius_m: f64,
}
impl OvertureIndex {
#[must_use]
pub fn is_duplicate(&self, record: &GeocodingRecord) -> bool {
let places = match record.layer {
GeocodingLayer::Venue => &self.venues,
GeocodingLayer::Address => &self.addresses,
_ => return false,
};
if !on_globe(record.lon, record.lat) {
return false;
}
let name = record.name.to_lowercase();
search_areas(record.lon, record.lat, self.radius_m)
.into_iter()
.flatten()
.any(|area| {
places.locate_in_envelope_intersecting(area).any(|place| {
let [lon, lat] = *place.geom();
haversine_distance_m(record.lon, record.lat, lon, lat) <= self.radius_m
&& strsim::jaro_winkler(&name, &place.data) >= DUPLICATE_NAME_SIMILARITY
&& same_words(&name, &place.data)
})
})
}
}
fn same_words(a: &str, b: &str) -> bool {
let words = |text: &str| -> Vec<String> {
let mut words: Vec<String> = text
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty() && *w != "and")
.map(str::to_owned)
.collect();
words.sort_unstable();
words
};
words(a) == words(b)
}
fn on_globe(lon: f64, lat: f64) -> bool {
lon.abs() <= 180.0 && lat.abs() <= 90.0
}
fn search_areas(lon: f64, lat: f64, radius_m: f64) -> [Option<AABB<[f64; 2]>>; 2] {
let angle = radius_m / EARTH_RADIUS_M * (1.0 + 1e-6);
let dlat = angle.to_degrees();
let (south, north) = (lat - dlat, lat + dlat);
let edge = lat.abs() + dlat;
let reach = (angle / 2.0).sin() / edge.to_radians().cos();
if edge >= 90.0 || reach >= 1.0 {
return [
Some(AABB::from_corners([-180.0, south], [180.0, north])),
None,
];
}
let dlon = (2.0 * reach.asin()).to_degrees() * (1.0 + 1e-6);
let (west, east) = (lon - dlon, lon + dlon);
let other_side = if west < -180.0 {
Some(AABB::from_corners([west + 360.0, south], [180.0, north]))
} else if east > 180.0 {
Some(AABB::from_corners([-180.0, south], [east - 360.0, north]))
} else {
None
};
[
Some(AABB::from_corners([west, south], [east, north])),
other_side,
]
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use geolith::admin::AdminHierarchyBuilder;
fn feature(
element_type: OsmElementType,
id: u64,
geometry: geo::Geometry<f64>,
tags: &[(&str, PropValue)],
) -> InputFeature {
InputFeature {
id,
geometry: Arc::new(geometry),
properties: tags
.iter()
.map(|(k, v)| ((*k).to_string(), v.clone()))
.collect(),
bbox: None,
source: DataSource::Osm {
element_type,
relations: Vec::new(),
},
}
}
fn node(id: u64, tags: &[(&str, PropValue)]) -> InputFeature {
feature(
OsmElementType::Node,
id,
geo::Geometry::Point(geo::Point::new(73.85, 18.52)),
tags,
)
}
fn s(v: &str) -> PropValue {
PropValue::Str(v.to_string())
}
fn record(feature: &InputFeature) -> Option<GeocodingRecord> {
osm_record(
feature,
&AdminHierarchyBuilder::new().build().unwrap(),
&Wikipedia::default(),
)
}
fn km_north(km: f64) -> (f64, f64) {
(77.0, 28.0 + km * 1000.0 / 111_194.926)
}
#[test]
fn the_nearest_city_or_town_within_30_km_wins() {
let mut index = SettlementIndex::new();
assert!(index.is_empty());
let (lon, lat) = km_north(12.0);
index.add("town", "Kalady", lon, lat);
let (lon, lat) = km_north(-20.0);
index.add("city", "Kochi", lon, lat);
let (lon, lat) = km_north(35.0);
index.add("town", "Far Town", lon, lat);
let (lon, lat) = km_north(1.0);
index.add("village", "Manjapra", lon, lat);
index.add("city", " ", 77.0, 28.0);
assert_eq!(
index.len(),
3,
"villages and unnamed places are not settlements"
);
assert_eq!(index.nearest(77.0, 28.0), Some("Kalady"));
let (lon, lat) = km_north(-15.0);
assert_eq!(index.nearest(lon, lat), Some("Kochi"));
let (lon, lat) = km_north(50.0);
assert_eq!(index.nearest(lon, lat), Some("Far Town"));
let (lon, lat) = km_north(80.0);
assert_eq!(
index.nearest(lon, lat),
None,
"68 km from Kalady is beyond 30 km"
);
}
fn admin_of(
divisions: &[(geolith::admin::AdminLevel, &str, &str, f64, f64, f64, f64)],
) -> AdminHierarchyIndex {
use geolith::admin::{AdminDivision, AdminHierarchyBuilder};
let mut builder = AdminHierarchyBuilder::new();
for (id, (level, name, country, w, s, e, n)) in divisions.iter().enumerate() {
builder
.add(AdminDivision {
id: id as u64 + 1,
level: *level,
name: (*name).to_owned(),
country_code: Some((*country).to_owned()),
region_code: None,
parts: vec![vec![vec![[*w, *s], [*e, *s], [*e, *n], [*w, *n], [*w, *s]]]],
})
.expect("division");
}
builder.build().expect("index")
}
fn venue_in(admin: &AdminHierarchyIndex, lon: f64, lat: f64) -> GeocodingRecord {
let mut record = venue_lon_lat("Venue", lon, lat, osm());
record.admin = admin.resolve(lon, lat);
record
}
fn resolved(places: &[(&str, &str, f64, f64)], admin: &AdminHierarchyIndex) -> SettlementIndex {
let mut index = SettlementIndex::new();
for (kind, name, lon, lat) in places {
index.add(kind, name, *lon, *lat);
}
index.resolve_admin(admin);
index
}
const LAT_A: f64 = 5.0;
#[test]
fn a_record_never_takes_a_locality_of_another_country() {
use geolith::admin::AdminLevel::Country;
let admin = admin_of(&[
(Country, "A-land", "AA", 0.0, 0.0, 10.0, 10.0),
(Country, "B-land", "BB", 10.0, 0.0, 20.0, 10.0),
]);
let mut hamlet = venue_in(&admin, 9.95, LAT_A);
assert_eq!(hamlet.admin.country_code.as_deref(), Some("AA"));
let only_b = resolved(&[("town", "Btown", 10.05, LAT_A)], &admin);
fill_locality(&mut hamlet, &only_b);
assert_eq!(hamlet.admin.locality, None, "Btown is in another country");
let both = resolved(
&[
("town", "Btown", 10.05, LAT_A),
("town", "Atown", 9.77, LAT_A),
],
&admin,
);
let mut hamlet = venue_in(&admin, 9.95, LAT_A);
fill_locality(&mut hamlet, &both);
assert_eq!(hamlet.admin.locality.as_deref(), Some("Atown"));
let mut across = venue_in(&admin, 10.02, LAT_A);
fill_locality(&mut across, &both);
assert_eq!(across.admin.locality.as_deref(), Some("Btown"));
}
#[test]
fn a_record_never_takes_a_locality_of_another_region() {
use geolith::admin::AdminLevel::{Country, Region};
let admin = admin_of(&[
(Country, "Indialike", "II", 0.0, 0.0, 10.0, 20.0),
(Region, "West Bengalish", "II", 0.0, 0.0, 10.0, 10.0),
(Region, "Sikkimish", "II", 0.0, 10.0, 10.0, 20.0),
]);
let mut venue = venue_in(&admin, 5.0, 9.95);
assert_eq!(venue.admin.region.as_deref(), Some("West Bengalish"));
let only_sikkim = resolved(&[("town", "Rhenockish", 5.0, 10.05)], &admin);
fill_locality(&mut venue, &only_sikkim);
assert_eq!(venue.admin.locality, None, "the town is in another state");
let with_own = resolved(
&[
("town", "Rhenockish", 5.0, 10.05),
("town", "Kalimpongish", 5.0, 9.72),
],
&admin,
);
let mut venue = venue_in(&admin, 5.0, 9.95);
fill_locality(&mut venue, &with_own);
assert_eq!(venue.admin.locality.as_deref(), Some("Kalimpongish"));
}
#[test]
fn the_neighbourhood_and_the_city_follow_the_country_rule_too() {
use geolith::admin::AdminLevel::Country;
let admin = admin_of(&[
(Country, "A-land", "AA", 0.0, 0.0, 10.0, 10.0),
(Country, "B-land", "BB", 10.0, 0.0, 20.0, 10.0),
]);
let places = resolved(
&[
("suburb", "Bsuburb", 10.001, LAT_A),
("city", "Bcity", 10.02, LAT_A),
],
&admin,
);
let mut venue = venue_in(&admin, 9.999, LAT_A);
fill_locality(&mut venue, &places);
assert_eq!(venue.admin.neighbourhood, None);
assert_eq!(venue.admin.borough, None);
assert_eq!(venue.admin.city, None);
}
#[test]
fn a_place_no_country_holds_is_still_taken() {
use geolith::admin::AdminLevel::Country;
let admin = admin_of(&[
(Country, "A-land", "AA", 0.0, 0.0, 10.0, 10.0),
(Country, "B-land", "BB", 10.0, 0.0, 20.0, 10.0),
]);
let index = resolved(
&[
("city", "Seaport", 5.0, 10.05),
("town", "Btown", 10.05, 9.9),
],
&admin,
);
let mut venue = venue_in(&admin, 5.0, 9.95);
assert_eq!(venue.admin.country_code.as_deref(), Some("AA"));
fill_locality(&mut venue, &index);
assert_eq!(venue.admin.locality.as_deref(), Some("Seaport"));
let mut resolver = SettlementIndex::new();
resolver.add("city", "Seaport", 5.0, 10.05);
resolver.add("town", "Atown", 5.0, 5.0);
let counts = resolver.resolve_admin(&admin);
assert_eq!(
counts,
ResolvedPlaces {
places: 2,
without_country: 1,
without_region: 2
}
);
}
#[test]
fn a_record_without_a_region_or_without_admin_data_still_gets_a_locality() {
use geolith::admin::AdminLevel::{Country, Region};
let admin = admin_of(&[(Country, "A-land", "AA", 0.0, 0.0, 10.0, 10.0)]);
let index = resolved(&[("town", "Atown", 5.05, LAT_A)], &admin);
let mut venue = venue_in(&admin, 5.0, LAT_A);
assert_eq!(venue.admin.region, None);
fill_locality(&mut venue, &index);
assert_eq!(venue.admin.locality.as_deref(), Some("Atown"));
let admin = admin_of(&[
(Country, "A-land", "AA", 0.0, 0.0, 10.0, 10.0),
(Region, "Eastern", "AA", 5.0, 0.0, 10.0, 10.0),
]);
let index = resolved(&[("town", "Wtown", 4.95, LAT_A)], &admin);
let mut venue = venue_in(&admin, 5.02, LAT_A);
assert_eq!(venue.admin.region.as_deref(), Some("Eastern"));
fill_locality(&mut venue, &index);
assert_eq!(venue.admin.locality.as_deref(), Some("Wtown"));
let mut bare = SettlementIndex::new();
bare.add("town", "Atown", 5.05, LAT_A);
let mut venue = venue_lon_lat("Venue", 5.0, LAT_A, osm());
fill_locality(&mut venue, &bare);
assert_eq!(venue.admin.locality.as_deref(), Some("Atown"));
}
#[test]
fn a_hamlet_on_soi_land_never_takes_a_town_across_the_line() {
use geolith::admin::AdminLevel::Country;
use geolith::admin::india::{IndiaOutline, IndiaView};
use geolith::admin::{AdminDivision, AdminHierarchyBuilder};
let ring = geo::LineString::from(vec![
(91.0, 26.0),
(97.5, 26.0),
(97.5, 29.5),
(91.0, 29.5),
(91.0, 26.0),
]);
let outline =
geolith::admin::india::IndiaOutline::new(geo::MultiPolygon(vec![geo::Polygon::new(
ring,
vec![],
)]))
.expect("outline");
let _: Option<IndiaOutline> = None;
let mut builder = AdminHierarchyBuilder::new();
IndiaView::new(&outline)
.finish_into(&mut builder)
.expect("india");
builder
.add(AdminDivision {
id: 900,
level: Country,
name: "Myanmar".into(),
country_code: Some("MM".into()),
region_code: None,
parts: vec![vec![vec![
[97.5, 20.0],
[100.0, 20.0],
[100.0, 29.5],
[97.5, 29.5],
[97.5, 20.0],
]]],
})
.expect("myanmar");
let admin = builder.build().expect("index");
let index = resolved(
&[
("town", "Indian Town", 97.3, 27.5),
("town", "Burmese Town", 97.6, 27.5),
],
&admin,
);
let mut hamlet = venue_in(&admin, 97.45, 27.5);
assert_eq!(hamlet.admin.country_code.as_deref(), Some("IN"));
fill_locality(&mut hamlet, &index);
assert_eq!(hamlet.admin.locality.as_deref(), Some("Indian Town"));
let mut across = venue_in(&admin, 97.55, 27.5);
assert_eq!(across.admin.country_code.as_deref(), Some("MM"));
fill_locality(&mut across, &index);
assert_eq!(across.admin.locality.as_deref(), Some("Burmese Town"));
}
#[test]
fn a_settlement_in_a_neighbouring_grid_cell_is_found() {
let mut index = SettlementIndex::new();
index.add("town", "Across", 77.0, 28.01);
assert_eq!(index.nearest(77.0, 27.99), Some("Across"));
}
#[test]
fn a_city_node_near_a_venue_becomes_its_city() {
let mut index = SettlementIndex::new();
index.add("city", "Thane", 72.97, 19.20);
index.add("town", "Kalwa", 73.00, 19.20);
let mut r = venue_at("Holy Trinity Hospital", 19.17, osm());
r.lon = 72.951;
r.admin.locality = Some("T Ward".into());
fill_locality(&mut r, &index);
assert_eq!(r.admin.city.as_deref(), Some("Thane"));
let mark = glx::tokenize::LANGUAGE_MARK;
assert_eq!(
r.search_text,
format!("Holy Trinity Hospital T Ward{mark}Thane")
);
let mut far = venue_at("Far Clinic", 19.05, osm());
far.lon = 72.951;
far.admin.locality = Some("T Ward".into());
fill_locality(&mut far, &index);
assert_eq!(far.admin.city, None);
let mut near_town = venue_at("Kalwa Clinic", 19.20, osm());
near_town.lon = 73.028;
near_town.admin.locality = Some("Kalwa".into());
fill_locality(&mut near_town, &index);
assert_eq!(near_town.admin.city.as_deref(), Some("Thane"));
}
#[test]
fn fill_locality_adds_the_settlement_to_the_search_text() {
let mut index = SettlementIndex::new();
index.add("town", "Cherupuzha", 77.0, 28.0);
let mut r = venue_at("Nadan Thattukada", 28.0, osm());
fill_locality(&mut r, &index);
assert_eq!(r.admin.locality.as_deref(), Some("Cherupuzha"));
assert_eq!(r.search_text, "Nadan Thattukada Cherupuzha");
}
#[test]
fn fill_locality_leaves_places_above_a_town() {
let mut index = SettlementIndex::new();
index.add("town", "Tungjoy", 94.15, 25.39);
for layer in [
GeocodingLayer::County,
GeocodingLayer::Region,
GeocodingLayer::Country,
] {
let mut r = venue_at("Senapati", 25.39, osm());
r.lon = 94.15;
r.layer = layer;
r.rebuild_search_text();
fill_locality(&mut r, &index);
assert_eq!(r.admin.locality, None, "{layer:?}");
assert_eq!(r.search_text, "Senapati", "{layer:?}");
}
}
fn km_east(km: f64) -> (f64, f64) {
(73.0 + km * 1000.0 / 105_137.6, 19.0)
}
fn venue_near_seawoods() -> GeocodingRecord {
let mut r = venue_at("Sterling Institute", 19.0, osm());
r.lon = 73.0;
r.admin.locality = Some("Navi Mumbai".into());
r.rebuild_search_text();
r
}
#[test]
fn a_venue_takes_the_suburb_whose_area_it_lies_in() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(1.5);
index.add("suburb", "Seawoods East", lon, lat);
let (lon, lat) = km_east(2.5);
index.add("suburb", "Too Far", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.neighbourhood.as_deref(), Some("Seawoods East"));
assert_eq!(r.admin.borough, None);
assert_eq!(
r.search_text,
"Sterling Institute Navi Mumbai\u{1F}Seawoods East"
);
let mut far = SettlementIndex::new();
let (lon, lat) = km_east(2.5);
far.add("suburb", "Too Far", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &far);
assert_eq!(r.admin.neighbourhood, None);
}
#[test]
fn a_neighbourhood_reaches_500_m_and_a_quarter_1_km() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(0.7);
index.add("neighbourhood", "Sector 40", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.neighbourhood, None, "0.7 km is outside 500 m");
let (lon, lat) = km_east(0.9);
index.add("quarter", "Old Quarter", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.neighbourhood.as_deref(), Some("Old Quarter"));
}
#[test]
fn a_neighbourhood_inside_a_suburb_keeps_both() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(0.3);
index.add("neighbourhood", "Sector 19", lon, lat);
let (lon, lat) = km_east(1.0);
index.add("suburb", "Nerul East", lon, lat);
let (lon, lat) = km_east(3.5);
index.add("borough", "Far Borough", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.neighbourhood.as_deref(), Some("Sector 19"));
assert_eq!(r.admin.borough.as_deref(), Some("Nerul East"));
assert_eq!(
r.search_text,
"Sterling Institute Navi Mumbai\u{1F}Sector 19 Nerul East"
);
}
#[test]
fn a_borough_reaches_4_km() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(3.5);
index.add("city_district", "Nerul", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.borough.as_deref(), Some("Nerul"));
}
#[test]
fn towns_take_no_neighbourhood_and_a_polygon_one_is_kept() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(0.2);
index.add("suburb", "Seawoods East", lon, lat);
let mut town = venue_near_seawoods();
town.layer = GeocodingLayer::Locality;
fill_locality(&mut town, &index);
assert_eq!(town.admin.neighbourhood, None);
let mut r = venue_near_seawoods();
r.admin.neighbourhood = Some("Polygon Hood".into());
fill_locality(&mut r, &index);
assert_eq!(r.admin.neighbourhood.as_deref(), Some("Polygon Hood"));
}
#[test]
fn a_venue_takes_the_postcode_with_the_nearest_centroid() {
let mut index = SettlementIndex::new();
for km in [1.0, 3.0] {
let (lon, lat) = km_east(km);
index.add_postcode("400 706", lon, lat);
}
let (lon, lat) = km_east(-4.0);
index.add_postcode("400614", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &index);
assert_eq!(r.admin.postcode.as_deref(), Some("400706"));
assert!(!r.search_text.contains("400706"));
let mut far = SettlementIndex::new();
let (lon, lat) = km_east(6.0);
far.add_postcode("400706", lon, lat);
let mut r = venue_near_seawoods();
fill_locality(&mut r, &far);
assert_eq!(r.admin.postcode, None);
}
#[test]
fn a_tagged_postcode_is_kept_and_towns_take_none() {
let mut index = SettlementIndex::new();
let (lon, lat) = km_east(1.0);
index.add_postcode("400706", lon, lat);
let mut r = venue_near_seawoods();
r.address = Some(AddressFields {
postcode: Some("400614".into()),
..Default::default()
});
fill_locality(&mut r, &index);
assert_eq!(r.admin.postcode, None);
let mut town = venue_near_seawoods();
town.layer = GeocodingLayer::Locality;
fill_locality(&mut town, &index);
assert_eq!(town.admin.postcode, None);
}
#[test]
fn fill_locality_keeps_an_existing_locality() {
let mut index = SettlementIndex::new();
index.add("town", "Elsewhere", 77.0, 28.0);
let mut r = venue_at("Cafe", 28.0, osm());
r.admin.locality = Some("Pune".into());
r.search_text = "Cafe Pune".into();
fill_locality(&mut r, &index);
assert_eq!(r.admin.locality.as_deref(), Some("Pune"));
assert_eq!(r.admin.city.as_deref(), Some("Elsewhere"));
assert_eq!(
r.search_text,
format!("Cafe Pune{}Elsewhere", glx::tokenize::LANGUAGE_MARK)
);
}
#[test]
fn addr_city_becomes_the_locality_of_an_osm_record() {
let r = record(&node(
3,
&[
("shop", s("bakery")),
("name", s("Kalyan Bakery")),
("addr:city", s("Hubballi")),
],
))
.expect("named shop");
assert_eq!(r.admin.locality.as_deref(), Some("Hubballi"));
assert_eq!(r.search_text, "Kalyan Bakery Hubballi bakery");
}
#[test]
fn a_town_takes_no_locality_of_its_own() {
let r = record(&node(
4,
&[
("place", s("city")),
("name", s("Mumbai")),
("addr:city", s("L Ward")),
],
))
.expect("named city");
assert_eq!(r.layer, GeocodingLayer::Locality);
assert_eq!(r.admin.locality, None);
assert_eq!(r.search_text, "Mumbai");
}
#[test]
fn only_tags_that_may_make_a_record_pass_the_check() {
let cases: [&[(&str, &str)]; 10] = [
&[("building", "yes")],
&[("highway", "residential"), ("name", "MG Road")],
&[("name", "Kalyan Bakery"), ("shop", "bakery")],
&[("name", "Pune"), ("place", "city")],
&[("addr:housenumber", "7")],
&[("addr:street", "MG Road"), ("building", "yes")],
&[("name", "Platform 2"), ("railway", "platform")],
&[("name", "Somewhere"), ("tourism", "yes")],
&[("shop", "bakery")],
&[("name", "Lake"), ("natural", "water")],
];
let expected = [
false, false, true, true, true, true, true, true, false, false,
];
for (tags, want) in cases.iter().zip(expected) {
let props: Vec<(&str, PropValue)> = tags.iter().map(|&(k, v)| (k, s(v))).collect();
let kept = record(&node(1, &props)).is_some();
let passes = may_be_record(tags.iter().copied());
assert_eq!(passes, want, "{tags:?}");
assert!(passes || !kept, "the check drops a kept record: {tags:?}");
}
}
#[test]
fn node_and_way_ids_stay_distinct_and_decode() {
let n = record_id(OsmElementType::Node, 42);
let w = record_id(OsmElementType::Way, 42);
let r = record_id(OsmElementType::Relation, 42);
assert_eq!(n, 42);
assert_eq!(w, (1 << 62) + 42);
assert_eq!(r, (2 << 62) + 42);
assert_eq!([element_id(n), element_id(w), element_id(r)], [42, 42, 42]);
}
#[test]
fn place_ranks_follow_nominatim() {
use GeocodingLayer::{Country, County, Locality, Region};
for (place, layer, rank) in [
("country", Country, 4),
("state", Region, 8),
("province", Region, 8),
("region", Region, 18),
("county", County, 12),
("district", County, 12),
("city", Locality, 16),
("town", Locality, 18),
("village", Locality, 19),
("suburb", Locality, 19),
("hamlet", Locality, 20),
("quarter", Locality, 20),
("neighbourhood", Locality, 24),
] {
assert_eq!(place_layer(place), Some((layer, rank)), "{place}");
}
assert_eq!(place_layer("island"), None);
}
#[test]
fn a_named_city_node_becomes_a_locality() {
let r = record(&node(
7,
&[
("place", s("city")),
("name", s("Pune")),
("name:mr", s("पुणे")),
],
))
.expect("named city");
assert_eq!(r.layer, GeocodingLayer::Locality);
assert_eq!(r.name, "Pune");
assert!((r.importance - 0.186_677).abs() < 1e-6, "{}", r.importance);
assert_eq!(r.names.get("mr").map(String::as_str), Some("पुणे"));
assert_eq!(r.source_id.as_deref(), Some("node/7"));
assert_eq!((r.lon, r.lat), (73.85, 18.52));
}
#[test]
fn a_named_cafe_becomes_a_venue_with_its_address() {
let r = record(&node(
11,
&[
("amenity", s("cafe")),
("name", s("Vohuman Cafe")),
("addr:housenumber", PropValue::I64(12)),
("addr:street", s("Dhole Patil Road")),
("addr:postcode", PropValue::I64(411001)),
],
))
.expect("named cafe");
assert_eq!(r.layer, GeocodingLayer::Venue);
assert_eq!(r.name, "Vohuman Cafe");
assert_eq!(r.categories, vec!["cafe".to_string()]);
assert!((r.importance - 0.000_01).abs() < 1e-6, "{}", r.importance);
let address = r.address.expect("address fields kept");
assert_eq!(address.number.as_deref(), Some("12"));
assert_eq!(address.street.as_deref(), Some("Dhole Patil Road"));
assert_eq!(address.postcode.as_deref(), Some("411001"));
assert!(
r.search_text.contains("Dhole Patil Road"),
"{}",
r.search_text
);
}
#[test]
fn a_venue_with_a_number_and_a_street_has_an_address_twin() {
let venue = record(&node(
11,
&[
("amenity", s("cafe")),
("name", s("Vohuman Cafe")),
("name:mr", s("वोहुमन कॅफे")),
("addr:housenumber", PropValue::I64(12)),
("addr:street", s("Dhole Patil Road")),
("addr:postcode", PropValue::I64(411001)),
],
))
.expect("named cafe");
let twin = address_twin(&venue).expect("twin of a venue with number and street");
assert_eq!(twin.layer, GeocodingLayer::Address);
assert_eq!(twin.name, "12 Dhole Patil Road");
assert_eq!(twin.id, 2_305_843_009_213_693_963);
assert_ne!(twin.id, venue.id);
assert_eq!(element_id(twin.id), 11);
assert_eq!(twin.source_id.as_deref(), Some("node/11/address"));
assert_eq!((twin.lon, twin.lat), (73.85, 18.52));
assert!(
(twin.importance - 0.000_01).abs() < 1e-6,
"{}",
twin.importance
);
let address = twin.address.as_ref().expect("address fields");
assert_eq!(address.number.as_deref(), Some("12"));
assert_eq!(address.street.as_deref(), Some("Dhole Patil Road"));
assert_eq!(address.postcode.as_deref(), Some("411001"));
assert!(twin.names.is_empty());
assert!(twin.categories.is_empty());
assert!(twin.shape.is_empty());
assert!(
twin.search_text.contains("12 Dhole Patil Road"),
"{}",
twin.search_text
);
assert!(
!twin.search_text.contains("Vohuman"),
"{}",
twin.search_text
);
assert_eq!(venue.layer, GeocodingLayer::Venue);
assert_eq!(venue.name, "Vohuman Cafe");
assert_eq!(venue.id, 11);
}
#[test]
fn only_a_venue_with_both_a_number_and_a_street_has_a_twin() {
let twin_of = |tags: &[(&str, PropValue)]| address_twin(&record(&node(5, tags)).unwrap());
assert!(
twin_of(&[
("amenity", s("cafe")),
("name", s("A")),
("addr:housenumber", PropValue::I64(12)),
])
.is_none()
);
assert!(
twin_of(&[
("amenity", s("cafe")),
("name", s("A")),
("addr:street", s("Dhole Patil Road")),
])
.is_none()
);
assert!(twin_of(&[("amenity", s("cafe")), ("name", s("A"))]).is_none());
assert!(
twin_of(&[
("place", s("city")),
("name", s("Pune")),
("addr:housenumber", PropValue::I64(1)),
("addr:street", s("Main Road")),
])
.is_none()
);
assert!(
twin_of(&[
("addr:housenumber", PropValue::I64(12)),
("addr:street", s("Dhole Patil Road")),
])
.is_none()
);
let place = twin_of(&[
("amenity", s("cafe")),
("name", s("A")),
("addr:housenumber", PropValue::I64(7)),
("addr:place", s("Camp Area")),
])
.expect("number and addr:place");
assert_eq!(place.name, "7 Camp Area");
}
const NAMESAKE_ROWS: &str = "sv\ta\tDesa_Tawang_(administrativ_by_i_Indonesien,_Jawa_Timur)\t0.21822785325192331\tQ12520130\n\
nl\ta\tTawang_(Wates)\t0.21822785325192331\tQ12520130\n\
id\ta\tTawang,_Wates,_Kediri\t0.21822785325192331\tQ12520130\n\
ro\ta\tAnini,_Buz\u{103}u\t0.4181697918103512\tQ12078787\n\
uk\ta\t\u{410}\u{43d}\u{456}\u{43d}\u{44c}_(\u{420}\u{443}\u{43c}\u{443}\u{43d}\u{456}\u{44f})\t0.4181697918103512\tQ12078787\n\
pl\ta\tAnini_(Rumunia)\t0.4181697918103512\tQ12078787\n\
ro\ta\tAnini,_H\u{ee}nce\u{15f}ti\t0.35263345776344923\tQ4066172\n\
uk\ta\t\u{410}\u{43d}\u{456}\u{43d}\u{44c}_(\u{41c}\u{43e}\u{43b}\u{434}\u{43e}\u{432}\u{430})\t0.35263345776344923\tQ4066172\n";
fn namesakes() -> Wikipedia {
Wikipedia::read(NAMESAKE_ROWS.as_bytes()).expect("rows")
}
fn settlement(id: u64, tags: &[(&str, &str)]) -> InputFeature {
let tags: Vec<(&str, PropValue)> = tags.iter().map(|(k, v)| (*k, s(v))).collect();
node(id, &tags)
}
fn overture_division(
osm_node: u64,
class: &str,
signals: &[(&str, PropValue)],
) -> InputFeature {
let mut properties: HashMap<String, PropValue> = signals
.iter()
.map(|(k, v)| ((*k).to_string(), v.clone()))
.collect();
properties.insert("subtype".into(), s("locality"));
properties.insert("class".into(), s(class));
properties.insert("sources.dataset".into(), s("OpenStreetMap"));
properties.insert("sources.record_id".into(), s(&format!("n{osm_node}@1")));
InputFeature {
id: osm_node,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(95.9, 28.8))),
properties,
bbox: None,
source: DataSource::Overture {
theme: "divisions".into(),
otype: "division".into(),
},
}
}
fn importance_of(feature: &InputFeature, places: &PlaceSignalIndex) -> f32 {
osm_record_with(
feature,
&AdminHierarchyBuilder::new().build().unwrap(),
&namesakes(),
places,
)
.expect("record")
.importance
}
#[test]
fn a_town_of_eleven_thousand_outranks_a_village_with_a_small_row() {
let tawang = settlement(
342_097_760,
&[
("place", "town"),
("name", "Tawang"),
("name:en", "Tawang"),
("population", "11000"),
],
);
let village = settlement(
1_308_726_649,
&[
("place", "village"),
("name", "Tawang"),
("wikidata", "Q12520130"),
],
);
let none = PlaceSignalIndex::default();
let (town, desa) = (
importance_of(&tawang, &none),
importance_of(&village, &none),
);
assert!(
(desa - 0.146_68).abs() < 1e-4,
"a village with an unknown population and only a small-language row: {desa}"
);
assert!((town - 0.264_15).abs() < 1e-4, "{town}");
assert!(town > desa);
}
#[test]
fn a_district_seat_outranks_villages_with_rows_from_small_wikis() {
let anini = settlement(
4_967_349_524,
&[
("place", "town"),
("name", "Anini"),
("wikidata", "Q2573018"),
],
);
let romanian = settlement(
447_932_093,
&[
("place", "village"),
("name", "Anini"),
("population", "99"),
("wikidata", "Q12078787"),
],
);
let moldovan = settlement(
277_635_103,
&[
("place", "village"),
("name", "Anini"),
("wikidata", "Q4066172"),
],
);
let mut places = PlaceSignalIndex::default();
places.add(&overture_division(
4_967_349_524,
"town",
&[
("cartography.prominence", PropValue::I64(22)),
("capital_of_divisions", s("county")),
],
));
let (seat, ro, md) = (
importance_of(&anini, &places),
importance_of(&romanian, &places),
importance_of(&moldovan, &places),
);
assert!((seat - 0.264_01).abs() < 1e-4, "a county seat: {seat}");
assert!(
(ro - 0.146_68).abs() < 1e-4,
"a village of 99 whose only article is Romanian takes its class: {ro}"
);
assert!(
(md - 0.146_68).abs() < 1e-4,
"no population and no lift: the row goes: {md}"
);
assert!(seat > ro && seat > md);
let alone = importance_of(&anini, &PlaceSignalIndex::default());
assert!((alone - 0.160_01).abs() < 1e-4, "{alone}");
}
#[test]
fn a_county_seat_does_not_outrank_a_town_of_thirty_thousand() {
let seat = settlement(
1_001,
&[("place", "town"), ("name", "Karanganyar"), ("capital", "5")],
);
let town = settlement(
1_002,
&[
("place", "town"),
("name", "Karanganyar"),
("population", "30479"),
],
);
let none = PlaceSignalIndex::default();
let (seat, town) = (importance_of(&seat, &none), importance_of(&town, &none));
assert!((town - 0.308_40).abs() < 1e-4, "{town}");
assert!((seat - 0.260_01).abs() < 1e-4, "{seat}");
assert!(
town > seat,
"the town of 30k, not the seat: {town} / {seat}"
);
}
#[test]
fn a_district_seat_outranks_a_village_row_with_no_english_article() {
let anini = settlement(
4_967_349_524,
&[("place", "town"), ("name", "Anini"), ("capital", "5")],
);
let moldovan = settlement(
277_635_103,
&[
("place", "village"),
("name", "Anini"),
("wikidata", "Q4066172"),
],
);
let mut places = PlaceSignalIndex::default();
places.add(&overture_division(
4_967_349_524,
"town",
&[("cartography.prominence", PropValue::I64(22))],
));
let (seat, md) = (
importance_of(&anini, &places),
importance_of(&moldovan, &places),
);
assert!((md - 0.146_68).abs() < 1e-4, "the row is dropped: {md}");
assert!(seat > md, "{seat} / {md}");
}
#[test]
fn a_wikidata_item_sets_the_importance() {
let wikipedia = Wikipedia::read(
"en\ta\tLondon\t0.892\tQ84\nen\ta\tEiffel_Tower\t0.621\tQ243\n".as_bytes(),
)
.expect("rows");
let with = |tags: &[(&str, PropValue)]| {
osm_record(
&node(9, tags),
&AdminHierarchyBuilder::new().build().unwrap(),
&wikipedia,
)
.expect("record")
};
let city = with(&[
("place", s("city")),
("name", s("London")),
("wikidata", s("Q84")),
]);
assert!(
(city.importance - 0.892).abs() < 1e-6,
"{}",
city.importance
);
let tower = with(&[
("tourism", s("attraction")),
("name", s("Tour Eiffel")),
("name:en", s("Eiffel Tower")),
("wikidata", s("Q243")),
]);
assert!(
(tower.importance - 0.621).abs() < 1e-6,
"{}",
tower.importance
);
assert_eq!(tower.search_text, "Tour Eiffel Eiffel Tower attraction");
assert!(is_notable(&tower));
let other = with(&[
("place", s("city")),
("name", s("London")),
("wikidata", s("Q999")),
]);
assert!(
(other.importance - 0.186_677).abs() < 1e-6,
"{}",
other.importance
);
}
const ARTICLES: &str = "en\ta\tBig_Ben\t0.52774415962364\tQ41225\n\
en\tr\tElizabeth_Tower\t0.52774415962364\tQ41225\n\
de\ta\tBrandenburger_Tor\t0.5504719991549523\tQ82425\n\
en\ta\tBrandenburg_Gate\t0.5504719991549523\tQ82425\n\
en\ta\t24th_Street_(PTC_station)\t0.12743869505990896\tQ4632026\n";
#[test]
fn a_wikipedia_article_title_is_searched_as_another_name() {
let wikipedia = Wikipedia::read(ARTICLES.as_bytes()).expect("rows");
let with = |id, tags: &[(&str, PropValue)]| {
osm_record(
&node(id, tags),
&AdminHierarchyBuilder::new().build().unwrap(),
&wikipedia,
)
.expect("record")
};
let tower = with(
20,
&[
("tourism", s("attraction")),
("name", s("Elizabeth Tower")),
("wikipedia", s("en:Big Ben")),
("wikidata", s("Q41225")),
],
);
assert_eq!(tower.name, "Elizabeth Tower");
assert_eq!(tower.article_names, ["Big Ben"]);
assert!(tower.other_names.is_empty());
assert_eq!(tower.name_text(), "Elizabeth Tower attraction Big Ben");
let mark = glx::tokenize::LANGUAGE_MARK;
assert_eq!(
tower.search_text,
format!("Elizabeth Tower attraction{mark}Big Ben")
);
let gate = with(
21,
&[
("tourism", s("attraction")),
("name", s("Brandenburger Tor")),
("wikipedia", s("de:Brandenburger_Tor")),
("wikidata", s("Q82425")),
],
);
assert_eq!(gate.article_names, ["Brandenburg Gate"]);
let named = with(
22,
&[
("tourism", s("attraction")),
("name", s("Brandenburger Tor")),
("name:en", s("Brandenburg Gate")),
("wikidata", s("Q82425")),
],
);
assert!(named.article_names.is_empty(), "{:?}", named.article_names);
let french = with(
25,
&[
("tourism", s("attraction")),
("name", s("Brandenburger Tor")),
("name:fr", s("Porte de Brandebourg")),
("wikipedia", s("fr:Porte de Brandebourg")),
],
);
assert!(
french.article_names.is_empty(),
"{:?}",
french.article_names
);
let tagged = with(
26,
&[
("tourism", s("attraction")),
("name", s("Elizabeth Tower")),
("wikipedia", s("en:Big Ben")),
],
);
assert_eq!(tagged.article_names, ["Big Ben"]);
let station = with(
23,
&[
("railway", s("station")),
("name", s("24th Street")),
("wikipedia", s("en:24th Street (PTC station)#History")),
("wikidata", s("Q4632026")),
],
);
assert!(
station.article_names.is_empty(),
"{:?}",
station.article_names
);
let village = with(
27,
&[
("place", s("town")),
("name", s("Sarwan")),
("alt_name", s("Sarawān")),
("wikipedia", s("en:Sarwan, Deoghar (village)")),
],
);
assert_eq!(village.other_names, ["Sarawān"]);
assert!(
village.article_names.is_empty(),
"{:?}",
village.article_names
);
let temple = with(
28,
&[
("amenity", s("place_of_worship")),
("name", s("Aranganathar Temple")),
("name:ta", s("அரங்கநாதர் திருக்கோவில்")),
("wikipedia", s("en:Ranganathaswamy temple, Karamadai")),
],
);
assert!(
temple.article_names.is_empty(),
"{:?}",
temple.article_names
);
let sakuragicho = with(
29,
&[
("railway", s("station")),
("name", s("桜木町")),
("name:en", s("Sakuragicho")),
("wikipedia", s("ja:桜木町駅")),
],
);
assert!(
sakuragicho.article_names.is_empty(),
"{:?}",
sakuragicho.article_names
);
let keep = with(
30,
&[
("tourism", s("attraction")),
("name", s("大阪城天守閣")),
("wikipedia", s("ja:大阪城")),
],
);
assert!(keep.article_names.is_empty(), "{:?}", keep.article_names);
let address = with(
24,
&[
("addr:housenumber", s("1")),
("addr:street", s("Bridge Street")),
("wikipedia", s("en:Big Ben")),
],
);
assert!(address.article_names.is_empty());
}
#[test]
fn other_names_are_searched_as_names_once_each() {
let city = record(&node(
12,
&[
("place", s("city")),
("name", s("Bengaluru")),
("name:en", s("Bengaluru")),
("old_name", s("Bangalore")),
("alt_name", s("Bangalore;Bengaluru;Bendakaluru")),
],
))
.expect("city");
assert_eq!(city.other_names, vec!["Bangalore", "Bendakaluru"]);
assert_eq!(city.search_text, "Bengaluru Bangalore Bendakaluru");
assert_eq!(city.name_text(), "Bengaluru Bangalore Bendakaluru");
let temple = record(&node(
13,
&[
("amenity", s("place_of_worship")),
("name", s("Shri Harmandir Sahib")),
("alt_name", s("Golden Temple")),
("int_name", s("golden temple")),
],
))
.expect("temple");
assert_eq!(
temple.name_text(),
"Shri Harmandir Sahib Golden Temple place of worship"
);
}
#[test]
fn addr_place_stands_in_for_a_missing_street() {
let address = record(&node(
15,
&[
("addr:housenumber", s("45")),
("addr:place", s("Panchsheel Enclave")),
],
))
.expect("address");
assert_eq!(address.name, "45 Panchsheel Enclave");
let fields = address.address.as_ref().expect("fields");
assert_eq!(fields.street.as_deref(), Some("Panchsheel Enclave"));
assert!(address.search_text.contains("Panchsheel Enclave"));
let both = record(&node(
16,
&[
("addr:housenumber", s("3")),
("addr:street", s("MG Road")),
("addr:place", s("Camp")),
],
))
.expect("address");
assert_eq!(both.name, "3 MG Road");
}
#[test]
fn an_address_takes_no_other_names() {
let address = record(&node(
14,
&[
("addr:housenumber", s("7")),
("addr:street", s("MG Road")),
("old_name", s("Old House")),
],
))
.expect("address");
assert!(address.other_names.is_empty());
assert!(!address.search_text.contains("Old House"));
}
#[test]
fn only_a_venue_with_an_article_is_notable() {
let cafe = record(&node(
11,
&[("amenity", s("cafe")), ("name", s("Vohuman Cafe"))],
))
.expect("named cafe");
assert!(!is_notable(&cafe));
let mut famous = cafe.clone();
famous.importance = 0.4;
assert!(is_notable(&famous));
}
#[test]
fn fill_locality_keeps_the_english_name() {
let mut index = SettlementIndex::new();
index.add("city", "Paris", 77.0, 28.0);
let mut r = venue_at("Tour Eiffel", 28.0, osm());
r.names.insert("en".into(), "Eiffel Tower".into());
fill_locality(&mut r, &index);
assert_eq!(r.search_text, "Tour Eiffel Eiffel Tower Paris");
}
#[test]
fn a_house_number_way_becomes_an_address_at_its_centroid() {
let square = geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(2.0, 0.0),
(2.0, 2.0),
(0.0, 2.0),
(0.0, 0.0),
]),
vec![],
);
let r = record(&feature(
OsmElementType::Way,
5,
geo::Geometry::Polygon(square),
&[
("building", s("yes")),
("addr:housenumber", s("4B")),
("addr:street", s("MG Road")),
],
))
.expect("address way");
assert_eq!(r.layer, GeocodingLayer::Address);
assert_eq!(r.name, "4B MG Road");
assert!((r.importance - 0.000_01).abs() < 1e-6, "{}", r.importance);
assert_eq!((r.lon, r.lat), (1.0, 1.0));
assert_eq!(r.id, (1 << 62) + 5);
assert_eq!(r.source_id.as_deref(), Some("way/5"));
}
#[test]
fn unnamed_or_untagged_features_are_skipped() {
assert!(record(&node(1, &[("amenity", s("bench"))])).is_none());
assert!(record(&node(2, &[("name", s("Just A Name"))])).is_none());
assert!(record(&node(3, &[("tourism", s("yes")), ("name", s("Somewhere"))])).is_none());
assert!(
record(&node(
4,
&[("place", s("island")), ("name", s("Elephanta"))]
))
.is_none()
);
}
fn venue_at(name: &str, lat: f64, source: DataSource) -> GeocodingRecord {
GeocodingRecord::new(RecordInit {
id: 1,
source,
layer: GeocodingLayer::Venue,
name: name.to_string(),
lon: 77.0,
lat,
admin: Default::default(),
address: None,
names: HashMap::new(),
importance: 0.5,
})
}
fn overture() -> DataSource {
DataSource::Overture {
theme: "places".into(),
otype: "place".into(),
}
}
fn osm() -> DataSource {
DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
}
}
#[test]
fn an_osm_venue_near_a_same_name_overture_venue_is_a_duplicate() {
let index = index_of(&[venue_at("Cafe Coffee Day", 28.0, overture())]);
assert!(index.is_duplicate(&venue_at(
"cafe coffee day",
28.0 + 20.0 / 111_194.926,
osm()
)));
assert!(!index.is_duplicate(&venue_at("Haldiram", 28.0 + 20.0 / 111_194.926, osm())));
assert!(!index.is_duplicate(&venue_at(
"Cafe Coffee Day",
28.0 + 200.0 / 111_194.926,
osm()
)));
}
#[test]
fn a_respelled_osm_venue_is_kept() {
let index = index_of(&[
venue_at("Vignesh Hospital", 28.0, overture()),
venue_at("Kiran Care and Cure Hospital", 29.0, overture()),
]);
let near = |name: &str, lat: f64| venue_at(name, lat + 31.0 / 111_194.926, osm());
assert!(!index.is_duplicate(&near("Viganesh Hospital", 28.0)));
assert!(index.is_duplicate(&near("Kiran Care & Cure Hospital", 29.0)));
assert!(same_words("a & b", "a and b"));
assert!(!same_words("viganesh hospital", "vignesh hospital"));
}
#[test]
fn a_locality_is_never_a_duplicate_of_a_venue() {
let index = index_of(&[venue_at("Pune", 28.0, overture())]);
let mut city = venue_at("Pune", 28.0, osm());
city.layer = GeocodingLayer::Locality;
assert!(!index.is_duplicate(&city));
}
#[test]
fn tag_reads_every_property_kind() {
let f = node(
1,
&[
("u", PropValue::U64(7)),
("f", PropValue::F64(1.5)),
("b", PropValue::Bool(true)),
("s", s(" padded ")),
("blank", s(" ")),
],
);
assert_eq!(tag(&f, "u").as_deref(), Some("7"));
assert_eq!(tag(&f, "f").as_deref(), Some("1.5"));
assert_eq!(tag(&f, "b").as_deref(), Some("true"));
assert_eq!(tag(&f, "s").as_deref(), Some("padded"));
assert_eq!(tag(&f, "blank"), None);
assert_eq!(tag(&f, "missing"), None);
}
#[test]
fn a_station_is_found_by_the_word_station() {
let r = record(&node(
6,
&[
("railway", s("station")),
("name", s("東京")),
("name:en", s("Tokyo")),
],
))
.expect("named station");
assert_eq!(r.search_text, "東京 Tokyo station");
assert_eq!(r.name_text(), "東京 Tokyo station");
}
#[test]
fn venue_categories_cover_railway_aeroway_and_no() {
assert!(
record(&node(
1,
&[("railway", s("station")), ("name", s("Pune Jn"))]
))
.is_some()
);
assert!(
record(&node(
2,
&[("aeroway", s("aerodrome")), ("name", s("Lohegaon"))]
))
.is_some()
);
assert!(record(&node(3, &[("railway", s("platform")), ("name", s("X"))])).is_none());
assert!(record(&node(4, &[("amenity", s("no")), ("name", s("Y"))])).is_none());
assert!(record(&node(5, &[("tourism", s("no")), ("name", s("Z"))])).is_none());
}
#[test]
fn names_skip_non_string_and_empty_values() {
let r = record(&node(
1,
&[
("place", s("town")),
("name", s("X")),
("name:num", PropValue::I64(2)),
("name:blank", s(" ")),
],
))
.expect("named town");
assert!(r.names.is_empty(), "{:?}", r.names);
}
#[test]
fn a_street_only_or_number_only_node_becomes_an_address() {
let street = record(&node(
1,
&[("addr:street", s("MG Road")), ("addr:unit", s("2B"))],
))
.expect("street only");
assert_eq!(street.name, "MG Road");
assert_eq!(street.address.expect("fields").unit.as_deref(), Some("2B"));
let number = record(&node(2, &[("addr:housenumber", s("9"))])).expect("number only");
assert_eq!(number.name, "9");
}
#[test]
fn empty_settlement_index_leaves_the_record_alone() {
let mut r = venue_at("Cafe", 28.0, osm());
fill_locality(&mut r, &SettlementIndex::new());
assert_eq!(r.admin.locality, None);
assert_eq!(r.search_text, "Cafe");
}
#[test]
fn overture_index_keeps_only_venues_and_addresses() {
let mut city = venue_at("Pune", 28.0, overture());
city.layer = GeocodingLayer::Locality;
let index = index_of(&[city]);
assert!(
!index.is_duplicate(&venue_at("Pune", 28.0, osm())),
"a locality must not enter the venue index"
);
}
#[test]
fn a_feature_from_another_source_is_skipped() {
let mut f = node(1, &[("amenity", s("cafe")), ("name", s("X"))]);
f.source = DataSource::Overture {
theme: "places".into(),
otype: "place".into(),
};
assert!(record(&f).is_none());
}
#[test]
fn a_relation_feature_keeps_its_source_id() {
let r = record(&feature(
OsmElementType::Relation,
9,
geo::Geometry::Point(geo::Point::new(0.0, 0.0)),
&[("place", s("city")), ("name", s("X"))],
))
.expect("named city");
assert_eq!(r.id, (2 << 62) + 9);
assert_eq!(r.source_id.as_deref(), Some("relation/9"));
}
#[test]
fn an_empty_overture_index_has_no_duplicates() {
let index = index_of(&[]);
assert!(!index.is_duplicate(&venue_at("Anything", 28.0, osm())));
}
const M_PER_DEG: f64 = 111_194.926;
fn venue_lon_lat(name: &str, lon: f64, lat: f64, source: DataSource) -> GeocodingRecord {
let mut record = venue_at(name, lat, source);
record.lon = lon;
record
}
fn index_of(records: &[GeocodingRecord]) -> OvertureIndex {
let mut builder = OvertureIndexBuilder::default();
for record in records {
builder.add(record);
}
builder.build()
}
fn venues(name: &str, places: &[(f64, f64)]) -> OvertureIndex {
let records: Vec<GeocodingRecord> = places
.iter()
.map(|&(lon, lat)| venue_lon_lat(name, lon, lat, overture()))
.collect();
index_of(&records)
}
fn from_the_pole(m: f64) -> f64 {
90.0 - m / M_PER_DEG
}
#[test]
fn a_same_name_venue_is_found_behind_a_closer_other_name() {
let index = index_of(&[
venue_at("Haldiram", 28.0 + 5.0 / M_PER_DEG, overture()),
venue_at("Cafe Coffee Day", 28.0 + 40.0 / M_PER_DEG, overture()),
]);
assert!(index.is_duplicate(&venue_at("cafe coffee day", 28.0, osm())));
}
#[test]
fn the_limit_is_50_m() {
let index = venues("Cafe", &[(77.0, 28.0)]);
assert!(index.is_duplicate(&venue_at("Cafe", 28.0 + 49.0 / M_PER_DEG, osm())));
assert!(!index.is_duplicate(&venue_at("Cafe", 28.0 + 51.0 / M_PER_DEG, osm())));
}
#[test]
fn a_repeat_across_the_antimeridian_is_found() {
let east = venues("Cafe", &[(179.9998, 0.0)]);
assert!(east.is_duplicate(&venue_lon_lat("Cafe", -179.9998, 0.0, osm())));
let west = venues("Cafe", &[(-179.9998, 0.0)]);
assert!(west.is_duplicate(&venue_lon_lat("Cafe", 179.9998, 0.0, osm())));
let date_line = venues("Cafe", &[(180.0, 0.0)]);
assert!(date_line.is_duplicate(&venue_lon_lat("Cafe", -179.9998, 0.0, osm())));
}
#[test]
fn a_repeat_near_the_pole_is_found_at_any_longitude() {
let across = venues("Cafe", &[(180.0, from_the_pole(11.0))]);
assert!(across.is_duplicate(&venue_lon_lat("Cafe", 0.0, from_the_pole(11.0), osm())));
let wide = venues("Cafe", &[(40.0, from_the_pole(60.0))]);
assert!(wide.is_duplicate(&venue_lon_lat("Cafe", 0.0, from_the_pole(60.0), osm())));
}
#[test]
fn a_repeat_closer_to_the_pole_is_found_at_a_wider_longitude() {
let osm_venue = venue_lon_lat("Cafe", 0.0, from_the_pole(100.0), osm());
assert!(venues("Cafe", &[(29.5, from_the_pole(87.0))]).is_duplicate(&osm_venue));
assert!(!venues("Cafe", &[(31.0, from_the_pole(87.0))]).is_duplicate(&osm_venue));
}
#[test]
fn unnamed_and_off_globe_places_never_match() {
let mut builder = OvertureIndexBuilder::default();
let at = |lon: f64, name: Option<&str>| SpatialCandidate {
id: 1,
centroid_lon: lon,
centroid_lat: 28.0,
area_m2: None,
name: name.map(str::to_owned),
};
builder.add_candidate(GeocodingLayer::Venue, at(77.0, None));
builder.add_candidate(GeocodingLayer::Venue, at(f64::NAN, Some("Cafe")));
let index = builder.build();
assert!(!index.is_duplicate(&venue_at("Cafe", 28.0, osm())));
let cafe = venues("Cafe", &[(77.0, 28.0)]);
assert!(!cafe.is_duplicate(&venue_lon_lat("Cafe", f64::NAN, 28.0, osm())));
assert!(!cafe.is_duplicate(&venue_lon_lat("Cafe", 77.0, 91.0, osm())));
}
fn scatter(n: usize, mut seed: u64) -> Vec<(f64, f64)> {
let mut unit = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed >> 11) as f64 / (1_u64 << 53) as f64
};
(0..n)
.map(|_| (77.0 + unit() * 0.03, 28.0 + unit() * 0.03))
.collect()
}
#[test]
fn the_index_agrees_with_a_scan_of_every_candidate() {
let names = [
"Cafe Coffee Day",
"cafe coffee day",
"Cafe Coffee",
"Haldiram",
"Haldirams",
"Pune Station",
"7 MG Road",
"7 MG Rd",
];
let candidates = scatter(2_000, 1);
let records: Vec<GeocodingRecord> = candidates
.iter()
.enumerate()
.map(|(i, &(lon, lat))| venue_lon_lat(names[i % names.len()], lon, lat, overture()))
.collect();
let index = index_of(&records);
let mut repeats = 0;
for (i, (lon, lat)) in scatter(2_000, 2).into_iter().enumerate() {
let name = names[(i * 3) % names.len()].to_lowercase();
let expected = candidates.iter().enumerate().any(|(j, &(clon, clat))| {
geolith::conflation::spatial::haversine_distance_m(lon, lat, clon, clat) <= 50.0
&& strsim::jaro_winkler(&name, &names[j % names.len()].to_lowercase())
>= DUPLICATE_NAME_SIMILARITY
&& same_words(&name, &names[j % names.len()].to_lowercase())
});
let osm_venue = venue_lon_lat(&name, lon, lat, osm());
assert_eq!(index.is_duplicate(&osm_venue), expected, "query {i}");
repeats += usize::from(expected);
}
assert!((200..1_800).contains(&repeats), "{repeats} of 2,000");
}
}