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

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

extract.rs431 lines · 15.3 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 => {
70 Err(format!("unknown --layer '{other}'; supported: {}", Layer::names().join(", ")))
71 }
72 }
73 }
74
75 pub fn names() -> Vec<&'static str> {
76 vec!["safety", "maxspeed", "roads", "transit_lines", "admin_city"]
77 }
78
79 pub fn name(self) -> &'static str {
80 match self {
81 Layer::Safety => "safety",
82 Layer::Maxspeed => "maxspeed",
83 Layer::Roads => "roads",
84 Layer::TransitLines => "transit_lines",
85 Layer::AdminCity => "admin_city",
86 }
87 }
88}
89
90pub struct Options {
91 pub layer: Layer,
92 pub bbox: Option<BBox>,
93}
94
95#[derive(Debug, Default, PartialEq)]
96pub struct Stats {
97 pub features: usize,
98 pub from_nodes: usize,
99 pub from_ways: usize,
100 pub from_relations: usize,
101 /// Classified, but outside `--bbox`. Reported so an empty layer can be told
102 /// apart from a badly placed box.
103 pub outside_bbox: usize,
104}
105
106impl Stats {
107 /// A layer assembled from two element kinds, reporting none of one of them.
108 ///
109 /// `transit_lines` is the case that matters: a rail corridor is covered by both
110 /// a `railway=*` way and a `type=route` relation, and only the relation carries
111 /// `colour`, `ref` and the route's `name`. A ways-only layer therefore looks
112 /// full, has the right feature count, and renders every line in the app's grey
113 /// `rail` fallback. It is not proof of a broken build -- a rural extract really
114 /// can hold track that no PTv2 route covers -- so this is a warning, and the
115 /// build scripts own the checks that can be certain.
116 pub fn missing_half(&self, layer: Layer) -> Option<String> {
117 if layer != Layer::TransitLines || self.from_relations > 0 || self.from_ways == 0 {
118 return None;
119 }
120 Some(format!(
121 "{} railway way(s) but 0 route relation(s). Only relations carry `colour`, \
122 `ref` and the route `name`, so every line will render grey.",
123 self.from_ways
124 ))
125 }
126}
127
128pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {
129 // Fail before the passes rather than after them if the output is unwritable.
130 if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
131 std::fs::create_dir_all(parent)
132 .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;
133 }
134
135 let blobs = pbf::scan_blobs(input)?;
136 println!("[extract] Scanned {} data blob(s) in {}", blobs.len(), input.display());
137
138 match opts.layer {
139 Layer::Safety => build_safety(input, &blobs, out, opts),
140 Layer::Maxspeed => build_maxspeed(input, &blobs, out, opts),
141 Layer::Roads => build_roads(input, &blobs, out, opts),
142 Layer::TransitLines => build_transit_lines(input, &blobs, out, opts),
143 Layer::AdminCity => build_admin_city(input, &blobs, out, opts),
144 }
145}
146
147// --- safety ---------------------------------------------------------------
148
149/// One classified node, with the attributes it carries copied out of the block.
150///
151/// The pass borrows tag values from the `PrimitiveBlock` it is reading, which is
152/// dropped when the blob is, so anything kept has to be owned.
153struct SafetyRow {
154 lat_e7: i32,
155 lon_e7: i32,
156 id: i64,
157 kind: Kind,
158 name: Option<String>,
159 direction: Option<String>,
160 operator: Option<String>,
161 reference: Option<String>,
162 surveillance_type: Option<String>,
163}
164
165#[derive(Default)]
166struct SafetyPass {
167 rows: Vec<SafetyRow>,
168 outside_bbox: usize,
169}
170
171fn build_safety(input: &Path, blobs: &[pbf::BlobLoc], out: &Path, opts: &Options) -> Result<Stats> {
172 // The `osmium tags-filter` expression this layer used, as a cheap screen: it
173 // reads three tags to reject almost every node, instead of the ten the
174 // classifier and the property builder would read between them. Tag lookup is
175 // a linear scan, so that matters at planet scale.
176 let select = Select::parse(&safety::FILTERS)?;
177 let bbox = opts.bbox.as_ref();
178
179 let (chunks, _) = pbf::run_pass(
180 input,
181 blobs,
182 None,
183 KIND_NODES,
184 "Pass 1: nodes",
185 SafetyPass::default,
186 |state, block| safety_blob(state, block, &select, bbox),
187 )?;
188
189 let mut rows: Vec<SafetyRow> = Vec::new();
190 let mut outside_bbox = 0usize;
191 for chunk in chunks {
192 rows.extend(chunk.rows);
193 outside_bbox += chunk.outside_bbox;
194 }
195
196 // Deterministic order, so two runs of the same input are byte-identical and a
197 // diff against the previous build shows only real changes. Position first
198 // keeps features that are near each other near each other in the file, which
199 // is what the tiler wants; the id only breaks ties.
200 rows.sort_by_key(|r| (r.lat_e7, r.lon_e7, r.id));
201
202 let mut writer = BufWriter::new(create(out)?);
203 let mut line: Vec<u8> = Vec::new();
204 for row in &rows {
205 let tags = SafetyTags {
206 name: row.name.as_deref(),
207 direction: row.direction.as_deref(),
208 operator: row.operator.as_deref(),
209 reference: row.reference.as_deref(),
210 surveillance_type: row.surveillance_type.as_deref(),
211 ..Default::default()
212 };
213 let f: Feature = safety::feature(
214 row.kind,
215 &tags,
216 row.lon_e7 as f64 * 1e-7,
217 row.lat_e7 as f64 * 1e-7,
218 row.id,
219 );
220 geojson::write_feature(&mut writer, &f, &mut line).map_err(io_err)?;
221 }
222 writer.flush().map_err(io_err)?;
223
224 println!("Wrote {} safety feature(s) to {}", rows.len(), out.display());
225 if outside_bbox > 0 {
226 println!("{outside_bbox} feature(s) dropped by --bbox");
227 }
228 Ok(Stats {
229 features: rows.len(),
230 from_nodes: rows.len(),
231 from_ways: 0,
232 from_relations: 0,
233 outside_bbox,
234 })
235}
236
237fn safety_blob(
238 state: &mut SafetyPass,
239 block: &pbf::PrimitiveBlock,
240 select: &Select,
241 bbox: Option<&BBox>,
242) -> Result<u8> {
243 let mut kinds = 0u8;
244 visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {
245 if let Element::Node(n) = el {
246 if n.tags.is_empty() {
247 return Ok(());
248 }
249 if !select.matches(|k| n.tags.get_str(k)) {
250 return Ok(());
251 }
252 let t = SafetyTags {
253 highway: n.tags.get_str("highway"),
254 man_made: n.tags.get_str("man_made"),
255 enforcement: n.tags.get_str("enforcement"),
256 surveillance_type: n.tags.get_str("surveillance:type"),
257 camera_type: n.tags.get_str("camera:type"),
258 operator: n.tags.get_str("operator"),
259 manufacturer: n.tags.get_str("manufacturer"),
260 name: n.tags.get_str("name"),
261 direction: n.tags.get_str("direction"),
262 reference: n.tags.get_str("ref"),
263 };
264 let Some(kind) = safety::classify(&t) else {
265 return Ok(());
266 };
267 // Counted after classification, so the number means "safety features
268 // outside the box" rather than "nodes outside the box".
269 if !bbox::keep_e7(bbox, n.lat_e7, n.lon_e7) {
270 state.outside_bbox += 1;
271 return Ok(());
272 }
273 state.rows.push(SafetyRow {
274 lat_e7: n.lat_e7,
275 lon_e7: n.lon_e7,
276 id: n.id,
277 kind,
278 name: t.name.map(str::to_string),
279 direction: t.direction.map(str::to_string),
280 operator: t.operator.map(str::to_string),
281 reference: t.reference.map(str::to_string),
282 surveillance_type: t.surveillance_type.map(str::to_string),
283 });
284 }
285 Ok(())
286 })?;
287 Ok(kinds)
288}
289
290// --- maxspeed -------------------------------------------------------------
291
292/// One way with a posted limit, with its tag values copied out of the block.
293struct MaxspeedRow {
294 id: i64,
295 refs: Vec<i64>,
296 maxspeed: String,
297 highway: Option<String>,
298 name: Option<String>,
299}
300
301fn build_maxspeed(
302 input: &Path,
303 blobs: &[pbf::BlobLoc],
304 out: &Path,
305 opts: &Options,
306) -> Result<Stats> {
307 let select = Select::parse(&maxspeed::FILTERS)?;
308
309 // Pass 1 runs with `blob_kinds = None`, which is what makes run_pass build the
310 // per-blob kind mask the node pass then uses to skip node-only blobs.
311 let (chunks, blob_kinds) = pbf::run_pass(
312 input,
313 blobs,
314 None,
315 KIND_WAYS,
316 "Pass 1: ways",
317 Vec::<MaxspeedRow>::new,
318 |state: &mut Vec<MaxspeedRow>, block| maxspeed_blob(state, block, &select),
319 )?;
320 let mut rows: Vec<MaxspeedRow> = Vec::new();
321 for chunk in chunks {
322 rows.extend(chunk);
323 }
324 println!("{} way(s) with a posted limit", rows.len());
325
326 let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect())?;
327 println!("{} node location(s) needed", table.len());
328 let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?;
329
330 let mut lines: Vec<LineFeature> = Vec::with_capacity(rows.len());
331 let mut outside_bbox = 0usize;
332 for row in &rows {
333 let coords = table.line(&row.refs);
334 if coords.len() < 2 {
335 continue;
336 }
337 if !parts_touch_bbox(std::slice::from_ref(&coords), opts.bbox.as_ref()) {
338 outside_bbox += 1;
339 continue;
340 }
341 let t = MaxspeedTags {
342 maxspeed: Some(row.maxspeed.as_str()),
343 highway: row.highway.as_deref(),
344 name: row.name.as_deref(),
345 ..Default::default()
346 };
347 let f = maxspeed::feature(&row.maxspeed, &t, Geometry::LineString(coords), row.id);
348 lines.push(LineFeature { sort: ("way", row.id), rendered: render(&f) });
349 }
350
351 let written = write_lines(out, lines)?;
352 println!("Wrote {} maxspeed feature(s) to {}", written, out.display());
353 if outside_bbox > 0 {
354 println!("{outside_bbox} feature(s) dropped by --bbox");
355 }
356 Ok(Stats {
357 features: written,
358 from_nodes: 0,
359 from_ways: written,
360 from_relations: 0,
361 outside_bbox,
362 })
363}
364
365fn maxspeed_blob(
366 state: &mut Vec<MaxspeedRow>,
367 block: &pbf::PrimitiveBlock,
368 select: &Select,
369) -> Result<u8> {
370 let mut kinds = 0u8;
371 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
372 if let Element::Way(w) = el {
373 if w.refs.len() < 2 || w.tags.is_empty() {
374 return Ok(());
375 }
376 if !select.matches(|k| w.tags.get_str(k)) {
377 return Ok(());
378 }
379 let t = MaxspeedTags {
380 maxspeed: w.tags.get_str("maxspeed"),
381 maxspeed_forward: w.tags.get_str("maxspeed:forward"),
382 maxspeed_backward: w.tags.get_str("maxspeed:backward"),
383 highway: w.tags.get_str("highway"),
384 name: w.tags.get_str("name"),
385 };
386 if let Some(value) = maxspeed::extract(&t) {
387 state.push(MaxspeedRow {
388 id: w.id,
389 refs: w.refs.to_vec(),
390 maxspeed: value.to_string(),
391 highway: t.highway.map(str::to_string),
392 name: t.name.map(str::to_string),
393 });
394 }
395 }
396 Ok(())
397 })?;
398 Ok(kinds)
399}
400
401// --- roads ----------------------------------------------------------------
402
403/// One road way, with every tag value the layer emits copied out of the block.
404///
405/// The tag strings are owned because the pass borrows them from the
406/// `PrimitiveBlock` it is reading, which is dropped with the blob. Thirteen
407/// `Option<String>` per road is the one place this layer is heavier than
408/// `maxspeed`, and since this is every road rather than only the ones with a posted
409/// limit, `build_roads` consumes the rows as it renders them rather than holding
410/// both the rows and the output at once.
411struct RoadRow {
412 id: i64,
413 refs: Vec<i64>,
414 class: u8,
415 maxspeed: Option<String>,
416 lanes: Option<String>,
417 lanes_forward: Option<String>,
418 lanes_backward: Option<String>,
419 turn_lanes: Option<String>,
420 turn_lanes_forward: Option<String>,
421 turn_lanes_backward: Option<String>,
422 oneway: Option<String>,
423 width: Option<String>,
424 bridge: Option<String>,
425 tunnel: Option<String>,
426 layer: Option<String>,
427}
428
429include!("extract_part1.rs");
430include!("extract_part2.rs");
431include!("extract_part3.rs");