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 item: usize,
152    pub junction: usize,
153    /// `ACDCTerminal.connected`.
154    pub connected: Option<bool>,
155}
156
157/// Positions of nodes and routes of edges, in one diagram (DL) or one
158/// coordinate system (GL), as the data writes them.
159#[derive(Debug, Default)]
160pub struct Layout {
161    pub id: String,
162    pub name: String,
163    /// `diagram` (x right, y as `flip_y` says) or `geographic` (x longitude,
164    /// y latitude, in degrees).
165    pub kind: &'static str,
166    /// A diagram whose y grows upwards (`OrientationKind.positive`).
167    pub flip_y: bool,
168    /// Node index → position.
169    pub nodes: BTreeMap<usize, (f64, f64)>,
170    /// Edge index → its route, from its source's end to its target's.
171    pub edges: BTreeMap<usize, Vec<(f64, f64)>>,
172}
173
174/// Points gathered for a layout: a node's own, and those it takes from the
175/// ends of its lines when it has none of its own.
176#[derive(Default)]
177struct Gather {
178    own: FastMap<usize, Vec<(f64, f64)>>,
179    ends: FastMap<usize, Vec<(f64, f64)>>,
180    routes: BTreeMap<usize, Vec<(f64, f64)>>,
181}
182
183impl Gather {
184    /// The points of one located object: an edge's route (whose ends also
185    /// locate its nodes), else points on the node it is in.
186    fn add(&mut self, grid: &Grid, object: &str, points: Vec<(f64, f64)>) {
187        if points.is_empty() {
188            return;
189        }
190        match grid.placed.get(object) {
191            Some(&Place::Edge(e)) if grid.edges[e].id == object => {
192                let edge = &grid.edges[e];
193                self.ends.entry(edge.source).or_default().push(points[0]);
194                self.ends.entry(edge.target).or_default().push(points[points.len() - 1]);
195                self.routes.insert(e, points);
196            }
197            Some(&Place::Node(n)) => self.own.entry(n).or_default().extend(points),
198            _ => {}
199        }
200    }
201
202    fn layout(self, id: String, name: String, kind: &'static str, flip_y: bool) -> Option<Layout> {
203        let mean = |ps: &[(f64, f64)]| {
204            let n = ps.len() as f64;
205            (ps.iter().map(|p| p.0).sum::<f64>() / n, ps.iter().map(|p| p.1).sum::<f64>() / n)
206        };
207        let mut nodes: BTreeMap<usize, (f64, f64)> = self.ends.iter().map(|(&n, ps)| (n, mean(ps))).collect();
208        nodes.extend(self.own.iter().map(|(&n, ps)| (n, mean(ps))));
209        (!nodes.is_empty()).then_some(Layout { id, name, kind, flip_y, nodes, edges: self.routes })
210    }
211}
212
213/// Each object's points by class, `(owner, sequence, x, y)`, sorted, and the
214/// owner of each point list: a DiagramObject's or a Location's.
215fn 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)>> {
216    let mut by_owner: FastMap<&str, Vec<(i64, &str, f64, f64)>> = FastMap::default();
217    for (&id, els) in &m.objects {
218        if els[0].type_name() != class {
219            continue;
220        }
221        if let (Some(owner), Some(x), Some(y)) = (m.reference(id, owner_key), m.number(id, x_key), m.number(id, y_key)) {
222            let seq = m.number(id, seq_key).map_or(i64::MAX, |n| n as i64);
223            by_owner.entry(owner).or_default().push((seq, id, x, y));
224        }
225    }
226    by_owner
227        .into_iter()
228        .map(|(owner, mut ps)| {
229            ps.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
230            (owner, ps.into_iter().map(|(_, _, x, y)| (x, y)).collect())
231        })
232        .collect()
233}
234
235/// Whether a diagram's y grows upwards, and its layout's name.
236fn diagram_flip(m: &Model, diagram: &str) -> (bool, String) {
237    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"));
238    (flip_y, format!("Diagram: {}", m.name(diagram)))
239}
240
241/// One layout per DL diagram and per GL coordinate system; and one per DL
242/// diagram for each substation whose items it draws, by node index.
243fn layouts(m: &Model, grid: &Grid) -> (Vec<Layout>, Vec<(usize, Layout)>) {
244    let mut out = Vec::new();
245
246    // DL: each DiagramObject's points, on the object it shows.
247    let diagram_points = points(m, "DiagramObjectPoint", "DiagramObjectPoint.DiagramObject",
248        "DiagramObjectPoint.xPosition", "DiagramObjectPoint.yPosition", "DiagramObjectPoint.sequenceNumber");
249    let mut diagrams: BTreeMap<&str, Gather> = BTreeMap::new();
250    // (diagram, node) → item → its points.
251    type Items = BTreeMap<usize, Vec<(f64, f64)>>;
252    let mut insides: BTreeMap<(&str, usize), Items> = BTreeMap::new();
253    let mut objects: Vec<&&str> = diagram_points.keys().collect();
254    objects.sort();
255    for &object in objects {
256        let (Some(diagram), Some(shown)) = (m.reference(object, "DiagramObject.Diagram"), m.reference(object, "DiagramObject.IdentifiedObject")) else { continue };
257        diagrams.entry(diagram).or_default().add(grid, shown, diagram_points[object].clone());
258        // An item, in each substation it is drawn in (a line in both of its ends').
259        let ns: Vec<usize> = match grid.placed.get(shown) {
260            Some(&Place::Edge(e)) => vec![grid.edges[e].source, grid.edges[e].target],
261            Some(&Place::Node(n)) => vec![n],
262            None => vec![],
263        };
264        for n in ns {
265            if let Some(i) = grid.inside.get(&n).and_then(|inside| inside.items.iter().position(|it| it.id == shown)) {
266                insides.entry((diagram, n)).or_default().entry(i).or_default().extend(&diagram_points[object]);
267            }
268        }
269    }
270    for (diagram, gather) in diagrams {
271        let (flip_y, name) = diagram_flip(m, diagram);
272        out.extend(gather.layout(format!("dl:{diagram}"), name, "diagram", flip_y));
273    }
274    let mut inside = Vec::new();
275    for ((diagram, n), placed) in insides {
276        if placed.len() < 2 {
277            continue;
278        }
279        let items = &grid.inside[&n].items;
280        let mean = |ps: &[(f64, f64)]| {
281            let k = ps.len() as f64;
282            (ps.iter().map(|p| p.0).sum::<f64>() / k, ps.iter().map(|p| p.1).sum::<f64>() / k)
283        };
284        let own: Vec<(f64, f64)> = placed.iter().filter(|(i, _)| items[**i].far.is_empty()).map(|(_, ps)| mean(ps)).collect();
285        let centre = (!own.is_empty()).then(|| mean(&own));
286        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);
287        let nodes = placed
288            .iter()
289            .map(|(&i, ps)| {
290                // A line drawn through the substation is at its end here, a
291                // little out along the line, off the node it ends at.
292                let at = match centre {
293                    Some(c) if !items[i].far.is_empty() && ps.len() > 1 => {
294                        let d = |p: (f64, f64)| (p.0 - c.0).hypot(p.1 - c.1);
295                        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]) };
296                        let k = (next.0 - end.0).hypot(next.1 - end.1);
297                        if k > 0.0 && span > 0.0 {
298                            let step = (0.06 * span).min(k / 2.0);
299                            (end.0 + (next.0 - end.0) / k * step, end.1 + (next.1 - end.1) / k * step)
300                        } else {
301                            end
302                        }
303                    }
304                    _ => mean(ps),
305                };
306                (i, at)
307            })
308            .collect();
309        let (flip_y, name) = diagram_flip(m, diagram);
310        inside.push((n, Layout { id: format!("dl:{diagram}"), name, kind: "diagram", flip_y, nodes, edges: BTreeMap::new() }));
311    }
312
313    // GL: each Location's points, on the resources it locates, by coordinate system.
314    let location_points = points(m, "PositionPoint", "PositionPoint.Location",
315        "PositionPoint.xPosition", "PositionPoint.yPosition", "PositionPoint.sequenceNumber");
316    let mut systems: BTreeMap<String, Gather> = BTreeMap::new();
317    let mut locations: Vec<&&str> = location_points.keys().collect();
318    locations.sort();
319    for &location in locations {
320        let crs = m
321            .reference(location, "Location.CoordinateSystem")
322            .and_then(|c| m.text(c, "CoordinateSystem.crsUrn"))
323            .unwrap_or("urn:ogc:def:crs:EPSG::4326")
324            .to_string();
325        let gather = systems.entry(crs).or_default();
326        let located = m.objects.get(location).map(|els| els.iter().flat_map(|el| el.get_refs("Location.PowerSystemResources")).cloned().collect::<Vec<_>>()).unwrap_or_default();
327        for psr in located {
328            gather.add(grid, mrid_of(&psr), location_points[location].clone());
329        }
330    }
331    for (crs, gather) in systems {
332        let short = crs.rsplit(':').next().unwrap_or(&crs).to_string();
333        out.extend(gather.layout(format!("gl:{crs}"), format!("Geographic (EPSG:{short})"), "geographic", false));
334    }
335    (out, inside)
336}
337
338/// The set's files read as one model: each object's elements, the defining
339/// one first.
340pub struct Model<'a> {
341    pub(crate) objects: FastMap<&'a str, Vec<&'a Element>>,
342    /// ConductingEquipment → its terminals, by sequence number.
343    terminals: FastMap<&'a str, Vec<&'a str>>,
344}
345
346impl<'a> Model<'a> {
347    pub fn new(datasets: &'a [CimDataset]) -> Self {
348        let mut objects: FastMap<&str, Vec<&Element>> = FastMap::default();
349        for ds in datasets {
350            for (mrid, el) in &ds.entries {
351                let els = objects.entry(mrid.as_str()).or_default();
352                if el.defined() { els.insert(0, el) } else { els.push(el) }
353            }
354        }
355        let mut model = Self { objects, terminals: FastMap::default() };
356        let mut terminals: FastMap<&str, Vec<(i64, &str)>> = FastMap::default();
357        for (&mrid, els) in &model.objects {
358            if els[0].type_name() != "Terminal" {
359                continue;
360            }
361            if let Some(ce) = model.reference(mrid, "Terminal.ConductingEquipment") {
362                let seq = model.number(mrid, "ACDCTerminal.sequenceNumber").map_or(i64::MAX, |n| n as i64);
363                terminals.entry(ce).or_default().push((seq, mrid));
364            }
365        }
366        model.terminals = terminals
367            .into_iter()
368            .map(|(ce, mut ts)| {
369                ts.sort();
370                (ce, ts.into_iter().map(|(_, t)| t).collect())
371            })
372            .collect();
373        model
374    }
375
376    pub(crate) fn class(&self, mrid: &str) -> Option<&'static str> {
377        self.objects.get(mrid).map(|els| els[0].type_name())
378    }
379
380    pub(crate) fn text(&self, mrid: &str, key: &str) -> Option<&'a str> {
381        self.objects.get(mrid)?.iter().find_map(|el| el.get_str(key))
382    }
383
384    fn number(&self, mrid: &str, key: &str) -> Option<f64> {
385        self.text(mrid, key)?.trim().parse().ok()
386    }
387
388    fn flag(&self, mrid: &str, key: &str) -> Option<bool> {
389        self.text(mrid, key).map(|t| t.trim() == "true")
390    }
391
392    /// The voltage level a container (VoltageLevel, Bay) is, or is in.
393    fn voltage_level(&self, container: &'a str) -> Option<&'a str> {
394        match self.class(container)? {
395            "VoltageLevel" => Some(container),
396            "Bay" => self.reference(container, "Bay.VoltageLevel"),
397            _ => None,
398        }
399    }
400
401    /// A terminal's connectivity node, else its topological node.
402    fn terminal_node(&self, terminal: &str) -> Option<&'a str> {
403        self.reference(terminal, "Terminal.ConnectivityNode").or_else(|| self.reference(terminal, "Terminal.TopologicalNode"))
404    }
405
406    /// The mRID a field refers to, whether or not the set has that object.
407    pub(crate) fn target(&self, mrid: &str, key: &str) -> Option<&'a str> {
408        self.objects.get(mrid)?.iter().find_map(|el| el.get_ref(key)).map(mrid_of)
409    }
410
411    /// The object a field refers to, if it is in the set.
412    pub(crate) fn reference(&self, mrid: &str, key: &str) -> Option<&'a str> {
413        let target = self.objects.get(mrid)?.iter().find_map(|el| el.get_ref(key))?;
414        self.objects.get_key_value(mrid_of(target)).map(|(k, _)| *k)
415    }
416
417    fn name(&self, mrid: &str) -> String {
418        self.text(mrid, "IdentifiedObject.name").filter(|n| !n.is_empty()).unwrap_or(mrid).to_string()
419    }
420
421    /// The substation a container (VoltageLevel, Bay, Substation) is in.
422    fn substation(&self, container: &'a str) -> Option<&'a str> {
423        let mut at = container;
424        for _ in 0..4 {
425            at = match self.class(at)? {
426                "Substation" => return Some(at),
427                "VoltageLevel" => self.reference(at, "VoltageLevel.Substation")?,
428                "Bay" => self.reference(at, "Bay.VoltageLevel")?,
429                _ => return None,
430            };
431        }
432        None
433    }
434
435    /// The node of a terminal: its connectivity (else topological) node's
436    /// substation, else that node itself, a boundary point.
437    fn terminal_end(&self, terminal: &'a str) -> Option<(&'a str, bool)> {
438        let node = self.terminal_node(terminal)?;
439        match self.node_container(node).and_then(|c| self.substation(c)) {
440            Some(sub) => Some((sub, false)),
441            None => Some((node, true)),
442        }
443    }
444
445    fn node_container(&self, node: &str) -> Option<&'a str> {
446        self.reference(node, "ConnectivityNode.ConnectivityNodeContainer")
447            .or_else(|| self.reference(node, "TopologicalNode.ConnectivityNodeContainer"))
448    }
449}
450
451/// The grid of a model set's files.
452pub fn build(m: &Model<'_>) -> Grid {
453    let mut grid = Grid::default();
454    let mut node_of: FastMap<&str, usize> = FastMap::default();
455
456    let mut subs: Vec<&str> = m.objects.keys().copied().filter(|k| m.class(k) == Some("Substation")).collect();
457    subs.sort_by_key(|s| (m.name(s), *s));
458    for sub in subs {
459        node_of.insert(sub, grid.nodes.len());
460        let region = m.reference(sub, "Substation.Region").map(|r| m.name(r));
461        grid.nodes.push(Node { id: sub.into(), label: m.name(sub), kind: "Substation", region, ..Default::default() });
462    }
463
464    // Equipment whose terminals reach two different nodes is an edge. Inside
465    // a substation, each terminal ending there links its equipment to its node.
466    let mut items: FastMap<(usize, &str), usize> = FastMap::default();
467    let mut groups: FastMap<(usize, &str), usize> = FastMap::default();
468    let mut equipment: Vec<&str> = m.terminals.keys().copied().collect();
469    equipment.sort();
470    for ce in equipment {
471        let terminals = &m.terminals[ce];
472        let ends: Vec<Option<(&str, bool)>> = terminals.iter().map(|t| m.terminal_end(t)).collect();
473        let mut distinct: Vec<(&str, bool)> = Vec::new();
474        for &end in ends.iter().flatten() {
475            if !distinct.iter().any(|e| e.0 == end.0) {
476                distinct.push(end);
477            }
478        }
479        if distinct.len() >= 2 {
480            let source = node_for(m, &mut grid, &mut node_of, distinct[0]);
481            for &end in &distinct[1..] {
482                let target = node_for(m, &mut grid, &mut node_of, end);
483                let kv = m.reference(ce, "ConductingEquipment.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
484                let id = if distinct.len() == 2 { ce.to_string() } else { format!("{ce}#{}", grid.edges.len()) };
485                grid.placed.insert(ce.to_string(), Place::Edge(grid.edges.len()));
486                grid.edges.push(Edge { id, label: m.name(ce), class: m.class(ce).unwrap_or(""), source, target, kv, findings: Counts::default() });
487            }
488        }
489        let reached: Vec<usize> = distinct.iter().filter_map(|e| node_of.get(e.0).copied()).collect();
490        for (t, end) in terminals.iter().zip(&ends) {
491            let (Some(&n), Some(node)) = (end.and_then(|e| node_of.get(e.0)), m.terminal_node(t)) else { continue };
492            if grid.nodes[n].kind != "Substation" {
493                continue;
494            }
495            let far: Vec<usize> = reached.iter().copied().filter(|&r| r != n).collect();
496            let item = item_for(m, &mut grid, &mut items, &mut groups, n, ce, false, far);
497            let junction = item_for(m, &mut grid, &mut items, &mut groups, n, node, true, vec![]);
498            grid.inside.entry(n).or_default().links.push(Link { id: t.to_string(), item, junction, connected: m.flag(t, "ACDCTerminal.connected") });
499        }
500    }
501
502    // Every other object goes where its container, equipment or node is.
503    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
504    ids.sort();
505    let mut within = FastMap::default();
506    for id in ids {
507        if let Some(Place::Node(n)) = place(m, &node_of, &items, &mut grid.placed, &mut within, id, 0)
508            && let Some(container) = m.reference(id, "Equipment.EquipmentContainer")
509            && m.substation(container).is_some()
510        {
511            *grid.nodes[n].equipment.entry(m.class(id).unwrap_or("")).or_default() += 1;
512        }
513    }
514    grid.within = within;
515    for (&vl, els) in &m.objects {
516        if els[0].type_name() != "VoltageLevel" {
517            continue;
518        }
519        if let Some(Place::Node(n)) = grid.placed.get(vl)
520            && let Some(kv) = m.reference(vl, "VoltageLevel.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"))
521        {
522            grid.nodes[*n].kv.push(kv);
523        }
524    }
525    for node in &mut grid.nodes {
526        node.kv.sort_by(|a, b| b.total_cmp(a));
527        node.kv.dedup();
528    }
529
530    let (layouts, inside) = layouts(m, &grid);
531    grid.layouts = layouts;
532    if !grid.nodes.is_empty() {
533        let edges: Vec<(usize, usize)> = grid.edges.iter().map(|e| (e.source, e.target)).collect();
534        let pos = crate::layout::force(grid.nodes.len(), &edges);
535        grid.auto = Some(Layout {
536            id: "auto".into(), name: "Automatic".into(), kind: "diagram",
537            nodes: pos.into_iter().enumerate().collect(), ..Default::default()
538        });
539    }
540    for (n, l) in inside {
541        grid.inside.get_mut(&n).unwrap().layouts.push(l);
542    }
543    grid
544}
545
546/// The item for `id` inside node `n`'s substation, added on first use, with
547/// its voltage level.
548#[allow(clippy::too_many_arguments)]
549fn item_for<'a>(
550    m: &Model<'a>, grid: &mut Grid, items: &mut FastMap<(usize, &'a str), usize>, groups: &mut FastMap<(usize, &'a str), usize>,
551    n: usize, id: &'a str, junction: bool, far: Vec<usize>,
552) -> usize {
553    if let Some(&i) = items.get(&(n, id)) {
554        return i;
555    }
556    let container = if junction { m.node_container(id) } else { m.reference(id, "Equipment.EquipmentContainer") };
557    let vl = container.and_then(|c| m.voltage_level(c)).filter(|vl| m.substation(vl) == Some(grid.nodes[n].id.as_str()));
558    let inside = grid.inside.entry(n).or_default();
559    let group = vl.map(|vl| {
560        *groups.entry((n, vl)).or_insert_with(|| {
561            let kv = m.reference(vl, "VoltageLevel.BaseVoltage").and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
562            inside.groups.push(Group { id: vl.into(), label: m.name(vl), kv });
563            inside.groups.len() - 1
564        })
565    });
566    let class = m.class(id).unwrap_or("");
567    let switch = !junction && (m.text(id, "Switch.open").is_some() || m.text(id, "Switch.normalOpen").is_some());
568    inside.items.push(Item {
569        id: id.into(),
570        label: m.name(id),
571        class,
572        junction,
573        group,
574        open: if switch { m.flag(id, "Switch.open").or_else(|| m.flag(id, "Switch.normalOpen")) } else { None },
575        in_service: if junction { None } else { m.flag(id, "Equipment.inService") },
576        far,
577        findings: Counts::default(),
578    });
579    items.insert((n, id), inside.items.len() - 1);
580    inside.items.len() - 1
581}
582
583/// The node of an edge's end, added on first use: a substation, or a
584/// boundary point.
585fn node_for<'a>(m: &Model<'a>, grid: &mut Grid, node_of: &mut FastMap<&'a str, usize>, (id, boundary): (&'a str, bool)) -> usize {
586    *node_of.entry(id).or_insert_with(|| {
587        grid.nodes.push(Node {
588            id: id.into(),
589            // An IGM often only refers to a boundary point the boundary set names.
590            label: m.text(id, "IdentifiedObject.name").unwrap_or_default().to_string(),
591            kind: if boundary { m.class(id).unwrap_or("ConnectivityNode") } else { "Substation" },
592            ..Default::default()
593        });
594        grid.nodes.len() - 1
595    })
596}
597
598/// Where `id` belongs, memoised in `placed`: a container's substation, a
599/// terminal's equipment, a node's substation, else the first referenced
600/// object that has a place. On a substation's node, also the item `id`
601/// stands for there, memoised in `within`: an item itself, else that of the
602/// object it takes its place from.
603#[allow(clippy::too_many_arguments)]
604fn place<'a>(
605    m: &Model<'a>, node_of: &FastMap<&str, usize>, items: &FastMap<(usize, &'a str), usize>, placed: &mut FastMap<String, Place>,
606    within: &mut FastMap<String, (usize, usize)>, id: &'a str, depth: u8,
607) -> Option<Place> {
608    if let Some(p) = placed.get(id) {
609        return Some(*p);
610    }
611    if depth > 3 {
612        return None;
613    }
614    let class = m.class(id)?;
615    let mut via = None;
616    let direct = match class {
617        "Substation" | "VoltageLevel" | "Bay" => m.substation(id).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n)),
618        "ConnectivityNode" | "TopologicalNode" => match node_of.get(id) {
619            Some(&n) => Some(Place::Node(n)),
620            None => {
621                let key = if class == "ConnectivityNode" { "ConnectivityNode.ConnectivityNodeContainer" } else { "TopologicalNode.ConnectivityNodeContainer" };
622                m.reference(id, key).and_then(|c| m.substation(c)).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n))
623            }
624        },
625        "Terminal" => m.reference(id, "Terminal.ConductingEquipment").and_then(|ce| {
626            via = Some(ce);
627            place(m, node_of, items, placed, within, ce, depth + 1)
628        }),
629        _ => m.reference(id, "Equipment.EquipmentContainer").and_then(|c| m.substation(c)).and_then(|s| node_of.get(s)).map(|&n| Place::Node(n)),
630    };
631    let found = match direct {
632        Some(p) => p,
633        None => {
634            // Limits, tap changers, regulating controls, state variables, …:
635            // where what they refer to is.
636            let els = m.objects.get(id)?;
637            let mut keys: Vec<&str> = els.iter().flat_map(|el| el.fields().keys().copied()).collect();
638            keys.sort();
639            keys.dedup();
640            let (r, p) = keys.into_iter().filter(|k| !k.ends_with(".BaseVoltage") && !k.ends_with(".Region")).find_map(|k| {
641                let r = m.reference(id, k).filter(|r| *r != id)?;
642                place(m, node_of, items, placed, within, r, depth + 1).map(|p| (r, p))
643            })?;
644            via = Some(r);
645            p
646        }
647    };
648    placed.insert(id.to_string(), found);
649    if let Place::Node(n) = found
650        && 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))
651    {
652        within.insert(id.to_string(), w);
653    }
654    Some(found)
655}
656
657impl Grid {
658    /// Count each finding on its object's node or edge.
659    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
660        for (_, v) in violations {
661            match self.placed.get(v.object_id.as_str()) {
662                Some(Place::Node(n)) => {
663                    self.nodes[*n].findings.add(&v.severity);
664                    if let Some(inside) = self.inside.get_mut(n) {
665                        match self.within.get(v.object_id.as_str()) {
666                            Some(&(_, i)) => inside.items[i].findings.add(&v.severity),
667                            None => inside.findings.add(&v.severity),
668                        }
669                    }
670                }
671                Some(Place::Edge(e)) => self.edges[*e].findings.add(&v.severity),
672                None => self.elsewhere.add(&v.severity),
673            }
674        }
675    }
676
677    /// Where the view shows object `id`: `select`, the node or edge it is
678    /// on, else the item it stands for inside `enter`, its substation; and
679    /// `inside`, a substation's own id. `None` if it is on neither.
680    pub fn reveal(&self, id: &str) -> Option<Value> {
681        match *self.placed.get(id)? {
682            Place::Edge(e) => Some(json!({ "select": format!("e:{}", self.edges[e].id) })),
683            Place::Node(n) => {
684                let node = &self.nodes[n];
685                if node.kind != "Substation" || node.id == id {
686                    let inside = (node.kind == "Substation").then_some(&node.id);
687                    return Some(json!({ "select": node.id, "inside": inside }));
688                }
689                let item = self.within.get(id).map(|&(_, i)| &self.inside[&n].items[i].id);
690                Some(json!({ "enter": node.id, "select": item }))
691            }
692        }
693    }
694
695    /// The view's data: nodes and edges, each with where it is written.
696    pub fn json(&self, set: &impl Locations) -> Value {
697        let location = |id: &str| set.location(id.split('#').next().unwrap_or(id));
698        let nodes: Vec<Value> = self
699            .nodes
700            .iter()
701            .map(|n| {
702                json!({
703                    "id": n.id, "label": n.label, "kind": n.kind, "region": n.region, "kV": n.kv,
704                    "equipment": n.equipment, "findings": n.findings.json(), "location": location(&n.id),
705                })
706            })
707            .collect();
708        let edges: Vec<Value> = self
709            .edges
710            .iter()
711            .map(|e| {
712                json!({
713                    "id": e.id, "label": e.label, "class": e.class, "source": self.nodes[e.source].id,
714                    "target": self.nodes[e.target].id, "kV": e.kv, "findings": e.findings.json(), "location": location(&e.id),
715                })
716            })
717            .collect();
718        let layout = |l: &Layout| {
719                let nodes: serde_json::Map<String, Value> = l.nodes.iter().map(|(&n, &(x, y))| (self.nodes[n].id.clone(), json!([x, y]))).collect();
720                let edges: serde_json::Map<String, Value> = l
721                    .edges
722                    .iter()
723                    .map(|(&e, ps)| (self.edges[e].id.clone(), json!(ps.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>())))
724                    .collect();
725                json!({ "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "nodes": nodes, "edges": edges })
726        };
727        json!({
728            "files": set.files(),
729            "nodes": nodes, "edges": edges, "elsewhere": self.elsewhere.json(),
730            "layouts": self.layouts.iter().map(layout).collect::<Vec<_>>(), "auto": self.auto.as_ref().map(layout),
731        })
732    }
733
734    /// What the substation `id` holds, for the view's drill-down; `None` if
735    /// no substation of the set has that mRID.
736    pub fn inside_json(&self, set: &impl Locations, id: &str) -> Option<Value> {
737        let n = self.nodes.iter().position(|x| x.id == id && x.kind == "Substation")?;
738        let node = &self.nodes[n];
739        let empty = Inside::default();
740        let inside = self.inside.get(&n).unwrap_or(&empty);
741        let location = |id: &str| set.location(id);
742        let groups: Vec<Value> = inside.groups.iter().map(|g| json!({ "id": g.id, "label": g.label, "kV": g.kv })).collect();
743        let items: Vec<Value> = inside
744            .items
745            .iter()
746            .map(|it| {
747                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();
748                json!({
749                    "id": it.id, "label": it.label, "class": it.class, "junction": it.junction,
750                    "group": it.group.map(|g| &inside.groups[g].id), "open": it.open, "inService": it.in_service,
751                    "far": far, "findings": it.findings.json(), "location": location(&it.id),
752                })
753            })
754            .collect();
755        let links: Vec<Value> = inside
756            .links
757            .iter()
758            .map(|l| json!({ "id": l.id, "source": inside.items[l.item].id, "target": inside.items[l.junction].id, "connected": l.connected }))
759            .collect();
760        let layouts: Vec<Value> = inside
761            .layouts
762            .iter()
763            .map(|l| {
764                let nodes: serde_json::Map<String, Value> = l.nodes.iter().map(|(&i, &(x, y))| (inside.items[i].id.clone(), json!([x, y]))).collect();
765                json!({ "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "nodes": nodes, "edges": {} })
766            })
767            .collect();
768        Some(json!({
769            "id": node.id, "label": node.label, "region": node.region, "kV": node.kv, "findings": inside.findings.json(),
770            "location": location(&node.id), "groups": groups, "items": items, "links": links, "layouts": layouts,
771        }))
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use std::path::Path;
778
779    use crate::testing::{collect, validate};
780
781    /// MicroGrid: Belgium's two substations and the Netherlands' one, joined
782    /// through the boundary's five border nodes; each line an edge.
783    #[test]
784    fn micro_grid() {
785        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
786            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
787        let files = collect(&dir);
788        assert_eq!(files.len(), 12, "missing test data — run `git submodule update --init`");
789        let set = validate(&files);
790        let g = &set.grid;
791        let mut subs: Vec<&str> = g.nodes.iter().filter(|n| n.kind == "Substation").map(|n| n.label.as_str()).collect();
792        subs.sort();
793        assert_eq!(subs, ["Anvers", "PP_Amsterdam", "PP_Brussels"]);
794        let mut borders: Vec<&str> = g.nodes.iter().filter(|n| n.kind == "ConnectivityNode").map(|n| n.label.as_str()).collect();
795        borders.sort();
796        assert_eq!(borders, ["Border_AL11", "Border_GY11", "Border_MA11", "Border_ST23", "Border_ST24"]);
797        assert_eq!(g.edges.len(), 12);
798        assert!(g.edges.iter().all(|e| e.class == "ACLineSegment"));
799
800        let node = |label: &str| g.nodes.iter().find(|n| n.label == label).unwrap();
801        let between = |a: &str, b: &str| {
802            g.edges.iter().filter(|e| {
803                let ends = [g.nodes[e.source].label.as_str(), g.nodes[e.target].label.as_str()];
804                ends.contains(&a) && ends.contains(&b)
805            }).count()
806        };
807        assert_eq!(between("PP_Brussels", "Anvers"), 2);
808        assert_eq!(between("PP_Amsterdam", "Border_AL11"), 1);
809        assert_eq!(between("PP_Brussels", "Border_AL11"), 1);
810        let brussels = node("PP_Brussels");
811        assert_eq!(brussels.kv, [380.0, 225.0, 110.0, 21.0, 10.5]);
812        assert_eq!(brussels.equipment["SynchronousMachine"], 2);
813        assert_eq!(brussels.region.as_deref(), Some("ELIA-Brussels"));
814
815        // Every finding counted once, and each node clicks through to its definition.
816        let json = g.json(&set);
817        let total: u64 = json["nodes"].as_array().unwrap().iter().chain(json["edges"].as_array().unwrap())
818            .chain(std::iter::once(&json["elsewhere"]))
819            .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() })
820            .sum();
821        let datasets: Vec<_> = files.iter().map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap()).collect();
822        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, vec![]);
823        assert_eq!(total as usize, cimvalidation::validate_files(datasets, &cfg).len());
824        let anvers = json["nodes"].as_array().unwrap().iter().find(|n| n["label"] == "Anvers").unwrap();
825        assert!(anvers["location"]["uri"].as_str().unwrap().ends_with("_BE_EQ_001.xml"), "{anvers}");
826
827        // The assembled DL diagram and the GL locations place every node and route every line.
828        let names: Vec<&str> = g.layouts.iter().map(|l| l.name.as_str()).collect();
829        assert_eq!(names, ["Diagram: Assembled", "Geographic (EPSG:4326)"]);
830        for l in &g.layouts {
831            assert_eq!((l.nodes.len(), l.edges.len()), (8, 12), "{}", l.name);
832        }
833        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
834        let (diagram, map) = (&g.layouts[0], &g.layouts[1]);
835        assert!(!diagram.flip_y);
836        // Brussels and Anvers left of the border points, Amsterdam right of them.
837        let x = |label: &str| diagram.nodes[&index(label)].0;
838        assert!(x("PP_Brussels") < x("Anvers") && x("Anvers") < x("Border_AL11") && x("Border_AL11") < x("PP_Amsterdam"));
839        // Brussels in Brussels, from the ends of its lines; Amsterdam north of it.
840        let (lon, lat) = map.nodes[&index("PP_Brussels")];
841        assert!((lon - 4.30).abs() < 0.01 && (lat - 50.80).abs() < 0.01, "{lon} {lat}");
842        assert!(map.nodes[&index("PP_Amsterdam")].1 > 52.3);
843        // A route runs from its source's end, through the line's points.
844        let line = g.edges.iter().position(|e| e.label == "BE-Line_2").unwrap();
845        assert_eq!(map.edges[&line].len(), 5);
846        let (start, source) = (map.edges[&line][0], map.nodes[&g.edges[line].source]);
847        assert!((start.0 - source.0).abs() < 0.01 && (start.1 - source.1).abs() < 0.01, "{start:?} {source:?}");
848        assert_eq!(json["layouts"][1]["nodes"].as_object().unwrap().len(), 8);
849
850    }
851
852    /// MicroGrid Type 1, node-breaker: inside a substation, its breakers,
853    /// busbars and connectivity nodes by voltage level, its lines with their
854    /// far ends, and its switches' states; placed on the DL diagrams.
855    #[test]
856    fn micro_grid_inside() {
857        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
858            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGrid-Type1/MicroGrid-Type1-Merged");
859        let mut files = collect(&dir);
860        assert_eq!(files.len(), 12, "missing test data — run `git submodule update --init`");
861        // A finding on a breaker (no normalOpen) and one on a voltage level (no name).
862        let eq = files.iter_mut().find(|(p, _)| p.to_string_lossy().ends_with("_BE_EQ_1.xml")).unwrap();
863        let mut text = eq.1.to_string();
864        for written in ["<cim:Switch.normalOpen>false</cim:Switch.normalOpen>", "<cim:IdentifiedObject.name>225.0</cim:IdentifiedObject.name>"] {
865            let at = text.find(written).unwrap();
866            text.replace_range(at..at + written.len(), "");
867        }
868        eq.1 = text.into();
869        let set = validate(&files);
870        let g = &set.grid;
871        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
872
873        // Each substation's findings are its items' and its own, once each.
874        let total = |c: &super::Counts| c.violation + c.warning + c.info;
875        for (n, inside) in &g.inside {
876            let items: usize = inside.items.iter().map(|it| total(&it.findings)).sum();
877            assert_eq!(items + total(&inside.findings), total(&g.nodes[*n].findings), "{}", g.nodes[*n].label);
878        }
879        let breaker = g.inside.values().flat_map(|i| &i.items).find(|it| it.label == "CIRCB-1230992285").unwrap();
880        assert!(breaker.findings.violation > 0, "{:?}", breaker.findings);
881        let vl = g.inside.values().find(|i| i.groups.iter().any(|gr| gr.id.ends_with("69ef0dbd-da79-4eef-a02f-690cb8a28361"))).unwrap();
882        assert!(total(&vl.findings) > 0, "{:?}", vl.findings);
883
884        let anvers = &g.inside[&index("Anvers")];
885        let count = |class: &str| anvers.items.iter().filter(|it| it.class == class).count();
886        assert_eq!((count("Breaker"), count("BusbarSection"), count("ConnectivityNode"), count("ACLineSegment")), (4, 3, 6, 4));
887        assert_eq!(anvers.groups.iter().map(|gr| gr.kv).collect::<Vec<_>>(), [Some(225.0)]);
888        assert_eq!(anvers.links.len(), 19);
889        // Every link runs from equipment to a junction.
890        assert!(anvers.links.iter().all(|l| !anvers.items[l.item].junction && anvers.items[l.junction].junction));
891        let line = anvers.items.iter().find(|it| it.label == "BE-Line_2").unwrap();
892        assert_eq!((line.group, line.far.iter().map(|&f| g.nodes[f].label.as_str()).collect::<Vec<_>>()), (None, vec!["PP_Brussels"]));
893        assert!(anvers.items.iter().filter(|it| it.class == "Breaker").all(|it| it.open == Some(false)));
894
895        // Amsterdam's bus coupler is open and out of service; its transformers sit between voltage levels.
896        let amsterdam = &g.inside[&index("PP_Amsterdam")];
897        let coupler = amsterdam.items.iter().find(|it| it.label == "busbarcoupler 1").unwrap();
898        assert_eq!((coupler.open, coupler.in_service), (Some(true), Some(false)));
899        assert!(amsterdam.items.iter().filter(|it| it.class == "PowerTransformer").all(|it| it.group.is_none()));
900        assert_eq!(amsterdam.groups.len(), 3);
901
902        // Both diagrams that draw Anvers place its equipment and nodes.
903        let names: Vec<&str> = anvers.layouts.iter().map(|l| l.name.as_str()).collect();
904        assert_eq!(names, ["Diagram: MAS BE", "Diagram: Assembled"]);
905        assert!(anvers.layouts.iter().all(|l| l.nodes.len() > 10), "{:?}", anvers.layouts.iter().map(|l| l.nodes.len()).collect::<Vec<_>>());
906
907        let json = g.inside_json(&set, &g.nodes[index("Anvers")].id).unwrap();
908        assert_eq!(json["items"].as_array().unwrap().len(), 20);
909        assert!(json["items"][0]["location"]["uri"].as_str().unwrap().ends_with("_BE_EQ_1.xml"));
910        assert!(g.inside_json(&set, "no such substation").is_none());
911    }
912}
913