Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / extract.rs

extract.rs441 lines · 15.4 KiBRaw
1//! Vector-layer extraction: `.osm.pbf` -> one geojsonseq per layer.
2//!
3//! The `osmium tags-filter | osmium export | normalize_*.py` chain, done in one
4//! pass over the PBF with no external tools. Each layer's schema lives in its own
5//! module ([`crate::safety`] and so on); this module owns the PBF traversal, the
6//! bbox filter, the deterministic ordering and the output file.
7//!
8//! ## Pass ordering is fixed, and reversed
9//!
10//! Layers that need way or relation geometry cannot be done in one pass, because
11//! a PBF stores nodes before the ways that reference them. So the traversal runs
12//! **relations, then ways, then nodes** -- the reverse of the file order:
13//!
14//! 1. **Relations** decide which ways matter (a boundary's member ways, a route's
15//! member ways).
16//! 2. **Ways** decide which node coordinates matter -- both their own refs and the
17//! refs of the ways relations claimed.
18//! 3. **Nodes** supply those coordinates, and any node-based features.
19//!
20//! Only the passes a layer actually needs are run. `safety` is node-based, so it
21//! runs one. The first pass to run is given `blob_kinds = None`, which is what
22//! makes [`crate::pbf::run_pass`] build the per-blob kind mask that later passes
23//! use to skip whole blobs.
24//!
25//! When way and relation layers land here, their node coordinates must be stored
26//! the way [`crate::poi_build`] does it -- a sorted `Vec` of the needed ids plus an
27//! index-aligned coordinate array, looked up by `binary_search` -- and **not** the
28//! way [`crate::graph_build`] does it. That module allocates a bitset sized from
29//! `BITSET_SIZE = 20e9`, i.e. 2.5 GB keyed by raw node id, and peaks around 10 GB
30//! on California. The sorted-`Vec` form costs 16 bytes per *needed* node, which
31//! for a selected subset is orders of magnitude smaller.
32
33use std::collections::HashMap;
34use std::fs::File;
35use std::io::{BufWriter, Write};
36use std::path::{Path, PathBuf};
37
38use crate::admin::{self, AdminTags};
39use crate::bbox::{self, BBox};
40use crate::geojson::{self, Coord, Feature, Geometry};
41use crate::maxspeed::{self, MaxspeedTags};
42use crate::nodeloc::{resolve_nodes, NodeLocations};
43use crate::osm::{visit_block, Element, Member, MEMBER_WAY};
44use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS};
45use crate::proto::{Error, Result};
46use crate::rings::{self, MemberWay, RingStats};
47use crate::roads::{self, RoadTags};
48use crate::safety::{self, Kind, SafetyTags};
49use crate::select::Select;
50use crate::transit_lines::{self, TransitTags};
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Layer {
54 Safety,
55 Maxspeed,
56 Roads,
57 TransitLines,
58 AdminCity,
59}
60
61impl Layer {
62 pub fn parse(s: &str) -> std::result::Result<Layer, String> {
63 match s {
64 "safety" => Ok(Layer::Safety),
65 "maxspeed" => Ok(Layer::Maxspeed),
66 "roads" => Ok(Layer::Roads),
67 "transit_lines" => Ok(Layer::TransitLines),
68 "admin_city" => Ok(Layer::AdminCity),
69 other => Err(format!(
70 "unknown --layer '{other}'; supported: {}",
71 Layer::names().join(", ")
72 )),
73 }
74 }
75
76 pub fn names() -> Vec<&'static str> {
77 vec!["safety", "maxspeed", "roads", "transit_lines", "admin_city"]
78 }
79
80 pub fn name(self) -> &'static str {
81 match self {
82 Layer::Safety => "safety",
83 Layer::Maxspeed => "maxspeed",
84 Layer::Roads => "roads",
85 Layer::TransitLines => "transit_lines",
86 Layer::AdminCity => "admin_city",
87 }
88 }
89}
90
91pub struct Options {
92 pub layer: Layer,
93 pub bbox: Option<BBox>,
94}
95
96#[derive(Debug, Default, PartialEq)]
97pub struct Stats {
98 pub features: usize,
99 pub from_nodes: usize,
100 pub from_ways: usize,
101 pub from_relations: usize,
102 /// Classified, but outside `--bbox`. Reported so an empty layer can be told
103 /// apart from a badly placed box.
104 pub outside_bbox: usize,
105}
106
107impl Stats {
108 /// A layer assembled from two element kinds, reporting none of one of them.
109 ///
110 /// `transit_lines` is the case that matters: a rail corridor is covered by both
111 /// a `railway=*` way and a `type=route` relation, and only the relation carries
112 /// `colour`, `ref` and the route's `name`. A ways-only layer therefore looks
113 /// full, has the right feature count, and renders every line in the app's grey
114 /// `rail` fallback. It is not proof of a broken build -- a rural extract really
115 /// can hold track that no PTv2 route covers -- so this is a warning, and the
116 /// build scripts own the checks that can be certain.
117 pub fn missing_half(&self, layer: Layer) -> Option<String> {
118 if layer != Layer::TransitLines || self.from_relations > 0 || self.from_ways == 0 {
119 return None;
120 }
121 Some(format!(
122 "{} railway way(s) but 0 route relation(s). Only relations carry `colour`, \
123 `ref` and the route `name`, so every line will render grey.",
124 self.from_ways
125 ))
126 }
127}
128
129pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {
130 // Fail before the passes rather than after them if the output is unwritable.
131 if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
132 std::fs::create_dir_all(parent)
133 .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;
134 }
135
136 let blobs = pbf::scan_blobs(input)?;
137 println!("[extract] Scanned {} data blob(s) in {}", blobs.len(), input.display());
138
139 match opts.layer {
140 Layer::Safety => build_safety(input, &blobs, out, opts),
141 Layer::Maxspeed => build_maxspeed(input, &blobs, out, opts),
142 Layer::Roads => build_roads(input, &blobs, out, opts),
143 Layer::TransitLines => build_transit_lines(input, &blobs, out, opts),
144 Layer::AdminCity => build_admin_city(input, &blobs, out, opts),
145 }
146}
147
148// --- safety ---------------------------------------------------------------
149
150/// One classified node, with the attributes it carries copied out of the block.
151///
152/// The pass borrows tag values from the `PrimitiveBlock` it is reading, which is
153/// dropped when the blob is, so anything kept has to be owned.
154struct SafetyRow {
155 lat_e7: i32,
156 lon_e7: i32,
157 id: i64,
158 kind: Kind,
159 name: Option<String>,
160 direction: Option<String>,
161 operator: Option<String>,
162 reference: Option<String>,
163 surveillance_type: Option<String>,
164}
165
166#[derive(Default)]
167struct SafetyPass {
168 rows: Vec<SafetyRow>,
169 outside_bbox: usize,
170}
171
172fn build_safety(
173 input: &Path,
174 blobs: &[pbf::BlobLoc],
175 out: &Path,
176 opts: &Options,
177) -> Result<Stats> {
178 // The `osmium tags-filter` expression this layer used, as a cheap screen: it
179 // reads three tags to reject almost every node, instead of the ten the
180 // classifier and the property builder would read between them. Tag lookup is
181 // a linear scan, so that matters at planet scale.
182 let select = Select::parse(&safety::FILTERS)?;
183 let bbox = opts.bbox.as_ref();
184
185 let (chunks, _) = pbf::run_pass(
186 input,
187 blobs,
188 None,
189 KIND_NODES,
190 "Pass 1: nodes",
191 SafetyPass::default,
192 |state, block| safety_blob(state, block, &select, bbox),
193 )?;
194
195 let mut rows: Vec<SafetyRow> = Vec::new();
196 let mut outside_bbox = 0usize;
197 for chunk in chunks {
198 rows.extend(chunk.rows);
199 outside_bbox += chunk.outside_bbox;
200 }
201
202 // Deterministic order, so two runs of the same input are byte-identical and a
203 // diff against the previous build shows only real changes. Position first
204 // keeps features that are near each other near each other in the file, which
205 // is what the tiler wants; the id only breaks ties.
206 rows.sort_by_key(|r| (r.lat_e7, r.lon_e7, r.id));
207
208 let mut writer = BufWriter::new(create(out)?);
209 let mut line: Vec<u8> = Vec::new();
210 for row in &rows {
211 let tags = SafetyTags {
212 name: row.name.as_deref(),
213 direction: row.direction.as_deref(),
214 operator: row.operator.as_deref(),
215 reference: row.reference.as_deref(),
216 surveillance_type: row.surveillance_type.as_deref(),
217 ..Default::default()
218 };
219 let f: Feature = safety::feature(
220 row.kind,
221 &tags,
222 row.lon_e7 as f64 * 1e-7,
223 row.lat_e7 as f64 * 1e-7,
224 row.id,
225 );
226 geojson::write_feature(&mut writer, &f, &mut line).map_err(io_err)?;
227 }
228 writer.flush().map_err(io_err)?;
229
230 println!(
231 "Wrote {} safety feature(s) to {}",
232 rows.len(),
233 out.display()
234 );
235 if outside_bbox > 0 {
236 println!("{outside_bbox} feature(s) dropped by --bbox");
237 }
238 Ok(Stats {
239 features: rows.len(),
240 from_nodes: rows.len(),
241 from_ways: 0,
242 from_relations: 0,
243 outside_bbox,
244 })
245}
246
247fn safety_blob(
248 state: &mut SafetyPass,
249 block: &pbf::PrimitiveBlock,
250 select: &Select,
251 bbox: Option<&BBox>,
252) -> Result<u8> {
253 let mut kinds = 0u8;
254 visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {
255 if let Element::Node(n) = el {
256 if n.tags.is_empty() {
257 return Ok(());
258 }
259 if !select.matches(|k| n.tags.get_str(k)) {
260 return Ok(());
261 }
262 let t = SafetyTags {
263 highway: n.tags.get_str("highway"),
264 man_made: n.tags.get_str("man_made"),
265 enforcement: n.tags.get_str("enforcement"),
266 surveillance_type: n.tags.get_str("surveillance:type"),
267 camera_type: n.tags.get_str("camera:type"),
268 operator: n.tags.get_str("operator"),
269 manufacturer: n.tags.get_str("manufacturer"),
270 name: n.tags.get_str("name"),
271 direction: n.tags.get_str("direction"),
272 reference: n.tags.get_str("ref"),
273 };
274 let Some(kind) = safety::classify(&t) else {
275 return Ok(());
276 };
277 // Counted after classification, so the number means "safety features
278 // outside the box" rather than "nodes outside the box".
279 if !bbox::keep_e7(bbox, n.lat_e7, n.lon_e7) {
280 state.outside_bbox += 1;
281 return Ok(());
282 }
283 state.rows.push(SafetyRow {
284 lat_e7: n.lat_e7,
285 lon_e7: n.lon_e7,
286 id: n.id,
287 kind,
288 name: t.name.map(str::to_string),
289 direction: t.direction.map(str::to_string),
290 operator: t.operator.map(str::to_string),
291 reference: t.reference.map(str::to_string),
292 surveillance_type: t.surveillance_type.map(str::to_string),
293 });
294 }
295 Ok(())
296 })?;
297 Ok(kinds)
298}
299
300// --- maxspeed -------------------------------------------------------------
301
302/// One way with a posted limit, with its tag values copied out of the block.
303struct MaxspeedRow {
304 id: i64,
305 refs: Vec<i64>,
306 maxspeed: String,
307 highway: Option<String>,
308 name: Option<String>,
309}
310
311fn build_maxspeed(
312 input: &Path,
313 blobs: &[pbf::BlobLoc],
314 out: &Path,
315 opts: &Options,
316) -> Result<Stats> {
317 let select = Select::parse(&maxspeed::FILTERS)?;
318
319 // Pass 1 runs with `blob_kinds = None`, which is what makes run_pass build the
320 // per-blob kind mask the node pass then uses to skip node-only blobs.
321 let (chunks, blob_kinds) = pbf::run_pass(
322 input,
323 blobs,
324 None,
325 KIND_WAYS,
326 "Pass 1: ways",
327 Vec::<MaxspeedRow>::new,
328 |state: &mut Vec<MaxspeedRow>, block| maxspeed_blob(state, block, &select),
329 )?;
330 let mut rows: Vec<MaxspeedRow> = Vec::new();
331 for chunk in chunks {
332 rows.extend(chunk);
333 }
334 println!("{} way(s) with a posted limit", rows.len());
335
336 let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect())?;
337 println!("{} node location(s) needed", table.len());
338 let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?;
339
340 let mut lines: Vec<LineFeature> = Vec::with_capacity(rows.len());
341 let mut outside_bbox = 0usize;
342 for row in &rows {
343 let coords = table.line(&row.refs);
344 if coords.len() < 2 {
345 continue;
346 }
347 if !parts_touch_bbox(std::slice::from_ref(&coords), opts.bbox.as_ref()) {
348 outside_bbox += 1;
349 continue;
350 }
351 let t = MaxspeedTags {
352 maxspeed: Some(row.maxspeed.as_str()),
353 highway: row.highway.as_deref(),
354 name: row.name.as_deref(),
355 ..Default::default()
356 };
357 let f = maxspeed::feature(&row.maxspeed, &t, Geometry::LineString(coords), row.id);
358 lines.push(LineFeature { sort: ("way", row.id), rendered: render(&f) });
359 }
360
361 let written = write_lines(out, lines)?;
362 println!("Wrote {} maxspeed feature(s) to {}", written, out.display());
363 if outside_bbox > 0 {
364 println!("{outside_bbox} feature(s) dropped by --bbox");
365 }
366 Ok(Stats {
367 features: written,
368 from_nodes: 0,
369 from_ways: written,
370 from_relations: 0,
371 outside_bbox,
372 })
373}
374
375fn maxspeed_blob(
376 state: &mut Vec<MaxspeedRow>,
377 block: &pbf::PrimitiveBlock,
378 select: &Select,
379) -> Result<u8> {
380 let mut kinds = 0u8;
381 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
382 if let Element::Way(w) = el {
383 if w.refs.len() < 2 || w.tags.is_empty() {
384 return Ok(());
385 }
386 if !select.matches(|k| w.tags.get_str(k)) {
387 return Ok(());
388 }
389 let t = MaxspeedTags {
390 maxspeed: w.tags.get_str("maxspeed"),
391 maxspeed_forward: w.tags.get_str("maxspeed:forward"),
392 maxspeed_backward: w.tags.get_str("maxspeed:backward"),
393 highway: w.tags.get_str("highway"),
394 name: w.tags.get_str("name"),
395 };
396 if let Some(value) = maxspeed::extract(&t) {
397 state.push(MaxspeedRow {
398 id: w.id,
399 refs: w.refs.to_vec(),
400 maxspeed: value.to_string(),
401 highway: t.highway.map(str::to_string),
402 name: t.name.map(str::to_string),
403 });
404 }
405 }
406 Ok(())
407 })?;
408 Ok(kinds)
409}
410
411// --- roads ----------------------------------------------------------------
412
413/// One road way, with every tag value the layer emits copied out of the block.
414///
415/// The tag strings are owned because the pass borrows them from the
416/// `PrimitiveBlock` it is reading, which is dropped with the blob. Thirteen
417/// `Option<String>` per road is the one place this layer is heavier than
418/// `maxspeed`, and since this is every road rather than only the ones with a posted
419/// limit, `build_roads` consumes the rows as it renders them rather than holding
420/// both the rows and the output at once.
421struct RoadRow {
422 id: i64,
423 refs: Vec<i64>,
424 class: u8,
425 maxspeed: Option<String>,
426 lanes: Option<String>,
427 lanes_forward: Option<String>,
428 lanes_backward: Option<String>,
429 turn_lanes: Option<String>,
430 turn_lanes_forward: Option<String>,
431 turn_lanes_backward: Option<String>,
432 oneway: Option<String>,
433 width: Option<String>,
434 bridge: Option<String>,
435 tunnel: Option<String>,
436 layer: Option<String>,
437}
438
439include!("extract_part1.rs");
440include!("extract_part2.rs");
441include!("extract_part3.rs");