Skip to main content

powerio_matrix/matrix/
ybus.rs

1//! Bus admittance matrix `Y_bus = G + jB` per MATPOWER's `makeYbus`.
2//!
3//! For each in-service branch from bus `i` to bus `j` with series impedance
4//! `z = r + jx`, terminal shunts `y_fr`/`y_to`, complex tap `a = tap * exp(j shift)`:
5//!
6//! ```text
7//! Y[i,i] += (1/z + y_fr) / |a|^2
8//! Y[j,j] += (1/z + y_to)
9//! Y[i,j] += -(1/z) / conj(a)
10//! Y[j,i] += -(1/z) / a
11//! ```
12//!
13//! Plus bus shunts `Y[i,i] += (g_s + j b_s) / baseMVA`.
14
15use num_complex::Complex64;
16use sprs::CsMat;
17
18use crate::Result;
19use crate::indexed::IndexedNetwork;
20
21use super::triplet::CooBuilder;
22
23/// `Re(Y_bus)` and `Im(Y_bus)` as separate CSR matrices.
24#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct YbusParts {
27    pub g: CsMat<f64>,
28    pub b: CsMat<f64>,
29}
30
31/// Internal flags used to derive MATPOWER `Bp` and `Bpp` from `Y_bus`.
32// Six independent on/off switches into one Y_bus kernel; an enum per pair
33// would just spread the same state across more types.
34#[allow(clippy::struct_excessive_bools)]
35#[derive(Debug, Clone, Copy)]
36pub(crate) struct YbusFlags {
37    pub zero_resistance: bool,
38    pub zero_charging: bool,
39    pub unity_taps: bool,
40    pub zero_shifts: bool,
41    pub skip_bus_shunts: bool,
42    pub skip_zero_impedance: bool,
43}
44
45impl Default for YbusFlags {
46    fn default() -> Self {
47        Self {
48            zero_resistance: false,
49            zero_charging: false,
50            unity_taps: false,
51            zero_shifts: false,
52            skip_bus_shunts: false,
53            skip_zero_impedance: true,
54        }
55    }
56}
57
58pub fn build_ybus(case: &IndexedNetwork, opts: &super::BuildOptions) -> Result<YbusParts> {
59    let flags = YbusFlags {
60        zero_resistance: false,
61        zero_charging: false,
62        unity_taps: !opts.include_taps,
63        zero_shifts: !opts.include_shifts,
64        skip_bus_shunts: false,
65        skip_zero_impedance: opts.skip_zero_impedance,
66    };
67    build_ybus_with_flags(case, flags)
68}
69
70// i/j bus indices, r/x impedance, a complex tap: the single-letter names are
71// the standard makeYbus notation and the math reads worse spelled out.
72#[allow(clippy::many_single_char_names)]
73pub(crate) fn build_ybus_with_flags(case: &IndexedNetwork, flags: YbusFlags) -> Result<YbusParts> {
74    // The bus shunt block divides by `per_unit_base()`. A zero or non-finite
75    // base made that `0.0/0.0`, storing NaN on every diagonal — including
76    // shunt-free buses, since `CooBuilder::add` skips only exact zero — and
77    // the matrix shipped with no error.
78    case.network().check_base_mva()?;
79    let n = case.n();
80    let mut g_coo = CooBuilder::with_capacity(n, 4 * case.branches().len() + n);
81    let mut b_coo = CooBuilder::with_capacity(n, 4 * case.branches().len() + n);
82
83    for (row_idx, br) in case.in_service_branches() {
84        let i = case.bus_index(br.from).ok_or(powerio::Error::UnknownBus {
85            bus_id: br.from,
86            element_index: row_idx,
87        })?;
88        let j = case.bus_index(br.to).ok_or(powerio::Error::UnknownBus {
89            bus_id: br.to,
90            element_index: row_idx,
91        })?;
92
93        let shift_rad = if flags.zero_shifts {
94            0.0
95        } else {
96            case.angle_radians(br.shift)
97        };
98        let Some([y_ii, y_ij, y_ji, y_jj]) = branch_admittance(br, flags, shift_rad, row_idx)?
99        else {
100            // Zero-impedance branch (r² + x² = 0): no admittance to scatter.
101            continue;
102        };
103
104        if i == j {
105            // Self-loop branch: combine all four contributions onto bus i.
106            let combined = y_ii + y_jj + y_ij + y_ji;
107            g_coo.add(i, i, combined.re);
108            b_coo.add(i, i, combined.im);
109            continue;
110        }
111
112        g_coo.add(i, i, y_ii.re);
113        b_coo.add(i, i, y_ii.im);
114        g_coo.add(j, j, y_jj.re);
115        b_coo.add(j, j, y_jj.im);
116        g_coo.add(i, j, y_ij.re);
117        b_coo.add(i, j, y_ij.im);
118        g_coo.add(j, i, y_ji.re);
119        b_coo.add(j, i, y_ji.im);
120    }
121
122    if !flags.skip_bus_shunts {
123        // ÷ per-unit base (1.0 if the network is already normalized), so a
124        // normalized network's shunts aren't divided by base a second time.
125        let base = case.per_unit_base();
126        for idx in 0..n {
127            g_coo.add(idx, idx, case.gs()[idx] / base);
128            b_coo.add(idx, idx, case.bs()[idx] / base);
129        }
130    }
131
132    Ok(YbusParts {
133        g: g_coo.finish_csr(),
134        b: b_coo.finish_csr(),
135    })
136}
137
138/// The four entries of a branch's 2×2 nodal admittance block, in per-unit:
139/// `[Yff, Yft, Ytf, Ytt]` (= `[y_ii, y_ij, y_ji, y_jj]` in `makeYbus` notation).
140/// A pure function of the branch — no bus indexing, no shunt fold — so the Y_bus
141/// assembly and the gridfm branch table compute the same numbers from one place.
142/// `flags` lets the Y_bus builder zero taps/shifts/charging; pass
143/// [`YbusFlags::default`] for the physical admittances (taps and shifts on).
144///
145/// Returns `Ok(None)` for a zero-impedance branch — one whose impedance
146/// magnitude is under [`MIN_DIVISIBLE_MAGNITUDE`](super::MIN_DIVISIBLE_MAGNITUDE) —
147/// which the callers skip (Y_bus) or zero out (gridfm). `row` only labels the
148/// error.
149///
150/// # Errors
151/// [`powerio::Error::NonFiniteSusceptance`] when `r`/`x` are NaN/Inf, so a bad value can't
152/// slip a NaN into Y_bus or a Parquet column. [`powerio::Error::DegenerateTap`] when the
153/// tap ratio is one the four admittances cannot be divided by.
154#[allow(clippy::many_single_char_names)]
155pub(crate) fn branch_admittance(
156    br: &crate::network::Branch,
157    flags: YbusFlags,
158    shift_rad: f64,
159    row: usize,
160) -> Result<Option<[Complex64; 4]>> {
161    let r = if flags.zero_resistance { 0.0 } else { br.r };
162    let x = br.x;
163    // Zero impedance in every sense the builder can act on; exact zero used to
164    // be the whole test. The guard and the division are shared with the AC
165    // path, so the two cannot drift; only the skip-vs-error policy is local.
166    let Some((g, b)) = powerio::series_admittance_of(r, x, row)? else {
167        if flags.skip_zero_impedance {
168            return Ok(None);
169        }
170        return Err(powerio::Error::ZeroImpedance { row }.into());
171    };
172    let y_series = Complex64::new(g, b);
173
174    let charging = if flags.zero_charging {
175        crate::network::BranchCharging::new(0.0, 0.0, 0.0, 0.0)
176    } else {
177        br.terminal_charging()
178    };
179    let y_fr = Complex64::new(charging.g_fr, charging.b_fr);
180    let y_to = Complex64::new(charging.g_to, charging.b_to);
181
182    // A tap of 1e-200 underflows `a_norm_sqr` to zero and scatters +/-Inf
183    // through the four admittances.
184    let tap_mag = if flags.unity_taps {
185        1.0
186    } else {
187        br.divisible_tap(row)?
188    };
189    // `shift_rad` is supplied already in radians and already zeroed when
190    // `flags.zero_shifts` is set (the caller has the network, so it knows whether
191    // the source angle is degrees or — for a normalized network — radians).
192    let a = Complex64::from_polar(tap_mag, shift_rad);
193    let a_norm_sqr = tap_mag * tap_mag;
194
195    let y_ff = (y_series + y_fr) / a_norm_sqr;
196    let y_tt = y_series + y_to;
197    let y_ft = -y_series / a.conj();
198    let y_tf = -y_series / a;
199    let out = [y_ff, y_ft, y_tf, y_tt];
200    // Each input is bounded on its own above; the products can still overflow
201    // when several sit near their bound at once.
202    if out.iter().any(|y| !y.re.is_finite() || !y.im.is_finite()) {
203        return Err(powerio::Error::NonFiniteSusceptance { row }.into());
204    }
205    Ok(Some(out))
206}
207
208/// Complex from/to power injections for one branch at the given bus voltages, in
209/// MVA before the per-unit → MW scaling the caller applies. `vi`/`vj` are complex
210/// bus voltages `vm·e^{jθ}` (θ in radians) and `y = [Yff, Yft, Ytf, Ytt]`:
211///
212/// ```text
213/// S_from = vi · conj(Yff·vi + Yft·vj)
214/// S_to   = vj · conj(Ytf·vi + Ytt·vj)
215/// ```
216///
217/// At a converged operating point these are the line flows; powerio computes them
218/// at the case's stored voltages (the parsed snapshot), not from a fresh solve.
219#[cfg(feature = "gridfm")]
220pub(crate) fn branch_flows(
221    y: &[Complex64; 4],
222    vi: Complex64,
223    vj: Complex64,
224) -> (Complex64, Complex64) {
225    let i_from = y[0] * vi + y[1] * vj;
226    let i_to = y[2] * vi + y[3] * vj;
227    (vi * i_from.conj(), vj * i_to.conj())
228}