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
205                    .entry(edge.target)
206                    .or_default()
207                    .push(points[points.len() - 1]);
208                self.routes.insert(e, points);
209            }
210            Some(&Place::Node(n)) => self.own.entry(n).or_default().extend(points),
211            _ => {}
212        }
213    }
214
215    fn layout(self, id: String, name: String, kind: &'static str, flip_y: bool) -> Option<Layout> {
216        let mean = |ps: &[(f64, f64)]| {
217            let n = ps.len() as f64;
218            (
219                ps.iter().map(|p| p.0).sum::<f64>() / n,
220                ps.iter().map(|p| p.1).sum::<f64>() / n,
221            )
222        };
223        let mut nodes: BTreeMap<usize, (f64, f64)> =
224            self.ends.iter().map(|(&n, ps)| (n, mean(ps))).collect();
225        nodes.extend(self.own.iter().map(|(&n, ps)| (n, mean(ps))));
226        (!nodes.is_empty()).then_some(Layout {
227            id,
228            name,
229            kind,
230            flip_y,
231            nodes,
232            edges: self.routes,
233            ..Default::default()
234        })
235    }
236}
237
238/// Each object's points by class, `(owner, sequence, x, y)`, sorted, and the
239/// owner of each point list: a DiagramObject's or a Location's.
240fn points<'a>(
241    m: &Model<'a>,
242    class: &str,
243    owner_key: &str,
244    x_key: &str,
245    y_key: &str,
246    seq_key: &str,
247) -> FastMap<&'a str, Vec<(f64, f64)>> {
248    let mut by_owner: FastMap<&str, Vec<(i64, &str, f64, f64)>> = FastMap::default();
249    for (&id, els) in &m.objects {
250        if els[0].type_name() != class {
251            continue;
252        }
253        if let (Some(owner), Some(x), Some(y)) = (
254            m.reference(id, owner_key),
255            m.number(id, x_key),
256            m.number(id, y_key),
257        ) {
258            let seq = m.number(id, seq_key).map_or(i64::MAX, |n| n as i64);
259            by_owner.entry(owner).or_default().push((seq, id, x, y));
260        }
261    }
262    by_owner
263        .into_iter()
264        .map(|(owner, mut ps)| {
265            ps.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
266            (owner, ps.into_iter().map(|(_, _, x, y)| (x, y)).collect())
267        })
268        .collect()
269}
270
271/// Whether a diagram's y grows upwards, and its layout's name.
272fn diagram_flip(m: &Model, diagram: &str) -> (bool, String) {
273    let flip_y = m
274        .objects
275        .get(diagram)
276        .and_then(|els| els.iter().find_map(|el| el.get_ref("Diagram.orientation")))
277        .is_some_and(|o| o.ends_with("positive"));
278    (flip_y, format!("Diagram: {}", m.name(diagram)))
279}
280
281/// One layout per DL diagram and per GL coordinate system; and one per DL
282/// diagram for each substation whose items it draws, by node index.
283fn layouts(m: &Model, grid: &Grid) -> (Vec<Layout>, Vec<(usize, Layout)>) {
284    let mut out = Vec::new();
285
286    // DL: each DiagramObject's points, on the object it shows.
287    let diagram_points = points(
288        m,
289        "DiagramObjectPoint",
290        "DiagramObjectPoint.DiagramObject",
291        "DiagramObjectPoint.xPosition",
292        "DiagramObjectPoint.yPosition",
293        "DiagramObjectPoint.sequenceNumber",
294    );
295    let mut diagrams: BTreeMap<&str, Gather> = BTreeMap::new();
296    // (diagram, node) → item → its points.
297    type Items = BTreeMap<usize, Vec<(f64, f64)>>;
298    let mut insides: BTreeMap<(&str, usize), Items> = BTreeMap::new();
299    // (diagram, node) → link → its route: a terminal drawn.
300    let mut wires: BTreeMap<(&str, usize), Items> = BTreeMap::new();
301    let mut objects: Vec<&&str> = diagram_points.keys().collect();
302    objects.sort();
303    for &object in objects {
304        let (Some(diagram), Some(shown)) = (
305            m.reference(object, "DiagramObject.Diagram"),
306            m.reference(object, "DiagramObject.IdentifiedObject"),
307        ) else {
308            continue;
309        };
310        diagrams
311            .entry(diagram)
312            .or_default()
313            .add(grid, shown, diagram_points[object].clone());
314        // An item, in each substation it is drawn in (a line in both of its ends').
315        let ns: Vec<usize> = match grid.placed.get(shown) {
316            Some(&Place::Edge(e)) => vec![grid.edges[e].source, grid.edges[e].target],
317            Some(&Place::Node(n)) => vec![n],
318            None => vec![],
319        };
320        for n in ns {
321            let Some(inside) = grid.inside.get(&n) else {
322                continue;
323            };
324            if let Some(i) = inside.items.iter().position(|it| it.id == shown) {
325                insides
326                    .entry((diagram, n))
327                    .or_default()
328                    .entry(i)
329                    .or_default()
330                    .extend(&diagram_points[object]);
331            } else if let Some(k) = inside.links.iter().position(|l| l.id == shown) {
332                wires
333                    .entry((diagram, n))
334                    .or_default()
335                    .insert(k, diagram_points[object].clone());
336            }
337        }
338    }
339    for (diagram, gather) in diagrams {
340        let (flip_y, name) = diagram_flip(m, diagram);
341        out.extend(gather.layout(format!("dl:{diagram}"), name, "diagram", flip_y));
342    }
343    let mut inside = Vec::new();
344    for ((diagram, n), placed) in insides {
345        if placed.len() < 2 {
346            continue;
347        }
348        let items = &grid.inside[&n].items;
349        let mean = |ps: &[(f64, f64)]| {
350            let k = ps.len() as f64;
351            (
352                ps.iter().map(|p| p.0).sum::<f64>() / k,
353                ps.iter().map(|p| p.1).sum::<f64>() / k,
354            )
355        };
356        let own: Vec<(f64, f64)> = placed
357            .iter()
358            .filter(|(i, _)| items[**i].far.is_empty())
359            .map(|(_, ps)| mean(ps))
360            .collect();
361        let centre = (!own.is_empty()).then(|| mean(&own));
362        let span = own
363            .iter()
364            .flat_map(|a| {
365                own.iter()
366                    .map(move |b| (a.0 - b.0).abs().max((a.1 - b.1).abs()))
367            })
368            .fold(0.0, f64::max);
369        let nodes = placed
370            .iter()
371            .map(|(&i, ps)| {
372                // A line drawn through the substation is at its end here, a
373                // little out along the line, off the node it ends at.
374                let at = match centre {
375                    Some(c) if !items[i].far.is_empty() && ps.len() > 1 => {
376                        let d = |p: (f64, f64)| (p.0 - c.0).hypot(p.1 - c.1);
377                        let (end, next) = if d(ps[0]) <= d(ps[ps.len() - 1]) {
378                            (ps[0], ps[1])
379                        } else {
380                            (ps[ps.len() - 1], ps[ps.len() - 2])
381                        };
382                        let k = (next.0 - end.0).hypot(next.1 - end.1);
383                        if k > 0.0 && span > 0.0 {
384                            let step = (0.06 * span).min(k / 2.0);
385                            (
386                                end.0 + (next.0 - end.0) / k * step,
387                                end.1 + (next.1 - end.1) / k * step,
388                            )
389                        } else {
390                            end
391                        }
392                    }
393                    _ => mean(ps),
394                };
395                (i, at)
396            })
397            .collect();
398        let (flip_y, name) = diagram_flip(m, diagram);
399        let mut layout = Layout {
400            id: format!("dl:{diagram}"),
401            name,
402            kind: "diagram",
403            flip_y,
404            nodes,
405            ..Default::default()
406        };
407        layout.edges = wires.remove(&(diagram, n)).unwrap_or_default();
408        busbars(&grid.inside[&n], &placed, &mut layout);
409        inside.push((n, layout));
410    }
411
412    // GL: each Location's points, on the resources it locates, by coordinate system.
413    let location_points = points(
414        m,
415        "PositionPoint",
416        "PositionPoint.Location",
417        "PositionPoint.xPosition",
418        "PositionPoint.yPosition",
419        "PositionPoint.sequenceNumber",
420    );
421    let mut systems: BTreeMap<String, Gather> = BTreeMap::new();
422    let mut locations: Vec<&&str> = location_points.keys().collect();
423    locations.sort();
424    for &location in locations {
425        let crs = m
426            .reference(location, "Location.CoordinateSystem")
427            .and_then(|c| m.text(c, "CoordinateSystem.crsUrn"))
428            .unwrap_or("urn:ogc:def:crs:EPSG::4326")
429            .to_string();
430        let gather = systems.entry(crs).or_default();
431        let located = m
432            .objects
433            .get(location)
434            .map(|els| {
435                els.iter()
436                    .flat_map(|el| el.get_refs("Location.PowerSystemResources"))
437                    .cloned()
438                    .collect::<Vec<_>>()
439            })
440            .unwrap_or_default();
441        for psr in located {
442            gather.add(grid, mrid_of(&psr), location_points[location].clone());
443        }
444    }
445    for (crs, gather) in systems {
446        let short = crs.rsplit(':').next().unwrap_or(&crs).to_string();
447        out.extend(gather.layout(
448            format!("gl:{crs}"),
449            format!("Geographic (EPSG:{short})"),
450            "geographic",
451            false,
452        ));
453    }
454    (out, inside)
455}
456
457/// A substation's diagram drawn as its single-line diagram is: to the
458/// scale that sets its items a row apart (half its wires, else its links
459/// from item to junction, are shorter); a bus drawn as a line a busbar of
460/// that length, a busbar section not drawn itself that bar, its junction at
461/// the bar's end; any other junction drawn as a line, a line as thin as a
462/// wire (a diagram may draw every junction as one).
463fn busbars(inside: &Inside, placed: &BTreeMap<usize, Vec<(f64, f64)>>, layout: &mut Layout) {
464    // The wires drawn, else from item to junction.
465    let wires: Vec<f64> = layout
466        .edges
467        .values()
468        .map(|ps| {
469            ps.windows(2)
470                .map(|w| (w[0].0 - w[1].0).hypot(w[0].1 - w[1].1))
471                .sum()
472        })
473        .collect();
474    let ends = || {
475        inside
476            .links
477            .iter()
478            .filter_map(|l| Some((layout.nodes.get(&l.item)?, layout.nodes.get(&l.junction)?)))
479            .map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1))
480            .collect::<Vec<f64>>()
481    };
482    let mut lengths: Vec<f64> = if wires.iter().any(|&d| d > 1e-9) {
483        wires
484    } else {
485        ends()
486    };
487    lengths.retain(|&d| d > 1e-9);
488    if lengths.is_empty() {
489        return;
490    }
491    lengths.sort_by(f64::total_cmp);
492    let typical = lengths[lengths.len() / 2];
493    let unit = crate::single_line::ROW / typical;
494    layout.unit = Some(unit);
495    let bus = crate::single_line::buses(inside);
496    for (&j, ps) in placed {
497        if !inside.items[j].junction || ps.len() < 2 {
498            continue;
499        }
500        let (x0, x1) = ps
501            .iter()
502            .fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));
503        let (y0, y1) = ps
504            .iter()
505            .fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));
506        let (w, h) = (x1 - x0, y1 - y0);
507        if w.max(h) < 1e-9 || !bus[j] && w.max(h) < typical {
508            continue;
509        }
510        let thick = if bus[j] {
511            crate::single_line::BAR
512        } else {
513            crate::single_line::WIRE
514        } / unit;
515        let (size, end) = if w >= h {
516            ((w, thick), (x1, (y0 + y1) / 2.0))
517        } else {
518            ((thick, h), ((x0 + x1) / 2.0, y1))
519        };
520        let centre = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
521        let sections: Vec<usize> = inside
522            .links
523            .iter()
524            .filter(|l| {
525                bus[j]
526                    && l.junction == j
527                    && inside.items[l.item].class == "BusbarSection"
528                    && !placed.contains_key(&l.item)
529            })
530            .map(|l| l.item)
531            .collect();
532        if sections.is_empty() {
533            layout.nodes.insert(j, centre);
534            layout.sizes.insert(j, size);
535        } else {
536            for s in sections {
537                layout.nodes.insert(s, centre);
538                layout.sizes.insert(s, size);
539            }
540            layout.nodes.insert(j, end);
541        }
542    }
543}
544
545/// The set's files read as one model: each object's elements, the defining
546/// one first.
547pub struct Model<'a> {
548    pub(crate) objects: FastMap<&'a str, Vec<&'a Element>>,
549    /// ConductingEquipment → its terminals, by sequence number.
550    pub(crate) terminals: FastMap<&'a str, Vec<&'a str>>,
551}
552
553impl<'a> Model<'a> {
554    pub fn new(datasets: &'a [CimDataset]) -> Self {
555        let mut objects: FastMap<&str, Vec<&Element>> = FastMap::default();
556        for ds in datasets {
557            for (mrid, el) in &ds.entries {
558                let els = objects.entry(mrid.as_str()).or_default();
559                if el.defined() {
560                    els.insert(0, el)
561                } else {
562                    els.push(el)
563                }
564            }
565        }
566        let mut model = Self {
567            objects,
568            terminals: FastMap::default(),
569        };
570        let mut terminals: FastMap<&str, Vec<(i64, &str)>> = FastMap::default();
571        for (&mrid, els) in &model.objects {
572            if els[0].type_name() != "Terminal" {
573                continue;
574            }
575            if let Some(ce) = model.reference(mrid, "Terminal.ConductingEquipment") {
576                let seq = model
577                    .number(mrid, "ACDCTerminal.sequenceNumber")
578                    .map_or(i64::MAX, |n| n as i64);
579                terminals.entry(ce).or_default().push((seq, mrid));
580            }
581        }
582        model.terminals = terminals
583            .into_iter()
584            .map(|(ce, mut ts)| {
585                ts.sort();
586                (ce, ts.into_iter().map(|(_, t)| t).collect())
587            })
588            .collect();
589        model
590    }
591
592    pub(crate) fn class(&self, mrid: &str) -> Option<&'static str> {
593        self.objects.get(mrid).map(|els| els[0].type_name())
594    }
595
596    pub(crate) fn text(&self, mrid: &str, key: &str) -> Option<&'a str> {
597        self.objects
598            .get(mrid)?
599            .iter()
600            .find_map(|el| el.get_str(key))
601    }
602
603    pub(crate) fn number(&self, mrid: &str, key: &str) -> Option<f64> {
604        self.text(mrid, key)?.trim().parse().ok()
605    }
606
607    fn flag(&self, mrid: &str, key: &str) -> Option<bool> {
608        self.text(mrid, key).map(|t| t.trim() == "true")
609    }
610
611    /// The voltage level a container (VoltageLevel, Bay) is, or is in.
612    pub(crate) fn voltage_level(&self, container: &'a str) -> Option<&'a str> {
613        match self.class(container)? {
614            "VoltageLevel" => Some(container),
615            "Bay" => self.reference(container, "Bay.VoltageLevel"),
616            _ => None,
617        }
618    }
619
620    /// A terminal's connectivity node, else its topological node.
621    fn terminal_node(&self, terminal: &str) -> Option<&'a str> {
622        self.reference(terminal, "Terminal.ConnectivityNode")
623            .or_else(|| self.reference(terminal, "Terminal.TopologicalNode"))
624    }
625
626    /// The mRID a field refers to, whether or not the set has that object.
627    pub(crate) fn target(&self, mrid: &str, key: &str) -> Option<&'a str> {
628        self.objects
629            .get(mrid)?
630            .iter()
631            .find_map(|el| el.get_ref(key))
632            .map(mrid_of)
633    }
634
635    /// The object a field refers to, if it is in the set.
636    pub(crate) fn reference(&self, mrid: &str, key: &str) -> Option<&'a str> {
637        let target = self
638            .objects
639            .get(mrid)?
640            .iter()
641            .find_map(|el| el.get_ref(key))?;
642        self.objects.get_key_value(mrid_of(target)).map(|(k, _)| *k)
643    }
644
645    fn name(&self, mrid: &str) -> String {
646        self.text(mrid, "IdentifiedObject.name")
647            .filter(|n| !n.is_empty())
648            .unwrap_or(mrid)
649            .to_string()
650    }
651
652    /// The substation a container (VoltageLevel, Bay, Substation) is in.
653    fn substation(&self, container: &'a str) -> Option<&'a str> {
654        let mut at = container;
655        for _ in 0..4 {
656            at = match self.class(at)? {
657                "Substation" => return Some(at),
658                "VoltageLevel" => self.reference(at, "VoltageLevel.Substation")?,
659                "Bay" => self.reference(at, "Bay.VoltageLevel")?,
660                _ => return None,
661            };
662        }
663        None
664    }
665
666    /// The node of a terminal: its connectivity (else topological) node's
667    /// substation, else that node itself, a boundary point.
668    fn terminal_end(&self, terminal: &'a str) -> Option<(&'a str, bool)> {
669        let node = self.terminal_node(terminal)?;
670        match self.node_container(node).and_then(|c| self.substation(c)) {
671            Some(sub) => Some((sub, false)),
672            None => Some((node, true)),
673        }
674    }
675
676    pub(crate) fn node_container(&self, node: &str) -> Option<&'a str> {
677        self.reference(node, "ConnectivityNode.ConnectivityNodeContainer")
678            .or_else(|| self.reference(node, "TopologicalNode.ConnectivityNodeContainer"))
679    }
680}
681
682/// The grid of a model set's files.
683pub fn build(m: &Model<'_>) -> Grid {
684    let mut grid = Grid::default();
685    let mut node_of: FastMap<&str, usize> = FastMap::default();
686
687    let mut subs: Vec<&str> = m
688        .objects
689        .keys()
690        .copied()
691        .filter(|k| m.class(k) == Some("Substation"))
692        .collect();
693    subs.sort_by_key(|s| (m.name(s), *s));
694    for sub in subs {
695        node_of.insert(sub, grid.nodes.len());
696        let region = m.reference(sub, "Substation.Region").map(|r| m.name(r));
697        grid.nodes.push(Node {
698            id: sub.into(),
699            label: m.name(sub),
700            kind: "Substation",
701            region,
702            ..Default::default()
703        });
704    }
705
706    // Equipment whose terminals reach two different nodes is an edge. Inside
707    // a substation, each terminal ending there links its equipment to its node.
708    let mut items: FastMap<(usize, &str), usize> = FastMap::default();
709    let mut groups: FastMap<(usize, &str), usize> = FastMap::default();
710    let mut equipment: Vec<&str> = m.terminals.keys().copied().collect();
711    equipment.sort();
712    for ce in equipment {
713        let terminals = &m.terminals[ce];
714        let ends: Vec<Option<(&str, bool)>> = terminals.iter().map(|t| m.terminal_end(t)).collect();
715        let mut distinct: Vec<(&str, bool)> = Vec::new();
716        for &end in ends.iter().flatten() {
717            if !distinct.iter().any(|e| e.0 == end.0) {
718                distinct.push(end);
719            }
720        }
721        if distinct.len() >= 2 {
722            let source = node_for(m, &mut grid, &mut node_of, distinct[0]);
723            for &end in &distinct[1..] {
724                let target = node_for(m, &mut grid, &mut node_of, end);
725                let kv = m
726                    .reference(ce, "ConductingEquipment.BaseVoltage")
727                    .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
728                let id = if distinct.len() == 2 {
729                    ce.to_string()
730                } else {
731                    format!("{ce}#{}", grid.edges.len())
732                };
733                grid.placed
734                    .insert(ce.to_string(), Place::Edge(grid.edges.len()));
735                grid.edges.push(Edge {
736                    id,
737                    label: m.name(ce),
738                    class: m.class(ce).unwrap_or(""),
739                    source,
740                    target,
741                    kv,
742                    findings: Counts::default(),
743                });
744            }
745        }
746        let reached: Vec<usize> = distinct
747            .iter()
748            .filter_map(|e| node_of.get(e.0).copied())
749            .collect();
750        for (t, end) in terminals.iter().zip(&ends) {
751            let (Some(&n), Some(node)) = (end.and_then(|e| node_of.get(e.0)), m.terminal_node(t))
752            else {
753                continue;
754            };
755            if grid.nodes[n].kind != "Substation" {
756                continue;
757            }
758            let far: Vec<usize> = reached.iter().copied().filter(|&r| r != n).collect();
759            let item = item_for(m, &mut grid, &mut items, &mut groups, n, ce, false, far);
760            let junction = item_for(m, &mut grid, &mut items, &mut groups, n, node, true, vec![]);
761            grid.inside.entry(n).or_default().links.push(Link {
762                id: t.to_string(),
763                label: m.name(t),
764                item,
765                junction,
766                connected: m.flag(t, "ACDCTerminal.connected"),
767            });
768        }
769    }
770
771    // Every other object goes where its container, equipment or node is.
772    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
773    ids.sort();
774    let mut within = FastMap::default();
775    for id in ids {
776        if let Some(Place::Node(n)) =
777            place(m, &node_of, &items, &mut grid.placed, &mut within, id, 0)
778            && let Some(container) = m.reference(id, "Equipment.EquipmentContainer")
779            && m.substation(container).is_some()
780        {
781            *grid.nodes[n]
782                .equipment
783                .entry(m.class(id).unwrap_or(""))
784                .or_default() += 1;
785        }
786    }
787    grid.within = within;
788    for (&vl, els) in &m.objects {
789        if els[0].type_name() != "VoltageLevel" {
790            continue;
791        }
792        if let Some(Place::Node(n)) = grid.placed.get(vl)
793            && let Some(kv) = m
794                .reference(vl, "VoltageLevel.BaseVoltage")
795                .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"))
796        {
797            grid.nodes[*n].kv.push(kv);
798        }
799    }
800    for node in &mut grid.nodes {
801        node.kv.sort_by(|a, b| b.total_cmp(a));
802        node.kv.dedup();
803    }
804
805    let (layouts, inside) = layouts(m, &grid);
806    grid.layouts = layouts;
807    if !grid.nodes.is_empty() {
808        let edges: Vec<(usize, usize)> = grid.edges.iter().map(|e| (e.source, e.target)).collect();
809        let pos = crate::layout::force(grid.nodes.len(), &edges);
810        // Drawn as a schematic: lines along axes and diagonals only, side by side where they share a stretch.
811        let s = crate::schematic::octilinear(&pos, &edges);
812        grid.auto = Some(Layout {
813            id: "auto".into(),
814            name: "Automatic".into(),
815            kind: "diagram",
816            nodes: s.nodes.into_iter().enumerate().collect(),
817            edges: s
818                .routes
819                .into_iter()
820                .enumerate()
821                .filter(|(_, r)| !r.is_empty())
822                .collect(),
823            tracks: s
824                .tracks
825                .into_iter()
826                .enumerate()
827                .filter(|(_, t)| *t != 0)
828                .collect(),
829            ..Default::default()
830        });
831    }
832    for (n, l) in inside {
833        grid.inside.get_mut(&n).unwrap().layouts.push(l);
834    }
835    grid
836}
837
838/// The item for `id` inside node `n`'s substation, added on first use, with
839/// its voltage level.
840#[allow(clippy::too_many_arguments)]
841fn item_for<'a>(
842    m: &Model<'a>,
843    grid: &mut Grid,
844    items: &mut FastMap<(usize, &'a str), usize>,
845    groups: &mut FastMap<(usize, &'a str), usize>,
846    n: usize,
847    id: &'a str,
848    junction: bool,
849    far: Vec<usize>,
850) -> usize {
851    if let Some(&i) = items.get(&(n, id)) {
852        return i;
853    }
854    let container = if junction {
855        m.node_container(id)
856    } else {
857        m.reference(id, "Equipment.EquipmentContainer")
858    };
859    let vl = container
860        .and_then(|c| m.voltage_level(c))
861        .filter(|vl| m.substation(vl) == Some(grid.nodes[n].id.as_str()));
862    let inside = grid.inside.entry(n).or_default();
863    let group = vl.map(|vl| {
864        *groups.entry((n, vl)).or_insert_with(|| {
865            let kv = m
866                .reference(vl, "VoltageLevel.BaseVoltage")
867                .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
868            inside.groups.push(Group {
869                id: vl.into(),
870                label: m.name(vl),
871                kv,
872            });
873            inside.groups.len() - 1
874        })
875    });
876    let class = m.class(id).unwrap_or("");
877    let switch = !junction
878        && (m.text(id, "Switch.open").is_some() || m.text(id, "Switch.normalOpen").is_some());
879    inside.items.push(Item {
880        id: id.into(),
881        label: m.name(id),
882        class,
883        junction,
884        group,
885        open: if switch {
886            m.flag(id, "Switch.open")
887                .or_else(|| m.flag(id, "Switch.normalOpen"))
888        } else {
889            None
890        },
891        in_service: if junction {
892            None
893        } else {
894            m.flag(id, "Equipment.inService")
895        },
896        far,
897        findings: Counts::default(),
898    });
899    items.insert((n, id), inside.items.len() - 1);
900    inside.items.len() - 1
901}
902
903/// The node of an edge's end, added on first use: a substation, or a
904/// boundary point.
905fn node_for<'a>(
906    m: &Model<'a>,
907    grid: &mut Grid,
908    node_of: &mut FastMap<&'a str, usize>,
909    (id, boundary): (&'a str, bool),
910) -> usize {
911    *node_of.entry(id).or_insert_with(|| {
912        grid.nodes.push(Node {
913            id: id.into(),
914            // An IGM often only refers to a boundary point the boundary set names.
915            label: m
916                .text(id, "IdentifiedObject.name")
917                .unwrap_or_default()
918                .to_string(),
919            kind: if boundary {
920                m.class(id).unwrap_or("ConnectivityNode")
921            } else {
922                "Substation"
923            },
924            ..Default::default()
925        });
926        grid.nodes.len() - 1
927    })
928}
929
930/// Where `id` belongs, memoised in `placed`: a container's substation, a
931/// terminal's equipment, a node's substation, else the first referenced
932/// object that has a place. On a substation's node, also the item `id`
933/// stands for there, memoised in `within`: an item itself, else that of the
934/// object it takes its place from.
935#[allow(clippy::too_many_arguments)]
936fn place<'a>(
937    m: &Model<'a>,
938    node_of: &FastMap<&str, usize>,
939    items: &FastMap<(usize, &'a str), usize>,
940    placed: &mut FastMap<String, Place>,
941    within: &mut FastMap<String, (usize, usize)>,
942    id: &'a str,
943    depth: u8,
944) -> Option<Place> {
945    if let Some(p) = placed.get(id) {
946        return Some(*p);
947    }
948    if depth > 3 {
949        return None;
950    }
951    let class = m.class(id)?;
952    let mut via = None;
953    let direct = match class {
954        "Substation" | "VoltageLevel" | "Bay" => m
955            .substation(id)
956            .and_then(|s| node_of.get(s))
957            .map(|&n| Place::Node(n)),
958        "ConnectivityNode" | "TopologicalNode" => match node_of.get(id) {
959            Some(&n) => Some(Place::Node(n)),
960            None => {
961                let key = if class == "ConnectivityNode" {
962                    "ConnectivityNode.ConnectivityNodeContainer"
963                } else {
964                    "TopologicalNode.ConnectivityNodeContainer"
965                };
966                m.reference(id, key)
967                    .and_then(|c| m.substation(c))
968                    .and_then(|s| node_of.get(s))
969                    .map(|&n| Place::Node(n))
970            }
971        },
972        "Terminal" => m
973            .reference(id, "Terminal.ConductingEquipment")
974            .and_then(|ce| {
975                via = Some(ce);
976                place(m, node_of, items, placed, within, ce, depth + 1)
977            }),
978        _ => m
979            .reference(id, "Equipment.EquipmentContainer")
980            .and_then(|c| m.substation(c))
981            .and_then(|s| node_of.get(s))
982            .map(|&n| Place::Node(n)),
983    };
984    let found = match direct {
985        Some(p) => p,
986        None => {
987            // Limits, tap changers, regulating controls, state variables, …:
988            // where what they refer to is.
989            let els = m.objects.get(id)?;
990            let mut keys: Vec<&str> = els
991                .iter()
992                .flat_map(|el| el.fields().keys().copied())
993                .collect();
994            keys.sort();
995            keys.dedup();
996            let (r, p) = keys
997                .into_iter()
998                .filter(|k| !k.ends_with(".BaseVoltage") && !k.ends_with(".Region"))
999                .find_map(|k| {
1000                    let r = m.reference(id, k).filter(|r| *r != id)?;
1001                    place(m, node_of, items, placed, within, r, depth + 1).map(|p| (r, p))
1002                })?;
1003            via = Some(r);
1004            p
1005        }
1006    };
1007    placed.insert(id.to_string(), found);
1008    if let Place::Node(n) = found
1009        && let Some(w) = items.get(&(n, id)).map(|&i| (n, i)).or_else(|| {
1010            via.and_then(|r| within.get(r).copied())
1011                .filter(|w| w.0 == n)
1012        })
1013    {
1014        within.insert(id.to_string(), w);
1015    }
1016    Some(found)
1017}
1018
1019impl Grid {
1020    /// Count each finding on its object's node or edge.
1021    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
1022        for (_, v) in violations {
1023            match self.placed.get(v.object_id.as_str()) {
1024                Some(Place::Node(n)) => {
1025                    self.nodes[*n].findings.add(&v.severity);
1026                    if let Some(inside) = self.inside.get_mut(n) {
1027                        match self.within.get(v.object_id.as_str()) {
1028                            Some(&(_, i)) => inside.items[i].findings.add(&v.severity),
1029                            None => inside.findings.add(&v.severity),
1030                        }
1031                    }
1032                }
1033                Some(Place::Edge(e)) => self.edges[*e].findings.add(&v.severity),
1034                None => self.elsewhere.add(&v.severity),
1035            }
1036        }
1037    }
1038
1039    /// Where the view shows object `id`: `select`, the node or edge it is
1040    /// on, else the item it stands for inside `enter`, its substation; and
1041    /// `inside`, a substation's own id. `None` if it is on neither.
1042    pub fn reveal(&self, id: &str) -> Option<Value> {
1043        match *self.placed.get(id)? {
1044            Place::Edge(e) => Some(json!({ "select": format!("e:{}", self.edges[e].id) })),
1045            Place::Node(n) => {
1046                let node = &self.nodes[n];
1047                if node.kind != "Substation" || node.id == id {
1048                    let inside = (node.kind == "Substation").then_some(&node.id);
1049                    return Some(json!({ "select": node.id, "inside": inside }));
1050                }
1051                let item = self
1052                    .within
1053                    .get(id)
1054                    .map(|&(_, i)| &self.inside[&n].items[i].id);
1055                Some(json!({ "enter": node.id, "select": item }))
1056            }
1057        }
1058    }
1059
1060    /// The view's data: nodes and edges, each with where it is written.
1061    pub fn json(&self, set: &impl Locations) -> Value {
1062        let location = |id: &str| set.location(id.split('#').next().unwrap_or(id));
1063        let nodes: Vec<Value> = self
1064            .nodes
1065            .iter()
1066            .map(|n| {
1067                json!({
1068                    "id": n.id, "label": n.label, "kind": n.kind, "region": n.region, "kV": n.kv,
1069                    "equipment": n.equipment, "findings": n.findings.json(), "location": location(&n.id),
1070                })
1071            })
1072            .collect();
1073        let edges: Vec<Value> = self
1074            .edges
1075            .iter()
1076            .map(|e| {
1077                json!({
1078                    "id": e.id, "label": e.label, "class": e.class, "source": self.nodes[e.source].id,
1079                    "target": self.nodes[e.target].id, "kV": e.kv, "findings": e.findings.json(), "location": location(&e.id),
1080                })
1081            })
1082            .collect();
1083        let layout = |l: &Layout| {
1084            let nodes: serde_json::Map<String, Value> = l
1085                .nodes
1086                .iter()
1087                .map(|(&n, &(x, y))| (self.nodes[n].id.clone(), json!([x, y])))
1088                .collect();
1089            let edges: serde_json::Map<String, Value> = l
1090                .edges
1091                .iter()
1092                .map(|(&e, ps)| {
1093                    (
1094                        self.edges[e].id.clone(),
1095                        json!(ps.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>()),
1096                    )
1097                })
1098                .collect();
1099            let mut out = json!({ "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit, "nodes": nodes, "edges": edges });
1100            if !l.tracks.is_empty() {
1101                out["tracks"] = l
1102                    .tracks
1103                    .iter()
1104                    .map(|(&e, &t)| (self.edges[e].id.clone(), json!(t)))
1105                    .collect::<serde_json::Map<_, _>>()
1106                    .into();
1107            }
1108            out
1109        };
1110        json!({
1111            "files": set.files(),
1112            "nodes": nodes, "edges": edges, "elsewhere": self.elsewhere.json(),
1113            "layouts": self.layouts.iter().map(layout).collect::<Vec<_>>(), "auto": self.auto.as_ref().map(layout),
1114        })
1115    }
1116
1117    /// What the substation `id` holds; `None` if no substation of the set
1118    /// has that mRID.
1119    pub fn inside_of(&self, id: &str) -> Option<&Inside> {
1120        let n = self
1121            .nodes
1122            .iter()
1123            .position(|x| x.id == id && x.kind == "Substation")?;
1124        self.inside.get(&n)
1125    }
1126
1127    /// The substation `id`'s layout `layout` (the view's JSON) after its
1128    /// items moved: busbars across what hangs from them, routes anew.
1129    pub fn reroute_json(&self, id: &str, layout: &Value) -> Option<Value> {
1130        let inside = self.inside_of(id)?;
1131        let l = inside.layout_from_json(layout);
1132        let mut moved = crate::single_line::reroute(inside, &l.nodes, &l.sizes);
1133        (moved.id, moved.name) = (l.id, l.name);
1134        Some(inside.layout_json(&moved))
1135    }
1136
1137    /// What the substation `id` holds, for the view's drill-down; `None` if
1138    /// no substation of the set has that mRID.
1139    pub fn inside_json(&self, set: &impl Locations, id: &str) -> Option<Value> {
1140        let n = self
1141            .nodes
1142            .iter()
1143            .position(|x| x.id == id && x.kind == "Substation")?;
1144        let node = &self.nodes[n];
1145        let empty = Inside::default();
1146        let inside = self.inside.get(&n).unwrap_or(&empty);
1147        let location = |id: &str| set.location(id);
1148        let groups: Vec<Value> = inside
1149            .groups
1150            .iter()
1151            .map(|g| json!({ "id": g.id, "label": g.label, "kV": g.kv }))
1152            .collect();
1153        let items: Vec<Value> = inside
1154            .items
1155            .iter()
1156            .map(|it| {
1157                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();
1158                json!({
1159                    "id": it.id, "label": it.label, "class": it.class, "junction": it.junction,
1160                    "group": it.group.map(|g| &inside.groups[g].id), "open": it.open, "inService": it.in_service,
1161                    "far": far, "findings": it.findings.json(), "location": location(&it.id),
1162                })
1163            })
1164            .collect();
1165        let links: Vec<Value> = inside
1166            .links
1167            .iter()
1168            .map(|l| json!({ "id": l.id, "source": inside.items[l.item].id, "target": inside.items[l.junction].id, "connected": l.connected }))
1169            .collect();
1170        let layouts: Vec<Value> = inside
1171            .layouts
1172            .iter()
1173            .map(|l| inside.layout_json(l))
1174            .collect();
1175        // Laid out when asked for: a few substations are opened, of thousands.
1176        let auto = inside.layout_json(&crate::single_line::single_line(inside));
1177        Some(json!({
1178            "id": node.id, "label": node.label, "region": node.region, "kV": node.kv, "findings": inside.findings.json(),
1179            "location": location(&node.id), "groups": groups, "items": items, "links": links, "layouts": layouts, "auto": auto,
1180        }))
1181    }
1182}
1183
1184impl Inside {
1185    /// A layout of its items, as the view takes it: positions and sizes by
1186    /// item, routes by terminal.
1187    pub fn layout_json(&self, l: &Layout) -> Value {
1188        let id_of = |i: &usize| self.items[*i].id.clone();
1189        json!({
1190            "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit,
1191            "nodes": l.nodes.iter().map(|(i, &(x, y))| (id_of(i), json!([x, y]))).collect::<serde_json::Map<_, _>>(),
1192            "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<_, _>>(),
1193            "sizes": l.sizes.iter().map(|(i, &(w, h))| (id_of(i), json!([w, h]))).collect::<serde_json::Map<_, _>>(),
1194        })
1195    }
1196
1197    /// A layout of its items from the view's JSON (as [`Inside::layout_json`]
1198    /// writes it); what names no item or terminal of it is left out.
1199    pub fn layout_from_json(&self, v: &Value) -> Layout {
1200        let item = |id: &str| self.items.iter().position(|it| it.id == id);
1201        let pair = |p: &Value| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?));
1202        let by_item = |key: &str| -> BTreeMap<usize, (f64, f64)> {
1203            v[key]
1204                .as_object()
1205                .into_iter()
1206                .flatten()
1207                .filter_map(|(id, p)| Some((item(id)?, pair(p)?)))
1208                .collect()
1209        };
1210        let edges = v["edges"]
1211            .as_object()
1212            .into_iter()
1213            .flatten()
1214            .filter_map(|(id, ps)| {
1215                let k = self.links.iter().position(|l| &l.id == id)?;
1216                Some((k, ps.as_array()?.iter().filter_map(pair).collect()))
1217            })
1218            .collect();
1219        Layout {
1220            id: v["id"].as_str().unwrap_or("auto").into(),
1221            name: v["name"].as_str().unwrap_or_default().into(),
1222            kind: "diagram",
1223            flip_y: false,
1224            nodes: by_item("nodes"),
1225            edges,
1226            sizes: by_item("sizes"),
1227            unit: v["unit"].as_f64(),
1228            tracks: BTreeMap::new(),
1229        }
1230    }
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235    use std::path::Path;
1236
1237    use crate::testing::{collect, validate};
1238
1239    /// MicroGrid: Belgium's two substations and the Netherlands' one, joined
1240    /// through the boundary's five border nodes; each line an edge.
1241    #[test]
1242    fn micro_grid() {
1243        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
1244            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
1245        let files = collect(&dir);
1246        assert_eq!(
1247            files.len(),
1248            12,
1249            "missing test data — run `git submodule update --init`"
1250        );
1251        let set = validate(&files);
1252        let g = &set.grid;
1253        let mut subs: Vec<&str> = g
1254            .nodes
1255            .iter()
1256            .filter(|n| n.kind == "Substation")
1257            .map(|n| n.label.as_str())
1258            .collect();
1259        subs.sort();
1260        assert_eq!(subs, ["Anvers", "PP_Amsterdam", "PP_Brussels"]);
1261        let mut borders: Vec<&str> = g
1262            .nodes
1263            .iter()
1264            .filter(|n| n.kind == "ConnectivityNode")
1265            .map(|n| n.label.as_str())
1266            .collect();
1267        borders.sort();
1268        assert_eq!(
1269            borders,
1270            [
1271                "Border_AL11",
1272                "Border_GY11",
1273                "Border_MA11",
1274                "Border_ST23",
1275                "Border_ST24"
1276            ]
1277        );
1278        assert_eq!(g.edges.len(), 12);
1279        assert!(g.edges.iter().all(|e| e.class == "ACLineSegment"));
1280
1281        let node = |label: &str| g.nodes.iter().find(|n| n.label == label).unwrap();
1282        let between = |a: &str, b: &str| {
1283            g.edges
1284                .iter()
1285                .filter(|e| {
1286                    let ends = [
1287                        g.nodes[e.source].label.as_str(),
1288                        g.nodes[e.target].label.as_str(),
1289                    ];
1290                    ends.contains(&a) && ends.contains(&b)
1291                })
1292                .count()
1293        };
1294        assert_eq!(between("PP_Brussels", "Anvers"), 2);
1295        assert_eq!(between("PP_Amsterdam", "Border_AL11"), 1);
1296        assert_eq!(between("PP_Brussels", "Border_AL11"), 1);
1297        let brussels = node("PP_Brussels");
1298        assert_eq!(brussels.kv, [380.0, 225.0, 110.0, 21.0, 10.5]);
1299        assert_eq!(brussels.equipment["SynchronousMachine"], 2);
1300        assert_eq!(brussels.region.as_deref(), Some("ELIA-Brussels"));
1301
1302        // Every finding counted once, and each node clicks through to its definition.
1303        let json = g.json(&set);
1304        let total: u64 = json["nodes"]
1305            .as_array()
1306            .unwrap()
1307            .iter()
1308            .chain(json["edges"].as_array().unwrap())
1309            .chain(std::iter::once(&json["elsewhere"]))
1310            .map(|x| {
1311                let f = if x.get("findings").is_some() {
1312                    &x["findings"]
1313                } else {
1314                    x
1315                };
1316                f["violation"].as_u64().unwrap()
1317                    + f["warning"].as_u64().unwrap()
1318                    + f["info"].as_u64().unwrap()
1319            })
1320            .sum();
1321        let datasets: Vec<_> = files
1322            .iter()
1323            .map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
1324            .collect();
1325        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, vec![]);
1326        assert_eq!(
1327            total as usize,
1328            cimvalidation::validate_files(datasets, &cfg).len()
1329        );
1330        let anvers = json["nodes"]
1331            .as_array()
1332            .unwrap()
1333            .iter()
1334            .find(|n| n["label"] == "Anvers")
1335            .unwrap();
1336        assert!(
1337            anvers["location"]["uri"]
1338                .as_str()
1339                .unwrap()
1340                .ends_with("_BE_EQ_001.xml"),
1341            "{anvers}"
1342        );
1343
1344        // The assembled DL diagram and the GL locations place every node and route every line.
1345        let names: Vec<&str> = g.layouts.iter().map(|l| l.name.as_str()).collect();
1346        assert_eq!(names, ["Diagram: Assembled", "Geographic (EPSG:4326)"]);
1347        for l in &g.layouts {
1348            assert_eq!((l.nodes.len(), l.edges.len()), (8, 12), "{}", l.name);
1349        }
1350        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
1351        let (diagram, map) = (&g.layouts[0], &g.layouts[1]);
1352        assert!(!diagram.flip_y);
1353        // Brussels and Anvers left of the border points, Amsterdam right of them.
1354        let x = |label: &str| diagram.nodes[&index(label)].0;
1355        assert!(
1356            x("PP_Brussels") < x("Anvers")
1357                && x("Anvers") < x("Border_AL11")
1358                && x("Border_AL11") < x("PP_Amsterdam")
1359        );
1360        // Brussels in Brussels, from the ends of its lines; Amsterdam north of it.
1361        let (lon, lat) = map.nodes[&index("PP_Brussels")];
1362        assert!(
1363            (lon - 4.30).abs() < 0.01 && (lat - 50.80).abs() < 0.01,
1364            "{lon} {lat}"
1365        );
1366        assert!(map.nodes[&index("PP_Amsterdam")].1 > 52.3);
1367        // A route runs from its source's end, through the line's points.
1368        let line = g.edges.iter().position(|e| e.label == "BE-Line_2").unwrap();
1369        assert_eq!(map.edges[&line].len(), 5);
1370        let (start, source) = (map.edges[&line][0], map.nodes[&g.edges[line].source]);
1371        assert!(
1372            (start.0 - source.0).abs() < 0.01 && (start.1 - source.1).abs() < 0.01,
1373            "{start:?} {source:?}"
1374        );
1375        assert_eq!(json["layouts"][1]["nodes"].as_object().unwrap().len(), 8);
1376    }
1377
1378    /// MicroGrid Type 1, node-breaker: inside a substation, its breakers,
1379    /// busbars and connectivity nodes by voltage level, its lines with their
1380    /// far ends, and its switches' states; placed on the DL diagrams.
1381    #[test]
1382    fn micro_grid_inside() {
1383        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(
1384            "../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGrid-Type1/MicroGrid-Type1-Merged",
1385        );
1386        let mut files = collect(&dir);
1387        assert_eq!(
1388            files.len(),
1389            12,
1390            "missing test data — run `git submodule update --init`"
1391        );
1392        // A finding on a breaker (no normalOpen) and one on a voltage level (no name).
1393        let eq = files
1394            .iter_mut()
1395            .find(|(p, _)| p.to_string_lossy().ends_with("_BE_EQ_1.xml"))
1396            .unwrap();
1397        let mut text = eq.1.to_string();
1398        for written in [
1399            "<cim:Switch.normalOpen>false</cim:Switch.normalOpen>",
1400            "<cim:IdentifiedObject.name>225.0</cim:IdentifiedObject.name>",
1401        ] {
1402            let at = text.find(written).unwrap();
1403            text.replace_range(at..at + written.len(), "");
1404        }
1405        eq.1 = text.into();
1406        let set = validate(&files);
1407        let g = &set.grid;
1408        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
1409
1410        // Each substation's findings are its items' and its own, once each.
1411        let total = |c: &super::Counts| c.violation + c.warning + c.info;
1412        for (n, inside) in &g.inside {
1413            let items: usize = inside.items.iter().map(|it| total(&it.findings)).sum();
1414            assert_eq!(
1415                items + total(&inside.findings),
1416                total(&g.nodes[*n].findings),
1417                "{}",
1418                g.nodes[*n].label
1419            );
1420        }
1421        let breaker = g
1422            .inside
1423            .values()
1424            .flat_map(|i| &i.items)
1425            .find(|it| it.label == "CIRCB-1230992285")
1426            .unwrap();
1427        assert!(breaker.findings.violation > 0, "{:?}", breaker.findings);
1428        let vl = g
1429            .inside
1430            .values()
1431            .find(|i| {
1432                i.groups
1433                    .iter()
1434                    .any(|gr| gr.id.ends_with("69ef0dbd-da79-4eef-a02f-690cb8a28361"))
1435            })
1436            .unwrap();
1437        assert!(total(&vl.findings) > 0, "{:?}", vl.findings);
1438
1439        let anvers = &g.inside[&index("Anvers")];
1440        let count = |class: &str| anvers.items.iter().filter(|it| it.class == class).count();
1441        assert_eq!(
1442            (
1443                count("Breaker"),
1444                count("BusbarSection"),
1445                count("ConnectivityNode"),
1446                count("ACLineSegment")
1447            ),
1448            (4, 3, 6, 4)
1449        );
1450        assert_eq!(
1451            anvers.groups.iter().map(|gr| gr.kv).collect::<Vec<_>>(),
1452            [Some(225.0)]
1453        );
1454        assert_eq!(anvers.links.len(), 19);
1455        // Every link runs from equipment to a junction.
1456        assert!(
1457            anvers
1458                .links
1459                .iter()
1460                .all(|l| !anvers.items[l.item].junction && anvers.items[l.junction].junction)
1461        );
1462        let line = anvers
1463            .items
1464            .iter()
1465            .find(|it| it.label == "BE-Line_2")
1466            .unwrap();
1467        assert_eq!(
1468            (
1469                line.group,
1470                line.far
1471                    .iter()
1472                    .map(|&f| g.nodes[f].label.as_str())
1473                    .collect::<Vec<_>>()
1474            ),
1475            (None, vec!["PP_Brussels"])
1476        );
1477        assert!(
1478            anvers
1479                .items
1480                .iter()
1481                .filter(|it| it.class == "Breaker")
1482                .all(|it| it.open == Some(false))
1483        );
1484
1485        // Amsterdam's bus coupler is open and out of service; its transformers sit between voltage levels.
1486        let amsterdam = &g.inside[&index("PP_Amsterdam")];
1487        let coupler = amsterdam
1488            .items
1489            .iter()
1490            .find(|it| it.label == "busbarcoupler 1")
1491            .unwrap();
1492        assert_eq!(
1493            (coupler.open, coupler.in_service),
1494            (Some(true), Some(false))
1495        );
1496        assert!(
1497            amsterdam
1498                .items
1499                .iter()
1500                .filter(|it| it.class == "PowerTransformer")
1501                .all(|it| it.group.is_none())
1502        );
1503        assert_eq!(amsterdam.groups.len(), 3);
1504
1505        // Both diagrams that draw Anvers place its equipment and nodes.
1506        let names: Vec<&str> = anvers.layouts.iter().map(|l| l.name.as_str()).collect();
1507        assert_eq!(names, ["Diagram: MAS BE", "Diagram: Assembled"]);
1508        assert!(
1509            anvers.layouts.iter().all(|l| l.nodes.len() > 10),
1510            "{:?}",
1511            anvers
1512                .layouts
1513                .iter()
1514                .map(|l| l.nodes.len())
1515                .collect::<Vec<_>>()
1516        );
1517
1518        // MAS BE draws every junction as a line: its busbars as bars (BE-Busbar_2, and the
1519        // sections the couplers join it to), the junctions inside bays as thin as a wire.
1520        let mas = anvers
1521            .layouts
1522            .iter()
1523            .find(|l| l.name == "Diagram: MAS BE")
1524            .unwrap();
1525        let unit = mas.unit.unwrap();
1526        let thickness = |class: &str, label: &str| {
1527            let i = anvers
1528                .items
1529                .iter()
1530                .position(|it| it.class == class && it.label == label)
1531                .unwrap();
1532            mas.sizes
1533                .get(&i)
1534                .map(|&(w, h)| (w.min(h) * unit * 100.0).round() / 100.0)
1535        };
1536        for section in ["BE-Busbar_2", "N1230992411", "N1230992414"] {
1537            assert_eq!(
1538                thickness("BusbarSection", section),
1539                Some(crate::single_line::BAR),
1540                "{section}"
1541            );
1542        }
1543        for node in ["N1230991550", "N1230991529", "Series Compensator"] {
1544            assert_eq!(
1545                thickness("ConnectivityNode", node),
1546                Some(crate::single_line::WIRE),
1547                "{node}"
1548            );
1549        }
1550
1551        let json = g.inside_json(&set, &g.nodes[index("Anvers")].id).unwrap();
1552        assert_eq!(json["items"].as_array().unwrap().len(), 20);
1553        // Its single-line diagram places every item, routes every link and sizes the busbars.
1554        assert_eq!(json["auto"]["nodes"].as_object().unwrap().len(), 20);
1555        assert_eq!(json["auto"]["edges"].as_object().unwrap().len(), 19);
1556        assert_eq!(json["auto"]["sizes"].as_object().unwrap().len(), 3);
1557        assert_eq!(json["auto"]["unit"], 1.0);
1558        assert!(
1559            json["items"][0]["location"]["uri"]
1560                .as_str()
1561                .unwrap()
1562                .ends_with("_BE_EQ_1.xml")
1563        );
1564        assert!(g.inside_json(&set, "no such substation").is_none());
1565    }
1566}