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
//! A parser/filter for OSM protobuf bundles.

use self::geo::get_compound_coordinates;
use self::items::{osm, AdminBoundary, Object, Street};
use admin::get_boundaries;
use filter::{Condition, Filter, Group};
use osmpbfreader::objects::{OsmId, OsmObj, Relation, RelationId, Way};
use osmpbfreader::OsmPbfReader;
use rstar::RTree;
use std::collections::BTreeMap;
use std::error::Error;
use std::io::{Read, Seek};
use streets::extract_streets;

mod admin;
pub mod filter;
mod geo;
mod geojson;
pub mod items;
pub mod output;
mod streets;
mod test_helpers;

trait OsmExt {
    fn get_coordinates(&self, objs: &BTreeMap<OsmId, OsmObj>) -> Vec<(f64, f64)>;
}

trait OsmCycle {
    fn get_coordinates(
        &self,
        objs: &BTreeMap<OsmId, OsmObj>,
        visited: &mut Vec<RelationId>,
    ) -> Vec<(f64, f64)>;
}

impl OsmExt for Way {
    fn get_coordinates(&self, objs: &BTreeMap<OsmId, OsmObj>) -> Vec<(f64, f64)> {
        self.nodes
            .iter()
            .filter_map(|&id| {
                let obj = objs.get(&id.into())?;
                let node = obj.node()?;
                Some((node.lon(), node.lat()))
            })
            .collect()
    }
}

impl OsmCycle for Relation {
    fn get_coordinates(
        &self,
        objs: &BTreeMap<OsmId, OsmObj>,
        visited: &mut Vec<RelationId>,
    ) -> Vec<(f64, f64)> {
        if visited.contains(&self.id) {
            return vec![];
        }
        visited.push(self.id);
        let coordinates = self
            .refs
            .iter()
            .filter_map(|osm_ref| {
                let obj = objs.get(&osm_ref.member)?;
                let coordinates = match obj {
                    OsmObj::Node(node) => vec![(node.lon(), node.lat())],
                    OsmObj::Way(way) => way.get_coordinates(objs),
                    OsmObj::Relation(rel) => rel.get_coordinates(objs, visited),
                };
                Some(coordinates)
            })
            .flatten()
            .collect();
        get_compound_coordinates(coordinates)
    }
}

fn build_admin_group(levels: Vec<u8>) -> Vec<Group> {
    levels
        .iter()
        .map(|level| {
            let level_match = Condition::new("admin_level", Some(&level.to_string()));
            let boundary_match = Condition::new("boundary", Some("administrative"));
            let conditions = vec![boundary_match, level_match];
            Group { conditions }
        })
        .collect()
}

fn build_street_group(name: Option<&str>) -> Vec<Group> {
    let values = vec![
        "primary",
        "secondary",
        "tertiary",
        "residential",
        "service",
        "living_street",
        "pedestrian",
    ];

    let name_condition = Condition::new("name", name);
    values
        .into_iter()
        .map(|val| {
            let highway_match = Condition::new("highway", Some(val));
            let conditions = vec![highway_match, name_condition.clone()];
            Group { conditions }
        })
        .collect()
}

/// Extract administrative boundaries from OSM
///
/// Administrative boundaries are stored in OSM as Relations with the Tag `boundary: administrative` and a `admin_level`. The meaning of the individual levels (state, country, etc.) depends on the respective region (read [here](https://wiki.openstreetmap.org/wiki/Key:admin_level) for details).
///
/// The levels can be specified, by default `4, 6, 8, 9, 10` are considered.
///
/// # Example
///
/// ```
/// use std::fs::File;
/// use osm_pbf2json::boundaries;
///
/// let file = File::open("./tests/data/wilhelmstrasse.pbf").unwrap();
/// let boundaries = boundaries(file, Some(vec![10])).unwrap();
/// assert_eq!(boundaries.len(), 2);
/// ```
pub fn boundaries(
    file: impl Seek + Read,
    levels: Option<Vec<u8>>,
) -> Result<Vec<AdminBoundary>, Box<dyn Error>> {
    let mut pbf = OsmPbfReader::new(file);
    let default_levels = vec![4, 6, 8, 9, 10];
    let levels = levels.unwrap_or(default_levels);
    let groups = build_admin_group(levels);
    let objs = pbf.get_objs_and_deps(|obj| obj.filter(&groups))?;
    let boundaries = get_boundaries(&objs);
    Ok(boundaries)
}

/// Extract a list of streets from a set of OSM Objects
///
/// Streets are represented in OSM as a collection of smaller Way segments. To cluster those into distinct street entities `name` Tag and the geographical distance are considered.
///
/// A `name` can be given to retrieve only streets with a matching name.
///
/// Sometimes continuous streets cross boundaries. Streets are split along administrative boundary borders, when specifying a `boundary` option.
///
/// # Example
///
/// ```
/// use std::fs::File;
/// use osm_pbf2json::streets;
///
/// let file = File::open("./tests/data/wilhelmstrasse.pbf").unwrap();
/// let name = "Wilhelmstraße";
/// let streets = streets(file, Some(name), Some(10)).unwrap();
/// assert_eq!(streets.len(), 2);
/// ```
pub fn streets(
    file: impl Seek + Read,
    name: Option<&str>,
    boundary: Option<u8>,
) -> Result<Vec<Street>, Box<dyn Error>> {
    let mut pbf = OsmPbfReader::new(file);
    let groups = build_street_group(name);
    let objs = pbf.get_objs_and_deps(|obj| obj.filter(&groups))?;
    let streets = extract_streets(&objs);
    let streets = {
        match boundary {
            None => streets,
            Some(level) => {
                let groups = build_admin_group(vec![level]);
                let objs = pbf.get_objs_and_deps(|obj| obj.filter(&groups))?;
                let boundaries = get_boundaries(&objs);
                let tree = RTree::<AdminBoundary>::bulk_load(boundaries);
                streets
                    .into_iter()
                    .flat_map(|street| street.split_by_boundaries(&tree))
                    .collect()
            }
        }
    };
    Ok(streets)
}

/// Extract Objects from OSM
///
/// Objects (i.e. Nodes, Ways & Relations) will be extracted according to filter options. Some geographic properties (centroid, bounding boxes) are computed for all entities.
///
/// Filtering `groups` can be applied to select objects according to their tags.
///
/// # Example
///
/// ```
/// use std::fs::File;
/// use osm_pbf2json::objects;
/// use osm_pbf2json::filter::{Condition, Group};
///
/// let file = File::open("./tests/data/alexanderplatz.pbf").unwrap();
/// let cond_1 = Condition::new("surface", Some("cobblestone"));
/// let cond_2 = Condition::new("highway", None);
/// let group = Group { conditions: vec![cond_1, cond_2] };
/// let cobblestone_ways = objects(file, &vec![group]).unwrap();
/// assert_eq!(cobblestone_ways.len(), 4);
/// ```
pub fn objects(file: impl Seek + Read, groups: &[Group]) -> Result<Vec<Object>, Box<dyn Error>> {
    let mut pbf = OsmPbfReader::new(file);
    let objs = pbf.get_objs_and_deps(|obj| obj.filter(groups))?;

    let objects = objs
        .values()
        .filter_map(|obj| {
            if !obj.filter(groups) {
                return None;
            }
            let object = match obj {
                OsmObj::Node(obj) => {
                    let node = osm::Node::new(obj.id.0, obj.lat(), obj.lon(), obj.tags.clone());
                    Object::Node(node)
                }
                OsmObj::Way(obj) => {
                    let coordinates = obj.get_coordinates(&objs);
                    let way = osm::Way::new(obj.id.0, obj.tags.clone(), &coordinates);
                    Object::Way(way)
                }
                OsmObj::Relation(obj) => {
                    let coordinates = obj.get_coordinates(&objs, &mut vec![]);
                    let relation = osm::Relation::new(obj.id.0, obj.tags.clone(), &coordinates);
                    Object::Relation(relation)
                }
            };
            Some(object)
        })
        .collect();
    Ok(objects)
}

#[cfg(test)]
mod get_coordinates {
    use super::*;
    use osmpbfreader::objects::{Node, NodeId, Ref, Relation, RelationId, Tags, Way, WayId};
    use std::collections::BTreeMap;

    fn create_node(id: NodeId, lng: i32, lat: i32) -> Node {
        let tags = Tags::new();
        let decimicro_lat = lat * 10_000_000;
        let decimicro_lon = lng * 10_000_000;
        Node {
            id,
            tags,
            decimicro_lat,
            decimicro_lon,
        }
    }

    fn create_relation(id: RelationId, refs: Vec<Ref>) -> Relation {
        let tags = Tags::new();
        Relation { id, tags, refs }
    }

    fn create_way(id: WayId, nodes: Vec<NodeId>) -> Way {
        let tags = Tags::new();
        Way { id, tags, nodes }
    }

    fn add_nodes(
        coordinates: Vec<(i32, i32)>,
        obj_map: &mut BTreeMap<OsmId, OsmObj>,
        node_ids: &mut Vec<NodeId>,
    ) {
        for (i, (lng, lat)) in coordinates.iter().enumerate() {
            let node_id = NodeId((i as i64) + 1);
            let node = create_node(node_id, *lng, *lat);
            obj_map.insert(node_id.into(), node.into());
            node_ids.push(node_id);
        }
    }

    fn create_refs(ids: Vec<OsmId>) -> Vec<Ref> {
        ids.into_iter()
            .map(|id| Ref {
                member: id,
                role: "something".into(),
            })
            .collect()
    }

    #[test]
    fn relation_without_refs() {
        let obj_map = BTreeMap::new();
        let id = RelationId(42);
        let rel = create_relation(id, vec![]);
        let coordinates = rel.get_coordinates(&obj_map, &mut vec![]);
        assert_eq!(coordinates.len(), 0);
    }

    #[test]
    fn relation_with_one_way() {
        let coordinates = vec![(9, 50), (9, 51), (10, 51)];

        // 1     2
        //
        //
        // 0

        let mut obj_map = BTreeMap::new();
        let mut node_ids = vec![];
        add_nodes(coordinates, &mut obj_map, &mut node_ids);

        let way_id = WayId(42);
        let way = create_way(way_id, node_ids);
        obj_map.insert(way_id.into(), way.into());

        let refs = create_refs(vec![way_id.into()]);
        let id = RelationId(43);
        let rel = create_relation(id, refs);

        // we expect a closed triangle

        let coordinates = rel.get_coordinates(&obj_map, &mut vec![]);
        assert_eq!(
            coordinates,
            vec![(9., 50.), (9., 51.), (10., 51.), (9., 50.)]
        );
    }

    #[test]
    fn relation_with_one_node() {
        let node_id = NodeId(41);
        let node = create_node(node_id, 5, 49);
        let mut obj_map = BTreeMap::new();
        obj_map.insert(node_id.into(), node.into());
        let id = RelationId(42);
        let refs = create_refs(vec![node_id.into()]);
        let rel = create_relation(id, refs);
        let coordinates = rel.get_coordinates(&obj_map, &mut vec![]);
        assert_eq!(coordinates, vec![(5., 49.)]);
    }

    #[test]
    fn relation_with_multiple_nodes() {
        let coordinates = vec![(6, 52), (6, 50), (8, 50), (8, 52), (7, 51)];

        // Node 4 is located in the middle of a grid
        // and should hence be ignored.
        //
        // 0     3
        //
        //    4
        //
        // 1     2

        let mut obj_map = BTreeMap::new();
        let mut node_ids = vec![];
        add_nodes(coordinates, &mut obj_map, &mut node_ids);

        let id = RelationId(42);
        let refs = create_refs(node_ids.into_iter().map(NodeId::into).collect());
        let rel = create_relation(id, refs);
        let coordinates = rel.get_coordinates(&obj_map, &mut vec![]);

        // We expect a simplified closed rectangle.
        //
        // 3-----2
        // |     |
        // |     |
        // |     |
        // 0/4---1

        assert_eq!(
            coordinates,
            vec![(6., 50.), (8., 50.), (8., 52.), (6., 52.), (6., 50.)]
        );
    }

    #[test]
    fn nested_relations() {
        let coordinates = vec![(6, 52), (6, 50)];
        let mut obj_map = BTreeMap::new();
        let mut node_ids = vec![];
        add_nodes(coordinates, &mut obj_map, &mut node_ids);

        let child_id = RelationId(42);
        let refs = create_refs(node_ids.into_iter().map(NodeId::into).collect());
        let child_rel = create_relation(child_id, refs);
        obj_map.insert(child_id.into(), child_rel.into());

        let node_id = NodeId(43);
        let node = create_node(node_id, 8, 52);
        obj_map.insert(node_id.into(), node.into());

        let parent_id = RelationId(44);
        let refs = create_refs(vec![child_id.into(), node_id.into()]);
        let parent_rel = create_relation(parent_id, refs);

        let coordinates = parent_rel.get_coordinates(&obj_map, &mut vec![]);

        assert_eq!(
            coordinates,
            vec![(6., 50.), (8., 52.), (6., 52.), (6., 50.)]
        );
    }

    #[test]
    fn nested_relations_with_cycle() {
        let mut obj_map = BTreeMap::new();
        let rel_id_1 = RelationId(42);
        let rel_id_2 = RelationId(44);
        let refs = create_refs(vec![rel_id_2.into()]);
        let rel_1 = create_relation(rel_id_1, refs);
        obj_map.insert(rel_id_1.into(), rel_1.into());

        let node_id = NodeId(43);
        let node = create_node(node_id, 8, 52);
        obj_map.insert(node_id.into(), node.into());

        let refs = create_refs(vec![rel_id_1.into(), node_id.into()]);
        let rel_2 = create_relation(rel_id_2, refs);

        let coordinates = rel_2.get_coordinates(&obj_map, &mut vec![]);

        assert_eq!(coordinates, vec![(8., 52.)]);
    }
}