cimoxide-view 0.7.2

A CGMES or NC model set as views: its grid at substation level, laid out, and its objects as a tree, with validation findings on each; and its files as text: where each object is written, and edits across them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! The grid's automatic layout as a schematic: lines only horizontal, vertical or at 45°, as
//! transmission overview diagrams draw them.
//!
//! The positions [`crate::layout::force`] finds are snapped to a lattice, the busiest node first,
//! one that would land on another taking the nearest free point. Each line then runs from lattice
//! point to lattice point in at most three straight pieces, each along an axis or a diagonal: of
//! the shapes it can take (straight; a diagonal and a straight piece, either way round; a
//! straight piece, a diagonal and another), the one that passes through no other node, shares no
//! piece with a line already drawn, crosses the fewest, and bends least. The shorter lines go
//! first, so that local connections keep the plainest shapes. Lines joining the same two nodes
//! (double circuits) run side by side, stepped aside where they leave a node.
//!
//! Linear in the lines times their lengths on the lattice, and deterministic.

use std::collections::{BTreeMap, HashMap, HashSet};

/// The lattice spacing, in the units of the positions it snaps ([`crate::layout::force`]'s, a
/// line's ideal length being one): a line spans about two points.
const STEP: f64 = 0.5;

/// What a shape costs: passing through another node, sharing a piece with a line drawn, crossing
/// one, and each bend.
const THROUGH_NODE: u32 = 40;
const SHARED: u32 = 12;
const CROSSING: u32 = 3;
const BEND: u32 = 1;

type Point = (i64, i64);

/// A schematic: each node's position and each edge's route, from its source to its target (in
/// [`crate::layout::force`]'s units; a loop has none), and the track each edge runs on.
#[derive(Debug, PartialEq)]
pub struct Schematic {
    pub nodes: Vec<(f64, f64)>,
    pub routes: Vec<Vec<(f64, f64)>>,
    /// How many line spacings aside each edge runs from its route, to the left of its way from
    /// source to target (negative: to the right), so that lines sharing a stretch — two circuits
    /// between the same nodes, or lines whose routes meet — are drawn side by side: the views
    /// space them by what they draw, in pixels.
    pub tracks: Vec<i32>,
}

/// Nodes at `pos` (in [`crate::layout::force`]'s units) and their `edges`, as a schematic.
pub fn octilinear(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Schematic {
    let at = snap(pos, edges);
    let unit = |p: Point| (p.0 as f64 * STEP, p.1 as f64 * STEP);
    let taken: HashSet<Point> = at.iter().copied().collect();

    // The edges by the two nodes they join; the pairs, shortest first.
    let mut pairs: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
    for (k, &(a, b)) in edges.iter().enumerate() {
        if a != b {
            pairs.entry((a.min(b), a.max(b))).or_default().push(k);
        }
    }
    let mut order: Vec<(usize, usize)> = pairs.keys().copied().collect();
    let span = |&(a, b): &(usize, usize)| {
        let (d0, d1) = ((at[b].0 - at[a].0).abs(), (at[b].1 - at[a].1).abs());
        (d0.max(d1), d0.min(d1))
    };
    order.sort_by_key(|p| (span(p), *p));

    let mut drawn = Drawn::default();
    let mut paths: Vec<Vec<Point>> = vec![Vec::new(); edges.len()];
    let mut walked = Vec::new();
    for pair in order {
        let (a, b) = pair;
        let path = shapes(at[a], at[b])
            .into_iter()
            .map(|path| (drawn.cost(&path, &taken), path))
            .min_by_key(|(cost, _)| *cost)
            .map(|(_, path)| path)
            .expect("a shape at least");
        drawn.add(&path);
        for &k in &pairs[&pair] {
            // From the edge's own source to its target.
            paths[k] = if edges[k].0 == a {
                path.clone()
            } else {
                path.iter().rev().copied().collect()
            };
            walked.push(k);
        }
    }

    // Tracks: each edge, in the order routed, on the track nearest its route that none drawn
    // before it takes on any piece it shares. A track to the left of one way along a piece is to
    // the right of the other, so each is kept as the piece's own side.
    let mut sides: HashMap<(Point, Point), HashSet<i32>> = HashMap::new();
    let mut tracks = vec![0; edges.len()];
    for k in walked {
        let pieces: Vec<((Point, Point), i32)> = steps(&paths[k])
            .map(|(p, d)| {
                let q = (p.0 + d.0, p.1 + d.1);
                (piece(p, q), if p <= q { 1 } else { -1 })
            })
            .collect();
        let free = |t: i32| {
            pieces
                .iter()
                .all(|(key, sign)| !sides.get(key).is_some_and(|s| s.contains(&(t * sign))))
        };
        let track = (0..)
            .flat_map(|i: i32| if i == 0 { vec![0] } else { vec![i, -i] })
            .find(|&t| free(t))
            .expect("a free track");
        for (key, sign) in pieces {
            sides.entry(key).or_default().insert(track * sign);
        }
        tracks[k] = track;
    }
    Schematic {
        nodes: at.into_iter().map(unit).collect(),
        routes: paths
            .into_iter()
            .map(|p| p.into_iter().map(unit).collect())
            .collect(),
        tracks,
    }
}

/// Each node's lattice point: the nearest free one to its position, the nodes with most edges
/// placed first.
fn snap(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Vec<Point> {
    let mut degree = vec![0usize; pos.len()];
    for &(a, b) in edges {
        degree[a] += 1;
        degree[b] += 1;
    }
    let mut order: Vec<usize> = (0..pos.len()).collect();
    order.sort_by_key(|&i| (std::cmp::Reverse(degree[i]), i));
    let mut taken: HashSet<Point> = HashSet::new();
    let mut at = vec![(0, 0); pos.len()];
    for i in order {
        let (x, y) = (pos[i].0 / STEP, pos[i].1 / STEP);
        let home = (x.round() as i64, y.round() as i64);
        let mut best = home;
        if taken.contains(&home) {
            // The ring around it, then the next, until one has a free point: its nearest.
            'rings: for r in 1i64.. {
                let mut ring: Vec<Point> = (-r..=r)
                    .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),
                        ]
                    })
                    .filter(|p| !taken.contains(p))
                    .collect();
                if ring.is_empty() {
                    continue;
                }
                ring.sort_by(|p, q| {
                    let d = |p: &Point| (p.0 as f64 - x).powi(2) + (p.1 as f64 - y).powi(2);
                    d(p).total_cmp(&d(q)).then(p.cmp(q))
                });
                best = ring[0];
                break 'rings;
            }
        }
        taken.insert(best);
        at[i] = best;
    }
    at
}

/// The shapes a line from `a` to `b` can take, as its lattice points, ends included: straight
/// where it can be; else a diagonal and a straight piece, either way round, and, where the
/// straight part is long enough to halve, a diagonal between its halves.
fn shapes(a: Point, b: Point) -> Vec<Vec<Point>> {
    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
    let (ax, ay) = (dx.abs(), dy.abs());
    if ax == 0 || ay == 0 || ax == ay {
        return vec![vec![a, b]];
    }
    let m = ax.min(ay);
    let r = ax.max(ay) - m;
    let diagonal = (dx.signum(), dy.signum());
    let straight = if ax > ay {
        (dx.signum(), 0)
    } else {
        (0, dy.signum())
    };
    let go = |p: Point, d: Point, n: i64| (p.0 + d.0 * n, p.1 + d.1 * n);
    let mut out = vec![
        vec![a, go(a, diagonal, m), b],
        vec![a, go(a, straight, r), b],
    ];
    if r >= 2 {
        let h = go(a, straight, r / 2);
        out.push(vec![a, h, go(h, diagonal, m), b]);
    }
    out
}

/// The lattice's unit pieces lines are drawn along, and the nodes' points.
#[derive(Default)]
struct Drawn {
    pieces: HashSet<(Point, Point)>,
}

/// A unit piece, the same whichever way it is walked.
fn piece(p: Point, q: Point) -> (Point, Point) {
    if p <= q { (p, q) } else { (q, p) }
}

/// Each unit step along `path`: from where, and which way.
fn steps(path: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
    path.windows(2).flat_map(|w| {
        let (p, q) = (w[0], w[1]);
        let d = ((q.0 - p.0).signum(), (q.1 - p.1).signum());
        let n = (q.0 - p.0).abs().max((q.1 - p.1).abs());
        (0..n).map(move |i| ((p.0 + d.0 * i, p.1 + d.1 * i), d))
    })
}

impl Drawn {
    fn cost(&self, path: &[Point], nodes: &HashSet<Point>) -> u32 {
        let (a, b) = (path[0], path[path.len() - 1]);
        let mut cost = BEND * (path.len() as u32 - 2);
        for (p, d) in steps(path) {
            let q = (p.0 + d.0, p.1 + d.1);
            if q != b && q != a && nodes.contains(&q) {
                cost += THROUGH_NODE;
            }
            if self.pieces.contains(&piece(p, q)) {
                cost += SHARED;
            }
            // A diagonal crosses the other diagonal of its square.
            if d.0 != 0
                && d.1 != 0
                && self
                    .pieces
                    .contains(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
            {
                cost += CROSSING;
            }
        }
        cost
    }

    fn add(&mut self, path: &[Point]) {
        for (p, d) in steps(path) {
            self.pieces.insert(piece(p, (p.0 + d.0, p.1 + d.1)));
        }
    }
}

/// Lines crossing others where the shapes are drawn, counted for the tests: each pair of unit
/// pieces crossing in a square.
#[cfg(test)]
fn crossings(routes: &[Vec<(f64, f64)>]) -> usize {
    let mut drawn: HashMap<(Point, Point), usize> = HashMap::new();
    let lattice = |p: (f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
    let mut count = 0;
    for (k, r) in routes.iter().enumerate() {
        let path: Vec<Point> = r.iter().map(|&p| lattice(p)).collect();
        let mut path = path;
        path.dedup();
        for (p, d) in steps(&path) {
            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)
            {
                count += 1;
            }
        }
        for (p, d) in steps(&path) {
            drawn.insert(piece(p, (p.0 + d.0, p.1 + d.1)), k);
        }
    }
    count
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Each piece of each route along an axis or a diagonal.
    fn octilinear_pieces(routes: &[Vec<(f64, f64)>]) -> bool {
        routes.iter().all(|r| {
            r.windows(2).all(|w| {
                let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
                dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9
            })
        })
    }

    #[test]
    fn lines_run_along_axes_and_diagonals() {
        let pos = [(0.0, 0.0), (1.7, 0.6), (0.4, 1.9), (2.2, 2.4), (-1.3, 0.8)];
        let edges = [(0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (4, 2)];
        let Schematic { nodes, routes, .. } = octilinear(&pos, &edges);
        assert!(octilinear_pieces(&routes), "{routes:?}");
        for (k, &(a, b)) in edges.iter().enumerate() {
            assert_eq!(
                routes[k].first(),
                Some(&nodes[a]),
                "edge {k} from its source"
            );
            assert_eq!(routes[k].last(), Some(&nodes[b]), "edge {k} to its target");
            assert!(routes[k].len() <= 4, "at most two bends: {:?}", routes[k]);
        }
    }

    #[test]
    fn nodes_keep_apart_and_near_where_they_were() {
        // Three on top of each other: each its own point, the nearest free ones.
        let pos = [(0.0, 0.0), (0.01, 0.0), (0.0, 0.02), (3.0, 3.0)];
        let Schematic { nodes, .. } = octilinear(&pos, &[(0, 3), (1, 3), (2, 3)]);
        let distinct: HashSet<(i64, i64)> = nodes
            .iter()
            .map(|p| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64))
            .collect();
        assert_eq!(distinct.len(), 4);
        assert!(
            nodes
                .iter()
                .zip(&pos)
                .all(|(p, q)| (p.0 - q.0).abs() <= 2.0 * STEP && (p.1 - q.1).abs() <= 2.0 * STEP)
        );
    }

    #[test]
    fn a_line_goes_round_a_node_in_its_way() {
        // A straight line from 0 to 2 would pass through 1.
        let pos = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.5)];
        let Schematic { nodes, routes, .. } = octilinear(&pos, &[(0, 2), (0, 1)]);
        let through = |r: &Vec<(f64, f64)>, p: (f64, f64)| {
            r.windows(2).any(|w| {
                let (a, b) = (w[0], w[1]);
                let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
                let within = (p.0 - a.0) * (p.0 - b.0) <= 1e-9 && (p.1 - a.1) * (p.1 - b.1) <= 1e-9;
                cross.abs() < 1e-9 && within && p != a && p != b
            })
        };
        assert!(
            !through(&routes[0], nodes[1]),
            "{:?} through {:?}",
            routes[0],
            nodes[1]
        );
    }

    #[test]
    fn double_circuits_run_side_by_side() {
        let pos = [(0.0, 0.0), (2.0, 1.0)];
        let Schematic {
            nodes,
            routes,
            tracks,
        } = octilinear(&pos, &[(0, 1), (1, 0), (0, 1)]);
        assert!(octilinear_pieces(&routes), "{routes:?}");
        // One route, three tracks: one each side of the middle one.
        assert_eq!(routes[0], routes[2]);
        assert_eq!(
            routes[1],
            routes[0].iter().rev().copied().collect::<Vec<_>>()
        );
        assert_eq!(
            routes[1][0], nodes[1],
            "the one written the other way round, from its own source"
        );
        // The second, walked the other way, on its own left: the first's right; the third on the
        // first's left.
        assert_eq!(tracks, vec![0, 1, 1]);
    }

    #[test]
    fn lines_sharing_a_stretch_take_tracks_of_their_own() {
        // 0 and 1 both reach 2 along the same diagonal from the left.
        let pos = [(0.0, 0.0), (-1.0, 0.0), (1.5, 1.5)];
        let Schematic { routes, tracks, .. } = octilinear(&pos, &[(0, 2), (1, 2)]);
        let shared = routes[0]
            .windows(2)
            .any(|w| routes[1].windows(2).any(|v| v == w));
        if shared {
            assert_ne!(tracks[0], tracks[1], "{routes:?} {tracks:?}");
        }
        assert!(tracks.contains(&0));
    }

    #[test]
    fn the_same_grid_the_same_schematic() {
        let pos: Vec<(f64, f64)> = (0..60)
            .map(|i| (((i * 37) % 23) as f64 * 0.7, ((i * 53) % 19) as f64 * 0.6))
            .collect();
        let edges: Vec<(usize, usize)> = (0..59).map(|i| (i, (i * 7 + 3) % 60)).collect();
        assert_eq!(octilinear(&pos, &edges), octilinear(&pos, &edges));
        let Schematic { routes, .. } = octilinear(&pos, &edges);
        assert!(octilinear_pieces(&routes));
        assert!(crossings(&routes) < edges.len());
    }
}

#[cfg(test)]
mod timing {
    /// RealGrid's size: 4875 nodes, 7752 edges, laid out by force first. `cargo test --release -- --ignored`.
    #[test]
    #[ignore]
    fn realgrid_sized() {
        let n = 4875;
        let mut edges: Vec<(usize, usize)> = (1..n).map(|i| (i, (i * 7919) % i)).collect();
        edges.extend((0..2878).map(|i| ((i * 31) % n, (i * 31 + 17) % n)));
        let pos = crate::layout::force(n, &edges);
        let t = std::time::Instant::now();
        let super::Schematic { routes, .. } = super::octilinear(&pos, &edges);
        eprintln!("octilinear: {:?} for {} routes", t.elapsed(), routes.len());
    }
}

#[cfg(test)]
mod shared_count {
    /// How many unit pieces lines between different pairs share, on SmallGrid and RealGrid.
    #[test]
    #[ignore]
    fn shared_pieces() {
        for dir in ["SmallGrid/SmallGrid-Merged", "RealGrid/RealGrid-Merged"] {
            let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../CGMES-Test-Configurations/v3.0")
                .join(dir);
            let read = crate::testing::collect(&path);
            let datasets: Vec<cimmodel::CimDataset> = read
                .iter()
                .map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
                .collect();
            let m = crate::grid::Model::new(&datasets);
            let g = crate::grid::build(&m);
            let auto = g.auto.as_ref().unwrap();
            let mut seen: std::collections::HashMap<((i64, i64), (i64, i64)), (usize, usize)> =
                std::collections::HashMap::new();
            let (mut shared, mut total) = (0, 0);
            let mut high = 0;
            for (&k, r) in &auto.edges {
                let e = &g.edges[k];
                let pair = (e.source.min(e.target), e.source.max(e.target));
                let lattice: Vec<(i64, i64)> = r
                    .iter()
                    .map(|p| {
                        (
                            (p.0 / super::STEP).round() as i64,
                            (p.1 / super::STEP).round() as i64,
                        )
                    })
                    .collect();
                for (p, d) in super::steps(&lattice) {
                    let q = (p.0 + d.0, p.1 + d.1);
                    let key = if p <= q { (p, q) } else { (q, p) };
                    total += 1;
                    if let Some(o) = seen.get(&key) {
                        if *o != pair {
                            shared += 1;
                            if e.kv.is_some_and(|v| v >= 300.0) {
                                high += 1;
                            }
                        }
                    } else {
                        seen.insert(key, pair);
                    }
                }
            }
            eprintln!(
                "{dir}: {shared} of {total} unit pieces shared between different pairs, {high} on ≥300 kV lines"
            );
        }
    }
}