Skip to main content

geolith/conflation/
spatial.rs

1//! Spatial deduplication fallback for Overture themes without GERS bridge files.
2//!
3//! Uses H3 cell blocking to avoid O(n²) comparisons, then ranks candidates
4//! by centroid distance, area ratio, name similarity, and feature ID.
5
6/// Configuration for spatial deduplication thresholds.
7#[derive(Debug, Clone)]
8pub struct SpatialDedupConfig {
9    /// Maximum centroid distance in meters for a match.
10    pub max_distance_m: f64,
11    /// Minimum area ratio (smaller/larger) for polygon match.
12    pub min_area_ratio: f64,
13    /// Maximum area ratio (larger/smaller) for polygon match.
14    pub max_area_ratio: f64,
15    /// H3 resolution for blocking (8 ≈ 460m cells).
16    pub h3_resolution: u8,
17}
18
19impl Default for SpatialDedupConfig {
20    fn default() -> Self {
21        Self {
22            max_distance_m: 50.0,
23            min_area_ratio: 0.5,
24            max_area_ratio: 2.0,
25            h3_resolution: 8,
26        }
27    }
28}
29
30/// A candidate feature for spatial deduplication.
31#[derive(Debug, Clone)]
32pub struct SpatialCandidate {
33    /// Feature ID.
34    pub id: u64,
35    /// Centroid longitude in WGS84 degrees.
36    pub centroid_lon: f64,
37    /// Centroid latitude in WGS84 degrees.
38    pub centroid_lat: f64,
39    /// Area in square meters (None for point features).
40    pub area_m2: Option<f64>,
41    /// Optional display name for name-similarity matching.
42    pub name: Option<String>,
43}
44
45/// Haversine distance in meters between two WGS84 lon/lat points.
46#[must_use]
47pub fn haversine_distance_m(lon1: f64, lat1: f64, lon2: f64, lat2: f64) -> f64 {
48    const EARTH_RADIUS_M: f64 = 6_371_000.0;
49    let dlat = (lat2 - lat1).to_radians();
50    let dlon = (lon2 - lon1).to_radians();
51    let lat1_r = lat1.to_radians();
52    let lat2_r = lat2.to_radians();
53    let a = (dlat / 2.0).sin().powi(2) + lat1_r.cos() * lat2_r.cos() * (dlon / 2.0).sin().powi(2);
54    let c = 2.0 * a.sqrt().asin();
55    EARTH_RADIUS_M * c
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn haversine_same_point_is_zero() {
64        let d = haversine_distance_m(77.0, 28.0, 77.0, 28.0);
65        assert!(d < 1e-6, "same point distance should be ~0, got {d}");
66    }
67
68    #[test]
69    fn haversine_known_distance() {
70        // ~111km per degree of latitude
71        let d = haversine_distance_m(0.0, 0.0, 0.0, 1.0);
72        assert!(
73            (d - 111_195.0).abs() < 100.0,
74            "1 degree lat ≈ 111km, got {d}"
75        );
76    }
77}