osmgraphing 0.12.0

Playing around with graphs created via parsing OpenStreetMap data
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use crate::{helpers, io::SupportingFileExts};
use serde::Deserialize;
use std::{fmt, fmt::Display, path::Path};

mod raw;

/// Storing (default) settings for parsing the graph.
///
/// # Configuration
///
/// ## Set config-values with yaml-file
///
/// You can change the configuration with an input-file (`*.yaml`).
/// With this `yaml`-config, the parser can be adjusted to parse (edge-)metrics in the order as provided by the config-file.
/// This can help especially with map-files in `fmi`-format, since the metrics are read sequentially.
/// But since `pbf`-files does not provide a column-based metric-list, but intrinsically by parsing `osm`-data, you can distinguish between default-metrics and custom-metrics via the key `category`.
/// Default-categories are described in `EdgeCategory`.
///
/// Internally, a default-metric uses provided calculation-rules to be calculated by other default-categories as well (like the duration from distance and maxspeed).
///
/// Keep in mind, that metrics (except for id) are stored as `f64` for better maintainability and efficiency.
///
///
/// ### Specifying routing (in the future)
///
/// Further, the metrics, which are used in the routing, can be listed in the routing-section with their previously defined id.
/// Comparisons are made using pareto-optimality, so there is no comparison between metrics.
/// In case you'll use personlized-routing, default-preferences can be set with weights.
/// The example below shows a routing-case, where the metric `distance` is weighted with `169 / (169 + 331) = 33.8 %` while the metric `duration` is weighted with `331 / (169 + 331) = 66.2 %`.
///
///
/// ### Supported structure
///
/// The supported `yaml`-structure can be seen in `resources/configs/schema.yaml`.
///
// Every metric (!= every category) will be stored in the graph, if mentioned in this `yaml`-file.
/// If a metric is mentioned, but `provided` is false, it will be calculated (e.g. edge-distance from node-coordinates and haversine).
/// Please note, that metrics being calculated (like the duration from distance and maxspeed) need the respective metrics to be calculated.
#[derive(Debug, Deserialize)]
#[serde(from = "raw::Config")]
pub struct Config {
    pub parser: parser::Config,
    pub generator: Option<generator::Config>,
    pub routing: Option<routing::Config>,
}

impl SupportingFileExts for Config {
    fn supported_exts<'a>() -> &'a [&'a str] {
        &["yaml"]
    }
}

impl Config {
    pub fn from_yaml<P: AsRef<Path> + ?Sized>(path: &P) -> Result<Config, String> {
        let file = {
            Config::find_supported_ext(path)?;
            helpers::open_file(path)?
        };
        match serde_yaml::from_reader(file) {
            Ok(cfg) => Ok(cfg),
            Err(msg) => Err(format!("{}", msg)),
        }
    }
}

pub mod parser {
    pub use edges::Category as EdgeCategory;
    pub use nodes::Category as NodeCategory;
    use std::path::PathBuf;

    #[derive(Debug)]
    pub struct Config {
        pub map_file: PathBuf,
        pub vehicles: vehicles::Config,
        pub nodes: nodes::Config,
        pub edges: edges::Config,
    }

    pub mod vehicles {
        use crate::network::VehicleCategory;

        #[derive(Debug)]
        pub struct Config {
            pub category: VehicleCategory,
            pub are_drivers_picky: bool,
        }
    }

    pub mod nodes {
        use serde::Deserialize;

        #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
        pub enum Category {
            NodeId,
            Latitude,
            Longitude,
            Level,
            Ignore,
        }

        #[derive(Debug)]
        pub struct Config {
            categories: Vec<Category>,
        }

        impl Config {
            pub fn new(categories: Vec<Category>) -> Config {
                Config { categories }
            }

            pub fn categories(&self) -> &Vec<Category> {
                &self.categories
            }
        }
    }

    pub mod edges {
        use crate::{configs::SimpleId, defaults::capacity::DimVec, network::MetricIdx};
        use serde::Deserialize;
        use smallvec::smallvec;
        use std::{
            collections::BTreeMap,
            fmt::{self, Display},
        };

        #[derive(Debug)]
        pub struct Config {
            // store all for order
            edge_categories: Vec<Category>,
            edge_ids: Vec<SimpleId>,
            // store only metrics for quick access
            metric_categories: DimVec<Category>,
            are_metrics_provided: DimVec<bool>,
            metric_ids: DimVec<SimpleId>,
            metric_indices: BTreeMap<SimpleId, MetricIdx>,
            calc_rules: DimVec<DimVec<(Category, MetricIdx)>>,
        }

        impl Config {
            pub fn new(
                edge_categories: Vec<Category>,
                edge_ids: Vec<SimpleId>,
                metric_categories: DimVec<Category>,
                are_metrics_provided: DimVec<bool>,
                metric_ids: DimVec<SimpleId>,
                metric_indices: BTreeMap<SimpleId, MetricIdx>,
                calc_rules: DimVec<DimVec<(Category, MetricIdx)>>,
            ) -> Config {
                Config {
                    edge_categories,
                    edge_ids,
                    metric_categories,
                    are_metrics_provided,
                    metric_ids,
                    metric_indices,
                    calc_rules,
                }
            }
        }

        impl Config {
            pub fn edge_categories(&self) -> &Vec<Category> {
                &self.edge_categories
            }

            /// For metrics, use `metric_category(idx)`, since it is faster.
            pub fn edge_category(&self, id: &SimpleId) -> &Category {
                match self.edge_ids.iter().position(|i| i == id) {
                    Some(idx) => &self.edge_categories[idx],
                    None => {
                        // if no id exists, it could be an ignored one, e.g. asked by the generator
                        if id == &SimpleId(format!("{}", Category::Ignore)) {
                            &Category::Ignore
                        } else {
                            panic!("Id {} not found in config.", id);
                        }
                    }
                }
            }

            pub fn metric_category(&self, idx: MetricIdx) -> Category {
                match self.metric_categories.get(*idx) {
                    Some(metric_category) => *metric_category,
                    None => {
                        panic!("Idx {} for metric-category not found in config.", idx);
                    }
                }
            }

            pub fn dim(&self) -> usize {
                self.metric_categories.len()
            }

            pub fn is_metric_provided(&self, idx: MetricIdx) -> bool {
                match self.are_metrics_provided.get(*idx) {
                    Some(is_provided) => *is_provided,
                    None => {
                        panic!("Idx {} for info 'is-provided' not found in config.", idx);
                    }
                }
            }

            pub fn metric_idx(&self, id: &SimpleId) -> MetricIdx {
                match self.metric_indices.get(id) {
                    Some(idx) => *idx,
                    None => {
                        panic!("Id {} not found in config.", id);
                    }
                }
            }

            pub fn calc_rules(&self, idx: MetricIdx) -> &DimVec<(Category, MetricIdx)> {
                match self.calc_rules.get(*idx) {
                    Some(calc_rule) => calc_rule,
                    None => {
                        panic!("Idx {} for calc-rule not found in config.", idx);
                    }
                }
            }
        }

        /// Types of metrics to consider when parsing a map.
        ///
        /// - `SrcId`/`DstId`, which is not a metric per se and stored differently, but needed for `csv`-like `fmi`-format.
        /// - `Ignore - SrcIdx`/`Ignore - DstIdx`, which are needed to be defined here for using their id in a generator afterwards.
        /// - `Meters` provided in meters, but internally stored as kilometers
        /// - `KilometersPerHour` in km/h
        /// - `Seconds`
        /// - `LaneCount`
        /// - `Custom`, which is just the plain f64-value
        /// - `Ignore`, which is used in `csv`-like `fmi`-maps to jump over columns
        #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
        pub enum Category {
            Meters,
            KilometersPerHour,
            Seconds,
            LaneCount,
            Custom,
            ShortcutEdgeIdx,
            SrcId,
            #[serde(rename = "Ignore - SrcIdx")]
            IgnoredSrcIdx,
            DstId,
            #[serde(rename = "Ignore - DstIdx")]
            IgnoredDstIdx,
            Ignore,
        }

        impl Display for Category {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                fmt::Debug::fmt(self, f)
            }
        }

        impl Category {
            pub fn must_be_positive(&self) -> bool {
                match self {
                    Category::Meters
                    | Category::KilometersPerHour
                    | Category::Seconds
                    | Category::LaneCount => true,
                    Category::Custom
                    | Category::ShortcutEdgeIdx
                    | Category::SrcId
                    | Category::IgnoredSrcIdx
                    | Category::DstId
                    | Category::IgnoredDstIdx
                    | Category::Ignore => false,
                }
            }

            pub fn is_metric(&self) -> bool {
                match self {
                    Category::SrcId
                    | Category::DstId
                    | Category::IgnoredSrcIdx
                    | Category::IgnoredDstIdx
                    | Category::ShortcutEdgeIdx
                    | Category::Ignore => false,
                    Category::Meters
                    | Category::KilometersPerHour
                    | Category::Seconds
                    | Category::LaneCount
                    | Category::Custom => true,
                }
            }

            pub fn expected_calc_rules(&self) -> DimVec<Category> {
                match self {
                    Category::KilometersPerHour => smallvec![Category::Meters, Category::Seconds],
                    Category::Seconds => smallvec![Category::Meters, Category::KilometersPerHour],
                    Category::Meters
                    | Category::LaneCount
                    | Category::Custom
                    | Category::ShortcutEdgeIdx
                    | Category::SrcId
                    | Category::IgnoredSrcIdx
                    | Category::DstId
                    | Category::IgnoredDstIdx
                    | Category::Ignore => smallvec![],
                }
            }
        }
    }
}

pub mod generator {
    use super::SimpleId;
    pub use edges::Category as EdgeCategory;
    pub use nodes::Category as NodeCategory;
    use std::path::PathBuf;

    pub mod nodes {
        use serde::Deserialize;

        #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
        pub enum Category {
            NodeId,
            NodeIdx,
            Latitude,
            Longitude,
            Level,
            Ignore,
        }
    }

    pub mod edges {
        use serde::Deserialize;

        #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
        pub enum Category {
            Meters,
            KilometersPerHour,
            Seconds,
            LaneCount,
            Custom,
            SrcId,
            SrcIdx,
            DstId,
            DstIdx,
            Ignore,
        }
    }

    #[derive(Debug)]
    pub struct Config {
        pub map_file: PathBuf,
        pub nodes: Vec<NodeCategory>,
        pub edges: Vec<SimpleId>,
    }
}

pub mod routing {
    use crate::{
        defaults::{self, capacity::DimVec},
        network::MetricIdx,
    };

    #[derive(Clone, Debug)]
    pub struct Config {
        is_ch_dijkstra: bool,
        metric_indices: DimVec<MetricIdx>,
        alphas: DimVec<f64>,
    }

    impl Config {
        fn _push(&mut self, idx: MetricIdx, alpha: f64) {
            self.metric_indices.push(idx);
            self.alphas.push(alpha);
        }

        pub fn is_ch_dijkstra(&self) -> bool {
            self.is_ch_dijkstra
        }

        pub fn set_ch_dijkstra(&mut self, is_ch_dijkstra: bool) {
            self.is_ch_dijkstra = is_ch_dijkstra
        }

        pub fn alpha(&self, metric_idx: MetricIdx) -> f64 {
            let idx = match self.metric_indices.iter().position(|i| i == &metric_idx) {
                Some(idx) => idx,
                None => {
                    panic!("Idx {} not found in config.", metric_idx);
                }
            };
            self.alphas[idx]
        }

        pub fn alphas(&self) -> &DimVec<f64> {
            &self.alphas
        }

        pub fn metric_indices(&self) -> &DimVec<MetricIdx> {
            &self.metric_indices
        }

        pub fn dim(&self) -> usize {
            self.metric_indices.len()
        }

        pub fn from_str(
            yaml_str: &str,
            cfg_graph: &super::parser::Config,
        ) -> Result<Config, String> {
            let raw_cfg = super::raw::routing::Config::from_str(yaml_str)?;
            Ok(Config::from_raw(raw_cfg, cfg_graph))
        }

        pub fn from_raw(
            raw_cfg: super::raw::routing::Config,
            cfg_parser: &super::parser::Config,
        ) -> Config {
            let (metric_indices, alphas) = raw_cfg
                .metrics
                .into_iter()
                .map(|entry| {
                    (
                        cfg_parser.edges.metric_idx(&entry.id),
                        entry.alpha.unwrap_or(defaults::routing::ALPHA),
                    )
                })
                .unzip();

            Config {
                is_ch_dijkstra: raw_cfg.is_ch_dijkstra.unwrap_or(false),
                metric_indices,
                alphas,
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
#[serde(from = "String")]
pub struct SimpleId(pub String);

impl From<String> for SimpleId {
    fn from(id: String) -> SimpleId {
        SimpleId(id)
    }
}

impl From<&str> for SimpleId {
    fn from(id: &str) -> SimpleId {
        SimpleId(id.to_owned())
    }
}

impl Display for SimpleId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}