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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
14#[non_exhaustive]
15pub enum Units {
16 #[default]
18 PerUnit,
19 Native,
21}
22
23impl std::str::FromStr for Units {
24 type Err = String;
25
26 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62pub struct DcOpfOptions {
63 pub formula: BranchSusceptanceFormula,
65 pub units: Units,
66 pub skip_zero_impedance: bool,
75 #[serde(default)]
81 pub synthesize_unrated_limits: bool,
82 #[serde(default)]
84 pub synthesized_limit_window: SynthesizedLimitWindow,
85 #[serde(default = "default_angle_difference_bounds")]
87 pub angle_difference_bounds: powerio_tx::AngleDifferenceBounds,
88 #[serde(default)]
90 pub hvdc_treatment: HvdcTreatment,
91 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116#[non_exhaustive]
117pub struct DcGeneratorParameters {
118 pub identities: Vec<String>,
120 pub bus_of_gen: Vec<usize>,
122 pub analysis_rows: Vec<usize>,
124 pub source_rows: Vec<Option<usize>>,
127 pub q: Vec<f64>,
129 pub c: Vec<f64>,
131 pub c0: Vec<f64>,
135 pub piecewise_linear: Vec<Option<PiecewiseLinearCost>>,
141 pub pmax: Vec<f64>,
142 pub pmin: Vec<f64>,
143 pub capability_active: Vec<bool>,
145}
146
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct DcBranchParameters {
151 pub identities: Vec<String>,
153 pub from_bus: Vec<usize>,
154 pub to_bus: Vec<usize>,
155 pub susceptance_magnitude: Vec<f64>,
158 pub shift: Vec<f64>,
161 #[serde(with = "crate::opf::nonfinite_vec")]
164 pub f_max: Vec<f64>,
165 #[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 pub analysis_rows: Vec<usize>,
172 pub analysis_sources: Vec<AnalysisBranchSource>,
175 pub skipped_zero_impedance: Vec<usize>,
177 pub thermal_limit_active: Vec<bool>,
179 pub angle_bound_active: Vec<bool>,
181}
182
183#[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 pub has_gen: Vec<bool>,
196}
197
198#[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 pub formula: BranchSusceptanceFormula,
214 pub objective: PreparedObjective,
216 pub skip_zero_impedance: bool,
217 #[serde(default)]
223 pub synthesize_unrated_limits: bool,
224 #[serde(default, skip_serializing_if = "SynthesizedLimitWindow::is_stated")]
228 pub synthesized_limit_window: SynthesizedLimitWindow,
229 pub correct_angle_difference_bounds: bool,
231 #[serde(default)]
235 pub angle_difference_bounds: Option<powerio_tx::AngleDifferenceBounds>,
236 pub bus_ids: Vec<BusId>,
238 pub bus_analysis_rows: Vec<usize>,
240 pub bus_source_rows: Vec<Option<usize>>,
243 pub reference_buses: ReferenceBuses,
244 pub p_d: Vec<f64>,
246 pub g_s: Vec<f64>,
254 pub p_shift: Vec<f64>,
258 #[serde(default)]
263 pub hvdc_treatment: HvdcTreatment,
264 #[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 #[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 #[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 #[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 #[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 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#[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 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 continue;
505 }
506 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 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 _ => 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
640pub(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 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 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}