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

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

transit_shapes_extra2.rs430 lines · 19.4 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
4use super::*;
5use rayon::prelude::*;
6use 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)]
10pub(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)]
17pub(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`].
25pub(crate) fn run_with_timer(
26 out_path: &Path,
27 inputs: Inputs<'_>,
28 timer: Option<PhaseTimer>,
29) -> Result<(), String> {
30 run_windowed(out_path, inputs, timer, FOLD_WINDOW)
31}
32
33/// [`run_with_timer`] with the cover gates' speculative window as a parameter, so a test can
34/// pin that the window changes nothing: a window of one line is the sequential fold exactly.
35pub(crate) fn run_windowed(
36 out_path: &Path,
37 inputs: Inputs<'_>,
38 mut timer: Option<PhaseTimer>,
39 fold_window: usize,
40) -> Result<(), String> {
41 let fold_window = fold_window.max(1);
42 let mut seen: HashSet<(u64, u32)> = HashSet::new();
43 let mut lines: Vec<Line> = Vec::new();
44 // Track already drawn, per colour and per mode. Two of one colour must never draw as
45 // parallel lines — nothing distinguishes them, so the second is pure over-draw — and what
46 // stops that is the slot, which is assigned per colour so they land on top of each other.
47 // This drops the ones that are wholly redundant as well, so the layer does not carry a
48 // route's two directions and every other feed's copy of them.
49 //
50 // The per-mode cover is for a line wearing its mode's fallback colour, which means the
51 // feed gave it none: if that track is already drawn in *someone's* colour, a line with
52 // no colour of its own should not be drawn over it in a guessed one.
53 let mut by_color: BTreeMap<(&'static str, u32), bundle::Covered> = BTreeMap::new();
54 let mut by_mode: BTreeMap<&'static str, bundle::Covered> = BTreeMap::new();
55 let (mut kept, mut without_shape, mut deduped, mut fell_back) =
56 (0usize, 0usize, 0usize, 0usize);
57 let (mut shapes_read, mut merged) = (0usize, 0usize);
58 let mut crowded = 0usize;
59
60 // Feeds are parsed in parallel and folded in sequentially.
61 //
62 // Parsing is pure per feed and was most of the wall clock: a world-scale set spent ~40 of
63 // its 54 minutes here, single-threaded, on machines with dozens of idle cores. The fold
64 // below cannot move — `seen`, `by_color` and `by_mode` are order-dependent, and feed order
65 // is what decides which duplicate of a shared alignment survives — so only the reads are
66 // spread out, and their results are put back into spec order before any of them is folded.
67 // The output is therefore bit-identical to the sequential version.
68 //
69 // Chunked rather than read-all-then-fold: a chunk of twice the pool keeps every core busy
70 // while capping how many parsed feeds are alive at once, so peak memory follows the pool
71 // size and not the number of feeds.
72 //
73 // ONE subphase for the whole feed loop below: thousands of feeds must not
74 // produce thousands of entries. The sequential fold rides along inside it.
75 if let Some(t) = timer.as_mut() {
76 t.switch("parse-feeds");
77 }
78 let parse_start = Instant::now();
79 let threads = gtfs_ingest::par::threads();
80 let chunk_size = threads.saturating_mul(2).max(1);
81
82 let total = match inputs {
83 Inputs::Feeds(specs) => specs.len(),
84 Inputs::Pack(_) => 1,
85 };
86 let chunks: Vec<&[FeedSpec]> = match inputs {
87 Inputs::Feeds(specs) => specs.chunks(chunk_size).collect(),
88 // One pass over the whole pack: it is already one merged, ordered set.
89 Inputs::Pack(_) => vec![&[]],
90 };
91 let mut processed = 0usize;
92 for chunk in chunks {
93 let parsed = match inputs {
94 Inputs::Pack(path) => vec![(0, super::pack::pack_lines(path))],
95 Inputs::Feeds(_) => parse_chunk(chunk, threads),
96 };
97
98 // Feeds unwrapped in spec order and their lines gathered, so the dedup key of every
99 // line can be computed wide before the sequential fold. Stats accumulate here so an
100 // unreadable feed still surfaces its error in feed order, exactly as before.
101 let mut chunk_lines: Vec<Line> = Vec::new();
102 for (_, feed) in parsed {
103 let feed = feed?;
104 kept += feed.routes_kept;
105 without_shape += feed.routes_without_shape;
106 shapes_read += feed.shapes_read;
107 chunk_lines.extend(feed.lines);
108 processed += 1;
109 print_feed_meter(processed, total, &parse_start);
110 }
111
112 // The dedup key is a content hash of the geometry, so it is order-independent and every
113 // line's can be computed in parallel.
114 let keys: Vec<(u64, u32)> =
115 chunk_lines.par_iter().map(|line| (polyline_hash(&line.points), line.color)).collect();
116
117 // Across feeds as well as within one, so an alignment published by both a city feed and
118 // the regional feed that merges it draws once.
119 //
120 // Keyed on the colour too, which the hash alone was not: two services running the same
121 // track are routinely published against one `shape_id`, and dropping one of them because
122 // its geometry had been seen is how a corridor loses a line. This is only the fast path
123 // for the subtraction below, which would reach the same answer the slow way.
124 //
125 // Settled for the whole chunk before any cover gate runs: every line reaches
126 // `seen.insert` whatever the gates later decide about it, so which lines survive it is a
127 // function of the key sequence alone, and decides which duplicate survives, in feed
128 // order, exactly as the interleaved loop did.
129 let mut survivors: Vec<Line> = Vec::with_capacity(chunk_lines.len());
130 for (line, key) in chunk_lines.into_iter().zip(keys) {
131 if seen.insert(key) {
132 survivors.push(line);
133 } else {
134 deduped += 1;
135 }
136 }
137
138 // The cover gates. They are order-dependent — each line is judged against everything
139 // accepted before it — and this loop used to be the whole run: 293 of a planet's 380 s,
140 // on one core, walking and probing ~52 k lines one after another.
141 //
142 // Now speculative, and still exact. A window of lines is walked and judged in parallel
143 // against the covers as they stand at the window's start, then resolved in order. A
144 // speculated per-sample answer can only be stale where a line accepted earlier in the
145 // same window appended samples to a cell that answer read (`Covered::changed_near`
146 // against the cover's mark at speculation time), and a `true` is never stale, since both
147 // gates only grow as samples are appended. So resolution re-asks the live cover only for
148 // the samples that answered `false` beside such a cell — usually none, since a colour's
149 // cover changes only when a line of that colour was accepted earlier in the window.
150 // Every other answer is the one the sequential loop would have computed. Adds stay
151 // sequential and in order, so the covers evolve exactly as before, and the window size
152 // decides how much is re-asked, never what is decided.
153 let mut rest = survivors.into_iter();
154 loop {
155 let window: Vec<Line> = rest.by_ref().take(fold_window).collect();
156 if window.is_empty() {
157 break;
158 }
159 let specs: Vec<Speculated> =
160 window.par_iter().map(|line| speculate(line, &by_color, &by_mode)).collect();
161 // Freed off this thread: each line's samples were allocated on a worker, and handing
162 // a few hundred MB back to other threads' arenas one line at a time was a fifth of
163 // this loop.
164 let mut spent: Vec<(Vec<bundle::Walked>, Vec<bundle::Cell>, Vec<u32>)> =
165 Vec::with_capacity(window.len());
166 for (line, spec) in window.into_iter().zip(specs) {
167 let Speculated {
168 walked,
169 cells,
170 drawn,
171 uncovered,
172 redundant,
173 crowd,
174 gate_mark,
175 mode_mark,
176 } = spec;
177 let spent_len = spent.len();
178 spent.push((walked, cells, uncovered));
179 let (walked, cells, uncovered) = {
180 let (w, c, u) = &spent[spent_len];
181 (w.as_slice(), c.as_slice(), u.as_slice())
182 };
183 let gate = if line.fallback {
184 by_mode.get(line.mode)
185 } else {
186 by_color.get(&(line.mode, line.color))
187 };
188 let redundant = redundant
189 || gate.is_some_and(|g| {
190 if g.mark() == gate_mark {
191 return false;
192 }
193 recount_reaches(g, gate_mark, walked, cells, drawn, uncovered)
194 });
195 if redundant {
196 merged += 1;
197 continue;
198 }
199 // The gates above are colour-scoped, deliberately: two services sharing a track
200 // are two real services and both should draw. On a planet that stops being true.
201 // One alignment is republished by a city feed, the regional feed containing it
202 // and a national feed on top, each with its own `route_color` and often its own
203 // `route_type`, so each reads as a distinct service and claims its own lane. That
204 // is what makes one railway render as fifteen jagged parallel lines.
205 //
206 // A ceiling rather than a ban, so the two-services-on-one-track case the tests
207 // pin still works. Above it the track is already saying everything it can.
208 //
209 // Intercity lines are exempt: at country zoom they are the only transit drawn, so
210 // losing one to a crowded shared corridor (the Northeast Corridor carries a dozen
211 // commuter services) would cut a gap in the national network.
212 if !line.intercity {
213 // Speculated for every non-intercity line speculation did not find redundant,
214 // which is every line that can reach here.
215 let over = crowd.expect("crowd speculated")
216 || by_mode.get(line.mode).is_some_and(|m| {
217 m.mark() != mode_mark && recrowd_reaches(m, mode_mark, walked, cells)
218 });
219 if over {
220 crowded += 1;
221 continue;
222 }
223 }
224 let mode_cover = by_mode.entry(line.mode).or_default();
225 let color_cover = by_color.entry((line.mode, line.color)).or_default();
226 rayon::join(
227 || mode_cover.add_tagged_walked_in(walked, cells, line.color),
228 || color_cover.add_tagged_walked_in(walked, cells, 0),
229 );
230 if line.fallback {
231 fell_back += 1;
232 }
233 lines.push(line);
234 }
235 // On a one-thread pool a spawned job would only run once this thread goes idle -
236 // at the end of the run - so every window's samples would pile up until then.
237 if rayon::current_num_threads() > 1 {
238 rayon::spawn(move || drop(spent));
239 } else {
240 drop(spent);
241 }
242 }
243 }
244 eprintln!();
245 drop(by_color);
246 drop(by_mode);
247
248 // Which routes share a corridor, which lane each takes in it, and where each line has
249 // to be cut for that lane to change. Once, over the whole set: neither the tiler nor
250 // the renderer sees more than one tile, so deciding it there is what puts a jog in every
251 // route at every tile seam.
252 let bundled = expand_corridor_spans(&mut lines, timer.as_mut());
253 if let Some(t) = timer.as_mut() {
254 t.switch("write-output");
255 }
256
257 // Deterministic output, so a rebuild produces a byte-identical layer and the
258 // tile diff is empty when nothing changed. Feed order already fixes which
259 // duplicate survives; this fixes the order they are written in.
260 lines.par_sort_by(|a, b| {
261 a.points
262 .cmp(&b.points)
263 .then_with(|| a.color.cmp(&b.color))
264 .then_with(|| a.mode.cmp(b.mode))
265 .then_with(|| (a.ordinal, a.lanes, a.taper).cmp(&(b.ordinal, b.lanes, b.taper)))
266 .then_with(|| a.route.cmp(&b.route))
267 });
268
269 let file = std::fs::File::create(out_path)
270 .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?;
271 // Large sequential writes: the output disk compresses per extent.
272 let mut out = BufWriter::with_capacity(8 << 20, file);
273 // Each line's JSON depends on that line alone, so blocks of lines are formatted wide and
274 // written in order.
275 for block in lines.chunks(4096) {
276 let texts: Vec<Result<Vec<u8>, String>> = block.par_iter().map(feature_json).collect();
277 for text in texts {
278 out.write_all(&text?).map_err(io_err)?;
279 }
280 }
281 out.flush().map_err(io_err)?;
282
283 // TIMING before the human summary: stdout carries facts + TIMING only.
284 if let Some(t) = timer {
285 t.finish();
286 }
287
288 println!(
289 "transit_shapes: wrote {} ({} feed(s), {kept} rail route(s) kept, \
290 {without_shape} with no usable shape, {shapes_read} shape(s) read, \
291 {deduped} republished byte-for-byte, {merged} already drawn in their colour, \
292 {crowded} over track already carrying {MAX_SERVICES_PER_TRACK} services, \
293 {} line(s), {} intercity, {bundled} in a shared corridor, \
294 {fell_back} on a per-mode fallback colour)",
295 out_path.display(),
296 total,
297 lines.len(),
298 lines.iter().filter(|l| l.intercity).count(),
299 );
300 Ok(())
301}
302
303/// One output line: a GeoJSON `Feature` and its newline.
304fn feature_json(line: &Line) -> Result<Vec<u8>, String> {
305 let mut buf: Vec<u8> = Vec::with_capacity(64 + line.points.len() * 26);
306 buf.extend_from_slice(
307 b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"LineString\",\"coordinates\":[",
308 );
309 for (i, (lat, lon)) in line.points.iter().enumerate() {
310 if i > 0 {
311 buf.push(b',');
312 }
313 write!(buf, "[{:.7},{:.7}]", *lon as f64 * 1e-7, *lat as f64 * 1e-7).map_err(io_err)?;
314 }
315 write!(
316 buf,
317 "]}},\"properties\":{{\"color\":\"{:06X}\",\"mode\":\"{}\",\"ordinal\":{},\
318 \"lanes\":{},\"taper\":{},{}\"route\":\"",
319 intercity::drawn_color(line.color, line.intercity, fallback_color(line.mode)),
320 line.mode,
321 line.ordinal,
322 line.lanes,
323 line.taper,
324 // Only when set, so every other line is written exactly as before.
325 if line.intercity { "\"intercity\":1," } else { "" },
326 )
327 .map_err(io_err)?;
328 json_escape(line.route.as_bytes(), &mut buf);
329 buf.extend_from_slice(b"\"}}\n");
330 Ok(buf)
331}
332
333/// Parse one chunk of feeds on `threads` workers, back in spec order, so the fold sees exactly
334/// the sequence a sequential read would give it.
335fn parse_chunk(chunk: &[FeedSpec], threads: usize) -> Vec<(usize, Result<FeedLines, String>)> {
336 let next = AtomicUsize::new(0);
337 let parsed: Mutex<Vec<(usize, Result<FeedLines, String>)>> =
338 Mutex::new(Vec::with_capacity(chunk.len()));
339 std::thread::scope(|scope| {
340 for _ in 0..threads.min(chunk.len()) {
341 scope.spawn(|| loop {
342 let i = next.fetch_add(1, Ordering::Relaxed);
343 if i >= chunk.len() {
344 break;
345 }
346 let read = read_feed(&chunk[i]);
347 parsed.lock().expect("feed reader pool").push((i, read));
348 });
349 }
350 });
351 let mut parsed = parsed.into_inner().expect("feed reader pool");
352 parsed.sort_unstable_by_key(|(i, _)| *i);
353 parsed
354}
355
356/// One stderr redraw of the feed-parse meter in the standard shape:
357/// `\r{label:<28} [{pct:>3}%] {done}/{total} {elapsed} elapsed, ETA {eta}`.
358fn print_feed_meter(done: usize, total: usize, start: &Instant) {
359 let elapsed = start.elapsed().as_secs_f64();
360 let pct = if total == 0 { 100 } else { (done * 100 / total.max(1)).min(100) };
361 let eta = if done == 0 {
362 "--".to_string()
363 } else {
364 fmt_dur(elapsed / done as f64 * (total - done) as f64)
365 };
366 eprint!(
367 "\r{:<28} [{:>3}%] {done}/{total} {} elapsed, ETA {eta}",
368 "Parse feeds",
369 pct,
370 fmt_dur(elapsed),
371 );
372 let _ = std::io::stderr().flush();
373}
374
375/// Short stable durations for the meter: `12s`, `2m05s`, `1h02m`.
376fn fmt_dur(secs: f64) -> String {
377 let s = secs.max(0.0).round() as u64;
378 if s < 60 {
379 format!("{s}s")
380 } else if s < 3600 {
381 format!("{}m{:02}s", s / 60, s % 60)
382 } else {
383 format!("{}h{:02}m", s / 3600, (s % 3600) / 60)
384 }
385}
386
387/// Lines per speculative window of the cover gates. Decides only how much is re-asked at
388/// resolution, never what is decided. Measured on the world pack at 192 threads: 16 lines
389/// spent 12 s in window barriers, 128 spent 8 s re-asking, 64 balanced the two (~17 s for the
390/// whole fold, against 293 s sequential).
391const FOLD_WINDOW: usize = 64;
392
393/// The fewest drawn samples out of `len` for which `drawn as f64 / len as f64 >=
394/// MOSTLY_DRAWN` — the gate's own arithmetic, solved for the count, so comparing a count
395/// against it decides exactly what the division would.
396fn drawn_needed(len: usize) -> usize {
397 let at = |d: usize| d as f64 / len as f64 >= MOSTLY_DRAWN;
398 let mut d = ((MOSTLY_DRAWN * len as f64).floor() as usize).min(len);
399 while d > 0 && at(d - 1) {
400 d -= 1;
401 }
402 while !at(d) {
403 d += 1;
404 }
405 d
406}
407
408/// Samples below which a per-line pass stays on the calling thread: under it a fork-join
409/// costs more than it saves. Changes no answer.
410const PAR_SAMPLES: usize = 4096;
411
412/// One line judged against the covers as they stood at its window's start.
413struct Speculated {
414 walked: Vec<bundle::Walked>,
415 /// `bundle::sample_cell` of every walked sample.
416 cells: Vec<bundle::Cell>,
417 /// Samples already drawn in the gating cover.
418 drawn: usize,
419 /// The rest, by index into `walked`: the only answers resolution may have to revise.
420 uncovered: Vec<u32>,
421 redundant: bool,
422 /// The crowd gate's answer, for a line that can reach it (not redundant, not intercity).
423 crowd: Option<bool>,
424 /// `Covered::mark` of the gating cover and of the mode's cover when this ran (0 for a
425 /// cover not created yet, which answered as an empty one).
426 gate_mark: u32,
427 mode_mark: u32,
428}
429
430include!("transit_shapes_extra2_parts/transit_shapes_extra2_s1.rs");