Skip to main content

powerio_dist/
connection.rs

1//! The channels of a typed load, injection, capacitor or winding connection.
2
3use crate::{Configuration, MulticonductorNetwork};
4
5/// One channel of a connection: the terminal its power enters and the
6/// terminal it returns through, as positions in the element's terminal map.
7/// `to` is `None` for a channel that returns through ground.
8#[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
21/// The channels of a connection of `terminal_count` terminals carrying
22/// `channel_count` stated powers, one channel per power in power order:
23///
24/// - single phase or delta, two terminals and one power: the first terminal
25///   to the second;
26/// - wye or single phase, one terminal per power: each terminal to ground;
27/// - wye with one terminal more than its powers: each phase terminal to the
28///   neutral, the terminal at `neutral` or else the last;
29/// - delta with two terminals per power: each consecutive pair, the first of
30///   the pair to the second;
31/// - delta with one terminal per power: a ring, terminal `k` to terminal
32///   `k + 1`, the last back to the first.
33///
34/// `neutral` is read only for a wye with an explicit neutral. The one
35/// connection rule: the LinDist3Flow incidence, the GridLAB-D writer,
36/// [`calc_element_connection`] (every load, capacitor, inverter, source and
37/// transformer winding the multiconductor calculations connect) read it.
38///
39/// # Errors
40/// A configuration and arity that describe none of these connections, or a
41/// `neutral` position outside the terminal map.
42pub 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/// Whether the LinDist3Flow model carries a connection: its
88/// [`calc_connection_channels`] exist and need no explicit neutral and no
89/// split delta, so every WYE channel returns through ground and a DELTA
90/// connection is one terminal pair or the three phase ring. The one
91/// LinDist3Flow connection rule: the instance shape check and the incidence
92/// builder read it.
93#[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
110/// The position of a WYE connection's explicit neutral in an element's
111/// terminal map: the one mapped terminal whose role on the bus
112/// ([`crate::calc_terminal_role`] over the network's terminal conventions)
113/// is not a phase, ground terminal `0` included
114/// ([`calc_mapped_neutral_position`]). `None` when every mapped terminal is
115/// a phase.
116///
117/// # Errors
118/// A bus the network does not declare, or more than one mapped terminal
119/// that is not a phase.
120pub 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
136/// The position in `terminal_map` of the one mapped terminal that is not a
137/// phase of a bus with terminals `bus_terminals`: a terminal the bus does
138/// not carry, or one whose [`crate::calc_terminal_role`] under
139/// `conventions` is neutral or earth. `None` when every mapped terminal is a
140/// phase. The one WYE neutral rule: [`calc_wye_neutral_position`] reads it
141/// over a network, the BMOPF capacitor lowering over a document's bus.
142///
143/// # Errors
144/// More than one mapped terminal that is not a phase.
145pub 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
168/// The channels of an element's connection at `bus` over its terminal map
169/// ([`calc_connection_channels`]), with a WYE neutral found by
170/// [`calc_wye_neutral_position`]. `channel_count` is the element's number of
171/// stated powers or phases; `None` reads it from the map: a WYE has one
172/// channel per phase terminal, a two terminal DELTA or single phase element
173/// one channel, and any other DELTA one channel per terminal (a ring).
174///
175/// The one rule for which terminal pair each coil of a connection spans:
176/// the multiconductor OPF, the capacitor primitive, the transformer
177/// primitive and its ideal constraints read it.
178///
179/// # Errors
180/// An undeclared bus, an ambiguous WYE neutral, or a connection
181/// [`calc_connection_channels`] refuses.
182pub 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
203/// Orient a DELTA ring of channels: `+1` keeps each channel from terminal
204/// `k` to the next terminal of the ring, `-1` returns each to the preceding
205/// one. A ring of fewer than three channels has one orientation.
206pub 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
217/// A capacitor bank's susceptance matrix, siemens, over its terminal map.
218///
219/// Each coil of the bank's connection ([`calc_element_connection`]: a WYE
220/// coil from each phase to its neutral or to ground, a DELTA coil between
221/// consecutive terminals or across a two terminal bank, a single phase coil
222/// across its two terminals) carries an equal share of the rated reactive
223/// power at its coil voltage:
224///
225/// ```text
226/// b = q_rated / coils / V²,   V = v_nom / √3 (WYE with more than one terminal), v_nom otherwise
227/// ```
228///
229/// The WYE nameplate is line to line when the bank has an explicit return
230/// or several phases; a one terminal WYE bank states its coil voltage.
231/// `None` for a configuration with no capacitor connection. The one
232/// capacitor stamp: the multiconductor admittance matrix
233/// (`powerio_matrix::calc_capacitor_primitive_admittance`), the PMD and PMD
234/// MATHEMATICAL writers and the LinDist3Flow preparation read it.
235///
236/// # Errors
237/// A nameplate that is not finite with a positive voltage, or a terminal map
238/// its configuration cannot carry (an undeclared bus, an ambiguous WYE
239/// neutral, a single phase bank without two terminals).
240pub 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/// The susceptance matrix over `terminal_count` terminals of coils
288/// `coils` with susceptances `susceptance` (one per coil, in coil order):
289/// each coil adds its susceptance to its terminal's diagonal and, when it
290/// returns through another terminal rather than ground, to that terminal's
291/// diagonal and subtracts it between the two. The one capacitor coil
292/// stamp: [`calc_capacitor_susceptance`], the BMOPF per coil capacitor
293/// lowering and the OpenDSS common return capacitor bank read it.
294///
295/// # Panics
296/// A coil terminal outside `terminal_count`, or a number of susceptances
297/// other than the number of coils.
298#[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}