Public API Reference
PowerNetworkMatrices.ABA_Matrix — Type
Structure containing the ABA matrix and related power system analysis data.
The ABA matrix represents the bus susceptance matrix computed as A^T * B * A, where A is the incidence matrix and B is the branch susceptance matrix. This matrix is fundamental for DC power flow analysis, sensitivity calculations, and linear power system studies.
Fields
data::SparseArrays.SparseMatrixCSC{Float64, Int}: The ABA matrix data representing the bus susceptance matrix. This square matrix has dimensions equal to the number of buses excluding reference busesaxes::Ax: Tuple containing identical bus number vectors for rows and columns, excluding reference buseslookup::L <: NTuple{2, Dict}: Tuple of identical dictionaries providing fast lookup from bus numbers to matrix indicessubnetwork_axes::Dict{Int, Ax}: Mapping from reference bus numbers to their corresponding subnetwork axesref_bus_position::Vector{Int}: Vector containing the original indices of reference buses before matrix reductionK::F <: Union{Nothing, KLU.KLUFactorization{Float64, Int}}: Optional KLU factorization object for efficient linear system solving. Nothing if unfactorizednetwork_reduction_data::NetworkReductionData: Container for network reduction information applied during matrix construction
Mathematical Properties
- Matrix Form: ABA = A^T * B * A (bus susceptance matrix)
- Dimensions: (nbuses - nref) × (nbuses - nref)
- Symmetry: Positive definite symmetric matrix (for connected networks)
- Sparsity: Inherits sparsity pattern from network topology
Notes
- Reference buses are excluded from the matrix to ensure invertibility
- Factorization enables efficient solving of linear systems Ax = b
- Used primarily for DC power flow analysis and power system sensitivity studies
- Supports various network reduction techniques for computational efficiency
PowerNetworkMatrices.ABA_Matrix — Method
ABA_Matrix(sys; factorize, network_reductions, kwargs...)
ABA_Matrix(sys::PSY.System; factorize::Bool = false, network_reductions::Vector{NetworkReduction} = NetworkReduction[], kwargs...)Construct an ABA_Matrix from a PowerSystems.System by computing A^T * B * A where A is the incidence matrix and B is the branch susceptance matrix. The resulting matrix is fundamental for DC power flow analysis and power system sensitivity studies.
Arguments
sys::PSY.System: The power system from which to construct the ABA matrix
Keyword Arguments
factorize::Bool = false: Whether to perform KLU factorization during construction for efficient linear system solvingnetwork_reductions::Vector{NetworkReduction} = NetworkReduction[]: Vector of network reduction algorithms to apply before matrix constructioninclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittances in the network modelsubnetwork_algorithm=iterative_union_find: Algorithm used for identifying electrical islands and connected components- Additional keyword arguments are passed to the underlying
Ybusconstructor
Returns
ABA_Matrix: The constructed ABA matrix structure containing:- Bus susceptance matrix data (excluding reference buses)
- Network topology information and reference bus positions
- Optional KLU factorization for efficient solving
Mathematical Process
- Ybus Construction: Creates admittance matrix from system data
- Incidence Matrix: Computes bus-branch incidence matrix A
- BA Matrix: Forms branch susceptance weighted incidence matrix
- ABA Computation: Calculates A^T * B * A (bus susceptance matrix)
- Reference Bus Removal: Excludes reference buses for invertibility
- Optional Factorization: Performs KLU decomposition if requested
Notes
- Reference buses are automatically detected and excluded from the final matrix
- Factorization significantly improves performance for repeated linear system solves
- Network reductions can dramatically improve computational efficiency for large systems
- The resulting matrix supports PTDF, LODF, and other power system analysis calculations
PowerNetworkMatrices.ABA_Matrix — Method
ABA_Matrix(ybus; factorize)
ABA_Matrix(ybus::Ybus; factorize::Bool = false)Construct an ABA_Matrix from a Ybus matrix by computing A^T * B * A where A is the incidence matrix and B is the branch susceptance matrix. The resulting matrix is fundamental for DC power flow analysis and power system sensitivity studies. Network reductions can be passed via the computed Ybus matrix.
Arguments
ybus::Ybus: The power system Ybus matrix from which to construct the ABA matrix
Keyword Arguments
factorize::Bool = false: Whether to perform KLU factorization during construction for efficient linear system solving
Returns
ABA_Matrix: The constructed ABA matrix structure containing:- Bus susceptance matrix data (excluding reference buses)
- Network topology information and reference bus positions
- Optional KLU factorization for efficient solving
Mathematical Process
- Incidence Matrix: Computes bus-branch incidence matrix A (from Ybus matrix)
- BA Matrix: Forms branch susceptance weighted incidence matrix
- ABA Computation: Calculates A^T * B * A (bus susceptance matrix)
- Reference Bus Removal: Excludes reference buses for invertibility
- Optional Factorization: Performs KLU decomposition if requested
Notes
- Reference buses are automatically detected and excluded from the final matrix
- Factorization significantly improves performance for repeated linear system solves
- Network reductions can dramatically improve computational efficiency for large systems
- The resulting matrix supports PTDF, LODF, and other power system analysis calculations
PowerNetworkMatrices.AdjacencyMatrix — Type
AdjacencyMatrix{Ax, L} <: PowerNetworkMatrix{Int8}An N × N adjacency matrix representing the connectivity structure of a power system with N buses. This matrix describes the directed connectivity between buses, where non-zero entries indicate electrical connections through transmission lines, transformers, or other network elements.
The matrix is indexed using bus numbers, which do not need to be sequential. Each element A[i,j] is non-zero if there is a direct electrical connection between bus i and bus j. Diagonal elements are typically zero since self-loops are not meaningful in power network topology.
Fields
data::SparseArrays.SparseMatrixCSC{Int8, Int}: The sparse adjacency matrix storing connectivity information as Int8 values (zero for no connection, non-zero for connection)axes::Ax: Tuple containing the axis labels for both dimensions. The first element contains bus identifiers for rows, the second contains bus identifiers for columns (typically identical)lookup::L: Tuple of dictionaries providing bidirectional mapping between bus numbers and their corresponding matrix indicessubnetwork_axes::Dict{Int, Ax}: Dictionary mapping subnetwork identifiers to their corresponding axis information, used for handling electrical islandsnetwork_reduction_data::NetworkReductionData: Container for network reduction algorithms and their associated data, enabling efficient matrix operations on reduced networks
Examples
# Create from a PowerSystems.System
sys = System("case5.m")
adj = AdjacencyMatrix(sys)
# Create from a Ybus matrix
ybus = Ybus(sys)
adj = AdjacencyMatrix(ybus)
# Check connectivity
is_connected = validate_connectivity(adj)
subnetworks = find_subnetworks(adj)See also: Ybus, IncidenceMatrix, PowerNetworkMatrix
PowerNetworkMatrices.AdjacencyMatrix — Method
AdjacencyMatrix(sys; kwargs...)
AdjacencyMatrix(sys::PSY.System; kwargs...)Construct an AdjacencyMatrix from a PowerSystems.System.
Arguments
sys::PSY.System: The power system from which to construct the adjacency matrix
Keyword arguments
network_reductions::Vector{NetworkReduction}=[]: Network reduction algorithms to applyinclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittancessubnetwork_algorithm=iterative_union_find: Algorithm for finding electrical islands
Returns
AdjacencyMatrix: An N x N adjacency matrix indexed with bus numbers showing connectivity
PowerNetworkMatrices.AdjacencyMatrix — Method
AdjacencyMatrix(ybus)
AdjacencyMatrix(ybus::Ybus)Construct an AdjacencyMatrix from a Ybus matrix.
Arguments
ybus::Ybus: The Ybus matrix from which to construct the adjacency matrix
Returns
AdjacencyMatrix: The constructed adjacency matrix showing bus connectivity
PowerNetworkMatrices.ArcAdmittanceMatrix — Type
Arc admittance matrix
Arguments
data::SparseArrays.SparseMatrixCSC{YBUS_ELTYPE, Int}: The arc admittance matrix in the from-to directionaxes<:NTuple{2, Dict}: Tuple containing two vectors (the first one showing the arc tuples, the second showing the buses numbers).lookup<:NTuple{2, Dict}: Tuple containing two dictionaries, the first mapping the arc tuples and the second the buses with their enumerated indexes.network_reduction::NetworkReduction: Structure containing the details of the network reduction applied when computing the matrixdirection::Symbol: Direction of admittance (:FromTo or :ToFrom)
PowerNetworkMatrices.ArcModification — Type
ArcModificationA susceptance change on a single aggregated arc, with optional Ybus Pi-model deltas. Full outage: delta_b = -b_arc. Single circuit on double-circuit: delta_b = -b_circuit.
Fields
arc_index::Int: Index of the modified arc in the network matrix.delta_b::Float64: Change in susceptance (negative for an outage or reduction).delta_y11::ComplexF32: Change in Pi-model self-admittance at the from bus.delta_y12::ComplexF32: Change in Pi-model mutual admittance (from -> to).delta_y21::ComplexF32: Change in Pi-model mutual admittance (to -> from).delta_y22::ComplexF32: Change in Pi-model self-admittance at the to bus.
PowerNetworkMatrices.ArcModification — Method
ArcModification(arc_index, delta_b)
Backward-compatible constructor that sets all Pi-model ΔY fields to zero.
PowerNetworkMatrices.BA_Matrix — Type
Structure containing the BA matrix and related network topology data.
The BA matrix represents the branch-bus incidence matrix weighted by branch susceptances, computed as the product of the incidence matrix A and the susceptance matrix B.
Fields
data::SparseArrays.SparseMatrixCSC{Float64, Int}: The transposed BA matrix data. Each row corresponds to a bus and each column corresponds to a branch, with values representing weighted branch susceptancesaxes::Ax: Tuple containing two vectors: bus numbers (rows) and branch identifiers (columns)lookup::L <: NTuple{2, Dict}: Tuple of dictionaries providing fast lookup from bus/branch names to matrix indicessubnetwork_axes::Dict{Int, Ax}: Mapping from reference bus numbers to their corresponding subnetwork axesnetwork_reduction_data::NetworkReductionData: Container for network reduction information applied during matrix construction
Notes
- The matrix is stored in transposed form for computational efficiency
- Reference buses are identified through
subnetwork_axeskeys - Supports various network reduction techniques for computational efficiency
PowerNetworkMatrices.BA_Matrix — Method
BA_Matrix(sys; network_reductions, kwargs...)
BA_Matrix(sys::PSY.System; network_reductions::Vector{NetworkReduction} = Vector{NetworkReduction}(), kwargs...)Construct a BA_Matrix from a PowerSystems.System by first building the underlying Ybus matrix and then computing the branch-bus incidence matrix weighted by branch susceptances.
Arguments
sys::PSY.System: The power system from which to construct the BA matrix
Keyword Arguments
network_reductions::Vector{NetworkReduction} = Vector{NetworkReduction}(): Vector of network reduction algorithms to apply before matrix constructioninclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittances in the network modelsubnetwork_algorithm=iterative_union_find: Algorithm used for identifying electrical islands and connected components- Additional keyword arguments are passed to the underlying
Ybusconstructor
Returns
BA_Matrix: The constructed BA matrix structure containing the transposed branch-bus incidence matrix weighted by susceptances, along with network topology information
Notes
- This constructor creates a
Ybusmatrix internally and then converts it to aBA_Matrix - Network reductions can significantly improve computational efficiency for large systems
- The resulting matrix supports DC power flow calculations and sensitivity analysis
PowerNetworkMatrices.BA_Matrix — Method
BA_Matrix(ybus)
BA_Matrix(ybus::Ybus)Construct a BA_Matrix from a Ybus matrix.
Arguments
ybus::Ybus: The Ybus matrix from which to construct the BA matrix
Returns
BA_Matrix: The constructed BA matrix structure containing the transposed BA matrix
PowerNetworkMatrices.ContingencySpec — Type
ContingencySpecA resolved, self-contained contingency specification backed by a NetworkModification. The UUID links back to the source PSY.Outage supplemental attribute for caching purposes.
Fields
uuid::Base.UUID: Unique identifier matching the source Outage supplemental attribute.modification::NetworkModification: The network topology change.
PowerNetworkMatrices.DegreeTwoReduction — Type
DegreeTwoReduction <: NetworkReductionNetwork reduction algorithm that eliminates buses with exactly two connections by combining the incident branches into a single equivalent branch. This reduction preserves the electrical characteristics of the network while simplifying its topology.
Fields
irreducible_buses::Vector{Int}: List of bus numbers that should not be eliminated even if they have degree tworeduce_reactive_power_injectors::Bool: Whether to reduce buses with reactive power injections (default: true)
Examples
# Create degree-two reduction with default settings
reduction = DegreeTwoReduction()
# Create degree-two reduction protecting specific buses
reduction = DegreeTwoReduction(irreducible_buses=[101, 205])
# Create reduction that preserves buses with reactive power injections
reduction = DegreeTwoReduction(reduce_reactive_power_injectors=false)
# Apply to system
ybus = Ybus(system; network_reductions=[reduction])PowerNetworkMatrices.EquivalentBranch — Type
EquivalentBranchRepresents the equivalent parameters of a network branch for power flow calculations.
Fields
equivalent_r::Float64: Equivalent series resistance (p.u.)equivalent_x::Float64: Equivalent series reactance (p.u.)equivalent_g_from::Float64: Equivalent shunt conductance at the "from" bus (p.u.)equivalent_b_from::Float64: Equivalent shunt susceptance at the "from" bus (p.u.)equivalent_g_to::Float64: Equivalent shunt conductance at the "to" bus (p.u.)equivalent_b_to::Float64: Equivalent shunt susceptance at the "to" bus (p.u.)equivalent_tap::Float64: Equivalent transformer tap ratioequivalent_shift::Float64: Equivalent phase shift angle (radians)
PowerNetworkMatrices.IncidenceMatrix — Type
Structure containing the network incidence matrix and related topology data.
The incidence matrix A represents the bus-branch connectivity of the power network, where each row corresponds to a branch and each column corresponds to a bus. Elements are:
- +1 for the "from" bus of a branch
- -1 for the "to" bus of a branch
- 0 for buses not connected to the branch
Fields
data::SparseArrays.SparseMatrixCSC{Int8, Int}: The incidence matrix data with dimensions (nbranches × nbuses). Values are {-1, 0, +1} representing the directed connectivity between branches and busesaxes::Ax: Tuple containing (arcidentifiers, busnumbers) where arcs are branch endpoint pairs and buses are the network bus numberslookup::L <: NTuple{2, Dict}: Tuple of dictionaries providing fast lookup from arc/bus identifiers to matrix indicessubnetwork_axes::Dict{Int, Ax}: Mapping from reference bus numbers to their corresponding subnetwork axesnetwork_reduction_data::NetworkReductionData: Container for network reduction information applied during matrix construction
Mathematical Properties
- Matrix Dimensions: (nbranches × nbuses)
- Element Values: {-1, 0, +1} representing directed branch-bus connectivity
- Row Sum: Each row sums to zero (conservation at branch level)
- Rank: Rank is (nbuses - nislands) for connected networks
- Sparsity: Very sparse with exactly 2 non-zero elements per branch row
Applications
- Power Flow: Forms the basis for DC power flow equations: P = A^T * f
- Sensitivity Analysis: Used in PTDF and LODF calculations
- Network Analysis: Identifies connected components and network structure
- Topology Processing: Enables network reduction and equivalencing algorithms
Notes
- Each branch contributes exactly one row with two non-zero entries (+1, -1)
- Reference buses are preserved in the matrix but identified separately
- Supports various network reduction techniques for computational efficiency
- Essential building block for BAMatrix and ABAMatrix constructions
PowerNetworkMatrices.IncidenceMatrix — Method
IncidenceMatrix(sys; network_reductions, kwargs...)
IncidenceMatrix(sys::PSY.System; network_reductions::Vector{NetworkReduction} = NetworkReduction[], kwargs...)Construct an IncidenceMatrix from a PowerSystems.System by extracting the network topology and creating the bus-branch connectivity matrix fundamental to power system analysis.
Arguments
sys::PSY.System: The power system from which to construct the incidence matrix
Keyword Arguments
network_reductions::Vector{NetworkReduction} = NetworkReduction[]: Vector of network reduction algorithms to apply before matrix constructioninclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittances in the network modelsubnetwork_algorithm=iterative_union_find: Algorithm used for identifying electrical islands and connected components- Additional keyword arguments are passed to the underlying
Ybusconstructor
Returns
IncidenceMatrix: The constructed incidence matrix structure containing:- Bus-branch connectivity matrix with {-1, 0, +1} elements
- Network topology information and reference bus identification
- Support for network reductions and connected component analysis
Mathematical Construction
- Network Extraction: Identifies all branches and buses from the power system
- Connectivity Mapping: Creates directed branch-bus relationships
- Matrix Assembly: Constructs sparse matrix with +1/-1 entries for branch endpoints
- Topology Analysis: Identifies reference buses and connected components
- Network Reductions: Applies specified reduction algorithms if provided
Applications
- Foundation Matrix: Essential for constructing BAMatrix and ABAMatrix
- DC Power Flow: Enables linearized power flow analysis through P = A^T * f
- Sensitivity Analysis: Required for PTDF, LODF, and other sensitivity calculations
- Network Analysis: Supports topology processing and network equivalencing
Notes
- Each branch creates exactly one matrix row with two non-zero entries
- Network reductions can significantly improve computational efficiency
- Reference buses are automatically identified for later matrix operations
- The matrix preserves full network topology for comprehensive power system analysis
PowerNetworkMatrices.IncidenceMatrix — Method
IncidenceMatrix(ybus)
IncidenceMatrix(ybus::Ybus)Construct an IncidenceMatrix from an existing Ybus matrix by extracting the network topology and creating the bus-branch connectivity matrix. This constructor leverages the network structure already captured in the Ybus matrix.
Arguments
ybus::Ybus: The Ybus matrix containing network topology and admittance data
Returns
IncidenceMatrix: The constructed incidence matrix structure containing:- Bus-branch connectivity matrix with {-1, 0, +1} elements representing directed connections
- Network topology information extracted from the Ybus structure
- Reference bus identification and subnetwork axes from the source matrix
- Network reduction data inherited from the Ybus matrix
Construction Process
- Topology Extraction: Retrieves bus and branch information from the Ybus matrix
- Arc Processing: Creates directed arc representations from branch connectivity
- Matrix Assembly: Constructs sparse incidence matrix with +1 (from bus) and -1 (to bus) entries
- Isolated Bus Handling: Includes isolated buses with zero entries for completeness
- Metadata Transfer: Preserves reference bus positions and network reduction information
Mathematical Properties
- Matrix Form: A[i,j] = +1 if branch i originates at bus j, -1 if it terminates at bus j, 0 otherwise
- Dimensions: (nbranches × nbuses) including all network branches and buses
- Sparsity: Exactly 2 non-zero entries per branch row (except for isolated buses)
- Consistency: Maintains the same network topology and reduction state as the source Ybus
Notes
- This constructor is more efficient when a Ybus matrix is already available
- Preserves all network reduction information from the source matrix
- Isolated buses are handled explicitly to maintain network completeness
- Essential for creating downstream matrices like BAMatrix and ABAMatrix from existing Ybus
PowerNetworkMatrices.LODF — Type
Structure containing the Line Outage Distribution Factor (LODF) matrix and related power system data.
The LODF matrix contains sensitivity coefficients that quantify how the outage of one transmission line affects the power flows on all other lines in the system. Each element LODF[i,j] represents the change in flow on line i when line j is taken out of service, normalized by the pre-outage flow on line j.
Fields
data::M <: AbstractArray{Float64, 2}: The LODF matrix data stored in transposed form for computational efficiency. Element (i,j) represents the sensitivity of line j flow to line i outageaxes::Ax: Tuple of identical branch/arc identifier vectors for both matrix dimensionslookup::L <: NTuple{2, Dict}: Tuple of identical dictionaries providing fast lookup from branch identifiers to matrix indicessubnetwork_axes::Dict{Int, Ax}: Mapping from reference bus numbers to their corresponding subnetwork branch axestol::Base.RefValue{Float64}: Tolerance threshold used for matrix sparsification (elements below this value are dropped)network_reduction_data::NetworkReductionData: Container for network reduction information applied during matrix construction
Mathematical Properties
- Matrix Form: LODF[i,j] = ∂fi/∂Pj where fi is flow on line i, Pj is injection change due to line j outage
- Dimensions: (nbranches × nbranches) for all transmission lines in the system
- Diagonal Elements: Always -1 (100% flow reduction on the outaged line itself)
- Symmetry: Generally non-symmetric matrix reflecting directional flow sensitivities
- Physical Meaning: Values represent fraction of pre-outage flow that redistributes to other lines
Applications
- Contingency Analysis: Evaluate impact of single line outages on system flows
- Security Assessment: Identify critical transmission bottlenecks and vulnerable lines
- System Planning: Analyze network robustness and redundancy requirements
- Real-time Operations: Support operator decision-making for preventive/corrective actions
Computational Notes
- Storage: Matrix stored in transposed form for efficient column-wise access patterns
- Sparsification: Small elements removed based on tolerance to reduce memory usage
- Linear Approximation: Based on DC power flow assumptions (neglects voltage magnitudes and reactive power)
- Single Contingencies: Designed for single line outage analysis (N-1 contingencies)
Usage Notes
- Access via
lodf[monitored_line, outaged_line]returns sensitivity coefficient - Diagonal elements are always -1.0 representing complete flow loss on outaged line
- Matrix sparsification improves performance but may introduce small numerical errors
- Results valid under DC power flow assumptions and normal operating conditions
PowerNetworkMatrices.LODF — Method
LODF(A, ABA, BA; linear_solver, tol)
LODF(A::IncidenceMatrix, ABA::ABA_Matrix, BA::BA_Matrix; linear_solver::String = "KLU", tol::Float64 = eps())Construct a Line Outage Distribution Factor (LODF) matrix from incidence, ABA, and BA matrices. This constructor provides direct control over the underlying matrix computations and is most efficient when the prerequisite matrices with factorization are already available.
Arguments
A::IncidenceMatrix: The incidence matrix containing bus-branch connectivity informationABA::ABA_Matrix: The bus susceptance matrix (A^T * B * A), preferably with KLU factorizationBA::BA_Matrix: The branch susceptance weighted incidence matrix (B * A)
Keyword Arguments
linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Currently only "KLU" is supportedtol::Float64 = eps(): Sparsification tolerance for dropping small matrix elements
Returns
LODF: The constructed LODF matrix structure with line outage sensitivity coefficients
Mathematical Computation
This method computes LODF using the factorized form:
LODF = (A * ABA^(-1) * BA) / (1 - diag(A * ABA^(-1) * BA))where:
- A is the incidence matrix
- ABA^(-1) uses the factorized form from the ABA matrix (requires
ABA.Kto be factorized) - BA is the susceptance-weighted incidence matrix
Requirements and Limitations
- Factorization Required: The ABA matrix should be pre-factorized (contains KLU factorization) for efficiency
- Single Slack Bus: This method does not support distributed slack bus configurations
- Network Consistency: All three input matrices must have equivalent network reduction states
- Solver Limitation: Currently only supports "KLU" linear solver
Performance Advantages
- Pre-factorization: Leverages existing KLU factorization in ABA matrix for maximum efficiency
- Direct Computation: Avoids intermediate PTDF calculation, reducing computational steps
- Memory Efficient: Works directly with sparse matrix structures throughout computation
- Numerical Stability: Uses numerically stable KLU solver for matrix operations
Error Handling
- Validates network reduction consistency across all three input matrices
- Raises error if matrices have mismatched reduction states
- Validates linear solver selection (currently only "KLU" supported)
Usage Recommendations
- Use this constructor when you have pre-computed and factorized matrices available
- Ensure ABA matrix is factorized using
factorize(ABA)or constructed withfactorize=true - For systems with distributed slack, use the PTDF-based constructor instead
- Most efficient option for repeated LODF computations on the same network topology
PowerNetworkMatrices.LODF — Method
LODF(A, PTDFm; linear_solver, tol)
LODF(A::IncidenceMatrix, PTDFm::PTDF; linear_solver::String = "KLU", tol::Float64 = eps())Construct a Line Outage Distribution Factor (LODF) matrix from existing incidence and PTDF matrices. This constructor is more efficient when the prerequisite matrices are already available.
Arguments
A::IncidenceMatrix: The incidence matrix containing bus-branch connectivity informationPTDFm::PTDF: The power transfer distribution factor matrix (should be non-sparsified for accuracy)
Keyword Arguments
linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Options: "KLU", "Dense", "MKLPardiso"tol::Float64 = eps(): Sparsification tolerance for the LODF matrix (not applied to input PTDF)
Returns
LODF: The constructed LODF matrix structure with line outage sensitivity coefficients
Mathematical Computation
The LODF matrix is computed using the formula:
LODF = (A * PTDF) / (1 - diag(A * PTDF))where:
- A is the incidence matrix representing bus-branch connectivity
- PTDF contains power transfer distribution factors
- The denominator (1 - diagonal terms) accounts for the outaged line's own flow
Important Notes
- PTDF Sparsification: The input PTDF matrix should be non-sparsified (constructed with default tolerance) to avoid accuracy issues
- Tolerance Application: The
tolparameter only affects LODF sparsification, not the input PTDF - Network Consistency: Both input matrices must have equivalent network reduction states
- Diagonal Elements: Automatically set to -1.0 representing complete flow loss on outaged lines
Performance Considerations
- Matrix Validation: Warns if input PTDF was sparsified and converts to dense format for accuracy
- Memory Usage: Sparsification with
tol > eps()can significantly reduce memory requirements - Computational Efficiency: More efficient than system-based constructor when matrices exist
Error Handling
- Validates that incidence and PTDF matrices have consistent network reduction data
- Issues warnings if sparsified PTDF matrices are used (potential accuracy issues)
- Supports automatic conversion of sparse PTDF to dense format when necessary
Linear Solver Selection
- "KLU": Recommended for most applications (sparse, numerically stable)
- "Dense": Faster for smaller systems but higher memory usage
- "MKLPardiso": Best performance for very large systems (requires MKL library)
PowerNetworkMatrices.LODF — Method
LODF(sys; linear_solver, tol, network_reductions, kwargs...)
LODF(sys::PSY.System; linear_solver::String = "KLU", tol::Float64 = eps(), network_reductions::Vector{NetworkReduction} = NetworkReduction[], kwargs...)Construct a Line Outage Distribution Factor (LODF) matrix from a PowerSystems.System by computing the sensitivity of line flows to single line outages. This is the primary constructor for LODF analysis starting from system data.
Arguments
sys::PSY.System: The power system from which to construct the LODF matrix
Keyword Arguments
linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Options: "KLU", "Dense", "MKLPardiso"tol::Float64 = eps(): Sparsification tolerance for dropping small matrix elements to reduce memory usagenetwork_reductions::Vector{NetworkReduction} = NetworkReduction[]: Vector of network reduction algorithms to apply before matrix constructioninclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittances in the network modelsubnetwork_algorithm=iterative_union_find: Algorithm used for identifying electrical islands and connected components- Additional keyword arguments are passed to the underlying matrix constructors
Returns
LODF: The constructed LODF matrix structure containing:- Line-to-line outage sensitivity coefficients
- Network topology information and branch identifiers
- Sparsification tolerance and computational metadata
Construction Process
- Ybus Construction: Creates system admittance matrix with specified reductions
- Incidence Matrix: Builds bus-branch connectivity matrix A
- BA Matrix: Computes branch susceptance weighted incidence matrix
- PTDF Calculation: Derives power transfer distribution factors
- LODF Computation: Calculates line outage distribution factors from PTDF
- Sparsification: Applies tolerance threshold to reduce matrix density
Linear Solver Options
- "KLU": Sparse LU factorization (default, recommended for most cases)
- "Dense": Dense matrix operations (faster for small systems)
- "MKLPardiso": Intel MKL Pardiso solver (requires MKL, best for very large systems)
Mathematical Foundation
The LODF matrix is computed using the relationship:
LODF = (A * PTDF) / (1 - diag(A * PTDF))where A is the incidence matrix and PTDF is the power transfer distribution factor matrix.
Notes
- Sparsification with
tol > eps()can significantly reduce memory usage - Network reductions can improve computational efficiency for large systems
- Results are valid under DC power flow assumptions (linear approximation)
- Diagonal elements are always -1.0 representing complete flow loss on outaged lines
- For very large systems, consider using "MKLPardiso" solver with appropriate chunk size
PowerNetworkMatrices.NetworkModification — Type
NetworkModificationCanonical description of topology changes to a power network. Wraps arc susceptance changes, shunt admittance changes, and islanding status. No dependency on PSY.System after construction.
Fields
label::String: Human-readable identifier for the modification.arc_modifications::Tuple{Vararg{ArcModification}}: One entry per affected arc (immutable).shunt_modifications::Tuple{Vararg{ShuntModification}}: One entry per affected shunt bus (immutable).is_islanding::Bool: Whether this modification disconnects the network.
Modification vectors are converted to tuples at construction time to guarantee immutability. This is required because NetworkModification is used as a Dict key (via custom hash/==) in VirtualMODF caches; mutable fields would silently corrupt lookups if modified after insertion.
PowerNetworkMatrices.NetworkModification — Method
NetworkModification(ctg)
NetworkModification(
ctg::ContingencySpec
) -> NetworkModification
Construct a NetworkModification from an existing ContingencySpec.
PowerNetworkMatrices.NetworkModification — Method
NetworkModification(mat, branch)
NetworkModification(
mat::PowerNetworkMatrices.PowerNetworkMatrix,
branch::PowerSystems.ACTransmission
) -> NetworkModification
Construct a NetworkModification from a branch component using network reduction reverse maps to classify the branch as direct, parallel, or series.
PowerNetworkMatrices.NetworkModification — Method
NetworkModification(mat, sys, outage)
NetworkModification(
mat::PowerNetworkMatrices.PowerNetworkMatrix,
sys::PowerSystems.System,
outage::PowerSystems.Outage
) -> NetworkModification
Construct a NetworkModification from a PSY.Outage supplemental attribute. Resolves the outage's associated ACTransmission components through the system, classifies each by the matrix's network reduction maps, and builds the modification. Handles multi-component outages with series-chain grouping.
PowerNetworkMatrices.NetworkModification — Method
NetworkModification(mat, arc)
NetworkModification(
mat::PowerNetworkMatrices.PowerNetworkMatrix,
arc::Tuple{Int64, Int64}
) -> NetworkModification
Construct a full arc outage NetworkModification by bus-pair tuple. Looks up arc susceptance from the matrix and sets Δb = -b_arc.
PowerNetworkMatrices.NetworkReduction — Type
NetworkReductionAbstract base type for all network reduction algorithms used in power network analysis. Network reductions are mathematical transformations that eliminate buses and branches while preserving the electrical behavior of the remaining network elements.
Concrete implementations include:
RadialReduction: Eliminates radial (dangling) buses and branchesDegreeTwoReduction: Eliminates buses with exactly two connectionsWardReduction: Reduces external buses while preserving study bus behavior
PowerNetworkMatrices.NetworkReductionData — Type
NetworkReductionDataMutable struct containing all data mappings and metadata for network reduction operations. This structure tracks how buses and branches are mapped, combined, or eliminated during network reduction algorithms.
Fields
irreducible_buses::Set{Int}: Buses that cannot be reducedbus_reduction_map::Dict{Int, Set{Int}}: Maps retained buses to sets of eliminated busesreverse_bus_search_map::Dict{Int, Int}: Maps eliminated buses to their parent busesdirect_branch_map::Dict{Tuple{Int, Int}, PSY.ACTransmission}: One-to-one branch mappingsreverse_direct_branch_map::Dict{PSY.ACTransmission, Tuple{Int, Int}}: Reverse direct mappingsparallel_branch_map::Dict{Tuple{Int, Int}, BranchesParallel}: Parallel branch combinationsreverse_parallel_branch_map::Dict{PSY.ACTransmission, Tuple{Int, Int}}: Reverse parallel mappingsseries_branch_map::Dict{Tuple{Int, Int}, BranchesSeries}: Series branch combinationsreverse_series_branch_map::Dict{Any, Tuple{Int, Int}}: Reverse series mappingstransformer3W_map::Dict{Tuple{Int, Int}, ThreeWindingTransformerWinding}: Three-winding transformer mappingsreverse_transformer3W_map::Dict{ThreeWindingTransformerWinding, Tuple{Int, Int}}: Reverse transformer mappingsremoved_buses::Set{Int}: Set of buses eliminated from the networkremoved_arcs::Set{Tuple{Int, Int}}: Set of arcs eliminated from the networkremoved_arc_to_surviving_bus::Dict{Tuple{Int, Int}, Int}: Maps removed arcs to the connected surviving bus number (occurs for radial reduction or Ward reduction)boundary_bus_to_removed_arcs::Dict{Int, Set{Tuple{Int, Int}}}: Maps boundary buses to the set of removed arcs connected to themadded_admittance_map::Dict{Int, PSY.FixedAdmittance}: Admittances added to buses during reductionadded_arc_impedance_map::Dict{Tuple{Int, Int}, PSY.GenericArcImpedance}: New arcs created during reductionall_branch_maps_by_type::BranchMapsByType: Branch mappings organized by component typereductions::ReductionContainer: Container tracking applied reduction algorithmsname_to_arc_map::Dict{Type, DataStructures.SortedDict{String, Tuple{Tuple{Int, Int}, String}}}: Lazily filled with the call topopulate_branch_maps_by_type!, maps string names to their corresponding arcs and the map where the arc can be found.component_to_reduction_name_map::Dict{Type, Dict{String, String}}: Lazily filled with the call topopulate_branch_maps_by_type!, maps component names to the names of the reduction entries used in nametoarc_map.filters_applied::Dict{Type, Function}: Filters applied when populating branch maps by typedirect_branch_name_map::Dict{String, Tuple{Int, Int}}: Lazily filled, maps branch names to their corresponding arc tuples for direct branches
PowerNetworkMatrices.PTDF — Type
Structure containing the Power Transfer Distribution Factor (PTDF) matrix and related power system data.
The PTDF matrix contains sensitivity coefficients that quantify how power injections at buses affect the power flows on transmission lines. Each element PTDF[i,j] represents the incremental change in flow on line i due to a unit power injection at bus j, under DC power flow assumptions.
Fields
data::M <: AbstractArray{Float64, 2}: The PTDF matrix data stored in transposed form for computational efficiency. Element (i,j) represents the sensitivity of line j flow to bus i injectionaxes::Ax: Tuple containing (busnumbers, branchidentifiers) for matrix dimensionslookup::L <: NTuple{2, Dict}: Tuple of dictionaries providing fast lookup from bus/branch identifiers to matrix indicessubnetwork_axes::Dict{Int, Ax}: Mapping from reference bus numbers to their corresponding subnetwork axestol::Base.RefValue{Float64}: Tolerance threshold used for matrix sparsification (elements below this value are dropped)network_reduction_data::NetworkReductionData: Container for network reduction information applied during matrix construction
Mathematical Properties
- Matrix Form: PTDF[i,j] = ∂fi/∂Pj where fi is flow on line i, Pj is injection at bus j
- Dimensions: (nbuses × narcs) for all buses and impedance arcs
- Linear Superposition: Total flow = Σ(PTDF[i,j] × Pj) for all injections Pj
- Physical Meaning: Values represent the fraction of bus injection that flows through each line
- Reference Bus: Rows corresponding to reference buses are typically zero
Applications
- Power Flow Analysis: Rapid calculation of line flows for given injection patterns
- Sensitivity Studies: Evaluate impact of generation/load changes on transmission flows
- Congestion Management: Identify lines affected by specific injection changes
- Market Analysis: Support nodal pricing and transmission rights calculations
- Planning Studies: Assess transmission utilization under various scenarios
Computational Features
- Matrix Storage: Stored in transposed form (bus × branch) for efficient computation
- Sparsification: Small elements removed based on tolerance to reduce memory usage
- Reference Bus Handling: Reference bus injections automatically handled in calculations
- Distributed Slack: Supports distributed slack bus configurations for improved realism
Usage Notes
- Access via
ptdf[bus, line]returns the sensitivity coefficient - Matrix indexing uses bus numbers and branch identifiers
- Sparsification improves memory efficiency but may introduce small numerical errors
- Results valid under DC power flow assumptions (neglects voltage magnitudes and reactive power)
- Reference bus choice affects the specific values but not the relative sensitivities
PowerNetworkMatrices.PTDF — Method
PTDF(filename)
Deserialize a PTDF from an HDF5 file.
Arguments
filename::AbstractString: File containing a serialized PTDF.
PowerNetworkMatrices.PTDF — Method
PTDF(A, BA; dist_slack, linear_solver, tol)
PTDF(A::IncidenceMatrix, BA::BA_Matrix; dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(), linear_solver = "KLU", tol::Float64 = eps())Construct a Power Transfer Distribution Factor (PTDF) matrix from existing incidence and BA matrices. This constructor is more efficient when the prerequisite matrices are already available and provides direct control over the underlying matrix computations.
Arguments
A::IncidenceMatrix: The incidence matrix containing bus-branch connectivity informationBA::BA_Matrix: The branch susceptance weighted incidence matrix (B × A)
Keyword Arguments
dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(): Dictionary mapping bus numbers to distributed slack participation factors. Empty dictionary uses single slack bus (reference bus from matrices)linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Options: "KLU", "Dense", "MKLPardiso"tol::Float64 = eps(): Sparsification tolerance for dropping small matrix elements to reduce memory usage
Returns
PTDF: The constructed PTDF matrix structure with injection-to-flow sensitivity coefficients
Mathematical Computation
The PTDF matrix is computed using the relationship:
PTDF = (A^T × B × A)^(-1) × A^T × Bwhere:
- A is the incidence matrix representing bus-branch connectivity
- B is the diagonal susceptance matrix (embedded in BA matrix)
- The computation involves solving the ABA linear system for efficiency
Distributed Slack Handling
- Single Slack: Uses reference bus identified from input matrices
- Distributed Slack: Applies participation factor corrections to final PTDF
- Automatic Processing: Dictionary converted to vector form matching matrix dimensions
- Validation: Ensures distributed slack bus numbers exist in the network
- Normalization: Participation factors automatically normalized to maintain power balance
Network Consistency Requirements
- Reduction Compatibility: Both input matrices must have equivalent network reduction states
- Reference Alignment: BA matrix reference buses determine the PTDF reference framework
- Topology Consistency: Matrices must represent the same network topology
Performance Considerations
- Matrix Reuse: More efficient when A and BA matrices are already computed
- Memory Management: Sparsification reduces storage requirements significantly
- Solver Selection: KLU recommended for sparse systems, Dense for small networks
- Computational Efficiency: Avoids redundant system matrix construction
Error Handling and Validation
- Matrix Compatibility: Validates that A and BA have consistent network reductions
- Slack Validation: Checks that distributed slack buses exist in the matrix structure
- Solver Validation: Ensures selected linear solver is supported and available
- Numerical Stability: Handles singular systems and provides informative error messages
Usage Recommendations
- Preferred Method: Use when incidence and BA matrices are already available
- Repeated Calculations: Ideal for multiple PTDF computations with different slack configurations
- Large Systems: Consider sparsification for memory efficiency
- Distributed Slack: Provides more realistic modeling of generator response to load changes
PowerNetworkMatrices.PTDF — Method
PTDF(sys; dist_slack, linear_solver, tol, kwargs...)
PTDF(sys::PSY.System; dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(), linear_solver = "KLU", tol::Float64 = eps(), network_reductions::Vector{NetworkReduction} = NetworkReduction[], kwargs...)Construct a Power Transfer Distribution Factor (PTDF) matrix from a PowerSystems.System by computing the sensitivity of transmission line flows to bus power injections. This is the primary constructor for PTDF analysis starting from system data.
Arguments
sys::PSY.System: The power system from which to construct the PTDF matrix
Keyword Arguments
dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(): Dictionary mapping bus numbers to distributed slack weights for realistic slack modeling. Empty dictionary uses single slack bus (default behavior)linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Options: "KLU", "Dense", "MKLPardiso"tol::Float64 = eps(): Sparsification tolerance for dropping small matrix elements to reduce memory usagenetwork_reductions::Vector{NetworkReduction} = NetworkReduction[]: Vector of network reduction algorithms to apply before matrix constructioninclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittances in the network modelsubnetwork_algorithm=iterative_union_find: Algorithm used for identifying electrical islands and connected components- Additional keyword arguments are passed to the underlying matrix constructors
Returns
PTDF: The constructed PTDF matrix structure containing:- Bus-to-impedance-arc injection sensitivity coefficients
- Network topology information and reference bus identification
- Sparsification tolerance and computational metadata
Construction Process
- Ybus Construction: Creates system admittance matrix with specified reductions
- Incidence Matrix: Builds bus-branch connectivity matrix A
- BA Matrix: Computes branch susceptance weighted incidence matrix
- PTDF Computation: Calculates power transfer distribution factors using A^T × B^(-1) × A
- Distributed Slack: Applies distributed slack correction if specified
- Sparsification: Removes small elements based on tolerance threshold
Distributed Slack Configuration
- Single Slack: Empty
dist_slackdictionary uses conventional single slack bus - Distributed Slack: Dictionary maps bus numbers to participation factors
- Normalization: Participation factors automatically normalized to sum to 1.0
- Physical Meaning: Distributed slack better represents generator response to load changes
Linear Solver Options
- "KLU": Sparse LU factorization (default, recommended for most cases)
- "Dense": Dense matrix operations (faster for small systems, higher memory usage)
- "MKLPardiso": Intel MKL Pardiso solver (requires MKL library, best for very large systems)
Mathematical Foundation
The PTDF matrix is computed as:
PTDF = (A^T × B × A)^(-1) × A^T × Bwhere A is the incidence matrix and B is the susceptance matrix.
Notes
- Results are valid under DC power flow assumptions (linear approximation)
- Reference bus selection affects specific values but not relative sensitivities
- Sparsification with
tol > eps()can significantly reduce memory usage - Network reductions improve computational efficiency for large systems
- Distributed slack provides more realistic representation of system response
PowerNetworkMatrices.PTDF — Method
PTDF(ybus; dist_slack, linear_solver, tol)
PTDF(ybus::Ybus; dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(), linear_solver = "KLU", tol::Float64 = eps(), network_reductions::Vector{NetworkReduction} = NetworkReduction[], kwargs...)Construct a Power Transfer Distribution Factor (PTDF) matrix from existing Ybus matrix. This constructor is more efficient when the prerequisite matrices are already available and provides direct control over the underlying matrix computations.
Arguments
ybus::Ybus: The power system Ybus matrix from which to construct the PTDF matrix
Keyword Arguments
dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(): Dictionary mapping bus numbers to distributed slack weights for realistic slack modeling. Empty dictionary uses single slack bus (default behavior)linear_solver::String = "KLU": Linear solver algorithm for matrix computations. Options: "KLU", "Dense", "MKLPardiso"tol::Float64 = eps(): Sparsification tolerance for dropping small matrix elements to reduce memory usage
Returns
PTDF: The constructed PTDF matrix structure containing:- Bus-to-impedance-arc injection sensitivity coefficients
- Network topology information and reference bus identification
- Sparsification tolerance and computational metadata
Construction Process
- Incidence Matrix: Builds bus-branch connectivity matrix A (from Ybus matrix)
- BA Matrix: Computes branch susceptance weighted incidence matrix
- PTDF Computation: Calculates power transfer distribution factors using A^T × B^(-1) × A
- Distributed Slack: Applies distributed slack correction if specified
- Sparsification: Removes small elements based on tolerance threshold
Distributed Slack Configuration
- Single Slack: Empty
dist_slackdictionary uses conventional single slack bus - Distributed Slack: Dictionary maps bus numbers to participation factors
- Normalization: Participation factors automatically normalized to sum to 1.0
- Physical Meaning: Distributed slack better represents generator response to load changes
Linear Solver Options
- "KLU": Sparse LU factorization (default, recommended for most cases)
- "Dense": Dense matrix operations (faster for small systems, higher memory usage)
- "MKLPardiso": Intel MKL Pardiso solver (requires MKL library, best for very large systems)
Mathematical Foundation
The PTDF matrix is computed as:
PTDF = (A^T × B × A)^(-1) × A^T × Bwhere A is the incidence matrix and B is the susceptance matrix.
Notes
- Results are valid under DC power flow assumptions (linear approximation)
- Reference bus selection affects specific values but not relative sensitivities
- Sparsification with
tol > eps()can significantly reduce memory usage - Network reductions improve computational efficiency for large systems
- Distributed slack provides more realistic representation of system response
PowerNetworkMatrices.PowerNetworkMatrix — Type
Type PowerNetworkMatrix gathers all the different types of Matrices considered in this package
PowerNetworkMatrices.PowerNetworkMatrixKey — Type
Structure to store the keys of a power network matrix
Arguments
I<:Tuple: tuple containing the indices of the matrix
PowerNetworkMatrices.PowerNetworkMatrixKeys — Type
Structure to store the keys of a power network matrix
Arguments
product_iter::Base.Iterators.ProductIterator{T} where T <: Tuple: iterator of the indices of the network power matrix
PowerNetworkMatrices.RadialReduction — Type
RadialReduction <: NetworkReductionNetwork reduction algorithm that eliminates radial (dangling) buses and their associated branches from the power network. Radial buses are leaf nodes with only one connection that do not affect the electrical behavior of the rest of the network.
Fields
irreducible_buses::Vector{Int}: List of bus numbers that should not be eliminated even if they are radial
Examples
# Create radial reduction with no protected buses
reduction = RadialReduction()
# Create radial reduction protecting specific buses
reduction = RadialReduction(irreducible_buses=[101, 205])
# Apply to system
ybus = Ybus(system; network_reductions=[reduction])PowerNetworkMatrices.RowCache — Type
Structure used for saving the rows of the Virtual PTDF and LODF matrix.
Arguments
temp_cache::Dict{Int, Union{Vector{Float64}, SparseArrays.SparseVector{Float64}}}: Dictionary saving the row of the PTDF/LODF matrixpersistent_cache_keys::Set{Int}: Set listing the rows to keep intemp_cachemax_cache_size::IntDefines the maximum allowed cache size (rows*row_size)max_num_keys::IntDefines the maximum number of keys saved (rows of the matrix)access_order::Vector{Int}: Vector tracking access order for LRU eviction (most recent at end)
PowerNetworkMatrices.RowCache — Method
RowCache(max_cache_size, persistent_rows, row_size)
Structure used for saving the rows of the Virtual PTDF and LODF matrix.
Arguments
max_cache_size::IntDefines the maximum allowed cache size (rows*row_size).persistent_rows::Set{Int}: Set listing the rows to keep intemp_cache.row_sizeDefines the size of the single row to store.
PowerNetworkMatrices.ShuntModification — Type
ShuntModificationA diagonal admittance change on a single bus (shunt outage or modification). Used to track shunt component outages (FixedAdmittance, SwitchedAdmittance, StandardLoad) that affect the Ybus but not DC sensitivity factors.
Fields
bus_index::Int: Index of the bus in the network matrix.delta_y::ComplexF32: Change in shunt admittance (negative for an outage).
PowerNetworkMatrices.ThreeWindingTransformerWinding — Type
ThreeWindingTransformerWinding{T<:PSY.ThreeWindingTransformer} <: PSY.ACTransmissionInternal object representing a single winding of a three-winding transformer. Do not export.
This structure is used internally to decompose three-winding transformers into individual winding components for network matrix construction and analysis purposes.
Fields
transformer::T: The parent three-winding transformer objectwinding_number::Int: The winding number (1, 2, or 3) that this object represents
Note
This is an internal object and should not be constructed directly by users or added to a system.
PowerNetworkMatrices.VirtualLODF — Type
The Virtual Line Outage Distribution Factor (VirtualLODF) structure gathers the rows of the LODF matrix as they are evaluated on-the-go. These rows are evaluated independently, cached in the structure and do not require the computation of the whole matrix (therefore significantly reducing the computational requirements).
The VirtualLODF is initialized with no row stored.
The VirtualLODF struct is indexed using branch names.
Arguments
K::KLU.KLUFactorization{Float64, Int}: LU factorization matrices of the ABA matrix, evaluated by means of KLU.BA::SparseArrays.SparseMatrixCSC{Float64, Int}: BA matrix.A::SparseArrays.SparseMatrixCSC{Int8, Int}: Incidence matrix.inv_PTDF_A_diag::Vector{Float64}: Vector contiaining the element-wise reciprocal of the diagonal elements coming from multuiplying the PTDF matrix with th Incidence matrixPTDF_A_diag::Vector{Float64}: Raw diagonal elements of the PTDF·A product (H[e,e] values), before tolerance clamping. Used for partial susceptance change computations.arc_susceptances::Vector{Float64}: Effective susceptance for each arc, extracted from the BA matrix. For arc j, this is the absolute value of the first nonzero in BA column j. BA columns always have the structure [+b, -b] (from-bus and to-bus entries), so both nonzeros have the same magnitude.branch_susceptances_by_arc::Vector{Vector{Float64}}: Per-branch susceptances for each arc. For single-branch arcs, contains one element equal to the arc susceptance. For parallel branches, contains one entry per branch in the parallel group.ref_bus_positions::Set{Int}: Vector containing the indexes of the rows of the transposed BA matrix corresponding to the reference buses.dist_slack::Vector{Float64}: Vector of weights to be used as distributed slack bus. The distributed slack vector has to be the same length as the number of buses.axes<:NTuple{2, Dict}: Tuple containing two vectors showing the branch names.lookup<:NTuple{2, Dict}: Tuple containing two dictionaries, mapping the branches names the enumerated row indexes indexes.valid_ix::Vector{Int}: Vector containing the row/columns indices of matrices related the buses which are not slack ones.temp_data::Vector{Float64}: Temporary vector for internal use.cache::RowCache: Cache were LODF rows are stored.subnetworks::Dict{Int, Set{Int}}: Dictionary containing the subsets of buses defining the different subnetwork of the system.tol::Base.RefValue{Float64}: Tolerance related to scarification and values to drop.network_reduction::NetworkReduction: Structure containing the details of the network reduction applied when computing the matrix
PowerNetworkMatrices.VirtualLODF — Method
VirtualLODF(
sys;
dist_slack,
tol,
max_cache_size,
persistent_arcs,
network_reductions,
kwargs...
)
Builds the Virtual LODF matrix from a system. The return is a VirtualLODF struct with an empty cache.
Arguments
sys::PSY.System: PSY system for which the matrix is constructed
Keyword Arguments
network_reduction::NetworkReduction: Structure containing the details of the network reduction applied when computing the matrixkwargs...: other keyword arguments used by VirtualPTDF
PowerNetworkMatrices.VirtualMODF — Type
The Virtual Multiple Outage Distribution Factor (VirtualMODF) structure computes post-contingency PTDF rows lazily for registered contingencies using the Woodbury matrix identity (van Dijk et al. Eq. 29).
Contingencies are resolved from PSY.Outage supplemental attributes at construction time. After registration, the System is not needed for queries.
Caching is two-tiered:
- Woodbury factors (M KLU solves) are cached per contingency
- PTDF rows (1 KLU solve each) are cached per (monitored_arc, contingency) via one RowCache per contingency
Arguments
K::KLU.KLUFactorization{Float64, Int}: LU factorization of ABA matrix.BA::SparseArrays.SparseMatrixCSC{Float64, Int}: BA matrix.A::SparseArrays.SparseMatrixCSC{Int8, Int}: Incidence matrix.PTDF_A_diag::Vector{Float64}: Raw diagonal elements of PTDF·A (H[e,e] values).arc_susceptances::Vector{Float64}: Effective susceptance for each arc.branch_susceptances_by_arc::Vector{Vector{Float64}}: Per-branch susceptances for each arc. For single-branch arcs, contains one element equal to the arc susceptance. For parallel branches, contains one entry per branch in the parallel group.dist_slack::Vector{Float64}: Distributed slack bus weights.axes::Ax: Tuple of (arcaxis, busaxis).lookup::L: Tuple of lookup dictionaries for indexing.valid_ix::Vector{Int}: Indices of non-reference buses.contingency_cache::Dict{Base.UUID, ContingencySpec}: Resolved contingencies keyed by outage UUID.woodbury_cache::Dict{NetworkModification, WoodburyFactors}: Precomputed Woodbury factors keyed by modification.row_caches::Dict{NetworkModification, RowCache}: One RowCache per modification, keyed by modification.subnetwork_axes::Dict{Int, Ax}: Maps reference bus indices to subnetwork axes.tol::Base.RefValue{Float64}: Tolerance for sparsification.max_cache_size_bytes::Int: Max cache size in bytes per contingency.network_reduction_data::NetworkReductionData: Network reduction mappings for branch resolution.temp_data::Vector{Float64}: Scratch vector of size n_buses.work_ba_col::Vector{Float64}: Pre-allocated work array for BA column extraction.system_uuid::Union{Base.UUID, Nothing}: UUID of the system used to construct the matrix, used to validate that modification operations are applied to the correct system.
PowerNetworkMatrices.VirtualMODF — Method
VirtualMODF(
sys;
dist_slack,
tol,
max_cache_size,
network_reductions,
kwargs...
)
VirtualMODF(sys::PSY.System; kwargs...) -> VirtualMODFBuild a VirtualMODF from a PowerSystems System. Automatically registers all Outage supplemental attributes found in the system.
Arguments
sys::PSY.System: Power system to build from
Keyword Arguments
dist_slack::Vector{Float64}: Distributed slack weights (default: empty)tol::Float64: Tolerance for row sparsification (default: eps())max_cache_size::Int: Max cache size in MiB per contingency (default: MAXCACHESIZE_MiB)network_reductions::Vector{NetworkReduction}: Network reductions to apply
PowerNetworkMatrices.VirtualPTDF — Type
The Virtual Power Transfer Distribution Factor (VirtualPTDF) structure gathers the rows of the PTDF matrix as they are evaluated on-the-go. These rows are evaluated independently, cached in the structure and do not require the computation of the whole matrix (therefore significantly reducing the computational requirements).
The VirtualPTDF is initialized with no row stored.
The VirtualPTDF is indexed using branch names and bus numbers as for the PTDF matrix.
Arguments
K::Union{KLU.KLUFactorization{Float64, Int}, AppleAccelerate.AAFactorization{Float64}}: LU factorization matrices of the ABA matrix, evaluated by means of KLU or AppleAccelerateBA::SparseArrays.SparseMatrixCSC{Float64, Int}: BA matrixref_bus_positions::Set{Int}: Vector containing the indexes of the columns of the BA matrix corresponding to the reference busesdist_slack::Vector{Float64}: Vector of weights to be used as distributed slack bus. The distributed slack vector has to be the same length as the number of buses.axes<:NTuple{2, Dict}: Tuple containing two vectors: the first one showing the branches names, the second showing the buses numbers. There is no link between the order of the vector of the branches names and the way the PTDF rows are stored in the cache.lookup<:NTuple{2, Dict}: Tuple containing two dictionaries, mapping the branches and buses with their enumerated indexes. The branch indexes refer to the key of the cache dictionary. The bus indexes refer to the position of the elements in the PTDF row stored.temp_data::Vector{Float64}: Temporary vector for internal use.valid_ix::Vector{Int}: Vector containing the row/columns indices of matrices related the buses which are not slack ones.cache::RowCache: Cache were PTDF rows are stored.subnetworks::Dict{Int, Set{Int}}: Dictionary containing the subsets of buses defining the different subnetwork of the system.tol::Base.RefValue{Float64}: Tolerance related to scarification and values to drop.network_reduction::NetworkReduction: Structure containing the details of the network reduction applied when computing the matrixsystem_uuid::Union{Base.UUID, Nothing}: UUID of the system used to construct the matrix, used to validate that modification operations are applied to the correct system.nothingwhen constructed from a Ybus without an associated system.
PowerNetworkMatrices.VirtualPTDF — Method
VirtualPTDF(
sys;
dist_slack,
linear_solver,
tol,
max_cache_size,
persistent_arcs,
network_reductions,
kwargs...
)
Builds the Virtual PTDF matrix from a system. The return is a VirtualPTDF struct with an empty cache.
Arguments
sys::PSY.System: PSY system for which the matrix is constructed
Keyword Arguments
dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(): Dictionary of weights to be used as distributed slack bus. The distributed slack dictionary must have the same number of entries as the number of buses.linear_solver::String = "KLU": Linear solver to use for factorization. Options: "KLU", "AppleAccelerate"tol::Float64 = eps(): Tolerance related to sparsification and values to drop.max_cache_size::Int: max cache size in MiB (initialized as MAXCACHESIZE_MiB).persistent_arcs::Vector{Tuple{Int, Int}} = Vector{Tuple{Int, Int}}(): arcs to be evaluated as soon as the VirtualPTDF is created (initialized as empty vector of tuples).network_reduction::NetworkReduction: Structure containing the details of the network reduction applied when computing the matrixkwargs...: other keyword arguments used by VirtualPTDF
PowerNetworkMatrices.VirtualPTDF — Method
VirtualPTDF(
ybus;
dist_slack,
linear_solver,
tol,
max_cache_size,
persistent_arcs,
system_uuid
)
Builds the Virtual PTDF matrix from a Ybus matrix. This constructor is more efficient when the prerequisite Ybus matrix is already available and provides direct control over the underlying matrix computations (including network reductions). The return is a VirtualPTDF struct with an empty cache.
Arguments
ybus::Ybus: Ybus matrix from which the matrix is constructed
Keyword Arguments
dist_slack::Dict{Int, Float64} = Dict{Int, Float64}(): Dictionary of weights to be used as distributed slack bus. The distributed slack dictionary must have the same number of entries as the number of buses.linear_solver::String = "KLU": Linear solver to use for factorization. Options: "KLU", "AppleAccelerate"tol::Float64 = eps(): Tolerance related to sparsification and values to drop.max_cache_size::Int: max cache size in MiB (initialized as MAXCACHESIZE_MiB).persistent_arcs::Vector{Tuple{Int, Int}} = Vector{Tuple{Int, Int}}(): arcs to be evaluated as soon as the VirtualPTDF is created (initialized as empty vector of tuples).
PowerNetworkMatrices.WardReduction — Type
WardReduction <: NetworkReductionA NetworkReduction that eliminates external buses while preserving the electrical behavior within the study area, using Ward equivalencing. External buses are mapped to boundary buses based on impedance criteria, and equivalent admittances are computed.
Fields
study_buses::Vector{Int}: bus numbers to retain in the reduced network
Examples
# Create ward reduction with internal bus numbers 101, 102, and 103
reduction = WardReduction([101, 102, 103])
# Apply to system
ybus = Ybus(system; network_reductions=[reduction])PowerNetworkMatrices.WoodburyFactors — Type
WoodburyFactorsCached Woodbury intermediates shared across monitored arcs for one contingency. Computed from van Dijk et al. Eq. 29: Bm⁻¹ = Br⁻¹ - Br⁻¹ U (A⁻¹ + U⊤ Br⁻¹ U)⁻¹ U⊤ B_r⁻¹
Fields
Z::Matrix{Float64}: B⁻¹U matrix (n_bus × M), one column per modified arcW_inv::Matrix{Float64}: Pre-inverted W = (A⁻¹ + U⊤B⁻¹U)⁻¹ (M × M). For M ≤ 2, computed analytically; for M > 2, computed via LU factorization.arc_indices::Vector{Int}: Arc indices of modified arcsdelta_b::Vector{Float64}: Susceptance changes per modified arcis_islanding::Bool: Whether this contingency islands the network
PowerNetworkMatrices.Ybus — Type
Ybus{Ax, L <: NTuple{2, Dict}} <: PowerNetworkMatrix{YBUS_ELTYPE}Nodal admittance matrix (Y-bus) representing the electrical admittance relationships between buses in a power system. This N×N sparse complex matrix encodes the network topology and electrical parameters needed for power flow calculations and network analysis.
Fields
data::SparseArrays.SparseMatrixCSC{YBUS_ELTYPE, Int}: Sparse Y-bus matrix with complex admittance valuesadjacency_data::SparseArrays.SparseMatrixCSC{Int8, Int}: Network connectivity informationaxes::Ax: Tuple of bus axis vectors for indexing (busnumbers, busnumbers)lookup::L: Tuple of lookup dictionaries mapping bus numbers to matrix indicessubnetwork_axes::Dict{Int, Ax}: Bus axes for each electrical island/subnetworkarc_subnetwork_axis::Dict{Int, Vector{Tuple{Int, Int}}}: Arc axes for each subnetworknetwork_reduction_data::NetworkReductionData: Metadata from network reduction operationsarc_admittance_from_to::Union{ArcAdmittanceMatrix, Nothing}: From-to arc admittance matrixarc_admittance_to_from::Union{ArcAdmittanceMatrix, Nothing}: To-from arc admittance matrix
Key Features
- Indexed by bus numbers (non-sequential numbering supported)
- Supports network reductions (radial, degree-two, Ward)
- Handles multiple electrical islands/subnetworks
- Optional arc admittance matrices for power flow calculations
- Sparse matrix representation for computational efficiency
Usage
The Y-bus is fundamental for:
- Power flow analysis: V = Y⁻¹I
- Short circuit calculations
- Network impedance analysis
- Sensitivity analysis (PTDF/LODF)
Examples
# Basic Y-bus construction
ybus = Ybus(system)
# With arc admittance matrices for power flow
ybus = Ybus(system; make_arc_admittance_matrices=true)
# With network reductions
ybus = Ybus(system; network_reductions=[RadialReduction(), DegreeTwoReduction()])See Also
PTDF: Power Transfer Distribution FactorsLODF: Line Outage Distribution FactorsNetworkReduction: Network reduction algorithms
PowerNetworkMatrices.Ybus — Method
Ybus(
sys;
make_arc_admittance_matrices,
network_reductions,
include_constant_impedance_loads,
subnetwork_algorithm
)
Ybus(
sys::PSY.System;
make_arc_admittance_matrices::Bool = false,
network_reductions::Vector{NetworkReduction} = NetworkReduction[],
include_constant_impedance_loads::Bool = true,
subnetwork_algorithm = iterative_union_find,
kwargs...
) -> YbusConstruct a nodal admittance matrix (Y-bus) from a power system.
Builds the sparse complex Y-bus matrix representing the electrical admittance relationships between buses in the power system. Handles AC branches, transformers, shunt elements, and network reductions while maintaining connectivity analysis.
Arguments
sys::PSY.System: Power system to build Y-bus from
Keyword arguments
make_arc_admittance_matrices::Bool=false: Whether to construct arc admittance matrices for power flownetwork_reductions::Vector{NetworkReduction}=[]: Network reduction algorithms to applyinclude_constant_impedance_loads::Bool=true: Whether to include constant impedance loads as shunt admittancessubnetwork_algorithm=iterative_union_find: Algorithm for finding electrical islands
Returns
Ybus: Constructed Y-bus matrix with network topology and electrical parameters
Features
- Branch Support: Lines, transformers, phase shifters, three-winding transformers
- Shunt Elements: Fixed admittances, switched admittances, constant impedance loads
- Network Reductions: Radial, degree-two, Ward reductions for computational efficiency
- Multiple Islands: Handles disconnected network components with separate reference buses
- Branch Matrices: Optional from-to/to-from admittance matrices for power flow calculations
Examples
# Basic Y-bus construction
ybus = Ybus(system)
# With arc admittance matrices for power flow
ybus = Ybus(system; make_arc_admittance_matrices=true)
# Apply network reductions for computational efficiency
reductions = [RadialReduction(), DegreeTwoReduction()]
ybus = Ybus(system; network_reductions=reductions)
# Exclude constant impedance loads
ybus = Ybus(system; include_constant_impedance_loads=false)See Also
NetworkReduction: Network reduction algorithmsPTDF: Power transfer distribution factorsLODF: Line outage distribution factors
Base.eachindex — Method
eachindex(vlodf)
Gives the cartesian indexes of the LODF matrix.
Base.eachindex — Method
eachindex(vptdf)
Gives the cartesian indexes of the PTDF matrix (same as the BA one).
Base.empty! — Method
empty!(cache)
Erases the cache.
Base.getindex — Method
getindex(cache, key)
Gets the row of the stored matrix in cache.
Arguments
cache::RowCache: cache where the row vector is going to be savedkey::Int: row number (corresponding to the enumerated branch index) related to the row vector.
Base.getindex — Method
getindex(vlodf, row, column)
Gets the value of the element of the LODF matrix given the row and column indices corresponding to the selected and outage branch respectively. If column is a Colon then the entire row is returned.
Arguments
vlodf::VirtualLODF: VirtualLODF struct where to evaluate and store the row values.row: selected line namecolumn: outage line name. IfColonthen get the values of the whole row.
Base.getindex — Method
getindex(vmodf, monitored_idx, contingency)
Get the post-contingency PTDF row for monitored arc under a ContingencySpec. Delegates to the NetworkModification-based getindex.
getindex(
vmodf::VirtualMODF,
monitored_idx::Int64,
contingency::ContingencySpec
) -> Union{SparseArrays.SparseVector{Float64}, Vector{Float64}}
Base.getindex — Method
getindex(vmodf, monitored_idx, mod)
Get the post-modification PTDF row for monitored arc monitored_idx under mod. Uses per-modification RowCache for LRU-eviction caching.
getindex(
vmodf::VirtualMODF,
monitored_idx::Int64,
mod::NetworkModification
) -> Union{SparseArrays.SparseVector{Float64}, Vector{Float64}}
Base.getindex — Method
getindex(vmodf, monitored, outage)
Get the post-contingency PTDF row for monitored arc monitored when outage outage trips. The outage must have been registered at VirtualMODF construction time.
getindex(
vmodf::VirtualMODF,
monitored::Int64,
outage::PowerSystems.Outage
) -> Union{SparseArrays.SparseVector{Float64}, Vector{Float64}}
Base.getindex — Method
getindex(vmodf, monitored, mod)
Arc-tuple indexed version of getindex for VirtualMODF with NetworkModification.
getindex(
vmodf::VirtualMODF,
monitored::Tuple{Int64, Int64},
mod::NetworkModification
) -> Union{SparseArrays.SparseVector{Float64}, Vector{Float64}}
Base.getindex — Method
getindex(vmodf, monitored, outage)
Arc-tuple indexed version of getindex by PSY.Outage.
getindex(
vmodf::VirtualMODF,
monitored::Tuple{Int64, Int64},
outage::PowerSystems.Outage
) -> Union{SparseArrays.SparseVector{Float64}, Vector{Float64}}
Base.getindex — Method
getindex(vptdf, row, column)
Gets the value of the element of the PTDF matrix given the row and column indices corresponding to the branch and buses one respectively. If column is a Colon then the entire row is returned.
Arguments
vptdf::VirtualPTDF: VirtualPTDF struct where to evaluate and store the row values.row: Branch index.column: Bus index. If Colon then get the values of the whole row.
Base.getindex — Method
getindex(vptdf, monitored, mod)
getindex(vptdf::VirtualPTDF, monitored::Int, mod::NetworkModification) -> Vector{Float64}Indexing overload for post-modification PTDF row queries. Dispatches to get_post_modification_ptdf_row.
getindex(
vptdf::VirtualPTDF,
monitored::Int64,
mod::NetworkModification
) -> Vector{Float64}
Base.haskey — Method
haskey(cache, key)
Checks if key is present as a key of the dictionary in cache
Arguments
cache::RowCache: cache where data is stored.key::Int: row number (corresponds to the enumerated branch index).
Base.isempty — Method
isempty(cache)
Check if cache is empty.
Base.isempty — Method
isempty(vlodf)
Checks if the any of the fields of VirtualLODF is empty.
Base.isempty — Method
isempty(vptdf)
Checks if the any of the fields of VirtualPTDF is empty.
Base.length — Method
length(cache)
Shows the number of rows stored in cache
Base.setindex! — Method
setindex!(_, _, _)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Method
setindex!(_, _, idx)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Method
setindex!(_, _, _)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Method
setindex!(_, _, idx)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Method
setindex!(cache, val, key)
Allocates vector as row of the matrix saved in cache.
Arguments
cache::RowCache: cache where the row vector is going to be savedval::Union{Vector{Float64}, SparseArrays.SparseVector{Float64}}: vector to be savedkey::Int: row number (corresponding to the enumerated branch index) related to the input row vector
PowerNetworkMatrices._apply_woodbury_correction — Method
_apply_woodbury_correction(mat, monitored_idx, wf)
_apply_woodbury_correction(mat, monitored_idx, wf) -> Vector{Float64}Compute the post-modification PTDF row for a monitored arc using precomputed Woodbury factors.
Post-modification PTDF: PTDF_m[mon,:] = b_mon_post · ν_mon⊤ · B_m⁻¹ Computed as: b_mon_post · (z_m - Z · W⁻¹ · (ν_mon⊤ · Z))
PowerNetworkMatrices._assert_not_phase_shifting — Method
_assert_not_phase_shifting(_)
_assert_not_phase_shifting(component::PSY.ACTransmission)No-op for non-PST branches. Throws ErrorException for PhaseShiftingTransformer.
PowerNetworkMatrices._build_row_to_cols — Method
_build_row_to_cols(A, buscount)
Pre-compute a mapping from each row (branch) in a CSC sparse matrix to its two column (bus) endpoints. This avoids the expensive A[row, :].nzind operation on CSC matrices which requires a full scan of all columns (O(nnz) per call).
Returns a Vector where index row gives (col1, col2) — the two bus columns connected by that branch.
PowerNetworkMatrices._calculate_PTDF_matrix_DENSE — Method
_calculate_PTDF_matrix_DENSE(
A,
BA,
ref_bus_positions,
dist_slack
)
Function for internal use only.
Computes the PTDF matrix by means of the LAPACK and BLAS functions for dense matrices.
Arguments
A::Matrix{Int8}: Incidence MatrixBA::Matrix{T} where {T <: Union{Float32, Float64}}: BA matrixref_bus_positions::Set{Int}: vector containing the indexes of the reference slack buses.dist_slack::Vector{Float64}): vector containing the weights for the distributed slacks.
PowerNetworkMatrices._calculate_PTDF_matrix_KLU — Method
_calculate_PTDF_matrix_KLU(
A,
BA,
ref_bus_positions,
dist_slack
)
Function for internal use only.
Computes the PTDF matrix by means of the KLU.LU factorization for sparse matrices.
Arguments
A::SparseArrays.SparseMatrixCSC{Int8, Int}: Incidence MatrixBA::SparseArrays.SparseMatrixCSC{Float64, Int}: BA matrixref_bus_positions::Set{Int}: vector containing the indexes of the reference slack buses.dist_slack::Vector{Float64}: vector containing the weights for the distributed slacks.
PowerNetworkMatrices._classify_branch_modification — Method
_classify_branch_modification(_, _, _, branch)
_classify_branch_modification(nr, arc_lookup, arc_susceptances, branch) -> Vector{ArcModification}Classify a single branch component into the appropriate arc modification using the network reduction reverse maps. For single-branch modifications only; use _classify_outage_component! for multi-component outages with series grouping.
PowerNetworkMatrices._classify_outage_component! — Method
_classify_outage_component!(
_,
_,
_,
_,
component,
_,
_,
_,
_,
_,
_
)
_classify_outage_component!(nr, arc_lookup, arc_sus, bus_lookup, component, ...) -> nothingClassify a single outage component via multiple dispatch. ACTransmission branches are classified into direct/parallel/series arc modifications. Shunt components produce diagonal admittance changes. Unsupported component types are silently ignored.
PowerNetworkMatrices._compute_arc_ybus_delta — Method
_compute_arc_ybus_delta(nr, arc_tuple, delta_b)
_compute_arc_ybus_delta(nr, arc_tuple, delta_b) -> NTuple{4, YBUS_ELTYPE}Compute the Pi-model Ybus delta (ΔY11, ΔY12, ΔY21, ΔY22) for an arc modification. Dispatches on the branch map that contains arc_tuple and handles full vs partial outages.
PowerNetworkMatrices._compute_modf_entry — Method
_compute_modf_entry(vmodf, monitored_idx, mod)
_compute_modf_entry(vmodf, monitored_idx, mod) -> Vector{Float64}Compute the post-modification PTDF row for a monitored arc under the given modification. Gets or computes Woodbury factors, then applies the Woodbury correction.
For N-1 contingencies, the result satisfies: postptdf[mon, :] = preptdf[mon, :] + LODF[mon, e] * pre_ptdf[e, :]
PowerNetworkMatrices._compute_parallel_partial_ybus_delta — Method
_compute_parallel_partial_ybus_delta(bp, delta_b)
_compute_parallel_partial_ybus_delta(bp, delta_b) -> NTuple{4, YBUS_ELTYPE}Compute the Pi-model Ybus delta for a partial outage on a parallel branch group. Finds the circuit whose susceptance matches delta_b and returns its negated Pi-model entries.
PowerNetworkMatrices._compute_series_outage_delta_b — Method
_compute_series_outage_delta_b(series_chain, component)
_compute_series_outage_delta_b(series_chain::BranchesSeries, component::PSY.ACTransmission) -> Float64Compute the change in equivalent arc susceptance when component is tripped from series_chain. Delegates to the vector version.
PowerNetworkMatrices._compute_series_outage_delta_b — Method
_compute_series_outage_delta_b(series_chain, tripped)
_compute_series_outage_delta_b(series_chain::BranchesSeries, tripped::Vector{<:PSY.ACTransmission}) -> Float64Compute the change in equivalent arc susceptance when multiple components are simultaneously tripped from a series chain.
For a series chain with segments of susceptance b₁, b₂, ..., bₙ, the equivalent susceptance is: b_eq = 1 / (1/b₁ + 1/b₂ + ... + 1/bₙ).
Segments can be individual branches or BranchesParallel groups. When a tripped component is inside a parallel group, only that branch's susceptance is removed from the group — the rest of the parallel group remains in the series chain.
Returns Δb = bnew - bold (always negative for outages). If all segments are fully tripped, returns -b_eq (full arc outage).
PowerNetworkMatrices._compute_woodbury_factors — Method
_compute_woodbury_factors(mat, modifications)
_compute_woodbury_factors(mat, modifications) -> WoodburyFactorsCompute the Woodbury correction factors for a set of arc modifications. Implements van Dijk et al. Eq. 29: Bm⁻¹ = Br⁻¹ - Br⁻¹U (A⁻¹ + U⊤Br⁻¹U)⁻¹ U⊤B_r⁻¹
where U = [ν{e1} ... ν{eM}] and A = diag(Δb₁, ..., Δb_M).
The expensive part (M KLU solves + M×M factorization) is shared across all monitored arcs for a given modification set.
PowerNetworkMatrices._extract_arc_susceptances — Method
_extract_arc_susceptances(BA)
Extract the effective susceptance for each arc from the BA matrix. For arc j, the susceptance is the absolute value of the first nonzero in BA column j. BA columns always have the structure [+b, -b] (from-bus and to-bus entries), so both nonzeros have the same magnitude.
PowerNetworkMatrices._extract_branch_susceptances_by_arc — Method
_extract_branch_susceptances_by_arc(BA, arc_ax, nr_data)
_extract_branch_susceptances_by_arc(BA, arc_ax, nr_data) -> Vector{Vector{Float64}}Extract per-branch susceptances for each arc. For arcs with a single branch, returns a one-element vector equal to the arc susceptance. For arcs with parallel branches (double circuits), returns one entry per branch. For arcs with series-reduced branches (D2 reduction), returns one entry per segment.
This enables single-branch contingencies on parallel and series-reduced arcs.
PowerNetworkMatrices._get_complete_chain — Method
_get_complete_chain(
adj_matrix,
start_node,
reduced_indices,
irreducible_indices
)
_get_complete_chain(adj_matrix::SparseArrays.SparseMatrixCSC, start_node::Int, reduced_indices::Set{Int}, irreducible_indices::Set{Int})Build a complete chain of degree-2 nodes starting from a given node.
PowerNetworkMatrices._get_degree2_nodes — Method
_get_degree2_nodes(adj_matrix, irreducible_indices)
_get_degree2_nodes(adj_matrix::SparseArrays.SparseMatrixCSC, irreducible_indices::Set{Int})Return all degree-2 nodes in the adjacency matrix, excluding irreducible indices.
PowerNetworkMatrices._get_equivalent_physical_branch_parameters — Method
_get_equivalent_physical_branch_parameters(equivalent_ybus)
_get_equivalent_physical_branch_parameters(equivalent_ybus::Matrix{ComplexF32})Takes as input a 2x2 Matrix{ComplexF32} representing the Ybus contribution of either a BranchesParallel or BranchesSeries object. Returns a dictionary of equivalent parameters, matching the PowerModels data format.
PowerNetworkMatrices._get_neighbors — Method
_get_neighbors(adj_matrix, node)
_get_neighbors(adj_matrix::SparseArrays.SparseMatrixCSC, node::Int)Get all neighbors of a given node from the adjacency matrix. For undirected graphs, checks both directions.
PowerNetworkMatrices._get_or_create_row_cache — Method
_get_or_create_row_cache(vmodf, mod)
_get_or_create_row_cache(vmodf, mod) -> RowCacheGet or create the per-modification RowCache for the given modification.
PowerNetworkMatrices._get_partial_chain_recursive! — Method
_get_partial_chain_recursive!(
current_chain,
adj_matrix,
current_node,
prev_node,
reduced_indices,
irreducible_indices
)
_get_partial_chain(adj_matrix::SparseArrays.SparseMatrixCSC,
current_node::Int,
prev_node::Int,
reduced_indices::Set{Int},
irreducible_indices::Set{Int})Recursively build a chain in one direction from currentnode, avoiding prevnode.
PowerNetworkMatrices._get_woodbury_factors — Method
_get_woodbury_factors(vmodf, mod)
_get_woodbury_factors(vmodf, mod) -> WoodburyFactorsCompute and cache the Woodbury factors for a network modification. Delegates to the shared Woodbury kernel _compute_woodbury_factors. Caches by content hash of the modification.
PowerNetworkMatrices._getindex_partial — Method
_getindex_partial(vlodf, arc_idx, delta_b)
_getindex_partial(vlodf, arc_idx, delta_b) -> Vector{Float64}Compute the partial LODF column for a susceptance change delta_b on arc arc_idx.
This function is NOT thread-safe. It mutates vlodf.work_ba_col and vlodf.temp_data on every call. Do not call concurrently on the same VirtualLODF instance from multiple threads.
Uses the Sherman-Morrison (matrix inversion lemma) formula derived from DC power flow sensitivity analysis. For a change Δb in the susceptance of arc e, the change in flow on monitoring arc ℓ per unit pre-change flow on arc e is:
partial_LODF[ℓ, e] = α · (b_ℓ / b_e) · H[ℓ,e] / (1 - α · H[e,e])where:
- α = -Δb / b_e (positive for outage/decrease, negative for increase)
- H[ℓ, e] = (A · (ABA)⁻¹ · BA)[ℓ, e] = b_e · C[e, ℓ] (computed via KLU solve)
- b_ℓ = susceptance of monitoring arc ℓ
- H[e,e] = PTDFAdiag[e]
When delta_b = -b_e (full outage), α = 1 and this reduces to the standard LODF column: LODF[ℓ, e] = bℓ · C[e, ℓ] / (1 - H[e,e]) When `deltab = 0`, returns zeros (no change). The self-element (ℓ = e) is overridden to -1.0 for full outage per standard LODF convention.
PowerNetworkMatrices._invert_woodbury_W — Method
_invert_woodbury_W(W_mat, _)
_invert_woodbury_W(W_mat, ::Val{M}) -> (W_inv::Matrix{Float64}, is_islanding::Bool)Invert the M×M Woodbury W matrix. Dispatches on Val{M} so the compiler can specialize each case. Analytical formulas for M=1 and M=2 avoid LU factorization overhead. Falls back to LU for M > 2.
PowerNetworkMatrices._is_2degree_node — Method
_is_2degree_node(adj_matrix, node)
_is_2degree_node(adj_matrix::SparseArrays.SparseMatrixCSC, node::Int)Checks if a node has exactly two connections in the network.
Arguments
adj_matrix::SparseArrays.SparseMatrixCSC: The adjacency matrix of the network.node::Int: The index of the node to check.
Returns
Bool:trueif the node has exactly two neighbors,falseotherwise.
PowerNetworkMatrices._is_final_node — Method
_is_final_node(
node,
adj_matrix,
reduced_indices,
irreducible_indices
)
_is_final_node(node::Int, adj_matrix::SparseArrays.SparseMatrixCSC, reduced_indices::BitVector, irreducible_indices::BitVector)Determines if a node is a final node in a path traversal.
Arguments
node::Int: The index of the node to check.adj_matrix::SparseArrays.SparseMatrixCSC: The adjacency matrix of the network.reduced_indices::BitVector: Bitmask of indices that have already been reduced.irreducible_indices::BitVector: Bitmask of indices that should not be reduced.
Returns
Bool:trueif the node is a final node,falseotherwise.
PowerNetworkMatrices._merge_arc_modifications — Method
_merge_arc_modifications(mods)
Merge ArcModifications that target the same arc index.
PowerNetworkMatrices._merge_shunt_modifications — Method
_merge_shunt_modifications(mods)
Merge ShuntModifications that target the same bus index, sorted by bus index.
PowerNetworkMatrices._register_outage! — Method
_register_outage!(vmodf, sys, outage)
_register_outage!(vmodf, sys, outage) -> ContingencySpecResolve an Outage supplemental attribute to a ContingencySpec and cache it. Delegates to NetworkModification(mat, sys, outage) for the resolution logic.
PowerNetworkMatrices._register_outages! — Method
_register_outages!(vmodf, sys)
_register_outages!(vmodf, sys)Bulk-register all Outage supplemental attributes in the system. Called automatically by the VirtualMODF constructor.
Uses PSY.get_supplemental_attributes(PSY.Outage, sys) which accepts the abstract type and iterates over all concrete subtypes (PlannedOutage, UnplannedOutage).
PowerNetworkMatrices._resolve_branch_arc — Method
_resolve_branch_arc(nr, component)
_resolve_branch_arc(nr::NetworkReductionData, component::PSY.ACTransmission)
-> Tuple{Symbol, Union{Tuple{Int, Int}, Nothing}}Classify a branch component by looking up which reverse map it belongs to in the NetworkReductionData. Returns (tag, arc_tuple) where tag is one of:
:direct– branch is the sole branch on its arc:parallel– branch is one of several parallel branches on its arc:series– branch is part of a series chain on its arc:transformer3w– branch is a three-winding transformer winding:not_found– branch is not in any map (e.g., eliminated by radial reduction)
The second element is the arc tuple (from_bus, to_bus), or nothing when :not_found.
PowerNetworkMatrices._segment_susceptance_after_outage — Method
_segment_susceptance_after_outage(segment, tripped_set)
_segment_susceptance_after_outage(segment, tripped_set) -> Float64Compute the remaining susceptance of a series chain segment after removing tripped components. Dispatches on segment type to handle both single branches and parallel groups within a series chain.
Returns 0.0 if the segment (or all branches in a parallel group) is fully tripped.
PowerNetworkMatrices._should_visit_node — Method
_should_visit_node(
node,
reduced_indices,
irreducible_indices
)
_should_visit_node(node::Int, reduced_indices::BitVector, irreducible_indices::BitVector)Determines whether a node should be visited during network traversal.
Arguments
node::Int: The index of the node to check.reduced_indices::BitVector: Bitmask of indices that have already been reduced.irreducible_indices::BitVector: Bitmask of indices that cannot be reduced.
Returns
Bool:trueif the node should be visited,falseotherwise.
PowerNetworkMatrices._update_bus_maps! — Method
_update_bus_maps!(
reverse_bus_search_map,
bus_reduction_map,
b1_number,
b2_number
)
Updates both existing bus maps (forward and reverse) for a new reduction of bus b1 into bus b2. Handles both the case where b2 is already reduced and the case where it is not.
PowerNetworkMatrices._validate_study_buses — Method
_validate_study_buses(ybus, study_buses)
_validate_study_buses(ybus::Ybus, study_buses::Vector{Int}) -> Union{Int, Nothing}Validate that Ward reduction study buses are compatible with the network islands.
Checks that all study buses exist in the reduced/unreduced bus maps, that they lie in a single synchronously connected subnetwork, and that any partially reduced subnetwork includes its slack bus. Returns the reference-bus key of the matching subnetwork when validation succeeds.
Errors
- Throws
IS.DataFormatErrorif any study bus is not present in the system. - Throws
IS.DataFormatErrorif study buses span multiple subnetworks. - Throws
IS.DataFormatErrorif a partially reduced subnetwork excludes its slack bus.
PowerNetworkMatrices._validate_system_uuid — Method
_validate_system_uuid(mat, sys)
_validate_system_uuid(mat::PowerNetworkMatrix, sys::PSY.System)Validate that the matrix was constructed from the same system. Throws an ErrorException if the matrix stores a system UUID that does not match the UUID of sys. No-op when the matrix does not track system origin.
PowerNetworkMatrices._ybus! — Method
_ybus!(
y11,
y12,
y21,
y22,
br,
num_bus,
branch_ix,
fb,
tb,
nr,
adj
)
Handles ybus entries for most 2-node AC branches. The types handled here are: Line, DiscreteControlledACBranch, Transformer2W, TapTransformer, and PhaseShiftingTransformer.
PowerNetworkMatrices.add_branch_entries_to_indexing_maps! — Method
add_branch_entries_to_indexing_maps!(
num_bus,
branch_ix,
nr,
fb,
tb,
adj,
br
)
add_branch_entries_to_indexing_maps!(
num_bus::Dict{Int, Int},
branch_ix::Int,
nr::NetworkReductionData,
fb::Vector{Int},
tb::Vector{Int},
adj::SparseArrays.SparseMatrixCSC{Int8, Int},
br::PSY.ACTransmission
)Update indexing structures when adding an AC transmission branch to the Y-bus.
This function handles the bookkeeping required when adding a branch: updates network reduction mappings, sets adjacency matrix entries, and records from/to bus indices for the branch in the Y-bus construction vectors.
Arguments
num_bus::Dict{Int, Int}: Mapping from bus numbers to matrix indicesbranch_ix::Int: Branch index in the vectorsnr::NetworkReductionData: Network reduction data to updatefb::Vector{Int}: Vector of from-bus indicestb::Vector{Int}: Vector of to-bus indicesadj::SparseArrays.SparseMatrixCSC{Int8, Int}: Adjacency matrixbr::PSY.ACTransmission: AC transmission branch to add
Implementation Details
- Calls
add_to_branch_maps!()to update reduction mappings - Updates adjacency matrix with branch connectivity
- Records bus indices in from/to vectors for sparse matrix construction
PowerNetworkMatrices.add_branch_entries_to_ybus! — Method
add_branch_entries_to_ybus!(
y11,
y12,
y21,
y22,
branch_ix,
br
)
add_branch_entries_to_ybus!(
y11::Vector{YBUS_ELTYPE},
y12::Vector{YBUS_ELTYPE},
y21::Vector{YBUS_ELTYPE},
y22::Vector{YBUS_ELTYPE},
branch_ix::Int,
br::PSY.ACTransmission
)Add Y-bus matrix entries for an AC transmission branch to the admittance vectors.
This function calculates the 2×2 Y-bus entries for a branch using ybus_branch_entries() and stores them in the provided vectors at the specified index. The entries represent the Pi-model admittances: Y11 (from-bus self), Y12 (from-to mutual), Y21 (to-from mutual), and Y22 (to-bus self).
Arguments
y11::Vector{YBUS_ELTYPE}: Vector for from-bus self admittancesy12::Vector{YBUS_ELTYPE}: Vector for from-to mutual admittancesy21::Vector{YBUS_ELTYPE}: Vector for to-from mutual admittancesy22::Vector{YBUS_ELTYPE}: Vector for to-bus self admittancesbranch_ix::Int: Index where to store the branch entriesbr::PSY.ACTransmission: AC transmission branch
Implementation Details
- Calls
ybus_branch_entries()to compute Pi-model parameters - Stores results directly in the provided vectors
- Used during Y-bus matrix assembly process
PowerNetworkMatrices.add_segment_to_ybus! — Method
add_segment_to_ybus!(
segment,
y11,
y12,
y21,
y22,
fb,
tb,
ix,
segment_orientation
)
add_segment_to_ybus!(
segment::BranchesParallel,
y11::Vector{YBUS_ELTYPE},
y12::Vector{YBUS_ELTYPE},
y21::Vector{YBUS_ELTYPE},
y22::Vector{YBUS_ELTYPE},
fb::Vector{Int},
tb::Vector{Int},
ix::Int,
segment_orientation::Symbol
)Add multiple parallel branches as a single segment to Y-bus vectors.
Handles the case where a segment in a series chain consists of multiple parallel branches between the same pair of buses. Each branch in the set is added to the same Y-bus position, effectively combining their admittances.
Arguments
segment::BranchesParallel: Set of parallel AC transmission branchesy11::Vector{YBUS_ELTYPE}: Vector for from-bus self admittancesy12::Vector{YBUS_ELTYPE}: Vector for from-to mutual admittancesy21::Vector{YBUS_ELTYPE}: Vector for to-from mutual admittancesy22::Vector{YBUS_ELTYPE}: Vector for to-bus self admittancesfb::Vector{Int}: Vector for from-bus indicestb::Vector{Int}: Vector for to-bus indicesix::Int: Index position for the segmentsegment_orientation::Symbol::FromToor:ToFromorientation
Implementation Details
- Iterates through all branches in the parallel set
- Calls single-branch
add_segment_to_ybus!()for each branch - Y-bus entries are accumulated at the same index position
- Results in equivalent admittance of parallel combination
See Also
add_segment_to_ybus!: Single branch variantDegreeTwoReduction: Series chain elimination
PowerNetworkMatrices.add_segment_to_ybus! — Method
add_segment_to_ybus!(
segment,
y11,
y12,
y21,
y22,
fb,
tb,
ix,
segment_orientation
)
add_segment_to_ybus!(
segment::PSY.ACTransmission
y11::Vector{YBUS_ELTYPE},
y12::Vector{YBUS_ELTYPE},
y21::Vector{YBUS_ELTYPE},
y22::Vector{YBUS_ELTYPE},
fb::Vector{Int},
tb::Vector{Int},
ix::Int,
segment_orientation::Symbol
)Add a branch segment to Y-bus vectors during series chain reduction.
Adds the Y-bus entries for a single segment (branch or transformer winding) to the admittance vectors, handling the proper orientation. Used when building equivalent Y-bus entries for series chains of degree-two buses.
Arguments
segment::Union{PSY.ACTransmission, Tuple{PSY.ThreeWindingTransformer, Int}}: Branch segment to addy11::Vector{YBUS_ELTYPE}: Vector for from-bus self admittancesy12::Vector{YBUS_ELTYPE}: Vector for from-to mutual admittancesy21::Vector{YBUS_ELTYPE}: Vector for to-from mutual admittancesy22::Vector{YBUS_ELTYPE}: Vector for to-bus self admittancesfb::Vector{Int}: Vector for from-bus indicestb::Vector{Int}: Vector for to-bus indicesix::Int: Index position for the segmentsegment_orientation::Symbol::FromToor:ToFromorientation
Implementation Details
- Computes Pi-model entries using
ybus_branch_entries() - Handles orientation by swapping entries for
:ToFrom - Sets bus indices to consecutive values (ix, ix+1) for chain building
- Used in degree-two network reduction algorithms
See Also
DegreeTwoReduction: Degree-two bus eliminationybus_branch_entries: Pi-model computation
PowerNetworkMatrices.add_to_branch_maps! — Method
add_to_branch_maps!(
nr,
primary_star_arc,
secondary_star_arc,
tertiary_star_arc,
br
)
add_to_branch_maps!(
nr::NetworkReductionData,
primary_star_arc::PSY.Arc,
secondary_star_arc::PSY.Arc,
tertiary_star_arc::PSY.Arc,
br::PSY.ThreeWindingTransformer
)Add a three-winding transformer to the transformer mapping in NetworkReductionData.
Three-winding transformers are modeled using a star (wye) configuration with three arcs connecting to a virtual star bus. Each available winding is mapped separately.
Arguments
nr::NetworkReductionData: Network reduction data to modifyprimary_star_arc::PSY.Arc: Arc for primary windingsecondary_star_arc::PSY.Arc: Arc for secondary windingtertiary_star_arc::PSY.Arc: Arc for tertiary windingbr::PSY.ThreeWindingTransformer: Three-winding transformer to add
Implementation Details
- Only adds arcs for available windings (checked via PSY.getavailable*)
- Maintains transformer3Wmap and reversetransformer3W_map
- Each winding is numbered (1=primary, 2=secondary, 3=tertiary)
PowerNetworkMatrices.add_to_branch_maps! — Method
add_to_branch_maps!(nr, arc, br)
add_to_branch_maps!(nr::NetworkReductionData, arc::PSY.Arc, br::PSY.ACTransmission)Add an AC transmission branch to the appropriate branch mapping in NetworkReductionData.
This function categorizes branches as direct (one-to-one), parallel (multiple branches between same buses), or creates new mappings as needed. It maintains both forward and reverse lookup dictionaries for efficient access.
Arguments
nr::NetworkReductionData: Network reduction data to modifyarc::PSY.Arc: Arc representing the branch connectionbr::PSY.ACTransmission: AC transmission branch to add
Implementation Details
- If arc already has a direct branch, converts to parallel mapping
- If arc already has parallel branches, adds to existing set
- Otherwise creates new direct mapping
- Maintains reverse lookup consistency
PowerNetworkMatrices.apply_woodbury_correction — Method
apply_woodbury_correction(vptdf, monitored_arc, wf)
apply_woodbury_correction(vptdf, monitored_arc, wf) -> Vector{Float64}Compute the post-modification PTDF row for a monitored arc using precomputed Woodbury factors. Accepts either an integer arc index or a Tuple{Int, Int} bus pair.
Not thread-safe. Mutates scratch vectors in vptdf. Do not call concurrently on the same VirtualPTDF instance.
apply_woodbury_correction(
vptdf::VirtualPTDF,
monitored_arc::Int64,
wf::PowerNetworkMatrices.WoodburyFactors
) -> Vector{Float64}
PowerNetworkMatrices.apply_ybus_modification — Method
apply_ybus_modification(ybus, mod)
apply_ybus_modification(ybus::Ybus, mod::NetworkModification) -> SparseMatrixCSCApply a canonical NetworkModification to a Ybus, returning the modified sparse matrix. Convenience wrapper around compute_ybus_delta.
PowerNetworkMatrices.assign_reference_buses! — Method
assign_reference_buses!(subnetworks, ref_buses)
Takes the reference bus numbers and re-assigns the keys in the subnetwork dictionaries to use the reference bus withing each subnetwork.
PowerNetworkMatrices.build_reduced_ybus — Method
build_reduced_ybus(ybus, sys, network_reduction)
build_reduced_ybus(
ybus::Ybus,
sys::PSY.System,
network_reduction::NetworkReduction
) -> YbusApply a network reduction algorithm to a Y-bus matrix.
Computes the network reduction data using the specified reduction algorithm and then applies the reduction to create a new Y-bus matrix with eliminated buses and branches. The electrical behavior of the remaining network is preserved.
Arguments
ybus::Ybus: Original Y-bus matrix to reducesys::PSY.System: Power system for validation and data accessnetwork_reduction::NetworkReduction: Reduction algorithm to apply
Returns
Ybus: New reduced Y-bus matrix with eliminated elements
Implementation Details
- Calls
get_reduction()to compute elimination data - Applies reduction via
_apply_reduction() - Preserves electrical equivalence of remaining network
- Updates all indexing and mapping structures
Examples
ybus = Ybus(system)
reduction = RadialReduction()
reduced_ybus = build_reduced_ybus(ybus, system, reduction)
println("Original buses: ", length(get_bus_axis(ybus)))
println("Reduced buses: ", length(get_bus_axis(reduced_ybus)))See Also
NetworkReduction: Reduction algorithm typesget_reduction: Reduction data computation
PowerNetworkMatrices.calculate_ABA_matrix — Method
calculate_ABA_matrix(A, BA, ref_bus_positions)
Evaluates the ABA matrix given the System's Incidence matrix (A), BA matrix and reference bus positions.
Arguments
A::SparseArrays.SparseMatrixCSC{Int8, Int}: Incidence matrix.BA::SparseArrays.SparseMatrixCSC{Float64, Int}BA matrix.
NOTE:
- evaluates A with "calculateAmatrix", or extract A.data (if A::IncidenceMatrix)
- evaluates BA with "calculateBAmatrix", or extract BA.data (if A::BA_Matrix)
PowerNetworkMatrices.calculate_radial_arcs — Method
calculate_radial_arcs(
A,
arc_map,
bus_map,
ref_bus_positions
)
calculate_radial_arcs(A::SparseArrays.SparseMatrixCSC{Int8, Int}, arc_map::Dict{Tuple{Int, Int}, Int}, bus_map::Dict{Int, Int}, ref_bus_positions::Set{Int})Identify and calculate radial branches and buses that can be eliminated from the network model by analyzing the topological structure of the incidence matrix. Radial elements are leaf nodes with only one connection that do not affect the electrical behavior of the core network.
Arguments
A::SparseArrays.SparseMatrixCSC{Int8, Int}: The incidence matrix data representing bus-branch connectivity structurearc_map::Dict{Tuple{Int, Int}, Int}: Dictionary mapping branch endpoint pairs (frombus, tobus) to matrix row indicesbus_map::Dict{Int, Int}: Dictionary mapping bus numbers to matrix column indicesref_bus_positions::Set{Int}: Set of matrix column indices corresponding to reference (slack) buses that cannot be eliminated
Returns
bus_reduction_map::Dict{Int, Set{Int}}: Dictionary mapping parent bus numbers to sets of child buses that can be reduced to the parentreverse_bus_search_map::Dict{Int, Int}: Dictionary mapping each bus number to its ultimate parent bus after all reductionsradial_arcs::Set{Tuple{Int, Int}}: Set of branch endpoint pairs representing radial branches that can be eliminatedfinal_arc_map::Dict{Tuple{Int, Int}, Int}: Dictionary mapping each final arc to the surviving bus number it connects to (the arc whose admittance must be subtracted from the surviving bus's diagonal)
Algorithm Overview
- Adjacency Pre-computation: Builds adjacency lists from the incidence matrix to avoid expensive sparse row access operations on the CSC matrix
- Leaf Detection: Identifies buses with exactly one connection (radial buses)
- Reference Protection: Preserves reference buses from elimination regardless of connectivity
- Iterative Chain Walking: Uses a queue-based approach to trace from radial buses toward the core network, walking through chains of degree-2 buses
- Cascading Reduction: Eliminates buses that become radial after initial reductions
Network Topology Preservation
- Electrical Equivalence: Ensures reduced network maintains same electrical behavior
- Connectivity Integrity: Preserves essential network connectivity and reference structure
- Reduction Validity: Only eliminates elements that truly don't affect network analysis
- Reversibility: Maintains mapping information for potential reconstruction if needed
Use Cases
- Network Simplification: Reduces computational burden by eliminating unnecessary elements
- Matrix Conditioning: Improves numerical properties of network matrices
- Analysis Acceleration: Speeds up power flow and other network computations
- Memory Optimization: Reduces storage requirements for large network models
Implementation Notes
- Pre-computes row-to-column mapping for O(1) branch endpoint lookup instead of O(nnz) sparse row access
- Uses iterative queue-based processing instead of recursive DFS for better performance
- Handles edge cases like fully radial networks and isolated islands
- Provides comprehensive mapping for traceability and debugging
PowerNetworkMatrices.check_cache_size! — Method
check_cache_size!(cache; new_add)
Check saved rows in cache and delete one not belonging to persistent_cache_keys.
PowerNetworkMatrices.check_linalg_backend — Method
Check for the recommended linear algebra sparse solver option for the user's operating system and whether it matches their preferred one.
PowerNetworkMatrices.clear_all_caches! — Method
clear_all_caches!(vmodf)
clear_all_caches!(vmodf::VirtualMODF)Clear all caches including contingency registrations. After calling this function, the VirtualMODF object is effectively empty and cannot be queried — it has no registered contingencies. To restore functionality, a new VirtualMODF must be constructed from a PSY.System.
Use clear_caches! instead to preserve contingency registrations while freeing computation cache memory.
PowerNetworkMatrices.clear_caches! — Method
clear_caches!(vmodf)
clear_caches!(vmodf::VirtualMODF)Clear Woodbury and row caches. Does NOT clear the contingency registration cache — registered outages remain valid and can be queried again.
PowerNetworkMatrices.compute_woodbury_factors — Method
compute_woodbury_factors(vptdf, mod)
compute_woodbury_factors(vptdf, mod) -> WoodburyFactorsPrecompute Woodbury correction factors for a network modification. The returned WoodburyFactors can be reused across multiple monitored arcs, making this the recommended path for optimization loops where factors are computed once per modification and many rows are queried.
Not thread-safe. Mutates scratch vectors in vptdf. Do not call concurrently on the same VirtualPTDF instance.
compute_woodbury_factors(
vptdf::VirtualPTDF,
mod::NetworkModification
) -> PowerNetworkMatrices.WoodburyFactors
PowerNetworkMatrices.compute_ybus_delta — Method
compute_ybus_delta(ybus, mod)
compute_ybus_delta(ybus::Ybus, mod::NetworkModification) -> SparseMatrixCSC{YBUS_ELTYPE, Int}Compute the sparse ΔYbus matrix from a canonical NetworkModification. Combines arc modifications (branch outages producing Pi-model deltas) and shunt modifications (diagonal admittance changes) into a single sparse delta.
This is the bridge between the DC sensitivity path (NetworkModification) and the AC admittance path (Ybus). The NetworkModification is the canonical representation; this function converts it to the Ybus domain.
PowerNetworkMatrices.depth_first_search — Method
depth_first_search(M, bus_numbers)
depth_first_search(M::SparseArrays.SparseMatrixCSC, bus_numbers::Vector{Int})Find connected subnetworks using depth-first search algorithm.
Arguments
M::SparseArrays.SparseMatrixCSC: Sparse matrix representing network connectivitybus_numbers::Vector{Int}: Vector containing the bus numbers of the system
Returns
Dict{Int, Set{Int}}: Dictionary mapping representative bus numbers to sets of connected buses
PowerNetworkMatrices.factorize — Method
factorize(ABA)
Evaluates the LU factorization matrices of the ABA matrix, using KLU.
Arguments
ABA::ABA_Matrix{Ax, L, Nothing} where {Ax, L <: NTuple{2, Dict}}: container for the ABA matrix, with ABA.K == nothing (LU matrices in K not evaluated)
PowerNetworkMatrices.find_degree2_chains — Method
find_degree2_chains(adj_matrix, irreducible_indices)
find_degree2_chains(adj_matrix::SparseArrays.SparseMatrixCSC, irreducible_indices::Set{Int})Find all chains of degree-2 nodes in a graph represented by a CSC adjacency matrix. A chain is a sequence of connected degree-2 nodes.
Returns a dictionary mapping each starting node to its chain of node indices.
PowerNetworkMatrices.find_slack_positions — Method
find_slack_positions(buses)
Gets the indices of the reference (slack) buses. NOTE:
- the indices corresponds to the columns of zeros belonging to the PTDF matrix.
- BA and ABA matrix miss the columns related to the reference buses.
PowerNetworkMatrices.find_subnetworks — Method
find_subnetworks(M)
Evaluates subnetworks by looking for the subsets of buses connected each other, but not connected with buses of other subsets.
PowerNetworkMatrices.find_subnetworks — Method
find_subnetworks(sys)
Finds the subnetworks in a system using Depth First Search (DFS). Returns a dictionary keyed by the reference bus of the subnetworks if they exist
PowerNetworkMatrices.find_subnetworks — Method
find_subnetworks(M, bus_numbers; subnetwork_algorithm)
Finds the subnetworks present in the considered System. This is evaluated by taking a the ABA or Adjacency Matrix.
Arguments
M::SparseArrays.SparseMatrixCSC: input sparse matrix.bus_numbers::Vector{Int}: vector containing the indices of the system's buses.subnetwork_algorithm::Function: algorithm for computing subnetworks. Valid options are iterativeunionfind (default) and depthfirstsearch
PowerNetworkMatrices.find_subnetworks — Method
find_subnetworks(M)
find_subnetworks(M::Ybus) -> Dict{Int, Set{Int}}Identify electrical islands (subnetworks) in the Y-bus matrix.
Analyzes the network topology to find groups of buses that are electrically connected to each other but isolated from other groups. Each subnetwork represents an electrical island that requires its own reference bus and can be solved independently.
Arguments
M::Ybus: Y-bus matrix to analyze
Returns
Dict{Int, Set{Int}}: Dictionary mapping reference bus numbers to sets of bus numbers in each subnetwork
Examples
ybus = Ybus(system)
subnetworks = find_subnetworks(ybus)
for (ref_bus, buses) in subnetworks
println("Island ", ref_bus, ": ", sort(collect(buses)))
end
if length(subnetworks) > 1
@warn "Network has ", length(subnetworks), " electrical islands"
endImplementation Details
- Uses adjacency matrix analysis to find connected components
- Each subnetwork gets assigned a reference bus for voltage angle reference
- Isolated buses or groups require separate power flow analysis
- Critical for power flow initialization and solution
See Also
validate_connectivity: Check for full connectivitydepth_first_search: Graph traversal algorithmiterative_union_find: Alternative connectivity algorithm
PowerNetworkMatrices.from_hdf5 — Method
from_hdf5(_, filename)
Deserialize a PTDF from an HDF5 file.
Arguments
::Type{PTDF}:filename::AbstractString: File containing a serialized PTDF.
PowerNetworkMatrices.get_ac_transmission_types — Method
get_ac_transmission_types(network_reduction_data)
getactransmissiontypes(networkreduction_data::NetworkReductionData)
Gets the concrete types of all AC transmission branches included in an instance of NetworkReductionData
Arguments
network_reduction_data::NetworkReductionData
Returns
Set{DataType}: Vector of the retained branch types.
PowerNetworkMatrices.get_arc_axis — Method
get_arc_axis(nr)
Interface to obtain the arc axis based on the network reduction data
PowerNetworkMatrices.get_arc_axis — Method
get_arc_axis(fb, tb, bus_axis)
get_arc_axis(fb::Vector{Int}, tb::Vector{Int}, bus_axis::Vector{Int}) -> Vector{Tuple{Int, Int}}Generate unique arc axis from from-bus and to-bus index vectors.
Creates a vector of unique (frombus, tobus) tuples representing the arcs (branches) in the system. Used for constructing arc admittance matrices and organizing network topology data.
Arguments
fb::Vector{Int}: Vector of from-bus indices into bus_axistb::Vector{Int}: Vector of to-bus indices into bus_axisbus_axis::Vector{Int}: Vector of bus numbers
Returns
Vector{Tuple{Int, Int}}: Unique arcs as (frombusnumber, tobusnumber) tuples
Examples
fb = [1, 2, 1] # indices into bus_axis
tb = [2, 3, 3] # indices into bus_axis
bus_axis = [101, 102, 103] # bus numbers
arcs = get_arc_axis(fb, tb, bus_axis)
# Returns: [(101, 102), (102, 103), (101, 103)]Implementation Details
- Maps indices to actual bus numbers using bus_axis
- Removes duplicates with unique()
- Preserves arc direction (from → to)
PowerNetworkMatrices.get_bus_reduction_map — Method
get_bus_reduction_map(rb)
get_bus_reduction_map(rb::NetworkReductionData)Get the bus reduction map from NetworkReductionData.
Arguments
rb::NetworkReductionData: The network reduction data
Returns
Dict{Int, Set{Int}}: Dictionary mapping retained buses to sets of removed buses
PowerNetworkMatrices.get_data — Method
get_data(mat)
returns the raw array data of the PowerNetworkMatrix
PowerNetworkMatrices.get_default_reduction — Method
get_default_reduction(sys)
get_default_reduction(sys::PSY.System) -> NetworkReductionDataBuild a Y-bus matrix from the system and return its default network reduction data.
This function constructs a Y-bus matrix with no network reductions applied and returns the resulting NetworkReductionData, which contains the basic bus and branch mappings for the system without any reduction algorithms.
Arguments
sys::PSY.System: Power system to analyze
Returns
NetworkReductionData: Default network reduction data with basic system mappings
Examples
system = System("system.json")
reduction_data = get_default_reduction(system)
println("Number of buses: ", length(get_bus_reduction_map(reduction_data)))See Also
Ybus: Y-bus matrix constructionNetworkReductionData: Network reduction data structure
PowerNetworkMatrices.get_equivalent_available — Method
get_equivalent_available(bp)
get_equivalent_available(bp::BranchesParallel)Get the availability status for parallel branches. All branches in parallel must be available for the parallel circuit to be available.
PowerNetworkMatrices.get_equivalent_available — Method
get_equivalent_available(bs)
get_equivalent_available(bs::BranchesSeries)Get the availability status for series branches. All branches in series must be available for the series circuit to be available.
PowerNetworkMatrices.get_equivalent_available — Method
get_equivalent_available(tw)
get_equivalent_available(tw::ThreeWindingTransformerWinding)Get the availability status for a specific winding of a three-winding transformer. Returns the availability status of the parent transformer.
PowerNetworkMatrices.get_equivalent_b — Method
get_equivalent_b(tw)
get_equivalent_b(tw::ThreeWindingTransformerWinding)Get the susceptance for a specific winding of a three-winding transformer. For the primary winding (winding 1), returns the shunt susceptance from the transformer. For secondary and tertiary windings, returns 0.0 as the shunt is only on the primary side.
PowerNetworkMatrices.get_equivalent_emergency_rating — Method
get_equivalent_emergency_rating(bp)
get_equivalent_emergency_rating(bp::BranchesParallel)Calculate the total emergency rating for branches in parallel. For parallel circuits, the emergency rating is the sum of individual emergency ratings divided by the number of circuits. This provides a conservative estimate that accounts for potential overestimation of total capacity.
PowerNetworkMatrices.get_equivalent_emergency_rating — Method
get_equivalent_emergency_rating(bs)
get_equivalent_emergency_rating(bs::BranchesSeries)Calculate the emergency rating for branches in series. For series circuits, the emergency rating is limited by the weakest link: Rating_total = min(Rating1, Rating2, ..., Ratingn)
PowerNetworkMatrices.get_equivalent_emergency_rating — Method
get_equivalent_emergency_rating(tw)
get_equivalent_emergency_rating(tw::ThreeWindingTransformerWinding)Get the rating for a specific winding of a three-winding transformer. Returns the winding-specific rating if non-zero, otherwise returns the parent transformer rating.
PowerNetworkMatrices.get_equivalent_emergency_rating — Method
get_equivalent_emergency_rating(branch)
get_equivalent_emergency_rating(bs<:PSY.ACTransmission)Return the emergency rating for PSY.ACTransmission branches.
PowerNetworkMatrices.get_equivalent_emergency_rating — Method
get_equivalent_emergency_rating(branch)
get_equivalent_emergency_rating(bs<:PSY.ACTransmission)Return the emergency rating for PSY.GenericArcImpedance.
PowerNetworkMatrices.get_equivalent_r — Method
get_equivalent_r(tw)
get_equivalent_r(tw::ThreeWindingTransformerWinding)Get the resistance for a specific winding of a three-winding transformer. Returns the winding-specific series resistance.
PowerNetworkMatrices.get_equivalent_rating — Method
get_equivalent_rating(bp)
get_equivalent_rating(bp::BranchesParallel)Calculate the total rating for branches in parallel. For parallel circuits, the rating is the sum of individual ratings divided by the number of circuits. This provides a conservative estimate that accounts for potential overestimation of total capacity.
PowerNetworkMatrices.get_equivalent_rating — Method
get_equivalent_rating(bs)
get_equivalent_rating(bs::BranchesSeries)Calculate the rating for branches in series. Series chains, can be composed of PSY.ACTransmission branches and PNM.BranchesParallel. For series circuits, the rating is limited by the weakest link: Rating_total = min(Rating1, Rating2, ..., Ratingn)
PowerNetworkMatrices.get_equivalent_rating — Method
get_equivalent_rating(tw)
get_equivalent_rating(tw::ThreeWindingTransformerWinding)Get the rating for a specific winding of a three-winding transformer. Returns the winding-specific rating if non-zero, otherwise returns the parent transformer rating.
PowerNetworkMatrices.get_equivalent_rating — Method
get_equivalent_rating(bs)
get_equivalent_rating(bs<:PSY.ACTransmission)Return the rating for PSY.ACTransmission branches.
PowerNetworkMatrices.get_equivalent_rating — Method
get_equivalent_rating(bs)
get_equivalent_rating(bs::PSY.GenericArcImpedance)Rating is assumed to be max_flow for GenericArcImpedance.
PowerNetworkMatrices.get_equivalent_tap — Method
get_equivalent_tap(tw)
get_equivalent_tap(tw::ThreeWindingTransformerWinding)Get the tap (turns ratio) for a specific winding of a three-winding transformer. Returns the winding-specific turns ratio for phase shifting transformers.
PowerNetworkMatrices.get_equivalent_x — Method
get_equivalent_x(tw)
get_equivalent_x(tw::ThreeWindingTransformerWinding)Get the reactance for a specific winding of a three-winding transformer. Returns the winding-specific series reactance.
PowerNetworkMatrices.get_equivalent_α — Method
get_equivalent_α(bp)
get_equivalent_α(bp::BranchesParallel)Get the phase angle shift for parallel branches. Returns the average phase angle shift across all parallel branches. Returns 0.0 if branches don't support phase angle shift (e.g., lines).
PowerNetworkMatrices.get_equivalent_α — Method
get_equivalent_α(bs)
get_equivalent_α(bs::BranchesSeries)Get the phase angle shift for series branches. Returns the sum of phase angle shifts across all series branches. Returns 0.0 if branches don't support phase angle shift (e.g., lines).
PowerNetworkMatrices.get_equivalent_α — Method
get_equivalent_α(tw)
get_equivalent_α(tw::ThreeWindingTransformerWinding)Get the phase angle (α) for a specific winding of a three-winding transformer. Returns the winding-specific phase shift angle for phase shifting transformers.
PowerNetworkMatrices.get_irreducible_indices — Method
get_irreducible_indices(A, irreducible_buses)
Convert the user input for irreducible_buses to a set of indices based on the Ybus lookup and the prior reductions.
PowerNetworkMatrices.get_isolated_buses — Method
get_isolated_buses(M)
get_isolated_buses(M::Ybus) -> Vector{Int}Return bus numbers that form isolated single-node subnetworks in the Y-bus matrix.
Isolated buses are electrical islands containing only one bus with no connections to other parts of the network. These typically represent buses that were disconnected during network reduction operations or buses with no active branches.
Arguments
M::Ybus: Y-bus matrix to analyze
Returns
Vector{Int}: Vector of bus numbers that form isolated single-node subnetworks
Examples
ybus = Ybus(system)
isolated = get_isolated_buses(ybus)
println("Isolated buses: ", isolated)PowerNetworkMatrices.get_lodf_data — Method
get_lodf_data(lodf)
get_lodf_data(lodf::LODF)Extract the LODF matrix data in the standard orientation (non-transposed).
Arguments
lodf::LODF: The LODF structure from which to extract data
Returns
AbstractArray{Float64, 2}: The LODF matrix data with standard orientation
PowerNetworkMatrices.get_lodf_data — Method
get_lodf_data(mat)
get_lodf_data(mat::VirtualLODF) -> Dict{Int, Vector{Float64}}Get the cached LODF row data from a VirtualLODF matrix.
Unlike get_lodf_data(::LODF), which returns a dense matrix, this returns a dictionary mapping row indices to lazily computed row vectors.
Arguments
mat::VirtualLODF: The virtual LODF matrix
Returns
Dict{Int, Vector{Float64}}: Cached row data keyed by row index
PowerNetworkMatrices.get_lookup — Method
get_lookup(mat)
returns the lookup tuple of the `PowerNetworkMatrix`. The entries correspond
to the dimensions of the underlying `axes` tuple, and each lookup dictionary maps
arc tuples `(from_bus, to_bus)` or bus numbers to integer indices into the stored
data.PowerNetworkMatrices.get_mapped_bus_number — Method
get_mapped_bus_number(rb, bus_number)
Interface to obtain the parent bus number of a reduced bus when radial branches are eliminated
Arguments
rb::NetworkReduction: NetworkReduction objectbus_number::Int: Bus number of the reduced bus
PowerNetworkMatrices.get_mapped_bus_number — Method
get_mapped_bus_number(rb, bus)
Interface to obtain the parent bus number of a reduced bus when radial branches are eliminated
Arguments
rb::NetworkReduction: NetworkReduction objectbus::ACBus: Reduced bus
PowerNetworkMatrices.get_network_reduction_data — Method
get_network_reduction_data(M)
Get the NetworkReduction data applied to this matrix.
PowerNetworkMatrices.get_partial_lodf_row — Method
get_partial_lodf_row(vlodf, arc_idx, delta_b)
get_partial_lodf_row(vlodf::VirtualLODF, arc_idx::Int, delta_b::Float64) -> Vector{Float64}Compute the LODF row for a partial susceptance change delta_b on arc arc_idx.
For a full outage, set delta_b = -arc_susceptance. For a single circuit outage on a double-circuit arc with total susceptance b_total, set delta_b = -b_circuit.
Arguments
vlodf::VirtualLODF: VirtualLODF matrixarc_idx::Int: Arc index (integer)delta_b::Float64: Change in susceptance (negative for outage)
Returns
Vector{Float64}: LODF row of length n_arcs
get_partial_lodf_row(
vlodf::VirtualLODF,
arc_idx::Int64,
delta_b::Float64
) -> Vector{Float64}
PowerNetworkMatrices.get_partial_lodf_row — Method
get_partial_lodf_row(vlodf, arc, delta_b)
get_partial_lodf_row(vlodf::VirtualLODF, arc::Tuple{Int, Int}, delta_b::Float64) -> Vector{Float64}Arc-tuple indexed version of get_partial_lodf_row.
get_partial_lodf_row(
vlodf::VirtualLODF,
arc::Tuple{Int64, Int64},
delta_b::Float64
) -> Vector{Float64}
PowerNetworkMatrices.get_post_modification_ptdf_row — Method
get_post_modification_ptdf_row(vptdf, monitored_arc, mod)
get_post_modification_ptdf_row(vptdf, monitored_arc, mod) -> Vector{Float64}One-shot convenience function: compute the post-modification PTDF row for a monitored arc under a network modification. Internally calls compute_woodbury_factors then apply_woodbury_correction.
No caching — each call recomputes. Use the two-step API (compute_woodbury_factors + apply_woodbury_correction) when querying multiple monitored arcs for the same modification.
get_post_modification_ptdf_row(
vptdf::VirtualPTDF,
monitored_arc::Int64,
mod::NetworkModification
) -> Vector{Float64}
PowerNetworkMatrices.get_post_modification_ptdf_row — Method
get_post_modification_ptdf_row(
vptdf,
monitored_arc,
sys,
outage
)
get_post_modification_ptdf_row(vptdf, monitored_arc, sys, outage) -> Vector{Float64}Compute the post-contingency PTDF row for a monitored arc when the given PSY.Outage trips. Resolves the outage's associated branches through the system and builds the modification automatically.
get_post_modification_ptdf_row(
vptdf::VirtualPTDF,
monitored_arc::Int64,
sys::PowerSystems.System,
outage::PowerSystems.Outage
) -> Vector{Float64}
PowerNetworkMatrices.get_ptdf_data — Method
get_ptdf_data(ptdf)
get_ptdf_data(ptdf::PTDF)Extract the PTDF matrix data in the standard orientation (non-transposed).
Arguments
ptdf::PTDF: The PTDF structure from which to extract data
Returns
AbstractArray{Float64, 2}: The PTDF matrix data with standard orientation
PowerNetworkMatrices.get_ptdf_data — Method
get_ptdf_data(mat)
get_ptdf_data(mat::VirtualPTDF) -> Dict{Int, Vector{Float64}}Get the cached PTDF row data from a VirtualPTDF matrix.
Unlike get_ptdf_data(::PTDF), which returns a dense matrix, this returns a dictionary mapping row indices to lazily computed row vectors.
Arguments
mat::VirtualPTDF: The virtual PTDF matrix
Returns
Dict{Int, Vector{Float64}}: Cached row data keyed by row index
PowerNetworkMatrices.get_reduction — Method
get_reduction(ybus, sys, reduction)
get_reduction(ybus::Ybus, sys::PSY.System, reduction::RadialReduction) -> NetworkReductionDataApply radial network reduction to a Y-bus matrix.
Radial reduction eliminates radial (dangling) buses that have only one connection. These buses do not affect power flows in the rest of the network and can be safely removed to reduce computational complexity.
Arguments
ybus::Ybus: Y-bus matrix to reducesys::PSY.System: Power system for validationreduction::RadialReduction: Radial reduction configuration
Returns
NetworkReductionData: Reduction data containing eliminated buses and updated mappings
Examples
ybus = Ybus(system)
reduction = RadialReduction(irreducible_buses=[101, 205])
reduction_data = get_reduction(ybus, system, reduction)See Also
RadialReduction: Radial reduction configurationget_reduction: Other reduction methods
PowerNetworkMatrices.get_reductions — Method
get_reductions(rb)
get_reductions(rb::NetworkReductionData)Get the reduction container from NetworkReductionData.
Arguments
rb::NetworkReductionData: The network reduction data
Returns
ReductionContainer: Container with the applied network reductions
PowerNetworkMatrices.get_registered_contingencies — Method
get_registered_contingencies(vmodf)
get_registered_contingencies(vmodf::VirtualMODF) -> Dict{Base.UUID, ContingencySpec}Return the cached contingency registrations for inspection.
PowerNetworkMatrices.get_representative — Method
get_representative(uf, x)
Find part of the union-find disjoint set data structure. Vector because nodes are 1:n.
PowerNetworkMatrices.get_retained_branches_names — Method
get_retained_branches_names(network_reduction_data)
getretainedbranchesnames(networkreduction_data::NetworkReductionData)
Gets the branch names that are retained after network reduction. This method only returns the branch names from non-three winding transformer branches that have a one-to-one correspondence with arcs after the reduction. This does not include parallel branches or branches that have been reduced as part of a series chain of degree two nodes.
Arguments
network_reduction_data::NetworkReductionData
Returns
Vector{String}: Vector of the retained branch names.
PowerNetworkMatrices.get_system_uuid — Method
get_system_uuid(_)
get_system_uuid(mat::PowerNetworkMatrix) -> Union{Base.UUID, Nothing}Return the UUID of the system used to construct the matrix, or nothing if the matrix type does not track system origin.
PowerNetworkMatrices.get_tol — Method
get_tol(mat)
Gets the tolerance used for sparsifying the rows of the VirtualLODF matrix
PowerNetworkMatrices.get_tol — Method
get_tol(vptdf)
Gets the tolerance used for sparsifying the rows of the VirtualPTDF matrix
PowerNetworkMatrices.get_ward_reduction — Method
get_ward_reduction(
data,
bus_lookup,
bus_axis,
arc_axis,
boundary_buses,
ref_bus_numbers,
study_buses,
subnetwork_bus_axis
)
get_ward_reduction(data, bus_lookup, bus_axis, arc_axis, boundary_buses, ref_bus_numbers, study_buses, subnetwork_bus_axis)Perform Ward reduction to create an equivalent network representation.
Ward reduction is a network reduction technique that eliminates external buses while preserving the electrical characteristics seen from the study buses. External buses are mapped to boundary buses based on impedance criteria, and equivalent admittances are computed.
Arguments
data::SparseArrays.SparseMatrixCSC{YBUS_ELTYPE, Int}: Admittance matrix of the systembus_lookup::Dict{Int, Int}: Dictionary mapping bus numbers to matrix indicesbus_axis::Vector{Int}: Vector of all bus numbers in the systemarc_axis::Vector{Tuple{Int, Int}}: Vector of all arc tuples in the systemboundary_buses::Set{Int}: Set of boundary bus numbers between study and external areasref_bus_numbers::Set{Int}: Set of reference bus numbersstudy_buses::Vector{Int}: Vector of study bus numbers to retainsubnetwork_bus_axis::Vector{Int}: Bus numbers in the selected subnetwork to reduce
Returns
Tuple: Contains bus reduction map, reverse bus search map, added branch map, and added admittance map
PowerNetworkMatrices.is_factorized — Method
is_factorized(ABA)
is_factorized(ABA::ABA_Matrix)Check if an ABA_Matrix has been factorized (i.e., contains LU factorization matrices).
Arguments
ABA::ABA_Matrix: The ABA matrix to check
Returns
Bool: true if the matrix has been factorized, false otherwise
PowerNetworkMatrices.iterative_union_find — Method
iterative_union_find(M, bus_numbers)
iterative_union_find(M::SparseArrays.SparseMatrixCSC, bus_numbers::Vector{Int})Find connected subnetworks using iterative union-find algorithm.
Arguments
M::SparseArrays.SparseMatrixCSC: Sparse matrix representing network connectivitybus_numbers::Vector{Int}: Vector containing the bus numbers of the system
Returns
Dict{Int, Set{Int}}: Dictionary mapping representative bus numbers to sets of connected buses
PowerNetworkMatrices.lookup_index — Method
lookup_index(i, lookup)
Gets the matrix index corresponding to a given key (arc tuple, bus number, etc.)
PowerNetworkMatrices.lookup_index — Method
lookup_index(i, lookup)
Gets the matrix index for a PSY.ACBus, converting it to a bus number first.
Arguments
i::PSY.ACBus: Power System AC buslookup::Dict: Dictionary mapping arc tuples or bus numbers to matrix indices
PowerNetworkMatrices.lookup_index — Method
lookup_index(i, lookup)
Gets the matrix index for a PSY.Arc, converting it to an arc tuple first.
Arguments
i::PSY.Arc: Power System Arc objectlookup::Dict: Dictionary mapping arc tuples or bus numbers to matrix indices
PowerNetworkMatrices.make_arc_arc_subnetwork_axes — Method
make_arc_arc_subnetwork_axes(A)
Make subnetwork axes for LODF and VirtualLODF
PowerNetworkMatrices.make_arc_bus_subnetwork_axes — Method
make_arc_bus_subnetwork_axes(ybus)
make_arc_bus_subnetwork_axes(ybus::Ybus) -> Dict{Int, Tuple{Vector{Tuple{Int, Int}}, Vector{Int}}}Create subnetwork axes for IncidenceMatrix construction from a Y-bus matrix.
Generates subnetwork-specific axes with arc-bus ordering needed for constructing incidence matrices. Each subnetwork gets its own arc list and corresponding bus list for matrix indexing.
Arguments
ybus::Ybus: Y-bus matrix containing subnetwork information
Returns
Dict{Int, Tuple{Vector{Tuple{Int, Int}}, Vector{Int}}}: Dictionary mapping reference bus numbers to (arcaxis, busaxis) tuples for each subnetwork
Implementation Details
- Swaps order compared to
make_bus_arc_subnetwork_axes(arc first, bus second) - Uses same underlying data from
ybus.subnetwork_axesandybus.arc_subnetwork_axis - Used for constructing incidence matrices that relate branch connectivity to bus topology
See Also
IncidenceMatrix: Network incidence matrixmake_bus_arc_subnetwork_axes: Bus-Arc variant
PowerNetworkMatrices.make_ax_ref — Method
make_ax_ref(buses)
Evaluates the map linking the system's buses and branches.
Arguments
buses::AbstractVector{PSY.ACBus}: system's buses
PowerNetworkMatrices.make_ax_ref — Method
make_ax_ref(ax)
Checks if repetitions are present in the dictionary mapping buses and branches.
Arguments
ax::AbstractVector: generic abstract vector
PowerNetworkMatrices.make_bus_arc_subnetwork_axes — Method
make_bus_arc_subnetwork_axes(ybus)
make_bus_arc_subnetwork_axes(ybus::Ybus) -> Dict{Int, Tuple{Vector{Int}, Vector{Tuple{Int, Int}}}}Create subnetwork axes for BA_Matrix construction from a Y-bus matrix.
Generates subnetwork-specific axes combining bus and arc information needed for constructing Bus-Arc (BA) matrices. Each subnetwork gets its own bus list and corresponding arc list for matrix indexing.
Arguments
ybus::Ybus: Y-bus matrix containing subnetwork information
Returns
Dict{Int, Tuple{Vector{Int}, Vector{Tuple{Int, Int}}}}: Dictionary mapping reference bus numbers to (busaxis, arcaxis) tuples for each subnetwork
Implementation Details
- Combines bus axes from
ybus.subnetwork_axeswith arc axes fromybus.arc_subnetwork_axis - Maintains consistency between bus and arc indexing within each electrical island
- Used for constructing BA matrices that relate bus injections to branch flows
See Also
BA_Matrix: Bus-Arc matrix constructionmake_arc_bus_subnetwork_axes: Arc-Bus variant
PowerNetworkMatrices.populate_branch_maps_by_type! — Function
populate_branch_maps_by_type!(nrd)
populate_branch_maps_by_type!(nrd, filters)
populate_branch_maps_by_type!(nrd::NetworkReductionData, filters = Dict())Populate the branch maps organized by component type within the NetworkReductionData structure.
This function processes various types of branch mappings (direct, parallel, series, and 3-winding transformers) and organizes them by their component types. It applies optional filters to determine which branches should be included in the type-organized maps.
Arguments
nrd::NetworkReductionData: The network reduction data structure to populatefilters: Optional dictionary of filters to apply when determining which branches to include (default: empty Dict)
Details
The function creates and populates the following map types organized by component type:
direct_branch_map: Direct branch connections between busesreverse_direct_branch_map: Reverse lookup for direct branchesparallel_branch_map: Parallel branch connections between the same bus pairreverse_parallel_branch_map: Reverse lookup for parallel branchesseries_branch_map: Series branch connections (chains of branches)reverse_series_branch_map: Reverse lookup for series branchestransformer3W_map: Three-winding transformer connectionsreverse_transformer3W_map: Reverse lookup for three-winding transformers
The function also populates the name_to_arc_map to provide name-based lookups for branches and stores the applied filters in nrd.filters_applied.
Modifies
nrd.all_branch_maps_by_type: Populated with type-organized branch mapsnrd.name_to_arc_map: Updated with name-to-arc mappingsnrd.filters_applied: Set to the provided filters
Returns
nothing: This function modifies the input structure in-place
PowerNetworkMatrices.purge_one! — Method
purge_one!(cache)
Deletes a row from the stored matrix in cache not belonging to the persistentcachekeys set. Uses LRU (Least Recently Used) eviction strategy based on access_order tracking.
PowerNetworkMatrices.set_linalg_backend_check — Method
Set a preference whether to run checklinalgbackend at the package loading time.
PowerNetworkMatrices.set_linalg_backend_preference — Method
Set a preference of the backend library for sparse linear algebra operations.
PowerNetworkMatrices.sparsify — Method
sparsify(dense_array, tol)
Return a sparse matrix given a dense one by dropping elements whose absolute value is below a certain tolerance.
Uses optimized droptol! for better performance compared to element-wise iteration.
Arguments
dense_array::Matrix{Float64}: input matrix (e.g., PTDF matrix).tol::Float64: tolerance.
PowerNetworkMatrices.sparsify — Method
sparsify(dense_array, tol)
Return a sparse vector given a dense one by dropping elements whose absolute value is below a certain tolerance.
Uses optimized droptol! for better performance compared to element-wise iteration.
Arguments
dense_array::Vector{Float64}: input vector (e.g., PTDF row from VirtualPTDF).tol::Float64: tolerance.
PowerNetworkMatrices.to_hdf5 — Method
to_hdf5(ptdf, filename; compress, compression_level, force)
Serialize the PTDF to an HDF5 file.
Arguments
ptdf::PTDF: matrixfilename::AbstractString: File to createcompress::Bool: Whether to enabled compression, defaults to true.compression_level::Int: Compression level to use if compression is enabled.force::Bool: Whether to overwrite the file if it already exists, defaults to false.
PowerNetworkMatrices.to_index — Method
to_index(A, idx)
Given the indices, gets the values of the power network matrix considered
PowerNetworkMatrices.union_sets! — Method
union_sets!(uf, x, y)
Union part of the union-find disjoint set data structure. Vector because nodes are 1:n.
PowerNetworkMatrices.validate_buses — Method
validate_buses(A, buses)
Validates that the user bus input is consistent with the ybus axes and the prior reductions. Is used to check irreducible_buses for Radial and DegreeTwo reductions and study_buses for WardReduction.
PowerNetworkMatrices.validate_connectivity — Method
validate_connectivity(M)
validate_connectivity(M::AdjacencyMatrix) -> BoolCheck whether the network represented by an AdjacencyMatrix is fully connected.
Arguments
M::AdjacencyMatrix: The adjacency matrix of the network
Returns
Bool:trueif the network has exactly one subnetwork (fully connected),falseotherwise
PowerNetworkMatrices.validate_connectivity — Method
validate_connectivity(
M,
nodes,
bus_lookup;
connectivity_method
)
validate_connectivity(M, nodes, bus_lookup; connectivity_method) -> BoolCheck whether the network described by matrix M is fully connected, using the specified connectivity algorithm.
Arguments
M: Matrix representation of the network (e.g., admittance or adjacency matrix)nodes::Vector{PSY.ACBus}: AC buses in the networkbus_lookup::Dict{Int64, Int64}: Mapping from bus numbers to matrix indicesconnectivity_method::Function: Algorithm to use (default:goderya_connectivity)
Returns
Bool:trueif the network is fully connected,falseotherwise
PowerNetworkMatrices.validate_connectivity — Method
validate_connectivity(sys)
validate_connectivity(sys::PSY.System) -> BoolCheck whether the power system network is fully connected using Depth First Search (DFS).
Arguments
sys::PSY.System: The power system to validate
Returns
Bool:trueif the network is fully connected,falseotherwise
PowerNetworkMatrices.validate_connectivity — Method
validate_connectivity(M)
validate_connectivity(M::Ybus) -> BoolValidate that the Y-bus represents a fully connected electrical network.
Checks network connectivity by counting the number of electrical islands (subnetworks) in the Y-bus matrix. A fully connected network should have exactly one subnetwork. Multiple subnetworks indicate electrical isolation between parts of the system.
Arguments
M::Ybus: Y-bus matrix to validate
Returns
Bool:trueif network is fully connected (single subnetwork),falseotherwise
Examples
ybus = Ybus(system)
if validate_connectivity(ybus)
println("Network is fully connected")
else
println("Network has isolated islands")
islands = find_subnetworks(ybus)
println("Number of islands: ", length(islands))
endImplementation Details
- Uses
find_subnetworks()to identify electrical islands - Single subnetwork indicates full electrical connectivity
- Multiple subnetworks may require separate power flow solutions
See Also
find_subnetworks: Identify electrical islandsvalidate_connectivity: System-level connectivity validation
PowerNetworkMatrices.ybus_branch_entries — Method
ybus_branch_entries(tp)
Ybus branch entries for an arc in the wye model of a ThreeWindingTransformer.
PowerNetworkMatrices.ybus_branch_entries — Method
ybus_branch_entries(br)
Ybus entries for a Line or a DiscreteControlledACBranch.
PowerNetworkMatrices.ybus_branch_entries — Method
ybus_branch_entries(br)
Ybus entries for a Transformer2W, TapTransformer, or PhaseShiftingTransformer.