geolith 0.1.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Spatial deduplication fallback for Overture themes without GERS bridge files.
//!
//! Uses H3 cell blocking to avoid O(n²) comparisons, then ranks candidates
//! by centroid distance, area ratio, name similarity, and feature ID.

/// Configuration for spatial deduplication thresholds.
#[derive(Debug, Clone)]
pub struct SpatialDedupConfig {
    /// Maximum centroid distance in meters for a match.
    pub max_distance_m: f64,
    /// Minimum area ratio (smaller/larger) for polygon match.
    pub min_area_ratio: f64,
    /// Maximum area ratio (larger/smaller) for polygon match.
    pub max_area_ratio: f64,
    /// H3 resolution for blocking (8 ≈ 460m cells).
    pub h3_resolution: u8,
}

impl Default for SpatialDedupConfig {
    fn default() -> Self {
        Self {
            max_distance_m: 50.0,
            min_area_ratio: 0.5,
            max_area_ratio: 2.0,
            h3_resolution: 8,
        }
    }
}

/// A candidate feature for spatial deduplication.
#[derive(Debug, Clone)]
pub struct SpatialCandidate {
    /// Feature ID.
    pub id: u64,
    /// Centroid longitude in WGS84 degrees.
    pub centroid_lon: f64,
    /// Centroid latitude in WGS84 degrees.
    pub centroid_lat: f64,
    /// Area in square meters (None for point features).
    pub area_m2: Option<f64>,
    /// Optional display name for name-similarity matching.
    pub name: Option<String>,
}

/// Haversine distance in meters between two WGS84 lon/lat points.
#[must_use]
pub fn haversine_distance_m(lon1: f64, lat1: f64, lon2: f64, lat2: f64) -> f64 {
    const EARTH_RADIUS_M: f64 = 6_371_000.0;
    let dlat = (lat2 - lat1).to_radians();
    let dlon = (lon2 - lon1).to_radians();
    let lat1_r = lat1.to_radians();
    let lat2_r = lat2.to_radians();
    let a = (dlat / 2.0).sin().powi(2) + lat1_r.cos() * lat2_r.cos() * (dlon / 2.0).sin().powi(2);
    let c = 2.0 * a.sqrt().asin();
    EARTH_RADIUS_M * c
}

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

    #[test]
    fn haversine_same_point_is_zero() {
        let d = haversine_distance_m(77.0, 28.0, 77.0, 28.0);
        assert!(d < 1e-6, "same point distance should be ~0, got {d}");
    }

    #[test]
    fn haversine_known_distance() {
        // ~111km per degree of latitude
        let d = haversine_distance_m(0.0, 0.0, 0.0, 1.0);
        assert!(
            (d - 111_195.0).abs() < 100.0,
            "1 degree lat ≈ 111km, got {d}"
        );
    }
}