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/iso.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//! Isochrone : du résultat d'un Dijkstra borné à un polygone.88//!89//! Les tronçons atteints (y compris la partie atteinte d'un tronçon coupé par la limite de temps) sont tracés sur90//! une grille, épaissis d'une marge (les bâtiments bordent la rue), les cours intérieures sont comblées, puis le91//! contour extérieur de la plus grande zone est suivi et simplifié. Une rivière sans pont reste donc infranchie :92//! aucune cellule n'est remplie là où aucune voie n'est atteinte.9394use crate::graph::{Graph, Profile, Scratch};9596pub struct IsoRing {97 /// Anneau extérieur fermé (lon, lat), sens antihoraire.98 pub ring: Vec<(f64, f64)>,99 pub area_km2: f64,100 pub cell_m: f64,101 pub parts: usize,102 pub reached_nodes: usize,103}104105fn margin_m(p: Profile) -> f64 {106 match p {107 Profile::Walking => 40.0,108 Profile::Cycling => 60.0,109 Profile::Driving => 120.0,110 }111}112113fn min_cell_m(p: Profile) -> f64 {114 match p {115 Profile::Walking => 12.0,116 Profile::Cycling => 25.0,117 Profile::Driving => 50.0,118 }119}120121pub fn polygon(g: &Graph, s: &Scratch, profile: Profile, t_ms: u32, origin: (f64, f64), max_vertices: usize) -> Option<IsoRing> {122 let (lon0, lat0) = origin;123 let kx = 111_320.0 * lat0.to_radians().cos();124 let ky = 110_574.0;125 let xy = |v: u32| -> (f64, f64) {126 let (lon, lat) = g.pos(v);127 ((lon - lon0) * kx, (lat - lat0) * ky)128 };129 // Emprise des sommets atteints dans le temps voulu130 let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);131 let mut reached = 0usize;132 for &v in &s.touched {133 if s.dist[v as usize] <= t_ms {134 let (x, y) = xy(v);135 x0 = x0.min(x);136 y0 = y0.min(y);137 x1 = x1.max(x);138 y1 = y1.max(y);139 reached += 1;140 }141 }142 if reached == 0 {143 return None;144 }145 let extent = (x1 - x0).max(y1 - y0).max(1.0);146 let cell = (extent / 360.0).max(min_cell_m(profile));147 let dil = (margin_m(profile) / cell).ceil().max(1.0) as usize;148 // Marge : la partie atteinte d'un tronçon peut dépasser l'emprise des sommets, plus l'épaississement.149 let pad = dil + 3 + (600.0 / cell).ceil().min(40.0) as usize;150 let w = ((x1 - x0) / cell).ceil() as usize + 2 * pad + 1;151 let h = ((y1 - y0) / cell).ceil() as usize + 2 * pad + 1;152 if w * h > 4_000_000 {153 return None;154 }155 let ox = x0 - pad as f64 * cell;156 let oy = y0 - pad as f64 * cell;157 let mut grid = vec![0u8; w * h];158 let mark = |x: f64, y: f64, grid: &mut Vec<u8>| {159 let i = ((x - ox) / cell).floor();160 let j = ((y - oy) / cell).floor();161 if i >= 0.0 && j >= 0.0 && (i as usize) < w && (j as usize) < h {162 grid[j as usize * w + i as usize] = 1;163 }164 };165 for &u in &s.touched {166 let du = s.dist[u as usize];167 if du > t_ms {168 continue;169 }170 let (ux, uy) = xy(u);171 mark(ux, uy, &mut grid);172 for e in g.off[u as usize] as usize..g.off[u as usize + 1] as usize {173 let Some(c) = g.cost_ms(e, profile) else { continue };174 let v = g.to[e];175 let frac = (((t_ms - du) as f64) / c as f64).min(1.0);176 if frac <= 0.0 {177 continue;178 }179 let (vx, vy) = xy(v);180 let (ex, ey) = (ux + (vx - ux) * frac, uy + (vy - uy) * frac);181 let len = ((ex - ux).powi(2) + (ey - uy).powi(2)).sqrt();182 let steps = (len / (cell * 0.5)).ceil().max(1.0) as usize;183 for k in 1..=steps {184 let t = k as f64 / steps as f64;185 mark(ux + (ex - ux) * t, uy + (ey - uy) * t, &mut grid);186 }187 }188 }189 // Épaississement (disque approché par passes 4-voisins / 8-voisins alternées)190 for pass in 0..dil {191 let src = grid.clone();192 for j in 1..h - 1 {193 for i in 1..w - 1 {194 if src[j * w + i] != 0 {195 continue;196 }197 let n4 = src[j * w + i - 1] | src[j * w + i + 1] | src[(j - 1) * w + i] | src[(j + 1) * w + i];198 let n8 = src[(j - 1) * w + i - 1] | src[(j - 1) * w + i + 1] | src[(j + 1) * w + i - 1] | src[(j + 1) * w + i + 1];199 if n4 != 0 || (pass % 2 == 1 && n8 != 0) {200 grid[j * w + i] = 1;201 }202 }203 }204 }205 // Comble les cours intérieures : tout ce que l'extérieur n'atteint pas est dedans.206 let mut stack: Vec<usize> = Vec::new();207 for i in 0..w {208 stack.push(i);209 stack.push((h - 1) * w + i);210 }211 for j in 0..h {212 stack.push(j * w);213 stack.push(j * w + w - 1);214 }215 while let Some(k) = stack.pop() {216 if grid[k] != 0 {217 continue;218 }219 grid[k] = 2; // extérieur220 let (i, j) = (k % w, k / w);221 if i > 0 { stack.push(k - 1); }222 if i + 1 < w { stack.push(k + 1); }223 if j > 0 { stack.push(k - w); }224 if j + 1 < h { stack.push(k + w); }225 }226 for c in grid.iter_mut() {227 *c = if *c == 2 { 0 } else { 1 };228 }229 // Plus grande zone 4-connexe230 let mut label = vec![0u32; w * h];231 let mut best = (0usize, 0u32);232 let mut parts = 0u32;233 for start in 0..w * h {234 if grid[start] == 0 || label[start] != 0 {235 continue;236 }237 parts += 1;238 let mut size = 0usize;239 stack.clear();240 stack.push(start);241 label[start] = parts;242 while let Some(k) = stack.pop() {243 size += 1;244 let (i, j) = (k % w, k / w);245 let mut go = |n: usize, stack: &mut Vec<usize>| {246 if grid[n] != 0 && label[n] == 0 {247 label[n] = parts;248 stack.push(n);249 }250 };251 if i > 0 { go(k - 1, &mut stack); }252 if i + 1 < w { go(k + 1, &mut stack); }253 if j > 0 { go(k - w, &mut stack); }254 if j + 1 < h { go(k + w, &mut stack); }255 }256 if size > best.0 {257 best = (size, parts);258 }259 }260 if best.0 == 0 {261 return None;262 }263 let filled = |i: i64, j: i64| -> bool { i >= 0 && j >= 0 && (i as usize) < w && (j as usize) < h && label[j as usize * w + i as usize] == best.1 };264 // Suivi du contour extérieur sur les coins de cellules, intérieur à gauche (sens antihoraire).265 let start_cell = (0..w * h).find(|&k| label[k] == best.1)?; // la plus au sud, puis la plus à l'ouest266 let (sx, sy) = ((start_cell % w) as i64, (start_cell / w) as i64);267 let dirs: [(i64, i64); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)]; // est, nord, ouest, sud268 let cells_ahead = |x: i64, y: i64, d: usize| -> ((i64, i64), (i64, i64)) {269 match d {270 0 => ((x, y), (x, y - 1)),271 1 => ((x - 1, y), (x, y)),272 2 => ((x - 1, y - 1), (x - 1, y)),273 _ => ((x, y - 1), (x - 1, y - 1)),274 }275 };276 let (mut x, mut y, mut d) = (sx, sy, 0usize);277 let mut pts: Vec<(f64, f64)> = Vec::new();278 let limit = 8 * (w + h) * 40 + 4 * w * h;279 let mut steps = 0usize;280 loop {281 let (fl, fr) = cells_ahead(x, y, d);282 let nd = if !filled(fl.0, fl.1) {283 (d + 1) % 4 // à gauche284 } else if !filled(fr.0, fr.1) {285 d // tout droit286 } else {287 (d + 3) % 4 // à droite288 };289 if steps > 0 && (x, y) == (sx, sy) && nd == 0 {290 break;291 }292 if nd != d || pts.is_empty() {293 pts.push((ox + x as f64 * cell, oy + y as f64 * cell));294 }295 d = nd;296 x += dirs[d].0;297 y += dirs[d].1;298 steps += 1;299 if steps > limit {300 break;301 }302 }303 if pts.len() < 4 || steps > limit {304 return None;305 }306 // Simplification (Douglas-Peucker en mètres), tolérance relevée jusqu'à respecter max_vertices307 let mut tol = cell * 0.75;308 let mut ring = simplify_ring(&pts, tol);309 let mut guard = 0;310 while ring.len() > max_vertices && guard < 40 {311 tol *= 1.35;312 ring = simplify_ring(&pts, tol);313 guard += 1;314 }315 if ring.len() < 3 {316 return None;317 }318 let mut area2 = 0.0;319 for k in 0..ring.len() {320 let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);321 area2 += a.0 * b.1 - b.0 * a.1;322 }323 let mut out: Vec<(f64, f64)> = ring.iter().map(|(x, y)| (lon0 + x / kx, lat0 + y / ky)).collect();324 out.push(out[0]);325 Some(IsoRing { ring: out, area_km2: (area2 / 2.0).abs() / 1e6, cell_m: cell, parts: parts as usize, reached_nodes: reached })326}327328fn simplify_ring(pts: &[(f64, f64)], tol: f64) -> Vec<(f64, f64)> {329 // Coupe l'anneau en deux arcs entre le premier point et le point le plus éloigné, simplifie chacun.330 let n = pts.len();331 let far = (0..n)332 .max_by(|&a, &b| {333 let da = (pts[a].0 - pts[0].0).powi(2) + (pts[a].1 - pts[0].1).powi(2);334 let db = (pts[b].0 - pts[0].0).powi(2) + (pts[b].1 - pts[0].1).powi(2);335 da.partial_cmp(&db).unwrap()336 })337 .unwrap_or(0);338 if far == 0 {339 return pts.to_vec();340 }341 let mut a = dp(&pts[0..=far], tol);342 let mut second: Vec<(f64, f64)> = pts[far..].to_vec();343 second.push(pts[0]);344 let b = dp(&second, tol);345 a.pop();346 a.extend_from_slice(&b[..b.len() - 1]);347 a348}349350fn dp(pts: &[(f64, f64)], tol: f64) -> Vec<(f64, f64)> {351 let n = pts.len();352 if n <= 2 {353 return pts.to_vec();354 }355 let mut keep = vec![false; n];356 keep[0] = true;357 keep[n - 1] = true;358 let mut stack = vec![(0usize, n - 1)];359 while let Some((a, b)) = stack.pop() {360 if b <= a + 1 {361 continue;362 }363 let (ax, ay) = pts[a];364 let (bx, by) = pts[b];365 let (dx, dy) = (bx - ax, by - ay);366 let l2 = dx * dx + dy * dy;367 let mut best = (0.0, a);368 for k in a + 1..b {369 let (px, py) = pts[k];370 let d = if l2 == 0.0 {371 ((px - ax).powi(2) + (py - ay).powi(2)).sqrt()372 } else {373 let t = (((px - ax) * dx + (py - ay) * dy) / l2).clamp(0.0, 1.0);374 ((px - ax - t * dx).powi(2) + (py - ay - t * dy).powi(2)).sqrt()375 };376 if d > best.0 {377 best = (d, k);378 }379 }380 if best.0 > tol {381 keep[best.1] = true;382 stack.push((a, best.1));383 stack.push((best.1, b));384 }385 }386 pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect()387}388389/// Simplifie une polyligne (lon, lat) à une tolérance en mètres.390pub fn simplify_line(pts: &[(f64, f64)], tol_m: f64) -> Vec<(f64, f64)> {391 if pts.len() <= 2 {392 return pts.to_vec();393 }394 let lat0 = pts[0].1;395 let kx = 111_320.0 * lat0.to_radians().cos();396 let ky = 110_574.0;397 let m: Vec<(f64, f64)> = pts.iter().map(|(lon, lat)| (lon * kx, lat * ky)).collect();398 dp(&m, tol_m).iter().map(|(x, y)| (x / kx, y / ky)).collect()399}400401#[allow(dead_code)]402pub fn point_in_ring(ring: &[(f64, f64)], p: (f64, f64)) -> bool {403 let mut inside = false;404 let n = ring.len();405 let mut j = n - 1;406 for i in 0..n {407 let (xi, yi) = ring[i];408 let (xj, yj) = ring[j];409 if (yi > p.1) != (yj > p.1) && p.0 < (xj - xi) * (p.1 - yi) / (yj - yi) + xi {410 inside = !inside;411 }412 j = i;413 }414 inside415}416417#[cfg(test)]418mod tests {419 use super::*;420 use crate::graph::tests::grid_graph;421422 #[test]423 fn walking_isochrone_on_a_grid() {424 let g = grid_graph(41, 41, 40, &|_, _, _, _| false);425 let mut s = Scratch::new(g.n());426 let src = (20 * 41 + 20) as u32;427 g.reach(src, Profile::Walking, 15 * 60_000, &mut s);428 let origin = g.pos(src);429 let iso = polygon(&g, &s, Profile::Walking, 15 * 60_000, origin, 180).unwrap();430 assert!(iso.ring.len() <= 181 && iso.ring.len() >= 5, "{}", iso.ring.len());431 assert_eq!(iso.ring.first(), iso.ring.last());432 assert!(point_in_ring(&iso.ring, origin));433 // Sur une grille de 100 m, 1 200 m de marche donnent un losange de diagonale 2,4 km : 2,88 km² (+ marge)434 assert!(iso.area_km2 > 2.7 && iso.area_km2 < 3.6, "{}", iso.area_km2);435 // 1,15 km à l'est le long de la rue : dedans ; 1,35 km : dehors436 let dlon = 1.0 / (111_320.0 * origin.1.to_radians().cos());437 assert!(point_in_ring(&iso.ring, (origin.0 + 1150.0 * dlon, origin.1)));438 assert!(!point_in_ring(&iso.ring, (origin.0 + 1350.0 * dlon, origin.1)));439 // sens antihoraire (aire signée positive)440 let a: f64 = iso.ring.windows(2).map(|w| w[0].0 * w[1].1 - w[1].0 * w[0].1).sum();441 assert!(a > 0.0);442 }443444 #[test]445 fn isochrone_stops_at_a_river() {446 // Pas de pont entre les colonnes 10 et 11 : la rive est (x ≥ 11) reste dehors.447 let g = grid_graph(21, 21, 40, &|ax, _, bx, _| (ax == 10 && bx == 11) || (ax == 11 && bx == 10));448 let mut s = Scratch::new(g.n());449 let src = (10 * 21 + 9) as u32;450 g.reach(src, Profile::Walking, 30 * 60_000, &mut s);451 let iso = polygon(&g, &s, Profile::Walking, 30 * 60_000, g.pos(src), 400).unwrap();452 assert!(point_in_ring(&iso.ring, g.pos((10 * 21 + 10) as u32)), "rive ouest dedans");453 assert!(!point_in_ring(&iso.ring, g.pos((10 * 21 + 11) as u32)), "rive est dehors");454 assert!(!point_in_ring(&iso.ring, g.pos((10 * 21 + 14) as u32)));455 }456457 #[test]458 fn max_vertices_is_respected() {459 let g = grid_graph(41, 41, 40, &|_, _, _, _| false);460 let mut s = Scratch::new(g.n());461 let src = (20 * 41 + 20) as u32;462 g.reach(src, Profile::Walking, 15 * 60_000, &mut s);463 for mv in [12usize, 40, 180] {464 let iso = polygon(&g, &s, Profile::Walking, 15 * 60_000, g.pos(src), mv).unwrap();465 assert!(iso.ring.len() - 1 <= mv, "{} > {mv}", iso.ring.len() - 1);466 }467 }468469 #[test]470 fn line_simplification() {471 let l = [(-73.6, 45.5), (-73.5999, 45.50000001), (-73.5998, 45.5), (-73.5998, 45.501)];472 let s = simplify_line(&l, 2.0);473 assert_eq!(s.len(), 3);474 assert_eq!(s[0], l[0]);475 }476}477