Skip to main content

powerio_matrix/
acopf.rs

1//! AC OPF assembly: the matrix free numerical arrays derived from an
2//! [`AcOpfInstance`], on the branch pi model. 0.9 exposed this surface as
3//! `powerio_prob::build_ac_opf_instance`; it lives here now beside the DC
4//! preparation so every solver formulates over the one shared assembly.
5
6use 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/// Assembly choices that select the numerical content derived from an AC
17/// instance without changing the instance itself. There is no convention
18/// field: the branch pi model always carries taps, shifts, and charging.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct AcOpfAssemblyOptions {
22    /// Power and cost scaling of the derived arrays.
23    pub units: Units,
24    /// Skip non-self-loop branches with `r² + x² = 0`. Off by default: zero
25    /// impedance branches are preserved in networks and instances, so
26    /// assembly refuses them until the caller resolves them explicitly
27    /// ([`powerio_prob::merge_zero_impedance_buses`]) or opts into skipping.
28    pub skip_zero_impedance: bool,
29    /// Give a branch with no thermal rating the bound
30    /// [`Branch::synthesize_rate_a`](powerio_tx::Branch::synthesize_rate_a)
31    /// states. If false, positive infinity is preserved in `s_max`.
32    /// A stated finite zero is always kept, regardless of this option.
33    pub synthesize_unrated_limits: bool,
34    /// The angle difference interval a synthesized limit spans: the source's
35    /// stated one (the default) or the selected bounds the preparation
36    /// carries ([`SynthesizedLimitWindow`]).
37    pub synthesized_limit_window: SynthesizedLimitWindow,
38    /// Apply PowerModels' ±60 degree correction to unconstrained or unusable
39    /// branch angle difference intervals in the prepared arrays.
40    pub correct_angle_difference_bounds: bool,
41    /// The angle difference bounds selected with
42    /// `with_angle_difference_bounds`. `None`, the default, leaves the choice
43    /// to `correct_angle_difference_bounds`
44    /// ([`AngleDifferenceBounds::from_correct_flag`]).
45    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    /// Select the angle difference interval a synthesized limit spans.
81    #[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    /// Turn PowerModels' angle difference pad on or off. This clears a
88    /// selection made with `with_angle_difference_bounds`.
89    #[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    /// Select the angle difference bounds the prepared arrays carry. The
97    /// selection takes precedence over `correct_angle_difference_bounds`,
98    /// which it sets to whether the selection pads.
99    #[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    /// The angle difference bounds these options select.
107    #[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/// Assembly choices for an AC power flow instance.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118#[non_exhaustive]
119pub struct AcPfAssemblyOptions {
120    /// Power and admittance scaling of the prepared values.
121    pub units: Units,
122    /// Skip non-self-loop branches with `r² + x² = 0`.
123    pub skip_zero_impedance: bool,
124    /// Apply PowerModels' ±60 degree correction to unconstrained or unusable
125    /// branch angle difference intervals in the prepared arrays.
126    pub correct_angle_difference_bounds: bool,
127    /// The angle difference bounds selected with
128    /// `with_angle_difference_bounds`. `None`, the default, leaves the choice
129    /// to `correct_angle_difference_bounds`
130    /// ([`AngleDifferenceBounds::from_correct_flag`]).
131    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    /// Turn PowerModels' angle difference pad on or off. This clears a
159    /// selection made with `with_angle_difference_bounds`.
160    #[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    /// Select the angle difference bounds the prepared arrays carry. The
168    /// selection takes precedence over `correct_angle_difference_bounds`,
169    /// which it sets to whether the selection pads.
170    #[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    /// The angle difference bounds these options select.
178    #[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/// One AC power flow bus specification in preparation units.
188///
189/// This has the same cases as [`AcBusSpecification`], but active and
190/// reactive power use the preparation's selected [`Units`] and reference
191/// angles are radians. The builder converts the caller's exact case and
192/// values; it never derives a replacement from the network bus type.
193#[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/// Bus values needed to start and evaluate an AC power flow.
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205#[non_exhaustive]
206pub struct AcPfBusData {
207    /// Nodal reactive demand in the selected power unit. Synthetic transformer
208    /// star buses carry zero.
209    pub q_d: Vec<f64>,
210    /// Nodal shunt conductance in the selected admittance unit.
211    pub g_s: Vec<f64>,
212    /// Nodal shunt susceptance in the selected admittance unit.
213    pub b_s: Vec<f64>,
214    /// Initial voltage magnitude, per unit.
215    pub initial_vm: Vec<f64>,
216    /// Initial voltage angle, radians.
217    pub initial_va: Vec<f64>,
218}
219
220/// Generator data used by PV to PQ reactive limit handling.
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct AcPfGeneratorData {
224    pub identities: Vec<String>,
225    /// Generator column to dense bus index.
226    pub bus_of_gen: Vec<usize>,
227    /// Generator column to row in the star-lowered analysis network.
228    pub analysis_rows: Vec<usize>,
229    /// Generator column to source generator row.
230    pub source_rows: Vec<Option<usize>>,
231    /// Initial reactive output in the selected power unit.
232    pub qg: Vec<f64>,
233    pub qmax: Vec<f64>,
234    pub qmin: Vec<f64>,
235}
236
237/// Matrix free AC power flow input on the branch pi model.
238#[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    /// Whether PowerModels' angle difference correction was applied.
249    pub correct_angle_difference_bounds: bool,
250    /// Which angle difference bounds `angle_min` and `angle_max` carry.
251    /// `None` only in a document written before the field existed, whose
252    /// `correct_angle_difference_bounds` says whether the pad was applied.
253    #[serde(default)]
254    pub angle_difference_bounds: Option<AngleDifferenceBounds>,
255    /// Dense bus index to external bus ID.
256    pub bus_ids: Vec<BusId>,
257    /// Dense bus index to row in the star-lowered analysis network.
258    pub bus_analysis_rows: Vec<usize>,
259    /// Dense bus index to source bus row. A synthetic transformer star bus has
260    /// no source row; a source bus specified as isolated has no dense row.
261    pub bus_source_rows: Vec<Option<usize>>,
262    /// Bus specifications in dense bus order. A synthetic transformer star
263    /// bus is a zero injection PQ junction. Source rows specified as isolated
264    /// are absent from the numerical rows but remain on the `AcPfInstance`.
265    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    /// The bus admittance matrix `Y = G + jB` of this preparation, in dense
279    /// bus order and the preparation's admittance unit: every branch column's
280    /// pi model block ([`AcBranchData::calc_branch_admittance`]) plus the bus
281    /// shunts `buses.g_s + j buses.b_s`. Every diagonal position is stored,
282    /// as an explicit zero where nothing stamps it.
283    ///
284    /// It agrees with [`calc_admittance_matrix`](crate::calc_admittance_matrix)
285    /// over the analysis network, restricted to the prepared buses, but needs
286    /// no network view and no remapping from analysis rows.
287    #[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/// Bus data in dense bus order.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub struct AcBusData {
303    /// Nodal active demand in the selected power unit.
304    pub p_d: Vec<f64>,
305    /// Nodal reactive demand in the selected power unit.
306    pub q_d: Vec<f64>,
307    /// Nodal shunt conductance in the selected admittance unit. Includes the
308    /// folded pi model stamp of any self-loop branch, matching `calc_admittance_matrix`.
309    pub g_s: Vec<f64>,
310    /// Nodal shunt susceptance in the selected admittance unit. Includes the
311    /// folded pi model stamp of any self-loop branch, matching `calc_admittance_matrix`.
312    pub b_s: Vec<f64>,
313    /// Voltage magnitude lower bound, per unit.
314    pub vm_min: Vec<f64>,
315    /// Voltage magnitude upper bound, per unit.
316    pub vm_max: Vec<f64>,
317    /// Initial voltage magnitude, per unit. The case voltage is used when the
318    /// instance does not supply an override.
319    pub initial_vm: Vec<f64>,
320    /// Initial voltage angle, radians. The case angle is used when the
321    /// instance does not supply an override.
322    pub initial_va: Vec<f64>,
323    /// Whether the instance activates each bus's voltage magnitude bounds.
324    pub voltage_bound_active: Vec<bool>,
325}
326
327/// Branch data in active branch column order.
328#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329#[non_exhaustive]
330pub struct AcBranchData {
331    /// Stable branch identity aligned with every following column.
332    pub identities: Vec<String>,
333    pub from_bus: Vec<usize>,
334    pub to_bus: Vec<usize>,
335    /// Series conductance `r / (r² + x²)` in the selected admittance unit.
336    pub g: Vec<f64>,
337    /// Series susceptance `−x / (r² + x²)` in the selected admittance unit.
338    pub b: Vec<f64>,
339    /// Charging conductance at the from terminal.
340    pub g_fr: Vec<f64>,
341    /// Charging susceptance at the from terminal.
342    pub b_fr: Vec<f64>,
343    /// Charging conductance at the to terminal.
344    pub g_to: Vec<f64>,
345    /// Charging susceptance at the to terminal.
346    pub b_to: Vec<f64>,
347    /// Tap ratio magnitude; one for a line. Kept separate from `shift` so a
348    /// consumer stamps the complex tap itself.
349    pub tap: Vec<f64>,
350    /// Phase shift in radians.
351    pub shift: Vec<f64>,
352    /// Apparent power limit in the selected power unit. Zero is a finite
353    /// bound; positive infinity is unlimited. Check `thermal_limit_active`.
354    #[serde(with = "crate::opf::nonfinite_vec")]
355    pub s_max: Vec<f64>,
356    /// Selected branch angle bounds in radians; absent sides are infinities.
357    #[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    /// Branch column to row in the star-lowered analysis network.
362    pub analysis_rows: Vec<usize>,
363    /// Source component for each analysis branch column. Lowered transformer
364    /// windings remain mapped to their typed transformer row and winding.
365    pub analysis_sources: Vec<AnalysisBranchSource>,
366    /// Analysis branch rows omitted because `r² + x² = 0`.
367    pub skipped_zero_impedance: Vec<usize>,
368    /// Whether the instance activates each apparent power limit.
369    pub thermal_limit_active: Vec<bool>,
370    /// Whether the instance activates each angle difference bound.
371    pub angle_bound_active: Vec<bool>,
372}
373
374/// Terminal branch flows in active branch column order, in the
375/// preparation's power unit: `S_f = pf + j qf` enters the branch at its from
376/// bus and `S_t = pt + j qt` at its to bus.
377#[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    /// Number of active branch columns.
388    #[must_use]
389    pub fn len(&self) -> usize {
390        self.g.len()
391    }
392
393    /// Whether the preparation carries no active branch.
394    #[must_use]
395    pub fn is_empty(&self) -> bool {
396        self.g.is_empty()
397    }
398
399    /// The branch's 2×2 pi model admittance block `[Yff, Yft, Ytf, Ytt]` in
400    /// the preparation's admittance unit, from its series admittance, terminal
401    /// charging, tap and shift columns:
402    ///
403    /// ```text
404    /// Yff = (y + y_fr) / tap²    Yft = -y / conj(t)
405    /// Ytf = -y / t               Ytt = y + y_to
406    /// ```
407    ///
408    /// with `y = g + j b` and `t = tap e^{j shift}`. These are the entries
409    /// [`calc_admittance_matrix`](crate::calc_admittance_matrix) stamps for
410    /// the same branch.
411    ///
412    /// # Panics
413    /// Panics if `branch` is not an active branch column.
414    #[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    /// The derivatives of [`Self::calc_branch_admittance`] for `branch`
427    /// with respect to its series conductance `g` and series susceptance
428    /// `b`, as `[d/dg, d/db]`, each a `[Yff, Yft, Ytf, Ytt]` block. The pi
429    /// model block is linear in the series admittance and does not depend on
430    /// it through the charging, so each derivative is the block of a unit
431    /// series admittance (`1` for `g`, `j` for `b`) with no charging, at the
432    /// branch's tap and shift: the same one block formula, evaluated there.
433    ///
434    /// # Panics
435    /// Panics if `branch` is not an active branch column.
436    #[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    /// The terminal flows of every active branch at the bus voltages
450    /// `vm` (per unit) and `va` (radians), both in dense bus order:
451    ///
452    /// ```text
453    /// S_f = V_f conj(Yff V_f + Yft V_t)
454    /// S_t = V_t conj(Ytf V_f + Ytt V_t)
455    /// ```
456    ///
457    /// over [`Self::calc_branch_admittance`].
458    ///
459    /// # Panics
460    /// Panics if `vm` and `va` differ in length or do not cover every bus a
461    /// branch column names.
462    #[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    /// The partials of branch column `branch`'s terminal powers
493    /// ([`Self::calc_branch_flows`]) with respect to the polar voltages of its
494    /// two buses, at `vm` (per unit) and `va` (radians) in dense bus order:
495    /// `(dS_from, dS_to)`, each ordered `[d/dva_from, d/dvm_from, d/dva_to,
496    /// d/dvm_to]`, with `S = p + j q`. The branch flow Jacobian `dSbr/dV` row
497    /// by row, over the same pi model block and terminal currents.
498    ///
499    /// # Panics
500    /// Panics if `branch` is not an active branch column or `vm`/`va` do not
501    /// cover its buses.
502    #[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    /// Zero the terminal charging of every near ideal jumper: a branch whose
518    /// series impedance satisfies `|z|² = 1 / (g² + b²) <= max_impedance_squared`.
519    /// The series admittance is kept. Returns the affected branch columns in
520    /// ascending order.
521    ///
522    /// A jumper's charging is a modeling artifact next to its very large
523    /// series admittance, and stamping both can leave a badly conditioned
524    /// admittance matrix. Apply this to a preparation before
525    /// [`AcOpfPreparation::calc_admittance_matrix`] or
526    /// [`AcPfPreparation::calc_admittance_matrix`] so the matrix, the flows of
527    /// [`Self::calc_branch_flows`] and every formulation over these columns
528    /// agree on the edited branches.
529    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    /// Stamp the bus admittance matrix of these branches and the bus shunts
546    /// `g_s + j b_s` over `n` dense buses, keeping an explicit entry at every
547    /// diagonal position, through the same accumulator as
548    /// [`calc_admittance_matrix`](crate::calc_admittance_matrix). With zero
549    /// shunts it is the branch admittance alone, whose injection
550    /// `V conj(Y V)` is the power each bus sends into its branches.
551    ///
552    /// # Panics
553    /// Panics if a branch endpoint is `>= n` or `g_s`/`b_s` is shorter than
554    /// `n`.
555    #[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/// Generator data in generator column order.
573#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
574#[non_exhaustive]
575pub struct AcGeneratorData {
576    /// Stable generator identity aligned with every following column.
577    pub identities: Vec<String>,
578    /// Generator column to dense bus index.
579    pub bus_of_gen: Vec<usize>,
580    /// Generator column to row in the analysis network.
581    pub analysis_rows: Vec<usize>,
582    /// Generator column to source generator row.
583    pub source_rows: Vec<Option<usize>>,
584    /// Quadratic objective diagonal in `0.5 * q * p^2 + c * p + c0`.
585    pub q: Vec<f64>,
586    /// Linear objective coefficient.
587    pub c: Vec<f64>,
588    /// Constant objective term. Unscaled in both unit systems: it carries no
589    /// power dimension.
590    pub c0: Vec<f64>,
591    /// Convex piecewise linear costs aligned with the generator columns. A
592    /// present curve is the complete objective term for that generator; its
593    /// `q`, `c`, and `c0` entries are zero.
594    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    /// Scheduled active output in the selected power unit.
600    pub pg: Vec<f64>,
601    /// Scheduled reactive output in the selected power unit.
602    pub qg: Vec<f64>,
603    /// Voltage magnitude setpoint, per unit; zero when the source has none.
604    pub vg: Vec<f64>,
605    /// Whether the instance activates this generator's capability bounds.
606    pub capability_active: Vec<bool>,
607}
608
609/// Storage data in active storage column order.
610///
611/// Power, energy, ratings, reactive limits, and fixed losses use the
612/// preparation's selected [`Units`]. Efficiencies, impedance, and service
613/// status are dimensionless. Out of service storage and storage attached to
614/// an isolated bus are omitted, matching the other prepared element tables.
615#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
616#[non_exhaustive]
617pub struct AcStorageData {
618    /// Stable storage identity aligned with every following column.
619    pub identities: Vec<String>,
620    /// Storage column to dense bus index.
621    pub bus_of_storage: Vec<usize>,
622    /// Storage column to source storage row.
623    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/// Generator data in dense bus order, aggregated over the generators at each
643/// bus. See [`AcOpfPreparation::calc_nodal_generator_data`].
644#[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    /// Which buses host a generator. A bus without one has a zero range and a
655    /// zero cost, which a formulation must not read as a free generator. A
656    /// reactive limit loop reads it to tell a bus that holds its voltage from
657    /// one that cannot.
658    pub has_gen: Vec<bool>,
659}
660
661/// Matrix free AC OPF input data on the branch pi model.
662///
663/// Units follow [`Units`]. Under [`Units::PerUnit`], powers are per unit on
664/// `base_mva` and admittances are per unit on the system base. Under
665/// [`Units::Native`], powers stay in MW/MVAr and every admittance vector is
666/// scaled by `base_mva`, so power computed from admittances and per unit
667/// voltages lands in MW/MVAr. Voltage magnitudes are per unit and angles are
668/// radians in both systems. Relaxations of AC OPF, the SOC forms included,
669/// consume this same preparation; the relaxation is a formulation choice
670/// made downstream.
671#[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    /// The objective represented by the generator cost columns.
681    pub objective: PreparedObjective,
682    pub skip_zero_impedance: bool,
683    /// Whether absent source ratings were replaced with synthesized limits.
684    pub synthesize_unrated_limits: bool,
685    /// The angle difference interval those limits span. Omitted from a
686    /// document when it is the stated one, so earlier documents read the
687    /// window they were built with.
688    #[serde(default, skip_serializing_if = "SynthesizedLimitWindow::is_stated")]
689    pub synthesized_limit_window: SynthesizedLimitWindow,
690    /// Whether PowerModels' angle difference correction was applied.
691    pub correct_angle_difference_bounds: bool,
692    /// Which angle difference bounds `angle_min` and `angle_max` carry.
693    /// `None` only in a document written before the field existed, whose
694    /// `correct_angle_difference_bounds` says whether the pad was applied.
695    #[serde(default)]
696    pub angle_difference_bounds: Option<AngleDifferenceBounds>,
697    /// Dense bus index to external bus ID.
698    pub bus_ids: Vec<BusId>,
699    /// Dense bus index to row in the star-lowered analysis network.
700    pub bus_analysis_rows: Vec<usize>,
701    /// Dense bus index to source bus row. A synthetic star bus has no source
702    /// row; an explicitly isolated source bus has no dense row here.
703    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    /// The bus admittance matrix `Y = G + jB` of this preparation, in dense
718    /// bus order and the preparation's admittance unit: every branch column's
719    /// pi model block ([`AcBranchData::calc_branch_admittance`]) plus the bus
720    /// shunts `buses.g_s + j buses.b_s`, which already hold any self-loop's
721    /// folded stamp. Every diagonal position is stored, as an explicit zero
722    /// where nothing stamps it.
723    ///
724    /// It agrees with [`calc_admittance_matrix`](crate::calc_admittance_matrix)
725    /// over the analysis network, restricted to the prepared buses, but needs
726    /// no network view and no remapping from analysis rows.
727    #[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    /// Project generator cost and bounds to bus space.
744    ///
745    /// The bounds at a bus are the sum of the generator bounds, which is the
746    /// range the bus total can reach. The cost curves at a bus combine by the
747    /// parallel rule `q = 1 / Σ(1/qᵢ)`, the curve that the least cost split of
748    /// the bus total follows. That combination is an approximation: it agrees
749    /// with generator space only while the split stays inside the bound of
750    /// each generator. A bus with one generator keeps that generator's own
751    /// coefficients.
752    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    /// Conventional voltage magnitude start: the case voltage, overwritten by
774    /// each generator's positive setpoint in generator column order (last
775    /// wins), with a non-positive case voltage falling back to 1.0.
776    ///
777    /// The result is not clamped to `[vm_min, vm_max]`;
778    /// [`calc_banded_vm_setpoints`](Self::calc_banded_vm_setpoints) is the
779    /// clamped form a power flow holding these magnitudes reads.
780    #[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    /// [`calc_vm_setpoints`](Self::calc_vm_setpoints) with each bus that a
798    /// generator setpoint regulates held inside its `[vm_min, vm_max]` band.
799    /// A power flow holds a regulated magnitude at its setpoint with no
800    /// magnitude variable to bound it, so an out of band setpoint would pin
801    /// the bus at an infeasible magnitude. A band that is not usable (a non
802    /// finite or inverted bound) applies no clamp, and a bus no generator
803    /// regulates keeps its case voltage.
804    #[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, &regulating);
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
826/// Derive the complete matrix free AC OPF arrays from the instance: demand,
827/// shunt, and voltage columns per bus, the full pi model per active branch,
828/// and generator costs, bounds, and schedules with their source row mapping.
829/// The AC counterpart of [`build_dc_opf_preparation`](crate::build_dc_opf_preparation).
830///
831/// # Errors
832/// A network the pi model cannot assemble: missing reference coverage, an
833/// unresolved zero impedance branch, or an unusable cost curve.
834pub 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
867/// Derive the complete matrix free AC power flow arrays from an instance.
868/// The caller's bus specifications remain authoritative. Network bus types
869/// are used only by `AcPfInstance::from_network` when it creates those
870/// specifications; this function does not infer them again.
871///
872/// # Errors
873/// A specification layout that leaves an energized component without a
874/// reference bus, or a branch pi model that cannot be assembled.
875pub 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
975/// The instance's bus specifications in preparation units, one per source
976/// bus row: power scaled by `units` over the network's per unit base (one for
977/// a normalized network), reference angles in radians. This is the conversion
978/// [`build_ac_pf_preparation`] applies; a caller that keeps its own bus index
979/// reads the same values here without building the preparation.
980///
981/// # Errors
982/// A specification case this build does not know.
983pub 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/// Build the matrix free AC OPF arrays from an indexed network view.
1026#[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    // Dense bus order is the position order of `network().buses()`; the view
1193    // already holds the star-lowered network when 3-winding expansion ran.
1194    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            // A self-loop is not a flow element; its whole pi model block
1225            // lands on the bus diagonal, folded exactly as
1226            // `calc_admittance_matrix` folds it.
1227            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    // The source buses, then each prepared bus the source does not state (a
1412    // star bus from three winding lowering). A set keeps the membership
1413    // test constant time: a linear scan here made this quadratic in the bus
1414    // count (seconds at 78,484 buses).
1415    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}