Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_shapes_extra2.rs
transit_shapes_extra2.rs295 lines · 13.1 KiBRaw
| 1 | //! The `run` pipeline for `transit_shapes`, moved out of `transit_shapes.rs` |
| 2 | //! to keep the bin under the file-size limit. Behaviour-identical. |
| 3 | |
| 4 | use super::*; |
| 5 | use rayon::prelude::*; |
| 6 | use std::time::Instant; |
| 7 | |
| 8 | /// Where the lines come from: raw GTFS feeds, or the `world.transit` pack built from them. |
| 9 | #[derive(Clone, Copy)] |
| 10 | pub(crate) enum Inputs<'a> { |
| 11 | Feeds(&'a [FeedSpec]), |
| 12 | Pack(&'a Path), |
| 13 | } |
| 14 | |
| 15 | /// Untimed entry, kept for the unit tests in `transit_shapes_extra`. |
| 16 | #[cfg(test)] |
| 17 | pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { |
| 18 | run_with_timer(out_path, Inputs::Feeds(specs), None) |
| 19 | } |
| 20 | |
| 21 | /// Timed pipeline entry: ticks `parse-feeds` over the feed loop below, the |
| 22 | /// corridor stages inside [`expand_corridor_spans`], then `write-output` over |
| 23 | /// the sort and file write, and emits the `TIMING` line before the human |
| 24 | /// summary. `None` skips every tick, which is what the tests drive via [`run`]. |
| 25 | pub(crate) fn run_with_timer( |
| 26 | out_path: &Path, |
| 27 | inputs: Inputs<'_>, |
| 28 | mut timer: Option<PhaseTimer>, |
| 29 | ) -> Result<(), String> { |
| 30 | let mut seen: HashSet<(u64, u32)> = HashSet::new(); |
| 31 | let mut lines: Vec<Line> = Vec::new(); |
| 32 | // Track already drawn, per colour and per mode. Two of one colour must never draw as |
| 33 | // parallel lines — nothing distinguishes them, so the second is pure over-draw — and what |
| 34 | // stops that is the slot, which is assigned per colour so they land on top of each other. |
| 35 | // This drops the ones that are wholly redundant as well, so the layer does not carry a |
| 36 | // route's two directions and every other feed's copy of them. |
| 37 | // |
| 38 | // The per-mode cover is for a line wearing its mode's fallback colour, which means the |
| 39 | // feed gave it none: if that track is already drawn in *someone's* colour, a line with |
| 40 | // no colour of its own should not be drawn over it in a guessed one. |
| 41 | let mut by_color: BTreeMap<(&'static str, u32), bundle::Covered> = BTreeMap::new(); |
| 42 | let mut by_mode: BTreeMap<&'static str, bundle::Covered> = BTreeMap::new(); |
| 43 | let (mut kept, mut without_shape, mut deduped, mut fell_back) = (0usize, 0usize, 0usize, 0usize); |
| 44 | let (mut shapes_read, mut merged) = (0usize, 0usize); |
| 45 | let mut crowded = 0usize; |
| 46 | |
| 47 | // Feeds are parsed in parallel and folded in sequentially. |
| 48 | // |
| 49 | // Parsing is pure per feed and was most of the wall clock: a world-scale set spent ~40 of |
| 50 | // its 54 minutes here, single-threaded, on machines with dozens of idle cores. The fold |
| 51 | // below cannot move — `seen`, `by_color` and `by_mode` are order-dependent, and feed order |
| 52 | // is what decides which duplicate of a shared alignment survives — so only the reads are |
| 53 | // spread out, and their results are put back into spec order before any of them is folded. |
| 54 | // The output is therefore bit-identical to the sequential version. |
| 55 | // |
| 56 | // Chunked rather than read-all-then-fold: a chunk of twice the pool keeps every core busy |
| 57 | // while capping how many parsed feeds are alive at once, so peak memory follows the pool |
| 58 | // size and not the number of feeds. |
| 59 | // |
| 60 | // ONE subphase for the whole feed loop below: thousands of feeds must not |
| 61 | // produce thousands of entries. The sequential fold rides along inside it. |
| 62 | if let Some(t) = timer.as_mut() { |
| 63 | t.switch("parse-feeds"); |
| 64 | } |
| 65 | let parse_start = Instant::now(); |
| 66 | let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); |
| 67 | let chunk_size = threads.saturating_mul(2).max(1); |
| 68 | |
| 69 | let total = match inputs { |
| 70 | Inputs::Feeds(specs) => specs.len(), |
| 71 | Inputs::Pack(_) => 1, |
| 72 | }; |
| 73 | let chunks: Vec<&[FeedSpec]> = match inputs { |
| 74 | Inputs::Feeds(specs) => specs.chunks(chunk_size).collect(), |
| 75 | // One pass over the whole pack: it is already one merged, ordered set. |
| 76 | Inputs::Pack(_) => vec![&[]], |
| 77 | }; |
| 78 | let mut processed = 0usize; |
| 79 | for chunk in chunks { |
| 80 | let parsed = match inputs { |
| 81 | Inputs::Pack(path) => vec![(0, super::pack::pack_lines(path))], |
| 82 | Inputs::Feeds(_) => parse_chunk(chunk, threads), |
| 83 | }; |
| 84 | |
| 85 | // Feeds unwrapped in spec order and their lines gathered, so the dedup key of every |
| 86 | // line can be computed wide before the sequential fold. Stats accumulate here so an |
| 87 | // unreadable feed still surfaces its error in feed order, exactly as before. |
| 88 | let mut chunk_lines: Vec<Line> = Vec::new(); |
| 89 | for (_, feed) in parsed { |
| 90 | let feed = feed?; |
| 91 | kept += feed.routes_kept; |
| 92 | without_shape += feed.routes_without_shape; |
| 93 | shapes_read += feed.shapes_read; |
| 94 | chunk_lines.extend(feed.lines); |
| 95 | processed += 1; |
| 96 | print_feed_meter(processed, total, &parse_start); |
| 97 | } |
| 98 | |
| 99 | // The dedup key is a content hash of the geometry, so it is order-independent and every |
| 100 | // line's can be computed in parallel. Only the `seen.insert` below stays sequential — |
| 101 | // it is what decides, in feed order, which duplicate of a shared alignment survives. |
| 102 | let keys: Vec<(u64, u32)> = chunk_lines |
| 103 | .par_iter() |
| 104 | .map(|line| (polyline_hash(&line.points), line.color)) |
| 105 | .collect(); |
| 106 | |
| 107 | for (line, key) in chunk_lines.into_iter().zip(keys) { |
| 108 | // Across feeds as well as within one, so an alignment published by both a city |
| 109 | // feed and the regional feed that merges it draws once. |
| 110 | // |
| 111 | // Keyed on the colour too, which the hash alone was not: two services running |
| 112 | // the same track are routinely published against one `shape_id`, and dropping |
| 113 | // one of them because its geometry had been seen is how a corridor loses a |
| 114 | // line. This is only the fast path for the subtraction below, which would reach |
| 115 | // the same answer the slow way. |
| 116 | if !seen.insert(key) { |
| 117 | deduped += 1; |
| 118 | continue; |
| 119 | } |
| 120 | // Walked once here: `covered_fraction`, `crowd_reaches` and the two `add`s |
| 121 | // below each used to re-walk `line.points` and allocate a fresh sample vector. |
| 122 | // The samples depend only on the geometry, so one walk feeds all four. |
| 123 | let walked = bundle::walk(&line.points); |
| 124 | let mode_cover = by_mode.entry(line.mode).or_default(); |
| 125 | let redundant = if line.fallback { |
| 126 | mode_cover.covered_fraction_walked(&walked) >= MOSTLY_DRAWN |
| 127 | } else { |
| 128 | by_color |
| 129 | .entry((line.mode, line.color)) |
| 130 | .or_default() |
| 131 | .covered_fraction_walked(&walked) |
| 132 | >= MOSTLY_DRAWN |
| 133 | }; |
| 134 | if redundant { |
| 135 | merged += 1; |
| 136 | continue; |
| 137 | } |
| 138 | // The gates above are colour-scoped, deliberately: two services sharing a track |
| 139 | // are two real services and both should draw. On a planet that stops being true. |
| 140 | // One alignment is republished by a city feed, the regional feed containing it and |
| 141 | // a national feed on top, each with its own `route_color` and often its own |
| 142 | // `route_type`, so each reads as a distinct service and claims its own lane. That |
| 143 | // is what makes one railway render as fifteen jagged parallel lines. |
| 144 | // |
| 145 | // A ceiling rather than a ban, so the two-services-on-one-track case the tests |
| 146 | // pin still works. Above it the track is already saying everything it can. |
| 147 | // |
| 148 | // Intercity lines are exempt: at country zoom they are the only transit drawn, so |
| 149 | // losing one to a crowded shared corridor (the Northeast Corridor carries a dozen |
| 150 | // commuter services) would cut a gap in the national network. |
| 151 | if !line.intercity && mode_cover.crowd_reaches_walked(&walked, MAX_SERVICES_PER_TRACK) { |
| 152 | crowded += 1; |
| 153 | continue; |
| 154 | } |
| 155 | mode_cover.add_tagged_walked(&walked, line.color); |
| 156 | by_color.entry((line.mode, line.color)).or_default().add_walked(&walked); |
| 157 | if line.fallback { |
| 158 | fell_back += 1; |
| 159 | } |
| 160 | lines.push(line); |
| 161 | } |
| 162 | } |
| 163 | eprintln!(); |
| 164 | drop(by_color); |
| 165 | drop(by_mode); |
| 166 | |
| 167 | // Which routes share a corridor, which lane each takes in it, and where each line has |
| 168 | // to be cut for that lane to change. Once, over the whole set: neither the tiler nor |
| 169 | // the renderer sees more than one tile, so deciding it there is what puts a jog in every |
| 170 | // route at every tile seam. |
| 171 | let bundled = expand_corridor_spans(&mut lines, timer.as_mut()); |
| 172 | if let Some(t) = timer.as_mut() { |
| 173 | t.switch("write-output"); |
| 174 | } |
| 175 | |
| 176 | // Deterministic output, so a rebuild produces a byte-identical layer and the |
| 177 | // tile diff is empty when nothing changed. Feed order already fixes which |
| 178 | // duplicate survives; this fixes the order they are written in. |
| 179 | lines.par_sort_by(|a, b| { |
| 180 | a.points |
| 181 | .cmp(&b.points) |
| 182 | .then_with(|| a.color.cmp(&b.color)) |
| 183 | .then_with(|| a.mode.cmp(b.mode)) |
| 184 | .then_with(|| (a.ordinal, a.lanes, a.taper).cmp(&(b.ordinal, b.lanes, b.taper))) |
| 185 | .then_with(|| a.route.cmp(&b.route)) |
| 186 | }); |
| 187 | |
| 188 | let file = std::fs::File::create(out_path) |
| 189 | .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?; |
| 190 | let mut out = BufWriter::new(file); |
| 191 | let mut buf: Vec<u8> = Vec::new(); |
| 192 | for line in &lines { |
| 193 | buf.clear(); |
| 194 | buf.extend_from_slice( |
| 195 | b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"LineString\",\"coordinates\":[", |
| 196 | ); |
| 197 | for (i, (lat, lon)) in line.points.iter().enumerate() { |
| 198 | if i > 0 { |
| 199 | buf.push(b','); |
| 200 | } |
| 201 | write!(buf, "[{:.7},{:.7}]", *lon as f64 * 1e-7, *lat as f64 * 1e-7) |
| 202 | .map_err(io_err)?; |
| 203 | } |
| 204 | write!( |
| 205 | buf, |
| 206 | "]}},\"properties\":{{\"color\":\"{:06X}\",\"mode\":\"{}\",\"ordinal\":{},\ |
| 207 | \"lanes\":{},\"taper\":{},{}\"route\":\"", |
| 208 | intercity::drawn_color(line.color, line.intercity, fallback_color(line.mode)), |
| 209 | line.mode, |
| 210 | line.ordinal, |
| 211 | line.lanes, |
| 212 | line.taper, |
| 213 | // Only when set, so every other line is written exactly as before. |
| 214 | if line.intercity { "\"intercity\":1," } else { "" }, |
| 215 | ) |
| 216 | .map_err(io_err)?; |
| 217 | json_escape(line.route.as_bytes(), &mut buf); |
| 218 | buf.extend_from_slice(b"\"}}\n"); |
| 219 | out.write_all(&buf).map_err(io_err)?; |
| 220 | } |
| 221 | out.flush().map_err(io_err)?; |
| 222 | |
| 223 | // TIMING before the human summary: stdout carries facts + TIMING only. |
| 224 | if let Some(t) = timer { |
| 225 | t.finish(); |
| 226 | } |
| 227 | |
| 228 | println!( |
| 229 | "transit_shapes: wrote {} ({} feed(s), {kept} rail route(s) kept, \ |
| 230 | {without_shape} with no usable shape, {shapes_read} shape(s) read, \ |
| 231 | {deduped} republished byte-for-byte, {merged} already drawn in their colour, \ |
| 232 | {crowded} over track already carrying {MAX_SERVICES_PER_TRACK} services, \ |
| 233 | {} line(s), {} intercity, {bundled} in a shared corridor, \ |
| 234 | {fell_back} on a per-mode fallback colour)", |
| 235 | out_path.display(), |
| 236 | total, |
| 237 | lines.len(), |
| 238 | lines.iter().filter(|l| l.intercity).count(), |
| 239 | ); |
| 240 | Ok(()) |
| 241 | } |
| 242 | |
| 243 | /// Parse one chunk of feeds on `threads` workers, back in spec order, so the fold sees exactly |
| 244 | /// the sequence a sequential read would give it. |
| 245 | fn parse_chunk(chunk: &[FeedSpec], threads: usize) -> Vec<(usize, Result<FeedLines, String>)> { |
| 246 | let next = AtomicUsize::new(0); |
| 247 | let parsed: Mutex<Vec<(usize, Result<FeedLines, String>)>> = |
| 248 | Mutex::new(Vec::with_capacity(chunk.len())); |
| 249 | std::thread::scope(|scope| { |
| 250 | for _ in 0..threads.min(chunk.len()) { |
| 251 | scope.spawn(|| loop { |
| 252 | let i = next.fetch_add(1, Ordering::Relaxed); |
| 253 | if i >= chunk.len() { |
| 254 | break; |
| 255 | } |
| 256 | let read = read_feed(&chunk[i]); |
| 257 | parsed.lock().expect("feed reader pool").push((i, read)); |
| 258 | }); |
| 259 | } |
| 260 | }); |
| 261 | let mut parsed = parsed.into_inner().expect("feed reader pool"); |
| 262 | parsed.sort_unstable_by_key(|(i, _)| *i); |
| 263 | parsed |
| 264 | } |
| 265 | |
| 266 | /// One stderr redraw of the feed-parse meter in the standard shape: |
| 267 | /// `\r{label:<28} [{pct:>3}%] {done}/{total} {elapsed} elapsed, ETA {eta}`. |
| 268 | fn print_feed_meter(done: usize, total: usize, start: &Instant) { |
| 269 | let elapsed = start.elapsed().as_secs_f64(); |
| 270 | let pct = if total == 0 { 100 } else { (done * 100 / total.max(1)).min(100) }; |
| 271 | let eta = if done == 0 { |
| 272 | "--".to_string() |
| 273 | } else { |
| 274 | fmt_dur(elapsed / done as f64 * (total - done) as f64) |
| 275 | }; |
| 276 | eprint!( |
| 277 | "\r{:<28} [{:>3}%] {done}/{total} {} elapsed, ETA {eta}", |
| 278 | "Parse feeds", |
| 279 | pct, |
| 280 | fmt_dur(elapsed), |
| 281 | ); |
| 282 | let _ = std::io::stderr().flush(); |
| 283 | } |
| 284 | |
| 285 | /// Short stable durations for the meter: `12s`, `2m05s`, `1h02m`. |
| 286 | fn fmt_dur(secs: f64) -> String { |
| 287 | let s = secs.max(0.0).round() as u64; |
| 288 | if s < 60 { |
| 289 | format!("{s}s") |
| 290 | } else if s < 3600 { |
| 291 | format!("{}m{:02}s", s / 60, s % 60) |
| 292 | } else { |
| 293 | format!("{}h{:02}m", s / 3600, (s % 3600) / 60) |
| 294 | } |
| 295 | } |