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

Modern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part10.rs

graph_build_part10.rs270 lines · 12.1 KiBRaw
1
2 // ---- stop reconnection by component size ------------------------------
3
4 /// Three road networks and a stop on each, plus a stop attached to nothing.
5 ///
6 /// This is the planet case stated at the smallest scale that can state it.
7 /// Continents are not road-connected, so a planet's largest component is
8 /// Eurasia-plus-Africa at 57.7% and the old "reconnect everything outside the
9 /// largest component" rule tried to drag every American, Australian, Japanese,
10 /// British and Indonesian stop across an ocean — failing 1,173,347 times. The
11 /// rule is component *size*, so a stop already on a real road network is left
12 /// alone whichever network that is.
13 #[test]
14 fn a_stop_on_any_routable_component_is_left_alone() {
15 const A: u32 = 1200; // the largest component
16 const B: u32 = 1000; // exactly MIN_ROUTABLE_COMPONENT, so still routable
17 const C: u32 = 999; // one node short of it, so not
18 let total = A + B + C + 1;
19
20 // A is far west; B and C are adjacent in both index and space, so the
21 // widening window around a stop in C reaches B before anything else.
22 let mut coords: Vec<geom::Pt> = Vec::with_capacity(total as usize);
23 for i in 0..A {
24 coords.push((370_000_000 + i as i32 * 1000, -1_220_000_000));
25 }
26 for i in 0..B {
27 coords.push((400_000_000 + i as i32 * 1000, -740_000_000));
28 }
29 for i in 0..C {
30 coords.push((410_000_000 + i as i32 * 1000, -740_000_000));
31 }
32 // The stop attached to nothing sits beside B's far end.
33 coords.push((400_999_500, -740_000_000));
34
35 let mut edges: Vec<(u32, u32)> = Vec::new();
36 let chain = |base: u32, len: u32, edges: &mut Vec<(u32, u32)>| {
37 for i in 1..len {
38 edges.push((base + i - 1, base + i));
39 edges.push((base + i, base + i - 1));
40 }
41 };
42 chain(0, A, &mut edges);
43 chain(A, B, &mut edges);
44 chain(A + B, C, &mut edges);
45 let csr = csr_of(total, &edges);
46
47 let mut stops = Bitset::new(u64::from(total));
48 for s in [A / 2, A + B / 2, A + B + C / 2, A + B + C] {
49 stops.set(u64::from(s));
50 }
51
52 let rec = reconnect_isolated_stops(&coords, &stops, &csr);
53 assert_eq!(rec.lcc_size, u64::from(A));
54 assert_eq!(
55 rec.already_connected, 2,
56 "the stops in A and in B are both already on a routable component"
57 );
58 assert_eq!(rec.unreachable, 0);
59 // The stop in C and the stop attached to nothing, both connectors both ways.
60 assert_eq!(rec.synth.len(), 4);
61 for source in [A + B + C / 2, A + B + C] {
62 let target = rec
63 .synth
64 .iter()
65 .find(|s| s.source == source)
66 .expect("every isolated stop gets a connector")
67 .target;
68 assert!(
69 target < A + B,
70 "stop {source} was connected to node {target}, which is in C"
71 );
72 assert_eq!(target, A + B - 1, "and to the nearest such node");
73 }
74 // Both directions of each connector are present, which is what makes the
75 // stop reachable rather than merely reaching.
76 for s in &rec.synth {
77 assert!(
78 rec.synth
79 .iter()
80 .any(|t| t.source == s.target && t.target == s.source),
81 "connector {} -> {} has no return",
82 s.source,
83 s.target
84 );
85 }
86 }
87
88 #[test]
89 fn the_routable_threshold_falls_back_to_the_largest_component() {
90 // A graph whose largest component is under MIN_ROUTABLE_COMPONENT still has
91 // a road network — it is just a small one. Requiring 1000 nodes there would
92 // qualify nothing and reconnect nothing, so the threshold is capped at the
93 // largest component that exists. Two nodes of road and a stop off to one
94 // side: the stop must still find the road.
95 let coords: Vec<geom::Pt> = vec![
96 (370_000_000, -1_220_000_000),
97 (370_010_000, -1_220_000_000),
98 (380_000_000, -1_220_000_000),
99 ];
100 let csr = csr_of(3, &[(0, 1), (1, 0)]);
101 let mut stops = Bitset::new(3);
102 stops.set(2);
103
104 let rec = reconnect_isolated_stops(&coords, &stops, &csr);
105 assert_eq!(rec.lcc_size, 2);
106 assert_eq!(rec.already_connected, 0);
107 assert_eq!(rec.unreachable, 0);
108 assert_eq!(rec.synth.len(), 2);
109 assert_eq!(rec.synth[0].source, 1, "the nearest node of the only road");
110 assert_eq!(rec.synth[0].target, 2);
111 }
112
113 #[test]
114 fn args_default_the_output_directory() {
115 let (input, out, opts) = parse_args(&["cal.osm.pbf".into()]).unwrap();
116 assert_eq!(input, PathBuf::from("cal.osm.pbf"));
117 assert_eq!(out, PathBuf::from("map_data"));
118 assert!(
119 opts.within_way_chains,
120 "the streaming within-way path is the CLI default"
121 );
122 let (_, out, _) = parse_args(&["cal.osm.pbf".into(), "--out".into(), "d".into()]).unwrap();
123 assert_eq!(out, PathBuf::from("d"));
124 let (_, _, opts) =
125 parse_args(&["cal.osm.pbf".into(), "--reference-collapse".into()]).unwrap();
126 assert!(
127 !opts.within_way_chains,
128 "--reference-collapse opts back into the reference path"
129 );
130 assert_eq!(opts.round_count(), 1, "one round is the default");
131 assert!(opts.spill_dir.is_none(), "the spill defaults to the output dir");
132 let (_, _, opts) = parse_args(&["cal.osm.pbf".into(), "--rounds".into(), "8".into()]).unwrap();
133 assert_eq!(opts.round_count(), 8);
134 let (_, _, opts) =
135 parse_args(&["c.pbf".into(), "--spill-dir".into(), "/fast".into()]).unwrap();
136 assert_eq!(opts.spill_dir, Some(PathBuf::from("/fast")));
137 assert!(parse_args(&["a".into(), "--spill-dir".into()]).is_err());
138 let (_, _, opts) = parse_args(&[
139 "c.pbf".into(),
140 "--spill-dir".into(),
141 "/roomy".into(),
142 "--spill-pts-dir".into(),
143 "/fast".into(),
144 ])
145 .unwrap();
146 assert_eq!(opts.spill_dir, Some(PathBuf::from("/roomy")));
147 assert_eq!(opts.spill_pts_dir, Some(PathBuf::from("/fast")));
148 assert!(parse_args(&["a".into(), "--spill-pts-dir".into()]).is_err());
149 assert!(parse_args(&["a".into(), "--rounds".into(), "0".into()]).is_err());
150 assert!(parse_args(&["a".into(), "--rounds".into(), "many".into()]).is_err());
151 assert!(parse_args(&["a".into(), "--rounds".into()]).is_err());
152 let (_, _, opts) = parse_args(&["c.pbf".into()]).unwrap();
153 assert!(opts.threads.is_none(), "the pool defaults to the box");
154 let (_, _, opts) =
155 parse_args(&["c.pbf".into(), "--threads".into(), "4".into()]).unwrap();
156 assert_eq!(opts.threads, Some(4));
157 assert!(parse_args(&["a".into(), "--threads".into(), "0".into()]).is_err());
158 assert!(parse_args(&["a".into(), "--threads".into()]).is_err());
159 assert!(parse_args(&[]).is_err());
160 assert!(parse_args(&["a".into(), "b".into()]).is_err());
161 assert!(parse_args(&["--wat".into()]).is_err());
162 }
163
164 // ---------------------------------------------------------------------
165 // TODO(write-pipe) re-entry checklist, step 1: bake_batch on a synthetic
166 // buffer, before any pool or drain exists.
167 // ---------------------------------------------------------------------
168
169 /// A one-point `chains.pts` mapping: the synthetic edges carry no chain,
170 /// so nothing reads it, but `bake_batch` takes the shared mapping.
171 fn dummy_points(tag: &str) -> crate::mem::Mapped {
172 let dir = std::env::temp_dir().join(format!("osm_ingest_bake_{tag}"));
173 let _ = std::fs::remove_dir_all(&dir);
174 std::fs::create_dir_all(&dir).unwrap();
175 let path = dir.join("chains.pts");
176 std::fs::write(&path, [0u8; 8]).unwrap();
177 crate::mem::Mapped::open(&path).unwrap()
178 }
179
180 /// `(node id, edge_ptr)` of every opener, in bake order.
181 fn bake_openers(b: &BakedBatch) -> Vec<(u32, u32)> {
182 (0..b.node_count())
183 .map(|i| {
184 let (lat, _, ptr) = b.opener(i);
185 (lat as u32, ptr)
186 })
187 .collect()
188 }
189
190 #[test]
191 fn bake_batch_opens_every_node_in_its_span_at_base_plus_run_offset() {
192 // Nodes 10..20, whose lat_e7 is the node id so an opener names its node.
193 let kept = 24u32;
194 let node_coords: Vec<geom::Pt> = (0..kept).map(|i| (i as i32, 0)).collect();
195 // Runs: 11 x2, 13 x1, 15 x3. Edgeless: 10 (leading), 12, 14 (interior),
196 // 16..20 (trailing) — the trailing ones are the case a batch that ends
197 // on an edgeless node must still open.
198 let spec: &[(u32, u32)] = &[(11, 3), (11, 4), (13, 2), (15, 1), (15, 5), (15, 6)];
199 let mut edges: Vec<TmpEdge> = spec.iter().map(|(s, t)| tmp_edge(*s, *t, 1000)).collect();
200 // One escaped (dist past u24) and one named edge, to pin their offsets.
201 edges[2].dist_mm = DIST_MM_ESCAPE;
202 edges[4].name_offset = 77;
203 let csr = csr_of(kept, spec);
204 let points = dummy_points("span");
205 let (first, end, base) = (10u32, 20u32, 100u64);
206 let b =
207 bake_batch(&edges, first, end, base, &node_coords, &[], &csr, &[], &points).unwrap();
208 let openers = bake_openers(&b);
209 assert_eq!(
210 openers.len(),
211 (end - first) as usize,
212 "opener count must equal the node span"
213 );
214 let want: Vec<(u32, u32)> = vec![
215 (10, 100),
216 (11, 100),
217 (12, 102),
218 (13, 102),
219 (14, 103),
220 (15, 103),
221 (16, 106),
222 (17, 106),
223 (18, 106),
224 (19, 106),
225 ];
226 assert_eq!(openers, want, "opener edge_ptrs must be base + run offsets");
227 // One record per edge, side tables keyed by the edge's offset in the batch.
228 assert_eq!(b.edge_count, edges.len() as u64);
229 assert_eq!(b.edge_recs.len(), edges.len() * EDGE_REC_BYTES as usize);
230 assert_eq!(b.escapes, vec![(2, 2, DIST_MM_ESCAPE)]);
231 assert_eq!(b.names, vec![(4, 77)]);
232 // The census saw every node of the span, edgeless ones included.
233 assert_eq!(b.census.degree_zero_nodes, 7);
234 assert_eq!(b.census.max_degree, 3);
235 }
236
237 #[test]
238 fn bake_batch_refuses_an_edge_outside_its_span() {
239 let node_coords: Vec<geom::Pt> = (0..8).map(|i| (i, 0)).collect();
240 let csr = csr_of(8, &[(6, 1)]);
241 let points = dummy_points("stray");
242 let edges = [tmp_edge(6, 1, 10)];
243 assert!(bake_batch(&edges, 2, 6, 0, &node_coords, &[], &csr, &[], &points).is_err());
244 }
245
246 #[test]
247 fn bake_batch_opens_a_wholly_edgeless_span() {
248 let node_coords: Vec<geom::Pt> = (0..8).map(|i| (i, 0)).collect();
249 let csr = csr_of(8, &[]);
250 let points = dummy_points("edgeless");
251 let b = bake_batch(&[], 2, 6, 7, &node_coords, &[], &csr, &[], &points).unwrap();
252 assert_eq!(bake_openers(&b), vec![(2, 7), (3, 7), (4, 7), (5, 7)]);
253 assert_eq!(b.edge_count, 0);
254 }
255
256 #[test]
257 fn a_duplicated_node_id_keeps_its_last_coordinates() {
258 // The parallel node scan lets only the first claimant write a slot, so
259 // a repeated id must fall back to the serial fold, where the LAST
260 // occurrence wins — as it always has.
261 let mut nodes = line_nodes(&[1, 2, 3]);
262 nodes.push((3, 370_090_000, -1_220_000_000));
263 let (pbf, dir) = testpbf::write_shape_sample("dup_node", &nodes, &[(100, &[1, 2, 3])]);
264 let stats = build_with(&pbf, &dir, within_opts()).unwrap();
265 assert_eq!(stats.raw_node_count, 3, "a repeated id is still one node");
266 let o = read_outputs(&dir);
267 let lats: Vec<i32> = (0..node_count(&o)).map(|i| node_at(&o, i).0).collect();
268 assert!(lats.contains(&370_090_000), "the last occurrence wins: {lats:?}");
269 assert!(!lats.contains(&370_030_000), "the first occurrence is gone: {lats:?}");
270 }