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