Skip to main content

powerio_matrix/dcopf/
bundle.rs

1use std::path::{Path, PathBuf};
2
3use powerio_tx::{GenCostPolicyReport, MissingGenCostPolicy};
4
5use crate::Result;
6use crate::SparseMatrix;
7use serde::Serialize;
8
9use super::prep::{DcOpfPreparation, Units};
10use super::{DcOpfAssemblyOptions, matrices_from_preparation};
11
12const DCOPF_SCHEMA: &str = "powerio.dcopf";
13
14/// Cost policy information recorded in a bundle manifest.
15#[derive(Debug, Clone)]
16pub struct DcOpfBundleMetadata {
17    pub cost_policy: MissingGenCostPolicy,
18    pub cost_report: GenCostPolicyReport,
19}
20
21impl Default for DcOpfBundleMetadata {
22    fn default() -> Self {
23        Self {
24            cost_policy: MissingGenCostPolicy::Require,
25            cost_report: GenCostPolicyReport::default(),
26        }
27    }
28}
29
30/// Options that affect bundle output without changing the instance.
31#[derive(Debug, Clone, Default)]
32pub struct DcOpfBundleOptions {
33    /// The assembly choices behind the written arrays.
34    pub assembly: DcOpfAssemblyOptions,
35    pub metadata: DcOpfBundleMetadata,
36}
37
38#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub struct DcOpfOutputs {
41    pub dir: PathBuf,
42    pub files: Vec<PathBuf>,
43}
44
45#[derive(Serialize)]
46struct DcOpfMeta<'a> {
47    schema: &'static str,
48    case_name: &'a str,
49    base_mva: f64,
50    dimensions: DcOpfDimensions,
51    index_base: IndexBaseMeta,
52    branch_susceptance_formula: &'static str,
53    build_options: BuildOptionsMeta,
54    zero_impedance: ZeroImpedanceMeta<'a>,
55    grounding: GroundingMeta<'a>,
56    operators: Vec<OperatorMeta>,
57    units: Units,
58    cost_policy: MissingGenCostPolicy,
59    synthesized_gen_costs: usize,
60    patched_gen_costs: usize,
61    files: Vec<String>,
62    powerio_version: &'static str,
63}
64
65#[derive(Serialize)]
66#[allow(clippy::struct_field_names)]
67struct DcOpfDimensions {
68    n_buses: usize,
69    n_source_branches: usize,
70    n_branch_columns: usize,
71    n_generators: usize,
72    n_reference_buses: usize,
73    n_grounded_buses: usize,
74}
75
76#[derive(Serialize)]
77struct IndexBaseMeta {
78    dense: usize,
79    matrix_market: usize,
80}
81
82#[derive(Serialize)]
83struct BuildOptionsMeta {
84    skip_zero_impedance: bool,
85    synthesize_unrated_limits: bool,
86    hvdc_treatment: powerio_tx::HvdcTreatment,
87    angle_difference_bounds: powerio_tx::AngleDifferenceBounds,
88}
89
90#[derive(Serialize)]
91struct ZeroImpedanceMeta<'a> {
92    skip: bool,
93    rule: &'static str,
94    skipped: ZeroImpedanceSkips<'a>,
95}
96
97#[derive(Serialize)]
98struct ZeroImpedanceSkips<'a> {
99    count: usize,
100    branch_indices: &'a [usize],
101}
102
103#[derive(Serialize)]
104struct GroundingMeta<'a> {
105    reference_buses: &'a [usize],
106    removed_rows_and_columns: &'a [usize],
107    grounded_operator: &'static str,
108    reference_selector: &'static str,
109}
110
111#[derive(Serialize)]
112struct OperatorMeta {
113    name: &'static str,
114    file: &'static str,
115    kind: &'static str,
116    rows: usize,
117    cols: usize,
118    index_space: &'static str,
119    units: &'static str,
120}
121
122/// Write matrix projections for a DC OPF instance.
123///
124/// The writer derives every cost, bound, mapping, and array privately from
125/// the instance's typed network under `options.assembly`, then writes the
126/// bundle directory.
127///
128/// # Errors
129/// A network the selected branch susceptance formula cannot assemble, or a filesystem
130/// refusal from the no-clobber output rules.
131pub fn emit_dcopf_bundle(
132    instance: &powerio_prob::DcOpfInstance,
133    out_dir: impl AsRef<Path>,
134    options: &DcOpfBundleOptions,
135) -> Result<DcOpfOutputs> {
136    emit_prepared(
137        &super::build_dc_opf_preparation(instance, &options.assembly)?,
138        out_dir,
139        options,
140    )
141}
142
143/// The writer body over the private preparation arrays.
144#[allow(clippy::too_many_lines)]
145fn emit_prepared(
146    instance: &DcOpfPreparation,
147    out_dir: impl AsRef<Path>,
148    options: &DcOpfBundleOptions,
149) -> Result<DcOpfOutputs> {
150    let matrices = matrices_from_preparation(instance);
151    let nodal = instance.calc_nodal_generator_data()?;
152    let fixed_withdrawal = instance.calc_fixed_nodal_withdrawal();
153    let flow_offset = instance.calc_branch_flow_offset();
154    // The case name comes from source file content, so it must not steer the
155    // output path. `sanitize_stem` reduces it to one safe component and
156    // disambiguates names that would otherwise sanitize alike, so a batch
157    // export cannot be steered into overwriting an earlier bundle.
158    let bundle_root = out_dir
159        .as_ref()
160        .join(format!("{}_dcopf", crate::sanitize_stem(&instance.name)));
161
162    // Numeric solver bounds: zero constrains flow; infinity is unbounded.
163    let limits: Vec<_> = instance
164        .branches
165        .f_max
166        .iter()
167        .zip(&instance.branches.thermal_limit_active)
168        .map(|(&limit, &active)| if active { limit } else { f64::INFINITY })
169        .collect();
170    let limit_file = "fmax.mtx";
171    let mut inventory: Vec<(&'static str, Vec<u8>)> = Vec::new();
172    put_mat(&mut inventory, "A.mtx", &matrices.bus_branch_incidence)?;
173    put_mat(&mut inventory, "L.mtx", &matrices.laplacian)?;
174    put_mat(
175        &mut inventory,
176        "L_grounded.mtx",
177        &matrices.grounded_laplacian,
178    )?;
179    put_mat(&mut inventory, "BAt.mtx", &matrices.branch_flow_matrix)?;
180    put_mat(&mut inventory, "Cg.mtx", &matrices.generator_bus)?;
181
182    put_vec(
183        &mut inventory,
184        "b.mtx",
185        &instance.branches.susceptance_magnitude,
186    )?;
187    put_vec(&mut inventory, "shift.mtx", &instance.branches.shift)?;
188    put_vec(&mut inventory, "flow_offset.mtx", &flow_offset)?;
189    put_vec(&mut inventory, "p_shift.mtx", &instance.p_shift)?;
190    put_vec(&mut inventory, "fixed_withdrawal.mtx", &fixed_withdrawal)?;
191    put_vec(&mut inventory, "e_r.mtx", &matrices.reference_selector)?;
192    put_vec(&mut inventory, "q.mtx", &nodal.q)?;
193    put_vec(&mut inventory, "c.mtx", &nodal.c)?;
194    put_vec(&mut inventory, "c0.mtx", &nodal.c0)?;
195    put_vec(&mut inventory, "pmax.mtx", &nodal.pmax)?;
196    put_vec(&mut inventory, "pmin.mtx", &nodal.pmin)?;
197    put_vec(&mut inventory, limit_file, &limits)?;
198    put_vec(&mut inventory, "pd.mtx", &instance.p_d)?;
199    put_vec(&mut inventory, "gs.mtx", &instance.g_s)?;
200    put_vec(&mut inventory, "p_hvdc.mtx", &instance.p_hvdc)?;
201    put_vec(
202        &mut inventory,
203        "angle_min.mtx",
204        &instance.branches.angle_min,
205    )?;
206    put_vec(
207        &mut inventory,
208        "angle_max.mtx",
209        &instance.branches.angle_max,
210    )?;
211
212    put_vec(&mut inventory, "q_gen.mtx", &instance.generators.q)?;
213    put_vec(&mut inventory, "c_gen.mtx", &instance.generators.c)?;
214    put_vec(&mut inventory, "c0_gen.mtx", &instance.generators.c0)?;
215    put_vec(&mut inventory, "pmax_gen.mtx", &instance.generators.pmax)?;
216    put_vec(&mut inventory, "pmin_gen.mtx", &instance.generators.pmin)?;
217
218    let power_units = match instance.units {
219        Units::PerUnit => "per_unit_power",
220        Units::Native => "native_power",
221    };
222    let meta = DcOpfMeta {
223        schema: DCOPF_SCHEMA,
224        case_name: &instance.name,
225        base_mva: instance.base_mva,
226        dimensions: DcOpfDimensions {
227            n_buses: instance.n_buses,
228            n_source_branches: instance.n_source_branches,
229            n_branch_columns: instance.n_branches(),
230            n_generators: instance.n_generators(),
231            n_reference_buses: instance.reference_buses.len(),
232            n_grounded_buses: instance.n_buses - instance.reference_buses.len(),
233        },
234        index_base: IndexBaseMeta {
235            dense: 0,
236            matrix_market: 1,
237        },
238        branch_susceptance_formula: instance.formula.formula_name(),
239        build_options: BuildOptionsMeta {
240            skip_zero_impedance: instance.skip_zero_impedance,
241            synthesize_unrated_limits: instance.synthesize_unrated_limits,
242            hvdc_treatment: instance.hvdc_treatment,
243            angle_difference_bounds: instance.angle_difference_bounds.unwrap_or(
244                powerio_tx::AngleDifferenceBounds::from_correct_flag(
245                    instance.correct_angle_difference_bounds,
246                ),
247            ),
248        },
249        zero_impedance: ZeroImpedanceMeta {
250            skip: instance.skip_zero_impedance,
251            rule: "Reactance",
252            skipped: ZeroImpedanceSkips {
253                count: instance.branches.skipped_zero_impedance.len(),
254                branch_indices: &instance.branches.skipped_zero_impedance,
255            },
256        },
257        grounding: GroundingMeta {
258            reference_buses: instance.reference_buses.as_ref(),
259            removed_rows_and_columns: instance.reference_buses.as_ref(),
260            grounded_operator: "L_grounded",
261            reference_selector: "e_r",
262        },
263        operators: operator_meta(
264            instance.n_buses,
265            instance.n_branches(),
266            instance.reference_buses.len(),
267            instance.n_generators(),
268            power_units,
269            limit_file,
270        ),
271        units: instance.units,
272        cost_policy: options.metadata.cost_policy,
273        synthesized_gen_costs: options.metadata.cost_report.synthesized,
274        patched_gen_costs: options.metadata.cost_report.patched,
275        // The manifest lists the operator files it describes; it does not
276        // list itself, matching the manifest shape consumers already read.
277        files: inventory
278            .iter()
279            .map(|(name, _)| (*name).to_string())
280            .collect(),
281        powerio_version: powerio_tx::VERSION,
282    };
283    let json = serde_json::to_string_pretty(&meta)
284        .map_err(|error| crate::Error::Mtx(error.to_string()))?;
285    inventory.push(("dcopf_meta.json", json.into_bytes()));
286
287    // The complete bundle commits at once through the no-replace destination:
288    // an existing bundle directory is refused rather than replaced.
289    let artifacts = inventory
290        .into_iter()
291        .map(|(name, bytes)| {
292            Ok(powerio_core::MemoryArtifact::new(
293                powerio_core::ArtifactPath::new(name)?,
294                bytes,
295            ))
296        })
297        .collect::<std::result::Result<Vec<_>, powerio_core::Error>>()
298        .map_err(crate::Error::from)?;
299    let committed = powerio_core::Destination::path(&bundle_root)
300        .__commit_artifacts(
301            true,
302            powerio_core::Fidelity::Canonical,
303            artifacts,
304            Vec::new(),
305        )
306        .map_err(crate::Error::from)?;
307    let powerio_core::EmittedOutput::Path { root, artifacts } = committed.into_output() else {
308        unreachable!("a path destination returns a path output")
309    };
310
311    Ok(DcOpfOutputs {
312        dir: root,
313        files: artifacts,
314    })
315}
316
317#[allow(clippy::too_many_lines)]
318fn operator_meta(
319    n: usize,
320    m: usize,
321    n_ref: usize,
322    n_gen: usize,
323    power_units: &'static str,
324    limit_file: &'static str,
325) -> Vec<OperatorMeta> {
326    let n_grounded = n - n_ref;
327    vec![
328        op(
329            "signed_incidence",
330            "A.mtx",
331            "matrix",
332            n,
333            m,
334            "bus_by_branch",
335            "unitless",
336        ),
337        op(
338            "branch_susceptance",
339            "b.mtx",
340            "vector",
341            m,
342            1,
343            "branch",
344            power_units,
345        ),
346        op(
347            "branch_phase_shift",
348            "shift.mtx",
349            "vector",
350            m,
351            1,
352            "branch",
353            "radian",
354        ),
355        op(
356            "branch_flow_offset",
357            "flow_offset.mtx",
358            "vector",
359            m,
360            1,
361            "branch",
362            power_units,
363        ),
364        op(
365            "weighted_laplacian",
366            "L.mtx",
367            "matrix",
368            n,
369            n,
370            "bus_by_bus",
371            power_units,
372        ),
373        op(
374            "grounded_laplacian",
375            "L_grounded.mtx",
376            "matrix",
377            n_grounded,
378            n_grounded,
379            "grounded_bus_by_grounded_bus",
380            power_units,
381        ),
382        op(
383            "branch_flow_matrix",
384            "BAt.mtx",
385            "matrix",
386            m,
387            n,
388            "branch_by_bus",
389            power_units,
390        ),
391        op(
392            "generator_to_bus",
393            "Cg.mtx",
394            "matrix",
395            n,
396            n_gen,
397            "bus_by_generator",
398            "unitless",
399        ),
400        op(
401            "phase_shift_injection",
402            "p_shift.mtx",
403            "vector",
404            n,
405            1,
406            "bus",
407            power_units,
408        ),
409        op(
410            "fixed_nodal_withdrawal",
411            "fixed_withdrawal.mtx",
412            "vector",
413            n,
414            1,
415            "bus",
416            power_units,
417        ),
418        op(
419            "reference_selector",
420            "e_r.mtx",
421            "vector",
422            n,
423            1,
424            "bus",
425            "indicator",
426        ),
427        op(
428            "bus_cost_quadratic",
429            "q.mtx",
430            "vector",
431            n,
432            1,
433            "bus",
434            "selected_cost_units",
435        ),
436        op(
437            "bus_cost_linear",
438            "c.mtx",
439            "vector",
440            n,
441            1,
442            "bus",
443            "selected_cost_units",
444        ),
445        op(
446            "bus_cost_constant",
447            "c0.mtx",
448            "vector",
449            n,
450            1,
451            "bus",
452            "selected_cost_units",
453        ),
454        op(
455            "bus_generation_upper",
456            "pmax.mtx",
457            "vector",
458            n,
459            1,
460            "bus",
461            power_units,
462        ),
463        op(
464            "bus_generation_lower",
465            "pmin.mtx",
466            "vector",
467            n,
468            1,
469            "bus",
470            power_units,
471        ),
472        op(
473            "branch_flow_limit",
474            limit_file,
475            "vector",
476            m,
477            1,
478            "branch",
479            power_units,
480        ),
481        op("bus_load", "pd.mtx", "vector", n, 1, "bus", power_units),
482        op(
483            "bus_shunt_conductance",
484            "gs.mtx",
485            "vector",
486            n,
487            1,
488            "bus",
489            power_units,
490        ),
491        op(
492            "bus_hvdc_injection",
493            "p_hvdc.mtx",
494            "vector",
495            n,
496            1,
497            "bus",
498            power_units,
499        ),
500        op(
501            "branch_angle_minimum",
502            "angle_min.mtx",
503            "vector",
504            m,
505            1,
506            "branch",
507            "radian",
508        ),
509        op(
510            "branch_angle_maximum",
511            "angle_max.mtx",
512            "vector",
513            m,
514            1,
515            "branch",
516            "radian",
517        ),
518        op(
519            "generator_cost_quadratic",
520            "q_gen.mtx",
521            "vector",
522            n_gen,
523            1,
524            "generator",
525            "selected_cost_units",
526        ),
527        op(
528            "generator_cost_linear",
529            "c_gen.mtx",
530            "vector",
531            n_gen,
532            1,
533            "generator",
534            "selected_cost_units",
535        ),
536        op(
537            "generator_cost_constant",
538            "c0_gen.mtx",
539            "vector",
540            n_gen,
541            1,
542            "generator",
543            "selected_cost_units",
544        ),
545        op(
546            "generator_upper",
547            "pmax_gen.mtx",
548            "vector",
549            n_gen,
550            1,
551            "generator",
552            power_units,
553        ),
554        op(
555            "generator_lower",
556            "pmin_gen.mtx",
557            "vector",
558            n_gen,
559            1,
560            "generator",
561            power_units,
562        ),
563    ]
564}
565
566fn op(
567    name: &'static str,
568    file: &'static str,
569    kind: &'static str,
570    rows: usize,
571    cols: usize,
572    index_space: &'static str,
573    units: &'static str,
574) -> OperatorMeta {
575    OperatorMeta {
576        name,
577        file,
578        kind,
579        rows,
580        cols,
581        index_space,
582        units,
583    }
584}
585
586fn put_mat(
587    inventory: &mut Vec<(&'static str, Vec<u8>)>,
588    name: &'static str,
589    matrix: &SparseMatrix,
590) -> Result<()> {
591    inventory.push((name, crate::io::to_mtx_bytes(matrix)?));
592    Ok(())
593}
594
595fn put_vec(
596    inventory: &mut Vec<(&'static str, Vec<u8>)>,
597    name: &'static str,
598    values: &[f64],
599) -> Result<()> {
600    inventory.push((name, crate::io::to_vector_mtx_bytes(values)?));
601    Ok(())
602}