use std::collections::HashMap;
use crate::division::osm_record_id;
use crate::importance::{Wikipedia, default_importance};
use geolith::source::input::InputFeature;
use geolith::tile::feature::PropValue;
pub const FLOOR_CAP: f32 = 0.40;
pub const POPULATION_PER_DECADE: f32 = 0.10;
pub const SMALL_POPULATION: u64 = 1_000;
pub const PROMINENCE_FREE: u8 = 20;
pub const PROMINENCE_PER_POINT: f32 = 0.002;
pub const COUNTRY_BONUS: f32 = 0.25;
pub const REGION_BONUS: f32 = 0.20;
pub const COUNTY_BONUS: f32 = 0.10;
const CAPITAL_OF: [&str; 6] = [
"country",
"dependency",
"region",
"macroregion",
"county",
"macrocounty",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SettlementClass {
City,
Town,
Village,
Hamlet,
}
impl SettlementClass {
#[must_use]
pub fn from_place(place: &str) -> Option<Self> {
Some(match place {
"city" => Self::City,
"town" => Self::Town,
"village" => Self::Village,
"hamlet" => Self::Hamlet,
_ => return None,
})
}
#[must_use]
pub fn from_overture(class: &str) -> Option<Self> {
Self::from_place(class)
}
#[must_use]
pub const fn rank(self) -> u8 {
match self {
Self::City => 16,
Self::Town => 18,
Self::Village => 19,
Self::Hamlet => 20,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct PlaceSignals {
pub population: Option<u64>,
pub prominence: Option<u8>,
pub capital: bool,
pub capital_bonus: f32,
}
impl PlaceSignals {
#[must_use]
pub fn or(self, other: Self) -> Self {
Self {
population: self.population.or(other.population),
prominence: self.prominence.or(other.prominence),
capital: self.capital || other.capital,
capital_bonus: self.capital_bonus.max(other.capital_bonus),
}
}
#[must_use]
pub fn any(&self) -> bool {
self.population.is_some() || self.prominence.is_some() || self.capital
}
#[must_use]
pub fn small(&self) -> bool {
self.population.is_some_and(|p| p < SMALL_POPULATION)
}
}
#[must_use]
pub fn floor(class: SettlementClass, signals: &PlaceSignals) -> f32 {
let base = default_importance(class.rank());
let population = signals
.population
.filter(|&p| p >= SMALL_POPULATION)
.map_or(0.0, |p| {
let people = f64::from(u32::try_from(p).unwrap_or(u32::MAX));
let decades = (people / 1_000.0).log10();
POPULATION_PER_DECADE * decades as f32
});
let prominence = signals
.prominence
.filter(|&p| p > PROMINENCE_FREE)
.map_or(0.0, |p| {
PROMINENCE_PER_POINT * f32::from(p - PROMINENCE_FREE)
});
let seat = signals.capital && matches!(class, SettlementClass::City | SettlementClass::Town);
let capital = if seat { signals.capital_bonus } else { 0.0 };
(base + population + prominence + capital).min(FLOOR_CAP)
}
#[must_use]
pub fn settlement_importance(
wikipedia: &Wikipedia,
wikidata: Option<&str>,
class: SettlementClass,
signals: &PlaceSignals,
) -> f32 {
let row = wikidata
.filter(|item| {
let tiny = signals.small()
|| (signals.population.is_none()
&& matches!(class, SettlementClass::Village | SettlementClass::Hamlet)
&& !signals.capital
&& signals.prominence.is_none_or(|p| p <= PROMINENCE_FREE));
!(tiny && wikipedia.english_title(item).is_none())
})
.and_then(|item| wikipedia.get(item));
let floor = floor(class, signals);
row.map_or(floor, |row| row.max(floor))
}
#[must_use]
pub fn parse_population(text: &str) -> Option<u64> {
let digits: String = text
.chars()
.filter(|c| !matches!(c, ' ' | ',' | '_' | '\u{a0}'))
.collect();
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
fn prop_int(feature: &InputFeature, key: &str) -> Option<i64> {
match feature.properties.get(key)? {
PropValue::I64(v) => Some(*v),
PropValue::U64(v) => i64::try_from(*v).ok(),
_ => None,
}
}
fn prop_str<'a>(feature: &'a InputFeature, key: &str) -> Option<&'a str> {
match feature.properties.get(key)? {
PropValue::Str(s) if !s.trim().is_empty() => Some(s.trim()),
_ => None,
}
}
#[must_use]
pub fn division_signals(feature: &InputFeature) -> PlaceSignals {
PlaceSignals {
population: prop_int(feature, "population").and_then(|p| u64::try_from(p).ok()),
prominence: prop_int(feature, "cartography.prominence").and_then(|p| u8::try_from(p).ok()),
capital: prop_str(feature, "capital_of_divisions")
.is_some_and(|list| list.split(';').any(|subtype| CAPITAL_OF.contains(&subtype))),
capital_bonus: prop_str(feature, "capital_of_divisions").map_or(0.0, |list| {
list.split(';').map(subtype_bonus).fold(0.0, f32::max)
}),
}
}
#[must_use]
pub fn osm_signals(population: Option<&str>, capital: Option<&str>) -> PlaceSignals {
let capital = capital.map(str::trim);
let seat = capital.is_some_and(|value| !value.eq_ignore_ascii_case("no"));
PlaceSignals {
population: population.and_then(parse_population),
prominence: None,
capital: seat,
capital_bonus: if seat {
capital.map_or(COUNTRY_BONUS, capital_value_bonus)
} else {
0.0
},
}
}
fn subtype_bonus(subtype: &str) -> f32 {
match subtype {
"country" | "dependency" => COUNTRY_BONUS,
"region" | "macroregion" => REGION_BONUS,
"county" | "macrocounty" | "localadmin" => COUNTY_BONUS,
_ => 0.0,
}
}
fn capital_value_bonus(value: &str) -> f32 {
match value {
"yes" | "2" => COUNTRY_BONUS,
"3" | "4" => REGION_BONUS,
_ => COUNTY_BONUS,
}
}
#[derive(Debug, Default)]
pub struct PlaceSignalIndex {
by_osm_id: HashMap<u64, PlaceSignals>,
}
impl PlaceSignalIndex {
pub fn add(&mut self, feature: &InputFeature) {
if prop_str(feature, "subtype") != Some("locality") {
return;
}
let Some(id) = osm_record_id(feature) else {
return;
};
let signals = division_signals(feature);
if signals.population.is_some()
|| signals.capital
|| signals.prominence.is_some_and(|p| p > PROMINENCE_FREE)
{
self.by_osm_id.insert(id, signals);
}
}
#[must_use]
pub fn get(&self, osm_record_id: u64) -> PlaceSignals {
self.by_osm_id
.get(&osm_record_id)
.copied()
.unwrap_or_default()
}
#[must_use]
pub fn len(&self) -> usize {
self.by_osm_id.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.by_osm_id.is_empty()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use geolith::source::input::DataSource;
fn s(v: &str) -> PropValue {
PropValue::Str(v.to_string())
}
fn division(props: &[(&str, PropValue)]) -> InputFeature {
InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(91.86, 27.59))),
properties: props
.iter()
.map(|(k, v)| ((*k).to_string(), v.clone()))
.collect(),
bbox: None,
source: DataSource::Overture {
theme: "divisions".into(),
otype: "division".into(),
},
}
}
fn signals(population: Option<u64>, prominence: Option<u8>, capital: bool) -> PlaceSignals {
PlaceSignals {
population,
prominence,
capital,
capital_bonus: if capital { COUNTY_BONUS } else { 0.0 },
}
}
#[test]
fn the_floor_of_each_case_written_out() {
let none = signals(None, None, false);
let cases = [
(SettlementClass::City, none, 0.186_68),
(SettlementClass::Town, none, 0.160_01),
(SettlementClass::Village, none, 0.146_68),
(SettlementClass::Hamlet, none, 0.133_34),
(
SettlementClass::Town,
signals(Some(11_000), None, false),
0.264_15,
),
(
SettlementClass::Town,
signals(Some(999), None, false),
0.160_01,
),
(
SettlementClass::Town,
signals(Some(1_000), None, false),
0.160_01,
),
(
SettlementClass::Village,
signals(Some(100_000), None, false),
0.346_68,
),
(
SettlementClass::Village,
signals(None, Some(12), false),
0.146_68,
),
(
SettlementClass::Town,
signals(None, Some(20), false),
0.160_01,
),
(
SettlementClass::Town,
signals(None, Some(58), false),
0.236_01,
),
(SettlementClass::Town, signals(None, None, true), 0.260_01),
(
SettlementClass::Town,
PlaceSignals {
capital: true,
capital_bonus: COUNTRY_BONUS,
..PlaceSignals::default()
},
0.40,
),
(
SettlementClass::Hamlet,
signals(Some(10_000_000), Some(100), true),
0.40,
),
];
for (class, given, want) in cases {
let got = floor(class, &given);
assert!(
(got - want).abs() < 1e-4,
"{class:?} {given:?}: {got}, not {want}"
);
}
}
const ROWS: &str = "en\ta\tLondon\t0.892\tQ84\n\
ro\ta\tTiny\t0.418\tQ1\n\
en\ta\tHallstatt\t0.50\tQ2\n\
sv\ta\tLow\t0.05\tQ3\n";
fn wikipedia() -> Wikipedia {
Wikipedia::read(ROWS.as_bytes()).expect("rows")
}
#[test]
fn the_importance_is_the_larger_of_the_row_and_the_floor() {
let w = wikipedia();
let none = signals(None, None, false);
let at = |item: Option<&str>, class, given: &PlaceSignals| {
settlement_importance(&w, item, class, given)
};
assert!((at(Some("Q84"), SettlementClass::City, &none) - 0.892).abs() < 1e-6);
assert!((at(Some("Q3"), SettlementClass::Town, &none) - 0.160_01).abs() < 1e-4);
assert!((at(None, SettlementClass::Town, &none) - 0.160_01).abs() < 1e-4);
assert!((at(Some("Q999"), SettlementClass::Town, &none) - 0.160_01).abs() < 1e-4);
let seat = signals(None, None, true);
assert!((at(Some("Q3"), SettlementClass::Town, &seat) - 0.260_01).abs() < 1e-4);
let country = PlaceSignals {
capital: true,
capital_bonus: COUNTRY_BONUS,
..PlaceSignals::default()
};
assert!((at(Some("Q3"), SettlementClass::Town, &country) - 0.40).abs() < 1e-6);
}
#[test]
fn a_small_language_row_of_a_tiny_place_is_dropped() {
let w = wikipedia();
let tiny = signals(Some(99), None, false);
let village = |item, given: &PlaceSignals| {
settlement_importance(&w, Some(item), SettlementClass::Village, given)
};
assert!((village("Q1", &tiny) - 0.146_68).abs() < 1e-4, "dropped");
assert!(
(village("Q2", &tiny) - 0.50).abs() < 1e-6,
"an English article: kept"
);
assert!(
(village("Q1", &signals(None, None, false)) - 0.146_68).abs() < 1e-4,
"unknown population, no lift: dropped"
);
assert!((village("Q1", &signals(None, Some(30), false)) - 0.418).abs() < 1e-6);
assert!((village("Q1", &signals(Some(1_000), None, false)) - 0.418).abs() < 1e-6);
}
#[test]
fn only_a_city_a_town_a_village_or_a_hamlet_has_a_floor() {
for place in ["city", "town", "village", "hamlet"] {
assert!(SettlementClass::from_place(place).is_some(), "{place}");
}
for place in [
"suburb",
"quarter",
"neighbourhood",
"state",
"locality",
"",
] {
assert!(SettlementClass::from_place(place).is_none(), "{place}");
}
}
#[test]
fn a_population_tag_is_read_only_when_it_is_a_plain_number() {
for (text, want) in [
("11000", Some(11_000)),
("11,000", Some(11_000)),
("11 000", Some(11_000)),
("1_000_000", Some(1_000_000)),
("0", Some(0)),
("1.2 million", None),
("~5000", None),
("1.234", None),
("", None),
("abc", None),
("99999999999999999999999", None),
] {
assert_eq!(parse_population(text), want, "{text:?}");
}
}
#[test]
fn osm_tags_give_population_and_capital() {
assert_eq!(
osm_signals(Some("11000"), None),
signals(Some(11_000), None, false)
);
for (capital, want) in [("yes", true), ("4", true), ("no", false), ("NO", false)] {
assert_eq!(osm_signals(None, Some(capital)).capital, want, "{capital}");
}
assert_eq!(osm_signals(None, None), PlaceSignals::default());
}
#[test]
fn overture_gives_population_prominence_and_the_seats_it_holds() {
let tawang = division(&[
("population", PropValue::I64(11_000)),
("cartography.prominence", PropValue::I64(58)),
("capital_of_divisions", s("county")),
]);
assert_eq!(
division_signals(&tawang),
signals(Some(11_000), Some(58), true)
);
let seat = division(&[("capital_of_divisions", s("localadmin"))]);
assert!(!division_signals(&seat).capital);
let both = division(&[("capital_of_divisions", s("localadmin;region"))]);
assert!(division_signals(&both).capital);
assert_eq!(division_signals(&division(&[])), PlaceSignals::default());
}
#[test]
fn the_index_holds_the_osm_sourced_localities_with_something_to_say() {
let point = |subtype: &str, record: &str, extra: &[(&str, PropValue)]| {
let mut props = vec![
("subtype", s(subtype)),
("sources.dataset", s("OpenStreetMap")),
("sources.record_id", s(record)),
];
props.extend(extra.iter().cloned());
division(&props)
};
let mut index = PlaceSignalIndex::default();
index.add(&point(
"locality",
"n10@1",
&[("cartography.prominence", PropValue::I64(58))],
));
index.add(&point(
"locality",
"n11@1",
&[("cartography.prominence", PropValue::I64(12))],
));
index.add(&point(
"locality",
"n12@1",
&[("population", PropValue::I64(99))],
));
index.add(&point(
"county",
"n13@1",
&[("capital_of_divisions", s("county"))],
));
assert_eq!(index.len(), 2);
assert_eq!(index.get(10).prominence, Some(58));
assert_eq!(
index.get(12).population,
Some(99),
"a small population is kept too"
);
assert_eq!(
index.get(11),
PlaceSignals::default(),
"prominence 12 says nothing"
);
assert_eq!(
index.get(13),
PlaceSignals::default(),
"a county is not a settlement"
);
assert_eq!(index.get(99), PlaceSignals::default());
}
}