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

Modern-Apps.git / scripts / networklocation / geodb_build / src / extract.rs

extract.rs335 lines · 11.3 KiBRaw
1//! What gets indexed, and how it is pulled out of a `.osm.pbf`.
2//!
3//! The database this replaces held **only** objects carrying both `addr:housenumber` and
4//! `addr:street`. That left three large gaps, all of which show up as a geocoder that says
5//! nothing useful:
6//!
7//! - **No streets.** Reverse geocoding could return a nearby house number or nothing at all;
8//! it could never say "you are on Foo Street".
9//! - **No POIs or places.** A named building, shop or neighbourhood was invisible in both
10//! directions.
11//! - **`addr:place` addresses dropped.** Many countries — much of Germany and Austria, and
12//! most of Japan and Korea — address buildings against a *place* rather than a street.
13//! Requiring `addr:street` silently discarded all of them.
14//!
15//! ## Pass ordering
16//!
17//! A PBF stores nodes before the ways that reference them and ways before the relations, so
18//! anything needing way or relation geometry has to be read backwards, in three passes:
19//! relations decide which ways matter, ways decide which node coordinates matter, and nodes
20//! supply them. `osm_ingest::extract` documents this; the same ordering is reproduced here
21//! because this crate drives the scan itself rather than emitting a layer.
22
23use std::collections::HashMap;
24
25use osm_ingest::bbox::{self, BBox};
26use osm_ingest::nodeloc::{resolve_nodes, NodeLocations};
27use osm_ingest::osm::{visit_block, Element, Tags, MEMBER_WAY};
28use osm_ingest::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS};
29use osm_ingest::proto::{Error, Result};
30use rayon::prelude::*;
31
32use crate::codec::Interner;
33use crate::extract_extra::STREET_SAMPLE_E7;
34use crate::progress::Progress;
35use crate::format::{e7_to_e5, in_range, DICTS, D_CITY, D_COUNTRY, D_HOUSE, D_NAME, D_POSTCODE,
36 D_STATE, D_STREET, K_ADDRESS, K_PLACE, K_POI, K_STREET};
37
38/// Cap on samples per street way, so one enormous way cannot dominate the database.
39const STREET_MAX_SAMPLES: usize = 32;
40
41/// Tag keys that make an object a POI when it also has a name.
42const POI_KEYS: [&str; 6] = ["amenity", "shop", "tourism", "leisure", "office", "healthcare"];
43
44/// `highway=*` values that are streets someone could be standing on or addressed against.
45/// Named footways, cycleways, tracks, service aisles, links and bus stops used to be sampled
46/// too; they were a large share of the street rows and a nearest-street answer of "Parking
47/// Aisle B" or a bus stop name is worse than the road beside it.
48const ROAD_VALUES: [&str; 10] = [
49 "motorway",
50 "trunk",
51 "primary",
52 "secondary",
53 "tertiary",
54 "unclassified",
55 "residential",
56 "living_street",
57 "pedestrian",
58 "road",
59];
60
61fn is_road(highway: &str) -> bool {
62 ROAD_VALUES.contains(&highway)
63}
64
65/// `place=*` values worth indexing: inhabited places people search for and expect to be told
66/// they are in. Deliberately excludes `place=locality` (often uninhabited), `region`, `ocean`
67/// and the administrative-only values.
68const PLACE_VALUES: [&str; 9] = [
69 "city",
70 "town",
71 "village",
72 "hamlet",
73 "suburb",
74 "neighbourhood",
75 "quarter",
76 "borough",
77 "island",
78];
79
80/// One indexed feature, with its strings already interned.
81///
82/// Holding `String`s here instead would be the single thing that stops a planet build from
83/// running: at roughly 640 million rows, seven `String`s each is about 250 GB of allocator
84/// headers and heap. Interned, a row is 40 bytes and the whole set is 25 GB, with the distinct
85/// strings stored once in [`Strings`].
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Row {
88 /// Latitude, e5.
89 pub lat: i32,
90 /// Longitude, e5.
91 pub lon: i32,
92 /// One of the `K_*` constants.
93 pub kind: u8,
94 /// Dictionary ids, indexed by the `D_*` constants in [`crate::format`].
95 pub ids: [u32; DICTS],
96}
97
98/// The string dictionaries, filled as extraction runs.
99pub struct Strings {
100 /// One interner per dictionary slot, in `D_*` order.
101 pub dicts: Vec<Interner>,
102}
103
104impl Default for Strings {
105 fn default() -> Strings {
106 Strings { dicts: (0..DICTS).map(|_| Interner::new()).collect() }
107 }
108}
109
110impl Strings {
111 pub(crate) fn intern(&mut self, a: &Attrs) -> [u32; DICTS] {
112 [
113 self.dicts[D_NAME].intern(&a.name),
114 self.dicts[D_HOUSE].intern(&a.house),
115 self.dicts[D_STREET].intern(&a.street),
116 self.dicts[D_CITY].intern(&a.city),
117 self.dicts[D_STATE].intern(&a.state),
118 self.dicts[D_COUNTRY].intern(&a.country),
119 self.dicts[D_POSTCODE].intern(&a.postcode),
120 ]
121 }
122}
123
124/// Whether a classified feature's **tags** carry what its kind requires. Checked before
125/// interning, so a useless feature never reaches the dictionaries.
126fn attrs_ok(kind: u8, a: &Attrs) -> bool {
127 match kind {
128 // An address with neither a street nor a place cannot be written down, and a house
129 // number on its own is not findable.
130 K_ADDRESS => !a.house.is_empty() && !a.street.is_empty(),
131 _ => !a.name.is_empty(),
132 }
133}
134
135/// Whether a classified feature is worth storing at all.
136fn is_useful(kind: u8, a: &Attrs, lat_e7: i32, lon_e7: i32) -> bool {
137 in_range(e7_to_e5(lat_e7), e7_to_e5(lon_e7)) && attrs_ok(kind, a)
138}
139
140/// What a pass decided about one element.
141#[derive(Default, Clone)]
142pub(crate) struct Attrs {
143 name: String,
144 house: String,
145 street: String,
146 city: String,
147 state: String,
148 country: String,
149 postcode: String,
150}
151
152fn tag(tags: &Tags, key: &str) -> String {
153 tags.get_str(key).unwrap_or("").trim().to_string()
154}
155
156fn read_attrs(tags: &Tags) -> Attrs {
157 let street = {
158 let s = tag(tags, "addr:street");
159 // `addr:place` is how much of DE/AT/JP/KR addresses buildings; treating it as the
160 // street is what makes those addresses representable at all.
161 if s.is_empty() {
162 tag(tags, "addr:place")
163 } else {
164 s
165 }
166 };
167 let state = {
168 let s = tag(tags, "addr:state");
169 if s.is_empty() {
170 tag(tags, "addr:province")
171 } else {
172 s
173 }
174 };
175 Attrs {
176 name: tag(tags, "name"),
177 house: tag(tags, "addr:housenumber"),
178 street,
179 city: tag(tags, "addr:city"),
180 state,
181 country: tag(tags, "addr:country"),
182 postcode: tag(tags, "addr:postcode"),
183 }
184}
185
186/// Decide what an element is, from its tags alone. `None` means "not indexed".
187fn classify(tags: &Tags) -> Option<u8> {
188 if tags.get("addr:housenumber").is_some() {
189 return Some(K_ADDRESS);
190 }
191 let named = tags.get("name").is_some();
192 if !named {
193 return None;
194 }
195 if tags.get_str("highway").is_some_and(is_road) {
196 return Some(K_STREET);
197 }
198 if let Some(place) = tags.get_str("place") {
199 if PLACE_VALUES.contains(&place) {
200 return Some(K_PLACE);
201 }
202 }
203 if POI_KEYS.iter().any(|k| tags.get(k).is_some()) {
204 return Some(K_POI);
205 }
206 None
207}
208
209/// OSM coordinates arrive as e7 and are rounded to the stored e5 here, once.
210fn row_from(kind: u8, ids: [u32; DICTS], lat_e7: i32, lon_e7: i32) -> Row {
211 Row { lat: e7_to_e5(lat_e7), lon: e7_to_e5(lon_e7), kind, ids }
212}
213
214// --------------------------------------------------------------------------- way handling
215/// A way held between passes, with everything it needs except coordinates.
216///
217/// Attributes are already interned: a planet run holds a quarter of a billion of these, and
218/// keeping seven `String`s per way is what would put the build over the machine's memory.
219pub(crate) struct PendingWay {
220 kind: u8,
221 ids: [u32; DICTS],
222 refs: Vec<i64>,
223}
224
225/// Vertex average of a closed or open way.
226///
227/// A closed ring repeats its first vertex; counting it twice biases the point, so it is
228/// dropped. This is a vertex average and not a true polygon centroid, which for an outline
229/// with unevenly spaced nodes differs by metres — acceptable for a search result's anchor.
230fn average(coords: &[(i32, i32)]) -> Option<(i32, i32)> {
231 let pts = if coords.len() > 2 && coords.first() == coords.last() {
232 &coords[..coords.len() - 1]
233 } else {
234 coords
235 };
236 if pts.is_empty() {
237 return None;
238 }
239 let mut lat = 0i64;
240 let mut lon = 0i64;
241 for &(a, o) in pts {
242 lat += a as i64;
243 lon += o as i64;
244 }
245 Some(((lat / pts.len() as i64) as i32, (lon / pts.len() as i64) as i32))
246}
247
248/// Sample points along a street.
249///
250/// One record per way would put a long road's only entry at its midpoint, so standing at one
251/// end you would be told the nearest street is something else entirely. Samples are spread
252/// **evenly along the way**, roughly [`crate::extract_extra::STREET_SAMPLE_E7`] apart, always including both ends,
253/// and capped at [`STREET_MAX_SAMPLES`].
254///
255/// Spreading evenly rather than walking until the cap is reached is what keeps a motorway
256/// represented over its whole length: taking the first 32 samples at a fixed spacing would
257/// cover the first few kilometres and leave the rest of the way invisible to reverse lookup.
258fn sample_line(coords: &[(i32, i32)]) -> Vec<(i32, i32)> {
259 let Some(&first) = coords.first() else { return Vec::new() };
260 let Some(&last) = coords.last() else { return Vec::new() };
261 if coords.len() == 1 {
262 return vec![first];
263 }
264
265 // Manhattan distance in e7 units, longitude unscaled. Cheap, and only ever used to space
266 // samples, never as a real distance.
267 let seg = |a: (i32, i32), b: (i32, i32)| -> i64 {
268 (a.0 as i64 - b.0 as i64).abs() + (a.1 as i64 - b.1 as i64).abs()
269 };
270 let total: i64 = coords.windows(2).map(|w| seg(w[0], w[1])).sum();
271 if total == 0 {
272 return vec![first];
273 }
274
275 let want = ((total / STREET_SAMPLE_E7) + 1).clamp(2, STREET_MAX_SAMPLES as i64) as usize;
276 let step = total as f64 / (want - 1) as f64;
277
278 let mut out = Vec::with_capacity(want);
279 out.push(first);
280 let mut acc = 0i64;
281 for w in coords.windows(2) {
282 acc += seg(w[0], w[1]);
283 while out.len() < want - 1 && acc as f64 >= step * out.len() as f64 {
284 out.push(w[1]);
285 }
286 }
287 out.push(last);
288 out.dedup();
289 out
290}
291
292// --------------------------------------------------------------------------- driver
293/// Counts describing what a run indexed, for the build report.
294#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
295pub struct Stats {
296 /// Rows from node elements.
297 pub from_nodes: usize,
298 /// Rows from way elements.
299 pub from_ways: usize,
300 /// Rows from relation elements.
301 pub from_relations: usize,
302 /// Addresses.
303 pub addresses: usize,
304 /// Street samples.
305 pub streets: usize,
306 /// Points of interest.
307 pub pois: usize,
308 /// Populated places.
309 pub places: usize,
310 /// Classified but outside `--bbox`.
311 pub outside_bbox: usize,
312 /// Classified but missing what its kind requires.
313 pub incomplete: usize,
314}
315
316impl Stats {
317 /// Rows produced.
318 pub fn rows(&self) -> usize {
319 self.addresses + self.streets + self.pois + self.places
320 }
321
322 fn add(&mut self, o: &Stats) {
323 self.from_nodes += o.from_nodes;
324 self.from_ways += o.from_ways;
325 self.from_relations += o.from_relations;
326 self.addresses += o.addresses;
327 self.streets += o.streets;
328 self.pois += o.pois;
329 self.places += o.places;
330 self.outside_bbox += o.outside_bbox;
331 self.incomplete += o.incomplete;
332 }
333}
334
335include!("extract_part1.rs");