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

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

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