Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / nodeloc_part2.rs
nodeloc_part2.rs284 lines · 12.0 KiBRaw
| 1 | // The id-index switch and the planet-scale rank-select form. |
| 2 | // |
| 3 | // [`NodeLocations`] holds a [`NodeIds`], which is one of two id indexes chosen by how the ids |
| 4 | // arrived. A vector of needed ids ([`NodeLocations::new`]) builds the compressed [`IdIndex`], whose |
| 5 | // cost follows the id *count* -- right for the sparse needed set of a sub-continent extract. An |
| 6 | // ascending id *stream* ([`NodeLocations::from_sorted`], which the planet path feeds from a bitset |
| 7 | // over the id space) builds a [`RankIndex`], whose cost follows the id *space* and whose `find` is |
| 8 | // `O(1)`. Both answer `find` identically for the same id set -- a position is the count of ids below |
| 9 | // the queried one either way -- so the coordinate array is byte-identical whichever backs it. |
| 10 | |
| 11 | /// Which id index backs a [`NodeLocations`]. See the module comment for the choice. |
| 12 | enum NodeIds { |
| 13 | /// `O(count)` bytes: the compressed block-and-varint index. Built by [`NodeLocations::new`]. |
| 14 | Compressed(IdIndex), |
| 15 | /// `O(id space)` bytes with `O(1)` lookup: the rank-select bitset. Built by |
| 16 | /// [`NodeLocations::from_sorted`]. |
| 17 | Rank(RankIndex), |
| 18 | } |
| 19 | |
| 20 | impl Default for NodeIds { |
| 21 | /// An empty compressed index, so [`std::mem::take`] in [`resolve_nodes`] has something to leave |
| 22 | /// behind. Empty either way, so the variant does not matter. |
| 23 | fn default() -> Self { |
| 24 | NodeIds::Compressed(IdIndex::default()) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl NodeIds { |
| 29 | /// From a sorted, unique id vector: the compressed index, for a needed set sparse in the id |
| 30 | /// space. |
| 31 | fn build(ids: &[i64]) -> NodeIds { |
| 32 | NodeIds::Compressed(IdIndex::build(ids)) |
| 33 | } |
| 34 | |
| 35 | /// From an ascending, unique id stream: the rank-select bitset, for a needed set that fills most |
| 36 | /// of the id space (a planet extract). `len` is unused here -- the bitset sizes itself from the |
| 37 | /// largest id the stream yields -- but kept to match [`IdIndex::build_sorted`]'s shape. |
| 38 | fn build_sorted(ids: impl Iterator<Item = i64>, len: usize) -> NodeIds { |
| 39 | NodeIds::Rank(RankIndex::build_sorted(ids, len)) |
| 40 | } |
| 41 | |
| 42 | /// From an already-populated bitset over the id space: the rank-select index without a second |
| 43 | /// words array. See [`RankIndex::from_words`] for why the ownership moves rather than streams. |
| 44 | fn from_words(words: Vec<u64>, len: usize) -> NodeIds { |
| 45 | NodeIds::Rank(RankIndex::from_words(words, len)) |
| 46 | } |
| 47 | |
| 48 | fn len(&self) -> usize { |
| 49 | match self { |
| 50 | NodeIds::Compressed(index) => index.len(), |
| 51 | NodeIds::Rank(index) => index.len(), |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn find(&self, id: i64) -> Option<u64> { |
| 56 | match self { |
| 57 | NodeIds::Compressed(index) => index.find(id), |
| 58 | NodeIds::Rank(index) => index.find(id), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn cursor(&self) -> NodeCursor<'_> { |
| 63 | match self { |
| 64 | NodeIds::Compressed(index) => NodeCursor::Walk(index.cursor()), |
| 65 | NodeIds::Rank(index) => NodeCursor::Direct(index), |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// A cursor over whichever index backs the table. The compressed side walks (a binary search then a |
| 71 | /// forward scan); the rank side has an `O(1)` `find`, so its "cursor" is just the index and query |
| 72 | /// order is irrelevant to it. |
| 73 | enum NodeCursor<'a> { |
| 74 | Walk(Cursor<'a>), |
| 75 | Direct(&'a RankIndex), |
| 76 | } |
| 77 | |
| 78 | impl NodeCursor<'_> { |
| 79 | fn find(&mut self, id: i64) -> Option<u64> { |
| 80 | match self { |
| 81 | NodeCursor::Walk(cursor) => cursor.find(id), |
| 82 | NodeCursor::Direct(index) => index.find(id), |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Words per rank superblock. A superblock stores one prefix-sum `u64`, so this is the overhead/scan |
| 88 | /// trade: 8 words is one `u64` per 512 bits -- ~1.6% over the bitset -- and a `find` pops at most 8 |
| 89 | /// words after the superblock lookup. |
| 90 | const RANK_WORDS: usize = 8; |
| 91 | |
| 92 | /// A sorted, unique id set as a bitset over the id space plus a rank directory. |
| 93 | /// |
| 94 | /// **This, not [`IdIndex`], for a planet extract.** Its size follows the largest id, not the count, |
| 95 | /// so where the needed set is most of a bounded id space it is a few GB against the compressed |
| 96 | /// index's ~12.9 GB -- and `find` is a directory lookup plus a bounded popcount rather than a binary |
| 97 | /// search over a base array that no longer fits in cache. |
| 98 | /// |
| 99 | /// `find(id)` returns the id's rank: the number of set bits below it, which is exactly the position |
| 100 | /// [`IdIndex::find`] returns for the same sorted set. That equality is what lets the two indexes back |
| 101 | /// the same coordinate array interchangeably; `the_two_indexes_answer_find_identically` holds them to |
| 102 | /// it. |
| 103 | #[derive(Default)] |
| 104 | struct RankIndex { |
| 105 | /// Bit `i` is set iff id `i` is in the set. |
| 106 | words: Vec<u64>, |
| 107 | /// `ranks[b]` is the number of set bits before superblock `b` (word `b * RANK_WORDS`). A prefix |
| 108 | /// sum, so a rank is this plus the popcount of the words between the superblock start and the |
| 109 | /// query word. |
| 110 | ranks: Vec<u64>, |
| 111 | len: usize, |
| 112 | } |
| 113 | |
| 114 | impl RankIndex { |
| 115 | /// Build from an ascending, unique, non-negative id stream. |
| 116 | /// |
| 117 | /// The bitset grows as ids arrive -- the stream is ascending, so the largest id is the last, and |
| 118 | /// growth is amortised by the vector's own doubling. The rank directory is filled in one pass |
| 119 | /// once every bit is set. |
| 120 | fn build_sorted(ids: impl Iterator<Item = i64>, _len: usize) -> RankIndex { |
| 121 | let mut words: Vec<u64> = Vec::new(); |
| 122 | let mut count = 0usize; |
| 123 | for id in ids { |
| 124 | // The stream's precondition is ascending, unique and non-negative; a negative id has no |
| 125 | // bit and is dropped rather than allowed to index a wild word. |
| 126 | if id < 0 { |
| 127 | continue; |
| 128 | } |
| 129 | let bit = id as u64; |
| 130 | let w = (bit / 64) as usize; |
| 131 | if w >= words.len() { |
| 132 | words.resize(w + 1, 0); |
| 133 | } |
| 134 | words[w] |= 1u64 << (bit % 64); |
| 135 | count += 1; |
| 136 | } |
| 137 | RankIndex::from_words(words, count) |
| 138 | } |
| 139 | |
| 140 | /// Build from an already-populated bitset over the id space: bit `i` set iff id `i` is in the |
| 141 | /// set. Takes ownership, so no second words array is ever allocated. |
| 142 | /// |
| 143 | /// **This is the planet path's memory argument.** The caller collected the needed ids as one |
| 144 | /// bit per id ([`crate::extract`]'s `NeededBits`); streaming those bits back out into ids just |
| 145 | /// to re-set them here would hold the collector's words and this index's words at once -- |
| 146 | /// ~1.5 GB twice. Moving the words across keeps the peak at one bitset plus the rank |
| 147 | /// directory (`words.len() / 8` u64s, ~1.6% over the bitset). |
| 148 | /// |
| 149 | /// `len` is the number of set bits (the distinct-id count), which the caller tracked as it |
| 150 | /// set them. Trailing zero words are trimmed: the collector sizes to its maximum *ref*, which |
| 151 | /// may sit past the maximum *set* id by less than a word. |
| 152 | pub(crate) fn from_words(mut words: Vec<u64>, len: usize) -> RankIndex { |
| 153 | while words.last() == Some(&0) { |
| 154 | words.pop(); |
| 155 | } |
| 156 | let mut ranks: Vec<u64> = Vec::with_capacity(words.len() / RANK_WORDS + 1); |
| 157 | let mut running = 0u64; |
| 158 | for (i, word) in words.iter().enumerate() { |
| 159 | if i % RANK_WORDS == 0 { |
| 160 | ranks.push(running); |
| 161 | } |
| 162 | running += word.count_ones() as u64; |
| 163 | } |
| 164 | debug_assert_eq!( |
| 165 | running, len as u64, |
| 166 | "the rank directory counted a different number of ids than the caller set", |
| 167 | ); |
| 168 | RankIndex { words, ranks, len: running as usize } |
| 169 | } |
| 170 | |
| 171 | fn len(&self) -> usize { |
| 172 | self.len |
| 173 | } |
| 174 | |
| 175 | /// The position of `id` -- the count of set bits below it -- or `None` if it is not in the set. |
| 176 | fn find(&self, id: i64) -> Option<u64> { |
| 177 | if id < 0 { |
| 178 | return None; |
| 179 | } |
| 180 | let bit = id as u64; |
| 181 | let w = (bit / 64) as usize; |
| 182 | if w >= self.words.len() { |
| 183 | return None; |
| 184 | } |
| 185 | let b = (bit % 64) as u32; |
| 186 | let word = self.words[w]; |
| 187 | if word & (1u64 << b) == 0 { |
| 188 | return None; |
| 189 | } |
| 190 | let superblock = w / RANK_WORDS; |
| 191 | let mut rank = self.ranks[superblock]; |
| 192 | for &full in &self.words[superblock * RANK_WORDS..w] { |
| 193 | rank += full.count_ones() as u64; |
| 194 | } |
| 195 | // Bits strictly below `b` in the query word. Zero when `b` is zero, which `1 << 0 - 1` gives. |
| 196 | rank += (word & ((1u64 << b) - 1)).count_ones() as u64; |
| 197 | Some(rank) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | #[cfg(test)] |
| 202 | mod rank_tests { |
| 203 | use super::*; |
| 204 | |
| 205 | /// **The equality the whole switch rests on.** The rank index and the compressed index must |
| 206 | /// answer `find` identically for the same sorted set -- present ids to the same position, absent |
| 207 | /// ids to `None` -- or the planet path would write coordinates at different offsets than the |
| 208 | /// sub-continent one and the two would not be interchangeable behind [`NodeLocations`]. |
| 209 | #[test] |
| 210 | fn the_two_indexes_answer_find_identically() { |
| 211 | let mut state = 0x1234_5678_9abc_def0u64; |
| 212 | let mut next = || { |
| 213 | state ^= state << 13; |
| 214 | state ^= state >> 7; |
| 215 | state ^= state << 17; |
| 216 | state |
| 217 | }; |
| 218 | // A mix of tight runs and large gaps, spanning many superblocks, with ids past `u32::MAX`. |
| 219 | let mut ids: Vec<i64> = Vec::new(); |
| 220 | let mut id = 1i64; |
| 221 | for i in 0..6_000 { |
| 222 | id += if i % 5 == 0 { (next() % 5_000) as i64 + 1 } else { (next() % 4) as i64 + 1 }; |
| 223 | ids.push(id); |
| 224 | } |
| 225 | ids.push(u32::MAX as i64 + 1); |
| 226 | ids.push(u32::MAX as i64 + 65); |
| 227 | ids.sort_unstable(); |
| 228 | ids.dedup(); |
| 229 | |
| 230 | let compressed = IdIndex::build(&ids); |
| 231 | let rank = RankIndex::build_sorted(ids.iter().copied(), ids.len()); |
| 232 | assert_eq!(rank.len(), compressed.len(), "the two indexes disagree on the count"); |
| 233 | |
| 234 | for &id in &ids { |
| 235 | assert_eq!(rank.find(id), compressed.find(id), "present id {id}"); |
| 236 | } |
| 237 | // Absent ids just below and just above each present one, plus the ends of the space. |
| 238 | for &id in &ids { |
| 239 | for probe in [id - 1, id + 1] { |
| 240 | assert_eq!(rank.find(probe), compressed.find(probe), "probe {probe}"); |
| 241 | } |
| 242 | } |
| 243 | for probe in [i64::MIN, -1, 0, *ids.last().unwrap() + 1_000_000, i64::MAX] { |
| 244 | assert_eq!(rank.find(probe), compressed.find(probe), "outside {probe}"); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// The rank index is what `from_sorted` builds, so a `NodeLocations` over an ascending stream |
| 249 | /// must resolve coordinates exactly as one built from the same ids as a vector does. |
| 250 | #[test] |
| 251 | fn from_sorted_and_new_resolve_the_same_coordinates() { |
| 252 | let ids = vec![5i64, 9, 64, 65, 4_000, 4_001, 300_000]; |
| 253 | let mut streamed = |
| 254 | NodeLocations::from_sorted(ids.iter().copied(), ids.len()).expect("stream"); |
| 255 | let mut vectored = NodeLocations::new(ids.clone()).expect("vector"); |
| 256 | assert_eq!(streamed.len(), vectored.len()); |
| 257 | for &id in &ids { |
| 258 | // Fill both at the id's own position and read it straight back; the positions must match |
| 259 | // or the two tables are not interchangeable. |
| 260 | let a = streamed.index_of(id).expect("present in stream") as usize; |
| 261 | let b = vectored.index_of(id).expect("present in vector") as usize; |
| 262 | assert_eq!(a, b, "id {id} sits at a different position in the two indexes"); |
| 263 | streamed.locs.set(a, id as i32, -(id as i32)); |
| 264 | vectored.locs.set(b, id as i32, -(id as i32)); |
| 265 | assert_eq!(streamed.get(id), vectored.get(id), "id {id}"); |
| 266 | } |
| 267 | assert!(streamed.get(123).is_none(), "an id never in the set must not resolve"); |
| 268 | } |
| 269 | |
| 270 | /// An empty stream and a single-id one, where the superblock arithmetic is easiest to get wrong. |
| 271 | #[test] |
| 272 | fn an_empty_or_single_id_rank_index_is_not_a_special_case() { |
| 273 | let empty = RankIndex::build_sorted(std::iter::empty(), 0); |
| 274 | assert_eq!(empty.len(), 0); |
| 275 | assert_eq!(empty.find(0), None); |
| 276 | assert_eq!(empty.find(42), None); |
| 277 | |
| 278 | let one = RankIndex::build_sorted(std::iter::once(42i64), 1); |
| 279 | assert_eq!(one.len(), 1); |
| 280 | assert_eq!(one.find(42), Some(0)); |
| 281 | assert_eq!(one.find(41), None); |
| 282 | assert_eq!(one.find(43), None); |
| 283 | } |
| 284 | } |