Skip to main content

powerio_dist/
voltage_zones.rs

1//! Voltage base zones: the buses that share one voltage base, and the flood
2//! of zone bases across transformers.
3
4use std::collections::BTreeMap;
5
6use crate::MulticonductorNetwork;
7
8/// Which switches join a voltage zone ([`calc_voltage_zone_labels`]).
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum ZoneSwitches {
12    /// Closed switches only: the zones of the energized network.
13    Closed,
14    /// Every switch, open or closed: an open tie still joins two sections
15    /// of one nominal voltage.
16    All,
17}
18
19/// The voltage zone of each network bus, in bus table order: buses joined by
20/// a line or a switch `switches` admits share a label (a representative bus
21/// index), with bus identities compared ASCII case insensitively.
22/// Transformers separate zones. The one network zone partition: the
23/// multiconductor to balanced lowering, the GridLAB-D writer and the load
24/// nominal voltage inference read it over closed switches, the MG-RAVENS
25/// writer's base voltages over every switch.
26///
27/// # Errors
28/// A line or admitted switch naming a bus the network does not declare.
29pub fn calc_voltage_zone_labels(
30    network: &MulticonductorNetwork,
31    switches: ZoneSwitches,
32) -> Result<Vec<usize>, String> {
33    let position: BTreeMap<String, usize> = network
34        .buses()
35        .iter()
36        .enumerate()
37        .map(|(index, bus)| (bus.id.to_ascii_lowercase(), index))
38        .collect();
39    let find = |bus: &str, label: &str| {
40        position
41            .get(&bus.to_ascii_lowercase())
42            .copied()
43            .ok_or_else(|| format!("{label} references unknown bus `{bus}`"))
44    };
45    let mut edges = Vec::new();
46    for line in network.lines() {
47        let label = format!("line `{}`", line.name);
48        edges.push((find(&line.bus_from, &label)?, find(&line.bus_to, &label)?));
49    }
50    for switch in network
51        .switches()
52        .iter()
53        .filter(|switch| switches == ZoneSwitches::All || !switch.open)
54    {
55        let label = format!("switch `{}`", switch.name);
56        edges.push((
57            find(&switch.bus_from, &label)?,
58            find(&switch.bus_to, &label)?,
59        ));
60    }
61    Ok(powerio_core::union_find::calc_component_labels(
62        network.buses().len(),
63        edges,
64    ))
65}
66
67/// Flood zone voltage bases across transformer edges, depth first from the
68/// seeded zones (`seeds`, in the order given; the last seed is explored
69/// first): crossing edge `k` from `edges[k].0` to `edges[k].1` gives the far
70/// zone `carry(k, true, base)`, and the reverse crossing
71/// `carry(k, false, base)`, where `base` is the near zone's. A zone keeps the
72/// first base that reaches it; `carry` returning `None` does not cross. The
73/// one zone base flood: the multiconductor to balanced lowering (the far
74/// winding's rated voltage) and the PMD MATHEMATICAL writer (`tm_nom`, as
75/// PMD's `calc_voltage_bases` scales) state only their crossing rule.
76pub fn calc_flooded_zone_bases(
77    seeds: impl IntoIterator<Item = (usize, f64)>,
78    edges: &[(usize, usize)],
79    carry: impl Fn(usize, bool, f64) -> Option<f64>,
80) -> BTreeMap<usize, f64> {
81    let mut adjacent: BTreeMap<usize, Vec<(usize, usize, bool)>> = BTreeMap::new();
82    for (k, &(from, to)) in edges.iter().enumerate() {
83        adjacent.entry(from).or_default().push((to, k, true));
84        adjacent.entry(to).or_default().push((from, k, false));
85    }
86    let mut base: BTreeMap<usize, f64> = BTreeMap::new();
87    let mut stack = Vec::new();
88    for (zone, value) in seeds {
89        if let std::collections::btree_map::Entry::Vacant(entry) = base.entry(zone) {
90            entry.insert(value);
91            stack.push(zone);
92        }
93    }
94    while let Some(near) = stack.pop() {
95        let near_base = base[&near];
96        for &(far, k, forward) in adjacent.get(&near).map_or(&[][..], Vec::as_slice) {
97            if base.contains_key(&far) {
98                continue;
99            }
100            if let Some(value) = carry(k, forward, near_base) {
101                base.insert(far, value);
102                stack.push(far);
103            }
104        }
105    }
106    base
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn bases_flood_from_the_seeds_across_each_edge_once() {
115        // zones 0 -(x10)- 1 -(x0.5)- 2, seeded at 1.
116        let edges = [(0, 1), (1, 2)];
117        let scale = [10.0, 0.5];
118        let base = calc_flooded_zone_bases([(1, 4.0)], &edges, |k, forward, value| {
119            Some(if forward {
120                value * scale[k]
121            } else {
122                value / scale[k]
123            })
124        });
125        assert_eq!(base, BTreeMap::from([(0, 0.4), (1, 4.0), (2, 2.0)]));
126    }
127}