Skip to main content

powerio_dist/
terminal_index.rs

1//! The flat terminal index of a multiconductor network: every declared bus
2//! terminal at one position, in bus table order and each bus's stated
3//! terminal order. The one terminal indexing every multiconductor calculation
4//! reads, with one bus identity rule: bus names compare ASCII case
5//! insensitively, terminal names exactly.
6
7use std::collections::BTreeMap;
8
9use crate::model::MulticonductorNetwork;
10
11/// Why a network's terminals cannot be indexed.
12#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum TerminalIndexError {
15    /// Two buses share one identity, compared ASCII case insensitively.
16    DuplicateBus { bus: String },
17    /// A bus states one terminal twice.
18    DuplicateTerminal { bus: String, terminal: String },
19}
20
21impl std::fmt::Display for TerminalIndexError {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::DuplicateBus { bus } => {
25                write!(f, "bus identity `{bus}` is duplicated case-insensitively")
26            }
27            Self::DuplicateTerminal { bus, terminal } => {
28                write!(f, "bus `{bus}` repeats terminal `{terminal}`")
29            }
30        }
31    }
32}
33
34impl std::error::Error for TerminalIndexError {}
35
36/// Every declared terminal of a multiconductor network at one flat position.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct MulticonductorTerminalIndex {
39    /// Position to `(bus, terminal)` in the network's own spelling.
40    terminals: Vec<(String, String)>,
41    /// Folded bus name to terminal name to position.
42    positions: BTreeMap<String, BTreeMap<String, usize>>,
43}
44
45impl MulticonductorTerminalIndex {
46    /// Index `network`'s terminals: bus table order, each bus's stated
47    /// terminal order. Grounded terminals and terminal `0` are indexed like
48    /// any other; whether a calculation treats one as ground is its own rule.
49    ///
50    /// # Errors
51    /// Two buses whose identities differ only in ASCII case, or a bus that
52    /// states a terminal twice.
53    pub fn build(network: &MulticonductorNetwork) -> Result<Self, TerminalIndexError> {
54        let mut index = Self::default();
55        for bus in network.buses() {
56            let key = bus.id.to_ascii_lowercase();
57            if index.positions.contains_key(&key) {
58                return Err(TerminalIndexError::DuplicateBus {
59                    bus: bus.id.clone(),
60                });
61            }
62            let terminals = index.positions.entry(key).or_default();
63            for terminal in &bus.terminals {
64                if terminals
65                    .insert(terminal.clone(), index.terminals.len())
66                    .is_some()
67                {
68                    return Err(TerminalIndexError::DuplicateTerminal {
69                        bus: bus.id.clone(),
70                        terminal: terminal.clone(),
71                    });
72                }
73                index.terminals.push((bus.id.clone(), terminal.clone()));
74            }
75        }
76        Ok(index)
77    }
78
79    /// Position to `(bus, terminal)`, in the network's own spelling.
80    #[must_use]
81    pub fn terminals(&self) -> &[(String, String)] {
82        &self.terminals
83    }
84
85    /// The number of indexed terminals.
86    #[must_use]
87    pub fn len(&self) -> usize {
88        self.terminals.len()
89    }
90
91    /// Whether the network declares no terminal.
92    #[must_use]
93    pub fn is_empty(&self) -> bool {
94        self.terminals.is_empty()
95    }
96
97    /// The position of terminal `terminal` of bus `bus` (bus compared ASCII
98    /// case insensitively), or `None` for an undeclared terminal.
99    #[must_use]
100    pub fn resolve(&self, bus: &str, terminal: &str) -> Option<usize> {
101        self.bus(bus)?.get(terminal).copied()
102    }
103
104    /// The positions of one bus's terminals, ascending; empty for an
105    /// undeclared bus.
106    #[must_use]
107    pub fn bus_terminals(&self, bus: &str) -> Vec<usize> {
108        let mut positions: Vec<usize> = self
109            .bus(bus)
110            .map(|terminals| terminals.values().copied().collect())
111            .unwrap_or_default();
112        positions.sort_unstable();
113        positions
114    }
115
116    fn bus(&self, bus: &str) -> Option<&BTreeMap<String, usize>> {
117        self.positions
118            .get(bus)
119            .or_else(|| self.positions.get(&bus.to_ascii_lowercase()))
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::model::DistBus;
127
128    #[test]
129    fn terminals_index_flat_with_case_insensitive_buses() {
130        let mut network = MulticonductorNetwork::default();
131        network
132            .buses_mut()
133            .push(DistBus::new("Src", vec!["1".into(), "2".into()]));
134        network
135            .buses_mut()
136            .push(DistBus::new("load", vec!["1".into(), "0".into()]));
137        let index = MulticonductorTerminalIndex::build(&network).unwrap();
138        assert_eq!(index.len(), 4);
139        assert_eq!(index.resolve("src", "2"), Some(1));
140        assert_eq!(index.resolve("SRC", "2"), Some(1));
141        assert_eq!(index.resolve("load", "0"), Some(3));
142        assert_eq!(index.resolve("load", "3"), None);
143        assert_eq!(index.bus_terminals("LOAD"), vec![2, 3]);
144        network
145            .buses_mut()
146            .push(DistBus::new("LOAD", vec!["1".into()]));
147        assert!(matches!(
148            MulticonductorTerminalIndex::build(&network),
149            Err(TerminalIndexError::DuplicateBus { .. })
150        ));
151    }
152}