SPB Git

Repository Public

graph_build.rs 16.9 KB 411 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/graph_build.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//! `km-geo graph-build <extrait.osm.pbf> <graphe.bin>` — construit le réseau routier depuis un extrait OSM.88//!89//! Règles (résumé ; détail dans docs/GEOGRAPHIC_DATA.md) :90//! - à pied : tout sauf autoroutes, voies rapides sans trottoir, `foot=no`, accès privé ; 4,8 km/h (escaliers : moitié) ;91//! - à vélo : tout sauf autoroutes, escaliers, trottoirs et zones piétonnes sans `bicycle=yes`, `bicycle=no` ;92//!   sens uniques respectés sauf contresens cyclable ; 16 km/h (10 km/h sur sentier ou non revêtu) ;93//! - en auto : voies carrossables, sens uniques et giratoires, `access`/`motor_vehicle` ; vitesse = `maxspeed` s'il94//!   existe, sinon défaut par classe, multipliée par un facteur d'écoulement libre (pas de circulation, pas de feux).95//! Les traversiers ne sont pas dans le réseau : une île sans pont n'est pas atteinte.9697use crate::graph::{haversine_m, Graph, RawEdge, F_BIKE, F_BIKE_SLOW, F_FOOT, F_FOOT_SLOW};98use osmpbf::{Element, ElementReader};99use std::collections::HashMap;100101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]102pub struct WayAttr {103    pub car_fwd: u8,104    pub car_bwd: u8,105    pub flags_fwd: u8,106    pub flags_bwd: u8,107}108109fn yes(v: Option<&&str>) -> bool {110    matches!(v.copied(), Some("yes" | "designated" | "permissive" | "official" | "destination" | "customers"))111}112113fn no(v: Option<&&str>) -> bool {114    matches!(v.copied(), Some("no" | "private" | "agricultural" | "forestry" | "military" | "delivery" | "emergency"))115}116117fn parse_maxspeed(s: &str) -> Option<f32> {118    let s = s.trim();119    let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();120    let v: f32 = digits.parse().ok()?;121    if !(5.0..=130.0).contains(&v) {122        return None;123    }124    Some(if s.contains("mph") { v * 1.609 } else { v })125}126127/// Classe la voie ; `None` si elle n'entre pas dans le réseau.128pub fn classify(t: &HashMap<&str, &str>) -> Option<WayAttr> {129    let hw = *t.get("highway")?;130    // (auto permise, vitesse par défaut km/h, facteur d'écoulement libre)131    let (car_ok, def_kmh, factor): (bool, f32, f32) = match hw {132        "motorway" => (true, 100.0, 0.95),133        "motorway_link" => (true, 60.0, 0.90),134        "trunk" => (true, 90.0, 0.90),135        "trunk_link" => (true, 50.0, 0.90),136        "primary" => (true, 60.0, 0.82),137        "primary_link" => (true, 45.0, 0.85),138        "secondary" => (true, 55.0, 0.82),139        "secondary_link" => (true, 40.0, 0.85),140        "tertiary" => (true, 50.0, 0.80),141        "tertiary_link" => (true, 40.0, 0.85),142        "unclassified" | "road" => (true, 50.0, 0.80),143        "residential" => (true, 40.0, 0.75),144        "living_street" => (true, 15.0, 0.80),145        "service" => (true, 20.0, 0.70),146        "pedestrian" | "track" | "path" | "footway" | "cycleway" | "steps" | "bridleway" => (false, 0.0, 0.0),147        _ => return None,148    };149    if t.get("area").map(|v| *v == "yes").unwrap_or(false) && hw != "pedestrian" {150        return None;151    }152    let access_no = no(t.get("access"));153    let unpaved = matches!(154        t.get("surface").copied(),155        Some("unpaved" | "gravel" | "dirt" | "ground" | "earth" | "sand" | "grass" | "mud" | "fine_gravel" | "compacted" | "pebblestone" | "wood")156    );157158    // --- auto ---159    let mut car = car_ok;160    for k in ["vehicle", "motor_vehicle", "motorcar"] {161        if no(t.get(k)) {162            car = false;163        } else if yes(t.get(k)) && car_ok {164            car = true;165        }166    }167    if access_no && !["vehicle", "motor_vehicle", "motorcar"].iter().any(|k| yes(t.get(k))) {168        car = false;169    }170    let mut kmh = t.get("maxspeed").and_then(|s| parse_maxspeed(s)).unwrap_or(def_kmh);171    if unpaved {172        kmh = kmh.min(50.0) * 0.8;173    }174    let car_kmh = (kmh * factor).round().clamp(5.0, 120.0) as u8;175    let roundabout = matches!(t.get("junction").copied(), Some("roundabout" | "circular"));176    let ow = t.get("oneway").copied().unwrap_or("");177    let (ow_fwd, ow_bwd) = match ow {178        "yes" | "1" | "true" => (true, false),179        "-1" | "reverse" => (false, true),180        "no" | "0" | "false" => (true, true),181        _ if hw == "motorway" || hw == "motorway_link" || roundabout => (true, false),182        _ => (true, true),183    };184185    // --- piéton ---186    let sidewalk = matches!(t.get("sidewalk").copied(), Some("both" | "left" | "right" | "yes" | "separate"));187    let mut foot = match hw {188        "motorway" | "motorway_link" => false,189        "trunk" | "trunk_link" => sidewalk,190        "bridleway" => false,191        _ => true,192    };193    if t.get("motorroad").map(|v| *v == "yes").unwrap_or(false) {194        foot = false;195    }196    if no(t.get("foot")) {197        foot = false;198    } else if yes(t.get("foot")) {199        foot = true;200    } else if access_no {201        foot = false;202    }203204    // --- vélo ---205    let mut bike = match hw {206        "motorway" | "motorway_link" | "steps" | "bridleway" => false,207        "footway" | "pedestrian" => false,208        "trunk" | "trunk_link" => !t.get("motorroad").map(|v| *v == "yes").unwrap_or(false),209        _ => true,210    };211    let b = t.get("bicycle");212    if no(b) || matches!(b.copied(), Some("dismount" | "use_sidepath")) {213        bike = false;214    } else if yes(b) && !matches!(hw, "motorway" | "motorway_link" | "steps") {215        bike = true;216    } else if access_no {217        bike = false;218    }219    let bike_slow = unpaved || matches!(hw, "path" | "track" | "footway" | "pedestrian");220    let contraflow = matches!(t.get("oneway:bicycle").copied(), Some("no"))221        || ["cycleway", "cycleway:left", "cycleway:right", "cycleway:both"]222            .iter()223            .any(|k| t.get(k).map(|v| v.starts_with("opposite")).unwrap_or(false));224    let (bike_fwd, bike_bwd) = if contraflow { (true, true) } else { (ow_fwd, ow_bwd) };225226    let mut a = WayAttr::default();227    if car {228        if ow_fwd { a.car_fwd = car_kmh; }229        if ow_bwd { a.car_bwd = car_kmh; }230    }231    let foot_flags = if foot { F_FOOT | if hw == "steps" { F_FOOT_SLOW } else { 0 } } else { 0 };232    let bike_flags = if bike { F_BIKE | if bike_slow { F_BIKE_SLOW } else { 0 } } else { 0 };233    a.flags_fwd = foot_flags | if bike_fwd { bike_flags } else { 0 };234    a.flags_bwd = foot_flags | if bike_bwd { bike_flags } else { 0 };235    if a == WayAttr::default() {236        return None;237    }238    Some(a)239}240241pub fn build(pbf: &str, out: &str) -> Result<(), Box<dyn std::error::Error>> {242    let t0 = std::time::Instant::now();243    // Passe 1 : voies du réseau244    let mut refs: Vec<i64> = Vec::new();245    let mut ways: Vec<(u32, u32, WayAttr)> = Vec::new(); // (début dans refs, longueur, attributs)246    ElementReader::from_path(pbf)?.for_each(|el| {247        if let Element::Way(w) = el {248            let tags: HashMap<&str, &str> = w.tags().collect();249            if !tags.contains_key("highway") {250                return;251            }252            if let Some(a) = classify(&tags) {253                let start = refs.len() as u32;254                refs.extend(w.refs());255                let len = refs.len() as u32 - start;256                if len >= 2 {257                    ways.push((start, len, a));258                } else {259                    refs.truncate(start as usize);260                }261            }262        }263    })?;264    eprintln!("passe 1 : {} voies, {} références de nœuds ({:.0} s)", ways.len(), refs.len(), t0.elapsed().as_secs_f64());265    let mut ids = refs.clone();266    ids.sort_unstable();267    ids.dedup();268    let n = ids.len();269    // Passe 2 : coordonnées des nœuds utilisés270    let mut lon = vec![i32::MIN; n];271    let mut lat = vec![i32::MIN; n];272    {273        let mut set = |id: i64, lo: f64, la: f64| {274            if let Ok(i) = ids.binary_search(&id) {275                lon[i] = (lo * 1e7).round() as i32;276                lat[i] = (la * 1e7).round() as i32;277            }278        };279        ElementReader::from_path(pbf)?.for_each(|el| match el {280            Element::DenseNode(nd) => set(nd.id(), nd.lon(), nd.lat()),281            Element::Node(nd) => set(nd.id(), nd.lon(), nd.lat()),282            _ => {}283        })?;284    }285    eprintln!("passe 2 : {} sommets ({:.0} s)", n, t0.elapsed().as_secs_f64());286    let mut edges: Vec<RawEdge> = Vec::with_capacity(refs.len() * 2);287    let mut skipped = 0usize;288    for (start, len, a) in &ways {289        let r = &refs[*start as usize..(*start + *len) as usize];290        let mut prev: Option<usize> = None;291        for id in r {292            let i = ids.binary_search(id).unwrap();293            if lon[i] == i32::MIN {294                prev = None; // nœud hors de l'extrait295                skipped += 1;296                continue;297            }298            if let Some(p) = prev {299                if p != i {300                    let d = haversine_m(lon[p] as f64 * 1e-7, lat[p] as f64 * 1e-7, lon[i] as f64 * 1e-7, lat[i] as f64 * 1e-7) as f32;301                    let d = d.max(0.1);302                    if a.car_fwd > 0 || a.flags_fwd != 0 {303                        edges.push(RawEdge { from: p as u32, to: i as u32, len: d, car: a.car_fwd, flags: a.flags_fwd });304                    }305                    if a.car_bwd > 0 || a.flags_bwd != 0 {306                        edges.push(RawEdge { from: i as u32, to: p as u32, len: d, car: a.car_bwd, flags: a.flags_bwd });307                    }308                }309            }310            prev = Some(i);311        }312    }313    drop(refs);314    for i in 0..n {315        if lon[i] == i32::MIN {316            lon[i] = 0;317            lat[i] = 0;318        }319    }320    eprintln!("{} arêtes orientées, {} nœuds hors extrait ({:.0} s)", edges.len(), skipped, t0.elapsed().as_secs_f64());321    let km: f64 = edges.iter().map(|e| e.len as f64).sum::<f64>() / 1000.0;322    let g = Graph::from_edges(lon, lat, edges, 500);323    g.save(out)?;324    let cnt = |bit: u8| g.vmask.iter().filter(|m| **m & bit != 0).count();325    println!(326        "{{\"vertices\": {}, \"edges\": {}, \"directed_km\": {:.0}, \"foot_vertices\": {}, \"bike_vertices\": {}, \"car_vertices\": {}, \"seconds\": {:.0}}}",327        g.n(), g.m(), km, cnt(crate::graph::M_FOOT), cnt(crate::graph::M_BIKE), cnt(crate::graph::M_CAR), t0.elapsed().as_secs_f64()328    );329    Ok(())330}331332#[cfg(test)]333mod tests {334    use super::*;335336    fn c(tags: &[(&'static str, &'static str)]) -> Option<WayAttr> {337        classify(&tags.iter().cloned().collect())338    }339340    #[test]341    fn residential_street() {342        let a = c(&[("highway", "residential")]).unwrap();343        assert_eq!((a.car_fwd, a.car_bwd), (30, 30)); // 40 km/h × 0,75344        assert_eq!(a.flags_fwd, F_FOOT | F_BIKE);345        assert_eq!(a.flags_bwd, F_FOOT | F_BIKE);346    }347348    #[test]349    fn motorway_is_oneway_and_closed_to_foot_and_bike() {350        let a = c(&[("highway", "motorway"), ("maxspeed", "100")]).unwrap();351        assert_eq!((a.car_fwd, a.car_bwd), (95, 0));352        assert_eq!((a.flags_fwd, a.flags_bwd), (0, 0));353    }354355    #[test]356    fn oneway_street_with_contraflow_cycling() {357        let a = c(&[("highway", "residential"), ("oneway", "yes")]).unwrap();358        assert_eq!((a.car_fwd > 0, a.car_bwd), (true, 0));359        assert_eq!(a.flags_fwd & F_BIKE, F_BIKE);360        assert_eq!(a.flags_bwd & F_BIKE, 0, "vélo : sens unique respecté");361        assert_eq!(a.flags_bwd & F_FOOT, F_FOOT, "piéton : dans les deux sens");362        let a = c(&[("highway", "residential"), ("oneway", "yes"), ("oneway:bicycle", "no")]).unwrap();363        assert_eq!(a.flags_bwd & F_BIKE, F_BIKE);364        let a = c(&[("highway", "tertiary"), ("oneway", "-1")]).unwrap();365        assert_eq!((a.car_fwd, a.car_bwd > 0), (0, true));366        let a = c(&[("highway", "tertiary"), ("junction", "roundabout")]).unwrap();367        assert_eq!(a.car_bwd, 0);368    }369370    #[test]371    fn paths_and_steps() {372        let a = c(&[("highway", "footway")]).unwrap();373        assert_eq!((a.car_fwd, a.flags_fwd), (0, F_FOOT));374        let a = c(&[("highway", "footway"), ("bicycle", "yes")]).unwrap();375        assert_eq!(a.flags_fwd, F_FOOT | F_BIKE | F_BIKE_SLOW);376        let a = c(&[("highway", "steps")]).unwrap();377        assert_eq!(a.flags_fwd, F_FOOT | F_FOOT_SLOW);378        let a = c(&[("highway", "cycleway")]).unwrap();379        assert_eq!((a.car_fwd, a.flags_fwd), (0, F_FOOT | F_BIKE));380        let a = c(&[("highway", "cycleway"), ("foot", "no")]).unwrap();381        assert_eq!(a.flags_fwd, F_BIKE);382    }383384    #[test]385    fn access_restrictions() {386        assert_eq!(c(&[("highway", "service"), ("access", "private")]), None);387        let a = c(&[("highway", "service"), ("access", "private"), ("foot", "yes")]).unwrap();388        assert_eq!((a.car_fwd, a.flags_fwd), (0, F_FOOT));389        let a = c(&[("highway", "residential"), ("motor_vehicle", "no")]).unwrap();390        assert_eq!((a.car_fwd, a.flags_fwd), (0, F_FOOT | F_BIKE));391        let a = c(&[("highway", "trunk")]).unwrap();392        assert_eq!(a.flags_fwd & F_FOOT, 0, "voie rapide sans trottoir : pas de piéton");393        assert_eq!(c(&[("highway", "construction")]), None);394        assert_eq!(c(&[("highway", "proposed")]), None);395        assert_eq!(c(&[("building", "yes")]), None);396    }397398    #[test]399    fn speeds() {400        assert_eq!(parse_maxspeed("50"), Some(50.0));401        assert_eq!(parse_maxspeed("30 mph").map(|v| v.round()), Some(48.0));402        assert_eq!(parse_maxspeed("signals"), None);403        assert_eq!(parse_maxspeed("900"), None);404        let a = c(&[("highway", "secondary"), ("maxspeed", "70")]).unwrap();405        assert_eq!(a.car_fwd, 57); // 70 × 0,82406        let a = c(&[("highway", "unclassified"), ("surface", "gravel")]).unwrap();407        assert_eq!(a.car_fwd, 32); // min(50, 50) × 0,8 × 0,80408        assert_eq!(a.flags_fwd & F_BIKE_SLOW, F_BIKE_SLOW);409    }410}411
Files main
Menu

Theme