SPB Git

Repository Public

graph.rs 23.7 KB 638 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.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//! Réseau routier en mémoire (OSM, tout le Québec) : chargement, accrochage, Dijkstra borné (isochrones), A* (trajets).88//!89//! Chaque nœud OSM d'une voie est un sommet ; chaque paire de nœuds consécutifs donne une arête par sens permis.90//! Par arête : longueur (m), vitesse automobile (km/h, 0 = interdit dans ce sens), drapeaux piéton/vélo.91//! Temps sans circulation, sans feux ni pénalités de virage.9293use std::cmp::Reverse;94use std::collections::BinaryHeap;95use std::io::{Read, Write};9697pub const F_FOOT: u8 = 1;98pub const F_BIKE: u8 = 2;99pub const F_FOOT_SLOW: u8 = 4; // escaliers100pub const F_BIKE_SLOW: u8 = 8; // sentier, non revêtu, zone piétonne101pub const M_FOOT: u8 = 1;102pub const M_BIKE: u8 = 2;103pub const M_CAR: u8 = 4;104105pub const WALK_KMH: f32 = 4.8;106pub const BIKE_KMH: f32 = 16.0;107pub const BIKE_SLOW_KMH: f32 = 10.0;108const MAGIC: &[u8; 8] = b"KMGRAPH1";109const CELL: f64 = 0.01; // degrés110const GX0: f64 = -81.0;111const GY0: f64 = 44.0;112const GW: usize = 2600;113const GH: usize = 2000;114115#[derive(Clone, Copy, PartialEq, Eq, Debug)]116pub enum Profile {117    Walking,118    Cycling,119    Driving,120}121122impl Profile {123    pub fn parse(s: &str) -> Option<Self> {124        match s {125            "walking" | "marche" | "foot" => Some(Self::Walking),126            "cycling" | "velo" | "bike" => Some(Self::Cycling),127            "driving" | "auto" | "car" => Some(Self::Driving),128            _ => None,129        }130    }131    pub fn name(self) -> &'static str {132        match self {133            Self::Walking => "walking",134            Self::Cycling => "cycling",135            Self::Driving => "driving",136        }137    }138    fn mask(self) -> u8 {139        match self {140            Self::Walking => M_FOOT,141            Self::Cycling => M_BIKE,142            Self::Driving => M_CAR,143        }144    }145    /// Vitesse maximale du profil (m/s), pour l'heuristique A* (admissible).146    fn vmax(self) -> f32 {147        match self {148            Self::Walking => WALK_KMH / 3.6,149            Self::Cycling => BIKE_KMH / 3.6,150            Self::Driving => 120.0 / 3.6,151        }152    }153}154155#[derive(Clone, Copy, Debug)]156pub struct RawEdge {157    pub from: u32,158    pub to: u32,159    pub len: f32,160    pub car: u8,161    pub flags: u8,162}163164pub struct Graph {165    pub lon: Vec<i32>, // 1e-7 degré166    pub lat: Vec<i32>,167    pub vmask: Vec<u8>, // modes utilisables depuis ce sommet (grande composante)168    pub off: Vec<u32>,169    pub to: Vec<u32>,170    pub len: Vec<f32>,171    pub car: Vec<u8>,172    pub flags: Vec<u8>,173    cell_off: Vec<u32>,174    cell_items: Vec<u32>,175}176177pub struct Scratch {178    pub dist: Vec<u32>, // millisecondes ; u32::MAX = non atteint179    pub prev: Vec<u32>,180    pub touched: Vec<u32>,181}182183impl Scratch {184    pub fn new(n: usize) -> Self {185        Self { dist: vec![u32::MAX; n], prev: vec![u32::MAX; n], touched: Vec::new() }186    }187    pub fn reset(&mut self) {188        for &v in &self.touched {189            self.dist[v as usize] = u32::MAX;190            self.prev[v as usize] = u32::MAX;191        }192        self.touched.clear();193    }194}195196pub fn haversine_m(lon1: f64, lat1: f64, lon2: f64, lat2: f64) -> f64 {197    let p = std::f64::consts::PI / 180.0;198    let a = ((lat2 - lat1) * p / 2.0).sin().powi(2) + (lat1 * p).cos() * (lat2 * p).cos() * ((lon2 - lon1) * p / 2.0).sin().powi(2);199    2.0 * 6_371_008.8 * a.sqrt().asin()200}201202fn cell_of(lon: f64, lat: f64) -> Option<usize> {203    let ix = ((lon - GX0) / CELL).floor();204    let iy = ((lat - GY0) / CELL).floor();205    if ix < 0.0 || iy < 0.0 || ix >= GW as f64 || iy >= GH as f64 {206        return None;207    }208    Some(iy as usize * GW + ix as usize)209}210211impl Graph {212    /// Construit le graphe (CSR + index spatial + masque des grandes composantes) depuis une liste d'arêtes orientées.213    pub fn from_edges(lon: Vec<i32>, lat: Vec<i32>, mut edges: Vec<RawEdge>, min_component: usize) -> Self {214        let n = lon.len();215        edges.sort_unstable_by_key(|e| (e.from, e.to));216        let mut off = vec![0u32; n + 1];217        for e in &edges {218            off[e.from as usize + 1] += 1;219        }220        for i in 0..n {221            off[i + 1] += off[i];222        }223        // Composantes connexes par mode (non orientées) : un sommet d'un îlot isolé n'est pas un point d'accrochage.224        let mut vmask = vec![0u8; n];225        for (bit, pred) in [226            (M_FOOT, (|e: &RawEdge| e.flags & F_FOOT != 0) as fn(&RawEdge) -> bool),227            (M_BIKE, |e: &RawEdge| e.flags & F_BIKE != 0),228            (M_CAR, |e: &RawEdge| e.car > 0),229        ] {230            let mut parent: Vec<u32> = (0..n as u32).collect();231            fn find(p: &mut [u32], mut x: u32) -> u32 {232                while p[x as usize] != x {233                    p[x as usize] = p[p[x as usize] as usize];234                    x = p[x as usize];235                }236                x237            }238            let mut has = vec![false; n];239            for e in edges.iter().filter(|e| pred(e)) {240                has[e.from as usize] = true;241                has[e.to as usize] = true;242                let (a, b) = (find(&mut parent, e.from), find(&mut parent, e.to));243                if a != b {244                    parent[a as usize] = b;245                }246            }247            let mut size = vec![0u32; n];248            for v in 0..n as u32 {249                if has[v as usize] {250                    let r = find(&mut parent, v);251                    size[r as usize] += 1;252                }253            }254            for v in 0..n as u32 {255                if has[v as usize] && size[find(&mut parent, v) as usize] as usize >= min_component {256                    vmask[v as usize] |= bit;257                }258            }259        }260        let mut g = Graph {261            lon,262            lat,263            vmask,264            off,265            to: edges.iter().map(|e| e.to).collect(),266            len: edges.iter().map(|e| e.len).collect(),267            car: edges.iter().map(|e| e.car).collect(),268            flags: edges.iter().map(|e| e.flags).collect(),269            cell_off: Vec::new(),270            cell_items: Vec::new(),271        };272        g.build_index();273        g274    }275276    fn build_index(&mut self) {277        let n = self.lon.len();278        let mut cnt = vec![0u32; GW * GH + 1];279        let cells: Vec<u32> = (0..n)280            .map(|v| cell_of(self.lon[v] as f64 * 1e-7, self.lat[v] as f64 * 1e-7).map(|c| c as u32).unwrap_or(u32::MAX))281            .collect();282        for &c in &cells {283            if c != u32::MAX {284                cnt[c as usize + 1] += 1;285            }286        }287        for i in 0..GW * GH {288            cnt[i + 1] += cnt[i];289        }290        let mut pos = cnt.clone();291        let mut items = vec![0u32; cnt[GW * GH] as usize];292        for (v, &c) in cells.iter().enumerate() {293            if c != u32::MAX {294                items[pos[c as usize] as usize] = v as u32;295                pos[c as usize] += 1;296            }297        }298        self.cell_off = cnt;299        self.cell_items = items;300    }301302    pub fn n(&self) -> usize {303        self.lon.len()304    }305    pub fn m(&self) -> usize {306        self.to.len()307    }308    pub fn pos(&self, v: u32) -> (f64, f64) {309        (self.lon[v as usize] as f64 * 1e-7, self.lat[v as usize] as f64 * 1e-7)310    }311312    pub fn save(&self, path: &str) -> std::io::Result<()> {313        let tmp = format!("{path}.tmp");314        let mut f = std::io::BufWriter::with_capacity(1 << 22, std::fs::File::create(&tmp)?);315        f.write_all(MAGIC)?;316        f.write_all(&(self.n() as u32).to_le_bytes())?;317        f.write_all(&(self.m() as u32).to_le_bytes())?;318        for v in &self.lon { f.write_all(&v.to_le_bytes())?; }319        for v in &self.lat { f.write_all(&v.to_le_bytes())?; }320        f.write_all(&self.vmask)?;321        for v in &self.off { f.write_all(&v.to_le_bytes())?; }322        for v in &self.to { f.write_all(&v.to_le_bytes())?; }323        for v in &self.len { f.write_all(&v.to_le_bytes())?; }324        f.write_all(&self.car)?;325        f.write_all(&self.flags)?;326        f.flush()?;327        drop(f);328        std::fs::rename(tmp, path)329    }330331    pub fn load(path: &str) -> std::io::Result<Self> {332        let bad = |m: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, m.to_string());333        let mut f = std::io::BufReader::with_capacity(1 << 22, std::fs::File::open(path)?);334        let mut head = [0u8; 16];335        f.read_exact(&mut head)?;336        if &head[0..8] != MAGIC {337            return Err(bad("signature du graphe"));338        }339        let n = u32::from_le_bytes(head[8..12].try_into().unwrap()) as usize;340        let m = u32::from_le_bytes(head[12..16].try_into().unwrap()) as usize;341        fn rd4<R: Read, T>(f: &mut R, count: usize, conv: fn([u8; 4]) -> T) -> std::io::Result<Vec<T>> {342            let mut buf = vec![0u8; count * 4];343            f.read_exact(&mut buf)?;344            Ok(buf.chunks_exact(4).map(|c| conv([c[0], c[1], c[2], c[3]])).collect())345        }346        fn rd1<R: Read>(f: &mut R, count: usize) -> std::io::Result<Vec<u8>> {347            let mut buf = vec![0u8; count];348            f.read_exact(&mut buf)?;349            Ok(buf)350        }351        let lon = rd4(&mut f, n, i32::from_le_bytes)?;352        let lat = rd4(&mut f, n, i32::from_le_bytes)?;353        let vmask = rd1(&mut f, n)?;354        let off = rd4(&mut f, n + 1, u32::from_le_bytes)?;355        let to = rd4(&mut f, m, u32::from_le_bytes)?;356        let len = rd4(&mut f, m, f32::from_le_bytes)?;357        let car = rd1(&mut f, m)?;358        let flags = rd1(&mut f, m)?;359        if off[n] as usize != m || to.iter().any(|&t| t as usize >= n) {360            return Err(bad("graphe incohérent"));361        }362        let mut g = Graph { lon, lat, vmask, off, to, len, car, flags, cell_off: Vec::new(), cell_items: Vec::new() };363        g.build_index();364        Ok(g)365    }366367    /// Sommet utilisable par le profil le plus proche du point, dans un rayon donné (≤ 700 m).368    pub fn snap(&self, lon: f64, lat: f64, profile: Profile, max_m: f64) -> Option<(u32, f64)> {369        let c = cell_of(lon, lat)?;370        let (cx, cy) = ((c % GW) as i64, (c / GW) as i64);371        let mask = profile.mask();372        let mut best: Option<(u32, f64)> = None;373        for dy in -1..=1i64 {374            for dx in -1..=1i64 {375                let (x, y) = (cx + dx, cy + dy);376                if x < 0 || y < 0 || x >= GW as i64 || y >= GH as i64 {377                    continue;378                }379                let k = y as usize * GW + x as usize;380                for &v in &self.cell_items[self.cell_off[k] as usize..self.cell_off[k + 1] as usize] {381                    if self.vmask[v as usize] & mask == 0 {382                        continue;383                    }384                    let (vlon, vlat) = self.pos(v);385                    let d = haversine_m(lon, lat, vlon, vlat);386                    if d <= max_m && best.map(|b| d < b.1).unwrap_or(true) {387                        best = Some((v, d));388                    }389                }390            }391        }392        best393    }394395    /// Durée de parcours de l'arête `e` pour le profil, en millisecondes ; `None` si interdite.396    #[inline]397    pub fn cost_ms(&self, e: usize, profile: Profile) -> Option<u32> {398        let len = self.len[e];399        let secs = match profile {400            Profile::Walking => {401                let f = self.flags[e];402                if f & F_FOOT == 0 {403                    return None;404                }405                len / (WALK_KMH / 3.6) * if f & F_FOOT_SLOW != 0 { 2.0 } else { 1.0 }406            }407            Profile::Cycling => {408                let f = self.flags[e];409                if f & F_BIKE == 0 {410                    return None;411                }412                len / (if f & F_BIKE_SLOW != 0 { BIKE_SLOW_KMH } else { BIKE_KMH } / 3.6)413            }414            Profile::Driving => {415                let k = self.car[e];416                if k == 0 {417                    return None;418                }419                len / (k as f32 / 3.6)420            }421        };422        Some((secs * 1000.0).round().max(1.0) as u32)423    }424425    /// Dijkstra borné : remplit `s.dist` (ms) pour tous les sommets atteints en `tmax_ms` au plus.426    pub fn reach(&self, src: u32, profile: Profile, tmax_ms: u32, s: &mut Scratch) {427        s.reset();428        let mut heap: BinaryHeap<Reverse<(u32, u32)>> = BinaryHeap::new();429        s.dist[src as usize] = 0;430        s.touched.push(src);431        heap.push(Reverse((0, src)));432        while let Some(Reverse((d, u))) = heap.pop() {433            if d > s.dist[u as usize] {434                continue;435            }436            for e in self.off[u as usize] as usize..self.off[u as usize + 1] as usize {437                let Some(c) = self.cost_ms(e, profile) else { continue };438                let nd = d.saturating_add(c);439                if nd > tmax_ms {440                    continue;441                }442                let v = self.to[e] as usize;443                if nd < s.dist[v] {444                    if s.dist[v] == u32::MAX {445                        s.touched.push(v as u32);446                    }447                    s.dist[v] = nd;448                    heap.push(Reverse((nd, v as u32)));449                }450            }451        }452    }453454    /// A* : (durée ms, distance m, sommets du trajet) ; `None` si inatteignable ou au-delà de `max_pops`.455    pub fn route(&self, src: u32, dst: u32, profile: Profile, max_pops: usize, s: &mut Scratch) -> Option<(u32, f64, Vec<u32>)> {456        s.reset();457        let (tlon, tlat) = self.pos(dst);458        let vmax = profile.vmax() as f64;459        let h = |v: u32| -> u32 {460            let (lon, lat) = self.pos(v);461            (haversine_m(lon, lat, tlon, tlat) / vmax * 1000.0 * 0.999) as u32462        };463        let mut heap: BinaryHeap<Reverse<(u32, u32, u32)>> = BinaryHeap::new();464        s.dist[src as usize] = 0;465        s.touched.push(src);466        heap.push(Reverse((h(src), 0, src)));467        let mut pops = 0usize;468        let mut found = false;469        while let Some(Reverse((_, d, u))) = heap.pop() {470            if d > s.dist[u as usize] {471                continue;472            }473            if u == dst {474                found = true;475                break;476            }477            pops += 1;478            if pops > max_pops {479                break;480            }481            for e in self.off[u as usize] as usize..self.off[u as usize + 1] as usize {482                let Some(c) = self.cost_ms(e, profile) else { continue };483                let nd = d.saturating_add(c);484                let v = self.to[e] as usize;485                if nd < s.dist[v] {486                    if s.dist[v] == u32::MAX {487                        s.touched.push(v as u32);488                    }489                    s.dist[v] = nd;490                    s.prev[v] = u;491                    heap.push(Reverse((nd.saturating_add(h(v as u32)), nd, v as u32)));492                }493            }494        }495        if !found {496            return None;497        }498        let mut path = vec![dst];499        let mut cur = dst;500        while cur != src {501            cur = s.prev[cur as usize];502            if cur == u32::MAX || path.len() > self.n() {503                return None;504            }505            path.push(cur);506        }507        path.reverse();508        let mut dist = 0.0;509        for w in path.windows(2) {510            let (a, b) = (self.pos(w[0]), self.pos(w[1]));511            dist += haversine_m(a.0, a.1, b.0, b.1);512        }513        Some((s.dist[dst as usize], dist, path))514    }515}516517#[cfg(test)]518pub mod tests {519    use super::*;520521    /// Grille de rues nord-sud / est-ouest, pas de 100 m, autour de (−73,6 ; 45,5). `skip` retire des arêtes.522    pub fn grid_graph(w: usize, h: usize, car: u8, skip: &dyn Fn(usize, usize, usize, usize) -> bool) -> Graph {523        let dlat = 100.0 / 111_195.0;524        let dlon = dlat / (45.5f64).to_radians().cos();525        let mut lon = Vec::new();526        let mut lat = Vec::new();527        for j in 0..h {528            for i in 0..w {529                lon.push(((-73.6 + i as f64 * dlon) * 1e7).round() as i32);530                lat.push(((45.5 + j as f64 * dlat) * 1e7).round() as i32);531            }532        }533        let mut edges = Vec::new();534        let mut add = |a: (usize, usize), b: (usize, usize)| {535            if skip(a.0, a.1, b.0, b.1) {536                return;537            }538            let (u, v) = ((a.1 * w + a.0) as u32, (b.1 * w + b.0) as u32);539            for (f, t) in [(u, v), (v, u)] {540                edges.push(RawEdge { from: f, to: t, len: 100.0, car, flags: F_FOOT | F_BIKE });541            }542        };543        for j in 0..h {544            for i in 0..w {545                if i + 1 < w {546                    add((i, j), (i + 1, j));547                }548                if j + 1 < h {549                    add((i, j), (i, j + 1));550                }551            }552        }553        Graph::from_edges(lon, lat, edges, 4)554    }555556    #[test]557    fn walking_reach_matches_speed() {558        let g = grid_graph(41, 41, 40, &|_, _, _, _| false);559        let mut s = Scratch::new(g.n());560        let src = (20 * 41 + 20) as u32;561        g.reach(src, Profile::Walking, 15 * 60_000, &mut s);562        // 15 min à 4,8 km/h = 1 200 m : 12 arêtes de 100 m le long d'une rue563        let east = |k: usize| s.dist[20 * 41 + 20 + k];564        assert_eq!(east(12), 900_000);565        assert_eq!(east(13), u32::MAX);566        // distance de Manhattan : (6, 6) atteint, (7, 6) non567        assert!(s.dist[26 * 41 + 26] <= 900_000);568        assert_eq!(s.dist[26 * 41 + 27], u32::MAX);569    }570571    #[test]572    fn river_without_bridge_is_not_crossed() {573        // Aucune arête entre les colonnes 10 et 11 : deux rives.574        let g = grid_graph(21, 21, 40, &|ax, _, bx, _| (ax == 10 && bx == 11) || (ax == 11 && bx == 10));575        let mut s = Scratch::new(g.n());576        g.reach((10 * 21 + 9) as u32, Profile::Walking, 60 * 60_000, &mut s);577        for j in 0..21 {578            for i in 0..21 {579                assert_eq!(s.dist[j * 21 + i] != u32::MAX, i <= 10, "({i}, {j})");580            }581        }582        // Un seul pont (ligne 0) : la rive est atteinte, par le pont583        let g = grid_graph(21, 21, 40, &|ax, ay, bx, _| ay != 0 && ((ax == 10 && bx == 11) || (ax == 11 && bx == 10)));584        g.reach((10 * 21 + 10) as u32, Profile::Walking, 60 * 60_000, &mut s);585        // (11, 10) : 10 arêtes vers le sud, 1 pont, 10 vers le nord = 2 100 m = 1 575 s586        assert_eq!(s.dist[10 * 21 + 11], 1_575_000);587    }588589    #[test]590    fn one_way_and_modes() {591        // Trois sommets en ligne ; A→B à sens unique pour l'auto, B—C interdit à l'auto (piste).592        let lon = vec![-736_000_000, -735_990_000, -735_980_000];593        let lat = vec![455_000_000; 3];594        let e = |from, to, car, flags| RawEdge { from, to, len: 78.0, car, flags };595        let g = Graph::from_edges(lon, lat, vec![596            e(0, 1, 50, F_FOOT | F_BIKE), e(1, 0, 0, F_FOOT | F_BIKE),597            e(1, 2, 0, F_FOOT | F_BIKE), e(2, 1, 0, F_FOOT | F_BIKE),598        ], 2);599        let mut s = Scratch::new(3);600        g.reach(0, Profile::Driving, 600_000, &mut s);601        assert!(s.dist[1] != u32::MAX && s.dist[2] == u32::MAX);602        g.reach(1, Profile::Driving, 600_000, &mut s);603        assert_eq!(s.dist[0], u32::MAX, "sens unique respecté");604        g.reach(2, Profile::Walking, 600_000, &mut s);605        assert!(s.dist[0] != u32::MAX);606        assert_eq!(g.vmask[2] & M_CAR, 0);607        assert!(g.route(2, 0, Profile::Cycling, 100, &mut s).is_some());608        assert!(g.route(1, 0, Profile::Driving, 100, &mut s).is_none());609    }610611    #[test]612    fn route_and_snap() {613        let g = grid_graph(21, 21, 36, &|_, _, _, _| false);614        let mut s = Scratch::new(g.n());615        let (t, d, path) = g.route(0, (20 * 21 + 20) as u32, Profile::Driving, 10_000, &mut s).unwrap();616        assert!((d - 4000.0).abs() < 5.0, "{d}");617        assert_eq!(t, 400_000); // 4 km à 36 km/h618        assert_eq!(path.len(), 41);619        let (lon, lat) = g.pos(5 * 21 + 7);620        let (v, dist) = g.snap(lon + 0.0001, lat + 0.0001, Profile::Walking, 300.0).unwrap();621        assert_eq!(v, (5 * 21 + 7) as u32);622        assert!(dist < 20.0);623        assert!(g.snap(2.35, 48.85, Profile::Walking, 300.0).is_none());624    }625626    #[test]627    fn save_and_load() {628        let g = grid_graph(5, 5, 30, &|_, _, _, _| false);629        let p = std::env::temp_dir().join(format!("kmgraph-test-{}.bin", std::process::id()));630        g.save(p.to_str().unwrap()).unwrap();631        let h = Graph::load(p.to_str().unwrap()).unwrap();632        assert_eq!((g.n(), g.m()), (h.n(), h.m()));633        assert_eq!(g.to, h.to);634        assert_eq!(g.vmask, h.vmask);635        std::fs::remove_file(p).unwrap();636    }637}638
Files main
Menu

Theme