Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bundle.rs

bundle.rs500 lines · 24.1 KiBRaw
1//! Which routes share a corridor, and which parallel lane each one takes through it.
2//!
3//! Where several services run over one physical track — six Muni Metro lines through the
4//! Market Street subway, BART and Caltrain sharing an alignment — every route's polyline
5//! lies on top of every other's and only one colour is visible. The standard transit-map
6//! treatment is to fan them out into parallel coloured lines, and this decides which line
7//! goes where.
8//!
9//! # Why here and not in the tiler or the renderer
10//!
11//! "Which routes share this corridor" is a global property of the feed set. The tiler sees
12//! features one tile at a time and the renderer sees one tile at a time in arbitrary order,
13//! so either would have to decide it per tile — which is exactly what puts a jog in every
14//! route at every tile seam. It is decided once, here, and travels with the feature.
15//!
16//! # What comes out
17//!
18//! An ordered list of [`Span`]s per candidate, each a polyline and the inputs to a lane
19//! choice. A route that shares nothing is one span: its own geometry, ordinal zero of one.
20//! A route that runs through a corridor is cut at the corridor's ends, and the part inside
21//! draws the **corridor's own reference polyline** rather than its own survey. That is what
22//! makes the members of a corridor exactly parallel and evenly spaced: two agencies' surveys
23//! of one track differ by a metre or two, which is a large fraction of the gap between lanes.
24//!
25//! The lane itself is *not* decided here. A span carries the colour's ordinal among the
26//! corridor's distinct colours and how many of those there are, and the renderer turns that
27//! into an offset — because how many lanes a corridor draws depends on the camera zoom, which
28//! nothing here has. A taper travels alongside as a 0–255 fraction of whatever that offset
29//! turns out to be, so a route eases into its lane instead of stepping sideways onto it. The
30//! ease is drawn on the route's *own* survey, and only where the route arrives from its own
31//! alignment: between two corridors it is in a lane on both sides and steps from one to the
32//! other.
33//!
34//! # How
35//!
36//! Every candidate is resampled at [`SAMPLE_M`] and its samples are dropped into a spatial
37//! grid — the sorted flat `Vec<(cell, id)>` [`crate::index`] uses for footpath transfers,
38//! not a `HashMap` of buckets. For each sample, the routes with a sample within
39//! [`CORRIDOR_M`] *running parallel to it* are that sample's local membership.
40//!
41//! A candidate's samples are then cut into maximal **runs** of equal membership. Runs, not
42//! one membership per route: a route takes its lane from the corridor it is in *here*, so a
43//! service that shares Market Street with nine others and the Bay Bridge with four takes a
44//! lane in each. Picking one membership for a whole route was the previous rule, and it is
45//! what left BART's five services on `-5, -3, +3, +7, +9` across the bay — slots assigned
46//! for Market Street and carried where they meant nothing.
47//!
48//! Membership flickers sample to sample wherever a route drifts in and out of another's
49//! tolerance, so runs shorter than [`MIN_SHARED_M`] are merged into their neighbour until
50//! none are left. That threshold already existed for exactly this judgement: two alignments
51//! that touch for fifty metres leaving a station are not a corridor.
52//!
53//! Parallelism is what keeps two tracks crossing at a junction from reading as a corridor:
54//! bearings are compared folded to `[0, 180)`, so opposite directions over one track count
55//! as parallel and a crossing does not.
56//!
57//! # Which lane is which
58//!
59//! The order across a corridor is the order its members arrive in, so a line never crosses
60//! its neighbours where corridor membership changes. Each member's side is read off the
61//! stretch of its own untouched survey immediately outside the corridor mouth — its
62//! **approach** — where two routes that then run over one identical alignment are still tens
63//! of metres apart and the sign is unambiguous. Inside the corridor they are within a metre
64//! or two of the reference and the sign is survey noise.
65//!
66//! Nothing propagates an order between corridors. It is read off the geometry at each one
67//! independently, and abutting corridors agree because the ground does.
68//!
69//! Nothing here may depend on `HashMap` iteration order — the exporter's output has to be
70//! byte-identical between runs — so every collection that feeds a decision is a sorted
71//! vector or a `BTreeMap`.
72
73use crate::shapes::{distance_m, project, resample};
74use crate::timing::PhaseTimer;
75use rayon::prelude::*;
76use std::cmp::Ordering;
77use std::collections::BTreeMap;
78use std::ops::Range;
79use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
80use std::sync::Mutex;
81
82/// Two polylines closer than this everywhere are the same line, and two tracks closer than
83/// this are one corridor.
84///
85/// Well above the few metres two agencies' surveys of one track disagree by, and well below
86/// `shapes.rs`' `MAX_STOP_OFFSET_M` (150 m), which is a shape belonging to another pattern.
87pub const CORRIDOR_M: f64 = 30.0;
88
89/// How close a member's own survey has to come to the reference before it stops drawing its
90/// own track and hands over to the corridor's.
91///
92/// The other half of the judgement [`CORRIDOR_M`] makes, which the two shared until now: 30 m
93/// is "these two tracks are one corridor", and this is "they are close enough that drawing
94/// one on the other's geometry cannot be seen". Two lines closing at a shallow angle become
95/// one corridor while still 30 m apart, and handing over there puts the whole 30 m into a
96/// single sideways step at the mouth. Above the metre or two two agencies' surveys of one
97/// track disagree by, and well below [`CORRIDOR_M`].
98const SNAP_M: f64 = 8.0;
99
100/// Spacing of the probe samples along a polyline.
101///
102/// Small enough that two parallel tracks are compared point-to-point rather than
103/// point-to-segment without the along-track offset mattering: half a step is 5 m against a
104/// 30 m radius.
105const SAMPLE_M: f64 = 10.0;
106
107/// Grid cell in metres, just above the search radius so a probe never has to scan more than
108/// the nine cells around it. The sizing rule [`crate::index`]'s transfer grid uses.
109const CELL_M: f64 = 40.0;
110
111/// How much track two routes have to share before it counts as a corridor.
112///
113/// Also the smoothing window on the runs. Membership flips sample to sample wherever a
114/// route grazes another's tolerance, and cutting on every flip would shatter a route into
115/// dozens of features; a run shorter than this is absorbed into its neighbour instead.
116/// Three hundred metres is well above a station throat and well below any shared trunk
117/// worth drawing.
118const MIN_SHARED_M: f64 = 300.0;
119
120/// Cosine of the angle within which two bearings count as parallel (25°).
121///
122/// Compared on `|u · v|`, so the fold to `[0, 180)` is free: two routes over one track
123/// stored in opposite directions are parallel, two tracks crossing at a junction are not.
124const COS_FOLD: f64 = 0.906_307_787;
125
126/// The shortest ease a member spends coming into its lane, and the whole of it where the
127/// member is already on the reference when its run begins.
128///
129/// Without it a route steps sideways by up to nine Dp at the corridor mouth, which reads as
130/// a break in the line rather than as a fan opening. Where the member converges slowly the
131/// ease is longer than this: it runs from the mouth to wherever the survey first comes within
132/// [`SNAP_M`].
133const TAPER_M: f64 = 100.0;
134
135/// Features in one taper. The taper travels as a 0–255 fraction of the full lane offset, so
136/// the step count is only how many pieces the ease is cut into — and, because the fraction is
137/// an equal-step ramp, how big the jump between two of them is. Eight puts every jump at
138/// 255/9, about 1 Dp at a 9 Dp offset.
139const TAPER_STEPS: usize = 8;
140
141/// How much of a member's own survey, immediately outside the corridor mouth, decides which
142/// side of the corridor it takes.
143///
144/// Across the shared stretch two routes on one track sit within a couple of metres of the
145/// reference and the sign of that is survey noise. On the approach they are still diverging,
146/// and the sign is what separates "came from the north" from "came from the south". Above
147/// [`TAPER_M`] so it clears the ease-in, and below [`MIN_SHARED_M`] so it cannot reach back
148/// into the body of the corridor before.
149const APPROACH_M: f64 = 150.0;
150
151/// Points sampled along the approach. The mean of a handful, because one point lands wherever
152/// the survey's own vertices happen to fall.
153const APPROACH_SAMPLES: usize = 8;
154
155/// One route's polyline, offered for slotting.
156pub struct Candidate<'a> {
157 pub points: &'a [(i32, i32)],
158 /// Which route this polyline belongs to. Two polylines of one route — a branch and its
159 /// trunk — count as one member of a corridor, because the lane is per route and not per
160 /// line.
161 pub route: u32,
162 /// `0xRRGGBB`. The lane is per colour, and the colour is the tie-break on the order
163 /// within a corridor when two surveys genuinely coincide.
164 pub color: u32,
165 /// The route's display name. The second half of that tie-break, so a rebuild puts the
166 /// same route in the same lane.
167 pub name: &'a str,
168}
169
170/// One stretch of a candidate as it should be drawn.
171#[derive(Clone, Debug, PartialEq, Eq)]
172pub struct Span {
173 /// The polyline to emit. The candidate's own geometry outside a corridor and across the
174 /// ease into one, and the corridor's reference geometry over the body.
175 pub points: Vec<(i32, i32)>,
176 /// This colour's index among the corridor's distinct colours, from zero. Zero outside a
177 /// corridor.
178 ///
179 /// The order is **positional**: the colours are laid out across the corridor in the order
180 /// their routes arrive at it, so two groups that merge do not interleave and nothing
181 /// crosses. Zero is the left-hand side of the reference's direction of travel.
182 ///
183 /// The index is over the distinct **colours** of the corridor, not its routes. Two routes
184 /// of one colour are indistinguishable once drawn, so giving them a lane each spends width
185 /// on a difference nobody can see — and it is what doubles a network whose feed publishes
186 /// each direction as its own route (BART's `Yellow-N` and `Yellow-S`) or splits one
187 /// service into branch variants. Sharing a lane makes them coincide exactly, because they
188 /// are also drawing the same reference geometry.
189 pub ordinal: u8,
190 /// How many distinct colours the corridor carries. One outside a corridor.
191 ///
192 /// Unclamped: how many lanes to actually draw is the renderer's decision, because it
193 /// depends on the camera zoom and the exporter has no zoom.
194 pub lanes: u8,
195 /// How far into its lane this piece sits, over 255. 255 outside a corridor and on a
196 /// corridor's body; less only across a taper at its mouth.
197 pub taper: u8,
198}
199
200/// Cut every candidate into spans and give each one its lane. One list out per candidate in,
201/// in the same order, never empty.
202pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> {
203 assign_with_timer(candidates, None)
204}
205
206/// [`assign`], ticking the gapless timer through the corridor stages — one
207/// switch per stage (`corridor-probe`, `corridor-spans`, `corridor-order`,
208/// `corridor-cut`), never one entry per sample. `None` skips the ticks, which
209/// is what [`assign`] and the unit tests drive.
210pub fn assign_with_timer(
211 candidates: &[Candidate],
212 mut timer: Option<&mut PhaseTimer>,
213) -> Vec<Vec<Span>> {
214 if candidates.is_empty() {
215 return Vec::new();
216 }
217 // One switch per corridor stage, matching the four stderr meters below.
218 // The timer ticks here on the orchestrating thread only; the worker
219 // threads inside never touch it.
220 tick(&mut timer, "corridor-probe");
221 let route_count = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0);
222 let (samples, blocks) = sample_all(candidates);
223 let grid = Grid::build(&samples);
224
225 // Local membership per sample, interned: distinct sets are few even on a world feed set,
226 // and holding one `Vec<u32>` per sample is what would not fit.
227 let mut sets: Vec<Vec<u32>> = Vec::new();
228 let mut set_ids: BTreeMap<Vec<u32>, u32> = BTreeMap::new();
229 let mut per_sample: Vec<u32> = Vec::with_capacity(samples.len());
230
231 // The probe is the whole cost of a large run — one per 10 m of every line, 287 million of
232 // them on a world feed set — and it ran on one core for the better part of an hour.
233 //
234 // It splits in two. Finding which routes are near a sample is a pure read of the grid, so
235 // that part goes wide: the samples are cut into one contiguous range per core and each
236 // thread writes its answers into its own flat buffer. Interning those answers into set ids
237 // cannot go wide, because an id is assigned on first sight and the ids have to come out in
238 // sample order or every downstream lane moves. So the threads hand back their buffers in
239 // range order and the interning walks them sequentially — cheap, since it is `BTreeMap`
240 // lookups over an answer already computed.
241 //
242 // Flat `(values, ends)` buffers rather than `Vec<Vec<u32>>`: 287 million heap allocations
243 // is its own kind of slow, and the whole point of interning is not to hold that many
244 // vectors at once.
245 let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
246 let span = samples.len().div_ceil(threads.max(1)).max(1);
247 let probed = AtomicUsize::new(0);
248 let parts: Mutex<Vec<(usize, Vec<u32>, Vec<u32>)>> = Mutex::new(Vec::new());
249 {
250 let grid = &grid;
251 let samples = &samples;
252 let parts = &parts;
253 let probed = &probed;
254 let total = samples.len();
255 std::thread::scope(|scope| {
256 for t in 0..threads {
257 let lo = t * span;
258 if lo >= total {
259 break;
260 }
261 let hi = ((t + 1) * span).min(total);
262 scope.spawn(move || {
263 // Per thread, so the stamp trick in `routes_near` needs no sharing: a
264 // stamp only has to be unique against this thread's own array.
265 let mut seen: Vec<u32> = vec![0; route_count];
266 let mut stamp: u32 = 0;
267 let mut near: Vec<u32> = Vec::new();
268 let mut values: Vec<u32> = Vec::new();
269 let mut ends: Vec<u32> = Vec::with_capacity(hi - lo);
270 for (i, sample) in samples[lo..hi].iter().enumerate() {
271 stamp += 1;
272 grid.routes_near(samples, sample, &mut near, &mut seen, stamp);
273 values.extend_from_slice(&near);
274 ends.push(values.len() as u32);
275 // Batched, because an atomic per probe would cost more than the probe.
276 if i % 65_536 == 0 {
277 let n = probed.fetch_add(65_536, AtomicOrdering::Relaxed) + 65_536;
278 eprint!(
279 "\r{:<28} [{:>3}%] {total} sample(s)",
280 "Corridor probe",
281 (n * 100 / total.max(1)).min(100)
282 );
283 }
284 }
285 parts.lock().expect("probe pool").push((t, values, ends));
286 });
287 }
288 });
289 }
290 eprintln!("\r{:<28} [100%] {} sample(s)", "Corridor probe", samples.len());
291 // The runs cutting below is spans work, not probe work.
292 tick(&mut timer, "corridor-spans");
293
294 // Back in sample order, then interned sequentially: first-seen order is what fixes the ids.
295 let mut parts = parts.into_inner().expect("probe pool");
296 parts.sort_unstable_by_key(|(t, _, _)| *t);
297 for (_, values, ends) in &parts {
298 let mut start = 0usize;
299 for &end in ends {
300 let near = &values[start..end as usize];
301 start = end as usize;
302 let id = match set_ids.get(near) {
303 Some(id) => *id,
304 None => {
305 let id = sets.len() as u32;
306 sets.push(near.to_vec());
307 set_ids.insert(near.to_vec(), id);
308 id
309 }
310 };
311 per_sample.push(id);
312 }
313 }
314 drop(parts);
315
316 // Distance along each candidate, for its own geometry and for its probes. `resample`
317 // walks *along* the polyline, so probe `k` is exactly `k * SAMPLE_M` along it and the
318 // last one is its end. Summing the chords between probes instead would fall short of
319 // that wherever the alignment curves, and the drift accumulates over a route's length
320 // until the last run is cut short of the line's own end.
321 let own_cum: Vec<Vec<f64>> = candidates.iter().map(|c| cumulative(c.points)).collect();
322 let probe_cum: Vec<Vec<f64>> = blocks
323 .iter()
324 .zip(&own_cum)
325 .map(|(block, own)| {
326 let total = own.last().copied().unwrap_or(0.0);
327 let count = block.len();
328 (0..count)
329 .map(|k| if k + 1 == count { total } else { (k as f64 * SAMPLE_M).min(total) })
330 .collect()
331 })
332 .collect();
333
334 let runs: Vec<Vec<Run>> = blocks
335 .iter()
336 .zip(&probe_cum)
337 .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum))
338 .collect();
339
340 let mut named: Vec<Option<(u32, &str)>> = vec![None; route_count];
341 for candidate in candidates {
342 named[candidate.route as usize].get_or_insert((candidate.color, candidate.name));
343 }
344
345 // Named too: on a large set the work after the probe loop is still minutes, and without a
346 // line here the run goes silent again the moment the bar reaches 100%.
347 eprintln!("{:<28} {} candidate(s)", "Corridor spans", candidates.len());
348 tick(&mut timer, "corridor-order");
349 let corridors = corridors_of(candidates, &sets, &runs, &named, &own_cum, &probe_cum);
350
351 if std::env::var_os("TRANSIT_BUNDLE_DEBUG").is_some() {
352 for (set, corridor) in &corridors {
353 let members = &sets[*set as usize];
354 eprintln!(
355 "corridor of {} over {} colour(s): {}",
356 members.len(),
357 corridor.colours.len(),
358 members
359 .iter()
360 .map(|&m| {
361 let (colour, name) = named[m as usize].unwrap_or((0, ""));
362 format!("{name}/{colour:06X}")
363 })
364 .collect::<Vec<String>>()
365 .join(" "),
366 );
367 }
368 }
369
370 // The last phase, and per candidate independent: each one cuts its own runs against
371 // corridors it only reads. Left sequential it was the tail that made a world set look
372 // hung again after the corridor bar hit 100%.
373 //
374 // Handed out one candidate at a time rather than in equal contiguous ranges, because the
375 // cost per candidate is wildly uneven — a transcontinental line carries orders of magnitude
376 // more runs than a tram loop. Splitting the range evenly gave whichever thread drew the
377 // long-distance rail all the work and left the rest idle: a world set sat at 98% on one
378 // core for ten minutes with sixty-three threads finished. Sample probes are uniform enough
379 // for a range split; candidates are not.
380 // The cut below is its own stage: close the order subphase first.
381 tick(&mut timer, "corridor-cut");
382 let total = candidates.len();
383 // Largest-first dispatch (longest-processing-time scheduling): hand out the heaviest
384 // candidates first so the one transcontinental line overlaps with all the small work
385 // instead of being picked last and grinding alone on one core at the end (the 99%
386 // straggler). Cost is proxied by run count -- the same "orders of magnitude more runs"
387 // the note above names. Output is unaffected: each result carries its candidate index and
388 // the parts are re-sorted by it below, so dispatch order never reaches the archive.
389 let order: Vec<usize> = {
390 let mut o: Vec<usize> = (0..total).collect();
391 o.sort_unstable_by_key(|&i| std::cmp::Reverse(runs[i].len()));
392 o
393 };
394 let cut_next = AtomicUsize::new(0);
395 let cut_done = AtomicUsize::new(0);
396 let cut_parts: Mutex<Vec<(usize, Vec<Span>)>> = Mutex::new(Vec::with_capacity(total));
397 {
398 let corridors = &corridors;
399 let cut_parts = &cut_parts;
400 let cut_done = &cut_done;
401 let cut_next = &cut_next;
402 let samples = &samples;
403 let runs = &runs;
404 let blocks = &blocks;
405 let probe_cum = &probe_cum;
406 let own_cum = &own_cum;
407 let order = &order;
408 std::thread::scope(|scope| {
409 for _ in 0..threads.min(total.max(1)) {
410 scope.spawn(move || {
411 let mut local: Vec<(usize, Vec<Span>)> = Vec::new();
412 loop {
413 let slot = cut_next.fetch_add(1, AtomicOrdering::Relaxed);
414 if slot >= total {
415 break;
416 }
417 let at = order[slot];
418 local.push((
419 at,
420 spans_of(
421 &candidates[at],
422 &runs[at],
423 &samples[blocks[at].clone()],
424 &probe_cum[at],
425 &own_cum[at],
426 corridors,
427 ),
428 ));
429 let n = cut_done.fetch_add(1, AtomicOrdering::Relaxed) + 1;
430 if n % 64 == 0 {
431 eprint!(
432 "\r{:<28} [{:>3}%] {total} line(s)",
433 "Corridor cut",
434 n * 100 / total.max(1)
435 );
436 }
437 }
438 cut_parts.lock().expect("cut pool").extend(local);
439 });
440 }
441 });
442 }
443 eprintln!("\r{:<28} [100%] {total} line(s)", "Corridor cut");
444 let mut cut_parts = cut_parts.into_inner().expect("cut pool");
445 cut_parts.sort_unstable_by_key(|(at, _)| *at);
446 cut_parts.into_iter().map(|(_, spans)| spans).collect()
447}
448
449/// One gapless tick, skipped when the caller passed `None`.
450///
451/// The timer lives on the orchestrating thread only, and every call site is
452/// sequential code between the parallel loops, so worker threads never touch
453/// it — the coarse loop/pass boundaries are the ticks.
454fn tick(timer: &mut Option<&mut PhaseTimer>, name: &str) {
455 if let Some(t) = timer {
456 t.switch(name);
457 }
458}
459
460/// A maximal stretch of one candidate's samples holding the same membership, as inclusive
461/// indices into that candidate's own block of samples.
462struct Run {
463 from: usize,
464 to: usize,
465 set: u32,
466}
467
468/// A shared corridor: the geometry every member of it draws, and the lane order.
469struct Corridor {
470 /// One member's polyline, folded into the canonical direction, which the whole corridor
471 /// draws slices of. Owned rather than borrowed because the fold may reverse it.
472 points: Vec<(i32, i32)>,
473 cum: Vec<f64>,
474 /// The corridor's distinct colours, ordered across it: the first is the left-hand side of
475 /// the reference's direction of travel, which is the side [`Span::ordinal`] zero draws on.
476 colours: Vec<u32>,
477}
478
479/// Cut a candidate's samples into runs of constant membership, then smooth away the ones too
480/// short to be a corridor.
481fn cut_runs(per_sample: &[u32], cum: &[f64]) -> Vec<Run> {
482 let Some(&first) = per_sample.first() else { return Vec::new() };
483 let mut runs = vec![Run { from: 0, to: 0, set: first }];
484 for (at, &set) in per_sample.iter().enumerate().skip(1) {
485 let last = runs.last_mut().expect("seeded above");
486 if last.set == set {
487 last.to = at;
488 } else {
489 runs.push(Run { from: at, to: at, set });
490 }
491 }
492 smooth(&mut runs, cum);
493 runs
494}
495
496include!("bundle_part1.rs");
497include!("bundle_part2.rs");
498include!("bundle_part3.rs");
499include!("bundle_part4.rs");
500include!("bundle_part5.rs");