1use crate::{Configuration, MulticonductorNetwork};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub struct ConnectionChannel {
11 pub from: usize,
12 pub to: Option<usize>,
13}
14
15impl ConnectionChannel {
16 const fn new(from: usize, to: Option<usize>) -> Self {
17 Self { from, to }
18 }
19}
20
21pub fn calc_connection_channels(
43 configuration: Configuration,
44 terminal_count: usize,
45 channel_count: usize,
46 neutral: Option<usize>,
47) -> Result<Vec<ConnectionChannel>, String> {
48 let channels = match configuration {
49 Configuration::SinglePhase | Configuration::Delta
50 if terminal_count == 2 && channel_count == 1 =>
51 {
52 vec![ConnectionChannel::new(0, Some(1))]
53 }
54 Configuration::Wye | Configuration::SinglePhase if terminal_count == channel_count => (0
55 ..terminal_count)
56 .map(|terminal| ConnectionChannel::new(terminal, None))
57 .collect(),
58 Configuration::Wye if terminal_count == channel_count + 1 => {
59 let neutral = neutral.unwrap_or(channel_count);
60 if neutral >= terminal_count {
61 return Err(format!(
62 "wye neutral position {neutral} is outside its {terminal_count} terminals"
63 ));
64 }
65 (0..terminal_count)
66 .filter(|&terminal| terminal != neutral)
67 .map(|phase| ConnectionChannel::new(phase, Some(neutral)))
68 .collect()
69 }
70 Configuration::Delta if channel_count > 0 && terminal_count == 2 * channel_count => (0
71 ..channel_count)
72 .map(|pair| ConnectionChannel::new(2 * pair, Some(2 * pair + 1)))
73 .collect(),
74 Configuration::Delta if channel_count > 0 && terminal_count == channel_count => (0
75 ..terminal_count)
76 .map(|terminal| ConnectionChannel::new(terminal, Some((terminal + 1) % terminal_count)))
77 .collect(),
78 _ => {
79 return Err(format!(
80 "{configuration:?} connection with {terminal_count} terminals and {channel_count} channels is unsupported"
81 ));
82 }
83 };
84 Ok(channels)
85}
86
87#[must_use]
94pub fn lindist3flow_carries_connection(
95 configuration: Configuration,
96 terminal_count: usize,
97 channel_count: usize,
98) -> bool {
99 calc_connection_channels(configuration, terminal_count, channel_count, None).is_ok_and(
100 |channels| match configuration {
101 Configuration::Wye => channels.iter().all(|channel| channel.to.is_none()),
102 Configuration::Delta => {
103 channels.len() == 1 || (channels.len() == 3 && terminal_count == 3)
104 }
105 _ => true,
106 },
107 )
108}
109
110pub fn calc_wye_neutral_position(
121 network: &MulticonductorNetwork,
122 bus: &str,
123 terminal_map: &[String],
124) -> Result<Option<usize>, String> {
125 let declared = network
126 .bus(bus)
127 .ok_or_else(|| format!("bus `{bus}` is not declared"))?;
128 calc_mapped_neutral_position(
129 &declared.terminals,
130 terminal_map,
131 network.terminal_conventions(),
132 )
133 .map_err(|reason| format!("bus `{bus}` {reason}"))
134}
135
136pub fn calc_mapped_neutral_position<S: AsRef<str>>(
146 bus_terminals: &[S],
147 terminal_map: &[String],
148 conventions: Option<&serde_json::Value>,
149) -> Result<Option<usize>, String> {
150 let mut nonphase = terminal_map
151 .iter()
152 .enumerate()
153 .filter(|(_, terminal)| {
154 !bus_terminals
155 .iter()
156 .any(|t| t.as_ref() == terminal.as_str())
157 || crate::calc_terminal_role(bus_terminals, terminal, conventions)
158 != crate::TerminalRole::Phase
159 })
160 .map(|(position, _)| position);
161 let neutral = nonphase.next();
162 if nonphase.next().is_some() {
163 return Err("maps more than one non-phase terminal: the WYE neutral is ambiguous".into());
164 }
165 Ok(neutral)
166}
167
168pub fn calc_element_connection(
183 network: &MulticonductorNetwork,
184 bus: &str,
185 terminal_map: &[String],
186 configuration: Configuration,
187 channel_count: Option<usize>,
188) -> Result<Vec<ConnectionChannel>, String> {
189 let neutral = if configuration == Configuration::Wye {
190 calc_wye_neutral_position(network, bus, terminal_map)?
191 } else {
192 None
193 };
194 let count = terminal_map.len();
195 let channels = channel_count.unwrap_or(match configuration {
196 Configuration::Wye => count - usize::from(neutral.is_some()),
197 _ if count == 2 => 1,
198 _ => count,
199 });
200 calc_connection_channels(configuration, count, channels, neutral)
201}
202
203pub fn orient_delta_ring(channels: &mut [ConnectionChannel], direction: i8) {
207 let n = channels.len();
208 if direction >= 0 || n < 3 {
209 return;
210 }
211 let positives: Vec<usize> = channels.iter().map(|channel| channel.from).collect();
212 for (k, channel) in channels.iter_mut().enumerate() {
213 channel.to = Some(positives[(k + n - 1) % n]);
214 }
215}
216
217pub fn calc_capacitor_susceptance(
241 network: &MulticonductorNetwork,
242 capacitor: &crate::DistCapacitor,
243) -> Result<Option<crate::model::ConductorMatrix>, String> {
244 if !matches!(
245 capacitor.configuration,
246 Configuration::Wye | Configuration::Delta | Configuration::SinglePhase
247 ) {
248 return Ok(None);
249 }
250 if !capacitor.q_rated.is_finite() || !capacitor.v_nom.is_finite() || capacitor.v_nom <= 0.0 {
251 return Err(format!(
252 "capacitor `{}` states no finite nameplate reactive power at a positive voltage",
253 capacitor.name
254 ));
255 }
256 let terminals = capacitor.terminal_map.len();
257 if capacitor.configuration == Configuration::SinglePhase && terminals != 2 {
258 return Err(format!(
259 "single phase capacitor `{}` maps {terminals} terminals",
260 capacitor.name
261 ));
262 }
263 let coils = calc_element_connection(
264 network,
265 &capacitor.bus,
266 &capacitor.terminal_map,
267 capacitor.configuration,
268 None,
269 )
270 .map_err(|reason| format!("capacitor `{}`: {reason}", capacitor.name))?;
271 let coil_voltage = if capacitor.configuration == Configuration::Wye && terminals > 1 {
272 crate::electrical::calc_wye_phase_voltage(capacitor.v_nom)
273 } else {
274 capacitor.v_nom
275 };
276 let y = crate::electrical::calc_rated_admittance(
277 capacitor.q_rated / (coils.len() as f64),
278 coil_voltage,
279 );
280 Ok(Some(calc_coil_susceptance_matrix(
281 terminals,
282 &coils,
283 &vec![y; coils.len()],
284 )))
285}
286
287#[must_use]
299pub fn calc_coil_susceptance_matrix(
300 terminal_count: usize,
301 coils: &[ConnectionChannel],
302 susceptance: &[f64],
303) -> crate::model::ConductorMatrix {
304 assert_eq!(
305 coils.len(),
306 susceptance.len(),
307 "one susceptance per capacitor coil"
308 );
309 let mut matrix = vec![vec![0.0; terminal_count]; terminal_count];
310 for (coil, &y) in coils.iter().zip(susceptance) {
311 matrix[coil.from][coil.from] += y;
312 if let Some(to) = coil.to {
313 matrix[to][to] += y;
314 matrix[coil.from][to] -= y;
315 matrix[to][coil.from] -= y;
316 }
317 }
318 matrix
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 fn pairs(channels: &[ConnectionChannel]) -> Vec<(usize, Option<usize>)> {
326 channels.iter().map(|c| (c.from, c.to)).collect()
327 }
328
329 #[test]
330 fn every_connection_shape_has_one_channel_per_power() {
331 let wye = calc_connection_channels(Configuration::Wye, 3, 3, None).unwrap();
332 assert_eq!(pairs(&wye), [(0, None), (1, None), (2, None)]);
333 let neutral = calc_connection_channels(Configuration::Wye, 4, 3, None).unwrap();
334 assert_eq!(pairs(&neutral), [(0, Some(3)), (1, Some(3)), (2, Some(3))]);
335 let first = calc_connection_channels(Configuration::Wye, 4, 3, Some(0)).unwrap();
336 assert_eq!(pairs(&first), [(1, Some(0)), (2, Some(0)), (3, Some(0))]);
337 let single = calc_connection_channels(Configuration::SinglePhase, 2, 1, None).unwrap();
338 assert_eq!(pairs(&single), [(0, Some(1))]);
339 let ring = calc_connection_channels(Configuration::Delta, 3, 3, None).unwrap();
340 assert_eq!(pairs(&ring), [(0, Some(1)), (1, Some(2)), (2, Some(0))]);
341 let stated = calc_connection_channels(Configuration::Delta, 4, 2, None).unwrap();
342 assert_eq!(pairs(&stated), [(0, Some(1)), (2, Some(3))]);
343 assert!(calc_connection_channels(Configuration::Wye, 5, 3, None).is_err());
344 assert!(calc_connection_channels(Configuration::Wye, 4, 3, Some(4)).is_err());
345 assert!(calc_connection_channels(Configuration::Delta, 5, 2, None).is_err());
346 }
347}