Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bundle_part3.rs
bundle_part3.rs428 lines · 18.9 KiBRaw
| 1 | impl Covered { |
| 2 | /// Record every metre of `line` as drawn. |
| 3 | pub fn add(&mut self, line: &[(i32, i32)]) { |
| 4 | self.add_tagged(line, 0); |
| 5 | } |
| 6 | |
| 7 | /// Record every metre of `line` as drawn by service `tag`. |
| 8 | pub fn add_tagged(&mut self, line: &[(i32, i32)], tag: u32) { |
| 9 | self.add_tagged_walked(&walk(line), tag); |
| 10 | } |
| 11 | |
| 12 | /// [`add`](Self::add) over samples already walked by [`walk`]. |
| 13 | pub fn add_walked(&mut self, walked: &[Walked]) { |
| 14 | self.add_tagged_walked(walked, 0); |
| 15 | } |
| 16 | |
| 17 | /// [`add_tagged`](Self::add_tagged) over samples already walked by [`walk`], so a caller |
| 18 | /// running several gates over one line walks it once and shares the result. |
| 19 | pub fn add_tagged_walked(&mut self, walked: &[Walked], tag: u32) { |
| 20 | let cells: Vec<Cell> = walked.iter().map(sample_cell).collect(); |
| 21 | self.add_tagged_walked_in(walked, &cells, tag); |
| 22 | } |
| 23 | |
| 24 | /// [`add_tagged_walked`](Self::add_tagged_walked) with each sample's [`sample_cell`] |
| 25 | /// already computed, parallel to `walked`. |
| 26 | pub fn add_tagged_walked_in(&mut self, walked: &[Walked], cells: &[Cell], tag: u32) { |
| 27 | debug_assert_eq!(walked.len(), cells.len()); |
| 28 | self.adds += 1; |
| 29 | let now = self.adds; |
| 30 | // A run of samples in one cell — about four per 40 m cell at 10 m spacing — needs one |
| 31 | // bucket probe, not four: after the first, the cell holds a sample of `tag` whichever |
| 32 | // way that probe went, so every later one would be dropped anyway. The same holds for |
| 33 | // any repeat of a cell within one add, which is why each shard may also skip its own |
| 34 | // consecutive repeats below. |
| 35 | let mut firsts: Vec<u32> = Vec::with_capacity(walked.len() / 3 + 1); |
| 36 | let mut prev: Option<Cell> = None; |
| 37 | for (k, &cell) in cells.iter().enumerate() { |
| 38 | if prev != Some(cell) { |
| 39 | firsts.push(k as u32); |
| 40 | prev = Some(cell); |
| 41 | } |
| 42 | } |
| 43 | if firsts.len() < 2048 { |
| 44 | for k in firsts { |
| 45 | let cell = cells[k as usize]; |
| 46 | insert(&mut self.cells[shard_of(cell)], cell, walked[k as usize], tag, now); |
| 47 | } |
| 48 | return; |
| 49 | } |
| 50 | // Counting sort by shard, stable, so each shard takes its samples in line order. |
| 51 | let mut starts = [0usize; COVER_SHARDS + 1]; |
| 52 | for &k in &firsts { |
| 53 | starts[shard_of(cells[k as usize]) + 1] += 1; |
| 54 | } |
| 55 | for i in 0..COVER_SHARDS { |
| 56 | starts[i + 1] += starts[i]; |
| 57 | } |
| 58 | let mut fill = starts; |
| 59 | let mut order = vec![0u32; firsts.len()]; |
| 60 | for &k in &firsts { |
| 61 | let s = shard_of(cells[k as usize]); |
| 62 | order[fill[s]] = k; |
| 63 | fill[s] += 1; |
| 64 | } |
| 65 | // A few thousand inserts per task: each fork wakes sleeping workers, and on a line of a |
| 66 | // few thousand cells waking all of them costs more than the inserts. |
| 67 | let tasks = (firsts.len() / 2048).clamp(1, COVER_SHARDS); |
| 68 | self.cells.par_iter_mut().enumerate().with_min_len(COVER_SHARDS.div_ceil(tasks)).for_each(|(s, map)| { |
| 69 | for &k in &order[starts[s]..starts[s + 1]] { |
| 70 | insert(map, cells[k as usize], walked[k as usize], tag, now); |
| 71 | } |
| 72 | }); |
| 73 | } |
| 74 | |
| 75 | /// The most distinct services already drawn over any one metre of `line`. |
| 76 | /// |
| 77 | /// The colour-scoped gates above stop a service being drawn twice, but they are deliberately |
| 78 | /// blind to *other* services: two lines sharing a track are two real services and both should |
| 79 | /// draw, fanned into lanes. That holds for a city. It does not hold for a planet, where one |
| 80 | /// physical alignment is republished by a city feed, the regional feed that contains it and a |
| 81 | /// national feed on top, each under its own `route_color` and often its own `route_type` — all |
| 82 | /// of which read as distinct services and each claim a lane. That is what turns one railway |
| 83 | /// into fifteen jagged parallel lines when you zoom in. |
| 84 | /// |
| 85 | /// So the rule is a ceiling rather than a ban: a few services over one track is real, fifteen |
| 86 | /// is a data artefact. Returns the worst point rather than an average, because a line that |
| 87 | /// joins a crowded trunk for part of its length is exactly the case worth suppressing. |
| 88 | /// |
| 89 | /// `limit` stops the walk as soon as any point reaches it. The answer above the ceiling is |
| 90 | /// never used, only compared against it, and this is called once per surviving line over a |
| 91 | /// structure holding every sample of every line already drawn. |
| 92 | pub fn crowd_reaches(&self, line: &[(i32, i32)], limit: usize) -> bool { |
| 93 | self.crowd_reaches_walked(&walk(line), limit) |
| 94 | } |
| 95 | |
| 96 | /// [`crowd_reaches`](Self::crowd_reaches) over samples already walked by [`walk`]. |
| 97 | pub fn crowd_reaches_walked(&self, walked: &[Walked], limit: usize) -> bool { |
| 98 | if limit == 0 { |
| 99 | return true; |
| 100 | } |
| 101 | let mut seen: Vec<u32> = Vec::new(); |
| 102 | for &(point, ux, uy) in walked { |
| 103 | seen.clear(); |
| 104 | self.tags_over(point, ux, uy, &mut seen, limit); |
| 105 | if seen.len() >= limit { |
| 106 | return true; |
| 107 | } |
| 108 | } |
| 109 | false |
| 110 | } |
| 111 | |
| 112 | /// The most distinct services already drawn over any one metre of `line`. |
| 113 | /// |
| 114 | /// Unbounded, for tests and for reporting. Prefer [`crowd_reaches`](Self::crowd_reaches) on |
| 115 | /// the build path, which stops as soon as the answer can no longer change the decision. |
| 116 | pub fn crowd(&self, line: &[(i32, i32)]) -> usize { |
| 117 | let mut worst = 0; |
| 118 | let mut seen: Vec<u32> = Vec::new(); |
| 119 | for &(point, ux, uy) in &walk(line) { |
| 120 | seen.clear(); |
| 121 | self.tags_over(point, ux, uy, &mut seen, usize::MAX); |
| 122 | worst = worst.max(seen.len()); |
| 123 | } |
| 124 | worst |
| 125 | } |
| 126 | |
| 127 | /// Every distinct service drawn within [`CORRIDOR_M`] of this point, running parallel to it. |
| 128 | /// |
| 129 | /// Stops once `limit` distinct services have been found, since no caller needs more. |
| 130 | fn tags_over(&self, point: (i32, i32), ux: f64, uy: f64, out: &mut Vec<u32>, limit: usize) { |
| 131 | self.tags_over_in(cell_of(point), point, ux, uy, out, limit); |
| 132 | } |
| 133 | |
| 134 | /// [`tags_over`](Self::tags_over) with `cell_of(point)` already known. |
| 135 | fn tags_over_in(&self, (cx, cy): Cell, point: (i32, i32), ux: f64, uy: f64, out: &mut Vec<u32>, limit: usize) { |
| 136 | for (dx, dy) in NEIGHBOURHOOD { |
| 137 | let Some(bucket) = self.bucket((cx + dx, cy + dy)) else { continue }; |
| 138 | for d in bucket.iter() { |
| 139 | if (ux * d.ux + uy * d.uy).abs() < COS_FOLD { |
| 140 | continue; |
| 141 | } |
| 142 | if distance_m(point, d.point) <= CORRIDOR_M { |
| 143 | let tag = d.tag; |
| 144 | if !out.contains(&tag) { |
| 145 | out.push(tag); |
| 146 | if out.len() >= limit { |
| 147 | return; |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Is every metre of `line` already drawn? |
| 156 | /// |
| 157 | /// Walked at [`SAMPLE_M`] rather than at the line's own vertices, whose spacing is a |
| 158 | /// feed's business and is sometimes hundreds of metres. |
| 159 | pub fn contains(&self, line: &[(i32, i32)]) -> bool { |
| 160 | self.covered_fraction(line) >= 1.0 |
| 161 | } |
| 162 | |
| 163 | /// How much of `line` is already drawn, from 0 to 1. A line too short to walk covers nothing, |
| 164 | /// so it reports 0 and is kept — matching what the all-or-nothing test used to do with it. |
| 165 | /// |
| 166 | /// The all-or-nothing [`contains`](Self::contains) is too strict for one real case: a route |
| 167 | /// published twice at slightly different *lengths*. A short-turn, or one feed's version |
| 168 | /// running two stops further than another's, shares 95% of its alignment with what is already |
| 169 | /// drawn, adds a little genuinely new track at one end, and is therefore kept **whole** — |
| 170 | /// duplicating the 95%. On the ground that draws the A line as two strands about a metre |
| 171 | /// apart, each fanned into its own corridor lane and tapered, so one line reads as two |
| 172 | /// diverging and reconverging. |
| 173 | /// |
| 174 | /// Subtracting the covered part instead is not the answer and was tried: it cut every route |
| 175 | /// into fragments and left holes where a piece fell below the length worth emitting. A |
| 176 | /// fraction keeps the whole-line rule and only moves where the threshold sits. |
| 177 | pub fn covered_fraction(&self, line: &[(i32, i32)]) -> f64 { |
| 178 | self.covered_fraction_walked(&walk(line)) |
| 179 | } |
| 180 | |
| 181 | /// [`covered_fraction`](Self::covered_fraction) over samples already walked by [`walk`]. |
| 182 | pub fn covered_fraction_walked(&self, walked: &[Walked]) -> f64 { |
| 183 | if walked.is_empty() { |
| 184 | return 0.0; |
| 185 | } |
| 186 | let drawn = walked.iter().filter(|&&(point, ux, uy)| self.covers(point, ux, uy)).count(); |
| 187 | drawn as f64 / walked.len() as f64 |
| 188 | } |
| 189 | |
| 190 | /// Is this point already drawn, by track running parallel to it? |
| 191 | /// |
| 192 | /// Returns on the first match, so visit order matters — see [`NEIGHBOURHOOD`], which is |
| 193 | /// ordered for exactly that reason. The buckets are unbounded: [`add`](Self::add) records |
| 194 | /// every sample of every line it draws, and a trunk alignment republished by a dozen feeds is |
| 195 | /// a dozen overlapping sample runs in the same cells. |
| 196 | fn covers(&self, point: (i32, i32), ux: f64, uy: f64) -> bool { |
| 197 | self.covers_in(cell_of(point), point, ux, uy) |
| 198 | } |
| 199 | |
| 200 | /// [`covers`](Self::covers) with `cell_of(point)` already known. |
| 201 | fn covers_in(&self, (cx, cy): Cell, point: (i32, i32), ux: f64, uy: f64) -> bool { |
| 202 | for (dx, dy) in NEIGHBOURHOOD { |
| 203 | let Some(bucket) = self.bucket((cx + dx, cy + dy)) else { continue }; |
| 204 | for d in bucket.iter() { |
| 205 | if (ux * d.ux + uy * d.uy).abs() < COS_FOLD { |
| 206 | continue; |
| 207 | } |
| 208 | if distance_m(point, d.point) <= CORRIDOR_M { |
| 209 | return true; |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | false |
| 214 | } |
| 215 | |
| 216 | /// Is this one walked sample, in `cell` (its [`sample_cell`]), already drawn? The |
| 217 | /// per-sample half of [`covered_fraction_walked`](Self::covered_fraction_walked), for a |
| 218 | /// caller that keeps the per-sample answers (see [`sample_cell`] for why that is sound). |
| 219 | pub fn covers_sample_in(&self, cell: Cell, sample: &Walked) -> bool { |
| 220 | self.covers_in(cell, sample.0, sample.1, sample.2) |
| 221 | } |
| 222 | |
| 223 | /// Do at least `limit` distinct services already run over this one sample, in `cell`? The |
| 224 | /// per-sample half of [`crowd_reaches_walked`](Self::crowd_reaches_walked): that is |
| 225 | /// exactly "any sample of the line answers true here". `scratch` is reused between calls. |
| 226 | pub fn crowd_reaches_in(&self, cell: Cell, sample: &Walked, limit: usize, scratch: &mut Vec<u32>) -> bool { |
| 227 | if limit == 0 { |
| 228 | return true; |
| 229 | } |
| 230 | scratch.clear(); |
| 231 | self.tags_over_in(cell, sample.0, sample.1, sample.2, scratch, limit); |
| 232 | scratch.len() >= limit |
| 233 | } |
| 234 | |
| 235 | fn bucket(&self, cell: Cell) -> Option<&Bucket> { |
| 236 | self.cells[shard_of(cell)].get(&cell) |
| 237 | } |
| 238 | |
| 239 | /// A mark to pass to [`changed_near`](Self::changed_near) later: how many adds this cover |
| 240 | /// has taken so far. |
| 241 | pub fn mark(&self) -> u32 { |
| 242 | self.adds |
| 243 | } |
| 244 | |
| 245 | /// Has any sample been added, since `mark` was taken, to a cell a query at `cell` reads? |
| 246 | /// |
| 247 | /// Each bucket records the last add that appended to it, so this is the nine bucket probes |
| 248 | /// a query makes anyway, without the scan. When it is `false`, every |
| 249 | /// [`covers_sample_in`](Self::covers_sample_in) / [`crowd_reaches_in`](Self::crowd_reaches_in) |
| 250 | /// answer at `cell` is exactly what it was at `mark`. |
| 251 | pub fn changed_near(&self, (cx, cy): Cell, mark: u32) -> bool { |
| 252 | if self.adds == mark { |
| 253 | return false; |
| 254 | } |
| 255 | NEIGHBOURHOOD |
| 256 | .iter() |
| 257 | .any(|(dx, dy)| self.bucket((cx + dx, cy + dy)).is_some_and(|b| b.added > mark)) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// A multiply-xorshift hasher for the cover's cell maps, probed nine times per query. |
| 262 | /// |
| 263 | /// SipHash's flood resistance buys nothing on our own grid coordinates, and nothing iterates |
| 264 | /// either map — every answer is a boolean or a count about one point — so the hasher cannot |
| 265 | /// leak an order into the output. |
| 266 | #[derive(Default, Clone, Copy)] |
| 267 | pub struct CellHasher(u64); |
| 268 | |
| 269 | impl std::hash::Hasher for CellHasher { |
| 270 | fn write(&mut self, bytes: &[u8]) { |
| 271 | for &b in bytes { |
| 272 | self.write_u64(u64::from(b)); |
| 273 | } |
| 274 | } |
| 275 | fn write_i32(&mut self, v: i32) { |
| 276 | self.write_u64(u64::from(v as u32)); |
| 277 | } |
| 278 | fn write_u32(&mut self, v: u32) { |
| 279 | self.write_u64(u64::from(v)); |
| 280 | } |
| 281 | fn write_u64(&mut self, v: u64) { |
| 282 | self.0 = (self.0.rotate_left(26) ^ v).wrapping_mul(0x9E37_79B9_7F4A_7C15); |
| 283 | } |
| 284 | fn finish(&self) -> u64 { |
| 285 | self.0 ^ (self.0 >> 29) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | /// `BuildHasher` for [`CellHasher`]. |
| 290 | pub type CellHash = std::hash::BuildHasherDefault<CellHasher>; |
| 291 | |
| 292 | /// Add one sample of `tag` to `cell`'s bucket in `map`, unless the cell already holds one. |
| 293 | fn insert(map: &mut std::collections::HashMap<Cell, Bucket, CellHash>, cell: Cell, (point, ux, uy): Walked, tag: u32, now: u32) { |
| 294 | let drawn = Drawn { point, ux, uy, tag }; |
| 295 | match map.entry(cell) { |
| 296 | std::collections::hash_map::Entry::Occupied(mut e) => { |
| 297 | let bucket = e.get_mut(); |
| 298 | // One representative per cell per service: a second sample of the same service in |
| 299 | // the same cell cannot change any `covers`/`tags_over` answer, and dropping it is |
| 300 | // what stops a heavily-republished trunk's buckets growing with the feed count. |
| 301 | if bucket.iter().any(|d| d.tag == tag) { |
| 302 | return; |
| 303 | } |
| 304 | bucket.rest.push(drawn); |
| 305 | bucket.added = now; |
| 306 | } |
| 307 | std::collections::hash_map::Entry::Vacant(e) => { |
| 308 | e.insert(Bucket { added: now, first: drawn, rest: Vec::new() }); |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// The grid cell a walked sample falls in. |
| 314 | /// |
| 315 | /// What makes per-sample answers reusable across [`Covered::add`]s: both |
| 316 | /// [`Covered::covers_sample`] and [`Covered::crowd_reaches_at`] read only the 3 x 3 block of |
| 317 | /// cells around this one, and adding a line only ever *appends* samples to the cells its own |
| 318 | /// samples fall in. So an answer computed before some adds is still exact after them unless |
| 319 | /// one of those adds touched that 3 x 3 block — and a `true` stays `true` regardless, since |
| 320 | /// both answers can only grow as samples are appended. |
| 321 | pub fn sample_cell(sample: &Walked) -> Cell { |
| 322 | cell_of(sample.0) |
| 323 | } |
| 324 | |
| 325 | /// Every candidate's samples, flat, with the range each candidate's own block occupies. |
| 326 | /// |
| 327 | /// Each candidate is resampled independently, so the walks go wide and are concatenated back |
| 328 | /// in candidate order — the blocks, and every sample within them, come out exactly as the |
| 329 | /// sequential walk left them, so nothing downstream can tell the difference. |
| 330 | fn sample_all(candidates: &[Candidate]) -> (Vec<Sample>, Vec<Range<usize>>) { |
| 331 | let per: Vec<Vec<Sample>> = candidates |
| 332 | .par_iter() |
| 333 | .map(|candidate| { |
| 334 | walk(candidate.points) |
| 335 | .into_iter() |
| 336 | .map(|(point, ux, uy)| Sample { route: candidate.route, point, ux, uy }) |
| 337 | .collect() |
| 338 | }) |
| 339 | .collect(); |
| 340 | let mut blocks = Vec::with_capacity(candidates.len()); |
| 341 | let mut start = 0usize; |
| 342 | for samples in &per { |
| 343 | blocks.push(start..start + samples.len()); |
| 344 | start += samples.len(); |
| 345 | } |
| 346 | // Concatenated wide too — ~9 GB of samples on a world set. `collect` keeps order. |
| 347 | let out: Vec<Sample> = per.into_par_iter().flatten_iter().collect(); |
| 348 | (out, blocks) |
| 349 | } |
| 350 | |
| 351 | /// A grid cell, `(x, y)` in [`CELL_M`] units. |
| 352 | pub type Cell = (i32, i32); |
| 353 | |
| 354 | /// The cell a point falls in. Square in metres rather than in degrees, so a cell near the |
| 355 | /// pole is not a sliver: longitude is scaled by the cosine of its own latitude. |
| 356 | fn cell_of(point: (i32, i32)) -> Cell { |
| 357 | let lat = point.0 as f64 * 1e-7; |
| 358 | let cos_lat = lat.to_radians().cos().max(1e-6); |
| 359 | let y = lat * 111_320.0 / CELL_M; |
| 360 | let x = point.1 as f64 * 1e-7 * 111_320.0 * cos_lat / CELL_M; |
| 361 | (x.floor() as i32, y.floor() as i32) |
| 362 | } |
| 363 | |
| 364 | /// A sorted flat `(cell, sample)` vector, as [`crate::index`]'s transfer grid is. |
| 365 | struct Grid { |
| 366 | entries: Vec<(Cell, u32)>, |
| 367 | } |
| 368 | |
| 369 | impl Grid { |
| 370 | fn build(samples: &[Sample]) -> Grid { |
| 371 | let mut entries: Vec<(Cell, u32)> = |
| 372 | samples.par_iter().enumerate().map(|(i, s)| (cell_of(s.point), i as u32)).collect(); |
| 373 | entries.par_sort_unstable(); |
| 374 | Grid { entries } |
| 375 | } |
| 376 | |
| 377 | /// The routes with a sample within [`CORRIDOR_M`] of `at` running parallel to it, |
| 378 | /// ascending and deduplicated. Always contains `at`'s own route. |
| 379 | /// |
| 380 | /// `seen` is a caller-owned scratch array of one slot per route, holding the `stamp` of |
| 381 | /// the sample a route was last accepted for. It replaces an `out.contains()` linear scan |
| 382 | /// that ran once per neighbouring sample: a 40 m cell holds ~4 samples per line at |
| 383 | /// [`SAMPLE_M`], so the nine-cell neighbourhood holds ~36 per route in the corridor, and |
| 384 | /// scanning `out` for each made the probe quadratic in *local route density*. On a |
| 385 | /// world-scale set that is the whole cost — dense metros carry the same trunk track |
| 386 | /// republished by every feed covering the city, so density there is far higher than the |
| 387 | /// feed count suggests, and the run time grows much faster than the input does. |
| 388 | /// |
| 389 | /// A route is stamped only when it is **accepted**, never when the angle or distance test |
| 390 | /// rejects it. That is what the `contains` check did — it tested membership of `out`, not |
| 391 | /// of everything examined — and a route rejected against one sample must stay eligible |
| 392 | /// against a nearer one in the same neighbourhood. |
| 393 | fn routes_near( |
| 394 | &self, |
| 395 | samples: &[Sample], |
| 396 | at: &Sample, |
| 397 | out: &mut Vec<u32>, |
| 398 | seen: &mut [u32], |
| 399 | stamp: u32, |
| 400 | ) { |
| 401 | out.clear(); |
| 402 | out.push(at.route); |
| 403 | seen[at.route as usize] = stamp; |
| 404 | let (cx, cy) = cell_of(at.point); |
| 405 | for dx in -1..=1 { |
| 406 | // The grid is sorted by `(x, y)`, so the three cells `(x, cy - 1..=cy + 1)` are one |
| 407 | // contiguous run of it, in exactly the order the three per-cell buckets were |
| 408 | // visited: two binary searches over the whole grid instead of six. |
| 409 | let x = cx + dx; |
| 410 | let lo = self.entries.partition_point(|(k, _)| *k < (x, cy - 1)); |
| 411 | let hi = lo + self.entries[lo..].partition_point(|(k, _)| *k <= (x, cy + 1)); |
| 412 | for &(_, i) in &self.entries[lo..hi] { |
| 413 | let other = &samples[i as usize]; |
| 414 | if seen[other.route as usize] == stamp { |
| 415 | continue; |
| 416 | } |
| 417 | if (at.ux * other.ux + at.uy * other.uy).abs() < COS_FOLD { |
| 418 | continue; |
| 419 | } |
| 420 | if distance_m(at.point, other.point) <= CORRIDOR_M { |
| 421 | seen[other.route as usize] = stamp; |
| 422 | out.push(other.route); |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | out.sort_unstable(); |
| 427 | } |
| 428 | } |