Function Reference
Sparlectra.Sparlectra — Module
Sparlectra 0.8.1Sparlectra is a Julia package for the calculation of electrical networks. It is designed to be used in the context of power system analysis and optimization.
- GitHub Repository: https://github.com/welthulk/Sparlectra.jl
- Website: https://welthulk.github.io/Sparlectra.jl
Sparlectra.DiagnosticsConfig — Type
DiagnosticsConfigTyped diagnostic-output configuration shared by examples and future modules.
Sparlectra.MatpowerImportConfig — Type
MatpowerImportConfigTyped MATPOWER import/example configuration for case selection and import conventions.
Sparlectra.ObservabilityConfig — Type
ObservabilityConfigState-estimation observability diagnostic configuration.
Sparlectra.OutputConfig — Type
OutputConfigTyped output and logfile-format configuration. Console and logfile result streams are intentionally independent so example runners can disable classic logfile tables without suppressing compact console progress.
Sparlectra.PerformanceConfig — Type
PerformanceConfigTyped performance and diagnostic-volume configuration.
Sparlectra.PowerFlowConfig — Type
PowerFlowConfigTyped power-flow configuration. It owns solver tolerances, sparse execution settings, automatic damping, start-mode controls, and Q-limit behavior.
Sparlectra.QLimitConfig — Type
QLimitConfigTyped reactive-power limit switching configuration used by power-flow runners.
Sparlectra.RuntimeConfig — Type
RuntimeConfigTyped runtime/threading configuration for example and benchmark entry points.
Sparlectra.SparlectraConfig — Type
SparlectraConfigCentral typed configuration assembled once at application or example boundaries. Module-specific sections own their parsing and validation through constructors such as PowerFlowConfig(raw) and MatpowerImportConfig(raw).
Sparlectra.StartModeConfig — Type
StartModeConfigTyped power-flow start-option configuration. These fields collect the flat-start and rectangular start-projection controls that otherwise tend to be forwarded as long keyword lists through example and benchmark call chains.
Sparlectra.StateEstimationConfig — Type
StateEstimationConfigTyped state-estimation configuration for future SE runners and diagnostics.
Sparlectra.load_sparlectra_config — Function
load_sparlectra_config([user_path]; reload=false, cli_overrides=Dict(), overrides=Dict())Load, validate, merge, and cache the central typed SparlectraConfig. Configuration precedence is src/configuration.yaml.example, optional examples/configuration.yaml (or an explicit user_path), CLI-style overrides, then explicit Julia API overrides. Unknown user keys throw an ArgumentError.
Sparlectra.print_effective_config — Method
print_effective_config([io], config::SparlectraConfig)Print an Effective Sparlectra Configuration block with typed module sections.
Sparlectra.Node — Type
NodeA mutable structure representing a node in a power system.
Fields
comp::AbstractComponent: The component of the node.busIdx::Integer: The index of the bus._nodeType::NodeType: The type of the node._ratedS::Union{Nothing,Float64}: The rated power of the node._lZone::Union{Nothing,Integer}: The loss zone of the node._area::Union{Nothing,Integer}: The area of the node._vm_pu::Union{Nothing,Float64}: The voltage magnitude of the node in per unit._va_deg::Union{Nothing,Float64}: The voltage angle of the node in degrees._pƩLoad::Union{Nothing,Float64}: The total active power load at the node._qƩLoad::Union{Nothing,Float64}: The total reactive power load at the node._pShunt::Union{Nothing,Float64}: The total active power shunt at the node._qShunt::Union{Nothing,Float64}: The total reactive power shunt at the node._pƩGen::Union{Nothing,Float64}: The total active power generation at the node._qƩGen::Union{Nothing,Float64}: The total reactive power generation at the node._vmin_pu::Union{Nothing,Float64}: The minimum voltage magnitude at the node in per unit._vmax_pu::Union{Nothing,Float64}: The maximum voltage magnitude at the node in per unit.
Constructors
Node(; busIdx::Integer, vn_kV::Float64, nodeType::NodeType, ratedS::Union{Nothing,Float64} = nothing, zone::Union{Nothing,Integer} = nothing, area::Union{Nothing,Integer} = nothing, vm_pu::Union{Nothing,Float64} = nothing, va_deg::Union{Nothing,Float64} = nothing, pƩLoad::Union{Nothing,Float64} = nothing, qƩLoad::Union{Nothing,Float64} = nothing, pShunt::Union{Nothing,Float64} = nothing, qShunt::Union{Nothing,Float64} = nothing, pƩGen::Union{Nothing,Float64} = nothing, qƩGen::Union{Nothing,Float64} = nothing, vmin_pu::Union{Nothing,Float64} = nothing, vmax_pu::Union{Nothing,Float64} = nothing, isAux::Bool = false, oBusIdx::Union{Nothing,Int} = nothing, ): Creates a newNodeinstance.
Methods
Base.show(io::IO, node::Node): Prints theNodeinstance.
Sparlectra.getLineRXBG — Method
getLineRXBG(o::ACLineSegment)::Tuple{Float64,Float64,Union{Nothing,Float64},Union{Nothing,Float64}}Returns the resistance, reactance, susceptance, and conductance of an AC line segment. If the parameters are based on length, they are multiplied by the length of the line segment.
Arguments
o::ACLineSegment: The AC line segment.
Returns
r::Float64: The resistance of the AC line segment.x::Float64: The reactance of the AC line segment.b::Union{Nothing,Float64}: The susceptance of the AC line segment. It can beNothingor aFloat64value.g::Union{Nothing,Float64}: The conductance of the AC line segment. It can beNothingor aFloat64value.
Example
getLineRXBG(acLineSegment)Sparlectra.get_line_parameters — Method
get_line_parameters(line::ACLineSegment)::Dict{Symbol,Any}Returns a dictionary of the parameters of an AC line segment. If a parameter is nothing, it is replaced with 0.0.
Arguments
line::ACLineSegment: The AC line segment.
Returns
parameters::Dict{Symbol,Any}: A dictionary where the keys are the parameter names and the values are the parameter values.
Example
get_line_parameters(acLineSegment)Sparlectra.BusLink — Type
BusLinkTopological, impedance-less connection between two buses. Bus links are not part of the electrical branch model (YBUS). They are intended for post-power-flow KCL allocation, e.g. busbar couplers / sectionalizers.
Sparlectra.PowerTransformerControl — Type
PowerTransformerControlTransformer outer-loop transformer controller channel.
Sparlectra.PowerTransformerTaps — Type
PowerTransformerTapsA mutable structure representing the tap settings of a power transformer.
Fields
step::Int: The actual step/position.lowStep::Int: The lowest step/position.highStep::Int: The highest step/position.neutralStep::Int: The neutral step/position.voltageIncrement_kV::Float64: The voltage increment per step in kV.neutralU::Float64: The voltage at the neutral step, usually equal to the rated voltage of the transformer end, but can deviate.neutralU_ratio::Float64: The ratio of the neutral voltage to the rated voltage.tapStepPercent::Float64: The percentage change in voltage per step.tapSign::Integer: The direction of the tap changer, 1 for increasing voltage with increasing step, -1 for decreasing.
Constructors
PowerTransformerTaps(; Vn_kV::Float64, step::Int, lowStep::Int, highStep::Int, neutralStep::Int, voltageIncrement_kV::Float64, neutralU::Union{Nothing,Float64} = nothing, neutralU_ratio::Union{Nothing,Float64} = nothing): Creates a newPowerTransformerTapsinstance.
Methods
Base.show(io::IO, x::PowerTransformerTaps): Prints thePowerTransformerTapsinstance.
Sparlectra.PowerTransformerWinding — Type
PowerTransformerWindingA mutable structure representing a winding of a power transformer.
Fields
Vn::Float64: The rated voltage of the winding in kV.r::Float64: The resistance of the winding in Ohm.x::Float64: The reactance of the winding in Ohm.b::Union{Nothing,Float64}: The susceptance of the winding in S.g::Union{Nothing,Float64}: The conductance of the winding in S.ratio::Union{Nothing,Float64}: The turns ratio of the winding.shift_degree::Union{Nothing,Float64}: The phase shift of the winding in degrees.ratedU::Union{Nothing,Float64}: The rated voltage of the winding.ratedS::Union{Nothing,Float64}: The rated power of the winding.taps::Union{Nothing,PowerTransformerTaps}: The tap settings of the winding.controls::Vector{PowerTransformerControl}: Controllers assigned to this winding side.isPu_RXGB::Union{Nothing,Bool}: Whether the resistance, reactance, susceptance, and conductance are given in per unit.modelData::Union{Nothing,TransformerModelParameters}: The model parameters of the transformer._isEmpty::Bool: Whether the has no model data.
Constructors
PowerTransformerWinding(Vn::Float64, r::Float64, x::Float64, b::Union{Nothing,Float64} = nothing, g::Union{Nothing,Float64} = nothing, ratio::Union{Nothing,Float64} = nothing, shift_degree::Union{Nothing,Float64} = nothing, ratedU::Union{Nothing,Float64} = nothing, ratedS::Union{Nothing,Float64} = nothing, taps::Union{Nothing,PowerTransformerTaps} = nothing, isPu_RXGB::Union{Nothing,Bool} = nothing, modelData::Union{Nothing,TransformerModelParameters} = nothing): Creates a newPowerTransformerWindinginstance.PowerTransformerWinding(; Vn_kV::Float64, modelData::Union{Nothing,TransformerModelParameters} = nothing, ratio::Union{Nothing,Float64} = nothing, shift_degree::Union{Nothing,Float64} = nothing, ratedU::Union{Nothing,Float64} = nothing, ratedS::Union{Nothing,Float64} = nothing, taps::Union{Nothing,PowerTransformerTaps} = nothing): Creates a newPowerTransformerWindinginstance.
Methods
Base.show(io::IO, x::PowerTransformerWinding): Prints thePowerTransformerWindinginstance.
Sparlectra.create3WTWindings! — Method
create3WTWindings!(; u_kV::Array{Float64,1}, sn_MVA::Array{Float64,1}, addEx_Side::Array{TransformerModelParameters,1}, sh_deg::Array{Float64,1}, tap_side::Int, tap::PowerTransformerTaps)::Tuple{PowerTransformerWinding,PowerTransformerWinding,PowerTransformerWinding}Creates windings for a three-winding transformer using the MVA method.
Arguments
u_kV::Array{Float64,1}: The rated voltages of the windings in kV.sn_MVA::Array{Float64,1}: The rated powers of the windings in MVA.addEx_Side::Array{TransformerModelParameters,1}: The additional parameters for each side of the transformer.sh_deg::Array{Float64,1}: The phase shift of each winding in degrees.tap_side::Int: The number of the tap side [1,2,3]. It is 0 if there is no tap.tap::PowerTransformerTaps: The tap settings of the winding.
Returns
Returns a tuple of PowerTransformerWinding instances for the three windings of the transformer.
Example
create3WTWindings!(u_kV = [110.0, 20.0, 10.0], sn_MVA = [100.0, 80.0, 20.0], addEx_Side = [tmp1, tmp2, tmp3], sh_deg = [0.0, 0.0, 0.0], tap_side = 1, tap = tapSettings)Sparlectra.adjacentBranches — Function
adjacentBranches: Find adjacent branches for each node in the network.
Parameters:
Y::AbstractMatrix{ComplexF64}: Admittance matrix of the network.log::Bool = false: Optional parameter indicating whether to print the adjacent branches (default is false).
Returns:
adjList::Vector{Vector{Int}}: Vector of vectors containing the indices of adjacent branches for each node.
Sparlectra.branchFlow_pu — Method
branchFlow_pu(branch::Branch, from::Int, to::Int, tapSide::Int, V::Vector{ComplexF64})Calculate branch flow in per unit for a given branch and voltage vector.
Arguments
branch::Branch: The branch for which to calculate flowfrom::Int: From bus indexto::Int: To bus indextapSide::Int: Tap side (1 or 2)V::Vector{ComplexF64}: Voltage vector in per unit
Returns
ComplexF64: Branch flow in per unit
Sparlectra.calcNeutralU — Method
calcNeutralU(neutralU_ratio::Float64, vn_hv::Float64, tap_min::Integer, tap_max::Integer, tap_step_percent::Float64)::Float64Calculates the neutral voltage of a transformer based on the given parameters.
Arguments
neutralU_ratio::Float64: The ratio of the neutral voltage to the rated high voltage.vn_hv::Float64: The rated high voltage of the transformer.tap_min::Integer: The minimum tap position.tap_max::Integer: The maximum tap position.tap_step_percent::Float64: The percentage change in voltage per tap step.
Returns
Float64: The calculated neutral voltage.
Example
```julia neutral_voltage = calcNeutralU(1.0, 110.0, -10, 10, 1.25)
Sparlectra.calcVKDependence — Method
calcVKDependence(xTaps::Vector{Int}, yVKs::Vector{Float64}, tapPos::Float64)::Float64Calculates the voltage dependence on the tap position using cubic spline interpolation.
Arguments
xTaps::Vector{Int}: A vector of tap positions.yVKs::Vector{Float64}: A vector of corresponding voltage values.tapPos::Float64: The current tap position for which the voltage is to be calculated.
Returns
Float64: The interpolated voltage value at the given tap position.
Example
```julia xTaps = [1, 2, 3, 4, 5] yVKs = [1.0, 1.1, 1.2, 1.3, 1.4] tapPos = 2.5 voltage = calcVKDependence(xTaps, yVKs, tapPos)
Sparlectra.createYBUS — Method
createYBUS(branchVec::Vector{Branch}, shuntVec::Vector{Shunt}, isoNodes::Vector{Int}, sparse::Bool = true, printYBUS::Bool = false)Creates the bus admittance matrix (YBUS) of the network.
Arguments
branchVec::Vector{Branch}: The vector of branches in the network.shuntVec::Vector{Shunt}: The vector of shunts in the network.isoNodes::Vector{Int}: The vector of isolated nodes in the network.sparse::Bool: A flag to indicate if the YBUS matrix should be sparse. Default istrue.printYBUS::Bool: A flag to indicate if the YBUS matrix should be printed. Default isfalse.
Returns
Y::Matrix{ComplexF64}: The bus admittance matrix (YBUS).
Sparlectra.cubicSplineCoefs — Method
cubicSplineCoefs(x::Vector{Float64}, y::Vector{Float64})::Tuple{Vector{Float64}, Vector{Float64}, Vector{Float64}, Vector{Float64}}Calculates the coefficients of the cubic spline interpolation for the given data points.
Arguments
x::Vector{Float64}: A vector of x-coordinates of the data points.y::Vector{Float64}: A vector of y-coordinates of the data points.
Returns
a::Vector{Float64}: The coefficients for the cubic term.b::Vector{Float64}: The coefficients for the quadratic term.c::Vector{Float64}: The coefficients for the linear term.d::Vector{Float64}: The coefficients for the constant term.
Example
```julia x = [1.0, 2.0, 3.0, 4.0] y = [1.0, 4.0, 9.0, 16.0] a, b, c, d = cubicSplineCoefs(x, y)
Sparlectra.fromPU_RXBG — Method
fromPU_RXBG(r_pu::Float64, x_pu::Float64, g_pu::Union{Nothing,Float64} = nothing, b_pu::Union{Nothing,Float64} = nothing, v_kv::Float64, baseMVA::Float64)::Tuple{Float64,Float64,Float64,Float64}Converts the resistance, reactance, conductance, and susceptance from per unit to physical units.
Arguments
r_pu::Float64: The per unit resistance.x_pu::Float64: The per unit reactance.g_pu::Union{Nothing, Float64}: The per unit conductance. It can beNothingor aFloat64value.b_pu::Union{Nothing, Float64}: The per unit susceptance. It can beNothingor aFloat64value.v_kv::Float64: The voltage in kV.baseMVA::Float64: The base power in MVA.
Returns
r::Float64: The resistance in Ohm.x::Float64: The reactance in Ohm.g::Float64: The conductance in S.b::Float64: The susceptance in S.
Example
fromPU_RXBG(r_pu = 0.01, x_pu = 0.1, g_pu = 0.02, b_pu = 0.02, v_kv = 110.0, baseMVA = 100.0)Sparlectra.toPU_RXBG — Method
toPU_RXGB(; r::Float64, x::Float64, g::Union{Nothing, Float64}=nothing, b::Union{Nothing, Float64}=nothing, v_kv::Float64, baseMVA::Float64)::Tuple{Float64, Float64, Float64, Float64}Converts the resistance, reactance, conductance, and susceptance from physical units to per unit.
Arguments
r::Float64: The resistance in Ohm.x::Float64: The reactance in Ohm.g::Union{Nothing, Float64}: The conductance in S. It can beNothingor aFloat64value.b::Union{Nothing, Float64}: The susceptance in S. It can beNothingor aFloat64value.v_kv::Float64: The voltage in kV.baseMVA::Float64: The base power in MVA.
Returns
r_pu::Float64: The per unit resistance.x_pu::Float64: The per unit reactance.g_pu::Float64: The per unit conductance.b_pu::Float64: The per unit susceptance.
Example
toPU_RXGB(r = 0.01, x = 0.1, g = 0.02, b = 0.02, v_kv = 110.0, baseMVA = 100.0)Sparlectra._runpf_with_config! — Method
runpf!(net, maxIte, tolerance=1e-6, verbose=0; method=:rectangular)Unified AC power flow interface.
Arguments:
net::Net: networkmaxIte::Int: maximum iterationstolerance::Float64: mismatch toleranceverbose::Int: verbosity levelmethod::Symbol: must be:rectangularautodamp::Bool: enable residual-based backtracking for rectangular Newton stepsautodamp_min::Float64: minimum automatic damping factor whenautodamp = trueqlimit_start_iter::Int: first Newton iteration where PV→PQ Q-limit switching may run in:iterationmodeqlimit_start_mode::Symbol::iteration,:auto_q_delta, or:iteration_or_autostart criterion for PV→PQ switchingqlimit_auto_q_delta_pu::Float64: PV reactive-power request change threshold for automatic switching start
Notes:
- Link-flow recovery (
calcLinkFlowsKCL!) is method-agnostic and uses solved PF results. - If active-link merges create internal isolated buses, the rectangular sparse solver remains the only supported PF path; there is no polar fallback.
Returns: (iterations::Int, status::Int)
where status == 0 indicates convergence.
Sparlectra.build_complex_jacobian — Method
build_complex_jacobian(Ybus, V)Builds the 2n × 2n Wirtinger-type Jacobian blocks for the complex-state Newton–Raphson formulation.
Given: I = Ybus * V S = V .* conj.(I)
We construct the blocks: J11 = ∂S/∂V J12 = ∂S/∂V* J21 = ∂conj(S)/∂V J22 = ∂conj(S)/∂V*
Returns: J11, J12, J21, J22 (all full matrices, not Diagonal)
Sparlectra.build_rectangular_jacobian_pq_pv — Method
build_rectangular_jacobian_pq_pv(
Ybus::SparseMatrixCSC{ComplexF64},
V,
bus_types,
Vset,
slack_idx;
)Sparlectra.build_rectangular_jacobian_pq_pv_dense — Method
build_rectangular_jacobian_pq_pv_dense(
Ybus, V, bus_types, Vset, slack_idx
) -> J::Matrix{Float64}Build the analytic rectangular Jacobian for the mismatch vector F(V) defined in mismatch_rectangular.
- State vector: x = [Vr(non-slack); Vi(non-slack)]
- Rows: for each non-slack bus i
- PQ: [ΔPi; ΔQi]
- PV: [ΔPi; ΔVi] with ΔVi = |Vi| - Vset[i]
bus_types and Vset must be consistent with mismatch_rectangular.
Sparlectra.build_rectangular_jacobian_pq_pv_sparse — Method
build_rectangular_jacobian_pq_pv_sparse(
Ybus,
V,
bus_types,
Vset,
slack_idx,
) -> SparseMatrixCSC{Float64}Builds the analytic rectangular Jacobian corresponding to mismatch_rectangular using the sparsity pattern of Ybus.
State vector: x = [Vr(non-slack); Vi(non-slack)] ∈ ℝ^(2(n-1))
Residual F(V): - PQ buses: ΔPi, ΔQi - PV buses: ΔPi, ΔVi - Slack bus: no equations
Jacobian entries are derived from Si(V) = Vi * conj( (Ybus * V)_i )
Wirtinger-based identities: ∂S/∂V = diag(conj(I)) + diag(V) * conj(Ybus) ∂S/∂V* = diag(V) * conj(Ybus)
Chain rule to rectangular: ∂S/∂Vr = ∂S/∂V + ∂S/∂V* ∂S/∂Vi = j(∂S/∂V - ∂S/∂V*)
With ΔPi = Re(ΔSi), ΔQi = Im(ΔSi), ΔVi = |Vi| - Vset[i].
Returns: J :: SparseMatrixCSC{Float64} with size (2(n-1)) × (2(n-1)).
Sparlectra.choose_rectangular_autodamp — Method
choose_rectangular_autodamp(Ybus, V, S, δx, F0; slack_idx, damp, autodamp_min, bus_types, Vset)Select a Newton step length for the rectangular power-flow solver by backtracking from damp toward autodamp_min. The first trial step that reduces the maximum absolute mismatch is accepted. If no trial reduces the mismatch, the smallest finite trial is returned so the solver can continue safely with a conservative step.
Returns (alpha, Vtrial, trial_mismatch).
Sparlectra.complex_newton_step_rectangular — Method
complex_newton_step_rectangular(
Ybus,
V,
S;
slack_idx,
damp,
bus_types,
Vset,
)Performs one Newton–Raphson step in rectangular coordinates using the analytic Jacobian that matches mismatch_rectangular.
- State: x = [Vr(non-slack); Vi(non-slack)]
- Residual: F(x) = mismatch_rectangular(...)
Sparlectra.mismatch_rectangular — Method
mismatch_rectangular(Ybus, V, S, bus_types, Vset, slack_idx) -> F::Vector{Float64}Compute the real-valued mismatch vector F(V) for the rectangular complex-state formulation with PQ and PV buses.
For each non-slack bus i:
if bustypes[i] == :PQ: ΔPi = Re(Scalc[i]) - Re(Sspec[i]) ΔQi = Im(Scalc[i]) - Im(S_spec[i])
if bustypes[i] == :PV: ΔPi = Re(Scalc[i]) - Re(Sspec[i]) ΔV_i = |V[i]| - Vset[i]
F is stacked as [ΔP2, ΔQ/ΔV2, ..., ΔPn, ΔQ/ΔVn] over all non-slack buses.
Sparlectra.project_rectangular_start — Method
project_rectangular_start(Ybus, Vraw, S, bus_types, Vset, slack_idx; ...)Build a projected initial voltage for the rectangular power-flow solver.
When enabled, the projection sanitizes the raw seed, optionally computes a DC-angle start from active-power injections and the Y-bus off-diagonal susceptances, and optionally scans convex blends between the raw and DC starts. The candidate with the lowest rectangular mismatch is returned.
Sparlectra.runpf_rectangular! — Function
runpf_rectangular!(net, maxIte, tolerance=1e-6, verbose=0)Runs a rectangular complex-state Newton–Raphson power flow on net::Net.
Returns: (iterations::Int, status::Int) where status == 0 indicates convergence.
Sparlectra.update_net_voltages_from_complex! — Method
update_net_voltages_from_complex!(net, V)Update the bus voltage magnitudes and angles in the network from the final complex voltages V (in per-unit).
Sparlectra.Measurement — Type
MeasurementGeneric state-estimation measurement model.
Fields:
typ: Measurement type.value: Measured value (Vm in p.u., powers in MW/MVar).sigma: Standard deviation in measurement units.weight: Weight used in WLS (1/sigma^2).active: Iffalse, measurement is ignored by estimator.busIdx: Bus index for bus measurements.branchIdx: Branch index for branch flow measurements.direction: Branch direction:fromor:to, otherwise:none.id: Optional measurement identifier.
Sparlectra.MeasurementType — Type
@enum MeasurementTypeSupported measurement types for the first WLS state-estimation implementation.
Sparlectra.addMeasurement! — Method
addMeasurement!(measurements; typ, value, sigma, active=true, busIdx=nothing, branchIdx=nothing, direction=:none, id="")Append a state-estimation measurement to measurements and return it.
Sparlectra.addPflowMeasurement! — Method
addPflowMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, active=true, id="")Append an active-power flow measurement identified by branchNr or a unique fromBus/toBus branch pair.
Sparlectra.addPinjMeasurement! — Method
addPinjMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append an active-power injection measurement identified by busName.
Sparlectra.addQflowMeasurement! — Method
addQflowMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, active=true, id="")Append a reactive-power flow measurement identified by branchNr or a unique fromBus/toBus branch pair.
Sparlectra.addQinjMeasurement! — Method
addQinjMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a reactive-power injection measurement identified by busName.
Sparlectra.addVmMeasurement! — Method
addVmMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a bus voltage-magnitude measurement identified by busName.
Sparlectra.addZeroInjectionMeasurements! — Method
addZeroInjectionMeasurements!(measurements; net, sigma=1e-6, busNames=nothing, busIdxs=nothing, active=true, idPrefix="ZI") -> Vector{Measurement}Append active- and reactive-power zero-injection pseudo-measurements for the selected buses and return the newly added measurements.
Selection rules:
- If
busIdxsis provided, those indices are used. - Else if
busNamesis provided, names are resolved to indices. - Else passive buses are detected automatically via
findPassiveBuses(net).
These pseudo-measurements are the current way to encode equality constraints P_inj = 0 and Q_inj = 0 in the WLS estimator.
Sparlectra.findPassiveBuses — Method
findPassiveBuses(net; atol=1e-9, includeSlack=false) -> Vector{Int}Return bus indices that have no generation, no load, and no shunt contribution within the given tolerance atol.
This is useful for state-estimation workflows where passive / transit buses are often modeled through zero-injection pseudo-measurements.
Sparlectra.generateMeasurementsFromPF — Method
generateMeasurementsFromPF(net; kwargs...) -> Vector{Measurement}Generate synthetic measurements from the current solved network state.
Keyword options:
includeVm,includePinj,includeQinj,includePflow,includeQflownoise: add Gaussian noise iftruestddev: dictionary fromMeasurementType => sigmarng: random number generator
Sparlectra.measurementStdDevs — Method
measurementStdDevs(; vm=0.005, pinj=1.0, qinj=1.0, pflow=1.0, qflow=1.0)Create default standard-deviation map for synthetic measurement generation.
Sparlectra.SEResult — Type
SEResultResult container for the first classical WLS state-estimation run.
Sparlectra.evaluate_global_observability — Method
evaluate_global_observability(net, measurements; kwargs...) -> NamedTupleEvaluate global observability on active measurements using the finite-difference measurement Jacobian.
Includes global redundancy metrics
redundancy = r = m - nredundancy_ratio = ρ = m / ndof = ν = m - n
Quality classes:
:good: observable and no critical single measurement:critical: observable, but at least one single critical measurement (or ν <= 0):not_observable: not observable
Sparlectra.evaluate_local_observability — Method
evaluate_local_observability(net, measurements, stateCols; kwargs...) -> NamedTupleEvaluate local observability on selected Jacobian columns (stateCols).
Procedure:
- Build global Jacobian
Hfrom currently active measurements. - Keep only rows that have at least one nonzero entry in the selected columns. These rows correspond to measurements that are locally sensitive to the requested states.
- Evaluate observability/redundancy on the reduced matrix
Hlocal.
Returned NamedTuple extends global metrics with:
rows: selected row indices (within global active-Jacobian row numbering)stateCols: copied input state-column selection.
Interpretation:
:goodmeans local states are observable with positive redundancy and no single critical measurement.:criticalmeans still observable but vulnerable to a single outage (or ν <= 0).:not_observablemeans local states cannot be uniquely reconstructed.
Sparlectra.evaluate_local_observability_matrix — Method
evaluate_local_observability_matrix(H, stateCols; tol=nothing) -> NamedTupleEvaluate local observability on a matrix H restricted to selected stateCols.
Sparlectra.evaluate_observability_matrix — Method
evaluate_observability_matrix(H; tol=nothing) -> NamedTupleEvaluate global observability and single-row criticality directly on a matrix H (without building a network model).
Sparlectra.numeric_rank — Method
numeric_rank(A; tol=nothing) -> IntCompute numerical matrix rank using singular values.
Sparlectra.numerical_observable — Method
numerical_observable(H; tol=nothing) -> BoolNumerical observability test on a Jacobian-like matrix H. Returns true when rank(H) == n (full column rank).
Sparlectra.numerical_row_redundant — Method
numerical_row_redundant(H, i; tol=nothing) -> BoolCheck if row i remains numerically redundant in H.
Sparlectra.print_se_diagnostics — Method
print_se_diagnostics(io, diag; topN=10)Pretty-print diagnostics from validate_measurements or runse_diagnostics including:
- explanation of
global_consistency - tabular measurement ranking
- BAD/OK marker per measurement
- optional rerun comparison if present
Sparlectra.runse! — Method
runse!(net, measurements; kwargs...) -> SEResultRun a first classical nonlinear weighted least-squares state estimator.
State representation:
- bus voltage angles for all non-slack buses (radians)
- bus voltage magnitudes for all buses (p.u.)
Sparlectra.runse_diagnostics — Method
runse_diagnostics(net, measurements; deactivate_and_rerun=false, kwargs...) -> NamedTupleExtended diagnostics workflow around validate_measurements with optional deactivate-and-rerun logic for the currently largest suspicious measurement.
Sparlectra.structural_observable — Method
structural_observable(H) -> BoolStructural observability test on a Jacobian-like matrix H. Returns true when the maximum bipartite matching size equals the number of state columns n.
Sparlectra.structural_row_redundant — Method
structural_row_redundant(H, i) -> BoolCheck if row i remains structurally redundant in H.
Sparlectra.summarize_se_diagnostics — Method
summarize_se_diagnostics(diag) -> NamedTupleCreate a compact interpretation summary for a diagnostics object returned by validate_measurements or runse_diagnostics.
global_consistency is interpreted as:
true: SE converged and objective is inside χ²-like 3σ plausibility bandfalse: either non-convergence or implausibly large objective
Sparlectra.validate_measurements — Method
validate_measurements(net, measurements; kwargs...) -> NamedTupleRun state-estimation diagnostics on currently active measurements and return a machine-readable report with:
- global bad-data consistency check (
global_consistency) - χ²-like objective plausibility summary
- largest-normalized-residual ranking
- suspicious measurement list (threshold-based)
Sparlectra.clearIsolatedBuses! — Method
clearIsolatedBuses!(; net::Net)Removes all isolated buses from the network.
Arguments
net::Net: The network from which to remove isolated buses.
Returns
Int: The number of isolated buses removed.
Example
clearIsolatedBuses!(net = network)Sparlectra.removeACLine! — Method
removeACLine!(; net::Net, fromBus::String, toBus::String)Removes an AC line between two buses from the network.
Arguments
net::Net: The network from which to remove the AC line.fromBus::String: The name of the bus where the line starts.toBus::String: The name of the bus where the line ends.
Returns
Bool: True if the AC line was successfully removed, false otherwise.
Example
removeACLine!(net = network, fromBus = "Bus1", toBus = "Bus2")Sparlectra.removeBranch! — Method
removeBranch!(; net::Net, branchNr::Int)Removes a branch from the network.
Arguments
net::Net: The network from which to remove the branch.branchNr::Int: The number of the branch to remove.
Returns
Bool: True if the branch was successfully removed, false otherwise.
Example
removeBranch!(net = network, branchNr = 1)Sparlectra.removeBus! — Method
removeBus!(; net::Net, busName::String)Checks if a bus could be removed from the network. Note: This function cannot actually remove the bus since Net is immutable, but it performs all validation checks.
Arguments
net::Net: The network to check.busName::String: The name of the bus to check.
Returns
Bool: True if the bus could be removed, false otherwise.
Example
removeBus!(net = network, busName = "Bus1")Sparlectra.removeTrafo! — Method
removeTrafo!(; net::Net, fromBus::String, toBus::String)Removes a transformer between two buses from the network.
Arguments
net::Net: The network from which to remove the transformer.fromBus::String: The name of the bus where the transformer starts.toBus::String: The name of the bus where the transformer ends.
Returns
Bool: True if the transformer was successfully removed, false otherwise.
Example
removeTrafo!(net = network, fromBus = "Bus1", toBus = "Bus2")Sparlectra.active_set_q_limits! — Method
active_set_q_limits!(
net, it, nb;
get_qreq_pu,
is_pv,
make_pq!,
make_pv!,
qmin_pu,
qmax_pu,
pv_orig_mask,
allow_reenable::Bool,
q_hyst_pu::Float64,
cooldown_iters::Int,
verbose::Int=0,
io::IO=stdout,
) -> (changed::Bool, reenabled::Bool)Core PV/Q-limit active-set logic shared by solvers.
Callbacks:
- getqreqpu(bus) -> Float64
- is_pv(bus) -> Bool
- makepq!(bus, qclamp_pu::Float64, side::Symbol) # side = :min/:max
- make_pv!(bus)
- onviolation!(bus, qreqpu::Float64, side::Symbol, qclamppu::Float64) -> Bool (optional; return true if violation was handled without PV->PQ fallback)
Sparlectra.getQLimits_pu — Method
getQLimits_pu(net::Net) -> (qmin_pu, qmax_pu)Return per-bus Q limits in p.u. (build once if empty).
Sparlectra.lastQLimitIter — Method
Returns the last iteration number where bus hit a Q-limit, or nothing.
Sparlectra.printFinalLimitValidation — Method
printFinalLimitValidation(net::Net; q_headroom::Float64=0.20, io::IO=stdout)Prints post-PF validation tables for violated Q limits and voltage limits. Returns (q_violations, v_violations).
Sparlectra.printPVQLimitsTable — Method
printPVQLimitsTable(net::Net; io::IO=stdout, max_rows::Int=30)Print a compact table of PV-bus reactive limits before the PF iteration starts. Values are shown in MVAr.
Sparlectra.printQLimitLog — Method
printQLimitLog(net::Net; sort_by=:iter, io::IO=stdout)Pretty-prints the structured Q-limit log (net.qLimitLog) as a small table.
Keyword arguments
sort_by::iter(default) or:bus— controls sorting.io: optional output stream (default =stdout).
Each line shows: where Side is :min or :max.
Sparlectra.pv_hit_q_limit — Method
pv_hit_q_limit(net, pv_names)Returns true if any of the PV buses from pv_names appears in net.qLimitEvents. pv_names is a list of bus names (strings).
Sparlectra.validate_q_limit_signs! — Method
validate_q_limit_signs!(qmin_pu, qmax_pu; io::IO=stdout, autocorrect::Bool=false, warn::Bool=true)Validate Q-limit sign conventions per bus:
- expect
qmin ≤ 0 - expect
qmax ≥ 0 - expect
qmin ≤ qmax
If autocorrect=true, suspicious sign-only limits are flipped and inverted ranges are swapped.
Sparlectra.calcLinkFlowsKCL! — Method
calcLinkFlowsKCL!(net::Net; tol::Float64 = 1e-6)Compute bus-link active/reactive flows from nodal KCL after a power-flow run, without introducing links into the YBUS matrix. Link direction uses the fromBus -> toBus sign convention.
For each bus i: sum(Plink,out - Plink,in) = Pinj(i) - Pbranch,out(i) (and analog for Q).
Algorithm overview:
- Build net nodal injections
P_inj/Q_injfrom static generation minus load. - Add solved shunt injections (
node._pShunt/_qShunt) to nodal injections. - Subtract outgoing terminal branch powers to get the link right-hand side
b. - Build oriented incidence matrix
Afor active links. - Solve per connected link component (BFS) using
pinv(A_component) * b_component. - If
sum(b_component)is not near zero, distribute the residual uniformly before solving so the component system becomes consistent. - Write resulting link P/Q flows and derive terminal currents from |S| and V_LL.
Notes:
tolis only used for the component residual-balancing step.- For meshed/singular components (e.g., rings),
pinvyields the minimum-norm least-squares solution consistent with KCL.
Sparlectra.calcNetLosses! — Method
calcNetLosses!(net::Net, V::Vector{ComplexF64})Calculates branch flows and network losses using an externally provided complex voltage vector V (typically from the final NR residual).
Sparlectra.calcNetLosses! — Method
calcNetLosses!(net::Net)Calculates branch flows and network losses for the given network.
This default method builds the complex voltage vector internally and forwards to calcNetLosses!(net, V). If the NR solver already has V available, it can call the two-argument variant directly to avoid recomputing V.
Sparlectra.ACPFlowReport — Type
ACPFlowReportStructured container for AC power flow results.
The vectors (nodes, branches, links, transformer_controls, q_limit_events) are table-like and can be converted directly to DataFrames if DataFrames.jl is available, e.g. DataFrame(report.nodes).
Fields
metadata: Global run/case metadata (solver, tolerance, elapsed time, losses, ...).nodes: Per-bus electrical state and power balance values.branches: Per-branch directional flows and losses.links: Link-flow values from KCL post-processing.transformer_controls: Tap-controller state rows with typedmissingfor non-applicable engineering values.q_limit_events: PV→PQ limit-hit markers.
Sparlectra._build_transformer_control_rows — Method
_build_transformer_control_rows(net::Net)Internal helper that mirrors transformer control state into table-like rows for ACPFlowReport.
Notes:
- Rows are intentionally typed for DataFrame conversion.
- Non-applicable controller fields remain
missing(not placeholder strings).
Sparlectra.buildACPFlowReport — Method
buildACPFlowReport(net::Net; ...)Builds a structured report object from solved network data. This provides a machine-readable alternative to printACPFlowResults.