osm_graph 0.2.0

This library provides a set of tools for generating isochrones from geographic coordinates. It leverages OpenStreetMap data to construct road networks and calculate areas accessible within specified time limits. The library is designed for both Rust and Python, offering high performance and easy integration into data science workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Read OpenStreetMap PBF files into the same intermediate shape produced by
//! the Overpass XML parser. This lets the rest of the pipeline (graph building,
//! POI extraction) work unchanged whether the data came from live Overpass or
//! a local PBF file.

use std::collections::{HashMap, HashSet};
use std::path::Path;

use osmpbf::{Element, ElementReader};

use crate::error::OsmGraphError;
use crate::graph::{XmlData, XmlNode, XmlNodeRef, XmlTag, XmlWay};
use crate::overpass::NetworkType;

/// Read a PBF file once and produce one `XmlData` per requested network type,
/// plus the set of node IDs that are POIs (POIs are network-type-independent).
///
/// This avoids re-reading the PBF for each network type — useful at server
/// startup when you want walk/bike/drive graphs for the same region.
pub fn read_pbf_multi(
    path: impl AsRef<Path>,
    network_types: &[NetworkType],
) -> Result<(HashMap<NetworkType, XmlData>, HashSet<i64>), OsmGraphError> {
    let mut all_nodes: HashMap<i64, RawNode> = HashMap::new();
    let mut roads_by_type: HashMap<NetworkType, Vec<RawWay>> =
        network_types.iter().map(|nt| (*nt, Vec::new())).collect();
    let mut poi_ids: HashSet<i64> = HashSet::new();

    let reader = ElementReader::from_path(path.as_ref())
        .map_err(|e| OsmGraphError::PbfError(e.to_string()))?;

    reader
        .for_each(|element| match element {
            Element::Node(node) => {
                let tags: Vec<(String, String)> = node
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                let id = node.id();
                if is_poi_node(&tags) {
                    poi_ids.insert(id);
                }
                all_nodes.insert(id, RawNode { lat: node.lat(), lon: node.lon(), tags });
            }
            Element::DenseNode(node) => {
                let tags: Vec<(String, String)> = node
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                let id = node.id();
                if is_poi_node(&tags) {
                    poi_ids.insert(id);
                }
                all_nodes.insert(id, RawNode { lat: node.lat(), lon: node.lon(), tags });
            }
            Element::Way(way) => {
                let tags: Vec<(String, String)> = way
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                // Quick reject: ways without a highway tag aren't roads for any mode.
                if !tags.iter().any(|(k, _)| k == "highway") { return; }
                let refs: Vec<i64> = way.refs().collect();
                for &nt in network_types {
                    if way_passes_road_filter(&tags, nt) {
                        roads_by_type.get_mut(&nt).unwrap().push(RawWay {
                            id: way.id(),
                            refs: refs.clone(),
                            tags: tags.clone(),
                        });
                    }
                }
            }
            Element::Relation(_) => {}
        })
        .map_err(|e| OsmGraphError::PbfError(e.to_string()))?;

    // Per-network-type, emit only the nodes referenced by that type's ways
    // (plus all POI nodes — they're shared across all network types).
    let mut out: HashMap<NetworkType, XmlData> = HashMap::new();
    for (nt, roads) in roads_by_type {
        let mut needed: HashSet<i64> = poi_ids.clone();
        for w in &roads {
            for r in &w.refs {
                needed.insert(*r);
            }
        }
        let nodes: Vec<XmlNode> = all_nodes
            .iter()
            .filter(|(id, _)| needed.contains(id))
            .map(|(id, n)| XmlNode {
                id: *id,
                lat: n.lat,
                lon: n.lon,
                tags: n.tags.iter().cloned()
                    .map(|(k, v)| XmlTag { key: k, value: v })
                    .collect(),
                geohash: None,
            })
            .collect();
        let ways: Vec<XmlWay> = roads
            .into_iter()
            .map(|w| XmlWay {
                id: w.id,
                nodes: w.refs.into_iter().map(|node_id| XmlNodeRef { node_id }).collect(),
                tags: w.tags.into_iter().map(|(k, v)| XmlTag { key: k, value: v }).collect(),
                length: 0.0, speed_kph: 0.0,
                walk_travel_time: 0.0, bike_travel_time: 0.0, drive_travel_time: 0.0,
            })
            .collect();
        out.insert(nt, XmlData { nodes, ways});
    }

    Ok((out, poi_ids))
}

/// Read a PBF file and produce an `XmlData` (the canonical intermediate shape
/// our graph builder consumes) plus the set of node IDs that are POIs.
///
/// Two-pass logic implemented in a single PBF iteration:
///   1. Collect every node into a temporary map (id → lat/lon/tags).
///   2. Collect every way that passes the road-network filter for `network_type`.
///   3. Mark POI nodes (any node with our standard amenity/tourism/etc. tags).
///
/// After iteration, emit only the nodes we actually need: those referenced by
/// a kept way, or flagged as a POI. Everything else is discarded — for DC this
/// drops the ~4 million tagless nodes.
pub fn read_pbf(
    path: impl AsRef<Path>,
    network_type: NetworkType,
) -> Result<(XmlData, HashSet<i64>), OsmGraphError> {
    let mut all_nodes: HashMap<i64, RawNode> = HashMap::new();
    let mut roads: Vec<RawWay> = Vec::new();
    let mut poi_ids: HashSet<i64> = HashSet::new();

    let reader = ElementReader::from_path(path.as_ref())
        .map_err(|e| OsmGraphError::PbfError(e.to_string()))?;

    reader
        .for_each(|element| match element {
            Element::Node(node) => {
                let tags: Vec<(String, String)> = node
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                let id = node.id();
                if is_poi_node(&tags) {
                    poi_ids.insert(id);
                }
                all_nodes.insert(
                    id,
                    RawNode { lat: node.lat(), lon: node.lon(), tags },
                );
            }
            Element::DenseNode(node) => {
                let tags: Vec<(String, String)> = node
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                let id = node.id();
                if is_poi_node(&tags) {
                    poi_ids.insert(id);
                }
                all_nodes.insert(
                    id,
                    RawNode { lat: node.lat(), lon: node.lon(), tags },
                );
            }
            Element::Way(way) => {
                let tags: Vec<(String, String)> = way
                    .tags()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect();
                if !way_passes_road_filter(&tags, network_type) {
                    return;
                }
                let refs: Vec<i64> = way.refs().collect();
                roads.push(RawWay { id: way.id(), refs, tags });
            }
            Element::Relation(_) => {}
        })
        .map_err(|e| OsmGraphError::PbfError(e.to_string()))?;

    // Build the set of nodes we actually need to keep.
    let mut needed: HashSet<i64> = poi_ids.clone();
    for w in &roads {
        for r in &w.refs {
            needed.insert(*r);
        }
    }

    let nodes: Vec<XmlNode> = all_nodes
        .into_iter()
        .filter(|(id, _)| needed.contains(id))
        .map(|(id, n)| XmlNode {
            id,
            lat: n.lat,
            lon: n.lon,
            tags: n
                .tags
                .into_iter()
                .map(|(k, v)| XmlTag { key: k, value: v })
                .collect(),
            geohash: None,
        })
        .collect();

    let ways: Vec<XmlWay> = roads
        .into_iter()
        .map(|w| XmlWay {
            id: w.id,
            nodes: w
                .refs
                .into_iter()
                .map(|node_id| XmlNodeRef { node_id })
                .collect(),
            tags: w
                .tags
                .into_iter()
                .map(|(k, v)| XmlTag { key: k, value: v })
                .collect(),
            length: 0.0,
            speed_kph: 0.0,
            walk_travel_time: 0.0,
            bike_travel_time: 0.0,
            drive_travel_time: 0.0,
        })
        .collect();

    Ok((XmlData { nodes, ways}, poi_ids))
}

struct RawNode {
    lat: f64,
    lon: f64,
    tags: Vec<(String, String)>,
}

struct RawWay {
    id: i64,
    refs: Vec<i64>,
    tags: Vec<(String, String)>,
}

/// Mirror of `overpass::get_osm_filter`. If Overpass filter rules ever change,
/// these need to change in lockstep.
fn way_passes_road_filter(tags: &[(String, String)], network_type: NetworkType) -> bool {
    let get = |k: &str| {
        tags.iter()
            .find(|(tk, _)| tk == k)
            .map(|(_, v)| v.as_str())
    };

    let highway = match get("highway") {
        Some(v) => v,
        None => return false,
    };
    if get("area") == Some("yes") {
        return false;
    }

    match network_type {
        NetworkType::Drive => {
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "bridleway", "bus_guideway", "construction", "corridor",
                "cycleway", "elevator", "escalator", "footway", "no", "path", "pedestrian",
                "planned", "platform", "proposed", "raceway", "razed", "service", "steps", "track",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) { return false; }
            if get("motor_vehicle") == Some("no") { return false; }
            if get("motorcar") == Some("no") { return false; }
            const EXCLUDE_SERVICE: &[&str] = &[
                "alley", "driveway", "emergency_access", "parking", "parking_aisle", "private",
            ];
            if let Some(s) = get("service") {
                if EXCLUDE_SERVICE.contains(&s) { return false; }
            }
        }
        NetworkType::DriveService => {
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "bridleway", "bus_guideway", "construction", "corridor",
                "cycleway", "elevator", "escalator", "footway", "no", "path", "pedestrian",
                "planned", "platform", "proposed", "raceway", "razed", "steps", "track",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) { return false; }
            if get("motor_vehicle") == Some("no") { return false; }
            if get("motorcar") == Some("no") { return false; }
            const EXCLUDE_SERVICE: &[&str] = &[
                "emergency_access", "parking", "parking_aisle", "private",
            ];
            if let Some(s) = get("service") {
                if EXCLUDE_SERVICE.contains(&s) { return false; }
            }
        }
        NetworkType::Walk => {
            // "motor" is a substring pattern in Overpass — matches motor, motorway, motorroad.
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "bus_guideway", "construction", "corridor", "elevator", "escalator",
                "no", "planned", "platform", "proposed", "raceway", "razed",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) || highway.starts_with("motor") { return false; }
            if get("foot") == Some("no") { return false; }
            if get("service") == Some("private") { return false; }
        }
        NetworkType::Bike => {
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "bus_guideway", "construction", "corridor", "elevator", "escalator",
                "footway", "no", "planned", "platform", "proposed", "raceway", "razed", "steps",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) || highway.starts_with("motor") { return false; }
            if get("bicycle") == Some("no") { return false; }
            if get("service") == Some("private") { return false; }
        }
        NetworkType::All => {
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "construction", "no", "planned", "platform", "proposed", "raceway", "razed",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) { return false; }
            if get("service") == Some("private") { return false; }
        }
        NetworkType::AllPrivate => {
            const EXCLUDE_HIGHWAY: &[&str] = &[
                "abandoned", "construction", "no", "planned", "platform", "proposed", "raceway", "razed",
            ];
            if EXCLUDE_HIGHWAY.contains(&highway) { return false; }
        }
    }
    true
}

/// Mirror of the node selectors in `poi::create_poi_query`.
fn is_poi_node(tags: &[(String, String)]) -> bool {
    let get = |k: &str| {
        tags.iter()
            .find(|(tk, _)| tk == k)
            .map(|(_, v)| v.as_str())
    };

    if get("tourism").is_some() { return true; }
    if get("historic").is_some() { return true; }

    if let Some(v) = get("natural") {
        if matches!(v, "peak" | "waterfall" | "cave_entrance" | "beach" | "hot_spring") {
            return true;
        }
    }

    if let Some(v) = get("amenity") {
        if matches!(
            v,
            "restaurant" | "fast_food" | "cafe" | "bar" | "pub" | "biergarten" | "ice_cream"
                | "food_court" | "museum" | "theatre" | "cinema" | "arts_centre" | "library"
                | "place_of_worship" | "spa" | "swimming_pool"
        ) {
            return true;
        }
    }

    if let Some(v) = get("leisure") {
        if matches!(v, "park" | "nature_reserve" | "garden" | "sports_centre" | "fitness_centre") {
            return true;
        }
    }

    if let Some(v) = get("shop") {
        if matches!(v, "bakery" | "deli" | "chocolate" | "wine" | "cheese" | "mall" | "department_store") {
            return true;
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn poi_detection_amenity() {
        let tags = vec![
            ("amenity".to_string(), "restaurant".to_string()),
            ("name".to_string(), "Joe's".to_string()),
        ];
        assert!(is_poi_node(&tags));
    }

    #[test]
    fn poi_detection_rejects_unrelated_amenity() {
        let tags = vec![("amenity".to_string(), "atm".to_string())];
        assert!(!is_poi_node(&tags));
    }

    #[test]
    fn poi_detection_tourism() {
        // Any tourism tag counts.
        let tags = vec![("tourism".to_string(), "hotel".to_string())];
        assert!(is_poi_node(&tags));
    }

    #[test]
    fn road_filter_walk_keeps_residential() {
        let tags = vec![("highway".to_string(), "residential".to_string())];
        assert!(way_passes_road_filter(&tags, NetworkType::Walk));
    }

    #[test]
    fn road_filter_walk_rejects_motor() {
        let tags = vec![("highway".to_string(), "motorway".to_string())];
        assert!(!way_passes_road_filter(&tags, NetworkType::Walk));
    }

    #[test]
    fn road_filter_drive_rejects_footway() {
        let tags = vec![("highway".to_string(), "footway".to_string())];
        assert!(!way_passes_road_filter(&tags, NetworkType::Drive));
    }

    #[test]
    fn road_filter_rejects_area_yes() {
        let tags = vec![
            ("highway".to_string(), "residential".to_string()),
            ("area".to_string(), "yes".to_string()),
        ];
        assert!(!way_passes_road_filter(&tags, NetworkType::Walk));
    }

    #[test]
    fn road_filter_walk_rejects_foot_no() {
        let tags = vec![
            ("highway".to_string(), "residential".to_string()),
            ("foot".to_string(), "no".to_string()),
        ];
        assert!(!way_passes_road_filter(&tags, NetworkType::Walk));
    }
}