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

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

extract_part1.rs430 lines · 16.7 KiBRaw
1/// Read `input` and return every indexable feature, plus the dictionaries its strings were
2/// interned into.
3///
4/// Every pass uses `run_pass_sink` rather than `run_pass`: the sink is called once per chunk,
5/// in order, so a chunk's owned strings are interned and dropped immediately instead of every
6/// chunk's strings being alive at once. On a planet run that is the difference between tens of
7/// gigabytes and hundreds.
8pub fn extract(
9 input: &std::path::Path,
10 bbox: Option<&BBox>,
11) -> Result<(Vec<Row>, Strings, Stats)> {
12 let blobs = pbf::scan_blobs(input)?;
13 println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());
14
15 let mut stats = Stats::default();
16 let mut rows: Vec<Row> = Vec::new();
17 let mut strings = Strings::default();
18 // Accumulated inside the pass sinks, which cannot borrow `stats` while it is also
19 // borrowed by the way/relation materialization below.
20 let mut incomplete = 0usize;
21
22 // --- pass 1: relations decide which ways matter -----------------------
23 let mut relations: Vec<(u8, [u32; DICTS], Vec<i64>)> = Vec::new();
24 let kinds = {
25 let relations = &mut relations;
26 let strings = &mut strings;
27 let incomplete = &mut incomplete;
28 pbf::run_pass_sink(
29 input,
30 &blobs,
31 pbf::PassSpec { blob_kinds: None, want: KIND_RELATIONS, label: "relations" },
32 Vec::<(u8, Attrs, Vec<i64>)>::new,
33 |acc, block| {
34 let mut kinds = 0u8;
35 visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el| {
36 let Element::Relation(r) = el else { return Ok(()) };
37 // Only areas: a `multipolygon` or a `boundary` has an inside to put a
38 // point in. A route or a turn restriction does not.
39 let ty = r.tags.get("type").unwrap_or(b"");
40 if ty != b"multipolygon" && ty != b"boundary" {
41 return Ok(());
42 }
43 let Some(kind) = classify(&r.tags) else { return Ok(()) };
44 let members: Vec<i64> = r
45 .members
46 .iter()
47 .filter(|m| {
48 m.kind == MEMBER_WAY && (m.role == b"outer" || m.role.is_empty())
49 })
50 .map(|m| m.id)
51 .collect();
52 if members.is_empty() {
53 return Ok(());
54 }
55 acc.push((kind, read_attrs(&r.tags), members));
56 Ok(())
57 })?;
58 Ok(kinds)
59 },
60 |chunk| {
61 for (kind, attrs, members) in chunk {
62 if !attrs_ok(kind, &attrs) {
63 *incomplete += 1;
64 continue;
65 }
66 relations.push((kind, strings.intern(&attrs), members));
67 }
68 Ok(())
69 },
70 )?
71 };
72 println!(" {} area relation(s)", relations.len());
73
74 // Ways claimed by a relation, so the way pass keeps their refs even when the way itself is
75 // untagged — which is the normal case for a multipolygon member.
76 let mut claimed: Vec<i64> = relations.iter().flat_map(|(_, _, m)| m.iter().copied()).collect();
77 claimed.sort_unstable();
78 claimed.dedup();
79
80 // --- pass 2: ways decide which node coordinates matter ----------------
81 let mut ways: Vec<PendingWay> = Vec::new();
82 let mut member_geom: HashMap<i64, Vec<i64>> = HashMap::new();
83 {
84 let ways = &mut ways;
85 let member_geom = &mut member_geom;
86 let strings = &mut strings;
87 let claimed = &claimed;
88 let incomplete = &mut incomplete;
89 let _ = pbf::run_pass_sink(
90 input,
91 &blobs,
92 pbf::PassSpec { blob_kinds: Some(&kinds), want: KIND_WAYS, label: "ways" },
93 || (Vec::<(u8, Attrs, Vec<i64>)>::new(), Vec::<(i64, Vec<i64>)>::new()),
94 |acc, block| {
95 let mut kinds = 0u8;
96 visit_block(block, KIND_WAYS, &mut kinds, &mut |el| {
97 let Element::Way(w) = el else { return Ok(()) };
98 if claimed.binary_search(&w.id).is_ok() {
99 acc.1.push((w.id, w.refs.to_vec()));
100 }
101 if let Some(kind) = classify(&w.tags) {
102 acc.0.push((kind, read_attrs(&w.tags), w.refs.to_vec()));
103 }
104 Ok(())
105 })?;
106 Ok(kinds)
107 },
108 |(tagged, members)| {
109 for (kind, attrs, refs) in tagged {
110 if !attrs_ok(kind, &attrs) {
111 *incomplete += 1;
112 continue;
113 }
114 ways.push(PendingWay { kind, ids: strings.intern(&attrs), refs });
115 }
116 for (id, refs) in members {
117 let _ = member_geom.insert(id, refs);
118 }
119 Ok(())
120 },
121 )?;
122 }
123 println!(" {} tagged way(s), {} relation member way(s)", ways.len(), member_geom.len());
124
125 // --- pass 3: node coordinates ----------------------------------------
126 let mut needed: Vec<i64> = Vec::new();
127 for w in &ways {
128 needed.extend_from_slice(&w.refs);
129 }
130 for refs in member_geom.values() {
131 needed.extend_from_slice(refs);
132 }
133 let table = NodeLocations::new(needed)?;
134 println!(" {} distinct node(s) needed for geometry", table.len());
135 let locs = resolve_nodes(input, &blobs, &kinds, "node coords", table)?;
136
137 // --- materialize ways -------------------------------------------------
138 // Chunks run in parallel and are collected in input order, so `rows` comes out exactly as
139 // a sequential loop would leave it.
140 let p = Progress::new("materialize ways", ways.len() as u64);
141 let parts: Vec<(Vec<Row>, Stats)> = ways
142 .par_chunks(MATERIALIZE_CHUNK)
143 .map(|chunk| {
144 let mut out = Vec::new();
145 let mut st = Stats::default();
146 for w in chunk {
147 let coords: Vec<(i32, i32)> =
148 w.refs.iter().filter_map(|&id| locs.get(id)).collect();
149 if coords.is_empty() {
150 continue;
151 }
152 let points: Vec<(i32, i32)> = if w.kind == K_STREET {
153 sample_line(&coords)
154 } else {
155 average(&coords).into_iter().collect()
156 };
157 for (lat, lon) in points {
158 if !bbox::keep_e7(bbox, lat, lon) {
159 st.outside_bbox += 1;
160 continue;
161 }
162 push_counted(&mut out, &mut st, row_from(w.kind, w.ids, lat, lon), Origin::Way);
163 }
164 }
165 p.add(chunk.len() as u64);
166 (out, st)
167 })
168 .collect();
169 absorb(&mut rows, &mut stats, parts);
170 p.finish();
171 drop(ways);
172
173 // --- materialize relations -------------------------------------------
174 let p = Progress::new("materialize relations", relations.len() as u64);
175 let parts: Vec<(Vec<Row>, Stats)> = relations
176 .par_chunks(MATERIALIZE_CHUNK)
177 .map(|chunk| {
178 let mut out = Vec::new();
179 let mut st = Stats::default();
180 for (kind, ids, members) in chunk {
181 let mut coords: Vec<(i32, i32)> = Vec::new();
182 for id in members {
183 if let Some(refs) = member_geom.get(id) {
184 coords.extend(refs.iter().filter_map(|&r| locs.get(r)));
185 }
186 }
187 let Some((lat, lon)) = average(&coords) else { continue };
188 if !bbox::keep_e7(bbox, lat, lon) {
189 st.outside_bbox += 1;
190 continue;
191 }
192 push_counted(&mut out, &mut st, row_from(*kind, *ids, lat, lon), Origin::Relation);
193 }
194 p.add(chunk.len() as u64);
195 (out, st)
196 })
197 .collect();
198 absorb(&mut rows, &mut stats, parts);
199 p.finish();
200 drop(relations);
201
202 drop(locs);
203 drop(member_geom);
204
205 // --- pass 4: node features -------------------------------------------
206 {
207 let rows = &mut rows;
208 let stats = &mut stats;
209 let strings = &mut strings;
210 let _ = pbf::run_pass_sink(
211 input,
212 &blobs,
213 pbf::PassSpec { blob_kinds: Some(&kinds), want: KIND_NODES, label: "node features" },
214 Vec::<(u8, Attrs, i32, i32)>::new,
215 |acc: &mut Vec<(u8, Attrs, i32, i32)>, block| {
216 let mut kinds = 0u8;
217 visit_block(block, KIND_NODES, &mut kinds, &mut |el| {
218 let Element::Node(n) = el else { return Ok(()) };
219 let Some(kind) = classify(&n.tags) else { return Ok(()) };
220 acc.push((kind, read_attrs(&n.tags), n.lat_e7, n.lon_e7));
221 Ok(())
222 })?;
223 Ok(kinds)
224 },
225 |chunk| {
226 for (kind, attrs, lat, lon) in chunk {
227 if !bbox::keep_e7(bbox, lat, lon) {
228 stats.outside_bbox += 1;
229 continue;
230 }
231 if !is_useful(kind, &attrs, lat, lon) {
232 stats.incomplete += 1;
233 continue;
234 }
235 let ids = strings.intern(&attrs);
236 push_counted(rows, stats, row_from(kind, ids, lat, lon), Origin::Node);
237 }
238 Ok(())
239 },
240 )?;
241 }
242
243 if rows.is_empty() {
244 return Err(Error("no indexable features found; check --bbox and the PBF".to_string()));
245 }
246 stats.incomplete += incomplete;
247 Ok((rows, strings, stats))
248}
249
250pub(crate) enum Origin {
251 Node,
252 Way,
253 Relation,
254}
255
256/// Ways or relations per parallel materialisation task.
257const MATERIALIZE_CHUNK: usize = 1 << 14;
258
259/// Append per-chunk results in chunk order, freeing each chunk as it goes.
260fn absorb(rows: &mut Vec<Row>, stats: &mut Stats, parts: Vec<(Vec<Row>, Stats)>) {
261 rows.reserve(parts.iter().map(|(r, _)| r.len()).sum());
262 for (r, s) in parts {
263 rows.extend_from_slice(&r);
264 stats.add(&s);
265 }
266}
267
268/// Record a materialized row, dropping any whose coordinates fell outside the representable
269/// range. Tag-level completeness was already decided by [`attrs_ok`] before interning.
270fn push_counted(rows: &mut Vec<Row>, stats: &mut Stats, row: Row, origin: Origin) {
271 if !in_range(row.lat, row.lon) {
272 stats.incomplete += 1;
273 return;
274 }
275 match row.kind {
276 K_ADDRESS => stats.addresses += 1,
277 K_STREET => stats.streets += 1,
278 K_POI => stats.pois += 1,
279 _ => stats.places += 1,
280 }
281 match origin {
282 Origin::Node => stats.from_nodes += 1,
283 Origin::Way => stats.from_ways += 1,
284 Origin::Relation => stats.from_relations += 1,
285 }
286 rows.push(row);
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn a_closed_rings_repeated_vertex_does_not_bias_the_average() {
295 // A unit square, with the first vertex repeated as OSM writes it.
296 let ring = vec![(0, 0), (0, 100), (100, 100), (100, 0), (0, 0)];
297 assert_eq!(average(&ring), Some((50, 50)));
298 // Without the fix the repeated (0,0) would drag it to (40, 40).
299 let naive: i64 = ring.iter().map(|c| c.0 as i64).sum::<i64>() / ring.len() as i64;
300 assert_eq!(naive, 40, "premise: counting it twice biases the point");
301 }
302
303 #[test]
304 fn an_open_way_averages_all_its_vertices() {
305 assert_eq!(average(&[(0, 0), (10, 20)]), Some((5, 10)));
306 assert_eq!(average(&[]), None);
307 }
308
309 #[test]
310 fn a_short_street_yields_one_sample() {
311 let line = vec![(37_7749300, -122_4194200), (37_7749400, -122_4194300)];
312 assert_eq!(sample_line(&line).len(), 2, "endpoints are always anchored");
313 assert_eq!(sample_line(&line[..1]).len(), 1);
314 }
315
316 #[test]
317 fn a_long_street_is_sampled_along_its_length_not_just_at_its_middle() {
318 // A degree of latitude in 1000 steps: 10 000 000 e7 units total.
319 let line: Vec<(i32, i32)> =
320 (0..1000).map(|i| (37_0000000 + i * 10_000, -122_0000000)).collect();
321 let s = sample_line(&line);
322 assert!(s.len() > 5, "expected several samples, got {}", s.len());
323 assert!(s.len() <= STREET_MAX_SAMPLES, "cap not honoured: {}", s.len());
324 assert_eq!(s[0], line[0], "the near end must be represented");
325 assert_eq!(*s.last().unwrap(), *line.last().unwrap(), "and the far end");
326 // Samples must be spread over the whole way, not bunched at the start: the midpoint
327 // of the sample list should sit near the midpoint of the way.
328 let mid = s[s.len() / 2].0;
329 let want = (line[0].0 + line[line.len() - 1].0) / 2;
330 assert!((mid - want).abs() < 1_000_000, "samples are bunched: mid {mid} vs {want}");
331 }
332
333 #[test]
334 fn street_samples_respect_the_minimum_spacing() {
335 // Vertices far closer together than the sample spacing.
336 let line: Vec<(i32, i32)> = (0..500).map(|i| (37_0000000 + i * 10, -122_0000000)).collect();
337 let s = sample_line(&line);
338 // 499 gaps x 10 units = 4990 units total, under one sample spacing, so only the two
339 // endpoints survive.
340 assert_eq!(s.len(), 2, "got {s:?}");
341 }
342
343 #[test]
344 fn a_zero_length_way_yields_one_point() {
345 let line = vec![(37_0000000, -122_0000000); 5];
346 assert_eq!(sample_line(&line), vec![(37_0000000, -122_0000000)]);
347 assert!(sample_line(&[]).is_empty());
348 }
349
350 #[test]
351 fn an_enormous_way_cannot_dominate_the_database() {
352 let line: Vec<(i32, i32)> =
353 (0..100_000).map(|i| (37_0000000 + i * 1_000, -122_0000000)).collect();
354 let s = sample_line(&line);
355 assert!(s.len() <= STREET_MAX_SAMPLES);
356 // Even at the cap, the far end is still covered.
357 assert_eq!(*s.last().unwrap(), *line.last().unwrap());
358 }
359
360 fn attrs(name: &str, house: &str, street: &str) -> Attrs {
361 Attrs {
362 name: name.to_string(),
363 house: house.to_string(),
364 street: street.to_string(),
365 ..Attrs::default()
366 }
367 }
368
369 #[test]
370 fn an_address_needs_a_number_and_something_to_hang_it_on() {
371 assert!(attrs_ok(K_ADDRESS, &attrs("", "123", "Main St")));
372 assert!(!attrs_ok(K_ADDRESS, &attrs("", "123", "")));
373 assert!(!attrs_ok(K_ADDRESS, &attrs("", "", "Main St")));
374 }
375
376 #[test]
377 fn everything_else_needs_a_name() {
378 assert!(attrs_ok(K_POI, &attrs("Blue Bottle", "", "")));
379 assert!(!attrs_ok(K_POI, &attrs("", "", "")));
380 assert!(attrs_ok(K_STREET, &attrs("Market Street", "", "")));
381 assert!(attrs_ok(K_PLACE, &attrs("Mission District", "", "")));
382 }
383
384 #[test]
385 fn only_roads_are_classified_as_streets() {
386 for road in ["residential", "primary", "living_street", "pedestrian"] {
387 assert!(is_road(road), "{road}");
388 }
389 for not_road in ["footway", "service", "bus_stop", "track", "motorway_link", "cycleway"] {
390 assert!(!is_road(not_road), "{not_road}");
391 }
392 }
393
394 #[test]
395 fn rows_are_stored_at_e5() {
396 let r = row_from(K_POI, [0; DICTS], 37_7749350, -122_4194249);
397 assert_eq!((r.lat, r.lon), (3_777_494, -12_241_942));
398 }
399
400 #[test]
401 fn out_of_range_coordinates_are_never_useful() {
402 let a = attrs("somewhere", "", "");
403 assert!(is_useful(K_POI, &a, 37_7749300, -122_4194200));
404 assert!(!is_useful(K_POI, &a, 900_000_100, -122_4194200));
405 assert!(!is_useful(K_POI, &a, 37_7749300, -1_800_000_100));
406 }
407
408 #[test]
409 fn interning_assigns_one_id_per_distinct_string() {
410 let mut s = Strings::default();
411 let a = s.intern(&attrs("Blue Bottle", "", ""));
412 let b = s.intern(&attrs("Blue Bottle", "", ""));
413 let c = s.intern(&attrs("Other", "", ""));
414 assert_eq!(a, b, "the same tags must intern to the same ids");
415 assert_ne!(a[D_NAME], c[D_NAME]);
416 assert_eq!(s.dicts[D_NAME].len(), 2);
417 // The empty strings all collapse to one id per dictionary.
418 assert_eq!(s.dicts[D_HOUSE].len(), 1);
419 }
420
421 #[test]
422 fn addr_place_stands_in_for_addr_street() {
423 // Much of DE/AT/JP/KR addresses buildings against a place, not a street. v2 required
424 // addr:street and silently dropped all of them.
425 let mut a = Attrs { house: "5".to_string(), ..Attrs::default() };
426 assert!(!attrs_ok(K_ADDRESS, &a));
427 a.street = "Marktplatz".to_string();
428 assert!(attrs_ok(K_ADDRESS, &a));
429 }
430}