Internal API
PowerNetworkMatrices.EquivalentBranch — TypeEquivalentBranchRepresents 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.PowerNetworkMatrix — TypeType PowerNetworkMatrix gathers all the different types of Matrices considered in this package
PowerNetworkMatrices.PowerNetworkMatrixKey — TypeStructure to store the keys of a power network matrix
Arguments
I<:Tuple: tuple containing the indices of the matrix
PowerNetworkMatrices.PowerNetworkMatrixKeys — TypeStructure 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.RowCache — TypeStructure used for saving the rows of the Virtual PTDF and LODF matrix.
Arguments
temp_cache::Dict{Int, Union{Vector{Float64}, SparseArrays.SparseVector{Float64}}}: Dictionay 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)
PowerNetworkMatrices.RowCache — MethodRowCache(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.ThreeWindingTransformerWinding — TypeThreeWindingTransformerWinding{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.
Base.eachindex — Methodeachindex(vlodf)
Gives the cartesian indexes of the LODF matrix.
Base.eachindex — Methodeachindex(vptdf)
Gives the cartesian indexes of the PTDF matrix (same as the BA one).
Base.empty! — Methodempty!(cache)
Erases the cache.
Base.getindex — Methodgetindex(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 — Methodgetindex(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 — Methodgetindex(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.haskey — Methodhaskey(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 — Methodisempty(cache)
Check if cache is empty.
Base.isempty — Methodisempty(vlodf)
Checks if the any of the fields of VirtualLODF is empty.
Base.isempty — Methodisempty(vptdf)
Checks if the any of the fields of VirtualPTDF is empty.
Base.length — Methodlength(cache)
Shows the number of rows stored in cache
Base.setindex! — Methodsetindex!(_, _, _)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Methodsetindex!(_, _, idx)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Methodsetindex!(_, _, _)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Methodsetindex!(_, _, idx)
!!! STILL TO IMPLEMENT !!!
Base.setindex! — Methodsetindex!(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
Base.size — Methodsize(vlodf)
Shows the size of the whole LODF matrix, not the number of rows stored.
Base.size — Methodsize(vptdf)
Gives the size of the whole PTDF matrix, not the number of rows stored.
PowerNetworkMatrices._calculate_LODF_matrix_AppleAccelerate — Method_calculate_LODF_matrix_AppleAccelerate(a, ptdf)
Function for internal use only.
Computes the LODF matrix by means of AppleAccelerate for sparse matrices.
Arguments
a::SparseArrays.SparseMatrixCSC{Int8, Int}: Incidence Matrixptdf::Matrix{Float64}: PTDF matrix
PowerNetworkMatrices._calculate_PTDF_matrix_AppleAccelerate — Method_calculate_PTDF_matrix_AppleAccelerate(
A,
BA,
ref_bus_positions,
dist_slack
)
Function for internal use only.
Computes the PTDF matrix by means of AppleAccelerate 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._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._calculate_PTDF_matrix_MKLPardiso — Method_calculate_PTDF_matrix_MKLPardiso(
A,
BA,
ref_bus_positions,
dist_slack
)
Function for internal use only.
Computes the PTDF matrix by means of the MKL Pardiso for dense 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._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_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._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::Set{Int})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::Set{Int}: Set of indices that have already been reduced.irreducible_indices::Set{Int}: Set of indices that should not be reduced.
Returns
Bool:trueif the node is a final node,falseotherwise.
PowerNetworkMatrices._should_visit_node — Method_should_visit_node(
node,
reduced_indices,
irreducible_indices
)
_should_visit_node(node::Int, reduced_indices::Set{Int}, irreducible_indices::Set{Int})Determines whether a node should be visited during network traversal.
Arguments
node::Int: The index of the node to check.reduced_indices::Set{Int}: Set of indices that have already been reduced.irreducible_indices::Set{Int}: Set of indices that cannot be reduced.
Returns
Bool:trueif the node should be visited,falseotherwise.
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! — Methodadd_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! — Methodadd_branch_entries_to_ybus!(
y11,
y12,
y21,
y22,
branch_ix,
br
)
add_branch_entries_to_ybus!(
y11::Vector{ComplexF32},
y12::Vector{ComplexF32},
y21::Vector{ComplexF32},
y22::Vector{ComplexF32},
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{ComplexF32}: Vector for from-bus self admittancesy12::Vector{ComplexF32}: Vector for from-to mutual admittancesy21::Vector{ComplexF32}: Vector for to-from mutual admittancesy22::Vector{ComplexF32}: 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! — Methodadd_segment_to_ybus!(
segment,
y11,
y12,
y21,
y22,
fb,
tb,
ix,
segment_orientation
)
add_segment_to_ybus!(
segment::BranchesParallel,
y11::Vector{ComplexF32},
y12::Vector{ComplexF32},
y21::Vector{ComplexF32},
y22::Vector{ComplexF32},
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{ComplexF32}: Vector for from-bus self admittancesy12::Vector{ComplexF32}: Vector for from-to mutual admittancesy21::Vector{ComplexF32}: Vector for to-from mutual admittancesy22::Vector{ComplexF32}: 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! — Methodadd_segment_to_ybus!(
segment,
y11,
y12,
y21,
y22,
fb,
tb,
ix,
segment_orientation
)
add_segment_to_ybus!(
segment::PSY.ACTransmission
y11::Vector{ComplexF32},
y12::Vector{ComplexF32},
y21::Vector{ComplexF32},
y22::Vector{ComplexF32},
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{ComplexF32}: Vector for from-bus self admittancesy12::Vector{ComplexF32}: Vector for from-to mutual admittancesy21::Vector{ComplexF32}: Vector for to-from mutual admittancesy22::Vector{ComplexF32}: 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! — Methodadd_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! — Methodadd_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.assign_reference_buses! — Methodassign_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 — Methodbuild_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 — Methodcalculate_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 — Methodcalculate_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 eliminated
Algorithm Overview
- Leaf Detection: Identifies buses with exactly one connection (radial buses)
- Reference Protection: Preserves reference buses from elimination regardless of connectivity
- Upstream Tracing: Traces from radial buses toward the core network to find parent buses
- Cascading Reduction: Recursively eliminates buses that become radial after initial reductions
- Parallel Processing: Uses multithreading for efficient analysis of large networks
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
- Uses sparse matrix operations for efficiency with large, sparse networks
- Handles edge cases like fully radial networks and isolated islands
- Maintains thread safety for concurrent processing of network analysis
- Provides comprehensive mapping for traceability and debugging
PowerNetworkMatrices.check_cache_size! — Methodcheck_cache_size!(cache; new_add)
Check saved rows in cache and delete one not belonging to persistent_cache_keys.
PowerNetworkMatrices.find_degree2_chains — Methodfind_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 — Methodfind_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.get_ac_transmission_types — Methodget_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 — Methodget_arc_axis(nr)
Interface to obtain the arc axis based on the network reduction data
PowerNetworkMatrices.get_arc_axis — Methodget_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_data — Methodget_data(mat)
returns the raw array data of the PowerNetworkMatrix
PowerNetworkMatrices.get_default_reduction — Methodget_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 — Methodget_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 — Methodget_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 — Methodget_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 — Methodget_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_r — Methodget_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 — Methodget_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 — Methodget_equivalent_rating(bs)
get_equivalent_rating(bs::BranchesSeries)Calculate the rating for branches in series. For series circuits, the rating is limited by the weakest link: Rating_total = min(Rating1, Rating2, ..., Ratingn)
PowerNetworkMatrices.get_equivalent_rating — Methodget_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_tap — Methodget_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 — Methodget_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_α — Methodget_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_α — Methodget_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_α — Methodget_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 — Methodget_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 — Methodget_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_lookup — Methodget_lookup(mat)
returns the lookup tuple of the `PowerNetworkMatrix`. The first entry corresponds
to the first dimension and the second entry corresponds to the second dimension. For
instance in Ybus the first dimension is buses and second dimension is buses too, and in
PTDF the first dimension is branches and the second dimension is busesPowerNetworkMatrices.get_mapped_bus_number — Methodget_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 — Methodget_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_reduction — Methodget_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_representative — Methodget_representative(uf, x)
Find part of the union-find disjoint set data structure. Vector because nodes are 1:n.
PowerNetworkMatrices.get_retained_branches_names — Methodget_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_tol — Methodget_tol(mat)
Gets the tolerance used for sparsifying the rows of the VirtualLODF matrix
PowerNetworkMatrices.get_tol — Methodget_tol(vptdf)
Gets the tolerance used for sparsifying the rows of the VirtualPTDF matrix
PowerNetworkMatrices.lookup_index — Methodlookup_index(i, lookup)
Gets bus indices to a certain branch index
PowerNetworkMatrices.lookup_index — Methodlookup_index(i, lookup)
Gets bus indices to a certain branch name
Arguments
i::PSY.ACBranch: Power System AC branchlookup::Dict: Dictionary mapping branches and buses
PowerNetworkMatrices.lookup_index — Methodlookup_index(i, lookup)
Gets bus indices to a certain branch name
Arguments
i::PSY.ACBranch: Power System AC branchlookup::Dict: Dictionary mapping branch and buses
PowerNetworkMatrices.make_arc_arc_subnetwork_axes — Methodmake_arc_arc_subnetwork_axes(A)
Make subnetwork axes for LODF and VirtualLODF
PowerNetworkMatrices.make_arc_bus_subnetwork_axes — Methodmake_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 — Methodmake_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 — Methodmake_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 — Methodmake_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! — Functionpopulate_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! — Methodpurge_one!(cache)
Deletes a row from the stored matrix in cache not belonging to the persistentcachekeys set.
PowerNetworkMatrices.sparsify — Methodsparsify(dense_array, tol)
Return a sparse matrix given a dense one by dropping element whose absolute value is above a certain tolerance.
Arguments
- dense_array::Matrix{Float64}`: input matrix (e.g., PTDF matrix).
tol::Float64: tolerance.
PowerNetworkMatrices.sparsify — Methodsparsify(dense_array, tol)
Return a sparse vector given a dense one by dropping element whose absolute value is above a certain tolerance.
Arguments
- dense_array::Vector{Float64}`: input vector (e.g., PTDF row from VirtualPTDF).
tol::Float64: tolerance.
PowerNetworkMatrices.to_index — Methodto_index(A, idx)
Given the indices, gets the values of the power network matrix considered
PowerNetworkMatrices.union_sets! — Methodunion_sets!(uf, x, y)
Union part of the union-find disjoint set data structure. Vector because nodes are 1:n.
PowerNetworkMatrices.validate_buses — Methodvalidate_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_linear_solver — Methodvalidate_linear_solver(linear_solver)
Validates if the selected linear solver is supported.
PowerNetworkMatrices.ybus_branch_entries — Methodybus_branch_entries(tp)
Ybus branch entries for an arc in the wye model of a ThreeWindingTransformer.
PowerNetworkMatrices.ybus_branch_entries — Methodybus_branch_entries(br)
Ybus entries for a Line or a DiscreteControlledACBranch.
PowerNetworkMatrices.ybus_branch_entries — Methodybus_branch_entries(br)
Ybus entries for a Transformer2W, TapTransformer, or PhaseShiftingTransformer.