Skip to main content

powerio_matrix/dcopf/
prep.rs

1use serde::{Deserialize, Serialize};
2
3use powerio_tx::{BalancedNetwork, BranchSusceptanceFormula, BusId, HvdcTreatment, IndexedNetwork};
4
5use crate::{AnalysisBranchSource, Error, Result};
6use powerio_prob::ReferenceBuses;
7
8use super::limits::{self, SynthesizedLimitWindow};
9use super::nodal;
10use crate::{PiecewiseLinearCost, PreparedObjective};
11
12/// Unit system for power and generator cost data.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
14#[non_exhaustive]
15pub enum Units {
16    /// Power is per unit. Cost coefficients are scaled for per unit power.
17    #[default]
18    PerUnit,
19    /// Power remains in the source unit, normally MW.
20    Native,
21}
22
23impl std::str::FromStr for Units {
24    type Err = String;
25
26    /// The one alias table for the bindings: `per-unit`/`perunit`/`pu` and
27    /// `native`, case insensitive, `-`/`_` ignored.
28    fn from_str(name: &str) -> std::result::Result<Self, Self::Err> {
29        match name.to_ascii_lowercase().replace(['-', '_'], "").as_str() {
30            "perunit" | "pu" => Ok(Units::PerUnit),
31            "native" => Ok(Units::Native),
32            other => Err(format!(
33                "unknown units `{other}`; expected \"per-unit\" or \"native\""
34            )),
35        }
36    }
37}
38
39impl Units {
40    /// `(power, admittance)` multipliers for source data on `base` MVA. MW
41    /// valued quantities (demand, bounds, limits, MW valued shunts) scale by
42    /// the first; per unit admittances and susceptances by the second.
43    pub(crate) fn power_scales(self, base: f64) -> (f64, f64) {
44        match self {
45            Self::PerUnit => (1.0 / base, 1.0),
46            Self::Native => (1.0, base),
47        }
48    }
49
50    /// `(quadratic, linear)` generator cost coefficient multipliers for the
51    /// same unit selection. The constant term never scales.
52    pub(crate) fn cost_scales(self, base: f64) -> (f64, f64) {
53        match self {
54            Self::PerUnit => (base * base, base),
55            Self::Native => (1.0, 1.0),
56        }
57    }
58}
59
60/// Options for DC OPF instance assembly.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62pub struct DcOpfOptions {
63    /// Formula used to calculate each branch susceptance.
64    pub formula: BranchSusceptanceFormula,
65    pub units: Units,
66    /// Skip non-self-loop branches with an unusable formula denominator.
67    /// Series-admittance formulas bound `hypot(r, x)`; reciprocal-reactance
68    /// formulas bound `abs(x)`. Purely resistive branches remain as zero-weight
69    /// rows for series-admittance formulas. Off by default:
70    /// zero impedance branches are preserved in networks and instances, so
71    /// assembly refuses them with [`powerio_tx::Error::ZeroImpedance`] until
72    /// the caller resolves them explicitly
73    /// ([`powerio_prob::merge_zero_impedance_buses`]) or opts into skipping.
74    pub skip_zero_impedance: bool,
75    /// Give a branch with no thermal rating the bound
76    /// [`Branch::synthesize_rate_a`](powerio_tx::Branch::synthesize_rate_a)
77    /// states. If false, positive infinity is preserved in `f_max`.
78    /// A stated finite zero is always kept. `#[serde(default)]`: documents serialized before the field
79    /// existed deserialize to the default (off), the pre-field behavior.
80    #[serde(default)]
81    pub synthesize_unrated_limits: bool,
82    /// The angle difference interval a synthesized limit spans.
83    #[serde(default)]
84    pub synthesized_limit_window: SynthesizedLimitWindow,
85    /// Which angle difference bounds the prepared arrays carry.
86    #[serde(default = "default_angle_difference_bounds")]
87    pub angle_difference_bounds: powerio_tx::AngleDifferenceBounds,
88    /// How in service HVDC lines enter the fixed withdrawal.
89    #[serde(default)]
90    pub hvdc_treatment: HvdcTreatment,
91    /// The already validated instance objective to compile into the arrays.
92    pub objective: PreparedObjective,
93}
94
95const fn default_angle_difference_bounds() -> powerio_tx::AngleDifferenceBounds {
96    powerio_tx::AngleDifferenceBounds::PowerModelsPad
97}
98
99impl Default for DcOpfOptions {
100    fn default() -> Self {
101        Self {
102            formula: BranchSusceptanceFormula::default(),
103            units: Units::default(),
104            skip_zero_impedance: false,
105            synthesize_unrated_limits: false,
106            synthesized_limit_window: SynthesizedLimitWindow::Stated,
107            angle_difference_bounds: default_angle_difference_bounds(),
108            hvdc_treatment: HvdcTreatment::default(),
109            objective: PreparedObjective::default(),
110        }
111    }
112}
113
114/// Generator parameters in generator column order.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116#[non_exhaustive]
117pub struct DcGeneratorParameters {
118    /// Stable generator identity aligned with every following column.
119    pub identities: Vec<String>,
120    /// Generator column to dense bus index.
121    pub bus_of_gen: Vec<usize>,
122    /// Generator column to row in the star-lowered analysis network.
123    pub analysis_rows: Vec<usize>,
124    /// Generator column to source generator row. A synthetic analysis row has
125    /// no source row.
126    pub source_rows: Vec<Option<usize>>,
127    /// Quadratic objective diagonal in `0.5 * q * p^2 + c * p + c0`.
128    pub q: Vec<f64>,
129    /// Linear objective coefficient.
130    pub c: Vec<f64>,
131    /// Constant objective term. Unscaled in both unit systems: it carries no
132    /// power dimension. It does not move the argmin, but a consumer reporting
133    /// or comparing objective values needs it.
134    pub c0: Vec<f64>,
135    /// Convex piecewise linear costs aligned with the generator columns.
136    ///
137    /// `Some` is the complete objective term for that generator; its `q`, `c`,
138    /// and `c0` entries above are zero. `None` means the three polynomial
139    /// columns carry the complete constant, linear, or quadratic term.
140    pub piecewise_linear: Vec<Option<PiecewiseLinearCost>>,
141    pub pmax: Vec<f64>,
142    pub pmin: Vec<f64>,
143    /// Whether the instance activates this generator's capability bounds.
144    pub capability_active: Vec<bool>,
145}
146
147/// Branch parameters in active branch column order.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct DcBranchParameters {
151    /// Stable branch identity aligned with every following column.
152    pub identities: Vec<String>,
153    pub from_bus: Vec<usize>,
154    pub to_bus: Vec<usize>,
155    /// Branch susceptance in the selected power unit per radian, positive for
156    /// an inductive branch.
157    pub susceptance_magnitude: Vec<f64>,
158    /// Phase shift in radians. Zero unless the formula carries phase shift
159    /// injections.
160    pub shift: Vec<f64>,
161    /// Thermal limit in the selected power unit. Zero is a finite bound;
162    /// positive infinity is unlimited. Check `thermal_limit_active`.
163    #[serde(with = "crate::opf::nonfinite_vec")]
164    pub f_max: Vec<f64>,
165    /// Selected branch angle bounds in radians; absent sides are infinities.
166    #[serde(with = "crate::opf::nonfinite_vec")]
167    pub angle_min: Vec<f64>,
168    #[serde(with = "crate::opf::nonfinite_vec")]
169    pub angle_max: Vec<f64>,
170    /// Branch column to row in the star-lowered analysis network.
171    pub analysis_rows: Vec<usize>,
172    /// Source component for each analysis branch column. Lowered transformer
173    /// windings remain mapped to their typed transformer row and winding.
174    pub analysis_sources: Vec<AnalysisBranchSource>,
175    /// Analysis branch rows omitted because their reactance was zero.
176    pub skipped_zero_impedance: Vec<usize>,
177    /// Whether the instance activates each thermal limit.
178    pub thermal_limit_active: Vec<bool>,
179    /// Whether the instance activates each angle difference bound.
180    pub angle_bound_active: Vec<bool>,
181}
182
183/// Generator parameters in dense bus order, aggregated over the generators at each
184/// bus. See [`DcOpfPreparation::calc_nodal_generator_data`].
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186#[non_exhaustive]
187pub struct NodalGeneratorParameters {
188    pub q: Vec<f64>,
189    pub c: Vec<f64>,
190    pub c0: Vec<f64>,
191    pub pmax: Vec<f64>,
192    pub pmin: Vec<f64>,
193    /// Which buses host a generator. A bus without one has a zero range and a
194    /// zero cost, which a formulation must not read as a free generator.
195    pub has_gen: Vec<bool>,
196}
197
198/// Matrix free DC OPF input data.
199///
200/// A problem instance is complete numerical input for one problem family. It
201/// is separate from the source network, a matrix projection, a solver
202/// formulation, and a solution.
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204#[non_exhaustive]
205pub struct DcOpfPreparation {
206    pub name: String,
207    pub n_buses: usize,
208    pub n_source_generators: usize,
209    pub n_source_branches: usize,
210    pub base_mva: f64,
211    pub units: Units,
212    /// Formula used to calculate each branch susceptance.
213    pub formula: BranchSusceptanceFormula,
214    /// The objective represented by the generator cost columns.
215    pub objective: PreparedObjective,
216    pub skip_zero_impedance: bool,
217    /// Whether zero and negative source thermal ratings were replaced with
218    /// synthesized limits while assembling this instance.
219    ///
220    /// `#[serde(default)]` keeps documents written before this field readable;
221    /// their limits retain the old unsynthesized meaning.
222    #[serde(default)]
223    pub synthesize_unrated_limits: bool,
224    /// The angle difference interval those limits span. Omitted from a
225    /// document when it is the stated one, so earlier documents read the
226    /// window they were built with.
227    #[serde(default, skip_serializing_if = "SynthesizedLimitWindow::is_stated")]
228    pub synthesized_limit_window: SynthesizedLimitWindow,
229    /// Whether PowerModels' angle difference correction was applied.
230    pub correct_angle_difference_bounds: bool,
231    /// Which angle difference bounds `angle_min` and `angle_max` carry.
232    /// `None` only in a document written before the field existed, whose
233    /// `correct_angle_difference_bounds` says whether the pad was applied.
234    #[serde(default)]
235    pub angle_difference_bounds: Option<powerio_tx::AngleDifferenceBounds>,
236    /// Dense bus index to external bus ID.
237    pub bus_ids: Vec<BusId>,
238    /// Dense bus index to row in the star-lowered analysis network.
239    pub bus_analysis_rows: Vec<usize>,
240    /// Dense bus index to source bus row. A synthetic star bus has no source
241    /// row; an explicitly isolated source bus has no dense row here.
242    pub bus_source_rows: Vec<Option<usize>>,
243    pub reference_buses: ReferenceBuses,
244    /// Nodal active demand in dense bus order.
245    pub p_d: Vec<f64>,
246    /// Nodal shunt conductance in dense bus order.
247    ///
248    /// The DC power flow model holds voltage magnitude at one per unit, so a
249    /// shunt draws the constant real power `g_s` and does not depend on the
250    /// angle. It belongs in the injection: the bus susceptance matrix keeps
251    /// zero row sums and carries no shunt. A nodal balance subtracts it
252    /// beside [`Self::p_d`], as MATPOWER `runpf` does.
253    pub g_s: Vec<f64>,
254    /// Nodal phase shift injection in dense bus order. The complete fixed
255    /// withdrawal in `L theta = Cg pg - fixed` is
256    /// `p_d + g_s + p_shift - p_hvdc`.
257    pub p_shift: Vec<f64>,
258    /// How in service HVDC lines entered [`Self::p_hvdc`].
259    ///
260    /// `#[serde(default)]` keeps documents written before this field
261    /// readable.
262    #[serde(default)]
263    pub hvdc_treatment: HvdcTreatment,
264    /// Nodal fixed HVDC injection in dense bus order: `-pf` at each in
265    /// service line's from bus and `+pt` at its to bus
266    /// ([`IndexedNetwork::p_hvdc`]). All zero under
267    /// [`HvdcTreatment::Ignore`]. An injection, so the fixed withdrawal
268    /// subtracts it.
269    ///
270    /// `#[serde(default)]`: a document written before this field reads as
271    /// empty, which [`Self::calc_fixed_nodal_withdrawal`] takes as zero.
272    #[serde(default)]
273    pub p_hvdc: Vec<f64>,
274    pub generators: DcGeneratorParameters,
275    pub branches: DcBranchParameters,
276}
277
278impl DcOpfPreparation {
279    #[must_use]
280    pub fn n_generators(&self) -> usize {
281        self.generators.q.len()
282    }
283
284    #[must_use]
285    pub fn n_branches(&self) -> usize {
286        self.branches.susceptance_magnitude.len()
287    }
288
289    /// Fixed nodal withdrawal in dense bus order.
290    ///
291    /// With `A` oriented from bus to bus and
292    /// `L = A diag(b) A^T`, the DC balance is
293    /// `L theta = Cg pg - (p_d + g_s + p_shift - p_hvdc)`.
294    /// It is [`calc_device_withdrawal`](Self::calc_device_withdrawal) plus
295    /// the phase shift withdrawal `p_shift`.
296    #[must_use]
297    pub fn calc_fixed_nodal_withdrawal(&self) -> Vec<f64> {
298        let mut withdrawal = self.calc_device_withdrawal();
299        for (value, shift) in withdrawal.iter_mut().zip(&self.p_shift) {
300            *value += shift;
301        }
302        withdrawal
303    }
304
305    /// The withdrawal of the bus devices in dense bus order,
306    /// `p_d + g_s - p_hvdc`: the fixed nodal withdrawal without the phase
307    /// shift term, which the branch flows carry rather than the bus. Net
308    /// generation less this is the bus injection a solution reports.
309    #[must_use]
310    pub fn calc_device_withdrawal(&self) -> Vec<f64> {
311        (0..self.n_buses)
312            .map(|bus| {
313                let p_hvdc = self.p_hvdc.get(bus).copied().unwrap_or(0.0);
314                self.p_d[bus] + self.g_s[bus] - p_hvdc
315            })
316            .collect()
317    }
318
319    /// Fixed branch flow offset in active branch column order.
320    ///
321    /// The complete branch flow over this preparation's internal positive
322    /// weights is `f = diag(b) A^T theta + branch_flow_offset`, where the
323    /// offset is `-b * shift` elementwise. In the public PowerModels sign
324    /// spelling the same flow is `p_branch = -Bf va + b .* shift` with the
325    /// negated susceptances ([`crate::DcOperators`] emits that
326    /// form); the two agree term for term because this `b` is the negation
327    /// of the public one.
328    #[must_use]
329    pub fn calc_branch_flow_offset(&self) -> Vec<f64> {
330        self.branches
331            .susceptance_magnitude
332            .iter()
333            .zip(&self.branches.shift)
334            .map(|(&weight, &shift)| crate::matrix::calc_dc_flow_offset(weight, shift))
335            .collect()
336    }
337
338    /// The nodal phase shift withdrawal `A branch_flow_offset` of this
339    /// preparation's branch columns, in dense bus order and the
340    /// preparation's power unit: each branch's
341    /// [`calc_branch_flow_offset`](Self::calc_branch_flow_offset) leaves at
342    /// its from bus and arrives at its to bus. This is the calculation behind
343    /// [`Self::p_shift`]; a caller that edits the branch weights or shifts
344    /// recomputes `p_shift` with it.
345    #[must_use]
346    pub fn calc_phase_shift_withdrawal(&self) -> Vec<f64> {
347        let branches = &self.branches;
348        crate::matrix::calc_dc_phase_shift_withdrawal(
349            self.n_buses,
350            branches
351                .from_bus
352                .iter()
353                .copied()
354                .zip(branches.to_bus.iter().copied())
355                .zip(branches.susceptance_magnitude.iter().copied())
356                .zip(branches.shift.iter().copied())
357                .map(|((endpoints, weight), shift)| (endpoints, weight, shift)),
358        )
359    }
360
361    /// Project generator cost and bounds to bus space.
362    ///
363    /// The bounds at a bus are the sum of the generator bounds, which is the
364    /// range the bus total can reach. The cost curves at a bus combine by the
365    /// parallel rule `q = 1 / Σ(1/qᵢ)`, the curve that the least cost split of
366    /// the bus total follows. That combination is an approximation: it agrees
367    /// with generator space only while the split stays inside the bound of
368    /// each generator. A bus with one generator keeps that generator's own
369    /// coefficients.
370    pub fn calc_nodal_generator_data(&self) -> Result<NodalGeneratorParameters> {
371        let n = self.n_buses;
372        let generators = &self.generators;
373        if let Some(gen_index) = generators.piecewise_linear.iter().position(Option::is_some) {
374            return Err(Error::PiecewiseNodalCost { gen_index });
375        }
376        let bus_of_gen = &generators.bus_of_gen;
377        let costs =
378            nodal::combine_costs(n, bus_of_gen, &generators.q, &generators.c, &generators.c0);
379        Ok(NodalGeneratorParameters {
380            q: costs.q,
381            c: costs.c,
382            c0: costs.c0,
383            pmax: nodal::calc_bus_totals(n, bus_of_gen, &generators.pmax),
384            pmin: nodal::calc_bus_totals(n, bus_of_gen, &generators.pmin),
385            has_gen: nodal::calc_bus_hosts(n, bus_of_gen),
386        })
387    }
388}
389
390/// Build the matrix free DC OPF arrays from an indexed network view. The
391/// public instance level entry is
392/// [`build_dc_opf_preparation`](crate::build_dc_opf_preparation), which
393/// derives the view and the options from a
394/// [`DcOpfInstance`](powerio_prob::DcOpfInstance).
395#[allow(clippy::too_many_lines)]
396pub(crate) fn preparation_from_view(
397    case: &IndexedNetwork,
398    options: DcOpfOptions,
399) -> Result<DcOpfPreparation> {
400    case.network().check_base_mva()?;
401
402    let active_buses = crate::opf::active_bus_index(case)?;
403    let n_buses = active_buses.analysis_rows.len();
404    let base = case.per_unit_base();
405    let (p_scale, b_scale) = options.units.power_scales(base);
406    let thermal = limits::ThermalLimits {
407        synthesize_unrated: options.synthesize_unrated_limits,
408        window: options.synthesized_limit_window,
409        power_scale: p_scale,
410        admittance_scale: b_scale,
411    };
412    let (q_scale, c_scale) = options.units.cost_scales(base);
413
414    let mut bus_of_gen = Vec::new();
415    let mut generator_identities = Vec::new();
416    let mut generator_rows = Vec::new();
417    let mut q = Vec::new();
418    let mut c = Vec::new();
419    let mut c0 = Vec::new();
420    let mut piecewise_linear = Vec::new();
421    let mut pmax = Vec::new();
422    let mut pmin = Vec::new();
423
424    for (source_row, generator) in case.in_service_gens() {
425        let analysis_bus = case
426            .bus_index(generator.bus)
427            .ok_or(powerio_tx::Error::UnknownBus {
428                bus_id: generator.bus,
429                element_index: source_row,
430            })?;
431        let Some(bus) = active_buses.dense_by_analysis[analysis_bus] else {
432            continue;
433        };
434        let terms = match options.objective {
435            PreparedObjective::Feasibility => nodal::GeneratorCostTerms {
436                q: 0.0,
437                c: 0.0,
438                c0: 0.0,
439                piecewise_linear: None,
440            },
441            PreparedObjective::NetworkGeneratorCost => {
442                let cost = generator
443                    .cost
444                    .as_ref()
445                    .ok_or(powerio_tx::Error::MissingGenCost {
446                        gen_index: source_row,
447                    })?;
448                nodal::generator_cost_terms(cost, source_row, p_scale)?
449            }
450        };
451        generator_identities.push(crate::opf::row_identity(
452            generator.uid.as_deref(),
453            "generators",
454            source_row,
455        ));
456        bus_of_gen.push(bus);
457        generator_rows.push(source_row);
458        q.push(terms.q * q_scale);
459        c.push(terms.c * c_scale);
460        c0.push(terms.c0);
461        piecewise_linear.push(terms.piecewise_linear);
462        pmax.push(generator.pmax * p_scale);
463        pmin.push(generator.pmin * p_scale);
464    }
465    if q.is_empty() {
466        return Err(Error::NoGenerators);
467    }
468
469    let mut from_bus = Vec::new();
470    let mut branch_identities = Vec::new();
471    let mut to_bus = Vec::new();
472    let mut b = Vec::new();
473    let mut shift = Vec::new();
474    let mut f_max = Vec::new();
475    let mut angle_min = Vec::new();
476    let mut angle_max = Vec::new();
477    let mut branch_rows = Vec::new();
478    let mut skipped_zero_impedance = Vec::new();
479    // Dense bus order is the position order of `network().buses`.
480    let buses = &case.network().buses();
481
482    for (source_row, branch) in case.in_service_branches() {
483        let from_analysis = case
484            .bus_index(branch.from)
485            .ok_or(powerio_tx::Error::UnknownBus {
486                bus_id: branch.from,
487                element_index: source_row,
488            })?;
489        let to_analysis = case
490            .bus_index(branch.to)
491            .ok_or(powerio_tx::Error::UnknownBus {
492                bus_id: branch.to,
493                element_index: source_row,
494            })?;
495        let (Some(from), Some(to)) = (
496            active_buses.dense_by_analysis[from_analysis],
497            active_buses.dense_by_analysis[to_analysis],
498        ) else {
499            continue;
500        };
501        if from == to {
502            // A self-loop carries no angle difference, so it contributes no
503            // DC flow, and its shift injection cancels at its own bus.
504            continue;
505        }
506        // The one DC column rule. A purely resistive branch keeps its
507        // zero-weight row under the series formulas.
508        let Some(column) =
509            options
510                .formula
511                .calc_dc_column(branch, source_row, case.network().is_normalized())?
512        else {
513            if options.skip_zero_impedance {
514                skipped_zero_impedance.push(source_row);
515                continue;
516            }
517            return Err(powerio_tx::Error::ZeroImpedance { row: source_row }.into());
518        };
519        let branch_b = column.weight * b_scale;
520        let shift_rad = column.shift;
521        let source_amin = case.to_radians(branch.angmin);
522        let source_amax = case.to_radians(branch.angmax);
523        let (amin, amax) =
524            options
525                .angle_difference_bounds
526                .calc_bounds(source_amin, source_amax, shift_rad);
527        from_bus.push(from);
528        branch_identities.push(crate::opf::row_identity(
529            branch.uid.as_deref(),
530            "branches",
531            source_row,
532        ));
533        to_bus.push(to);
534        b.push(branch_b);
535        shift.push(shift_rad);
536        f_max.push(thermal.of(
537            branch,
538            (source_amin, source_amax),
539            (amin, amax),
540            &buses[from_analysis],
541            &buses[to_analysis],
542        )?);
543        angle_min.push(amin);
544        angle_max.push(amax);
545        branch_rows.push(source_row);
546    }
547
548    let n_active_generators = q.len();
549    let n_active_branches = b.len();
550    // The flow offset of every branch leaves at its from bus and arrives at
551    // its to bus, as a withdrawal.
552    let p_shift = crate::matrix::calc_dc_phase_shift_withdrawal(
553        n_buses,
554        from_bus
555            .iter()
556            .copied()
557            .zip(to_bus.iter().copied())
558            .zip(b.iter().copied())
559            .zip(shift.iter().copied())
560            .map(|((endpoints, weight), shift)| (endpoints, weight, shift)),
561    );
562    let thermal_limit_active = f_max.iter().map(|limit| limit.is_finite()).collect();
563    let bus_analysis_rows = active_buses.analysis_rows;
564    let p_d = bus_analysis_rows
565        .iter()
566        .map(|&row| case.pd()[row] * p_scale)
567        .collect();
568    let g_s = bus_analysis_rows
569        .iter()
570        .map(|&row| case.gs()[row] * p_scale)
571        .collect();
572    let p_hvdc = match options.hvdc_treatment {
573        HvdcTreatment::Ignore => vec![0.0; n_buses],
574        // A future treatment must state its own withdrawal; until then the
575        // stated injection is the only one this preparation knows.
576        _ => bus_analysis_rows
577            .iter()
578            .map(|&row| case.p_hvdc()[row] * p_scale)
579            .collect(),
580    };
581    let bus_source_rows = bus_analysis_rows.iter().copied().map(Some).collect();
582    Ok(DcOpfPreparation {
583        name: case.name().to_owned(),
584        n_buses,
585        n_source_generators: case.generators().len(),
586        n_source_branches: case.branches().len(),
587        base_mva: case.base_mva(),
588        units: options.units,
589        formula: options.formula,
590        objective: options.objective,
591        skip_zero_impedance: options.skip_zero_impedance,
592        synthesize_unrated_limits: options.synthesize_unrated_limits,
593        synthesized_limit_window: options.synthesized_limit_window,
594        correct_angle_difference_bounds: options.angle_difference_bounds.is_padded(),
595        angle_difference_bounds: Some(options.angle_difference_bounds),
596        bus_ids: active_buses.bus_ids,
597        bus_analysis_rows,
598        bus_source_rows,
599        reference_buses: active_buses.reference_buses,
600        p_d,
601        g_s,
602        p_shift,
603        hvdc_treatment: options.hvdc_treatment,
604        p_hvdc,
605        generators: DcGeneratorParameters {
606            identities: generator_identities,
607            bus_of_gen,
608            analysis_rows: generator_rows.clone(),
609            source_rows: generator_rows.into_iter().map(Some).collect(),
610            q,
611            c,
612            c0,
613            piecewise_linear,
614            pmax,
615            pmin,
616            capability_active: vec![true; n_active_generators],
617        },
618        branches: DcBranchParameters {
619            identities: branch_identities,
620            from_bus,
621            to_bus,
622            susceptance_magnitude: b,
623            shift,
624            f_max,
625            angle_min,
626            angle_max,
627            analysis_rows: branch_rows.clone(),
628            analysis_sources: branch_rows
629                .iter()
630                .copied()
631                .map(|row| AnalysisBranchSource::Branch { row })
632                .collect(),
633            skipped_zero_impedance,
634            thermal_limit_active,
635            angle_bound_active: vec![true; n_active_branches],
636        },
637    })
638}
639
640/// Apply the source instance's active constraint selections and source row
641/// provenance after the numerical view has been star-lowered.
642pub(crate) fn apply_instance_semantics(
643    preparation: &mut DcOpfPreparation,
644    source: &BalancedNetwork,
645    constraints: &powerio_prob::ActiveConstraints,
646) -> Result<()> {
647    let source_generator_ids: Vec<String> = source
648        .generators()
649        .iter()
650        .enumerate()
651        .map(|(row, generator)| {
652            crate::opf::row_identity(generator.uid.as_deref(), "generators", row)
653        })
654        .collect();
655    let source_branch_ids: Vec<String> = source
656        .branches()
657        .iter()
658        .enumerate()
659        .map(|(row, branch)| crate::opf::row_identity(branch.uid.as_deref(), "branches", row))
660        .collect();
661
662    preparation.generators.capability_active = crate::opf::constraint_mask(
663        "generator capability",
664        &constraints.generator_capability,
665        &source_generator_ids,
666        &preparation.generators.identities,
667    )?;
668
669    // DC fixes every voltage magnitude at one per unit, so it has no voltage
670    // bound rows to expose. Still validate an explicit identity selection:
671    // a misspelled bus must not disappear merely because this formulation
672    // has no corresponding variable.
673    let source_bus_ids: Vec<String> = source
674        .buses()
675        .iter()
676        .map(|bus| bus.id.to_string())
677        .collect();
678    let _ = crate::opf::constraint_mask(
679        "bus voltage bounds",
680        &constraints.voltage_bounds,
681        &source_bus_ids,
682        &[],
683    )?;
684
685    // Synthetic winding branches are part of the analysis family and are
686    // addressable by the identities returned in the preparation.
687    let mut analysis_branch_ids = source_branch_ids;
688    analysis_branch_ids.extend(
689        preparation
690            .branches
691            .identities
692            .iter()
693            .zip(&preparation.branches.analysis_rows)
694            .filter(|(_, row)| **row >= source.branches().len())
695            .map(|(identity, _)| identity.clone()),
696    );
697    preparation.branches.thermal_limit_active = crate::opf::constraint_mask(
698        "branch thermal limits",
699        &constraints.thermal_limits,
700        &analysis_branch_ids,
701        &preparation.branches.identities,
702    )?;
703    for (active, limit) in preparation
704        .branches
705        .thermal_limit_active
706        .iter_mut()
707        .zip(&preparation.branches.f_max)
708    {
709        *active &= limit.is_finite();
710    }
711    preparation.branches.angle_bound_active = crate::opf::constraint_mask(
712        "branch angle bounds",
713        &constraints.angle_bounds,
714        &analysis_branch_ids,
715        &preparation.branches.identities,
716    )?;
717
718    preparation.n_source_generators = source.generators().len();
719    preparation.n_source_branches = source.branches().len();
720    preparation.bus_source_rows = preparation
721        .bus_analysis_rows
722        .iter()
723        .map(|&row| (row < source.buses().len()).then_some(row))
724        .collect();
725    preparation.generators.source_rows = preparation
726        .generators
727        .analysis_rows
728        .iter()
729        .map(|&row| (row < source.generators().len()).then_some(row))
730        .collect();
731    let analysis_sources = crate::opf::analysis_branch_sources(source);
732    preparation.branches.analysis_sources = preparation
733        .branches
734        .analysis_rows
735        .iter()
736        .map(|&row| analysis_sources[row])
737        .collect();
738    Ok(())
739}