Skip to main content

cimview/
schematic.rs

1//! The grid's automatic layout as a schematic: lines only horizontal, vertical or at 45°, as
2//! transmission overview diagrams draw them.
3//!
4//! The positions [`crate::layout::force`] finds are snapped to a lattice, the busiest node first,
5//! one that would land on another taking the nearest free point. Each line then runs from lattice
6//! point to lattice point in at most three straight pieces, each along an axis or a diagonal: of
7//! the shapes it can take (straight; a diagonal and a straight piece, either way round; a
8//! straight piece, a diagonal and another), the one that passes through no other node, shares no
9//! piece with a line already drawn, crosses the fewest, and bends least. The shorter lines go
10//! first, so that local connections keep the plainest shapes. Lines joining the same two nodes
11//! (double circuits) run side by side, stepped aside where they leave a node.
12//!
13//! Linear in the lines times their lengths on the lattice, and deterministic.
14
15use std::collections::{BTreeMap, HashMap, HashSet};
16
17/// The lattice spacing, in the units of the positions it snaps ([`crate::layout::force`]'s, a
18/// line's ideal length being one): a line spans about two points.
19const STEP: f64 = 0.5;
20
21/// What a shape costs: passing through another node, sharing a piece with a line drawn, crossing
22/// one, and each bend.
23const THROUGH_NODE: u32 = 40;
24const SHARED: u32 = 12;
25const CROSSING: u32 = 3;
26const BEND: u32 = 1;
27
28type Point = (i64, i64);
29
30/// A schematic: each node's position and each edge's route, from its source to its target (in
31/// [`crate::layout::force`]'s units; a loop has none), and the track each edge runs on.
32#[derive(Debug, PartialEq)]
33pub struct Schematic {
34    pub nodes: Vec<(f64, f64)>,
35    pub routes: Vec<Vec<(f64, f64)>>,
36    /// How many line spacings aside each edge runs from its route, to the left of its way from
37    /// source to target (negative: to the right), so that lines sharing a stretch — two circuits
38    /// between the same nodes, or lines whose routes meet — are drawn side by side: the views
39    /// space them by what they draw, in pixels.
40    pub tracks: Vec<i32>,
41}
42
43/// Nodes at `pos` (in [`crate::layout::force`]'s units) and their `edges`, as a schematic.
44pub 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    // The edges by the two nodes they join; the pairs, shortest first.
50    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            // From the edge's own source to its target.
77            paths[k] = if edges[k].0 == a {
78                path.clone()
79            } else {
80                path.iter().rev().copied().collect()
81            };
82            walked.push(k);
83        }
84    }
85
86    // Tracks: each edge, in the order routed, on the track nearest its route that none drawn
87    // before it takes on any piece it shares. A track to the left of one way along a piece is to
88    // the right of the other, so each is kept as the piece's own side.
89    let mut sides: HashMap<(Point, Point), HashSet<i32>> = HashMap::new();
90    let mut tracks = vec![0; edges.len()];
91    for k in walked {
92        let pieces: Vec<((Point, Point), i32)> = steps(&paths[k])
93            .map(|(p, d)| {
94                let q = (p.0 + d.0, p.1 + d.1);
95                (piece(p, q), if p <= q { 1 } else { -1 })
96            })
97            .collect();
98        let free = |t: i32| {
99            pieces
100                .iter()
101                .all(|(key, sign)| !sides.get(key).is_some_and(|s| s.contains(&(t * sign))))
102        };
103        let track = (0..)
104            .flat_map(|i: i32| if i == 0 { vec![0] } else { vec![i, -i] })
105            .find(|&t| free(t))
106            .expect("a free track");
107        for (key, sign) in pieces {
108            sides.entry(key).or_default().insert(track * sign);
109        }
110        tracks[k] = track;
111    }
112    Schematic {
113        nodes: at.into_iter().map(unit).collect(),
114        routes: paths
115            .into_iter()
116            .map(|p| p.into_iter().map(unit).collect())
117            .collect(),
118        tracks,
119    }
120}
121
122/// An edge's route and the track it runs on, as a [`Schematic`] has them.
123pub type Route = (Vec<(f64, f64)>, i32);
124
125/// A schematic carried over an edit of what it draws: node `i` where `kept[i]` has it, edge `k`
126/// along the route and on the track `routes[k]` has for it, both in [`crate::layout::force`]'s
127/// units as [`octilinear`] gives them. Nothing kept moves. Each other node goes to the free lattice
128/// point nearest the middle of its placed neighbours, off the routes kept; one joined to nothing
129/// placed, in a row below the rest. Each other edge is routed as [`octilinear`] routes it, around
130/// what is drawn, beside an edge kept between the same nodes, and given the nearest free track.
131pub fn extend(
132    kept: &[Option<(f64, f64)>],
133    edges: &[(usize, usize)],
134    routes: &[Option<Route>],
135) -> Schematic {
136    let lattice = |p: &(f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
137    let unit = |p: Point| (p.0 as f64 * STEP, p.1 as f64 * STEP);
138    let mut at: Vec<Option<Point>> = kept.iter().map(|p| p.as_ref().map(lattice)).collect();
139    let mut paths: Vec<Vec<Point>> = vec![Vec::new(); edges.len()];
140    let mut tracks = vec![0; edges.len()];
141    let mut drawn = Drawn::default();
142    let mut sides: HashMap<(Point, Point), HashSet<i32>> = HashMap::new();
143    let pieces_of = |path: &[Point]| -> Vec<((Point, Point), i32)> {
144        steps(path)
145            .map(|(p, d)| {
146                let q = (p.0 + d.0, p.1 + d.1);
147                (piece(p, q), if p <= q { 1 } else { -1 })
148            })
149            .collect()
150    };
151    // What is kept: its nodes' points, and every point its routes pass, where a node put would
152    // sit on a line.
153    let mut busy: HashSet<Point> = at.iter().flatten().copied().collect();
154    let mut routed = vec![false; edges.len()];
155    for (k, kept) in routes.iter().enumerate() {
156        let Some((route, track)) = kept else {
157            continue;
158        };
159        let path: Vec<Point> = route.iter().map(lattice).collect();
160        if path.len() < 2 || edges[k].0 == edges[k].1 {
161            continue;
162        }
163        drawn.add(&path);
164        for (p, d) in steps(&path) {
165            busy.insert(p);
166            busy.insert((p.0 + d.0, p.1 + d.1));
167        }
168        for (key, sign) in pieces_of(&path) {
169            sides.entry(key).or_default().insert(track * sign);
170        }
171        paths[k] = path;
172        tracks[k] = *track;
173        routed[k] = true;
174    }
175
176    // The nodes new: beside their neighbours placed, in rounds, so that a chain of them follows
177    // from what is kept.
178    let mut neighbours = vec![Vec::new(); at.len()];
179    for &(a, b) in edges {
180        if a != b {
181            neighbours[a].push(b);
182            neighbours[b].push(a);
183        }
184    }
185    loop {
186        let mut placed = false;
187        for i in 0..at.len() {
188            if at[i].is_some() {
189                continue;
190            }
191            let known: Vec<Point> = neighbours[i].iter().filter_map(|&n| at[n]).collect();
192            if known.is_empty() {
193                continue;
194            }
195            let n = known.len() as f64;
196            let x = known.iter().map(|p| p.0 as f64).sum::<f64>() / n;
197            let y = known.iter().map(|p| p.1 as f64).sum::<f64>() / n;
198            let p = nearest_free((x.round() as i64, y.round() as i64), (x, y), &busy);
199            busy.insert(p);
200            at[i] = Some(p);
201            placed = true;
202        }
203        if !placed {
204            break;
205        }
206    }
207    let bottom = busy.iter().map(|p| p.1).max().unwrap_or(0) + 2;
208    let mut x = busy.iter().map(|p| p.0).min().unwrap_or(0);
209    for p in at.iter_mut().filter(|p| p.is_none()) {
210        while busy.contains(&(x, bottom)) {
211            x += 2;
212        }
213        busy.insert((x, bottom));
214        *p = Some((x, bottom));
215        x += 2;
216    }
217    let at: Vec<Point> = at.into_iter().map(|p| p.expect("placed")).collect();
218    let taken: HashSet<Point> = at.iter().copied().collect();
219
220    // The edges new, by the two nodes they join, shortest first; beside one kept between them.
221    let mut pairs: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
222    let mut beside: HashMap<(usize, usize), usize> = HashMap::new();
223    for (k, &(a, b)) in edges.iter().enumerate() {
224        if a == b {
225            continue;
226        }
227        let pair = (a.min(b), a.max(b));
228        if routed[k] {
229            beside.entry(pair).or_insert(k);
230        } else {
231            pairs.entry(pair).or_default().push(k);
232        }
233    }
234    let mut order: Vec<(usize, usize)> = pairs.keys().copied().collect();
235    let span = |&(a, b): &(usize, usize)| {
236        let (d0, d1) = ((at[b].0 - at[a].0).abs(), (at[b].1 - at[a].1).abs());
237        (d0.max(d1), d0.min(d1))
238    };
239    order.sort_by_key(|p| (span(p), *p));
240    let mut walked = Vec::new();
241    for pair in order {
242        let (a, b) = pair;
243        let path = match beside.get(&pair) {
244            Some(&j) if paths[j].first() == Some(&at[a]) => paths[j].clone(),
245            Some(&j) => paths[j].iter().rev().copied().collect(),
246            None => {
247                let path = shapes(at[a], at[b])
248                    .into_iter()
249                    .map(|path| (drawn.cost(&path, &taken), path))
250                    .min_by_key(|(cost, _)| *cost)
251                    .map(|(_, path)| path)
252                    .expect("a shape at least");
253                drawn.add(&path);
254                path
255            }
256        };
257        for &k in &pairs[&pair] {
258            paths[k] = if edges[k].0 == a {
259                path.clone()
260            } else {
261                path.iter().rev().copied().collect()
262            };
263            walked.push(k);
264        }
265    }
266    for k in walked {
267        let pieces = pieces_of(&paths[k]);
268        let free = |t: i32| {
269            pieces
270                .iter()
271                .all(|(key, sign)| !sides.get(key).is_some_and(|s| s.contains(&(t * sign))))
272        };
273        let track = (0..)
274            .flat_map(|i: i32| if i == 0 { vec![0] } else { vec![i, -i] })
275            .find(|&t| free(t))
276            .expect("a free track");
277        for (key, sign) in pieces {
278            sides.entry(key).or_default().insert(track * sign);
279        }
280        tracks[k] = track;
281    }
282    Schematic {
283        nodes: at.into_iter().map(unit).collect(),
284        routes: paths
285            .into_iter()
286            .map(|p| p.into_iter().map(unit).collect())
287            .collect(),
288        tracks,
289    }
290}
291
292/// Each node's lattice point: the nearest free one to its position, the nodes with most edges
293/// placed first.
294fn snap(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Vec<Point> {
295    let mut degree = vec![0usize; pos.len()];
296    for &(a, b) in edges {
297        degree[a] += 1;
298        degree[b] += 1;
299    }
300    let mut order: Vec<usize> = (0..pos.len()).collect();
301    order.sort_by_key(|&i| (std::cmp::Reverse(degree[i]), i));
302    let mut taken: HashSet<Point> = HashSet::new();
303    let mut at = vec![(0, 0); pos.len()];
304    for i in order {
305        let (x, y) = (pos[i].0 / STEP, pos[i].1 / STEP);
306        let home = (x.round() as i64, y.round() as i64);
307        let best = nearest_free(home, (x, y), &taken);
308        taken.insert(best);
309        at[i] = best;
310    }
311    at
312}
313
314/// The free lattice point nearest `(x, y)` (in lattice units), `home` its rounding: `home` itself
315/// where it is free, else the nearest of the first ring around it to hold a free point.
316fn nearest_free(home: Point, (x, y): (f64, f64), taken: &HashSet<Point>) -> Point {
317    if !taken.contains(&home) {
318        return home;
319    }
320    for r in 1i64.. {
321        let mut ring: Vec<Point> = (-r..=r)
322            .flat_map(|i| {
323                [
324                    (home.0 + i, home.1 - r),
325                    (home.0 + i, home.1 + r),
326                    (home.0 - r, home.1 + i),
327                    (home.0 + r, home.1 + i),
328                ]
329            })
330            .filter(|p| !taken.contains(p))
331            .collect();
332        if ring.is_empty() {
333            continue;
334        }
335        ring.sort_by(|p, q| {
336            let d = |p: &Point| (p.0 as f64 - x).powi(2) + (p.1 as f64 - y).powi(2);
337            d(p).total_cmp(&d(q)).then(p.cmp(q))
338        });
339        return ring[0];
340    }
341    unreachable!("a ring holds a free point")
342}
343
344/// The shapes a line from `a` to `b` can take, as its lattice points, ends included: straight
345/// where it can be; else a diagonal and a straight piece, either way round, and, where the
346/// straight part is long enough to halve, a diagonal between its halves.
347fn shapes(a: Point, b: Point) -> Vec<Vec<Point>> {
348    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
349    let (ax, ay) = (dx.abs(), dy.abs());
350    if ax == 0 || ay == 0 || ax == ay {
351        return vec![vec![a, b]];
352    }
353    let m = ax.min(ay);
354    let r = ax.max(ay) - m;
355    let diagonal = (dx.signum(), dy.signum());
356    let straight = if ax > ay {
357        (dx.signum(), 0)
358    } else {
359        (0, dy.signum())
360    };
361    let go = |p: Point, d: Point, n: i64| (p.0 + d.0 * n, p.1 + d.1 * n);
362    let mut out = vec![
363        vec![a, go(a, diagonal, m), b],
364        vec![a, go(a, straight, r), b],
365    ];
366    if r >= 2 {
367        let h = go(a, straight, r / 2);
368        out.push(vec![a, h, go(h, diagonal, m), b]);
369    }
370    out
371}
372
373/// The lattice's unit pieces lines are drawn along, and the nodes' points.
374#[derive(Default)]
375struct Drawn {
376    pieces: HashSet<(Point, Point)>,
377}
378
379/// A unit piece, the same whichever way it is walked.
380fn piece(p: Point, q: Point) -> (Point, Point) {
381    if p <= q { (p, q) } else { (q, p) }
382}
383
384/// Each unit step along `path`: from where, and which way.
385fn steps(path: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
386    path.windows(2).flat_map(|w| {
387        let (p, q) = (w[0], w[1]);
388        let d = ((q.0 - p.0).signum(), (q.1 - p.1).signum());
389        let n = (q.0 - p.0).abs().max((q.1 - p.1).abs());
390        (0..n).map(move |i| ((p.0 + d.0 * i, p.1 + d.1 * i), d))
391    })
392}
393
394impl Drawn {
395    fn cost(&self, path: &[Point], nodes: &HashSet<Point>) -> u32 {
396        let (a, b) = (path[0], path[path.len() - 1]);
397        let mut cost = BEND * (path.len() as u32 - 2);
398        for (p, d) in steps(path) {
399            let q = (p.0 + d.0, p.1 + d.1);
400            if q != b && q != a && nodes.contains(&q) {
401                cost += THROUGH_NODE;
402            }
403            if self.pieces.contains(&piece(p, q)) {
404                cost += SHARED;
405            }
406            // A diagonal crosses the other diagonal of its square.
407            if d.0 != 0
408                && d.1 != 0
409                && self
410                    .pieces
411                    .contains(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
412            {
413                cost += CROSSING;
414            }
415        }
416        cost
417    }
418
419    fn add(&mut self, path: &[Point]) {
420        for (p, d) in steps(path) {
421            self.pieces.insert(piece(p, (p.0 + d.0, p.1 + d.1)));
422        }
423    }
424}
425
426/// Lines crossing others where the shapes are drawn, counted for the tests: each pair of unit
427/// pieces crossing in a square.
428#[cfg(test)]
429fn crossings(routes: &[Vec<(f64, f64)>]) -> usize {
430    let mut drawn: HashMap<(Point, Point), usize> = HashMap::new();
431    let lattice = |p: (f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
432    let mut count = 0;
433    for (k, r) in routes.iter().enumerate() {
434        let path: Vec<Point> = r.iter().map(|&p| lattice(p)).collect();
435        let mut path = path;
436        path.dedup();
437        for (p, d) in steps(&path) {
438            if d.0 != 0
439                && d.1 != 0
440                && drawn
441                    .get(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
442                    .is_some_and(|&o| o != k)
443            {
444                count += 1;
445            }
446        }
447        for (p, d) in steps(&path) {
448            drawn.insert(piece(p, (p.0 + d.0, p.1 + d.1)), k);
449        }
450    }
451    count
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    /// Each piece of each route along an axis or a diagonal.
459    fn octilinear_pieces(routes: &[Vec<(f64, f64)>]) -> bool {
460        routes.iter().all(|r| {
461            r.windows(2).all(|w| {
462                let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
463                dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9
464            })
465        })
466    }
467
468    #[test]
469    fn lines_run_along_axes_and_diagonals() {
470        let pos = [(0.0, 0.0), (1.7, 0.6), (0.4, 1.9), (2.2, 2.4), (-1.3, 0.8)];
471        let edges = [(0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (4, 2)];
472        let Schematic { nodes, routes, .. } = octilinear(&pos, &edges);
473        assert!(octilinear_pieces(&routes), "{routes:?}");
474        for (k, &(a, b)) in edges.iter().enumerate() {
475            assert_eq!(
476                routes[k].first(),
477                Some(&nodes[a]),
478                "edge {k} from its source"
479            );
480            assert_eq!(routes[k].last(), Some(&nodes[b]), "edge {k} to its target");
481            assert!(routes[k].len() <= 4, "at most two bends: {:?}", routes[k]);
482        }
483    }
484
485    #[test]
486    fn nodes_keep_apart_and_near_where_they_were() {
487        // Three on top of each other: each its own point, the nearest free ones.
488        let pos = [(0.0, 0.0), (0.01, 0.0), (0.0, 0.02), (3.0, 3.0)];
489        let Schematic { nodes, .. } = octilinear(&pos, &[(0, 3), (1, 3), (2, 3)]);
490        let distinct: HashSet<(i64, i64)> = nodes
491            .iter()
492            .map(|p| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64))
493            .collect();
494        assert_eq!(distinct.len(), 4);
495        assert!(
496            nodes
497                .iter()
498                .zip(&pos)
499                .all(|(p, q)| (p.0 - q.0).abs() <= 2.0 * STEP && (p.1 - q.1).abs() <= 2.0 * STEP)
500        );
501    }
502
503    #[test]
504    fn a_line_goes_round_a_node_in_its_way() {
505        // A straight line from 0 to 2 would pass through 1.
506        let pos = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.5)];
507        let Schematic { nodes, routes, .. } = octilinear(&pos, &[(0, 2), (0, 1)]);
508        let through = |r: &Vec<(f64, f64)>, p: (f64, f64)| {
509            r.windows(2).any(|w| {
510                let (a, b) = (w[0], w[1]);
511                let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
512                let within = (p.0 - a.0) * (p.0 - b.0) <= 1e-9 && (p.1 - a.1) * (p.1 - b.1) <= 1e-9;
513                cross.abs() < 1e-9 && within && p != a && p != b
514            })
515        };
516        assert!(
517            !through(&routes[0], nodes[1]),
518            "{:?} through {:?}",
519            routes[0],
520            nodes[1]
521        );
522    }
523
524    #[test]
525    fn double_circuits_run_side_by_side() {
526        let pos = [(0.0, 0.0), (2.0, 1.0)];
527        let Schematic {
528            nodes,
529            routes,
530            tracks,
531        } = octilinear(&pos, &[(0, 1), (1, 0), (0, 1)]);
532        assert!(octilinear_pieces(&routes), "{routes:?}");
533        // One route, three tracks: one each side of the middle one.
534        assert_eq!(routes[0], routes[2]);
535        assert_eq!(
536            routes[1],
537            routes[0].iter().rev().copied().collect::<Vec<_>>()
538        );
539        assert_eq!(
540            routes[1][0], nodes[1],
541            "the one written the other way round, from its own source"
542        );
543        // The second, walked the other way, on its own left: the first's right; the third on the
544        // first's left.
545        assert_eq!(tracks, vec![0, 1, 1]);
546    }
547
548    #[test]
549    fn lines_sharing_a_stretch_take_tracks_of_their_own() {
550        // 0 and 1 both reach 2 along the same diagonal from the left.
551        let pos = [(0.0, 0.0), (-1.0, 0.0), (1.5, 1.5)];
552        let Schematic { routes, tracks, .. } = octilinear(&pos, &[(0, 2), (1, 2)]);
553        let shared = routes[0]
554            .windows(2)
555            .any(|w| routes[1].windows(2).any(|v| v == w));
556        if shared {
557            assert_ne!(tracks[0], tracks[1], "{routes:?} {tracks:?}");
558        }
559        assert!(tracks.contains(&0));
560    }
561
562    #[test]
563    fn the_same_grid_the_same_schematic() {
564        let pos: Vec<(f64, f64)> = (0..60)
565            .map(|i| (((i * 37) % 23) as f64 * 0.7, ((i * 53) % 19) as f64 * 0.6))
566            .collect();
567        let edges: Vec<(usize, usize)> = (0..59).map(|i| (i, (i * 7 + 3) % 60)).collect();
568        assert_eq!(octilinear(&pos, &edges), octilinear(&pos, &edges));
569        let Schematic { routes, .. } = octilinear(&pos, &edges);
570        assert!(octilinear_pieces(&routes));
571        assert!(crossings(&routes) < edges.len());
572    }
573}
574
575#[cfg(test)]
576mod timing {
577    /// RealGrid's size: 4875 nodes, 7752 edges, laid out by force first. `cargo test --release -- --ignored`.
578    #[test]
579    #[ignore]
580    fn realgrid_sized() {
581        let n = 4875;
582        let mut edges: Vec<(usize, usize)> = (1..n).map(|i| (i, (i * 7919) % i)).collect();
583        edges.extend((0..2878).map(|i| ((i * 31) % n, (i * 31 + 17) % n)));
584        let pos = crate::layout::force(n, &edges);
585        let t = std::time::Instant::now();
586        let super::Schematic { routes, .. } = super::octilinear(&pos, &edges);
587        eprintln!("octilinear: {:?} for {} routes", t.elapsed(), routes.len());
588    }
589}
590
591#[cfg(test)]
592mod shared_count {
593    /// How many unit pieces lines between different pairs share, on SmallGrid and RealGrid.
594    #[test]
595    #[ignore]
596    fn shared_pieces() {
597        for dir in ["SmallGrid/SmallGrid-Merged", "RealGrid/RealGrid-Merged"] {
598            let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
599                .join("../CGMES-Test-Configurations/v3.0")
600                .join(dir);
601            let read = crate::testing::collect(&path);
602            let datasets: Vec<cimmodel::CimDataset> = read
603                .iter()
604                .map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
605                .collect();
606            let m = crate::grid::Model::new(&datasets);
607            let g = crate::grid::build(&m);
608            let auto = g.auto.as_ref().unwrap();
609            let mut seen: std::collections::HashMap<((i64, i64), (i64, i64)), (usize, usize)> =
610                std::collections::HashMap::new();
611            let (mut shared, mut total) = (0, 0);
612            let mut high = 0;
613            for (&k, r) in &auto.edges {
614                let e = &g.edges[k];
615                let pair = (e.source.min(e.target), e.source.max(e.target));
616                let lattice: Vec<(i64, i64)> = r
617                    .iter()
618                    .map(|p| {
619                        (
620                            (p.0 / super::STEP).round() as i64,
621                            (p.1 / super::STEP).round() as i64,
622                        )
623                    })
624                    .collect();
625                for (p, d) in super::steps(&lattice) {
626                    let q = (p.0 + d.0, p.1 + d.1);
627                    let key = if p <= q { (p, q) } else { (q, p) };
628                    total += 1;
629                    if let Some(o) = seen.get(&key) {
630                        if *o != pair {
631                            shared += 1;
632                            if e.kv.is_some_and(|v| v >= 300.0) {
633                                high += 1;
634                            }
635                        }
636                    } else {
637                        seen.insert(key, pair);
638                    }
639                }
640            }
641            eprintln!(
642                "{dir}: {shared} of {total} unit pieces shared between different pairs, {high} on ≥300 kV lines"
643            );
644        }
645    }
646}