Skip to main content

powerio_matrix/
stated_state.rs

1//! The AC bus balance at the voltages a case states:
2//! [`calc_stated_state_mismatch`] and [`calc_stated_branch_flows`].
3
4use std::collections::BTreeMap;
5use std::ops::BitOr;
6
7use num_complex::Complex64;
8
9use powerio_tx::{
10    BalancedNetwork, BusId, BusType, HvdcConverterKind, HvdcTreatment, IndexedNetwork,
11};
12
13use crate::diagnostics::{Diagnostic, codes};
14use crate::matrix::{YbusFlags, branch_admittance, branch_flows};
15use crate::opf::{AnalysisBranchSource, analysis_branch_sources};
16use crate::{Error, Result};
17
18/// Equipment at a bus that a stated-state residual is commonly traced to.
19///
20/// A set of named bits; combine them with `|`.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22pub struct StatedBusFlags(u16);
23
24impl StatedBusFlags {
25    /// No flag.
26    pub const NONE: Self = Self(0);
27    /// A terminal of an in service HVDC line.
28    pub const HVDC: Self = Self(1);
29    /// A terminal of an in service HVDC line with a voltage source converter.
30    pub const VSC: Self = Self(1 << 1);
31    /// An in service static VAR compensator.
32    pub const FACTS: Self = Self(1 << 2);
33    /// An in service generator on a bus the case types as PQ.
34    pub const GENERATOR_ON_PQ_BUS: Self = Self(1 << 3);
35    /// The star point a three winding transformer was lowered to.
36    pub const STAR_BUS: Self = Self(1 << 4);
37    /// The bus that survived a bus merge
38    /// ([`StatedStateOptions::merged_buses`]).
39    pub const MERGED_GROUP: Self = Self(1 << 5);
40    /// An in service load with a constant current or constant impedance part,
41    /// or an exponential voltage model.
42    pub const VOLTAGE_DEPENDENT_LOAD: Self = Self(1 << 6);
43    /// An in service switched shunt.
44    pub const SWITCHED_SHUNT: Self = Self(1 << 7);
45    /// A reference bus.
46    pub const REFERENCE: Self = Self(1 << 8);
47    /// An in service storage unit.
48    pub const STORAGE: Self = Self(1 << 9);
49    /// A terminal of an in service branch or winding whose series impedance
50    /// magnitude is below [`StatedStateOptions::low_impedance_threshold`]. The
51    /// flow such a branch carries is the small difference of two stored
52    /// voltages divided by a small impedance, so the rounding of the stored
53    /// values alone can leave a residual here.
54    pub const LOW_IMPEDANCE_BRANCH: Self = Self(1 << 10);
55
56    const NAMED: [(Self, &'static str); 11] = [
57        (Self::HVDC, "hvdc"),
58        (Self::VSC, "vsc"),
59        (Self::FACTS, "facts"),
60        (Self::GENERATOR_ON_PQ_BUS, "generator_on_pq_bus"),
61        (Self::STAR_BUS, "star_bus"),
62        (Self::MERGED_GROUP, "merged_group"),
63        (Self::VOLTAGE_DEPENDENT_LOAD, "voltage_dependent_load"),
64        (Self::SWITCHED_SHUNT, "switched_shunt"),
65        (Self::REFERENCE, "reference"),
66        (Self::STORAGE, "storage"),
67        (Self::LOW_IMPEDANCE_BRANCH, "low_impedance_branch"),
68    ];
69
70    /// Every flag.
71    pub const ALL: Self = Self((1 << 11) - 1);
72
73    /// Whether every flag in `other` is set.
74    #[must_use]
75    pub const fn contains(self, other: Self) -> bool {
76        self.0 & other.0 == other.0
77    }
78
79    /// Whether any flag in `other` is set.
80    #[must_use]
81    pub const fn intersects(self, other: Self) -> bool {
82        self.0 & other.0 != 0
83    }
84
85    /// Whether no flag is set.
86    #[must_use]
87    pub const fn is_empty(self) -> bool {
88        self.0 == 0
89    }
90
91    /// The snake case names of the set flags, in declaration order.
92    #[must_use]
93    pub fn names(self) -> Vec<&'static str> {
94        Self::NAMED
95            .iter()
96            .filter(|(flag, _)| self.contains(*flag))
97            .map(|(_, name)| *name)
98            .collect()
99    }
100
101    /// The flag a snake case name spells, as [`names`](Self::names) writes it.
102    #[must_use]
103    pub fn from_name(name: &str) -> Option<Self> {
104        Self::NAMED
105            .iter()
106            .find(|(_, spelled)| *spelled == name)
107            .map(|(flag, _)| *flag)
108    }
109}
110
111impl BitOr for StatedBusFlags {
112    type Output = Self;
113
114    fn bitor(self, rhs: Self) -> Self {
115        Self(self.0 | rhs.0)
116    }
117}
118
119impl std::ops::BitOrAssign for StatedBusFlags {
120    fn bitor_assign(&mut self, rhs: Self) {
121        self.0 |= rhs.0;
122    }
123}
124
125/// Where a line-commutated (LCC) converter's reactive demand comes from in
126/// [`calc_stated_state_mismatch`].
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128#[non_exhaustive]
129pub enum LccReactivePower {
130    /// The converter bridge equations at the stored AC voltages
131    /// ([`Hvdc::calc_lcc_operating_point`](powerio_tx::Hvdc::calc_lcc_operating_point)):
132    /// each converter of a line read from a PSS/E two-terminal record draws
133    /// the reactive power its firing or extinction angle and overlap imply,
134    /// substituted for the terminal reactive powers of
135    /// [`Hvdc::calc_bus_to_device_powers`](powerio_tx::Hvdc::calc_bus_to_device_powers)
136    /// (positive, absorbed from the bus) and negated once into the bus
137    /// injection. The active powers stay the stated `pf` and `pt`. A line
138    /// without such a record keeps its stated `qf` and `qt`, as does one
139    /// whose record reaches no operating point, with a
140    /// `BUILD.STATED_STATE.LCC_MODEL_UNAVAILABLE` warning in
141    /// [`StatedStateMismatch::diagnostics`]; a normalized network, whose
142    /// powers are per unit, keeps them throughout.
143    #[default]
144    ConverterModel,
145    /// The line's stated `qf` and `qt`, which a PSS/E record leaves at zero.
146    Stated,
147}
148
149/// Options for [`calc_stated_state_mismatch`].
150#[derive(Debug, Clone, PartialEq)]
151#[non_exhaustive]
152pub struct StatedStateOptions {
153    /// How HVDC lines enter the stated injections.
154    pub hvdc_treatment: HvdcTreatment,
155    /// How many buses [`StatedStateMismatch::top`] lists. Default 20.
156    pub top_k: usize,
157    /// Merged bus to surviving bus, as a bus merge reports it
158    /// ([`BusMerge::merged_buses`](powerio_tx::BusMerge::merged_buses), or
159    /// `ZeroImpedanceMerge::merged_buses` in `powerio-prob`). Every
160    /// survivor is flagged [`StatedBusFlags::MERGED_GROUP`]; the map is not
161    /// otherwise read.
162    pub merged_buses: BTreeMap<BusId, BusId>,
163    /// Series impedance magnitude, per unit, below which a branch's
164    /// terminals are flagged [`StatedBusFlags::LOW_IMPEDANCE_BRANCH`].
165    /// Default `1e-3`: a case that states voltage magnitudes to five decimals
166    /// leaves such a branch's flow uncertain by about one MW on a 100 MVA
167    /// base.
168    pub low_impedance_threshold: f64,
169    /// Where an LCC converter's reactive demand comes from.
170    pub lcc_reactive_power: LccReactivePower,
171}
172
173impl Default for StatedStateOptions {
174    fn default() -> Self {
175        Self {
176            hvdc_treatment: HvdcTreatment::default(),
177            top_k: 20,
178            merged_buses: BTreeMap::new(),
179            low_impedance_threshold: 1e-3,
180            lcc_reactive_power: LccReactivePower::default(),
181        }
182    }
183}
184
185impl StatedStateOptions {
186    #[must_use]
187    pub const fn with_hvdc_treatment(mut self, treatment: HvdcTreatment) -> Self {
188        self.hvdc_treatment = treatment;
189        self
190    }
191
192    #[must_use]
193    pub const fn with_top_k(mut self, top_k: usize) -> Self {
194        self.top_k = top_k;
195        self
196    }
197
198    #[must_use]
199    pub fn with_merged_buses(mut self, merged_buses: BTreeMap<BusId, BusId>) -> Self {
200        self.merged_buses = merged_buses;
201        self
202    }
203
204    #[must_use]
205    pub const fn with_low_impedance_threshold(mut self, threshold: f64) -> Self {
206        self.low_impedance_threshold = threshold;
207        self
208    }
209
210    #[must_use]
211    pub const fn with_lcc_reactive_power(mut self, source: LccReactivePower) -> Self {
212        self.lcc_reactive_power = source;
213        self
214    }
215}
216
217/// The balance at one bus.
218#[derive(Debug, Clone, Copy, PartialEq)]
219#[non_exhaustive]
220pub struct StatedBusMismatch {
221    pub bus: BusId,
222    /// Index into [`StatedStateMismatch::islands`]. `None` for a bus the case
223    /// types as isolated, which has no balance equation.
224    pub island: Option<usize>,
225    /// Active mismatch, MW: drawn by the network minus stated injection.
226    pub p_mw: f64,
227    /// Reactive mismatch, MVAr, same sign.
228    pub q_mvar: f64,
229    pub flags: StatedBusFlags,
230}
231
232impl StatedBusMismatch {
233    /// `|ΔP + jΔQ|`, MVA.
234    #[must_use]
235    pub fn calc_magnitude_mva(&self) -> f64 {
236        self.p_mw.hypot(self.q_mvar)
237    }
238}
239
240/// The balance summed over one island of the in service topology.
241#[derive(Debug, Clone, Copy, PartialEq)]
242#[non_exhaustive]
243pub struct StatedIslandMismatch {
244    pub n_buses: usize,
245    /// Signed sums, MW and MVAr.
246    pub p_mw: f64,
247    pub q_mvar: f64,
248    /// Sums of magnitudes, MW and MVAr.
249    pub abs_p_mw: f64,
250    pub abs_q_mvar: f64,
251    /// The bus with the largest `|ΔS|` in the island.
252    pub largest_bus: BusId,
253}
254
255/// An injection that closes one bus's stated-state mismatch.
256#[derive(Debug, Clone, Copy, PartialEq)]
257#[non_exhaustive]
258pub struct ClosureInjection {
259    pub bus: BusId,
260    /// Active injection, MW.
261    pub p_mw: f64,
262    /// Reactive injection, MVAr.
263    pub q_mvar: f64,
264    pub flags: StatedBusFlags,
265}
266
267/// The AC bus balance at the stored voltages, from
268/// [`calc_stated_state_mismatch`].
269#[derive(Debug, Clone, PartialEq)]
270#[non_exhaustive]
271pub struct StatedStateMismatch {
272    /// One row per bus of the analysis network: the source buses in table
273    /// order, then one star bus per in service three winding transformer.
274    pub buses: Vec<StatedBusMismatch>,
275    /// The islands of the in service topology, largest first. Isolated buses
276    /// belong to none.
277    pub islands: Vec<StatedIslandMismatch>,
278    /// Indices into [`buses`](Self::buses) of the largest `|ΔS|`, largest
279    /// first, at most [`StatedStateOptions::top_k`] of them.
280    pub top: Vec<usize>,
281    /// What the evaluation could not do as asked: one
282    /// `BUILD.STATED_STATE.LCC_MODEL_UNAVAILABLE` warning per line with an LCC
283    /// converter record whose stated reactive powers stood in for the
284    /// converter model.
285    pub diagnostics: Vec<Diagnostic>,
286}
287
288impl StatedStateMismatch {
289    /// `Σ|ΔP|` over every bus in an island, MW.
290    #[must_use]
291    pub fn calc_total_abs_p_mw(&self) -> f64 {
292        self.islands.iter().map(|island| island.abs_p_mw).sum()
293    }
294
295    /// `Σ|ΔQ|` over every bus in an island, MVAr.
296    #[must_use]
297    pub fn calc_total_abs_q_mvar(&self) -> f64 {
298        self.islands.iter().map(|island| island.abs_q_mvar).sum()
299    }
300
301    /// The largest `|ΔS|` of any bus in an island, MVA.
302    #[must_use]
303    pub fn calc_max_magnitude_mva(&self) -> f64 {
304        self.top
305            .first()
306            .map_or(0.0, |&row| self.buses[row].calc_magnitude_mva())
307    }
308
309    /// The fixed injections that close the mismatch at every bus in an island
310    /// that carries any flag in `mask`: each is the bus's own `ΔP` and `ΔQ`,
311    /// so adding it to the bus's stated injection makes that bus balance at
312    /// the stored voltages exactly. A calculation that cannot model a device
313    /// (an HVDC converter's reactive demand, a FACTS controller) can hold it
314    /// at this injection and start from the stored solution.
315    #[must_use]
316    pub fn closure_injections(&self, mask: StatedBusFlags) -> Vec<ClosureInjection> {
317        self.buses
318            .iter()
319            .filter(|bus| bus.island.is_some() && bus.flags.intersects(mask))
320            .map(|bus| ClosureInjection {
321                bus: bus.bus,
322                p_mw: bus.p_mw,
323                q_mvar: bus.q_mvar,
324                flags: bus.flags,
325            })
326            .collect()
327    }
328}
329
330/// Active and reactive power entering every analysis branch at both ends, at
331/// the stored voltages, from [`calc_stated_branch_flows`].
332#[derive(Debug, Clone, PartialEq)]
333#[non_exhaustive]
334pub struct StatedBranchFlows {
335    /// The source of each analysis branch: every source branch row in order,
336    /// then the three windings of each in service three winding transformer.
337    pub sources: Vec<AnalysisBranchSource>,
338    /// Whether the branch is in service. An out of service branch carries
339    /// zero flow.
340    pub in_service: Vec<bool>,
341    /// Power entering the branch at its from end, MW and MVAr.
342    pub p_from_mw: Vec<f64>,
343    pub q_from_mvar: Vec<f64>,
344    /// Power entering the branch at its to end, MW and MVAr.
345    pub p_to_mw: Vec<f64>,
346    pub q_to_mvar: Vec<f64>,
347}
348
349/// The complex bus voltages a case stores, per unit and radians, in analysis
350/// bus order.
351fn stored_voltages(view: &IndexedNetwork<'_>) -> Vec<Complex64> {
352    view.network()
353        .buses()
354        .iter()
355        .map(|bus| Complex64::from_polar(bus.vm, view.to_radians(bus.va)))
356        .collect()
357}
358
359/// A description of an analysis branch for an error message.
360fn describe_branch(source: AnalysisBranchSource) -> String {
361    match source {
362        AnalysisBranchSource::Branch { row } => format!("branch row {row}"),
363        AnalysisBranchSource::ThreeWindingTransformerWinding {
364            transformer_row,
365            winding,
366        } => format!(
367            "winding {} of three winding transformer row {transformer_row}",
368            winding + 1
369        ),
370    }
371}
372
373/// One in service analysis branch at the stored voltages: the per unit
374/// complex power entering it at each end.
375struct TerminalPowers {
376    s_from: Complex64,
377    s_to: Complex64,
378}
379
380/// [`TerminalPowers`] of each analysis branch, `None` for an out of service
381/// branch, in analysis branch order.
382fn branch_terminal_powers(
383    view: &IndexedNetwork<'_>,
384    source: &BalancedNetwork,
385    voltages: &[Complex64],
386) -> Result<Vec<Option<TerminalPowers>>> {
387    let sources = analysis_branch_sources(source);
388    let mut powers = Vec::with_capacity(view.branches().len());
389    for (row, branch) in view.branches().iter().enumerate() {
390        if !branch.in_service {
391            powers.push(None);
392            continue;
393        }
394        let from = view
395            .bus_index(branch.from)
396            .ok_or(powerio_tx::Error::UnknownBus {
397                bus_id: branch.from,
398                element_index: row,
399            })?;
400        let to = view
401            .bus_index(branch.to)
402            .ok_or(powerio_tx::Error::UnknownBus {
403                bus_id: branch.to,
404                element_index: row,
405            })?;
406        let shift = view.to_radians(branch.shift);
407        let admittance = match branch_admittance(branch, YbusFlags::default(), shift, row) {
408            Ok(Some(admittance)) => admittance,
409            Ok(None) | Err(Error::Transmission(powerio_tx::Error::ZeroImpedance { .. })) => {
410                return Err(Error::UnmergedZeroImpedance {
411                    element: describe_branch(sources[row]),
412                    from: branch.from,
413                    to: branch.to,
414                });
415            }
416            Err(other) => return Err(other),
417        };
418        let (s_from, s_to) = branch_flows(&admittance, voltages[from], voltages[to]);
419        powers.push(Some(TerminalPowers { s_from, s_to }));
420    }
421    Ok(powers)
422}
423
424/// Calculate the AC bus balance at the voltages `net` stores, with every
425/// device at its stated output.
426///
427/// A case saved from a converged power flow stores bus voltage magnitudes
428/// and angles that balance the network's injections. Evaluating every bus
429/// balance at those stored voltages measures how faithfully the case was
430/// read: a bus whose equipment PowerIO reads the way the solving program
431/// read it closes to the precision of the stored values, and a residual
432/// points at the equipment read differently.
433///
434/// A bus mismatch is the power the network draws from the bus at the stored
435/// voltages minus the power the bus's devices state they inject,
436/// `S_calc - S_stated`, the mismatch MATPOWER's `newtonpf` drives to zero. An
437/// extra injection equal to the mismatch closes the bus
438/// ([`StatedStateMismatch::closure_injections`]).
439///
440/// The network side is every in service branch and three winding
441/// transformer winding at its stated tap and shift, plus every in service
442/// fixed and switched shunt at its stated admittance, through the branch
443/// admittances [`calc_admittance_matrix`](crate::calc_admittance_matrix)
444/// uses. The device side is every in service generator at its stated `pg`
445/// and `qg`, every in service load at the stored voltage through its voltage
446/// model, every in service static VAR compensator and storage unit at its
447/// stated terminal power, and every HVDC line under
448/// [`StatedStateOptions::hvdc_treatment`], with an LCC converter's reactive
449/// demand from [`StatedStateOptions::lcc_reactive_power`].
450///
451/// Closed switches are refused rather than modeled. The balance stamps
452/// branches only, while the island labels join the buses a closed switch
453/// connects, so an unmerged switch carrying power would show as two equal
454/// and opposite residuals at its ends instead of a flow.
455///
456/// # Errors
457/// [`Error::UnmergedZeroImpedance`] for an in service branch or winding with
458/// zero series impedance: the stored voltages do not determine its flow, so
459/// merge the buses it joins first
460/// ([`BalancedNetwork::merge_buses`], or `--merge-buses` on the command
461/// line). `powerio_tx::Error::ClosedSwitch` (`BUILD.SWITCH.CLOSED`), as
462/// [`IndexedNetwork::check_closed_switches`] raises it, for a closed switch
463/// joining two buses; a rule that selects closed switches
464/// ([`BusMergeRule::closed_switches`](powerio_tx::BusMergeRule::closed_switches),
465/// `--merge-buses switches`) merges them first. An element naming an
466/// undeclared bus, a non-finite admittance, or an unusable tap or base fail
467/// as the admittance builders do.
468#[allow(clippy::too_many_lines)] // one pass per element table, stated in full
469pub fn calc_stated_state_mismatch(
470    net: &BalancedNetwork,
471    opts: &StatedStateOptions,
472) -> Result<StatedStateMismatch> {
473    net.check_base_mva()?;
474    let view = IndexedNetwork::new(net);
475    view.check_closed_switches()?;
476    let n = view.n();
477    let base = view.per_unit_base();
478    let base_mva = view.base_mva();
479    let voltages = stored_voltages(&view);
480
481    // The network side: the power drawn from each bus into its branches and
482    // shunts, per unit, `S = diag(V) conj(Y_bus V)` through the crate's one
483    // injection over the one `Y_bus`.
484    let sources = analysis_branch_sources(net);
485    let admittance =
486        match crate::calc_admittance_matrix(&view, &crate::matrix::BuildOptions::default()) {
487            Ok(admittance) => admittance,
488            Err(Error::Transmission(powerio_tx::Error::ZeroImpedance { row })) => {
489                let branch = &view.branches()[row];
490                return Err(Error::UnmergedZeroImpedance {
491                    element: describe_branch(sources[row]),
492                    from: branch.from,
493                    to: branch.to,
494                });
495            }
496            Err(other) => return Err(other),
497        };
498    let buses = view.network().buses();
499    let vm: Vec<f64> = buses.iter().map(|bus| bus.vm).collect();
500    let va: Vec<f64> = buses.iter().map(|bus| view.to_radians(bus.va)).collect();
501    let (p_drawn, q_drawn) = crate::calc_bus_power_injection(&admittance, &vm, &va)?;
502    let drawn: Vec<Complex64> = p_drawn
503        .into_iter()
504        .zip(q_drawn)
505        .map(|(p, q)| Complex64::new(p, q))
506        .collect();
507    let mut flags = vec![StatedBusFlags::NONE; n];
508    for branch in view.branches().iter().filter(|branch| branch.in_service) {
509        if branch.r.hypot(branch.x) < opts.low_impedance_threshold
510            && let (Some(from), Some(to)) = (view.bus_index(branch.from), view.bus_index(branch.to))
511        {
512            flags[from] |= StatedBusFlags::LOW_IMPEDANCE_BRANCH;
513            flags[to] |= StatedBusFlags::LOW_IMPEDANCE_BRANCH;
514        }
515    }
516
517    // The device side: stated injections, per unit.
518    let mut stated = vec![Complex64::new(0.0, 0.0); n];
519    for (idx, bus) in buses.iter().enumerate() {
520        if bus.kind == BusType::Ref {
521            flags[idx] |= StatedBusFlags::REFERENCE;
522        }
523        if idx >= net.buses().len() {
524            flags[idx] |= StatedBusFlags::STAR_BUS;
525        }
526    }
527    for survivor in opts.merged_buses.values() {
528        if let Some(idx) = view.bus_index(*survivor) {
529            flags[idx] |= StatedBusFlags::MERGED_GROUP;
530        }
531    }
532    for generator in view.generators().iter().filter(|g| g.in_service) {
533        if let Some(idx) = view.bus_index(generator.bus) {
534            stated[idx] += Complex64::new(generator.pg, generator.qg) / base;
535            if buses[idx].kind == BusType::Pq {
536                flags[idx] |= StatedBusFlags::GENERATOR_ON_PQ_BUS;
537            }
538        }
539    }
540    for load in view.network().loads().iter().filter(|l| l.in_service) {
541        if let Some(idx) = view.bus_index(load.bus) {
542            // The load's power at the stored magnitude through powerio-tx's one
543            // voltage model evaluation.
544            let base_kv = buses[idx].base_kv;
545            let invalid = |reason| powerio_tx::Error::InvalidLoadVoltageModel {
546                bus: load.bus,
547                reason,
548            };
549            let power = load
550                .calc_power_at(buses[idx].vm, base_kv)
551                .map_err(invalid)?;
552            stated[idx] -= Complex64::new(power.p, power.q) / base;
553            if load
554                .calc_voltage_terms(base_kv)
555                .map_err(invalid)?
556                .is_some_and(|terms| !terms.is_empty())
557            {
558                flags[idx] |= StatedBusFlags::VOLTAGE_DEPENDENT_LOAD;
559            }
560        }
561    }
562    for shunt in view.network().shunts().iter().filter(|s| s.in_service) {
563        if shunt.control.is_some()
564            && let Some(idx) = view.bus_index(shunt.bus)
565        {
566            flags[idx] |= StatedBusFlags::SWITCHED_SHUNT;
567        }
568    }
569    // Terminal power in the load sign the static VAR compensator readers
570    // state: positive flows from the bus into the device.
571    for svc in view
572        .network()
573        .static_var_compensators()
574        .iter()
575        .filter(|s| s.in_service)
576    {
577        if let Some(idx) = view.bus_index(svc.bus) {
578            stated[idx] -= Complex64::new(svc.p, svc.q) / base;
579            flags[idx] |= StatedBusFlags::FACTS;
580        }
581    }
582    // Storage power is a withdrawal, PowerModels' `ps`/`qs`.
583    for storage in view.network().storage().iter().filter(|s| s.in_service) {
584        if let Some(idx) = view.bus_index(storage.bus) {
585            stated[idx] -= Complex64::new(storage.ps, storage.qs) / base;
586            flags[idx] |= StatedBusFlags::STORAGE;
587        }
588    }
589    let mut diagnostics = Vec::new();
590    if opts.hvdc_treatment == HvdcTreatment::FixedInjection {
591        // The converter model's power is MW and MVAr, so a normalized
592        // network keeps the stated reactive powers throughout.
593        let bridge_q =
594            opts.lcc_reactive_power == LccReactivePower::ConverterModel && !net.is_normalized();
595        // Each injecting line states its from end, then its to end.
596        for ends in view.hvdc_injections().terminals.chunks(2) {
597            let [from, to] = ends else { continue };
598            let line = &view.network().hvdc()[from.row];
599            let (Some(f), Some(t)) = (view.bus_index(from.bus), view.bus_index(to.bus)) else {
600                continue;
601            };
602            let mut terminal = line.calc_bus_to_device_powers();
603            if bridge_q && line.has_lcc_converter_record() {
604                // The bridge model's reactive demand replaces the stated
605                // terminal reactive powers; the active powers stay the
606                // reader's `pf` and `pt` (the bridge model prices the DC
607                // current differently, see `powerio_tx::lcc`).
608                match line.calc_lcc_operating_point(voltages[f].norm(), voltages[t].norm()) {
609                    Some(point) => {
610                        terminal.q_from = point.rectifier.q_mvar;
611                        terminal.q_to = point.inverter.q_mvar;
612                    }
613                    None => diagnostics.push(Diagnostic::of(
614                        &codes::BUILD_STATED_STATE_LCC_MODEL_UNAVAILABLE,
615                        format!(
616                            "HVDC line row {} between buses {} and {} reaches no LCC bridge \
617                             operating point at the stored voltages (no converter AC base, \
618                             capacitor commutation, or a schedule no angle reaches at a \
619                             positive power factor); its stated reactive powers were kept",
620                            from.row, from.bus, to.bus
621                        ),
622                    )),
623                }
624            }
625            // The one negation from terminal power to bus injection.
626            let [(p_from, q_from), (p_to, q_to)] = terminal.calc_bus_injections();
627            stated[f] += Complex64::new(p_from, q_from) / base;
628            stated[t] += Complex64::new(p_to, q_to) / base;
629        }
630    }
631    for line in view.network().hvdc().iter().filter(|line| line.in_service) {
632        let vsc = [&line.converter1, &line.converter2]
633            .iter()
634            .any(|c| c.as_ref().is_some_and(|c| c.kind == HvdcConverterKind::Vsc));
635        for bus in [line.from, line.to] {
636            if let Some(idx) = view.bus_index(bus) {
637                flags[idx] |= StatedBusFlags::HVDC;
638                if vsc {
639                    flags[idx] |= StatedBusFlags::VSC;
640                }
641            }
642        }
643    }
644
645    // Islands, largest first, over the energized buses.
646    let labels = view.calc_island_labels();
647    let mut members: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
648    for (idx, bus) in buses.iter().enumerate() {
649        if bus.kind != BusType::Isolated {
650            members.entry(labels[idx]).or_default().push(idx);
651        }
652    }
653    let mut groups: Vec<Vec<usize>> = members.into_values().collect();
654    groups.sort_by(|a, b| b.len().cmp(&a.len()).then(a[0].cmp(&b[0])));
655    let mut island_of = vec![None; n];
656    for (island, group) in groups.iter().enumerate() {
657        for &idx in group {
658            island_of[idx] = Some(island);
659        }
660    }
661
662    let rows: Vec<StatedBusMismatch> = (0..n)
663        .map(|idx| {
664            let mismatch = (drawn[idx] - stated[idx]) * base_mva;
665            StatedBusMismatch {
666                bus: buses[idx].id,
667                island: island_of[idx],
668                p_mw: mismatch.re,
669                q_mvar: mismatch.im,
670                flags: flags[idx],
671            }
672        })
673        .collect();
674
675    let islands = groups
676        .iter()
677        .map(|group| {
678            let mut island = StatedIslandMismatch {
679                n_buses: group.len(),
680                p_mw: 0.0,
681                q_mvar: 0.0,
682                abs_p_mw: 0.0,
683                abs_q_mvar: 0.0,
684                largest_bus: rows[group[0]].bus,
685            };
686            let mut largest = -1.0;
687            for &idx in group {
688                let row = &rows[idx];
689                island.p_mw += row.p_mw;
690                island.q_mvar += row.q_mvar;
691                island.abs_p_mw += row.p_mw.abs();
692                island.abs_q_mvar += row.q_mvar.abs();
693                let magnitude = row.calc_magnitude_mva();
694                if magnitude > largest {
695                    largest = magnitude;
696                    island.largest_bus = row.bus;
697                }
698            }
699            island
700        })
701        .collect();
702
703    let mut top: Vec<usize> = (0..n).filter(|&idx| island_of[idx].is_some()).collect();
704    top.sort_by(|&a, &b| {
705        rows[b]
706            .calc_magnitude_mva()
707            .total_cmp(&rows[a].calc_magnitude_mva())
708            .then(a.cmp(&b))
709    });
710    top.truncate(opts.top_k);
711
712    Ok(StatedStateMismatch {
713        buses: rows,
714        islands,
715        top,
716        diagnostics,
717    })
718}
719
720/// Calculate the active and reactive power entering every analysis branch
721/// at both ends, at the voltages `net` stores.
722///
723/// A closed switch is not refused here: each branch's flow depends on its
724/// own terminal voltages only.
725///
726/// # Errors
727/// As [`calc_stated_state_mismatch`], except closed switches.
728pub fn calc_stated_branch_flows(net: &BalancedNetwork) -> Result<StatedBranchFlows> {
729    net.check_base_mva()?;
730    let view = IndexedNetwork::new(net);
731    let base_mva = view.base_mva();
732    let voltages = stored_voltages(&view);
733    let powers = branch_terminal_powers(&view, net, &voltages)?;
734    let m = powers.len();
735    let mut flows = StatedBranchFlows {
736        sources: analysis_branch_sources(net),
737        in_service: Vec::with_capacity(m),
738        p_from_mw: Vec::with_capacity(m),
739        q_from_mvar: Vec::with_capacity(m),
740        p_to_mw: Vec::with_capacity(m),
741        q_to_mvar: Vec::with_capacity(m),
742    };
743    for power in powers {
744        let (s_from, s_to) = power
745            .as_ref()
746            .map_or_else(Default::default, |p| (p.s_from, p.s_to));
747        flows.in_service.push(power.is_some());
748        flows.p_from_mw.push(s_from.re * base_mva);
749        flows.q_from_mvar.push(s_from.im * base_mva);
750        flows.p_to_mw.push(s_to.re * base_mva);
751        flows.q_to_mvar.push(s_to.im * base_mva);
752    }
753    Ok(flows)
754}