gtfs_ingest: split oversized Rust files under the 500-line limit
- Commit
4af9ec1144b478faaec9c2b93412a1cce9d5b41f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 20:30 UTC (4 days ago)
- Parents
0653945
bundle_part2.rs (571), transit_shapes_extra2.rs (546), bundle.rs (536) and reader.rs (517) exceeded the 500-line rustFileLength limit; index_part3.rs (503) is a single finalize_feed method and stays for a separate extraction. Split each along module lines using the established include! part pattern: whole top-level items move verbatim into *_sN.rs files spliced into the same module or binary root (binary parts in a *_parts/ subdirectory so Cargo does not discover them as binaries), so every item and call path is identical. Verified: cargo fmt -p gtfs_ingest -- --check clean and cargo test -p gtfs_ingest --locked green (85 passed).
Diff
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rsindex 2751a28f14..b4d868b0ed 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs@@ -427,120 +427,4 @@ struct Speculated { mode_mark: u32, } -fn speculate(- line: &Line,- by_color: &BTreeMap<(&'static str, u32), bundle::Covered>,- by_mode: &BTreeMap<&'static str, bundle::Covered>,-) -> Speculated {- let walked = bundle::walk(&line.points);- let cells: Vec<bundle::Cell> = walked.iter().map(bundle::sample_cell).collect();- // Exactly the cover the sequential gate reads: the mode's for a line on its mode's- // fallback colour, the colour's otherwise. A cover not created yet is an empty one.- let gate =- if line.fallback { by_mode.get(line.mode) } else { by_color.get(&(line.mode, line.color)) };- let mode = by_mode.get(line.mode);- let uncovered: Vec<u32> = match gate {- None => (0..walked.len() as u32).collect(),- Some(g) => {- let scan = |lo: usize, hi: usize| -> Vec<u32> {- (lo..hi)- .filter(|&k| !g.covers_sample_in(cells[k], &walked[k]))- .map(|k| k as u32)- .collect()- };- if walked.len() < PAR_SAMPLES {- scan(0, walked.len())- } else {- let starts: Vec<usize> = (0..walked.len()).step_by(PAR_SAMPLES).collect();- let parts: Vec<Vec<u32>> = starts- .par_iter()- .map(|&lo| scan(lo, (lo + PAR_SAMPLES).min(walked.len())))- .collect();- parts.concat()- }- }- };- let drawn = walked.len() - uncovered.len();- // `covered_fraction_walked`'s arithmetic, including 0 for a line too short to walk.- let redundant = !walked.is_empty() && drawn as f64 / walked.len() as f64 >= MOSTLY_DRAWN;- let crowd = (!redundant && !line.intercity).then(|| {- mode.is_some_and(|m| {- let at = |k: usize| {- m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new())- };- if walked.len() < PAR_SAMPLES {- (0..walked.len()).any(at)- } else {- (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)- }- })- });- Speculated {- walked,- cells,- drawn,- uncovered,- redundant,- crowd,- gate_mark: gate.map_or(0, bundle::Covered::mark),- mode_mark: mode.map_or(0, bundle::Covered::mark),- }-}--/// The redundancy gate re-decided against the live cover `g`: the speculated `drawn`, plus-/// every speculated-uncovered sample that is now covered — which only a sample beside a cell-/// `g` has gained since `mark` can be. Whether the count reaches the threshold is all that-/// matters, so a small line stops as soon as that is settled either way.-fn recount_reaches(- g: &bundle::Covered,- mark: u32,- walked: &[bundle::Walked],- cells: &[bundle::Cell],- drawn: usize,- uncovered: &[u32],-) -> bool {- let need = drawn_needed(walked.len());- let now_covered = |k: u32| {- let k = k as usize;- g.changed_near(cells[k], mark) && g.covers_sample_in(cells[k], &walked[k])- };- if uncovered.len() >= PAR_SAMPLES {- return drawn- + uncovered- .par_iter()- .with_min_len(PAR_SAMPLES / 4)- .filter(|&&k| now_covered(k))- .count()- >= need;- }- let (mut drawn, mut left) = (drawn, uncovered.len());- for &k in uncovered {- if drawn >= need || drawn + left < need {- break;- }- left -= 1;- if now_covered(k) {- drawn += 1;- }- }- drawn >= need-}--/// The crowd gate re-decided against the live mode cover `m`, where the speculated answer-/// was `false`: only a sample beside a cell `m` has gained since `mark` can have changed.-fn recrowd_reaches(- m: &bundle::Covered,- mark: u32,- walked: &[bundle::Walked],- cells: &[bundle::Cell],-) -> bool {- let at = |k: usize| {- m.changed_near(cells[k], mark)- && m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new())- };- if walked.len() < PAR_SAMPLES {- (0..walked.len()).any(at)- } else {- (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)- }-}+include!("transit_shapes_extra2_parts/transit_shapes_extra2_s1.rs");
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2_parts/transit_shapes_extra2_s1.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2_parts/transit_shapes_extra2_s1.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2_parts/transit_shapes_extra2_s1.rsnew file mode 100644index 0000000000..44f4dd2722--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2_parts/transit_shapes_extra2_s1.rs@@ -0,0 +1,117 @@+fn speculate(+ line: &Line,+ by_color: &BTreeMap<(&'static str, u32), bundle::Covered>,+ by_mode: &BTreeMap<&'static str, bundle::Covered>,+) -> Speculated {+ let walked = bundle::walk(&line.points);+ let cells: Vec<bundle::Cell> = walked.iter().map(bundle::sample_cell).collect();+ // Exactly the cover the sequential gate reads: the mode's for a line on its mode's+ // fallback colour, the colour's otherwise. A cover not created yet is an empty one.+ let gate =+ if line.fallback { by_mode.get(line.mode) } else { by_color.get(&(line.mode, line.color)) };+ let mode = by_mode.get(line.mode);+ let uncovered: Vec<u32> = match gate {+ None => (0..walked.len() as u32).collect(),+ Some(g) => {+ let scan = |lo: usize, hi: usize| -> Vec<u32> {+ (lo..hi)+ .filter(|&k| !g.covers_sample_in(cells[k], &walked[k]))+ .map(|k| k as u32)+ .collect()+ };+ if walked.len() < PAR_SAMPLES {+ scan(0, walked.len())+ } else {+ let starts: Vec<usize> = (0..walked.len()).step_by(PAR_SAMPLES).collect();+ let parts: Vec<Vec<u32>> = starts+ .par_iter()+ .map(|&lo| scan(lo, (lo + PAR_SAMPLES).min(walked.len())))+ .collect();+ parts.concat()+ }+ }+ };+ let drawn = walked.len() - uncovered.len();+ // `covered_fraction_walked`'s arithmetic, including 0 for a line too short to walk.+ let redundant = !walked.is_empty() && drawn as f64 / walked.len() as f64 >= MOSTLY_DRAWN;+ let crowd = (!redundant && !line.intercity).then(|| {+ mode.is_some_and(|m| {+ let at = |k: usize| {+ m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new())+ };+ if walked.len() < PAR_SAMPLES {+ (0..walked.len()).any(at)+ } else {+ (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)+ }+ })+ });+ Speculated {+ walked,+ cells,+ drawn,+ uncovered,+ redundant,+ crowd,+ gate_mark: gate.map_or(0, bundle::Covered::mark),+ mode_mark: mode.map_or(0, bundle::Covered::mark),+ }+}++/// The redundancy gate re-decided against the live cover `g`: the speculated `drawn`, plus+/// every speculated-uncovered sample that is now covered — which only a sample beside a cell+/// `g` has gained since `mark` can be. Whether the count reaches the threshold is all that+/// matters, so a small line stops as soon as that is settled either way.+fn recount_reaches(+ g: &bundle::Covered,+ mark: u32,+ walked: &[bundle::Walked],+ cells: &[bundle::Cell],+ drawn: usize,+ uncovered: &[u32],+) -> bool {+ let need = drawn_needed(walked.len());+ let now_covered = |k: u32| {+ let k = k as usize;+ g.changed_near(cells[k], mark) && g.covers_sample_in(cells[k], &walked[k])+ };+ if uncovered.len() >= PAR_SAMPLES {+ return drawn+ + uncovered+ .par_iter()+ .with_min_len(PAR_SAMPLES / 4)+ .filter(|&&k| now_covered(k))+ .count()+ >= need;+ }+ let (mut drawn, mut left) = (drawn, uncovered.len());+ for &k in uncovered {+ if drawn >= need || drawn + left < need {+ break;+ }+ left -= 1;+ if now_covered(k) {+ drawn += 1;+ }+ }+ drawn >= need+}++/// The crowd gate re-decided against the live mode cover `m`, where the speculated answer+/// was `false`: only a sample beside a cell `m` has gained since `mark` can have changed.+fn recrowd_reaches(+ m: &bundle::Covered,+ mark: u32,+ walked: &[bundle::Walked],+ cells: &[bundle::Cell],+) -> bool {+ let at = |k: usize| {+ m.changed_near(cells[k], mark)+ && m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new())+ };+ if walked.len() < PAR_SAMPLES {+ (0..walked.len()).any(at)+ } else {+ (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)+ }+}
scripts/maps/gtfs_ingest/src/bundle.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle.rs b/scripts/maps/gtfs_ingest/src/bundle.rsindex e73fbb7266..464654c729 100644--- a/scripts/maps/gtfs_ingest/src/bundle.rs+++ b/scripts/maps/gtfs_ingest/src/bundle.rs@@ -210,325 +210,7 @@ pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> { assign_with_timer(candidates, None) } -/// [`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<Vec<Span>> {- 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<u32>` per sample is what would not fit.- let mut sets: Vec<Vec<u32>> = Vec::new();- let mut set_ids: BTreeMap<Vec<u32>, u32> = BTreeMap::new();- let mut per_sample: Vec<u32> = 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<Vec<u32>>`: 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<Vec<ProbePart>> = 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<u32> = vec![0; route_count];- let mut stamp: u32 = 0;- let mut near: Vec<u32> = Vec::new();- let mut done: Vec<ProbePart> = 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<Vec<u32>, u32> =- std::collections::HashMap::new();- let mut ids: Vec<u32> = Vec::with_capacity(hi - lo);- let mut values: Vec<u32> = Vec::new();- let mut ends: Vec<u32> = 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<u32>> = 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<Vec<u32>> = 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<Vec<f64>> = candidates.par_iter().map(|c| cumulative(c.points)).collect();- let probe_cum: Vec<Vec<f64>> = 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<Vec<Run>> = blocks- .par_iter()- .zip(probe_cum.par_iter())- .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum))- .collect();-- let mut named: Vec<Option<(u32, &str)>> = 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::<Vec<String>>()- .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<usize> = {- let mut o: Vec<usize> = (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<Span>)> = 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<f64>,- /// 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<u32>,- /// 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<SegBlock>,-}--impl Corridor {- fn new(points: Vec<(i32, i32)>, cum: Vec<f64>, colours: Vec<u32>) -> 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<Run> {- 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-}-+include!("bundle_s1.rs"); include!("bundle_part1.rs"); include!("bundle_part2.rs"); include!("bundle_part3.rs");
scripts/maps/gtfs_ingest/src/bundle_part2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part2.rs b/scripts/maps/gtfs_ingest/src/bundle_part2.rsindex 68a200cc10..5768a92f24 100644--- a/scripts/maps/gtfs_ingest/src/bundle_part2.rs+++ b/scripts/maps/gtfs_ingest/src/bundle_part2.rs@@ -394,178 +394,4 @@ fn within(corridor: &Corridor, p: (i32, i32), radius: f64) -> bool { }) } -/// How far to the side of a corridor's reference `p` lies, in metres, signed positive to the-/// right of the reference's direction of travel.-///-/// The same nearest-segment walk [`distance_along`] does, because [`project`] returns an-/// unsigned distance and no side. Against the nearest segment's unit tangent `(ux, uy)` in an-/// (east, north) frame — the frame [`directed`] already produces — the side of the offset `d`-/// is `d.east * uy - d.north * ux`. Positive is the right-hand side because `tess::stroke`-/// emits `(0, +1)` as the normal of an eastward segment and `line.vert` shifts along it, so-/// ascending offset is ascending ordinal: `lane_offset_px` gives ordinal zero the most-/// negative offset, which is the left of the reference's travel.-///-/// Only the reference's own stretch of the corridor, `extent`, is searched. Past the mouth the-/// reference has left the corridor too, and the segment nearest an approaching member is then-/// as likely to be the reference's departure as the corridor — which reads a member leaving-/// west as having no side at all. Clamped, the approach is measured against the reference's-/// tangent at the mouth, which is the axis the lanes are laid out across.-fn signed_offset(corridor: &Corridor, extent: (f64, f64), p: (i32, i32)) -> f64 {- let (points, cum) = (&corridor.points, &corridor.cum);- let mut best = (f64::INFINITY, 0.0f64);- for at in 0..points.len().saturating_sub(1) {- if cum[at + 1] < extent.0 || cum[at] > extent.1 {- continue;- }- let (a, b) = (points[at], points[at + 1]);- let (_, distance) = project(p, a, b, 0.0);- if distance >= best.0 {- continue;- }- let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();- let (east, north) = ((b.1 - a.1) as f64 * cos_lat, (b.0 - a.0) as f64);- let length = (east * east + north * north).sqrt();- if length <= 0.0 {- continue;- }- let (ux, uy) = (east / length, north / length);- let d_east = (p.1 - a.1) as f64 * 1e-7 * 111_320.0 * cos_lat;- let d_north = (p.0 - a.0) as f64 * 1e-7 * 111_320.0;- best = (distance, d_east * uy - d_north * ux);- }- best.1-}--/// One probe point along a candidate, with the unit direction of travel there.-struct Sample {- route: u32,- point: (i32, i32),- ux: f64,- uy: f64,-}--/// One walked sample of a line: its point and the unit direction of travel there.-///-/// Exposed so a caller that runs several of [`Covered`]'s gates over one line can walk it-/// once and hand the samples to each, rather than every gate re-walking the same points.-pub type Walked = ((i32, i32), f64, f64);--/// Walk a polyline at [`SAMPLE_M`], returning each sample with its unit direction of travel.-pub fn walk(points: &[(i32, i32)]) -> Vec<Walked> {- let walked = resample(points, SAMPLE_M);- if walked.len() < 2 {- return Vec::new();- }- directed(&walked)-}--/// Each point of `line` with the unit direction of travel there. One entry per input point:-/// a degenerate segment carries the previous direction forward rather than dropping the-/// point, so the result stays index-aligned with its input.-fn directed(line: &[(i32, i32)]) -> Vec<((i32, i32), f64, f64)> {- let mut out = Vec::with_capacity(line.len());- let (mut ux, mut uy) = (1.0f64, 0.0f64);- for i in 0..line.len() {- let (a, b) = if i + 1 < line.len() { (line[i], line[i + 1]) } else { (line[i.max(1) - 1], line[i]) };- let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();- let dy = (b.0 - a.0) as f64;- let dx = (b.1 - a.1) as f64 * cos_lat;- let length = (dx * dx + dy * dy).sqrt();- if length > 0.0 {- (ux, uy) = (dx / length, dy / length);- }- out.push((line[i], ux, uy));- }- out-}--/// The nine cells a corridor-radius match can live in, centre first.-///-/// Returning on the first match means visit order decides how much of the neighbourhood is-/// scanned. The point's own cell is by far the likeliest to hold it — a corridor of 30 m inside a-/// cell of 40 m — so it goes first, then the four edge neighbours, then the corners, which can-/// only match across a cell join. Visiting them in `-1..=1` order put a corner first and scanned-/// most of the neighbourhood before reaching the answer.-///-/// A pure reordering: the set of samples examined is unchanged, so every result is too.-const NEIGHBOURHOOD: [(i32, i32); 9] =- [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)];--/// Track already drawn, for suppressing a line that adds nothing.-///-/// Two services of one colour must never draw as parallel lines: nothing distinguishes them,-/// so the second is pure over-draw. What stops that is the lane, which is assigned per-/// **colour** — two lines of one colour in one corridor take the same offset over the same-/// reference geometry and coincide exactly, reading as the one line they are.-///-/// This is the other half: a line wholly on top of track already drawn in its colour is not-/// worth carrying at all. A route publishes its two directions, its short-turns and its-/// branch variants as separate shapes, and every other feed covering the city republishes-/// the lot re-surveyed a few metres off.-///-/// **Whole lines only.** Subtracting the covered *parts* of a line was tried and is wrong: it-/// cut every route into fragments, and a stretch too short to be worth emitting left a hole-/// that nothing else drew. A line either adds something or it does not.-///-/// The lookup is a `HashMap` of cells rather than the sorted vector the rest of this module-/// uses. Nothing iterates it — the answer is a boolean about one point — so it cannot leak an-/// order into the output.-pub struct Covered {- /// Every drawn sample, bucketed by its cell.- ///- /// **One representative per cell per service**: a bucket holds at most one sample of each- /// tag. That is enough for [`covers`](Covered::covers) and [`tags_over`](Covered::tags_over):- /// both ask whether *any* sample of a service is within a corridor of a point, and every- /// sample of one service in one cell answers that identically. Keeping only the first turns- /// a cell's occupancy from overlap depth — a trunk republished by a dozen feeds is a dozen- /// sample runs in the same cells — into distinct services, which is what those gates read.- /// It also makes "is this service already in this cell" a scan of a handful of entries in a- /// bucket already being looked up, rather than a second set of `(cell, tag)` pairs.- ///- /// Split into [`COVER_SHARDS`] maps by [`shard_of`], so a long line's add fills them all- /// at once. A pure partition: every cell lives in exactly one shard, and each shard sees its- /// cells' samples in line order, so every bucket ends up holding exactly what one map would.- cells: Vec<std::collections::HashMap<Cell, Bucket, CellHash>>,- /// How many `add` calls this cover has taken; see [`Covered::mark`].- adds: u32,-}--impl Default for Covered {- fn default() -> Self {- Covered { cells: (0..COVER_SHARDS).map(|_| Default::default()).collect(), adds: 0 }- }-}--/// Shards per [`Covered`]. Changes no answer; only how wide an add can go.-const COVER_SHARDS: usize = 64;--/// The shard holding `cell`. Mixed independently of [`CellHasher`], so the cells of one shard-/// still spread over its own table.-fn shard_of((x, y): Cell) -> usize {- let h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA77);- (h.wrapping_mul(0xC2B2_AE35) >> 26) as usize % COVER_SHARDS-}--/// One cell's representatives, in the order they were added.-struct Bucket {- /// The `adds` count of the last add that appended here.- added: u32,- /// Inline, because most buckets — every bucket of a colour's cover — hold exactly one.- first: Drawn,- rest: Vec<Drawn>,-}--impl Bucket {- fn iter(&self) -> impl Iterator<Item = &Drawn> {- std::iter::once(&self.first).chain(self.rest.iter())- }-}--/// One drawn sample and the service that drew it.-#[derive(Clone, Copy)]-struct Drawn {- point: (i32, i32),- ux: f64,- uy: f64,- tag: u32,-}+include!("bundle_part2_s1.rs");
scripts/maps/gtfs_ingest/src/bundle_part2_s1.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part2_s1.rs b/scripts/maps/gtfs_ingest/src/bundle_part2_s1.rsnew file mode 100644index 0000000000..2b276311ec--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bundle_part2_s1.rs@@ -0,0 +1,175 @@+/// How far to the side of a corridor's reference `p` lies, in metres, signed positive to the+/// right of the reference's direction of travel.+///+/// The same nearest-segment walk [`distance_along`] does, because [`project`] returns an+/// unsigned distance and no side. Against the nearest segment's unit tangent `(ux, uy)` in an+/// (east, north) frame — the frame [`directed`] already produces — the side of the offset `d`+/// is `d.east * uy - d.north * ux`. Positive is the right-hand side because `tess::stroke`+/// emits `(0, +1)` as the normal of an eastward segment and `line.vert` shifts along it, so+/// ascending offset is ascending ordinal: `lane_offset_px` gives ordinal zero the most+/// negative offset, which is the left of the reference's travel.+///+/// Only the reference's own stretch of the corridor, `extent`, is searched. Past the mouth the+/// reference has left the corridor too, and the segment nearest an approaching member is then+/// as likely to be the reference's departure as the corridor — which reads a member leaving+/// west as having no side at all. Clamped, the approach is measured against the reference's+/// tangent at the mouth, which is the axis the lanes are laid out across.+fn signed_offset(corridor: &Corridor, extent: (f64, f64), p: (i32, i32)) -> f64 {+ let (points, cum) = (&corridor.points, &corridor.cum);+ let mut best = (f64::INFINITY, 0.0f64);+ for at in 0..points.len().saturating_sub(1) {+ if cum[at + 1] < extent.0 || cum[at] > extent.1 {+ continue;+ }+ let (a, b) = (points[at], points[at + 1]);+ let (_, distance) = project(p, a, b, 0.0);+ if distance >= best.0 {+ continue;+ }+ let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();+ let (east, north) = ((b.1 - a.1) as f64 * cos_lat, (b.0 - a.0) as f64);+ let length = (east * east + north * north).sqrt();+ if length <= 0.0 {+ continue;+ }+ let (ux, uy) = (east / length, north / length);+ let d_east = (p.1 - a.1) as f64 * 1e-7 * 111_320.0 * cos_lat;+ let d_north = (p.0 - a.0) as f64 * 1e-7 * 111_320.0;+ best = (distance, d_east * uy - d_north * ux);+ }+ best.1+}++/// One probe point along a candidate, with the unit direction of travel there.+struct Sample {+ route: u32,+ point: (i32, i32),+ ux: f64,+ uy: f64,+}++/// One walked sample of a line: its point and the unit direction of travel there.+///+/// Exposed so a caller that runs several of [`Covered`]'s gates over one line can walk it+/// once and hand the samples to each, rather than every gate re-walking the same points.+pub type Walked = ((i32, i32), f64, f64);++/// Walk a polyline at [`SAMPLE_M`], returning each sample with its unit direction of travel.+pub fn walk(points: &[(i32, i32)]) -> Vec<Walked> {+ let walked = resample(points, SAMPLE_M);+ if walked.len() < 2 {+ return Vec::new();+ }+ directed(&walked)+}++/// Each point of `line` with the unit direction of travel there. One entry per input point:+/// a degenerate segment carries the previous direction forward rather than dropping the+/// point, so the result stays index-aligned with its input.+fn directed(line: &[(i32, i32)]) -> Vec<((i32, i32), f64, f64)> {+ let mut out = Vec::with_capacity(line.len());+ let (mut ux, mut uy) = (1.0f64, 0.0f64);+ for i in 0..line.len() {+ let (a, b) = if i + 1 < line.len() { (line[i], line[i + 1]) } else { (line[i.max(1) - 1], line[i]) };+ let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();+ let dy = (b.0 - a.0) as f64;+ let dx = (b.1 - a.1) as f64 * cos_lat;+ let length = (dx * dx + dy * dy).sqrt();+ if length > 0.0 {+ (ux, uy) = (dx / length, dy / length);+ }+ out.push((line[i], ux, uy));+ }+ out+}++/// The nine cells a corridor-radius match can live in, centre first.+///+/// Returning on the first match means visit order decides how much of the neighbourhood is+/// scanned. The point's own cell is by far the likeliest to hold it — a corridor of 30 m inside a+/// cell of 40 m — so it goes first, then the four edge neighbours, then the corners, which can+/// only match across a cell join. Visiting them in `-1..=1` order put a corner first and scanned+/// most of the neighbourhood before reaching the answer.+///+/// A pure reordering: the set of samples examined is unchanged, so every result is too.+const NEIGHBOURHOOD: [(i32, i32); 9] =+ [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)];++/// Track already drawn, for suppressing a line that adds nothing.+///+/// Two services of one colour must never draw as parallel lines: nothing distinguishes them,+/// so the second is pure over-draw. What stops that is the lane, which is assigned per+/// **colour** — two lines of one colour in one corridor take the same offset over the same+/// reference geometry and coincide exactly, reading as the one line they are.+///+/// This is the other half: a line wholly on top of track already drawn in its colour is not+/// worth carrying at all. A route publishes its two directions, its short-turns and its+/// branch variants as separate shapes, and every other feed covering the city republishes+/// the lot re-surveyed a few metres off.+///+/// **Whole lines only.** Subtracting the covered *parts* of a line was tried and is wrong: it+/// cut every route into fragments, and a stretch too short to be worth emitting left a hole+/// that nothing else drew. A line either adds something or it does not.+///+/// The lookup is a `HashMap` of cells rather than the sorted vector the rest of this module+/// uses. Nothing iterates it — the answer is a boolean about one point — so it cannot leak an+/// order into the output.+pub struct Covered {+ /// Every drawn sample, bucketed by its cell.+ ///+ /// **One representative per cell per service**: a bucket holds at most one sample of each+ /// tag. That is enough for [`covers`](Covered::covers) and [`tags_over`](Covered::tags_over):+ /// both ask whether *any* sample of a service is within a corridor of a point, and every+ /// sample of one service in one cell answers that identically. Keeping only the first turns+ /// a cell's occupancy from overlap depth — a trunk republished by a dozen feeds is a dozen+ /// sample runs in the same cells — into distinct services, which is what those gates read.+ /// It also makes "is this service already in this cell" a scan of a handful of entries in a+ /// bucket already being looked up, rather than a second set of `(cell, tag)` pairs.+ ///+ /// Split into [`COVER_SHARDS`] maps by [`shard_of`], so a long line's add fills them all+ /// at once. A pure partition: every cell lives in exactly one shard, and each shard sees its+ /// cells' samples in line order, so every bucket ends up holding exactly what one map would.+ cells: Vec<std::collections::HashMap<Cell, Bucket, CellHash>>,+ /// How many `add` calls this cover has taken; see [`Covered::mark`].+ adds: u32,+}++impl Default for Covered {+ fn default() -> Self {+ Covered { cells: (0..COVER_SHARDS).map(|_| Default::default()).collect(), adds: 0 }+ }+}++/// Shards per [`Covered`]. Changes no answer; only how wide an add can go.+const COVER_SHARDS: usize = 64;++/// The shard holding `cell`. Mixed independently of [`CellHasher`], so the cells of one shard+/// still spread over its own table.+fn shard_of((x, y): Cell) -> usize {+ let h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA77);+ (h.wrapping_mul(0xC2B2_AE35) >> 26) as usize % COVER_SHARDS+}++/// One cell's representatives, in the order they were added.+struct Bucket {+ /// The `adds` count of the last add that appended here.+ added: u32,+ /// Inline, because most buckets — every bucket of a colour's cover — hold exactly one.+ first: Drawn,+ rest: Vec<Drawn>,+}++impl Bucket {+ fn iter(&self) -> impl Iterator<Item = &Drawn> {+ std::iter::once(&self.first).chain(self.rest.iter())+ }+}++/// One drawn sample and the service that drew it.+#[derive(Clone, Copy)]+struct Drawn {+ point: (i32, i32),+ ux: f64,+ uy: f64,+ tag: u32,+}
scripts/maps/gtfs_ingest/src/bundle_s1.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_s1.rs b/scripts/maps/gtfs_ingest/src/bundle_s1.rsnew file mode 100644index 0000000000..fec882efb2--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bundle_s1.rs@@ -0,0 +1,319 @@+/// [`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<Vec<Span>> {+ 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<u32>` per sample is what would not fit.+ let mut sets: Vec<Vec<u32>> = Vec::new();+ let mut set_ids: BTreeMap<Vec<u32>, u32> = BTreeMap::new();+ let mut per_sample: Vec<u32> = 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<Vec<u32>>`: 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<Vec<ProbePart>> = 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<u32> = vec![0; route_count];+ let mut stamp: u32 = 0;+ let mut near: Vec<u32> = Vec::new();+ let mut done: Vec<ProbePart> = 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<Vec<u32>, u32> =+ std::collections::HashMap::new();+ let mut ids: Vec<u32> = Vec::with_capacity(hi - lo);+ let mut values: Vec<u32> = Vec::new();+ let mut ends: Vec<u32> = 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<u32>> = 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<Vec<u32>> = 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<Vec<f64>> = candidates.par_iter().map(|c| cumulative(c.points)).collect();+ let probe_cum: Vec<Vec<f64>> = 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<Vec<Run>> = blocks+ .par_iter()+ .zip(probe_cum.par_iter())+ .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum))+ .collect();++ let mut named: Vec<Option<(u32, &str)>> = 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::<Vec<String>>()+ .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<usize> = {+ let mut o: Vec<usize> = (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<Span>)> = 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<f64>,+ /// 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<u32>,+ /// 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<SegBlock>,+}++impl Corridor {+ fn new(points: Vec<(i32, i32)>, cum: Vec<f64>, colours: Vec<u32>) -> 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<Run> {+ 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+}+
scripts/maps/gtfs_ingest/src/reader.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader.rs b/scripts/maps/gtfs_ingest/src/reader.rsindex face65b0c8..4e46540f65 100644--- a/scripts/maps/gtfs_ingest/src/reader.rs+++ b/scripts/maps/gtfs_ingest/src/reader.rs@@ -96,422 +96,4 @@ pub struct Reader { sec: Vec<(usize, usize)>, } -impl Reader {- /// Validate the header and index the section directory.- pub fn new(buf: Vec<u8>) -> Result<Reader, String> {- if buf.len() < HEADER_LEN {- return Err(format!("pack is {} bytes, shorter than the header", buf.len()));- }- let magic = ru32(&buf, 0);- if magic != MAGIC {- return Err(format!("bad magic {magic:#x}"));- }- let version = ru32(&buf, 4);- if !(VERSION_MIN..=VERSION).contains(&version) {- return Err(format!("version {version} outside {VERSION_MIN}..={VERSION}"));- }- let count = ru32(&buf, 8) as usize;- if count != SECTION_COUNT && count != SECTION_COUNT_V6 {- return Err(format!("section_count {count}, expected {SECTION_COUNT}"));- }- if buf.len() < HEADER_LEN + count * 16 {- return Err("pack is truncated inside the section directory".to_string());- }- let mut sec = Vec::with_capacity(count);- for i in 0..count {- let base = HEADER_LEN + i * 16;- let off = ru64(&buf, base) as usize;- let len = ru64(&buf, base + 8) as usize;- match off.checked_add(len) {- Some(end) if end <= buf.len() => {}- _ => return Err(format!("section {i} at {off}+{len} runs past the file")),- }- sec.push((off, len));- }- Ok(Reader { buf, sec })- }-- /// Read the pack at `path`.- pub fn open(path: &std::path::Path) -> Result<Reader, String> {- let buf =- std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;- Reader::new(buf)- }-- /// Read the pack at `path`, but only the header, the directory and the listed sections.- ///- /// For a caller that needs a few hundred MB of a multi-GB pack: `transit_shapes --pack`- /// reads three sections, and reading the whole 4.4 GB world pack first was most of its- /// start-up. The buffer is still the file's full length, so every offset means what it- /// does in [`open`](Self::open), and it is validated identically; the sections not listed- /// read as zeros and must not be used. The zeroed buffer is allocated untouched, so the- /// unread sections cost address space, not memory. Listed sections the pack does not have- /// (a v6 pack has no RAIL_LINES) are skipped, for the accessors to report.- pub fn open_sections(path: &std::path::Path, sections: &[usize]) -> Result<Reader, String> {- use std::io::{Read, Seek, SeekFrom};- let fail = |e: std::io::Error| format!("cannot read {}: {e}", path.display());- let mut f = std::fs::File::open(path).map_err(fail)?;- let len = f.metadata().map_err(fail)?.len() as usize;- let mut buf = vec![0u8; len];- // Header, then the directory it sizes. `new` re-checks both against the real length.- let head = HEADER_LEN.min(len);- f.read_exact(&mut buf[..head]).map_err(fail)?;- if head == HEADER_LEN {- let dir_end = (HEADER_LEN + ru32(&buf, 8) as usize * 16).min(len);- f.read_exact(&mut buf[HEADER_LEN..dir_end]).map_err(fail)?;- }- let mut reader = Reader::new(buf)?;- for &s in sections {- let Some(&(off, l)) = reader.sec.get(s) else { continue };- f.seek(SeekFrom::Start(off as u64)).map_err(fail)?;- f.read_exact(&mut reader.buf[off..off + l]).map_err(fail)?;- }- Ok(reader)- }-- /// The `idx`-th u32 of the header.- fn hdr(&self, idx: usize) -> u32 {- ru32(&self.buf, idx * 4)- }-- pub fn version(&self) -> u32 {- self.hdr(1)- }- pub fn section_count(&self) -> u32 {- self.hdr(2)- }- pub fn stop_count(&self) -> u32 {- self.hdr(3)- }- pub fn route_count(&self) -> u32 {- self.hdr(4)- }- pub fn trip_count(&self) -> u32 {- self.hdr(5)- }- pub fn service_count(&self) -> u32 {- self.hdr(6)- }- pub fn profile_count(&self) -> u32 {- self.hdr(7)- }- pub fn feed_count(&self) -> u32 {- self.hdr(8)- }- pub fn grid_cell_count(&self) -> u32 {- self.hdr(9)- }- /// The pack name the device falls back to.- pub fn pack_name(&self) -> String {- self.read_str(self.hdr(10))- }- /// `(min_lat_e7, min_lon_e7, max_lat_e7, max_lon_e7)`.- pub fn bbox(&self) -> (i32, i32, i32, i32) {- (self.hdr(11) as i32, self.hdr(12) as i32, self.hdr(13) as i32, self.hdr(14) as i32)- }- pub fn grid(&self) -> GridParams {- GridParams {- lat0_e7: self.hdr(15) as i32,- lon0_e7: self.hdr(16) as i32,- cell_e7: self.hdr(17),- cols: self.hdr(18),- rows: self.hdr(19),- }- }-- pub fn sec_bytes(&self, s: usize) -> &[u8] {- let (o, l) = self.sec[s];- &self.buf[o..o + l]- }-- /// The NUL-terminated string at STRINGS offset `off`; "" for [`NONE`].- pub fn read_str(&self, off: u32) -> String {- if off == NONE {- return String::new();- }- let s = self.sec_bytes(SEC_STRINGS);- let start = off as usize;- let mut n = 0;- while start + n < s.len() && s[start + n] != 0 {- n += 1;- }- String::from_utf8_lossy(&s[start..start + n]).into_owned()- }-- /// `(lat, lon)` in degrees.- pub fn stop_ll(&self, i: u32) -> (f64, f64) {- let (lat, lon) = self.stop_ll_e7(i);- (lat as f64 * 1e-7, lon as f64 * 1e-7)- }-- pub fn stop_ll_e7(&self, i: u32) -> (i32, i32) {- let s = self.sec_bytes(SEC_STOPS);- let base = i as usize * 16;- (ri32(s, base), ri32(s, base + 4))- }-- pub fn stop_name(&self, i: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 8))- }-- pub fn stop_code(&self, i: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 12))- }-- /// The raw GTFS `stop_id` (v5 STOP_GTFS_ID).- pub fn stop_gtfs_id(&self, i: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_STOP_GTFS_ID), i as usize * 4))- }-- pub fn route(&self, r: u32) -> RouteRec {- let s = self.sec_bytes(SEC_ROUTES);- let base = r as usize * 32;- RouteRec {- name_off: ru32(s, base),- color: ru32(s, base + 4),- route_type: ru32(s, base + 8),- feed_idx: ru32(s, base + 12),- n_stops: ru32(s, base + 16),- first_route_stop: ru32(s, base + 20),- n_trips: ru32(s, base + 24),- trips_off: ru32(s, base + 28),- }- }-- /// ROUTE_STOPS entry `i` (an absolute stop index).- pub fn route_stop(&self, i: u32) -> u32 {- ru32(self.sec_bytes(SEC_ROUTE_STOPS), i as usize * 4)- }-- /// A route's stop pattern.- pub fn route_stops(&self, rec: &RouteRec) -> Vec<u32> {- (0..rec.n_stops).map(|p| self.route_stop(rec.first_route_stop + p)).collect()- }-- /// Decode a route's varint trip block, in start-time order.- pub fn route_trips(&self, rec: &RouteRec) -> Vec<TripRec> {- let s = self.sec_bytes(SEC_ROUTE_TRIPS);- let mut pos = rec.trips_off as usize;- let mut prev = 0u32;- let mut out = Vec::with_capacity(rec.n_trips as usize);- for _ in 0..rec.n_trips {- let start_time = prev + read_uvarint(s, &mut pos) as u32;- out.push(TripRec {- start_time,- profile_id: read_uvarint(s, &mut pos) as u32,- service_idx: read_uvarint(s, &mut pos) as u32,- headsign_off: read_uvarint(s, &mut pos) as u32,- });- prev = start_time;- }- out- }-- /// A route's trips read from v6's fixed-stride table instead of the varint stream.- ///- /// The point of the table is that a trip is addressable by index, so the device- /// reader can stop decoding trips its scan never looks at. Here it serves a second- /// purpose: it is an independent decoding of the same data, so- /// [`Self::route_trips_strided`] and [`Self::route_trips`] disagreeing means the- /// writer emitted two views that do not match.- pub fn route_trips_strided(&self, route_idx: u32) -> Vec<TripRec> {- let off = self.sec_bytes(SEC_ROUTE_TRIP_OFF);- let recs = self.sec_bytes(SEC_ROUTE_TRIP_RECS);- if (route_idx as usize + 2) * 4 > off.len() {- return Vec::new();- }- let base = ru32(off, route_idx as usize * 4) as usize;- let end = ru32(off, (route_idx as usize + 1) * 4) as usize;- if end < base || end * TRIP_REC_BYTES > recs.len() {- return Vec::new();- }- (base..end)- .map(|i| {- let at = i * TRIP_REC_BYTES;- TripRec {- start_time: ru32(recs, at),- profile_id: ru32(recs, at + 4),- service_idx: ru32(recs, at + 8),- headsign_off: ru32(recs, at + 12),- }- })- .collect()- }-- /// Profile `pid` as per-stop `(arr, dep)` offsets relative to a trip's- /// `start_time`. `arr[0]` is negative by the first dwell.- pub fn profile(&self, pid: u32) -> Vec<(i64, i64)> {- let idx = self.sec_bytes(SEC_PROFILES_IDX);- let off = ru32(idx, pid as usize * 4) as usize;- let s = self.sec_bytes(SEC_PROFILES);- let mut pos = off;- let n = read_uvarint(s, &mut pos) as usize;- let dwell0 = read_uvarint(s, &mut pos) as i64;- let mut out = Vec::with_capacity(n);- out.push((-dwell0, 0i64));- let mut prev_dep = 0i64;- for _ in 1..n {- let hop = read_uvarint(s, &mut pos) as i64;- let dwell = read_uvarint(s, &mut pos) as i64;- let arr = prev_dep + hop;- let dep = arr + dwell;- out.push((arr, dep));- prev_dep = dep;- }- out- }-- pub fn feed_name(&self, feed_idx: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_FEEDS), feed_idx as usize * 4))- }-- pub fn feed_tz(&self, feed_idx: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_FEED_TZ), feed_idx as usize * 4))- }-- pub fn feed_motis_prefix(&self, feed_idx: u32) -> String {- self.read_str(ru32(self.sec_bytes(SEC_FEED_MOTIS_PREFIX), feed_idx as usize * 4))- }-- pub fn service(&self, service_idx: u32) -> ServiceRec {- let s = self.sec_bytes(SEC_SERVICES);- let base = service_idx as usize * 12;- ServiceRec {- weekday_mask: s[base],- start_date: ru32(s, base + 4),- end_date: ru32(s, base + 8),- }- }-- /// `(service_idx, date, added)` exceptions for one service, via the CSR.- pub fn service_exceptions(&self, service_idx: u32) -> Vec<(u32, u32, u32)> {- let idx = self.sec_bytes(SEC_EXCEPTIONS_IDX);- let s = self.sec_bytes(SEC_EXCEPTIONS);- let lo = ru32(idx, service_idx as usize * 4) as usize;- let hi = ru32(idx, (service_idx as usize + 1) * 4) as usize;- (lo..hi).map(|i| (ru32(s, i * 12), ru32(s, i * 12 + 4), ru32(s, i * 12 + 8))).collect()- }-- /// `(route_idx, stop_pos)` pairs serving `stop`, via STOP_ROUTES(+_POS).- pub fn stop_routes(&self, stop: u32) -> Vec<(u32, u32)> {- let idx = self.sec_bytes(SEC_STOP_ROUTES_IDX);- let routes = self.sec_bytes(SEC_STOP_ROUTES);- let pos = self.sec_bytes(SEC_STOP_ROUTE_POS);- let lo = ru32(idx, stop as usize * 4) as usize;- let hi = ru32(idx, (stop as usize + 1) * 4) as usize;- (lo..hi).map(|i| (ru32(routes, i * 4), ru32(pos, i * 4))).collect()- }-- /// `(to_stop, secs)` footpaths from `stop`.- pub fn transfers(&self, stop: u32) -> Vec<(u32, u32)> {- let idx = self.sec_bytes(SEC_TRANSFERS_IDX);- let s = self.sec_bytes(SEC_TRANSFERS);- let lo = ru32(idx, stop as usize * 4) as usize;- let hi = ru32(idx, (stop as usize + 1) * 4) as usize;- (lo..hi).map(|i| (ru32(s, i * 8), ru32(s, i * 8 + 4))).collect()- }-- /// Every non-empty grid cell as `(cell_id, stops)`, in file order (which the- /// reader requires to be `cell_id`-ascending).- pub fn grid_cells(&self) -> Vec<(u32, Vec<u32>)> {- let ids = self.sec_bytes(SEC_GRID_CELL_IDS);- let offs = self.sec_bytes(SEC_GRID_CELL_OFF);- let stops = self.sec_bytes(SEC_GRID_STOPS);- (0..self.grid_cell_count() as usize)- .map(|c| {- let lo = ru32(offs, c * 4) as usize;- let hi = ru32(offs, (c + 1) * 4) as usize;- (ru32(ids, c * 4), (lo..hi).map(|k| ru32(stops, k * 4)).collect())- })- .collect()- }-- /// Byte offset of route `r`'s shape blob in SHAPE_COORDS, or `None`.- pub fn route_shape_off(&self, r: u32) -> Option<usize> {- let idx = self.sec_bytes(SEC_ROUTE_SHAPE_IDX);- let route_count = self.route_count() as usize;- assert_eq!(idx.len(), (route_count + 1) * 4, "ROUTE_SHAPE_IDX size");- let off = ru32(idx, r as usize * 4);- if off == NONE {- return None;- }- let bound = ru32(idx, route_count * 4) as usize;- assert_eq!(bound, self.sec_bytes(SEC_SHAPE_COORDS).len(), "ROUTE_SHAPE_IDX bound");- assert!(off as usize + 4 <= bound, "shape offset {off} out of SHAPE_COORDS");- Some(off as usize)- }-- /// Decode the whole polyline at byte offset `off` in SHAPE_COORDS.- pub fn shape_points(&self, off: usize) -> Vec<(i32, i32)> {- let s = self.sec_bytes(SEC_SHAPE_COORDS);- let n = ru32(s, off) as usize;- let mut pos = off + 4;- let (mut lat, mut lon) = (0i64, 0i64);- (0..n)- .map(|_| {- lat += zigzag(read_uvarint(s, &mut pos));- lon += zigzag(read_uvarint(s, &mut pos));- (lat as i32, lon as i32)- })- .collect()- }-- /// Vertex index for ROUTE_STOPS entry `i` ([`NONE`] when unshaped).- pub fn route_stop_shape(&self, i: u32) -> u32 {- ru32(self.sec_bytes(SEC_ROUTE_STOP_SHAPE), i as usize * 4)- }-- /// Nearest stop to `(lat, lon)` via the sparse spatial grid, searching ±1- /// cell exactly as the device does.- pub fn nearest(&self, lat: f64, lon: f64) -> Option<u32> {- let g = self.grid();- let lat_e7 = (lat * 1e7) as i64;- let lon_e7 = (lon * 1e7) as i64;- let row0 = ((lat_e7 - g.lat0_e7 as i64) / g.cell_e7 as i64).max(0);- let col0 = ((lon_e7 - g.lon0_e7 as i64) / g.cell_e7 as i64).max(0);- let ids = self.sec_bytes(SEC_GRID_CELL_IDS);- let offs = self.sec_bytes(SEC_GRID_CELL_OFF);- let stops = self.sec_bytes(SEC_GRID_STOPS);- let n_cells = ids.len() / 4;- let find = |cid: u32| -> Option<usize> {- let (mut lo, mut hi) = (0usize, n_cells);- while lo < hi {- let mid = (lo + hi) / 2;- let v = ru32(ids, mid * 4);- if v == cid {- return Some(mid);- } else if v < cid {- lo = mid + 1;- } else {- hi = mid;- }- }- None- };- let mut best = None;- let mut bestd = f64::MAX;- for dr in -1..=1 {- for dc in -1..=1 {- let r = row0 + dr;- let c = col0 + dc;- if r < 0 || c < 0 || c >= g.cols as i64 {- continue;- }- if let Some(ci) = find((r * g.cols as i64 + c) as u32) {- let s = ru32(offs, ci * 4) as usize;- let e = ru32(offs, (ci + 1) * 4) as usize;- for k in s..e {- let sid = ru32(stops, k * 4);- let (slat, slon) = self.stop_ll(sid);- let d = (slat - lat).powi(2) + (slon - lon).powi(2);- if d < bestd {- bestd = d;- best = Some(sid);- }- }- }- }- }- best- }-}+include!("reader_s1.rs");
scripts/maps/gtfs_ingest/src/reader_s1.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader_s1.rs b/scripts/maps/gtfs_ingest/src/reader_s1.rsnew file mode 100644index 0000000000..78746a9b64--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/reader_s1.rs@@ -0,0 +1,419 @@+impl Reader {+ /// Validate the header and index the section directory.+ pub fn new(buf: Vec<u8>) -> Result<Reader, String> {+ if buf.len() < HEADER_LEN {+ return Err(format!("pack is {} bytes, shorter than the header", buf.len()));+ }+ let magic = ru32(&buf, 0);+ if magic != MAGIC {+ return Err(format!("bad magic {magic:#x}"));+ }+ let version = ru32(&buf, 4);+ if !(VERSION_MIN..=VERSION).contains(&version) {+ return Err(format!("version {version} outside {VERSION_MIN}..={VERSION}"));+ }+ let count = ru32(&buf, 8) as usize;+ if count != SECTION_COUNT && count != SECTION_COUNT_V6 {+ return Err(format!("section_count {count}, expected {SECTION_COUNT}"));+ }+ if buf.len() < HEADER_LEN + count * 16 {+ return Err("pack is truncated inside the section directory".to_string());+ }+ let mut sec = Vec::with_capacity(count);+ for i in 0..count {+ let base = HEADER_LEN + i * 16;+ let off = ru64(&buf, base) as usize;+ let len = ru64(&buf, base + 8) as usize;+ match off.checked_add(len) {+ Some(end) if end <= buf.len() => {}+ _ => return Err(format!("section {i} at {off}+{len} runs past the file")),+ }+ sec.push((off, len));+ }+ Ok(Reader { buf, sec })+ }++ /// Read the pack at `path`.+ pub fn open(path: &std::path::Path) -> Result<Reader, String> {+ let buf =+ std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ Reader::new(buf)+ }++ /// Read the pack at `path`, but only the header, the directory and the listed sections.+ ///+ /// For a caller that needs a few hundred MB of a multi-GB pack: `transit_shapes --pack`+ /// reads three sections, and reading the whole 4.4 GB world pack first was most of its+ /// start-up. The buffer is still the file's full length, so every offset means what it+ /// does in [`open`](Self::open), and it is validated identically; the sections not listed+ /// read as zeros and must not be used. The zeroed buffer is allocated untouched, so the+ /// unread sections cost address space, not memory. Listed sections the pack does not have+ /// (a v6 pack has no RAIL_LINES) are skipped, for the accessors to report.+ pub fn open_sections(path: &std::path::Path, sections: &[usize]) -> Result<Reader, String> {+ use std::io::{Read, Seek, SeekFrom};+ let fail = |e: std::io::Error| format!("cannot read {}: {e}", path.display());+ let mut f = std::fs::File::open(path).map_err(fail)?;+ let len = f.metadata().map_err(fail)?.len() as usize;+ let mut buf = vec![0u8; len];+ // Header, then the directory it sizes. `new` re-checks both against the real length.+ let head = HEADER_LEN.min(len);+ f.read_exact(&mut buf[..head]).map_err(fail)?;+ if head == HEADER_LEN {+ let dir_end = (HEADER_LEN + ru32(&buf, 8) as usize * 16).min(len);+ f.read_exact(&mut buf[HEADER_LEN..dir_end]).map_err(fail)?;+ }+ let mut reader = Reader::new(buf)?;+ for &s in sections {+ let Some(&(off, l)) = reader.sec.get(s) else { continue };+ f.seek(SeekFrom::Start(off as u64)).map_err(fail)?;+ f.read_exact(&mut reader.buf[off..off + l]).map_err(fail)?;+ }+ Ok(reader)+ }++ /// The `idx`-th u32 of the header.+ fn hdr(&self, idx: usize) -> u32 {+ ru32(&self.buf, idx * 4)+ }++ pub fn version(&self) -> u32 {+ self.hdr(1)+ }+ pub fn section_count(&self) -> u32 {+ self.hdr(2)+ }+ pub fn stop_count(&self) -> u32 {+ self.hdr(3)+ }+ pub fn route_count(&self) -> u32 {+ self.hdr(4)+ }+ pub fn trip_count(&self) -> u32 {+ self.hdr(5)+ }+ pub fn service_count(&self) -> u32 {+ self.hdr(6)+ }+ pub fn profile_count(&self) -> u32 {+ self.hdr(7)+ }+ pub fn feed_count(&self) -> u32 {+ self.hdr(8)+ }+ pub fn grid_cell_count(&self) -> u32 {+ self.hdr(9)+ }+ /// The pack name the device falls back to.+ pub fn pack_name(&self) -> String {+ self.read_str(self.hdr(10))+ }+ /// `(min_lat_e7, min_lon_e7, max_lat_e7, max_lon_e7)`.+ pub fn bbox(&self) -> (i32, i32, i32, i32) {+ (self.hdr(11) as i32, self.hdr(12) as i32, self.hdr(13) as i32, self.hdr(14) as i32)+ }+ pub fn grid(&self) -> GridParams {+ GridParams {+ lat0_e7: self.hdr(15) as i32,+ lon0_e7: self.hdr(16) as i32,+ cell_e7: self.hdr(17),+ cols: self.hdr(18),+ rows: self.hdr(19),+ }+ }++ pub fn sec_bytes(&self, s: usize) -> &[u8] {+ let (o, l) = self.sec[s];+ &self.buf[o..o + l]+ }++ /// The NUL-terminated string at STRINGS offset `off`; "" for [`NONE`].+ pub fn read_str(&self, off: u32) -> String {+ if off == NONE {+ return String::new();+ }+ let s = self.sec_bytes(SEC_STRINGS);+ let start = off as usize;+ let mut n = 0;+ while start + n < s.len() && s[start + n] != 0 {+ n += 1;+ }+ String::from_utf8_lossy(&s[start..start + n]).into_owned()+ }++ /// `(lat, lon)` in degrees.+ pub fn stop_ll(&self, i: u32) -> (f64, f64) {+ let (lat, lon) = self.stop_ll_e7(i);+ (lat as f64 * 1e-7, lon as f64 * 1e-7)+ }++ pub fn stop_ll_e7(&self, i: u32) -> (i32, i32) {+ let s = self.sec_bytes(SEC_STOPS);+ let base = i as usize * 16;+ (ri32(s, base), ri32(s, base + 4))+ }++ pub fn stop_name(&self, i: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 8))+ }++ pub fn stop_code(&self, i: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 12))+ }++ /// The raw GTFS `stop_id` (v5 STOP_GTFS_ID).+ pub fn stop_gtfs_id(&self, i: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_STOP_GTFS_ID), i as usize * 4))+ }++ pub fn route(&self, r: u32) -> RouteRec {+ let s = self.sec_bytes(SEC_ROUTES);+ let base = r as usize * 32;+ RouteRec {+ name_off: ru32(s, base),+ color: ru32(s, base + 4),+ route_type: ru32(s, base + 8),+ feed_idx: ru32(s, base + 12),+ n_stops: ru32(s, base + 16),+ first_route_stop: ru32(s, base + 20),+ n_trips: ru32(s, base + 24),+ trips_off: ru32(s, base + 28),+ }+ }++ /// ROUTE_STOPS entry `i` (an absolute stop index).+ pub fn route_stop(&self, i: u32) -> u32 {+ ru32(self.sec_bytes(SEC_ROUTE_STOPS), i as usize * 4)+ }++ /// A route's stop pattern.+ pub fn route_stops(&self, rec: &RouteRec) -> Vec<u32> {+ (0..rec.n_stops).map(|p| self.route_stop(rec.first_route_stop + p)).collect()+ }++ /// Decode a route's varint trip block, in start-time order.+ pub fn route_trips(&self, rec: &RouteRec) -> Vec<TripRec> {+ let s = self.sec_bytes(SEC_ROUTE_TRIPS);+ let mut pos = rec.trips_off as usize;+ let mut prev = 0u32;+ let mut out = Vec::with_capacity(rec.n_trips as usize);+ for _ in 0..rec.n_trips {+ let start_time = prev + read_uvarint(s, &mut pos) as u32;+ out.push(TripRec {+ start_time,+ profile_id: read_uvarint(s, &mut pos) as u32,+ service_idx: read_uvarint(s, &mut pos) as u32,+ headsign_off: read_uvarint(s, &mut pos) as u32,+ });+ prev = start_time;+ }+ out+ }++ /// A route's trips read from v6's fixed-stride table instead of the varint stream.+ ///+ /// The point of the table is that a trip is addressable by index, so the device+ /// reader can stop decoding trips its scan never looks at. Here it serves a second+ /// purpose: it is an independent decoding of the same data, so+ /// [`Self::route_trips_strided`] and [`Self::route_trips`] disagreeing means the+ /// writer emitted two views that do not match.+ pub fn route_trips_strided(&self, route_idx: u32) -> Vec<TripRec> {+ let off = self.sec_bytes(SEC_ROUTE_TRIP_OFF);+ let recs = self.sec_bytes(SEC_ROUTE_TRIP_RECS);+ if (route_idx as usize + 2) * 4 > off.len() {+ return Vec::new();+ }+ let base = ru32(off, route_idx as usize * 4) as usize;+ let end = ru32(off, (route_idx as usize + 1) * 4) as usize;+ if end < base || end * TRIP_REC_BYTES > recs.len() {+ return Vec::new();+ }+ (base..end)+ .map(|i| {+ let at = i * TRIP_REC_BYTES;+ TripRec {+ start_time: ru32(recs, at),+ profile_id: ru32(recs, at + 4),+ service_idx: ru32(recs, at + 8),+ headsign_off: ru32(recs, at + 12),+ }+ })+ .collect()+ }++ /// Profile `pid` as per-stop `(arr, dep)` offsets relative to a trip's+ /// `start_time`. `arr[0]` is negative by the first dwell.+ pub fn profile(&self, pid: u32) -> Vec<(i64, i64)> {+ let idx = self.sec_bytes(SEC_PROFILES_IDX);+ let off = ru32(idx, pid as usize * 4) as usize;+ let s = self.sec_bytes(SEC_PROFILES);+ let mut pos = off;+ let n = read_uvarint(s, &mut pos) as usize;+ let dwell0 = read_uvarint(s, &mut pos) as i64;+ let mut out = Vec::with_capacity(n);+ out.push((-dwell0, 0i64));+ let mut prev_dep = 0i64;+ for _ in 1..n {+ let hop = read_uvarint(s, &mut pos) as i64;+ let dwell = read_uvarint(s, &mut pos) as i64;+ let arr = prev_dep + hop;+ let dep = arr + dwell;+ out.push((arr, dep));+ prev_dep = dep;+ }+ out+ }++ pub fn feed_name(&self, feed_idx: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_FEEDS), feed_idx as usize * 4))+ }++ pub fn feed_tz(&self, feed_idx: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_FEED_TZ), feed_idx as usize * 4))+ }++ pub fn feed_motis_prefix(&self, feed_idx: u32) -> String {+ self.read_str(ru32(self.sec_bytes(SEC_FEED_MOTIS_PREFIX), feed_idx as usize * 4))+ }++ pub fn service(&self, service_idx: u32) -> ServiceRec {+ let s = self.sec_bytes(SEC_SERVICES);+ let base = service_idx as usize * 12;+ ServiceRec {+ weekday_mask: s[base],+ start_date: ru32(s, base + 4),+ end_date: ru32(s, base + 8),+ }+ }++ /// `(service_idx, date, added)` exceptions for one service, via the CSR.+ pub fn service_exceptions(&self, service_idx: u32) -> Vec<(u32, u32, u32)> {+ let idx = self.sec_bytes(SEC_EXCEPTIONS_IDX);+ let s = self.sec_bytes(SEC_EXCEPTIONS);+ let lo = ru32(idx, service_idx as usize * 4) as usize;+ let hi = ru32(idx, (service_idx as usize + 1) * 4) as usize;+ (lo..hi).map(|i| (ru32(s, i * 12), ru32(s, i * 12 + 4), ru32(s, i * 12 + 8))).collect()+ }++ /// `(route_idx, stop_pos)` pairs serving `stop`, via STOP_ROUTES(+_POS).+ pub fn stop_routes(&self, stop: u32) -> Vec<(u32, u32)> {+ let idx = self.sec_bytes(SEC_STOP_ROUTES_IDX);+ let routes = self.sec_bytes(SEC_STOP_ROUTES);+ let pos = self.sec_bytes(SEC_STOP_ROUTE_POS);+ let lo = ru32(idx, stop as usize * 4) as usize;+ let hi = ru32(idx, (stop as usize + 1) * 4) as usize;+ (lo..hi).map(|i| (ru32(routes, i * 4), ru32(pos, i * 4))).collect()+ }++ /// `(to_stop, secs)` footpaths from `stop`.+ pub fn transfers(&self, stop: u32) -> Vec<(u32, u32)> {+ let idx = self.sec_bytes(SEC_TRANSFERS_IDX);+ let s = self.sec_bytes(SEC_TRANSFERS);+ let lo = ru32(idx, stop as usize * 4) as usize;+ let hi = ru32(idx, (stop as usize + 1) * 4) as usize;+ (lo..hi).map(|i| (ru32(s, i * 8), ru32(s, i * 8 + 4))).collect()+ }++ /// Every non-empty grid cell as `(cell_id, stops)`, in file order (which the+ /// reader requires to be `cell_id`-ascending).+ pub fn grid_cells(&self) -> Vec<(u32, Vec<u32>)> {+ let ids = self.sec_bytes(SEC_GRID_CELL_IDS);+ let offs = self.sec_bytes(SEC_GRID_CELL_OFF);+ let stops = self.sec_bytes(SEC_GRID_STOPS);+ (0..self.grid_cell_count() as usize)+ .map(|c| {+ let lo = ru32(offs, c * 4) as usize;+ let hi = ru32(offs, (c + 1) * 4) as usize;+ (ru32(ids, c * 4), (lo..hi).map(|k| ru32(stops, k * 4)).collect())+ })+ .collect()+ }++ /// Byte offset of route `r`'s shape blob in SHAPE_COORDS, or `None`.+ pub fn route_shape_off(&self, r: u32) -> Option<usize> {+ let idx = self.sec_bytes(SEC_ROUTE_SHAPE_IDX);+ let route_count = self.route_count() as usize;+ assert_eq!(idx.len(), (route_count + 1) * 4, "ROUTE_SHAPE_IDX size");+ let off = ru32(idx, r as usize * 4);+ if off == NONE {+ return None;+ }+ let bound = ru32(idx, route_count * 4) as usize;+ assert_eq!(bound, self.sec_bytes(SEC_SHAPE_COORDS).len(), "ROUTE_SHAPE_IDX bound");+ assert!(off as usize + 4 <= bound, "shape offset {off} out of SHAPE_COORDS");+ Some(off as usize)+ }++ /// Decode the whole polyline at byte offset `off` in SHAPE_COORDS.+ pub fn shape_points(&self, off: usize) -> Vec<(i32, i32)> {+ let s = self.sec_bytes(SEC_SHAPE_COORDS);+ let n = ru32(s, off) as usize;+ let mut pos = off + 4;+ let (mut lat, mut lon) = (0i64, 0i64);+ (0..n)+ .map(|_| {+ lat += zigzag(read_uvarint(s, &mut pos));+ lon += zigzag(read_uvarint(s, &mut pos));+ (lat as i32, lon as i32)+ })+ .collect()+ }++ /// Vertex index for ROUTE_STOPS entry `i` ([`NONE`] when unshaped).+ pub fn route_stop_shape(&self, i: u32) -> u32 {+ ru32(self.sec_bytes(SEC_ROUTE_STOP_SHAPE), i as usize * 4)+ }++ /// Nearest stop to `(lat, lon)` via the sparse spatial grid, searching ±1+ /// cell exactly as the device does.+ pub fn nearest(&self, lat: f64, lon: f64) -> Option<u32> {+ let g = self.grid();+ let lat_e7 = (lat * 1e7) as i64;+ let lon_e7 = (lon * 1e7) as i64;+ let row0 = ((lat_e7 - g.lat0_e7 as i64) / g.cell_e7 as i64).max(0);+ let col0 = ((lon_e7 - g.lon0_e7 as i64) / g.cell_e7 as i64).max(0);+ let ids = self.sec_bytes(SEC_GRID_CELL_IDS);+ let offs = self.sec_bytes(SEC_GRID_CELL_OFF);+ let stops = self.sec_bytes(SEC_GRID_STOPS);+ let n_cells = ids.len() / 4;+ let find = |cid: u32| -> Option<usize> {+ let (mut lo, mut hi) = (0usize, n_cells);+ while lo < hi {+ let mid = (lo + hi) / 2;+ let v = ru32(ids, mid * 4);+ if v == cid {+ return Some(mid);+ } else if v < cid {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ None+ };+ let mut best = None;+ let mut bestd = f64::MAX;+ for dr in -1..=1 {+ for dc in -1..=1 {+ let r = row0 + dr;+ let c = col0 + dc;+ if r < 0 || c < 0 || c >= g.cols as i64 {+ continue;+ }+ if let Some(ci) = find((r * g.cols as i64 + c) as u32) {+ let s = ru32(offs, ci * 4) as usize;+ let e = ru32(offs, (ci + 1) * 4) as usize;+ for k in s..e {+ let sid = ru32(stops, k * 4);+ let (slat, slon) = self.stop_ll(sid);+ let d = (slat - lat).powi(2) + (slon - lon).powi(2);+ if d < bestd {+ bestd = d;+ best = Some(sid);+ }+ }+ }+ }+ }+ best+ }+}