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

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

bundle_part4.rs439 lines · 20.7 KiBRaw
1#[cfg(test)]
2/// A straight line of `n` points, `metres` apart, running north from `(lat, lon)`.
3fn north(lat: f64, lon: f64, metres: f64, n: usize) -> Vec<(i32, i32)> {
4 let step = metres / 111_320.0 * 1e7;
5 (0..n).map(|i| (((lat * 1e7) + i as f64 * step) as i32, (lon * 1e7) as i32)).collect()
6}
7
8#[cfg(test)]
9/// The same line shifted `metres` east: a second track in one corridor.
10fn shifted(line: &[(i32, i32)], metres: f64) -> Vec<(i32, i32)> {
11 let cos_lat = (line[0].0 as f64 * 1e-7).to_radians().cos();
12 let d = (metres / (111_320.0 * cos_lat) * 1e7) as i32;
13 line.iter().map(|&(lat, lon)| (lat, lon + d)).collect()
14}
15
16#[cfg(test)]
17/// One line offered to [`assign`]: route, colour, name and geometry.
18type Fixture = (u32, u32, &'static str, Vec<(i32, i32)>);
19
20#[cfg(test)]
21fn candidates(lines: &[Fixture]) -> Vec<Candidate<'_>> {
22 lines
23 .iter()
24 .map(|(route, color, name, points)| Candidate {
25 points,
26 route: *route,
27 color: *color,
28 name,
29 })
30 .collect()
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 /// The lane inputs each candidate ends up with: the `(ordinal, count)` of the span
38 /// furthest into its lane, which is the one the tapers lead into.
39 fn lanes(spans: &[Vec<Span>]) -> Vec<(u8, u8)> {
40 spans
41 .iter()
42 .map(|s| {
43 s.iter()
44 .max_by_key(|span| (span.lanes, span.taper))
45 .map(|span| (span.ordinal, span.lanes))
46 .unwrap_or((0, 1))
47 })
48 .collect()
49 }
50
51 #[test]
52 fn a_route_running_alone_is_a_corridor_of_one() {
53 let line = north(37.7, -122.4, 1000.0, 20);
54 let lines = [(0u32, 0x00_54_A5u32, "N", line.clone())];
55 let spans = assign(&candidates(&lines));
56 assert_eq!(spans, vec![vec![Span { points: line, ordinal: 0, lanes: 1, taper: 255 }]]);
57 }
58
59 /// The corridor's colours get consecutive ordinals from zero and every member reports the
60 /// same count, which is all the renderer needs to centre the fan on the track.
61 #[test]
62 fn two_routes_on_one_track_take_the_two_ordinals_of_a_corridor_of_two() {
63 let a = north(37.7, -122.4, 1000.0, 20);
64 let b = shifted(&a, 8.0);
65 let lines = [(0u32, 0x00_00_FFu32, "A", a), (1, 0xFF_00_00, "B", b)];
66 let spans = assign(&candidates(&lines));
67 assert_eq!(lanes(&spans), vec![(0, 2), (1, 2)]);
68 }
69
70 /// A corridor of three is three ordinals of three, laid out across it: the west track
71 /// takes lane zero, because lane zero is the left of the reference's direction of travel
72 /// and this one runs north.
73 #[test]
74 fn three_routes_on_one_track_take_three_ordinals() {
75 let a = north(37.7, -122.4, 1000.0, 20);
76 let (b, c) = (shifted(&a, 8.0), shifted(&a, -8.0));
77 let lines =
78 [(0u32, 0x00_00_11u32, "A", a), (1, 0x00_00_22, "B", b), (2, 0x00_00_33, "C", c)];
79 let spans = assign(&candidates(&lines));
80 assert_eq!(lanes(&spans), vec![(1, 3), (2, 3), (0, 3)], "west to east");
81 }
82
83 /// THE defect this pass exists to fix: the members of a corridor draw the *same*
84 /// polyline at their own offsets, so they are exactly parallel and evenly spaced rather
85 /// than each being its own survey pushed sideways.
86 #[test]
87 fn the_members_of_a_corridor_all_draw_the_reference_geometry() {
88 let a = north(37.7, -122.4, 1000.0, 20);
89 let b = shifted(&a, 8.0);
90 let lines = [(0u32, 0x00_00_11u32, "A", a.clone()), (1, 0x00_00_22, "B", b)];
91 let spans = assign(&candidates(&lines));
92 assert_eq!(spans[0].len(), 1, "one corridor, one span");
93 assert_eq!(spans[1].len(), 1);
94 assert_eq!(spans[0][0].points, a, "the lower colour is the reference");
95 assert_eq!(spans[1][0].points, a, "and its corridor-mate draws it too");
96 }
97
98 /// The tie-break under the geometric order: two routes published on one identical survey
99 /// have the same offset everywhere, so there is no ground truth to recover and the order
100 /// falls to the colour and then the name — never the input order, or a feed reordering
101 /// its routes would move every line on the map.
102 #[test]
103 fn coincident_surveys_fall_back_to_colour_then_name() {
104 let track = north(37.7, -122.4, 1000.0, 20);
105 let lines = [(0u32, 0xFF_00_00u32, "Z", track.clone()), (1, 0x00_00_FF, "A", track)];
106 let spans = assign(&candidates(&lines));
107 // Route 1's colour is lower, so it takes the first ordinal despite being second in.
108 assert_eq!(lanes(&spans), vec![(1, 2), (0, 2)]);
109 }
110
111 /// The direction bucket is the whole reason a junction is not a corridor.
112 #[test]
113 fn two_tracks_crossing_at_a_junction_do_not_share_a_corridor() {
114 let north_south = north(37.7, -122.4, 1000.0, 20);
115 // Due east through the middle of it.
116 let mid = north_south[10];
117 let cos_lat = (mid.0 as f64 * 1e-7).to_radians().cos();
118 let step = (1000.0 / (111_320.0 * cos_lat) * 1e7) as i32;
119 let east_west: Vec<(i32, i32)> =
120 (0..20).map(|i| (mid.0, mid.1 + (i - 10) * step)).collect();
121 let lines = [(0u32, 0x11u32, "NS", north_south), (1, 0x22, "EW", east_west)];
122 let spans = assign(&candidates(&lines));
123 assert_eq!(lanes(&spans), vec![(0, 1), (0, 1)]);
124 }
125
126 /// The renderer's perpendicular is the polyline's own left-hand normal, so the side a
127 /// lane lands on depends on the direction the geometry is stored in. Every member of a
128 /// corridor stores the reference in the reference's own **canonical** direction, so
129 /// neither the direction a feed happened to publish a member in nor which member won the
130 /// reference tie-break can reach the output.
131 #[test]
132 fn the_direction_an_input_is_stored_in_does_not_reach_the_output() {
133 let a = north(37.7, -122.4, 1000.0, 20);
134 let b = shifted(&a, 8.0);
135 let flip = |line: &[(i32, i32)]| -> Vec<(i32, i32)> {
136 line.iter().rev().copied().collect()
137 };
138
139 let forward = [(0u32, 0x11u32, "A", a.clone()), (1, 0x22, "B", b.clone())];
140 let member = [(0u32, 0x11u32, "A", a.clone()), (1, 0x22, "B", flip(&b))];
141 assert_eq!(assign(&candidates(&forward)), assign(&candidates(&member)));
142 // And the reference itself, which is what the canonical fold is for: without it the
143 // whole fan mirrors and B lands on the far side of A.
144 let reference = [(0u32, 0x11u32, "A", flip(&a)), (1, 0x22, "B", b)];
145 assert_eq!(assign(&candidates(&forward)), assign(&candidates(&reference)));
146 }
147
148 /// The same, for a fixture that actually eases. An ease piece is cut from the member's
149 /// own survey and inherits whatever direction the feed stored that in, and `stroke::band`
150 /// takes its normal from the polyline's own direction — so a piece left the wrong way
151 /// round puts the member on the far side of the fan across the ease and nowhere else.
152 #[test]
153 fn an_ease_against_the_references_direction_does_not_mirror() {
154 let forward = a_shallow_merge();
155 let mut flipped = a_shallow_merge();
156 flipped[1].3.reverse();
157 let reference = corridor_of(&forward[0].3);
158
159 assert_eq!(lanes(&assign(&candidates(&forward))), lanes(&assign(&candidates(&flipped))));
160 for lines in [forward, flipped] {
161 let spans = assign(&candidates(&lines));
162 assert_eq!(
163 spans[1].iter().filter(|s| s.taper < 255).count(),
164 TAPER_STEPS,
165 "the fixture has to actually ease, or this proves nothing",
166 );
167 for candidate in &spans {
168 for span in candidate.iter().filter(|s| s.lanes > 1) {
169 let head = distance_along(&reference, span.points[0]);
170 let tail =
171 distance_along(&reference, span.points[span.points.len() - 1]);
172 assert!(head <= tail, "a piece stored against the reference: {span:?}");
173 }
174 }
175 }
176 }
177
178 /// The junction the merging fixtures meet at.
179 const JUNCTION: (f64, f64) = (37.70, -122.40);
180
181 /// A line approaching [`JUNCTION`] from `(east, north)` metres away and then running 4 km
182 /// north out of it, the whole thing shifted `side` metres east so several of them are one
183 /// corridor over the northbound stretch and separate groups on the way in.
184 fn joins_from(from: (f64, f64), side: f64) -> Vec<(i32, i32)> {
185 let cos_lat = JUNCTION.0.to_radians().cos();
186 let east = |m: f64| m / (111_320.0 * cos_lat) * 1e7;
187 let up = |m: f64| m / 111_320.0 * 1e7;
188 let (jy, jx) = (JUNCTION.0 * 1e7, JUNCTION.1 * 1e7 + east(side));
189 let steps = 20;
190 let mut line: Vec<(i32, i32)> = (0..steps)
191 .map(|i| {
192 let t = 1.0 - i as f64 / steps as f64;
193 ((jy + up(from.1 * t)) as i32, (jx + east(from.0 * t)) as i32)
194 })
195 .collect();
196 line.extend((0..=40).map(|i| ((jy + up(i as f64 * 100.0)) as i32, jx as i32)));
197 line
198 }
199
200 /// A line arriving from the south-west.
201 const FROM_WEST: (f64, f64) = (-1400.0, -1400.0);
202 /// A line arriving from the south-east.
203 const FROM_EAST: (f64, f64) = (1400.0, -1400.0);
204
205 /// THE defect this pass exists to fix. Two routes that merge and then run north together
206 /// keep the sides they arrived on: the one that came from the west stays west, whatever
207 /// its colour, because lane zero is the left of the reference's direction of travel.
208 #[test]
209 fn two_routes_merging_keep_the_sides_they_arrived_on() {
210 let lines = [
211 (0u32, 0x00_00_11u32, "E", joins_from(FROM_EAST, 8.0)),
212 (1, 0x00_00_22, "W", joins_from(FROM_WEST, 0.0)),
213 ];
214 let spans = assign(&candidates(&lines));
215 assert_eq!(lanes(&spans), vec![(1, 2), (0, 2)], "the western arrival takes lane 0");
216 }
217
218 /// Two pairs that each share a corridor and then all four share one: each pair stays
219 /// contiguous in the merged order and keeps its internal order, rather than the two
220 /// groups interleaving by colour value. The colours here run the other way to the
221 /// geometry, so ordering by colour would interleave them.
222 #[test]
223 fn two_groups_joining_keep_their_blocks() {
224 let lines = [
225 (0u32, 0x00_00_33u32, "P1", joins_from(FROM_WEST, 0.0)),
226 (1, 0x00_00_44, "P2", joins_from(FROM_WEST, 8.0)),
227 (2, 0x00_00_11, "Q1", joins_from(FROM_EAST, 16.0)),
228 (3, 0x00_00_22, "Q2", joins_from(FROM_EAST, 24.0)),
229 ];
230 let spans = assign(&candidates(&lines));
231 assert_eq!(lanes(&spans), vec![(0, 4), (1, 4), (2, 4), (3, 4)]);
232 }
233
234 /// A lone line joining a group lands on the outside of it, on the side it joined from,
235 /// rather than in the middle of a group it was never part of.
236 #[test]
237 fn a_lone_line_joining_a_group_lands_on_the_outside_of_it() {
238 let lines = [
239 (0u32, 0x00_00_22u32, "P1", joins_from(FROM_WEST, 0.0)),
240 (1, 0x00_00_33, "P2", joins_from(FROM_WEST, 8.0)),
241 (2, 0x00_00_11, "Lone", joins_from(FROM_EAST, 16.0)),
242 ];
243 let spans = assign(&candidates(&lines));
244 assert_eq!(lanes(&spans), vec![(0, 3), (1, 3), (2, 3)], "and not between the pair");
245 }
246
247 /// Two lines of one route — a trunk and a branch — are one member of the corridor and
248 /// take one lane, because the lane is per route and not per polyline.
249 #[test]
250 fn two_lines_of_one_route_share_its_lane() {
251 let trunk = north(37.7, -122.4, 1000.0, 20);
252 let branch = north(37.7, -122.4, 1000.0, 10);
253 let other = shifted(&trunk, 8.0);
254 let lines = [
255 (0u32, 0x11u32, "A", trunk.clone()),
256 (0, 0x11, "A", branch),
257 (1, 0x22, "B", other),
258 ];
259 let spans = assign(&candidates(&lines));
260 assert_eq!(lanes(&spans), vec![(0, 2), (0, 2), (1, 2)], "one route, one lane");
261 // And the reference is the *longer* of the two, or the trunk would be clipped to
262 // the branch that runs half of it.
263 assert_eq!(spans[2][0].points, trunk);
264 }
265
266 /// Two services of one colour — a feed publishing each direction as its own route —
267 /// take one lane, so they coincide exactly rather than drawing as two lines nothing
268 /// distinguishes.
269 #[test]
270 fn two_routes_of_one_colour_take_one_lane_and_coincide() {
271 let a = north(37.7, -122.4, 1000.0, 20);
272 let b: Vec<(i32, i32)> = shifted(&a, 8.0).iter().rev().copied().collect();
273 let lines = [(0u32, 0x11u32, "Yellow-N", a), (1, 0x11, "Yellow-S", b)];
274 let spans = assign(&candidates(&lines));
275 assert_eq!(lanes(&spans), vec![(0, 1), (0, 1)], "one colour is one lane");
276 assert_eq!(spans[0], spans[1], "so the two directions are the same line");
277 }
278
279 /// The lane is per corridor, not per route: a service that shares one track here and a
280 /// different one there takes its place in each. Carrying one lane for a whole route is
281 /// what left BART's five services on a sparse uneven subset across the bay.
282 #[test]
283 fn a_route_crossing_two_corridors_takes_a_lane_in_each() {
284 // The main line runs 6 km north. One route joins it for the first 2 km and another
285 // for the last 2 km, with 2 km to itself in between.
286 let main = north(37.70, -122.40, 100.0, 61);
287 let first = shifted(&north(37.70, -122.40, 100.0, 21), 8.0);
288 let last = shifted(&north(37.70 + 4000.0 / 111_320.0, -122.40, 100.0, 21), -8.0);
289 let lines = [
290 (0u32, 0x00_00_10u32, "Main", main),
291 (1, 0x00_00_20, "First", first),
292 (2, 0x00_00_05, "Last", last),
293 ];
294 let spans = assign(&candidates(&lines));
295 let places: Vec<(u8, u8)> = spans[0].iter().map(|s| (s.ordinal, s.lanes)).collect();
296 // West of the first corridor's partner and east of the second's, so it takes the
297 // west lane of one and the east lane of the other.
298 assert!(places.contains(&(0, 2)), "the first corridor's lower ordinal: {places:?}");
299 assert!(places.contains(&(1, 2)), "the second corridor's higher ordinal: {places:?}");
300 assert!(places.contains(&(0, 1)), "and its own track in between: {places:?}");
301 assert_eq!(lanes(&spans[1..2]), vec![(1, 2)], "the first corridor's higher ordinal");
302 assert_eq!(lanes(&spans[2..3]), vec![(0, 2)], "the second corridor's lower ordinal");
303 }
304
305 /// Nothing here caps the count: the style bounds how many lanes are drawn, so a corridor
306 /// of five reports five and every member gets its own ordinal.
307 #[test]
308 fn every_colour_of_a_corridor_gets_its_own_ordinal() {
309 let a = north(37.7, -122.4, 1000.0, 20);
310 // Within `CORRIDOR_M` end to end, or the outer two would be in corridors of their
311 // own rather than in one of five.
312 let lines: Vec<Fixture> = (0..5)
313 .map(|i| {
314 let colour = 0x10u32 + i;
315 let points = shifted(&a, (i as f64 - 2.0) * 6.0);
316 (i, colour, "X", points)
317 })
318 .collect();
319 let spans = assign(&candidates(&lines));
320 assert_eq!(lanes(&spans), vec![(0, 5), (1, 5), (2, 5), (3, 5), (4, 5)]);
321 }
322
323 /// THE case the corridor rule exists for: a radial network. Three services share a short
324 /// central subway and then run a long way alone, and the lane has to be taken where it
325 /// does some work rather than where the route spends its length.
326 #[test]
327 fn a_shared_trunk_gives_a_lane_and_the_run_alone_does_not() {
328 let lines = trunk_then_branches(2000.0, 3);
329 let spans = assign(&candidates(&lines));
330 // C leaves the trunk westward and A eastward, so they take the outer lanes and B,
331 // which carries straight on, takes the middle.
332 assert_eq!(lanes(&spans), vec![(2, 3), (1, 3), (0, 3)], "the shared trunk decides");
333 for candidate in &spans {
334 assert_eq!(
335 candidate.last().expect("a span").lanes,
336 1,
337 "and the long run alone stays on its own alignment",
338 );
339 }
340 }
341
342 /// The guard on that rule: two alignments that touch briefly leaving a station are not a
343 /// corridor, and fanning a route out on that evidence would move it off its own casing
344 /// for nothing.
345 #[test]
346 fn a_run_shorter_than_the_minimum_does_not_become_a_corridor() {
347 let lines = trunk_then_branches(100.0, 2);
348 let spans = assign(&candidates(&lines));
349 assert_eq!(lanes(&spans), vec![(0, 1), (0, 1)]);
350 for candidate in &spans {
351 assert_eq!(candidate.len(), 1, "and the route is not cut up over it");
352 }
353 }
354
355 /// A route stepping sideways by nine Dp at a corridor mouth reads as a break in the
356 /// line, so it eases in over a hundred metres or more instead.
357 #[test]
358 fn a_route_tapers_into_its_lane_at_the_end_of_a_corridor() {
359 let lines = trunk_then_branches(2000.0, 4);
360 let spans = assign(&candidates(&lines));
361 let pieces: Vec<(u8, u8, u8)> =
362 spans[0].iter().map(|s| (s.ordinal, s.lanes, s.taper)).collect();
363 assert_eq!(pieces[0], (3, 4, 255), "the east lane of four, fully in lane");
364 assert_eq!(
365 pieces.last().expect("a span").1,
366 1,
367 "and its own track at the far end",
368 );
369 let tapers: Vec<u8> = pieces.iter().filter(|p| p.1 == 4).map(|p| p.2).collect();
370 assert!(
371 tapers.windows(2).all(|w| w[0] >= w[1]),
372 "the taper only ever eases out of the lane: {tapers:?}",
373 );
374 assert!(pieces.len() >= 2 + TAPER_STEPS, "with a step per taper piece: {pieces:?}");
375 // The ramp is equal-stepped the whole way, including the jump between the last ease
376 // piece and the full lane of the body — there is no gap at either end of it.
377 let step = 255.0 / (TAPER_STEPS + 1) as f64;
378 for pair in tapers.windows(2) {
379 let jump = f64::from(pair[0]) - f64::from(pair[1]);
380 assert!((jump - step).abs() <= 1.0, "an uneven jump in the ease: {tapers:?}");
381 }
382 assert_eq!(
383 *tapers.last().expect("a taper"),
384 taper_fraction(1),
385 "and the far end of the ease is one step off the alignment: {tapers:?}",
386 );
387 }
388
389 /// A line in a lane on both sides of a run boundary steps from one lane to the other. It
390 /// has no alignment of its own to ease onto there, and tapering to nothing and back is
391 /// what collapsed every member of both corridors onto the centreline at the seam.
392 #[test]
393 fn two_abutting_corridors_do_not_taper_between_them() {
394 let spans = assign(&candidates(&back_to_back_corridors()));
395 for span in &spans[0] {
396 assert_eq!(
397 span.taper, 255,
398 "the through route dips out of its lane at the seam: {span:?}",
399 );
400 }
401 }
402
403 /// A member hands over to the reference where the two surveys are close enough that the
404 /// swap cannot be seen, not where they first count as one corridor. Two lines closing at
405 /// a shallow angle are one corridor thirty metres apart, and handing over there puts the
406 /// whole thirty metres into one sideways step at the mouth.
407 #[test]
408 fn a_shallow_approach_draws_its_own_track_until_it_is_close() {
409 let lines = a_shallow_merge();
410 let spans = assign(&candidates(&lines));
411 let reference = corridor_of(&lines[0].3);
412 let body = spans[1]
413 .iter()
414 .position(|s| s.lanes > 1 && s.taper == 255)
415 .expect("a corridor body");
416 let ease_from =
417 spans[1].iter().position(|s| s.lanes > 1).expect("a piece in the corridor");
418 assert!(ease_from < body, "the joining line eases in before it reaches the reference");
419 assert!(
420 nearest(&reference, spans[1][ease_from].points[0]).0 > SNAP_M,
421 "the ease starts on the member's own track, well off the reference",
422 );
423 // Adaptive: the ease stretches to reach the handover rather than being the fixed
424 // hundred metres a member that is already on the reference gets.
425 let eased: f64 = spans[1][..body]
426 .iter()
427 .filter(|span| span.lanes > 1)
428 .flat_map(|span| span.points.windows(2))
429 .map(|pair| distance_m(pair[0], pair[1]))
430 .sum();
431 assert!(eased > TAPER_M, "an ease of only {eased} m for a kilometre of convergence");
432 // The weld carries the body's first point onto the end of the ease, so the last step
433 // of the ease *is* the handover.
434 let ease = &spans[1][body - 1].points;
435 let step = distance_m(ease[ease.len() - 2], ease[ease.len() - 1]);
436 assert!(step <= SNAP_M, "a handover step of {step} m");
437 }
438
439}