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

Modern-Apps.git / scripts / maps / mamaps_build / src / lanefill.rs

lanefill.rs464 lines · 21.7 KiBRaw
1//! Fill in the lane count of a junction stub from the road it interrupts.
2//!
3//! # The defect this exists for
4//!
5//! [`schema::roads::lane_count`](crate::schema::roads::lane_count) reads the OSM `lanes` tag and
6//! nothing else, and a way that does not carry one gets zero — which the renderer turns into
7//! `oneway ? 1 : 2`. That default is right for the untagged residential street it was written for.
8//! It is wrong for the twenty metres of asphalt between the two carriageways of a divided
9//! arterial, because a mapper who tagged `lanes=6` on the road either side very often left the
10//! short piece in the middle untagged.
11//!
12//! The result reaches a screen as an intersection that is *narrower than the roads entering it*.
13//! Measured at Broadway × Rollins Road in Burlingame, the case this was written for: Rollins is
14//! 6.1 painted lanes west of the junction and 4.1 east of it, and **2.0 lanes through it** — the
15//! narrowest pavement in the scene is the middle of the intersection. Way `417329335` is that
16//! stub: nineteen metres, no `lanes`, no `lanes:forward`, no `lanes:backward`, sitting between
17//! neighbours tagged 6 and 4.
18//!
19//! **This is not a defect in the extract.** [`crate::extract`] reads one OSM way to one feature
20//! and never splits a way, so there is no `lanes` tag being dropped anywhere. The data genuinely
21//! does not have one.
22//!
23//! # What this is, and what it is not
24//!
25//! **It is inference, and it must be read as inference.** Nothing here is tagged. What makes it
26//! legitimate is not that the guess is good but that *the thing it replaces is also a guess* —
27//! `oneway ? 1 : 2` is an invention with no more support in the data than this has, and it is a
28//! worse one, because it ignores the two tagged measurements sitting at either end of the way it
29//! is guessing about. Replacing a context-free invention with a context-sensitive one is the whole
30//! of the claim. It is not a claim that the answer is right.
31//!
32//! Nothing here ever overrides a tag. A way that carries `lanes` keeps it.
33//!
34//! # What counts as the same road
35//!
36//! A way inherits only when **every** one of these holds. Each was measured against the whole San
37//! Francisco peninsula extract — 27,287 drivable ways, of which 13,674 carry no `lanes` tag.
38//!
39//! * **It carries no `lanes` tag at all.** Never override data.
40//! * **It has a name**, and the donor has the same one.
41//! * **It is at most [`MAX_STUB_M`] long.**
42//! * **A donor at *both* ends**, each collinear within [`MAX_TURN_DEGREES`] and agreeing on
43//! one-wayness.
44//! * **The donor is itself tagged.** Not inherited — see "one hop" below.
45//!
46//! ## Why name *and* collinearity, rather than either
47//!
48//! | rule | candidates | of which the donor disagrees on one-wayness |
49//! |---|---|---|
50//! | same name only | 343 | 77 |
51//! | collinear only | 393 | 77 |
52//! | **both** | **290** | **40** |
53//!
54//! Neither alone is safe. Name alone joins a street to itself around a hard corner, which is a
55//! different carriageway. Collinearity alone joins a street to whatever runs straight on through
56//! the junction, and a road changing its name at a crossroads is ordinary. Requiring both is the
57//! intersection of the two, and the last column is the evidence that it is the *right*
58//! intersection rather than merely the smaller one: the disagreement rate on an independent
59//! attribute nobody selected for — one-wayness — halves. Pairs that were never the same
60//! carriageway are what that column counts, and requiring both conditions removes half of them.
61//!
62//! Matching on `ref` as well as `name` was measured and rejected: over the same extract it admits
63//! exactly one further way, a 257 m motorway spur, which [`MAX_STUB_M`] excludes anyway.
64//!
65//! ## Why one-wayness has to agree
66//!
67//! `lanes` counts **both** directions. A two-way `lanes=6` inherited onto a one-way stub paints
68//! six lanes running one way where the truth is about three, so the error is not a small
69//! misjudgement but a doubling, in the direction that reads as a broken map. This is a
70//! correctness condition and not a tuning knob; it costs 290 candidates down to 252.
71//!
72//! ## Why the minimum of the donors
73//!
74//! Over the same extract, at [`MAX_STUB_M`]: taking the minimum changes 113 ways by an average of
75//! +1.33 lanes; taking the maximum changes 135 by +1.82. Both fix the reported defect. The
76//! minimum is preferred because the two errors are not symmetric — too narrow reads as a cautious
77//! map and too wide reads as a wrong one.
78//!
79//! Note the gap between 156 ways that qualify and 113 that change: where the minimum lands on the
80//! value the default would have produced anyway, nothing is emitted. A rule that declines to speak
81//! unless both of its neighbours jointly justify it is behaving correctly, not under-reaching.
82//!
83//! ## Why a length bound, and why in metres
84//!
85//! Candidate lengths run to a long tail — median 33.5 m but p90 202.7 m and a maximum of 804 m.
86//! Unbounded, half a kilometre of El Camino Real quietly goes from the default 1 to 2, and 519 m
87//! of San Bruno Avenue West from 1 to 3. That is no longer a junction stub; it is a road, and a
88//! road acquiring a width from a neighbour it merely touches is the failure mode this bound
89//! exists to prevent.
90//!
91//! [`MAX_STUB_M`] is 50 because of what is being modelled rather than where a percentile falls.
92//! The subject is the pavement inside a junction, or the link between the two carriageways of a
93//! divided road: [`schema::junction`](crate::schema::junction) already takes an intersection to be
94//! about 14 m from its centre to its edge, so a box some 28 m across, and a divided-carriageway
95//! link runs 15–30 m. Fifty clears that comfortably and sits well below the p75 of 99 m, so it
96//! excludes the tail by construction. Relaxing 50 → 100 m buys 17 more changed ways; removing the
97//! bound entirely buys 49 and admits the two above.
98//!
99//! **Metres, not node count.** A node count looks like a proxy for a short way and is not one: way
100//! `23925587` in the same extract is a two-node way 497 m long.
101//!
102//! ## One hop, never a chain
103//!
104//! A donor must carry a real tag. An inherited count never becomes a donor, so a tagged way's
105//! width can travel exactly one way and no further — a property of the rule's shape rather than a
106//! limit someone has to remember to enforce. Chaining would also need iteration to a fixpoint
107//! inside a pass whose output must be byte-identical at every thread count.
108//!
109//! # What is deliberately *not* touched
110//!
111//! Only the lane **count** — the width the carriageway is painted. Not
112//! [`turn_masks`](crate::schema::roads::turn_masks) and not
113//! [`carriageway`](crate::schema::roads::carriageway).
114//!
115//! A count is a physical property of the road that plainly continues across a junction. A turn
116//! arrow and a directional split are surveys of a *particular* piece of asphalt, and they do not.
117//! There is also a concrete trap: `osm_ingest::tags::build_dir_lanes` pads its mask list to the
118//! lane count, so feeding an inferred count into the masks would grow the list and **draw turn
119//! arrows that no one tagged**. Ways with `turn:lanes` and no `lanes` do exist — way `417976725`
120//! on Rollins Road is one. Arrows stay strictly data-driven.
121//!
122//! # How it is computed
123//!
124//! A hash-partitioned external group-by, because the in-memory form does not survive contact with
125//! a planet build. Every named road way contributes one record per endpoint; on the peninsula
126//! extract that is tens of thousands, but scaled to a planet's ~70 M drivable ways it is of the
127//! order of 4 GB against a build already peaking near 7 GB. Pre-filtering by node count was
128//! measured and does not rescue it — it still holds ~1 GB while losing real candidates.
129//!
130//! So records go to [`PARTITIONS`] files, partitioned on the endpoint node id. Every way meeting
131//! at a node lands in the same file, which is the only grouping the rule needs, and each file is
132//! then sorted and grouped on its own. Peak memory is one partition rather than the whole planet.
133//!
134//! Recipients longer than [`MAX_STUB_M`] are dropped before they are ever written — an untagged
135//! way is never a donor, so a long untagged way cannot affect anything and need not be stored.
136//! That alone removes three quarters of the recipient records.
137//!
138//! Names are hashed to a `u64` rather than carried. A collision costs one wrong inheritance and
139//! cannot cost more than that: the collinearity and one-wayness conditions still have to pass, and
140//! the result is still bounded by [`MAX_STUB_M`] and by the minimum of the donors.
141
142use std::fs::File;
143use std::io::{BufWriter, Read, Write};
144use std::path::{Path, PathBuf};
145
146use osm_ingest::proto::{err, Error, Result};
147use rayon::prelude::*;
148use tile_build::par;
149
150/// The longest way that may inherit, in metres. See the module docs for why 50 and why metres.
151pub const MAX_STUB_M: f64 = 50.0;
152
153/// How far from straight a donor may leave the shared node and still be the same road, in degrees.
154///
155/// Zero is a perfect continuation. 45° was measured and rejected: it admits 17 more candidates and
156/// brings 17 more one-wayness disagreements with them, which is the whole of what it buys.
157pub const MAX_TURN_DEGREES: f64 = 30.0;
158
159/// How many files the endpoint records are partitioned across.
160///
161/// Only peak memory depends on this — one partition is held at a time — so it wants to be large
162/// enough that a planet's records divide into pieces of tens of megabytes, and small enough that
163/// the open file handles and the write buffers behind them stay cheap.
164pub const PARTITIONS: usize = 256;
165
166/// Metres per degree of latitude. Spherical, matching [`crate::schema::junction`], and worth
167/// centimetres over the tens of metres this module measures.
168const METRES_PER_DEGREE: f64 = 111_320.0;
169
170/// One endpoint record, fixed width so a partition is read back without a varint decoder.
171const RECORD_LEN: usize = 30;
172
173/// Bit 0 of a record's flag byte: the way is `oneway=yes`.
174const FLAG_ONEWAY: u8 = 1 << 0;
175/// Bit 1: this record is the way's *last* node rather than its first.
176const FLAG_LAST_END: u8 = 1 << 1;
177
178/// One named road way offered to the join.
179///
180/// `nodes` and `line` must be the same length: a way whose extract cut some of its nodes away has
181/// coordinates that no longer line up with its refs, and its neighbours are as likely to be
182/// missing as its geometry. Such a way is skipped rather than guessed at.
183pub struct Segment<'a> {
184 pub id: i64,
185 /// The OSM `name`. A way without one cannot take part.
186 pub name: &'a str,
187 /// The way's tagged lane count. Zero — no `lanes` tag — is what makes it a recipient; anything
188 /// else makes it a donor.
189 pub lanes: u8,
190 pub oneway: bool,
191 pub nodes: &'a [i64],
192 /// The way's coordinates in lon/lat, parallel to `nodes`.
193 pub line: &'a [(f64, f64)],
194}
195
196#[derive(Clone, Copy)]
197struct Record {
198 node: i64,
199 way: i64,
200 name_hash: u64,
201 /// Degrees clockwise from north, pointing *away* from `node` along the way.
202 bearing: f32,
203 lanes: u8,
204 flags: u8,
205}
206
207impl Record {
208 fn oneway(self) -> bool {
209 self.flags & FLAG_ONEWAY != 0
210 }
211
212 fn end(self) -> u8 {
213 u8::from(self.flags & FLAG_LAST_END != 0)
214 }
215
216 fn write(self, out: &mut impl Write) -> Result<()> {
217 let mut buf = [0u8; RECORD_LEN];
218 buf[0..8].copy_from_slice(&self.node.to_le_bytes());
219 buf[8..16].copy_from_slice(&self.way.to_le_bytes());
220 buf[16..24].copy_from_slice(&self.name_hash.to_le_bytes());
221 buf[24..28].copy_from_slice(&self.bearing.to_le_bytes());
222 buf[28] = self.lanes;
223 buf[29] = self.flags;
224 out.write_all(&buf).map_err(|e| Error(format!("cannot write a lanefill partition: {e}")))
225 }
226
227 fn read(buf: &[u8]) -> Record {
228 let at = |a: usize, b: usize| -> [u8; 8] { buf[a..b].try_into().expect("8 bytes") };
229 Record {
230 node: i64::from_le_bytes(at(0, 8)),
231 way: i64::from_le_bytes(at(8, 16)),
232 name_hash: u64::from_le_bytes(at(16, 24)),
233 bearing: f32::from_le_bytes(buf[24..28].try_into().expect("4 bytes")),
234 lanes: buf[28],
235 flags: buf[29],
236 }
237 }
238}
239
240/// Accumulates endpoint records, then resolves them into the ways whose lane count changes.
241pub struct Collector {
242 files: Vec<BufWriter<File>>,
243 paths: Vec<PathBuf>,
244}
245
246impl Collector {
247 /// Open the partition files. `stem` is a scratch path; each partition appends to it.
248 pub fn create(stem: &Path) -> Result<Collector> {
249 let mut files = Vec::with_capacity(PARTITIONS);
250 let mut paths = Vec::with_capacity(PARTITIONS);
251 for i in 0..PARTITIONS {
252 let path = stem.with_extension(format!("lanefill{i:03}.tmp"));
253 let file = File::create(&path)
254 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
255 // Small buffers: there are `PARTITIONS` of them held open at once, and each takes a
256 // steady trickle rather than a burst.
257 files.push(BufWriter::with_capacity(1 << 14, file));
258 paths.push(path);
259 }
260 Ok(Collector { files, paths })
261 }
262
263 /// Offer one way to the join. Ways that cannot take part are dropped here.
264 pub fn push(&mut self, segment: &Segment) -> Result<()> {
265 if segment.name.is_empty() || segment.nodes.len() < 2 {
266 return Ok(());
267 }
268 if segment.nodes.len() != segment.line.len() {
269 return Ok(());
270 }
271 let first = segment.nodes[0];
272 let last = segment.nodes[segment.nodes.len() - 1];
273 // A closed way has one endpoint, not two, so it can never have a donor at "both" ends and
274 // is not a junction stub in any case.
275 if first == last {
276 return Ok(());
277 }
278 // An untagged way is never a donor, so one too long to be a recipient cannot affect
279 // anything. Dropping it here rather than at resolve time is what keeps the spill small.
280 if segment.lanes == 0 && polyline_length_m(segment.line) > MAX_STUB_M {
281 return Ok(());
282 }
283 // The bearing leaving each end, skipping repeated coordinates: a duplicated vertex has no
284 // direction, and the graph does contain them where a way was split at a coincident point.
285 let Some(head) = leaving(segment.line, true) else { return Ok(()) };
286 let Some(tail) = leaving(segment.line, false) else { return Ok(()) };
287
288 let name_hash = hash_name(segment.name);
289 let base = if segment.oneway { FLAG_ONEWAY } else { 0 };
290 for (node, bearing, end) in [(first, head, 0u8), (last, tail, FLAG_LAST_END)] {
291 let record = Record {
292 node,
293 way: segment.id,
294 name_hash,
295 bearing: bearing as f32,
296 lanes: segment.lanes,
297 flags: base | end,
298 };
299 record.write(&mut self.files[partition_of(node)])?;
300 }
301 Ok(())
302 }
303
304 /// Resolve every partition and return `(way id, inherited lane count)` for the ways that
305 /// actually change, ascending by way id so the materialise pass can binary-search it.
306 ///
307 /// Ways whose inherited count equals the default they would have had anyway are left out, the
308 /// same way [`crate::corridor::promote`] leaves out ways its corridor does not move.
309 pub fn finish(mut self) -> Result<Vec<(i64, u8)>> {
310 for file in &mut self.files {
311 file.flush().map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?;
312 }
313 drop(self.files);
314
315 // `(way, end, donor lanes, one-way)`. The only state that outlives a partition, because a
316 // way's two endpoints hash to two different files and the "donor at both ends" condition
317 // cannot be decided until both have been seen.
318 //
319 // The 256 partitions are independent — every record for a node lives in exactly the one
320 // partition `partition_of` sends it to — so each is read, sorted and paired on its own
321 // thread and the per-partition pairs concatenated. `found` is globally sorted below, so the
322 // concatenation order never reaches the output: the resolution stays independent of both
323 // the write order and the partition order.
324 let per_partition: Vec<Vec<(i64, u8, u8, bool)>> = par::install(|| {
325 self.paths
326 .par_iter()
327 .map(|path| -> Result<Vec<(i64, u8, u8, bool)>> {
328 let mut records: Vec<Record> = Vec::new();
329 read_partition(path, &mut records)?;
330 let mut local: Vec<(i64, u8, u8, bool)> = Vec::new();
331 if !records.is_empty() {
332 // Sorted rather than hashed, for the reason `corridor::promote` gives: a
333 // hash map over the record count is the largest thing this pass would
334 // otherwise allocate. The full key makes the order total, so the output
335 // does not depend on the write order.
336 records.sort_unstable_by_key(|r| (r.node, r.way, r.flags));
337 for run in records.chunk_by(|a, b| a.node == b.node) {
338 pair_up(run, &mut local);
339 }
340 }
341 Ok(local)
342 })
343 .collect::<Result<Vec<_>>>()
344 })?;
345 let mut found: Vec<(i64, u8, u8, bool)> = per_partition.into_iter().flatten().collect();
346 for path in &self.paths {
347 let _ = std::fs::remove_file(path);
348 }
349
350 found.sort_unstable();
351 let mut out: Vec<(i64, u8)> = Vec::new();
352 for run in found.chunk_by(|a, b| a.0 == b.0) {
353 if !run.iter().any(|e| e.1 == 0) || !run.iter().any(|e| e.1 == 1) {
354 continue;
355 }
356 let inherited = run.iter().map(|e| e.2).min().unwrap_or(0);
357 // What the renderer would have drawn without us: `tile/geometry.rs` turns a zero lane
358 // count into one lane for a one-way and two for anything else.
359 let default = if run[0].3 { 1 } else { 2 };
360 if inherited != default {
361 out.push((run[0].0, inherited));
362 }
363 }
364 Ok(out)
365 }
366}
367
368/// Every recipient in `run` against every donor, appending the pairs that survive the conditions.
369fn pair_up(run: &[Record], found: &mut Vec<(i64, u8, u8, bool)>) {
370 for recipient in run.iter().filter(|r| r.lanes == 0) {
371 for donor in run.iter().filter(|d| d.lanes > 0) {
372 if donor.way == recipient.way
373 || donor.name_hash != recipient.name_hash
374 || donor.oneway() != recipient.oneway()
375 {
376 continue;
377 }
378 if deviation(f64::from(recipient.bearing), f64::from(donor.bearing)) > MAX_TURN_DEGREES
379 {
380 continue;
381 }
382 found.push((recipient.way, recipient.end(), donor.lanes, recipient.oneway()));
383 }
384 }
385}
386
387fn read_partition(path: &Path, out: &mut Vec<Record>) -> Result<()> {
388 out.clear();
389 let mut file =
390 File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
391 let mut bytes = Vec::new();
392 file.read_to_end(&mut bytes)
393 .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;
394 if bytes.len() % RECORD_LEN != 0 {
395 return err(format!(
396 "{} holds {} bytes, which is not a whole number of {RECORD_LEN}-byte records",
397 path.display(),
398 bytes.len(),
399 ));
400 }
401 out.reserve(bytes.len() / RECORD_LEN);
402 for chunk in bytes.chunks_exact(RECORD_LEN) {
403 out.push(Record::read(chunk));
404 }
405 Ok(())
406}
407
408/// Which partition an endpoint node belongs to.
409///
410/// Mixed rather than taken modulo directly: OSM node ids are allocated in runs, so the low bits of
411/// neighbouring ids are correlated and a plain modulo would fill a few partitions and starve the
412/// rest. This is the SplitMix64 finaliser, which is cheap and spreads the low bits.
413fn partition_of(node: i64) -> usize {
414 let mut z = (node as u64) ^ 0x9e37_79b9_7f4a_7c15;
415 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
416 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
417 ((z ^ (z >> 31)) % PARTITIONS as u64) as usize
418}
419
420/// FNV-1a over the name's bytes. See the module docs on why a collision is survivable.
421fn hash_name(name: &str) -> u64 {
422 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
423 for byte in name.as_bytes() {
424 hash ^= u64::from(*byte);
425 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
426 }
427 hash
428}
429
430/// The bearing leaving the line's first (or last) point, walking past repeated coordinates.
431///
432/// `None` when every point is the same place, which has no direction to report.
433fn leaving(line: &[(f64, f64)], from_start: bool) -> Option<f64> {
434 if from_start {
435 let origin = *line.first()?;
436 Some(bearing(origin, *line.iter().skip(1).find(|p| **p != origin)?))
437 } else {
438 let origin = *line.last()?;
439 Some(bearing(origin, *line.iter().rev().skip(1).find(|p| **p != origin)?))
440 }
441}
442
443/// Bearing from `a` to `b` in degrees clockwise from north. Both are lon/lat.
444fn bearing(a: (f64, f64), b: (f64, f64)) -> f64 {
445 let north = b.1 - a.1;
446 let east = (b.0 - a.0) * a.1.to_radians().cos();
447 east.atan2(north).to_degrees()
448}
449
450/// How far two bearings are from being a straight continuation of one another, in degrees.
451///
452/// Both point *away* from the node they share, so a road running straight through it leaves on two
453/// bearings 180° apart and scores zero.
454fn deviation(a: f64, b: f64) -> f64 {
455 let mut delta = (a - b) % 360.0;
456 if delta > 180.0 {
457 delta -= 360.0;
458 } else if delta < -180.0 {
459 delta += 360.0;
460 }
461 (180.0 - delta.abs()).abs()
462}
463
464include!("lanefill_part1.rs");