Skip to main content

cimview/
tree.rs

1//! A model set's objects as a tree, for the extension's model view. Its
2//! sections:
3//! - **Geographical**: regions, their substations and lines, down through
4//!   voltage levels, bays and equipment to terminals, limits and state
5//!   variables; each object under the object the first of [`CONTAINED`] it
6//!   writes names;
7//! - **Operational**: control areas and load areas, with what names them
8//!   ([`OPERATIONAL`]);
9//! - **Not contained**: the rest of that containment, by class: what no
10//!   container holds (base voltages, curves, diagrams, …) with what it holds;
11//! - **By class**: every object, flat.
12//!
13//! A parent the set lacks (an IGM's region, which its boundary set names) is
14//! an object of its own, labelled with its mRID. Each node counts the
15//! findings of its subtree. The view asks for one node's children at a time,
16//! by key; more than [`PAGE`] are grouped in ranges.
17
18use cimmodel::base::FastMap;
19use cimvalidation::Violation;
20use serde_json::{Value, json};
21
22use crate::Locations;
23use crate::grid::{Counts, Grid, Model};
24
25/// The fields that name an object's container, the first written winning.
26pub const CONTAINED: &[&str] = &[
27    "SubGeographicalRegion.Region",
28    "Substation.Region",
29    "Line.Region",
30    "DCLine.Region",
31    "VoltageLevel.Substation",
32    "Bay.VoltageLevel",
33    "DCConverterUnit.Substation",
34    "Equipment.EquipmentContainer",
35    "ConnectivityNode.ConnectivityNodeContainer",
36    "TopologicalNode.ConnectivityNodeContainer",
37    "DCNode.DCEquipmentContainer",
38    "DCTopologicalNode.DCEquipmentContainer",
39    "BoundaryPoint.ConnectivityNode",
40    "Terminal.ConductingEquipment",
41    "DCTerminal.DCConductingEquipment",
42    "ACDCConverterDCTerminal.DCConductingEquipment",
43    "PowerTransformerEnd.PowerTransformer",
44    "RatioTapChanger.TransformerEnd",
45    "PhaseTapChanger.TransformerEnd",
46    "RatioTapChangerTablePoint.RatioTapChangerTable",
47    "PhaseTapChangerTablePoint.PhaseTapChangerTable",
48    "OperationalLimitSet.Equipment",
49    "OperationalLimitSet.Terminal",
50    "OperationalLimit.OperationalLimitSet",
51    "RegulatingControl.Terminal",
52    "CurveData.Curve",
53    "Measurement.PowerSystemResource",
54    "AnalogValue.Analog",
55    "DiscreteValue.Discrete",
56    "AccumulatorValue.Accumulator",
57    "StringMeasurementValue.StringMeasurement",
58    "Location.PowerSystemResources",
59    "PositionPoint.Location",
60    "SvVoltage.TopologicalNode",
61    "SvInjection.TopologicalNode",
62    "SvPowerFlow.Terminal",
63    "SvStatus.ConductingEquipment",
64    "SvSwitch.Switch",
65    "SvTapStep.TapChanger",
66    "SvShuntCompensatorSections.ShuntCompensator",
67];
68
69/// What the Geographical section starts from: classes that contain, but
70/// need not be contained in the set.
71const CONTAINERS: &[&str] = &[
72    "GeographicalRegion",
73    "SubGeographicalRegion",
74    "Substation",
75    "Line",
76    "DCLine",
77    "VoltageLevel",
78    "Bay",
79    "DCConverterUnit",
80    "EquivalentNetwork",
81    "Plant",
82];
83
84/// The fields that name an object's area, under [`AREAS`].
85const OPERATIONAL: &[&str] = &[
86    "TieFlow.ControlArea",
87    "ControlAreaGeneratingUnit.ControlArea",
88    "SubLoadArea.LoadArea",
89    "LoadGroup.SubLoadArea",
90    "ConformLoad.LoadGroup",
91    "NonConformLoad.LoadGroup",
92];
93
94const AREAS: &[&str] = &["ControlArea", "LoadArea"];
95
96/// Children a node lists at once; more are grouped in ranges of this size.
97const PAGE: usize = 500;
98
99const NONE: u32 = u32::MAX;
100
101/// The class of a group of parents the set lacks.
102const MISSING: &str = "";
103
104struct Object {
105    id: String,
106    /// `IdentifiedObject.name`, if written.
107    label: Option<Box<str>>,
108    /// Empty for a parent the set lacks.
109    class: &'static str,
110    findings: Counts,
111    /// Its node in the containment and in the operational forest.
112    contained: Option<u32>,
113    operational: Option<u32>,
114}
115
116enum What {
117    Section { key: &'static str, label: &'static str },
118    /// Objects of a class: forest nodes in Not contained, leaf objects in By class.
119    Group { section: &'static str, class: &'static str },
120    /// An object in the containment (`c`) or operational (`o`) forest.
121    Object { object: u32, forest: char },
122}
123
124struct Node {
125    what: What,
126    children: Vec<u32>,
127    /// The node listing it; [`NONE`] for a section.
128    parent: u32,
129    findings: Counts,
130}
131
132/// A child as listed: a node, or a leaf object of By class.
133#[derive(Clone, Copy)]
134enum Entry {
135    Node(u32),
136    Leaf(u32),
137}
138
139#[derive(Default)]
140pub struct Tree {
141    objects: Vec<Object>,
142    by_id: FastMap<String, u32>,
143    nodes: Vec<Node>,
144    sections: Vec<u32>,
145    /// Sections and groups, by key.
146    named: FastMap<String, u32>,
147}
148
149/// The tree of a model set's files.
150pub fn build(m: &Model<'_>) -> Tree {
151    let mut t = Tree::default();
152    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
153    ids.sort_unstable();
154    for &id in &ids {
155        let label = m.text(id, "IdentifiedObject.name").filter(|n| !n.is_empty()).map(Box::from);
156        t.object(id, label, m.class(id).unwrap_or(""));
157    }
158
159    let contained = forest(&mut t, m, &ids, CONTAINED, 'c');
160    let mut roots: Vec<u32> = contained.roots.clone();
161    let mut geo = Vec::new();
162    let mut other: Vec<u32> = Vec::new();
163    // A cycle has no root: start from its first object.
164    for &id in &ids {
165        let o = t.by_id[id];
166        if t.objects[o as usize].contained.is_none() {
167            roots.push(grow(&mut t, &contained.children, o, 'c'));
168        }
169    }
170    let operational = forest(&mut t, m, &ids, OPERATIONAL, 'o');
171    let areas = operational.roots;
172    for n in roots {
173        let class = t.class_of(n);
174        let holds_container = || t.nodes[n as usize].children.iter().any(|&c| CONTAINERS.contains(&t.class_of(c)));
175        if CONTAINERS.contains(&class) || (class == MISSING && holds_container()) {
176            geo.push(n);
177        } else {
178            other.push(n);
179        }
180    }
181
182    let geo = t.section("geo", "Geographical", geo);
183    let op = t.section("op", "Operational", areas);
184    let mut by_class: FastMap<&'static str, Vec<u32>> = FastMap::default();
185    for n in other {
186        by_class.entry(t.class_of(n)).or_default().push(n);
187    }
188    let mut groups: Vec<u32> = by_class.into_iter().map(|(class, ns)| t.group("other", class, ns)).collect();
189    groups.sort_by_key(|&g| t.class_of(g));
190    let other = t.section("other", "Not contained", groups);
191    let mut by_class: FastMap<&'static str, Vec<u32>> = FastMap::default();
192    for (o, obj) in t.objects.iter().enumerate() {
193        if obj.class != MISSING {
194            by_class.entry(obj.class).or_default().push(o as u32);
195        }
196    }
197    let mut groups: Vec<u32> = by_class
198        .into_iter()
199        .map(|(class, mut os)| {
200            os.sort_by_cached_key(|&o| t.label_of(o).to_lowercase());
201            t.group("class", class, os)
202        })
203        .collect();
204    groups.sort_by_key(|&g| t.class_of(g));
205    let class = t.section("class", "By class", groups);
206    t.sections = [geo, op, other, class].into_iter().filter(|&s| !t.nodes[s as usize].children.is_empty()).collect();
207    t
208}
209
210/// A forest built from parent fields: its roots (in the operational forest,
211/// the areas), and each object's children.
212struct Forest {
213    roots: Vec<u32>,
214    children: FastMap<u32, Vec<u32>>,
215}
216
217/// The forest `keys` make, each object under the target of the first of them
218/// it writes, its nodes added to `t`.
219fn forest(t: &mut Tree, m: &Model<'_>, ids: &[&str], keys: &[&str], name: char) -> Forest {
220    let rank: FastMap<&str, usize> = keys.iter().enumerate().map(|(i, &k)| (k, i)).collect();
221    let mut parent: FastMap<u32, u32> = FastMap::default();
222    for &id in ids {
223        let Some(els) = m.objects.get(id) else { continue };
224        let best = els.iter().flat_map(|el| el.fields().keys()).filter_map(|k| rank.get(k).map(|&r| (r, *k))).min();
225        let Some(target) = best.and_then(|(_, k)| m.target(id, k)).filter(|p| *p != id) else { continue };
226        let p = match t.by_id.get(target) {
227            Some(&p) => p,
228            None => t.object(target, None, MISSING),
229        };
230        parent.insert(t.by_id[id], p);
231    }
232    let mut children: FastMap<u32, Vec<u32>> = FastMap::default();
233    for (&c, &p) in &parent {
234        children.entry(p).or_default().push(c);
235    }
236    let mut roots = Vec::new();
237    for o in 0..t.objects.len() as u32 {
238        let is_root = !parent.contains_key(&o) && (name == 'c' || AREAS.contains(&t.objects[o as usize].class));
239        if is_root {
240            roots.push(grow(t, &children, o, name));
241        }
242    }
243    Forest { roots, children }
244}
245
246/// Add object `o` and what it holds to forest `name`; returns its node.
247fn grow(t: &mut Tree, children: &FastMap<u32, Vec<u32>>, o: u32, name: char) -> u32 {
248    let root = t.node(o, name);
249    let mut stack = vec![(root, o)];
250    while let Some((n, o)) = stack.pop() {
251        let mut kids = Vec::new();
252        for &c in children.get(&o).map_or(&[][..], Vec::as_slice) {
253            let slot = if name == 'c' { t.objects[c as usize].contained } else { t.objects[c as usize].operational };
254            if slot.is_some() {
255                continue;
256            }
257            let cn = t.node(c, name);
258            kids.push(cn);
259            stack.push((cn, c));
260        }
261        t.sort(&mut kids);
262        for &k in &kids {
263            t.nodes[k as usize].parent = n;
264        }
265        t.nodes[n as usize].children = kids;
266    }
267    root
268}
269
270impl Tree {
271    fn object(&mut self, id: &str, label: Option<Box<str>>, class: &'static str) -> u32 {
272        let o = self.objects.len() as u32;
273        self.objects.push(Object { id: id.into(), label, class, findings: Counts::default(), contained: None, operational: None });
274        self.by_id.insert(id.into(), o);
275        o
276    }
277
278    fn node(&mut self, o: u32, forest: char) -> u32 {
279        let n = self.nodes.len() as u32;
280        self.nodes.push(Node { what: What::Object { object: o, forest }, children: Vec::new(), parent: NONE, findings: Counts::default() });
281        let obj = &mut self.objects[o as usize];
282        if forest == 'c' { obj.contained = Some(n) } else { obj.operational = Some(n) }
283        n
284    }
285
286    fn section(&mut self, key: &'static str, label: &'static str, children: Vec<u32>) -> u32 {
287        let n = self.nodes.len() as u32;
288        for &c in &children {
289            self.nodes[c as usize].parent = n;
290        }
291        self.nodes.push(Node { what: What::Section { key, label }, children, parent: NONE, findings: Counts::default() });
292        self.named.insert(key.into(), n);
293        n
294    }
295
296    fn group(&mut self, section: &'static str, class: &'static str, children: Vec<u32>) -> u32 {
297        let n = self.nodes.len() as u32;
298        if section != "class" {
299            for &c in &children {
300                self.nodes[c as usize].parent = n;
301            }
302        }
303        self.nodes.push(Node { what: What::Group { section, class }, children, parent: NONE, findings: Counts::default() });
304        self.named.insert(format!("{section}/{class}"), n);
305        n
306    }
307
308    /// The key the view knows node `n` by.
309    fn key_of(&self, n: u32) -> String {
310        match self.nodes[n as usize].what {
311            What::Section { key, .. } => key.into(),
312            What::Group { section, class } => format!("{section}/{class}"),
313            What::Object { object, forest } => format!("{forest}/{}", self.objects[object as usize].id),
314        }
315    }
316
317    /// The objects whose name or mRID holds `query` (ignoring case), at most
318    /// `limit`: a name equal to it first, then one starting with it, then one
319    /// holding it, then an mRID holding it; by name within each.
320    pub fn search(&self, query: &str, limit: usize) -> Vec<(&str, &str, &'static str)> {
321        let q = query.trim().to_lowercase();
322        if q.is_empty() {
323            return Vec::new();
324        }
325        let mut hits: Vec<(u8, String, usize)> = self
326            .objects
327            .iter()
328            .enumerate()
329            .filter(|(_, o)| o.class != MISSING)
330            .filter_map(|(i, o)| {
331                let name = o.label.as_deref().map(str::to_lowercase).unwrap_or_default();
332                let rank = if name == q {
333                    0
334                } else if name.starts_with(&q) {
335                    1
336                } else if name.contains(&q) {
337                    2
338                } else if o.id.to_lowercase().contains(&q) {
339                    3
340                } else {
341                    return None;
342                };
343                Some((rank, name, i))
344            })
345            .collect();
346        hits.sort();
347        hits.into_iter()
348            .take(limit)
349            .map(|(_, _, i)| {
350                let o = &self.objects[i];
351                (o.id.as_str(), self.label_of(i as u32), o.class)
352            })
353            .collect()
354    }
355
356    /// Object `id`'s label and class.
357    pub fn describe(&self, id: &str) -> Option<(&str, &'static str)> {
358        let &o = self.by_id.get(id)?;
359        Some((self.label_of(o), self.objects[o as usize].class))
360    }
361
362    /// What object `id` holds directly.
363    pub fn children(&self, id: &str) -> Vec<&str> {
364        let Some(n) = self.by_id.get(id).and_then(|&o| self.objects[o as usize].contained) else { return Vec::new() };
365        self.nodes[n as usize]
366            .children
367            .iter()
368            .filter_map(|&c| match self.nodes[c as usize].what {
369                What::Object { object, .. } => Some(self.objects[object as usize].id.as_str()),
370                _ => None,
371            })
372            .collect()
373    }
374
375    /// What object `id` holds, at any depth: its subtree in the containment.
376    pub fn descendants(&self, id: &str) -> Vec<&str> {
377        let Some(root) = self.by_id.get(id).and_then(|&o| self.objects[o as usize].contained) else { return Vec::new() };
378        let mut out = Vec::new();
379        let mut stack = self.nodes[root as usize].children.clone();
380        while let Some(n) = stack.pop() {
381            let node = &self.nodes[n as usize];
382            if let What::Object { object, .. } = node.what {
383                out.push(self.objects[object as usize].id.as_str());
384            }
385            stack.extend(&node.children);
386        }
387        out
388    }
389
390    /// Object `id`'s node in the containment and its containers' before it,
391    /// outermost first, as node numbers; empty if it is not in the tree.
392    pub fn chain(&self, id: &str) -> Vec<u32> {
393        let Some(mut n) = self.by_id.get(id).and_then(|&o| self.objects[o as usize].contained) else { return Vec::new() };
394        let mut out = vec![n];
395        while let Some(What::Object { .. }) = self.nodes.get(self.nodes[n as usize].parent as usize).map(|p| &p.what) {
396            n = self.nodes[n as usize].parent;
397            out.push(n);
398        }
399        out.reverse();
400        out
401    }
402
403    /// The labels of the containers of object `id`, outermost first; the
404    /// regions left out below a substation or line.
405    pub fn containers(&self, id: &str) -> Vec<&str> {
406        let mut out = self.chain(id);
407        out.pop();
408        let region = |&n: &u32| matches!(self.class_of(n), "GeographicalRegion" | "SubGeographicalRegion");
409        if out.iter().any(|n| !region(n)) {
410            out.retain(|n| !region(n));
411        }
412        out.into_iter().map(|n| self.node_label(n)).collect()
413    }
414
415    /// The keys the view expands to reach object `id` in Geographical or Not
416    /// contained, from its section on, the class groups and pages a long
417    /// level is split into included; `None` if it is not listed (filtered out).
418    pub fn path(&self, id: &str, only_findings: bool) -> Option<Vec<String>> {
419        let mut chain = vec![self.objects[*self.by_id.get(id)? as usize].contained?];
420        while let Some(&p) = chain.last().map(|&n| &self.nodes[n as usize].parent).filter(|&&p| p != NONE) {
421            chain.push(p);
422        }
423        chain.reverse();
424        let mut keys = vec![self.key_of(chain[0])];
425        for pair in chain.windows(2) {
426            let (parent, child) = (self.key_of(pair[0]), pair[1]);
427            let entries = self.entries(&parent, only_findings)?;
428            let at = entries.iter().position(|e| matches!(e, Entry::Node(c) if *c == child))?;
429            // As `children_json` lists a long level.
430            if entries.len() > PAGE {
431                let class = self.class_of(child);
432                if entries.iter().any(|&e| self.entry_class(e) != class) {
433                    let within = entries.iter().take(at).filter(|&&e| self.entry_class(e) == class).count();
434                    keys.push(format!("{parent}|{class}"));
435                    if entries.iter().filter(|&&e| self.entry_class(e) == class).count() > PAGE {
436                        keys.push(format!("{parent}|{class}~{}", within / PAGE * PAGE));
437                    }
438                } else {
439                    keys.push(format!("{parent}~{}", at / PAGE * PAGE));
440                }
441            }
442            keys.push(self.key_of(child));
443        }
444        Some(keys)
445    }
446
447    fn class_of(&self, n: u32) -> &'static str {
448        match self.nodes[n as usize].what {
449            What::Object { object, .. } => self.objects[object as usize].class,
450            What::Group { class, .. } => class,
451            What::Section { .. } => "",
452        }
453    }
454
455    fn label_of(&self, o: u32) -> &str {
456        let obj = &self.objects[o as usize];
457        obj.label.as_deref().unwrap_or(&obj.id)
458    }
459
460    fn node_label(&self, n: u32) -> &str {
461        match self.nodes[n as usize].what {
462            What::Object { object, .. } => self.label_of(object),
463            What::Group { class, .. } => class,
464            What::Section { label, .. } => label,
465        }
466    }
467
468    /// Containers first, then by class and label.
469    fn sort(&self, nodes: &mut [u32]) {
470        nodes.sort_by_cached_key(|&n| {
471            let class = self.class_of(n);
472            (!(class == MISSING || CONTAINERS.contains(&class)), class, self.node_label(n).to_lowercase())
473        });
474    }
475
476    /// Count each finding on its object, and each node's subtree.
477    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
478        for (_, v) in violations {
479            if let Some(&o) = self.by_id.get(v.object_id.as_str()) {
480                self.objects[o as usize].findings.add(&v.severity);
481            }
482        }
483        // A forest node comes before its children; groups and sections after
484        // what they hold, sections after groups.
485        for pass in 0..3 {
486            for n in (0..self.nodes.len()).rev() {
487                let node = &self.nodes[n];
488                let mut sum = match (&node.what, pass) {
489                    (What::Object { object, .. }, 0) => self.objects[*object as usize].findings,
490                    (What::Group { section: "class", .. }, 1) => {
491                        let mut sum = Counts::default();
492                        for &o in &node.children {
493                            sum.merge(self.objects[o as usize].findings);
494                        }
495                        self.nodes[n].findings = sum;
496                        continue;
497                    }
498                    (What::Group { .. }, 1) | (What::Section { .. }, 2) => Counts::default(),
499                    _ => continue,
500                };
501                for &c in &node.children {
502                    sum.merge(self.nodes[c as usize].findings);
503                }
504                self.nodes[n].findings = sum;
505            }
506        }
507    }
508
509    /// What `key` lists: its children; for `<key>|<class>`, those of a
510    /// class; for a range key, `…~<start>`, a page of them. `None` for an
511    /// unknown key.
512    fn entries(&self, key: &str, only_findings: bool) -> Option<Vec<Entry>> {
513        let (key, start) = match key.rsplit_once('~') {
514            Some((key, start)) if start.parse::<usize>().is_ok() => (key, start.parse::<usize>().ok()),
515            _ => (key, None),
516        };
517        let (base, class) = match key.split_once('|') {
518            Some((base, class)) => (base, Some(class)),
519            None => (key, None),
520        };
521        let n = match base.split_once('/') {
522            Some(("c", id)) => self.objects[*self.by_id.get(id)? as usize].contained?,
523            Some(("o", id)) => self.objects[*self.by_id.get(id)? as usize].operational?,
524            _ => *self.named.get(base)?,
525        };
526        let node = &self.nodes[n as usize];
527        let leaves = matches!(node.what, What::Group { section: "class", .. });
528        let mut out: Vec<Entry> = node.children.iter().map(|&c| if leaves { Entry::Leaf(c) } else { Entry::Node(c) }).collect();
529        if only_findings {
530            out.retain(|&e| self.findings(e).total() > 0);
531        }
532        if let Some(class) = class {
533            out.retain(|&e| self.entry_class(e) == class);
534        }
535        if let Some(start) = start {
536            out = out.into_iter().skip(start).take(PAGE).collect();
537        }
538        Some(out)
539    }
540
541    fn entry_class(&self, e: Entry) -> &'static str {
542        match e {
543            Entry::Node(n) => self.class_of(n),
544            Entry::Leaf(o) => self.objects[o as usize].class,
545        }
546    }
547
548    fn findings(&self, e: Entry) -> Counts {
549        match e {
550            Entry::Node(n) => self.nodes[n as usize].findings,
551            Entry::Leaf(o) => self.objects[o as usize].findings,
552        }
553    }
554
555    /// The children of node `key`, or the sections for `None`, for the view:
556    /// each with its key, label, class, number of children, findings, where
557    /// it is written and where the grid view shows it. `None` for a key the
558    /// tree does not have (any more).
559    pub fn children_json(&self, set: &impl Locations, grid: &Grid, key: Option<&str>, only_findings: bool) -> Option<Value> {
560        let entries = match key {
561            Some(key) => self.entries(key, only_findings)?,
562            None => {
563                let mut sections: Vec<Entry> = self.sections.iter().map(|&s| Entry::Node(s)).collect();
564                if only_findings {
565                    sections.retain(|&e| self.findings(e).total() > 0);
566                }
567                sections
568            }
569        };
570        // Too many to list: by class if they differ, else in pages.
571        if let Some(key) = key.filter(|k| !k.contains('~')) && entries.len() > PAGE {
572            let sum = |es: &[Entry]| {
573                let mut findings = Counts::default();
574                for &e in es {
575                    findings.merge(self.findings(e));
576                }
577                findings.json()
578            };
579            let mut classes: Vec<(&str, Vec<Entry>)> = Vec::new();
580            if !key.contains('|') {
581                for &e in &entries {
582                    let class = self.entry_class(e);
583                    match classes.iter_mut().find(|c| c.0 == class) {
584                        Some(c) => c.1.push(e),
585                        None => classes.push((class, vec![e])),
586                    }
587                }
588            }
589            let ranges: Vec<Value> = if classes.len() > 1 {
590                classes
591                    .iter()
592                    .map(|(class, es)| {
593                        json!({
594                            "key": format!("{key}|{class}"), "kind": "group", "class": class,
595                            "label": if *class == MISSING { "Not in the set" } else { class }, "children": es.len(), "findings": sum(es),
596                        })
597                    })
598                    .collect()
599            } else {
600                entries
601                    .chunks(PAGE)
602                    .enumerate()
603                    .map(|(i, chunk)| {
604                        json!({
605                            "key": format!("{key}~{}", i * PAGE), "kind": "range",
606                            "label": format!("{}–{}", i * PAGE + 1, i * PAGE + chunk.len()), "children": chunk.len(), "findings": sum(chunk),
607                        })
608                    })
609                    .collect()
610            };
611            return Some(Value::Array(ranges));
612        }
613        let location = |id: &str| set.location(id);
614        // A line is shown as its segments are: the first of them on the grid.
615        let reveal = |o: u32, kids: &[u32]| -> Option<Value> {
616            grid.reveal(&self.objects[o as usize].id).or_else(|| {
617                kids.iter().find_map(|&c| match self.nodes[c as usize].what {
618                    What::Object { object, .. } => grid.reveal(&self.objects[object as usize].id).filter(|r| r.get("enter").is_none()),
619                    _ => None,
620                })
621            })
622        };
623        let object = |o: u32, key: String, kids: &[u32], findings: Counts| -> Value {
624            let obj = &self.objects[o as usize];
625            json!({
626                "key": key, "kind": if obj.class == MISSING { "missing" } else { "object" }, "id": obj.id,
627                "label": self.label_of(o), "class": obj.class, "children": kids.len(), "findings": findings.json(),
628                "location": location(&obj.id), "grid": reveal(o, kids),
629            })
630        };
631        let items = entries
632            .into_iter()
633            .map(|e| match e {
634                Entry::Leaf(o) => object(o, format!("k/{}", self.objects[o as usize].id), &[], self.objects[o as usize].findings),
635                Entry::Node(n) => {
636                    let node = &self.nodes[n as usize];
637                    match node.what {
638                        What::Object { object: o, forest } => {
639                            object(o, format!("{forest}/{}", self.objects[o as usize].id), &node.children, node.findings)
640                        }
641                        What::Group { section, class } => json!({
642                            "key": format!("{section}/{class}"), "kind": "group", "class": class,
643                            "label": if class == MISSING { "Not in the set" } else { class },
644                            "children": node.children.len(), "findings": node.findings.json(),
645                        }),
646                        What::Section { key, label } => json!({
647                            "key": key, "kind": "section", "label": label, "children": node.children.len(), "findings": node.findings.json(),
648                        }),
649                    }
650                }
651            })
652            .collect();
653        Some(Value::Array(items))
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use std::path::Path;
660
661    use serde_json::Value;
662
663    use crate::testing::{collect, validate};
664
665    fn labels(v: &Value) -> Vec<&str> {
666        v.as_array().unwrap().iter().map(|x| x["label"].as_str().unwrap()).collect()
667    }
668
669    /// MicroGrid: regions down to terminals, the boundary's lines among them;
670    /// each object once in the containment, findings summed up the tree.
671    #[test]
672    fn micro_grid_tree() {
673        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
674            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
675        let files = collect(&dir);
676        assert_eq!(files.len(), 12, "missing test data — run `git submodule update --init`");
677        let set = validate(&files);
678        let t = &set.tree;
679        let children = |key: Option<&str>| t.children_json(&set, &set.grid, key, false).unwrap();
680        assert_eq!(labels(&children(None)), ["Geographical", "Operational", "Not contained", "By class"]);
681
682        let geo = children(Some("geo"));
683        assert!(labels(&geo).contains(&"BE"), "{:?}", labels(&geo));
684        let find = |list: &Value, label: &str| list.as_array().unwrap().iter().find(|x| x["label"] == label).cloned().unwrap();
685        let be = find(&geo, "BE");
686        let sub_regions = children(be["key"].as_str());
687        let brussels_region = find(&sub_regions, "ELIA-Brussels");
688        let subs = children(brussels_region["key"].as_str());
689        let brussels = find(&subs, "PP_Brussels");
690        assert_eq!(brussels["class"], "Substation");
691        assert_eq!(brussels["grid"]["inside"], brussels["id"]);
692        // Its voltage levels first, then the transformers it holds itself.
693        let held = children(brussels["key"].as_str());
694        let classes: Vec<&str> = held.as_array().unwrap().iter().map(|x| x["class"].as_str().unwrap()).collect();
695        assert_eq!(&classes[..5], ["VoltageLevel"; 5], "{classes:?}");
696        assert!(classes.contains(&"PowerTransformer"), "{classes:?}");
697        assert_eq!(t.containers(brussels["id"].as_str().unwrap()), ["BE", "ELIA-Brussels"]);
698
699        // Search: by name, ignoring case, the exact one first; by mRID.
700        assert_eq!(t.search("anvers", 5)[0].1, "Anvers");
701        // Names starting with it before names holding it; objects may share a name.
702        let lines: Vec<&str> = t.search("be-line_", 30).into_iter().map(|h| h.1).collect();
703        let starting = lines.iter().take_while(|l| l.starts_with("BE-Line_")).count();
704        assert!(starting >= 7 && lines[starting..].iter().all(|l| l.contains("BE-Line_") && !l.starts_with("BE-Line_")), "{lines:?}");
705        let id = brussels["id"].as_str().unwrap();
706        assert_eq!(t.search(&id[3..15], 5)[0].0, id);
707        assert!(t.search("  ", 5).is_empty());
708        assert_eq!(t.containers(held[0]["id"].as_str().unwrap()), ["PP_Brussels"]);
709
710        // Each object's path leads to it, a listed level at a time.
711        for group in children(Some("class")).as_array().unwrap() {
712            for x in children(group["key"].as_str()).as_array().unwrap() {
713                let keys = t.path(x["id"].as_str().unwrap(), false).unwrap();
714                assert!(["geo", "other"].contains(&keys[0].as_str()), "{keys:?}");
715                for step in keys.windows(2) {
716                    let listed = children(Some(&step[0]));
717                    assert!(listed.as_array().unwrap().iter().any(|y| y["key"] == step[1].as_str()), "{keys:?}");
718                }
719                assert_eq!(keys.last().unwrap(), &format!("c/{}", x["id"].as_str().unwrap()));
720            }
721        }
722
723        // Each object of the set is once in Geographical or Not contained.
724        let mut seen = 0;
725        let mut stack: Vec<String> = vec!["geo".into(), "other".into()];
726        while let Some(key) = stack.pop() {
727            for x in children(Some(&key)).as_array().unwrap() {
728                if x["kind"] == "object" {
729                    seen += 1;
730                }
731                if x["children"].as_u64().unwrap() > 0 {
732                    stack.push(x["key"].as_str().unwrap().into());
733                }
734            }
735        }
736        let by_class: u64 = children(Some("class")).as_array().unwrap().iter().map(|x| x["children"].as_u64().unwrap()).sum();
737        assert_eq!(seen, by_class);
738
739        // A section counts the findings of what it holds; By class, of every
740        // object, so all the findings on objects of the set.
741        let total = |x: &Value| ["violation", "warning", "info"].iter().map(|s| x["findings"][s].as_u64().unwrap()).sum::<u64>();
742        let sections = children(None);
743        let sum_of = |key: &str| children(Some(key)).as_array().unwrap().iter().map(total).sum::<u64>();
744        for s in sections.as_array().unwrap() {
745            assert_eq!(total(s), sum_of(s["key"].as_str().unwrap()), "{}", s["label"]);
746        }
747        let all = total(&find(&sections, "By class"));
748        assert!(all > 0);
749        assert_eq!(total(&find(&sections, "Geographical")) + total(&find(&sections, "Not contained")), all);
750        assert!(t.children_json(&set, &set.grid, None, true).unwrap().as_array().unwrap().iter().all(|x| total(x) > 0));
751    }
752}