/// [`assign`], ticking the gapless timer through the corridor stages — one /// switch per stage (`corridor-probe`, `corridor-spans`, `corridor-order`, /// `corridor-cut`), never one entry per sample. `None` skips the ticks, which /// is what [`assign`] and the unit tests drive. pub fn assign_with_timer( candidates: &[Candidate], mut timer: Option<&mut PhaseTimer>, ) -> Vec> { if candidates.is_empty() { return Vec::new(); } // One switch per corridor stage, matching the four stderr meters below. // The timer ticks here on the orchestrating thread only; the worker // threads inside never touch it. tick(&mut timer, "corridor-probe"); let route_count = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0); let (samples, blocks) = sample_all(candidates); let grid = Grid::build(&samples); // Local membership per sample, interned: distinct sets are few even on a world feed set, // and holding one `Vec` per sample is what would not fit. let mut sets: Vec> = Vec::new(); let mut set_ids: BTreeMap, u32> = BTreeMap::new(); let mut per_sample: Vec = Vec::with_capacity(samples.len()); // The probe is the whole cost of a large run — one per 10 m of every line, 287 million of // them on a world feed set — and it ran on one core for the better part of an hour. // // It splits in two. Finding which routes are near a sample is a pure read of the grid, so // that part goes wide: the samples are cut into one contiguous range per core and each // thread writes its answers into its own flat buffer. Interning those answers into set ids // cannot go wide, because an id is assigned on first sight and the ids have to come out in // sample order or every downstream lane moves. So the threads hand back their buffers in // range order and the interning walks them sequentially — cheap, since it is `BTreeMap` // lookups over an answer already computed. // // Flat `(values, ends)` buffers rather than `Vec>`: 287 million heap allocations // is its own kind of slow, and the whole point of interning is not to hold that many // vectors at once. let threads = crate::par::threads(); // Fixed-size ranges claimed first-come, not one range per thread: sample density is wildly // uneven (a European trunk holds dozens of routes per cell, a desert line one), and with // equal shares the thread that drew the dense ranges finished long after the rest. const PROBE_RANGE: usize = 1 << 18; let ranges = samples.len().div_ceil(PROBE_RANGE); let next_range = AtomicUsize::new(0); let probed = AtomicUsize::new(0); // Per range: its samples as local set ids, plus its distinct sets in the order it first saw // them, flat (`values`, `ends`). let parts: Mutex> = Mutex::new(Vec::new()); { let grid = &grid; let samples = &samples; let parts = &parts; let probed = &probed; let next_range = &next_range; let total = samples.len(); std::thread::scope(|scope| { for _ in 0..threads.min(ranges) { scope.spawn(move || { // Per thread, so the stamp trick in `routes_near` needs no sharing: a // stamp only has to be unique against this thread's own array. let mut seen: Vec = vec![0; route_count]; let mut stamp: u32 = 0; let mut near: Vec = Vec::new(); let mut done: Vec = Vec::new(); loop { let r = next_range.fetch_add(1, AtomicOrdering::Relaxed); if r >= ranges { break; } let (lo, hi) = (r * PROBE_RANGE, ((r + 1) * PROBE_RANGE).min(total)); // Interned locally, in first-seen order within this range; see the // merge below for why that composes into the global first-seen ids // exactly. let mut local: std::collections::HashMap, u32> = std::collections::HashMap::new(); let mut ids: Vec = Vec::with_capacity(hi - lo); let mut values: Vec = Vec::new(); let mut ends: Vec = Vec::new(); for sample in &samples[lo..hi] { stamp += 1; grid.routes_near(samples, sample, &mut near, &mut seen, stamp); let id = match local.get(near.as_slice()) { Some(&id) => id, None => { let id = ends.len() as u32; values.extend_from_slice(&near); ends.push(values.len() as u32); local.insert(near.clone(), id); id } }; ids.push(id); } done.push((r, ids, values, ends)); let n = probed.fetch_add(hi - lo, AtomicOrdering::Relaxed) + (hi - lo); eprint!( "\r{:<28} [{:>3}%] {total} sample(s)", "Corridor probe", (n * 100 / total.max(1)).min(100) ); } parts.lock().expect("probe pool").extend(done); }); } }); } eprintln!("\r{:<28} [100%] {} sample(s)", "Corridor probe", samples.len()); // The runs cutting below is spans work, not probe work. tick(&mut timer, "corridor-spans"); // Back in sample order, then each range's local ids mapped onto global ones. The global id // of a set is its rank in first-seen order over the whole sample sequence. A set first // occurs globally in the earliest range holding it, at that range's own first occurrence of // it, so walking the ranges in order and each range's distinct sets in its local first-seen // order meets every set's first global occurrence in global order — the ids come out exactly // as the sample-by-sample interning assigned them, at one map lookup per distinct set per // range instead of one per sample (287 M on a world set, ~50 s on one core). let mut parts = parts.into_inner().expect("probe pool"); parts.sort_unstable_by_key(|(t, _, _, _)| *t); let mut remaps: Vec> = Vec::with_capacity(parts.len()); for (_, _, values, ends) in &parts { let mut remap = Vec::with_capacity(ends.len()); let mut start = 0usize; for &end in ends { let near = &values[start..end as usize]; start = end as usize; let id = match set_ids.get(near) { Some(id) => *id, None => { let id = sets.len() as u32; sets.push(near.to_vec()); set_ids.insert(near.to_vec(), id); id } }; remap.push(id); } remaps.push(remap); } let mapped: Vec> = parts .par_iter() .zip(remaps.par_iter()) .map(|((_, ids, _, _), remap)| ids.iter().map(|&l| remap[l as usize]).collect()) .collect(); for ids in mapped { per_sample.extend_from_slice(&ids); } drop(parts); // Distance along each candidate, for its own geometry and for its probes. `resample` // walks *along* the polyline, so probe `k` is exactly `k * SAMPLE_M` along it and the // last one is its end. Summing the chords between probes instead would fall short of // that wherever the alignment curves, and the drift accumulates over a route's length // until the last run is cut short of the line's own end. let own_cum: Vec> = candidates.par_iter().map(|c| cumulative(c.points)).collect(); let probe_cum: Vec> = blocks .par_iter() .zip(own_cum.par_iter()) .map(|(block, own)| { let total = own.last().copied().unwrap_or(0.0); let count = block.len(); (0..count) .map(|k| if k + 1 == count { total } else { (k as f64 * SAMPLE_M).min(total) }) .collect() }) .collect(); let runs: Vec> = blocks .par_iter() .zip(probe_cum.par_iter()) .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum)) .collect(); let mut named: Vec> = vec![None; route_count]; for candidate in candidates { named[candidate.route as usize].get_or_insert((candidate.color, candidate.name)); } // Named too: on a large set the work after the probe loop is still minutes, and without a // line here the run goes silent again the moment the bar reaches 100%. eprintln!("{:<28} {} candidate(s)", "Corridor spans", candidates.len()); tick(&mut timer, "corridor-order"); let corridors = corridors_of(candidates, &sets, &runs, &named, &own_cum, &probe_cum); if std::env::var_os("TRANSIT_BUNDLE_DEBUG").is_some() { for (set, corridor) in &corridors { let members = &sets[*set as usize]; eprintln!( "corridor of {} over {} colour(s): {}", members.len(), corridor.colours.len(), members .iter() .map(|&m| { let (colour, name) = named[m as usize].unwrap_or((0, "")); format!("{name}/{colour:06X}") }) .collect::>() .join(" "), ); } } // The last phase, and per candidate independent: each one cuts its own runs against // corridors it only reads. Left sequential it was the tail that made a world set look // hung again after the corridor bar hit 100%. // // Handed out one candidate at a time rather than in equal contiguous ranges, because the // cost per candidate is wildly uneven — a transcontinental line carries orders of magnitude // more runs than a tram loop. Splitting the range evenly gave whichever thread drew the // long-distance rail all the work and left the rest idle: a world set sat at 98% on one // core for ten minutes with sixty-three threads finished. Sample probes are uniform enough // for a range split; candidates are not. // The cut below is its own stage: close the order subphase first. tick(&mut timer, "corridor-cut"); let total = candidates.len(); // Largest-first dispatch (longest-processing-time scheduling): hand out the heaviest // candidates first so the one transcontinental line overlaps with all the small work // instead of being picked last and grinding alone on one core at the end (the 99% // straggler). Cost is proxied by run count -- the same "orders of magnitude more runs" // the note above names. Output is unaffected: each result carries its candidate index and // the parts are re-sorted by it below, so dispatch order never reaches the archive. let order: Vec = { let mut o: Vec = (0..total).collect(); o.sort_unstable_by_key(|&i| std::cmp::Reverse(runs[i].len())); o }; // On the run's own pool rather than on scoped threads, so the one transcontinental line // that used to grind alone at the end can split its own placements across the idle // workers (see `spans_of`). One candidate per task, so dispatch stays first-come in the // largest-first order above. let cut_done = AtomicUsize::new(0); let mut cut_parts: Vec<(usize, Vec)> = order .par_iter() .with_max_len(1) .map(|&at| { let spans = spans_of( &candidates[at], &runs[at], &samples[blocks[at].clone()], &probe_cum[at], &own_cum[at], &corridors, ); let n = cut_done.fetch_add(1, AtomicOrdering::Relaxed) + 1; if n % 64 == 0 { eprint!( "\r{:<28} [{:>3}%] {total} line(s)", "Corridor cut", n * 100 / total.max(1) ); } (at, spans) }) .collect(); eprintln!("\r{:<28} [100%] {total} line(s)", "Corridor cut"); cut_parts.sort_unstable_by_key(|(at, _)| *at); cut_parts.into_iter().map(|(_, spans)| spans).collect() } /// One gapless tick, skipped when the caller passed `None`. /// /// The timer lives on the orchestrating thread only, and every call site is /// sequential code between the parallel loops, so worker threads never touch /// it — the coarse loop/pass boundaries are the ticks. fn tick(timer: &mut Option<&mut PhaseTimer>, name: &str) { if let Some(t) = timer { t.switch(name); } } /// A maximal stretch of one candidate's samples holding the same membership, as inclusive /// indices into that candidate's own block of samples. struct Run { from: usize, to: usize, set: u32, } /// A shared corridor: the geometry every member of it draws, and the lane order. struct Corridor { /// One member's polyline, folded into the canonical direction, which the whole corridor /// draws slices of. Owned rather than borrowed because the fold may reverse it. points: Vec<(i32, i32)>, cum: Vec, /// The corridor's distinct colours, ordered across it: the first is the left-hand side of /// the reference's direction of travel, which is the side [`Span::ordinal`] zero draws on. colours: Vec, /// Bounds over runs of [`SEG_BLOCK`] consecutive segments of `points`, so [`nearest`] can /// skip the ones that cannot hold the answer. Derived from `points`. blocks: Vec, } impl Corridor { fn new(points: Vec<(i32, i32)>, cum: Vec, colours: Vec) -> Corridor { let blocks = seg_blocks(&points); Corridor { points, cum, colours, blocks } } } /// Cut a candidate's samples into runs of constant membership, then smooth away the ones too /// short to be a corridor. fn cut_runs(per_sample: &[u32], cum: &[f64]) -> Vec { let Some(&first) = per_sample.first() else { return Vec::new() }; let mut runs = vec![Run { from: 0, to: 0, set: first }]; for (at, &set) in per_sample.iter().enumerate().skip(1) { let last = runs.last_mut().expect("seeded above"); if last.set == set { last.to = at; } else { runs.push(Run { from: at, to: at, set }); } } smooth(&mut runs, cum); runs }