geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
Documentation
//! Place importance, as Nominatim computes it.
//!
//! A place with a `wikidata` tag takes the importance of its Wikipedia
//! article from Nominatim's `wikimedia-importance.csv.gz`: a value from 0 to
//! 1 that grows with the links to the article. Any other place takes a
//! default from its place rank, `0.40001 - rank / 75`: 0.347 for a country
//! (rank 4), 0.187 for a city (16) and 0.00001 for a shop or a house (30).
//! Overture `confidence` tells whether a place exists, not how well known it
//! is, so it does not set importance.
//!
//! See <https://nominatim.org/release-docs/latest/customize/Importance/>.

use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;

use crate::error::{Result, SearchError};
use flate2::read::MultiGzDecoder;

/// Place rank of a point of interest or an address: the lowest rank.
pub const POI_RANK: u8 = 30;

/// Importance of a place with no Wikipedia article: Nominatim's
/// `0.40001 - rank / 75`.
#[must_use]
pub fn default_importance(rank: u8) -> f32 {
    0.40001 - f32::from(rank) / 75.0
}

/// Wikipedia importance and English article title by Wikidata item.
#[derive(Debug, Default)]
pub struct Wikipedia {
    /// Item number and importance, sorted by item number, one per item.
    items: Vec<(u32, f32)>,
    /// Item number and the title of its English article (type `a`, not a
    /// redirect), sorted by item number, one per item.
    titles: Vec<(u32, Box<str>)>,
}

impl Wikipedia {
    /// Read Nominatim's `wikimedia-importance.csv.gz`.
    ///
    /// # Errors
    /// When the file cannot be read, is not gzip, or has a row that is not
    /// `language, type, title, importance, wikidata_id`.
    pub fn load(path: &Path) -> Result<Self> {
        let file = File::open(path).map_err(|source| SearchError::OpenImportance {
            path: path.to_path_buf(),
            source,
        })?;
        Self::read(BufReader::new(MultiGzDecoder::new(BufReader::new(file)))).map_err(|source| {
            SearchError::ReadImportance {
                path: path.to_path_buf(),
                source,
            }
        })
    }

    /// Read tab-separated rows of `language, type, title, importance,
    /// wikidata_id`, with or without a header row. An item in several rows
    /// (one per language and redirect) keeps its highest importance.
    ///
    /// # Errors
    /// When a row has no importance or no Wikidata item.
    pub fn read(input: impl BufRead) -> io::Result<Self> {
        let mut items = Vec::new();
        let mut titles = Vec::new();
        for (number, line) in input.lines().enumerate() {
            let line = line?;
            if line.is_empty() || (number == 0 && line.starts_with("language\t")) {
                continue;
            }
            // The last two columns are read from the end, so a tab in the
            // title cannot shift them.
            let mut columns = line.rsplitn(3, '\t');
            let item = columns.next().and_then(item_number);
            // "NaN" and "inf" parse as f32; a value outside 0..1 is clamped.
            let importance = columns
                .next()
                .and_then(|value| value.parse::<f32>().ok())
                .filter(|value| value.is_finite())
                .map(|value| value.clamp(0.0, 1.0));
            let (Some(item), Some(importance)) = (item, importance) else {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "line {}: not language, type, title, importance, wikidata_id",
                        number + 1
                    ),
                ));
            };
            items.push((item, importance));
            if let Some(title) = columns
                .next()
                .and_then(|rest| rest.strip_prefix("en\ta\t"))
                .filter(|title| !title.is_empty())
            {
                titles.push((item, title.replace('_', " ").into_boxed_str()));
            }
        }
        items.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.total_cmp(&a.1)));
        items.dedup_by_key(|entry| entry.0);
        titles.sort_by_key(|entry| entry.0);
        titles.dedup_by_key(|entry| entry.0);
        titles.shrink_to_fit();
        Ok(Self { items, titles })
    }

    /// Items with an importance.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.items.len()
    }

    /// Whether no item has an importance.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The importance of a Wikidata item such as `Q84`, or of the first item
    /// of a list such as `Q84;Q23306`.
    #[must_use]
    pub fn get(&self, wikidata: &str) -> Option<f32> {
        let item = item_number(wikidata.split(';').next()?)?;
        let at = self
            .items
            .binary_search_by_key(&item, |entry| entry.0)
            .ok()?;
        self.items.get(at).map(|entry| entry.1)
    }

    /// The title of the English article of a Wikidata item, or of the first
    /// item of a list, with spaces for underscores: "Big Ben" for `Q41225`.
    #[must_use]
    pub fn english_title(&self, wikidata: &str) -> Option<&str> {
        let item = item_number(wikidata.split(';').next()?)?;
        let at = self
            .titles
            .binary_search_by_key(&item, |entry| entry.0)
            .ok()?;
        self.titles.get(at).map(|entry| &*entry.1)
    }
}

/// The number of a Wikidata item: 84 for `Q84`.
fn item_number(text: &str) -> Option<u32> {
    let text = text.trim();
    text.strip_prefix('Q')
        .or_else(|| text.strip_prefix('q'))?
        .parse()
        .ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    /// London twice (English and French article), the Eiffel Tower once.
    const ROWS: &str = "language\ttype\ttitle\timportance\twikidata_id\n\
                        fr\ta\tLondres\t0.7\tQ84\n\
                        en\ta\tLondon\t0.8920997258748663\tQ84\n\
                        en\tr\tEiffel_Tower\t0.6205937724353116\tQ243\n\
                        \n";

    #[test]
    fn a_place_without_an_article_takes_the_nominatim_default() {
        // 0.40001 - rank / 75, worked by hand.
        assert!((default_importance(4) - 0.346_677).abs() < 1e-6, "country");
        assert!((default_importance(16) - 0.186_677).abs() < 1e-6, "city");
        assert!(
            (default_importance(POI_RANK) - 0.000_01).abs() < 1e-6,
            "shop or house"
        );
    }

    #[test]
    fn an_item_keeps_its_highest_importance() {
        let wikipedia = Wikipedia::read(ROWS.as_bytes()).expect("rows");
        assert_eq!(wikipedia.len(), 2);
        assert!(!wikipedia.is_empty());
        let london = wikipedia.get("Q84").expect("London");
        assert!((london - 0.892_1).abs() < 1e-4, "{london}");
        let tower = wikipedia.get(" q243 ").expect("Eiffel Tower");
        assert!((tower - 0.620_6).abs() < 1e-4, "{tower}");
    }

    #[test]
    fn a_list_of_items_takes_the_first() {
        let wikipedia = Wikipedia::read(ROWS.as_bytes()).expect("rows");
        let first = wikipedia.get("Q84;Q243").expect("London");
        assert!((first - 0.892_1).abs() < 1e-4, "{first}");
        assert_eq!(wikipedia.get("Q999"), None);
        assert_eq!(wikipedia.get("London"), None);
        assert_eq!(wikipedia.get(""), None);
    }

    #[test]
    fn an_item_has_the_title_of_its_english_article() {
        let wikipedia = Wikipedia::read(ROWS.as_bytes()).expect("rows");
        assert_eq!(wikipedia.english_title("Q84"), Some("London"));
        // A redirect is not an article.
        assert_eq!(wikipedia.english_title("Q243"), None);
        let rows = "fr\ta\tTour_Eiffel\t0.62\tQ243\nen\tr\tBig_Ben_Tower\t0.53\tQ41225\n\
                    en\ta\tBig_Ben\t0.53\tQ41225\n";
        let wikipedia = Wikipedia::read(rows.as_bytes()).expect("rows");
        assert_eq!(wikipedia.english_title("Q41225;Q84"), Some("Big Ben"));
        assert_eq!(wikipedia.english_title("Q243"), None);
    }

    #[test]
    fn rows_without_a_header_are_read() {
        let wikipedia = Wikipedia::read("en\ta\tLondon\t0.5\tQ84\n".as_bytes()).expect("row");
        assert_eq!(wikipedia.get("Q84"), Some(0.5));
    }

    #[test]
    fn a_row_without_an_importance_or_an_item_fails() {
        for row in ["en\ta\tLondon\tnot a number\tQ84\n", "en\ta\tLondon\t0.5\n"] {
            let err = Wikipedia::read(row.as_bytes()).expect_err(row);
            assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{row}");
            assert!(err.to_string().starts_with("line 1:"), "{err}");
        }
    }

    #[test]
    fn the_gzip_file_loads() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("wikimedia-importance.csv.gz");
        let mut gz = flate2::write::GzEncoder::new(
            File::create(&path).expect("create"),
            flate2::Compression::default(),
        );
        gz.write_all(ROWS.as_bytes()).expect("write");
        gz.finish().expect("finish");

        let wikipedia = Wikipedia::load(&path).expect("load");
        assert_eq!(wikipedia.len(), 2);
    }

    #[test]
    fn a_missing_or_plain_file_fails() {
        let dir = tempfile::tempdir().expect("tempdir");
        let missing = dir.path().join("missing.csv.gz");
        let err = Wikipedia::load(&missing).expect_err("missing");
        assert!(err.to_string().contains("failed to open"), "{err}");

        let plain = dir.path().join("plain.csv");
        std::fs::write(&plain, ROWS).expect("write");
        let err = Wikipedia::load(&plain).expect_err("not gzip");
        assert!(err.to_string().contains("failed to read"), "{err}");
    }

    /// `parse::<f32>()` takes "NaN" and "inf", and a value above 1 would
    /// reach the sort band and the glx importance as it is.
    #[test]
    fn a_non_finite_importance_is_refused_and_a_large_one_is_clamped() {
        let nan = "en\ta\tParis\tNaN\tQ90\n";
        assert!(Wikipedia::read(nan.as_bytes()).is_err(), "NaN");
        let inf = "en\ta\tParis\tinf\tQ90\n";
        assert!(Wikipedia::read(inf.as_bytes()).is_err(), "inf");
        let big = "en\ta\tParis\t1.7\tQ90\nen\ta\tLyon\t-0.2\tQ456\n";
        let table = Wikipedia::read(big.as_bytes()).expect("finite values");
        assert_eq!(table.get("Q90"), Some(1.0));
        assert_eq!(table.get("Q456"), Some(0.0));
    }
}