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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_shapes_pack.rs

transit_shapes_pack.rs144 lines · 7.1 KiBRaw
1//! Lines for `transit_shapes` read from a built `world.transit` pack instead of raw GTFS.
2//!
3//! A v7 pack's RAIL_LINES section holds exactly what [`read_feed`] takes out of each raw feed:
4//! every whole, unsimplified shape of every rail route, with its route's type, colour, name and
5//! id, in the same order. So the fold, corridor pass and writer downstream produce the same layer
6//! from the pack as from the ~80 GB of feeds it was built from.
7
8use super::*;
9use gtfs_ingest::reader::Reader;
10
11/// Every RAIL_LINES entry as a candidate line, in pack order.
12pub(crate) fn pack_lines(path: &Path) -> Result<FeedLines, String> {
13 let pack = Reader::open(path)?;
14 let Some(recs) = pack.rail_lines() else {
15 return Err(format!(
16 "{} is a v{} pack with no RAIL_LINES section; rebuild it with scripts/maps/build_world_transit.ps1",
17 path.display(),
18 pack.version(),
19 ));
20 };
21 let feeds: Vec<String> = (0..pack.feed_count()).map(|f| pack.feed_name(f)).collect();
22 let mut out = FeedLines::default();
23 for rec in recs {
24 let Some(mode) = mode_of(rec.route_type) else {
25 return Err(format!("RAIL_LINES carries route_type {}, which is not rail", rec.route_type));
26 };
27 let (color, fallback) = match rec.color {
28 0 => (fallback_color(mode), true),
29 c => (c, false),
30 };
31 out.shapes_read += 1;
32 out.lines.push(Line {
33 intercity: intercity::is_intercity(intercity::is_long_distance_type(rec.route_type), &rec.points),
34 points: rec.points,
35 color,
36 mode,
37 fallback,
38 route: rec.name,
39 route_key: format!("{}\u{0}{}", feeds[rec.feed_idx as usize], rec.route_id),
40 ordinal: 0,
41 lanes: 1,
42 taper: 255,
43 });
44 }
45 Ok(out)
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51 use gtfs_ingest::index::{FeedDir, IndexBuilder};
52
53 /// Two feeds sharing a rail alignment plus a bus, through the real pack builder: the layer
54 /// derived from the pack is byte-identical to the one derived from the feeds.
55 #[test]
56 fn a_pack_draws_exactly_the_lines_of_the_feeds_it_was_built_from() {
57 let root = std::env::temp_dir().join(format!("transit_shapes_pack_{}", std::process::id()));
58 let feed = |tag: &str, rail_color: &str, lat: &str| -> PathBuf {
59 let dir = root.join(tag);
60 std::fs::create_dir_all(&dir).unwrap();
61 let w = |f: &str, s: String| std::fs::write(dir.join(f), s).unwrap();
62 w("agency.txt", "agency_id,agency_name,agency_url,agency_timezone\nA,A,http://a,America/Los_Angeles\n".into());
63 w("stops.txt", format!("stop_id,stop_name,stop_lat,stop_lon\nS1,One,37.700,-122.40\nS2,Two,{lat},-122.40\n"));
64 w("routes.txt", format!(
65 "route_id,route_short_name,route_long_name,route_type,route_color\nR,Rail,,2,{rail_color}\nB,Bus,,3,FF0000\n"
66 ));
67 w("trips.txt", "route_id,service_id,trip_id,shape_id\nR,WK,T1,SH1\nR,WK,T2,SH2\nB,WK,T3,SH1\n".into());
68 w("stop_times.txt", "trip_id,arrival_time,departure_time,stop_id,stop_sequence\n\
69 T1,08:00:00,08:00:00,S1,1\nT1,08:10:00,08:10:00,S2,2\n\
70 T2,09:00:00,09:00:00,S2,1\nT2,09:10:00,09:10:00,S1,2\n\
71 T3,10:00:00,10:00:00,S1,1\nT3,10:10:00,10:10:00,S2,2\n".into());
72 w("calendar.txt", "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\nWK,1,1,1,1,1,0,0,20240101,20301231\n".into());
73 // A long outbound shape at full precision and a short return with a kink.
74 w("shapes.txt", format!(
75 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
76 SH1,37.6999999,-122.4000001,1\nSH1,37.75,-122.4,2\nSH1,{lat},-122.4,3\n\
77 SH2,{lat},-122.4,1\nSH2,37.75,-122.39,2\nSH2,37.7,-122.4,3\n"
78 ));
79 dir
80 };
81 let specs: Vec<FeedSpec> = vec![
82 ("a".to_string(), feed("a", "0054A5", "37.800"), String::new()),
83 ("b".to_string(), feed("b", "", "39.500"), String::new()),
84 ];
85 let mut builder = IndexBuilder::new("test");
86 for (name, dir, prefix) in &specs {
87 let table = |f: &str| gtfs::read_table(dir, f);
88 let (stops, routes, trips) =
89 (table("stops.txt").unwrap(), table("routes.txt").unwrap(), table("trips.txt").unwrap());
90 let (calendar, agency, shapes) = (table("calendar.txt"), table("agency.txt"), gtfs::read_shapes(dir));
91 builder
92 .add_feed_dir(&FeedDir {
93 name: name.clone(),
94 motis_prefix: prefix.clone(),
95 dir,
96 stops: &stops,
97 routes: &routes,
98 trips: &trips,
99 calendar: calendar.as_ref(),
100 calendar_dates: None,
101 agency: agency.as_ref(),
102 shapes: shapes.as_ref(),
103 })
104 .unwrap();
105 }
106 let mut blob = Vec::new();
107 builder.finish_to(&mut blob).unwrap();
108 let pack = root.join("test.transit");
109 std::fs::write(&pack, &blob).unwrap();
110
111 let (from_feeds, from_pack) = (root.join("feeds.geojsonseq"), root.join("pack.geojsonseq"));
112 super::super::extra2::run_with_timer(&from_feeds, super::super::extra2::Inputs::Feeds(&specs), None).unwrap();
113 super::super::extra2::run_with_timer(&from_pack, super::super::extra2::Inputs::Pack(&pack), None).unwrap();
114 let (a, b) = (std::fs::read_to_string(&from_feeds).unwrap(), std::fs::read_to_string(&from_pack).unwrap());
115 let stored = Reader::open(&pack).unwrap().rail_lines().expect("a v7 pack");
116 let _ = std::fs::remove_dir_all(&root);
117 assert!(
118 stored.iter().any(|l| l.points.first() == Some(&(376_999_999, -1_224_000_001)) && l.points.len() == 3),
119 "every shapes.txt point, at full e7 precision"
120 );
121 assert_eq!(stored.len(), 4, "two shapes per feed, and no bus");
122 assert!(a.contains("\"intercity\":1"), "the 200 km line is intercity");
123 assert!(!a.contains("FF0000"), "no bus");
124 assert_eq!(a, b, "the pack-derived layer is byte-identical");
125 }
126
127 #[test]
128 fn a_v6_pack_is_refused_with_a_rebuild_hint() {
129 let path = std::env::temp_dir().join(format!("transit_shapes_v6_{}.transit", std::process::id()));
130 let mut blob = vec![0u8; gtfs_ingest::index::HEADER_LEN + 27 * 16];
131 blob[0..4].copy_from_slice(&gtfs_ingest::index::MAGIC.to_le_bytes());
132 blob[4..8].copy_from_slice(&6u32.to_le_bytes());
133 blob[8..12].copy_from_slice(&27u32.to_le_bytes());
134 let end = (blob.len() as u64).to_le_bytes();
135 for i in 0..27 {
136 let at = gtfs_ingest::index::HEADER_LEN + i * 16;
137 blob[at..at + 8].copy_from_slice(&end);
138 }
139 std::fs::write(&path, &blob).unwrap();
140 let err = pack_lines(&path).err().expect("refused");
141 let _ = std::fs::remove_file(&path);
142 assert!(err.contains("rebuild"), "{err}");
143 }
144}