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

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

poi_build_s1.rs403 lines · 15.0 KiBRaw
1#[allow(clippy::too_many_arguments)]
2fn build_inner(
3 input: &Path,
4 geojson: &Path,
5 names: &Path,
6 index: &Path,
7 attrs: &Path,
8 spatial: &Path,
9 name_index: &Path,
10 region: &Path,
11 bbox: Option<crate::bbox::BBox>,
12 mut reviews: Reviews<'_>,
13) -> Result<Stats> {
14 // Fail before the three passes rather than after them if an output path is
15 // unwritable.
16 for path in [geojson, names, index, attrs, spatial, name_index, region] {
17 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
18 std::fs::create_dir_all(parent)
19 .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;
20 }
21 }
22
23 let mut timer = crate::timing::PhaseTimer::start("poi");
24 let blobs = pbf::scan_blobs(input)?;
25 println!("[poi] Scanned {} data blob(s) in {}", blobs.len(), input.display());
26
27 timer.switch("relations");
28 // --- Pass 1: area relations ---------------------------------------------
29 let (chunks, blob_kinds) = pbf::run_pass(
30 input,
31 &blobs,
32 None,
33 KIND_RELATIONS,
34 "Pass 1: relations",
35 RelPass::default,
36 relation_blob,
37 )?;
38 let mut rel_areas: Vec<RelArea> = Vec::new();
39 let mut boundaries: Vec<BoundaryRel> = Vec::new();
40 for chunk in chunks {
41 rel_areas.extend(chunk.areas);
42 boundaries.extend(chunk.boundaries);
43 }
44 let mut outer_wanted: Vec<i64> = rel_areas
45 .iter()
46 .flat_map(|a| a.outer_ways.iter().copied())
47 .chain(boundaries.iter().flat_map(|b| b.member_ways.iter().map(|(w, _)| *w)))
48 .collect();
49 par_sort_dedup(&mut outer_wanted);
50 println!("{} POI relation(s)", rel_areas.len());
51 reviews.poll()?;
52
53 timer.switch("ways");
54 // --- Pass 2: closed-way areas + the relations' outer ways ----------------
55 let (chunks, _) = pbf::run_pass(
56 input,
57 &blobs,
58 Some(&blob_kinds),
59 KIND_WAYS,
60 "Pass 2: ways",
61 WayPass::default,
62 |state, block| way_blob(state, block, &outer_wanted),
63 )?;
64 let mut way_areas: Vec<WayArea> = Vec::new();
65 let mut outer_refs: HashMap<i64, Vec<i64>> = HashMap::new();
66 for chunk in chunks {
67 way_areas.extend(chunk.areas);
68 outer_refs.extend(chunk.outer_refs);
69 }
70
71 // Every node whose location an area centroid needs.
72 let mut needed: Vec<i64> = way_areas
73 .iter()
74 .flat_map(|a| a.refs.iter().copied())
75 .chain(outer_refs.values().flat_map(|r| r.iter().copied()))
76 .collect();
77 par_sort_dedup(&mut needed);
78 println!("{} closed-way area(s), {} node location(s) needed", way_areas.len(), needed.len());
79
80 reviews.poll()?;
81 timer.switch("nodes");
82 // --- Pass 3: node POIs + the node locations areas need -------------------
83 let (chunks, _) = pbf::run_pass(
84 input,
85 &blobs,
86 Some(&blob_kinds),
87 KIND_NODES,
88 "Pass 3: nodes",
89 NodePass::default,
90 |state, block| node_blob(state, block, &needed, bbox.as_ref()),
91 )?;
92 let mut pois: Vec<Poi> = Vec::new();
93 let mut locs: Vec<(i32, i32)> = vec![(NO_LOC, NO_LOC); needed.len()];
94 for chunk in chunks {
95 pois.extend(chunk.pois);
96 for (idx, lat, lon) in chunk.locs {
97 locs[idx as usize] = (lat, lon);
98 }
99 }
100 let from_nodes = pois.len();
101
102 let location = |id: i64| -> Option<(i32, i32)> {
103 let idx = needed.binary_search(&id).ok()?;
104 let (lat, lon) = locs[idx];
105 (lat != NO_LOC).then_some((lat, lon))
106 };
107
108 // A POI touches the region when any of its vertices does — same
109 // `complete_ways` rule as the graph. The centroid is computed from the
110 // whole ring regardless, so a border-straddling POI keeps its true
111 // location.
112 let touches = |ids: &mut dyn Iterator<Item = i64>| -> bool {
113 let Some(b) = bbox.as_ref() else {
114 return true;
115 };
116 ids.filter_map(&location).any(|(lat, lon)| b.contains_e7(lat, lon))
117 };
118
119 timer.switch("centroids");
120 // --- Area centroids ------------------------------------------------------
121 // Each area's POI depends on that area alone; `collect` keeps area order, so
122 // `pois` comes out exactly as the serial loop pushed it.
123 use rayon::prelude::*;
124 let way_pois: Vec<Option<Poi>> = crate::par::install(|| {
125 way_areas
126 .par_iter()
127 .with_min_len(256)
128 .map(|area| {
129 if !touches(&mut area.refs.iter().copied()) {
130 return None;
131 }
132 // A closed way's ring is its own node list minus the repeated
133 // closing node.
134 let poi =
135 ring_centroid(area.refs[..area.refs.len() - 1].iter().copied(), &location)?;
136 Some(make_poi(
137 poi,
138 area.type_,
139 area.id,
140 &area.name,
141 area.attrs.clone(),
142 area.self_region,
143 area.place_cap,
144 ))
145 })
146 .collect()
147 });
148 pois.extend(way_pois.into_iter().flatten());
149 let from_ways = pois.len() - from_nodes;
150
151 let rel_pois: Vec<Option<Poi>> = crate::par::install(|| {
152 rel_areas
153 .par_iter()
154 .with_max_len(16)
155 .map(|area| {
156 // libosmium assembled a true ring from the member ways; we cannot,
157 // so deduplicate the member node ids instead. That is exact when
158 // the outer ring is a single closed way, and drops the endpoints
159 // shared between consecutive ways when it is split across several.
160 let mut refs: Vec<i64> = area
161 .outer_ways
162 .iter()
163 .filter_map(|w| outer_refs.get(w))
164 .flat_map(|r| r.iter().copied())
165 .collect();
166 refs.sort_unstable();
167 refs.dedup();
168 if !touches(&mut refs.iter().copied()) {
169 return None;
170 }
171 let poi = ring_centroid(refs.iter().copied(), &location)?;
172 Some(make_poi(
173 poi,
174 area.type_,
175 -area.id,
176 &area.name,
177 area.attrs.clone(),
178 area.self_region,
179 area.place_cap,
180 ))
181 })
182 .collect()
183 });
184 pois.extend(rel_pois.into_iter().flatten());
185 let from_relations = pois.len() - from_nodes - from_ways;
186 println!(
187 "Extracted {} POI(s): {from_nodes} node, {from_ways} closed-way, {from_relations} relation",
188 pois.len()
189 );
190
191 // Before the sort: `pois` is still nodes, then ways, then relations, which is
192 // the only place the OSM element type is known.
193 timer.switch("reviews-wait");
194 reviews.join()?;
195 timer.switch("reviews");
196 let with_reviews = match reviews.table() {
197 Some(table) => {
198 let n = apply_reviews(&mut pois, from_nodes, from_ways, table);
199 println!("{n} POI(s) with review data ({} review row(s) loaded)", table.len());
200 n
201 }
202 None => 0,
203 };
204
205 // Before the sort: `pois` is still nodes, then ways, then relations, which is
206 // the only place the OSM element type is known. Region links resolve here
207 // for the same reason reviews do — and the stamped ids ride the Morton sort
208 // on the `Poi` struct, so `poi_region.bin` joins by ordinal afterwards.
209 timer.switch("regions-assemble");
210 let assembled = assemble_boundaries(&boundaries, &outer_refs, &location);
211 timer.switch("regions-stamp");
212 let with_region = stamp_regions(&mut pois, from_nodes, &boundaries, &assembled);
213 if with_region > 0 {
214 println!("{with_region} POI(s) with a boundary link");
215 }
216
217 // Morton order, ties broken by osm_id, so both poi_index.bin and the geojson
218 // are stable across runs.
219 timer.switch("sort");
220 // `par_sort_by_key` is stable like `sort_by_key`, so equal keys keep the
221 // pre-sort (nodes, ways, relations) order exactly as before.
222 crate::par::install(|| pois.par_sort_by_key(|p| (p.morton, p.osm_id)));
223
224 let written = write_outputs(
225 &pois, geojson, names, index, attrs, spatial, name_index, region, &mut timer,
226 )?;
227 // `poi_admin.bin` rides beside `poi_region.bin` (no new flag, so every caller emits it).
228 timer.switch("admin");
229 let admin = admin_table(&boundaries, &assembled, &pois);
230 let admin_entries = write_with(&region.with_file_name("poi_admin.bin"), |out| {
231 crate::poi_admin::write_admin(out, &admin)
232 })?;
233 println!("Wrote {admin_entries} administrative boundar(ies) to poi_admin.bin");
234 timer.finish();
235 Ok(Stats {
236 records: written.records,
237 unique_names: written.unique_names,
238 name_bytes: written.name_bytes,
239 from_nodes,
240 from_ways,
241 from_relations,
242 with_attrs: written.with_attrs,
243 unique_attrs: written.unique_attrs,
244 attr_bytes: written.attr_bytes,
245 spatial_cells: written.spatial_cells,
246 name_entries: written.name_entries,
247 with_reviews,
248 with_region,
249 admin_entries,
250 })
251}
252
253/// Append each matching review row to its POI's attribute body; returns the match
254/// count. `pois[..from_nodes]` are nodes, the next `from_ways` closed ways, the
255/// rest relations (whose `osm_id` is stored negated).
256fn apply_reviews(
257 pois: &mut [Poi],
258 from_nodes: usize,
259 from_ways: usize,
260 table: &ReviewTable,
261) -> usize {
262 use rayon::prelude::*;
263 // Per-POI and independent, so chunking cannot change any POI's body.
264 crate::par::install(|| {
265 pois.par_iter_mut()
266 .enumerate()
267 .with_min_len(4096)
268 .map(|(i, p)| {
269 let (element, id) = if i < from_nodes {
270 (ELEMENT_NODE, p.osm_id)
271 } else if i < from_nodes + from_ways {
272 (ELEMENT_WAY, p.osm_id)
273 } else {
274 (ELEMENT_RELATION, -p.osm_id)
275 };
276 match table.get(element, id) {
277 Some(review) => {
278 p.attrs = crate::poi_attrs::append(
279 std::mem::take(&mut p.attrs),
280 &review.fields(),
281 );
282 true
283 }
284 None => false,
285 }
286 })
287 .filter(|hit| *hit)
288 .count()
289 })
290}
291
292/// Sort ascending and drop duplicates. The values are plain integers, so an
293/// unstable parallel sort yields exactly the serial `sort_unstable` + `dedup`.
294fn par_sort_dedup(v: &mut Vec<i64>) {
295 use rayon::prelude::*;
296 crate::par::install(|| v.par_sort_unstable());
297 v.dedup();
298}
299
300fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> {
301 PoiTags {
302 railway: t.get_str("railway"),
303 public_transport: t.get_str("public_transport"),
304 amenity: t.get_str("amenity"),
305 shop: t.get_str("shop"),
306 tourism: t.get_str("tourism"),
307 leisure: t.get_str("leisure"),
308 healthcare: t.get_str("healthcare"),
309 office: t.get_str("office"),
310 place: t.get_str("place"),
311 }
312}
313
314/// Deepest `admin_level` a place POI may link to, from its `place` value:
315/// a country links at level 2, a state/province at 4, everything else (cities
316/// down to neighbourhoods) at 8. Non-place POIs link at any level.
317fn place_level_cap(place: Option<&str>) -> u8 {
318 match place {
319 Some("country") => 2,
320 Some("state" | "province") => 4,
321 Some(_) => 8,
322 None => 8,
323 }
324}
325
326fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8> {
327 let mut kinds = 0u8;
328 visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| {
329 if let Element::Relation(r) = el {
330 // Boundary relations feed the region-link geometry whether or not they
331 // are POIs themselves. A `boundary=administrative` relation is
332 // linkable when it carries an `admin_level`; `type=boundary` without
333 // one still assembles but links at the deepest level.
334 if r.tags.get_str("type") == Some("boundary")
335 && r.tags.get_str("boundary") == Some("administrative")
336 {
337 let admin_level: u8 =
338 r.tags.get_str("admin_level").and_then(|v| v.parse().ok()).unwrap_or(8);
339 state.boundaries.push(BoundaryRel {
340 id: r.id,
341 admin_level,
342 name: r.tags.get("name").map(|v| v.to_vec()).unwrap_or_default(),
343 name_en: r.tags.get("name:en").map(|v| v.to_vec()).unwrap_or_default(),
344 member_ways: r
345 .members
346 .iter()
347 .filter(|m| {
348 m.kind == MEMBER_WAY
349 && (m.role == b"outer" || m.role == b"inner" || m.role.is_empty())
350 })
351 .map(|m| (m.id, m.role != b"inner"))
352 .collect(),
353 label_nodes: r
354 .members
355 .iter()
356 .filter(|m| {
357 m.kind == MEMBER_NODE
358 && (m.role == b"label" || m.role == b"admin_centre")
359 })
360 .map(|m| m.id)
361 .collect(),
362 });
363 // A boundary relation with a name and POI tags is still a POI in its
364 // own right (a national park on the relation, a `place` label on the
365 // boundary). Fall through to the area path below.
366 }
367 let is_area = r.tags.get_str("type").is_some_and(|t| AREA_RELATION_TYPES.contains(&t));
368 if !is_area {
369 return Ok(());
370 }
371 let name = match r.tags.get("name") {
372 Some(n) if !n.is_empty() => n,
373 _ => return Ok(()),
374 };
375 if let Some(type_) = tags::classify(&poi_tags(&r.tags)) {
376 let self_region = if r.tags.get_str("boundary") == Some("administrative") {
377 poi_side::tag_relation(r.id)
378 } else {
379 poi_side::REGION_NONE
380 };
381 state.areas.push(RelArea {
382 id: r.id,
383 type_,
384 name: name.to_vec(),
385 attrs: crate::poi_attrs::encode(|k| r.tags.get(k)),
386 outer_ways: r
387 .members
388 .iter()
389 .filter(|m| {
390 m.kind == MEMBER_WAY && (m.role == b"outer" || m.role.is_empty())
391 })
392 .map(|m| m.id)
393 .collect(),
394 self_region,
395 place_cap: place_level_cap(r.tags.get_str("place")),
396 });
397 }
398 }
399 Ok(())
400 })?;
401 Ok(kinds)
402}
403