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

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

poi_build.rs313 lines · 10.9 KiBRaw
1//! POI extraction: `.osm.pbf` -> a geojsonseq for tippecanoe plus
2//! `poi_names.bin`, `poi_index.bin` and `poi_attrs.bin`.
3//!
4//! A port of the former `scripts/maps/poi_extract.cpp`. The seven outputs are
5//! mutually consistent — same POI set, same order, same coordinates:
6//!
7//! 1. **geojsonseq** newline-delimited GeoJSON `Point` features, fed to
8//! tippecanoe to build the `ma_pois` source layer. Properties: `name`
9//! (string), `type` (number), `osm_id` (number).
10//! 2. **`poi_names.bin`** deduped NUL-terminated UTF-8 name table; a "name start
11//! index" is the byte offset of a name's first byte (the same convention as
12//! `road_names.bin`).
13//! 3. **`poi_index.bin`** flat 14-byte little-endian records —
14//! `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type` — sorted by the 64-bit
15//! Morton key of `(lat, lon)`, so the app can mmap and binary-scan a spatial
16//! range. The record contract lives in
17//! `maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt`.
18//! 4. **`poi_attrs.bin`** the attribute sidecar: opening hours, phone, website,
19//! address, cuisine and wheelchair access, indexed by the ORDINAL of the
20//! matching `poi_index.bin` record. See [`crate::poi_attrs`] for the layout.
21//! Kept separate because the 14-byte record is full and its width is load
22//! bearing in three places.
23//! 5. **`poi_spatial.bin`** coarse-grid CSR over the record coordinates, so the
24//! app can jump to a spatial range. See [`crate::poi_side`].
25//! 6. **`poi_name_index.bin`** word-level inverted index into the record
26//! ordinals for name search. See [`crate::poi_side`].
27//! 7. **`poi_region.bin`** one tagged OSM boundary id per record ordinal — the
28//! member link first, else the smallest containing administrative boundary —
29//! so the app can mask search results to a region. Zero where the POI
30//! matched nothing. See [`crate::poi_side`].
31//! 8. **`poi_admin.bin`** the hierarchy behind those links: name, `name:en`,
32//! `admin_level` and parent of every linked boundary and its ancestors,
33//! written beside `poi_region.bin`. See [`crate::poi_admin`].
34//!
35//! A POI is any node, or closed-way / multipolygon area, carrying BOTH a `name`
36//! and one of the recognised POI keys (see [`crate::tags::classify`]). Area
37//! geometry is reduced to a representative centroid because POIs render as
38//! points.
39//!
40//! ## Where this differs from the libosmium version
41//!
42//! libosmium assembled true polygon rings (`MultipolygonManager` + `Assembler`).
43//! Porting a ring assembler is a large piece of work on its own, so a relation's
44//! outer ring is approximated by the deduplicated node ids of its `outer`-role
45//! member ways. That is exact when the ring is a single closed way; when it is
46//! split across several, the ring's true vertex order is lost and the centroid
47//! shifts by a few metres at most. Node- and closed-way-derived POIs match the
48//! old tool exactly.
49
50use std::collections::HashMap;
51use std::fs::File;
52use std::io::{BufWriter, Write};
53use std::path::{Path, PathBuf};
54
55use crate::geojson::{json_escape, Coord};
56use crate::names::NamePool;
57use crate::osm::{self, visit_block, Element, MEMBER_NODE, MEMBER_WAY};
58use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS};
59use crate::poi_attrs::AttrPool;
60use crate::poi_reviews::{ReviewTable, ELEMENT_NODE, ELEMENT_RELATION, ELEMENT_WAY};
61use crate::poi_side;
62use crate::proto::{Error, Result};
63use crate::rings::{self, MemberWay, RingStats};
64use crate::spatial::spatial_from_e7;
65use crate::tags::{self, PoiTags};
66
67/// Relation types libosmium's `MultipolygonManager` accepts as areas.
68const AREA_RELATION_TYPES: [&str; 2] = ["multipolygon", "boundary"];
69
70/// Sentinel latitude for "this node's location was never seen".
71const NO_LOC: i32 = i32::MIN;
72
73pub struct Stats {
74 pub records: usize,
75 pub unique_names: usize,
76 pub name_bytes: u32,
77 pub from_nodes: usize,
78 pub from_ways: usize,
79 pub from_relations: usize,
80 /// POIs carrying at least one sidecar attribute.
81 pub with_attrs: usize,
82 pub unique_attrs: usize,
83 pub attr_bytes: usize,
84 /// Populated cells in `poi_spatial.bin`.
85 pub spatial_cells: usize,
86 /// `(record, word)` entries in `poi_name_index.bin`.
87 pub name_entries: usize,
88 /// POIs that matched a row of the `--reviews` table.
89 pub with_reviews: usize,
90 /// POIs stamped with a non-zero boundary link in `poi_region.bin`.
91 pub with_region: usize,
92 /// Boundaries written to `poi_admin.bin` (linked ones plus their ancestors).
93 pub admin_entries: usize,
94}
95
96struct Poi {
97 lat: f64,
98 lon: f64,
99 lat_e7: i32,
100 lon_e7: i32,
101 morton: u64,
102 type_: u16,
103 osm_id: i64,
104 name: Vec<u8>,
105 /// Encoded sidecar record body, empty when the POI has no attributes.
106 attrs: Vec<u8>,
107 /// Tagged OSM boundary id (`poi_side::tag_relation`/`tag_way`), or
108 /// [`crate::poi_side::REGION_NONE`]. A self-link is stamped at creation;
109 /// member-link and containment links are resolved pre-sort in [`build`].
110 region: u64,
111 /// Deepest `admin_level` this POI may link to: place-implied
112 /// (country 2, state/province 4, everything else 8).
113 place_cap: u8,
114}
115
116/// A `type=multipolygon`/`boundary` relation that is itself a POI.
117struct RelArea {
118 id: i64,
119 type_: u16,
120 name: Vec<u8>,
121 attrs: Vec<u8>,
122 outer_ways: Vec<i64>,
123 /// [`crate::poi_side::tag_relation`] of this relation when it is itself an
124 /// administrative boundary, else [`crate::poi_side::REGION_NONE`].
125 self_region: u64,
126 place_cap: u8,
127}
128
129/// A `type=boundary` + `boundary=administrative` relation (POI or not) whose
130/// geometry POIs link against.
131struct BoundaryRel {
132 id: i64,
133 admin_level: u8,
134 /// `name` and `name:en`, for `poi_admin.bin` (empty when untagged).
135 name: Vec<u8>,
136 name_en: Vec<u8>,
137 /// `(way id, outer)` — empty-role ways count as outer per OSM convention.
138 member_ways: Vec<(i64, bool)>,
139 /// Node members with a `label`/`admin_centre` role.
140 label_nodes: Vec<i64>,
141}
142
143#[derive(Default)]
144struct RelPass {
145 areas: Vec<RelArea>,
146 boundaries: Vec<BoundaryRel>,
147}
148
149/// A closed way that is a POI in its own right.
150struct WayArea {
151 id: i64,
152 type_: u16,
153 name: Vec<u8>,
154 attrs: Vec<u8>,
155 refs: Vec<i64>,
156 /// [`crate::poi_side::tag_way`] of this way when it is itself tagged
157 /// `boundary=administrative`, else [`crate::poi_side::REGION_NONE`].
158 self_region: u64,
159 place_cap: u8,
160}
161
162#[derive(Default)]
163struct WayPass {
164 areas: Vec<WayArea>,
165 /// Node refs of ways that are outer members of a POI relation.
166 outer_refs: Vec<(i64, Vec<i64>)>,
167}
168
169#[derive(Default)]
170struct NodePass {
171 pois: Vec<Poi>,
172 /// `(index into the needed-node table, lat_e7, lon_e7)`.
173 locs: Vec<(u32, i32, i32)>,
174}
175
176/// The input PBF and every output file of a POI build, grouped so the build
177/// entry points take one paths argument instead of eight loose ones.
178#[derive(Clone, Copy)]
179pub struct Paths<'a> {
180 /// Input `.osm.pbf`.
181 pub input: &'a Path,
182 /// GeoJSONSeq output.
183 pub geojson: &'a Path,
184 /// Name pool output.
185 pub names: &'a Path,
186 /// POI index output.
187 pub index: &'a Path,
188 /// Attribute sidecar output.
189 pub attrs: &'a Path,
190 /// Spatial grid output.
191 pub spatial: &'a Path,
192 /// Name index output.
193 pub name_index: &'a Path,
194 /// Region (boundary link) output.
195 pub region: &'a Path,
196}
197
198pub fn build(paths: Paths<'_>) -> Result<Stats> {
199 build_with(paths, None)
200}
201
202/// [`build`] with a region bbox filter: `Some` keeps only POIs touching the
203/// box, `None` (world) keeps everything. Ways and relations are kept whole
204/// when any vertex touches — the `complete_ways` rule — so a POI straddling
205/// the border keeps its true centroid rather than one computed from a clip.
206pub fn build_with(paths: Paths<'_>, bbox: Option<crate::bbox::BBox>) -> Result<Stats> {
207 build_with_reviews(paths, bbox, None)
208}
209
210/// [`build_with`] plus an external review table whose rows are appended to the
211/// matching POIs' attribute records (see [`crate::poi_reviews`]).
212pub fn build_with_reviews(
213 paths: Paths<'_>,
214 bbox: Option<crate::bbox::BBox>,
215 reviews: Option<&ReviewTable>,
216) -> Result<Stats> {
217 build_inner(
218 paths.input,
219 paths.geojson,
220 paths.names,
221 paths.index,
222 paths.attrs,
223 paths.spatial,
224 paths.name_index,
225 paths.region,
226 bbox,
227 match reviews {
228 Some(t) => Reviews::Ready(t),
229 None => Reviews::None,
230 },
231 )
232}
233
234/// A review table still being loaded on another thread; see
235/// [`build_with_review_loader`].
236pub type ReviewLoader = std::thread::JoinHandle<Result<ReviewTable>>;
237
238/// [`build_with_reviews`], with the table still loading on `loader`'s thread.
239///
240/// The table is ~400 MB of TSV on a planet build and is not needed until after
241/// the three PBF passes, so loading it up front serialised a second-scale parse
242/// in front of the whole run. The join happens right before the reviews are
243/// applied; a loader that has already failed is noticed between passes, so a bad
244/// table still fails the run early rather than after the node pass.
245///
246/// `on_loaded` runs once with the joined table (the binary prints its row
247/// count there).
248pub fn build_with_review_loader(
249 paths: Paths<'_>,
250 bbox: Option<crate::bbox::BBox>,
251 loader: ReviewLoader,
252 on_loaded: &dyn Fn(&ReviewTable),
253) -> Result<Stats> {
254 build_inner(
255 paths.input,
256 paths.geojson,
257 paths.names,
258 paths.index,
259 paths.attrs,
260 paths.spatial,
261 paths.name_index,
262 paths.region,
263 bbox,
264 Reviews::Loading(Some(loader), on_loaded, None),
265 )
266}
267
268/// Where the review table comes from.
269enum Reviews<'a> {
270 None,
271 Ready(&'a ReviewTable),
272 /// The loader (until joined), the joined-callback, and the joined table.
273 Loading(Option<ReviewLoader>, &'a dyn Fn(&ReviewTable), Option<ReviewTable>),
274}
275
276impl Reviews<'_> {
277 /// Join the loader if it has already finished, so a failed load surfaces now.
278 fn poll(&mut self) -> Result<()> {
279 if let Reviews::Loading(h, _, _) = self {
280 if h.as_ref().is_some_and(|h| h.is_finished()) {
281 return self.join();
282 }
283 }
284 Ok(())
285 }
286
287 /// Block until the table is loaded (no-op unless loading).
288 fn join(&mut self) -> Result<()> {
289 if let Reviews::Loading(h, cb, table) = self {
290 if let Some(h) = h.take() {
291 let t = h.join().map_err(|_| Error("the review loader panicked".into()))??;
292 cb(&t);
293 *table = Some(t);
294 }
295 }
296 Ok(())
297 }
298
299 fn table(&self) -> Option<&ReviewTable> {
300 match self {
301 Reviews::None => None,
302 Reviews::Ready(t) => Some(t),
303 Reviews::Loading(_, _, t) => t.as_ref(),
304 }
305 }
306}
307
308include!("poi_build_s1.rs");
309include!("poi_build_s2.rs");
310include!("poi_build_part1.rs");
311include!("poi_build_part2.rs");
312include!("poi_build_part3.rs");
313include!("poi_build_part4.rs");