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 outlines for the `.glx` file.
//!
//! A place with an area (a park, a campus, a city, a state) keeps its
//! outline as polygons beside its point, so a client can draw the whole
//! place. Outlines are simplified (Ramer-Douglas-Peucker) to a tolerance
//! and written with [`glx::format::encode_shape`].

use geo::{Geometry, LineString, Simplify};

use crate::record::{GeocodingLayer, GeocodingRecord};
use geolith::admin::{AdminHierarchyIndex, AdminLevel};

/// Tolerance for venues and other OSM areas, in degrees: about 1 m.
pub const VENUE_TOLERANCE: f64 = 1e-5;

/// Tolerance for admin areas (countries to neighbourhoods), in degrees:
/// about 11 m, below what a map shows at the zoom that holds the area.
pub const AREA_TOLERANCE: f64 = 1e-4;

/// One ring simplified to `tolerance`, closed; `None` when fewer than
/// three distinct points are left.
fn simplify_ring(ring: &[[f64; 2]], tolerance: f64) -> Option<Vec<[f64; 2]>> {
    let line: LineString<f64> = ring.iter().map(|p| (p[0], p[1])).collect();
    let mut points: Vec<[f64; 2]> = line
        .simplify(tolerance)
        .0
        .iter()
        .map(|c| [c.x, c.y])
        .collect();
    if points.first() != points.last()
        && let Some(&first) = points.first()
    {
        points.push(first);
    }
    (points.len() >= 4).then_some(points)
}

/// A large outline is simplified more: to at least its box's diagonal
/// divided by this (about 1 km for India, 3 m for New Delhi), below what a
/// map shows at the zoom that holds the whole outline.
pub const SIZE_FRACTION: f64 = 4000.0;

/// The encoded shape of polygons given as rings (each polygon its outer ring,
/// then its holes), simplified to `tolerance` or, for a large outline, to
/// [`SIZE_FRACTION`] of its diagonal;
///
/// Empty when no outer ring survives simplification.
#[must_use]
pub fn from_rings(polygons: &[Vec<Vec<[f64; 2]>>], tolerance: f64) -> Vec<u8> {
    let tolerance = glx::format::shape_bbox(polygons).map_or(tolerance, |[w, s, e, n]| {
        tolerance.max((e - w).hypot(n - s) / SIZE_FRACTION)
    });
    let mut kept: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(polygons.len());
    for polygon in polygons {
        let mut rings = polygon.iter();
        let Some(outer) = rings.next().and_then(|ring| simplify_ring(ring, tolerance)) else {
            continue;
        };
        let mut out = vec![outer];
        out.extend(rings.filter_map(|ring| simplify_ring(ring, tolerance)));
        kept.push(out);
    }
    let mut bytes = Vec::new();
    if !kept.is_empty() {
        glx::format::encode_shape(&kept, &mut bytes);
    }
    bytes
}

/// The encoded shape of a polygonal geometry; empty for points and lines.
#[must_use]
pub fn from_geometry(geometry: &Geometry<f64>, tolerance: f64) -> Vec<u8> {
    let ring =
        |line: &LineString<f64>| -> Vec<[f64; 2]> { line.0.iter().map(|c| [c.x, c.y]).collect() };
    let polygon = |p: &geo::Polygon<f64>| -> Vec<Vec<[f64; 2]>> {
        std::iter::once(p.exterior())
            .chain(p.interiors())
            .map(ring)
            .collect()
    };
    let polygons: Vec<Vec<Vec<[f64; 2]>>> = match geometry {
        Geometry::Polygon(p) => vec![polygon(p)],
        Geometry::MultiPolygon(m) => m.0.iter().map(polygon).collect(),
        _ => return Vec::new(),
    };
    from_rings(&polygons, tolerance)
}

/// The admin levels whose divisions a record of `layer` may be.
const fn levels(layer: GeocodingLayer) -> &'static [AdminLevel] {
    match layer {
        GeocodingLayer::Country => &[AdminLevel::Country, AdminLevel::Dependency],
        GeocodingLayer::Region => &[AdminLevel::Region],
        GeocodingLayer::County => &[AdminLevel::County],
        GeocodingLayer::Locality => &[AdminLevel::Locality, AdminLevel::Neighbourhood],
        GeocodingLayer::Address | GeocodingLayer::Venue | GeocodingLayer::Street => &[],
    }
}

/// The encoded outline of the admin division a record names: one that
/// holds the record's point, at the record's level, named one of the
/// record's names. Empty when there is none.
#[must_use]
pub fn admin_outline(index: &AdminHierarchyIndex, record: &GeocodingRecord) -> Vec<u8> {
    let levels = levels(record.layer);
    if levels.is_empty() {
        return Vec::new();
    }
    index
        .outline(record.lon, record.lat, levels, &record.all_names())
        .map(|polygons| from_rings(&polygons, AREA_TOLERANCE))
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::{Polygon, polygon};

    /// A square with a midpoint 0.5 m off its edge: at a 1 m tolerance the
    /// midpoint goes; the four corners stay, closed.
    #[test]
    fn a_ring_keeps_its_corners_within_the_tolerance() {
        let square: Polygon<f64> = polygon![
            (x: 0.0, y: 0.0),
            (x: 0.001, y: 0.000_005),
            (x: 0.002, y: 0.0),
            (x: 0.002, y: 0.002),
            (x: 0.0, y: 0.002),
            (x: 0.0, y: 0.0),
        ];
        let bytes = from_geometry(&Geometry::Polygon(square), VENUE_TOLERANCE);
        let shape = glx::format::decode_shape(&bytes).expect("shape");
        assert_eq!(
            shape,
            vec![vec![vec![
                [0.0, 0.0],
                [0.002, 0.0],
                [0.002, 0.002],
                [0.0, 0.002],
                [0.0, 0.0]
            ]]]
        );
    }

    /// A 10-degree square with a corner 0.002 degrees off its edge: the
    /// diagonal is 14.14 degrees, so the tolerance is 0.0035 and the bend
    /// goes, though it is far above the 1 m venue tolerance.
    #[test]
    fn a_large_outline_is_simplified_to_its_size() {
        let bent = vec![vec![vec![
            [0.0, 0.0],
            [5.0, -0.002],
            [10.0, 0.0],
            [10.0, 10.0],
            [0.0, 10.0],
            [0.0, 0.0],
        ]]];
        let shape = glx::format::decode_shape(&from_rings(&bent, VENUE_TOLERANCE)).expect("shape");
        assert_eq!(shape[0][0].len(), 5);
        // A bend of 0.004 degrees stays.
        let deeper = vec![vec![vec![
            [0.0, 0.0],
            [5.0, -0.004],
            [10.0, 0.0],
            [10.0, 10.0],
            [0.0, 10.0],
            [0.0, 0.0],
        ]]];
        let shape =
            glx::format::decode_shape(&from_rings(&deeper, VENUE_TOLERANCE)).expect("shape");
        assert_eq!(shape[0][0].len(), 6);
    }

    #[test]
    fn points_and_lines_have_no_shape() {
        assert!(
            from_geometry(&Geometry::Point(geo::Point::new(1.0, 2.0)), VENUE_TOLERANCE).is_empty()
        );
        let line = LineString::from(vec![(0.0, 0.0), (1.0, 1.0)]);
        assert!(from_geometry(&Geometry::LineString(line), VENUE_TOLERANCE).is_empty());
    }

    /// A sliver thinner than the tolerance collapses and is dropped, and a
    /// hole that collapses goes while its polygon stays.
    #[test]
    fn collapsed_rings_are_dropped() {
        let sliver = vec![vec![vec![
            [0.0, 0.0],
            [1.0, 0.0],
            [0.5, 0.000_001],
            [0.0, 0.0],
        ]]];
        assert!(from_rings(&sliver, VENUE_TOLERANCE).is_empty());
        let holed = vec![vec![
            vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
            vec![[0.5, 0.5], [0.6, 0.5], [0.55, 0.500_001], [0.5, 0.5]],
        ]];
        let shape = glx::format::decode_shape(&from_rings(&holed, VENUE_TOLERANCE)).expect("shape");
        assert_eq!(shape.len(), 1);
        assert_eq!(shape[0].len(), 1);
    }
}