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

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

poi_side.rs464 lines · 18.0 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//! **`poi_region.bin`** — one tagged OSM boundary id per POI ordinal:
38//!
39//! ```text
40//! magic "PRG1" | u32 version | u32 record_count (12-byte header)
41//! u64 tagged_ids[record_count] native OSM label-member link first,
42//! smallest containing admin fallback, else 0
43//! ```
44//!
45//! The tagged id packs the OSM id space in the low 2 bits (0 none / 1 node /
46//! 2 way / 3 relation): `tagged = (osm_id << 2) | space`. Boundary relations
47//! use space 3, boundary ways space 2. `0` (`REGION_NONE`) stamps nothing, so
48//! the reader masks nothing and the app's name-match fallback still applies.
49//!
50//! Parallel arrays rather than a packed struct, so an entry costs 5 bytes and not the 8
51//! that alignment would round it up to. It is still the largest of the POI files:
52//! indexing *every* word, not just the name's first, means the entry count is roughly
53//! the record count times the average word count, and it cannot be per-*name* instead —
54//! `poi_names.bin` is deduplicated, so a word only identifies a name, and a name still
55//! has to be resolved to the records that use it.
56//!
57//! ## The cross-language contract
58//!
59//! A sorted index is only searchable if the reader orders words exactly as the writer
60//! did, so both sides commit to this and nothing subtler:
61//!
62//! * A **word** is a maximal run of bytes that are not ASCII whitespace. Splitting on
63//! whitespace only is safe on raw UTF-8 because no byte of a multi-byte sequence is
64//! ever below `0x80`.
65//! * The **sort key** is the word's bytes with ASCII `A-Z` mapped to lowercase and every
66//! other byte, including all non-ASCII, left alone. Deliberately *not* Unicode
67//! case folding: `str::to_lowercase` and Kotlin's `String.lowercase` do not agree
68//! byte-for-byte on every input, and a disagreement here is a silently unfindable POI.
69//! * At most [`MAX_WORDS`] words per name are indexed, since the word index is a `u8`.
70//!
71//! The Kotlin reader is `PoiIndex.kt`; [`tests`] pins the ordering from this side.
72
73/// Tagged-OSM-id space bits packed into the low 2 bits of a region link.
74pub const REGION_NONE: u64 = 0;
75
76/// Tag an OSM relation id as a region link.
77pub fn tag_relation(id: i64) -> u64 {
78 ((id as u64) << 2) | 3
79}
80
81/// Tag an OSM way id as a region link.
82pub fn tag_way(id: i64) -> u64 {
83 ((id as u64) << 2) | 2
84}
85
86use std::cmp::Ordering;
87use std::io::{self, Write};
88
89pub const SPATIAL_MAGIC: &[u8; 4] = b"PSP1";
90pub const SPATIAL_VERSION: u32 = 1;
91pub const SPATIAL_HEADER_BYTES: usize = 32;
92
93pub const NAME_MAGIC: &[u8; 4] = b"PNI1";
94pub const NAME_VERSION: u32 = 1;
95pub const NAME_HEADER_BYTES: usize = 16;
96
97pub const REGION_MAGIC: &[u8; 4] = b"PRG1";
98pub const REGION_VERSION: u32 = 1;
99pub const REGION_HEADER_BYTES: usize = 12;
100
101/// Grid cell size in 1e-7 degrees: 0.02°, the same as the transit pack's.
102pub const CELL_E7: u32 = 200_000;
103
104/// Words indexed per name. Bounded because the word index is stored as a `u8`.
105pub const MAX_WORDS: usize = 255;
106
107/// ASCII-only lowercase. See the module's cross-language contract.
108#[inline]
109pub fn ascii_lower(b: u8) -> u8 {
110 if b.is_ascii_uppercase() {
111 b + 32
112 } else {
113 b
114 }
115}
116
117/// Order two words as the index is sorted: ASCII-lowercased byte order.
118pub fn cmp_word(a: &[u8], b: &[u8]) -> Ordering {
119 let common = a.len().min(b.len());
120 for i in 0..common {
121 match ascii_lower(a[i]).cmp(&ascii_lower(b[i])) {
122 Ordering::Equal => {}
123 other => return other,
124 }
125 }
126 a.len().cmp(&b.len())
127}
128
129/// The whitespace-separated words of `name`, paired with their index, capped at
130/// [`MAX_WORDS`].
131pub fn words(name: &[u8]) -> impl Iterator<Item = (u8, &[u8])> {
132 name.split(|b| b.is_ascii_whitespace())
133 .filter(|w| !w.is_empty())
134 .take(MAX_WORDS)
135 .enumerate()
136 .map(|(i, w)| (i as u8, w))
137}
138
139/// The `word_idx`th word of `name`, or `None` when the name has fewer.
140///
141/// The reader needs the same lookup, so this is the definition both sides share rather
142/// than each re-deriving "which run of bytes is word 3".
143pub fn word_at(name: &[u8], word_idx: u8) -> Option<&[u8]> {
144 words(name).find(|(i, _)| *i == word_idx).map(|(_, w)| w)
145}
146
147/// Where the grid is anchored and how wide it is.
148///
149/// Anchored at the minimum corner of the records' own extent, like the transit pack's,
150/// so a regional extract does not pay for cells covering the rest of the planet.
151pub struct Grid {
152 pub lat0_e7: i32,
153 pub lon0_e7: i32,
154 pub cols: u32,
155}
156
157impl Grid {
158 /// Fit a grid to `coords`. `None` when there are no records to bound.
159 pub fn fit(coords: &[(i32, i32)]) -> Option<Grid> {
160 let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX);
161 let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN);
162 for &(lat, lon) in coords {
163 min_lat = min_lat.min(lat);
164 min_lon = min_lon.min(lon);
165 max_lat = max_lat.max(lat);
166 max_lon = max_lon.max(lon);
167 }
168 if min_lat > max_lat {
169 return None;
170 }
171 let cols = cell_axis(max_lon, min_lon) + 1;
172 Some(Grid { lat0_e7: min_lat, lon0_e7: min_lon, cols })
173 }
174
175 pub fn row(&self, lat_e7: i32) -> u32 {
176 cell_axis(lat_e7, self.lat0_e7)
177 }
178
179 pub fn col(&self, lon_e7: i32) -> u32 {
180 cell_axis(lon_e7, self.lon0_e7).min(self.cols.saturating_sub(1))
181 }
182
183 pub fn cell(&self, lat_e7: i32, lon_e7: i32) -> u32 {
184 self.row(lat_e7).saturating_mul(self.cols).saturating_add(self.col(lon_e7))
185 }
186}
187
188/// Cell offset of `value` from the grid origin, floored at 0.
189fn cell_axis(value: i32, origin: i32) -> u32 {
190 let d = value as i64 - origin as i64;
191 if d <= 0 {
192 0
193 } else {
194 (d / CELL_E7 as i64) as u32
195 }
196}
197
198/// Write `poi_spatial.bin` for records whose coordinates are `coords[ordinal]`.
199///
200/// Returns the number of populated cells. Writes a valid, empty grid for no records
201/// rather than refusing, so the file's presence never depends on the extract.
202pub fn write_spatial<W: Write>(out: &mut W, coords: &[(i32, i32)]) -> io::Result<usize> {
203 use rayon::prelude::*;
204 let grid = Grid::fit(coords);
205 let (lat0, lon0, cols) = match &grid {
206 Some(g) => (g.lat0_e7, g.lon0_e7, g.cols),
207 None => (0, 0, 0),
208 };
209
210 // `(cell, ordinal)` pairs are unique (the ordinal is), so the parallel
211 // unstable sort orders them exactly as the serial one did.
212 let mut pairs: Vec<(u32, u32)> = match &grid {
213 Some(g) => crate::par::install(|| {
214 coords
215 .par_iter()
216 .enumerate()
217 .map(|(ordinal, &(lat, lon))| (g.cell(lat, lon), ordinal as u32))
218 .collect()
219 }),
220 None => Vec::new(),
221 };
222 crate::par::install(|| pairs.par_sort_unstable());
223
224 let mut cell_ids: Vec<u32> = Vec::new();
225 let mut cell_off: Vec<u32> = Vec::new();
226 for (i, &(cell, _)) in pairs.iter().enumerate() {
227 if cell_ids.last() != Some(&cell) {
228 cell_ids.push(cell);
229 cell_off.push(i as u32);
230 }
231 }
232 cell_off.push(pairs.len() as u32);
233
234 // One buffer, one write: the file is a few hundred MB on a planet, and
235 // 4-byte `write_all`s through a default `BufWriter` cost more than the sort.
236 let mut buf: Vec<u8> =
237 Vec::with_capacity(SPATIAL_HEADER_BYTES + 4 * (2 * cell_ids.len() + 1 + pairs.len()));
238 buf.extend_from_slice(SPATIAL_MAGIC);
239 buf.extend_from_slice(&SPATIAL_VERSION.to_le_bytes());
240 buf.extend_from_slice(&(coords.len() as u32).to_le_bytes());
241 buf.extend_from_slice(&(cell_ids.len() as u32).to_le_bytes());
242 buf.extend_from_slice(&lat0.to_le_bytes());
243 buf.extend_from_slice(&lon0.to_le_bytes());
244 buf.extend_from_slice(&CELL_E7.to_le_bytes());
245 buf.extend_from_slice(&cols.to_le_bytes());
246 for id in &cell_ids {
247 buf.extend_from_slice(&id.to_le_bytes());
248 }
249 for off in &cell_off {
250 buf.extend_from_slice(&off.to_le_bytes());
251 }
252 for &(_, ordinal) in &pairs {
253 buf.extend_from_slice(&ordinal.to_le_bytes());
254 }
255 out.write_all(&buf)?;
256 Ok(cell_ids.len())
257}
258
259/// Write `poi_name_index.bin` for records whose names are `names[ordinal]`.
260///
261/// Returns the number of entries.
262///
263/// Each entry carries its word's byte range inside its name, so the sort compares
264/// slices directly. The serial version re-split the name with [`word_at`] on every
265/// comparison — O(name) work inside an O(n log n) sort, on one thread — which was
266/// 1.4 s of a 14 s California run and the largest serial stage after the region
267/// stamp. 16 bytes an entry instead of 8; on a planet's ~10^8 entries that is
268/// ~0.8 GB more, at a stage whose peak is otherwise just the POI vector.
269///
270/// Same order, bit for bit: the key is still `cmp_word(word, word)` then
271/// `(ordinal, word_idx)`, a total order (the pair is unique), so the parallel
272/// unstable sort cannot order equal keys differently from the serial one.
273pub fn write_name_index<W: Write>(out: &mut W, names: &[&[u8]]) -> io::Result<usize> {
274 use rayon::prelude::*;
275 /// `(ordinal, word start, word end, word_idx)`.
276 type Entry = (u32, u32, u32, u8);
277 let per_name: Vec<Vec<Entry>> = crate::par::install(|| {
278 names
279 .par_iter()
280 .enumerate()
281 .with_min_len(4096)
282 .map(|(ordinal, name)| {
283 let base = name.as_ptr() as usize;
284 words(name)
285 .map(|(word_idx, w)| {
286 let start = (w.as_ptr() as usize - base) as u32;
287 (ordinal as u32, start, start + w.len() as u32, word_idx)
288 })
289 .collect()
290 })
291 .collect()
292 });
293 let mut entries: Vec<Entry> = Vec::with_capacity(per_name.iter().map(Vec::len).sum());
294 for v in per_name {
295 entries.extend(v);
296 }
297 let word = |e: &Entry| &names[e.0 as usize][e.1 as usize..e.2 as usize];
298 // Ordinal breaks ties so the file is reproducible: two runs over the same input
299 // must be byte-identical, which an unstable sort only gives on a total order.
300 crate::par::install(|| {
301 entries.par_sort_unstable_by(|a, b| {
302 cmp_word(word(a), word(b)).then((a.0, a.3).cmp(&(b.0, b.3)))
303 })
304 });
305
306 let mut buf: Vec<u8> = Vec::with_capacity(NAME_HEADER_BYTES + 5 * entries.len());
307 buf.extend_from_slice(NAME_MAGIC);
308 buf.extend_from_slice(&NAME_VERSION.to_le_bytes());
309 buf.extend_from_slice(&(names.len() as u32).to_le_bytes());
310 buf.extend_from_slice(&(entries.len() as u32).to_le_bytes());
311 for e in &entries {
312 buf.extend_from_slice(&e.0.to_le_bytes());
313 }
314 for e in &entries {
315 buf.push(e.3);
316 }
317 out.write_all(&buf)?;
318 Ok(entries.len())
319}
320
321/// Write `poi_region.bin`: one tagged OSM boundary id per record ordinal, in
322/// the same Morton-sorted order as `poi_index.bin`. Same count-refused
323/// convention as the other side files: the reader joins by ordinal only when
324/// the counts agree.
325pub fn write_region<W: Write>(out: &mut W, region_ids: &[u64]) -> io::Result<()> {
326 out.write_all(REGION_MAGIC)?;
327 out.write_all(&REGION_VERSION.to_le_bytes())?;
328 out.write_all(&(region_ids.len() as u32).to_le_bytes())?;
329 for id in region_ids {
330 out.write_all(&id.to_le_bytes())?;
331 }
332 Ok(())
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 fn u32_at(bytes: &[u8], at: usize) -> u32 {
340 u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
341 }
342
343 #[test]
344 fn words_split_on_whitespace_only() {
345 let got: Vec<&[u8]> = words(b"Joe's Pizza\tBar").map(|(_, w)| w).collect();
346 assert_eq!(got, vec![&b"Joe's"[..], &b"Pizza"[..], &b"Bar"[..]]);
347 }
348
349 #[test]
350 fn word_indices_count_from_zero() {
351 let name = b"San Francisco Public Library";
352 assert_eq!(word_at(name, 0), Some(&b"San"[..]));
353 assert_eq!(word_at(name, 3), Some(&b"Library"[..]));
354 assert_eq!(word_at(name, 4), None);
355 }
356
357 /// Only ASCII folds. A Unicode-aware lowercase would disagree with the reader.
358 #[test]
359 fn comparison_folds_ascii_and_leaves_other_bytes_alone() {
360 assert_eq!(cmp_word(b"PIZZA", b"pizza"), Ordering::Equal);
361 assert_eq!(cmp_word(b"Cafe", b"cafz"), Ordering::Less);
362 // U+00C9 vs U+00E9: both pass through, so they order by raw byte.
363 assert_eq!(cmp_word("É".as_bytes(), "é".as_bytes()), Ordering::Less);
364 }
365
366 #[test]
367 fn a_shorter_word_sorts_before_a_longer_one_sharing_its_prefix() {
368 assert_eq!(cmp_word(b"pizz", b"pizza"), Ordering::Less);
369 }
370
371 #[test]
372 fn the_grid_is_anchored_at_the_records_minimum_corner() {
373 let coords = [(37_700_000, -122_400_000), (37_720_000, -122_380_000)];
374 let g = Grid::fit(&coords).expect("records exist");
375 assert_eq!(g.lat0_e7, 37_700_000);
376 assert_eq!(g.lon0_e7, -122_400_000);
377 assert_eq!(g.cell(37_700_000, -122_400_000), 0);
378 }
379
380 #[test]
381 fn an_empty_extract_has_no_grid() {
382 assert!(Grid::fit(&[]).is_none());
383 }
384
385 #[test]
386 fn the_spatial_csr_groups_every_ordinal_under_its_cell() {
387 // Two POIs in one cell (0.02deg apart is one cell over, so keep them closer)
388 // and a third far away.
389 let coords =
390 [(37_700_000, -122_400_000), (37_700_100, -122_400_100), (38_000_000, -122_000_000)];
391 let mut buf = Vec::new();
392 let cells = write_spatial(&mut buf, &coords).unwrap();
393 assert_eq!(cells, 2, "two populated cells");
394 assert_eq!(&buf[0..4], SPATIAL_MAGIC);
395 assert_eq!(u32_at(&buf, 8), 3, "record count");
396 assert_eq!(u32_at(&buf, 12), 2, "cell count");
397
398 let ids = SPATIAL_HEADER_BYTES;
399 let off = ids + 4 * cells;
400 let ords = off + 4 * (cells + 1);
401 assert!(u32_at(&buf, ids) < u32_at(&buf, ids + 4), "cell ids ascend");
402 assert_eq!(u32_at(&buf, off), 0);
403 assert_eq!(u32_at(&buf, off + 4), 2, "first cell holds two records");
404 assert_eq!(u32_at(&buf, off + 8), 3);
405 assert_eq!(u32_at(&buf, ords), 0);
406 assert_eq!(u32_at(&buf, ords + 4), 1);
407 assert_eq!(u32_at(&buf, ords + 8), 2);
408 assert_eq!(buf.len(), ords + 4 * coords.len());
409 }
410
411 #[test]
412 fn the_name_index_sorts_every_word_of_every_record() {
413 let names: Vec<&[u8]> = vec![b"Joe's Pizza", b"Pizza Hut"];
414 let mut buf = Vec::new();
415 let entries = write_name_index(&mut buf, &names).unwrap();
416 assert_eq!(entries, 4, "two words each");
417 assert_eq!(&buf[0..4], NAME_MAGIC);
418 assert_eq!(u32_at(&buf, 8), 2, "record count");
419 assert_eq!(u32_at(&buf, 12), 4, "entry count");
420
421 // Sorted: "hut", "joe's", "pizza"(#0 word 1), "pizza"(#1 word 0).
422 let ord = NAME_HEADER_BYTES;
423 let widx = ord + 4 * entries;
424 let got: Vec<(u32, u8)> =
425 (0..entries).map(|i| (u32_at(&buf, ord + 4 * i), buf[widx + i])).collect();
426 assert_eq!(got, vec![(1, 1), (0, 0), (0, 1), (1, 0)]);
427 }
428
429 /// Both words of a name resolve to the same record, which is what makes "pizza"
430 /// find "Joe's Pizza" without a scan.
431 #[test]
432 fn a_trailing_word_still_points_at_its_record() {
433 let names: Vec<&[u8]> = vec![b"Joe's Pizza"];
434 let mut buf = Vec::new();
435 let entries = write_name_index(&mut buf, &names).unwrap();
436 assert_eq!(entries, 2);
437 let widx = NAME_HEADER_BYTES + 4 * entries;
438 assert_eq!(u32_at(&buf, NAME_HEADER_BYTES), 0);
439 assert_eq!(buf[widx], 0, "\"joe's\" first");
440 assert_eq!(buf[widx + 1], 1, "then \"pizza\"");
441 }
442
443 #[test]
444 fn two_runs_over_the_same_input_are_byte_identical() {
445 let names: Vec<&[u8]> = vec![b"Cafe Roma", b"Roma Cafe", b"Cafe Roma"];
446 let coords = [(1_000, 2_000), (3_000, 4_000), (5_000, 6_000)];
447 let (mut a, mut b) = (Vec::new(), Vec::new());
448 write_name_index(&mut a, &names).unwrap();
449 write_name_index(&mut b, &names).unwrap();
450 assert_eq!(a, b);
451 let (mut c, mut d) = (Vec::new(), Vec::new());
452 write_spatial(&mut c, &coords).unwrap();
453 write_spatial(&mut d, &coords).unwrap();
454 assert_eq!(c, d);
455 }
456
457 #[test]
458 fn an_unnamed_record_contributes_no_entries() {
459 let names: Vec<&[u8]> = vec![b"", b" ", b"Real Name"];
460 let mut buf = Vec::new();
461 assert_eq!(write_name_index(&mut buf, &names).unwrap(), 2);
462 assert_eq!(u32_at(&buf, 8), 3, "record count still counts them");
463 }
464}