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

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

bundle_part2.rs397 lines · 16.7 KiBRaw
1/// Run length, in samples, from which the snap search in [`spans_of`] goes wide. Changes no
2/// answer.
3const PAR_SNAP: usize = 64;
4
5/// One candidate's spans, in its own order of travel.
6fn spans_of(
7 candidate: &Candidate,
8 runs: &[Run],
9 samples: &[Sample],
10 probe_cum: &[f64],
11 own_cum: &[f64],
12 corridors: &BTreeMap<u32, Corridor>,
13) -> Vec<Span> {
14 let whole = || {
15 vec![Span { points: candidate.points.to_vec(), ordinal: 0, lanes: 1, taper: 255 }]
16 };
17 if runs.is_empty() || (runs.len() == 1 && !corridors.contains_key(&runs[0].set)) {
18 return whole();
19 }
20
21 // Per run independent, and collected in run order.
22 let placements: Vec<Option<Placement>> = runs
23 .par_iter()
24 .map(|run| {
25 let corridor = corridors.get(&run.set)?;
26 let a = distance_along(corridor, samples[run.from].point);
27 let b = distance_along(corridor, samples[run.to].point);
28 let (forward, lo, hi) = if a <= b { (true, a, b) } else { (false, b, a) };
29 // A run with no usable extent on the reference — the two ends project to one
30 // place — has nothing to snap to, so the candidate keeps its own geometry there.
31 if hi - lo < SAMPLE_M {
32 return None;
33 }
34 let near = |at: usize| within(corridor, samples[at].point, SNAP_M);
35 // Each probe is a walk of the whole reference, so a long run on a long corridor is
36 // the single most expensive thing in the cut. `find_first` / `find_last` are the
37 // sequential first and last match exactly, just searched wide.
38 let snap = if run.to - run.from < PAR_SNAP {
39 (run.from..=run.to).find(|&at| near(at)).map(|first| {
40 (first, (first..=run.to).rev().find(|&at| near(at)).unwrap_or(first))
41 })
42 } else {
43 (run.from..run.to + 1).into_par_iter().with_min_len(8).find_first(|&at| near(at)).map(|first| {
44 (first, (first..run.to + 1).into_par_iter().with_min_len(8).find_last(|&at| near(at)).unwrap_or(first))
45 })
46 };
47 Some(Placement { corridor, forward, lo, hi, snap })
48 })
49 .collect();
50
51 // Per run: its pieces and the points it begins and ends at, both in the candidate's order
52 // of travel, and whether that order runs against the reference's.
53 let mut pieces: Vec<Vec<Span>> = Vec::with_capacity(runs.len());
54 let mut ends: Vec<Option<Bounds>> = Vec::with_capacity(runs.len());
55 let mut against: Vec<bool> = Vec::with_capacity(runs.len());
56
57 for (at, run) in runs.iter().enumerate() {
58 let (own_from, own_to) = (probe_cum[run.from], probe_cum[run.to]);
59 let own_piece = |from: f64, to: f64, ordinal: u8, lanes: u8, taper: u8| -> Option<Span> {
60 let points = slice_between(candidate.points, own_cum, from, to);
61 (points.len() >= 2).then_some(Span { points, ordinal, lanes, taper })
62 };
63
64 let Some(place) = &placements[at] else {
65 let out: Vec<Span> = own_piece(own_from, own_to, 0, 1, 255).into_iter().collect();
66 ends.push(bounds_of(&out));
67 pieces.push(out);
68 against.push(false);
69 continue;
70 };
71 let corridor = place.corridor;
72 let lanes = u8::try_from(corridor.colours.len()).unwrap_or(u8::MAX);
73 let ordinal = corridor
74 .colours
75 .iter()
76 .position(|c| *c == candidate.color)
77 .and_then(|at| u8::try_from(at).ok())
78 .unwrap_or(0);
79
80 let Some((first, last)) = place.snap else {
81 let out: Vec<Span> =
82 own_piece(own_from, own_to, ordinal, lanes, 255).into_iter().collect();
83 ends.push(bounds_of(&out));
84 pieces.push(out);
85 against.push(!place.forward);
86 continue;
87 };
88
89 // A taper means one thing: opening the fan off the member's own alignment. A corridor
90 // of one colour has no fan to open, and where the neighbouring run is on a corridor
91 // too there is no own alignment to leave — the line is in a lane on both sides and
92 // steps from one to the other, which is a fraction of the fan rather than the whole
93 // of it dipping through zero.
94 let fanned = lanes > 1;
95 let eases = |other: Option<usize>| {
96 fanned && matches!(other, Some(i) if placements[i].is_none())
97 };
98 let at_start = eases(at.checked_sub(1));
99 let at_end = eases((at + 1 < runs.len()).then_some(at + 1));
100
101 // The ease runs from the run's start to where the member's own survey first comes
102 // within `SNAP_M`, which makes it adaptive: a shallow convergence gets a long ease
103 // and a sharp junction a short one. At least `TAPER_M` so the offset has somewhere to
104 // ramp when the member converges at once, and never more than a quarter of the run so
105 // the body keeps a usable share of it.
106 let extent = own_to - own_from;
107 let ease = |to_snap: f64| to_snap.max(TAPER_M).min(extent / 4.0);
108 let lead = if at_start { ease(probe_cum[first] - own_from) } else { 0.0 };
109 let trail = if at_end { ease(own_to - probe_cum[last]) } else { 0.0 };
110
111 // Where the body meets the reference: the handover point where there is an ease, and
112 // the run boundary where there is not.
113 let ref_at =
114 |own: f64| distance_along(corridor, point_at(candidate.points, own_cum, own));
115 let (from_end, to_end) =
116 if place.forward { (place.lo, place.hi) } else { (place.hi, place.lo) };
117 let body_from = if lead > 0.0 { ref_at(own_from + lead) } else { from_end };
118 let body_to = if trail > 0.0 { ref_at(own_to - trail) } else { to_end };
119
120 let mut out: Vec<Span> = Vec::new();
121 if lead > 0.0 {
122 let step = lead / TAPER_STEPS as f64;
123 for k in 0..TAPER_STEPS {
124 let base = own_from + k as f64 * step;
125 out.extend(own_piece(base, base + step, ordinal, lanes, taper_fraction(k + 1)));
126 }
127 }
128 let mut body = slice_between(&corridor.points, &corridor.cum, body_from, body_to);
129 if !place.forward {
130 body.reverse();
131 }
132 let mut body_exit = None;
133 if body.len() >= 2 {
134 let (head, tail) = (body[0], body[body.len() - 1]);
135 // The ease is on the member's own survey and the body is on the reference, up to
136 // `SNAP_M` apart. Carry one vertex across so the two meet, the same trick the
137 // inter-run weld below uses. The ease pieces themselves are adjoining slices of
138 // one polyline and already share their boundary vertex exactly.
139 if let Some(lead_end) = out.last_mut() {
140 if lead_end.points.last() != Some(&head) {
141 lead_end.points.push(head);
142 }
143 }
144 out.push(Span { points: body, ordinal, lanes, taper: 255 });
145 body_exit = Some(tail);
146 }
147 if trail > 0.0 {
148 let step = trail / TAPER_STEPS as f64;
149 let starts_at = out.len();
150 for k in 0..TAPER_STEPS {
151 let base = own_to - trail + k as f64 * step;
152 out.extend(own_piece(
153 base,
154 base + step,
155 ordinal,
156 lanes,
157 taper_fraction(TAPER_STEPS - k),
158 ));
159 }
160 if let (Some(tail), Some(trail_start)) = (body_exit, out.get_mut(starts_at)) {
161 if trail_start.points.first() != Some(&tail) {
162 trail_start.points.insert(0, tail);
163 }
164 }
165 }
166
167 ends.push(bounds_of(&out));
168 pieces.push(out);
169 against.push(!place.forward);
170 }
171
172 // Two runs meet at a point each of them located only to a sample step, and on two
173 // different polylines: a member's own survey and a reference, or two references where a
174 // route steps straight from one corridor into the next. Carry one across to the other so
175 // the pieces meet rather than leaving a gap at the seam — the corridor's own geometry
176 // where there is one to preserve, and the run that follows otherwise.
177 for at in 1..pieces.len() {
178 let (Some(before), Some(after)) = (ends[at - 1], ends[at]) else { continue };
179 if placements[at - 1].is_some() && placements[at].is_none() {
180 let head = pieces[at].first_mut().expect("bounds imply a piece");
181 if head.points.first() != Some(&before.1) {
182 head.points.insert(0, before.1);
183 }
184 } else {
185 let tail = pieces[at - 1].last_mut().expect("bounds imply a piece");
186 if tail.points.last() != Some(&after.0) {
187 tail.points.push(after.0);
188 }
189 }
190 }
191
192 // Every piece of a corridor run is stored in the reference's direction, so all its
193 // members share one left-hand normal and ordinal `i` is the same physical side for all of
194 // them. An ease piece is cut from the member's own survey and inherits that survey's
195 // direction, so for a member travelling against the reference it has to be turned round
196 // here or the fan mirrors across the ease. Only the order the pieces are listed in
197 // follows the candidate.
198 for (run_pieces, against) in pieces.iter_mut().zip(&against) {
199 if *against {
200 for span in run_pieces.iter_mut() {
201 span.points.reverse();
202 }
203 }
204 }
205
206 let flat: Vec<Span> = pieces.into_iter().flatten().collect();
207 if flat.is_empty() {
208 whole()
209 } else {
210 flat
211 }
212}
213
214/// Cumulative ground distance to each vertex of a polyline.
215fn cumulative(points: &[(i32, i32)]) -> Vec<f64> {
216 let mut out = Vec::with_capacity(points.len());
217 let mut total = 0.0;
218 for (at, point) in points.iter().enumerate() {
219 if at > 0 {
220 total += distance_m(points[at - 1], *point);
221 }
222 out.push(total);
223 }
224 out
225}
226
227/// The point `at` metres along a polyline, interpolated within its segment.
228fn point_at(points: &[(i32, i32)], cum: &[f64], at: f64) -> (i32, i32) {
229 if points.len() < 2 {
230 return points.first().copied().unwrap_or((0, 0));
231 }
232 let last = points.len() - 1;
233 if at <= 0.0 {
234 return points[0];
235 }
236 if at >= cum[last] {
237 return points[last];
238 }
239 let seg = cum.partition_point(|d| *d <= at).max(1) - 1;
240 let span = cum[seg + 1] - cum[seg];
241 let t = if span > 0.0 { (at - cum[seg]) / span } else { 0.0 };
242 let (a, b) = (points[seg], points[seg + 1]);
243 (
244 (a.0 as f64 + (b.0 - a.0) as f64 * t).round() as i32,
245 (a.1 as f64 + (b.1 - a.1) as f64 * t).round() as i32,
246 )
247}
248
249/// The part of a polyline between two distances along it, with both ends interpolated.
250///
251/// Both ends land exactly on the polyline, so two adjacent slices share their boundary
252/// vertex and the pieces of one route meet. Empty when the two distances leave nothing
253/// between them.
254fn slice_between(points: &[(i32, i32)], cum: &[f64], from: f64, to: f64) -> Vec<(i32, i32)> {
255 if points.len() < 2 {
256 return Vec::new();
257 }
258 let total = cum[cum.len() - 1];
259 let (from, to) = (from.clamp(0.0, total), to.clamp(0.0, total));
260 let (from, to) = if from <= to { (from, to) } else { (to, from) };
261 let mut out = vec![point_at(points, cum, from)];
262 for (at, along) in cum.iter().enumerate() {
263 if *along > from && *along < to && out[out.len() - 1] != points[at] {
264 out.push(points[at]);
265 }
266 }
267 let end = point_at(points, cum, to);
268 if out[out.len() - 1] != end {
269 out.push(end);
270 }
271 if out.len() < 2 {
272 Vec::new()
273 } else {
274 out
275 }
276}
277
278/// How far along a corridor's reference the nearest point to `p` lies.
279fn distance_along(corridor: &Corridor, p: (i32, i32)) -> f64 {
280 nearest(corridor, p).1
281}
282
283/// Segments per [`SegBlock`].
284const SEG_BLOCK: usize = 32;
285
286/// Slack, in metres, taken off every [`SegBlock::lower_bound`]: far above the nanometres of
287/// rounding [`project`] can introduce at planetary coordinates, far below anything a skip
288/// could save.
289const BOUND_SLACK_M: f64 = 0.01;
290
291/// The extent of a run of consecutive reference segments, in the terms [`project`] measures in.
292struct SegBlock {
293 lat_lo: i32,
294 lat_hi: i32,
295 lon_lo: i32,
296 lon_hi: i32,
297 /// The smallest of the run's per-segment `cos_lat`s, computed exactly as [`project`] does.
298 cos_min: f64,
299}
300
301impl SegBlock {
302 /// A floor under [`project`]'s distance from `p` to any segment of the run.
303 ///
304 /// `project` measures in metres north (`lat × k`, the same for every segment) and metres
305 /// east scaled by the segment's own `cos_lat`. The closest point of a segment lies inside
306 /// the segment's box, so its northing is at least the latitude gap from `p` to the run's
307 /// box away, and its easting at least the longitude gap times the smallest `cos_lat` in the
308 /// run. Less the slack, so the floor holds through rounding.
309 fn lower_bound(&self, p: (i32, i32)) -> f64 {
310 let k = 1e-7 * 111_320.0;
311 let (lat, lon) = (p.0 as f64, p.1 as f64);
312 let gy = (self.lat_lo as f64 - lat).max(lat - self.lat_hi as f64).max(0.0) * k;
313 let gx = (self.lon_lo as f64 - lon).max(lon - self.lon_hi as f64).max(0.0) * k * self.cos_min.max(0.0);
314 (gx * gx + gy * gy).sqrt() - BOUND_SLACK_M
315 }
316}
317
318fn seg_blocks(points: &[(i32, i32)]) -> Vec<SegBlock> {
319 let segs = points.len().saturating_sub(1);
320 (0..segs.div_ceil(SEG_BLOCK))
321 .map(|b| {
322 let (lo, hi) = (b * SEG_BLOCK, ((b + 1) * SEG_BLOCK).min(segs));
323 let run = &points[lo..=hi];
324 let cos_min = (lo..hi)
325 .map(|at| ((points[at].0 as f64 + points[at + 1].0 as f64) * 0.5 * 1e-7).to_radians().cos())
326 .fold(f64::INFINITY, f64::min);
327 SegBlock {
328 lat_lo: run.iter().map(|q| q.0).min().expect("two points"),
329 lat_hi: run.iter().map(|q| q.0).max().expect("two points"),
330 lon_lo: run.iter().map(|q| q.1).min().expect("two points"),
331 lon_hi: run.iter().map(|q| q.1).max().expect("two points"),
332 cos_min,
333 }
334 })
335 .collect()
336}
337
338/// The segments of block `b` of a polyline with `segs` segments.
339fn block_segs(b: usize, segs: usize) -> std::ops::Range<usize> {
340 b * SEG_BLOCK..((b + 1) * SEG_BLOCK).min(segs)
341}
342
343/// The nearest point on a corridor's reference to `p`, as `(distance to it, distance along)`.
344///
345/// The first segment, in reference order, at the smallest [`project`] distance — what a walk
346/// of every segment keeping strict improvements returns, which is what this used to be. That
347/// walk was most of the corridor cut on a world set: one per probe, over references of tens of
348/// thousands of points. Now the block with the lowest floor is measured first; its best
349/// distance bounds the answer from above, every block whose floor is over that bound is
350/// skipped — it cannot hold the minimum, nor tie it — and the rest are walked in reference
351/// order exactly as before.
352fn nearest(corridor: &Corridor, p: (i32, i32)) -> (f64, f64) {
353 let (points, cum) = (&corridor.points, &corridor.cum);
354 let segs = points.len().saturating_sub(1);
355 let blocks = &corridor.blocks;
356 let mut bound = f64::INFINITY;
357 if blocks.len() > 2 {
358 let mut seed = (f64::INFINITY, 0usize);
359 for (b, block) in blocks.iter().enumerate() {
360 let lb = block.lower_bound(p);
361 if lb < seed.0 {
362 seed = (lb, b);
363 }
364 }
365 for at in block_segs(seed.1, segs) {
366 let offset = project(p, points[at], points[at + 1], 0.0).1;
367 if offset < bound {
368 bound = offset;
369 }
370 }
371 }
372 let mut best = (f64::INFINITY, 0.0f64);
373 for (b, block) in blocks.iter().enumerate() {
374 if block.lower_bound(p) > bound {
375 continue;
376 }
377 for at in block_segs(b, segs) {
378 let (t, offset) = project(p, points[at], points[at + 1], 0.0);
379 if offset < best.0 {
380 best = (offset, cum[at] + t * (cum[at + 1] - cum[at]));
381 }
382 }
383 }
384 best
385}
386
387/// `nearest(corridor, p).0 <= radius`, deciding as soon as any segment is that close and
388/// skipping every block whose floor is already further.
389fn within(corridor: &Corridor, p: (i32, i32), radius: f64) -> bool {
390 let (points, segs) = (&corridor.points, corridor.points.len().saturating_sub(1));
391 corridor.blocks.iter().enumerate().any(|(b, block)| {
392 block.lower_bound(p) <= radius
393 && block_segs(b, segs).any(|at| project(p, points[at], points[at + 1], 0.0).1 <= radius)
394 })
395}
396
397include!("bundle_part2_s1.rs");