1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22pub struct StatedBusFlags(u16);
23
24impl StatedBusFlags {
25 pub const NONE: Self = Self(0);
27 pub const HVDC: Self = Self(1);
29 pub const VSC: Self = Self(1 << 1);
31 pub const FACTS: Self = Self(1 << 2);
33 pub const GENERATOR_ON_PQ_BUS: Self = Self(1 << 3);
35 pub const STAR_BUS: Self = Self(1 << 4);
37 pub const MERGED_GROUP: Self = Self(1 << 5);
40 pub const VOLTAGE_DEPENDENT_LOAD: Self = Self(1 << 6);
43 pub const SWITCHED_SHUNT: Self = Self(1 << 7);
45 pub const REFERENCE: Self = Self(1 << 8);
47 pub const STORAGE: Self = Self(1 << 9);
49 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 pub const ALL: Self = Self((1 << 11) - 1);
72
73 #[must_use]
75 pub const fn contains(self, other: Self) -> bool {
76 self.0 & other.0 == other.0
77 }
78
79 #[must_use]
81 pub const fn intersects(self, other: Self) -> bool {
82 self.0 & other.0 != 0
83 }
84
85 #[must_use]
87 pub const fn is_empty(self) -> bool {
88 self.0 == 0
89 }
90
91 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128#[non_exhaustive]
129pub enum LccReactivePower {
130 #[default]
144 ConverterModel,
145 Stated,
147}
148
149#[derive(Debug, Clone, PartialEq)]
151#[non_exhaustive]
152pub struct StatedStateOptions {
153 pub hvdc_treatment: HvdcTreatment,
155 pub top_k: usize,
157 pub merged_buses: BTreeMap<BusId, BusId>,
163 pub low_impedance_threshold: f64,
169 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#[derive(Debug, Clone, Copy, PartialEq)]
219#[non_exhaustive]
220pub struct StatedBusMismatch {
221 pub bus: BusId,
222 pub island: Option<usize>,
225 pub p_mw: f64,
227 pub q_mvar: f64,
229 pub flags: StatedBusFlags,
230}
231
232impl StatedBusMismatch {
233 #[must_use]
235 pub fn calc_magnitude_mva(&self) -> f64 {
236 self.p_mw.hypot(self.q_mvar)
237 }
238}
239
240#[derive(Debug, Clone, Copy, PartialEq)]
242#[non_exhaustive]
243pub struct StatedIslandMismatch {
244 pub n_buses: usize,
245 pub p_mw: f64,
247 pub q_mvar: f64,
248 pub abs_p_mw: f64,
250 pub abs_q_mvar: f64,
251 pub largest_bus: BusId,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq)]
257#[non_exhaustive]
258pub struct ClosureInjection {
259 pub bus: BusId,
260 pub p_mw: f64,
262 pub q_mvar: f64,
264 pub flags: StatedBusFlags,
265}
266
267#[derive(Debug, Clone, PartialEq)]
270#[non_exhaustive]
271pub struct StatedStateMismatch {
272 pub buses: Vec<StatedBusMismatch>,
275 pub islands: Vec<StatedIslandMismatch>,
278 pub top: Vec<usize>,
281 pub diagnostics: Vec<Diagnostic>,
286}
287
288impl StatedStateMismatch {
289 #[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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq)]
333#[non_exhaustive]
334pub struct StatedBranchFlows {
335 pub sources: Vec<AnalysisBranchSource>,
338 pub in_service: Vec<bool>,
341 pub p_from_mw: Vec<f64>,
343 pub q_from_mvar: Vec<f64>,
344 pub p_to_mw: Vec<f64>,
346 pub q_to_mvar: Vec<f64>,
347}
348
349fn 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
359fn 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
373struct TerminalPowers {
376 s_from: Complex64,
377 s_to: Complex64,
378}
379
380fn 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#[allow(clippy::too_many_lines)] pub 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 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 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 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 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 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 let bridge_q =
594 opts.lcc_reactive_power == LccReactivePower::ConverterModel && !net.is_normalized();
595 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 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 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 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
720pub 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}