Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bundle_s1.rs
bundle_s1.rs319 lines · 14.8 KiBRaw
| 1 | /// [`assign`], ticking the gapless timer through the corridor stages — one |
| 2 | /// switch per stage (`corridor-probe`, `corridor-spans`, `corridor-order`, |
| 3 | /// `corridor-cut`), never one entry per sample. `None` skips the ticks, which |
| 4 | /// is what [`assign`] and the unit tests drive. |
| 5 | pub fn assign_with_timer( |
| 6 | candidates: &[Candidate], |
| 7 | mut timer: Option<&mut PhaseTimer>, |
| 8 | ) -> Vec<Vec<Span>> { |
| 9 | if candidates.is_empty() { |
| 10 | return Vec::new(); |
| 11 | } |
| 12 | // One switch per corridor stage, matching the four stderr meters below. |
| 13 | // The timer ticks here on the orchestrating thread only; the worker |
| 14 | // threads inside never touch it. |
| 15 | tick(&mut timer, "corridor-probe"); |
| 16 | let route_count = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0); |
| 17 | let (samples, blocks) = sample_all(candidates); |
| 18 | let grid = Grid::build(&samples); |
| 19 | |
| 20 | // Local membership per sample, interned: distinct sets are few even on a world feed set, |
| 21 | // and holding one `Vec<u32>` per sample is what would not fit. |
| 22 | let mut sets: Vec<Vec<u32>> = Vec::new(); |
| 23 | let mut set_ids: BTreeMap<Vec<u32>, u32> = BTreeMap::new(); |
| 24 | let mut per_sample: Vec<u32> = Vec::with_capacity(samples.len()); |
| 25 | |
| 26 | // The probe is the whole cost of a large run — one per 10 m of every line, 287 million of |
| 27 | // them on a world feed set — and it ran on one core for the better part of an hour. |
| 28 | // |
| 29 | // It splits in two. Finding which routes are near a sample is a pure read of the grid, so |
| 30 | // that part goes wide: the samples are cut into one contiguous range per core and each |
| 31 | // thread writes its answers into its own flat buffer. Interning those answers into set ids |
| 32 | // cannot go wide, because an id is assigned on first sight and the ids have to come out in |
| 33 | // sample order or every downstream lane moves. So the threads hand back their buffers in |
| 34 | // range order and the interning walks them sequentially — cheap, since it is `BTreeMap` |
| 35 | // lookups over an answer already computed. |
| 36 | // |
| 37 | // Flat `(values, ends)` buffers rather than `Vec<Vec<u32>>`: 287 million heap allocations |
| 38 | // is its own kind of slow, and the whole point of interning is not to hold that many |
| 39 | // vectors at once. |
| 40 | let threads = crate::par::threads(); |
| 41 | // Fixed-size ranges claimed first-come, not one range per thread: sample density is wildly |
| 42 | // uneven (a European trunk holds dozens of routes per cell, a desert line one), and with |
| 43 | // equal shares the thread that drew the dense ranges finished long after the rest. |
| 44 | const PROBE_RANGE: usize = 1 << 18; |
| 45 | let ranges = samples.len().div_ceil(PROBE_RANGE); |
| 46 | let next_range = AtomicUsize::new(0); |
| 47 | let probed = AtomicUsize::new(0); |
| 48 | // Per range: its samples as local set ids, plus its distinct sets in the order it first saw |
| 49 | // them, flat (`values`, `ends`). |
| 50 | let parts: Mutex<Vec<ProbePart>> = Mutex::new(Vec::new()); |
| 51 | { |
| 52 | let grid = &grid; |
| 53 | let samples = &samples; |
| 54 | let parts = &parts; |
| 55 | let probed = &probed; |
| 56 | let next_range = &next_range; |
| 57 | let total = samples.len(); |
| 58 | std::thread::scope(|scope| { |
| 59 | for _ in 0..threads.min(ranges) { |
| 60 | scope.spawn(move || { |
| 61 | // Per thread, so the stamp trick in `routes_near` needs no sharing: a |
| 62 | // stamp only has to be unique against this thread's own array. |
| 63 | let mut seen: Vec<u32> = vec![0; route_count]; |
| 64 | let mut stamp: u32 = 0; |
| 65 | let mut near: Vec<u32> = Vec::new(); |
| 66 | let mut done: Vec<ProbePart> = Vec::new(); |
| 67 | loop { |
| 68 | let r = next_range.fetch_add(1, AtomicOrdering::Relaxed); |
| 69 | if r >= ranges { |
| 70 | break; |
| 71 | } |
| 72 | let (lo, hi) = (r * PROBE_RANGE, ((r + 1) * PROBE_RANGE).min(total)); |
| 73 | // Interned locally, in first-seen order within this range; see the |
| 74 | // merge below for why that composes into the global first-seen ids |
| 75 | // exactly. |
| 76 | let mut local: std::collections::HashMap<Vec<u32>, u32> = |
| 77 | std::collections::HashMap::new(); |
| 78 | let mut ids: Vec<u32> = Vec::with_capacity(hi - lo); |
| 79 | let mut values: Vec<u32> = Vec::new(); |
| 80 | let mut ends: Vec<u32> = Vec::new(); |
| 81 | for sample in &samples[lo..hi] { |
| 82 | stamp += 1; |
| 83 | grid.routes_near(samples, sample, &mut near, &mut seen, stamp); |
| 84 | let id = match local.get(near.as_slice()) { |
| 85 | Some(&id) => id, |
| 86 | None => { |
| 87 | let id = ends.len() as u32; |
| 88 | values.extend_from_slice(&near); |
| 89 | ends.push(values.len() as u32); |
| 90 | local.insert(near.clone(), id); |
| 91 | id |
| 92 | } |
| 93 | }; |
| 94 | ids.push(id); |
| 95 | } |
| 96 | done.push((r, ids, values, ends)); |
| 97 | let n = probed.fetch_add(hi - lo, AtomicOrdering::Relaxed) + (hi - lo); |
| 98 | eprint!( |
| 99 | "\r{:<28} [{:>3}%] {total} sample(s)", |
| 100 | "Corridor probe", |
| 101 | (n * 100 / total.max(1)).min(100) |
| 102 | ); |
| 103 | } |
| 104 | parts.lock().expect("probe pool").extend(done); |
| 105 | }); |
| 106 | } |
| 107 | }); |
| 108 | } |
| 109 | eprintln!("\r{:<28} [100%] {} sample(s)", "Corridor probe", samples.len()); |
| 110 | // The runs cutting below is spans work, not probe work. |
| 111 | tick(&mut timer, "corridor-spans"); |
| 112 | |
| 113 | // Back in sample order, then each range's local ids mapped onto global ones. The global id |
| 114 | // of a set is its rank in first-seen order over the whole sample sequence. A set first |
| 115 | // occurs globally in the earliest range holding it, at that range's own first occurrence of |
| 116 | // it, so walking the ranges in order and each range's distinct sets in its local first-seen |
| 117 | // order meets every set's first global occurrence in global order — the ids come out exactly |
| 118 | // as the sample-by-sample interning assigned them, at one map lookup per distinct set per |
| 119 | // range instead of one per sample (287 M on a world set, ~50 s on one core). |
| 120 | let mut parts = parts.into_inner().expect("probe pool"); |
| 121 | parts.sort_unstable_by_key(|(t, _, _, _)| *t); |
| 122 | let mut remaps: Vec<Vec<u32>> = Vec::with_capacity(parts.len()); |
| 123 | for (_, _, values, ends) in &parts { |
| 124 | let mut remap = Vec::with_capacity(ends.len()); |
| 125 | let mut start = 0usize; |
| 126 | for &end in ends { |
| 127 | let near = &values[start..end as usize]; |
| 128 | start = end as usize; |
| 129 | let id = match set_ids.get(near) { |
| 130 | Some(id) => *id, |
| 131 | None => { |
| 132 | let id = sets.len() as u32; |
| 133 | sets.push(near.to_vec()); |
| 134 | set_ids.insert(near.to_vec(), id); |
| 135 | id |
| 136 | } |
| 137 | }; |
| 138 | remap.push(id); |
| 139 | } |
| 140 | remaps.push(remap); |
| 141 | } |
| 142 | let mapped: Vec<Vec<u32>> = parts |
| 143 | .par_iter() |
| 144 | .zip(remaps.par_iter()) |
| 145 | .map(|((_, ids, _, _), remap)| ids.iter().map(|&l| remap[l as usize]).collect()) |
| 146 | .collect(); |
| 147 | for ids in mapped { |
| 148 | per_sample.extend_from_slice(&ids); |
| 149 | } |
| 150 | drop(parts); |
| 151 | |
| 152 | // Distance along each candidate, for its own geometry and for its probes. `resample` |
| 153 | // walks *along* the polyline, so probe `k` is exactly `k * SAMPLE_M` along it and the |
| 154 | // last one is its end. Summing the chords between probes instead would fall short of |
| 155 | // that wherever the alignment curves, and the drift accumulates over a route's length |
| 156 | // until the last run is cut short of the line's own end. |
| 157 | let own_cum: Vec<Vec<f64>> = candidates.par_iter().map(|c| cumulative(c.points)).collect(); |
| 158 | let probe_cum: Vec<Vec<f64>> = blocks |
| 159 | .par_iter() |
| 160 | .zip(own_cum.par_iter()) |
| 161 | .map(|(block, own)| { |
| 162 | let total = own.last().copied().unwrap_or(0.0); |
| 163 | let count = block.len(); |
| 164 | (0..count) |
| 165 | .map(|k| if k + 1 == count { total } else { (k as f64 * SAMPLE_M).min(total) }) |
| 166 | .collect() |
| 167 | }) |
| 168 | .collect(); |
| 169 | |
| 170 | let runs: Vec<Vec<Run>> = blocks |
| 171 | .par_iter() |
| 172 | .zip(probe_cum.par_iter()) |
| 173 | .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum)) |
| 174 | .collect(); |
| 175 | |
| 176 | let mut named: Vec<Option<(u32, &str)>> = vec![None; route_count]; |
| 177 | for candidate in candidates { |
| 178 | named[candidate.route as usize].get_or_insert((candidate.color, candidate.name)); |
| 179 | } |
| 180 | |
| 181 | // Named too: on a large set the work after the probe loop is still minutes, and without a |
| 182 | // line here the run goes silent again the moment the bar reaches 100%. |
| 183 | eprintln!("{:<28} {} candidate(s)", "Corridor spans", candidates.len()); |
| 184 | tick(&mut timer, "corridor-order"); |
| 185 | let corridors = corridors_of(candidates, &sets, &runs, &named, &own_cum, &probe_cum); |
| 186 | |
| 187 | if std::env::var_os("TRANSIT_BUNDLE_DEBUG").is_some() { |
| 188 | for (set, corridor) in &corridors { |
| 189 | let members = &sets[*set as usize]; |
| 190 | eprintln!( |
| 191 | "corridor of {} over {} colour(s): {}", |
| 192 | members.len(), |
| 193 | corridor.colours.len(), |
| 194 | members |
| 195 | .iter() |
| 196 | .map(|&m| { |
| 197 | let (colour, name) = named[m as usize].unwrap_or((0, "")); |
| 198 | format!("{name}/{colour:06X}") |
| 199 | }) |
| 200 | .collect::<Vec<String>>() |
| 201 | .join(" "), |
| 202 | ); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // The last phase, and per candidate independent: each one cuts its own runs against |
| 207 | // corridors it only reads. Left sequential it was the tail that made a world set look |
| 208 | // hung again after the corridor bar hit 100%. |
| 209 | // |
| 210 | // Handed out one candidate at a time rather than in equal contiguous ranges, because the |
| 211 | // cost per candidate is wildly uneven — a transcontinental line carries orders of magnitude |
| 212 | // more runs than a tram loop. Splitting the range evenly gave whichever thread drew the |
| 213 | // long-distance rail all the work and left the rest idle: a world set sat at 98% on one |
| 214 | // core for ten minutes with sixty-three threads finished. Sample probes are uniform enough |
| 215 | // for a range split; candidates are not. |
| 216 | // The cut below is its own stage: close the order subphase first. |
| 217 | tick(&mut timer, "corridor-cut"); |
| 218 | let total = candidates.len(); |
| 219 | // Largest-first dispatch (longest-processing-time scheduling): hand out the heaviest |
| 220 | // candidates first so the one transcontinental line overlaps with all the small work |
| 221 | // instead of being picked last and grinding alone on one core at the end (the 99% |
| 222 | // straggler). Cost is proxied by run count -- the same "orders of magnitude more runs" |
| 223 | // the note above names. Output is unaffected: each result carries its candidate index and |
| 224 | // the parts are re-sorted by it below, so dispatch order never reaches the archive. |
| 225 | let order: Vec<usize> = { |
| 226 | let mut o: Vec<usize> = (0..total).collect(); |
| 227 | o.sort_unstable_by_key(|&i| std::cmp::Reverse(runs[i].len())); |
| 228 | o |
| 229 | }; |
| 230 | // On the run's own pool rather than on scoped threads, so the one transcontinental line |
| 231 | // that used to grind alone at the end can split its own placements across the idle |
| 232 | // workers (see `spans_of`). One candidate per task, so dispatch stays first-come in the |
| 233 | // largest-first order above. |
| 234 | let cut_done = AtomicUsize::new(0); |
| 235 | let mut cut_parts: Vec<(usize, Vec<Span>)> = order |
| 236 | .par_iter() |
| 237 | .with_max_len(1) |
| 238 | .map(|&at| { |
| 239 | let spans = spans_of( |
| 240 | &candidates[at], |
| 241 | &runs[at], |
| 242 | &samples[blocks[at].clone()], |
| 243 | &probe_cum[at], |
| 244 | &own_cum[at], |
| 245 | &corridors, |
| 246 | ); |
| 247 | let n = cut_done.fetch_add(1, AtomicOrdering::Relaxed) + 1; |
| 248 | if n % 64 == 0 { |
| 249 | eprint!( |
| 250 | "\r{:<28} [{:>3}%] {total} line(s)", |
| 251 | "Corridor cut", |
| 252 | n * 100 / total.max(1) |
| 253 | ); |
| 254 | } |
| 255 | (at, spans) |
| 256 | }) |
| 257 | .collect(); |
| 258 | eprintln!("\r{:<28} [100%] {total} line(s)", "Corridor cut"); |
| 259 | cut_parts.sort_unstable_by_key(|(at, _)| *at); |
| 260 | cut_parts.into_iter().map(|(_, spans)| spans).collect() |
| 261 | } |
| 262 | |
| 263 | /// One gapless tick, skipped when the caller passed `None`. |
| 264 | /// |
| 265 | /// The timer lives on the orchestrating thread only, and every call site is |
| 266 | /// sequential code between the parallel loops, so worker threads never touch |
| 267 | /// it — the coarse loop/pass boundaries are the ticks. |
| 268 | fn tick(timer: &mut Option<&mut PhaseTimer>, name: &str) { |
| 269 | if let Some(t) = timer { |
| 270 | t.switch(name); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /// A maximal stretch of one candidate's samples holding the same membership, as inclusive |
| 275 | /// indices into that candidate's own block of samples. |
| 276 | struct Run { |
| 277 | from: usize, |
| 278 | to: usize, |
| 279 | set: u32, |
| 280 | } |
| 281 | |
| 282 | /// A shared corridor: the geometry every member of it draws, and the lane order. |
| 283 | struct Corridor { |
| 284 | /// One member's polyline, folded into the canonical direction, which the whole corridor |
| 285 | /// draws slices of. Owned rather than borrowed because the fold may reverse it. |
| 286 | points: Vec<(i32, i32)>, |
| 287 | cum: Vec<f64>, |
| 288 | /// The corridor's distinct colours, ordered across it: the first is the left-hand side of |
| 289 | /// the reference's direction of travel, which is the side [`Span::ordinal`] zero draws on. |
| 290 | colours: Vec<u32>, |
| 291 | /// Bounds over runs of [`SEG_BLOCK`] consecutive segments of `points`, so [`nearest`] can |
| 292 | /// skip the ones that cannot hold the answer. Derived from `points`. |
| 293 | blocks: Vec<SegBlock>, |
| 294 | } |
| 295 | |
| 296 | impl Corridor { |
| 297 | fn new(points: Vec<(i32, i32)>, cum: Vec<f64>, colours: Vec<u32>) -> Corridor { |
| 298 | let blocks = seg_blocks(&points); |
| 299 | Corridor { points, cum, colours, blocks } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// Cut a candidate's samples into runs of constant membership, then smooth away the ones too |
| 304 | /// short to be a corridor. |
| 305 | fn cut_runs(per_sample: &[u32], cum: &[f64]) -> Vec<Run> { |
| 306 | let Some(&first) = per_sample.first() else { return Vec::new() }; |
| 307 | let mut runs = vec![Run { from: 0, to: 0, set: first }]; |
| 308 | for (at, &set) in per_sample.iter().enumerate().skip(1) { |
| 309 | let last = runs.last_mut().expect("seeded above"); |
| 310 | if last.set == set { |
| 311 | last.to = at; |
| 312 | } else { |
| 313 | runs.push(Run { from: at, to: at, set }); |
| 314 | } |
| 315 | } |
| 316 | smooth(&mut runs, cum); |
| 317 | runs |
| 318 | } |
| 319 |