SPB Git

Repository Public

measure.rs 11.5 KB 280 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/measure.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//! `POST /v1/measure` (GeoJSON) et `GET /v1/measure?points=` — longueurs et superficies géodésiques (WGS 84).8889use crate::err::ApiError;90use crate::geom::{line_length, ring_measure};91use serde_json::{json, Value};9293pub const MAX_VERTICES: usize = 20_000;9495#[derive(Default, Debug, PartialEq)]96pub struct Measure {97    pub length_m: f64,98    pub area_m2: f64,99    pub perimeter_m: f64,100    pub vertices: usize,101    pub lines: usize,102    pub polygons: usize,103}104105fn coords(v: &Value, m: &mut Measure) -> Result<Vec<(f64, f64)>, ApiError> {106    let arr = v.as_array().ok_or_else(|| ApiError::bad("coordonnées : tableau attendu"))?;107    m.vertices += arr.len();108    if m.vertices > MAX_VERTICES {109        return Err(ApiError::bad("trop de sommets (maximum 20 000)"));110    }111    arr.iter()112        .map(|p| {113            let p = p.as_array().filter(|p| p.len() >= 2).ok_or_else(|| ApiError::bad("position : [lon, lat] attendu"))?;114            match (p[0].as_f64(), p[1].as_f64()) {115                (Some(lon), Some(lat)) if lon.is_finite() && lat.is_finite() && lon.abs() <= 180.0 && lat.abs() <= 90.0 => Ok((lon, lat)),116                _ => Err(ApiError::bad("position hors limites (lon ±180, lat ±90)")),117            }118        })119        .collect()120}121122fn polygon(rings: &Value, m: &mut Measure) -> Result<(), ApiError> {123    let rings = rings.as_array().ok_or_else(|| ApiError::bad("polygone : tableau d'anneaux attendu"))?;124    for (i, r) in rings.iter().enumerate() {125        let (per, area) = ring_measure(&coords(r, m)?);126        m.perimeter_m += per;127        // Premier anneau : extérieur ; les suivants sont des trous.128        m.area_m2 += if i == 0 { area } else { -area };129    }130    m.polygons += 1;131    Ok(())132}133134fn geometry(g: &Value, m: &mut Measure, depth: usize) -> Result<(), ApiError> {135    if depth > 4 {136        return Err(ApiError::bad("géométrie trop imbriquée"));137    }138    let t = g.get("type").and_then(|t| t.as_str()).ok_or_else(|| ApiError::bad("GeoJSON : « type » manquant"))?;139    let c = g.get("coordinates").unwrap_or(&Value::Null);140    match t {141        "Feature" => geometry(g.get("geometry").ok_or_else(|| ApiError::bad("Feature sans géométrie"))?, m, depth + 1)?,142        "FeatureCollection" => {143            let fs = g.get("features").and_then(|f| f.as_array()).ok_or_else(|| ApiError::bad("FeatureCollection sans « features »"))?;144            if fs.len() > 200 {145                return Err(ApiError::bad("trop d'entités (maximum 200)"));146            }147            for f in fs {148                geometry(f, m, depth + 1)?;149            }150        }151        "GeometryCollection" => {152            let gs = g.get("geometries").and_then(|f| f.as_array()).ok_or_else(|| ApiError::bad("GeometryCollection sans « geometries »"))?;153            if gs.len() > 200 {154                return Err(ApiError::bad("trop de géométries (maximum 200)"));155            }156            for x in gs {157                geometry(x, m, depth + 1)?;158            }159        }160        "LineString" => {161            m.length_m += line_length(&coords(c, m)?);162            m.lines += 1;163        }164        "MultiLineString" => {165            for l in c.as_array().ok_or_else(|| ApiError::bad("MultiLineString invalide"))? {166                m.length_m += line_length(&coords(l, m)?);167                m.lines += 1;168            }169        }170        "Polygon" => polygon(c, m)?,171        "MultiPolygon" => {172            for p in c.as_array().ok_or_else(|| ApiError::bad("MultiPolygon invalide"))? {173                polygon(p, m)?;174            }175        }176        "Point" | "MultiPoint" => {}177        _ => return Err(ApiError::bad("type GeoJSON non pris en charge")),178    }179    Ok(())180}181182pub fn measure_geojson(v: &Value) -> Result<Measure, ApiError> {183    let mut m = Measure::default();184    geometry(v, &mut m, 0)?;185    m.area_m2 = m.area_m2.max(0.0);186    Ok(m)187}188189/// `points=lon,lat;lon,lat;…` — `close=true` mesure le polygone fermé.190pub fn measure_points(points: &str, close: bool) -> Result<Measure, ApiError> {191    let mut pts = Vec::new();192    for part in points.split(';').filter(|p| !p.trim().is_empty()) {193        if pts.len() >= 2000 {194            return Err(ApiError::bad("trop de points (maximum 2000 en GET ; utiliser POST)"));195        }196        let (a, b) = part.split_once(',').ok_or_else(|| ApiError::bad("points : lon,lat;lon,lat;… attendu"))?;197        match (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {198            (Ok(lon), Ok(lat)) if lon.is_finite() && lat.is_finite() && lon.abs() <= 180.0 && lat.abs() <= 90.0 => pts.push((lon, lat)),199            _ => return Err(ApiError::bad("points : coordonnées invalides")),200        }201    }202    if pts.len() < 2 {203        return Err(ApiError::bad("points : au moins deux positions"));204    }205    let mut m = Measure { vertices: pts.len(), ..Default::default() };206    if close {207        if pts.len() < 3 {208            return Err(ApiError::bad("polygone : au moins trois positions"));209        }210        let (per, area) = ring_measure(&pts);211        m.perimeter_m = per;212        m.area_m2 = area;213        m.polygons = 1;214    } else {215        m.length_m = line_length(&pts);216        m.lines = 1;217    }218    Ok(m)219}220221pub fn to_json(m: &Measure) -> Value {222    let r3 = |v: f64| (v * 1000.0).round() / 1000.0;223    json!({224        "length_m": r3(m.length_m), "perimeter_m": r3(m.perimeter_m), "area_m2": r3(m.area_m2),225        "area_ha": r3(m.area_m2 / 10_000.0), "area_km2": (m.area_m2 / 1e6 * 1e6).round() / 1e6,226        "area_sqft": (m.area_m2 * 10.763_910_416_709_722).round(),227        "lines": m.lines, "polygons": m.polygons, "vertices": m.vertices,228        "method": "géodésique, ellipsoïde WGS 84 (Karney)",229    })230}231232#[cfg(test)]233mod tests {234    use super::*;235236    #[test]237    fn geojson_polygon_with_hole() {238        let outer = json!([[-73.60, 45.50], [-73.59, 45.50], [-73.59, 45.51], [-73.60, 45.51], [-73.60, 45.50]]);239        let hole = json!([[-73.598, 45.502], [-73.598, 45.504], [-73.596, 45.504], [-73.596, 45.502], [-73.598, 45.502]]);240        let full = measure_geojson(&json!({"type": "Polygon", "coordinates": [outer]})).unwrap();241        let holed = measure_geojson(&json!({"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [outer, hole]}})).unwrap();242        assert!((full.area_m2 - 866_600.0).abs() < 2000.0);243        let hole_area = full.area_m2 - holed.area_m2;244        assert!((hole_area - 34_670.0).abs() < 300.0, "{hole_area}");245        assert!(holed.perimeter_m > full.perimeter_m);246    }247248    #[test]249    fn geojson_lines_and_collections() {250        let m = measure_geojson(&json!({"type": "FeatureCollection", "features": [251            {"type": "Feature", "geometry": {"type": "LineString", "coordinates": [[-73.0, 45.0], [-73.0, 46.0]]}},252            {"type": "Feature", "geometry": {"type": "MultiLineString", "coordinates": [[[-73.0, 45.0], [-73.0, 46.0]]]}}253        ]})).unwrap();254        assert!((m.length_m - 2.0 * 111_141.5).abs() < 40.0);255        assert_eq!(m.lines, 2);256    }257258    #[test]259    fn rejects_bad_input() {260        assert!(measure_geojson(&json!({"coordinates": []})).is_err());261        assert!(measure_geojson(&json!({"type": "Polygon", "coordinates": "x"})).is_err());262        assert!(measure_geojson(&json!({"type": "LineString", "coordinates": [[0, 0], [0, 95]]})).is_err());263        assert!(measure_geojson(&json!({"type": "LineString", "coordinates": [[0], [0, 1]]})).is_err());264        assert!(measure_geojson(&json!({"type": "Circle", "coordinates": []})).is_err());265        let big: Vec<Value> = (0..MAX_VERTICES + 1).map(|i| json!([0.0, (i as f64) * 1e-6])).collect();266        assert!(measure_geojson(&json!({"type": "LineString", "coordinates": big})).is_err());267        assert!(measure_points("1,2", false).is_err());268        assert!(measure_points("a,b;1,2", false).is_err());269        assert!(measure_points("0,0;0,91", false).is_err());270    }271272    #[test]273    fn points_param() {274        let m = measure_points("-73,45;-73,46", false).unwrap();275        assert!((m.length_m - 111_141.5).abs() < 20.0);276        let m = measure_points("-73.60,45.50;-73.59,45.50;-73.59,45.51;-73.60,45.51", true).unwrap();277        assert!((m.area_m2 - 866_600.0).abs() < 2000.0);278    }279}280
Files main
Menu

Theme