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, MC_OPF_DROOP_SMOOTHING, McAcOpfAssemblyOptions, McAcOpfPreparation,
67    McOpfAngleLimit, McOpfBranch, McOpfCoil, McOpfComplexRow, McOpfDevice, McOpfDeviceKind,
68    McOpfDroop, McOpfDroopHinge, McOpfDroopTerms, McOpfDroopValue, McOpfLoadLaw,
69    McOpfLoadLawProjection, McOpfShunt, McOpfTerminal, McOpfTransformer, McOpfTransformerCoil,
70    McOpfTransformerPort, McOpfVoltageLimit, build_mc_ac_opf_preparation,
71};
72mod dc_operators;
73mod dcopf;
74pub mod io;
75mod lindist3flow;
76mod lindist3flow_conic;
77mod lindist3flow_devices;
78mod lindist3flow_pf;
79mod lindist3flow_standard;
80pub mod matrix;
81mod opf;
82pub mod pipeline;
83mod stated_state;
84pub mod synth;
85
86pub use ac_jacobian::{
87    BusPowerInjection, PowerFlowJacobian, VoltageCoordinates, calc_bus_power_injection,
88    calc_power_flow_jacobian,
89};
90pub use acopf::{
91    AcBranchData, AcBranchFlows, AcBusData, AcGeneratorData, AcOpfAssemblyOptions,
92    AcOpfPreparation, AcPfAssemblyOptions, AcPfBusData, AcPfGeneratorData, AcPfPreparation,
93    AcStorageData, NodalAcGeneratorData, PreparedAcBusSpecification, build_ac_opf_preparation,
94    build_ac_pf_preparation, calc_prepared_bus_specifications,
95};
96pub use dc_operators::{
97    DcOperatorOptions, DcOperators, ReferenceConstrainedSystem, calc_reference_constrained_system,
98};
99pub use dcopf::{
100    DcBranchParameters, DcGeneratorParameters, DcOpfAssemblyOptions, DcOpfBundleMetadata,
101    DcOpfBundleOptions, DcOpfMatrices, DcOpfOutputs, DcOpfPreparation, NodalGeneratorParameters,
102    SynthesizedLimitWindow, Units, build_dc_opf_preparation, calc_bus_hosts, calc_bus_totals,
103    calc_dc_opf_matrices, emit_dcopf_bundle,
104};
105pub use lindist3flow::{
106    AffineScalarCoefficients, ConnectionPowerMap, CrossVoltageCoefficients, LinDist3FlowLineData,
107    LinDist3FlowNetworkData, LinDist3FlowNodeData, LineDropCoefficients,
108    build_lindist3flow_network_data, connection_power_map, cross_voltage_coefficients,
109    evaluate_affine, evaluate_cross_voltage, line_drop_coefficients, winding_voltage_coefficients,
110};
111pub use lindist3flow_conic::{
112    LinDist3FlowCone, LinDist3FlowConeOrigin, LinDist3FlowConicProblem,
113    LinDist3FlowDecisionVariable, LinDist3FlowEquality, LinDist3FlowEqualityOrigin,
114    LinDist3FlowLinearExpression, LinDist3FlowLinearTerm, LinDist3FlowVariableData,
115    build_lindist3flow_conic_problem, lindist3flow_values_from_primal,
116};
117pub use lindist3flow_devices::{
118    LinDist3FlowAffineExpression, LinDist3FlowBalanceEquation, LinDist3FlowBalanceRow,
119    LinDist3FlowBalanceTerm, LinDist3FlowComplexAffinePower, LinDist3FlowDeviceData,
120    LinDist3FlowDispatchChannel, LinDist3FlowGeneratorData, LinDist3FlowLoadData,
121    LinDist3FlowPreparation, LinDist3FlowShuntData, LinDist3FlowSourceData, LinDist3FlowVariable,
122    LinDist3FlowVoltageTerm, build_lindist3flow_device_data, build_lindist3flow_preparation,
123    lindist3flow_connection_incidence,
124};
125pub use lindist3flow_pf::{
126    build_lindist3flow_pf_conic_problem, build_lindist3flow_pf_standard_form,
127    build_lindist3flow_pf_standard_form_with_options, evaluate_lindist3flow_pf_limits,
128    lindist3flow_pf_values_from_primal, lindist3flow_pf_values_from_standard_primal,
129};
130pub use lindist3flow_standard::{
131    LinDist3FlowScaling, LinDist3FlowStandardCone, LinDist3FlowStandardForm,
132    LinDist3FlowStandardFormOptions, LinDist3FlowStandardRowOrigin,
133    build_lindist3flow_standard_form, build_lindist3flow_standard_form_with_options,
134    lindist3flow_values_from_standard_primal,
135};
136pub use opf::{AnalysisBranchSource, PiecewiseLinearCost, PreparedObjective};
137
138pub use matrix::multiconductor::{
139    AugmentedSystem, DistNode, GroundedNeutral, MulticonductorAdmittance, MulticonductorNodeIndex,
140    NetworkPrimitives, NodeRef, PassiveFamily, PassivePrimitive, TransformerLeakageBase,
141    TransformerPrimitive, assemble_multiconductor_admittance, calc_capacitor_primitive_admittance,
142    calc_line_primitive_admittance, calc_multiconductor_admittance_matrix, calc_passive_primitives,
143    calc_shunt_primitive_admittance, calc_transformer_leakage_impedances,
144    calc_transformer_primitive_admittance, calc_transformer_winding_admittance,
145    scatter_primitive_admittance,
146};
147pub use matrix::{
148    BranchSusceptanceFormula, BuildOptions, GroundedIndexMap, GroundedLaplacianFactor, Grounding,
149    IslandPtdf, MatrixStats, Scheme, SensitivityMatrices, SensitivityMatrixMetadata,
150    SensitivityMetadata, SensitivityOptions, SensitivitySolver, SensitivitySolverPath,
151    ZeroImpedanceRule, ZeroImpedanceSkips, calc_adjacency_matrix, calc_admittance_matrix,
152    calc_bdoubleprime_matrix, calc_bprime_matrix, calc_diagonal, calc_edge_flows,
153    calc_edge_laplacian_product, calc_lacpf_matrix, calc_lodf, calc_lodf_columns, calc_ptdf,
154    calc_ptdf_by_island, calc_ptdf_columns, calc_ptdf_lodf, calc_ptdf_lodf_with_options,
155    calc_ptdf_rows, calc_reference_indicator, calc_solver_branch_flow_matrix,
156    calc_susceptance_diagonal, calc_unit_vector, calc_weighted_laplacian,
157    calc_zero_impedance_skips, check_sddm, ground_at, ground_at_each,
158};
159pub use pipeline::{
160    MatrixKind, Pipeline, PipelineOutputs, RhsKind, calc_matrix, calc_matrix_stats_for_kind,
161    calc_zero_impedance_skips_for_kind, sanitize_stem, select_zero_impedance_rule_for_kind,
162};
163pub use stated_state::{
164    ClosureInjection, LccReactivePower, StatedBranchFlows, StatedBusFlags, StatedBusMismatch,
165    StatedIslandMismatch, StatedStateMismatch, StatedStateOptions, calc_stated_branch_flows,
166    calc_stated_state_mismatch,
167};
168
169#[cfg(feature = "gridfm")]
170pub use io::gridfm::{
171    GridfmDataset, GridfmOptions, GridfmOutputs, GridfmSnapshot, GridfmTables, build_gridfm_batch,
172    build_gridfm_dataset, emit_gridfm_batch, emit_gridfm_dataset, number_snapshots,
173    to_gridfm_record_batches, to_gridfm_record_batches_single,
174};