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

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

shapes.rs456 lines · 17.2 KiBRaw
1//! Fitting GTFS `shapes.txt` geometry to a RAPTOR route's stop pattern, for the
2//! v4 `SHAPE_COORDS` / `ROUTE_SHAPE_IDX` / `ROUTE_STOP_SHAPE` sections.
3//!
4//! A ride leg has to draw the path the vehicle actually takes, and the device
5//! slices that path by *vertex index* for the boarded span. So a fitted shape is
6//! a polyline plus one vertex index per pattern stop, and those indices must be
7//! non-decreasing or the slice is meaningless.
8//!
9//! Two things make that work:
10//! * each stop's projection onto the shape is **inserted as a vertex**, so a
11//! boarded span begins and ends exactly at its stop rather than at whichever
12//! shape point happened to be nearest;
13//! * the shape is trimmed to `[first stop, last stop]`, dropping the deadhead
14//! prologue/epilogue no ride leg can reach.
15//!
16//! Every `shapes.txt` point in between is kept: the pack is the build's source of
17//! truth for transit geometry, so it is stored at full resolution.
18//!
19//! `shape_dist_traveled` is used only to *order* — to pick which segment a stop
20//! belongs to, which is what disambiguates a loop route that passes a stop
21//! twice. Its units are feed-defined (km, mi, ft, ...) and are never read as
22//! metres.
23
24use crate::gtfs::Shape;
25
26/// How far a stop may sit
27/// How far a stop may sit from the shape before the fit is rejected. A genuine
28/// mismatch (shape belonging to another pattern, swapped lat/lon) blows past
29/// this; ordinary stop-to-kerb offsets do not.
30const MAX_STOP_OFFSET_M: f64 = 150.0;
31
32/// A shape fitted to one route's stop pattern.
33pub struct FittedShape {
34 /// The polyline to store, as `(lat_e7, lon_e7)`.
35 pub points: Vec<(i32, i32)>,
36 /// Vertex index in `points` for each pattern stop; non-decreasing.
37 pub stop_vertices: Vec<u32>,
38}
39
40/// Nearest point on segment `a`-`b` to `p`, with the parameter forced to at
41/// least `t_min`. Returns `(t, distance in metres)`. Local equirectangular
42/// metres about the segment's own mean latitude, which is exact enough at
43/// shape-segment scale.
44pub fn project(p: (i32, i32), a: (i32, i32), b: (i32, i32), t_min: f64) -> (f64, f64) {
45 let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();
46 let m = |q: (i32, i32)| {
47 (q.1 as f64 * 1e-7 * 111_320.0 * cos_lat, q.0 as f64 * 1e-7 * 111_320.0)
48 };
49 let (ax, ay) = m(a);
50 let (bx, by) = m(b);
51 let (px, py) = m(p);
52 let (dx, dy) = (bx - ax, by - ay);
53 let len2 = dx * dx + dy * dy;
54 let t = if len2 <= 0.0 {
55 t_min
56 } else {
57 (((px - ax) * dx + (py - ay) * dy) / len2).clamp(t_min, 1.0)
58 };
59 let (cx, cy) = (ax + t * dx, ay + t * dy);
60 (t, ((px - cx).powi(2) + (py - cy).powi(2)).sqrt())
61}
62
63/// Ground distance between two e7 points in metres, in the same local
64/// equirectangular frame [`project`] measures in.
65pub fn distance_m(a: (i32, i32), b: (i32, i32)) -> f64 {
66 let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos();
67 let dy = (b.0 as f64 - a.0 as f64) * 1e-7 * 111_320.0;
68 let dx = (b.1 as f64 - a.1 as f64) * 1e-7 * 111_320.0 * cos_lat;
69 (dx * dx + dy * dy).sqrt()
70}
71
72/// Walk `points` emitting a point every `step_m` metres along it.
73///
74/// The first and last points are always kept, so the walk covers the whole
75/// polyline and a short one still yields both ends. The other half of
76/// [`project`]: that measures across a polyline, this measures along one, and
77/// together they are enough to ask whether two polylines are the same line.
78pub fn resample(points: &[(i32, i32)], step_m: f64) -> Vec<(i32, i32)> {
79 if points.len() < 2 || !(step_m > 0.0) {
80 return points.to_vec();
81 }
82 let lerp = |a: i32, b: i32, t: f64| (a as f64 + (b as f64 - a as f64) * t).round() as i32;
83 let mut out = vec![points[0]];
84 // Distance already walked since the last emitted sample, carried across the
85 // segment boundary so the spacing is along the polyline and not per segment.
86 let mut carry = 0.0f64;
87 for pair in points.windows(2) {
88 let (a, b) = (pair[0], pair[1]);
89 let length = distance_m(a, b);
90 if length <= 0.0 {
91 continue;
92 }
93 let mut at = step_m - carry;
94 while at < length {
95 let t = at / length;
96 out.push((lerp(a.0, b.0, t), lerp(a.1, b.1, t)));
97 at += step_m;
98 }
99 carry = length - (at - step_m);
100 }
101 let last = points[points.len() - 1];
102 if out[out.len() - 1] != last {
103 out.push(last);
104 }
105 out
106}
107
108fn non_decreasing(v: &[f64]) -> bool {
109 v.windows(2).all(|w| w[1] >= w[0])
110}
111
112/// Segment index whose `shape_dist_traveled` span contains `d`, searched from
113/// `from` onwards so the result can never step backwards along the shape.
114fn bracket(shape_dist: &[f64], d: f64, from: usize) -> usize {
115 let last = shape_dist.len() - 2;
116 let mut seg = from.min(last);
117 while seg < last && shape_dist[seg + 1] < d {
118 seg += 1;
119 }
120 seg
121}
122
123/// Fit `shape` to `stops` (a route's stop pattern, in order). `stop_dists` is
124/// `shape_dist_traveled` from `stop_times.txt`, used only when the shape carries
125/// it too. Returns `None` when the shape cannot be trusted for this pattern, in
126/// which case the caller stores no shape and the device draws stop-to-stop.
127pub fn fit(shape: &Shape, stops: &[(i32, i32)], stop_dists: Option<&[f64]>) -> Option<FittedShape> {
128 let n = shape.lat_e7.len();
129 if n < 2 || stops.len() < 2 {
130 return None;
131 }
132 let orig: Vec<(i32, i32)> =
133 (0..n).map(|i| (shape.lat_e7[i], shape.lon_e7[i])).collect();
134
135 // Ordering key, only when both sides supply it and both are monotone.
136 let ordering = match (shape.dist.as_ref(), stop_dists) {
137 (Some(sd), Some(td))
138 if sd.len() == n
139 && td.len() == stops.len()
140 && non_decreasing(sd)
141 && non_decreasing(td) =>
142 {
143 Some((sd, td))
144 }
145 _ => None,
146 };
147
148 // Project each stop, never stepping backwards along the shape.
149 let mut proj: Vec<(usize, f64)> = Vec::with_capacity(stops.len());
150 let mut cur_seg = 0usize;
151 let mut cur_t = 0.0f64;
152 for (k, &stop) in stops.iter().enumerate() {
153 let (seg, t, offset) = match ordering {
154 Some((sd, td)) => {
155 let seg = bracket(sd, td[k], cur_seg);
156 let t_min = if seg == cur_seg { cur_t } else { 0.0 };
157 let (t, d) = project(stop, orig[seg], orig[seg + 1], t_min);
158 (seg, t, d)
159 }
160 None => {
161 let mut best: Option<(usize, f64, f64)> = None;
162 for seg in cur_seg..(n - 1) {
163 let t_min = if seg == cur_seg { cur_t } else { 0.0 };
164 let (t, d) = project(stop, orig[seg], orig[seg + 1], t_min);
165 if best.is_none_or(|(_, _, bd)| d < bd) {
166 best = Some((seg, t, d));
167 }
168 }
169 best?
170 }
171 };
172 if offset > MAX_STOP_OFFSET_M {
173 return None;
174 }
175 cur_seg = seg;
176 cur_t = t;
177 proj.push((seg, t));
178 }
179
180 // Insert each projection as its own vertex, so the pinned indices below are
181 // exactly the stops rather than the nearest shape point to them.
182 let lerp = |a: i32, b: i32, t: f64| (a as f64 + (b as f64 - a as f64) * t).round() as i32;
183 let mut pts: Vec<(i32, i32)> = Vec::with_capacity(n + stops.len());
184 let mut pinned: Vec<usize> = Vec::with_capacity(stops.len());
185 let mut k = 0usize;
186 for i in 0..n {
187 pts.push(orig[i]);
188 while k < proj.len() && proj[k].0 == i {
189 let (seg, t) = proj[k];
190 let (a, b) = (orig[seg], orig[seg + 1]);
191 pts.push((lerp(a.0, b.0, t), lerp(a.1, b.1, t)));
192 pinned.push(pts.len() - 1);
193 k += 1;
194 }
195 }
196 if pinned.len() != stops.len() {
197 return None;
198 }
199
200 // Trim to the boarded extent, keeping every point between pinned vertices.
201 let mut keep: Vec<usize> = vec![pinned[0]];
202 let mut stop_vertices: Vec<u32> = vec![0];
203 for w in pinned.windows(2) {
204 let (a, b) = (w[0], w[1]);
205 if b > a {
206 keep.extend(a + 1..=b);
207 }
208 stop_vertices.push((keep.len() - 1) as u32);
209 }
210 if keep.len() < 2 {
211 return None;
212 }
213
214 Some(FittedShape {
215 points: keep.into_iter().map(|i| pts[i]).collect(),
216 stop_vertices,
217 })
218}
219
220/// Encode a fitted polyline for SHAPE_COORDS: `u32 point_count`, then per point
221/// a zigzag varint latitude delta and longitude delta (1e-7 degrees, cumulative
222/// from zero). Zigzag varints rather than the `i16` deltas `graph.rs` uses for
223/// road geometry: consecutive `shapes.txt` points are routinely far enough apart
224/// to overflow an `i16` at 1e-7 degrees.
225pub fn encode(points: &[(i32, i32)]) -> Vec<u8> {
226 let mut out = Vec::with_capacity(4 + points.len() * 6);
227 out.extend_from_slice(&(points.len() as u32).to_le_bytes());
228 let (mut plat, mut plon) = (0i64, 0i64);
229 for &(lat, lon) in points {
230 write_zigzag(&mut out, lat as i64 - plat);
231 write_zigzag(&mut out, lon as i64 - plon);
232 plat = lat as i64;
233 plon = lon as i64;
234 }
235 out
236}
237
238fn write_zigzag(v: &mut Vec<u8>, x: i64) {
239 let mut u = ((x << 1) ^ (x >> 63)) as u64;
240 loop {
241 let b = (u & 0x7f) as u8;
242 u >>= 7;
243 if u != 0 {
244 v.push(b | 0x80);
245 } else {
246 v.push(b);
247 break;
248 }
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 fn shape(points: &[(f64, f64)], dist: Option<&[f64]>) -> Shape {
257 Shape {
258 lat_e7: points.iter().map(|&(la, _)| (la * 1e7) as i32).collect(),
259 lon_e7: points.iter().map(|&(_, lo)| (lo * 1e7) as i32).collect(),
260 dist: dist.map(|d| d.to_vec()),
261 }
262 }
263 fn e7(lat: f64, lon: f64) -> (i32, i32) {
264 ((lat * 1e7) as i32, (lon * 1e7) as i32)
265 }
266
267 fn decode(bytes: &[u8]) -> Vec<(i32, i32)> {
268 let n = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
269 let mut pos = 4usize;
270 let mut read = || -> i64 {
271 let mut result = 0u64;
272 let mut shift = 0u32;
273 loop {
274 let b = bytes[pos];
275 pos += 1;
276 result |= ((b & 0x7f) as u64) << shift;
277 if b & 0x80 == 0 {
278 break;
279 }
280 shift += 7;
281 }
282 ((result >> 1) as i64) ^ -((result & 1) as i64)
283 };
284 let (mut lat, mut lon) = (0i64, 0i64);
285 (0..n)
286 .map(|_| {
287 lat += read();
288 lon += read();
289 (lat as i32, lon as i32)
290 })
291 .collect()
292 }
293
294 #[test]
295 fn fits_stops_by_nearest_point_when_no_dist_is_given() {
296 // A shape detouring east between three collinear stops.
297 let s = shape(
298 &[
299 (37.700, -122.400),
300 (37.705, -122.390),
301 (37.710, -122.400),
302 (37.715, -122.390),
303 (37.720, -122.400),
304 ],
305 None,
306 );
307 let stops = [e7(37.700, -122.400), e7(37.710, -122.400), e7(37.720, -122.400)];
308 let f = fit(&s, &stops, None).expect("fits");
309 assert_eq!(f.stop_vertices.len(), 3);
310 assert!(
311 f.stop_vertices.windows(2).all(|w| w[1] >= w[0]),
312 "vertex indices must be non-decreasing, got {:?}",
313 f.stop_vertices
314 );
315 assert_eq!(f.stop_vertices[0], 0, "trimmed to the first stop");
316 assert_eq!(
317 *f.stop_vertices.last().unwrap() as usize,
318 f.points.len() - 1,
319 "trimmed to the last stop"
320 );
321 // Each stop's vertex is the stop itself, so the drawn ride starts on it.
322 for (k, &v) in f.stop_vertices.iter().enumerate() {
323 assert_eq!(f.points[v as usize], stops[k]);
324 }
325 // The detour is kept.
326 assert!(f.points.iter().any(|&(_, lon)| lon > -1_223_950_000));
327 }
328
329 #[test]
330 fn shape_dist_traveled_disambiguates_a_stop_visited_twice() {
331 // An out-and-back: the middle stop's coordinates match two passes, and
332 // only the distance key can say which one the pattern means.
333 let s = shape(
334 &[
335 (37.700, -122.400),
336 (37.710, -122.400),
337 (37.720, -122.400),
338 (37.710, -122.400),
339 (37.700, -122.400),
340 ],
341 // Kilometres, deliberately not metres.
342 Some(&[0.0, 1.1, 2.2, 3.3, 4.4]),
343 );
344 let stops = [e7(37.700, -122.400), e7(37.710, -122.400), e7(37.700, -122.400)];
345 let f = fit(&s, &stops, Some(&[0.0, 3.3, 4.4])).expect("fits");
346 // The second stop is the *return* pass, so its vertex must sit past the
347 // northern turn rather than on the outbound leg.
348 let turn = f
349 .points
350 .iter()
351 .position(|&(lat, _)| lat >= 377_195_000)
352 .expect("the turn is kept");
353 assert!(
354 f.stop_vertices[1] as usize > turn,
355 "stop 1 landed on the outbound pass: {:?} vs turn {turn}",
356 f.stop_vertices
357 );
358 }
359
360 #[test]
361 fn rejects_a_shape_belonging_to_another_pattern() {
362 let s = shape(&[(40.700, -74.000), (40.710, -74.000)], None);
363 let stops = [e7(37.700, -122.400), e7(37.710, -122.400)];
364 assert!(fit(&s, &stops, None).is_none(), "a shape 4000 km away must be dropped");
365 }
366
367 #[test]
368 fn rejects_a_degenerate_shape() {
369 let s = shape(&[(37.700, -122.400)], None);
370 let stops = [e7(37.700, -122.400), e7(37.710, -122.400)];
371 assert!(fit(&s, &stops, None).is_none());
372 }
373
374 #[test]
375 fn every_shape_point_between_the_stops_is_kept() {
376 let mut pts = Vec::new();
377 for i in 0..101 {
378 pts.push((37.700 + i as f64 * 0.0001, -122.400));
379 }
380 let s = shape(&pts, None);
381 let stops = [e7(37.700, -122.400), e7(37.7100, -122.400)];
382 let f = fit(&s, &stops, None).expect("fits");
383 assert_eq!(f.points.len(), 101, "full resolution: even a straight run keeps its points");
384 assert_eq!(f.stop_vertices, vec![0, 100]);
385 }
386
387 #[test]
388 fn resampling_walks_the_polyline_at_a_fixed_spacing() {
389 // 0.1 degrees of latitude: 11,132 m due north.
390 let line = [(37_700_000, -122_400_000), (38_700_000, -122_400_000)];
391 let walked = resample(&line, 1000.0);
392 // Eleven interior samples plus both ends.
393 assert_eq!(walked.len(), 13, "{walked:?}");
394 assert_eq!(walked[0], line[0], "the first point is always kept");
395 assert_eq!(walked[walked.len() - 1], line[1], "and so is the last");
396 for pair in walked[..walked.len() - 1].windows(2) {
397 let step = distance_m(pair[0], pair[1]);
398 assert!((step - 1000.0).abs() < 1.0, "uneven step {step}");
399 }
400 }
401
402 /// The spacing is along the whole polyline, not restarted per segment: a
403 /// chain of short segments must not emit a sample at every joint.
404 #[test]
405 fn resampling_carries_the_spacing_across_segments() {
406 let mut pts = Vec::new();
407 for i in 0..101 {
408 pts.push((37_700_000 + i * 1_000, -122_400_000));
409 }
410 // 100 segments of ~11 m each, so ~1113 m in total.
411 let walked = resample(&pts, 100.0);
412 assert!(walked.len() >= 12 && walked.len() <= 13, "{}", walked.len());
413 }
414
415 #[test]
416 fn resampling_leaves_something_it_cannot_walk_alone() {
417 assert_eq!(resample(&[], 10.0), Vec::new());
418 let one = [(37_700_000, -122_400_000)];
419 assert_eq!(resample(&one, 10.0), one.to_vec());
420 // A step of zero would loop forever rather than divide by it.
421 let two = [(37_700_000, -122_400_000), (37_700_100, -122_400_000)];
422 assert_eq!(resample(&two, 0.0), two.to_vec());
423 // A duplicated point is a zero-length segment, not a division by zero.
424 let doubled = [(37_700_000, -122_400_000), (37_700_000, -122_400_000)];
425 assert_eq!(resample(&doubled, 10.0), vec![doubled[0]]);
426 }
427
428 #[test]
429 fn a_metre_is_a_metre_in_both_axes() {
430 // 0.001 degrees of latitude is 111.3 m anywhere.
431 let north = distance_m((377_000_000, -1_224_000_000), (377_010_000, -1_224_000_000));
432 assert!((north - 111.32).abs() < 0.1, "{north}");
433 // The same longitude span is shorter, by cos(37.7).
434 let east = distance_m((377_000_000, -1_224_000_000), (377_000_000, -1_223_990_000));
435 assert!((east - 111.32 * 37.7f64.to_radians().cos()).abs() < 0.1, "{east}");
436 }
437
438 #[test]
439 fn encoding_survives_deltas_that_would_overflow_an_i16() {
440 // ~40 km apart: 3.6e6 in 1e-7 degrees, far past i16::MAX.
441 let points =
442 vec![(377_000_000, -1_224_000_000), (380_600_000, -1_224_000_000), (377_000_000, -1_219_000_000)];
443 assert_eq!(decode(&encode(&points)), points);
444 }
445
446 #[test]
447 fn encoding_roundtrips_a_fitted_shape() {
448 let s = shape(
449 &[(37.700, -122.400), (37.705, -122.390), (37.710, -122.400)],
450 None,
451 );
452 let stops = [e7(37.700, -122.400), e7(37.710, -122.400)];
453 let f = fit(&s, &stops, None).expect("fits");
454 assert_eq!(decode(&encode(&f.points)), f.points);
455 }
456}