Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_build_part2.rs
poi_build_part2.rs379 lines · 15.1 KiBRaw
| 1 | #[cfg(test)] |
| 2 | mod 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 | fn build_sample(tag: &str) -> (Stats, PathBuf) { |
| 70 | let (pbf_path, dir) = testpbf::write_sample(tag); |
| 71 | let stats = build( |
| 72 | &pbf_path, |
| 73 | &dir.join("pois.geojsonseq"), |
| 74 | &dir.join("poi_names.bin"), |
| 75 | &dir.join("poi_index.bin"), |
| 76 | &dir.join("poi_attrs.bin"), |
| 77 | &dir.join("poi_spatial.bin"), |
| 78 | &dir.join("poi_name_index.bin"), |
| 79 | ) |
| 80 | .unwrap(); |
| 81 | (stats, dir) |
| 82 | } |
| 83 | |
| 84 | #[test] |
| 85 | fn extracts_nodes_closed_ways_and_relations() { |
| 86 | let (stats, dir) = build_sample("poi_build"); |
| 87 | |
| 88 | // The cafe node, the closed "Plaza" way and the "Riverside Park" |
| 89 | // relation. The bus stop node has a name but `highway=bus_stop` is not a |
| 90 | // POI key, so it is correctly absent. |
| 91 | assert_eq!( |
| 92 | (stats.from_nodes, stats.from_ways, stats.from_relations), |
| 93 | (1, 1, 1) |
| 94 | ); |
| 95 | assert_eq!(stats.records, 3); |
| 96 | |
| 97 | let (records, lines) = read_records(&dir); |
| 98 | assert_eq!(records.len(), 3); |
| 99 | assert_eq!(lines.len(), 3); |
| 100 | |
| 101 | let by_name = |n: &str| records.iter().find(|r| r.name == n).unwrap(); |
| 102 | // amenity=cafe -> 1, at the cafe node's own location. |
| 103 | let cafe = by_name("Corner Cafe"); |
| 104 | assert_eq!(cafe.type_, 1); |
| 105 | assert_eq!((cafe.lat_e7, cafe.lon_e7), (370_040_000, -1_220_010_000)); |
| 106 | // The closed way's ring is nodes 1-4 plus a repeat of the ring's start, |
| 107 | // which libosmium picks as the vertex with the smallest (lon, lat) — here |
| 108 | // node 1. So the average is over lat 370_000_000 twice, then 010, 020, 030. |
| 109 | let plaza = by_name("Plaza"); |
| 110 | assert_eq!(plaza.type_, 1); |
| 111 | assert_eq!(plaza.lat_e7, 370_012_000); |
| 112 | assert_eq!(plaza.lon_e7, -1_220_000_000); |
| 113 | // leisure=park -> 12. The relation's outer ring IS that closed way, the |
| 114 | // case the approximation reproduces exactly, so the centroid must match. |
| 115 | let park = by_name("Riverside Park"); |
| 116 | assert_eq!(park.type_, 12); |
| 117 | assert_eq!((park.lat_e7, park.lon_e7), (plaza.lat_e7, plaza.lon_e7)); |
| 118 | |
| 119 | // Records are Morton-ordered. |
| 120 | let keys: Vec<u64> = records |
| 121 | .iter() |
| 122 | .map(|r| crate::spatial::spatial_from_e7(r.lat_e7, r.lon_e7)) |
| 123 | .collect(); |
| 124 | assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}"); |
| 125 | |
| 126 | // The geojson mirrors the index exactly, in the same order. |
| 127 | assert!(lines[0].starts_with("{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[")); |
| 128 | for (line, rec) in lines.iter().zip(&records) { |
| 129 | assert!(line.contains(&format!("\"name\":\"{}\"", rec.name)), "{line}"); |
| 130 | assert!(line.contains(&format!("\"type\":{}", rec.type_)), "{line}"); |
| 131 | assert!( |
| 132 | line.contains(&format!("{:.7},{:.7}", rec.lon_e7 as f64 * 1e-7, rec.lat_e7 as f64 * 1e-7)), |
| 133 | "{line}" |
| 134 | ); |
| 135 | } |
| 136 | // The relation's osm_id is negated so way and relation ids cannot collide. |
| 137 | let park_line = lines.iter().find(|l| l.contains("Riverside Park")).unwrap(); |
| 138 | assert!(park_line.contains(&format!("\"osm_id\":{}", -testpbf::RELATION_ID))); |
| 139 | } |
| 140 | |
| 141 | #[test] |
| 142 | fn ring_centroid_doubles_the_smallest_lon_lat_vertex() { |
| 143 | // libosmium sorted a ring's segments before walking them, so the ring |
| 144 | // always starts — and therefore repeats — at the vertex with the smallest |
| 145 | // (lon, lat). Averaging the way's own node list instead doubles the way's |
| 146 | // FIRST node, which put small buildings metres off. |
| 147 | let pts = [ |
| 148 | (1, (350_000_000, -1_200_000_000)), |
| 149 | (2, (350_000_000, -1_200_010_000)), // smallest lon |
| 150 | (3, (350_030_000, -1_200_010_000)), |
| 151 | (4, (350_030_000, -1_200_000_000)), |
| 152 | ]; |
| 153 | let location = |id: i64| pts.iter().find(|(i, _)| *i == id).map(|(_, l)| *l); |
| 154 | |
| 155 | // Same ring, three different starting vertices: the centroid must not move. |
| 156 | for order in [ |
| 157 | vec![1, 2, 3, 4], |
| 158 | vec![3, 4, 1, 2], |
| 159 | vec![4, 3, 2, 1], |
| 160 | ] { |
| 161 | let (lat, lon) = ring_centroid(order.iter().copied(), &location).unwrap(); |
| 162 | // lat: (350.0 + 350.0 + 350.03 + 350.03 + 350.0[repeat of node 2]) / 5 |
| 163 | assert_eq!((lat * 1e7).round() as i64, 350_012_000, "order {order:?}"); |
| 164 | // lon: (-120.0 - 120.001 - 120.001 - 120.0 - 120.001) / 5 |
| 165 | assert_eq!((lon * 1e7).round() as i64, -1_200_006_000, "order {order:?}"); |
| 166 | } |
| 167 | |
| 168 | // Ties on lon are broken by lat, matching libosmium's Location ordering. |
| 169 | let flat = [ |
| 170 | (1, (350_020_000, -1_200_000_000)), |
| 171 | (2, (350_010_000, -1_200_000_000)), |
| 172 | ]; |
| 173 | let loc2 = |id: i64| flat.iter().find(|(i, _)| *i == id).map(|(_, l)| *l); |
| 174 | let (lat, _) = ring_centroid([1i64, 2].into_iter(), &loc2).unwrap(); |
| 175 | // Node 2 has the smaller lat, so it is the repeated vertex. |
| 176 | assert_eq!((lat * 1e7).round() as i64, 350_013_333); |
| 177 | |
| 178 | // Nothing resolvable -> no POI rather than a (0, 0) centroid. |
| 179 | assert!(ring_centroid([99i64].into_iter(), &location).is_none()); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn two_runs_are_byte_identical() { |
| 184 | let (pbf_path, dir) = testpbf::write_sample("poi_det"); |
| 185 | let run = |suffix: &str| { |
| 186 | build( |
| 187 | &pbf_path, |
| 188 | &dir.join(format!("pois{suffix}.geojsonseq")), |
| 189 | &dir.join(format!("names{suffix}.bin")), |
| 190 | &dir.join(format!("index{suffix}.bin")), |
| 191 | &dir.join(format!("attrs{suffix}.bin")), |
| 192 | &dir.join(format!("spatial{suffix}.bin")), |
| 193 | &dir.join(format!("nameidx{suffix}.bin")), |
| 194 | ) |
| 195 | .unwrap(); |
| 196 | }; |
| 197 | run("a"); |
| 198 | run("b"); |
| 199 | for (a, b) in [ |
| 200 | ("poisa.geojsonseq", "poisb.geojsonseq"), |
| 201 | ("namesa.bin", "namesb.bin"), |
| 202 | ("indexa.bin", "indexb.bin"), |
| 203 | ("attrsa.bin", "attrsb.bin"), |
| 204 | ("spatiala.bin", "spatialb.bin"), |
| 205 | ("nameidxa.bin", "nameidxb.bin"), |
| 206 | ] { |
| 207 | assert_eq!( |
| 208 | std::fs::read(dir.join(a)).unwrap(), |
| 209 | std::fs::read(dir.join(b)).unwrap(), |
| 210 | "{a} differs between runs" |
| 211 | ); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// The sidecar's join to `poi_index.bin` is by ordinal, so the two files have to |
| 216 | /// have exactly the same length in records and agree row for row. |
| 217 | #[test] |
| 218 | fn the_attribute_sidecar_lines_up_with_the_index_by_ordinal() { |
| 219 | use crate::poi_attrs::{ |
| 220 | KEY_CUISINE, KEY_HOUSENUMBER, KEY_OPENING_HOURS, KEY_PHONE, KEY_STREET, KEY_WEBSITE, |
| 221 | }; |
| 222 | let (stats, dir) = build_sample("poi_attrs_join"); |
| 223 | let (records, _) = read_records(&dir); |
| 224 | let attrs = read_attrs(&dir); |
| 225 | |
| 226 | assert_eq!(attrs.len(), records.len(), "one slot per index record"); |
| 227 | assert_eq!(stats.with_attrs, 1, "only the cafe node carries any"); |
| 228 | assert_eq!(stats.unique_attrs, 1); |
| 229 | |
| 230 | let cafe = records.iter().position(|r| r.name == "Corner Cafe").unwrap(); |
| 231 | assert_eq!( |
| 232 | attrs[cafe], |
| 233 | vec![ |
| 234 | (KEY_OPENING_HOURS, "24/7".to_string()), |
| 235 | // The fixture tags `contact:phone` rather than `phone`, so the alias |
| 236 | // has to be read. |
| 237 | (KEY_PHONE, "+1-555-0100".to_string()), |
| 238 | (KEY_WEBSITE, "https://cafe.example".to_string()), |
| 239 | (KEY_HOUSENUMBER, "120".to_string()), |
| 240 | (KEY_STREET, "Market St".to_string()), |
| 241 | (KEY_CUISINE, "coffee_shop".to_string()), |
| 242 | ] |
| 243 | ); |
| 244 | |
| 245 | for (i, a) in attrs.iter().enumerate() { |
| 246 | if i != cafe { |
| 247 | assert!(a.is_empty(), "{} has no attributes", records[i].name); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// Adding the sidecar must not have widened the record everything else measures |
| 253 | /// the file by. `record_count = filesize / 14` is asserted in the README too. |
| 254 | #[test] |
| 255 | fn the_index_record_is_still_fourteen_bytes() { |
| 256 | let (stats, dir) = build_sample("poi_width"); |
| 257 | let index = std::fs::read(dir.join("poi_index.bin")).unwrap(); |
| 258 | assert_eq!(index.len(), stats.records * 14); |
| 259 | } |
| 260 | |
| 261 | /// Review rows join on (element, OSM id) before the Morton sort, and land on the |
| 262 | /// right ordinal after it. The relation row uses the plain id even though the |
| 263 | /// POI stores it negated. |
| 264 | #[test] |
| 265 | fn review_rows_join_by_element_and_osm_id() { |
| 266 | use crate::poi_attrs::{KEY_RATING, KEY_REVIEW_COUNT, KEY_REVIEW_SUMMARY, KEY_CUISINE}; |
| 267 | let (pbf_path, dir) = testpbf::write_sample("poi_reviews_join"); |
| 268 | let table = crate::poi_reviews::ReviewTable::parse(&format!( |
| 269 | "node\t{}\t4.3\t120\tGreat coffee, slow at lunch.\n\ |
| 270 | way\t{}\t3.8\t15\t\n\ |
| 271 | relation\t{}\t\t40\tShady lawns.\n\ |
| 272 | way\t{}\t1.0\t1\tWrong element, must not match.\n", |
| 273 | testpbf::CAFE_NODE_ID, |
| 274 | testpbf::AREA_WAY_ID, |
| 275 | testpbf::RELATION_ID, |
| 276 | testpbf::CAFE_NODE_ID, |
| 277 | )) |
| 278 | .unwrap(); |
| 279 | let stats = build_with_reviews( |
| 280 | &pbf_path, |
| 281 | &dir.join("pois.geojsonseq"), |
| 282 | &dir.join("poi_names.bin"), |
| 283 | &dir.join("poi_index.bin"), |
| 284 | &dir.join("poi_attrs.bin"), |
| 285 | &dir.join("poi_spatial.bin"), |
| 286 | &dir.join("poi_name_index.bin"), |
| 287 | None, |
| 288 | Some(&table), |
| 289 | ) |
| 290 | .unwrap(); |
| 291 | assert_eq!(stats.with_reviews, 3); |
| 292 | |
| 293 | let (records, _) = read_records(&dir); |
| 294 | let attrs = read_attrs(&dir); |
| 295 | let of = |n: &str| &attrs[records.iter().position(|r| r.name == n).unwrap()]; |
| 296 | |
| 297 | let cafe = of("Corner Cafe"); |
| 298 | assert_eq!(cafe[cafe.len() - 4], (KEY_CUISINE, "coffee_shop".to_string()), "tag fields first"); |
| 299 | assert_eq!( |
| 300 | cafe[cafe.len() - 3..], |
| 301 | [ |
| 302 | (KEY_RATING, "4.3".to_string()), |
| 303 | (KEY_REVIEW_COUNT, "120".to_string()), |
| 304 | (KEY_REVIEW_SUMMARY, "Great coffee, slow at lunch.".to_string()), |
| 305 | ] |
| 306 | ); |
| 307 | assert_eq!( |
| 308 | of("Plaza"), |
| 309 | &vec![(KEY_RATING, "3.8".to_string()), (KEY_REVIEW_COUNT, "15".to_string())] |
| 310 | ); |
| 311 | assert_eq!( |
| 312 | of("Riverside Park"), |
| 313 | &vec![(KEY_REVIEW_COUNT, "40".to_string()), (KEY_REVIEW_SUMMARY, "Shady lawns.".to_string())] |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn args_require_all_three_outputs() { |
| 319 | let ok = parse_args(&[ |
| 320 | "in.pbf".into(), |
| 321 | "--geojson".into(), |
| 322 | "g".into(), |
| 323 | "--names".into(), |
| 324 | "n".into(), |
| 325 | "--index".into(), |
| 326 | "out/poi_index.bin".into(), |
| 327 | ]) |
| 328 | .unwrap(); |
| 329 | assert_eq!(ok.input, PathBuf::from("in.pbf")); |
| 330 | assert_eq!(ok.index, PathBuf::from("out/poi_index.bin")); |
| 331 | // Defaulted beside the index, so a caller written before the sidecar existed |
| 332 | // still emits one rather than silently skipping it. |
| 333 | assert_eq!(ok.attrs, PathBuf::from("out/poi_attrs.bin")); |
| 334 | assert!(ok.threads.is_none(), "the pool defaults to the box"); |
| 335 | assert!(parse_args(&["in.pbf".into()]).is_err()); |
| 336 | assert!(parse_args(&["in.pbf".into(), "--geojson".into()]).is_err()); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn threads_must_be_positive() { |
| 341 | let base: Vec<String> = vec![ |
| 342 | "in.pbf".into(), |
| 343 | "--geojson".into(), |
| 344 | "g".into(), |
| 345 | "--names".into(), |
| 346 | "n".into(), |
| 347 | "--index".into(), |
| 348 | "i".into(), |
| 349 | ]; |
| 350 | let mut with = base.clone(); |
| 351 | with.extend(["--threads".to_string(), "3".to_string()]); |
| 352 | assert_eq!(parse_args(&with).unwrap().threads, Some(3)); |
| 353 | |
| 354 | let mut zero = base.clone(); |
| 355 | zero.extend(["--threads".to_string(), "0".to_string()]); |
| 356 | assert!(parse_args(&zero).is_err()); |
| 357 | |
| 358 | let mut bare = base; |
| 359 | bare.push("--threads".into()); |
| 360 | assert!(parse_args(&bare).is_err()); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn an_explicit_attrs_path_overrides_the_default() { |
| 365 | let ok = parse_args(&[ |
| 366 | "in.pbf".into(), |
| 367 | "--geojson".into(), |
| 368 | "g".into(), |
| 369 | "--names".into(), |
| 370 | "n".into(), |
| 371 | "--index".into(), |
| 372 | "i".into(), |
| 373 | "--attrs".into(), |
| 374 | "elsewhere/a.bin".into(), |
| 375 | ]) |
| 376 | .unwrap(); |
| 377 | assert_eq!(ok.attrs, PathBuf::from("elsewhere/a.bin")); |
| 378 | } |
| 379 | } |