Skip to main content

powerio_matrix/
opf.rs

1//! Shared OPF preparation semantics.
2
3use std::collections::HashSet;
4
5use powerio_prob::{ConstraintSelection, Objective, ObjectiveTerm, ReferenceBuses};
6use powerio_tx::{BalancedNetwork, BusId, BusType, IndexedNetwork};
7
8use crate::{Error, Result};
9
10/// The objective compiled into a balanced OPF preparation.
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
12#[serde(rename_all = "snake_case")]
13#[non_exhaustive]
14pub enum PreparedObjective {
15    /// A feasibility problem with an identically zero objective.
16    Feasibility,
17    /// The sum of the in service generators' network cost curves.
18    #[default]
19    NetworkGeneratorCost,
20}
21
22/// One convex piecewise linear generator cost in preparation units.
23///
24/// `power[i]` and `value[i]` are the supplied breakpoint coordinates after
25/// scaling the power coordinate into the preparation's [`Units`](crate::Units).
26/// Objective values do not scale with the power unit. The preparation builder
27/// validates that both columns have the same length, power is strictly
28/// increasing, and adjacent segment slopes are nondecreasing.
29#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
30#[non_exhaustive]
31pub struct PiecewiseLinearCost {
32    /// Breakpoint powers in the preparation's selected power unit.
33    pub power: Vec<f64>,
34    /// Objective values at the corresponding breakpoints.
35    pub value: Vec<f64>,
36}
37
38/// The source component represented by one branch row in a lowered analysis
39/// network.
40///
41/// Ordinary branches map to their row in `BalancedNetwork::branches()`. Each
42/// in service three winding transformer contributes three analysis branches,
43/// one for each winding in the transformer's declared terminal order. Those
44/// rows stay distinct from the source branch table.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
46#[serde(rename_all = "snake_case", tag = "kind")]
47#[non_exhaustive]
48pub enum AnalysisBranchSource {
49    Branch {
50        row: usize,
51    },
52    ThreeWindingTransformerWinding {
53        transformer_row: usize,
54        /// Winding position in `0..3`.
55        winding: usize,
56    },
57}
58
59pub(crate) fn analysis_branch_sources(source: &BalancedNetwork) -> Vec<AnalysisBranchSource> {
60    let mut sources = (0..source.branches().len())
61        .map(|row| AnalysisBranchSource::Branch { row })
62        .collect::<Vec<_>>();
63    for (transformer_row, transformer) in source.transformers_3w().iter().enumerate() {
64        if !transformer.in_service {
65            continue;
66        }
67        sources.extend((0..3).map(|winding| {
68            AnalysisBranchSource::ThreeWindingTransformerWinding {
69                transformer_row,
70                winding,
71            }
72        }));
73    }
74    sources
75}
76
77pub(crate) fn compile_objective(objective: &Objective) -> Result<PreparedObjective> {
78    match objective.terms() {
79        [] => Ok(PreparedObjective::Feasibility),
80        [ObjectiveTerm::NetworkGeneratorCost] => Ok(PreparedObjective::NetworkGeneratorCost),
81        [ObjectiveTerm::ActivePowerDispatchCost] => Err(Error::UnsupportedOpfObjective {
82            reason: "`active_power_dispatch_cost` belongs to multiconductor OPF".to_owned(),
83        }),
84        _ => Err(Error::UnsupportedOpfObjective {
85            reason: "balanced OPF preparation supports either an empty objective or exactly one `network_generator_cost` term".to_owned(),
86        }),
87    }
88}
89
90pub(crate) fn row_identity(uid: Option<&str>, table: &str, row: usize) -> String {
91    uid.map_or_else(|| format!("{table}:{row}"), str::to_owned)
92}
93
94/// Dense bus rows used by a balanced OPF preparation. A bus explicitly typed
95/// isolated states no equation, so it and every incident element stay out of
96/// the numerical problem while its source row remains in the PowerIO model.
97pub(crate) struct ActiveBusIndex {
98    pub analysis_rows: Vec<usize>,
99    pub dense_by_analysis: Vec<Option<usize>>,
100    pub bus_ids: Vec<BusId>,
101    pub reference_buses: ReferenceBuses,
102}
103
104/// Select non-isolated buses and check reference coverage on the topology that
105/// the OPF preparation will actually contain. In-service branches touching an
106/// isolated bus are excluded with that bus, matching PowerIO normalization.
107pub(crate) fn active_bus_index(case: &IndexedNetwork<'_>) -> Result<ActiveBusIndex> {
108    let mut analysis_rows = Vec::new();
109    let mut dense_by_analysis = vec![None; case.n()];
110    let mut bus_ids = Vec::new();
111    let mut reference_rows = Vec::new();
112    for (analysis_row, bus) in case.network().buses().iter().enumerate() {
113        if bus.kind == BusType::Isolated {
114            continue;
115        }
116        let dense = analysis_rows.len();
117        analysis_rows.push(analysis_row);
118        dense_by_analysis[analysis_row] = Some(dense);
119        bus_ids.push(bus.id);
120        if bus.kind == BusType::Ref {
121            reference_rows.push(dense);
122        }
123    }
124
125    // The islands of the dense buses over the in-service branches between
126    // them, by the one island labeling in powerio-tx.
127    let (from_bus, to_bus): (Vec<usize>, Vec<usize>) = case
128        .in_service_branches()
129        .filter_map(|(_, branch)| {
130            let from = dense_by_analysis[case.bus_index(branch.from)?]?;
131            let to = dense_by_analysis[case.bus_index(branch.to)?]?;
132            Some((from, to))
133        })
134        .unzip();
135    let labels = powerio_tx::calc_dense_island_labels(analysis_rows.len(), &from_bus, &to_bus);
136    let islands = labels.iter().max().map_or(0, |&last| last + 1);
137    let mut grounded = vec![false; islands];
138    for &reference in &reference_rows {
139        grounded[labels[reference]] = true;
140    }
141    let ungrounded = grounded.iter().filter(|&&grounded| !grounded).count();
142    if ungrounded > 0 {
143        return Err(powerio_tx::Error::UngroundedComponent {
144            components: ungrounded,
145        }
146        .into());
147    }
148
149    Ok(ActiveBusIndex {
150        analysis_rows,
151        dense_by_analysis,
152        bus_ids,
153        reference_buses: ReferenceBuses::new(reference_rows),
154    })
155}
156
157/// Validate a selection against the complete family and return one flag per
158/// active analysis row.
159pub(crate) fn constraint_mask(
160    family: &'static str,
161    selection: &ConstraintSelection,
162    all_identities: &[String],
163    active_identities: &[String],
164) -> Result<Vec<bool>> {
165    let mut declared = HashSet::with_capacity(all_identities.len());
166    for identity in all_identities {
167        if !declared.insert(identity.as_str()) {
168            return Err(Error::DuplicateElementIdentity {
169                family,
170                identity: identity.clone(),
171            });
172        }
173    }
174    let ConstraintSelection::Only(selected) = selection else {
175        return Ok(active_identities
176            .iter()
177            .map(|identity| selection.selects(identity))
178            .collect());
179    };
180    for identity in selected {
181        if !declared.contains(identity.as_str()) {
182            return Err(Error::UnknownConstraintIdentity {
183                family,
184                identity: identity.clone(),
185            });
186        }
187    }
188    // `ConstraintSelection::selects` scans the list per identity; a set
189    // gives the same membership in time linear in the element count.
190    let selected: HashSet<&str> = selected.iter().map(String::as_str).collect();
191    Ok(active_identities
192        .iter()
193        .map(|identity| selected.contains(identity.as_str()))
194        .collect())
195}
196
197// Keep prepared numeric bounds round-trippable without changing finite JSON
198// numbers or the binary representation. Use the shared PowerIO spelling.
199pub(crate) mod nonfinite_vec {
200    use powerio_core::__implementation::nonfinite::{NonFiniteDe, NonFiniteSer};
201    use serde::{Deserialize, Deserializer, Serialize, Serializer};
202
203    pub fn serialize<S: Serializer>(values: &[f64], serializer: S) -> Result<S::Ok, S::Error> {
204        values.serialize(NonFiniteSer(serializer))
205    }
206
207    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<f64>, D::Error> {
208        Vec::<f64>::deserialize(NonFiniteDe(deserializer))
209    }
210}