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/// Each node's lattice point: the nearest free one to its position, the nodes with most edges
123/// placed first.
124fn snap(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Vec<Point> {
125    let mut degree = vec![0usize; pos.len()];
126    for &(a, b) in edges {
127        degree[a] += 1;
128        degree[b] += 1;
129    }
130    let mut order: Vec<usize> = (0..pos.len()).collect();
131    order.sort_by_key(|&i| (std::cmp::Reverse(degree[i]), i));
132    let mut taken: HashSet<Point> = HashSet::new();
133    let mut at = vec![(0, 0); pos.len()];
134    for i in order {
135        let (x, y) = (pos[i].0 / STEP, pos[i].1 / STEP);
136        let home = (x.round() as i64, y.round() as i64);
137        let mut best = home;
138        if taken.contains(&home) {
139            // The ring around it, then the next, until one has a free point: its nearest.
140            'rings: for r in 1i64.. {
141                let mut ring: Vec<Point> = (-r..=r)
142                    .flat_map(|i| {
143                        [
144                            (home.0 + i, home.1 - r),
145                            (home.0 + i, home.1 + r),
146                            (home.0 - r, home.1 + i),
147                            (home.0 + r, home.1 + i),
148                        ]
149                    })
150                    .filter(|p| !taken.contains(p))
151                    .collect();
152                if ring.is_empty() {
153                    continue;
154                }
155                ring.sort_by(|p, q| {
156                    let d = |p: &Point| (p.0 as f64 - x).powi(2) + (p.1 as f64 - y).powi(2);
157                    d(p).total_cmp(&d(q)).then(p.cmp(q))
158                });
159                best = ring[0];
160                break 'rings;
161            }
162        }
163        taken.insert(best);
164        at[i] = best;
165    }
166    at
167}
168
169/// The shapes a line from `a` to `b` can take, as its lattice points, ends included: straight
170/// where it can be; else a diagonal and a straight piece, either way round, and, where the
171/// straight part is long enough to halve, a diagonal between its halves.
172fn shapes(a: Point, b: Point) -> Vec<Vec<Point>> {
173    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
174    let (ax, ay) = (dx.abs(), dy.abs());
175    if ax == 0 || ay == 0 || ax == ay {
176        return vec![vec![a, b]];
177    }
178    let m = ax.min(ay);
179    let r = ax.max(ay) - m;
180    let diagonal = (dx.signum(), dy.signum());
181    let straight = if ax > ay {
182        (dx.signum(), 0)
183    } else {
184        (0, dy.signum())
185    };
186    let go = |p: Point, d: Point, n: i64| (p.0 + d.0 * n, p.1 + d.1 * n);
187    let mut out = vec![
188        vec![a, go(a, diagonal, m), b],
189        vec![a, go(a, straight, r), b],
190    ];
191    if r >= 2 {
192        let h = go(a, straight, r / 2);
193        out.push(vec![a, h, go(h, diagonal, m), b]);
194    }
195    out
196}
197
198/// The lattice's unit pieces lines are drawn along, and the nodes' points.
199#[derive(Default)]
200struct Drawn {
201    pieces: HashSet<(Point, Point)>,
202}
203
204/// A unit piece, the same whichever way it is walked.
205fn piece(p: Point, q: Point) -> (Point, Point) {
206    if p <= q { (p, q) } else { (q, p) }
207}
208
209/// Each unit step along `path`: from where, and which way.
210fn steps(path: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
211    path.windows(2).flat_map(|w| {
212        let (p, q) = (w[0], w[1]);
213        let d = ((q.0 - p.0).signum(), (q.1 - p.1).signum());
214        let n = (q.0 - p.0).abs().max((q.1 - p.1).abs());
215        (0..n).map(move |i| ((p.0 + d.0 * i, p.1 + d.1 * i), d))
216    })
217}
218
219impl Drawn {
220    fn cost(&self, path: &[Point], nodes: &HashSet<Point>) -> u32 {
221        let (a, b) = (path[0], path[path.len() - 1]);
222        let mut cost = BEND * (path.len() as u32 - 2);
223        for (p, d) in steps(path) {
224            let q = (p.0 + d.0, p.1 + d.1);
225            if q != b && q != a && nodes.contains(&q) {
226                cost += THROUGH_NODE;
227            }
228            if self.pieces.contains(&piece(p, q)) {
229                cost += SHARED;
230            }
231            // A diagonal crosses the other diagonal of its square.
232            if d.0 != 0
233                && d.1 != 0
234                && self
235                    .pieces
236                    .contains(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
237            {
238                cost += CROSSING;
239            }
240        }
241        cost
242    }
243
244    fn add(&mut self, path: &[Point]) {
245        for (p, d) in steps(path) {
246            self.pieces.insert(piece(p, (p.0 + d.0, p.1 + d.1)));
247        }
248    }
249}
250
251/// Lines crossing others where the shapes are drawn, counted for the tests: each pair of unit
252/// pieces crossing in a square.
253#[cfg(test)]
254fn crossings(routes: &[Vec<(f64, f64)>]) -> usize {
255    let mut drawn: HashMap<(Point, Point), usize> = HashMap::new();
256    let lattice = |p: (f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
257    let mut count = 0;
258    for (k, r) in routes.iter().enumerate() {
259        let path: Vec<Point> = r.iter().map(|&p| lattice(p)).collect();
260        let mut path = path;
261        path.dedup();
262        for (p, d) in steps(&path) {
263            if d.0 != 0
264                && d.1 != 0
265                && drawn
266                    .get(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
267                    .is_some_and(|&o| o != k)
268            {
269                count += 1;
270            }
271        }
272        for (p, d) in steps(&path) {
273            drawn.insert(piece(p, (p.0 + d.0, p.1 + d.1)), k);
274        }
275    }
276    count
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    /// Each piece of each route along an axis or a diagonal.
284    fn octilinear_pieces(routes: &[Vec<(f64, f64)>]) -> bool {
285        routes.iter().all(|r| {
286            r.windows(2).all(|w| {
287                let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
288                dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9
289            })
290        })
291    }
292
293    #[test]
294    fn lines_run_along_axes_and_diagonals() {
295        let pos = [(0.0, 0.0), (1.7, 0.6), (0.4, 1.9), (2.2, 2.4), (-1.3, 0.8)];
296        let edges = [(0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (4, 2)];
297        let Schematic { nodes, routes, .. } = octilinear(&pos, &edges);
298        assert!(octilinear_pieces(&routes), "{routes:?}");
299        for (k, &(a, b)) in edges.iter().enumerate() {
300            assert_eq!(
301                routes[k].first(),
302                Some(&nodes[a]),
303                "edge {k} from its source"
304            );
305            assert_eq!(routes[k].last(), Some(&nodes[b]), "edge {k} to its target");
306            assert!(routes[k].len() <= 4, "at most two bends: {:?}", routes[k]);
307        }
308    }
309
310    #[test]
311    fn nodes_keep_apart_and_near_where_they_were() {
312        // Three on top of each other: each its own point, the nearest free ones.
313        let pos = [(0.0, 0.0), (0.01, 0.0), (0.0, 0.02), (3.0, 3.0)];
314        let Schematic { nodes, .. } = octilinear(&pos, &[(0, 3), (1, 3), (2, 3)]);
315        let distinct: HashSet<(i64, i64)> = nodes
316            .iter()
317            .map(|p| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64))
318            .collect();
319        assert_eq!(distinct.len(), 4);
320        assert!(
321            nodes
322                .iter()
323                .zip(&pos)
324                .all(|(p, q)| (p.0 - q.0).abs() <= 2.0 * STEP && (p.1 - q.1).abs() <= 2.0 * STEP)
325        );
326    }
327
328    #[test]
329    fn a_line_goes_round_a_node_in_its_way() {
330        // A straight line from 0 to 2 would pass through 1.
331        let pos = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.5)];
332        let Schematic { nodes, routes, .. } = octilinear(&pos, &[(0, 2), (0, 1)]);
333        let through = |r: &Vec<(f64, f64)>, p: (f64, f64)| {
334            r.windows(2).any(|w| {
335                let (a, b) = (w[0], w[1]);
336                let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
337                let within = (p.0 - a.0) * (p.0 - b.0) <= 1e-9 && (p.1 - a.1) * (p.1 - b.1) <= 1e-9;
338                cross.abs() < 1e-9 && within && p != a && p != b
339            })
340        };
341        assert!(
342            !through(&routes[0], nodes[1]),
343            "{:?} through {:?}",
344            routes[0],
345            nodes[1]
346        );
347    }
348
349    #[test]
350    fn double_circuits_run_side_by_side() {
351        let pos = [(0.0, 0.0), (2.0, 1.0)];
352        let Schematic {
353            nodes,
354            routes,
355            tracks,
356        } = octilinear(&pos, &[(0, 1), (1, 0), (0, 1)]);
357        assert!(octilinear_pieces(&routes), "{routes:?}");
358        // One route, three tracks: one each side of the middle one.
359        assert_eq!(routes[0], routes[2]);
360        assert_eq!(
361            routes[1],
362            routes[0].iter().rev().copied().collect::<Vec<_>>()
363        );
364        assert_eq!(
365            routes[1][0], nodes[1],
366            "the one written the other way round, from its own source"
367        );
368        // The second, walked the other way, on its own left: the first's right; the third on the
369        // first's left.
370        assert_eq!(tracks, vec![0, 1, 1]);
371    }
372
373    #[test]
374    fn lines_sharing_a_stretch_take_tracks_of_their_own() {
375        // 0 and 1 both reach 2 along the same diagonal from the left.
376        let pos = [(0.0, 0.0), (-1.0, 0.0), (1.5, 1.5)];
377        let Schematic { routes, tracks, .. } = octilinear(&pos, &[(0, 2), (1, 2)]);
378        let shared = routes[0]
379            .windows(2)
380            .any(|w| routes[1].windows(2).any(|v| v == w));
381        if shared {
382            assert_ne!(tracks[0], tracks[1], "{routes:?} {tracks:?}");
383        }
384        assert!(tracks.contains(&0));
385    }
386
387    #[test]
388    fn the_same_grid_the_same_schematic() {
389        let pos: Vec<(f64, f64)> = (0..60)
390            .map(|i| (((i * 37) % 23) as f64 * 0.7, ((i * 53) % 19) as f64 * 0.6))
391            .collect();
392        let edges: Vec<(usize, usize)> = (0..59).map(|i| (i, (i * 7 + 3) % 60)).collect();
393        assert_eq!(octilinear(&pos, &edges), octilinear(&pos, &edges));
394        let Schematic { routes, .. } = octilinear(&pos, &edges);
395        assert!(octilinear_pieces(&routes));
396        assert!(crossings(&routes) < edges.len());
397    }
398}
399
400#[cfg(test)]
401mod timing {
402    /// RealGrid's size: 4875 nodes, 7752 edges, laid out by force first. `cargo test --release -- --ignored`.
403    #[test]
404    #[ignore]
405    fn realgrid_sized() {
406        let n = 4875;
407        let mut edges: Vec<(usize, usize)> = (1..n).map(|i| (i, (i * 7919) % i)).collect();
408        edges.extend((0..2878).map(|i| ((i * 31) % n, (i * 31 + 17) % n)));
409        let pos = crate::layout::force(n, &edges);
410        let t = std::time::Instant::now();
411        let super::Schematic { routes, .. } = super::octilinear(&pos, &edges);
412        eprintln!("octilinear: {:?} for {} routes", t.elapsed(), routes.len());
413    }
414}
415
416#[cfg(test)]
417mod shared_count {
418    /// How many unit pieces lines between different pairs share, on SmallGrid and RealGrid.
419    #[test]
420    #[ignore]
421    fn shared_pieces() {
422        for dir in ["SmallGrid/SmallGrid-Merged", "RealGrid/RealGrid-Merged"] {
423            let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
424                .join("../CGMES-Test-Configurations/v3.0")
425                .join(dir);
426            let read = crate::testing::collect(&path);
427            let datasets: Vec<cimmodel::CimDataset> = read
428                .iter()
429                .map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
430                .collect();
431            let m = crate::grid::Model::new(&datasets);
432            let g = crate::grid::build(&m);
433            let auto = g.auto.as_ref().unwrap();
434            let mut seen: std::collections::HashMap<((i64, i64), (i64, i64)), (usize, usize)> =
435                std::collections::HashMap::new();
436            let (mut shared, mut total) = (0, 0);
437            let mut high = 0;
438            for (&k, r) in &auto.edges {
439                let e = &g.edges[k];
440                let pair = (e.source.min(e.target), e.source.max(e.target));
441                let lattice: Vec<(i64, i64)> = r
442                    .iter()
443                    .map(|p| {
444                        (
445                            (p.0 / super::STEP).round() as i64,
446                            (p.1 / super::STEP).round() as i64,
447                        )
448                    })
449                    .collect();
450                for (p, d) in super::steps(&lattice) {
451                    let q = (p.0 + d.0, p.1 + d.1);
452                    let key = if p <= q { (p, q) } else { (q, p) };
453                    total += 1;
454                    if let Some(o) = seen.get(&key) {
455                        if *o != pair {
456                            shared += 1;
457                            if e.kv.is_some_and(|v| v >= 300.0) {
458                                high += 1;
459                            }
460                        }
461                    } else {
462                        seen.insert(key, pair);
463                    }
464                }
465            }
466            eprintln!(
467                "{dir}: {shared} of {total} unit pieces shared between different pairs, {high} on ≥300 kV lines"
468            );
469        }
470    }
471}