powerio_matrix/dcopf/mod.rs
1//! DC OPF assembly: the numerical preparation arrays, sparse matrices, and
2//! bundle writer derived from a [`DcOpfInstance`].
3
4mod bundle;
5pub(crate) mod limits;
6pub(crate) mod nodal;
7mod prep;
8#[cfg(test)]
9mod tests;
10
11use crate::matrix::calc_solver_branch_flow_matrix;
12use crate::{
13 IndexedNetwork, SparseMatrix, calc_diagonal, calc_reference_indicator, calc_weighted_laplacian,
14 ground_at_each,
15};
16
17use crate::Result;
18use powerio_prob::DcOpfInstance;
19use powerio_tx::AngleDifferenceBounds;
20use powerio_tx::HvdcTreatment;
21use prep::{DcOpfOptions, apply_instance_semantics, preparation_from_view};
22
23pub use bundle::{DcOpfBundleMetadata, DcOpfBundleOptions, DcOpfOutputs, emit_dcopf_bundle};
24pub use limits::SynthesizedLimitWindow;
25pub use nodal::{calc_bus_hosts, calc_bus_totals};
26pub use prep::{
27 DcBranchParameters, DcGeneratorParameters, DcOpfPreparation, NodalGeneratorParameters, Units,
28};
29
30/// Assembly choices that select the numerical content derived from an
31/// instance without changing the instance itself.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct DcOpfAssemblyOptions {
35 /// Power and cost scaling of the derived arrays.
36 pub units: Units,
37 /// Skip non-self-loop branches with an unusable formula denominator.
38 /// Series-admittance formulas bound `hypot(r, x)`; reciprocal-reactance
39 /// formulas bound `abs(x)`. Purely resistive branches remain as zero-weight
40 /// rows for series-admittance formulas. Off by default:
41 /// zero impedance branches are preserved in networks and instances, so
42 /// assembly refuses them until the caller resolves them explicitly
43 /// ([`powerio_prob::merge_zero_impedance_buses`]) or opts into skipping.
44 pub skip_zero_impedance: bool,
45 /// Give a branch with no thermal rating the bound
46 /// [`Branch::synthesize_rate_a`](powerio_tx::Branch::synthesize_rate_a)
47 /// states. If false, an absent rating reads as unlimited.
48 pub synthesize_unrated_limits: bool,
49 /// The angle difference interval a synthesized limit spans: the source's
50 /// stated one (the default) or the selected bounds the preparation
51 /// carries ([`SynthesizedLimitWindow`]).
52 pub synthesized_limit_window: SynthesizedLimitWindow,
53 /// Apply PowerModels' ±60 degree correction to unconstrained or unusable
54 /// branch angle difference intervals in the prepared arrays.
55 pub correct_angle_difference_bounds: bool,
56 /// How in service HVDC lines enter the fixed withdrawal. The default
57 /// carries each as a fixed injection at its stated terminal powers
58 /// ([`DcOpfPreparation::p_hvdc`]).
59 pub hvdc_treatment: HvdcTreatment,
60 /// The angle difference bounds selected with
61 /// `with_angle_difference_bounds`. `None`, the default, leaves the choice
62 /// to `correct_angle_difference_bounds`
63 /// ([`AngleDifferenceBounds::from_correct_flag`]).
64 pub angle_difference_bounds: Option<AngleDifferenceBounds>,
65}
66
67impl Default for DcOpfAssemblyOptions {
68 fn default() -> Self {
69 Self {
70 units: Units::default(),
71 skip_zero_impedance: false,
72 synthesize_unrated_limits: false,
73 synthesized_limit_window: SynthesizedLimitWindow::Stated,
74 correct_angle_difference_bounds: true,
75 hvdc_treatment: HvdcTreatment::default(),
76 angle_difference_bounds: None,
77 }
78 }
79}
80
81impl DcOpfAssemblyOptions {
82 #[must_use]
83 pub const fn with_units(mut self, units: Units) -> Self {
84 self.units = units;
85 self
86 }
87
88 #[must_use]
89 pub const fn with_skip_zero_impedance(mut self, skip: bool) -> Self {
90 self.skip_zero_impedance = skip;
91 self
92 }
93
94 #[must_use]
95 pub const fn with_synthesize_unrated_limits(mut self, synthesize: bool) -> Self {
96 self.synthesize_unrated_limits = synthesize;
97 self
98 }
99
100 /// Select the angle difference interval a synthesized limit spans.
101 #[must_use]
102 pub const fn with_synthesized_limit_window(mut self, window: SynthesizedLimitWindow) -> Self {
103 self.synthesized_limit_window = window;
104 self
105 }
106
107 /// Turn PowerModels' angle difference pad on or off. This clears a
108 /// selection made with `with_angle_difference_bounds`.
109 #[must_use]
110 pub const fn with_correct_angle_difference_bounds(mut self, correct: bool) -> Self {
111 self.correct_angle_difference_bounds = correct;
112 self.angle_difference_bounds = None;
113 self
114 }
115
116 #[must_use]
117 pub const fn with_hvdc_treatment(mut self, treatment: HvdcTreatment) -> Self {
118 self.hvdc_treatment = treatment;
119 self
120 }
121
122 /// Select the angle difference bounds the prepared arrays carry. The
123 /// selection takes precedence over `correct_angle_difference_bounds`,
124 /// which it sets to whether the selection pads.
125 #[must_use]
126 pub const fn with_angle_difference_bounds(mut self, bounds: AngleDifferenceBounds) -> Self {
127 self.correct_angle_difference_bounds = bounds.is_padded();
128 self.angle_difference_bounds = Some(bounds);
129 self
130 }
131
132 /// The angle difference bounds these options select.
133 #[must_use]
134 pub const fn selected_angle_difference_bounds(&self) -> AngleDifferenceBounds {
135 match self.angle_difference_bounds {
136 Some(bounds) => bounds,
137 None => AngleDifferenceBounds::from_correct_flag(self.correct_angle_difference_bounds),
138 }
139 }
140}
141
142/// Sparse matrices for a DC OPF instance.
143#[derive(Debug, Clone)]
144#[non_exhaustive]
145pub struct DcOpfMatrices {
146 /// Bus by branch incidence matrix, with `+1` at each from bus and `-1` at
147 /// each to bus.
148 pub bus_branch_incidence: SparseMatrix,
149 pub laplacian: SparseMatrix,
150 pub grounded_laplacian: SparseMatrix,
151 /// Branch by bus flow matrix over the positive solver susceptance
152 /// magnitudes.
153 pub branch_flow_matrix: SparseMatrix,
154 pub generator_bus: SparseMatrix,
155 /// Generator space quadratic cost diagonal.
156 pub generator_cost: SparseMatrix,
157 pub reference_selector: Vec<f64>,
158}
159
160/// Derive the sparse DC OPF matrices from the instance. The instance keeps
161/// the typed network; an external solver that needs the contiguous arrays
162/// behind these matrices calls [`build_dc_opf_preparation`] instead.
163///
164/// # Errors
165/// A network the selected branch susceptance formula cannot assemble: missing reference
166/// coverage, an unresolved zero impedance branch, or an unusable cost curve.
167pub fn calc_dc_opf_matrices(
168 instance: &DcOpfInstance,
169 options: &DcOpfAssemblyOptions,
170) -> Result<DcOpfMatrices> {
171 Ok(matrices_from_preparation(&build_dc_opf_preparation(
172 instance, options,
173 )?))
174}
175
176/// Derive the complete matrix free DC OPF arrays from the instance: demand,
177/// shunt, phase shift, and HVDC withdrawals, generator costs and bounds with their
178/// source row mapping, branch susceptances as positive solver edge weights,
179/// thermal limits, angle bounds, and the reference bus set. This is the one
180/// numerical assembly the matrix builders, the bundle writer, and external
181/// solvers read, published so each consumer formulates over the same arrays
182/// instead of re-deriving them from the network. [`DcOpfPreparation`]
183/// documents each field's unit and sign.
184///
185/// # Errors
186/// As [`calc_dc_opf_matrices`].
187pub fn build_dc_opf_preparation(
188 instance: &DcOpfInstance,
189 options: &DcOpfAssemblyOptions,
190) -> Result<DcOpfPreparation> {
191 let view = IndexedNetwork::new(instance.network());
192 let objective = crate::opf::compile_objective(instance.objective())?;
193 let mut preparation = preparation_from_view(
194 &view,
195 DcOpfOptions {
196 formula: instance.branch_susceptance_formula(),
197 units: options.units,
198 skip_zero_impedance: options.skip_zero_impedance,
199 synthesize_unrated_limits: options.synthesize_unrated_limits,
200 synthesized_limit_window: options.synthesized_limit_window,
201 angle_difference_bounds: options.selected_angle_difference_bounds(),
202 hvdc_treatment: options.hvdc_treatment,
203 objective,
204 },
205 )?;
206 apply_instance_semantics(&mut preparation, instance.network(), instance.constraints())?;
207 Ok(preparation)
208}
209
210impl DcOpfPreparation {
211 /// The signed bus by branch incidence matrix `A` of this preparation,
212 /// `n_buses × n_branches` CSR: column `e` has `+1` at the branch's from
213 /// bus and `-1` at its to bus, in active branch column order. Self-loops
214 /// never reach the preparation, so every column has exactly two entries.
215 ///
216 /// This is the matrix [`DcOpfMatrices::bus_branch_incidence`] carries,
217 /// from the one incidence assembly every builder in the crate uses, read
218 /// from the arrays the preparation already holds: one pass over the
219 /// branch columns, with no network indexing and no
220 /// [`DcOperators`](crate::DcOperators) build. Row `i` of the CSR lists
221 /// the `(branch, sign)` pairs at bus `i` in ascending branch order.
222 ///
223 /// # Panics
224 /// Panics if a branch column names a bus `>= n_buses`, which no
225 /// preparation builder produces.
226 #[must_use]
227 pub fn calc_bus_branch_incidence(&self) -> SparseMatrix {
228 crate::matrix::assemble_bus_branch_incidence(
229 self.n_buses,
230 self.branches
231 .from_bus
232 .iter()
233 .copied()
234 .zip(self.branches.to_bus.iter().copied()),
235 )
236 }
237
238 /// The generator to bus map `Cg` of this preparation, `n_buses ×
239 /// n_generators` CSR with a `1` at row `bus_of_gen[g]` of column `g`. Row
240 /// `i` lists the generators at bus `i` in ascending column order. This is
241 /// [`DcOpfMatrices::generator_bus`].
242 ///
243 /// # Panics
244 /// Panics if a generator names a bus `>= n_buses`, which no preparation
245 /// builder produces.
246 #[must_use]
247 pub fn calc_generator_bus_incidence(&self) -> SparseMatrix {
248 crate::matrix::assemble_bus_indicator(self.n_buses, &self.generators.bus_of_gen)
249 }
250
251 /// Every sparse DC OPF matrix of this preparation, as
252 /// [`calc_dc_opf_matrices`] returns them for the instance the
253 /// preparation came from, without preparing it again.
254 #[must_use]
255 pub fn calc_matrices(&self) -> DcOpfMatrices {
256 matrices_from_preparation(self)
257 }
258
259 /// The branch flows at the bus angles `theta` (radians, dense bus order),
260 /// in active branch column order and the preparation's power unit:
261 /// `f = diag(b) Aᵀ theta + branch_flow_offset`, with `b` the positive
262 /// [`DcBranchParameters::susceptance_magnitude`] and the offset from
263 /// [`Self::calc_branch_flow_offset`]. Positive flow runs from the from
264 /// bus to the to bus.
265 ///
266 /// # Panics
267 /// Panics if `theta.len()` is not `n_buses`.
268 #[must_use]
269 pub fn calc_branch_flow(&self, theta: &[f64]) -> Vec<f64> {
270 assert_eq!(
271 theta.len(),
272 self.n_buses,
273 "calc_branch_flow: theta has {} entries for {} buses",
274 theta.len(),
275 self.n_buses
276 );
277 let branches = &self.branches;
278 crate::matrix::calc_dc_branch_flow(
279 theta,
280 branches
281 .from_bus
282 .iter()
283 .copied()
284 .zip(branches.to_bus.iter().copied())
285 .zip(branches.susceptance_magnitude.iter().copied())
286 .zip(branches.shift.iter().copied())
287 .map(|((endpoints, weight), shift)| (endpoints, weight, shift)),
288 )
289 }
290
291 /// The angle difference `theta_from - theta_to` across active branch
292 /// column `branch`, its entry of `Aᵀ theta`, for any bus vector `theta`
293 /// (angles, or a bus dual).
294 ///
295 /// # Panics
296 /// Panics if `branch` is not an active branch column or `theta` is shorter
297 /// than `n_buses`.
298 #[must_use]
299 pub fn calc_angle_difference(&self, theta: &[f64], branch: usize) -> f64 {
300 crate::matrix::calc_dc_angle_difference(
301 theta,
302 (self.branches.from_bus[branch], self.branches.to_bus[branch]),
303 )
304 }
305
306 /// The derivative of branch column `branch`'s flow
307 /// ([`calc_branch_flow`](Self::calc_branch_flow)) at the bus angles
308 /// `theta` with respect to its positive weight
309 /// [`DcBranchParameters::susceptance_magnitude`]:
310 /// `theta_from - theta_to - shift`, in radians.
311 ///
312 /// # Panics
313 /// As [`calc_angle_difference`](Self::calc_angle_difference).
314 #[must_use]
315 pub fn calc_branch_flow_weight_derivative(&self, theta: &[f64], branch: usize) -> f64 {
316 crate::matrix::calc_dc_flow_weight_derivative(
317 theta,
318 (self.branches.from_bus[branch], self.branches.to_bus[branch]),
319 self.branches.shift[branch],
320 )
321 }
322}
323
324pub(crate) fn matrices_from_preparation(instance: &DcOpfPreparation) -> DcOpfMatrices {
325 let n = instance.n_buses;
326 let incidence = instance.calc_bus_branch_incidence();
327 let laplacian = calc_weighted_laplacian(&incidence, &instance.branches.susceptance_magnitude);
328 let grounded_laplacian = ground_at_each(&laplacian, instance.reference_buses.as_ref());
329 let branch_flow_matrix =
330 calc_solver_branch_flow_matrix(&incidence, &instance.branches.susceptance_magnitude);
331
332 DcOpfMatrices {
333 bus_branch_incidence: incidence,
334 laplacian,
335 grounded_laplacian,
336 branch_flow_matrix,
337 generator_bus: instance.calc_generator_bus_incidence(),
338 generator_cost: calc_diagonal(&instance.generators.q),
339 reference_selector: calc_reference_indicator(n, instance.reference_buses.as_ref()),
340 }
341}