Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-geo/src/routing.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//! `GET /v1/isochrone` et `GET /v1/route` — sur le réseau en mémoire (voir graph.rs, iso.rs).8889use crate::err::ApiError;90use crate::geom::round6;91use crate::graph::{Graph, Profile, Scratch};92use crate::iso;93use serde_json::{json, Value};94use std::collections::HashMap;95use std::sync::{Arc, Mutex};96use std::time::{Duration, Instant};9798pub const NOTICE: &str = "Temps estimés sans la circulation, d'après le réseau OpenStreetMap et des vitesses types par catégorie de voie ; sans feux, virages ni traversiers.";99pub const ATTRIBUTION: &str = "© les contributeurs d'OpenStreetMap (ODbL)";100const CACHE_TTL: Duration = Duration::from_secs(3600);101const CACHE_CAP: usize = 4000;102103pub struct Routing {104 pub graph: Arc<Graph>,105 scratch: Mutex<Vec<Scratch>>,106 pub sem: Arc<tokio::sync::Semaphore>,107 cache: Mutex<HashMap<String, (Instant, Arc<Value>)>>,108}109110impl Routing {111 pub fn new(graph: Graph, workers: usize) -> Self {112 Self { graph: Arc::new(graph), scratch: Mutex::new(Vec::new()), sem: Arc::new(tokio::sync::Semaphore::new(workers)), cache: Mutex::new(HashMap::new()) }113 }114 fn take(&self) -> Scratch {115 self.scratch.lock().unwrap().pop().unwrap_or_else(|| Scratch::new(self.graph.n()))116 }117 fn give(&self, mut s: Scratch) {118 s.reset();119 let mut pool = self.scratch.lock().unwrap();120 if pool.len() < 6 {121 pool.push(s);122 }123 }124 fn cache_get(&self, key: &str) -> Option<Arc<Value>> {125 let c = self.cache.lock().unwrap();126 c.get(key).filter(|(t, _)| t.elapsed() < CACHE_TTL).map(|(_, v)| v.clone())127 }128 fn cache_put(&self, key: String, v: Arc<Value>) {129 let mut c = self.cache.lock().unwrap();130 if c.len() >= CACHE_CAP {131 c.retain(|_, (t, _)| t.elapsed() < CACHE_TTL);132 if c.len() >= CACHE_CAP {133 c.clear();134 }135 }136 c.insert(key, (Instant::now(), v));137 }138 pub fn cache_len(&self) -> usize {139 self.cache.lock().unwrap().len()140 }141}142143fn snap_radius(p: Profile) -> f64 {144 match p {145 Profile::Driving => 700.0,146 _ => 400.0,147 }148}149150pub struct IsoParams {151 pub lon: f64,152 pub lat: f64,153 pub profile: Profile,154 /// Minutes, triées en ordre décroissant.155 pub minutes: Vec<f64>,156 pub max_vertices: usize,157}158159/// Calcul synchrone (à lancer hors de l'exécuteur). L'origine est arrondie à 4 décimales (≈ 10 m) : c'est la clé de cache.160pub fn isochrone(r: &Routing, p: &IsoParams) -> Result<Arc<Value>, ApiError> {161 let lon = (p.lon * 1e4).round() / 1e4;162 let lat = (p.lat * 1e4).round() / 1e4;163 let key = format!("{}|{lon:.4}|{lat:.4}|{:?}|{}", p.profile.name(), p.minutes, p.max_vertices);164 if let Some(v) = r.cache_get(&key) {165 return Ok(v);166 }167 let g = &r.graph;168 let Some((src, snap_d)) = g.snap(lon, lat, p.profile, snap_radius(p.profile)) else {169 return Err(ApiError::not_found("Aucune voie praticable pour ce mode à proximité du point."));170 };171 let tmax = (p.minutes[0] * 60_000.0).round() as u32;172 let mut s = r.take();173 g.reach(src, p.profile, tmax, &mut s);174 let origin = g.pos(src);175 let mut features = Vec::new();176 for m in &p.minutes {177 let t = (m * 60_000.0).round() as u32;178 if let Some(iso) = iso::polygon(g, &s, p.profile, t, origin, p.max_vertices) {179 let ring: Vec<Value> = iso.ring.iter().map(|(x, y)| json!([round6(*x), round6(*y)])).collect();180 features.push(json!({181 "type": "Feature",182 "properties": {183 "minutes": m, "contour": m, "profile": p.profile.name(),184 "area_km2": (iso.area_km2 * 1000.0).round() / 1000.0,185 "vertices": iso.ring.len() - 1, "grid_m": (iso.cell_m * 10.0).round() / 10.0,186 "reached_nodes": iso.reached_nodes, "parts_dropped": iso.parts.saturating_sub(1),187 },188 "geometry": { "type": "Polygon", "coordinates": [ring] },189 }));190 }191 }192 r.give(s);193 if features.is_empty() {194 return Err(ApiError::not_found("Isochrone vide en ce point."));195 }196 let v = Arc::new(json!({197 "type": "FeatureCollection",198 "features": features,199 "origin": { "lon": round6(origin.0), "lat": round6(origin.1), "snap_distance_m": snap_d.round() },200 "profile": p.profile.name(),201 "notice": NOTICE,202 "attribution": ATTRIBUTION,203 }));204 r.cache_put(key, v.clone());205 Ok(v)206}207208pub fn route(r: &Routing, from: (f64, f64), to: (f64, f64), profile: Profile) -> Result<Value, ApiError> {209 let g = &r.graph;210 let (Some((a, da)), Some((b, db))) = (g.snap(from.0, from.1, profile, snap_radius(profile)), g.snap(to.0, to.1, profile, snap_radius(profile))) else {211 return Err(ApiError::not_found("Aucune voie praticable pour ce mode à proximité du départ ou de l'arrivée."));212 };213 let mut s = r.take();214 let res = g.route(a, b, profile, 8_000_000, &mut s);215 r.give(s);216 let Some((ms, dist, path)) = res else {217 return Err(ApiError::not_found("Aucun trajet trouvé pour ce mode (réseau non relié, ou trajet trop long)."));218 };219 let pts: Vec<(f64, f64)> = path.iter().map(|v| g.pos(*v)).collect();220 let mut tol = 2.0;221 let mut line = iso::simplify_line(&pts, tol);222 while line.len() > 4000 {223 tol *= 2.0;224 line = iso::simplify_line(&pts, tol);225 }226 let coords: Vec<Value> = line.iter().map(|(x, y)| json!([round6(*x), round6(*y)])).collect();227 let (pa, pb) = (g.pos(a), g.pos(b));228 Ok(json!({229 "profile": profile.name(),230 "distance_m": dist.round(),231 "duration_s": (ms as f64 / 1000.0).round(),232 "duration_min": (ms as f64 / 6000.0).round() / 10.0,233 "geometry": { "type": "LineString", "coordinates": coords },234 "from": { "lon": round6(pa.0), "lat": round6(pa.1), "snap_distance_m": da.round() },235 "to": { "lon": round6(pb.0), "lat": round6(pb.1), "snap_distance_m": db.round() },236 "notice": NOTICE,237 "attribution": ATTRIBUTION,238 }))239}240241/// `minutes=15` ou `minutes=10,20,30` (quatre valeurs au plus, 1 à 60).242pub fn parse_minutes(s: &str) -> Result<Vec<f64>, ApiError> {243 let mut v = Vec::new();244 for part in s.split(',') {245 let m: f64 = part.trim().parse().map_err(|_| ApiError::bad("minutes : nombre(s) attendu(s), séparés par des virgules"))?;246 if !m.is_finite() || !(1.0..=60.0).contains(&m) {247 return Err(ApiError::bad("minutes : de 1 à 60"));248 }249 let m = (m * 10.0).round() / 10.0;250 if !v.contains(&m) {251 v.push(m);252 }253 }254 if v.is_empty() || v.len() > 4 {255 return Err(ApiError::bad("minutes : une à quatre valeurs"));256 }257 v.sort_by(|a, b| b.partial_cmp(a).unwrap());258 Ok(v)259}260261#[cfg(test)]262mod tests {263 use super::*;264 use crate::graph::tests::grid_graph;265266 #[test]267 fn minutes_param() {268 assert_eq!(parse_minutes("15").unwrap(), vec![15.0]);269 assert_eq!(parse_minutes("10, 30,20,10").unwrap(), vec![30.0, 20.0, 10.0]);270 assert!(parse_minutes("0").is_err());271 assert!(parse_minutes("61").is_err());272 assert!(parse_minutes("5,10,15,20,25").is_err());273 assert!(parse_minutes("abc").is_err());274 assert!(parse_minutes("NaN").is_err());275 }276277 #[test]278 fn isochrone_end_to_end_and_cache() {279 let r = Routing::new(grid_graph(41, 41, 40, &|_, _, _, _| false), 2);280 let (lon, lat) = r.graph.pos((20 * 41 + 20) as u32);281 let p = IsoParams { lon, lat, profile: Profile::Walking, minutes: vec![15.0, 5.0], max_vertices: 180 };282 let v = isochrone(&r, &p).unwrap();283 let f = v["features"].as_array().unwrap();284 assert_eq!(f.len(), 2);285 assert_eq!(f[0]["properties"]["minutes"], 15.0);286 assert!(f[0]["properties"]["area_km2"].as_f64().unwrap() > f[1]["properties"]["area_km2"].as_f64().unwrap());287 assert_eq!(f[0]["geometry"]["type"], "Polygon");288 assert!(v["notice"].as_str().unwrap().contains("sans la circulation"));289 assert_eq!(r.cache_len(), 1);290 // Même origine à quelques mètres près : même entrée de cache (pointeur identique)291 let p2 = IsoParams { lon: lon + 0.00002, lat, profile: Profile::Walking, minutes: vec![15.0, 5.0], max_vertices: 180 };292 assert!(Arc::ptr_eq(&v, &isochrone(&r, &p2).unwrap()));293 // Loin de tout réseau294 let far = IsoParams { lon: -70.0, lat: 50.0, profile: Profile::Walking, minutes: vec![15.0], max_vertices: 180 };295 assert!(isochrone(&r, &far).is_err());296 }297298 #[test]299 fn route_end_to_end() {300 let r = Routing::new(grid_graph(21, 21, 36, &|_, _, _, _| false), 2);301 let (a, b) = (r.graph.pos(0), r.graph.pos((20 * 21 + 20) as u32));302 let v = route(&r, a, b, Profile::Driving).unwrap();303 assert!((v["distance_m"].as_f64().unwrap() - 4000.0).abs() < 5.0);304 assert_eq!(v["duration_s"], 400.0);305 assert!(v["geometry"]["coordinates"].as_array().unwrap().len() >= 2);306 }307}308