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

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

poi_build_part2.rs404 lines · 17.7 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4 use crate::testpbf;
5
6 struct Record {
7 lat_e7: i32,
8 lon_e7: i32,
9 name: String,
10 type_: u16,
11 }
12
13 fn read_records(dir: &Path) -> (Vec<Record>, Vec<String>) {
14 let index = std::fs::read(dir.join("poi_index.bin")).unwrap();
15 let names = std::fs::read(dir.join("poi_names.bin")).unwrap();
16 let geojson = std::fs::read_to_string(dir.join("pois.geojsonseq")).unwrap();
17 assert_eq!(index.len() % 14, 0, "records must be exactly 14 bytes");
18 let records = index
19 .chunks_exact(14)
20 .map(|r| {
21 let off = u32::from_le_bytes(r[8..12].try_into().unwrap()) as usize;
22 let end = off + names[off..].iter().position(|b| *b == 0).unwrap();
23 Record {
24 lat_e7: i32::from_le_bytes(r[0..4].try_into().unwrap()),
25 lon_e7: i32::from_le_bytes(r[4..8].try_into().unwrap()),
26 name: String::from_utf8(names[off..end].to_vec()).unwrap(),
27 type_: u16::from_le_bytes(r[12..14].try_into().unwrap()),
28 }
29 })
30 .collect();
31 let lines = geojson.lines().map(|l| l.to_string()).collect();
32 (records, lines)
33 }
34
35 /// Decode `poi_attrs.bin` the way [`crate::poi_attrs`] documents it: one
36 /// `(key, value)` list per record ordinal, empty where the POI had nothing.
37 fn read_attrs(dir: &Path) -> Vec<Vec<(u8, String)>> {
38 use crate::poi_attrs::{HEADER_BYTES, MAGIC, NO_ATTRS, VERSION};
39 let bytes = std::fs::read(dir.join("poi_attrs.bin")).unwrap();
40 assert_eq!(&bytes[0..4], &MAGIC);
41 assert_eq!(bytes[4], VERSION);
42 let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
43 let blob = &bytes[HEADER_BYTES + 4 * count..];
44 (0..count)
45 .map(|i| {
46 let at = HEADER_BYTES + 4 * i;
47 let off = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
48 if off == NO_ATTRS {
49 return Vec::new();
50 }
51 let at = off as usize;
52 let len = u16::from_le_bytes(blob[at..at + 2].try_into().unwrap()) as usize;
53 let body = &blob[at + 2..at + 2 + len];
54 let mut out = Vec::new();
55 let mut j = 0;
56 while j + 3 <= body.len() {
57 let vlen = u16::from_le_bytes(body[j + 1..j + 3].try_into().unwrap()) as usize;
58 out.push((
59 body[j],
60 String::from_utf8(body[j + 3..j + 3 + vlen].to_vec()).unwrap(),
61 ));
62 j += 3 + vlen;
63 }
64 out
65 })
66 .collect()
67 }
68
69 /// Decode `poi_region.bin` the way [`crate::poi_side`] documents it: one
70 /// tagged OSM boundary id per record ordinal, `0` where the POI matched
71 /// nothing.
72 fn read_regions(dir: &Path) -> Vec<u64> {
73 use crate::poi_side::{REGION_HEADER_BYTES, REGION_MAGIC, REGION_VERSION};
74 let bytes = std::fs::read(dir.join("poi_region.bin")).unwrap();
75 assert_eq!(&bytes[0..4], REGION_MAGIC);
76 assert_eq!(
77 u32::from_le_bytes(bytes[4..8].try_into().unwrap()),
78 REGION_VERSION
79 );
80 let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
81 assert_eq!(bytes.len(), REGION_HEADER_BYTES + 8 * count);
82 bytes[REGION_HEADER_BYTES..]
83 .chunks_exact(8)
84 .map(|r| u64::from_le_bytes(r.try_into().unwrap()))
85 .collect()
86 }
87
88 fn build_sample(tag: &str) -> (Stats, PathBuf) {
89 let (pbf_path, dir) = testpbf::write_sample(tag);
90 let stats = build(Paths { input: &pbf_path, geojson: &dir.join("pois.geojsonseq"), names: &dir.join("poi_names.bin"), index: &dir.join("poi_index.bin"), attrs: &dir.join("poi_attrs.bin"), spatial: &dir.join("poi_spatial.bin"), name_index: &dir.join("poi_name_index.bin"), region: &dir.join("poi_region.bin") })
91 .unwrap();
92 (stats, dir)
93 }
94
95 #[test]
96 fn extracts_nodes_closed_ways_and_relations() {
97 let (stats, dir) = build_sample("poi_build");
98
99 // The cafe node, the closed "Plaza" way and the "Riverside Park"
100 // relation. The bus stop node has a name but `highway=bus_stop` is not a
101 // POI key, so it is correctly absent.
102 assert_eq!(
103 (stats.from_nodes, stats.from_ways, stats.from_relations),
104 (1, 1, 1)
105 );
106 assert_eq!(stats.records, 3);
107
108 let (records, lines) = read_records(&dir);
109 assert_eq!(records.len(), 3);
110 assert_eq!(lines.len(), 3);
111
112 let by_name = |n: &str| records.iter().find(|r| r.name == n).unwrap();
113 // amenity=cafe -> 1, at the cafe node's own location.
114 let cafe = by_name("Corner Cafe");
115 assert_eq!(cafe.type_, 1);
116 assert_eq!((cafe.lat_e7, cafe.lon_e7), (370_040_000, -1_220_010_000));
117 // The closed way's ring is nodes 1-4 plus a repeat of the ring's start,
118 // which libosmium picks as the vertex with the smallest (lon, lat) — here
119 // node 1. So the average is over lat 370_000_000 twice, then 010, 020, 030.
120 let plaza = by_name("Plaza");
121 assert_eq!(plaza.type_, 1);
122 assert_eq!(plaza.lat_e7, 370_012_000);
123 assert_eq!(plaza.lon_e7, -1_220_000_000);
124 // leisure=park -> 12. The relation's outer ring IS that closed way, the
125 // case the approximation reproduces exactly, so the centroid must match.
126 let park = by_name("Riverside Park");
127 assert_eq!(park.type_, 12);
128 assert_eq!((park.lat_e7, park.lon_e7), (plaza.lat_e7, plaza.lon_e7));
129
130 // Records are Morton-ordered.
131 let keys: Vec<u64> = records
132 .iter()
133 .map(|r| crate::spatial::spatial_from_e7(r.lat_e7, r.lon_e7))
134 .collect();
135 assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}");
136
137 // The geojson mirrors the index exactly, in the same order.
138 assert!(lines[0].starts_with("{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":["));
139 for (line, rec) in lines.iter().zip(&records) {
140 assert!(line.contains(&format!("\"name\":\"{}\"", rec.name)), "{line}");
141 assert!(line.contains(&format!("\"type\":{}", rec.type_)), "{line}");
142 assert!(
143 line.contains(&format!("{:.7},{:.7}", rec.lon_e7 as f64 * 1e-7, rec.lat_e7 as f64 * 1e-7)),
144 "{line}"
145 );
146 }
147 // The relation's osm_id is negated so way and relation ids cannot collide.
148 let park_line = lines.iter().find(|l| l.contains("Riverside Park")).unwrap();
149 assert!(park_line.contains(&format!("\"osm_id\":{}", -testpbf::RELATION_ID)));
150 }
151
152 #[test]
153 fn ring_centroid_doubles_the_smallest_lon_lat_vertex() {
154 // libosmium sorted a ring's segments before walking them, so the ring
155 // always starts — and therefore repeats — at the vertex with the smallest
156 // (lon, lat). Averaging the way's own node list instead doubles the way's
157 // FIRST node, which put small buildings metres off.
158 let pts = [
159 (1, (350_000_000, -1_200_000_000)),
160 (2, (350_000_000, -1_200_010_000)), // smallest lon
161 (3, (350_030_000, -1_200_010_000)),
162 (4, (350_030_000, -1_200_000_000)),
163 ];
164 let location = |id: i64| pts.iter().find(|(i, _)| *i == id).map(|(_, l)| *l);
165
166 // Same ring, three different starting vertices: the centroid must not move.
167 for order in [
168 vec![1, 2, 3, 4],
169 vec![3, 4, 1, 2],
170 vec![4, 3, 2, 1],
171 ] {
172 let (lat, lon) = ring_centroid(order.iter().copied(), &location).unwrap();
173 // lat: (350.0 + 350.0 + 350.03 + 350.03 + 350.0[repeat of node 2]) / 5
174 assert_eq!((lat * 1e7).round() as i64, 350_012_000, "order {order:?}");
175 // lon: (-120.0 - 120.001 - 120.001 - 120.0 - 120.001) / 5
176 assert_eq!((lon * 1e7).round() as i64, -1_200_006_000, "order {order:?}");
177 }
178
179 // Ties on lon are broken by lat, matching libosmium's Location ordering.
180 let flat = [
181 (1, (350_020_000, -1_200_000_000)),
182 (2, (350_010_000, -1_200_000_000)),
183 ];
184 let loc2 = |id: i64| flat.iter().find(|(i, _)| *i == id).map(|(_, l)| *l);
185 let (lat, _) = ring_centroid([1i64, 2].into_iter(), &loc2).unwrap();
186 // Node 2 has the smaller lat, so it is the repeated vertex.
187 assert_eq!((lat * 1e7).round() as i64, 350_013_333);
188
189 // Nothing resolvable -> no POI rather than a (0, 0) centroid.
190 assert!(ring_centroid([99i64].into_iter(), &location).is_none());
191 }
192
193 #[test]
194 fn two_runs_are_byte_identical() {
195 let (pbf_path, dir) = testpbf::write_sample("poi_det");
196 let run = |suffix: &str| {
197 build(Paths { input: &pbf_path, geojson: &dir.join(format!("pois{suffix}.geojsonseq")), names: &dir.join(format!("names{suffix}.bin")), index: &dir.join(format!("index{suffix}.bin")), attrs: &dir.join(format!("attrs{suffix}.bin")), spatial: &dir.join(format!("spatial{suffix}.bin")), name_index: &dir.join(format!("nameidx{suffix}.bin")), region: &dir.join(format!("region{suffix}.bin")) })
198 .unwrap();
199 };
200 run("a");
201 run("b");
202 for (a, b) in [
203 ("poisa.geojsonseq", "poisb.geojsonseq"),
204 ("namesa.bin", "namesb.bin"),
205 ("indexa.bin", "indexb.bin"),
206 ("attrsa.bin", "attrsb.bin"),
207 ("spatiala.bin", "spatialb.bin"),
208 ("nameidxa.bin", "nameidxb.bin"),
209 ("regiona.bin", "regionb.bin"),
210 ] {
211 assert_eq!(
212 std::fs::read(dir.join(a)).unwrap(),
213 std::fs::read(dir.join(b)).unwrap(),
214 "{a} differs between runs"
215 );
216 }
217 }
218
219 /// The sidecar's join to `poi_index.bin` is by ordinal, so the two files have to
220 /// have exactly the same length in records and agree row for row.
221 #[test]
222 fn the_attribute_sidecar_lines_up_with_the_index_by_ordinal() {
223 use crate::poi_attrs::{
224 KEY_CUISINE, KEY_HOUSENUMBER, KEY_OPENING_HOURS, KEY_PHONE, KEY_STREET, KEY_WEBSITE,
225 };
226 let (stats, dir) = build_sample("poi_attrs_join");
227 let (records, _) = read_records(&dir);
228 let attrs = read_attrs(&dir);
229
230 assert_eq!(attrs.len(), records.len(), "one slot per index record");
231 assert_eq!(stats.with_attrs, 1, "only the cafe node carries any");
232 assert_eq!(stats.unique_attrs, 1);
233
234 let cafe = records.iter().position(|r| r.name == "Corner Cafe").unwrap();
235 assert_eq!(
236 attrs[cafe],
237 vec![
238 (KEY_OPENING_HOURS, "24/7".to_string()),
239 // The fixture tags `contact:phone` rather than `phone`, so the alias
240 // has to be read.
241 (KEY_PHONE, "+1-555-0100".to_string()),
242 (KEY_WEBSITE, "https://cafe.example".to_string()),
243 (KEY_HOUSENUMBER, "120".to_string()),
244 (KEY_STREET, "Market St".to_string()),
245 (KEY_CUISINE, "coffee_shop".to_string()),
246 ]
247 );
248
249 for (i, a) in attrs.iter().enumerate() {
250 if i != cafe {
251 assert!(a.is_empty(), "{} has no attributes", records[i].name);
252 }
253 }
254 }
255
256 /// Adding the sidecar must not have widened the record everything else measures
257 /// the file by. `record_count = filesize / 14` is asserted in the README too.
258 #[test]
259 fn the_index_record_is_still_fourteen_bytes() {
260 let (stats, dir) = build_sample("poi_width");
261 let index = std::fs::read(dir.join("poi_index.bin")).unwrap();
262 assert_eq!(index.len(), stats.records * 14);
263 }
264
265 /// Member links win, containment covers the rest, misses stay zero: the
266 /// town label is a `label` member of the boundary relation (stamped even
267 /// though it sits outside the ring), the inside cafe resolves by
268 /// containment, the outside cafe matches nothing.
269 #[test]
270 fn boundary_links_resolve_member_first_then_containment() {
271 let (pbf_path, dir) = testpbf::write_region_sample("poi_region");
272 let stats = build(Paths { input: &pbf_path, geojson: &dir.join("pois.geojsonseq"), names: &dir.join("poi_names.bin"), index: &dir.join("poi_index.bin"), attrs: &dir.join("poi_attrs.bin"), spatial: &dir.join("poi_spatial.bin"), name_index: &dir.join("poi_name_index.bin"), region: &dir.join("poi_region.bin") })
273 .unwrap();
274 let (records, _) = read_records(&dir);
275 assert_eq!(records.len(), 4);
276 assert_eq!(stats.with_region, 3);
277
278 let regions = read_regions(&dir);
279 assert_eq!(regions.len(), records.len());
280 let of = |n: &str| regions[records.iter().position(|r| r.name == n).unwrap()];
281
282 // Tagged ids carry the OSM id space in the low 2 bits: relation 300 is
283 // `(300 << 2) | 3`.
284 let boundary = (testpbf::REGION_BOUNDARY_ID as u64) << 2 | 3;
285 // The town label is type 51 and resolves through the member link alone.
286 let town = records.iter().find(|r| r.name == "Testville").unwrap();
287 assert_eq!(town.type_, 51);
288 assert_eq!(of("Testville"), boundary);
289 // The boundary relation is itself a park POI and links to itself.
290 assert_eq!(of("Green Boundary"), boundary);
291 assert_eq!(of("Inside Cafe"), boundary);
292 assert_eq!(of("Outside Cafe"), 0);
293 }
294
295 /// Review rows join on (element, OSM id) before the Morton sort, and land on the
296 /// right ordinal after it. The relation row uses the plain id even though the
297 /// POI stores it negated.
298 #[test]
299 fn review_rows_join_by_element_and_osm_id() {
300 use crate::poi_attrs::{KEY_RATING, KEY_REVIEW_COUNT, KEY_REVIEW_SUMMARY, KEY_CUISINE};
301 let (pbf_path, dir) = testpbf::write_sample("poi_reviews_join");
302 let table = crate::poi_reviews::ReviewTable::parse(&format!(
303 "node\t{}\t4.3\t120\tGreat coffee, slow at lunch.\n\
304 way\t{}\t3.8\t15\t\n\
305 relation\t{}\t\t40\tShady lawns.\n\
306 way\t{}\t1.0\t1\tWrong element, must not match.\n",
307 testpbf::CAFE_NODE_ID,
308 testpbf::AREA_WAY_ID,
309 testpbf::RELATION_ID,
310 testpbf::CAFE_NODE_ID,
311 ))
312 .unwrap();
313 let stats = build_with_reviews(Paths { input: &pbf_path, geojson: &dir.join("pois.geojsonseq"), names: &dir.join("poi_names.bin"), index: &dir.join("poi_index.bin"), attrs: &dir.join("poi_attrs.bin"), spatial: &dir.join("poi_spatial.bin"), name_index: &dir.join("poi_name_index.bin"), region: &dir.join("poi_region.bin") }, None, Some(&table))
314 .unwrap();
315 assert_eq!(stats.with_reviews, 3);
316
317 let (records, _) = read_records(&dir);
318 let attrs = read_attrs(&dir);
319 let of = |n: &str| &attrs[records.iter().position(|r| r.name == n).unwrap()];
320
321 let cafe = of("Corner Cafe");
322 assert_eq!(cafe[cafe.len() - 4], (KEY_CUISINE, "coffee_shop".to_string()), "tag fields first");
323 assert_eq!(
324 cafe[cafe.len() - 3..],
325 [
326 (KEY_RATING, "4.3".to_string()),
327 (KEY_REVIEW_COUNT, "120".to_string()),
328 (KEY_REVIEW_SUMMARY, "Great coffee, slow at lunch.".to_string()),
329 ]
330 );
331 assert_eq!(
332 of("Plaza"),
333 &vec![(KEY_RATING, "3.8".to_string()), (KEY_REVIEW_COUNT, "15".to_string())]
334 );
335 assert_eq!(
336 of("Riverside Park"),
337 &vec![(KEY_REVIEW_COUNT, "40".to_string()), (KEY_REVIEW_SUMMARY, "Shady lawns.".to_string())]
338 );
339 }
340
341 #[test]
342 fn args_require_all_three_outputs() {
343 let ok = parse_args(&[
344 "in.pbf".into(),
345 "--geojson".into(),
346 "g".into(),
347 "--names".into(),
348 "n".into(),
349 "--index".into(),
350 "out/poi_index.bin".into(),
351 ])
352 .unwrap();
353 assert_eq!(ok.input, PathBuf::from("in.pbf"));
354 assert_eq!(ok.index, PathBuf::from("out/poi_index.bin"));
355 // Defaulted beside the index, so a caller written before the sidecar existed
356 // still emits one rather than silently skipping it.
357 assert_eq!(ok.attrs, PathBuf::from("out/poi_attrs.bin"));
358 assert_eq!(ok.region, PathBuf::from("out/poi_region.bin"));
359 assert!(ok.threads.is_none(), "the pool defaults to the box");
360 assert!(parse_args(&["in.pbf".into()]).is_err());
361 assert!(parse_args(&["in.pbf".into(), "--geojson".into()]).is_err());
362 }
363
364 #[test]
365 fn threads_must_be_positive() {
366 let base: Vec<String> = vec![
367 "in.pbf".into(),
368 "--geojson".into(),
369 "g".into(),
370 "--names".into(),
371 "n".into(),
372 "--index".into(),
373 "i".into(),
374 ];
375 let mut with = base.clone();
376 with.extend(["--threads".to_string(), "3".to_string()]);
377 assert_eq!(parse_args(&with).unwrap().threads, Some(3));
378
379 let mut zero = base.clone();
380 zero.extend(["--threads".to_string(), "0".to_string()]);
381 assert!(parse_args(&zero).is_err());
382
383 let mut bare = base;
384 bare.push("--threads".into());
385 assert!(parse_args(&bare).is_err());
386 }
387
388 #[test]
389 fn an_explicit_attrs_path_overrides_the_default() {
390 let ok = parse_args(&[
391 "in.pbf".into(),
392 "--geojson".into(),
393 "g".into(),
394 "--names".into(),
395 "n".into(),
396 "--index".into(),
397 "i".into(),
398 "--attrs".into(),
399 "elsewhere/a.bin".into(),
400 ])
401 .unwrap();
402 assert_eq!(ok.attrs, PathBuf::from("elsewhere/a.bin"));
403 }
404}