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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bundle_part3.rs

bundle_part3.rs274 lines · 12.0 KiBRaw
1impl Covered {
2 /// Record every metre of `line` as drawn.
3 pub fn add(&mut self, line: &[(i32, i32)]) {
4 self.add_tagged(line, 0);
5 }
6
7 /// Record every metre of `line` as drawn by service `tag`.
8 pub fn add_tagged(&mut self, line: &[(i32, i32)], tag: u32) {
9 self.add_tagged_walked(&walk(line), tag);
10 }
11
12 /// [`add`](Self::add) over samples already walked by [`walk`].
13 pub fn add_walked(&mut self, walked: &[Walked]) {
14 self.add_tagged_walked(walked, 0);
15 }
16
17 /// [`add_tagged`](Self::add_tagged) over samples already walked by [`walk`], so a caller
18 /// running several gates over one line walks it once and shares the result.
19 pub fn add_tagged_walked(&mut self, walked: &[Walked], tag: u32) {
20 for &sample in walked {
21 let cell = cell_of(sample.0);
22 // One representative per cell per service: a second sample of the same service in
23 // the same cell cannot change any `covers`/`tags_over` answer, and dropping it is
24 // what stops a heavily-republished trunk's buckets growing with the feed count.
25 if !self.filled.insert((cell, tag)) {
26 continue;
27 }
28 let at = self.points.len() as u32;
29 self.cells.entry(cell).or_default().push(at);
30 self.points.push(sample);
31 self.tags.push(tag);
32 }
33 }
34
35 /// The most distinct services already drawn over any one metre of `line`.
36 ///
37 /// The colour-scoped gates above stop a service being drawn twice, but they are deliberately
38 /// blind to *other* services: two lines sharing a track are two real services and both should
39 /// draw, fanned into lanes. That holds for a city. It does not hold for a planet, where one
40 /// physical alignment is republished by a city feed, the regional feed that contains it and a
41 /// national feed on top, each under its own `route_color` and often its own `route_type` — all
42 /// of which read as distinct services and each claim a lane. That is what turns one railway
43 /// into fifteen jagged parallel lines when you zoom in.
44 ///
45 /// So the rule is a ceiling rather than a ban: a few services over one track is real, fifteen
46 /// is a data artefact. Returns the worst point rather than an average, because a line that
47 /// joins a crowded trunk for part of its length is exactly the case worth suppressing.
48 ///
49 /// `limit` stops the walk as soon as any point reaches it. The answer above the ceiling is
50 /// never used, only compared against it, and this is called once per surviving line over a
51 /// structure holding every sample of every line already drawn.
52 pub fn crowd_reaches(&self, line: &[(i32, i32)], limit: usize) -> bool {
53 self.crowd_reaches_walked(&walk(line), limit)
54 }
55
56 /// [`crowd_reaches`](Self::crowd_reaches) over samples already walked by [`walk`].
57 pub fn crowd_reaches_walked(&self, walked: &[Walked], limit: usize) -> bool {
58 if limit == 0 {
59 return true;
60 }
61 let mut seen: Vec<u32> = Vec::new();
62 for &(point, ux, uy) in walked {
63 seen.clear();
64 self.tags_over(point, ux, uy, &mut seen, limit);
65 if seen.len() >= limit {
66 return true;
67 }
68 }
69 false
70 }
71
72 /// The most distinct services already drawn over any one metre of `line`.
73 ///
74 /// Unbounded, for tests and for reporting. Prefer [`crowd_reaches`](Self::crowd_reaches) on
75 /// the build path, which stops as soon as the answer can no longer change the decision.
76 pub fn crowd(&self, line: &[(i32, i32)]) -> usize {
77 let mut worst = 0;
78 let mut seen: Vec<u32> = Vec::new();
79 for &(point, ux, uy) in &walk(line) {
80 seen.clear();
81 self.tags_over(point, ux, uy, &mut seen, usize::MAX);
82 worst = worst.max(seen.len());
83 }
84 worst
85 }
86
87 /// Every distinct service drawn within [`CORRIDOR_M`] of this point, running parallel to it.
88 ///
89 /// Stops once `limit` distinct services have been found, since no caller needs more.
90 fn tags_over(&self, point: (i32, i32), ux: f64, uy: f64, out: &mut Vec<u32>, limit: usize) {
91 let (cx, cy) = cell_of(point);
92 for (dx, dy) in NEIGHBOURHOOD {
93 let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else { continue };
94 for &i in bucket {
95 let (other, oux, ouy) = self.points[i as usize];
96 if (ux * oux + uy * ouy).abs() < COS_FOLD {
97 continue;
98 }
99 if distance_m(point, other) <= CORRIDOR_M {
100 let tag = self.tags[i as usize];
101 if !out.contains(&tag) {
102 out.push(tag);
103 if out.len() >= limit {
104 return;
105 }
106 }
107 }
108 }
109 }
110 }
111
112 /// Is every metre of `line` already drawn?
113 ///
114 /// Walked at [`SAMPLE_M`] rather than at the line's own vertices, whose spacing is a
115 /// feed's business and is sometimes hundreds of metres.
116 pub fn contains(&self, line: &[(i32, i32)]) -> bool {
117 self.covered_fraction(line) >= 1.0
118 }
119
120 /// How much of `line` is already drawn, from 0 to 1. A line too short to walk covers nothing,
121 /// so it reports 0 and is kept — matching what the all-or-nothing test used to do with it.
122 ///
123 /// The all-or-nothing [`contains`](Self::contains) is too strict for one real case: a route
124 /// published twice at slightly different *lengths*. A short-turn, or one feed's version
125 /// running two stops further than another's, shares 95% of its alignment with what is already
126 /// drawn, adds a little genuinely new track at one end, and is therefore kept **whole** —
127 /// duplicating the 95%. On the ground that draws the A line as two strands about a metre
128 /// apart, each fanned into its own corridor lane and tapered, so one line reads as two
129 /// diverging and reconverging.
130 ///
131 /// Subtracting the covered part instead is not the answer and was tried: it cut every route
132 /// into fragments and left holes where a piece fell below the length worth emitting. A
133 /// fraction keeps the whole-line rule and only moves where the threshold sits.
134 pub fn covered_fraction(&self, line: &[(i32, i32)]) -> f64 {
135 self.covered_fraction_walked(&walk(line))
136 }
137
138 /// [`covered_fraction`](Self::covered_fraction) over samples already walked by [`walk`].
139 pub fn covered_fraction_walked(&self, walked: &[Walked]) -> f64 {
140 if walked.is_empty() {
141 return 0.0;
142 }
143 let drawn = walked.iter().filter(|&&(point, ux, uy)| self.covers(point, ux, uy)).count();
144 drawn as f64 / walked.len() as f64
145 }
146
147 /// Is this point already drawn, by track running parallel to it?
148 ///
149 /// Returns on the first match, so visit order matters — see [`NEIGHBOURHOOD`], which is
150 /// ordered for exactly that reason. The buckets are unbounded: [`add`](Self::add) records
151 /// every sample of every line it draws, and a trunk alignment republished by a dozen feeds is
152 /// a dozen overlapping sample runs in the same cells.
153 fn covers(&self, point: (i32, i32), ux: f64, uy: f64) -> bool {
154 let (cx, cy) = cell_of(point);
155 for (dx, dy) in NEIGHBOURHOOD {
156 let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else { continue };
157 for &i in bucket {
158 let (other, oux, ouy) = self.points[i as usize];
159 if (ux * oux + uy * ouy).abs() < COS_FOLD {
160 continue;
161 }
162 if distance_m(point, other) <= CORRIDOR_M {
163 return true;
164 }
165 }
166 }
167 false
168 }
169}
170
171/// Every candidate's samples, flat, with the range each candidate's own block occupies.
172///
173/// Each candidate is resampled independently, so the walks go wide and are concatenated back
174/// in candidate order — the blocks, and every sample within them, come out exactly as the
175/// sequential walk left them, so nothing downstream can tell the difference.
176fn sample_all(candidates: &[Candidate]) -> (Vec<Sample>, Vec<Range<usize>>) {
177 let per: Vec<Vec<Sample>> = candidates
178 .par_iter()
179 .map(|candidate| {
180 walk(candidate.points)
181 .into_iter()
182 .map(|(point, ux, uy)| Sample { route: candidate.route, point, ux, uy })
183 .collect()
184 })
185 .collect();
186 let mut out = Vec::with_capacity(per.iter().map(Vec::len).sum());
187 let mut blocks = Vec::with_capacity(candidates.len());
188 for samples in per {
189 let start = out.len();
190 out.extend(samples);
191 blocks.push(start..out.len());
192 }
193 (out, blocks)
194}
195
196type Cell = (i32, i32);
197
198/// The cell a point falls in. Square in metres rather than in degrees, so a cell near the
199/// pole is not a sliver: longitude is scaled by the cosine of its own latitude.
200fn cell_of(point: (i32, i32)) -> Cell {
201 let lat = point.0 as f64 * 1e-7;
202 let cos_lat = lat.to_radians().cos().max(1e-6);
203 let y = lat * 111_320.0 / CELL_M;
204 let x = point.1 as f64 * 1e-7 * 111_320.0 * cos_lat / CELL_M;
205 (x.floor() as i32, y.floor() as i32)
206}
207
208fn bucket<T: Copy>(grid: &[(Cell, T)], key: Cell) -> &[(Cell, T)] {
209 let lo = grid.partition_point(|(k, _)| *k < key);
210 let hi = grid.partition_point(|(k, _)| *k <= key);
211 &grid[lo..hi]
212}
213
214/// A sorted flat `(cell, sample)` vector, as [`crate::index`]'s transfer grid is.
215struct Grid {
216 entries: Vec<(Cell, u32)>,
217}
218
219impl Grid {
220 fn build(samples: &[Sample]) -> Grid {
221 let mut entries: Vec<(Cell, u32)> =
222 samples.iter().enumerate().map(|(i, s)| (cell_of(s.point), i as u32)).collect();
223 entries.par_sort_unstable();
224 Grid { entries }
225 }
226
227 /// The routes with a sample within [`CORRIDOR_M`] of `at` running parallel to it,
228 /// ascending and deduplicated. Always contains `at`'s own route.
229 ///
230 /// `seen` is a caller-owned scratch array of one slot per route, holding the `stamp` of
231 /// the sample a route was last accepted for. It replaces an `out.contains()` linear scan
232 /// that ran once per neighbouring sample: a 40 m cell holds ~4 samples per line at
233 /// [`SAMPLE_M`], so the nine-cell neighbourhood holds ~36 per route in the corridor, and
234 /// scanning `out` for each made the probe quadratic in *local route density*. On a
235 /// world-scale set that is the whole cost — dense metros carry the same trunk track
236 /// republished by every feed covering the city, so density there is far higher than the
237 /// feed count suggests, and the run time grows much faster than the input does.
238 ///
239 /// A route is stamped only when it is **accepted**, never when the angle or distance test
240 /// rejects it. That is what the `contains` check did — it tested membership of `out`, not
241 /// of everything examined — and a route rejected against one sample must stay eligible
242 /// against a nearer one in the same neighbourhood.
243 fn routes_near(
244 &self,
245 samples: &[Sample],
246 at: &Sample,
247 out: &mut Vec<u32>,
248 seen: &mut [u32],
249 stamp: u32,
250 ) {
251 out.clear();
252 out.push(at.route);
253 seen[at.route as usize] = stamp;
254 let (cx, cy) = cell_of(at.point);
255 for dx in -1..=1 {
256 for dy in -1..=1 {
257 for &(_, i) in bucket(&self.entries, (cx + dx, cy + dy)) {
258 let other = &samples[i as usize];
259 if seen[other.route as usize] == stamp {
260 continue;
261 }
262 if (at.ux * other.ux + at.uy * other.uy).abs() < COS_FOLD {
263 continue;
264 }
265 if distance_m(at.point, other.point) <= CORRIDOR_M {
266 seen[other.route as usize] = stamp;
267 out.push(other.route);
268 }
269 }
270 }
271 }
272 out.sort_unstable();
273 }
274}