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 {
118        key: &'static str,
119        label: &'static str,
120    },
121    /// Objects of a class: forest nodes in Not contained, leaf objects in By class.
122    Group {
123        section: &'static str,
124        class: &'static str,
125    },
126    /// An object in the containment (`c`) or operational (`o`) forest.
127    Object { object: u32, forest: char },
128}
129
130struct Node {
131    what: What,
132    children: Vec<u32>,
133    /// The node listing it; [`NONE`] for a section.
134    parent: u32,
135    findings: Counts,
136}
137
138/// A child as listed: a node, or a leaf object of By class.
139#[derive(Clone, Copy)]
140enum Entry {
141    Node(u32),
142    Leaf(u32),
143}
144
145#[derive(Default)]
146pub struct Tree {
147    objects: Vec<Object>,
148    by_id: FastMap<String, u32>,
149    nodes: Vec<Node>,
150    sections: Vec<u32>,
151    /// Sections and groups, by key.
152    named: FastMap<String, u32>,
153}
154
155/// The tree of a model set's files.
156pub fn build(m: &Model<'_>) -> Tree {
157    let mut t = Tree::default();
158    let mut ids: Vec<&str> = m.objects.keys().copied().collect();
159    ids.sort_unstable();
160    for &id in &ids {
161        let label = m
162            .text(id, "IdentifiedObject.name")
163            .filter(|n| !n.is_empty())
164            .map(Box::from);
165        t.object(id, label, m.class(id).unwrap_or(""));
166    }
167
168    let contained = forest(&mut t, m, &ids, CONTAINED, 'c');
169    let mut roots: Vec<u32> = contained.roots.clone();
170    let mut geo = Vec::new();
171    let mut other: Vec<u32> = Vec::new();
172    // A cycle has no root: start from its first object.
173    for &id in &ids {
174        let o = t.by_id[id];
175        if t.objects[o as usize].contained.is_none() {
176            roots.push(grow(&mut t, &contained.children, o, 'c'));
177        }
178    }
179    let operational = forest(&mut t, m, &ids, OPERATIONAL, 'o');
180    let areas = operational.roots;
181    for n in roots {
182        let class = t.class_of(n);
183        let holds_container = || {
184            t.nodes[n as usize]
185                .children
186                .iter()
187                .any(|&c| CONTAINERS.contains(&t.class_of(c)))
188        };
189        if CONTAINERS.contains(&class) || (class == MISSING && holds_container()) {
190            geo.push(n);
191        } else {
192            other.push(n);
193        }
194    }
195
196    let geo = t.section("geo", "Geographical", geo);
197    let op = t.section("op", "Operational", areas);
198    let mut by_class: FastMap<&'static str, Vec<u32>> = FastMap::default();
199    for n in other {
200        by_class.entry(t.class_of(n)).or_default().push(n);
201    }
202    let mut groups: Vec<u32> = by_class
203        .into_iter()
204        .map(|(class, ns)| t.group("other", class, ns))
205        .collect();
206    groups.sort_by_key(|&g| t.class_of(g));
207    let other = t.section("other", "Not contained", groups);
208    let mut by_class: FastMap<&'static str, Vec<u32>> = FastMap::default();
209    for (o, obj) in t.objects.iter().enumerate() {
210        if obj.class != MISSING {
211            by_class.entry(obj.class).or_default().push(o as u32);
212        }
213    }
214    let mut groups: Vec<u32> = by_class
215        .into_iter()
216        .map(|(class, mut os)| {
217            os.sort_by_cached_key(|&o| t.label_of(o).to_lowercase());
218            t.group("class", class, os)
219        })
220        .collect();
221    groups.sort_by_key(|&g| t.class_of(g));
222    let class = t.section("class", "By class", groups);
223    t.sections = [geo, op, other, class]
224        .into_iter()
225        .filter(|&s| !t.nodes[s as usize].children.is_empty())
226        .collect();
227    t
228}
229
230/// A forest built from parent fields: its roots (in the operational forest,
231/// the areas), and each object's children.
232struct Forest {
233    roots: Vec<u32>,
234    children: FastMap<u32, Vec<u32>>,
235}
236
237/// The forest `keys` make, each object under the target of the first of them
238/// it writes, its nodes added to `t`.
239fn forest(t: &mut Tree, m: &Model<'_>, ids: &[&str], keys: &[&str], name: char) -> Forest {
240    let rank: FastMap<&str, usize> = keys.iter().enumerate().map(|(i, &k)| (k, i)).collect();
241    let mut parent: FastMap<u32, u32> = FastMap::default();
242    for &id in ids {
243        let Some(els) = m.objects.get(id) else {
244            continue;
245        };
246        let best = els
247            .iter()
248            .flat_map(|el| el.fields().keys())
249            .filter_map(|k| rank.get(k).map(|&r| (r, *k)))
250            .min();
251        let Some(target) = best.and_then(|(_, k)| m.target(id, k)).filter(|p| *p != id) else {
252            continue;
253        };
254        let p = match t.by_id.get(target) {
255            Some(&p) => p,
256            None => t.object(target, None, MISSING),
257        };
258        parent.insert(t.by_id[id], p);
259    }
260    let mut children: FastMap<u32, Vec<u32>> = FastMap::default();
261    for (&c, &p) in &parent {
262        children.entry(p).or_default().push(c);
263    }
264    let mut roots = Vec::new();
265    for o in 0..t.objects.len() as u32 {
266        let is_root = !parent.contains_key(&o)
267            && (name == 'c' || AREAS.contains(&t.objects[o as usize].class));
268        if is_root {
269            roots.push(grow(t, &children, o, name));
270        }
271    }
272    Forest { roots, children }
273}
274
275/// Add object `o` and what it holds to forest `name`; returns its node.
276fn grow(t: &mut Tree, children: &FastMap<u32, Vec<u32>>, o: u32, name: char) -> u32 {
277    let root = t.node(o, name);
278    let mut stack = vec![(root, o)];
279    while let Some((n, o)) = stack.pop() {
280        let mut kids = Vec::new();
281        for &c in children.get(&o).map_or(&[][..], Vec::as_slice) {
282            let slot = if name == 'c' {
283                t.objects[c as usize].contained
284            } else {
285                t.objects[c as usize].operational
286            };
287            if slot.is_some() {
288                continue;
289            }
290            let cn = t.node(c, name);
291            kids.push(cn);
292            stack.push((cn, c));
293        }
294        t.sort(&mut kids);
295        for &k in &kids {
296            t.nodes[k as usize].parent = n;
297        }
298        t.nodes[n as usize].children = kids;
299    }
300    root
301}
302
303impl Tree {
304    fn object(&mut self, id: &str, label: Option<Box<str>>, class: &'static str) -> u32 {
305        let o = self.objects.len() as u32;
306        self.objects.push(Object {
307            id: id.into(),
308            label,
309            class,
310            findings: Counts::default(),
311            contained: None,
312            operational: None,
313        });
314        self.by_id.insert(id.into(), o);
315        o
316    }
317
318    fn node(&mut self, o: u32, forest: char) -> u32 {
319        let n = self.nodes.len() as u32;
320        self.nodes.push(Node {
321            what: What::Object { object: o, forest },
322            children: Vec::new(),
323            parent: NONE,
324            findings: Counts::default(),
325        });
326        let obj = &mut self.objects[o as usize];
327        if forest == 'c' {
328            obj.contained = Some(n)
329        } else {
330            obj.operational = Some(n)
331        }
332        n
333    }
334
335    fn section(&mut self, key: &'static str, label: &'static str, children: Vec<u32>) -> u32 {
336        let n = self.nodes.len() as u32;
337        for &c in &children {
338            self.nodes[c as usize].parent = n;
339        }
340        self.nodes.push(Node {
341            what: What::Section { key, label },
342            children,
343            parent: NONE,
344            findings: Counts::default(),
345        });
346        self.named.insert(key.into(), n);
347        n
348    }
349
350    fn group(&mut self, section: &'static str, class: &'static str, children: Vec<u32>) -> u32 {
351        let n = self.nodes.len() as u32;
352        if section != "class" {
353            for &c in &children {
354                self.nodes[c as usize].parent = n;
355            }
356        }
357        self.nodes.push(Node {
358            what: What::Group { section, class },
359            children,
360            parent: NONE,
361            findings: Counts::default(),
362        });
363        self.named.insert(format!("{section}/{class}"), n);
364        n
365    }
366
367    /// The key the view knows node `n` by.
368    fn key_of(&self, n: u32) -> String {
369        match self.nodes[n as usize].what {
370            What::Section { key, .. } => key.into(),
371            What::Group { section, class } => format!("{section}/{class}"),
372            What::Object { object, forest } => {
373                format!("{forest}/{}", self.objects[object as usize].id)
374            }
375        }
376    }
377
378    /// The objects whose name or mRID holds `query` (ignoring case), at most
379    /// `limit`: a name equal to it first, then one starting with it, then one
380    /// holding it, then an mRID holding it; by name within each.
381    pub fn search(&self, query: &str, limit: usize) -> Vec<(&str, &str, &'static str)> {
382        let q = query.trim().to_lowercase();
383        if q.is_empty() {
384            return Vec::new();
385        }
386        let mut hits: Vec<(u8, String, usize)> = self
387            .objects
388            .iter()
389            .enumerate()
390            .filter(|(_, o)| o.class != MISSING)
391            .filter_map(|(i, o)| {
392                let name = o
393                    .label
394                    .as_deref()
395                    .map(str::to_lowercase)
396                    .unwrap_or_default();
397                let rank = if name == q {
398                    0
399                } else if name.starts_with(&q) {
400                    1
401                } else if name.contains(&q) {
402                    2
403                } else if o.id.to_lowercase().contains(&q) {
404                    3
405                } else {
406                    return None;
407                };
408                Some((rank, name, i))
409            })
410            .collect();
411        hits.sort();
412        hits.into_iter()
413            .take(limit)
414            .map(|(_, _, i)| {
415                let o = &self.objects[i];
416                (o.id.as_str(), self.label_of(i as u32), o.class)
417            })
418            .collect()
419    }
420
421    /// Object `id`'s label and class.
422    pub fn describe(&self, id: &str) -> Option<(&str, &'static str)> {
423        let &o = self.by_id.get(id)?;
424        Some((self.label_of(o), self.objects[o as usize].class))
425    }
426
427    /// What object `id` holds directly.
428    pub fn children(&self, id: &str) -> Vec<&str> {
429        let Some(n) = self
430            .by_id
431            .get(id)
432            .and_then(|&o| self.objects[o as usize].contained)
433        else {
434            return Vec::new();
435        };
436        self.nodes[n as usize]
437            .children
438            .iter()
439            .filter_map(|&c| match self.nodes[c as usize].what {
440                What::Object { object, .. } => Some(self.objects[object as usize].id.as_str()),
441                _ => None,
442            })
443            .collect()
444    }
445
446    /// What object `id` holds, at any depth: its subtree in the containment.
447    pub fn descendants(&self, id: &str) -> Vec<&str> {
448        let Some(root) = self
449            .by_id
450            .get(id)
451            .and_then(|&o| self.objects[o as usize].contained)
452        else {
453            return Vec::new();
454        };
455        let mut out = Vec::new();
456        let mut stack = self.nodes[root as usize].children.clone();
457        while let Some(n) = stack.pop() {
458            let node = &self.nodes[n as usize];
459            if let What::Object { object, .. } = node.what {
460                out.push(self.objects[object as usize].id.as_str());
461            }
462            stack.extend(&node.children);
463        }
464        out
465    }
466
467    /// Object `id`'s node in the containment and its containers' before it,
468    /// outermost first, as node numbers; empty if it is not in the tree.
469    pub fn chain(&self, id: &str) -> Vec<u32> {
470        let Some(mut n) = self
471            .by_id
472            .get(id)
473            .and_then(|&o| self.objects[o as usize].contained)
474        else {
475            return Vec::new();
476        };
477        let mut out = vec![n];
478        while let Some(What::Object { .. }) = self
479            .nodes
480            .get(self.nodes[n as usize].parent as usize)
481            .map(|p| &p.what)
482        {
483            n = self.nodes[n as usize].parent;
484            out.push(n);
485        }
486        out.reverse();
487        out
488    }
489
490    /// The labels of the containers of object `id`, outermost first; the
491    /// regions left out below a substation or line.
492    pub fn containers(&self, id: &str) -> Vec<&str> {
493        let mut out = self.chain(id);
494        out.pop();
495        let region = |&n: &u32| {
496            matches!(
497                self.class_of(n),
498                "GeographicalRegion" | "SubGeographicalRegion"
499            )
500        };
501        if out.iter().any(|n| !region(n)) {
502            out.retain(|n| !region(n));
503        }
504        out.into_iter().map(|n| self.node_label(n)).collect()
505    }
506
507    /// The keys the view expands to reach object `id` in Geographical or Not
508    /// contained, from its section on, the class groups and pages a long
509    /// level is split into included; `None` if it is not listed (filtered out).
510    pub fn path(&self, id: &str, only_findings: bool) -> Option<Vec<String>> {
511        let mut chain = vec![self.objects[*self.by_id.get(id)? as usize].contained?];
512        while let Some(&p) = chain
513            .last()
514            .map(|&n| &self.nodes[n as usize].parent)
515            .filter(|&&p| p != NONE)
516        {
517            chain.push(p);
518        }
519        chain.reverse();
520        let mut keys = vec![self.key_of(chain[0])];
521        for pair in chain.windows(2) {
522            let (parent, child) = (self.key_of(pair[0]), pair[1]);
523            let entries = self.entries(&parent, only_findings)?;
524            let at = entries
525                .iter()
526                .position(|e| matches!(e, Entry::Node(c) if *c == child))?;
527            // As `children_json` lists a long level.
528            if entries.len() > PAGE {
529                let class = self.class_of(child);
530                if entries.iter().any(|&e| self.entry_class(e) != class) {
531                    let within = entries
532                        .iter()
533                        .take(at)
534                        .filter(|&&e| self.entry_class(e) == class)
535                        .count();
536                    keys.push(format!("{parent}|{class}"));
537                    if entries
538                        .iter()
539                        .filter(|&&e| self.entry_class(e) == class)
540                        .count()
541                        > PAGE
542                    {
543                        keys.push(format!("{parent}|{class}~{}", within / PAGE * PAGE));
544                    }
545                } else {
546                    keys.push(format!("{parent}~{}", at / PAGE * PAGE));
547                }
548            }
549            keys.push(self.key_of(child));
550        }
551        Some(keys)
552    }
553
554    fn class_of(&self, n: u32) -> &'static str {
555        match self.nodes[n as usize].what {
556            What::Object { object, .. } => self.objects[object as usize].class,
557            What::Group { class, .. } => class,
558            What::Section { .. } => "",
559        }
560    }
561
562    fn label_of(&self, o: u32) -> &str {
563        let obj = &self.objects[o as usize];
564        obj.label.as_deref().unwrap_or(&obj.id)
565    }
566
567    fn node_label(&self, n: u32) -> &str {
568        match self.nodes[n as usize].what {
569            What::Object { object, .. } => self.label_of(object),
570            What::Group { class, .. } => class,
571            What::Section { label, .. } => label,
572        }
573    }
574
575    /// Containers first, then by class and label.
576    fn sort(&self, nodes: &mut [u32]) {
577        nodes.sort_by_cached_key(|&n| {
578            let class = self.class_of(n);
579            (
580                !(class == MISSING || CONTAINERS.contains(&class)),
581                class,
582                self.node_label(n).to_lowercase(),
583            )
584        });
585    }
586
587    /// Count each finding on its object, and each node's subtree.
588    pub fn add_findings(&mut self, violations: &[(Option<usize>, Violation)]) {
589        for (_, v) in violations {
590            if let Some(&o) = self.by_id.get(v.object_id.as_str()) {
591                self.objects[o as usize].findings.add(&v.severity);
592            }
593        }
594        // A forest node comes before its children; groups and sections after
595        // what they hold, sections after groups.
596        for pass in 0..3 {
597            for n in (0..self.nodes.len()).rev() {
598                let node = &self.nodes[n];
599                let mut sum = match (&node.what, pass) {
600                    (What::Object { object, .. }, 0) => self.objects[*object as usize].findings,
601                    (
602                        What::Group {
603                            section: "class", ..
604                        },
605                        1,
606                    ) => {
607                        let mut sum = Counts::default();
608                        for &o in &node.children {
609                            sum.merge(self.objects[o as usize].findings);
610                        }
611                        self.nodes[n].findings = sum;
612                        continue;
613                    }
614                    (What::Group { .. }, 1) | (What::Section { .. }, 2) => Counts::default(),
615                    _ => continue,
616                };
617                for &c in &node.children {
618                    sum.merge(self.nodes[c as usize].findings);
619                }
620                self.nodes[n].findings = sum;
621            }
622        }
623    }
624
625    /// What `key` lists: its children; for `<key>|<class>`, those of a
626    /// class; for a range key, `…~<start>`, a page of them. `None` for an
627    /// unknown key.
628    fn entries(&self, key: &str, only_findings: bool) -> Option<Vec<Entry>> {
629        let (key, start) = match key.rsplit_once('~') {
630            Some((key, start)) if start.parse::<usize>().is_ok() => {
631                (key, start.parse::<usize>().ok())
632            }
633            _ => (key, None),
634        };
635        let (base, class) = match key.split_once('|') {
636            Some((base, class)) => (base, Some(class)),
637            None => (key, None),
638        };
639        let n = match base.split_once('/') {
640            Some(("c", id)) => self.objects[*self.by_id.get(id)? as usize].contained?,
641            Some(("o", id)) => self.objects[*self.by_id.get(id)? as usize].operational?,
642            _ => *self.named.get(base)?,
643        };
644        let node = &self.nodes[n as usize];
645        let leaves = matches!(
646            node.what,
647            What::Group {
648                section: "class",
649                ..
650            }
651        );
652        let mut out: Vec<Entry> = node
653            .children
654            .iter()
655            .map(|&c| {
656                if leaves {
657                    Entry::Leaf(c)
658                } else {
659                    Entry::Node(c)
660                }
661            })
662            .collect();
663        if only_findings {
664            out.retain(|&e| self.findings(e).total() > 0);
665        }
666        if let Some(class) = class {
667            out.retain(|&e| self.entry_class(e) == class);
668        }
669        if let Some(start) = start {
670            out = out.into_iter().skip(start).take(PAGE).collect();
671        }
672        Some(out)
673    }
674
675    fn entry_class(&self, e: Entry) -> &'static str {
676        match e {
677            Entry::Node(n) => self.class_of(n),
678            Entry::Leaf(o) => self.objects[o as usize].class,
679        }
680    }
681
682    fn findings(&self, e: Entry) -> Counts {
683        match e {
684            Entry::Node(n) => self.nodes[n as usize].findings,
685            Entry::Leaf(o) => self.objects[o as usize].findings,
686        }
687    }
688
689    /// The children of node `key`, or the sections for `None`, for the view:
690    /// each with its key, label, class, number of children, findings, where
691    /// it is written and where the grid view shows it. `None` for a key the
692    /// tree does not have (any more).
693    pub fn children_json(
694        &self,
695        set: &impl Locations,
696        grid: &Grid,
697        key: Option<&str>,
698        only_findings: bool,
699    ) -> Option<Value> {
700        let entries = match key {
701            Some(key) => self.entries(key, only_findings)?,
702            None => {
703                let mut sections: Vec<Entry> =
704                    self.sections.iter().map(|&s| Entry::Node(s)).collect();
705                if only_findings {
706                    sections.retain(|&e| self.findings(e).total() > 0);
707                }
708                sections
709            }
710        };
711        // Too many to list: by class if they differ, else in pages.
712        if let Some(key) = key.filter(|k| !k.contains('~'))
713            && entries.len() > PAGE
714        {
715            let sum = |es: &[Entry]| {
716                let mut findings = Counts::default();
717                for &e in es {
718                    findings.merge(self.findings(e));
719                }
720                findings.json()
721            };
722            let mut classes: Vec<(&str, Vec<Entry>)> = Vec::new();
723            if !key.contains('|') {
724                for &e in &entries {
725                    let class = self.entry_class(e);
726                    match classes.iter_mut().find(|c| c.0 == class) {
727                        Some(c) => c.1.push(e),
728                        None => classes.push((class, vec![e])),
729                    }
730                }
731            }
732            let ranges: Vec<Value> = if classes.len() > 1 {
733                classes
734                    .iter()
735                    .map(|(class, es)| {
736                        json!({
737                            "key": format!("{key}|{class}"), "kind": "group", "class": class,
738                            "label": if *class == MISSING { "Not in the set" } else { class }, "children": es.len(), "findings": sum(es),
739                        })
740                    })
741                    .collect()
742            } else {
743                entries
744                    .chunks(PAGE)
745                    .enumerate()
746                    .map(|(i, chunk)| {
747                        json!({
748                            "key": format!("{key}~{}", i * PAGE), "kind": "range",
749                            "label": format!("{}–{}", i * PAGE + 1, i * PAGE + chunk.len()), "children": chunk.len(), "findings": sum(chunk),
750                        })
751                    })
752                    .collect()
753            };
754            return Some(Value::Array(ranges));
755        }
756        let location = |id: &str| set.location(id);
757        // A line is shown as its segments are: the first of them on the grid.
758        let reveal = |o: u32, kids: &[u32]| -> Option<Value> {
759            grid.reveal(&self.objects[o as usize].id).or_else(|| {
760                kids.iter()
761                    .find_map(|&c| match self.nodes[c as usize].what {
762                        What::Object { object, .. } => grid
763                            .reveal(&self.objects[object as usize].id)
764                            .filter(|r| r.get("enter").is_none()),
765                        _ => None,
766                    })
767            })
768        };
769        let object = |o: u32, key: String, kids: &[u32], findings: Counts| -> Value {
770            let obj = &self.objects[o as usize];
771            json!({
772                "key": key, "kind": if obj.class == MISSING { "missing" } else { "object" }, "id": obj.id,
773                "label": self.label_of(o), "class": obj.class, "children": kids.len(), "findings": findings.json(),
774                "location": location(&obj.id), "grid": reveal(o, kids),
775            })
776        };
777        let items = entries
778            .into_iter()
779            .map(|e| match e {
780                Entry::Leaf(o) => object(o, format!("k/{}", self.objects[o as usize].id), &[], self.objects[o as usize].findings),
781                Entry::Node(n) => {
782                    let node = &self.nodes[n as usize];
783                    match node.what {
784                        What::Object { object: o, forest } => {
785                            object(o, format!("{forest}/{}", self.objects[o as usize].id), &node.children, node.findings)
786                        }
787                        What::Group { section, class } => json!({
788                            "key": format!("{section}/{class}"), "kind": "group", "class": class,
789                            "label": if class == MISSING { "Not in the set" } else { class },
790                            "children": node.children.len(), "findings": node.findings.json(),
791                        }),
792                        What::Section { key, label } => json!({
793                            "key": key, "kind": "section", "label": label, "children": node.children.len(), "findings": node.findings.json(),
794                        }),
795                    }
796                }
797            })
798            .collect();
799        Some(Value::Array(items))
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use std::path::Path;
806
807    use serde_json::Value;
808
809    use crate::testing::{collect, validate};
810
811    fn labels(v: &Value) -> Vec<&str> {
812        v.as_array()
813            .unwrap()
814            .iter()
815            .map(|x| x["label"].as_str().unwrap())
816            .collect()
817    }
818
819    /// MicroGrid: regions down to terminals, the boundary's lines among them;
820    /// each object once in the containment, findings summed up the tree.
821    #[test]
822    fn micro_grid_tree() {
823        let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
824            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
825        let files = collect(&dir);
826        assert_eq!(
827            files.len(),
828            12,
829            "missing test data — run `git submodule update --init`"
830        );
831        let set = validate(&files);
832        let t = &set.tree;
833        let children = |key: Option<&str>| t.children_json(&set, &set.grid, key, false).unwrap();
834        assert_eq!(
835            labels(&children(None)),
836            ["Geographical", "Operational", "Not contained", "By class"]
837        );
838
839        let geo = children(Some("geo"));
840        assert!(labels(&geo).contains(&"BE"), "{:?}", labels(&geo));
841        let find = |list: &Value, label: &str| {
842            list.as_array()
843                .unwrap()
844                .iter()
845                .find(|x| x["label"] == label)
846                .cloned()
847                .unwrap()
848        };
849        let be = find(&geo, "BE");
850        let sub_regions = children(be["key"].as_str());
851        let brussels_region = find(&sub_regions, "ELIA-Brussels");
852        let subs = children(brussels_region["key"].as_str());
853        let brussels = find(&subs, "PP_Brussels");
854        assert_eq!(brussels["class"], "Substation");
855        assert_eq!(brussels["grid"]["inside"], brussels["id"]);
856        // Its voltage levels first, then the transformers it holds itself.
857        let held = children(brussels["key"].as_str());
858        let classes: Vec<&str> = held
859            .as_array()
860            .unwrap()
861            .iter()
862            .map(|x| x["class"].as_str().unwrap())
863            .collect();
864        assert_eq!(&classes[..5], ["VoltageLevel"; 5], "{classes:?}");
865        assert!(classes.contains(&"PowerTransformer"), "{classes:?}");
866        assert_eq!(
867            t.containers(brussels["id"].as_str().unwrap()),
868            ["BE", "ELIA-Brussels"]
869        );
870
871        // Search: by name, ignoring case, the exact one first; by mRID.
872        assert_eq!(t.search("anvers", 5)[0].1, "Anvers");
873        // Names starting with it before names holding it; objects may share a name.
874        let lines: Vec<&str> = t.search("be-line_", 30).into_iter().map(|h| h.1).collect();
875        let starting = lines
876            .iter()
877            .take_while(|l| l.starts_with("BE-Line_"))
878            .count();
879        assert!(
880            starting >= 7
881                && lines[starting..]
882                    .iter()
883                    .all(|l| l.contains("BE-Line_") && !l.starts_with("BE-Line_")),
884            "{lines:?}"
885        );
886        let id = brussels["id"].as_str().unwrap();
887        assert_eq!(t.search(&id[3..15], 5)[0].0, id);
888        assert!(t.search("  ", 5).is_empty());
889        assert_eq!(
890            t.containers(held[0]["id"].as_str().unwrap()),
891            ["PP_Brussels"]
892        );
893
894        // Each object's path leads to it, a listed level at a time.
895        for group in children(Some("class")).as_array().unwrap() {
896            for x in children(group["key"].as_str()).as_array().unwrap() {
897                let keys = t.path(x["id"].as_str().unwrap(), false).unwrap();
898                assert!(["geo", "other"].contains(&keys[0].as_str()), "{keys:?}");
899                for step in keys.windows(2) {
900                    let listed = children(Some(&step[0]));
901                    assert!(
902                        listed
903                            .as_array()
904                            .unwrap()
905                            .iter()
906                            .any(|y| y["key"] == step[1].as_str()),
907                        "{keys:?}"
908                    );
909                }
910                assert_eq!(
911                    keys.last().unwrap(),
912                    &format!("c/{}", x["id"].as_str().unwrap())
913                );
914            }
915        }
916
917        // Each object of the set is once in Geographical or Not contained.
918        let mut seen = 0;
919        let mut stack: Vec<String> = vec!["geo".into(), "other".into()];
920        while let Some(key) = stack.pop() {
921            for x in children(Some(&key)).as_array().unwrap() {
922                if x["kind"] == "object" {
923                    seen += 1;
924                }
925                if x["children"].as_u64().unwrap() > 0 {
926                    stack.push(x["key"].as_str().unwrap().into());
927                }
928            }
929        }
930        let by_class: u64 = children(Some("class"))
931            .as_array()
932            .unwrap()
933            .iter()
934            .map(|x| x["children"].as_u64().unwrap())
935            .sum();
936        assert_eq!(seen, by_class);
937
938        // A section counts the findings of what it holds; By class, of every
939        // object, so all the findings on objects of the set.
940        let total = |x: &Value| {
941            ["violation", "warning", "info"]
942                .iter()
943                .map(|s| x["findings"][s].as_u64().unwrap())
944                .sum::<u64>()
945        };
946        let sections = children(None);
947        let sum_of = |key: &str| {
948            children(Some(key))
949                .as_array()
950                .unwrap()
951                .iter()
952                .map(total)
953                .sum::<u64>()
954        };
955        for s in sections.as_array().unwrap() {
956            assert_eq!(
957                total(s),
958                sum_of(s["key"].as_str().unwrap()),
959                "{}",
960                s["label"]
961            );
962        }
963        let all = total(&find(&sections, "By class"));
964        assert!(all > 0);
965        assert_eq!(
966            total(&find(&sections, "Geographical")) + total(&find(&sections, "Not contained")),
967            all
968        );
969        assert!(
970            t.children_json(&set, &set.grid, None, true)
971                .unwrap()
972                .as_array()
973                .unwrap()
974                .iter()
975                .all(|x| total(x) > 0)
976        );
977    }
978}