Skip to main content

powerio_matrix/
lib.rs

1//! Sparse matrix and graph projections from PowerIO networks.
2//!
3//! Outputs include signed incidence, weighted bus Laplacian, MATPOWER Bp/Bpp,
4//! Y bus, PTDF, LODF, adjacency, and LACPF views. Calculations take the
5//! dense [`IndexedNetwork`] view of a [`BalancedNetwork`]. Parsing and emitting
6//! belong to the top level `powerio` facade; this crate owns derived matrix and
7//! graph calculations.
8//!
9//! ```
10//! use powerio_core::Source;
11//! use powerio_matrix::{BuildOptions, IndexedNetwork, calc_bprime_matrix};
12//! use powerio_tx::parse;
13//!
14//! # let case = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/data/case14.m");
15//! let net = parse(Source::open(case)?)?.into_value();
16//! let g = IndexedNetwork::new(&net);           // dense [0, n) analysis view
17//! let bprime = calc_bprime_matrix(&g, &BuildOptions::default())?;
18//! assert_eq!(bprime.rows(), g.n());            // Bp is n×n
19//! # Ok::<(), Box<dyn std::error::Error>>(())
20//! ```
21//!
22//! # Conventions
23//!
24//! Public DC operators follow PowerModels: an inductive branch has negative
25//! `b`. Their branch by bus incidence matrix `A_pm` gives
26//! `B = A_pmᵀ diag(b) A_pm`, with nonpositive diagonals and nonnegative
27//! off-diagonals. Solver preparation retains its bus by branch factor
28//! `A_s = A_pmᵀ` and uses `w = -b`, so the sparse factor is the positive
29//! M-matrix `L = A_s diag(w) A_sᵀ = -B`. Source bus IDs remain on the model;
30//! [`IndexedNetwork`] maps them to dense indices in `[0, n)`.
31//! `tap == 0` means `tap = 1`. `calc_bprime_matrix` and
32//! `calc_bdoubleprime_matrix` follow MATPOWER `makeB`; Y_bus keeps tap
33//! magnitudes and phase shifts. Branch
34//! terminal admittance is stored per unit. The default public DC formula is
35//! `b = -x/(r² + x²)`. [`BranchSusceptanceFormula::TapAdjustedReactance`] uses
36//! `b = -1/(x·τ)`; both carry phase shift injection.
37//! [`BranchSusceptanceFormula::TapAdjustedSeriesSusceptance`] divides the series
38//! coefficient by the tap; [`BranchSusceptanceFormula::SeriesSusceptanceNoPhaseShift`]
39//! ignores taps and shifts to match PowerModels DCP. The full reference is in
40//! [the matrix guide](https://eigenergy.github.io/powerio/guide/matrices.html).
41
42// Re-export the balanced model types used by matrix signatures. Parsing,
43// emitting, conversion, and display operations stay on their owning crate and
44// the top level facade. `Error` and `Result` are this crate's own: the variants
45// below are raised here and nowhere in the hub.
46pub use powerio_tx::{
47    AngleDifferenceBounds, BalancedNetwork, Branch, Bus, BusId, BusType, ConnectivityReport,
48    Extras, GenCost, Generator, Hvdc, IndexCore, IndexedNetwork, Load,
49    POWER_MODELS_ANGLE_BOUND_PAD, Shunt, SourceFormat, Storage,
50};
51
52// Internal compatibility paths used throughout the matrix implementation.
53pub(crate) use powerio_tx::{indexed, network};
54
55pub mod diagnostics;
56pub mod error;
57pub use error::{ElementCounts, Error, PiecewiseCostInvalidity, Result, ScenarioMismatch};
58
59/// Compressed sparse row matrix used by the projection calculations.
60pub type SparseMatrix = sprs::CsMat<f64>;
61
62mod ac_jacobian;
63mod acopf;
64mod mcopf;
65pub use mcopf::{
66    BoundedLoadLawPolicy, McAcOpfAssemblyOptions, McAcOpfPreparation, McOpfAngleLimit, McOpfBranch,
67    McOpfCoil, McOpfComplexRow, McOpfDevice, McOpfDeviceKind, McOpfDroop, McOpfLoadLaw,
68    McOpfLoadLawProjection, McOpfShunt, McOpfTerminal, McOpfTransformer, McOpfTransformerCoil,
69    McOpfTransformerPort, McOpfVoltageLimit, build_mc_ac_opf_preparation,
70};
71mod dc_operators;
72mod dcopf;
73pub mod io;
74mod lindist3flow;
75mod lindist3flow_conic;
76mod lindist3flow_devices;
77mod lindist3flow_pf;
78mod lindist3flow_standard;
79pub mod matrix;
80mod opf;
81pub mod pipeline;
82mod stated_state;
83pub mod synth;
84
85pub use ac_jacobian::{PowerFlowJacobian, VoltageCoordinates, calc_power_flow_jacobian};
86pub use acopf::{
87    AcBranchData, AcBusData, AcGeneratorData, AcOpfAssemblyOptions, AcOpfPreparation,
88    AcPfAssemblyOptions, AcPfBusData, AcPfGeneratorData, AcPfPreparation, AcStorageData,
89    NodalAcGeneratorData, PreparedAcBusSpecification, build_ac_opf_preparation,
90    build_ac_pf_preparation,
91};
92pub use dc_operators::{DcOperatorOptions, DcOperators, ReferenceConstrainedSystem};
93pub use dcopf::{
94    DcBranchParameters, DcGeneratorParameters, DcOpfAssemblyOptions, DcOpfBundleMetadata,
95    DcOpfBundleOptions, DcOpfMatrices, DcOpfOutputs, DcOpfPreparation, NodalGeneratorParameters,
96    Units, build_dc_opf_preparation, calc_dc_opf_matrices, emit_dcopf_bundle,
97};
98pub use lindist3flow::{
99    AffineScalarCoefficients, ConnectionPowerMap, CrossVoltageCoefficients, LinDist3FlowLineData,
100    LinDist3FlowNetworkData, LinDist3FlowNodeData, LineDropCoefficients,
101    build_lindist3flow_network_data, connection_power_map, cross_voltage_coefficients,
102    evaluate_affine, evaluate_cross_voltage, line_drop_coefficients, winding_voltage_coefficients,
103};
104pub use lindist3flow_conic::{
105    LinDist3FlowCone, LinDist3FlowConeOrigin, LinDist3FlowConicProblem,
106    LinDist3FlowDecisionVariable, LinDist3FlowEquality, LinDist3FlowEqualityOrigin,
107    LinDist3FlowLinearExpression, LinDist3FlowLinearTerm, LinDist3FlowVariableData,
108    build_lindist3flow_conic_problem, lindist3flow_values_from_primal,
109};
110pub use lindist3flow_devices::{
111    LinDist3FlowAffineExpression, LinDist3FlowBalanceEquation, LinDist3FlowBalanceRow,
112    LinDist3FlowBalanceTerm, LinDist3FlowComplexAffinePower, LinDist3FlowDeviceData,
113    LinDist3FlowDispatchChannel, LinDist3FlowGeneratorData, LinDist3FlowLoadData,
114    LinDist3FlowPreparation, LinDist3FlowShuntData, LinDist3FlowSourceData, LinDist3FlowVariable,
115    LinDist3FlowVoltageTerm, build_lindist3flow_device_data, build_lindist3flow_preparation,
116    lindist3flow_connection_incidence,
117};
118pub use lindist3flow_pf::{
119    build_lindist3flow_pf_conic_problem, build_lindist3flow_pf_standard_form,
120    build_lindist3flow_pf_standard_form_with_options, evaluate_lindist3flow_pf_limits,
121    lindist3flow_pf_values_from_primal, lindist3flow_pf_values_from_standard_primal,
122};
123pub use lindist3flow_standard::{
124    LinDist3FlowScaling, LinDist3FlowStandardCone, LinDist3FlowStandardForm,
125    LinDist3FlowStandardFormOptions, LinDist3FlowStandardRowOrigin,
126    build_lindist3flow_standard_form, build_lindist3flow_standard_form_with_options,
127    lindist3flow_values_from_standard_primal,
128};
129pub use opf::{AnalysisBranchSource, PiecewiseLinearCost, PreparedObjective};
130
131pub use matrix::multiconductor::{
132    AugmentedSystem, DistNode, MulticonductorAdmittance, MulticonductorNodeIndex, NodeRef,
133    calc_multiconductor_admittance_matrix,
134};
135pub use matrix::{
136    BranchSusceptanceFormula, BuildOptions, GroundedIndexMap, IslandPtdf, MatrixStats, Scheme,
137    SensitivityMatrices, SensitivityMatrixMetadata, SensitivityMetadata, SensitivityOptions,
138    SensitivitySolver, SensitivitySolverPath, ZeroImpedanceRule, ZeroImpedanceSkips,
139    calc_adjacency_matrix, calc_admittance_matrix, calc_bdoubleprime_matrix, calc_bprime_matrix,
140    calc_diagonal, calc_lacpf_matrix, calc_lodf, calc_lodf_columns, calc_ptdf, calc_ptdf_by_island,
141    calc_ptdf_columns, calc_ptdf_lodf, calc_ptdf_lodf_with_options, calc_ptdf_rows,
142    calc_reference_indicator, calc_susceptance_diagonal, calc_unit_vector, calc_weighted_laplacian,
143    calc_zero_impedance_skips, check_sddm, ground_at, ground_at_each,
144};
145pub use pipeline::{
146    MatrixKind, Pipeline, PipelineOutputs, RhsKind, calc_matrix, calc_matrix_stats_for_kind,
147    calc_zero_impedance_skips_for_kind, sanitize_stem, select_zero_impedance_rule_for_kind,
148};
149pub use stated_state::{
150    ClosureInjection, LccReactivePower, StatedBranchFlows, StatedBusFlags, StatedBusMismatch,
151    StatedIslandMismatch, StatedStateMismatch, StatedStateOptions, calc_stated_branch_flows,
152    calc_stated_state_mismatch,
153};
154
155#[cfg(feature = "gridfm")]
156pub use io::gridfm::{
157    GridfmDataset, GridfmOptions, GridfmOutputs, GridfmSnapshot, GridfmTables, build_gridfm_batch,
158    build_gridfm_dataset, emit_gridfm_batch, emit_gridfm_dataset, number_snapshots,
159    to_gridfm_record_batches, to_gridfm_record_batches_single,
160};