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