Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_side.rs
poi_side.rs390 lines · 14.8 KiBRaw
| 1 | //! The two optional POI side files: `poi_spatial.bin` and `poi_name_index.bin`. |
| 2 | //! |
| 3 | //! Both exist to remove lookups whose cost grew with the size of the whole dataset. |
| 4 | //! `poi_index.bin` is Morton-sorted, which bounds a bbox query by the *Morton span* of |
| 5 | //! that bbox — and a box straddling a high-order Morton boundary spans a huge key |
| 6 | //! interval even when it is geographically tiny. A plain row/column grid has no such |
| 7 | //! pathology, so `nearest`/`inViewport` become exactly cell-local. Name search had no |
| 8 | //! index at all and scanned the name pool and then every record. |
| 9 | //! |
| 10 | //! ## Layouts |
| 11 | //! |
| 12 | //! Both files are little-endian, self-describing (unlike the transit pack's grid, whose |
| 13 | //! parameters live in a shared header), and both carry the record count so a reader can |
| 14 | //! refuse a side file left over from a different `poi_index.bin` rather than silently |
| 15 | //! joining by a stale ordinal. |
| 16 | //! |
| 17 | //! **`poi_spatial.bin`** — the sparse CSR grid the transit pack already uses |
| 18 | //! (`gtfs_ingest/src/index.rs`, read by `maps/src/main/rust/src/transit.rs`), so there |
| 19 | //! is a working reference on both sides: |
| 20 | //! |
| 21 | //! ```text |
| 22 | //! magic "PSP1" | u32 version | u32 record_count | u32 cell_count |
| 23 | //! i32 lat0_e7 | i32 lon0_e7 | u32 cell_e7 | u32 cols (32-byte header) |
| 24 | //! u32 cell_ids[cell_count] ascending, populated cells only |
| 25 | //! u32 cell_off[cell_count + 1] CSR prefix into ordinals |
| 26 | //! u32 ordinals[record_count] grouped by cell, ascending within a cell |
| 27 | //! ``` |
| 28 | //! |
| 29 | //! **`poi_name_index.bin`** — one entry per (record, word), sorted by the word: |
| 30 | //! |
| 31 | //! ```text |
| 32 | //! magic "PNI1" | u32 version | u32 record_count | u32 entry_count (16-byte header) |
| 33 | //! u32 ordinals[entry_count] the record the word belongs to |
| 34 | //! u8 word_idx[entry_count] which word of that record's name |
| 35 | //! ``` |
| 36 | //! |
| 37 | //! Parallel arrays rather than a packed struct, so an entry costs 5 bytes and not the 8 |
| 38 | //! that alignment would round it up to. It is still the largest of the POI files: |
| 39 | //! indexing *every* word, not just the name's first, means the entry count is roughly |
| 40 | //! the record count times the average word count, and it cannot be per-*name* instead — |
| 41 | //! `poi_names.bin` is deduplicated, so a word only identifies a name, and a name still |
| 42 | //! has to be resolved to the records that use it. |
| 43 | //! |
| 44 | //! ## The cross-language contract |
| 45 | //! |
| 46 | //! A sorted index is only searchable if the reader orders words exactly as the writer |
| 47 | //! did, so both sides commit to this and nothing subtler: |
| 48 | //! |
| 49 | //! * A **word** is a maximal run of bytes that are not ASCII whitespace. Splitting on |
| 50 | //! whitespace only is safe on raw UTF-8 because no byte of a multi-byte sequence is |
| 51 | //! ever below `0x80`. |
| 52 | //! * The **sort key** is the word's bytes with ASCII `A-Z` mapped to lowercase and every |
| 53 | //! other byte, including all non-ASCII, left alone. Deliberately *not* Unicode |
| 54 | //! case folding: `str::to_lowercase` and Kotlin's `String.lowercase` do not agree |
| 55 | //! byte-for-byte on every input, and a disagreement here is a silently unfindable POI. |
| 56 | //! * At most [`MAX_WORDS`] words per name are indexed, since the word index is a `u8`. |
| 57 | //! |
| 58 | //! The Kotlin reader is `PoiIndex.kt`; [`tests`] pins the ordering from this side. |
| 59 | |
| 60 | use std::cmp::Ordering; |
| 61 | use std::io::{self, Write}; |
| 62 | |
| 63 | pub const SPATIAL_MAGIC: &[u8; 4] = b"PSP1"; |
| 64 | pub const SPATIAL_VERSION: u32 = 1; |
| 65 | pub const SPATIAL_HEADER_BYTES: usize = 32; |
| 66 | |
| 67 | pub const NAME_MAGIC: &[u8; 4] = b"PNI1"; |
| 68 | pub const NAME_VERSION: u32 = 1; |
| 69 | pub const NAME_HEADER_BYTES: usize = 16; |
| 70 | |
| 71 | /// Grid cell size in 1e-7 degrees: 0.02°, the same as the transit pack's. |
| 72 | pub const CELL_E7: u32 = 200_000; |
| 73 | |
| 74 | /// Words indexed per name. Bounded because the word index is stored as a `u8`. |
| 75 | pub const MAX_WORDS: usize = 255; |
| 76 | |
| 77 | /// ASCII-only lowercase. See the module's cross-language contract. |
| 78 | #[inline] |
| 79 | pub fn ascii_lower(b: u8) -> u8 { |
| 80 | if b.is_ascii_uppercase() { |
| 81 | b + 32 |
| 82 | } else { |
| 83 | b |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Order two words as the index is sorted: ASCII-lowercased byte order. |
| 88 | pub fn cmp_word(a: &[u8], b: &[u8]) -> Ordering { |
| 89 | let common = a.len().min(b.len()); |
| 90 | for i in 0..common { |
| 91 | match ascii_lower(a[i]).cmp(&ascii_lower(b[i])) { |
| 92 | Ordering::Equal => {} |
| 93 | other => return other, |
| 94 | } |
| 95 | } |
| 96 | a.len().cmp(&b.len()) |
| 97 | } |
| 98 | |
| 99 | /// The whitespace-separated words of `name`, paired with their index, capped at |
| 100 | /// [`MAX_WORDS`]. |
| 101 | pub fn words(name: &[u8]) -> impl Iterator<Item = (u8, &[u8])> { |
| 102 | name.split(|b| b.is_ascii_whitespace()) |
| 103 | .filter(|w| !w.is_empty()) |
| 104 | .take(MAX_WORDS) |
| 105 | .enumerate() |
| 106 | .map(|(i, w)| (i as u8, w)) |
| 107 | } |
| 108 | |
| 109 | /// The `word_idx`th word of `name`, or `None` when the name has fewer. |
| 110 | /// |
| 111 | /// The reader needs the same lookup, so this is the definition both sides share rather |
| 112 | /// than each re-deriving "which run of bytes is word 3". |
| 113 | pub fn word_at(name: &[u8], word_idx: u8) -> Option<&[u8]> { |
| 114 | words(name).find(|(i, _)| *i == word_idx).map(|(_, w)| w) |
| 115 | } |
| 116 | |
| 117 | /// Where the grid is anchored and how wide it is. |
| 118 | /// |
| 119 | /// Anchored at the minimum corner of the records' own extent, like the transit pack's, |
| 120 | /// so a regional extract does not pay for cells covering the rest of the planet. |
| 121 | pub struct Grid { |
| 122 | pub lat0_e7: i32, |
| 123 | pub lon0_e7: i32, |
| 124 | pub cols: u32, |
| 125 | } |
| 126 | |
| 127 | impl Grid { |
| 128 | /// Fit a grid to `coords`. `None` when there are no records to bound. |
| 129 | pub fn fit(coords: &[(i32, i32)]) -> Option<Grid> { |
| 130 | let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX); |
| 131 | let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN); |
| 132 | for &(lat, lon) in coords { |
| 133 | min_lat = min_lat.min(lat); |
| 134 | min_lon = min_lon.min(lon); |
| 135 | max_lat = max_lat.max(lat); |
| 136 | max_lon = max_lon.max(lon); |
| 137 | } |
| 138 | if min_lat > max_lat { |
| 139 | return None; |
| 140 | } |
| 141 | let cols = cell_axis(max_lon, min_lon) + 1; |
| 142 | Some(Grid { |
| 143 | lat0_e7: min_lat, |
| 144 | lon0_e7: min_lon, |
| 145 | cols, |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | pub fn row(&self, lat_e7: i32) -> u32 { |
| 150 | cell_axis(lat_e7, self.lat0_e7) |
| 151 | } |
| 152 | |
| 153 | pub fn col(&self, lon_e7: i32) -> u32 { |
| 154 | cell_axis(lon_e7, self.lon0_e7).min(self.cols.saturating_sub(1)) |
| 155 | } |
| 156 | |
| 157 | pub fn cell(&self, lat_e7: i32, lon_e7: i32) -> u32 { |
| 158 | self.row(lat_e7) |
| 159 | .saturating_mul(self.cols) |
| 160 | .saturating_add(self.col(lon_e7)) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Cell offset of `value` from the grid origin, floored at 0. |
| 165 | fn cell_axis(value: i32, origin: i32) -> u32 { |
| 166 | let d = value as i64 - origin as i64; |
| 167 | if d <= 0 { |
| 168 | 0 |
| 169 | } else { |
| 170 | (d / CELL_E7 as i64) as u32 |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Write `poi_spatial.bin` for records whose coordinates are `coords[ordinal]`. |
| 175 | /// |
| 176 | /// Returns the number of populated cells. Writes a valid, empty grid for no records |
| 177 | /// rather than refusing, so the file's presence never depends on the extract. |
| 178 | pub fn write_spatial<W: Write>(out: &mut W, coords: &[(i32, i32)]) -> io::Result<usize> { |
| 179 | let grid = Grid::fit(coords); |
| 180 | let (lat0, lon0, cols) = match &grid { |
| 181 | Some(g) => (g.lat0_e7, g.lon0_e7, g.cols), |
| 182 | None => (0, 0, 0), |
| 183 | }; |
| 184 | |
| 185 | // (cell, ordinal), sorted so equal cells are adjacent and ordinals ascend within |
| 186 | // one — the order the CSR encodes, and the order a reader walks. |
| 187 | let mut pairs: Vec<(u32, u32)> = Vec::with_capacity(coords.len()); |
| 188 | if let Some(g) = &grid { |
| 189 | for (ordinal, &(lat, lon)) in coords.iter().enumerate() { |
| 190 | pairs.push((g.cell(lat, lon), ordinal as u32)); |
| 191 | } |
| 192 | } |
| 193 | pairs.sort_unstable(); |
| 194 | |
| 195 | let mut cell_ids: Vec<u32> = Vec::new(); |
| 196 | let mut cell_off: Vec<u32> = Vec::new(); |
| 197 | for (i, &(cell, _)) in pairs.iter().enumerate() { |
| 198 | if cell_ids.last() != Some(&cell) { |
| 199 | cell_ids.push(cell); |
| 200 | cell_off.push(i as u32); |
| 201 | } |
| 202 | } |
| 203 | cell_off.push(pairs.len() as u32); |
| 204 | |
| 205 | out.write_all(SPATIAL_MAGIC)?; |
| 206 | out.write_all(&SPATIAL_VERSION.to_le_bytes())?; |
| 207 | out.write_all(&(coords.len() as u32).to_le_bytes())?; |
| 208 | out.write_all(&(cell_ids.len() as u32).to_le_bytes())?; |
| 209 | out.write_all(&lat0.to_le_bytes())?; |
| 210 | out.write_all(&lon0.to_le_bytes())?; |
| 211 | out.write_all(&CELL_E7.to_le_bytes())?; |
| 212 | out.write_all(&cols.to_le_bytes())?; |
| 213 | for id in &cell_ids { |
| 214 | out.write_all(&id.to_le_bytes())?; |
| 215 | } |
| 216 | for off in &cell_off { |
| 217 | out.write_all(&off.to_le_bytes())?; |
| 218 | } |
| 219 | for &(_, ordinal) in &pairs { |
| 220 | out.write_all(&ordinal.to_le_bytes())?; |
| 221 | } |
| 222 | Ok(cell_ids.len()) |
| 223 | } |
| 224 | |
| 225 | /// Write `poi_name_index.bin` for records whose names are `names[ordinal]`. |
| 226 | /// |
| 227 | /// Returns the number of entries. The sort resolves each entry's word out of `names` |
| 228 | /// rather than materialising it, which keeps the working set to 8 bytes per entry |
| 229 | /// instead of that plus a copy of every word. |
| 230 | pub fn write_name_index<W: Write>(out: &mut W, names: &[&[u8]]) -> io::Result<usize> { |
| 231 | let mut entries: Vec<(u32, u8)> = Vec::new(); |
| 232 | for (ordinal, name) in names.iter().enumerate() { |
| 233 | for (word_idx, _) in words(name) { |
| 234 | entries.push((ordinal as u32, word_idx)); |
| 235 | } |
| 236 | } |
| 237 | // Ordinal breaks ties so the file is reproducible: two runs over the same input |
| 238 | // must be byte-identical, which an unstable sort only gives on a total order. |
| 239 | entries.sort_unstable_by(|a, b| { |
| 240 | let wa = word_at(names[a.0 as usize], a.1).unwrap_or_default(); |
| 241 | let wb = word_at(names[b.0 as usize], b.1).unwrap_or_default(); |
| 242 | cmp_word(wa, wb).then(a.cmp(b)) |
| 243 | }); |
| 244 | |
| 245 | out.write_all(NAME_MAGIC)?; |
| 246 | out.write_all(&NAME_VERSION.to_le_bytes())?; |
| 247 | out.write_all(&(names.len() as u32).to_le_bytes())?; |
| 248 | out.write_all(&(entries.len() as u32).to_le_bytes())?; |
| 249 | for &(ordinal, _) in &entries { |
| 250 | out.write_all(&ordinal.to_le_bytes())?; |
| 251 | } |
| 252 | for &(_, word_idx) in &entries { |
| 253 | out.write_all(&[word_idx])?; |
| 254 | } |
| 255 | Ok(entries.len()) |
| 256 | } |
| 257 | |
| 258 | #[cfg(test)] |
| 259 | mod tests { |
| 260 | use super::*; |
| 261 | |
| 262 | fn u32_at(bytes: &[u8], at: usize) -> u32 { |
| 263 | u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) |
| 264 | } |
| 265 | |
| 266 | #[test] |
| 267 | fn words_split_on_whitespace_only() { |
| 268 | let got: Vec<&[u8]> = words(b"Joe's Pizza\tBar").map(|(_, w)| w).collect(); |
| 269 | assert_eq!(got, vec![&b"Joe's"[..], &b"Pizza"[..], &b"Bar"[..]]); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn word_indices_count_from_zero() { |
| 274 | let name = b"San Francisco Public Library"; |
| 275 | assert_eq!(word_at(name, 0), Some(&b"San"[..])); |
| 276 | assert_eq!(word_at(name, 3), Some(&b"Library"[..])); |
| 277 | assert_eq!(word_at(name, 4), None); |
| 278 | } |
| 279 | |
| 280 | /// Only ASCII folds. A Unicode-aware lowercase would disagree with the reader. |
| 281 | #[test] |
| 282 | fn comparison_folds_ascii_and_leaves_other_bytes_alone() { |
| 283 | assert_eq!(cmp_word(b"PIZZA", b"pizza"), Ordering::Equal); |
| 284 | assert_eq!(cmp_word(b"Cafe", b"cafz"), Ordering::Less); |
| 285 | // U+00C9 vs U+00E9: both pass through, so they order by raw byte. |
| 286 | assert_eq!(cmp_word("É".as_bytes(), "é".as_bytes()), Ordering::Less); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn a_shorter_word_sorts_before_a_longer_one_sharing_its_prefix() { |
| 291 | assert_eq!(cmp_word(b"pizz", b"pizza"), Ordering::Less); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn the_grid_is_anchored_at_the_records_minimum_corner() { |
| 296 | let coords = [(37_700_000, -122_400_000), (37_720_000, -122_380_000)]; |
| 297 | let g = Grid::fit(&coords).expect("records exist"); |
| 298 | assert_eq!(g.lat0_e7, 37_700_000); |
| 299 | assert_eq!(g.lon0_e7, -122_400_000); |
| 300 | assert_eq!(g.cell(37_700_000, -122_400_000), 0); |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn an_empty_extract_has_no_grid() { |
| 305 | assert!(Grid::fit(&[]).is_none()); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn the_spatial_csr_groups_every_ordinal_under_its_cell() { |
| 310 | // Two POIs in one cell (0.02deg apart is one cell over, so keep them closer) |
| 311 | // and a third far away. |
| 312 | let coords = [ |
| 313 | (37_700_000, -122_400_000), |
| 314 | (37_700_100, -122_400_100), |
| 315 | (38_000_000, -122_000_000), |
| 316 | ]; |
| 317 | let mut buf = Vec::new(); |
| 318 | let cells = write_spatial(&mut buf, &coords).unwrap(); |
| 319 | assert_eq!(cells, 2, "two populated cells"); |
| 320 | assert_eq!(&buf[0..4], SPATIAL_MAGIC); |
| 321 | assert_eq!(u32_at(&buf, 8), 3, "record count"); |
| 322 | assert_eq!(u32_at(&buf, 12), 2, "cell count"); |
| 323 | |
| 324 | let ids = SPATIAL_HEADER_BYTES; |
| 325 | let off = ids + 4 * cells; |
| 326 | let ords = off + 4 * (cells + 1); |
| 327 | assert!(u32_at(&buf, ids) < u32_at(&buf, ids + 4), "cell ids ascend"); |
| 328 | assert_eq!(u32_at(&buf, off), 0); |
| 329 | assert_eq!(u32_at(&buf, off + 4), 2, "first cell holds two records"); |
| 330 | assert_eq!(u32_at(&buf, off + 8), 3); |
| 331 | assert_eq!(u32_at(&buf, ords), 0); |
| 332 | assert_eq!(u32_at(&buf, ords + 4), 1); |
| 333 | assert_eq!(u32_at(&buf, ords + 8), 2); |
| 334 | assert_eq!(buf.len(), ords + 4 * coords.len()); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn the_name_index_sorts_every_word_of_every_record() { |
| 339 | let names: Vec<&[u8]> = vec![b"Joe's Pizza", b"Pizza Hut"]; |
| 340 | let mut buf = Vec::new(); |
| 341 | let entries = write_name_index(&mut buf, &names).unwrap(); |
| 342 | assert_eq!(entries, 4, "two words each"); |
| 343 | assert_eq!(&buf[0..4], NAME_MAGIC); |
| 344 | assert_eq!(u32_at(&buf, 8), 2, "record count"); |
| 345 | assert_eq!(u32_at(&buf, 12), 4, "entry count"); |
| 346 | |
| 347 | // Sorted: "hut", "joe's", "pizza"(#0 word 1), "pizza"(#1 word 0). |
| 348 | let ord = NAME_HEADER_BYTES; |
| 349 | let widx = ord + 4 * entries; |
| 350 | let got: Vec<(u32, u8)> = |
| 351 | (0..entries).map(|i| (u32_at(&buf, ord + 4 * i), buf[widx + i])).collect(); |
| 352 | assert_eq!(got, vec![(1, 1), (0, 0), (0, 1), (1, 0)]); |
| 353 | } |
| 354 | |
| 355 | /// Both words of a name resolve to the same record, which is what makes "pizza" |
| 356 | /// find "Joe's Pizza" without a scan. |
| 357 | #[test] |
| 358 | fn a_trailing_word_still_points_at_its_record() { |
| 359 | let names: Vec<&[u8]> = vec![b"Joe's Pizza"]; |
| 360 | let mut buf = Vec::new(); |
| 361 | let entries = write_name_index(&mut buf, &names).unwrap(); |
| 362 | assert_eq!(entries, 2); |
| 363 | let widx = NAME_HEADER_BYTES + 4 * entries; |
| 364 | assert_eq!(u32_at(&buf, NAME_HEADER_BYTES), 0); |
| 365 | assert_eq!(buf[widx], 0, "\"joe's\" first"); |
| 366 | assert_eq!(buf[widx + 1], 1, "then \"pizza\""); |
| 367 | } |
| 368 | |
| 369 | #[test] |
| 370 | fn two_runs_over_the_same_input_are_byte_identical() { |
| 371 | let names: Vec<&[u8]> = vec![b"Cafe Roma", b"Roma Cafe", b"Cafe Roma"]; |
| 372 | let coords = [(1_000, 2_000), (3_000, 4_000), (5_000, 6_000)]; |
| 373 | let (mut a, mut b) = (Vec::new(), Vec::new()); |
| 374 | write_name_index(&mut a, &names).unwrap(); |
| 375 | write_name_index(&mut b, &names).unwrap(); |
| 376 | assert_eq!(a, b); |
| 377 | let (mut c, mut d) = (Vec::new(), Vec::new()); |
| 378 | write_spatial(&mut c, &coords).unwrap(); |
| 379 | write_spatial(&mut d, &coords).unwrap(); |
| 380 | assert_eq!(c, d); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn an_unnamed_record_contributes_no_entries() { |
| 385 | let names: Vec<&[u8]> = vec![b"", b" ", b"Real Name"]; |
| 386 | let mut buf = Vec::new(); |
| 387 | assert_eq!(write_name_index(&mut buf, &names).unwrap(), 2); |
| 388 | assert_eq!(u32_at(&buf, 8), 3, "record count still counts them"); |
| 389 | } |
| 390 | } |