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

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

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