Core Model Reference
Public API
Sparlectra.Sparlectra — Module
Sparlectra 0.11.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.Wurzel3 — Constant
The square root of three, the line-to-line factor of three-phase power.
Sparlectra.AbstractBranch — Type
Supertype of every branch-like element (lines, transformers).
Sparlectra.version — Method
version() -> VersionNumberThe version of the loaded Sparlectra package.
Sparlectra.Branch — Type
BranchA 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 newBranchinstance.
Methods
Base.show(io::IO, b::Branch): Prints theBranchinstance.
Sparlectra.BranchFlow — Type
BranchFlowA 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 newBranchFlowinstance.
Methods
Base.show(io::IO, b::BranchFlow): Prints theBranchFlowinstance.
Example
BranchFlow(vm_pu = 1.0, va_deg = 0.0, pFlow = 100.0, qFlow = 50.0)Sparlectra.BranchModel — Type
BranchModelA 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 newBranchModelinstance.
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)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); atap_stepof 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 amplituder2 = n * phase_du_stepalong the nameplate directionpsi_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.
Sparlectra.calcAdmittance — Method
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.
Sparlectra.calcBranchRatio — Method
calcBranchRatio(branch) -> ComplexF64The complex winding ratio of the branch (magnitude and phase shift).
Sparlectra.calcBranchYser — Method
calcBranchYser(branch) -> ComplexF64The series admittance of the branch in per unit.
Sparlectra.calcBranchYserBase — Method
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).
Sparlectra.calcBranchYshunt — Method
calcBranchYshunt(branch) -> ComplexF64The total shunt admittance of the branch in per unit.
Sparlectra.getBranchFlow — Method
getBranchFlow(branch, from, to) -> BranchFlowThe stored flow record for the given orientation of the branch.
Sparlectra.getBranchIdx — Method
getBranchIdx(branch) -> IntThe position of the branch in the network's branch vector.
Sparlectra.getBranchLosses — Method
getBranchLosses(branch) -> (p, q)The stored losses of the branch in MW/MVar.
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.
Sparlectra.setBranchFlow! — Method
setBranchFlow!(branch, tfBranchFlow, fBranchFlow)Store the solved flows of both branch ends.
Sparlectra.setBranchLosses! — Method
setBranchLosses!(branch, pLosses, qLosses)Store the solved losses of the branch in MW/MVar.
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).
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.
Sparlectra.BusData — Type
Per-bus working record of the solvers: type, voltage state and the aggregated injections in per unit.
Sparlectra.buildVoltageVector_from_busVec — Method
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.
Sparlectra.countNodes — Method
countNodes(busTypeVec, pos, value) -> IntCount buses of the given type up to position pos.
Sparlectra.getBusData — Method
getBusData(nodes, Sbase_MVA, flatStart; net = nothing) -> Vector{BusData}Build the per-bus solver records from the node vector.
Sparlectra.getBusTypeVec — Method
getBusTypeVec(busVec) -> Vector{NodeType}The bus types of the solver records, in order.
Sparlectra.map_NR_voltage_to_net! — Method
map_NR_voltage_to_net!(V_nr, busVec, net) -> V_netMaps 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.
Sparlectra.AbstractComponent — Type
Supertype of every identifiable network component (name, id, type).
Sparlectra.Component — Type
ComponentA 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 newComponentinstance with a specified nominal voltage.Component(id::String, name::String, typ::ComponentTyp): Creates a newComponentinstance with a nominal voltage of 1 kV.Component(id, name, cmp::String, Unenn::Float64): Creates a newComponentinstance with a specified nominal voltage and component type as a string.
Methods
Base.show(io::IO, x::Component): Prints theComponentinstance.
Example
Component("1", "Generator", "GENERATOR", 110.0)Sparlectra.ComponentTyp — Type
The component vocabulary of the model (buses, lines, transformers, machine and load kinds), shared by every importer.
Sparlectra.ImpPGMComp — Type
Component identity in the power-grid-model style: generated name, external id, component type, and the bus indices the element connects.
Sparlectra.ImpPGMComp3WT — Type
Component identity of a three-winding transformer, carrying all three bus indices next to the common identity fields.
Sparlectra.TrafoTyp — Type
Transformer kinds: ratio transformer, phase shifter, phase tap changer, or a plain PI-model branch.
Sparlectra.getCompID — Method
getCompID(c) -> StringThe external (source-system) id of the component.
Sparlectra.getCompName — Method
getCompName(c) -> StringThe reference name of the component.
Sparlectra.toComponentTyp — Method
toComponentTyp(s) -> ComponentTypMap a component-type name (case insensitive) onto the enum.
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.calcComplexRatio — Method
calcComplexRatio(; tapRatio, angleInDegrees) -> ComplexF64The complex winding ratio from a magnitude ratio and a phase-shift angle.
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.calcPhaseTapAngleRatio — Method
calcPhaseTapAngleRatio(m::PhaseTapChangerModel; step::Int = m.step) -> NamedTupleEffective 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 always1.0(effective_ratio == 1.0regardless ofconvention). With the default:reciprocal_from_sideconvention the returnedeffective_shift_degis-α(mirroringcalcSkewAngleTap's sign convention);:direct_regulating_vectorreturns+α.kind == :asymmetrical(ch. 6.2, quadrature booster =ψ = 90°): delegates tocalcSkewAngleTap(tap_fraction = f, skew_angle_deg = winding_connection_angle_deg, convention = m.convention)unchanged.kind == :tabular: table OVERRIDES the formula path — delegates tocalcPhaseTapTablefor(effective_ratio, effective_shift_deg)and reconstructsregulating_vectoras the exact inverse ofcalcSkewAngleTap's regulating-vector-to-(ratio,shift) mapping form.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).
Sparlectra.calcPhaseTapFraction — Method
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).
Sparlectra.calcPhaseTapReactance — Method
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 thex_puof them.tablerow atm.step(may benothing);alpha_degis 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, ornothingifm.x_min/m.x_max(formula kinds) or the table row'sx_pu(:tabular) isnothing.
Sparlectra.calcPhaseTapTable — Method
calcPhaseTapTable(m::PhaseTapChangerModel; step::Int = m.step) -> NamedTupleExact 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 matchingTapTablePoint(ratio,angle_deg,x_pu).
Failure behavior
Throws ArgumentError if m.table === nothing or if no row matches step.
Sparlectra.calcRatioTapCorrection — Method
calcRatioTapCorrection(taps::PowerTransformerTaps; step::Int = taps.step) -> Float64Multiplicative 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 totaps.step.
Returns
Float64: the correction factor (1.0at the neutral step).
Sparlectra.calcRatioTapRange — Method
calcRatioTapRange(taps::PowerTransformerTaps) -> NamedTupleRatio-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).
Sparlectra.calcSkewAngleTap — Method
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).
Sparlectra.calcTapCorrectedRX — Method
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.
Sparlectra.calcTapImpedanceCorrectionFactor — Method
calcTapImpedanceCorrectionFactor(; tap_changer_model::Symbol, tap_fraction::Union{Nothing,Real} = nothing, skew_angle_deg::Real = 0.0, ratio::Union{Nothing,Real} = nothing)::Float64Return 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 (factor1.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$, wherefis 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::idealor:impedance_correction.tap_fraction::Union{Nothing,Real}: longitudinal regulating-voltage fractionf.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.
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.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.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.has_q_limits — Method
has_q_limits(qmin_pu, qmax_pu, i) -> BoolWhether bus i carries a finite reactive band.
Sparlectra.lastQLimitIter — Method
Returns the last iteration number where bus hit a Q-limit, or nothing.
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.
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.printQVCharacteristicCheck — Method
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.
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.qvCharacteristicViolations — Method
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 = QmaxwithVm > Vset, orQ = QminwithVm < 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).
Sparlectra.resetQLimitLog! — Method
resetQLimitLog!(net)Clear the Q-limit event log of the network.
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.ACLineSegment — Type
An AC line with its physical parameters (ohm, siemens per length or absolute) and the PI-model form the solver consumes.
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.getLineRXBG_pu — Method
getLineRXBG_pu(o, vn_kV, baseMVA) -> (r, x, b, g)The line parameters converted to per unit on the given base.
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.isLinePIModel — Method
isLinePIModel(line) -> BoolWhether the line was built directly from per-unit PI-model parameters.
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.setLinkCurrent! — Method
setLinkCurrent!(link, iFrom_kA, iTo_kA)Store the solved end currents of a busbar link.
Sparlectra.setLinkFlow! — Method
setLinkFlow!(link, pFlow_MW, qFlow_MVar)Store the solved flow of a busbar link.
Sparlectra.setLinkStatus! — Method
setLinkStatus!(link, status)Set the in-service status of a busbar link.
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.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.
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.Net — Type
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.
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 isnothing.ratedS::Union{Nothing, Float64}: Rated apparent power of the transformer. Default isnothing.ratio::Union{Nothing, Float64}: Ratio of the transformer. Default isnothing.shift_deg::Union{Nothing, Float64}: Phase shift angle of the transformer. Default isnothing.isAux::Bool: Whether the transformer is an auxiliary transformer. Default isfalse.
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.
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:
ratiois set to Uaux / Uside (HV/MV/LV) for MV and LV, and 1.0 for HB.ratedUpassed to add2WTPIModelTrafo! is the AUX-side rated voltage (HV), because the branch is defined from AUX (HV base) to the respective side.
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).
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.
Sparlectra.addBusGenPower! — Method
Add active/reactive power to the NODE-level generation sum of a bus (node._pƩGen/node._qƩGen).
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. Defaultnothing.q::Union{Nothing, Float64}: reactive power to add in MVAr. Defaultnothing.
Sparlectra.addBusLoadPower! — Method
Add active/reactive power to the NODE-level load sum of a bus (node._pƩLoad/node._qƩLoad).
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. Defaultnothing.q::Union{Nothing, Float64}: reactive power to add in MVAr. Defaultnothing.
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:mincase 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 torx_maxwhensk_min_MVAis given, so a deliberately declared minimum feeder does not carry a spurious defaulted-data flag.name::Union{Nothing,String} = nothing: feeder name (defaultbusName).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.
Sparlectra.addLink! — Method
addLink!(; net, fromBus, toBus, status = 1) -> IntAdd 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!.
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.
Sparlectra.addPIModelTrafo! — Method
addPIModelTrafo!(; net, fromBus, toBus, r_pu, x_pu, ...)Add a two-winding transformer branch from PI-model per-unit parameters.
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 isnothing.q::Union{Nothing, Float64}: Reactive power produced or consumed. Default isnothing.pMin::Union{Nothing, Float64}: Minimum active power. Default isnothing.pMax::Union{Nothing, Float64}: Maximum active power. Default isnothing.qMin::Union{Nothing, Float64}: Minimum reactive power. Default isnothing.qMax::Union{Nothing, Float64}: Maximum reactive power. Default isnothing.referencePri::Union{Nothing, String}: Reference bus for the prosumer. Default isnothing.vm_pu::Union{Nothing, Float64}: Voltage magnitude setpoint. Default isnothing.va_deg::Union{Nothing, Float64}: Voltage angle setpoint. Default isnothing.isRegulated::Bool: Marks a prosumer as voltage-regulating for PV bus resolution. Default isfalse.
Sparlectra.addShunt! — Method
addShunt!(; net, busName, pShunt, qShunt, in_service=1)Adds a Y-model shunt to the network.
Semantics:
pShunt,qShuntare 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.
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.
Sparlectra.buildComplexSVec — Method
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).
Sparlectra.buildControlledSVec — Method
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.).
Sparlectra.buildQLimits! — Method
buildQLimits!(net; reset=true)Public wrapper to (re)build aggregated per-bus Q limits in p.u.
Sparlectra.buildVoltageVector — Method
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.
Sparlectra.bus_shunt_totals_pu — Method
bus_shunt_totals_pu(net) -> NamedTupleReturn 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.
Sparlectra.convertSlackToExternalGrid! — Method
convertSlackToExternalGrid!(; net, sk_max_MVA, kwargs...) -> StringReplace 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 toaddExternalGrid!.
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.
Sparlectra.distributeBusResults! — Method
distributeBusResults!(net)Write the solved bus results back onto the attached prosumers and shunts (per-machine P/Q, shunt injections).
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!.
Sparlectra.geNetBusIdx — Method
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.
Sparlectra.getBusProsumers — Method
getBusProsumers(net, busIdx) -> Vector{ProSumer}Every prosumer attached to the bus.
Sparlectra.getBusType — Method
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.
Sparlectra.getEffectiveBusType — Method
getEffectiveBusType(net, busIdx) -> NodeTypeThe bus type as the solver sees it, derived from the attached prosumers (slack wins over PV, PV over PQ).
Sparlectra.getNetBranch — Method
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, ornothingif no such branch exists.
Example
```julia getNetBranch(net = network, fromBus = "Bus1", toBus = "Bus2")
Sparlectra.getNetBranchNumberVec — 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
brVec = getNetBranchNumberVec(net = net, fromBus = "B1", toBus = "B2")
setNetBranchStatus!(net = net, branchNr = brVec[1], status = 0)Sparlectra.getNetLinks — Method
getNetLinks(; net::Net, fromBus::String, toBus::String)::Vector{BusLink}Returns all links between two buses (both directions).
Sparlectra.getNetOrigBusIdx — Method
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.
Sparlectra.getShunt! — Method
getShunt!(; net::Net, busName::String)::ShuntRetrieves 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")
Sparlectra.getTotalBusPower — Method
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)Sparlectra.getTotalLosses — Method
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.
Sparlectra.get_bus_vn_kV — Method
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.
Sparlectra.get_vn_kV — Method
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.
Sparlectra.hasBusInNet — Method
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.
Sparlectra.hasShunt! — Method
hasShunt!(; net::Net, busName::String)::BoolChecks 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")
Sparlectra.has_voltage_dependent_control — Method
has_voltage_dependent_control(net) -> BoolWhether any prosumer carries a Q(U) or P(U) controller.
Sparlectra.initialVrect — Method
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
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.
Sparlectra.log_bus_shunt_model — Method
log_bus_shunt_model(net) -> NothingEmit a compact log message with the selected bus-shunt modeling mode, in-service bus-shunt count, and aggregate per-unit conductance/susceptance.
Sparlectra.markIsolatedBuses! — Method
markIsolatedBuses!(;net::Net)Finds and marks isolated buses in the network.
Arguments
net::Net: The network.
Sparlectra.normalize_bus_shunt_model — Method
normalize_bus_shunt_model(value) -> SymbolValidate and normalize the bus-shunt modeling option. Supported values are "admittance" and "voltage_dependent_injection".
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.
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)Sparlectra.setNetLinkStatus! — Method
setNetLinkStatus!(; net::Net, linkNr::Int, status::Int)Sets an existing link status (0/1).
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)Sparlectra.setNodeVoltage! — Method
setNodeVoltage!(; net, busName, vm_pu, va_deg)Set the voltage state of one bus by name.
Sparlectra.setPVBusVset! — Method
setPVBusVset!(; net, busName, vm_pu)Set the voltage setpoint of the regulating machine at the bus.
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.
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.
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)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.
Sparlectra.showNet — Method
showNet(io, net; verbose = false)Print a component summary of the network; verbose lists the elements.
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)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)
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.
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.addGenPower! — Method
addGenPower!(; node, p, q)Add generation P/Q (MW/MVar) to the bus aggregate; nothing adds nothing.
Sparlectra.addLoadPower! — Method
addLoadPower!(; node, p, q)Add load P/Q (MW/MVar) to the bus aggregate; nothing adds nothing.
Sparlectra.addShuntPower! — Method
addShuntPower!(; node, p, q)Add a shunt draw (MW/MVar at 1 pu) to the bus aggregate.
Sparlectra.busComparison — Method
busComparison(node1, node2) -> BoolOrder two buses by their index; the sort predicate of the node vector.
Sparlectra.getNodeType — Method
getNodeType(o) -> NodeTypeThe bus type (Slack, PV, PQ, Isolated) of the node.
Sparlectra.getNodeVm — Method
getNodeVm(o) -> Float64The voltage magnitude of the node in per unit (1.0 when unset).
Sparlectra.getNodeVn — Method
getNodeVn(o) -> Float64The rated voltage of the node in kV.
Sparlectra.isIsolated — Method
isIsolated(o) -> BoolWhether the node is marked isolated (out of every island).
Sparlectra.isPQNode — Method
isPQNode(o) -> BoolWhether the node is a PQ bus.
Sparlectra.isPVNode — Method
isPVNode(o) -> BoolWhether the node is a PV bus.
Sparlectra.setNodeType! — Method
setNodeType!(o, typ)Set the bus type from its string name ("Slack", "PV", "PQ", "Isolated").
Sparlectra.setVmVa! — Method
setVmVa!(; node, vm_pu, va_deg = nothing)Set the voltage state of the node; a missing angle keeps the stored one.
Sparlectra.toNodeType — Method
toNodeType(x) -> NodeTypeMap a MATPOWER bus-type number (or a string name) onto the NodeType enum.
Sparlectra.AbstractVoltageDependentController — Type
Supertype of the voltage-dependent prosumer controllers (Q(U), P(U)).
Sparlectra.PUController — Method
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.
Sparlectra.PiecewiseLinearCharacteristic — Type
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.
Sparlectra.ProSumer — Type
ProSumerA 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 newProSumerinstance.
Methods
Base.show(io::IO, prosumer::ProSumer): Prints theProSumerinstance.
Example
prosumer = ProSumer(comp, 1, 100.0, 50.0, 80.0, 40.0, 1)Sparlectra.QUController — Method
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.
Sparlectra.VoltageAdjustConfig — Type
Step-voltage regulation data of a prosumer: step size in per unit and the number of steps below and above the neutral position.
Sparlectra.evaluate_characteristic — Method
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.
Sparlectra.evaluate_controller — Method
evaluate_controller(ctrl, u_pu) -> Float64Evaluate a voltage-dependent controller characteristic at the voltage u_pu and return the controlled quantity (Q or P) it demands there.
Sparlectra.getPosumerBusIndex — Method
getPosumerBusIndex(ps) -> IntThe bus index a prosumer is attached to.
Sparlectra.getQGenReplacement — Method
getQGenReplacement(o) -> Union{Nothing,Float64}The reactive output a Q-limit switch fixed for this machine, nothing while it regulates freely.
Sparlectra.has_pu_controller — Method
has_pu_controller(ps) -> BoolWhether the prosumer carries a P(U) controller.
Sparlectra.has_qu_controller — Method
has_qu_controller(ps) -> BoolWhether the prosumer carries a Q(U) controller.
Sparlectra.isAPUNode — Method
isAPUNode(o) -> BoolWhether the prosumer marks its bus as an active-power/voltage (APU) node.
Sparlectra.isGenerator — Method
isGenerator(x) -> BoolWhether a prosumer (or prosumption type) injects power, as opposed to consuming it.
Sparlectra.isRegulating — Method
isRegulating(o) -> BoolWhether the machine takes part in voltage regulation: it is marked regulated or carries a step/tap voltage controller.
Sparlectra.isSlack — Method
isSlack(o) -> BoolWhether this prosumer carries the reference (slack) role.
Sparlectra.make_characteristic — Method
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 = :puexpects voltage in per-unit.voltage_unit = :kVexpects voltage in kV and requiresvn_kV.value_unit = :puexpects power output in per-unit.value_unit = :MWor:MVArexpects physical power values and requiressbase_MVA.interpolation = :linearuses piecewise linear interpolation.interpolation = :splineuses natural cubic spline interpolation through all points. If only two points are provided, linear interpolation is used automatically.interpolation = :polynomialuses one global polynomial through all points. If only two points are provided, linear interpolation is used automatically.
Sparlectra.setPQResult! — Method
setPQResult!(ps, p, q)Store the solved injection of the machine (MW/MVar) as its result fields.
Sparlectra.setQGenReplacement! — Method
setQGenReplacement!(o, q)Fix the machine's reactive output at q after a Q-limit switch.
Sparlectra.toProSumptionType — Method
toProSumptionType(t) -> ProSumptionTypeMap a component type (Generator, EnergyConsumer, ...) onto the coarse Injection/Consumption class.
Sparlectra.updatePQ! — Method
updatePQ!(o, p, q)Update the specified P/Q of the prosumer; nothing leaves a value as is.
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.removeProsumer! — Method
removeProsumer!(; net, busName, type = "") -> BoolRemove a prosumer from the bus (optionally by type) and refresh the bus types; returns whether one was removed.
Sparlectra.removeShunt! — Method
removeShunt!(; net, busName) -> BoolRemove the shunt at the bus; returns whether one was removed.
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.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.hvdc_links: One row per HVDC link (net.hvdcLinks): terminal flows, loss, mode, rating, controller status (see_hvdc_link_flow_rows).
Sparlectra.buildACPFlowReport — Method
buildACPFlowReport(net::Net; ...)Builds a structured report object from solved network data. This provides a machine-readable alternative to printACPFlowResults.
Sparlectra.printACPFlowResults — Function
printACPFlowResults(net, ...; kwargs...)Print the solved power-flow result tables (buses, branches, summary) to the console or a file.
Sparlectra.printProsumerResults — Method
printProsumerResults(net)Print the per-machine result table of the solved network.
Sparlectra.Shunt — Type
A bus shunt: its admittance in per unit, the nominal draw it was built from, its model (admittance or voltage-dependent injection) and status.
Sparlectra.getGBShunt — Method
getGBShunt(o) -> (g, b)The shunt admittance in per unit.
Sparlectra.getPQShunt — Method
getPQShunt(o) -> (p, q)The nominal shunt draw in MW/MVar at 1 pu voltage.
Sparlectra.updatePQShunt! — Method
updatePQShunt!(o, p, q)Update the shunt draw and recompute its per-unit admittance.
Sparlectra.AbstractTapChangerModel — Type
AbstractTapChangerModelSupertype 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.
Sparlectra.PhaseTapChangerModel — Type
PhaseTapChangerModelA 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 fromtablefor:tabularif omitted).highStep::Int: The highest step/position (auto-derived fromtablefor:tabularif omitted).neutralStep::Int: The neutral step/position; for:tabularit must be a step present intable.voltage_step_increment::Union{Nothing,Float64}:u, per step, in per unit of rated voltage (cim:PhaseTapChangerNonLinear.voltageStepIncrement); must benothingfor: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:asymmetricalwithψ = 90°. Must benothingfor:tabular.x_min::Union{Nothing,Float64}:X(0)in per unit; must benothingfor:tabular.x_max::Union{Nothing,Float64}:X(αmax)in per unit; must benothingfor:tabular.convention::Symbol: sign/reciprocal convention forwarded tocalcSkewAngleTapfor:asymmetricalmodels, and used to reconstruct the regulating vector for:tabularmodels; default:reciprocal_from_side.table::Union{Nothing,Vector{TapTablePoint}}: required, non-empty, strictly ascending/unique-by-stepfor:tabular; must benothingotherwise. 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 newPhaseTapChangerModelinstance.lowStep/highStepare required for:symmetrical/:asymmetrical; for:tabularthey are derived fromtablewhen omitted, and validated against it otherwise.
Methods
Base.show(io::IO, x::PhaseTapChangerModel): Prints thePhaseTapChangerModelinstance.
Sparlectra.PowerTransformer — Type
A power transformer with up to three windings, its tap changers and the nameplate data the importers deliver.
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.convention::Symbol: The ratio-tap correction convention. Only:neutral_relativeis currently supported: thecalcRatioTapCorrectionfactor is applied as a divisor on the winding ratio (ratio / corr), matchingcalcTransformerRatio.
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 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.phase_taps::Union{Nothing,PhaseTapChangerModel}: The phase-tap-changer (PST) model of the winding, parallel totaps;nothingif 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 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, controls::Union{Nothing,Vector{PowerTransformerControl}} = nothing, phase_taps::Union{Nothing,PhaseTapChangerModel} = nothing): Creates a newPowerTransformerWindinginstance.
Methods
Base.show(io::IO, x::PowerTransformerWinding): Prints thePowerTransformerWindinginstance.
Sparlectra.TapTablePoint — Type
TapTablePointAn 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;nothingif not provided.
Constructors
TapTablePoint(; step::Int, ratio::Float64, angle_deg::Float64, x_pu::Union{Nothing,Float64} = nothing): Creates a newTapTablePointinstance.
Sparlectra.TransformerModelParameters — Type
Nameplate model parameters of a transformer (short-circuit voltage, copper and iron losses, no-load current) used to derive the PI-model impedances.
Sparlectra.calcTransformerRatio — Method
calcTransformerRatio(x) -> Float64The effective winding ratio of the transformer at its current tap.
Sparlectra.create2WTRatioTransformerNoTaps — Method
create2WTRatioTransformerNoTaps(; from, to, vn_hv_kV, vn_lv_kV, sn_mva, vk_percent, vkr_percent, pfe_kw, i0_percent) -> PowerTransformerBuild a two-winding ratio transformer from nameplate data, without a tap changer.
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 aPhaseTapChangerModel(Schrägregler);0means none. Uses the same 1-based winding-index convention astap_side. May equaltap_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 atphase_tap_side. Must benothingiffphase_tap_side == 0; aPhaseTapChangerModelis required wheneverphase_tap_side != 0.
Returns
Returns a tuple of PowerTransformerWinding instances for the three windings of the transformer.
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)Sparlectra.getSideNumber2WT — Method
getSideNumber2WT(x) -> IntWhich side (1 or 2) of a two-winding transformer carries the tapped winding.
Sparlectra.getTrafoImpPGMComp — Function
getTrafoImpPGMComp(aux, Vn, from, to, to3 = nothing) -> ImpPGMCompBuild the component identity of a transformer branch (name embeds voltage and bus numbers; aux marks a three-winding star leg).
Sparlectra.getTrafoRXBG — Method
getTrafoRXBG(o) -> (r, x, b, g)The winding impedance and magnetising admittance as stored on the winding.
Sparlectra.getTrafoRXBG_pu — Method
getTrafoRXBG_pu(o, vn_kV, baseMVA) -> (r, x, b, g)The winding impedance and magnetising admittance converted to per unit on the given base.
Sparlectra.getWT3AuxBusID — Method
getWT3AuxBusID(Vn, from, to, to3) -> StringThe generated identity of the auxiliary star bus of a three-winding transformer.
Sparlectra.getWinding2WT — Method
getWinding2WT(x) -> PowerTransformerWindingThe winding that models a two-winding transformer (the one carrying the impedance).
Sparlectra.getWindingRatedS — Method
getWindingRatedS(o) -> Union{Nothing,Float64}The rated apparent power of the winding in MVA.
Sparlectra.isPerUnit_RXGB — Method
isPerUnit_RXGB(o) -> Union{Nothing,Bool}Whether the winding stores its R/X/G/B already in per unit.
Sparlectra.toString — Method
toString(x) -> StringHuman-readable name of an enum value (transformer type, prosumption type).
Internals
Sparlectra._branch_terminal_state — Method
_branch_terminal_state(br::Branch) -> SymbolSingle 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.
Sparlectra._open_end_voltage — Method
_open_end_voltage(branch, u_closed::ComplexF64) -> ComplexF64Voltage 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.
Sparlectra._open_terminal_yin — Method
_open_terminal_yin(branch) -> ComplexF64Exact 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).
Sparlectra.assertPhysicalBranchImpedances — Method
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").
Sparlectra.calc2WTEndsReferredRXGB — Method
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).
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.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.HvdcLink — Type
HvdcLinkImmutable 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.
Sparlectra._qv_effective_qgen — Method
_qv_effective_qgen(net, bus) -> Float64The reactive generation at bus as the Q-V check must read it. Neither single source is right on its own:
node._qƩGencarries 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_componentsevaluates the Q(U) characteristic (and the classic outer loop's clamp, which it writes to the prosumer), but falls back to_qƩGenonly 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.
Sparlectra._closed_branch_flow_pu — Method
_closed_branch_flow_pu(V, from, to, br, tapSide) -> ComplexF64Complex 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).
Sparlectra._addbus_bus_type_warned — Constant
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).
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. CGMESgchafter conversion). Default isnothing(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)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 isnothing.ratedS::Union{Nothing, Float64}: Rated apparent power of the transformer. Default isnothing.ratio::Union{Nothing, Float64}: Ratio of the transformer. Default isnothing.shift_deg::Union{Nothing, Float64}: Phase shift angle of the transformer. Default isnothing.isAux::Bool: Whether the transformer is an auxiliary transformer. Default isfalse.
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).
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).
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")
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._distributed_slack_bus_shares — Method
_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.
Sparlectra._fitColumn — Method
_fitColumn(text, width) -> StringTrim 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.
Sparlectra._hvdc_link_flow_rows — Method
_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).
Sparlectra._print_distributed_slack_summary_line — Method
_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.
Sparlectra._print_wrong_branch_summary_line — Method
_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.
Sparlectra._perf_profile_child — Method
_perf_profile_child(profile) -> Dict{Symbol,Any} | nothingCreate 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.
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.