Core Model Reference

Public API

Sparlectra.SparlectraModule
Sparlectra 0.11.1

Sparlectra 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
source
Sparlectra.BranchType
Branch

A mutable structure representing a branch in a power system.

Fields

  • comp::AbstractComponent: The component of the branch.
  • fromBus::Integer: The index of the bus where the branch starts.
  • toBus::Integer: The index of the bus where the branch ends.
  • r_pu::Float64: The per unit resistance of the branch.
  • x_pu::Float64: The per unit reactance of the branch.
  • b_pu::Float64: The per unit total line charging susceptance of the branch.
  • g_pu::Float64: The per unit total line charging conductance of the branch.
  • ratio::Float64: The transformer off nominal turns ratio.
  • angle::Float64: The transformer off nominal phase shift angle.
  • status::Integer: The status of the branch. 1 = in service, 0 = out of service.
  • sn_MVA::Union{Nothing,Float64}: The nominal power of the branch = rateA.
  • fBranchFlow::Union{Nothing,BranchFlow}: The flow from fromNodeID to toNodeID.
  • tBranchFlow::Union{Nothing,BranchFlow}: The flow from toNodeID to fromNodeID.
  • pLosses::Union{Nothing,Float64}: The active power losses.
  • qLosses::Union{Nothing,Float64}: The reactive power losses.

Constructors

  • Branch(; from::Int, to::Int, baseMVA::Float64, branch::AbstractBranch, id::Int, status::Integer = 1, ratio::Union{Nothing,Float64} = nothing, side::Union{Nothing,Int} = nothing, vn_kV::Union{Nothing,Float64} = nothing, fromOid::Union{Nothing,Int} = nothing, toOid::Union{Nothing,Int} = nothing): Creates a new Branch instance.

Methods

  • Base.show(io::IO, b::Branch): Prints the Branch instance.
source
Sparlectra.BranchFlowType
BranchFlow

A structure representing the flow in a branch of a power system.

Fields

  • vm_pu::Union{Nothing,Float64}: The voltage magnitude in per unit.
  • va_deg::Union{Nothing,Float64}: The voltage angle in degrees.
  • pFlow::Union{Nothing,Float64}: The active power flow.
  • qFlow::Union{Nothing,Float64}: The reactive power flow.

Constructors

  • BranchFlow(vm_pu::Union{Nothing,Float64} = nothing, va_deg::Union{Nothing,Float64} = nothing, pFlow::Union{Nothing,Float64} = nothing, qFlow::Union{Nothing,Float64} = nothing): Creates a new BranchFlow instance.

Methods

  • Base.show(io::IO, b::BranchFlow): Prints the BranchFlow instance.

Example

BranchFlow(vm_pu = 1.0, va_deg = 0.0, pFlow = 100.0, qFlow = 50.0)
source
Sparlectra.BranchModelType
BranchModel

A structure representing a branch model in a power system.

Fields

  • r_pu::Float64: The per unit resistance of the branch.
  • x_pu::Float64: The per unit reactance of the branch.
  • b_pu::Float64: The per unit total line charging susceptance of the branch.
  • g_pu::Float64: The per unit total line charging conductance of the branch.
  • ratio::Float64: The transformer off nominal turns ratio.
  • angle::Float64: The transformer off nominal phase shift angle.
  • sn_MVA::Union{Nothing,Float64}: The nominal power of the branch = rateA.

Constructors

  • BranchModel(; r_pu::Float64, x_pu::Float64, b_pu::Float64, g_pu::Float64, ratio::Float64, angle::Float64, sn_MVA::Union{Nothing,Float64} = nothing): Creates a new BranchModel instance.

Example

BranchModel(r_pu = 0.01, x_pu = 0.1, b_pu = 0.02, g_pu = 0.02, ratio = 1.0, angle = 0.0, sn_MVA = 100.0)
source
Sparlectra.applyTapNameplate!Method
applyTapNameplate!(branch; tap_step, tap_min_step, tap_max_step,
                   tap_current_step, phase_step_deg, phase_min_step,
                   phase_max_step, phase_current_step, psi_deg = 0.0,
                   phase_du_step = 0.0, context = "tap changer")

Apply nameplate tap-changer data to a transformer branch: the branch's own ratio/angle stay the NEUTRAL position, and the current steps move the LIVE tap_ratio/phase_shift_deg off it on the same mechanical grids the tap estimation fixes to.

  • Ratio changer: tap = neutral / (1 + n * tap_step) (cascade convention); a tap_step of 0 explicitly declares "no ratio tap changer" and keeps the transformer out of the estimator's mass release.
  • Phase changer, additional-voltage form (phase_du_step > 0): the mechanical grid is the additional-voltage amplitude r2 = n * phase_du_step along the nameplate direction psi_deg; the shift angle follows from the cascade and is NOT the grid.
  • Phase changer, degree form (phase_step_deg > 0): additive degrees on the neutral shift; the band is stored relative to neutral, which is what the fixation compares against.

phase_step_deg and phase_du_step are exclusive (a changer has one mechanical grid). context prefixes the error messages, so a MATPOWER mpc.sparlectra.tap_changers row and an SCF tap_changer entry report in their own vocabulary. This is the single tap-nameplate application path; every importer routes through it.

source
Sparlectra.calcAdmittanceMethod
calcAdmittance(branch, u_rated, s_rated) -> (yaa, yab, yba, ybb)

The four admittance-matrix entries of the branch on the given base, including ratio and phase shift.

source
Sparlectra.calcBranchYserBaseMethod
calcBranchYserBase(branch)

Series admittance from the PHYSICAL equipment impedance (r_base_pu/x_base_pu, issue #329). Short circuit and the CGMES/MATPOWER exports use this instead of calcBranchYser so a series-FACTS operating point stamped onto the live r_pu/x_pu does not leak into fault or interchange data. The power flow keeps using calcBranchYser (the live, compensated value).

source
Sparlectra.restoreBaseImpedances!Method
restoreBaseImpedances!(net)

Reset every branch's live series impedance (r_pu/x_pu) to its physical base (r_base_pu/x_base_pu), discarding any series-FACTS operating point that a power-flow control run stamped in place (#329). Non-FACTS branches are unchanged (their base equals the live value). Use this to return a net to its equipment model, for example before a second, independent study on the same net. Returns net.

source
Sparlectra.setBranchStatus!Method
setBranchStatus!(branch, service::Bool)

User-facing aggregate switch: sets the aggregate status and BOTH terminal flags consistently (in service = all closed, out of service = all open).

source
Sparlectra.setBranchTerminalStatus!Method
setBranchTerminalStatus!(branch; from = nothing, to = nothing)

Open or close individual branch terminals (true = closed, false = open; nothing leaves a terminal unchanged) and recompute the aggregate status (1 iff both terminals closed). A branch open at exactly one terminal stays in the model as its exact pi reduction at the closed bus, see the "One-sided open branches" section of the branch-model docs.

source
Sparlectra.BusDataType

Per-bus working record of the solvers: type, voltage state and the aggregated injections in per unit.

source
Sparlectra.buildVoltageVector_from_busVecMethod
buildVoltageVector_from_busVec(busVec::Vector{BusData}) -> Vector{ComplexF64}

Builds the complex voltage vector in NR ordering: Vnr[k] = busVec[k].vmpu * exp(j * busVec[k].va_rad)

This is the canonical source of V_nr for mapping and post-processing.

source
Sparlectra.getBusDataMethod
getBusData(nodes, Sbase_MVA, flatStart; net = nothing) -> Vector{BusData}

Build the per-bus solver records from the node vector.

source
Sparlectra.map_NR_voltage_to_net!Method
map_NR_voltage_to_net!(V_nr, busVec, net) -> V_net

Maps the NR-solver voltage vector V_nr (in busVec order) into the original bus index order used by net.nodeVec.

Returns a Vector{ComplexF64} such that: Vnet[busIdx] == Vnr[k] where k is the index in busVec with busVec[k].idx == busIdx.

source
Sparlectra.ComponentType
Component

A structure representing a component in a power system.

Fields

  • cID::String: The ID of the component.
  • cName::String: The name of the component.
  • cTyp::ComponentTyp: The type of the component.
  • cVN::Float64: The nominal voltage of the component in kV.

Constructors

  • Component(id::String, name::String, typ::ComponentTyp, vn::Float64): Creates a new Component instance with a specified nominal voltage.
  • Component(id::String, name::String, typ::ComponentTyp): Creates a new Component instance with a nominal voltage of 1 kV.
  • Component(id, name, cmp::String, Unenn::Float64): Creates a new Component instance with a specified nominal voltage and component type as a string.

Methods

  • Base.show(io::IO, x::Component): Prints the Component instance.

Example

Component("1", "Generator", "GENERATOR", 110.0)
source
Sparlectra.ComponentTypType

The component vocabulary of the model (buses, lines, transformers, machine and load kinds), shared by every importer.

source
Sparlectra.ImpPGMCompType

Component identity in the power-grid-model style: generated name, external id, component type, and the bus indices the element connects.

source
Sparlectra.ImpPGMComp3WTType

Component identity of a three-winding transformer, carrying all three bus indices next to the common identity fields.

source
Sparlectra.TrafoTypType

Transformer kinds: ratio transformer, phase shifter, phase tap changer, or a plain PI-model branch.

source
Sparlectra.adjacentBranchesFunction

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.
source
Sparlectra.branchFlow_puMethod
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 flow
  • from::Int: From bus index
  • to::Int: To bus index
  • tapSide::Int: Tap side (1 or 2)
  • V::Vector{ComplexF64}: Voltage vector in per unit

Returns

  • ComplexF64: Branch flow in per unit
source
Sparlectra.calcComplexRatioMethod
calcComplexRatio(; tapRatio, angleInDegrees) -> ComplexF64

The complex winding ratio from a magnitude ratio and a phase-shift angle.

source
Sparlectra.calcNeutralUMethod
calcNeutralU(neutralU_ratio::Float64, vn_hv::Float64, tap_min::Integer, tap_max::Integer, tap_step_percent::Float64)::Float64

Calculates 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)

source
Sparlectra.calcPhaseTapAngleRatioMethod
calcPhaseTapAngleRatio(m::PhaseTapChangerModel; step::Int = m.step) -> NamedTuple

Effective ratio/shift/regulating-vector of a CGMES phase-tap-changer model (ENTSO-E PST Modelling, CGMES v2.4, 2014-05-28) at the given tap step.

  • kind == :symmetrical (ch. 4.2): α = 2·atand(f/2), magnitude is always 1.0 (effective_ratio == 1.0 regardless of convention). With the default :reciprocal_from_side convention the returned effective_shift_deg is (mirroring calcSkewAngleTap's sign convention); :direct_regulating_vector returns .
  • kind == :asymmetrical (ch. 6.2, quadrature booster = ψ = 90°): delegates to calcSkewAngleTap(tap_fraction = f, skew_angle_deg = winding_connection_angle_deg, convention = m.convention) unchanged.
  • kind == :tabular: table OVERRIDES the formula path — delegates to calcPhaseTapTable for (effective_ratio, effective_shift_deg) and reconstructs regulating_vector as the exact inverse of calcSkewAngleTap's regulating-vector-to-(ratio,shift) mapping for m.convention (:reciprocal_from_side: regulating_vector = (1/ratio) * cis(-deg2rad(shift_deg)); :direct_regulating_vector: regulating_vector = ratio * cis(deg2rad(shift_deg))).

Returns

  • NamedTuple (effective_ratio, effective_shift_deg, regulating_vector).
source
Sparlectra.calcPhaseTapFractionMethod
calcPhaseTapFraction(m::PhaseTapChangerModel; step::Int = m.step) -> Float64

(step - neutralStep) * voltage_step_increment, the CGMES n-n₀ tap fraction f shared by the :symmetrical and :asymmetrical formulas in calcPhaseTapAngleRatio.

Failure behavior

Errors if m.voltage_step_increment is nothing. Always throws ArgumentError for kind == :tabular — a tabular model has no linear tap fraction, only discrete (ratio, angle_deg) rows (see calcPhaseTapTable).

source
Sparlectra.calcPhaseTapReactanceMethod
calcPhaseTapReactance(m::PhaseTapChangerModel, alpha_deg::Real) -> Union{Nothing,Float64}

CGMES series-reactance dependence on the phase-tap angle (ch. 3 summary table), evaluated at the given alpha_deg (typically the effective_shift_deg of calcPhaseTapAngleRatio at some step):

  • :symmetrical: X(α) = x_min + (x_max - x_min) * (sind(α/2) / sind(αmax/2))^2
  • :asymmetrical: X(α) = x_min + (x_max - x_min) * (tand(α) / tand(αmax))^2
  • :tabular: returns the x_pu of the m.table row at m.step (may be nothing); alpha_deg is ignored — the table is the single source of truth and carries no continuous angle dependence.

where (for the formula kinds) αmax is calcPhaseTapAngleRatio(m; step = m.highStep).effective_shift_deg. Squaring cancels any sign flip from m.convention, so the result does not depend on which convention was used to obtain alpha_deg as long as it is consistent with m.

Returns

  • Float64, or nothing if m.x_min/m.x_max (formula kinds) or the table row's x_pu (:tabular) is nothing.
source
Sparlectra.calcPhaseTapTableMethod
calcPhaseTapTable(m::PhaseTapChangerModel; step::Int = m.step) -> NamedTuple

Exact lookup of the m.table row for step (no interpolation between table steps — taps are discrete; continuous interpolation is deferred to a later, outer-loop-facing stage). Implemented as a linear findfirst scan over the already-validated, strictly ascending table — no Dict caching in this stage.

Returns

  • NamedTuple (effective_ratio, effective_shift_deg, x_pu), taken verbatim from the matching TapTablePoint (ratio, angle_deg, x_pu).

Failure behavior

Throws ArgumentError if m.table === nothing or if no row matches step.

source
Sparlectra.calcRatioTapCorrectionMethod
calcRatioTapCorrection(taps::PowerTransformerTaps; step::Int = taps.step) -> Float64

Multiplicative ratio-tap correction 1 + (step - neutralStep) * tapStepPercent/100 for the :neutral_relative convention (the only convention PowerTransformerTaps currently supports). Applied as a divisor on the winding ratio by calcTransformerRatio; this is the single source of truth for that formula, see docs/src/branchmodel.md.

Arguments

  • taps::PowerTransformerTaps: the tap-changer model.
  • step::Int: tap position to evaluate at; defaults to taps.step.

Returns

  • Float64: the correction factor (1.0 at the neutral step).
source
Sparlectra.calcRatioTapRangeMethod
calcRatioTapRange(taps::PowerTransformerTaps) -> NamedTuple

Ratio-terms tap range (tap_min, tap_max, tap_step), evaluated with calcRatioTapCorrection at lowStep and highStep: tap_min = min(corr(lowStep), corr(highStep)), tap_max = max(...), tap_step = abs(tapStepPercent / 100).

Returns

  • NamedTuple (tap_min, tap_max, tap_step).
source
Sparlectra.calcSkewAngleTapMethod
calcSkewAngleTap(; tap_fraction::Real, skew_angle_deg::Real, convention::Symbol = :reciprocal_from_side)

Convert a longitudinal regulating-voltage fraction and skew angle into the effective complex tap quantities used by transformer equivalent circuits.

The regulating vector is 1 + tap_fraction * cis(skew_angle_deg). With the default :reciprocal_from_side convention, the returned magnitude/angle represent the from-side off-nominal tap convention used by Sparlectra: the effective ratio multiplier is 1 / abs(regulating_vector) and the effective phase shift is -angle(regulating_vector).

source
Sparlectra.calcTapCorrectedRXMethod
calcTapCorrectedRX(; r_pu::Real, x_pu::Real, tap_changer_model::Symbol, tap_fraction::Union{Nothing,Real} = nothing, skew_angle_deg::Real = 0.0, ratio::Union{Nothing,Real} = nothing)

Apply the tap-changer impedance correction of calcTapImpedanceCorrectionFactor to a transformer series impedance. This is the central implementation used by both the MATPOWER and the native DTF importer; importers must not duplicate the correction math.

Returns

  • NamedTuple (r_pu, x_pu, factor) with the corrected per-unit series resistance/reactance and the applied correction factor.
source
Sparlectra.calcTapImpedanceCorrectionFactorMethod
calcTapImpedanceCorrectionFactor(; tap_changer_model::Symbol, tap_fraction::Union{Nothing,Real} = nothing, skew_angle_deg::Real = 0.0, ratio::Union{Nothing,Real} = nothing)::Float64

Return the multiplicative correction factor applied to the transformer series impedance (R and X) for the selected tap-changer model.

Sparlectra distinguishes two tap-changer models:

  • :ideal — the tap changer only changes the complex winding ratio; the short-circuit impedance keeps its neutral-position value (factor 1.0).
  • :impedance_correction — the tap changer acts on a physical winding, so the short-circuit impedance is re-referred through the tapped winding. R and X are scaled with $|1 + f e^{j\varphi}|^2$, where f is the additional-voltage fraction (tap_fraction) and $\varphi$ the skew angle in degrees (skew_angle_deg).

Callers provide either the regulating-vector parameters (tap_fraction and skew_angle_deg; used by the native DTF importer) or the effective Sparlectra off-nominal tap ratio (used by the MATPOWER importer). With Sparlectra's reciprocal from-side tap convention (ratio = 1 / |1 + f e^{jφ}|, see calcSkewAngleTap) both forms are equivalent; the ratio form yields 1 / ratio^2. A ratio of 0.0 (MATPOWER "no tap") or 1.0 is treated as neutral. When neither tap_fraction nor ratio is given, the factor is 1.0.

Arguments

  • tap_changer_model::Symbol: :ideal or :impedance_correction.
  • tap_fraction::Union{Nothing,Real}: longitudinal regulating-voltage fraction f.
  • skew_angle_deg::Real: skew angle of the additional voltage in degrees.
  • ratio::Union{Nothing,Real}: effective Sparlectra off-nominal tap ratio.

Returns

  • Float64: multiplicative factor for the series resistance and reactance.

Failure behavior

Throws an ArgumentError for an unsupported tap_changer_model value.

source
Sparlectra.createYBUSMethod
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 is true.
  • printYBUS::Bool: A flag to indicate if the YBUS matrix should be printed. Default is false.

Returns

  • Y::Matrix{ComplexF64}: The bus admittance matrix (YBUS).
source
Sparlectra.fromPU_RXBGMethod
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 be Nothing or a Float64 value.
  • b_pu::Union{Nothing, Float64}: The per unit susceptance. It can be Nothing or a Float64 value.
  • 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)
source
Sparlectra.toPU_RXBGMethod
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 be Nothing or a Float64 value.
  • b::Union{Nothing, Float64}: The susceptance in S. It can be Nothing or a Float64 value.
  • 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)
source
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)
source
Sparlectra.logQLimitHit!Method
logQLimitHit!(net, iter, bus, side)

Record a Q-limit hit (bus, iteration, min or max side) in the network's Q-limit log.

source
Sparlectra.printFinalLimitValidationMethod
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).

source
Sparlectra.printPVQLimitsTableMethod
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.

source
Sparlectra.printQLimitLogMethod
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.

source
Sparlectra.printQVCharacteristicCheckMethod
printQVCharacteristicCheck(net; io=stdout, band_pu=1e-4, converged=true) -> Vector{NamedTuple}

Print the qvCharacteristicViolations of the current solution and return them. On a non-converged solve the check is skipped with a note: the state is not a solution, so the question does not apply.

source
Sparlectra.pv_hit_q_limitMethod
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).

source
Sparlectra.qvCharacteristicViolationsMethod
qvCharacteristicViolations(net; band_pu = 1e-4) -> Vector{NamedTuple}

Generators that ended a solve AT a reactive limit while their voltage sits on the WRONG side of their own setpoint:

  • Q = Qmax with Vm > Vset, or
  • Q = Qmin with Vm < Vset.

Such a point satisfies the power-flow equations and still contradicts the physical Q-V characteristic: a machine that is already at its upper reactive limit cannot hold a voltage that is above its setpoint. The literature calls this a non-physical solution (Zeng, Chiang, Neves, Alberto, IJEPES 147 (2023) 108905) or an anomalous one (Sundaresh, Rao 2015), and it is a property of the PV/PQ switching strategy, not of the network.

Each row carries (bus, side, vm_pu, vset_pu, dv_pu, q_MVAr, limit_MVAr, significant). dv_pu is Vm - Vset and therefore signed; significant is abs(dv_pu) > band_pu. The band exists because a converged solve leaves voltages within its tolerance of the setpoint, so a bus that sits ON its setpoint can fall to either side by rounding. Report BOTH counts: the raw one is the literature's definition, the significant one is what a reader can act on.

Returns an empty vector when no bus hit a limit, and also when the state does not come from a converged solve (converged = false at the call site).

source
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.

source
Sparlectra.ACLineSegmentType

An AC line with its physical parameters (ohm, siemens per length or absolute) and the PI-model form the solver consumes.

source
Sparlectra.getLineRXBGMethod
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 be Nothing or a Float64 value.
  • g::Union{Nothing,Float64}: The conductance of the AC line segment. It can be Nothing or a Float64 value.

Example

getLineRXBG(acLineSegment)
source
Sparlectra.get_line_parametersMethod
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)
source
Sparlectra.BusLinkType
BusLink

Topological, 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.

source
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:

  1. Build net nodal injections P_inj/Q_inj from static generation minus load.
  2. Add solved shunt injections (node._pShunt/_qShunt) to nodal injections.
  3. Subtract outgoing terminal branch powers to get the link right-hand side b.
  4. Build oriented incidence matrix A for active links.
  5. Solve per connected link component (BFS) using pinv(A_component) * b_component.
  6. If sum(b_component) is not near zero, distribute the residual uniformly before solving so the component system becomes consistent.
  7. Write resulting link P/Q flows and derive terminal currents from |S| and V_LL.

Notes:

  • tol is only used for the component residual-balancing step.
  • For meshed/singular components (e.g., rings), pinv yields the minimum-norm least-squares solution consistent with KCL.
source
Sparlectra.calcLinkFlowsSE!Method
calcLinkFlowsSE!(net; tol=1e-6) -> Union{Nothing,Vector{NamedTuple}}

W2 link-flow allocation with measurements (SE phase 3): the KCL allocation of calcLinkFlowsKCL! extended to a weighted least-squares split per link component. Active link flow measurements on net.measurements (PflowMeas/ QflowMeas with a linkIdx) enter as extra rows f_j = z_j with weight 1/sigma^2 (P rows into the P solve, Q rows into the Q solve); the nodal balance rows keep weight 1. With no link measurements the result equals calcLinkFlowsKCL! exactly (shared core, identical code path).

Link measurements constrain only the flow split, never the system state: the estimator excludes them from the WLS (the link is not in the Ybus).

The balance construction reads solved branch flows (fBranchFlow/ tBranchFlow, filled by calcNetLosses!, which runse!(updateNet = true) calls) and the shunt injections (node._pShunt/_qShunt, refreshed by the SE write-back). Run after runse! with updateNet = true.

Returns one row per active link: (linkIdx, name, pFlow_MW, qFlow_MVar, source, p_meas_residual, q_meas_residual) with source = :kcl (no measurement on that link) or :measured_ls, and the measurement residuals f_est - z (NaN when unmeasured). nothing when the net has no active link.

source
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).

source
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.

source
Sparlectra.NetType

The in-memory network: buses, branches, prosumers, shunts, links and the run-level state the solvers read (Q-limit parameters, flat-start flag, measurements, solver status). Built by the importers or by the add*! constructors.

source
Sparlectra.add2WTPIModelTrafo!Method

Add a transformer with PI model to the network.

Arguments

  • net::Net: The network to which the transformer will be added.
  • fromBus::String: The name of the bus where the transformer originates.
  • toBus::String: The name of the bus where the transformer terminates.
  • r_pu::Float64: The per-unit resistance of the transformer.
  • x_pu::Float64: The per-unit reactance of the transformer.
  • b_pu::Float64: The per-unit susceptance of the transformer.
  • status::Int: The status of the transformer.
  • ratedU::Union{Nothing, Float64}: Rated voltage of the transformer. Default is nothing.
  • ratedS::Union{Nothing, Float64}: Rated apparent power of the transformer. Default is nothing.
  • ratio::Union{Nothing, Float64}: Ratio of the transformer. Default is nothing.
  • shift_deg::Union{Nothing, Float64}: Phase shift angle of the transformer. Default is nothing.
  • isAux::Bool: Whether the transformer is an auxiliary transformer. Default is false.
source
Sparlectra.add2WTrafo!Method

Add a two-winding transformer to the network.

Arguments

  • net::Net: The network to which the transformer will be added.
  • fromBus::String: The name of the bus where the transformer originates.
  • toBus::String: The name of the bus where the transformer terminates.
  • sn_mva::Float64: Rated power of the transformer.
  • vk_percent::Float64: Voltage regulation percent of the transformer.
  • vkr_percent::Float64: Voltage regulation percent of the transformer.
  • pfe_kw::Float64: Iron loss of the transformer.
  • i0_percent::Float64: No-load current percent of the transformer.
  • status::Int: The status of the transformer. Default is 1.
source
Sparlectra.add3WTPiModelTrafo!Method

Add a 3-winding transformer using a star-equivalent with an internal AUX bus.

Implementation strategy:

  • Ensure an AUX bus exists (PQ, isAux=true) at the HV-side nominal voltage.
  • Add three 2-winding PI-model transformers: AUX – HB, AUX – MB, AUX – LV
  • Convert r/x/b to PU (using toPU_RXBG) for each branch (mainly for validation/logging). The actual insertion uses add2WTPIModelTrafo!, which performs the conversion internally.

Notes:

  • ratio is set to Uaux / Uside (HV/MV/LV) for MV and LV, and 1.0 for HB.
  • ratedU passed to add2WTPIModelTrafo! is the AUX-side rated voltage (HV), because the branch is defined from AUX (HV base) to the respective side.
source
Sparlectra.addACLine!Method

addACLine!: Adds an AC line segment to the network.

Parameters:

  • net::Net: Network object.
  • fromBus::String: Name of the "from" bus.
  • toBus::String: Name of the "to" bus.
  • length::Float64: Length of the line segment.
  • r::Float64: Resistance per Meter of the line segment.
  • x::Float64: Reactance per Meter of the line segment.
  • b::Union{Nothing,Float64} = nothing: Susceptance per Meter of the line segment (default is nothing).
  • c_nf_per_km::Union{Nothing,Float64} = nothing: Capacitance per Meter of the line segment in nF/km (default is nothing).
  • tanδ::Union{Nothing,Float64} = nothing: Tangent of the loss angle (default is nothing).
  • ratedS::Union{Nothing, Float64}= nothing: Rated power of the line segment in MVA (default is nothing).
  • status::Int = 1: Status of the line segment (default is 1).
source
Sparlectra.addBus!Method
addBus!(; net, busName, vn_kV, ...)

Add a bus to the network. Voltage limits default to the network's; area, zone and the source bus number are optional identity data.

source
Sparlectra.addBusGenPower!Method

Add active/reactive power to the NODE-level generation sum of a bus (node._pƩGen/node._qƩGen).

Report layer only — no solver reads this

Every solver builds its injections from the PROSUMER objects (buildComplexSVec reads net.prosumpsVec; since 0.9.12 the DC solver uses the same source, issue #323), so this edit does NOT change any solve. The node sums feed reporting, MATPOWER export, and measurement generation. To change what the solvers compute, edit the prosumer (e.g. ps.pVal/ps.qVal) or add one (addProsumer!).

Arguments

  • net::Net: The network object.
  • busName::String: The name of the bus.
  • p::Union{Nothing, Float64}: active power to add in MW. Default nothing.
  • q::Union{Nothing, Float64}: reactive power to add in MVAr. Default nothing.
source
Sparlectra.addBusLoadPower!Method

Add active/reactive power to the NODE-level load sum of a bus (node._pƩLoad/node._qƩLoad).

Report layer only — no solver reads this

Every solver builds its injections from the PROSUMER objects (buildComplexSVec reads net.prosumpsVec; since 0.9.12 the DC solver uses the same source, issue #323), so this edit does NOT change any solve. The node sums feed reporting, MATPOWER export, and measurement generation. To add load the solvers see, add a prosumer instead: addProsumer!(net = net, busName = ..., type = "LOAD", p = ..., q = ...).

Arguments

  • net::Net: The network object.
  • busName::String: The name of the bus.
  • p::Union{Nothing, Float64}: active power to add in MW. Default nothing.
  • q::Union{Nothing, Float64}: reactive power to add in MVAr. Default nothing.
source
Sparlectra.addExternalGrid!Method
addExternalGrid!(; net, busName, sk_max_MVA, kwargs...)

Add an external grid (IEC 60909-0 network feeder, issue #299): the ideal voltage source of the superordinate network plus its declared short-circuit data.

Load-flow side: by default the connection bus becomes the reference (REF) bus, exactly as a manually added slack-type prosumer does — the external grid is ideal in the power flow, and the short-circuit attributes change no power-flow result (participationFactor precedent). With internal_impedance = true the source instead becomes non-ideal: a hidden auxiliary bus <busName>__extgrid_int carries the reference voltage, and a series branch with z_pu = baseMVA / sk_max_MVA (voltage factor c = 1 — the c-factor is a short-circuit concept), split by rx_max, connects it to the terminal bus. The terminal bus then stays an ordinary solved bus. The auxiliary bus is tagged isAux; expect it in reports under its generated name. Very large sk_max_MVA values degrade Jacobian conditioning — use the default ideal representation when ideal behavior is wanted.

Short-circuit side: sk_max_MVA (and optionally sk_min_MVA) with the rx_max/rx_min ratios are converted at add time into the feeder record consumed by runShortCircuit! — anchored at the physical connection bus also in the internal_impedance variant (the auxiliary branch is a dead end in the short-circuit network and carries no fault current).

Arguments

  • net::Net: the network.
  • busName::String: connection bus (must exist).
  • vm_pu::Float64 = 1.0, va_deg::Float64 = 0.0: reference voltage.
  • sk_max_MVA::Float64: declared initial symmetrical short-circuit power, maximum case. Mandatory — without it the feeder cannot contribute to any short circuit.
  • sk_min_MVA::Union{Nothing,Float64} = nothing: minimum case; without it the :min case skips the feeder with the engine's safety flag.
  • rx_max::Float64 = 0.1: R/X ratio, maximum case (IEC 60909-0 default).
  • rx_min::Union{Nothing,Float64} = nothing: R/X ratio, minimum case. Defaults to rx_max when sk_min_MVA is given, so a deliberately declared minimum feeder does not carry a spurious defaulted-data flag.
  • name::Union{Nothing,String} = nothing: feeder name (default busName).
  • internal_impedance::Bool = false: non-ideal load-flow variant (above).

Failure behavior: throws ArgumentError for a non-positive/non-finite sk_max_MVA, sk_min_MVA > sk_max_MVA, or negative R/X ratios. Multiple external grids on one bus are allowed and stack as parallel feeders.

source
Sparlectra.addLink!Method
addLink!(; net, fromBus, toBus, status = 1) -> Int

Add an impedance-less topological busbar link (e.g. a busbar coupler) between two buses of the SAME bus type, used for post-power-flow KCL allocation, and return its index in net.linkVec.

Links are NOT branches: they live in net.linkVec, carry no component object and no name, and the solver contracts closed-link clusters onto one electrical node. In particular, net.branchVec[end] right after this call is an UNRELATED branch; renaming or mutating it there silently corrupts a different element (this exact slip broke a demo case's same-name double-circuit exercise, 2026-09-03). Address links by the returned index, e.g. through setNetLinkStatus!.

source
Sparlectra.addPIModelACLine!Method
addPIModelACLine!(; net, fromBus, toBus, r_pu, x_pu, b_pu, status, ...)

Add an AC line branch from PI-model per-unit parameters.

source
Sparlectra.addPIModelTrafo!Method
addPIModelTrafo!(; net, fromBus, toBus, r_pu, x_pu, ...)

Add a two-winding transformer branch from PI-model per-unit parameters.

source
Sparlectra.addProsumer!Method

Add a prosumer (combination of a producer and consumer) to the network.

Arguments

  • net::Net: The network to which the prosumer will be added.
  • busName::String: The name of the bus where the prosumer is connected.
  • type::String: The type of the prosumer.
  • p::Union{Nothing, Float64}: Active power produced or consumed. Default is nothing.
  • q::Union{Nothing, Float64}: Reactive power produced or consumed. Default is nothing.
  • pMin::Union{Nothing, Float64}: Minimum active power. Default is nothing.
  • pMax::Union{Nothing, Float64}: Maximum active power. Default is nothing.
  • qMin::Union{Nothing, Float64}: Minimum reactive power. Default is nothing.
  • qMax::Union{Nothing, Float64}: Maximum reactive power. Default is nothing.
  • referencePri::Union{Nothing, String}: Reference bus for the prosumer. Default is nothing.
  • vm_pu::Union{Nothing, Float64}: Voltage magnitude setpoint. Default is nothing.
  • va_deg::Union{Nothing, Float64}: Voltage angle setpoint. Default is nothing.
  • isRegulated::Bool: Marks a prosumer as voltage-regulating for PV bus resolution. Default is false.
source
Sparlectra.addShunt!Method
addShunt!(; net, busName, pShunt, qShunt, in_service=1)

Adds a Y-model shunt to the network.

Semantics:

  • pShunt, qShunt are interpreted as MW/MVar at V = 1.0 pu (MATPOWER-style).
  • Internally, the shunt is represented as a pu-admittance stamped into YBUS: ypu = (pShunt + j*qShunt) / baseMVA when `busshunt_model = "admittance"`.
  • When bus_shunt_model = "voltage_dependent_injection", the same pu-admittance is excluded from YBUS and contributes -|V|^2 * conj(y_pu) to the specified net injection.
  • The shunt power is not constant; it depends on |V|² and will be computed after solving via updateShuntPowers!(net).

IMPORTANT:

  • This does NOT call addShuntPower! or add a constant-power shunt load.
  • In voltage-dependent injection mode, the solver adds only the voltage-dependent equivalent term to the injection/mismatch path.
source
Sparlectra.addShuntMatpower!Method
addShuntMatpower!(; net, busName, Gs, Bs, in_service=1)

MATPOWER semantics:

  • Gs/Bs are shunt admittance parameters given as MW/MVAr at V = 1.0 pu.
  • Internally we stamp them as pu-admittance: y_pu = (Gs + j*Bs)/baseMVA.
  • IMPORTANT: do NOT add fixed P/Q to the bus power balance.
source
Sparlectra.buildComplexSVecMethod
buildComplexSVec(net) -> S::Vector{ComplexF64}

Build the specified complex power injection vector S = P + jQ in per-unit for each bus, based on the net's bus load / generation / shunt data. Positive P/Q means net injection into the bus (generation), negative means net consumption (load).

source
Sparlectra.buildControlledSVecMethod
buildControlledSVec(net, V) -> (Sspec, dPinj_dVm, dQinj_dVm)

Evaluate bus injections for the current voltage state. If a prosumer carries a PUController and/or QUController, the corresponding active/reactive setpoint is evaluated as a function of local bus voltage magnitude. The derivative vectors contain dP_spec/d|V| and dQ_spec/d|V| (both in p.u. per p.u.).

source
Sparlectra.buildVoltageVectorMethod
buildVoltageVector(net::Net) -> Vector{ComplexF64}

Builds the complex bus voltage vector V[k] = vmpu[k] * exp(j * varad[k]) using the current nodal state stored in net.nodeVec.

source
Sparlectra.bus_shunt_totals_puMethod
bus_shunt_totals_pu(net) -> NamedTuple

Return the count and total per-unit conductance/susceptance of in-service bus shunts. The totals are based on the stored shunt admittances and are useful for compact import/configuration logging.

source
Sparlectra.convertSlackToExternalGrid!Method
convertSlackToExternalGrid!(; net, sk_max_MVA, kwargs...) -> String

Replace the marked slack bus by a non-ideal external-grid source (issue #299): the slack marker moves to a hidden internal bus behind the feeder impedance, so the former slack bus becomes an ordinary solved bus whose voltage reacts to loading.

Steps: the slack prosumers at the bus are demoted (reference marker and voltage regulation removed — their scheduled p/q injections stay), and addExternalGrid! with internal_impedance = true is added at the bus, carrying the former slack's voltage setpoint as the source's reference voltage. With multiple slack buses (island references) only the addressed bus is converted — every other island keeps its reference.

Arguments

  • net::Net: the network.
  • busName::Union{Nothing,String} = nothing: slack bus to convert; default is the primary (first registered) slack bus.
  • sk_max_MVA, sk_min_MVA, rx_max, rx_min, name: forwarded to addExternalGrid!.

Returns a short human-readable note describing the conversion (for run logs). Failure behavior: throws ArgumentError when the net has no slack bus or busName is not a slack bus.

source
Sparlectra.ensureSlack!Method
ensureSlack!(net::Net; log::Bool = true) -> Union{Nothing,Int}

Make sure the network has a usable voltage reference. When at least one slack is already registered on a non-isolated bus, nothing changes and nothing is returned. Otherwise the strongest injection candidate on a non-isolated bus is promoted to slack (referencePri = 1) and its bus index is returned.

Candidate ranking: ExternalNetworkInjection units win over generators and synchronous machines (an external grid equivalent is the natural reference); within each group the largest unit wins, sized by ratedS, then maxP, then the current dispatch |p|. Static var compensators are never promoted — they carry no active power. When no candidate exists the network is left untouched and the regular no-slack error will name the situation.

The promotion mutates the network: the chosen prosumer becomes the reference and the bus voltage gets a 1.0 pu / 0.0° setpoint if it has none. Enabled at solve time via the power_flow.auto_slack configuration key (default false) or the auto_slack keyword of runpf!.

source
Sparlectra.geNetBusIdxMethod

geNetBusIdx: Gets the index of a bus in the network.

Parameters:

  • net::Net: Network object.
  • busName::String: Name of the bus.

Returns:

  • Int: Index of the bus in the network.
source
Sparlectra.getBusTypeMethod

Get the type of a specific bus in the network.

Arguments

  • net::Net: The network from which to retrieve the bus type.
  • busName::String: The name of the bus.

Returns

The type of the specified bus.

source
Sparlectra.getEffectiveBusTypeMethod
getEffectiveBusType(net, busIdx) -> NodeType

The bus type as the solver sees it, derived from the attached prosumers (slack wins over PV, PV over PQ).

source
Sparlectra.getNetBranchMethod
getNetBranch(; net::Net, fromBus::String, toBus::String)::Union{Branch,Nothing}

Retrieves the first branch found between two specified buses in the network.

Arguments

  • net::Net: The network.
  • fromBus::String: The name of the bus where the branch starts.
  • toBus::String: The name of the bus where the branch ends.

Returns

  • Union{Branch,Nothing}: The branch between the specified buses, or nothing if no such branch exists.

Example

```julia getNetBranch(net = network, fromBus = "Bus1", toBus = "Bus2")

source
Sparlectra.getNetBranchNumberVecMethod
setNetBranchStatus!(; net::Net, branchNr::Int, status::Int)

Sets the status of a branch in the network.

Arguments

  • net::Net: The network.
  • branchNr::Int: The number of the branch.
  • status::Int: The status of the branch. 1 = in service, 0 = out of service.

Example

  brVec = getNetBranchNumberVec(net = net, fromBus = "B1", toBus = "B2")  
  setNetBranchStatus!(net = net, branchNr = brVec[1], status = 0)
source
Sparlectra.getNetLinksMethod
getNetLinks(; net::Net, fromBus::String, toBus::String)::Vector{BusLink}

Returns all links between two buses (both directions).

source
Sparlectra.getNetOrigBusIdxMethod

getNetOrigBusIdx: Gets the original index of a bus in the network.

Parameters:

  • net::Net: Network object.
  • busName::String: Name of the bus.

Returns:

  • Int: Original index of the bus in the network.
source
Sparlectra.getShunt!Method
getShunt!(; net::Net, busName::String)::Shunt

Retrieves the shunt at the specified bus in the network.

Arguments

  • net::Net: The network.
  • busName::String: The name of the bus.

Returns

  • Shunt: The shunt at the specified bus.

Example

```julia getShunt!(net = network, busName = "Bus1")

source
Sparlectra.getTotalBusPowerMethod
getTotalBusPower(; net::Net)::Tuple{Float64, Float64}

Gets the total active and reactive power for the network.

Arguments

  • net::Net: The network.

Returns

  • n::Tuple{Float64, Float64}:

Example

getTotalBusPower(net = network)
source
Sparlectra.getTotalLossesMethod

Get the total losses in the network.

Arguments

  • net::Net: The network from which to retrieve the losses.

Returns

A tuple (pLosses::Float64, qLosses::Float64) containing the total active and reactive power losses in the network.

source
Sparlectra.get_bus_vn_kVMethod

Get the voltage magnitude of a specific bus in the network.

Arguments

  • net::Net: The network from which to retrieve the voltage magnitude.
  • busName::String: The name of the bus.

Returns

The voltage magnitude of the specified bus.

source
Sparlectra.get_vn_kVMethod

Get the voltage magnitude of a specific bus in the network.

Arguments

  • net::Net: The network from which to retrieve the voltage magnitude.
  • busIdx::Int: The index of the bus.

Returns

The voltage magnitude of the specified bus.

source
Sparlectra.hasBusInNetMethod

hasBusInNet: Checks if a bus exists in the network.

Parameters:

  • net::Net: Network object.
  • busName::String: Name of the bus to check.

Returns:

  • Bool: True if the bus exists in the network, otherwise false.
source
Sparlectra.hasShunt!Method
hasShunt!(; net::Net, busName::String)::Bool

Checks if a shunt exists at the specified bus in the network.

Arguments

  • net::Net: The network.
  • busName::String: The name of the bus.

Returns

  • Bool: True if a shunt exists at the specified bus, false otherwise.

Example

```julia hasShunt!(net = network, busName = "Bus1")

source
Sparlectra.initialVrectMethod
initial_Vrect_from_net(net) -> (V0, slack_idx)

Build the initial complex voltage vector V0 from the network bus data (Vm, Va), and detect the slack bus index.

Returns:

  • V0::Vector{ComplexF64}
  • slack_idx::Int
source
Sparlectra.lockNet!Method

Lock or unlock the network.

Arguments

  • net::Net: The network to be locked or unlocked.
  • locked::Bool: Boolean indicating whether to lock the network.
source
Sparlectra.log_bus_shunt_modelMethod
log_bus_shunt_model(net) -> Nothing

Emit a compact log message with the selected bus-shunt modeling mode, in-service bus-shunt count, and aggregate per-unit conductance/susceptance.

source
Sparlectra.normalize_bus_shunt_modelMethod
normalize_bus_shunt_model(value) -> Symbol

Validate and normalize the bus-shunt modeling option. Supported values are "admittance" and "voltage_dependent_injection".

source
Sparlectra.refreshBusTypesFromProsumers!Method
refreshBusTypesFromProsumers!(net)

Rebuild the effective bus types (slack, PV, PQ) from the attached prosumers. Called once per import; per-element calls made the reader quadratic.

source
Sparlectra.setNetBranchStatus!Method
setNetBranchStatus!(; net::Net, branchNr::Int, status::Int)

Sets the status of a branch in the network.

Arguments

  • net::Net: The network.
  • branchNr::Int: The number of the branch.
  • status::Int: The status of the branch. 1 = in service, 0 = out of service.

Example

setNetBranchStatus!(net = network, branchNr = 1, status = 1)
source
Sparlectra.setNodeAngle!Method
setBusAngle!(; net::Net, busName::String, va_deg::Float64)

Sets the voltage angle of a bus in the network.

Arguments

  • net::Net: The network.
  • busName::String: The name of the bus.
  • va_deg::Float64: The voltage angle in degrees.

Example

setBusAngle!(net = network, busName = "Bus1", va_deg = 5.0)
source
Sparlectra.setQLimits!Method
setQLimits!(; net, qmin_MVar, qmax_MVar, busName = nothing)

Set the reactive band of the regulating machines, at one bus, a list of buses, or everywhere when no name is given.

source
Sparlectra.setShuntEstimation!Method
setShuntEstimation!(net; busName, enabled=true)

Release (or freeze) the shunt at busName for state-estimation susceptance estimation (SE phase 2, case A). A released shunt contributes one additional state (its susceptance B in pu) to runse!, provided at least one active direct shunt measurement (ShuntQMeas or a bus-referenced ImagMeas) references its bus; without one the estimator freezes it at the model value with a warning. Errors when the bus carries no shunt. Returns the Shunt.

source
Sparlectra.setTotalBusPower!Method
setTotalBusPower!(; net::Net, p::Float64, q::Float64)

Sets the total active and reactive power at the buses in the network.

Arguments

  • net::Net: The network.
  • p::Float64: The total active power for the network.
  • q::Float64: The total reactive power for the network.

Example

setTotalBusPower!(net = network, p = 100.0, q = 50.0)
source
Sparlectra.setTotalLosses!Method

Set the total losses in the network.

Arguments

  • net::Net: The network to which the losses will be added.
  • pLosses::Float64: Total active power losses.
  • qLosses::Float64: Total reactive power losses.
source
Sparlectra.showNetMethod
showNet(io, net; verbose = false)

Print a component summary of the network; verbose lists the elements.

source
Sparlectra.updateBranchParameters!Method
updateBranchParameters!(;net::Net, fromBus::String, toBus::String, branch::AbstractBranch)

Updates the parameters of a branch in the network.

Arguments

  • net::Net: The network.
  • fromBus::String: The name of the bus where the branch starts.
  • toBus::String: The name of the bus where the branch ends.
  • branch::BranchModel: The branch with the updated parameters.

Example

updateBranchParameters!(net = network, fromBus = "Bus1", toBus = "Bus2", branch = updatedBranch)
source
Sparlectra.updateShuntPowers!Method
updateShuntPowers!(net; reset_node=true)

Recomputes shunt P/Q (MW/MVar) from solved bus voltages and shunt pu-admittances. Writes back:

  • sh.pshunt / sh.qshunt (results)
  • node.pShunt / node.qShunt (for reporting)
source
Sparlectra.validate!Method

Validate the network configuration.

Arguments

  • net::Net: The network to be validated.

Returns

A tuple (valid::Bool, message::String) where valid is a boolean indicating whether the network is valid, and message is a string containing an error message if the network is invalid.

source
Sparlectra.NodeType
Node

A 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 new Node instance.

Methods

  • Base.show(io::IO, node::Node): Prints the Node instance.
source
Sparlectra.setVmVa!Method
setVmVa!(; node, vm_pu, va_deg = nothing)

Set the voltage state of the node; a missing angle keeps the stored one.

source
Sparlectra.toNodeTypeMethod
toNodeType(x) -> NodeType

Map a MATPOWER bus-type number (or a string name) onto the NodeType enum.

source
Sparlectra.PUControllerMethod
PUController(characteristic; pmin_pu=nothing, pmax_pu=nothing,
             pmin_MW=nothing, pmax_MW=nothing, sbase_MVA=nothing)

Convenience constructor for PUController that accepts limits either in p.u. or in MW.

source
Sparlectra.PiecewiseLinearCharacteristicType
PiecewiseLinearCharacteristic(points)

Piecewise linear characteristic y = f(u) represented by ordered (u, y) points. Outside the point range, values are clamped to the edge points and the derivative is 0.0.

source
Sparlectra.ProSumerType
ProSumer

A mutable structure representing a prosumer in a power system. A prosumer is an entity that either produces or consumes power.

Fields

  • comp::AbstractComponent: The component of the prosumer.
  • busIdx::Int: The index of the bus where the prosumer is connected.
  • pGen::Float64: The active power generation of the prosumer.
  • qGen::Float64: The reactive power generation of the prosumer.
  • pLoad::Float64: The active power consumption of the prosumer.
  • qLoad::Float64: The reactive power consumption of the prosumer.
  • status::Int: The status of the prosumer. 1 = in service, 0 = out of service.

Constructors

  • ProSumer(comp::AbstractComponent, busIdx::Int, pGen::Float64, qGen::Float64, pLoad::Float64, qLoad::Float64, status::Int): Creates a new ProSumer instance.

Methods

  • Base.show(io::IO, prosumer::ProSumer): Prints the ProSumer instance.

Example

prosumer = ProSumer(comp, 1, 100.0, 50.0, 80.0, 40.0, 1)
source
Sparlectra.QUControllerMethod
QUController(characteristic; qmin_pu=nothing, qmax_pu=nothing,
             qmin_MVAr=nothing, qmax_MVAr=nothing, sbase_MVA=nothing)

Convenience constructor for QUController that accepts limits either in p.u. or in MVAr.

source
Sparlectra.evaluate_characteristicMethod
evaluate_characteristic(ch, u_pu) -> (value, slope)

Evaluate piecewise linear characteristic at u_pu.

For interior breakpoints (turning points), the implementation uses the segment found first during the left-to-right scan, i.e. the slope of the segment on the left side of the breakpoint. Outside the point range, the value is clamped and the returned slope is 0.0.

source
Sparlectra.evaluate_controllerMethod
evaluate_controller(ctrl, u_pu) -> Float64

Evaluate a voltage-dependent controller characteristic at the voltage u_pu and return the controlled quantity (Q or P) it demands there.

source
Sparlectra.getQGenReplacementMethod
getQGenReplacement(o) -> Union{Nothing,Float64}

The reactive output a Q-limit switch fixed for this machine, nothing while it regulates freely.

source
Sparlectra.isAPUNodeMethod
isAPUNode(o) -> Bool

Whether the prosumer marks its bus as an active-power/voltage (APU) node.

source
Sparlectra.isGeneratorMethod
isGenerator(x) -> Bool

Whether a prosumer (or prosumption type) injects power, as opposed to consuming it.

source
Sparlectra.isRegulatingMethod
isRegulating(o) -> Bool

Whether the machine takes part in voltage regulation: it is marked regulated or carries a step/tap voltage controller.

source
Sparlectra.make_characteristicMethod
make_characteristic(points; voltage_unit=:pu, value_unit=:pu, vn_kV=nothing, sbase_MVA=nothing, interpolation=:linear)

Create a piecewise linear characteristic from points in p.u. or physical units.

  • voltage_unit = :pu expects voltage in per-unit.
  • voltage_unit = :kV expects voltage in kV and requires vn_kV.
  • value_unit = :pu expects power output in per-unit.
  • value_unit = :MW or :MVAr expects physical power values and requires sbase_MVA.
  • interpolation = :linear uses piecewise linear interpolation.
  • interpolation = :spline uses natural cubic spline interpolation through all points. If only two points are provided, linear interpolation is used automatically.
  • interpolation = :polynomial uses one global polynomial through all points. If only two points are provided, linear interpolation is used automatically.
source
Sparlectra.toProSumptionTypeMethod
toProSumptionType(t) -> ProSumptionType

Map a component type (Generator, EnergyConsumer, ...) onto the coarse Injection/Consumption class.

source
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)
source
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")
source
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)
source
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")
source
Sparlectra.removeProsumer!Method
removeProsumer!(; net, busName, type = "") -> Bool

Remove a prosumer from the bus (optionally by type) and refresh the bus types; returns whether one was removed.

source
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")
source
Sparlectra.ACPFlowReportType
ACPFlowReport

Structured 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 typed missing for non-applicable engineering values.
  • q_limit_events: PV→PQ limit-hit markers.
  • hvdc_links: One row per HVDC link (net.hvdcLinks): terminal flows, loss, mode, rating, controller status (see _hvdc_link_flow_rows).
source
Sparlectra.buildACPFlowReportMethod
buildACPFlowReport(net::Net; ...)

Builds a structured report object from solved network data. This provides a machine-readable alternative to printACPFlowResults.

source
Sparlectra.printACPFlowResultsFunction
printACPFlowResults(net, ...; kwargs...)

Print the solved power-flow result tables (buses, branches, summary) to the console or a file.

source
Sparlectra.ShuntType

A bus shunt: its admittance in per unit, the nominal draw it was built from, its model (admittance or voltage-dependent injection) and status.

source
Sparlectra.AbstractTapChangerModelType
AbstractTapChangerModel

Supertype for tap-changer model structs attached to a PowerTransformerWinding (PowerTransformerTaps for the ratio-tap-changer case; further variants, e.g. a CGMES-style phase-tap-changer model, are staged separately). See docs/src/branchmodel.md for the overall layering.

source
Sparlectra.PhaseTapChangerModelType
PhaseTapChangerModel

A mutable structure representing a CGMES-style phase-tap-changer (PST) model, data only — the CGMES formulas are implemented in equicircuit.jl (calcPhaseTapFraction, calcPhaseTapAngleRatio, calcPhaseTapReactance, calcPhaseTapTable). See docs/src/branchmodel.md.

Fields

  • kind::Symbol: :symmetrical, :asymmetrical, or :tabular.
  • step::Int: The actual step/position.
  • lowStep::Int: The lowest step/position (auto-derived from table for :tabular if omitted).
  • highStep::Int: The highest step/position (auto-derived from table for :tabular if omitted).
  • neutralStep::Int: The neutral step/position; for :tabular it must be a step present in table.
  • voltage_step_increment::Union{Nothing,Float64}: u, per step, in per unit of rated voltage (cim:PhaseTapChangerNonLinear.voltageStepIncrement); must be nothing for :tabular.
  • step_phase_shift_increment::Union{Nothing,Float64}: Degrees per step for linear models (cim:PhaseTapChangerLinear.stepPhaseShiftIncrement).
  • winding_connection_angle_deg::Union{Nothing,Float64}: ψ, required for :asymmetrical (cim:PhaseTapChangerAsymmetrical.windingConnectionAngle). A quadrature booster is :asymmetrical with ψ = 90°. Must be nothing for :tabular.
  • x_min::Union{Nothing,Float64}: X(0) in per unit; must be nothing for :tabular.
  • x_max::Union{Nothing,Float64}: X(αmax) in per unit; must be nothing for :tabular.
  • convention::Symbol: sign/reciprocal convention forwarded to calcSkewAngleTap for :asymmetrical models, and used to reconstruct the regulating vector for :tabular models; default :reciprocal_from_side.
  • table::Union{Nothing,Vector{TapTablePoint}}: required, non-empty, strictly ascending/unique-by-step for :tabular; must be nothing otherwise. The table is the single source of truth whenever present — no formula reconstruction and no interpolation between steps.

Constructors

  • PhaseTapChangerModel(; kind::Symbol, step::Int, lowStep::Union{Nothing,Int} = nothing, highStep::Union{Nothing,Int} = nothing, neutralStep::Int, voltage_step_increment::Union{Nothing,Float64} = nothing, step_phase_shift_increment::Union{Nothing,Float64} = nothing, winding_connection_angle_deg::Union{Nothing,Float64} = nothing, x_min::Union{Nothing,Float64} = nothing, x_max::Union{Nothing,Float64} = nothing, convention::Symbol = :reciprocal_from_side, table::Union{Nothing,Vector{TapTablePoint}} = nothing): Creates a new PhaseTapChangerModel instance. lowStep/highStep are required for :symmetrical/:asymmetrical; for :tabular they are derived from table when omitted, and validated against it otherwise.

Methods

  • Base.show(io::IO, x::PhaseTapChangerModel): Prints the PhaseTapChangerModel instance.
source
Sparlectra.PowerTransformerTapsType
PowerTransformerTaps

A 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.
  • convention::Symbol: The ratio-tap correction convention. Only :neutral_relative is currently supported: the calcRatioTapCorrection factor is applied as a divisor on the winding ratio (ratio / corr), matching calcTransformerRatio.

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, convention::Symbol = :neutral_relative): Creates a new PowerTransformerTaps instance.

Methods

  • Base.show(io::IO, x::PowerTransformerTaps): Prints the PowerTransformerTaps instance.
source
Sparlectra.PowerTransformerWindingType
PowerTransformerWinding

A 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.
  • phase_taps::Union{Nothing,PhaseTapChangerModel}: The phase-tap-changer (PST) model of the winding, parallel to taps; nothing if this winding has no PST.

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, controls::Union{Nothing,Vector{PowerTransformerControl}} = nothing, phase_taps::Union{Nothing,PhaseTapChangerModel} = nothing): Creates a new PowerTransformerWinding instance.
  • 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, controls::Union{Nothing,Vector{PowerTransformerControl}} = nothing, phase_taps::Union{Nothing,PhaseTapChangerModel} = nothing): Creates a new PowerTransformerWinding instance.

Methods

  • Base.show(io::IO, x::PowerTransformerWinding): Prints the PowerTransformerWinding instance.
source
Sparlectra.TapTablePointType
TapTablePoint

An immutable row of a tabular phase-tap-changer characteristic (cim:PhaseTapChangerTablePoint / cim:TapChangerTablePoint): step maps to ratio/angle_deg (and optionally x_pu), overriding formula-based reconstruction whenever present on a PhaseTapChangerModel.

Fields

  • step::Int: cim:TapChangerTablePoint.step.
  • ratio::Float64: effective off-nominal ratio at this step, cim:TapChangerTablePoint.ratio.
  • angle_deg::Float64: effective phase shift in degrees at this step, cim:TapChangerTablePoint.angle.
  • x_pu::Union{Nothing,Float64}: series reactance in per unit at this step, cim:TapChangerTablePoint.x; nothing if not provided.

Constructors

  • TapTablePoint(; step::Int, ratio::Float64, angle_deg::Float64, x_pu::Union{Nothing,Float64} = nothing): Creates a new TapTablePoint instance.
source
Sparlectra.create2WTRatioTransformerNoTapsMethod
create2WTRatioTransformerNoTaps(; from, to, vn_hv_kV, vn_lv_kV, sn_mva, vk_percent, vkr_percent, pfe_kw, i0_percent) -> PowerTransformer

Build a two-winding ratio transformer from nameplate data, without a tap changer.

source
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, phase_tap_side::Int = 0, phase_taps::Union{Nothing,PhaseTapChangerModel} = nothing)::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.
  • phase_tap_side::Int = 0: Winding index [1,2,3] carrying a PhaseTapChangerModel (Schrägregler); 0 means none. Uses the same 1-based winding-index convention as tap_side. May equal tap_side — a ratio tap and a phase tap on the same winding is a valid configuration and is not rejected.
  • phase_taps::Union{Nothing,PhaseTapChangerModel} = nothing: The phase-tap-changer model attached at phase_tap_side. Must be nothing iff phase_tap_side == 0; a PhaseTapChangerModel is required whenever phase_tap_side != 0.

Returns

Returns a tuple of PowerTransformerWinding instances for the three windings of the transformer.

Note

Resolving phase_taps into an effective ratio/shift on the AUX-bus branch is out of scope for this function; it only stores the model on the selected winding's phase_taps field.

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)

With a phase-tap-changer model attached to winding 2:

psc = PhaseTapChangerModel(kind = :asymmetrical, step = 0, lowStep = -8, highStep = 8, neutralStep = 0, winding_connection_angle_deg = 60.0)
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, phase_tap_side = 2, phase_taps = psc)
source
Sparlectra.getTrafoImpPGMCompFunction
getTrafoImpPGMComp(aux, Vn, from, to, to3 = nothing) -> ImpPGMComp

Build the component identity of a transformer branch (name embeds voltage and bus numbers; aux marks a three-winding star leg).

source
Sparlectra.getTrafoRXBGMethod
getTrafoRXBG(o) -> (r, x, b, g)

The winding impedance and magnetising admittance as stored on the winding.

source
Sparlectra.getTrafoRXBG_puMethod
getTrafoRXBG_pu(o, vn_kV, baseMVA) -> (r, x, b, g)

The winding impedance and magnetising admittance converted to per unit on the given base.

source
Sparlectra.getWT3AuxBusIDMethod
getWT3AuxBusID(Vn, from, to, to3) -> String

The generated identity of the auxiliary star bus of a three-winding transformer.

source
Sparlectra.getWinding2WTMethod
getWinding2WT(x) -> PowerTransformerWinding

The winding that models a two-winding transformer (the one carrying the impedance).

source
Sparlectra.toStringMethod
toString(x) -> String

Human-readable name of an enum value (transformer type, prosumption type).

source

Internals

Sparlectra._branch_terminal_stateMethod
_branch_terminal_state(br::Branch) -> Symbol

Single source of truth for the service state of a branch: :closed (both terminals in service), :open_from / :open_to (exactly one terminal open, the branch reduces to its pi-model Schur complement at the closed bus), or :open (out of service: aggregate status == 0 with untouched terminal flags, or both flags open). Every consumer reads the state through this helper, never the raw fields.

source
Sparlectra._open_end_voltageMethod
_open_end_voltage(branch, u_closed::ComplexF64) -> ComplexF64

Voltage at the open terminal of a one-sided open branch from the pi-model voltage divider (zero current at the open end): with TO open U_open = -Y21/Y22 * U_from, with FROM open U_open = -Y12/Y11 * U_to. Reproduces the Ferranti rise (|U_open| > |U_closed| for b > 0) without adding a node to the solved system.

source
Sparlectra._open_terminal_yinMethod
_open_terminal_yin(branch) -> ComplexF64

Exact pi-model input admittance of a one-sided open branch seen from its closed bus, as the Schur complement of the two-port from calcAdmittance: with the TO end open Y_in = Y11 - Y12*Y21/Y22, with the FROM end open Y_in = Y22 - Y21*Y12/Y11. The two-port already carries the complex ratio, so lines and transformers (off-nominal ratio, phase shift) are covered uniformly without a case distinction. For |Y_s| >> |Y_0| this approaches the FULL line charging g + jb (not half of it).

source
Sparlectra.assertPhysicalBranchImpedancesMethod
assertPhysicalBranchImpedances(net, context)

Defensive check (#329): refuse to proceed when any branch carries a NEGATIVE BASE series resistance. A physical line/transformer has r >= 0. Since short circuit and the CGMES/MATPOWER exports read the base (equipment) impedance r_base_pu/x_base_pu, a series-FACTS operating point stamped onto the live r_pu/x_pu (e.g. a full UPFC's Re(z_add) < 0, #326) no longer reaches them; this assertion is therefore expected NOT to fire in the normal FACTS plus export/SC workflow. It stays as a last-resort guard against a corrupted base model. context names the caller (e.g. "CGMES export", "MATPOWER export").

source
Sparlectra.calc2WTEndsReferredRXGBMethod
calc2WTEndsReferredRXGB(; r1, x1, g1, b1, r2, x2, g2, b2, U1, U2) -> (r, x, g, b)

Refer the impedance/admittance contributions of both PowerTransformerEnds of a CGMES two-winding transformer to the end-2 voltage base and sum them. Each end's r,x [Ω] and g,b [S] are given on that end's own ratedU base (U1, U2 [kV]); real exports often put everything on one end, but this referral must not rely on it. Impedances scale with (U2/U1)², admittances with the inverse. The end-2 (to-side) base matches the branch-model convention of calcAdmittance (series/shunt admittance on the to side, complex ratio at the from side).

source
Sparlectra.calcVKDependenceMethod
calcVKDependence(xTaps::Vector{Int}, yVKs::Vector{Float64}, tapPos::Float64)::Float64

Calculates 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)

source
Sparlectra.cubicSplineCoefsMethod
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)

source
Sparlectra.HvdcLinkType
HvdcLink

Immutable record of one HVDC link between two converter prosumers. The record identifies the terminals and their provenance; live electrical values are always read from the prosumers or the attached controller, never stored here. controller_name is nothing for Stage-0 fixed injections and carries the HvdcPairControl name once a pair controller is attached (updates replace the vector element, the record itself stays immutable).

Fields: name, from_bus/to_bus (bus indices), from_prosumer/ to_prosumer (indices into net.prosumpsVec), status (1 = in service), source (:matpower, :cgmes, :api), kind (:b2b back-to-back or :p2p point-to-point, CGMES: a participating DCLineSegment makes it :p2p), controller_name.

source
Sparlectra._qv_effective_qgenMethod
_qv_effective_qgen(net, bus) -> Float64

The reactive generation at bus as the Q-V check must read it. Neither single source is right on its own:

  • node._qƩGen carries the value the solver clamped a PV bus to, including the active-set path, but stays 0 for a machine under Q(U) control;
  • _effective_bus_power_components evaluates the Q(U) characteristic (and the classic outer loop's clamp, which it writes to the prosumer), but falls back to _qƩGen only on Slack and PV buses, not on a bus that was switched to PQ.

So: a Q(U) machine is read from its characteristic, everything else from the bus aggregate where the solver left one.

source
Sparlectra._closed_branch_flow_puMethod
_closed_branch_flow_pu(V, from, to, br, tapSide) -> ComplexF64

Complex branch power S_ij in per unit from bus from to bus to of a fully CLOSED branch, evaluated on the complex voltage vector V. This is the flow formula calcNetLosses! uses (extracted so the contingency screening can estimate loadings from a trial voltage vector without writing the net); tapSide says which terminal carries the tap (1 = from, 2 = to).

source
Sparlectra._addbus_bus_type_warnedConstant

addBus!: Adds a bus to the network.

Parameters:

  • net::Net: Network object.
  • busName::String: Name of the bus.
  • vn_kV::Float64: Nominal voltage of the bus in kV.
  • busType::Union{Nothing,String} = nothing: Legacy static bus label (deprecated, ignored for PF typing).
  • vm_pu::Float64 = 1.0: Voltage magnitude of the bus in per unit (default is 1.0).
  • va_deg::Float64 = 0.0: Voltage angle of the bus in degrees (default is 0.0).
  • vmin_pu::Union{Nothing,Float64} = nothing: Minimum voltage limit in per unit (default is network's vmin_pu).
  • vmax_pu::Union{Nothing,Float64} = nothing: Maximum voltage limit in per unit (default is network's vmax_pu).
  • isAux::Bool = false: Boolean indicating if the bus is auxiliary (default is false).
  • oBusIdx::Union{Nothing,Int} = nothing: Original bus index (default is nothing).
  • zone::Union{Nothing,Int} = nothing: Zone index (default is nothing).
  • area::Union{Nothing,Int} = nothing: Area index (default is nothing).
  • ratedS::Union{Nothing,Float64} = nothing: Rated power of the bus in MVA (default is nothing).
source
Sparlectra._addPIModelACLine_by_idx!Method
addPIModelACLine!(; net::Net, fromBus::String, toBus::String, r_pu::Float64, x_pu::Float64, b_pu::Float64, g_pu::Union{Nothing,Float64}=nothing, status::Int, ratedS::Union{Nothing,Float64}=nothing)

Adds a PI model AC line to the network.

Arguments

  • net::Net: The network.
  • fromBus::String: The name of the bus where the line starts.
  • toBus::String: The name of the bus where the line ends.
  • r_pu::Float64: The per unit resistance of the line.
  • x_pu::Float64: The per unit reactance of the line.
  • b_pu::Float64: The per unit total line charging susceptance of the line.
  • g_pu::Union{Nothing,Float64}: The per unit total shunt conductance of the line (e.g. CGMES gch after conversion). Default is nothing (treated as 0.0).
  • status::Int: The status of the line. 1 = in service, 0 = out of service.
  • ratedS::Union{Nothing,Float64}: The rated power of the line.

Example

addPIModelACLine!(net = network, fromBus = "Bus1", toBus = "Bus2", r_pu = 0.01, x_pu = 0.1, b_pu = 0.02, status = 1, ratedS = 100.0)
source
Sparlectra._addPIModelTrafo_by_idx!Method

Add a transformer with PI model to the network.

Arguments

  • net::Net: The network to which the transformer will be added.
  • fromBus::String: The name of the bus where the transformer originates.
  • toBus::String: The name of the bus where the transformer terminates.
  • r_pu::Float64: The per-unit resistance of the transformer.
  • x_pu::Float64: The per-unit reactance of the transformer.
  • b_pu::Float64: The per-unit susceptance of the transformer.
  • status::Int: The status of the transformer.
  • ratedU::Union{Nothing, Float64}: Rated voltage of the transformer. Default is nothing.
  • ratedS::Union{Nothing, Float64}: Rated apparent power of the transformer. Default is nothing.
  • ratio::Union{Nothing, Float64}: Ratio of the transformer. Default is nothing.
  • shift_deg::Union{Nothing, Float64}: Phase shift angle of the transformer. Default is nothing.
  • isAux::Bool: Whether the transformer is an auxiliary transformer. Default is false.
source
Sparlectra._apply_external_grid_config!Method
_apply_external_grid_config!(net, pf::PowerFlowConfig; declared = nothing) -> Union{Nothing,String}

Apply power_flow.external_grid to a freshly imported net: when enabled, convert the marked slack bus into a non-ideal source via convertSlackToExternalGrid!. declared optionally carries (sk_MVA, rx) read from the case data (CGMES ExternalNetworkInjection); it wins over the config numbers when source = :auto. Idempotent: a net that already contains an external-grid internal bus is left untouched, so re-runs and rescue retries cannot stack sources. Returns the conversion note (or nothing when nothing was done).

source
Sparlectra.addBranch!Method

addBranch!: Adds a branch to the network.

Parameters:

  • net::Net: Network object.
  • from::Int: Index of the "from" bus.
  • to::Int: Index of the "to" bus.
  • branch::AbstractBranch: Branch object to add.
  • status::Int = 1: Status of the branch (default is 1).
  • ratio::Union{Nothing,Float64} = nothing: Ratio of the branch (default is nothing).
  • side::Union{Nothing,Int} = nothing: Side of the branch (default is nothing).
  • vn_kV::Union{Nothing,Float64} = nothing: Nominal voltage of the branch in kV (default is nothing).
  • values_are_pu = false: Boolean indicating if the values are in per unit (default is false).
source
Sparlectra.setBusType!Method

Sets the type of a bus in the network.

Parameters:

  • net::Net: Network object.
  • bus::Int: Index of the bus.
  • busType::String: Type of the bus (e.g., "Slack", "PQ", "PV")
source
Sparlectra._build_transformer_control_rowsMethod
_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).
source
Sparlectra._distributed_slack_bus_sharesMethod
_distributed_slack_bus_shares(net) -> (active::Bool, shares::Dict{Int,NTuple{2,Float64}})

Per-bus distributed-slack participation for the bus table of the classical result print: bus index to (alpha, dp_mw), aggregated over the generators of a bus (the persisted participation table is per generator). active is false when the last solve ran without the distributed slack or no solver status exists; the table then omits the participation columns.

source
Sparlectra._fitColumnMethod
_fitColumn(text, width) -> String

Trim text to width characters, marking the cut with . Fixed-width @sprintf fields pad but never truncate, so long names — CGMES bus and branch identifiers routinely exceed 25 characters — would otherwise push every following column out of alignment.

source
Sparlectra._hvdc_link_flow_rowsMethod
_hvdc_link_flow_rows(net) -> Vector{NamedTuple}

One row per HvdcLink for the HVDC Link Flows table, ACPFlowReport, and the CSV export. Sign convention: p_from_MW is the power leaving the from bus into the link (positive for export), p_to_MW the power delivered into the to bus. With an attached controller the values come from its setpoints and live terminal state (mode is the controller mode); without one they come from the terminal prosumers (mode = :fixed, loss = -(P_from_injection + P_to_injection) in the MATPOWER convention where the from injection is negative).

source
Sparlectra._print_distributed_slack_summary_lineMethod
_print_distributed_slack_summary_line(io, net)

One line inside the classical result header when the last solve ran with the distributed slack active: mode, the solved lambda_P, and the participant count. The per-bus participation itself lives in the bus table (columns dSl alpha and Pg eff MW, see _distributed_slack_bus_shares). Prints nothing when the feature was off or the net has no rectangular solver status.

source
Sparlectra._print_wrong_branch_summary_lineMethod
_print_wrong_branch_summary_line(io, net)

Prints a single console/log line summarizing the wrong-branch detection outcome when it is suspect or invalid (status is neither :ok nor :not_checked). Clean runs and disabled detection print nothing, keeping logs stable for the common case.

source
Sparlectra._perf_profile_childMethod
_perf_profile_child(profile) -> Dict{Symbol,Any} | nothing

Create a fresh per-worker profile for a parallel work item (thread-safety Phase 1). Returns nothing when profile is not an enabled profile Dict; otherwise a new Dict carrying only the read-only seed keys (_PERF_PROFILE_CHILD_KEYS). Workers write timings, iteration rows, and scalar diagnostics into their child only; the orchestrator folds children back with _perf_profile_merge! after fetch, so the parent Dict is never touched concurrently.

source
Sparlectra._perf_profile_merge!Method
_perf_profile_merge!(parent, child, prefix::AbstractString)

Fold a worker's child profile into the parent (serial, orchestrator-only). :timings rows are SUMMED into the parent's :timings under their original phase names, so the phase-name set of a parallel run stays identical to the serial run (calls/elapsed/bytes accumulate exactly like the serial loop did). :iterations rows are appended in call order. Every other child key is copied under Symbol(prefix, key) so per-worker scalars (backend names, matrix stats, start-projection summaries) stop overwriting each other. The wall-clock of the orchestrating fan-out is accounted separately by the caller via _perf_profile_add!(parent, :parallel_wall_time, elapsed, 0), which keeps serial-sum versus wall-clock visible in performance.log.

source