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

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

bundle_part5.rs392 lines · 17.6 KiBRaw
1#[cfg(test)]
2/// A 6 km line, shared with one route over its first half and another over its second,
3/// on opposite sides of it, so the lane it takes really does have to change at the seam.
4fn back_to_back_corridors() -> Vec<Fixture> {
5 vec![
6 (0u32, 0x00_00_10u32, "Main", north(37.70, -122.40, 100.0, 61)),
7 (1, 0x00_00_20, "First", shifted(&north(37.70, -122.40, 100.0, 31), 8.0)),
8 (
9 2,
10 0x00_00_05,
11 "Last",
12 shifted(&north(37.70 + 3000.0 / 111_320.0, -122.40, 100.0, 31), -8.0),
13 ),
14 ]
15}
16
17#[cfg(test)]
18/// Two lines closing at a shallow angle: one runs 4 km north, the other comes in from a
19/// hundred metres west over the first kilometre of it and then runs alongside. They are
20/// one corridor from wherever they first come within [`CORRIDOR_M`], which is a long way
21/// before either could draw the other's geometry without it showing.
22fn a_shallow_merge() -> Vec<Fixture> {
23 let main = north(37.70, -122.40, 100.0, 41);
24 let cos_lat = 37.70_f64.to_radians().cos();
25 let east = |m: f64| (m / (111_320.0 * cos_lat) * 1e7) as i32;
26 let joining: Vec<(i32, i32)> = main
27 .iter()
28 .enumerate()
29 .map(|(i, &(lat, lon))| {
30 let closed = (i as f64 * 100.0 / 1000.0).min(1.0);
31 (lat, lon + east(8.0 - 108.0 * (1.0 - closed)))
32 })
33 .collect();
34 vec![(0u32, 0x00_00_10u32, "Main", main), (1, 0x00_00_20, "Join", joining)]
35}
36
37#[cfg(test)]
38/// The corridor a polyline would be the reference of, for measuring the output against.
39fn corridor_of(points: &[(i32, i32)]) -> Corridor {
40 let points = canonical(points);
41 let cum = cumulative(&points);
42 Corridor::new(points, cum, Vec::new())
43}
44
45#[cfg(test)]
46/// `n` services sharing `metres` of trunk running north and then leaving it in
47/// different directions for 20 km.
48fn trunk_then_branches(metres: f64, n: usize) -> Vec<Fixture> {
49 let steps = (metres / 100.0).round() as usize + 1;
50 let trunk = north(37.70, -122.40, 100.0, steps);
51 let top = *trunk.last().expect("a trunk");
52 let cos_lat = (top.0 as f64 * 1e-7).to_radians().cos();
53 let east = |m: f64| (m / (111_320.0 * cos_lat) * 1e7) as i32;
54 let up = |m: f64| (m / 111_320.0 * 1e7) as i32;
55 let branch = |dx: f64, dy: f64| -> Vec<(i32, i32)> {
56 let mut line = trunk.clone();
57 for i in 1..=200 {
58 line.push((top.0 + up(dy * i as f64), top.1 + east(dx * i as f64)));
59 }
60 line
61 };
62 let away = [(100.0, 0.0), (0.0, 100.0), (-100.0, 0.0), (70.0, 70.0)];
63 let names = ["A", "B", "C", "D"];
64 (0..n)
65 .map(|i| {
66 let (dx, dy) = away[i];
67 (i as u32, 0x11u32 * (i as u32 + 1), names[i], branch(dx, dy))
68 })
69 .collect()
70}
71
72#[cfg(test)]
73mod tests_continued {
74 use super::*;
75
76 /// The pieces of one route meet: the span before a corridor is carried across to the
77 /// point on the reference the corridor span begins at, and so is the ease across to the
78 /// body it leads into.
79 #[test]
80 fn the_spans_of_one_route_share_their_boundary_vertex() {
81 for lines in
82 [trunk_then_branches(2000.0, 4), back_to_back_corridors(), a_shallow_merge()]
83 {
84 let spans = assign(&candidates(&lines));
85 for candidate in &spans {
86 for pair in candidate.windows(2) {
87 assert_eq!(
88 pair[0].points.last(),
89 pair[1].points.first(),
90 "a gap between two spans of one route",
91 );
92 }
93 }
94 }
95 }
96
97 /// A route can step straight out of one corridor and into the next, with nothing of its
98 /// own in between and two different references either side of the seam.
99 #[test]
100 fn a_route_passing_from_one_corridor_into_the_next_changes_lane_where_they_meet() {
101 let spans = assign(&candidates(&back_to_back_corridors()));
102 let places: Vec<(u8, u8)> = spans[0].iter().map(|s| (s.ordinal, s.lanes)).collect();
103 assert!(places.contains(&(0, 2)), "the first corridor's lower ordinal: {places:?}");
104 assert!(places.contains(&(1, 2)), "the second corridor's higher ordinal: {places:?}");
105 assert!(
106 !places.iter().any(|p| p.1 == 1),
107 "and no stretch of its own between them: {places:?}",
108 );
109 }
110
111 /// A 6 km line, shared with one route over its first half and another over its second,
112 /// on opposite sides of it, so the lane it takes really does have to change at the seam.
113 fn back_to_back_corridors() -> Vec<Fixture> {
114 vec![
115 (0u32, 0x00_00_10u32, "Main", north(37.70, -122.40, 100.0, 61)),
116 (1, 0x00_00_20, "First", shifted(&north(37.70, -122.40, 100.0, 31), 8.0)),
117 (
118 2,
119 0x00_00_05,
120 "Last",
121 shifted(&north(37.70 + 3000.0 / 111_320.0, -122.40, 100.0, 31), -8.0),
122 ),
123 ]
124 }
125
126 /// Two lines closing at a shallow angle: one runs 4 km north, the other comes in from a
127 /// hundred metres west over the first kilometre of it and then runs alongside. They are
128 /// one corridor from wherever they first come within [`CORRIDOR_M`], which is a long way
129 /// before either could draw the other's geometry without it showing.
130 fn a_shallow_merge() -> Vec<Fixture> {
131 let main = north(37.70, -122.40, 100.0, 41);
132 let cos_lat = 37.70_f64.to_radians().cos();
133 let east = |m: f64| (m / (111_320.0 * cos_lat) * 1e7) as i32;
134 let joining: Vec<(i32, i32)> = main
135 .iter()
136 .enumerate()
137 .map(|(i, &(lat, lon))| {
138 let closed = (i as f64 * 100.0 / 1000.0).min(1.0);
139 (lat, lon + east(8.0 - 108.0 * (1.0 - closed)))
140 })
141 .collect();
142 vec![(0u32, 0x00_00_10u32, "Main", main), (1, 0x00_00_20, "Join", joining)]
143 }
144
145 /// `n` services sharing `metres` of trunk running north and then leaving it in
146 /// different directions for 20 km.
147 fn trunk_then_branches(metres: f64, n: usize) -> Vec<Fixture> {
148 let steps = (metres / 100.0).round() as usize + 1;
149 let trunk = north(37.70, -122.40, 100.0, steps);
150 let top = *trunk.last().expect("a trunk");
151 let cos_lat = (top.0 as f64 * 1e-7).to_radians().cos();
152 let east = |m: f64| (m / (111_320.0 * cos_lat) * 1e7) as i32;
153 let up = |m: f64| (m / 111_320.0 * 1e7) as i32;
154 let branch = |dx: f64, dy: f64| -> Vec<(i32, i32)> {
155 let mut line = trunk.clone();
156 for i in 1..=200 {
157 line.push((top.0 + up(dy * i as f64), top.1 + east(dx * i as f64)));
158 }
159 line
160 };
161 let away = [(100.0, 0.0), (0.0, 100.0), (-100.0, 0.0), (70.0, 70.0)];
162 let names = ["A", "B", "C", "D"];
163 (0..n)
164 .map(|i| {
165 let (dx, dy) = away[i];
166 (i as u32, 0x11u32 * (i as u32 + 1), names[i], branch(dx, dy))
167 })
168 .collect()
169 }
170
171 /// A second copy of a line adds nothing to the map, whichever way round it is drawn.
172 /// THE case: a feed publishes each direction of a service as its own shape, and a
173 /// regional feed republishes the lot re-surveyed a few metres off.
174 #[test]
175 fn track_already_drawn_is_not_carried_again() {
176 let line = north(37.7, -122.4, 100.0, 60);
177 let mut covered = Covered::default();
178 assert!(!covered.contains(&line), "the first copy is all new");
179 covered.add(&line);
180 assert!(covered.contains(&line), "the same line again");
181 let reversed: Vec<(i32, i32)> = line.iter().rev().copied().collect();
182 assert!(covered.contains(&reversed), "the other direction");
183 assert!(covered.contains(&shifted(&line, 9.0)), "the adjacent track");
184 // A short-turn lies on its parent for its whole length, so it adds nothing either.
185 assert!(covered.contains(&north(37.7, -122.4, 100.0, 30)), "a short-turn");
186 }
187
188 /// How many distinct services already draw over a stretch of track.
189 ///
190 /// The colour-scoped gates let two services share a track on purpose, and that is right for a
191 /// city. On a planet one alignment is republished by a city feed, the regional feed containing
192 /// it and a national feed on top, each under its own colour, and every one of them claims a
193 /// lane — which is what draws one railway as fifteen jagged parallel lines.
194 #[test]
195 fn crowd_counts_the_distinct_services_over_a_track() {
196 let line = north(37.7, -122.4, 100.0, 60);
197 let mut covered = Covered::default();
198 assert_eq!(covered.crowd(&line), 0, "empty track carries nobody");
199
200 covered.add_tagged(&line, 0xE31E24);
201 assert_eq!(covered.crowd(&line), 1);
202 // A second service on the same track is real and must be counted, not merged.
203 covered.add_tagged(&line, 0x0054A5);
204 assert_eq!(covered.crowd(&line), 2);
205 // The same service again is not a third.
206 covered.add_tagged(&line, 0xE31E24);
207 assert_eq!(covered.crowd(&line), 2, "one service counted twice");
208 // Slightly off, still the same corridor.
209 covered.add_tagged(&shifted(&line, 9.0), 0x00A650);
210 assert_eq!(covered.crowd(&line), 3, "a re-survey a few metres off is the same track");
211 // Track nobody has drawn is uncrowded however busy its neighbour is.
212 assert_eq!(covered.crowd(&north(37.9, -122.9, 100.0, 60)), 0, "elsewhere");
213 }
214
215 /// The worst point along the line, not the average: a branch joining a busy trunk for part of
216 /// its length is exactly the line worth suppressing.
217 #[test]
218 fn crowd_reports_the_busiest_point_not_the_whole_line() {
219 let trunk = north(37.7, -122.4, 100.0, 30);
220 let longer = north(37.7, -122.4, 100.0, 60);
221 let mut covered = Covered::default();
222 for colour in [1u32, 2, 3] {
223 covered.add_tagged(&trunk, colour);
224 }
225 assert_eq!(
226 covered.crowd(&longer),
227 3,
228 "a line overlapping a crowded trunk for half its length is crowded"
229 );
230 }
231
232 /// A re-publication that runs a little further is still a duplicate of the part it shares.
233 ///
234 /// The case that drew the LA A line as two strands a metre apart: two feeds publish the same
235 /// alignment at slightly different lengths, the longer one "adds new track" at one end, and an
236 /// all-or-nothing rule therefore keeps it whole — duplicating everything they share. Each copy
237 /// then gets its own corridor lane and taper, so one line reads as two that diverge and
238 /// reconverge.
239 #[test]
240 fn a_longer_republication_of_the_same_track_is_mostly_drawn() {
241 let short = north(37.7, -122.4, 100.0, 60);
242 let long = north(37.7, -122.4, 100.0, 63);
243 let mut covered = Covered::default();
244 covered.add(&short);
245 assert!(!covered.contains(&long), "it does add a little new track at the end");
246 let fraction = covered.covered_fraction(&long);
247 assert!(fraction > 0.9, "but nearly all of it is already drawn: {fraction}");
248 assert!(fraction < 1.0, "and not quite all");
249 }
250
251 /// A branch is not a duplicate. Half shared, half genuinely new track, so it must survive
252 /// whatever threshold the duplicate test uses.
253 #[test]
254 fn a_route_that_branches_away_is_not_mostly_drawn() {
255 let trunk = north(37.7, -122.4, 100.0, 60);
256 let mut covered = Covered::default();
257 covered.add(&trunk);
258 // Same start, then off to its own alignment well outside the corridor.
259 let mut branch: Vec<(i32, i32)> = trunk[..30].to_vec();
260 branch.extend(shifted(&north(37.72, -122.4, 100.0, 30), 500.0));
261 let fraction = covered.covered_fraction(&branch);
262 assert!(fraction < 0.9, "half of it is new track: {fraction}");
263 }
264
265 /// Survey noise is not new track. Two agencies' surveys of one track disagree by a few
266 /// metres, and a wobble inside the tolerance must not resurrect a duplicate line.
267 #[test]
268 fn a_wobble_inside_the_tolerance_is_the_same_track() {
269 let straight = north(37.7, -122.4, 100.0, 60);
270 let mut covered = Covered::default();
271 covered.add(&straight);
272 let cos_lat = (straight[0].0 as f64 * 1e-7).to_radians().cos();
273 let east = |m: f64| (m / (111_320.0 * cos_lat) * 1e7) as i32;
274 let wobbled: Vec<(i32, i32)> = straight
275 .iter()
276 .enumerate()
277 .map(|(i, &(lat, lon))| (lat, lon + east(if i % 2 == 0 { 9.0 } else { -9.0 })))
278 .collect();
279 assert!(covered.contains(&wobbled), "9 m of survey drift is the same track");
280 }
281
282 /// A branch adds track, so it is carried **whole** rather than trimmed to the part that
283 /// diverges. Trimming was tried and is wrong: it leaves a route in fragments, and a
284 /// stretch too short to be worth emitting leaves a hole that nothing else draws. The
285 /// trunk it shares is over-drawn in its own colour at its own offset, which is invisible.
286 #[test]
287 fn a_branch_adds_track_and_is_carried_whole() {
288 let trunk = north(37.7, -122.4, 100.0, 60);
289 let mut covered = Covered::default();
290 covered.add(&trunk);
291 let mut branch = north(37.7, -122.4, 100.0, 30);
292 let split_at = *branch.last().unwrap();
293 let cos_lat = (split_at.0 as f64 * 1e-7).to_radians().cos();
294 for i in 1..=20 {
295 branch.push((
296 split_at.0,
297 split_at.1 + (i as f64 * 100.0 / (111_320.0 * cos_lat) * 1e7) as i32,
298 ));
299 }
300 assert!(!covered.contains(&branch), "it leaves the trunk, so it is not redundant");
301 }
302
303 #[test]
304 fn a_different_alignment_is_all_new_track() {
305 let line = north(37.7, -122.4, 100.0, 60);
306 let mut covered = Covered::default();
307 covered.add(&line);
308 assert!(!covered.contains(&shifted(&line, 1000.0)));
309 }
310
311 #[test]
312 fn a_line_with_fewer_than_two_points_covers_nothing() {
313 let line = north(37.7, -122.4, 100.0, 10);
314 let covered = Covered::default();
315 assert!(!covered.contains(&line[..1]));
316 assert!(!covered.contains(&[]));
317 }
318
319 /// The two halves of the slicing primitive: measuring along a polyline and cutting it
320 /// between two of those measurements, with both ends landing exactly on the line.
321 #[test]
322 fn a_slice_of_a_polyline_lands_exactly_on_it_at_both_ends() {
323 let line = north(37.7, -122.4, 100.0, 11);
324 let cum = cumulative(&line);
325 assert!((cum[10] - 1000.0).abs() < 1.0, "{cum:?}");
326 assert_eq!(slice_between(&line, &cum, 0.0, cum[10]), line, "the whole thing");
327 let middle = slice_between(&line, &cum, 250.0, 750.0);
328 assert_eq!(middle.len(), 7, "both cut ends plus the five vertices between");
329 assert!(distance_m(middle[0], line[2]) < 60.0, "a quarter of the way along");
330 // Two adjacent slices meet exactly, which is what keeps a route's pieces joined.
331 let before = slice_between(&line, &cum, 0.0, 250.0);
332 assert_eq!(before.last(), middle.first());
333 // Nothing between the two distances is nothing at all.
334 assert!(slice_between(&line, &cum, 400.0, 400.0).is_empty());
335 }
336
337 #[test]
338 fn nothing_in_nothing_out() {
339 assert!(assign(&[]).is_empty());
340 }
341
342 /// The block-pruned [`nearest`] and [`within`] against the plain walk of every segment they
343 /// replaced, over long, kinked, self-approaching references and probes near and far —
344 /// including probes exactly on a vertex, where several segments tie.
345 #[test]
346 fn pruned_nearest_is_the_full_walk_exactly() {
347 let full = |c: &Corridor, p: (i32, i32)| -> (f64, f64) {
348 let mut best = (f64::INFINITY, 0.0f64);
349 for at in 0..c.points.len().saturating_sub(1) {
350 let (t, offset) = project(p, c.points[at], c.points[at + 1], 0.0);
351 if offset < best.0 {
352 best = (offset, c.cum[at] + t * (c.cum[at + 1] - c.cum[at]));
353 }
354 }
355 best
356 };
357 let mut x = 0x9E37_79B9_7F4A_7C15u64;
358 let mut next = move || {
359 x ^= x << 13;
360 x ^= x >> 7;
361 x ^= x << 17;
362 x
363 };
364 for case in 0..40 {
365 let n = [2usize, 3, 33, 64, 65, 500, 3000][case % 7];
366 let (mut lat, mut lon) = (600_000_000i32 - (next() % 1_200_000_000) as i32, (next() % 1_000_000_000) as i32);
367 let mut points = vec![(lat, lon)];
368 for _ in 1..n {
369 // Mostly onward, sometimes doubling back, so distant segments come close.
370 lat += (next() % 20_001) as i32 - 6_000;
371 lon += (next() % 20_001) as i32 - 10_000;
372 points.push((lat, lon));
373 }
374 let c = Corridor::new(points.clone(), cumulative(&points), Vec::new());
375 for probe in 0..200 {
376 let base = points[(next() % points.len() as u64) as usize];
377 let p = if probe % 10 == 0 {
378 base
379 } else {
380 let r = [50i32, 500, 5_000, 200_000][probe % 4];
381 (base.0 + (next() % (2 * r as u64 + 1)) as i32 - r, base.1 + (next() % (2 * r as u64 + 1)) as i32 - r)
382 };
383 let (want, got) = (full(&c, p), nearest(&c, p));
384 assert_eq!(want.0.to_bits(), got.0.to_bits(), "distance, case {case} probe {probe}");
385 assert_eq!(want.1.to_bits(), got.1.to_bits(), "along, case {case} probe {probe}");
386 for radius in [SNAP_M, CORRIDOR_M, 0.0] {
387 assert_eq!(within(&c, p, radius), want.0 <= radius, "case {case} probe {probe} r {radius}");
388 }
389 }
390 }
391 }
392}