SPB Git

Repository Public

geom.rs 7.0 KB 193 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : server/km-geo/src/geom.rs10// Module           : server11// Repository       : https://git.spboucher.ai/ka-maps-engine12// Created          : 2026-12-0113// Last Modified    : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Projection Web Mercator, validation des coordonnées, mesures géodésiques (WGS 84, Karney).8889use geographiclib_rs::{Geodesic, InverseGeodesic, PolygonArea, Winding};9091pub const R: f64 = 6_378_137.0;92/// Emprise prise en charge : le Québec et son voisinage immédiat.93pub const LON_MIN: f64 = -80.5;94pub const LON_MAX: f64 = -56.5;95pub const LAT_MIN: f64 = 44.5;96pub const LAT_MAX: f64 = 63.0;9798pub fn to_merc(lon: f64, lat: f64) -> (f64, f64) {99    (R * lon.to_radians(), R * (std::f64::consts::FRAC_PI_4 + lat.to_radians() / 2.0).tan().ln())100}101102pub fn from_merc(x: f64, y: f64) -> (f64, f64) {103    ((x / R).to_degrees(), (2.0 * (y / R).exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees())104}105106pub fn in_area(lon: f64, lat: f64) -> bool {107    lon.is_finite() && lat.is_finite() && (LON_MIN..=LON_MAX).contains(&lon) && (LAT_MIN..=LAT_MAX).contains(&lat)108}109110pub fn round6(v: f64) -> f64 {111    (v * 1e6).round() / 1e6112}113114pub fn round1(v: f64) -> f64 {115    (v * 10.0).round() / 10.0116}117118/// Longueur géodésique d'une polyligne (lon, lat), en mètres.119pub fn line_length(pts: &[(f64, f64)]) -> f64 {120    let g = Geodesic::wgs84();121    pts.windows(2)122        .map(|w| {123            let s: f64 = g.inverse(w[0].1, w[0].0, w[1].1, w[1].0);124            s125        })126        .sum()127}128129/// (périmètre m, superficie m²) d'un anneau (lon, lat) ; l'anneau peut être fermé ou non.130pub fn ring_measure(ring: &[(f64, f64)]) -> (f64, f64) {131    let mut pts = ring;132    if pts.len() >= 2 && pts[0] == pts[pts.len() - 1] {133        pts = &pts[..pts.len() - 1];134    }135    if pts.len() < 3 {136        return (0.0, 0.0);137    }138    let g = Geodesic::wgs84();139    let mut pa = PolygonArea::new(&g, Winding::CounterClockwise);140    for (lon, lat) in pts {141        pa.add_point(*lat, *lon);142    }143    let (perimeter, area, _) = pa.compute(true);144    (perimeter, area.abs())145}146147#[cfg(test)]148mod tests {149    use super::*;150151    #[test]152    fn mercator_round_trip() {153        let (x, y) = to_merc(-73.5673, 45.5017);154        assert!((x - -8189475.0).abs() < 50.0, "{x}");155        let (lon, lat) = from_merc(x, y);156        assert!((lon + 73.5673).abs() < 1e-9 && (lat - 45.5017).abs() < 1e-9);157    }158159    #[test]160    fn geodesic_length() {161        // Un degré de méridien près de 45° N ≈ 111,13 km162        let d = line_length(&[(-73.0, 45.0), (-73.0, 46.0)]);163        assert!((d - 111_141.5).abs() < 20.0, "{d}");164        // Montréal (45.5017, -73.5673) → Québec (46.8139, -71.2080) ≈ 233 km165        let d = line_length(&[(-73.5673, 45.5017), (-71.2080, 46.8139)]);166        assert!((d - 233_000.0).abs() < 1500.0, "{d}");167        assert_eq!(line_length(&[(-73.0, 45.0)]), 0.0);168    }169170    #[test]171    fn geodesic_area() {172        // Carré de 0,01° × 0,01° à 45,5° N : ≈ 1111,5 m × 779,7 m ≈ 0,8667 km²173        let ring = [(-73.60, 45.50), (-73.59, 45.50), (-73.59, 45.51), (-73.60, 45.51), (-73.60, 45.50)];174        let (per, area) = ring_measure(&ring);175        assert!((area - 866_600.0).abs() < 2_000.0, "{area}");176        assert!((per - 3_782.0).abs() < 10.0, "{per}");177        // Sens horaire : même superficie178        let mut cw = ring.to_vec();179        cw.reverse();180        let (_, area2) = ring_measure(&cw);181        assert!((area - area2).abs() < 1e-3);182        assert_eq!(ring_measure(&[(-73.0, 45.0), (-73.1, 45.0)]), (0.0, 0.0));183    }184185    #[test]186    fn area_bounds() {187        assert!(in_area(-73.56, 45.5));188        assert!(!in_area(2.35, 48.85));189        assert!(!in_area(f64::NAN, 45.0));190        assert!(!in_area(-73.0, 91.0));191    }192}193
Files main
Menu

Theme