1use num_complex::Complex64;
7use serde::{Deserialize, Serialize};
8
9use powerio_prob::{AcBusSpecification, AcOpfInstance, AcPfInstance, ReferenceBuses};
10use powerio_tx::{AngleDifferenceBounds, BalancedNetwork, BusId, IndexedNetwork};
11
12use crate::dcopf::{SynthesizedLimitWindow, Units, limits, nodal};
13use crate::matrix::{AdmittanceStamp, YbusParts};
14use crate::{AnalysisBranchSource, Error, PiecewiseLinearCost, PreparedObjective, Result};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct AcOpfAssemblyOptions {
22 pub units: Units,
24 pub skip_zero_impedance: bool,
29 pub synthesize_unrated_limits: bool,
34 pub synthesized_limit_window: SynthesizedLimitWindow,
38 pub correct_angle_difference_bounds: bool,
41 pub angle_difference_bounds: Option<AngleDifferenceBounds>,
46}
47
48impl Default for AcOpfAssemblyOptions {
49 fn default() -> Self {
50 Self {
51 units: Units::default(),
52 skip_zero_impedance: false,
53 synthesize_unrated_limits: false,
54 synthesized_limit_window: SynthesizedLimitWindow::Stated,
55 correct_angle_difference_bounds: true,
56 angle_difference_bounds: None,
57 }
58 }
59}
60
61impl AcOpfAssemblyOptions {
62 #[must_use]
63 pub const fn with_units(mut self, units: Units) -> Self {
64 self.units = units;
65 self
66 }
67
68 #[must_use]
69 pub const fn with_skip_zero_impedance(mut self, skip: bool) -> Self {
70 self.skip_zero_impedance = skip;
71 self
72 }
73
74 #[must_use]
75 pub const fn with_synthesize_unrated_limits(mut self, synthesize: bool) -> Self {
76 self.synthesize_unrated_limits = synthesize;
77 self
78 }
79
80 #[must_use]
82 pub const fn with_synthesized_limit_window(mut self, window: SynthesizedLimitWindow) -> Self {
83 self.synthesized_limit_window = window;
84 self
85 }
86
87 #[must_use]
90 pub const fn with_correct_angle_difference_bounds(mut self, correct: bool) -> Self {
91 self.correct_angle_difference_bounds = correct;
92 self.angle_difference_bounds = None;
93 self
94 }
95
96 #[must_use]
100 pub const fn with_angle_difference_bounds(mut self, bounds: AngleDifferenceBounds) -> Self {
101 self.correct_angle_difference_bounds = bounds.is_padded();
102 self.angle_difference_bounds = Some(bounds);
103 self
104 }
105
106 #[must_use]
108 pub const fn selected_angle_difference_bounds(&self) -> AngleDifferenceBounds {
109 match self.angle_difference_bounds {
110 Some(bounds) => bounds,
111 None => AngleDifferenceBounds::from_correct_flag(self.correct_angle_difference_bounds),
112 }
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118#[non_exhaustive]
119pub struct AcPfAssemblyOptions {
120 pub units: Units,
122 pub skip_zero_impedance: bool,
124 pub correct_angle_difference_bounds: bool,
127 pub angle_difference_bounds: Option<AngleDifferenceBounds>,
132}
133
134impl Default for AcPfAssemblyOptions {
135 fn default() -> Self {
136 Self {
137 units: Units::default(),
138 skip_zero_impedance: false,
139 correct_angle_difference_bounds: true,
140 angle_difference_bounds: None,
141 }
142 }
143}
144
145impl AcPfAssemblyOptions {
146 #[must_use]
147 pub const fn with_units(mut self, units: Units) -> Self {
148 self.units = units;
149 self
150 }
151
152 #[must_use]
153 pub const fn with_skip_zero_impedance(mut self, skip: bool) -> Self {
154 self.skip_zero_impedance = skip;
155 self
156 }
157
158 #[must_use]
161 pub const fn with_correct_angle_difference_bounds(mut self, correct: bool) -> Self {
162 self.correct_angle_difference_bounds = correct;
163 self.angle_difference_bounds = None;
164 self
165 }
166
167 #[must_use]
171 pub const fn with_angle_difference_bounds(mut self, bounds: AngleDifferenceBounds) -> Self {
172 self.correct_angle_difference_bounds = bounds.is_padded();
173 self.angle_difference_bounds = Some(bounds);
174 self
175 }
176
177 #[must_use]
179 pub const fn selected_angle_difference_bounds(&self) -> AngleDifferenceBounds {
180 match self.angle_difference_bounds {
181 Some(bounds) => bounds,
182 None => AngleDifferenceBounds::from_correct_flag(self.correct_angle_difference_bounds),
183 }
184 }
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
194#[serde(rename_all = "snake_case", tag = "kind")]
195#[non_exhaustive]
196pub enum PreparedAcBusSpecification {
197 Pq { p: f64, q: f64 },
198 Pv { p: f64, vm: f64 },
199 Reference { vm: f64, va: f64 },
200 Isolated,
201}
202
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205#[non_exhaustive]
206pub struct AcPfBusData {
207 pub q_d: Vec<f64>,
210 pub g_s: Vec<f64>,
212 pub b_s: Vec<f64>,
214 pub initial_vm: Vec<f64>,
216 pub initial_va: Vec<f64>,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct AcPfGeneratorData {
224 pub identities: Vec<String>,
225 pub bus_of_gen: Vec<usize>,
227 pub analysis_rows: Vec<usize>,
229 pub source_rows: Vec<Option<usize>>,
231 pub qg: Vec<f64>,
233 pub qmax: Vec<f64>,
234 pub qmin: Vec<f64>,
235}
236
237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
239#[non_exhaustive]
240pub struct AcPfPreparation {
241 pub name: String,
242 pub n_buses: usize,
243 pub n_source_generators: usize,
244 pub n_source_branches: usize,
245 pub base_mva: f64,
246 pub units: Units,
247 pub skip_zero_impedance: bool,
248 pub correct_angle_difference_bounds: bool,
250 #[serde(default)]
254 pub angle_difference_bounds: Option<AngleDifferenceBounds>,
255 pub bus_ids: Vec<BusId>,
257 pub bus_analysis_rows: Vec<usize>,
259 pub bus_source_rows: Vec<Option<usize>>,
262 pub specifications: Vec<PreparedAcBusSpecification>,
266 pub reference_buses: ReferenceBuses,
267 pub buses: AcPfBusData,
268 pub generators: AcPfGeneratorData,
269 pub branches: AcBranchData,
270}
271
272impl AcPfPreparation {
273 #[must_use]
274 pub fn n_generators(&self) -> usize {
275 self.generators.qg.len()
276 }
277
278 #[must_use]
288 pub fn calc_admittance_matrix(&self) -> YbusParts {
289 self.branches
290 .calc_admittance_matrix(self.n_buses, &self.buses.g_s, &self.buses.b_s)
291 }
292
293 #[must_use]
294 pub fn n_branches(&self) -> usize {
295 self.branches.g.len()
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub struct AcBusData {
303 pub p_d: Vec<f64>,
305 pub q_d: Vec<f64>,
307 pub g_s: Vec<f64>,
310 pub b_s: Vec<f64>,
313 pub vm_min: Vec<f64>,
315 pub vm_max: Vec<f64>,
317 pub initial_vm: Vec<f64>,
320 pub initial_va: Vec<f64>,
323 pub voltage_bound_active: Vec<bool>,
325}
326
327#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329#[non_exhaustive]
330pub struct AcBranchData {
331 pub identities: Vec<String>,
333 pub from_bus: Vec<usize>,
334 pub to_bus: Vec<usize>,
335 pub g: Vec<f64>,
337 pub b: Vec<f64>,
339 pub g_fr: Vec<f64>,
341 pub b_fr: Vec<f64>,
343 pub g_to: Vec<f64>,
345 pub b_to: Vec<f64>,
347 pub tap: Vec<f64>,
350 pub shift: Vec<f64>,
352 #[serde(with = "crate::opf::nonfinite_vec")]
355 pub s_max: Vec<f64>,
356 #[serde(with = "crate::opf::nonfinite_vec")]
358 pub angle_min: Vec<f64>,
359 #[serde(with = "crate::opf::nonfinite_vec")]
360 pub angle_max: Vec<f64>,
361 pub analysis_rows: Vec<usize>,
363 pub analysis_sources: Vec<AnalysisBranchSource>,
366 pub skipped_zero_impedance: Vec<usize>,
368 pub thermal_limit_active: Vec<bool>,
370 pub angle_bound_active: Vec<bool>,
372}
373
374#[derive(Debug, Clone, PartialEq)]
378#[non_exhaustive]
379pub struct AcBranchFlows {
380 pub pf: Vec<f64>,
381 pub qf: Vec<f64>,
382 pub pt: Vec<f64>,
383 pub qt: Vec<f64>,
384}
385
386impl AcBranchData {
387 #[must_use]
389 pub fn len(&self) -> usize {
390 self.g.len()
391 }
392
393 #[must_use]
395 pub fn is_empty(&self) -> bool {
396 self.g.is_empty()
397 }
398
399 #[must_use]
415 pub fn calc_branch_admittance(&self, branch: usize) -> [Complex64; 4] {
416 powerio_tx::PiModel::new(
417 Complex64::new(self.g[branch], self.b[branch]),
418 Complex64::new(self.g_fr[branch], self.b_fr[branch]),
419 Complex64::new(self.g_to[branch], self.b_to[branch]),
420 self.tap[branch],
421 self.shift[branch],
422 )
423 .calc_block()
424 }
425
426 #[must_use]
437 pub fn calc_branch_admittance_series_derivative(&self, branch: usize) -> [[Complex64; 4]; 2] {
438 let zero = Complex64::new(0.0, 0.0);
439 let block = |y_series| {
440 powerio_tx::PiModel::new(y_series, zero, zero, self.tap[branch], self.shift[branch])
441 .calc_block()
442 };
443 [
444 block(Complex64::new(1.0, 0.0)),
445 block(Complex64::new(0.0, 1.0)),
446 ]
447 }
448
449 #[must_use]
463 pub fn calc_branch_flows(&self, vm: &[f64], va: &[f64]) -> AcBranchFlows {
464 assert_eq!(
465 vm.len(),
466 va.len(),
467 "calc_branch_flows: {} magnitudes for {} angles",
468 vm.len(),
469 va.len()
470 );
471 let m = self.len();
472 let mut flows = AcBranchFlows {
473 pf: Vec::with_capacity(m),
474 qf: Vec::with_capacity(m),
475 pt: Vec::with_capacity(m),
476 qt: Vec::with_capacity(m),
477 };
478 for branch in 0..m {
479 let (from, to) = (self.from_bus[branch], self.to_bus[branch]);
480 let vi = Complex64::from_polar(vm[from], va[from]);
481 let vj = Complex64::from_polar(vm[to], va[to]);
482 let (s_from, s_to) =
483 crate::matrix::branch_flows(&self.calc_branch_admittance(branch), vi, vj);
484 flows.pf.push(s_from.re);
485 flows.qf.push(s_from.im);
486 flows.pt.push(s_to.re);
487 flows.qt.push(s_to.im);
488 }
489 flows
490 }
491
492 #[must_use]
503 pub fn calc_branch_flow_partials(
504 &self,
505 branch: usize,
506 vm: &[f64],
507 va: &[f64],
508 ) -> ([Complex64; 4], [Complex64; 4]) {
509 let (from, to) = (self.from_bus[branch], self.to_bus[branch]);
510 crate::matrix::branch_flow_partials(
511 &self.calc_branch_admittance(branch),
512 (vm[from], va[from]),
513 (vm[to], va[to]),
514 )
515 }
516
517 pub fn clear_jumper_charging(&mut self, max_impedance_squared: f64) -> Vec<usize> {
530 let mut cleared = Vec::new();
531 for branch in 0..self.len() {
532 let admittance_squared =
533 self.g[branch] * self.g[branch] + self.b[branch] * self.b[branch];
534 if admittance_squared > 0.0 && admittance_squared.recip() <= max_impedance_squared {
535 self.g_fr[branch] = 0.0;
536 self.b_fr[branch] = 0.0;
537 self.g_to[branch] = 0.0;
538 self.b_to[branch] = 0.0;
539 cleared.push(branch);
540 }
541 }
542 cleared
543 }
544
545 #[must_use]
556 pub fn calc_admittance_matrix(&self, n: usize, g_s: &[f64], b_s: &[f64]) -> YbusParts {
557 let mut stamp = AdmittanceStamp::with_capacity(n, self.len());
558 for branch in 0..self.len() {
559 stamp.add_branch(
560 self.from_bus[branch],
561 self.to_bus[branch],
562 self.calc_branch_admittance(branch),
563 );
564 }
565 for bus in 0..n {
566 stamp.add_shunt(bus, Complex64::new(g_s[bus], b_s[bus]));
567 }
568 stamp.finish(true)
569 }
570}
571
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
574#[non_exhaustive]
575pub struct AcGeneratorData {
576 pub identities: Vec<String>,
578 pub bus_of_gen: Vec<usize>,
580 pub analysis_rows: Vec<usize>,
582 pub source_rows: Vec<Option<usize>>,
584 pub q: Vec<f64>,
586 pub c: Vec<f64>,
588 pub c0: Vec<f64>,
591 pub piecewise_linear: Vec<Option<PiecewiseLinearCost>>,
595 pub pmax: Vec<f64>,
596 pub pmin: Vec<f64>,
597 pub qmax: Vec<f64>,
598 pub qmin: Vec<f64>,
599 pub pg: Vec<f64>,
601 pub qg: Vec<f64>,
603 pub vg: Vec<f64>,
605 pub capability_active: Vec<bool>,
607}
608
609#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
616#[non_exhaustive]
617pub struct AcStorageData {
618 pub identities: Vec<String>,
620 pub bus_of_storage: Vec<usize>,
622 pub source_rows: Vec<usize>,
624 pub p: Vec<f64>,
625 pub q: Vec<f64>,
626 pub energy: Vec<f64>,
627 pub energy_rating: Vec<f64>,
628 pub charge_rating: Vec<f64>,
629 pub discharge_rating: Vec<f64>,
630 pub charge_efficiency: Vec<f64>,
631 pub discharge_efficiency: Vec<f64>,
632 pub s_max: Vec<f64>,
633 pub qmin: Vec<f64>,
634 pub qmax: Vec<f64>,
635 pub r: Vec<f64>,
636 pub x: Vec<f64>,
637 pub p_loss: Vec<f64>,
638 pub q_loss: Vec<f64>,
639 pub in_service: Vec<bool>,
640}
641
642#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
645#[non_exhaustive]
646pub struct NodalAcGeneratorData {
647 pub q: Vec<f64>,
648 pub c: Vec<f64>,
649 pub c0: Vec<f64>,
650 pub pmax: Vec<f64>,
651 pub pmin: Vec<f64>,
652 pub qmax: Vec<f64>,
653 pub qmin: Vec<f64>,
654 pub has_gen: Vec<bool>,
659}
660
661#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
672#[non_exhaustive]
673pub struct AcOpfPreparation {
674 pub name: String,
675 pub n_buses: usize,
676 pub n_source_generators: usize,
677 pub n_source_branches: usize,
678 pub base_mva: f64,
679 pub units: Units,
680 pub objective: PreparedObjective,
682 pub skip_zero_impedance: bool,
683 pub synthesize_unrated_limits: bool,
685 #[serde(default, skip_serializing_if = "SynthesizedLimitWindow::is_stated")]
689 pub synthesized_limit_window: SynthesizedLimitWindow,
690 pub correct_angle_difference_bounds: bool,
692 #[serde(default)]
696 pub angle_difference_bounds: Option<AngleDifferenceBounds>,
697 pub bus_ids: Vec<BusId>,
699 pub bus_analysis_rows: Vec<usize>,
701 pub bus_source_rows: Vec<Option<usize>>,
704 pub reference_buses: ReferenceBuses,
705 pub buses: AcBusData,
706 pub generators: AcGeneratorData,
707 pub storage: AcStorageData,
708 pub branches: AcBranchData,
709}
710
711impl AcOpfPreparation {
712 #[must_use]
713 pub fn n_generators(&self) -> usize {
714 self.generators.q.len()
715 }
716
717 #[must_use]
728 pub fn calc_admittance_matrix(&self) -> YbusParts {
729 self.branches
730 .calc_admittance_matrix(self.n_buses, &self.buses.g_s, &self.buses.b_s)
731 }
732
733 #[must_use]
734 pub fn n_branches(&self) -> usize {
735 self.branches.g.len()
736 }
737
738 #[must_use]
739 pub fn n_storage(&self) -> usize {
740 self.storage.identities.len()
741 }
742
743 pub fn calc_nodal_generator_data(&self) -> Result<NodalAcGeneratorData> {
753 let n = self.n_buses;
754 let generators = &self.generators;
755 if let Some(gen_index) = generators.piecewise_linear.iter().position(Option::is_some) {
756 return Err(Error::PiecewiseNodalCost { gen_index });
757 }
758 let bus_of_gen = &generators.bus_of_gen;
759 let costs =
760 nodal::combine_costs(n, bus_of_gen, &generators.q, &generators.c, &generators.c0);
761 Ok(NodalAcGeneratorData {
762 q: costs.q,
763 c: costs.c,
764 c0: costs.c0,
765 pmax: nodal::calc_bus_totals(n, bus_of_gen, &generators.pmax),
766 pmin: nodal::calc_bus_totals(n, bus_of_gen, &generators.pmin),
767 qmax: nodal::calc_bus_totals(n, bus_of_gen, &generators.qmax),
768 qmin: nodal::calc_bus_totals(n, bus_of_gen, &generators.qmin),
769 has_gen: nodal::calc_bus_hosts(n, bus_of_gen),
770 })
771 }
772
773 #[must_use]
781 pub fn calc_vm_setpoints(&self) -> Vec<f64> {
782 let mut vm: Vec<f64> = self
783 .buses
784 .initial_vm
785 .iter()
786 .map(|&value| if value > 0.0 { value } else { 1.0 })
787 .collect();
788 for generator in 0..self.n_generators() {
789 let vg = self.generators.vg[generator];
790 if vg > 0.0 {
791 vm[self.generators.bus_of_gen[generator]] = vg;
792 }
793 }
794 vm
795 }
796
797 #[must_use]
805 pub fn calc_banded_vm_setpoints(&self) -> Vec<f64> {
806 let mut vm = self.calc_vm_setpoints();
807 let regulating: Vec<usize> = self
808 .generators
809 .bus_of_gen
810 .iter()
811 .zip(&self.generators.vg)
812 .filter(|&(_, &vg)| vg > 0.0)
813 .map(|(&bus, _)| bus)
814 .collect();
815 let regulated = nodal::calc_bus_hosts(self.n_buses, ®ulating);
816 for (bus, value) in vm.iter_mut().enumerate() {
817 let (lo, hi) = (self.buses.vm_min[bus], self.buses.vm_max[bus]);
818 if regulated[bus] && lo.is_finite() && hi.is_finite() && lo <= hi {
819 *value = value.clamp(lo, hi);
820 }
821 }
822 vm
823 }
824}
825
826pub fn build_ac_opf_preparation(
835 instance: &AcOpfInstance,
836 options: &AcOpfAssemblyOptions,
837) -> Result<AcOpfPreparation> {
838 let view = IndexedNetwork::new(instance.network());
839 let objective = crate::opf::compile_objective(instance.objective())?;
840 let mut preparation = preparation_from_view(&view, *options, objective)?;
841 apply_instance_semantics(&mut preparation, instance.network(), instance.constraints())?;
842 if let Some(point) = instance.initial_point() {
843 let (power_scale, _) = options.units.power_scales(preparation.base_mva);
844 for (dense, bus) in preparation.bus_ids.iter().copied().enumerate() {
845 if let Some(value) = point.bus_voltage_magnitude(bus) {
846 preparation.buses.initial_vm[dense] = value;
847 }
848 if let Some(value) = point.bus_voltage_angle(bus) {
849 preparation.buses.initial_va[dense] = value;
850 }
851 }
852 for (generator, identity) in preparation.generators.identities.iter().enumerate() {
853 if let Some(value) = point.generator_active_power(identity) {
854 preparation.generators.pg[generator] = value * power_scale;
855 }
856 if let Some(value) = point.generator_reactive_power(identity) {
857 preparation.generators.qg[generator] = value * power_scale;
858 }
859 if let Some(value) = point.generator_voltage_setpoint(identity) {
860 preparation.generators.vg[generator] = value;
861 }
862 }
863 }
864 Ok(preparation)
865}
866
867pub fn build_ac_pf_preparation(
876 instance: &AcPfInstance,
877 options: &AcPfAssemblyOptions,
878) -> Result<AcPfPreparation> {
879 let source = instance.network();
880 let mut analysis_network = source.clone();
881 for (bus, specification) in analysis_network
882 .buses_mut()
883 .iter_mut()
884 .zip(instance.specifications())
885 {
886 bus.kind = match specification {
887 AcBusSpecification::Pq { .. } => powerio_tx::BusType::Pq,
888 AcBusSpecification::Pv { .. } => powerio_tx::BusType::Pv,
889 AcBusSpecification::Reference { .. } => powerio_tx::BusType::Ref,
890 AcBusSpecification::Isolated => powerio_tx::BusType::Isolated,
891 _ => return Err(Error::UnsupportedAcPfSpecification),
892 };
893 }
894
895 let view = IndexedNetwork::new(&analysis_network);
896 let mut common = preparation_from_view(
897 &view,
898 AcOpfAssemblyOptions {
899 units: options.units,
900 skip_zero_impedance: options.skip_zero_impedance,
901 synthesize_unrated_limits: false,
902 synthesized_limit_window: SynthesizedLimitWindow::Stated,
903 correct_angle_difference_bounds: options.correct_angle_difference_bounds,
904 angle_difference_bounds: options.angle_difference_bounds,
905 },
906 PreparedObjective::Feasibility,
907 )?;
908 apply_source_mappings(&mut common, source);
909
910 let by_source_row = calc_prepared_bus_specifications(instance, options.units)?;
911 let specifications = common
912 .bus_source_rows
913 .iter()
914 .map(|source_row| match source_row {
915 Some(row) => by_source_row[*row],
916 None => PreparedAcBusSpecification::Pq { p: 0.0, q: 0.0 },
917 })
918 .collect();
919
920 let mut initial_vm = common.buses.initial_vm.clone();
921 let mut initial_va = common
922 .bus_analysis_rows
923 .iter()
924 .map(|&row| view.to_radians(view.network().buses()[row].va))
925 .collect::<Vec<_>>();
926 if let Some(point) = instance.initial_point() {
927 for (dense, bus) in common.bus_ids.iter().copied().enumerate() {
928 if common.bus_source_rows[dense].is_none() {
929 continue;
930 }
931 if let Some(value) = point.bus_voltage_magnitude(bus) {
932 initial_vm[dense] = value;
933 }
934 if let Some(value) = point.bus_voltage_angle(bus) {
935 initial_va[dense] = value;
936 }
937 }
938 }
939
940 Ok(AcPfPreparation {
941 name: common.name,
942 n_buses: common.n_buses,
943 n_source_generators: common.n_source_generators,
944 n_source_branches: common.n_source_branches,
945 base_mva: common.base_mva,
946 units: common.units,
947 skip_zero_impedance: common.skip_zero_impedance,
948 correct_angle_difference_bounds: common.correct_angle_difference_bounds,
949 angle_difference_bounds: common.angle_difference_bounds,
950 bus_ids: common.bus_ids,
951 bus_analysis_rows: common.bus_analysis_rows,
952 bus_source_rows: common.bus_source_rows,
953 specifications,
954 reference_buses: common.reference_buses,
955 buses: AcPfBusData {
956 q_d: common.buses.q_d,
957 g_s: common.buses.g_s,
958 b_s: common.buses.b_s,
959 initial_vm,
960 initial_va,
961 },
962 generators: AcPfGeneratorData {
963 identities: common.generators.identities,
964 bus_of_gen: common.generators.bus_of_gen,
965 analysis_rows: common.generators.analysis_rows,
966 source_rows: common.generators.source_rows,
967 qg: common.generators.qg,
968 qmax: common.generators.qmax,
969 qmin: common.generators.qmin,
970 },
971 branches: common.branches,
972 })
973}
974
975pub fn calc_prepared_bus_specifications(
984 instance: &AcPfInstance,
985 units: Units,
986) -> Result<Vec<PreparedAcBusSpecification>> {
987 let source = instance.network();
988 let (power_scale, _) = units.power_scales(source.per_unit_base());
989 instance
990 .specifications()
991 .iter()
992 .map(|&specification| {
993 prepare_bus_specification(specification, power_scale, source.is_normalized())
994 })
995 .collect()
996}
997
998fn prepare_bus_specification(
999 specification: AcBusSpecification,
1000 power_scale: f64,
1001 source_is_normalized: bool,
1002) -> Result<PreparedAcBusSpecification> {
1003 Ok(match specification {
1004 AcBusSpecification::Pq { p, q } => PreparedAcBusSpecification::Pq {
1005 p: p * power_scale,
1006 q: q * power_scale,
1007 },
1008 AcBusSpecification::Pv { p, vm } => PreparedAcBusSpecification::Pv {
1009 p: p * power_scale,
1010 vm,
1011 },
1012 AcBusSpecification::Reference { vm, va } => PreparedAcBusSpecification::Reference {
1013 vm,
1014 va: if source_is_normalized {
1015 va
1016 } else {
1017 va.to_radians()
1018 },
1019 },
1020 AcBusSpecification::Isolated => PreparedAcBusSpecification::Isolated,
1021 _ => return Err(Error::UnsupportedAcPfSpecification),
1022 })
1023}
1024
1025#[allow(clippy::too_many_lines)]
1027fn preparation_from_view(
1028 case: &IndexedNetwork,
1029 options: AcOpfAssemblyOptions,
1030 objective: PreparedObjective,
1031) -> Result<AcOpfPreparation> {
1032 case.network().check_base_mva()?;
1033
1034 let active_buses = crate::opf::active_bus_index(case)?;
1035 let n_buses = active_buses.analysis_rows.len();
1036 let base = case.per_unit_base();
1037 let (p_scale, y_scale) = options.units.power_scales(base);
1038 let angle_bounds = options.selected_angle_difference_bounds();
1039 let thermal = limits::ThermalLimits {
1040 synthesize_unrated: options.synthesize_unrated_limits,
1041 window: options.synthesized_limit_window,
1042 power_scale: p_scale,
1043 admittance_scale: y_scale,
1044 };
1045 let (q_scale, c_scale) = options.units.cost_scales(base);
1046
1047 let mut bus_of_gen = Vec::new();
1048 let mut generator_identities = Vec::new();
1049 let mut generator_rows = Vec::new();
1050 let mut cost_q = Vec::new();
1051 let mut cost_c = Vec::new();
1052 let mut cost_c0 = Vec::new();
1053 let mut piecewise_linear = Vec::new();
1054 let mut pmax = Vec::new();
1055 let mut pmin = Vec::new();
1056 let mut qmax = Vec::new();
1057 let mut qmin = Vec::new();
1058 let mut pg = Vec::new();
1059 let mut qg = Vec::new();
1060 let mut vg = Vec::new();
1061
1062 for (source_row, generator) in case.in_service_gens() {
1063 let analysis_bus = case
1064 .bus_index(generator.bus)
1065 .ok_or(powerio_tx::Error::UnknownBus {
1066 bus_id: generator.bus,
1067 element_index: source_row,
1068 })?;
1069 let Some(bus) = active_buses.dense_by_analysis[analysis_bus] else {
1070 continue;
1071 };
1072 let terms = match objective {
1073 PreparedObjective::Feasibility => nodal::GeneratorCostTerms {
1074 q: 0.0,
1075 c: 0.0,
1076 c0: 0.0,
1077 piecewise_linear: None,
1078 },
1079 PreparedObjective::NetworkGeneratorCost => {
1080 let cost = generator
1081 .cost
1082 .as_ref()
1083 .ok_or(powerio_tx::Error::MissingGenCost {
1084 gen_index: source_row,
1085 })?;
1086 nodal::generator_cost_terms(cost, source_row, p_scale)?
1087 }
1088 };
1089 generator_identities.push(crate::opf::row_identity(
1090 generator.uid.as_deref(),
1091 "generators",
1092 source_row,
1093 ));
1094 bus_of_gen.push(bus);
1095 generator_rows.push(source_row);
1096 cost_q.push(terms.q * q_scale);
1097 cost_c.push(terms.c * c_scale);
1098 cost_c0.push(terms.c0);
1099 piecewise_linear.push(terms.piecewise_linear);
1100 pmax.push(generator.pmax * p_scale);
1101 pmin.push(generator.pmin * p_scale);
1102 qmax.push(generator.qmax * p_scale);
1103 qmin.push(generator.qmin * p_scale);
1104 pg.push(generator.pg * p_scale);
1105 qg.push(generator.qg * p_scale);
1106 vg.push(generator.vg);
1107 }
1108
1109 let mut storage_identities = Vec::new();
1110 let mut bus_of_storage = Vec::new();
1111 let mut storage_source_rows = Vec::new();
1112 let mut storage_p = Vec::new();
1113 let mut storage_q = Vec::new();
1114 let mut storage_energy = Vec::new();
1115 let mut storage_energy_rating = Vec::new();
1116 let mut storage_charge_rating = Vec::new();
1117 let mut storage_discharge_rating = Vec::new();
1118 let mut storage_charge_efficiency = Vec::new();
1119 let mut storage_discharge_efficiency = Vec::new();
1120 let mut storage_s_max = Vec::new();
1121 let mut storage_qmin = Vec::new();
1122 let mut storage_qmax = Vec::new();
1123 let mut storage_r = Vec::new();
1124 let mut storage_x = Vec::new();
1125 let mut storage_p_loss = Vec::new();
1126 let mut storage_q_loss = Vec::new();
1127 let mut storage_in_service = Vec::new();
1128 for (source_row, storage) in case.network().storage().iter().enumerate() {
1129 if !storage.in_service {
1130 continue;
1131 }
1132 let analysis_bus = case
1133 .bus_index(storage.bus)
1134 .ok_or(powerio_tx::Error::UnknownBus {
1135 bus_id: storage.bus,
1136 element_index: source_row,
1137 })?;
1138 let Some(bus) = active_buses.dense_by_analysis[analysis_bus] else {
1139 continue;
1140 };
1141 storage_identities.push(crate::opf::row_identity(
1142 storage.uid.as_deref(),
1143 "storage",
1144 source_row,
1145 ));
1146 bus_of_storage.push(bus);
1147 storage_source_rows.push(source_row);
1148 storage_p.push(storage.ps * p_scale);
1149 storage_q.push(storage.qs * p_scale);
1150 storage_energy.push(storage.energy * p_scale);
1151 storage_energy_rating.push(storage.energy_rating * p_scale);
1152 storage_charge_rating.push(storage.charge_rating * p_scale);
1153 storage_discharge_rating.push(storage.discharge_rating * p_scale);
1154 storage_charge_efficiency.push(storage.charge_efficiency);
1155 storage_discharge_efficiency.push(storage.discharge_efficiency);
1156 storage_s_max.push(storage.thermal_rating * p_scale);
1157 storage_qmin.push(storage.qmin * p_scale);
1158 storage_qmax.push(storage.qmax * p_scale);
1159 storage_r.push(storage.r);
1160 storage_x.push(storage.x);
1161 storage_p_loss.push(storage.p_loss * p_scale);
1162 storage_q_loss.push(storage.q_loss * p_scale);
1163 storage_in_service.push(storage.in_service);
1164 }
1165 let mut g_s: Vec<f64> = active_buses
1166 .analysis_rows
1167 .iter()
1168 .map(|&row| case.gs()[row] * p_scale)
1169 .collect();
1170 let mut b_s: Vec<f64> = active_buses
1171 .analysis_rows
1172 .iter()
1173 .map(|&row| case.bs()[row] * p_scale)
1174 .collect();
1175
1176 let mut from_bus = Vec::new();
1177 let mut branch_identities = Vec::new();
1178 let mut to_bus = Vec::new();
1179 let mut g = Vec::new();
1180 let mut b = Vec::new();
1181 let mut g_fr = Vec::new();
1182 let mut b_fr = Vec::new();
1183 let mut g_to = Vec::new();
1184 let mut b_to = Vec::new();
1185 let mut tap = Vec::new();
1186 let mut shift = Vec::new();
1187 let mut s_max = Vec::new();
1188 let mut angle_min = Vec::new();
1189 let mut angle_max = Vec::new();
1190 let mut branch_rows = Vec::new();
1191 let mut skipped_zero_impedance = Vec::new();
1192 let network = case.network();
1195
1196 for (source_row, branch) in case.in_service_branches() {
1197 let from_analysis = case
1198 .bus_index(branch.from)
1199 .ok_or(powerio_tx::Error::UnknownBus {
1200 bus_id: branch.from,
1201 element_index: source_row,
1202 })?;
1203 let to_analysis = case
1204 .bus_index(branch.to)
1205 .ok_or(powerio_tx::Error::UnknownBus {
1206 bus_id: branch.to,
1207 element_index: source_row,
1208 })?;
1209 let (Some(from), Some(to)) = (
1210 active_buses.dense_by_analysis[from_analysis],
1211 active_buses.dense_by_analysis[to_analysis],
1212 ) else {
1213 continue;
1214 };
1215 let Some((series_g, series_b)) = branch.calc_series_admittance(source_row)? else {
1216 if options.skip_zero_impedance {
1217 skipped_zero_impedance.push(source_row);
1218 continue;
1219 }
1220 return Err(powerio_tx::Error::ZeroImpedance { row: source_row }.into());
1221 };
1222 let charging = branch.calc_terminal_charging();
1223 if from == to {
1224 let folded = powerio_tx::PiModel::new(
1228 Complex64::new(series_g, series_b),
1229 Complex64::new(charging.g_fr, charging.b_fr),
1230 Complex64::new(charging.g_to, charging.b_to),
1231 branch.calc_divisible_tap(source_row)?,
1232 case.to_radians(branch.shift),
1233 )
1234 .calc_folded()
1235 * y_scale;
1236 g_s[from] += folded.re;
1237 b_s[from] += folded.im;
1238 continue;
1239 }
1240 from_bus.push(from);
1241 branch_identities.push(crate::opf::row_identity(
1242 branch.uid.as_deref(),
1243 "branches",
1244 source_row,
1245 ));
1246 to_bus.push(to);
1247 g.push(series_g * y_scale);
1248 b.push(series_b * y_scale);
1249 g_fr.push(charging.g_fr * y_scale);
1250 b_fr.push(charging.b_fr * y_scale);
1251 g_to.push(charging.g_to * y_scale);
1252 b_to.push(charging.b_to * y_scale);
1253 let source_amin = case.to_radians(branch.angmin);
1254 let source_amax = case.to_radians(branch.angmax);
1255 let branch_shift = case.to_radians(branch.shift);
1256 let (amin, amax) = angle_bounds.calc_bounds(source_amin, source_amax, branch_shift);
1257 tap.push(branch.calc_divisible_tap(source_row)?);
1258 shift.push(branch_shift);
1259 s_max.push(thermal.of(
1260 branch,
1261 (source_amin, source_amax),
1262 (amin, amax),
1263 &network.buses()[from_analysis],
1264 &network.buses()[to_analysis],
1265 )?);
1266 angle_min.push(amin);
1267 angle_max.push(amax);
1268 branch_rows.push(source_row);
1269 }
1270
1271 let mut vm_min = Vec::with_capacity(n_buses);
1272 let mut vm_max = Vec::with_capacity(n_buses);
1273 let mut initial_vm = Vec::with_capacity(n_buses);
1274 let mut initial_va = Vec::with_capacity(n_buses);
1275 for &analysis_row in &active_buses.analysis_rows {
1276 let bus = &network.buses()[analysis_row];
1277 vm_min.push(bus.vmin);
1278 vm_max.push(bus.vmax);
1279 initial_vm.push(bus.vm);
1280 initial_va.push(case.to_radians(bus.va));
1281 }
1282 let n_active_generators = cost_q.len();
1283 let n_active_branches = g.len();
1284 let thermal_limit_active = s_max.iter().map(|limit| limit.is_finite()).collect();
1285 let p_d = active_buses
1286 .analysis_rows
1287 .iter()
1288 .map(|&row| case.pd()[row] * p_scale)
1289 .collect();
1290 let q_d = active_buses
1291 .analysis_rows
1292 .iter()
1293 .map(|&row| case.qd()[row] * p_scale)
1294 .collect();
1295 let bus_analysis_rows = active_buses.analysis_rows;
1296 let bus_source_rows = bus_analysis_rows.iter().copied().map(Some).collect();
1297 Ok(AcOpfPreparation {
1298 name: case.name().to_owned(),
1299 n_buses,
1300 n_source_generators: case.generators().len(),
1301 n_source_branches: case.branches().len(),
1302 base_mva: case.base_mva(),
1303 units: options.units,
1304 objective,
1305 skip_zero_impedance: options.skip_zero_impedance,
1306 synthesize_unrated_limits: options.synthesize_unrated_limits,
1307 synthesized_limit_window: options.synthesized_limit_window,
1308 correct_angle_difference_bounds: angle_bounds.is_padded(),
1309 angle_difference_bounds: Some(angle_bounds),
1310 bus_ids: active_buses.bus_ids,
1311 bus_analysis_rows,
1312 bus_source_rows,
1313 reference_buses: active_buses.reference_buses,
1314 buses: AcBusData {
1315 p_d,
1316 q_d,
1317 g_s,
1318 b_s,
1319 vm_min,
1320 vm_max,
1321 initial_vm,
1322 initial_va,
1323 voltage_bound_active: vec![true; n_buses],
1324 },
1325 generators: AcGeneratorData {
1326 identities: generator_identities,
1327 bus_of_gen,
1328 analysis_rows: generator_rows.clone(),
1329 source_rows: generator_rows.into_iter().map(Some).collect(),
1330 q: cost_q,
1331 c: cost_c,
1332 c0: cost_c0,
1333 piecewise_linear,
1334 pmax,
1335 pmin,
1336 qmax,
1337 qmin,
1338 pg,
1339 qg,
1340 vg,
1341 capability_active: vec![true; n_active_generators],
1342 },
1343 storage: AcStorageData {
1344 identities: storage_identities,
1345 bus_of_storage,
1346 source_rows: storage_source_rows,
1347 p: storage_p,
1348 q: storage_q,
1349 energy: storage_energy,
1350 energy_rating: storage_energy_rating,
1351 charge_rating: storage_charge_rating,
1352 discharge_rating: storage_discharge_rating,
1353 charge_efficiency: storage_charge_efficiency,
1354 discharge_efficiency: storage_discharge_efficiency,
1355 s_max: storage_s_max,
1356 qmin: storage_qmin,
1357 qmax: storage_qmax,
1358 r: storage_r,
1359 x: storage_x,
1360 p_loss: storage_p_loss,
1361 q_loss: storage_q_loss,
1362 in_service: storage_in_service,
1363 },
1364 branches: AcBranchData {
1365 identities: branch_identities,
1366 from_bus,
1367 to_bus,
1368 g,
1369 b,
1370 g_fr,
1371 b_fr,
1372 g_to,
1373 b_to,
1374 tap,
1375 shift,
1376 s_max,
1377 angle_min,
1378 angle_max,
1379 analysis_rows: branch_rows.clone(),
1380 analysis_sources: branch_rows
1381 .iter()
1382 .copied()
1383 .map(|row| AnalysisBranchSource::Branch { row })
1384 .collect(),
1385 skipped_zero_impedance,
1386 thermal_limit_active,
1387 angle_bound_active: vec![true; n_active_branches],
1388 },
1389 })
1390}
1391
1392fn apply_instance_semantics(
1393 preparation: &mut AcOpfPreparation,
1394 source: &BalancedNetwork,
1395 constraints: &powerio_prob::ActiveConstraints,
1396) -> Result<()> {
1397 let source_generator_ids: Vec<String> = source
1398 .generators()
1399 .iter()
1400 .enumerate()
1401 .map(|(row, generator)| {
1402 crate::opf::row_identity(generator.uid.as_deref(), "generators", row)
1403 })
1404 .collect();
1405 let source_branch_ids: Vec<String> = source
1406 .branches()
1407 .iter()
1408 .enumerate()
1409 .map(|(row, branch)| crate::opf::row_identity(branch.uid.as_deref(), "branches", row))
1410 .collect();
1411 let mut analysis_bus_ids: Vec<String> = source
1416 .buses()
1417 .iter()
1418 .map(|bus| bus.id.to_string())
1419 .collect();
1420 let source_bus_set: std::collections::HashSet<BusId> =
1421 source.buses().iter().map(|bus| bus.id).collect();
1422 let mut added = std::collections::HashSet::new();
1423 for &bus in &preparation.bus_ids {
1424 if !source_bus_set.contains(&bus) && added.insert(bus) {
1425 analysis_bus_ids.push(bus.to_string());
1426 }
1427 }
1428
1429 preparation.buses.voltage_bound_active = crate::opf::constraint_mask(
1430 "bus voltage bounds",
1431 &constraints.voltage_bounds,
1432 &analysis_bus_ids,
1433 &preparation
1434 .bus_ids
1435 .iter()
1436 .map(ToString::to_string)
1437 .collect::<Vec<_>>(),
1438 )?;
1439 preparation.generators.capability_active = crate::opf::constraint_mask(
1440 "generator capability",
1441 &constraints.generator_capability,
1442 &source_generator_ids,
1443 &preparation.generators.identities,
1444 )?;
1445 let mut analysis_branch_ids = source_branch_ids;
1446 analysis_branch_ids.extend(
1447 preparation
1448 .branches
1449 .identities
1450 .iter()
1451 .zip(&preparation.branches.analysis_rows)
1452 .filter(|(_, row)| **row >= source.branches().len())
1453 .map(|(identity, _)| identity.clone()),
1454 );
1455 preparation.branches.thermal_limit_active = crate::opf::constraint_mask(
1456 "branch thermal limits",
1457 &constraints.thermal_limits,
1458 &analysis_branch_ids,
1459 &preparation.branches.identities,
1460 )?;
1461 for (active, limit) in preparation
1462 .branches
1463 .thermal_limit_active
1464 .iter_mut()
1465 .zip(&preparation.branches.s_max)
1466 {
1467 *active &= limit.is_finite();
1468 }
1469 preparation.branches.angle_bound_active = crate::opf::constraint_mask(
1470 "branch angle bounds",
1471 &constraints.angle_bounds,
1472 &analysis_branch_ids,
1473 &preparation.branches.identities,
1474 )?;
1475
1476 apply_source_mappings(preparation, source);
1477 Ok(())
1478}
1479
1480fn apply_source_mappings(preparation: &mut AcOpfPreparation, source: &BalancedNetwork) {
1481 preparation.n_source_generators = source.generators().len();
1482 preparation.n_source_branches = source.branches().len();
1483 preparation.bus_source_rows = preparation
1484 .bus_analysis_rows
1485 .iter()
1486 .map(|&row| (row < source.buses().len()).then_some(row))
1487 .collect();
1488 preparation.generators.source_rows = preparation
1489 .generators
1490 .analysis_rows
1491 .iter()
1492 .map(|&row| (row < source.generators().len()).then_some(row))
1493 .collect();
1494 let analysis_sources = crate::opf::analysis_branch_sources(source);
1495 preparation.branches.analysis_sources = preparation
1496 .branches
1497 .analysis_rows
1498 .iter()
1499 .map(|&row| analysis_sources[row])
1500 .collect();
1501}