maps: multi-day transit planning + intercity network for long journeys
- Commit
28190e4acbfac44588d8f0e8419b0f193463018c- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 07:25 UTC (1 month ago)
- Parents
2abcad3
Diff
maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.ktindex aa1f272d74..17a785f7ea 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt@@ -53,13 +53,17 @@ private fun yyyymmdd(d: LocalDate): Int = d.year * YEAR_MULTIPLIER + d.monthValue * MONTH_MULTIPLIER + d.dayOfMonth /**- * Format a GTFS service-day time (which may exceed 86400 for a trip running- * past midnight) as a wall clock `HH:mm`. Empty for a missing time.+ * Format a time in the query day's frame (which exceeds 86400 for anything+ * after midnight, and spans several days on a long-distance journey) as a wall+ * clock `HH:mm`, with a `+N` day marker once it falls on a later day, as+ * timetables print it. Empty for a missing time. */ internal fun formatServiceTime(secs: Int): String { if (secs <= 0) return ""+ val day = secs / SECONDS_PER_DAY val s = secs % SECONDS_PER_DAY- return "%02d:%02d".format(Locale.ROOT, s / SECONDS_PER_HOUR, (s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE)+ val clock = "%02d:%02d".format(Locale.ROOT, s / SECONDS_PER_HOUR, (s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE)+ return if (day > 0) "$clock +$day" else clock } /** DayOfWeek is Mon=1..Sun=7; the index wants Mon=0..Sun=6. */
maps/src/main/rust/examples/route_diff.rs
diff --git a/maps/src/main/rust/examples/route_diff.rs b/maps/src/main/rust/examples/route_diff.rsindex d3c43a07ea..cd1284b43c 100644--- a/maps/src/main/rust/examples/route_diff.rs+++ b/maps/src/main/rust/examples/route_diff.rs@@ -58,6 +58,7 @@ fn main() -> std::process::ExitCode { Some("dump") => dump(&args[1..]), Some("dump-compare") => dump_compare(&args[1..]), Some("sections") => sections(&args[1..]),+ Some("transit") => transit(&args[1..]), _ => Err(USAGE.to_string()), }; match r {@@ -80,7 +81,8 @@ usage: route_diff dump route_diff dump --graph DIR --out FILE route_diff dump-compare --baseline FILE --candidate FILE [--limit N]- route_diff sections --archive FILE [--dump KIND]";+ route_diff sections --archive FILE [--dump KIND]+ route_diff transit --graph DIR --from LAT,LON --to LAT,LON --dep SECS --date YYYYMMDD --weekday N"; fn flag(args: &[String], name: &str) -> Option<String> { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()@@ -90,6 +92,63 @@ fn need(args: &[String], name: &str) -> Result<String, String> { flag(args, name).ok_or_else(|| format!("missing {name}\n{USAGE}")) } +/// Plan one transit journey from an archive's transit section and print its+/// legs, the time the first plan took (which includes classifying the+/// intercity routes), and a second, warm plan.+fn transit(args: &[String]) -> Result<bool, String> {+ use offlinerouter::transit::{plan, LegKind, QueryDay, Schedule, TransitIndex};+ let dir = need(args, "--graph")?;+ let point = |name: &str| -> Result<(f64, f64), String> {+ let v = need(args, name)?;+ let (a, b) = v.split_once(',').ok_or_else(|| format!("{name} wants LAT,LON"))?;+ Ok((a.trim().parse().map_err(|e| format!("{name}: {e}"))?, b.trim().parse().map_err(|e| format!("{name}: {e}"))?))+ };+ let num = |name: &str| -> Result<u32, String> { need(args, name)?.parse().map_err(|e| format!("{name}: {e}")) };+ let (from, to) = (point("--from")?, point("--to")?);+ let (dep, date, weekday) = (num("--dep")?, num("--date")?, num("--weekday")?);+ let started = std::time::Instant::now();+ let idx = TransitIndex::load_archive(&archive_path(&dir)).ok_or("no transit section in the archive")?;+ println!(" load {:>10.1} ms", started.elapsed().as_secs_f64() * 1e3);+ let sched = Schedule { day: QueryDay::for_date(weekday, date), overlay: None };+ let hhmm = |s: u32| {+ let (d, r) = (s / 86_400, s % 86_400);+ format!("{:02}:{:02}{}", r / 3600, r % 3600 / 60, if d > 0 { format!(" +{d}d") } else { String::new() })+ };+ let mut first = None;+ for pass in ["cold", "warm"] {+ let t = std::time::Instant::now();+ let legs = plan(&idx, from.0, from.1, to.0, to.1, dep, sched);+ println!(" plan ({pass}) {:>10.1} ms", t.elapsed().as_secs_f64() * 1e3);+ if first.is_none() {+ first = Some(legs);+ }+ }+ let Some(legs) = first.flatten() else {+ println!(" no journey");+ return Ok(false);+ };+ for l in &legs {+ let kind = match l.kind {+ LegKind::Walk => "walk",+ LegKind::Wait => "wait",+ LegKind::Ride => "ride",+ };+ println!(+ " {kind:<4} {:>9} -> {:<9} {:<28} {} -> {} ({} stops, {:.0} km)",+ hhmm(l.dep_secs),+ hhmm(l.arr_secs),+ l.name,+ l.from_stop,+ l.to_stop,+ l.stop_count,+ l.dist_m / 1000.0+ );+ }+ let total = legs.last().map_or(0, |l| l.arr_secs).saturating_sub(dep);+ println!(" total {:.1} h, {} rides", f64::from(total) / 3600.0, legs.iter().filter(|l| l.kind == LegKind::Ride).count());+ Ok(true)+}+ /// Print `kind offset len` for every sidecar section of a `.mamaps`, reading /// only the footer and directory, so sections can be cut out with `dd`. fn sections(args: &[String]) -> Result<bool, String> {
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex 38a7360b38..a6ffeb30bd 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -21,7 +21,7 @@ mod jni; mod mvt; pub mod routing; pub mod state;-mod transit;+pub mod transit; #[cfg(test)] mod tests {
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex f86ac64f77..1701150166 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -93,6 +93,10 @@ const WALK_SPEED_M_S: f64 = 1.33; const ACCESS_RADIUS_M: f64 = 1000.0; const MAX_ROUNDS: usize = 6; const SECS_PER_DAY: u32 = 24 * 3600;+/// Service days after the query day a journey may draw trips from, so a+/// multi-day long-distance trip, or a connection that only runs tomorrow, is+/// still found.+const PLAN_DAYS_AHEAD: i32 = 3; // --- On-disk fixed records (`#[repr(C, packed)]`, read via `read_at`). --- // Variable-length sections (ROUTE_TRIPS, PROFILES) are decoded with `uvarint`.@@ -305,6 +309,8 @@ pub struct TransitIndex { grid_cell_count: u32, // Section (offset, len) directory. sec: [(usize, usize); SECTION_COUNT],+ /// Long-distance route classification, built on first use.+ intercity: std::sync::OnceLock<Intercity>, } // Read-only after load; the raw pointer is sound to share.@@ -318,6 +324,7 @@ include!("transit_part4.rs"); include!("transit_part5.rs"); include!("transit_part10.rs"); include!("transit_part11.rs");+include!("transit_part13.rs"); #[cfg(test)] mod tests { include!("transit_part6.rs");@@ -325,4 +332,5 @@ mod tests { include!("transit_part8.rs"); include!("transit_part9.rs"); include!("transit_part12.rs");+ include!("transit_part14.rs"); }
maps/src/main/rust/src/transit_part1.rs
diff --git a/maps/src/main/rust/src/transit_part1.rs b/maps/src/main/rust/src/transit_part1.rsindex d08b01edf6..eebfacf558 100644--- a/maps/src/main/rust/src/transit_part1.rs+++ b/maps/src/main/rust/src/transit_part1.rs@@ -88,6 +88,7 @@ impl TransitIndex { grid_cols, grid_cell_count, sec,+ intercity: std::sync::OnceLock::new(), }) }
maps/src/main/rust/src/transit_part13.rs
diff --git a/maps/src/main/rust/src/transit_part13.rs b/maps/src/main/rust/src/transit_part13.rsnew file mode 100644index 0000000000..35782a0ef4--- /dev/null+++ b/maps/src/main/rust/src/transit_part13.rs@@ -0,0 +1,149 @@+// Multi-day service dates and the intercity route classification the planner+// uses for long journeys.+//+// Included into `transit.rs`, so `TransitIndex`'s private helpers are in scope.++/// A trip qualifies as long-distance when its stops span at least this far.+/// Commuter rail and regional coaches mostly fall short of it; Amtrak, VIA,+/// European intercity trains and FlixBus-style coaches clear it.+const INTERCITY_SPAN_M: f64 = 100_000.0;+/// Origin-destination distance from which a journey is planned on the+/// intercity network between its two local areas.+const INTERCITY_TRIP_M: f64 = 150_000.0;+/// Within this distance of either end every route is scanned.+const TRANSIT_LOCAL_M: f64 = 50_000.0;++impl QueryDay {+ /// The query day for weekday `weekday` (0=Mon) and date `yyyymmdd`, with its+ /// previous service day derived.+ pub fn for_date(weekday: u32, date: u32) -> QueryDay {+ QueryDay { weekday, date, prev_weekday: (weekday + 6) % 7, prev_date: add_days(date, -1) }+ }++ /// Weekday (0=Mon) and `yyyymmdd` date of the service day `offset` days from+ /// the query day: `-1` is the previous day, `1` tomorrow.+ pub(crate) fn on(&self, offset: i32) -> (u32, u32) {+ match offset {+ -1 => (self.prev_weekday, self.prev_date),+ 0 => (self.weekday, self.date),+ n => ((self.weekday + n.rem_euclid(7) as u32) % 7, add_days(self.date, n)),+ }+ }+}++/// `yyyymmdd` shifted by `n` days in the proleptic Gregorian calendar.+fn add_days(yyyymmdd: u32, n: i32) -> u32 {+ let (y, m, d) = (+ i64::from(yyyymmdd / 10_000),+ i64::from(yyyymmdd / 100 % 100),+ i64::from(yyyymmdd % 100),+ );+ let (y, m, d) = civil_from_days(days_from_civil(y, m, d) + i64::from(n));+ (y * 10_000 + m * 100 + d) as u32+}++/// Days since 1970-01-01 (Howard Hinnant's `days_from_civil`).+fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {+ let y = if m <= 2 { y - 1 } else { y };+ let era = y.div_euclid(400);+ let yoe = y - era * 400;+ let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ era * 146_097 + doe - 719_468+}++fn civil_from_days(z: i64) -> (i64, i64, i64) {+ let z = z + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ (if m <= 2 { yoe + era * 400 + 1 } else { yoe + era * 400 }, m, d)+}++/// Long-distance routes of a pack, classified once on first use.+pub struct Intercity {+ /// Bit per route: long-distance rail or coach.+ long: Vec<u64>,+}++impl Intercity {+ fn build(idx: &TransitIndex) -> Intercity {+ let n = idx.route_count;+ let mut long = vec![0u64; (n as usize).div_ceil(64)];+ for r in 0..n {+ let route = idx.route(r);+ let is_rail = matches!(route.route_type, 2 | 100..=199);+ let is_coach = matches!(route.route_type, 3 | 200..=299);+ if !(is_rail || is_coach) || route.n_stops < 2 {+ continue;+ }+ // Three stops bound the span well enough for a threshold this coarse,+ // and keep the pass to a few reads per route over a world pack.+ let at = |pos: u32| idx.stop_ll(idx.route_stop(route.first_route_stop + pos));+ let pts = [at(0), at(route.n_stops / 2), at(route.n_stops - 1)];+ let span = [(0, 1), (0, 2), (1, 2)]+ .iter()+ .map(|&(a, b)| dist_m(pts[a].0, pts[a].1, pts[b].0, pts[b].1))+ .fold(0.0, f64::max);+ if span < INTERCITY_SPAN_M {+ continue;+ }+ long[(r / 64) as usize] |= 1 << (r % 64);+ }+ Intercity { long }+ }++ fn is_long(&self, route: u32) -> bool {+ self.long.get((route / 64) as usize).is_some_and(|w| w & (1 << (route % 64)) != 0)+ }+}++impl TransitIndex {+ pub(crate) fn intercity(&self) -> &Intercity {+ self.intercity.get_or_init(|| Intercity::build(self))+ }+}++/// The planner's intercity overlay for one long journey: near either end every+/// route is scanned, but a stop far from both only boards long-distance routes.+///+/// Without it, an earliest-arrival search across a continent marks every local+/// bus in every city it passes before reaching the destination. The filter+/// depends only on the stop, so the result is still a valid journey; it can+/// miss one that strings local services together far from both ends.+struct IntercityScope<'a> {+ intercity: &'a Intercity,+ from: (f64, f64),+ to: (f64, f64),+}++impl<'a> IntercityScope<'a> {+ fn for_trip(+ idx: &'a TransitIndex,+ from_lat: f64,+ from_lon: f64,+ to_lat: f64,+ to_lon: f64,+ ) -> Option<IntercityScope<'a>> {+ (dist_m(from_lat, from_lon, to_lat, to_lon) >= INTERCITY_TRIP_M).then(|| IntercityScope {+ intercity: idx.intercity(),+ from: (from_lat, from_lon),+ to: (to_lat, to_lon),+ })+ }++ fn long_only_at(&self, idx: &TransitIndex, stop: u32) -> bool {+ let (lat, lon) = idx.stop_ll(stop);+ dist_m(lat, lon, self.from.0, self.from.1) >= TRANSIT_LOCAL_M+ && dist_m(lat, lon, self.to.0, self.to.1) >= TRANSIT_LOCAL_M+ }++ fn is_long(&self, route: u32) -> bool {+ self.intercity.is_long(route)+ }+}+
maps/src/main/rust/src/transit_part14.rs
diff --git a/maps/src/main/rust/src/transit_part14.rs b/maps/src/main/rust/src/transit_part14.rsnew file mode 100644index 0000000000..b40e5316d2--- /dev/null+++ b/maps/src/main/rust/src/transit_part14.rs@@ -0,0 +1,125 @@++ /// Two long-distance trains meeting at a mid-continent hub, ~510 km end to+ /// end, plus a short local bus at the hub. Stop 0 is the origin, 4 the+ /// destination, 2 the hub, 5 a stop 4 km from it.+ fn intercity_pack() -> Pack {+ let stop = |lon: f64, name: &'static str| Stop { lat: 40.0, lon, name, code: name, gtfs_id: name };+ Pack {+ stops: vec![+ stop(-120.00, "Origin"),+ stop(-119.99, "OriginSide"),+ stop(-118.00, "Hub"),+ stop(-116.00, "Junction"),+ stop(-114.00, "Destination"),+ stop(-117.95, "HubSide"),+ ],+ routes: vec![+ // Reaches the hub at 10:00, after the connection's 09:00 departure.+ Route {+ name: "Zephyr",+ color: 0,+ route_type: 2,+ feed: 0,+ pattern: vec![0, 2],+ trips: vec![Trip {+ start: 28_800,+ stoptimes: vec![(28_800, 28_800), (36_000, 36_000)],+ service: 0,+ headsign: "East",+ }],+ shape: None,+ },+ Route {+ name: "Limited",+ color: 0x00_3366,+ route_type: 2,+ feed: 0,+ pattern: vec![2, 4],+ trips: vec![Trip {+ start: 32_400,+ stoptimes: vec![(32_400, 32_400), (54_000, 54_000)],+ service: 1,+ headsign: "East",+ }],+ shape: None,+ },+ Route {+ name: "Local",+ color: 0,+ route_type: 3,+ feed: 0,+ pattern: vec![2, 5],+ trips: vec![Trip {+ start: 37_000,+ stoptimes: vec![(37_000, 37_000), (37_600, 37_600)],+ service: 0,+ headsign: "Side",+ }],+ shape: None,+ },+ ],+ services: vec![+ Service { mask: 0b0111_1111, start: 20_240_101, end: 20_241_231 },+ Service { mask: 0b0111_1111, start: 20_240_101, end: 20_241_231 },+ ],+ exceptions: Vec::new(),+ feeds: vec![("rail", "America/Denver", "us-Rail")],+ }+ }++ #[test]+ fn a_connection_leaving_tomorrow_completes_the_journey() {+ let idx = intercity_pack().index();+ let legs = plan(&idx, 40.0, -120.0, 40.0, -114.0, 25_200, sched(wednesday()))+ .expect("the hub connection runs the next morning");+ let rides: Vec<&TransitLeg> = legs.iter().filter(|l| l.kind == LegKind::Ride).collect();+ assert_eq!(rides.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["Zephyr", "Limited"]);+ assert_eq!(rides[0].arr_secs, 36_000);+ assert_eq!(rides[1].dep_secs, SECS_PER_DAY + 32_400, "Thursday 09:00");+ assert_eq!(rides[1].arr_secs, SECS_PER_DAY + 54_000);+ assert!(legs.iter().any(|l| l.kind == LegKind::Wait && l.arr_secs == SECS_PER_DAY + 32_400));+ }++ #[test]+ fn a_connection_two_days_out_is_still_found() {+ let mut pack = intercity_pack();+ // The connection only runs on Fridays: two service days after Wednesday.+ pack.services[1].mask = 1 << 4;+ let idx = pack.index();+ let legs = plan(&idx, 40.0, -120.0, 40.0, -114.0, 25_200, sched(wednesday()))+ .expect("Friday is within the horizon");+ let last = legs.iter().filter(|l| l.kind == LegKind::Ride).last().expect("a ride");+ assert_eq!(last.dep_secs, 2 * SECS_PER_DAY + 32_400);+ }++ #[test]+ fn later_service_days_resolve_their_weekday_and_date() {+ assert_eq!(add_days(20_240_228, 1), 20_240_229, "leap day");+ assert_eq!(add_days(20_240_228, 2), 20_240_301);+ assert_eq!(add_days(20_231_231, 1), 20_240_101);+ assert_eq!(add_days(20_240_301, -1), 20_240_229);+ let sunday = QueryDay { weekday: 6, date: 20_240_107, prev_weekday: 5, prev_date: 20_240_106 };+ assert_eq!(sunday.on(-1), (5, 20_240_106));+ assert_eq!(sunday.on(0), (6, 20_240_107));+ assert_eq!(sunday.on(2), (1, 20_240_109), "Tuesday");+ }++ #[test]+ fn long_routes_are_classified_by_span_and_mode() {+ let idx = intercity_pack().index();+ let ic = idx.intercity();+ assert!(ic.is_long(0) && ic.is_long(1), "both trains span 170+ km");+ assert!(!ic.is_long(2), "a 4 km bus is local");+ }++ #[test]+ fn only_long_routes_are_boarded_far_from_both_ends() {+ let idx = intercity_pack().index();+ assert!(IntercityScope::for_trip(&idx, 40.0, -120.0, 40.0, -119.5).is_none(), "a 43 km trip");+ let scope = IntercityScope::for_trip(&idx, 40.0, -120.0, 40.0, -114.0).expect("a 510 km trip");+ assert!(!scope.long_only_at(&idx, 1), "next to the origin");+ assert!(scope.long_only_at(&idx, 2), "the hub is far from both ends");+ assert!(!scope.long_only_at(&idx, 4), "the destination");+ assert!(scope.is_long(1) && !scope.is_long(2));+ }+
maps/src/main/rust/src/transit_part2.rs
diff --git a/maps/src/main/rust/src/transit_part2.rs b/maps/src/main/rust/src/transit_part2.rsindex f0cf90138e..b12af80a00 100644--- a/maps/src/main/rust/src/transit_part2.rs+++ b/maps/src/main/rust/src/transit_part2.rs@@ -143,8 +143,13 @@ fn zigzag(u: u64) -> i64 { /// (`24:30:00`), so a trip inherited from the previous service day is shifted /// back one full day. fn abs_time_on(start_time: u32, rel: i32, prev_day: bool) -> u32 {- let shift = if prev_day { SECS_PER_DAY as i64 } else { 0 };- (start_time as i64 + rel as i64 - shift).max(0) as u32+ abs_time_day(start_time, rel, if prev_day { -1 } else { 0 })+}++/// [`abs_time_on`] for a trip on the service day `day` days from the query day+/// (`-1` is the previous day, `1` tomorrow).+fn abs_time_day(start_time: u32, rel: i32, day: i32) -> u32 {+ (start_time as i64 + rel as i64 + day as i64 * SECS_PER_DAY as i64).max(0) as u32 } /// The two service days a query may draw trips from: the query day itself, and@@ -170,11 +175,14 @@ impl Schedule<'_> { /// Whether `service_idx` runs on the query day (`prev = false`) or on the /// preceding service day (`prev = true`). fn runs(&self, idx: &TransitIndex, service_idx: u32, prev: bool) -> bool {- if prev {- idx.service_runs(service_idx, self.day.prev_weekday, self.day.prev_date)- } else {- idx.service_runs(service_idx, self.day.weekday, self.day.date)- }+ self.runs_on(idx, service_idx, if prev { -1 } else { 0 })+ }++ /// Whether `service_idx` runs on the service day `day` days from the query+ /// day (see [`QueryDay::on`]).+ fn runs_on(&self, idx: &TransitIndex, service_idx: u32, day: i32) -> bool {+ let (weekday, date) = self.day.on(day);+ idx.service_runs(service_idx, weekday, date) } fn adjustment(&self, route: u32, pos: u32, sched: u32) -> Option<Adjustment> {@@ -276,8 +284,9 @@ fn delayed(sched: u32, delay_secs: i32) -> u32 { struct Boarding { /// Local index into the route's decoded trip list. trip: usize,- /// This trip belongs to the previous service day (a `>24:00:00` trip).- prev_day: bool,+ /// The trip's service day relative to the query day: `-1` for a previous-day+ /// `>24:00:00` trip, `0` today, `1..=PLAN_DAYS_AHEAD` for a later day.+ day: i32, delay_secs: i32, }
maps/src/main/rust/src/transit_part3.rs
diff --git a/maps/src/main/rust/src/transit_part3.rs b/maps/src/main/rust/src/transit_part3.rsindex 7de124bc9e..bc986646c1 100644--- a/maps/src/main/rust/src/transit_part3.rs+++ b/maps/src/main/rust/src/transit_part3.rs@@ -50,6 +50,10 @@ pub fn plan( let mut queue: Vec<u32> = seeds.clone(); relax_transfers(idx, &mut reach, &seeds, &mut queue); + // A long journey rides the intercity network between the two local areas;+ // see [`IntercityScope`].+ let scope = IntercityScope::for_trip(idx, from_lat, from_lon, to_lat, to_lon);+ // --- RAPTOR rounds --- for _round in 0..MAX_ROUNDS { if queue.is_empty() {@@ -58,9 +62,13 @@ pub fn plan( // Routes to scan, and the earliest marked stop-position on each. let mut route_earliest: HashMap<u32, u32> = HashMap::new(); for &s in &queue {+ let long_only = scope.as_ref().is_some_and(|sc| sc.long_only_at(idx, s)); let (rs, re) = idx.stop_routes_range(s); for i in rs..re { let r = idx.stop_route(i);+ if long_only && !scope.as_ref().is_some_and(|sc| sc.is_long(r)) {+ continue;+ } let pos = idx.stop_route_pos(i); route_earliest .entry(r)@@ -96,7 +104,7 @@ pub fn plan( }; if let Some(arr_rel) = arr_rel { let arr = delayed(- abs_time_on(td.start_time, arr_rel, b.prev_day),+ abs_time_day(td.start_time, arr_rel, b.day), b.delay_secs, ); let how = Reached::Transit { route: r, board_stop, boarding: b };@@ -400,8 +408,13 @@ pub fn stop_departures( if !sched.runs(idx, td.service_idx, prev_day) { continue; }- let Some(scheduled) = trip_sched_dep(idx, &mut prof_cache, td, pos, prev_day)- else {+ let Some(scheduled) = trip_sched_dep(+ idx,+ &mut prof_cache,+ td,+ pos,+ if prev_day { -1 } else { 0 },+ ) else { continue; }; let adj = sched.adjustment(r, pos, scheduled);@@ -446,5 +459,5 @@ fn trip_dep( let p = get_profile(cache, idx, trip.profile_id); p.dep_rel.get(pos as usize).copied().unwrap_or(0) };- delayed(abs_time_on(trip.start_time, dep_rel, boarding.prev_day), boarding.delay_secs)+ delayed(abs_time_day(trip.start_time, dep_rel, boarding.day), boarding.delay_secs) }
maps/src/main/rust/src/transit_part4.rs
diff --git a/maps/src/main/rust/src/transit_part4.rs b/maps/src/main/rust/src/transit_part4.rsindex 026ec728f3..2c65abd5c8 100644--- a/maps/src/main/rust/src/transit_part4.rs+++ b/maps/src/main/rust/src/transit_part4.rs@@ -1,20 +1,20 @@ /// Scheduled (timetable) departure of `trip` at `pos` in the query day's frame,-/// ignoring realtime. `None` when `prev_day` is set but the trip does not-/// actually run into the query day โ i.e. its GTFS time is below `24:00:00`, so-/// it belongs wholly to yesterday and must not be considered at all.+/// ignoring realtime, for the trip as run on service day `day` (see+/// [`QueryDay::on`]). `None` when a previous-day trip does not actually run into+/// the query day โ i.e. its GTFS time is below `24:00:00`, so it belongs wholly+/// to yesterday and must not be considered at all. fn trip_sched_dep( idx: &TransitIndex, cache: &mut HashMap<u32, ProfileDec>, trip: &TripDec, pos: u32,- prev_day: bool,+ day: i32, ) -> Option<u32> { let dep_rel = { let p = get_profile(cache, idx, trip.profile_id); p.dep_rel.get(pos as usize).copied().unwrap_or(0) };- let t = trip.start_time as i64 + dep_rel as i64- - if prev_day { SECS_PER_DAY as i64 } else { 0 };+ let t = trip.start_time as i64 + dep_rel as i64 + day as i64 * SECS_PER_DAY as i64; if t < 0 { return None; }@@ -66,29 +66,33 @@ fn earliest_trip( // earlier by `max_early_secs`. let slack = sched.max_early_secs(); // Previous-day trips first: theirs are the earliest times in this frame.- for prev_day in [true, false] {- // A previous-day trip departs at `start_time + rel - SECS_PER_DAY` in this- // frame, so its `start_time` has to clear the bound by a whole day. The- // day belongs in the bound rather than disabling the break: exempting the- // pass made it an unconditional scan of every trip on the route, each with- // a `service_runs` binary search.- let day_shift = if prev_day { SECS_PER_DAY } else { 0 };+ // Later days follow, so a journey whose next connection leaves tomorrow (a+ // long-distance train, a last bus missed) is still found.+ for day in -1..=PLAN_DAYS_AHEAD {+ // A trip on day `d` departs at `start_time + rel + d * SECS_PER_DAY` in+ // this frame, and `rel >= 0`, so once that lower bound clears the best+ // departure no later trip on this day can improve on it. The day belongs+ // in the bound rather than disabling the break: exempting a pass made it+ // an unconditional scan of every trip on the route, each with a+ // `service_runs` binary search.+ let day_shift = day as i64 * SECS_PER_DAY as i64; for i in 0..trips.len() { let Some(td) = trips.get(i) else { break }; if best.is_some()- && td.start_time >= best_dep.saturating_add(slack).saturating_add(day_shift)+ && td.start_time as i64 + day_shift >= best_dep as i64 + slack as i64 { break; }- if !sched.runs(idx, td.service_idx, prev_day) {+ if !sched.runs_on(idx, td.service_idx, day) { continue; } // A previous-day trip only counts if it actually runs into the query // day (a GTFS time at or past 24:00:00).- let Some(scheduled) = trip_sched_dep(idx, cache, &td, pos, prev_day) else {+ let Some(scheduled) = trip_sched_dep(idx, cache, &td, pos, day) else { continue; };- let adj = sched.adjustment(route_idx, pos, scheduled);+ // Realtime describes today's vehicles; a later day runs to timetable.+ let adj = if day <= 0 { sched.adjustment(route_idx, pos, scheduled) } else { None }; if adj.is_some_and(|a| a.cancelled) { continue; }@@ -96,7 +100,7 @@ fn earliest_trip( let dep = delayed(scheduled, delay_secs); if dep >= ready && dep < best_dep { best_dep = dep;- best = Some(Boarding { trip: i, prev_day, delay_secs });+ best = Some(Boarding { trip: i, day, delay_secs }); } } }@@ -136,15 +140,15 @@ fn make_transit_leg( } let (dep, arr) = { let p = get_profile(cache, idx, td.profile_id);- let dep = abs_time_on(+ let dep = abs_time_day( td.start_time, p.dep_rel.get(board_pos as usize).copied().unwrap_or(0),- boarding.prev_day,+ boarding.day, );- let arr = abs_time_on(+ let arr = abs_time_day( td.start_time, p.arr_rel.get(alight_pos as usize).copied().unwrap_or(0),- boarding.prev_day,+ boarding.day, ); (delayed(dep, boarding.delay_secs), delayed(arr, boarding.delay_secs)) };
maps/src/main/rust/src/transit_part7.rs
diff --git a/maps/src/main/rust/src/transit_part7.rs b/maps/src/main/rust/src/transit_part7.rsindex 4581384f40..6e3913da00 100644--- a/maps/src/main/rust/src/transit_part7.rs+++ b/maps/src/main/rust/src/transit_part7.rs@@ -175,10 +175,12 @@ // exception_type 2 (removed) for the query date. pack.exceptions = vec![(0, 20_240_103, 0)]; let idx = pack.index();- assert!(- plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday())).is_none(),- "service removed for this date, so no journey"- );+ // Wednesday's service is removed, so the journey waits for Thursday's+ // 08:00 rather than riding a trip that does not run.+ let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+ .expect("Thursday's service is within the planning horizon");+ let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+ assert_eq!(ride.dep_secs, SECS_PER_DAY + 28_800, "service removed for this date"); // The neighbouring date is unaffected โ the CSR range is date-keyed. let thursday = QueryDay { weekday: 3,
maps/src/main/rust/src/transit_part8.rs
diff --git a/maps/src/main/rust/src/transit_part8.rs b/maps/src/main/rust/src/transit_part8.rsindex f26045a176..376e66fe00 100644--- a/maps/src/main/rust/src/transit_part8.rs+++ b/maps/src/main/rust/src/transit_part8.rs@@ -354,17 +354,30 @@ } #[test]- fn returns_none_when_nothing_runs_on_the_query_day() {+ fn nothing_running_today_waits_for_the_next_service_day() { let pack = one_route_pack(); let idx = pack.index();- // Sunday is not in the weekday mask and there is no exception.+ // Sunday is not in the weekday mask and there is no exception, so the+ // first ride is Monday's 08:00, one service day later. let sunday = QueryDay { weekday: 6, date: 20_240_107, prev_weekday: 5, prev_date: 20_240_106, };- assert!(plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(sunday)).is_none());+ let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(sunday))+ .expect("Monday's service is within the planning horizon");+ let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+ assert_eq!(ride.dep_secs, SECS_PER_DAY + 28_800, "Monday 08:00 in Sunday's frame");+ }++ #[test]+ fn nothing_within_the_horizon_is_no_journey() {+ let mut pack = one_route_pack();+ // Service ends on the query day's eve, so no day in the horizon runs it.+ pack.services[0].end = 20_240_102;+ let idx = pack.index();+ assert!(plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday())).is_none()); } /// The hand-built harness above is an independent *reimplementation* of the
maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.ktindex a6011b315a..2c11655aa2 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt@@ -79,8 +79,10 @@ class TransitClockTest { fun `formats a service time as a wall clock`() { assertEquals("08:30", formatServiceTime(8 * 3600 + 30 * 60)) assertEquals("23:59", formatServiceTime(23 * 3600 + 59 * 60))- // A GTFS 24:30:00 trip renders as the 00:30 it actually runs at.- assertEquals("00:30", formatServiceTime(24 * 3600 + 30 * 60))+ // A GTFS 24:30:00 trip renders as the 00:30 it actually runs at, marked as+ // the next day; a multi-day journey counts the days.+ assertEquals("00:30 +1", formatServiceTime(24 * 3600 + 30 * 60))+ assertEquals("13:15 +3", formatServiceTime(3 * 86_400 + 13 * 3600 + 15 * 60)) assertEquals("", formatServiceTime(0)) } }