1use std::collections::{BTreeMap, HashMap, HashSet};
16
17const STEP: f64 = 0.5;
20
21const THROUGH_NODE: u32 = 40;
24const SHARED: u32 = 12;
25const CROSSING: u32 = 3;
26const BEND: u32 = 1;
27
28type Point = (i64, i64);
29
30#[derive(Debug, PartialEq)]
33pub struct Schematic {
34 pub nodes: Vec<(f64, f64)>,
35 pub routes: Vec<Vec<(f64, f64)>>,
36 pub tracks: Vec<i32>,
41}
42
43pub fn octilinear(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Schematic {
45 let at = snap(pos, edges);
46 let unit = |p: Point| (p.0 as f64 * STEP, p.1 as f64 * STEP);
47 let taken: HashSet<Point> = at.iter().copied().collect();
48
49 let mut pairs: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
51 for (k, &(a, b)) in edges.iter().enumerate() {
52 if a != b {
53 pairs.entry((a.min(b), a.max(b))).or_default().push(k);
54 }
55 }
56 let mut order: Vec<(usize, usize)> = pairs.keys().copied().collect();
57 let span = |&(a, b): &(usize, usize)| {
58 let (d0, d1) = ((at[b].0 - at[a].0).abs(), (at[b].1 - at[a].1).abs());
59 (d0.max(d1), d0.min(d1))
60 };
61 order.sort_by_key(|p| (span(p), *p));
62
63 let mut drawn = Drawn::default();
64 let mut paths: Vec<Vec<Point>> = vec![Vec::new(); edges.len()];
65 let mut walked = Vec::new();
66 for pair in order {
67 let (a, b) = pair;
68 let path = shapes(at[a], at[b])
69 .into_iter()
70 .map(|path| (drawn.cost(&path, &taken), path))
71 .min_by_key(|(cost, _)| *cost)
72 .map(|(_, path)| path)
73 .expect("a shape at least");
74 drawn.add(&path);
75 for &k in &pairs[&pair] {
76 paths[k] = if edges[k].0 == a { path.clone() } else { path.iter().rev().copied().collect() };
78 walked.push(k);
79 }
80 }
81
82 let mut sides: HashMap<(Point, Point), HashSet<i32>> = HashMap::new();
86 let mut tracks = vec![0; edges.len()];
87 for k in walked {
88 let pieces: Vec<((Point, Point), i32)> = steps(&paths[k])
89 .map(|(p, d)| {
90 let q = (p.0 + d.0, p.1 + d.1);
91 (piece(p, q), if p <= q { 1 } else { -1 })
92 })
93 .collect();
94 let free = |t: i32| pieces.iter().all(|(key, sign)| !sides.get(key).is_some_and(|s| s.contains(&(t * sign))));
95 let track = (0..).flat_map(|i: i32| if i == 0 { vec![0] } else { vec![i, -i] }).find(|&t| free(t)).expect("a free track");
96 for (key, sign) in pieces {
97 sides.entry(key).or_default().insert(track * sign);
98 }
99 tracks[k] = track;
100 }
101 Schematic {
102 nodes: at.into_iter().map(unit).collect(),
103 routes: paths.into_iter().map(|p| p.into_iter().map(unit).collect()).collect(),
104 tracks,
105 }
106}
107
108fn snap(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Vec<Point> {
111 let mut degree = vec![0usize; pos.len()];
112 for &(a, b) in edges {
113 degree[a] += 1;
114 degree[b] += 1;
115 }
116 let mut order: Vec<usize> = (0..pos.len()).collect();
117 order.sort_by_key(|&i| (std::cmp::Reverse(degree[i]), i));
118 let mut taken: HashSet<Point> = HashSet::new();
119 let mut at = vec![(0, 0); pos.len()];
120 for i in order {
121 let (x, y) = (pos[i].0 / STEP, pos[i].1 / STEP);
122 let home = (x.round() as i64, y.round() as i64);
123 let mut best = home;
124 if taken.contains(&home) {
125 'rings: for r in 1i64.. {
127 let mut ring: Vec<Point> = (-r..=r)
128 .flat_map(|i| [(home.0 + i, home.1 - r), (home.0 + i, home.1 + r), (home.0 - r, home.1 + i), (home.0 + r, home.1 + i)])
129 .filter(|p| !taken.contains(p))
130 .collect();
131 if ring.is_empty() {
132 continue;
133 }
134 ring.sort_by(|p, q| {
135 let d = |p: &Point| (p.0 as f64 - x).powi(2) + (p.1 as f64 - y).powi(2);
136 d(p).total_cmp(&d(q)).then(p.cmp(q))
137 });
138 best = ring[0];
139 break 'rings;
140 }
141 }
142 taken.insert(best);
143 at[i] = best;
144 }
145 at
146}
147
148fn shapes(a: Point, b: Point) -> Vec<Vec<Point>> {
152 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
153 let (ax, ay) = (dx.abs(), dy.abs());
154 if ax == 0 || ay == 0 || ax == ay {
155 return vec![vec![a, b]];
156 }
157 let m = ax.min(ay);
158 let r = ax.max(ay) - m;
159 let diagonal = (dx.signum(), dy.signum());
160 let straight = if ax > ay { (dx.signum(), 0) } else { (0, dy.signum()) };
161 let go = |p: Point, d: Point, n: i64| (p.0 + d.0 * n, p.1 + d.1 * n);
162 let mut out = vec![vec![a, go(a, diagonal, m), b], vec![a, go(a, straight, r), b]];
163 if r >= 2 {
164 let h = go(a, straight, r / 2);
165 out.push(vec![a, h, go(h, diagonal, m), b]);
166 }
167 out
168}
169
170#[derive(Default)]
172struct Drawn {
173 pieces: HashSet<(Point, Point)>,
174}
175
176fn piece(p: Point, q: Point) -> (Point, Point) {
178 if p <= q { (p, q) } else { (q, p) }
179}
180
181fn steps(path: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
183 path.windows(2).flat_map(|w| {
184 let (p, q) = (w[0], w[1]);
185 let d = ((q.0 - p.0).signum(), (q.1 - p.1).signum());
186 let n = (q.0 - p.0).abs().max((q.1 - p.1).abs());
187 (0..n).map(move |i| ((p.0 + d.0 * i, p.1 + d.1 * i), d))
188 })
189}
190
191impl Drawn {
192 fn cost(&self, path: &[Point], nodes: &HashSet<Point>) -> u32 {
193 let (a, b) = (path[0], path[path.len() - 1]);
194 let mut cost = BEND * (path.len() as u32 - 2);
195 for (p, d) in steps(path) {
196 let q = (p.0 + d.0, p.1 + d.1);
197 if q != b && q != a && nodes.contains(&q) {
198 cost += THROUGH_NODE;
199 }
200 if self.pieces.contains(&piece(p, q)) {
201 cost += SHARED;
202 }
203 if d.0 != 0 && d.1 != 0 && self.pieces.contains(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1))) {
205 cost += CROSSING;
206 }
207 }
208 cost
209 }
210
211 fn add(&mut self, path: &[Point]) {
212 for (p, d) in steps(path) {
213 self.pieces.insert(piece(p, (p.0 + d.0, p.1 + d.1)));
214 }
215 }
216}
217
218#[cfg(test)]
221fn crossings(routes: &[Vec<(f64, f64)>]) -> usize {
222 let mut drawn: HashMap<(Point, Point), usize> = HashMap::new();
223 let lattice = |p: (f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
224 let mut count = 0;
225 for (k, r) in routes.iter().enumerate() {
226 let path: Vec<Point> = r.iter().map(|&p| lattice(p)).collect();
227 let mut path = path;
228 path.dedup();
229 for (p, d) in steps(&path) {
230 if d.0 != 0 && d.1 != 0 && drawn.get(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1))).is_some_and(|&o| o != k) {
231 count += 1;
232 }
233 }
234 for (p, d) in steps(&path) {
235 drawn.insert(piece(p, (p.0 + d.0, p.1 + d.1)), k);
236 }
237 }
238 count
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn octilinear_pieces(routes: &[Vec<(f64, f64)>]) -> bool {
247 routes.iter().all(|r| {
248 r.windows(2).all(|w| {
249 let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
250 dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9
251 })
252 })
253 }
254
255 #[test]
256 fn lines_run_along_axes_and_diagonals() {
257 let pos = [(0.0, 0.0), (1.7, 0.6), (0.4, 1.9), (2.2, 2.4), (-1.3, 0.8)];
258 let edges = [(0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (4, 2)];
259 let Schematic { nodes, routes, .. } = octilinear(&pos, &edges);
260 assert!(octilinear_pieces(&routes), "{routes:?}");
261 for (k, &(a, b)) in edges.iter().enumerate() {
262 assert_eq!(routes[k].first(), Some(&nodes[a]), "edge {k} from its source");
263 assert_eq!(routes[k].last(), Some(&nodes[b]), "edge {k} to its target");
264 assert!(routes[k].len() <= 4, "at most two bends: {:?}", routes[k]);
265 }
266 }
267
268 #[test]
269 fn nodes_keep_apart_and_near_where_they_were() {
270 let pos = [(0.0, 0.0), (0.01, 0.0), (0.0, 0.02), (3.0, 3.0)];
272 let Schematic { nodes, .. } = octilinear(&pos, &[(0, 3), (1, 3), (2, 3)]);
273 let distinct: HashSet<(i64, i64)> = nodes.iter().map(|p| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64)).collect();
274 assert_eq!(distinct.len(), 4);
275 assert!(nodes.iter().zip(&pos).all(|(p, q)| (p.0 - q.0).abs() <= 2.0 * STEP && (p.1 - q.1).abs() <= 2.0 * STEP));
276 }
277
278 #[test]
279 fn a_line_goes_round_a_node_in_its_way() {
280 let pos = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.5)];
282 let Schematic { nodes, routes, .. } = octilinear(&pos, &[(0, 2), (0, 1)]);
283 let through = |r: &Vec<(f64, f64)>, p: (f64, f64)| {
284 r.windows(2).any(|w| {
285 let (a, b) = (w[0], w[1]);
286 let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
287 let within = (p.0 - a.0) * (p.0 - b.0) <= 1e-9 && (p.1 - a.1) * (p.1 - b.1) <= 1e-9;
288 cross.abs() < 1e-9 && within && p != a && p != b
289 })
290 };
291 assert!(!through(&routes[0], nodes[1]), "{:?} through {:?}", routes[0], nodes[1]);
292 }
293
294 #[test]
295 fn double_circuits_run_side_by_side() {
296 let pos = [(0.0, 0.0), (2.0, 1.0)];
297 let Schematic { nodes, routes, tracks } = octilinear(&pos, &[(0, 1), (1, 0), (0, 1)]);
298 assert!(octilinear_pieces(&routes), "{routes:?}");
299 assert_eq!(routes[0], routes[2]);
301 assert_eq!(routes[1], routes[0].iter().rev().copied().collect::<Vec<_>>());
302 assert_eq!(routes[1][0], nodes[1], "the one written the other way round, from its own source");
303 assert_eq!(tracks, vec![0, 1, 1]);
306 }
307
308 #[test]
309 fn lines_sharing_a_stretch_take_tracks_of_their_own() {
310 let pos = [(0.0, 0.0), (-1.0, 0.0), (1.5, 1.5)];
312 let Schematic { routes, tracks, .. } = octilinear(&pos, &[(0, 2), (1, 2)]);
313 let shared = routes[0].windows(2).any(|w| routes[1].windows(2).any(|v| v == w));
314 if shared {
315 assert_ne!(tracks[0], tracks[1], "{routes:?} {tracks:?}");
316 }
317 assert!(tracks.contains(&0));
318 }
319
320 #[test]
321 fn the_same_grid_the_same_schematic() {
322 let pos: Vec<(f64, f64)> = (0..60).map(|i| (((i * 37) % 23) as f64 * 0.7, ((i * 53) % 19) as f64 * 0.6)).collect();
323 let edges: Vec<(usize, usize)> = (0..59).map(|i| (i, (i * 7 + 3) % 60)).collect();
324 assert_eq!(octilinear(&pos, &edges), octilinear(&pos, &edges));
325 let Schematic { routes, .. } = octilinear(&pos, &edges);
326 assert!(octilinear_pieces(&routes));
327 assert!(crossings(&routes) < edges.len());
328 }
329}
330
331#[cfg(test)]
332mod timing {
333 #[test]
335 #[ignore]
336 fn realgrid_sized() {
337 let n = 4875;
338 let mut edges: Vec<(usize, usize)> = (1..n).map(|i| (i, (i * 7919) % i)).collect();
339 edges.extend((0..2878).map(|i| ((i * 31) % n, (i * 31 + 17) % n)));
340 let pos = crate::layout::force(n, &edges);
341 let t = std::time::Instant::now();
342 let super::Schematic { routes, .. } = super::octilinear(&pos, &edges);
343 eprintln!("octilinear: {:?} for {} routes", t.elapsed(), routes.len());
344 }
345}
346
347#[cfg(test)]
348mod shared_count {
349 #[test]
351 #[ignore]
352 fn shared_pieces() {
353 for dir in ["SmallGrid/SmallGrid-Merged", "RealGrid/RealGrid-Merged"] {
354 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../CGMES-Test-Configurations/v3.0").join(dir);
355 let read = crate::testing::collect(&path);
356 let datasets: Vec<cimmodel::CimDataset> = read.iter().map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap()).collect();
357 let m = crate::grid::Model::new(&datasets);
358 let g = crate::grid::build(&m);
359 let auto = g.auto.as_ref().unwrap();
360 let mut seen: std::collections::HashMap<((i64, i64), (i64, i64)), (usize, usize)> = std::collections::HashMap::new();
361 let (mut shared, mut total) = (0, 0);
362 let mut high = 0;
363 for (&k, r) in &auto.edges {
364 let e = &g.edges[k];
365 let pair = (e.source.min(e.target), e.source.max(e.target));
366 let lattice: Vec<(i64, i64)> = r.iter().map(|p| ((p.0 / super::STEP).round() as i64, (p.1 / super::STEP).round() as i64)).collect();
367 for (p, d) in super::steps(&lattice) {
368 let q = (p.0 + d.0, p.1 + d.1);
369 let key = if p <= q { (p, q) } else { (q, p) };
370 total += 1;
371 if let Some(o) = seen.get(&key) {
372 if *o != pair {
373 shared += 1;
374 if e.kv.is_some_and(|v| v >= 300.0) {
375 high += 1;
376 }
377 }
378 } else {
379 seen.insert(key, pair);
380 }
381 }
382 }
383 eprintln!("{dir}: {shared} of {total} unit pieces shared between different pairs, {high} on ≥300 kV lines");
384 }
385 }
386}