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

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

bundle_part1.rs329 lines · 15.3 KiBRaw
1/// Absorb every run shorter than [`MIN_SHARED_M`] into a neighbour, longest neighbour first,
2/// and coalesce the neighbours that end up equal.
3///
4/// Without this a route drifting in and out of another's tolerance flips membership sample
5/// to sample and shatters into dozens of features, most of them a few metres long.
6fn smooth(runs: &mut Vec<Run>, cum: &[f64]) {
7 let length = |run: &Run| cum[run.to] - cum[run.from];
8 while runs.len() > 1 {
9 let Some(at) = (0..runs.len())
10 .filter(|&i| length(&runs[i]) < MIN_SHARED_M)
11 .min_by(|&a, &b| length(&runs[a]).total_cmp(&length(&runs[b])).then(a.cmp(&b)))
12 else {
13 break;
14 };
15 let into = match (at.checked_sub(1), runs.get(at + 1)) {
16 (None, _) => at + 1,
17 (Some(before), None) => before,
18 (Some(before), Some(after)) => {
19 if length(after) > length(&runs[before]) {
20 at + 1
21 } else {
22 before
23 }
24 }
25 };
26 if into < at {
27 runs[into].to = runs[at].to;
28 } else {
29 runs[into].from = runs[at].from;
30 }
31 runs.remove(at);
32 let mut i = 1;
33 while i < runs.len() {
34 if runs[i].set == runs[i - 1].set {
35 runs[i - 1].to = runs[i].to;
36 runs.remove(i);
37 } else {
38 i += 1;
39 }
40 }
41 }
42}
43
44/// Every membership that survived as a run of more than one route, with the geometry and the
45/// lane order its members share.
46///
47/// No transitive closure. Unioning the members of neighbouring corridors was tried and is
48/// badly wrong: BART shares Market Street with Muni Metro, Millbrae with Caltrain, Caltrain
49/// shares San Jose with Capitol Corridor and ACE, and following that chain collapsed the
50/// whole west-coast rail network into one corridor of twenty-three. A corridor is a local
51/// thing, and two routes that share one see the same local membership, so they agree on the
52/// reference and on the lane order without anything having to reconcile them.
53///
54/// Nor is there a corridor adjacency graph to propagate an order along. The order is read off
55/// the geometry at each corridor independently, from the members' own untouched surveys, and
56/// two abutting corridors agree because the ground does — the routes really are arranged that
57/// way at the seam.
58fn corridors_of(
59 candidates: &[Candidate],
60 sets: &[Vec<u32>],
61 runs: &[Vec<Run>],
62 named: &[Option<(u32, &str)>],
63 own_cum: &[Vec<f64>],
64 probe_cum: &[Vec<f64>],
65) -> BTreeMap<u32, Corridor> {
66 // Per corridor, each member run as the candidate it belongs to and where the run begins
67 // and ends along that candidate's own survey — which is what the approach is measured
68 // just outside of.
69 let mut members: BTreeMap<u32, Vec<(usize, f64, f64)>> = BTreeMap::new();
70 for (at, candidate_runs) in runs.iter().enumerate() {
71 for run in candidate_runs {
72 if sets[run.set as usize].len() > 1 {
73 members
74 .entry(run.set)
75 .or_default()
76 .push((at, probe_cum[at][run.from], probe_cum[at][run.to]));
77 }
78 }
79 }
80 let length = |at: usize| own_cum[at].last().copied().unwrap_or(0.0);
81 // Every corridor projects every member onto the reference geometry, so the work is members
82 // times reference length per corridor, and on a world set that ran for the better part of
83 // an hour on one core.
84 //
85 // Each corridor is an independent pure function of read-only shared state — it reads
86 // `candidates`, `sets`, `named` and `own_cum` and writes only its own entry — so the loop
87 // spreads across the machine with no coordination beyond handing out indices. Results go
88 // into a `BTreeMap` keyed by set id, which is ordered by key rather than by insertion, so
89 // the output is byte-identical however the threads interleave.
90 let entries: Vec<(u32, Vec<(usize, f64, f64)>)> = members.into_iter().collect();
91 let total = entries.len();
92 let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
93 let next = AtomicUsize::new(0);
94 let finished = AtomicUsize::new(0);
95 let collected: Mutex<Vec<(u32, Corridor)>> = Mutex::new(Vec::with_capacity(total));
96 std::thread::scope(|scope| {
97 for _ in 0..threads.min(total.max(1)) {
98 scope.spawn(|| {
99 // Accumulated per thread and merged once at the end: locking per corridor
100 // would serialise the very loop this is spreading out.
101 let mut local: Vec<(u32, Corridor)> = Vec::new();
102 loop {
103 let i = next.fetch_add(1, AtomicOrdering::Relaxed);
104 if i >= total {
105 break;
106 }
107 let (set, in_corridor) = &entries[i];
108 local.push((
109 *set,
110 one_corridor(*set, in_corridor, candidates, sets, named, own_cum, &length),
111 ));
112 // Redrawn on a count, not a percentage: the threads finish out of order, so
113 // "the whole number changed" is not a thing any one of them can see.
114 let n = finished.fetch_add(1, AtomicOrdering::Relaxed) + 1;
115 if n % 128 == 0 {
116 eprint!(
117 "\r{:<28} [{:>3}%] {total} corridor(s)",
118 "Corridor order",
119 n * 100 / total.max(1)
120 );
121 }
122 }
123 collected.lock().expect("corridor pool").extend(local);
124 });
125 }
126 });
127 eprintln!("\r{:<28} [100%] {total} corridor(s)", "Corridor order");
128 collected.into_inner().expect("corridor pool").into_iter().collect()
129}
130
131/// One corridor's reference geometry and the order its colours sit in across it.
132///
133/// Split out of [`corridors_of`] so the loop there can run on every core: this reads only
134/// shared immutable state and returns an owned value, which is what makes that safe.
135#[allow(clippy::too_many_arguments)]
136fn one_corridor(
137 set: u32,
138 in_corridor: &[(usize, f64, f64)],
139 candidates: &[Candidate],
140 sets: &[Vec<u32>],
141 named: &[Option<(u32, &str)>],
142 own_cum: &[Vec<f64>],
143 length: &dyn Fn(usize) -> f64,
144) -> Corridor {
145 {
146 {
147 // Whose geometry the corridor draws — and only that. It no longer decides the
148 // direction, which is canonical, nor the order, which is the approaches. The
149 // first member by colour and then name, so it does not move when a feed reorders
150 // its routes. Between two polylines of that one member — a trunk and the
151 // short-turn that runs half of it — the longer, because a shorter reference clips
152 // every other member to itself.
153 let pick = in_corridor
154 .iter()
155 .map(|&(at, _, _)| at)
156 .reduce(|a, b| {
157 let better = match (candidates[a].color, candidates[a].name)
158 .cmp(&(candidates[b].color, candidates[b].name))
159 {
160 Ordering::Less => true,
161 Ordering::Greater => false,
162 Ordering::Equal => match length(b).total_cmp(&length(a)) {
163 Ordering::Less => true,
164 Ordering::Greater => false,
165 Ordering::Equal => candidates[a].points <= candidates[b].points,
166 },
167 };
168 if better {
169 a
170 } else {
171 b
172 }
173 })
174 .expect("a corridor has at least one member");
175 let points = canonical(candidates[pick].points);
176 let cum = cumulative(&points);
177 let reference = Corridor { points, cum, colours: Vec::new() };
178
179 // Where each member sits across the corridor, averaged over the colour: two
180 // routes of one colour share a lane, so they share one place in the order.
181 // Measured against the corridor's own stretch of the reference, which is every
182 // member's run projected onto it.
183 let projected = |at: usize, along: f64| {
184 distance_along(&reference, point_at(candidates[at].points, &own_cum[at], along))
185 };
186 let extent = in_corridor.iter().fold(
187 (f64::INFINITY, f64::NEG_INFINITY),
188 |(lo, hi), &(at, from, to)| {
189 let (a, b) = (projected(at, from), projected(at, to));
190 (lo.min(a).min(b), hi.max(a).max(b))
191 },
192 );
193 // Less a taper at each end. A run boundary is only located to a sample step, so
194 // the extent bleeds a little past the mouth — and one segment past the mouth the
195 // reference has left the corridor too and is heading wherever it goes next, which
196 // is not an axis to measure anyone's side against.
197 let margin = TAPER_M.min((extent.1 - extent.0) / 4.0);
198 let extent = (extent.0 + margin, extent.1 - margin);
199 let mut sides: BTreeMap<u32, (f64, u32)> = BTreeMap::new();
200 for &(at, from, to) in in_corridor {
201 let side = approach_offset(
202 &reference,
203 extent,
204 candidates[at].points,
205 &own_cum[at],
206 from,
207 to,
208 );
209 let seen = sides.entry(candidates[at].color).or_insert((0.0, 0));
210 seen.0 += side;
211 seen.1 += 1;
212 }
213 // A route can be in the membership without having a run of its own here, in which
214 // case it draws nothing in this corridor and there is no approach to measure. It
215 // still occupies a colour, so it still takes a place: the reference's own, zero.
216 let mut ordered: Vec<(f64, u32, &str)> = sets[set as usize]
217 .iter()
218 .map(|&member| {
219 let (colour, name) = named[member as usize].unwrap_or((0, ""));
220 let side = sides
221 .get(&colour)
222 .map(|&(sum, n)| sum / f64::from(n))
223 .unwrap_or(0.0);
224 (side, colour, name)
225 })
226 .collect();
227 // Ascending offset is ascending ordinal, because `lane_offset_px` gives ordinal
228 // zero the most negative offset and a negative offset is the left of the
229 // reference's travel. The `(colour, name)` tail is the tie-break for two surveys
230 // that genuinely coincide, and is what keeps a rebuild byte-identical.
231 ordered.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(b.2)));
232 let mut colours: Vec<u32> = ordered.into_iter().map(|(_, c, _)| c).collect();
233 colours.dedup();
234 Corridor { colours, ..reference }
235 }
236 }
237}
238
239/// Fold a polyline into a fixed half-plane: northward, or exactly east-west and eastward.
240///
241/// The lane side is measured along the reference, so the direction the reference is stored in
242/// mirrors the whole fan. Inheriting it from whichever member won the name tie-break means a
243/// lower-coloured route joining at a junction can flip the arrangement of everyone else.
244/// Abutting corridors run roughly parallel where they meet, so folding both by their own
245/// first-to-last chord makes them fold the same way and the fan does not mirror across the
246/// seam. The same idea as [`COS_FOLD`]'s fold to `[0, 180)`, applied to a whole polyline.
247fn canonical(points: &[(i32, i32)]) -> Vec<(i32, i32)> {
248 let (Some(first), Some(last)) = (points.first(), points.last()) else {
249 return points.to_vec();
250 };
251 // Signs only, so the longitude scaling that would make these metres cannot change the
252 // answer and is not worth doing.
253 let (north, east) = (last.0 - first.0, last.1 - first.1);
254 if north < 0 || (north == 0 && east < 0) {
255 points.iter().rev().copied().collect()
256 } else {
257 points.to_vec()
258 }
259}
260
261/// Which side of the corridor one member arrives on, in metres, positive to the right of the
262/// reference's direction of travel.
263///
264/// The **approach** — the stretch of the member's own untouched survey immediately before it
265/// enters the corridor — rather than the shared stretch, where every member is within a
266/// couple of metres of the reference and the sign is noise. A run that starts at the line's
267/// own start has no approach and uses the departure instead; one that is the whole line has
268/// neither, and falls back to the mean across the run, which is weaker but still correct.
269fn approach_offset(
270 corridor: &Corridor,
271 extent: (f64, f64),
272 points: &[(i32, i32)],
273 own_cum: &[f64],
274 from: f64,
275 to: f64,
276) -> f64 {
277 let total = own_cum.last().copied().unwrap_or(0.0);
278 let (lo, hi) = if from <= to { (from, to) } else { (to, from) };
279 let (a, b) = if lo > 0.0 {
280 ((lo - APPROACH_M).max(0.0), lo)
281 } else if hi < total {
282 (hi, (hi + APPROACH_M).min(total))
283 } else {
284 (lo, hi)
285 };
286 let mut sum = 0.0;
287 for k in 0..APPROACH_SAMPLES {
288 let t = k as f64 / (APPROACH_SAMPLES - 1) as f64;
289 sum += signed_offset(corridor, extent, point_at(points, own_cum, a + (b - a) * t));
290 }
291 sum / APPROACH_SAMPLES as f64
292}
293
294/// The taper fraction of step `step` of [`TAPER_STEPS`], climbing toward but never reaching
295/// 255 — the full lane belongs to the corridor span the taper leads into.
296fn taper_fraction(step: usize) -> u8 {
297 (255.0 * step as f64 / (TAPER_STEPS + 1) as f64).round() as u8
298}
299
300/// Where a run begins and ends on the ground, as `(entry, exit)` in the candidate's own
301/// order of travel.
302type Bounds = ((i32, i32), (i32, i32));
303
304/// Where one run of a candidate is drawn, decided for every run before any of it is emitted.
305///
306/// A run has to know whether its *neighbours* are on a corridor to know whether to ease into
307/// its lane, so the placement is a pass of its own. Testing `corridors.contains_key` at the
308/// neighbour is not enough: a run whose two ends project to one place on the reference draws
309/// its own geometry despite being a corridor set, and easing against that would leave a step.
310struct Placement<'a> {
311 corridor: &'a Corridor,
312 /// Whether the candidate travels in the reference's direction over this run.
313 forward: bool,
314 /// The run's extent along the reference.
315 lo: f64,
316 hi: f64,
317 /// The first and last of the run's samples within [`SNAP_M`] of the reference, as indices
318 /// into the candidate's own block of samples. `None` where it never comes that close, in
319 /// which case it keeps its own survey across the whole run — fanned, but not exactly
320 /// parallel, which it was never going to be honestly at that separation.
321 snap: Option<(usize, usize)>,
322}
323
324/// The points a run begins and ends at, which is what the runs either side have to reach.
325fn bounds_of(pieces: &[Span]) -> Option<Bounds> {
326 let entry = *pieces.first()?.points.first()?;
327 let exit = *pieces.last()?.points.last()?;
328 Some((entry, exit))
329}