Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / lanefill.rs
lanefill.rs354 lines · 16.6 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 | |
| 142 | use std::fs::File; |
| 143 | use std::io::{BufWriter, Read, Write}; |
| 144 | use std::path::{Path, PathBuf}; |
| 145 | |
| 146 | use osm_ingest::proto::{err, Error, Result}; |
| 147 | use rayon::prelude::*; |
| 148 | use tile_build::par; |
| 149 | |
| 150 | /// The longest way that may inherit, in metres. See the module docs for why 50 and why metres. |
| 151 | pub 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. |
| 157 | pub 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. |
| 164 | pub 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. |
| 168 | const METRES_PER_DEGREE: f64 = 111_320.0; |
| 169 | |
| 170 | /// One endpoint record, fixed width so a partition is read back without a varint decoder. |
| 171 | const RECORD_LEN: usize = 30; |
| 172 | |
| 173 | /// Bit 0 of a record's flag byte: the way is `oneway=yes`. |
| 174 | const FLAG_ONEWAY: u8 = 1 << 0; |
| 175 | /// Bit 1: this record is the way's *last* node rather than its first. |
| 176 | const 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. |
| 183 | pub 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)] |
| 197 | struct 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 | |
| 207 | impl 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 | /// A way's two endpoint records, built off the serial path. See [`Collector::push_prepared`]. |
| 241 | pub struct Prepared([Record; 2]); |
| 242 | |
| 243 | /// What [`Collector::push`] writes for `segment`, or `None` where it writes nothing. |
| 244 | /// |
| 245 | /// Pure over the segment: the same checks, in the same order, with the same arithmetic as the |
| 246 | /// inline body this was lifted out of, so a pool-built `Prepared` is bit-for-bit the record pair |
| 247 | /// the serial path produced. |
| 248 | pub fn prepare(segment: &Segment) -> Option<Prepared> { |
| 249 | if segment.name.is_empty() || segment.nodes.len() < 2 { |
| 250 | return None; |
| 251 | } |
| 252 | if segment.nodes.len() != segment.line.len() { |
| 253 | return None; |
| 254 | } |
| 255 | let first = segment.nodes[0]; |
| 256 | let last = segment.nodes[segment.nodes.len() - 1]; |
| 257 | // A closed way has one endpoint, not two, so it can never have a donor at "both" ends and |
| 258 | // is not a junction stub in any case. |
| 259 | if first == last { |
| 260 | return None; |
| 261 | } |
| 262 | // An untagged way is never a donor, so one too long to be a recipient cannot affect |
| 263 | // anything. Dropping it here rather than at resolve time is what keeps the spill small. |
| 264 | if segment.lanes == 0 && polyline_length_m(segment.line) > MAX_STUB_M { |
| 265 | return None; |
| 266 | } |
| 267 | // The bearing leaving each end, skipping repeated coordinates: a duplicated vertex has no |
| 268 | // direction, and the graph does contain them where a way was split at a coincident point. |
| 269 | let head = leaving(segment.line, true)?; |
| 270 | let tail = leaving(segment.line, false)?; |
| 271 | |
| 272 | let name_hash = hash_name(segment.name); |
| 273 | let base = if segment.oneway { FLAG_ONEWAY } else { 0 }; |
| 274 | let record = |node: i64, bearing: f64, end: u8| Record { |
| 275 | node, |
| 276 | way: segment.id, |
| 277 | name_hash, |
| 278 | bearing: bearing as f32, |
| 279 | lanes: segment.lanes, |
| 280 | flags: base | end, |
| 281 | }; |
| 282 | Some(Prepared([record(first, head, 0u8), record(last, tail, FLAG_LAST_END)])) |
| 283 | } |
| 284 | |
| 285 | /// [`prepare`] for a way whose coordinates are read on demand: `coord(i)` is node `i`'s |
| 286 | /// coordinate, valid for every `i < nodes.len()` (the caller has checked every node resolves -- |
| 287 | /// `prepare`'s `nodes.len() == line.len()` test). |
| 288 | /// |
| 289 | /// The same decisions on the same arithmetic, reading only the coordinates they need: a donor |
| 290 | /// (`lanes > 0`) needs only the bearings leaving its two ends, and a recipient's length test can |
| 291 | /// stop as soon as the running sum passes [`MAX_STUB_M`] -- the sum of non-negative segments only |
| 292 | /// grows, so a prefix over the limit means the whole way is. On the planet every coordinate read |
| 293 | /// is a random read of an ~80 GB table, and lane inheritance read every coordinate of every named |
| 294 | /// road (134 s); most of them are long and decided after a few nodes. |
| 295 | pub fn prepare_lazy( |
| 296 | id: i64, |
| 297 | name: &str, |
| 298 | lanes: u8, |
| 299 | oneway: bool, |
| 300 | nodes: &[i64], |
| 301 | coord: impl Fn(usize) -> (f64, f64), |
| 302 | ) -> Option<Prepared> { |
| 303 | if name.is_empty() || nodes.len() < 2 { |
| 304 | return None; |
| 305 | } |
| 306 | let first = nodes[0]; |
| 307 | let last = nodes[nodes.len() - 1]; |
| 308 | if first == last { |
| 309 | return None; |
| 310 | } |
| 311 | if lanes == 0 { |
| 312 | // `polyline_length_m`, summed in the same order, stopping once it is decided. |
| 313 | let mut length = -0.0f64; |
| 314 | let mut previous = coord(0); |
| 315 | for i in 1..nodes.len() { |
| 316 | let p = coord(i); |
| 317 | let north = (p.1 - previous.1) * METRES_PER_DEGREE; |
| 318 | let east = (p.0 - previous.0) * METRES_PER_DEGREE * previous.1.to_radians().cos(); |
| 319 | length += (north * north + east * east).sqrt(); |
| 320 | if length > MAX_STUB_M { |
| 321 | return None; |
| 322 | } |
| 323 | previous = p; |
| 324 | } |
| 325 | } |
| 326 | // `leaving`, scanning from each end for the first coordinate that differs. |
| 327 | let origin = coord(0); |
| 328 | let head = bearing(origin, (1..nodes.len()).map(&coord).find(|p| *p != origin)?); |
| 329 | let origin = coord(nodes.len() - 1); |
| 330 | let tail = bearing(origin, (0..nodes.len() - 1).rev().map(&coord).find(|p| *p != origin)?); |
| 331 | |
| 332 | let name_hash = hash_name(name); |
| 333 | let base = if oneway { FLAG_ONEWAY } else { 0 }; |
| 334 | let record = |node: i64, bearing: f64, end: u8| Record { |
| 335 | node, |
| 336 | way: id, |
| 337 | name_hash, |
| 338 | bearing: bearing as f32, |
| 339 | lanes, |
| 340 | flags: base | end, |
| 341 | }; |
| 342 | Some(Prepared([record(first, head, 0u8), record(last, tail, FLAG_LAST_END)])) |
| 343 | } |
| 344 | |
| 345 | /// Accumulates endpoint records, then resolves them into the ways whose lane count changes. |
| 346 | pub struct Collector { |
| 347 | files: Vec<BufWriter<File>>, |
| 348 | paths: Vec<PathBuf>, |
| 349 | /// Whether the partition names were unlinked at creation (Unix); if not, `finish` and drop |
| 350 | /// delete them. |
| 351 | unlinked: bool, |
| 352 | } |
| 353 | |
| 354 | include!("lanefill_s1.rs"); |