Skip to main content

cimview/
grid.rs

1//! A model set's grid at substation level, for a grid view:
2//! substations (and boundary points no substation holds) as nodes, the
3//! equipment joining two of them (lines, mostly) as edges, and each
4//! object's findings counted on the node or edge it belongs to. Where the
5//! set has a Diagram Layout or Geographical Location profile, each diagram
6//! and coordinate system is a [`Layout`]: node positions and line routes.
7//! What each substation holds is its [`Inside`], for the view's drill-down.
8//!
9//! Built from the set's files before validation consumes them; the files are
10//! read as one model (a field from whichever file writes it), without
11//! merging them.
12
13use std::collections::BTreeMap;
14
15use cimmodel::base::FastMap;
16use cimmodel::{CimDataset, Element};
17use cimvalidation::Violation;
18use serde_json::{Value, json};
19
20use crate::{Locations, mrid_of};
21
22/// Where an object belongs in the view.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Place {
25    Node(usize),
26    Edge(usize),
27}
28
29#[derive(Debug, Default)]
30pub struct Node {
31    pub id: String,
32    pub label: String,
33    /// `Substation`, or `ConnectivityNode`/`TopologicalNode` for a boundary point.
34    pub kind: &'static str,
35    pub region: Option<String>,
36    pub kv: Vec<f64>,
37    /// Equipment the node contains, by class.
38    pub equipment: BTreeMap<&'static str, usize>,
39    pub findings: Counts,
40}
41
42#[derive(Debug, Default)]
43pub struct Edge {
44    pub id: String,
45    pub label: String,
46    pub class: &'static str,
47    pub source: usize,
48    pub target: usize,
49    pub kv: Option<f64>,
50    pub findings: Counts,
51}
52
53/// Findings by severity.
54#[derive(Debug, Default, Clone, Copy)]
55pub struct Counts {
56    pub violation: usize,
57    pub warning: usize,
58    pub info: usize,
59}
60
61impl Counts {
62    pub(crate) fn add(&mut self, severity: &str) {
63        match severity {
64            "sh:Violation" => self.violation += 1,
65            "sh:Warning" => self.warning += 1,
66            _ => self.info += 1,
67        }
68    }
69
70    pub(crate) fn merge(&mut self, other: Counts) {
71        self.violation += other.violation;
72        self.warning += other.warning;
73        self.info += other.info;
74    }
75
76    pub(crate) fn total(&self) -> usize {
77        self.violation + self.warning + self.info
78    }
79
80    pub(crate) fn json(&self) -> Value {
81        json!({ "violation": self.violation, "warning": self.warning, "info": self.info })
82    }
83}
84
85#[derive(Debug, Default)]
86pub struct Grid {
87    pub nodes: Vec<Node>,
88    pub edges: Vec<Edge>,
89    /// Each placed object, by mRID.
90    placed: FastMap<String, Place>,
91    /// Findings on objects with no node or edge (headers, regions, …).
92    pub elsewhere: Counts,
93    /// Positions from the DL diagrams and GL coordinate systems.
94    pub layouts: Vec<Layout>,
95    /// Positions laid out here ([`crate::layout::force`]), for the view's
96    /// automatic layout: the view's own is quadratic, and this one is the
97    /// same each time.
98    pub auto: Option<Layout>,
99    /// What each substation holds, by node index.
100    pub inside: FastMap<usize, Inside>,
101    /// Each object on a substation's node that one of its items stands for:
102    /// (node, item).
103    within: FastMap<String, (usize, usize)>,
104}
105
106/// Inside one substation: its equipment and the connectivity nodes (else
107/// topological nodes) their terminals meet at, by voltage level; equipment
108/// reaching other nodes (lines, mostly) as an item with its far ends.
109#[derive(Debug, Default)]
110pub struct Inside {
111    pub groups: Vec<Group>,
112    pub items: Vec<Item>,
113    pub links: Vec<Link>,
114    /// Findings on the substation's node that no item stands for: the
115    /// substation, its voltage levels and bays, …
116    pub findings: Counts,
117    /// Positions from each DL diagram that draws its items, by item index.
118    pub layouts: Vec<Layout>,
119}
120
121/// A voltage level.
122#[derive(Debug, Default)]
123pub struct Group {
124    pub id: String,
125    pub label: String,
126    pub kv: Option<f64>,
127}
128
129#[derive(Debug, Default)]
130pub struct Item {
131    pub id: String,
132    pub label: String,
133    pub class: &'static str,
134    /// A connectivity or topological node, which the item's terminals meet at.
135    pub junction: bool,
136    /// Its voltage level, by index into `groups`.
137    pub group: Option<usize>,
138    /// A switch's state: `Switch.open`, else `Switch.normalOpen`.
139    pub open: Option<bool>,
140    /// `Equipment.inService`.
141    pub in_service: Option<bool>,
142    /// The other nodes the equipment reaches.
143    pub far: Vec<usize>,
144    pub findings: Counts,
145}
146
147/// A terminal: equipment item → junction item.
148#[derive(Debug)]
149pub struct Link {
150    pub id: String,
151    pub label: String,
152    pub item: usize,
153    pub junction: usize,
154    /// `ACDCTerminal.connected`.
155    pub connected: Option<bool>,
156}
157
158/// Positions of nodes and routes of edges, in one diagram (DL) or one
159/// coordinate system (GL), as the data writes them.
160#[derive(Debug, Default)]
161pub struct Layout {
162    pub id: String,
163    pub name: String,
164    /// `diagram` (x right, y as `flip_y` says) or `geographic` (x longitude,
165    /// y latitude, in degrees).
166    pub kind: &'static str,
167    /// A diagram whose y grows upwards (`OrientationKind.positive`).
168    pub flip_y: bool,
169    /// Node index → position.
170    pub nodes: BTreeMap<usize, (f64, f64)>,
171    /// Edge index → its route, from its source's end to its target's.
172    pub edges: BTreeMap<usize, Vec<(f64, f64)>>,
173    /// Node index → its width and height, where the layout sizes it (a
174    /// busbar, as long as the bays it joins).
175    pub sizes: BTreeMap<usize, (f64, f64)>,
176    /// Pixels per unit, where the positions are to be drawn as they are;
177    /// `None`, to be scaled to fit.
178    pub unit: Option<f64>,
179    /// Edge index → how many line spacings aside it runs from its route, to
180    /// the left of its way (negative: right); the views space them in pixels.
181    pub tracks: BTreeMap<usize, i32>,
182}
183
184/// Points gathered for a layout: a node's own, and those it takes from the
185/// ends of its lines when it has none of its own.
186#[derive(Default)]
187struct Gather {
188    own: FastMap<usize, Vec<(f64, f64)>>,
189    ends: FastMap<usize, Vec<(f64, f64)>>,
190    routes: BTreeMap<usize, Vec<(f64, f64)>>,
191}
192
193impl Gather {
194    /// The points of one located object: an edge's route (whose ends also
195    /// locate its nodes), else points on the node it is in.
196    fn add(&mut self, grid: &Grid, object: &str, points: Vec<(f64, f64)>) {
197        if points.is_empty() {
198            return;
199        }
200        match grid.placed.get(object) {
201            Some(&Place::Edge(e)) if grid.edges[e].id == object => {
202                let edge = &grid.edges[e];
203                self.ends.entry(edge.source).or_default().push(points[0]);
204                self.ends.entry(edge.target).or_default().push(points[points.len() - 1]);
205                self.routes.insert(e, points);
206            }
207            Some(&Place::Node(n)) => self.own.entry(n).or_default().extend(points),
208            _ => {}
209        }
210    }
211
212    fn layout(self, id: String, name: String, kind: &'static str, flip_y: bool) -> Option<Layout> {
213        let mean = |ps: &[(f64, f64)]| {
214            let n = ps.len() as f64;
215            (ps.iter().map(|p| p.0).sum::<f64>() / n, ps.iter().map(|p| p.1).sum::<f64>() / n)
216        };
217        let mut nodes: BTreeMap<usize, (f64, f64)> = self.ends.iter().map(|(&n, ps)| (n, mean(ps))).collect();
218        nodes.extend(self.own.iter().map(|(&n, ps)| (n, mean(ps))));
219        (!nodes.is_empty()).then_some(Layout { id, name, kind, flip_y, nodes, edges: self.routes, ..Default::default() })
220    }
221}
222
223/// Each object's points by class, `(owner, sequence, x, y)`, sorted, and the
224/// owner of each point list: a DiagramObject's or a Location's.
225fn points<'a>(m: &Model<'a>, class: &str, owner_key: &str, x_key: &str, y_key: &str, seq_key: &str) -> FastMap<&'a str, Vec<(f64, f64)>> {
226    let mut by_owner: FastMap<&str, Vec<(i64, &str, f64, f64)>> = FastMap::default();
227    for (&id, els) in &m.objects {
228        if els[0].type_name() != class {
229            continue;
230        }
231        if let (Some(owner), Some(x), Some(y)) = (m.reference(id, owner_key), m.number(id, x_key), m.number(id, y_key)) {
232            let seq = m.number(id, seq_key).map_or(i64::MAX, |n| n as i64);
233            by_owner.entry(owner).or_default().push((seq, id, x, y));
234        }
235    }
236    by_owner
237        .into_iter()
238        .map(|(owner, mut ps)| {
239            ps.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
240            (owner, ps.into_iter().map(|(_, _, x, y)| (x, y)).collect())
241        })
242        .collect()
243}
244
245/// Whether a diagram's y grows upwards, and its layout's name.
246fn diagram_flip(m: &Model, diagram: &str) -> (bool, String) {
247    let flip_y = m.objects.get(diagram).and_then(|els| els.iter().find_map(|el| el.get_ref("Diagram.orientation"))).is_some_and(|o| o.ends_with("positive"));
248    (flip_y, format!("Diagram: {}", m.name(diagram)))
249}
250
251/// One layout per DL diagram and per GL coordinate system; and one per DL
252/// diagram for each substation whose items it draws, by node index.
253fn layouts(m: &Model, grid: &Grid) -> (Vec<Layout>, Vec<(usize, Layout)>) {
254    let mut out = Vec::new();
255
256    // DL: each DiagramObject's points, on the object it shows.
257    let diagram_points = points(m, "DiagramObjectPoint", "DiagramObjectPoint.DiagramObject",
258        "DiagramObjectPoint.xPosition", "DiagramObjectPoint.yPosition", "DiagramObjectPoint.sequenceNumber");
259    let mut diagrams: BTreeMap<&str, Gather> = BTreeMap::new();
260    // (diagram, node) → item → its points.
261    type Items = BTreeMap<usize, Vec<(f64, f64)>>;
262    let mut insides: BTreeMap<(&str, usize), Items> = BTreeMap::new();
263    // (diagram, node) → link → its route: a terminal drawn.
264    let mut wires: BTreeMap<(&str, usize), Items> = BTreeMap::new();
265    let mut objects: Vec<&&str> = diagram_points.keys().collect();
266    objects.sort();
267    for &object in objects {
268        let (Some(diagram), Some(shown)) = (m.reference(object, "DiagramObject.Diagram"), m.reference(object, "DiagramObject.IdentifiedObject")) else { continue };
269        diagrams.entry(diagram).or_default().add(grid, shown, diagram_points[object].clone());
270        // An item, in each substation it is drawn in (a line in both of its ends').
271        let ns: Vec<usize> = match grid.placed.get(shown) {
272            Some(&Place::Edge(e)) => vec![grid.edges[e].source, grid.edges[e].target],
273            Some(&Place::Node(n)) => vec![n],
274            None => vec![],
275        };
276        for n in ns {
277            let Some(inside) = grid.inside.get(&n) else { continue };
278            if let Some(i) = inside.items.iter().position(|it| it.id == shown) {
279                insides.entry((diagram, n)).or_default().entry(i).or_default().extend(&diagram_points[object]);
280            } else if let Some(k) = inside.links.iter().position(|l| l.id == shown) {
281                wires.entry((diagram, n)).or_default().insert(k, diagram_points[object].clone());
282            }
283        }
284    }
285    for (diagram, gather) in diagrams {
286        let (flip_y, name) = diagram_flip(m, diagram);
287        out.extend(gather.layout(format!("dl:{diagram}"), name, "diagram", flip_y));
288    }
289    let mut inside = Vec::new();
290    for ((diagram, n), placed) in insides {
291        if placed.len() < 2 {
292            continue;
293        }
294        let items = &grid.inside[&n].items;
295        let mean = |ps: &[(f64, f64)]| {
296            let k = ps.len() as f64;
297            (ps.iter().map(|p| p.0).sum::<f64>() / k, ps.iter().map(|p| p.1).sum::<f64>() / k)
298        };
299        let own: Vec<(f64, f64)> = placed.iter().filter(|(i, _)| items[**i].far.is_empty()).map(|(_, ps)| mean(ps)).collect();
300        let centre = (!own.is_empty()).then(|| mean(&own));
301        let span = own.iter().flat_map(|a| own.iter().map(move |b| (a.0 - b.0).abs().max((a.1 - b.1).abs()))).fold(0.0, f64::max);
302        let nodes = placed
303            .iter()
304            .map(|(&i, ps)| {
305                // A line drawn through the substation is at its end here, a
306                // little out along the line, off the node it ends at.
307                let at = match centre {
308                    Some(c) if !items[i].far.is_empty() && ps.len() > 1 => {
309                        let d = |p: (f64, f64)| (p.0 - c.0).hypot(p.1 - c.1);
310                        let (end, next) = if d(ps[0]) <= d(ps[ps.len() - 1]) { (ps[0], ps[1]) } else { (ps[ps.len() - 1], ps[ps.len() - 2]) };
311                        let k = (next.0 - end.0).hypot(next.1 - end.1);
312                        if k > 0.0 && span > 0.0 {
313                            let step = (0.06 * span).min(k / 2.0);
314                            (end.0 + (next.0 - end.0) / k * step, end.1 + (next.1 - end.1) / k * step)
315                        } else {
316                            end
317                        }
318                    }
319                    _ => mean(ps),
320                };
321                (i, at)
322            })
323            .collect();
324        let (flip_y, name) = diagram_flip(m, diagram);
325        let mut layout = Layout { id: format!("dl:{diagram}"), name, kind: "diagram", flip_y, nodes, ..Default::default() };
326        layout.edges = wires.remove(&(diagram, n)).unwrap_or_default();
327        busbars(&grid.inside[&n], &placed, &mut layout);
328        inside.push((n, layout));
329    }
330
331    // GL: each Location's points, on the resources it locates, by coordinate system.
332    let location_points = points(m, "PositionPoint", "PositionPoint.Location",
333        "PositionPoint.xPosition", "PositionPoint.yPosition", "PositionPoint.sequenceNumber");
334    let mut systems: BTreeMap<String, Gather> = BTreeMap::new();
335    let mut locations: Vec<&&str> = location_points.keys().collect();
336    locations.sort();
337    for &location in locations {
338        let crs = m
339            .reference(location, "Location.CoordinateSystem")
340            .and_then(|c| m.text(c, "CoordinateSystem.crsUrn"))
341            .unwrap_or("urn:ogc:def:crs:EPSG::4326")
342            .to_string();
343        let gather = systems.entry(crs).or_default();
344        let located = m.objects.get(location).map(|els| els.iter().flat_map(|el| el.get_refs("Location.PowerSystemResources")).cloned().collect::<Vec<_>>()).unwrap_or_default();
345        for psr in located {
346            gather.add(grid, mrid_of(&psr), location_points[location].clone());
347        }
348    }
349    for (crs, gather) in systems {
350        let short = crs.rsplit(':').next().unwrap_or(&crs).to_string();
351        out.extend(gather.layout(format!("gl:{crs}"), format!("Geographic (EPSG:{short})"), "geographic", false));
352    }
353    (out, inside)
354}
355
356/// A substation's diagram drawn as its single-line diagram is: to the
357/// scale that sets its items a row apart (half its wires, else its links
358/// from item to junction, are shorter); a bus drawn as a line a busbar of
359/// that length, a busbar section not drawn itself that bar, its junction at
360/// the bar's end; any other junction drawn as a line, a line as thin as a
361/// wire (a diagram may draw every junction as one).
362fn busbars(inside: &Inside, placed: &BTreeMap<usize, Vec<(f64, f64)>>, layout: &mut Layout) {
363    // The wires drawn, else from item to junction.
364    let wires: Vec<f64> = layout.edges.values().map(|ps| ps.windows(2).map(|w| (w[0].0 - w[1].0).hypot(w[0].1 - w[1].1)).sum()).collect();
365    let ends = || {
366        inside
367            .links
368            .iter()
369            .filter_map(|l| Some((layout.nodes.get(&l.item)?, layout.nodes.get(&l.junction)?)))
370            .map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1))
371            .collect::<Vec<f64>>()
372    };
373    let mut lengths: Vec<f64> = if wires.iter().any(|&d| d > 1e-9) { wires } else { ends() };
374    lengths.retain(|&d| d > 1e-9);
375    if lengths.is_empty() {
376        return;
377    }
378    lengths.sort_by(f64::total_cmp);
379    let typical = lengths[lengths.len() / 2];
380    let unit = crate::single_line::ROW / typical;
381    layout.unit = Some(unit);
382    let bus = crate::single_line::buses(inside);
383    for (&j, ps) in placed {
384        if !inside.items[j].junction || ps.len() < 2 {
385            continue;
386        }
387        let (x0, x1) = ps.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));
388        let (y0, y1) = ps.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));
389        let (w, h) = (x1 - x0, y1 - y0);
390        if w.max(h) < 1e-9 || !bus[j] && w.max(h) < typical {
391            continue;
392        }
393        let thick = if bus[j] { crate::single_line::BAR } else { crate::single_line::WIRE } / unit;
394        let (size, end) = if w >= h { ((w, thick), (x1, (y0 + y1) / 2.0)) } else { ((thick, h), ((x0 + x1) / 2.0, y1)) };
395        let centre = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
396        let sections: Vec<usize> = inside
397            .links
398            .iter()
399            .filter(|l| bus[j] && l.junction == j && inside.items[l.item].class == "BusbarSection" && !placed.contains_key(&l.item))
400            .map(|l| l.item)
401            .collect();
402        if sections.is_empty() {
403            layout.nodes.insert(j, centre);
404            layout.sizes.insert(j, size);
405        } else {
406            for s in sections {
407                layout.nodes.insert(s, centre);
408                layout.sizes.insert(s, size);
409            }
410            layout.nodes.insert(j, end);
411        }
412    }
413}
414
415/// The set's files read as one model: each object's elements, the defining
416/// one first.
417pub struct Model<'a> {
418    pub(crate) objects: FastMap<&'a str, Vec<&'a Element>>,
419    /// ConductingEquipment → its terminals, by sequence number.
420    pub(crate) terminals: FastMap<&'a str, Vec<&'a str>>,
421}
422
423impl<'a> Model<'a> {
424    pub fn new(datasets: &'a [CimDataset]) -> Self {
425        let mut objects: FastMap<&str, Vec<&Element>> = FastMap::default();
426        for ds in datasets {
427            for (mrid, el) in &ds.entries {
428                let els = objects.entry(mrid.as_str()).or_default();
429                if el.defined() { els.insert(0, el) } else { els.push(el) }
430            }
431        }
432        let mut model = Self { objects, terminals: FastMap::default() };
433        let mut terminals: FastMap<&str, Vec<(i64, &str)>> = FastMap::default();
434        for (&mrid, els) in &model.objects {
435            if els[0].type_name() != "Terminal" {
436                continue;
437            }
438            if let Some(ce) = model.reference(mrid, "Terminal.ConductingEquipment") {
439                let seq = model.number(mrid, "ACDCTerminal.sequenceNumber").map_or(i64::MAX, |n| n as i64);
440                terminals.entry(ce).or_default().push((seq, mrid));
441            }
442        }
443        model.terminals = terminals
444            .into_iter()
445            .map(|(ce, mut ts)| {
446                ts.sort();
447                (ce, ts.into_iter().map(|(_, t)| t).collect())
448            })
449            .collect();
450        model
451    }
452
453    pub(crate) fn class(&self, mrid: &str) -> Option<&'static str> {
454        self.objects.get(mrid).map(|els| els[0].type_name())
455    }
456
457    pub(crate) fn text(&self, mrid: &str, key: &str) -> Option<&'a str> {
458        self.objects.get(mrid)?.iter().find_map(|el| el.get_str(key))
459    }
460
461    pub(crate) fn number(&self, mrid: &str, key: &str) -> Option<f64> {
462        self.text(mrid, key)?.trim().parse().ok()
463    }
464
465    fn flag(&self, mrid: &str, key: &str) -> Option<bool> {
466        self.text(mrid, key).map(|t| t.trim() == "true")
467    }
468
469    /// The voltage level a container (VoltageLevel, Bay) is, or is in.
470    pub(crate) fn voltage_level(&self, container: &'a str) -> Option<&'a str> {
471        match self.class(container)? {
472            "VoltageLevel" => Some(container),
473            "Bay" => self.reference(container, "Bay.VoltageLevel"),
474            _ => None,
475        }
476    }
477
478    /// A terminal's connectivity node, else its topological node.
479    fn terminal_node(&self, terminal: &str) -> Option<&'a str> {
480        self.reference(terminal, "Terminal.ConnectivityNode").or_else(|| self.reference(terminal, "Terminal.TopologicalNode"))
481    }
482
483    /// The mRID a field refers to, whether or not the set has that object.
484    pub(crate) fn target(&self, mrid: &str, key: &str) -> Option<&'a str> {
485        self.objects.get(mrid)?.iter().find_map(|el| el.get_ref(key)).map(mrid_of)
486    }
487
488    /// The object a field refers to, if it is in the set.
489    pub(crate) fn reference(&self, mrid: &str, key: &str) -> Option<&'a str> {
490        let target = self.objects.get(mrid)?.iter().find_map(|el| el.get_ref(key))?;
491        self.objects.get_key_value(mrid_of(target)).map(|(k, _)| *k)
492    }
493
494    fn name(&self, mrid: &str) -> String {
495        self.text(mrid, "IdentifiedObject.name").filter(|n| !n.is_empty()).unwrap_or(mrid).to_string()
496    }
497
498    /// The substation a container (VoltageLevel, Bay, Substation) is in.
499    fn substation(&self, container: &'a str) -> Option<&'a str> {
500        let mut at = container;
501        for _ in 0..4 {
502            at = match self.class(at)? {
503                "Substation" => return Some(at),
504                "VoltageLevel" => self.reference(at, "VoltageLevel.Substation")?,
505                "Bay" => self.reference(at, "Bay.VoltageLevel")?,
506                _ => return None,
507            };
508        }
509        None
510    }
511
512    /// The node of a terminal: its connectivity (else topological) node's
513    /// substation, else that node itself, a boundary point.
514    fn terminal_end(&self, terminal: &'a str) -> Option<(&'a str, bool)> {
515        let node = self.terminal_node(terminal)?;
516        match self.node_container(node).and_then(|c| self.substation(c)) {
517            Some(sub) => Some((sub, false)),
518            None => Some((node, true)),
519        }
520    }
521
522    pub(crate) fn node_container(&self, node: &str) -> Option<&'a str> {
523        self.reference(node, "ConnectivityNode.ConnectivityNodeContainer")
524            .or_else(|| self.reference(node, "TopologicalNode.ConnectivityNodeContainer"))
525    }
526}
527
528/// The grid of a model set's files.
529pub fn build(m: &Model<'_>) -> Grid {
530    let mut grid = Grid::default();
531    let mut node_of: FastMap<&str, usize> = FastMap::default();
532
533    let mut subs: Vec<&str> = m.objects.keys().copied().filter(|k| m.class(k) == Some("Substation")).collect();
534    subs.sort_by_key(|s| (m.name(s), *s));
535    for sub in subs {
536        node_of.insert(sub, grid.nodes.len());
537        let region = m.reference(sub, "Substation.Region").map(|r| m.name(r));
538        grid.nodes.push(Node { id: sub.into(), label: m.name(sub), kind: "Substation", region, ..Default::default() });
539    }
540
541    // Equipment whose terminals reach two different nodes is an edge. Inside
542    // a substation, each terminal ending there links its equipment to its node.
543    let mut items: FastMap<(usize, &str), usize> = FastMap::default();
544    let mut groups: FastMap<(usize, &str), usize> = FastMap::default();
545    let mut equipment: Vec<&str> = m.terminals.keys().copied().collect();
546    equipment.sort();
547    for ce in equipment {
548        let terminals = &m.terminals[ce];
549        let ends: Vec<Option<(&str, bool)>> = terminals.iter().map(|t| m.terminal_end(t)).collect();
550        let mut distinct: Vec<(&str, bool)> = Vec::new();
551        for &end in ends.iter().flatten() {
552            if !distinct.iter().any(|e| e.0 == end.0) {
553                distinct.push(end);
554            }
555        }
556        if distinct.len() >= 2 {
557            let source = node_for(m, &mut grid, &mut node_of, distinct[0]);
558            for &end in &distinct[1..] {
559                let target = node_for(m, &mut grid, &mut node_of, end);
560                let kv = m.reference(ce, "ConductingEquipment.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
561                let id = if distinct.len() == 2 { ce.to_string() } else { format!("{ce}#{}", grid.edges.len()) };
562                grid.placed.insert(ce.to_string(), Place::Edge(grid.edges.len()));
563                grid.edges.push(Edge { id, label: m.name(ce), class: m.class(ce).unwrap_or(""), source, target, kv, findings: Counts::default() });
564            }
565        }
566        let reached: Vec<usize> = distinct.iter().filter_map(|e| node_of.get(e.0).copied()).collect();
567        for (t, end) in terminals.iter().zip(&ends) {
568            let (Some(&n), Some(node)) = (end.and_then(|e| node_of.get(e.0)), m.terminal_node(t)) else { continue };
569            if grid.nodes[n].kind != "Substation" {
570                continue;
571            }
572            let far: Vec<usize> = reached.iter().copied().filter(|&r| r != n).collect();
573            let item = item_for(m, &mut grid, &mut items, &mut groups, n, ce, false, far);
574            let junction = item_for(m, &mut grid, &mut items, &mut groups, n, node, true, vec![]);
575            grid.inside.entry(n).or_default().links.push(Link { id: t.to_string(), label: m.name(t), item, junction, connected: m.flag(t, "ACDCTerminal.connected") });
576        }
577    }
578
579    // Every other object goes where its container, equipment or node is.
580    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
581    ids.sort();
582    let mut within = FastMap::default();
583    for id in ids {
584        if let Some(Place::Node(n)) = place(m, &node_of, &items, &mut grid.placed, &mut within, id, 0)
585            && let Some(container) = m.reference(id, "Equipment.EquipmentContainer")
586            && m.substation(container).is_some()
587        {
588            *grid.nodes[n].equipment.entry(m.class(id).unwrap_or("")).or_default() += 1;
589        }
590    }
591    grid.within = within;
592    for (&vl, els) in &m.objects {
593        if els[0].type_name() != "VoltageLevel" {
594            continue;
595        }
596        if let Some(Place::Node(n)) = grid.placed.get(vl)
597            && let Some(kv) = m.reference(vl, "VoltageLevel.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"))
598        {
599            grid.nodes[*n].kv.push(kv);
600        }
601    }
602    for node in &mut grid.nodes {
603        node.kv.sort_by(|a, b| b.total_cmp(a));
604        node.kv.dedup();
605    }
606
607    let (layouts, inside) = layouts(m, &grid);
608    grid.layouts = layouts;
609    if !grid.nodes.is_empty() {
610        let edges: Vec<(usize, usize)> = grid.edges.iter().map(|e| (e.source, e.target)).collect();
611        let pos = crate::layout::force(grid.nodes.len(), &edges);
612        // Drawn as a schematic: lines along axes and diagonals only, side by side where they share a stretch.
613        let s = crate::schematic::octilinear(&pos, &edges);
614        grid.auto = Some(Layout {
615            id: "auto".into(), name: "Automatic".into(), kind: "diagram",
616            nodes: s.nodes.into_iter().enumerate().collect(),
617            edges: s.routes.into_iter().enumerate().filter(|(_, r)| !r.is_empty()).collect(),
618            tracks: s.tracks.into_iter().enumerate().filter(|(_, t)| *t != 0).collect(),
619            ..Default::default()
620        });
621    }
622    for (n, l) in inside {
623        grid.inside.get_mut(&n).unwrap().layouts.push(l);
624    }
625    grid
626}
627
628/// The item for `id` inside node `n`'s substation, added on first use, with
629/// its voltage level.
630#[allow(clippy::too_many_arguments)]
631fn item_for<'a>(
632    m: &Model<'a>, grid: &mut Grid, items: &mut FastMap<(usize, &'a str), usize>, groups: &mut FastMap<(usize, &'a str), usize>,
633    n: usize, id: &'a str, junction: bool, far: Vec<usize>,
634) -> usize {
635    if let Some(&i) = items.get(&(n, id)) {
636        return i;
637    }
638    let container = if junction { m.node_container(id) } else { m.reference(id, "Equipment.EquipmentContainer") };
639    let vl = container.and_then(|c| m.voltage_level(c)).filter(|vl| m.substation(vl) == Some(grid.nodes[n].id.as_str()));
640    let inside = grid.inside.entry(n).or_default();
641    let group = vl.map(|vl| {
642        *groups.entry((n, vl)).or_insert_with(|| {
643            let kv = m.reference(vl, "VoltageLevel.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
644            inside.groups.push(Group { id: vl.into(), label: m.name(vl), kv });
645            inside.groups.len() - 1
646        })
647    });
648    let class = m.class(id).unwrap_or("");
649    let switch = !junction && (m.text(id, "Switch.open").is_some() || m.text(id, "Switch.normalOpen").is_some());
650    inside.items.push(Item {
651        id: id.into(),
652        label: m.name(id),
653        class,
654        junction,
655        group,
656        open: if switch { m.flag(id, "Switch.open").or_else(|| m.flag(id, "Switch.normalOpen")) } else { None },
657        in_service: if junction { None } else { m.flag(id, "Equipment.inService") },
658        far,
659        findings: Counts::default(),
660    });
661    items.insert((n, id), inside.items.len() - 1);
662    inside.items.len() - 1
663}
664
665/// The node of an edge's end, added on first use: a substation, or a
666/// boundary point.
667fn node_for<'a>(m: &Model<'a>, grid: &mut Grid, node_of: &mut FastMap<&'a str, usize>, (id, boundary): (&'a str, bool)) -> usize {
668    *node_of.entry(id).or_insert_with(|| {
669        grid.nodes.push(Node {
670            id: id.into(),
671            // An IGM often only refers to a boundary point the boundary set names.
672            label: m.text(id, "IdentifiedObject.name").unwrap_or_default().to_string(),
673            kind: if boundary { m.class(id).unwrap_or("ConnectivityNode") } else { "Substation" },
674            ..Default::default()
675        });
676        grid.nodes.len() - 1
677    })
678}
679
680/// Where `id` belongs, memoised in `placed`: a container's substation, a
681/// terminal's equipment, a node's substation, else the first referenced
682/// object that has a place. On a substation's node, also the item `id`
683/// stands for there, memoised in `within`: an item itself, else that of the
684/// object it takes its place from.
685#[allow(clippy::too_many_arguments)]
686fn place<'a>(
687    m: &Model<'a>, node_of: &FastMap<&str, usize>, items: &FastMap<(usize, &'a str), usize>, placed: &mut FastMap<String, Place>,
688    within: &mut FastMap<String, (usize, usize)>, id: &'a str, depth: u8,
689) -> Option<Place> {
690    if let Some(p) = placed.get(id) {
691        return Some(*p);
692    }
693    if depth > 3 {
694        return None;
695    }
696    let class = m.class(id)?;
697    let mut via = None;
698    let direct = match class {
699        "Substation" | "VoltageLevel" | "Bay" => m.substation(id).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n)),
700        "ConnectivityNode" | "TopologicalNode" => match node_of.get(id) {
701            Some(&n) => Some(Place::Node(n)),
702            None => {
703                let key = if class == "ConnectivityNode" { "ConnectivityNode.ConnectivityNodeContainer" } else { "TopologicalNode.ConnectivityNodeContainer" };
704                m.reference(id, key).and_then(|c| m.substation(c)).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n))
705            }
706        },
707        "Terminal" => m.reference(id, "Terminal.ConductingEquipment").and_then(|ce| {
708            via = Some(ce);
709            place(m, node_of, items, placed, within, ce, depth + 1)
710        }),
711        _ => m.reference(id, "Equipment.EquipmentContainer").and_then(|c| m.substation(c)).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n)),
712    };
713    let found = match direct {
714        Some(p) => p,
715        None => {
716            // Limits, tap changers, regulating controls, state variables, …:
717            // where what they refer to is.
718            let els = m.objects.get(id)?;
719            let mut keys: Vec<&str> = els.iter().flat_map(|el| el.fields().keys().copied()).collect();
720            keys.sort();
721            keys.dedup();
722            let (r, p) = keys.into_iter().filter(|k| !k.ends_with(".BaseVoltage") && !k.ends_with(".Region")).find_map(|k| {
723                let r = m.reference(id, k).filter(|r| *r != id)?;
724                place(m, node_of, items, placed, within, r, depth + 1).map(|p| (r, p))
725            })?;
726            via = Some(r);
727            p
728        }
729    };
730    placed.insert(id.to_string(), found);
731    if let Place::Node(n) = found
732        && let Some(w) = items.get(&(n, id)).map(|&i| (n, i)).or_else(|| via.and_then(|r| within.get(r).copied()).filter(|w| w.0 == n))
733    {
734        within.insert(id.to_string(), w);
735    }
736    Some(found)
737}
738
739impl Grid {
740    /// Count each finding on its object's node or edge.
741    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
742        for (_, v) in violations {
743            match self.placed.get(v.object_id.as_str()) {
744                Some(Place::Node(n)) => {
745                    self.nodes[*n].findings.add(&v.severity);
746                    if let Some(inside) = self.inside.get_mut(n) {
747                        match self.within.get(v.object_id.as_str()) {
748                            Some(&(_, i)) => inside.items[i].findings.add(&v.severity),
749                            None => inside.findings.add(&v.severity),
750                        }
751                    }
752                }
753                Some(Place::Edge(e)) => self.edges[*e].findings.add(&v.severity),
754                None => self.elsewhere.add(&v.severity),
755            }
756        }
757    }
758
759    /// Where the view shows object `id`: `select`, the node or edge it is
760    /// on, else the item it stands for inside `enter`, its substation; and
761    /// `inside`, a substation's own id. `None` if it is on neither.
762    pub fn reveal(&self, id: &str) -> Option<Value> {
763        match *self.placed.get(id)? {
764            Place::Edge(e) => Some(json!({ "select": format!("e:{}", self.edges[e].id) })),
765            Place::Node(n) => {
766                let node = &self.nodes[n];
767                if node.kind != "Substation" || node.id == id {
768                    let inside = (node.kind == "Substation").then_some(&node.id);
769                    return Some(json!({ "select": node.id, "inside": inside }));
770                }
771                let item = self.within.get(id).map(|&(_, i)| &self.inside[&n].items[i].id);
772                Some(json!({ "enter": node.id, "select": item }))
773            }
774        }
775    }
776
777    /// The view's data: nodes and edges, each with where it is written.
778    pub fn json(&self, set: &impl Locations) -> Value {
779        let location = |id: &str| set.location(id.split('#').next().unwrap_or(id));
780        let nodes: Vec<Value> = self
781            .nodes
782            .iter()
783            .map(|n| {
784                json!({
785                    "id": n.id, "label": n.label, "kind": n.kind, "region": n.region, "kV": n.kv,
786                    "equipment": n.equipment, "findings": n.findings.json(), "location": location(&n.id),
787                })
788            })
789            .collect();
790        let edges: Vec<Value> = self
791            .edges
792            .iter()
793            .map(|e| {
794                json!({
795                    "id": e.id, "label": e.label, "class": e.class, "source": self.nodes[e.source].id,
796                    "target": self.nodes[e.target].id, "kV": e.kv, "findings": e.findings.json(), "location": location(&e.id),
797                })
798            })
799            .collect();
800        let layout = |l: &Layout| {
801                let nodes: serde_json::Map<String, Value> = l.nodes.iter().map(|(&n, &(x, y))| (self.nodes[n].id.clone(), json!([x, y]))).collect();
802                let edges: serde_json::Map<String, Value> = l
803                    .edges
804                    .iter()
805                    .map(|(&e, ps)| (self.edges[e].id.clone(), json!(ps.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>())))
806                    .collect();
807                let mut out = json!({ "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit, "nodes": nodes, "edges": edges });
808                if !l.tracks.is_empty() {
809                    out["tracks"] = l.tracks.iter().map(|(&e, &t)| (self.edges[e].id.clone(), json!(t))).collect::<serde_json::Map<_, _>>().into();
810                }
811                out
812        };
813        json!({
814            "files": set.files(),
815            "nodes": nodes, "edges": edges, "elsewhere": self.elsewhere.json(),
816            "layouts": self.layouts.iter().map(layout).collect::<Vec<_>>(), "auto": self.auto.as_ref().map(layout),
817        })
818    }
819
820    /// What the substation `id` holds; `None` if no substation of the set
821    /// has that mRID.
822    pub fn inside_of(&self, id: &str) -> Option<&Inside> {
823        let n = self.nodes.iter().position(|x| x.id == id && x.kind == "Substation")?;
824        self.inside.get(&n)
825    }
826
827    /// The substation `id`'s layout `layout` (the view's JSON) after its
828    /// items moved: busbars across what hangs from them, routes anew.
829    pub fn reroute_json(&self, id: &str, layout: &Value) -> Option<Value> {
830        let inside = self.inside_of(id)?;
831        let l = inside.layout_from_json(layout);
832        let mut moved = crate::single_line::reroute(inside, &l.nodes, &l.sizes);
833        (moved.id, moved.name) = (l.id, l.name);
834        Some(inside.layout_json(&moved))
835    }
836
837    /// What the substation `id` holds, for the view's drill-down; `None` if
838    /// no substation of the set has that mRID.
839    pub fn inside_json(&self, set: &impl Locations, id: &str) -> Option<Value> {
840        let n = self.nodes.iter().position(|x| x.id == id && x.kind == "Substation")?;
841        let node = &self.nodes[n];
842        let empty = Inside::default();
843        let inside = self.inside.get(&n).unwrap_or(&empty);
844        let location = |id: &str| set.location(id);
845        let groups: Vec<Value> = inside.groups.iter().map(|g| json!({ "id": g.id, "label": g.label, "kV": g.kv })).collect();
846        let items: Vec<Value> = inside
847            .items
848            .iter()
849            .map(|it| {
850                let far: Vec<Value> = it.far.iter().map(|&f| json!({ "id": self.nodes[f].id, "label": self.nodes[f].label, "kind": self.nodes[f].kind })).collect();
851                json!({
852                    "id": it.id, "label": it.label, "class": it.class, "junction": it.junction,
853                    "group": it.group.map(|g| &inside.groups[g].id), "open": it.open, "inService": it.in_service,
854                    "far": far, "findings": it.findings.json(), "location": location(&it.id),
855                })
856            })
857            .collect();
858        let links: Vec<Value> = inside
859            .links
860            .iter()
861            .map(|l| json!({ "id": l.id, "source": inside.items[l.item].id, "target": inside.items[l.junction].id, "connected": l.connected }))
862            .collect();
863        let layouts: Vec<Value> = inside
864            .layouts
865            .iter()
866            .map(|l| inside.layout_json(l))
867            .collect();
868        // Laid out when asked for: a few substations are opened, of thousands.
869        let auto = inside.layout_json(&crate::single_line::single_line(inside));
870        Some(json!({
871            "id": node.id, "label": node.label, "region": node.region, "kV": node.kv, "findings": inside.findings.json(),
872            "location": location(&node.id), "groups": groups, "items": items, "links": links, "layouts": layouts, "auto": auto,
873        }))
874    }
875}
876
877impl Inside {
878    /// A layout of its items, as the view takes it: positions and sizes by
879    /// item, routes by terminal.
880    pub fn layout_json(&self, l: &Layout) -> Value {
881        let id_of = |i: &usize| self.items[*i].id.clone();
882        json!({
883            "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit,
884            "nodes": l.nodes.iter().map(|(i, &(x, y))| (id_of(i), json!([x, y]))).collect::<serde_json::Map<_, _>>(),
885            "edges": l.edges.iter().map(|(&k, ps)| (self.links[k].id.clone(), json!(ps.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>()))).collect::<serde_json::Map<_, _>>(),
886            "sizes": l.sizes.iter().map(|(i, &(w, h))| (id_of(i), json!([w, h]))).collect::<serde_json::Map<_, _>>(),
887        })
888    }
889
890    /// A layout of its items from the view's JSON (as [`Inside::layout_json`]
891    /// writes it); what names no item or terminal of it is left out.
892    pub fn layout_from_json(&self, v: &Value) -> Layout {
893        let item = |id: &str| self.items.iter().position(|it| it.id == id);
894        let pair = |p: &Value| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?));
895        let by_item = |key: &str| -> BTreeMap<usize, (f64, f64)> {
896            v[key].as_object().into_iter().flatten().filter_map(|(id, p)| Some((item(id)?, pair(p)?))).collect()
897        };
898        let edges = v["edges"]
899            .as_object()
900            .into_iter()
901            .flatten()
902            .filter_map(|(id, ps)| {
903                let k = self.links.iter().position(|l| &l.id == id)?;
904                Some((k, ps.as_array()?.iter().filter_map(pair).collect()))
905            })
906            .collect();
907        Layout {
908            id: v["id"].as_str().unwrap_or("auto").into(),
909            name: v["name"].as_str().unwrap_or_default().into(),
910            kind: "diagram",
911            flip_y: false,
912            nodes: by_item("nodes"),
913            edges,
914            sizes: by_item("sizes"),
915            unit: v["unit"].as_f64(),
916            tracks: BTreeMap::new(),
917        }
918    }
919}
920
921#[cfg(test)]
922mod tests {
923    use std::path::Path;
924
925    use crate::testing::{collect, validate};
926
927    /// MicroGrid: Belgium's two substations and the Netherlands' one, joined
928    /// through the boundary's five border nodes; each line an edge.
929    #[test]
930    fn micro_grid() {
931        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
932            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
933        let files = collect(&dir);
934        assert_eq!(files.len(), 12, "missing test data — run `git submodule update --init`");
935        let set = validate(&files);
936        let g = &set.grid;
937        let mut subs: Vec<&str> = g.nodes.iter().filter(|n| n.kind == "Substation").map(|n| n.label.as_str()).collect();
938        subs.sort();
939        assert_eq!(subs, ["Anvers", "PP_Amsterdam", "PP_Brussels"]);
940        let mut borders: Vec<&str> = g.nodes.iter().filter(|n| n.kind == "ConnectivityNode").map(|n| n.label.as_str()).collect();
941        borders.sort();
942        assert_eq!(borders, ["Border_AL11", "Border_GY11", "Border_MA11", "Border_ST23", "Border_ST24"]);
943        assert_eq!(g.edges.len(), 12);
944        assert!(g.edges.iter().all(|e| e.class == "ACLineSegment"));
945
946        let node = |label: &str| g.nodes.iter().find(|n| n.label == label).unwrap();
947        let between = |a: &str, b: &str| {
948            g.edges.iter().filter(|e| {
949                let ends = [g.nodes[e.source].label.as_str(), g.nodes[e.target].label.as_str()];
950                ends.contains(&a) && ends.contains(&b)
951            }).count()
952        };
953        assert_eq!(between("PP_Brussels", "Anvers"), 2);
954        assert_eq!(between("PP_Amsterdam", "Border_AL11"), 1);
955        assert_eq!(between("PP_Brussels", "Border_AL11"), 1);
956        let brussels = node("PP_Brussels");
957        assert_eq!(brussels.kv, [380.0, 225.0, 110.0, 21.0, 10.5]);
958        assert_eq!(brussels.equipment["SynchronousMachine"], 2);
959        assert_eq!(brussels.region.as_deref(), Some("ELIA-Brussels"));
960
961        // Every finding counted once, and each node clicks through to its definition.
962        let json = g.json(&set);
963        let total: u64 = json["nodes"].as_array().unwrap().iter().chain(json["edges"].as_array().unwrap())
964            .chain(std::iter::once(&json["elsewhere"]))
965            .map(|x| { let f = if x.get("findings").is_some() { &x["findings"] } else { x }; f["violation"].as_u64().unwrap() + f["warning"].as_u64().unwrap() + f["info"].as_u64().unwrap() })
966            .sum();
967        let datasets: Vec<_> = files.iter().map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap()).collect();
968        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, vec![]);
969        assert_eq!(total as usize, cimvalidation::validate_files(datasets, &cfg).len());
970        let anvers = json["nodes"].as_array().unwrap().iter().find(|n| n["label"] == "Anvers").unwrap();
971        assert!(anvers["location"]["uri"].as_str().unwrap().ends_with("_BE_EQ_001.xml"), "{anvers}");
972
973        // The assembled DL diagram and the GL locations place every node and route every line.
974        let names: Vec<&str> = g.layouts.iter().map(|l| l.name.as_str()).collect();
975        assert_eq!(names, ["Diagram: Assembled", "Geographic (EPSG:4326)"]);
976        for l in &g.layouts {
977            assert_eq!((l.nodes.len(), l.edges.len()), (8, 12), "{}", l.name);
978        }
979        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
980        let (diagram, map) = (&g.layouts[0], &g.layouts[1]);
981        assert!(!diagram.flip_y);
982        // Brussels and Anvers left of the border points, Amsterdam right of them.
983        let x = |label: &str| diagram.nodes[&index(label)].0;
984        assert!(x("PP_Brussels") < x("Anvers") && x("Anvers") < x("Border_AL11") && x("Border_AL11") < x("PP_Amsterdam"));
985        // Brussels in Brussels, from the ends of its lines; Amsterdam north of it.
986        let (lon, lat) = map.nodes[&index("PP_Brussels")];
987        assert!((lon - 4.30).abs() < 0.01 && (lat - 50.80).abs() < 0.01, "{lon} {lat}");
988        assert!(map.nodes[&index("PP_Amsterdam")].1 > 52.3);
989        // A route runs from its source's end, through the line's points.
990        let line = g.edges.iter().position(|e| e.label == "BE-Line_2").unwrap();
991        assert_eq!(map.edges[&line].len(), 5);
992        let (start, source) = (map.edges[&line][0], map.nodes[&g.edges[line].source]);
993        assert!((start.0 - source.0).abs() < 0.01 && (start.1 - source.1).abs() < 0.01, "{start:?} {source:?}");
994        assert_eq!(json["layouts"][1]["nodes"].as_object().unwrap().len(), 8);
995
996    }
997
998    /// MicroGrid Type 1, node-breaker: inside a substation, its breakers,
999    /// busbars and connectivity nodes by voltage level, its lines with their
1000    /// far ends, and its switches' states; placed on the DL diagrams.
1001    #[test]
1002    fn micro_grid_inside() {
1003        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
1004            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGrid-Type1/MicroGrid-Type1-Merged");
1005        let mut files = collect(&dir);
1006        assert_eq!(files.len(), 12, "missing test data — run `git submodule update --init`");
1007        // A finding on a breaker (no normalOpen) and one on a voltage level (no name).
1008        let eq = files.iter_mut().find(|(p, _)| p.to_string_lossy().ends_with("_BE_EQ_1.xml")).unwrap();
1009        let mut text = eq.1.to_string();
1010        for written in ["<cim:Switch.normalOpen>false</cim:Switch.normalOpen>", "<cim:IdentifiedObject.name>225.0</cim:IdentifiedObject.name>"] {
1011            let at = text.find(written).unwrap();
1012            text.replace_range(at..at + written.len(), "");
1013        }
1014        eq.1 = text.into();
1015        let set = validate(&files);
1016        let g = &set.grid;
1017        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
1018
1019        // Each substation's findings are its items' and its own, once each.
1020        let total = |c: &super::Counts| c.violation + c.warning + c.info;
1021        for (n, inside) in &g.inside {
1022            let items: usize = inside.items.iter().map(|it| total(&it.findings)).sum();
1023            assert_eq!(items + total(&inside.findings), total(&g.nodes[*n].findings), "{}", g.nodes[*n].label);
1024        }
1025        let breaker = g.inside.values().flat_map(|i| &i.items).find(|it| it.label == "CIRCB-1230992285").unwrap();
1026        assert!(breaker.findings.violation > 0, "{:?}", breaker.findings);
1027        let vl = g.inside.values().find(|i| i.groups.iter().any(|gr| gr.id.ends_with("69ef0dbd-da79-4eef-a02f-690cb8a28361"))).unwrap();
1028        assert!(total(&vl.findings) > 0, "{:?}", vl.findings);
1029
1030        let anvers = &g.inside[&index("Anvers")];
1031        let count = |class: &str| anvers.items.iter().filter(|it| it.class == class).count();
1032        assert_eq!((count("Breaker"), count("BusbarSection"), count("ConnectivityNode"), count("ACLineSegment")), (4, 3, 6, 4));
1033        assert_eq!(anvers.groups.iter().map(|gr| gr.kv).collect::<Vec<_>>(), [Some(225.0)]);
1034        assert_eq!(anvers.links.len(), 19);
1035        // Every link runs from equipment to a junction.
1036        assert!(anvers.links.iter().all(|l| !anvers.items[l.item].junction && anvers.items[l.junction].junction));
1037        let line = anvers.items.iter().find(|it| it.label == "BE-Line_2").unwrap();
1038        assert_eq!((line.group, line.far.iter().map(|&f| g.nodes[f].label.as_str()).collect::<Vec<_>>()), (None, vec!["PP_Brussels"]));
1039        assert!(anvers.items.iter().filter(|it| it.class == "Breaker").all(|it| it.open == Some(false)));
1040
1041        // Amsterdam's bus coupler is open and out of service; its transformers sit between voltage levels.
1042        let amsterdam = &g.inside[&index("PP_Amsterdam")];
1043        let coupler = amsterdam.items.iter().find(|it| it.label == "busbarcoupler 1").unwrap();
1044        assert_eq!((coupler.open, coupler.in_service), (Some(true), Some(false)));
1045        assert!(amsterdam.items.iter().filter(|it| it.class == "PowerTransformer").all(|it| it.group.is_none()));
1046        assert_eq!(amsterdam.groups.len(), 3);
1047
1048        // Both diagrams that draw Anvers place its equipment and nodes.
1049        let names: Vec<&str> = anvers.layouts.iter().map(|l| l.name.as_str()).collect();
1050        assert_eq!(names, ["Diagram: MAS BE", "Diagram: Assembled"]);
1051        assert!(anvers.layouts.iter().all(|l| l.nodes.len() > 10), "{:?}", anvers.layouts.iter().map(|l| l.nodes.len()).collect::<Vec<_>>());
1052
1053        // MAS BE draws every junction as a line: its busbars as bars (BE-Busbar_2, and the
1054        // sections the couplers join it to), the junctions inside bays as thin as a wire.
1055        let mas = anvers.layouts.iter().find(|l| l.name == "Diagram: MAS BE").unwrap();
1056        let unit = mas.unit.unwrap();
1057        let thickness = |class: &str, label: &str| {
1058            let i = anvers.items.iter().position(|it| it.class == class && it.label == label).unwrap();
1059            mas.sizes.get(&i).map(|&(w, h)| (w.min(h) * unit * 100.0).round() / 100.0)
1060        };
1061        for section in ["BE-Busbar_2", "N1230992411", "N1230992414"] {
1062            assert_eq!(thickness("BusbarSection", section), Some(crate::single_line::BAR), "{section}");
1063        }
1064        for node in ["N1230991550", "N1230991529", "Series Compensator"] {
1065            assert_eq!(thickness("ConnectivityNode", node), Some(crate::single_line::WIRE), "{node}");
1066        }
1067
1068        let json = g.inside_json(&set, &g.nodes[index("Anvers")].id).unwrap();
1069        assert_eq!(json["items"].as_array().unwrap().len(), 20);
1070        // Its single-line diagram places every item, routes every link and sizes the busbars.
1071        assert_eq!(json["auto"]["nodes"].as_object().unwrap().len(), 20);
1072        assert_eq!(json["auto"]["edges"].as_object().unwrap().len(), 19);
1073        assert_eq!(json["auto"]["sizes"].as_object().unwrap().len(), 3);
1074        assert_eq!(json["auto"]["unit"], 1.0);
1075        assert!(json["items"][0]["location"]["uri"].as_str().unwrap().ends_with("_BE_EQ_1.xml"));
1076        assert!(g.inside_json(&set, "no such substation").is_none());
1077    }
1078}
1079