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, BTreeSet};
14
15use cimmodel::base::{FastMap, FastSet};
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    /// The objects with no place, which an edit could give one ([`rebuild`]).
105    unplaced: FastSet<String>,
106}
107
108/// Inside one substation: its equipment and the connectivity nodes (else
109/// topological nodes) their terminals meet at, by voltage level; equipment
110/// reaching other nodes (lines, mostly) as an item with its far ends.
111#[derive(Debug, Default)]
112pub struct Inside {
113    pub groups: Vec<Group>,
114    pub items: Vec<Item>,
115    pub links: Vec<Link>,
116    /// Findings on the substation's node that no item stands for: the
117    /// substation, its voltage levels and bays, …
118    pub findings: Counts,
119    /// Positions from each DL diagram that draws its items, by item index.
120    pub layouts: Vec<Layout>,
121}
122
123/// A voltage level.
124#[derive(Debug, Default)]
125pub struct Group {
126    pub id: String,
127    pub label: String,
128    pub kv: Option<f64>,
129}
130
131#[derive(Debug, Default)]
132pub struct Item {
133    pub id: String,
134    pub label: String,
135    pub class: &'static str,
136    /// A connectivity or topological node, which the item's terminals meet at.
137    pub junction: bool,
138    /// Its voltage level, by index into `groups`.
139    pub group: Option<usize>,
140    /// A switch's state: `Switch.open`, else `Switch.normalOpen`.
141    pub open: Option<bool>,
142    /// `Equipment.inService`.
143    pub in_service: Option<bool>,
144    /// The other nodes the equipment reaches.
145    pub far: Vec<usize>,
146    pub findings: Counts,
147}
148
149/// A terminal: equipment item → junction item.
150#[derive(Debug)]
151pub struct Link {
152    pub id: String,
153    pub label: String,
154    pub item: usize,
155    pub junction: usize,
156    /// `ACDCTerminal.connected`.
157    pub connected: Option<bool>,
158}
159
160/// Positions of nodes and routes of edges, in one diagram (DL) or one
161/// coordinate system (GL), as the data writes them.
162#[derive(Debug, Default)]
163pub struct Layout {
164    pub id: String,
165    pub name: String,
166    /// `diagram` (x right, y as `flip_y` says) or `geographic` (x longitude,
167    /// y latitude, in degrees).
168    pub kind: &'static str,
169    /// A diagram whose y grows upwards (`OrientationKind.positive`).
170    pub flip_y: bool,
171    /// Node index → position.
172    pub nodes: BTreeMap<usize, (f64, f64)>,
173    /// Edge index → its route, from its source's end to its target's.
174    pub edges: BTreeMap<usize, Vec<(f64, f64)>>,
175    /// Node index → its width and height, where the layout sizes it (a
176    /// busbar, as long as the bays it joins).
177    pub sizes: BTreeMap<usize, (f64, f64)>,
178    /// Pixels per unit, where the positions are to be drawn as they are;
179    /// `None`, to be scaled to fit.
180    pub unit: Option<f64>,
181    /// Edge index → how many line spacings aside it runs from its route, to
182    /// the left of its way (negative: right); the views space them in pixels.
183    pub tracks: BTreeMap<usize, i32>,
184}
185
186/// Points gathered for a layout: a node's own, and those it takes from the
187/// ends of its lines when it has none of its own.
188#[derive(Default)]
189struct Gather {
190    own: FastMap<usize, Vec<(f64, f64)>>,
191    ends: FastMap<usize, Vec<(f64, f64)>>,
192    routes: BTreeMap<usize, Vec<(f64, f64)>>,
193}
194
195impl Gather {
196    /// The points of one located object: an edge's route (whose ends also
197    /// locate its nodes), else points on the node it is in.
198    fn add(&mut self, grid: &Grid, object: &str, points: Vec<(f64, f64)>) {
199        if points.is_empty() {
200            return;
201        }
202        match grid.placed.get(object) {
203            Some(&Place::Edge(e)) if grid.edges[e].id == object => {
204                let edge = &grid.edges[e];
205                self.ends.entry(edge.source).or_default().push(points[0]);
206                self.ends
207                    .entry(edge.target)
208                    .or_default()
209                    .push(points[points.len() - 1]);
210                self.routes.insert(e, points);
211            }
212            Some(&Place::Node(n)) => self.own.entry(n).or_default().extend(points),
213            _ => {}
214        }
215    }
216
217    fn layout(self, id: String, name: String, kind: &'static str, flip_y: bool) -> Option<Layout> {
218        let mean = |ps: &[(f64, f64)]| {
219            let n = ps.len() as f64;
220            (
221                ps.iter().map(|p| p.0).sum::<f64>() / n,
222                ps.iter().map(|p| p.1).sum::<f64>() / n,
223            )
224        };
225        let mut nodes: BTreeMap<usize, (f64, f64)> =
226            self.ends.iter().map(|(&n, ps)| (n, mean(ps))).collect();
227        nodes.extend(self.own.iter().map(|(&n, ps)| (n, mean(ps))));
228        (!nodes.is_empty()).then_some(Layout {
229            id,
230            name,
231            kind,
232            flip_y,
233            nodes,
234            edges: self.routes,
235            ..Default::default()
236        })
237    }
238}
239
240/// Each object's points by class, `(owner, sequence, x, y)`, sorted, and the
241/// owner of each point list: a DiagramObject's or a Location's.
242fn points<'a>(
243    m: &Model<'a>,
244    class: &str,
245    owner_key: &str,
246    x_key: &str,
247    y_key: &str,
248    seq_key: &str,
249) -> FastMap<&'a str, Vec<(f64, f64)>> {
250    let mut by_owner: FastMap<&str, Vec<(i64, &str, f64, f64)>> = FastMap::default();
251    for (&id, els) in &m.objects {
252        if els[0].type_name() != class {
253            continue;
254        }
255        if let (Some(owner), Some(x), Some(y)) = (
256            m.reference(id, owner_key),
257            m.number(id, x_key),
258            m.number(id, y_key),
259        ) {
260            let seq = m.number(id, seq_key).map_or(i64::MAX, |n| n as i64);
261            by_owner.entry(owner).or_default().push((seq, id, x, y));
262        }
263    }
264    by_owner
265        .into_iter()
266        .map(|(owner, mut ps)| {
267            ps.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
268            (owner, ps.into_iter().map(|(_, _, x, y)| (x, y)).collect())
269        })
270        .collect()
271}
272
273/// Whether a diagram's y grows upwards, and its layout's name.
274fn diagram_flip(m: &Model, diagram: &str) -> (bool, String) {
275    let flip_y = m
276        .objects
277        .get(diagram)
278        .and_then(|els| els.iter().find_map(|el| el.get_ref("Diagram.orientation")))
279        .is_some_and(|o| o.ends_with("positive"));
280    (flip_y, format!("Diagram: {}", m.name(diagram)))
281}
282
283/// One layout per DL diagram and per GL coordinate system; and one per DL
284/// diagram for each substation whose items it draws, by node index.
285fn layouts(m: &Model, grid: &Grid) -> (Vec<Layout>, Vec<(usize, Layout)>) {
286    let mut out = Vec::new();
287
288    // DL: each DiagramObject's points, on the object it shows.
289    let diagram_points = points(
290        m,
291        "DiagramObjectPoint",
292        "DiagramObjectPoint.DiagramObject",
293        "DiagramObjectPoint.xPosition",
294        "DiagramObjectPoint.yPosition",
295        "DiagramObjectPoint.sequenceNumber",
296    );
297    let mut diagrams: BTreeMap<&str, Gather> = BTreeMap::new();
298    // (diagram, node) → item → its points.
299    type Items = BTreeMap<usize, Vec<(f64, f64)>>;
300    let mut insides: BTreeMap<(&str, usize), Items> = BTreeMap::new();
301    // (diagram, node) → link → its route: a terminal drawn.
302    let mut wires: BTreeMap<(&str, usize), Items> = BTreeMap::new();
303    let mut objects: Vec<&&str> = diagram_points.keys().collect();
304    objects.sort();
305    for &object in objects {
306        let (Some(diagram), Some(shown)) = (
307            m.reference(object, "DiagramObject.Diagram"),
308            m.reference(object, "DiagramObject.IdentifiedObject"),
309        ) else {
310            continue;
311        };
312        diagrams
313            .entry(diagram)
314            .or_default()
315            .add(grid, shown, diagram_points[object].clone());
316        // An item, in each substation it is drawn in (a line in both of its ends').
317        let ns: Vec<usize> = match grid.placed.get(shown) {
318            Some(&Place::Edge(e)) => vec![grid.edges[e].source, grid.edges[e].target],
319            Some(&Place::Node(n)) => vec![n],
320            None => vec![],
321        };
322        for n in ns {
323            let Some(inside) = grid.inside.get(&n) else {
324                continue;
325            };
326            if let Some(i) = inside.items.iter().position(|it| it.id == shown) {
327                insides
328                    .entry((diagram, n))
329                    .or_default()
330                    .entry(i)
331                    .or_default()
332                    .extend(&diagram_points[object]);
333            } else if let Some(k) = inside.links.iter().position(|l| l.id == shown) {
334                wires
335                    .entry((diagram, n))
336                    .or_default()
337                    .insert(k, diagram_points[object].clone());
338            }
339        }
340    }
341    for (diagram, gather) in diagrams {
342        let (flip_y, name) = diagram_flip(m, diagram);
343        out.extend(gather.layout(format!("dl:{diagram}"), name, "diagram", flip_y));
344    }
345    let mut inside = Vec::new();
346    for ((diagram, n), placed) in insides {
347        if placed.len() < 2 {
348            continue;
349        }
350        let items = &grid.inside[&n].items;
351        let mean = |ps: &[(f64, f64)]| {
352            let k = ps.len() as f64;
353            (
354                ps.iter().map(|p| p.0).sum::<f64>() / k,
355                ps.iter().map(|p| p.1).sum::<f64>() / k,
356            )
357        };
358        let own: Vec<(f64, f64)> = placed
359            .iter()
360            .filter(|(i, _)| items[**i].far.is_empty())
361            .map(|(_, ps)| mean(ps))
362            .collect();
363        let centre = (!own.is_empty()).then(|| mean(&own));
364        let span = own
365            .iter()
366            .flat_map(|a| {
367                own.iter()
368                    .map(move |b| (a.0 - b.0).abs().max((a.1 - b.1).abs()))
369            })
370            .fold(0.0, f64::max);
371        let nodes = placed
372            .iter()
373            .map(|(&i, ps)| {
374                // A line drawn through the substation is at its end here, a
375                // little out along the line, off the node it ends at.
376                let at = match centre {
377                    Some(c) if !items[i].far.is_empty() && ps.len() > 1 => {
378                        let d = |p: (f64, f64)| (p.0 - c.0).hypot(p.1 - c.1);
379                        let (end, next) = if d(ps[0]) <= d(ps[ps.len() - 1]) {
380                            (ps[0], ps[1])
381                        } else {
382                            (ps[ps.len() - 1], ps[ps.len() - 2])
383                        };
384                        let k = (next.0 - end.0).hypot(next.1 - end.1);
385                        if k > 0.0 && span > 0.0 {
386                            let step = (0.06 * span).min(k / 2.0);
387                            (
388                                end.0 + (next.0 - end.0) / k * step,
389                                end.1 + (next.1 - end.1) / k * step,
390                            )
391                        } else {
392                            end
393                        }
394                    }
395                    _ => mean(ps),
396                };
397                (i, at)
398            })
399            .collect();
400        let (flip_y, name) = diagram_flip(m, diagram);
401        let mut layout = Layout {
402            id: format!("dl:{diagram}"),
403            name,
404            kind: "diagram",
405            flip_y,
406            nodes,
407            ..Default::default()
408        };
409        layout.edges = wires.remove(&(diagram, n)).unwrap_or_default();
410        busbars(&grid.inside[&n], &placed, &mut layout);
411        inside.push((n, layout));
412    }
413
414    // GL: each Location's points, on the resources it locates, by coordinate system.
415    let location_points = points(
416        m,
417        "PositionPoint",
418        "PositionPoint.Location",
419        "PositionPoint.xPosition",
420        "PositionPoint.yPosition",
421        "PositionPoint.sequenceNumber",
422    );
423    let mut systems: BTreeMap<String, Gather> = BTreeMap::new();
424    let mut locations: Vec<&&str> = location_points.keys().collect();
425    locations.sort();
426    for &location in locations {
427        let crs = m
428            .reference(location, "Location.CoordinateSystem")
429            .and_then(|c| m.text(c, "CoordinateSystem.crsUrn"))
430            .unwrap_or("urn:ogc:def:crs:EPSG::4326")
431            .to_string();
432        let gather = systems.entry(crs).or_default();
433        let located = m
434            .objects
435            .get(location)
436            .map(|els| {
437                els.iter()
438                    .flat_map(|el| el.get_refs("Location.PowerSystemResources"))
439                    .cloned()
440                    .collect::<Vec<_>>()
441            })
442            .unwrap_or_default();
443        for psr in located {
444            gather.add(grid, mrid_of(&psr), location_points[location].clone());
445        }
446    }
447    for (crs, gather) in systems {
448        let short = crs.rsplit(':').next().unwrap_or(&crs).to_string();
449        out.extend(gather.layout(
450            format!("gl:{crs}"),
451            format!("Geographic (EPSG:{short})"),
452            "geographic",
453            false,
454        ));
455    }
456    (out, inside)
457}
458
459/// A substation's diagram drawn as its single-line diagram is: to the
460/// scale that sets its items a row apart (half its wires, else its links
461/// from item to junction, are shorter); a bus drawn as a line a busbar of
462/// that length, a busbar section not drawn itself that bar, its junction at
463/// the bar's end; any other junction drawn as a line, a line as thin as a
464/// wire (a diagram may draw every junction as one).
465fn busbars(inside: &Inside, placed: &BTreeMap<usize, Vec<(f64, f64)>>, layout: &mut Layout) {
466    // The wires drawn, else from item to junction.
467    let wires: Vec<f64> = layout
468        .edges
469        .values()
470        .map(|ps| {
471            ps.windows(2)
472                .map(|w| (w[0].0 - w[1].0).hypot(w[0].1 - w[1].1))
473                .sum()
474        })
475        .collect();
476    let ends = || {
477        inside
478            .links
479            .iter()
480            .filter_map(|l| Some((layout.nodes.get(&l.item)?, layout.nodes.get(&l.junction)?)))
481            .map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1))
482            .collect::<Vec<f64>>()
483    };
484    let mut lengths: Vec<f64> = if wires.iter().any(|&d| d > 1e-9) {
485        wires
486    } else {
487        ends()
488    };
489    lengths.retain(|&d| d > 1e-9);
490    if lengths.is_empty() {
491        return;
492    }
493    lengths.sort_by(f64::total_cmp);
494    let typical = lengths[lengths.len() / 2];
495    let unit = crate::single_line::ROW / typical;
496    layout.unit = Some(unit);
497    let bus = crate::single_line::buses(inside);
498    for (&j, ps) in placed {
499        if !inside.items[j].junction || ps.len() < 2 {
500            continue;
501        }
502        let (x0, x1) = ps
503            .iter()
504            .fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));
505        let (y0, y1) = ps
506            .iter()
507            .fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));
508        let (w, h) = (x1 - x0, y1 - y0);
509        if w.max(h) < 1e-9 || !bus[j] && w.max(h) < typical {
510            continue;
511        }
512        let thick = if bus[j] {
513            crate::single_line::BAR
514        } else {
515            crate::single_line::WIRE
516        } / unit;
517        let (size, end) = if w >= h {
518            ((w, thick), (x1, (y0 + y1) / 2.0))
519        } else {
520            ((thick, h), ((x0 + x1) / 2.0, y1))
521        };
522        let centre = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
523        let sections: Vec<usize> = inside
524            .links
525            .iter()
526            .filter(|l| {
527                bus[j]
528                    && l.junction == j
529                    && inside.items[l.item].class == "BusbarSection"
530                    && !placed.contains_key(&l.item)
531            })
532            .map(|l| l.item)
533            .collect();
534        if sections.is_empty() {
535            layout.nodes.insert(j, centre);
536            layout.sizes.insert(j, size);
537        } else {
538            for s in sections {
539                layout.nodes.insert(s, centre);
540                layout.sizes.insert(s, size);
541            }
542            layout.nodes.insert(j, end);
543        }
544    }
545}
546
547/// The set's files read as one model: each object's elements, the defining
548/// one first.
549pub struct Model<'a> {
550    pub(crate) objects: FastMap<&'a str, Vec<&'a Element>>,
551    /// ConductingEquipment → its terminals, by sequence number.
552    pub(crate) terminals: FastMap<&'a str, Vec<&'a str>>,
553}
554
555impl<'a> Model<'a> {
556    pub fn new(datasets: &'a [CimDataset]) -> Self {
557        let mut objects: FastMap<&str, Vec<&Element>> = FastMap::default();
558        for ds in datasets {
559            for (mrid, el) in &ds.entries {
560                let els = objects.entry(mrid.as_str()).or_default();
561                if el.defined() {
562                    els.insert(0, el)
563                } else {
564                    els.push(el)
565                }
566            }
567        }
568        let mut model = Self {
569            objects,
570            terminals: FastMap::default(),
571        };
572        let mut terminals: FastMap<&str, Vec<(i64, &str)>> = FastMap::default();
573        for (&mrid, els) in &model.objects {
574            if els[0].type_name() != "Terminal" {
575                continue;
576            }
577            if let Some(ce) = model.reference(mrid, "Terminal.ConductingEquipment") {
578                let seq = model
579                    .number(mrid, "ACDCTerminal.sequenceNumber")
580                    .map_or(i64::MAX, |n| n as i64);
581                terminals.entry(ce).or_default().push((seq, mrid));
582            }
583        }
584        model.terminals = terminals
585            .into_iter()
586            .map(|(ce, mut ts)| {
587                ts.sort();
588                (ce, ts.into_iter().map(|(_, t)| t).collect())
589            })
590            .collect();
591        model
592    }
593
594    pub(crate) fn class(&self, mrid: &str) -> Option<&'static str> {
595        self.objects.get(mrid).map(|els| els[0].type_name())
596    }
597
598    pub(crate) fn text(&self, mrid: &str, key: &str) -> Option<&'a str> {
599        self.objects
600            .get(mrid)?
601            .iter()
602            .find_map(|el| el.get_str(key))
603    }
604
605    pub(crate) fn number(&self, mrid: &str, key: &str) -> Option<f64> {
606        self.text(mrid, key)?.trim().parse().ok()
607    }
608
609    fn flag(&self, mrid: &str, key: &str) -> Option<bool> {
610        self.text(mrid, key).map(|t| t.trim() == "true")
611    }
612
613    /// The voltage level a container (VoltageLevel, Bay) is, or is in.
614    pub(crate) fn voltage_level(&self, container: &'a str) -> Option<&'a str> {
615        match self.class(container)? {
616            "VoltageLevel" => Some(container),
617            "Bay" => self.reference(container, "Bay.VoltageLevel"),
618            _ => None,
619        }
620    }
621
622    /// A terminal's connectivity node, else its topological node.
623    fn terminal_node(&self, terminal: &str) -> Option<&'a str> {
624        self.reference(terminal, "Terminal.ConnectivityNode")
625            .or_else(|| self.reference(terminal, "Terminal.TopologicalNode"))
626    }
627
628    /// The mRID a field refers to, whether or not the set has that object.
629    pub(crate) fn target(&self, mrid: &str, key: &str) -> Option<&'a str> {
630        self.objects
631            .get(mrid)?
632            .iter()
633            .find_map(|el| el.get_ref(key))
634            .map(mrid_of)
635    }
636
637    /// The object a field refers to, if it is in the set.
638    pub(crate) fn reference(&self, mrid: &str, key: &str) -> Option<&'a str> {
639        let target = self
640            .objects
641            .get(mrid)?
642            .iter()
643            .find_map(|el| el.get_ref(key))?;
644        self.objects.get_key_value(mrid_of(target)).map(|(k, _)| *k)
645    }
646
647    fn name(&self, mrid: &str) -> String {
648        self.text(mrid, "IdentifiedObject.name")
649            .filter(|n| !n.is_empty())
650            .unwrap_or(mrid)
651            .to_string()
652    }
653
654    /// The substation a container (VoltageLevel, Bay, Substation) is in.
655    fn substation(&self, container: &'a str) -> Option<&'a str> {
656        let mut at = container;
657        for _ in 0..4 {
658            at = match self.class(at)? {
659                "Substation" => return Some(at),
660                "VoltageLevel" => self.reference(at, "VoltageLevel.Substation")?,
661                "Bay" => self.reference(at, "Bay.VoltageLevel")?,
662                _ => return None,
663            };
664        }
665        None
666    }
667
668    /// The node of a terminal: its connectivity (else topological) node's
669    /// substation, else that node itself, a boundary point.
670    fn terminal_end(&self, terminal: &'a str) -> Option<(&'a str, bool)> {
671        let node = self.terminal_node(terminal)?;
672        match self.node_container(node).and_then(|c| self.substation(c)) {
673            Some(sub) => Some((sub, false)),
674            None => Some((node, true)),
675        }
676    }
677
678    pub(crate) fn node_container(&self, node: &str) -> Option<&'a str> {
679        self.reference(node, "ConnectivityNode.ConnectivityNodeContainer")
680            .or_else(|| self.reference(node, "TopologicalNode.ConnectivityNodeContainer"))
681    }
682}
683
684/// The grid of a model set's files.
685pub fn build(m: &Model<'_>) -> Grid {
686    build_like(m, None)
687}
688
689/// [`build`], given the grid built before an edit of the files: its automatic layout kept when the
690/// substations and what joins them are the same, as after an edit inside a substation; else
691/// carried over to the grid now ([`carried`]), so that a substation or a line added or deleted
692/// moves nothing else, and an edit undone gives back the layout before it. Laid out anew, it comes
693/// out the same each time; on RealGrid laying it out takes 0.3 s.
694pub fn build_like(m: &Model<'_>, previous: Option<Grid>) -> Grid {
695    let mut grid = Grid::default();
696    let mut node_of: FastMap<&str, usize> = FastMap::default();
697
698    let mut subs: Vec<&str> = m
699        .objects
700        .keys()
701        .copied()
702        .filter(|k| m.class(k) == Some("Substation"))
703        .collect();
704    subs.sort_by_key(|s| (m.name(s), *s));
705    for sub in subs {
706        node_of.insert(sub, grid.nodes.len());
707        let region = m.reference(sub, "Substation.Region").map(|r| m.name(r));
708        grid.nodes.push(Node {
709            id: sub.into(),
710            label: m.name(sub),
711            kind: "Substation",
712            region,
713            ..Default::default()
714        });
715    }
716
717    // Equipment whose terminals reach two different nodes is an edge. Inside
718    // a substation, each terminal ending there links its equipment to its node.
719    let mut items: FastMap<(usize, &str), usize> = FastMap::default();
720    let mut groups: FastMap<(usize, &str), usize> = FastMap::default();
721    let mut equipment: Vec<&str> = m.terminals.keys().copied().collect();
722    equipment.sort();
723    for ce in equipment {
724        let (ends, distinct) = ends_of(m, ce);
725        if distinct.len() >= 2 {
726            let source = node_for(m, &mut grid, &mut node_of, distinct[0]);
727            for &end in &distinct[1..] {
728                let target = node_for(m, &mut grid, &mut node_of, end);
729                let kv = m
730                    .reference(ce, "ConductingEquipment.BaseVoltage")
731                    .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
732                let id = if distinct.len() == 2 {
733                    ce.to_string()
734                } else {
735                    format!("{ce}#{}", grid.edges.len())
736                };
737                grid.placed
738                    .insert(ce.to_string(), Place::Edge(grid.edges.len()));
739                grid.edges.push(Edge {
740                    id,
741                    label: m.name(ce),
742                    class: m.class(ce).unwrap_or(""),
743                    source,
744                    target,
745                    kv,
746                    findings: Counts::default(),
747                });
748            }
749        }
750        let reached: Vec<usize> = distinct
751            .iter()
752            .filter_map(|e| node_of.get(e.0).copied())
753            .collect();
754        link(
755            m,
756            &mut grid,
757            &mut items,
758            &mut groups,
759            &node_of,
760            ce,
761            &ends,
762            &reached,
763            None,
764        );
765    }
766
767    // Every other object goes where its container, equipment or node is.
768    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
769    ids.sort();
770    let mut within = FastMap::default();
771    for &id in &ids {
772        if let Some(Place::Node(n)) =
773            place(m, &node_of, &items, &mut grid.placed, &mut within, id, 0)
774        {
775            count(m, &mut grid.nodes[n], id);
776        }
777    }
778    grid.within = within;
779    grid.unplaced = ids
780        .iter()
781        .filter(|id| !grid.placed.contains_key(**id))
782        .map(|id| id.to_string())
783        .collect();
784    for (&vl, els) in &m.objects {
785        if els[0].type_name() != "VoltageLevel" {
786            continue;
787        }
788        if let Some(Place::Node(n)) = grid.placed.get(vl) {
789            add_kv(m, &mut grid.nodes[*n], vl);
790        }
791    }
792    for node in &mut grid.nodes {
793        node.kv.sort_by(|a, b| b.total_cmp(a));
794        node.kv.dedup();
795    }
796
797    let (layouts, inside) = layouts(m, &grid);
798    grid.layouts = layouts;
799    let edges: Vec<(usize, usize)> = grid.edges.iter().map(|e| (e.source, e.target)).collect();
800    let same = |p: &Grid| {
801        p.nodes.len() == grid.nodes.len()
802            && p.edges.len() == edges.len()
803            && p.edges
804                .iter()
805                .zip(&edges)
806                .all(|(e, &(s, t))| (e.source, e.target) == (s, t))
807    };
808    grid.auto = match previous {
809        Some(p) if same(&p) && p.auto.is_some() => p.auto,
810        previous => {
811            let carried = previous.and_then(|p| carried(&p, &grid, &edges));
812            match carried {
813                Some(s) => Some(automatic(s)),
814                // Drawn as a schematic: lines along axes and diagonals only, side by side where
815                // they share a stretch.
816                None if !grid.nodes.is_empty() => {
817                    let pos = crate::layout::force(grid.nodes.len(), &edges);
818                    Some(automatic(crate::schematic::octilinear(&pos, &edges)))
819                }
820                None => None,
821            }
822        }
823    };
824    for (n, l) in inside {
825        grid.inside.get_mut(&n).unwrap().layouts.push(l);
826    }
827    grid
828}
829
830/// The automatic layout of schematic `s`.
831fn automatic(s: crate::schematic::Schematic) -> Layout {
832    Layout {
833        id: "auto".into(),
834        name: "Automatic".into(),
835        kind: "diagram",
836        nodes: s.nodes.into_iter().enumerate().collect(),
837        edges: s
838            .routes
839            .into_iter()
840            .enumerate()
841            .filter(|(_, r)| !r.is_empty())
842            .collect(),
843        tracks: s
844            .tracks
845            .into_iter()
846            .enumerate()
847            .filter(|(_, t)| *t != 0)
848            .collect(),
849        ..Default::default()
850    }
851}
852
853/// The automatic layout of `previous` carried over to `grid` ([`crate::schematic::extend`]): each
854/// substation kept where it was, each line kept between the same substations along its route; the
855/// rest placed and routed around them. `None` where `previous` has no automatic layout, or `grid`
856/// keeps less than half of its substations, or is less than half made of them, as another
857/// model's: that is laid out anew.
858fn carried(
859    previous: &Grid,
860    grid: &Grid,
861    edges: &[(usize, usize)],
862) -> Option<crate::schematic::Schematic> {
863    let auto = previous.auto.as_ref()?;
864    let was: FastMap<&str, usize> = previous
865        .nodes
866        .iter()
867        .enumerate()
868        .map(|(i, n)| (n.id.as_str(), i))
869        .collect();
870    let kept: Vec<Option<(f64, f64)>> = grid
871        .nodes
872        .iter()
873        .map(|n| {
874            was.get(n.id.as_str())
875                .and_then(|i| auto.nodes.get(i))
876                .copied()
877        })
878        .collect();
879    let n = kept.iter().flatten().count();
880    if n * 2 < grid.nodes.len() || n * 2 < previous.nodes.len() {
881        return None;
882    }
883    let lines: FastMap<&str, usize> = previous
884        .edges
885        .iter()
886        .enumerate()
887        .map(|(k, e)| (e.id.as_str(), k))
888        .collect();
889    let routes: Vec<Option<crate::schematic::Route>> = grid
890        .edges
891        .iter()
892        .map(|e| {
893            let k = *lines.get(e.id.as_str())?;
894            let p = &previous.edges[k];
895            let ends =
896                |s: usize, t: usize, g: &Grid| (g.nodes[s].id.clone(), g.nodes[t].id.clone());
897            (ends(p.source, p.target, previous) == ends(e.source, e.target, grid)).then_some(())?;
898            Some((
899                auto.edges.get(&k)?.clone(),
900                auto.tracks.get(&k).copied().unwrap_or(0),
901            ))
902        })
903        .collect();
904    Some(crate::schematic::extend(&kept, edges, &routes))
905}
906
907/// [`build_like`] after an edit that touched the objects `touched` (as
908/// [`crate::index::Index::edited`] tells them), given the grid built before it:
909/// that grid brought up to date in the substations those objects were and
910/// are in, the rest kept, where the edit stays inside substations. Else, a
911/// substation or what joins two touched, an object that had no place
912/// touched, or equipment come to join two nodes or no longer, it is built as
913/// [`build_like`] builds it. Either way, the grid [`build`] gives, with no
914/// findings yet; but an object that referred to one the files did not hold
915/// keeps its place when that one is added, until a grid is built anew. On
916/// RealGrid an edit inside a substation takes some 13 ms, where a build
917/// takes 0.65 s.
918pub fn rebuild(m: &Model<'_>, mut previous: Grid, touched: &BTreeSet<String>) -> Grid {
919    if update(m, &mut previous, touched).is_some() {
920        previous
921    } else {
922        build_like(m, Some(previous))
923    }
924}
925
926/// [`rebuild`]'s update of `grid` in place, `None` where it cannot be: then
927/// only its nodes, edges and automatic layout are as they were.
928pub(crate) fn update(m: &Model<'_>, grid: &mut Grid, touched: &BTreeSet<String>) -> Option<()> {
929    let mut node_of: FastMap<&str, usize> = FastMap::default();
930    for (i, n) in grid.nodes.iter().enumerate() {
931        let (&id, _) = m.objects.get_key_value(n.id.as_str())?;
932        node_of.insert(id, i);
933    }
934    let substation = |grid: &Grid, n: usize| grid.nodes[n].kind == "Substation";
935
936    // The substations the edit is in: where each touched object was and is
937    // (found without what is kept, so not in it), and those whose items or
938    // terminals it touched.
939    let mut at: BTreeSet<usize> = BTreeSet::new();
940    let (mut scratch, mut scratch_within) = (FastMap::default(), FastMap::default());
941    let none = FastMap::default();
942    for t in touched {
943        if node_of.contains_key(t.as_str())
944            || m.class(t) == Some("Substation")
945            || grid.unplaced.contains(t)
946        {
947            return None;
948        }
949        let was = grid.placed.get(t.as_str()).copied();
950        let is = m.objects.get_key_value(t.as_str()).and_then(|(&id, _)| {
951            place(m, &node_of, &none, &mut scratch, &mut scratch_within, id, 0)
952        });
953        for p in [was, is].into_iter().flatten() {
954            match p {
955                Place::Node(n) if substation(grid, n) => at.insert(n),
956                _ => return None,
957            };
958        }
959    }
960    for (&n, inside) in &grid.inside {
961        if inside.items.iter().any(|i| touched.contains(&i.id))
962            || inside.links.iter().any(|l| touched.contains(&l.id))
963        {
964            at.insert(n);
965        }
966    }
967
968    // The equipment with a terminal in them, before or now: each still
969    // joining the nodes it joined, or none.
970    let mut equipment: BTreeSet<&str> = BTreeSet::new();
971    for n in &at {
972        for item in grid.inside.get(n).map_or(&[][..], |i| &i.items[..]) {
973            if let Some((&ce, _)) = m.terminals.get_key_value(item.id.as_str())
974                && !item.junction
975            {
976                equipment.insert(ce);
977            }
978        }
979    }
980    for t in touched {
981        if let Some((&ce, _)) = m.terminals.get_key_value(t.as_str()) {
982            equipment.insert(ce);
983        }
984        if let Some(ce) = m.reference(t, "Terminal.ConductingEquipment")
985            && let Some((&ce, _)) = m.terminals.get_key_value(ce)
986        {
987            equipment.insert(ce);
988        }
989    }
990    let mut linked = Vec::new();
991    for &ce in &equipment {
992        let (ends, distinct) = ends_of(m, ce);
993        let edge = match grid.placed.get(ce) {
994            Some(&Place::Edge(e)) => Some(&grid.edges[e]),
995            _ => None,
996        };
997        let reached: Vec<usize> = if distinct.len() >= 2 {
998            let reached: Vec<usize> = distinct
999                .iter()
1000                .map(|e| node_of.get(e.0).copied())
1001                .collect::<Option<_>>()?;
1002            match edge {
1003                Some(e) if reached == [e.source, e.target] => reached,
1004                _ => return None,
1005            }
1006        } else {
1007            let reached: Vec<usize> = distinct
1008                .iter()
1009                .filter_map(|e| node_of.get(e.0).copied())
1010                .collect();
1011            if edge.is_some()
1012                || reached
1013                    .iter()
1014                    .any(|&n| substation(grid, n) && !at.contains(&n))
1015            {
1016                return None;
1017            }
1018            reached
1019        };
1020        linked.push((ce, ends, reached));
1021    }
1022
1023    // Their insides anew, in the order a build makes them.
1024    for n in &at {
1025        grid.inside.remove(n);
1026    }
1027    let (mut items, mut groups) = (FastMap::default(), FastMap::default());
1028    for (ce, ends, reached) in &linked {
1029        link(
1030            m,
1031            grid,
1032            &mut items,
1033            &mut groups,
1034            &node_of,
1035            ce,
1036            ends,
1037            reached,
1038            Some(&at),
1039        );
1040    }
1041
1042    // What was in them, and what the edit touched, placed again.
1043    let mut again: BTreeSet<&str> = BTreeSet::new();
1044    let mut gone: Vec<String> = Vec::new();
1045    for (id, p) in &grid.placed {
1046        if matches!(p, Place::Node(n) if at.contains(n)) {
1047            match m.objects.get_key_value(id.as_str()) {
1048                Some((&id, _)) => again.insert(id),
1049                None => {
1050                    gone.push(id.clone());
1051                    false
1052                }
1053            };
1054        }
1055    }
1056    for t in touched {
1057        if let Some((&id, _)) = m.objects.get_key_value(t.as_str()) {
1058            again.insert(id);
1059        } else {
1060            gone.push(t.clone());
1061        }
1062    }
1063    for id in again.iter().copied().chain(gone.iter().map(String::as_str)) {
1064        grid.placed.remove(id);
1065        grid.within.remove(id);
1066        grid.unplaced.remove(id);
1067    }
1068    for &n in &at {
1069        grid.nodes[n].equipment.clear();
1070        grid.nodes[n].kv.clear();
1071    }
1072    let mut within = std::mem::take(&mut grid.within);
1073    for &id in &again {
1074        match place(m, &node_of, &items, &mut grid.placed, &mut within, id, 0) {
1075            Some(Place::Node(n)) if at.contains(&n) => {
1076                count(m, &mut grid.nodes[n], id);
1077                if m.class(id) == Some("VoltageLevel") {
1078                    add_kv(m, &mut grid.nodes[n], id);
1079                }
1080            }
1081            None => {
1082                grid.unplaced.insert(id.to_string());
1083            }
1084            _ => return None,
1085        }
1086    }
1087    grid.within = within;
1088    for &n in &at {
1089        let node = &mut grid.nodes[n];
1090        node.kv.sort_by(|a, b| b.total_cmp(a));
1091        node.kv.dedup();
1092    }
1093
1094    // The layouts read again (some ms on RealGrid), the findings gone.
1095    let (layouts, inside) = layouts(m, grid);
1096    grid.layouts = layouts;
1097    for i in grid.inside.values_mut() {
1098        i.layouts.clear();
1099        i.findings = Counts::default();
1100        for item in &mut i.items {
1101            item.findings = Counts::default();
1102        }
1103    }
1104    for (n, l) in inside {
1105        grid.inside.get_mut(&n).unwrap().layouts.push(l);
1106    }
1107    for node in &mut grid.nodes {
1108        node.findings = Counts::default();
1109    }
1110    for edge in &mut grid.edges {
1111        edge.findings = Counts::default();
1112    }
1113    grid.elsewhere = Counts::default();
1114    Some(())
1115}
1116
1117/// The end of each of `ce`'s terminals, and the distinct ends, in order.
1118#[allow(clippy::type_complexity)]
1119fn ends_of<'a>(m: &Model<'a>, ce: &str) -> (Vec<Option<(&'a str, bool)>>, Vec<(&'a str, bool)>) {
1120    let ends: Vec<Option<(&str, bool)>> =
1121        m.terminals[ce].iter().map(|t| m.terminal_end(t)).collect();
1122    let mut distinct: Vec<(&str, bool)> = Vec::new();
1123    for &end in ends.iter().flatten() {
1124        if !distinct.iter().any(|e| e.0 == end.0) {
1125            distinct.push(end);
1126        }
1127    }
1128    (ends, distinct)
1129}
1130
1131/// Inside each substation one of `ce`'s terminals ends at (of `only`, if
1132/// given), the equipment's item, the item of the node it meets there, and
1133/// the terminal between them.
1134#[allow(clippy::too_many_arguments)]
1135fn link<'a>(
1136    m: &Model<'a>,
1137    grid: &mut Grid,
1138    items: &mut FastMap<(usize, &'a str), usize>,
1139    groups: &mut FastMap<(usize, &'a str), usize>,
1140    node_of: &FastMap<&'a str, usize>,
1141    ce: &'a str,
1142    ends: &[Option<(&'a str, bool)>],
1143    reached: &[usize],
1144    only: Option<&BTreeSet<usize>>,
1145) {
1146    for (&t, end) in m.terminals[ce].iter().zip(ends) {
1147        let (Some(&n), Some(node)) = (end.and_then(|e| node_of.get(e.0)), m.terminal_node(t))
1148        else {
1149            continue;
1150        };
1151        if grid.nodes[n].kind != "Substation" || only.is_some_and(|o| !o.contains(&n)) {
1152            continue;
1153        }
1154        let far: Vec<usize> = reached.iter().copied().filter(|&r| r != n).collect();
1155        let item = item_for(m, grid, items, groups, n, ce, false, far);
1156        let junction = item_for(m, grid, items, groups, n, node, true, vec![]);
1157        grid.inside.entry(n).or_default().links.push(Link {
1158            id: t.to_string(),
1159            label: m.name(t),
1160            item,
1161            junction,
1162            connected: m.flag(t, "ACDCTerminal.connected"),
1163        });
1164    }
1165}
1166
1167/// `id` counted on `node` if it is equipment of a substation.
1168fn count(m: &Model<'_>, node: &mut Node, id: &str) {
1169    if let Some(container) = m.reference(id, "Equipment.EquipmentContainer")
1170        && m.substation(container).is_some()
1171    {
1172        *node.equipment.entry(m.class(id).unwrap_or("")).or_default() += 1;
1173    }
1174}
1175
1176/// The voltage of the voltage level `vl` added to `node`'s.
1177fn add_kv(m: &Model<'_>, node: &mut Node, vl: &str) {
1178    if let Some(kv) = m
1179        .reference(vl, "VoltageLevel.BaseVoltage")
1180        .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"))
1181    {
1182        node.kv.push(kv);
1183    }
1184}
1185
1186/// The item for `id` inside node `n`'s substation, added on first use, with
1187/// its voltage level.
1188#[allow(clippy::too_many_arguments)]
1189fn item_for<'a>(
1190    m: &Model<'a>,
1191    grid: &mut Grid,
1192    items: &mut FastMap<(usize, &'a str), usize>,
1193    groups: &mut FastMap<(usize, &'a str), usize>,
1194    n: usize,
1195    id: &'a str,
1196    junction: bool,
1197    far: Vec<usize>,
1198) -> usize {
1199    if let Some(&i) = items.get(&(n, id)) {
1200        return i;
1201    }
1202    let container = if junction {
1203        m.node_container(id)
1204    } else {
1205        m.reference(id, "Equipment.EquipmentContainer")
1206    };
1207    let vl = container
1208        .and_then(|c| m.voltage_level(c))
1209        .filter(|vl| m.substation(vl) == Some(grid.nodes[n].id.as_str()));
1210    let inside = grid.inside.entry(n).or_default();
1211    let group = vl.map(|vl| {
1212        *groups.entry((n, vl)).or_insert_with(|| {
1213            let kv = m
1214                .reference(vl, "VoltageLevel.BaseVoltage")
1215                .and_then(|b| m.number(b, "BaseVoltage.nominalVoltage"));
1216            inside.groups.push(Group {
1217                id: vl.into(),
1218                label: m.name(vl),
1219                kv,
1220            });
1221            inside.groups.len() - 1
1222        })
1223    });
1224    let class = m.class(id).unwrap_or("");
1225    let switch = !junction
1226        && (m.text(id, "Switch.open").is_some() || m.text(id, "Switch.normalOpen").is_some());
1227    inside.items.push(Item {
1228        id: id.into(),
1229        label: m.name(id),
1230        class,
1231        junction,
1232        group,
1233        open: if switch {
1234            m.flag(id, "Switch.open")
1235                .or_else(|| m.flag(id, "Switch.normalOpen"))
1236        } else {
1237            None
1238        },
1239        in_service: if junction {
1240            None
1241        } else {
1242            m.flag(id, "Equipment.inService")
1243        },
1244        far,
1245        findings: Counts::default(),
1246    });
1247    items.insert((n, id), inside.items.len() - 1);
1248    inside.items.len() - 1
1249}
1250
1251/// The node of an edge's end, added on first use: a substation, or a
1252/// boundary point.
1253fn node_for<'a>(
1254    m: &Model<'a>,
1255    grid: &mut Grid,
1256    node_of: &mut FastMap<&'a str, usize>,
1257    (id, boundary): (&'a str, bool),
1258) -> usize {
1259    *node_of.entry(id).or_insert_with(|| {
1260        grid.nodes.push(Node {
1261            id: id.into(),
1262            // An IGM often only refers to a boundary point the boundary set names.
1263            label: m
1264                .text(id, "IdentifiedObject.name")
1265                .unwrap_or_default()
1266                .to_string(),
1267            kind: if boundary {
1268                m.class(id).unwrap_or("ConnectivityNode")
1269            } else {
1270                "Substation"
1271            },
1272            ..Default::default()
1273        });
1274        grid.nodes.len() - 1
1275    })
1276}
1277
1278/// Where `id` belongs, memoised in `placed`: a container's substation, a
1279/// terminal's equipment, a node's substation, else the first referenced
1280/// object that has a place. On a substation's node, also the item `id`
1281/// stands for there, memoised in `within`: an item itself, else that of the
1282/// object it takes its place from.
1283#[allow(clippy::too_many_arguments)]
1284fn place<'a>(
1285    m: &Model<'a>,
1286    node_of: &FastMap<&str, usize>,
1287    items: &FastMap<(usize, &'a str), usize>,
1288    placed: &mut FastMap<String, Place>,
1289    within: &mut FastMap<String, (usize, usize)>,
1290    id: &'a str,
1291    depth: u8,
1292) -> Option<Place> {
1293    if let Some(p) = placed.get(id) {
1294        return Some(*p);
1295    }
1296    if depth > 3 {
1297        return None;
1298    }
1299    let class = m.class(id)?;
1300    let mut via = None;
1301    let direct = match class {
1302        "Substation" | "VoltageLevel" | "Bay" => m
1303            .substation(id)
1304            .and_then(|s| node_of.get(s))
1305            .map(|&n| Place::Node(n)),
1306        "ConnectivityNode" | "TopologicalNode" => match node_of.get(id) {
1307            Some(&n) => Some(Place::Node(n)),
1308            None => {
1309                let key = if class == "ConnectivityNode" {
1310                    "ConnectivityNode.ConnectivityNodeContainer"
1311                } else {
1312                    "TopologicalNode.ConnectivityNodeContainer"
1313                };
1314                m.reference(id, key)
1315                    .and_then(|c| m.substation(c))
1316                    .and_then(|s| node_of.get(s))
1317                    .map(|&n| Place::Node(n))
1318            }
1319        },
1320        "Terminal" => m
1321            .reference(id, "Terminal.ConductingEquipment")
1322            .and_then(|ce| {
1323                via = Some(ce);
1324                place(m, node_of, items, placed, within, ce, depth + 1)
1325            }),
1326        _ => m
1327            .reference(id, "Equipment.EquipmentContainer")
1328            .and_then(|c| m.substation(c))
1329            .and_then(|s| node_of.get(s))
1330            .map(|&n| Place::Node(n)),
1331    };
1332    let found = match direct {
1333        Some(p) => p,
1334        None => {
1335            // Limits, tap changers, regulating controls, state variables, …:
1336            // where what they refer to is.
1337            let els = m.objects.get(id)?;
1338            let mut keys: Vec<&str> = els
1339                .iter()
1340                .flat_map(|el| el.fields().keys().copied())
1341                .collect();
1342            keys.sort();
1343            keys.dedup();
1344            let (r, p) = keys
1345                .into_iter()
1346                .filter(|k| !k.ends_with(".BaseVoltage") && !k.ends_with(".Region"))
1347                .find_map(|k| {
1348                    let r = m.reference(id, k).filter(|r| *r != id)?;
1349                    place(m, node_of, items, placed, within, r, depth + 1).map(|p| (r, p))
1350                })?;
1351            via = Some(r);
1352            p
1353        }
1354    };
1355    placed.insert(id.to_string(), found);
1356    if let Place::Node(n) = found
1357        && let Some(w) = items.get(&(n, id)).map(|&i| (n, i)).or_else(|| {
1358            via.and_then(|r| within.get(r).copied())
1359                .filter(|w| w.0 == n)
1360        })
1361    {
1362        within.insert(id.to_string(), w);
1363    }
1364    Some(found)
1365}
1366
1367impl Grid {
1368    /// All of it as text, each map in order, for tests to compare grids.
1369    #[cfg(test)]
1370    pub(crate) fn snapshot(&self) -> String {
1371        let sorted = |m: Vec<String>| {
1372            let mut m = m;
1373            m.sort();
1374            m.join("\n")
1375        };
1376        let inside = sorted(
1377            self.inside
1378                .iter()
1379                .map(|(n, i)| format!("{n} {i:?}"))
1380                .collect(),
1381        );
1382        let placed = sorted(
1383            self.placed
1384                .iter()
1385                .map(|(k, p)| format!("{k} {p:?}"))
1386                .collect(),
1387        );
1388        let within = sorted(
1389            self.within
1390                .iter()
1391                .map(|(k, w)| format!("{k} {w:?}"))
1392                .collect(),
1393        );
1394        let unplaced = sorted(self.unplaced.iter().cloned().collect());
1395        format!(
1396            "{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{inside}\n{placed}\n{within}\n{unplaced}",
1397            self.nodes, self.edges, self.elsewhere, self.layouts, self.auto
1398        )
1399    }
1400
1401    /// Count each finding on its object's node or edge.
1402    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
1403        for (_, v) in violations {
1404            match self.placed.get(v.object_id.as_str()) {
1405                Some(Place::Node(n)) => {
1406                    self.nodes[*n].findings.add(&v.severity);
1407                    if let Some(inside) = self.inside.get_mut(n) {
1408                        match self.within.get(v.object_id.as_str()) {
1409                            Some(&(_, i)) => inside.items[i].findings.add(&v.severity),
1410                            None => inside.findings.add(&v.severity),
1411                        }
1412                    }
1413                }
1414                Some(Place::Edge(e)) => self.edges[*e].findings.add(&v.severity),
1415                None => self.elsewhere.add(&v.severity),
1416            }
1417        }
1418    }
1419
1420    /// Where the view shows object `id`: `select`, the node or edge it is
1421    /// on, else the item it stands for inside `enter`, its substation; and
1422    /// `inside`, a substation's own id. `None` if it is on neither.
1423    pub fn reveal(&self, id: &str) -> Option<Value> {
1424        match *self.placed.get(id)? {
1425            Place::Edge(e) => Some(json!({ "select": format!("e:{}", self.edges[e].id) })),
1426            Place::Node(n) => {
1427                let node = &self.nodes[n];
1428                if node.kind != "Substation" || node.id == id {
1429                    let inside = (node.kind == "Substation").then_some(&node.id);
1430                    return Some(json!({ "select": node.id, "inside": inside }));
1431                }
1432                let item = self
1433                    .within
1434                    .get(id)
1435                    .map(|&(_, i)| &self.inside[&n].items[i].id);
1436                Some(json!({ "enter": node.id, "select": item }))
1437            }
1438        }
1439    }
1440
1441    /// The view's data: nodes and edges, each with where it is written.
1442    pub fn json(&self, set: &impl Locations) -> Value {
1443        let location = |id: &str| set.location(id.split('#').next().unwrap_or(id));
1444        let nodes: Vec<Value> = self
1445            .nodes
1446            .iter()
1447            .map(|n| {
1448                json!({
1449                    "id": n.id, "label": n.label, "kind": n.kind, "region": n.region, "kV": n.kv,
1450                    "equipment": n.equipment, "findings": n.findings.json(), "location": location(&n.id),
1451                })
1452            })
1453            .collect();
1454        let edges: Vec<Value> = self
1455            .edges
1456            .iter()
1457            .map(|e| {
1458                json!({
1459                    "id": e.id, "label": e.label, "class": e.class, "source": self.nodes[e.source].id,
1460                    "target": self.nodes[e.target].id, "kV": e.kv, "findings": e.findings.json(), "location": location(&e.id),
1461                })
1462            })
1463            .collect();
1464        let layout = |l: &Layout| {
1465            let nodes: serde_json::Map<String, Value> = l
1466                .nodes
1467                .iter()
1468                .map(|(&n, &(x, y))| (self.nodes[n].id.clone(), json!([x, y])))
1469                .collect();
1470            let edges: serde_json::Map<String, Value> = l
1471                .edges
1472                .iter()
1473                .map(|(&e, ps)| {
1474                    (
1475                        self.edges[e].id.clone(),
1476                        json!(ps.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>()),
1477                    )
1478                })
1479                .collect();
1480            let mut out = json!({ "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit, "nodes": nodes, "edges": edges });
1481            if !l.tracks.is_empty() {
1482                out["tracks"] = l
1483                    .tracks
1484                    .iter()
1485                    .map(|(&e, &t)| (self.edges[e].id.clone(), json!(t)))
1486                    .collect::<serde_json::Map<_, _>>()
1487                    .into();
1488            }
1489            out
1490        };
1491        json!({
1492            "files": set.files(),
1493            "nodes": nodes, "edges": edges, "elsewhere": self.elsewhere.json(),
1494            "layouts": self.layouts.iter().map(layout).collect::<Vec<_>>(), "auto": self.auto.as_ref().map(layout),
1495        })
1496    }
1497
1498    /// What the substation `id` holds; `None` if no substation of the set
1499    /// has that mRID.
1500    pub fn inside_of(&self, id: &str) -> Option<&Inside> {
1501        let n = self
1502            .nodes
1503            .iter()
1504            .position(|x| x.id == id && x.kind == "Substation")?;
1505        self.inside.get(&n)
1506    }
1507
1508    /// The substation `id`'s layout `layout` (the view's JSON) after its
1509    /// items moved: busbars across what hangs from them, routes anew.
1510    pub fn reroute_json(&self, id: &str, layout: &Value) -> Option<Value> {
1511        let inside = self.inside_of(id)?;
1512        let l = inside.layout_from_json(layout);
1513        let mut moved = crate::single_line::reroute(inside, &l.nodes, &l.sizes);
1514        (moved.id, moved.name) = (l.id, l.name);
1515        Some(inside.layout_json(&moved))
1516    }
1517
1518    /// What the substation `id` holds, for the view's drill-down; `None` if
1519    /// no substation of the set has that mRID.
1520    pub fn inside_json(&self, set: &impl Locations, id: &str) -> Option<Value> {
1521        let n = self
1522            .nodes
1523            .iter()
1524            .position(|x| x.id == id && x.kind == "Substation")?;
1525        let node = &self.nodes[n];
1526        let empty = Inside::default();
1527        let inside = self.inside.get(&n).unwrap_or(&empty);
1528        let location = |id: &str| set.location(id);
1529        let groups: Vec<Value> = inside
1530            .groups
1531            .iter()
1532            .map(|g| json!({ "id": g.id, "label": g.label, "kV": g.kv }))
1533            .collect();
1534        let items: Vec<Value> = inside
1535            .items
1536            .iter()
1537            .map(|it| {
1538                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();
1539                json!({
1540                    "id": it.id, "label": it.label, "class": it.class, "junction": it.junction,
1541                    "group": it.group.map(|g| &inside.groups[g].id), "open": it.open, "inService": it.in_service,
1542                    "far": far, "findings": it.findings.json(), "location": location(&it.id),
1543                })
1544            })
1545            .collect();
1546        let links: Vec<Value> = inside
1547            .links
1548            .iter()
1549            .map(|l| json!({ "id": l.id, "source": inside.items[l.item].id, "target": inside.items[l.junction].id, "connected": l.connected }))
1550            .collect();
1551        let layouts: Vec<Value> = inside
1552            .layouts
1553            .iter()
1554            .map(|l| inside.layout_json(l))
1555            .collect();
1556        // Laid out when asked for: a few substations are opened, of thousands.
1557        let auto = inside.layout_json(&crate::single_line::single_line(inside));
1558        Some(json!({
1559            "id": node.id, "label": node.label, "region": node.region, "kV": node.kv, "findings": inside.findings.json(),
1560            "location": location(&node.id), "groups": groups, "items": items, "links": links, "layouts": layouts, "auto": auto,
1561        }))
1562    }
1563}
1564
1565impl Inside {
1566    /// A layout of its items, as the view takes it: positions and sizes by
1567    /// item, routes by terminal.
1568    pub fn layout_json(&self, l: &Layout) -> Value {
1569        let id_of = |i: &usize| self.items[*i].id.clone();
1570        json!({
1571            "id": l.id, "name": l.name, "kind": l.kind, "flipY": l.flip_y, "unit": l.unit,
1572            "nodes": l.nodes.iter().map(|(i, &(x, y))| (id_of(i), json!([x, y]))).collect::<serde_json::Map<_, _>>(),
1573            "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<_, _>>(),
1574            "sizes": l.sizes.iter().map(|(i, &(w, h))| (id_of(i), json!([w, h]))).collect::<serde_json::Map<_, _>>(),
1575        })
1576    }
1577
1578    /// A layout of its items from the view's JSON (as [`Inside::layout_json`]
1579    /// writes it); what names no item or terminal of it is left out.
1580    pub fn layout_from_json(&self, v: &Value) -> Layout {
1581        let item = |id: &str| self.items.iter().position(|it| it.id == id);
1582        let pair = |p: &Value| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?));
1583        let by_item = |key: &str| -> BTreeMap<usize, (f64, f64)> {
1584            v[key]
1585                .as_object()
1586                .into_iter()
1587                .flatten()
1588                .filter_map(|(id, p)| Some((item(id)?, pair(p)?)))
1589                .collect()
1590        };
1591        let edges = v["edges"]
1592            .as_object()
1593            .into_iter()
1594            .flatten()
1595            .filter_map(|(id, ps)| {
1596                let k = self.links.iter().position(|l| &l.id == id)?;
1597                Some((k, ps.as_array()?.iter().filter_map(pair).collect()))
1598            })
1599            .collect();
1600        Layout {
1601            id: v["id"].as_str().unwrap_or("auto").into(),
1602            name: v["name"].as_str().unwrap_or_default().into(),
1603            kind: "diagram",
1604            flip_y: false,
1605            nodes: by_item("nodes"),
1606            edges,
1607            sizes: by_item("sizes"),
1608            unit: v["unit"].as_f64(),
1609            tracks: BTreeMap::new(),
1610        }
1611    }
1612}
1613
1614#[cfg(test)]
1615mod tests {
1616    use std::path::Path;
1617
1618    use crate::testing::{collect, validate};
1619
1620    /// MicroGrid: Belgium's two substations and the Netherlands' one, joined
1621    /// through the boundary's five border nodes; each line an edge.
1622    #[test]
1623    fn micro_grid() {
1624        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
1625            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
1626        let files = collect(&dir);
1627        assert_eq!(
1628            files.len(),
1629            12,
1630            "missing test data — run `git submodule update --init`"
1631        );
1632        let set = validate(&files);
1633        let g = &set.grid;
1634        let mut subs: Vec<&str> = g
1635            .nodes
1636            .iter()
1637            .filter(|n| n.kind == "Substation")
1638            .map(|n| n.label.as_str())
1639            .collect();
1640        subs.sort();
1641        assert_eq!(subs, ["Anvers", "PP_Amsterdam", "PP_Brussels"]);
1642        let mut borders: Vec<&str> = g
1643            .nodes
1644            .iter()
1645            .filter(|n| n.kind == "ConnectivityNode")
1646            .map(|n| n.label.as_str())
1647            .collect();
1648        borders.sort();
1649        assert_eq!(
1650            borders,
1651            [
1652                "Border_AL11",
1653                "Border_GY11",
1654                "Border_MA11",
1655                "Border_ST23",
1656                "Border_ST24"
1657            ]
1658        );
1659        assert_eq!(g.edges.len(), 12);
1660        assert!(g.edges.iter().all(|e| e.class == "ACLineSegment"));
1661
1662        let node = |label: &str| g.nodes.iter().find(|n| n.label == label).unwrap();
1663        let between = |a: &str, b: &str| {
1664            g.edges
1665                .iter()
1666                .filter(|e| {
1667                    let ends = [
1668                        g.nodes[e.source].label.as_str(),
1669                        g.nodes[e.target].label.as_str(),
1670                    ];
1671                    ends.contains(&a) && ends.contains(&b)
1672                })
1673                .count()
1674        };
1675        assert_eq!(between("PP_Brussels", "Anvers"), 2);
1676        assert_eq!(between("PP_Amsterdam", "Border_AL11"), 1);
1677        assert_eq!(between("PP_Brussels", "Border_AL11"), 1);
1678        let brussels = node("PP_Brussels");
1679        assert_eq!(brussels.kv, [380.0, 225.0, 110.0, 21.0, 10.5]);
1680        assert_eq!(brussels.equipment["SynchronousMachine"], 2);
1681        assert_eq!(brussels.region.as_deref(), Some("ELIA-Brussels"));
1682
1683        // Every finding counted once, and each node clicks through to its definition.
1684        let json = g.json(&set);
1685        let total: u64 = json["nodes"]
1686            .as_array()
1687            .unwrap()
1688            .iter()
1689            .chain(json["edges"].as_array().unwrap())
1690            .chain(std::iter::once(&json["elsewhere"]))
1691            .map(|x| {
1692                let f = if x.get("findings").is_some() {
1693                    &x["findings"]
1694                } else {
1695                    x
1696                };
1697                f["violation"].as_u64().unwrap()
1698                    + f["warning"].as_u64().unwrap()
1699                    + f["info"].as_u64().unwrap()
1700            })
1701            .sum();
1702        let datasets: Vec<_> = files
1703            .iter()
1704            .map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
1705            .collect();
1706        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, vec![]);
1707        assert_eq!(
1708            total as usize,
1709            cimvalidation::validate_files(datasets, &cfg).len()
1710        );
1711        let anvers = json["nodes"]
1712            .as_array()
1713            .unwrap()
1714            .iter()
1715            .find(|n| n["label"] == "Anvers")
1716            .unwrap();
1717        assert!(
1718            anvers["location"]["uri"]
1719                .as_str()
1720                .unwrap()
1721                .ends_with("_BE_EQ_001.xml"),
1722            "{anvers}"
1723        );
1724
1725        // The assembled DL diagram and the GL locations place every node and route every line.
1726        let names: Vec<&str> = g.layouts.iter().map(|l| l.name.as_str()).collect();
1727        assert_eq!(names, ["Diagram: Assembled", "Geographic (EPSG:4326)"]);
1728        for l in &g.layouts {
1729            assert_eq!((l.nodes.len(), l.edges.len()), (8, 12), "{}", l.name);
1730        }
1731        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
1732        let (diagram, map) = (&g.layouts[0], &g.layouts[1]);
1733        assert!(!diagram.flip_y);
1734        // Brussels and Anvers left of the border points, Amsterdam right of them.
1735        let x = |label: &str| diagram.nodes[&index(label)].0;
1736        assert!(
1737            x("PP_Brussels") < x("Anvers")
1738                && x("Anvers") < x("Border_AL11")
1739                && x("Border_AL11") < x("PP_Amsterdam")
1740        );
1741        // Brussels in Brussels, from the ends of its lines; Amsterdam north of it.
1742        let (lon, lat) = map.nodes[&index("PP_Brussels")];
1743        assert!(
1744            (lon - 4.30).abs() < 0.01 && (lat - 50.80).abs() < 0.01,
1745            "{lon} {lat}"
1746        );
1747        assert!(map.nodes[&index("PP_Amsterdam")].1 > 52.3);
1748        // A route runs from its source's end, through the line's points.
1749        let line = g.edges.iter().position(|e| e.label == "BE-Line_2").unwrap();
1750        assert_eq!(map.edges[&line].len(), 5);
1751        let (start, source) = (map.edges[&line][0], map.nodes[&g.edges[line].source]);
1752        assert!(
1753            (start.0 - source.0).abs() < 0.01 && (start.1 - source.1).abs() < 0.01,
1754            "{start:?} {source:?}"
1755        );
1756        assert_eq!(json["layouts"][1]["nodes"].as_object().unwrap().len(), 8);
1757    }
1758
1759    /// MicroGrid Type 1, node-breaker: inside a substation, its breakers,
1760    /// busbars and connectivity nodes by voltage level, its lines with their
1761    /// far ends, and its switches' states; placed on the DL diagrams.
1762    #[test]
1763    fn micro_grid_inside() {
1764        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(
1765            "../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGrid-Type1/MicroGrid-Type1-Merged",
1766        );
1767        let mut files = collect(&dir);
1768        assert_eq!(
1769            files.len(),
1770            12,
1771            "missing test data — run `git submodule update --init`"
1772        );
1773        // A finding on a breaker (no normalOpen) and one on a voltage level (no name).
1774        let eq = files
1775            .iter_mut()
1776            .find(|(p, _)| p.to_string_lossy().ends_with("_BE_EQ_1.xml"))
1777            .unwrap();
1778        let mut text = eq.1.to_string();
1779        for written in [
1780            "<cim:Switch.normalOpen>false</cim:Switch.normalOpen>",
1781            "<cim:IdentifiedObject.name>225.0</cim:IdentifiedObject.name>",
1782        ] {
1783            let at = text.find(written).unwrap();
1784            text.replace_range(at..at + written.len(), "");
1785        }
1786        eq.1 = text.into();
1787        let set = validate(&files);
1788        let g = &set.grid;
1789        let index = |label: &str| g.nodes.iter().position(|n| n.label == label).unwrap();
1790
1791        // Each substation's findings are its items' and its own, once each.
1792        let total = |c: &super::Counts| c.violation + c.warning + c.info;
1793        for (n, inside) in &g.inside {
1794            let items: usize = inside.items.iter().map(|it| total(&it.findings)).sum();
1795            assert_eq!(
1796                items + total(&inside.findings),
1797                total(&g.nodes[*n].findings),
1798                "{}",
1799                g.nodes[*n].label
1800            );
1801        }
1802        let breaker = g
1803            .inside
1804            .values()
1805            .flat_map(|i| &i.items)
1806            .find(|it| it.label == "CIRCB-1230992285")
1807            .unwrap();
1808        assert!(breaker.findings.violation > 0, "{:?}", breaker.findings);
1809        let vl = g
1810            .inside
1811            .values()
1812            .find(|i| {
1813                i.groups
1814                    .iter()
1815                    .any(|gr| gr.id.ends_with("69ef0dbd-da79-4eef-a02f-690cb8a28361"))
1816            })
1817            .unwrap();
1818        assert!(total(&vl.findings) > 0, "{:?}", vl.findings);
1819
1820        let anvers = &g.inside[&index("Anvers")];
1821        let count = |class: &str| anvers.items.iter().filter(|it| it.class == class).count();
1822        assert_eq!(
1823            (
1824                count("Breaker"),
1825                count("BusbarSection"),
1826                count("ConnectivityNode"),
1827                count("ACLineSegment")
1828            ),
1829            (4, 3, 6, 4)
1830        );
1831        assert_eq!(
1832            anvers.groups.iter().map(|gr| gr.kv).collect::<Vec<_>>(),
1833            [Some(225.0)]
1834        );
1835        assert_eq!(anvers.links.len(), 19);
1836        // Every link runs from equipment to a junction.
1837        assert!(
1838            anvers
1839                .links
1840                .iter()
1841                .all(|l| !anvers.items[l.item].junction && anvers.items[l.junction].junction)
1842        );
1843        let line = anvers
1844            .items
1845            .iter()
1846            .find(|it| it.label == "BE-Line_2")
1847            .unwrap();
1848        assert_eq!(
1849            (
1850                line.group,
1851                line.far
1852                    .iter()
1853                    .map(|&f| g.nodes[f].label.as_str())
1854                    .collect::<Vec<_>>()
1855            ),
1856            (None, vec!["PP_Brussels"])
1857        );
1858        assert!(
1859            anvers
1860                .items
1861                .iter()
1862                .filter(|it| it.class == "Breaker")
1863                .all(|it| it.open == Some(false))
1864        );
1865
1866        // Amsterdam's bus coupler is open and out of service; its transformers sit between voltage levels.
1867        let amsterdam = &g.inside[&index("PP_Amsterdam")];
1868        let coupler = amsterdam
1869            .items
1870            .iter()
1871            .find(|it| it.label == "busbarcoupler 1")
1872            .unwrap();
1873        assert_eq!(
1874            (coupler.open, coupler.in_service),
1875            (Some(true), Some(false))
1876        );
1877        assert!(
1878            amsterdam
1879                .items
1880                .iter()
1881                .filter(|it| it.class == "PowerTransformer")
1882                .all(|it| it.group.is_none())
1883        );
1884        assert_eq!(amsterdam.groups.len(), 3);
1885
1886        // Both diagrams that draw Anvers place its equipment and nodes.
1887        let names: Vec<&str> = anvers.layouts.iter().map(|l| l.name.as_str()).collect();
1888        assert_eq!(names, ["Diagram: MAS BE", "Diagram: Assembled"]);
1889        assert!(
1890            anvers.layouts.iter().all(|l| l.nodes.len() > 10),
1891            "{:?}",
1892            anvers
1893                .layouts
1894                .iter()
1895                .map(|l| l.nodes.len())
1896                .collect::<Vec<_>>()
1897        );
1898
1899        // MAS BE draws every junction as a line: its busbars as bars (BE-Busbar_2, and the
1900        // sections the couplers join it to), the junctions inside bays as thin as a wire.
1901        let mas = anvers
1902            .layouts
1903            .iter()
1904            .find(|l| l.name == "Diagram: MAS BE")
1905            .unwrap();
1906        let unit = mas.unit.unwrap();
1907        let thickness = |class: &str, label: &str| {
1908            let i = anvers
1909                .items
1910                .iter()
1911                .position(|it| it.class == class && it.label == label)
1912                .unwrap();
1913            mas.sizes
1914                .get(&i)
1915                .map(|&(w, h)| (w.min(h) * unit * 100.0).round() / 100.0)
1916        };
1917        for section in ["BE-Busbar_2", "N1230992411", "N1230992414"] {
1918            assert_eq!(
1919                thickness("BusbarSection", section),
1920                Some(crate::single_line::BAR),
1921                "{section}"
1922            );
1923        }
1924        for node in ["N1230991550", "N1230991529", "Series Compensator"] {
1925            assert_eq!(
1926                thickness("ConnectivityNode", node),
1927                Some(crate::single_line::WIRE),
1928                "{node}"
1929            );
1930        }
1931
1932        let json = g.inside_json(&set, &g.nodes[index("Anvers")].id).unwrap();
1933        assert_eq!(json["items"].as_array().unwrap().len(), 20);
1934        // Its single-line diagram places every item, routes every link and sizes the busbars.
1935        assert_eq!(json["auto"]["nodes"].as_object().unwrap().len(), 20);
1936        assert_eq!(json["auto"]["edges"].as_object().unwrap().len(), 19);
1937        assert_eq!(json["auto"]["sizes"].as_object().unwrap().len(), 3);
1938        assert_eq!(json["auto"]["unit"], 1.0);
1939        assert!(
1940            json["items"][0]["location"]["uri"]
1941                .as_str()
1942                .unwrap()
1943                .ends_with("_BE_EQ_1.xml")
1944        );
1945        assert!(g.inside_json(&set, "no such substation").is_none());
1946    }
1947}