Skip to main content

powerio_matrix/
ac_jacobian.rs

1//! The sparse AC power flow Jacobian at an operating point (#407).
2//!
3//! [`calc_power_flow_jacobian`] returns the full physical derivative of every
4//! bus active and reactive power injection with respect to every voltage
5//! coordinate, `2n × 2n`, over an [`AcPfInstance`] plus a separately supplied
6//! complete [`OperatingPoint`] sharing the same network identities. It does
7//! not replace columns with generator injection variables, remove fixed
8//! variables, or add voltage setpoint equations: those belong to the solver
9//! that selects its equations and variable arrangement.
10//!
11//! Row `k` is bus `k`'s active power and row `n + k` its reactive power, in
12//! bus table order. Under polar coordinates column `m` is bus `m`'s voltage
13//! angle (radians) and column `n + m` its voltage magnitude (per unit); under
14//! Cartesian coordinates the columns are the real then imaginary voltage. All
15//! powers are per unit on the network MVA base.
16//!
17//! The sparse structure is allocated once from the admittance matrix pattern;
18//! [`PowerFlowJacobian::update`] refreshes the numerical values in place
19//! across operating points with unchanged topology.
20
21use crate::matrix::YbusParts;
22use crate::{IndexCore, IndexedNetwork, SparseMatrix};
23use powerio_core::Error;
24use powerio_tx::BusId;
25
26use powerio_prob::diagnostics::codes;
27use powerio_prob::{AcPfInstance, BalancedOperatingPointQuantity, OperatingPoint};
28
29/// The voltage coordinate selection, the one option of the calculation.
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum VoltageCoordinates {
33    /// Angle (radians) then magnitude (per unit) columns.
34    #[default]
35    Polar,
36    /// Real then imaginary voltage columns, both per unit.
37    Cartesian,
38}
39
40/// The assembled sparse physical Jacobian, with its bus mappings and the
41/// machinery to update values in place.
42#[derive(Clone, Debug)]
43pub struct PowerFlowJacobian {
44    coordinates: VoltageCoordinates,
45    bus_ids: Vec<BusId>,
46    matrix: SparseMatrix,
47    /// The merged admittance rows the values derive from, built once:
48    /// sorted `(column, g, b)` per bus row.
49    admittance_rows: Vec<Vec<(usize, f64, f64)>>,
50    /// The instance network's derived index, cached so
51    /// [`update`](Self::update) rebinds a view over a fresh instance with
52    /// [`IndexedNetwork::with_core`] instead of re-deriving it on every
53    /// refresh. `None` for a Jacobian assembled
54    /// [`from_admittance`](Self::from_admittance), which has no instance.
55    index_core: Option<IndexCore>,
56}
57
58impl PowerFlowJacobian {
59    /// The `2n × 2n` sparse matrix. Row `k` is active power at bus `k`, row
60    /// `n + k` reactive power; the columns follow
61    /// [`coordinates`](Self::coordinates).
62    #[must_use]
63    pub const fn matrix(&self) -> &SparseMatrix {
64        &self.matrix
65    }
66
67    /// The bus behind row and column block position `k`, for both blocks of
68    /// both dimensions.
69    #[must_use]
70    pub fn bus_ids(&self) -> &[BusId] {
71        &self.bus_ids
72    }
73
74    /// The selected voltage coordinates.
75    #[must_use]
76    pub const fn coordinates(&self) -> VoltageCoordinates {
77        self.coordinates
78    }
79
80    /// Refresh the numerical values at a new operating point. The sparse
81    /// structure and the admittance parts are reused; topology changes
82    /// require a rebuild through [`calc_power_flow_jacobian`].
83    ///
84    /// # Errors
85    /// An operating point that does not share the instance's network
86    /// identities or does not state both voltage quantities.
87    pub fn update(
88        &mut self,
89        instance: &AcPfInstance,
90        point: &OperatingPoint<powerio_tx::BalancedNetwork>,
91    ) -> Result<(), Error> {
92        let Some(index_core) = &self.index_core else {
93            return Err(Error::new(
94                &codes::BUILD_OPERATING_POINT_IDENTITY_UNKNOWN,
95                "a Jacobian assembled from an admittance matrix has no instance to pair an \
96                 operating point with; refresh it with update_from_voltages",
97            ));
98        };
99        // `with_core` rebinds a view over the cached derivation with no
100        // allocation when the instance's network has no 3-winding
101        // transformer (the common case); it only re-derives the core when
102        // one is present, matching `new`'s behavior exactly either way.
103        let view = IndexedNetwork::with_core(instance.network(), index_core);
104        // The refresh operates on the axis the structure was assembled over;
105        // an instance lowering to a different bus count is a different
106        // problem, never a value update.
107        if view.n() != self.bus_ids.len() {
108            return Err(Error::new(
109                &codes::BUILD_OPERATING_POINT_IDENTITY_UNKNOWN,
110                "the instance's lowered bus axis does not match the assembled Jacobian's",
111            ));
112        }
113        // Identity pairing between an instance and a point is validated
114        // with a real error the one time `calc_power_flow_jacobian` built
115        // this Jacobian; every refresh after that trusts the same pairing
116        // and only asserts it in debug builds.
117        let voltages = point_voltages(instance, point, &self.bus_ids, &view, false)?;
118        let injection = calc_injection(&self.admittance_rows, &voltages.magnitude, &voltages.angle);
119        fill_values(
120            &mut self.matrix,
121            &self.admittance_rows,
122            &injection,
123            self.coordinates,
124        );
125        Ok(())
126    }
127
128    /// Assemble the Jacobian over a caller's bus admittance matrix at the
129    /// voltages `vm` (per unit) and `va` (radians), in the matrix's own bus
130    /// order. `bus_ids` names the bus behind each row; a preparation passes
131    /// its `bus_ids` with the matrix from its `calc_admittance_matrix`. The
132    /// values are the same functions of `(G, B, vm, va)` that
133    /// [`calc_power_flow_jacobian`] fills, so a solver that already holds
134    /// its admittance matrix and voltages builds the structure once here and
135    /// refreshes it with [`update_from_voltages`](Self::update_from_voltages)
136    /// on every iteration, with no operating point or identity check.
137    ///
138    /// # Errors
139    /// An admittance matrix that is not square, a conductance and
140    /// susceptance of different shapes, or `bus_ids`, `vm` or `va` whose
141    /// length is not the matrix side.
142    pub fn from_admittance(
143        admittance: &YbusParts,
144        bus_ids: Vec<BusId>,
145        coordinates: VoltageCoordinates,
146        vm: &[f64],
147        va: &[f64],
148    ) -> Result<Self, Error> {
149        let n = admittance.g.rows();
150        if admittance.g.cols() != n || admittance.b.shape() != (n, n) {
151            return Err(Error::new(
152                &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
153                "the admittance matrix the Jacobian derives from must be square, with \
154                 conductance and susceptance of one shape",
155            ));
156        }
157        if bus_ids.len() != n {
158            return Err(Error::new(
159                &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
160                format!(
161                    "{} bus ids for an admittance matrix of side {n}",
162                    bus_ids.len()
163                ),
164            ));
165        }
166        check_voltage_lengths(n, vm, va)?;
167        let mut jacobian = assemble(&admittance.g, &admittance.b, bus_ids, coordinates, None);
168        let injection = calc_injection(&jacobian.admittance_rows, vm, va);
169        fill_values(
170            &mut jacobian.matrix,
171            &jacobian.admittance_rows,
172            &injection,
173            coordinates,
174        );
175        Ok(jacobian)
176    }
177
178    /// The bus power injection `S = diag(V) conj(Y V)` over this Jacobian's
179    /// admittance at the voltages `vm` (per unit) and `va` (radians) in bus
180    /// row order: the power flow mismatch's network term. Pass the result to
181    /// [`update_from_injection`](Self::update_from_injection) to refresh the
182    /// Jacobian at the same voltages without forming the injection again, so
183    /// a Newton step computes it once for the mismatch and the Jacobian.
184    ///
185    /// # Errors
186    /// `vm` or `va` whose length is not the bus count.
187    pub fn calc_bus_power_injection(
188        &self,
189        vm: &[f64],
190        va: &[f64],
191    ) -> Result<BusPowerInjection, Error> {
192        check_voltage_lengths(self.bus_ids.len(), vm, va)?;
193        Ok(calc_injection(&self.admittance_rows, vm, va))
194    }
195
196    /// Refresh the numerical values at the voltages an injection from
197    /// [`calc_bus_power_injection`](Self::calc_bus_power_injection) was
198    /// formed at, reusing its currents and powers. The injection must come
199    /// from this Jacobian (or one assembled over the same admittance); the
200    /// values are those [`update_from_voltages`](Self::update_from_voltages)
201    /// fills at the same voltages.
202    ///
203    /// # Errors
204    /// An injection whose bus count is not this Jacobian's.
205    pub fn update_from_injection(&mut self, injection: &BusPowerInjection) -> Result<(), Error> {
206        if injection.p.len() != self.bus_ids.len() {
207            return Err(Error::new(
208                &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
209                format!(
210                    "an injection over {} buses for a Jacobian over {}",
211                    injection.p.len(),
212                    self.bus_ids.len()
213                ),
214            ));
215        }
216        fill_values(
217            &mut self.matrix,
218            &self.admittance_rows,
219            injection,
220            self.coordinates,
221        );
222        Ok(())
223    }
224
225    /// Refresh the numerical values at the voltages `vm` (per unit) and `va`
226    /// (radians) in bus row order. The sparse structure and admittance are
227    /// reused; this is the per iteration refresh of a Newton solve.
228    ///
229    /// # Errors
230    /// `vm` or `va` whose length is not the bus count.
231    pub fn update_from_voltages(&mut self, vm: &[f64], va: &[f64]) -> Result<(), Error> {
232        let injection = self.calc_bus_power_injection(vm, va)?;
233        self.update_from_injection(&injection)
234    }
235}
236
237/// The complex power injection `S = diag(V) conj(Y V)` at every bus, split
238/// into active and reactive parts `(p, q)`, at the voltages `vm` (per unit)
239/// and `va` (radians) in the admittance matrix's bus order. The injections
240/// are the ones the Jacobian of [`PowerFlowJacobian::from_admittance`]
241/// differentiates, formed by the same calculation as
242/// [`PowerFlowJacobian::calc_bus_power_injection`]; a solver that holds a
243/// Jacobian calls that method instead, which reuses its merged admittance.
244///
245/// # Errors
246/// An admittance matrix that is not square, or voltages whose length is not
247/// its side.
248pub fn calc_bus_power_injection(
249    admittance: &YbusParts,
250    vm: &[f64],
251    va: &[f64],
252) -> Result<(Vec<f64>, Vec<f64>), Error> {
253    let n = admittance.g.rows();
254    if admittance.g.cols() != n || admittance.b.shape() != (n, n) {
255        return Err(Error::new(
256            &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
257            "the admittance matrix must be square, with conductance and susceptance of one shape",
258        ));
259    }
260    check_voltage_lengths(n, vm, va)?;
261    let injection = calc_injection(&merge_admittance_rows(&admittance.g, &admittance.b), vm, va);
262    Ok((injection.p, injection.q))
263}
264
265fn check_voltage_lengths(n: usize, vm: &[f64], va: &[f64]) -> Result<(), Error> {
266    if vm.len() != n || va.len() != n {
267        return Err(Error::new(
268            &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
269            format!(
270                "{} voltage magnitudes and {} angles for {n} buses",
271                vm.len(),
272                va.len()
273            ),
274        ));
275    }
276    Ok(())
277}
278
279/// The sparse structure over an admittance pattern: each admittance entry
280/// contributes to all four blocks, and every diagonal position is present for
281/// the current terms. Values are left for [`fill_values`].
282///
283/// Row `k` and row `n + k` both hold the columns of merged admittance row
284/// `k` (which always includes the diagonal), first in the angle block and
285/// then in the magnitude block. The CSR is written in that layout directly,
286/// so the fill walks each row beside its admittance row with no search.
287fn assemble(
288    conductance: &SparseMatrix,
289    susceptance: &SparseMatrix,
290    bus_ids: Vec<BusId>,
291    coordinates: VoltageCoordinates,
292    index_core: Option<IndexCore>,
293) -> PowerFlowJacobian {
294    let n = bus_ids.len();
295    let admittance_rows = merge_admittance_rows(conductance, susceptance);
296    let nnz: usize = admittance_rows.iter().map(Vec::len).sum::<usize>() * 4;
297    let mut indptr = Vec::with_capacity(2 * n + 1);
298    let mut indices = Vec::with_capacity(nnz);
299    indptr.push(0);
300    for _block in 0..2 {
301        for row in &admittance_rows {
302            indices.extend(row.iter().map(|&(column, _, _)| column));
303            indices.extend(row.iter().map(|&(column, _, _)| n + column));
304            indptr.push(indices.len());
305        }
306    }
307    let data = vec![0.0; indices.len()];
308    PowerFlowJacobian {
309        coordinates,
310        bus_ids,
311        matrix: SparseMatrix::new((2 * n, 2 * n), indptr, indices, data),
312        admittance_rows,
313        index_core,
314    }
315}
316
317/// One complete complex voltage assignment, split for the fill.
318struct Voltages {
319    magnitude: Vec<f64>,
320    angle: Vec<f64>,
321}
322
323/// Compute the sparse physical AC power flow Jacobian for `instance` at
324/// `point`.
325///
326/// # Errors
327/// An operating point that does not share the instance's network identities
328/// or does not state bus voltage magnitudes and angles; an admittance build
329/// failure (a zero impedance branch is refused, never skipped).
330pub fn calc_power_flow_jacobian(
331    instance: &AcPfInstance,
332    point: &OperatingPoint<powerio_tx::BalancedNetwork>,
333    coordinates: VoltageCoordinates,
334) -> Result<PowerFlowJacobian, Error> {
335    let network = instance.network();
336    // Derived once here and cached on the returned Jacobian, so
337    // `update` rebinds a view over it with `IndexedNetwork::with_core`
338    // instead of re-deriving it on every refresh.
339    let index_core = IndexCore::build(network);
340    // The analysis axis comes from the same lowered view the admittance is
341    // built from, so a three winding expansion's star buses are part of the
342    // pattern and the assembled dimension always equals the admittance
343    // dimension.
344    let view = IndexedNetwork::with_core(network, &index_core);
345    let bus_ids: Vec<BusId> = (0..view.n()).map(|idx| view.bus_id(idx)).collect();
346    // The one point this pairing is validated with a real error; every
347    // later `update` call trusts it instead (see `point_voltages`).
348    let voltages = point_voltages(instance, point, &bus_ids, &view, true)?;
349
350    let parts = crate::calc_admittance_matrix(
351        &view,
352        &crate::BuildOptions {
353            skip_zero_impedance: false,
354            ..Default::default()
355        },
356    )
357    .map_err(|error| {
358        Error::new(
359            &codes::BUILD_OPERATOR_ZERO_IMPEDANCE,
360            format!(
361                "the admittance matrix the Jacobian derives from cannot be built: {error}; resolve zero impedance branches explicitly with merge_zero_impedance_buses"
362            ),
363        )
364    })?;
365
366    let mut jacobian = assemble(&parts.g, &parts.b, bus_ids, coordinates, Some(index_core));
367    let injection = calc_injection(
368        &jacobian.admittance_rows,
369        &voltages.magnitude,
370        &voltages.angle,
371    );
372    fill_values(
373        &mut jacobian.matrix,
374        &jacobian.admittance_rows,
375        &injection,
376        coordinates,
377    );
378    Ok(jacobian)
379}
380
381/// The complete voltage assignment from the operating point, in bus row
382/// order, with the identity checks #407 requires.
383///
384/// `validate_identities` runs the network pairing check with a real error on
385/// mismatch — [`calc_power_flow_jacobian`] passes `true` the one time it
386/// builds a Jacobian. [`PowerFlowJacobian::update`] passes `false`: every
387/// refresh reuses the pairing that build already proved, so re-checking it
388/// in full on each call would cost as much as the rebuild `update` exists to
389/// avoid; the same check still runs as a `debug_assert` to catch a
390/// genuine misuse in tests.
391fn point_voltages(
392    instance: &AcPfInstance,
393    point: &OperatingPoint<powerio_tx::BalancedNetwork>,
394    bus_ids: &[BusId],
395    view: &IndexedNetwork<'_>,
396    validate_identities: bool,
397) -> Result<Voltages, Error> {
398    // The point must share the instance's own bus identity list exactly, in
399    // the same order; the analysis axis may extend it with the expansion's
400    // star buses, whose voltages come from the lowered network below. Every
401    // bus quantity's column order is `network.buses()` order (how
402    // `BalancedOperatingPointBuilder` lays the columns out), so this reads
403    // the typed quantity iterators rather than allocating a decimal spelling
404    // of every bus id to look one up at a time.
405    let raw_buses = instance.network().buses();
406    let read_bus_values = |values: powerio_prob::OperatingPointValues<'_>| {
407        if values.len() != raw_buses.len() {
408            return Err(Error::new(
409                &codes::BUILD_OPERATING_POINT_IDENTITY_UNKNOWN,
410                "the operating point's network does not share the instance's bus identities",
411            ));
412        }
413        let identities_match = values
414            .clone()
415            .zip(raw_buses)
416            .all(|((id, _), bus)| id.parse::<usize>().is_ok_and(|id| id == bus.id.0));
417        if validate_identities && !identities_match {
418            return Err(Error::new(
419                &codes::BUILD_OPERATING_POINT_IDENTITY_UNKNOWN,
420                "the operating point's network does not share the instance's bus identities",
421            ));
422        } else if !validate_identities {
423            debug_assert!(
424                identities_match,
425                "operating point bus identities do not match the instance's; this pairing \
426                 is checked once when the Jacobian is built and trusted on every refresh"
427            );
428        }
429        Ok(values.map(|(_, value)| value).collect::<Vec<_>>())
430    };
431
432    // Both quantities' complete columns, one bulk read each rather than one
433    // string keyed lookup per bus per quantity.
434    let (Some(magnitude_values), Some(angle_values)) = (
435        point.values(BalancedOperatingPointQuantity::BusVoltageMagnitude),
436        point.values(BalancedOperatingPointQuantity::BusVoltageAngle),
437    ) else {
438        return Err(Error::new(
439            &codes::BUILD_OPERATING_POINT_SHAPE_MISMATCH,
440            "the operating point does not state a complete complex voltage at every bus; \
441             the Jacobian needs both quantities",
442        ));
443    };
444
445    let raw_n = raw_buses.len();
446    let mut magnitude = read_bus_values(magnitude_values)?;
447    let mut angle = read_bus_values(angle_values)?;
448    magnitude.reserve(bus_ids.len() - raw_n);
449    angle.reserve(bus_ids.len() - raw_n);
450    for (idx, &bus) in bus_ids.iter().enumerate().skip(raw_n) {
451        // A star bus the three winding expansion synthesized: the point
452        // cannot state it, so its voltage comes from the lowered network's
453        // own stated values, through a checked lookup.
454        let star = view
455            .network()
456            .buses()
457            .get(idx)
458            .filter(|star| star.id == bus);
459        let Some(star) = star else {
460            return Err(Error::new(
461                &codes::BUILD_OPERATING_POINT_IDENTITY_UNKNOWN,
462                "the operating point's network does not share the instance's bus identities",
463            ));
464        };
465        magnitude.push(star.vm);
466        angle.push(view.to_radians(star.va));
467    }
468    Ok(Voltages { magnitude, angle })
469}
470
471/// Fill every value of the assembled structure at the voltages `injection`
472/// was formed at. The fill walks each Jacobian row beside its merged
473/// admittance row (the layout [`assemble`] writes), so the cost follows the
474/// nonzero count, never the dense square, and reuses the injection's one
475/// sine and cosine per bus.
476#[allow(clippy::many_single_char_names)] // k/m/n and G/B are the textbook notation
477fn fill_values(
478    matrix: &mut SparseMatrix,
479    admittance_rows: &[Vec<(usize, f64, f64)>],
480    injection: &BusPowerInjection,
481    coordinates: VoltageCoordinates,
482) {
483    let BusPowerInjection {
484        p,
485        q,
486        vm,
487        cos,
488        sin,
489        current_re,
490        current_im,
491    } = injection;
492    let n = vm.len();
493    let half = matrix.nnz() / 2;
494    let data = matrix.data_mut();
495    let (active, reactive) = data.split_at_mut(half);
496    let mut offset = 0;
497    for (k, row) in admittance_rows.iter().enumerate() {
498        let len = row.len();
499        let (p_angle, p_magnitude) = active[offset..offset + 2 * len].split_at_mut(len);
500        let (q_angle, q_magnitude) = reactive[offset..offset + 2 * len].split_at_mut(len);
501        offset += 2 * len;
502        for (position, &(m, g, b)) in row.iter().enumerate() {
503            let entries = match coordinates {
504                VoltageCoordinates::Polar => {
505                    if k == m {
506                        // MATPOWER dSbus_dV diagonals.
507                        let vk2 = vm[k] * vm[k];
508                        let (p_over, q_over) = if vm[k] == 0.0 {
509                            (0.0, 0.0)
510                        } else {
511                            (p[k] / vm[k], q[k] / vm[k])
512                        };
513                        [
514                            -q[k] - b * vk2,
515                            p_over + g * vm[k],
516                            p[k] - g * vk2,
517                            q_over - b * vm[k],
518                        ]
519                    } else {
520                        // sin and cos of va[k] - va[m] from the per bus values.
521                        let cos_km = cos[k] * cos[m] + sin[k] * sin[m];
522                        let sin_km = sin[k] * cos[m] - cos[k] * sin[m];
523                        let odd = g * sin_km - b * cos_km;
524                        let even = g * cos_km + b * sin_km;
525                        let vkm = vm[k] * vm[m];
526                        [vkm * odd, vm[k] * even, -vkm * even, vm[k] * odd]
527                    }
528                }
529                VoltageCoordinates::Cartesian => {
530                    // dS_k/dVr_m = δ conj(I_k) + V_k conj(Y_km);
531                    // dS_k/dVi_m = jδ conj(I_k) − j V_k conj(Y_km).
532                    let vr_k = vm[k] * cos[k];
533                    let vi_k = vm[k] * sin[k];
534                    let real_part = vr_k * g + vi_k * b;
535                    let imag_part = vi_k * g - vr_k * b;
536                    if k == m {
537                        [
538                            real_part + current_re[k],
539                            imag_part + current_im[k],
540                            imag_part - current_im[k],
541                            -real_part + current_re[k],
542                        ]
543                    } else {
544                        [real_part, imag_part, imag_part, -real_part]
545                    }
546                }
547            };
548            // [(P, angle), (P, magnitude), (Q, angle), (Q, magnitude)].
549            p_angle[position] = entries[0];
550            p_magnitude[position] = entries[1];
551            q_angle[position] = entries[2];
552            q_magnitude[position] = entries[3];
553        }
554    }
555    debug_assert_eq!(offset, half);
556    debug_assert_eq!(n, admittance_rows.len());
557}
558
559/// Merged sparse admittance rows: sorted `(column, g, b)` per bus row, with
560/// the diagonal always present (zero where neither matrix stores it).
561fn merge_admittance_rows(
562    conductance: &SparseMatrix,
563    susceptance: &SparseMatrix,
564) -> Vec<Vec<(usize, f64, f64)>> {
565    let n = conductance.rows();
566    let mut admittance_rows: Vec<Vec<(usize, f64, f64)>> = vec![Vec::new(); n];
567    for (row, row_vec) in conductance.outer_iterator().enumerate() {
568        for (column, &g) in row_vec.iter() {
569            admittance_rows[row].push((column, g, 0.0));
570        }
571    }
572    for (row, row_vec) in susceptance.outer_iterator().enumerate() {
573        for (column, &b) in row_vec.iter() {
574            match admittance_rows[row].binary_search_by_key(&column, |entry| entry.0) {
575                Ok(position) => admittance_rows[row][position].2 = b,
576                Err(position) => admittance_rows[row].insert(position, (column, 0.0, b)),
577            }
578        }
579    }
580    for (k, row) in admittance_rows.iter_mut().enumerate() {
581        if let Err(position) = row.binary_search_by_key(&k, |entry| entry.0) {
582            row.insert(position, (k, 0.0, 0.0));
583        }
584    }
585    admittance_rows
586}
587
588/// The bus power injection `S = diag(V) conj(Y V)` at one voltage point:
589/// `p` and `q` in bus row order, per unit on the admittance's base. It also
590/// keeps the voltages, per bus angle cosines and sines, and currents
591/// `I = Y V` it was formed from, so
592/// [`PowerFlowJacobian::update_from_injection`] refreshes the Jacobian at the
593/// same point without recomputing them.
594#[derive(Clone, Debug, PartialEq)]
595#[non_exhaustive]
596pub struct BusPowerInjection {
597    /// Active power injection per bus.
598    pub p: Vec<f64>,
599    /// Reactive power injection per bus.
600    pub q: Vec<f64>,
601    vm: Vec<f64>,
602    cos: Vec<f64>,
603    sin: Vec<f64>,
604    current_re: Vec<f64>,
605    current_im: Vec<f64>,
606}
607
608/// The one calculation of `I = Y V` and `S = diag(V) conj(I)` over merged
609/// admittance rows: every injection this module reports or differentiates
610/// comes from here.
611fn calc_injection(
612    admittance_rows: &[Vec<(usize, f64, f64)>],
613    vm: &[f64],
614    va: &[f64],
615) -> BusPowerInjection {
616    let n = vm.len();
617    let (sin, cos): (Vec<f64>, Vec<f64>) = va.iter().map(|angle| angle.sin_cos()).unzip();
618    let vr: Vec<f64> = (0..n).map(|k| vm[k] * cos[k]).collect();
619    let vi: Vec<f64> = (0..n).map(|k| vm[k] * sin[k]).collect();
620    let mut current_re = vec![0.0; n];
621    let mut current_im = vec![0.0; n];
622    for (k, row) in admittance_rows.iter().enumerate() {
623        let mut ir = 0.0;
624        let mut ii = 0.0;
625        for &(m, g, b) in row {
626            ir += g * vr[m] - b * vi[m];
627            ii += g * vi[m] + b * vr[m];
628        }
629        current_re[k] = ir;
630        current_im[k] = ii;
631    }
632    let p: Vec<f64> = (0..n)
633        .map(|k| vr[k] * current_re[k] + vi[k] * current_im[k])
634        .collect();
635    let q: Vec<f64> = (0..n)
636        .map(|k| vi[k] * current_re[k] - vr[k] * current_im[k])
637        .collect();
638    BusPowerInjection {
639        p,
640        q,
641        vm: vm.to_vec(),
642        cos,
643        sin,
644        current_re,
645        current_im,
646    }
647}