Core Model Reference
Public API
Sparlectra.Sparlectra — Module
Sparlectra 1.3.0Sparlectra 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 (sum of the two terminal values).g_pu::Float64: The per unit total line charging conductance of the branch (sum of the two terminal values).g_from_pu,b_from_pu,g_to_pu,b_to_pu::Float64: the charging admittance per terminal; the from arm sits behind the ideal transformer. Change them throughset_branch_shunt!, never one total alone.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.tap_step_impedance::Union{Nothing,TapStepImpedance}: impedance per tap step of a tap changer table, applied when a tap controller moves the branch.se_tap_changers::Union{Nothing,SETapChangerSet}: the tap changers of a transformer as an import stored them for the tap estimation (state estimation only);nothingmeans the set is derived from the typed models or the branch fields.phase_tap_declared::Bool: a nameplate row declared the phase tap changer of the branch fields (applyTapNameplate!); the constructor default phase grid is not declared.ratio_tap_declared::Bool: a nameplate row declared the ratio tap changer of the branch fields (applyTapNameplate!withtap_step > 0); the constructor default ratio grid is not declared.ratio_step_assumed::Bool,phase_step_assumed::Bool: the import carried no current step for the ratio changer (phase changer) of the branch fields or the typed models, so it sits at its middle position (the neutral step, the band middle without one); the tap estimation names it in its report row.
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.g_from_pu,b_from_pu,g_to_pu,b_to_pu::Float64: the charging admittance per terminal; the totals are always their sums, the symmetric half split is the default.
Constructors
BranchModel(; r_pu, x_pu, b_pu, g_pu, ratio, angle, sn_MVA = nothing, g_from_pu = nothing, b_from_pu = nothing, g_to_pu = nothing, b_to_pu = nothing): the four terminal values are given together or not at all; without them the totals are split in halves.
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 mechanical grids the tap estimation reads as its changers.
- Ratio changer:
tap = neutral / (1 + n * tap_step)(fraction grid,tap_ratio_grid = :fraction); withtap_ratio_grid = :linearthe steps lie on the grid of a CGMES changer,tap = neutral + n * tap_step(_ratio_grid_shift), andratiois the position the steps count from. 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 it and is NOT the grid. The factor divides the LIVE ratio of the ratio changer (the neutral ratio without one):t = tap_ratio * cis(angle) / (1 + r2 * cis(psi)). With both changerspsi_degmust not be 180 degrees (0 reads as 90 here), else the two positions cannot be told apart fromt(ArgumentError). The SCF import builds a statedalpha_deg0 as 0 (a missing key reads as 90) and refuses such a pair at 0 as well, unless the Delta-u position is 0. - Phase changer, degree form (
phase_step_deg > 0): additive degrees on the neutral shift; the band is stored relative to neutral.
phase_step_deg and phase_du_step are exclusive (a changer has one mechanical grid). A NaN current step means the file carried no step: the changer starts at its middle position, the neutral position 0 the steps count from, and ratio_step_assumed (phase_step_assumed) is set. A phase changer applied here is declared nameplate data (phase_tap_declared), which releases it for the tap estimation whatever its psi; a ratio changer applied here (tap_step > 0) is declared in the same way (ratio_tap_declared). The tap estimation releases declared changers only, never the constructor's default 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. With flatStart every angle but the slack's is 0 and a PQ bus starts at the mean voltage setpoint of the slack and PV buses of its AC island (the flat start of initialVrect), 1.0 pu in an island without such a bus or without net.
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.DynamicData — Type
DynamicData(; inertia_s = nothing, damping_pu = 0.0, rating_mva = nothing,
droop_pu = nothing, deadband_hz = 0.0, primary_reserve_mw = 0.0,
governor_time_s = nothing, agc_participation = 0.0,
secondary_reserve_mw = 0.0, unit_type = nothing,
virtual_inertia_s = nothing, black_start = false,
min_stable_mw = nothing)Dynamic parameters of one generating unit, referenced from ProSumer.dynamics (nothing when the unit has none). No power flow, state estimation, short circuit or contingency calculation reads them. The only reader is the island slack choice of the CGMES import, which takes unit_type into account.
Fields
inertia_s::Union{Nothing,Float64}: inertia constant H in s, on the rating below.nothing: the unit has no inertia.damping_pu::Float64: damping coefficient D in pu/pu. Default 0.0.rating_mva::Union{Nothing,Float64}: rating in MVA that H and D refer to, when it differs from the unit'sratedS.nothing:ratedSapplies.droop_pu::Union{Nothing,Float64}: primary control droop (statics) in pu, for example 0.05.nothing: no primary control.deadband_hz::Float64: primary control deadband in Hz. Default 0.0.primary_reserve_mw::Float64: primary reserve limit in MW, symmetric. Default 0.0.governor_time_s::Union{Nothing,Float64}: governor/turbine time constant in s of a first-order lag.nothing: not given.agc_participation::Float64: share of the secondary control signal, 0 to- Default 0.0.
secondary_reserve_mw::Float64: secondary reserve limit in MW, symmetric. Default 0.0.unit_type::DynamicUnitType:DynamicUnitType. DefaultSynchronousUnitwheninertia_sis set, elseGridFollowingUnit.virtual_inertia_s::Union{Nothing,Float64}: synthetic inertia in s of a grid-forming unit.nothing: none.black_start::Bool: the unit can energise a dead network. Default false.min_stable_mw::Union{Nothing,Float64}: minimum stable generation in MW.nothing: not given.
Validation
Every number must be finite; inertia, virtual inertia, time constant, deadband and both reserves must not be negative; droop and rating must be greater than zero when set; agc_participation lies in [0, 1]. A violation throws DynamicDataError naming the field. A negative zero is stored as 0.0.
Example
ps.dynamics = DynamicData(inertia_s = 4.0, droop_pu = 0.05, primary_reserve_mw = 20.0)Sparlectra.DynamicDataError — Type
DynamicDataError(field, value, rule)Thrown by the DynamicData constructor when a value breaks the rule of its field. field names the field, value is the rejected value and rule the condition it fails (for example "must be >= 0").
Sparlectra.DynamicUnitType — Type
DynamicUnitTypeHow a unit holds the grid frequency:
SynchronousUnit: a synchronous machine, inertia from its rotating mass.GridFollowingUnit: a converter that follows the grid voltage and needs another unit to form it. It cannot hold an island alone.GridFormingUnit: a converter that forms voltage and frequency itself, with a synthetic inertia (virtual_inertia_sofDynamicData).
SCF writes the values as "synchronous", "grid_following", "grid_forming" (dynamic_unit_type_name).
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(; net::Net, sparse::Bool = true, printYBUS::Bool = false)Build the bus admittance matrix (YBUS) of net.
Branches and :Y-model shunts in service are stamped; isolated buses (net.isoNodes) are left out and the remaining bus indices are shifted down, so the matrix has length(net.nodeVec) - length(net.isoNodes) rows. A branch open at one end stamps only its reduced admittance on the diagonal of the closed bus.
Keywords
net::Net: the network.sparse::Bool = true: return aSparseMatrixCSC{ComplexF64};falsereturns a denseMatrix{ComplexF64}.printYBUS::Bool = false: print the matrix (suppressed above 30 buses).
Returns
The bus admittance matrix, sparse or dense as requested.
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_RXBG(; 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,
get_vm_pu=nothing,
get_vset_pu=nothing,
v_hyst_pu::Float64=1e-4,
converged_iterate::Bool=false,
narrow_band_mask=falses(0),
verbose::Int=0,
io::IO=stdout,
) -> (changed::Bool, reenabled::Bool)Core PV/Q-limit active-set logic shared by solvers.
The PQ->PV release of a clamped bus is decided on the VOLTAGE side (#375, the "back off" rule of Sundaresh and Rao): a bus clamped at Qmax is released when Vm > Vset + v_hyst_pu, one clamped at Qmin when Vm < Vset - v_hyst_pu. The reactive injection of a clamped bus converges to the limit itself, so the former test "Q strictly inside the band" could never be true at a converged point and non-physical solutions were kept. The Q test remains the fallback for a bus without a stored side or without the voltage callbacks. Cooldown and the one-retry guard apply to both forms.
The one-retry guard keeps a bus clamped once it has hit its limit twice, against chattering in unsettled iterates. On a converged iterate (converged_iterate = true) on which nothing else switched, all such buses whose voltage sits on the release side are released together: a clamp taken in an early iterate must not outlive the state that caused it (#475: seven machines stayed at Qmin with the voltage below their setpoint). The group shrinks when it does not hold. A member that violates its limit again stays clamped for the rest of the solve (logged as kind = :group_hit); the other members go back to their limits with it (kind = :group_revert); neither counts as a hit. Only the bus types and the Q clamps go back, the voltages stay those of the failed iterate. On the next converged iterate the remaining members are released again as a smaller group. Each failed round removes at least one member, a solve allows at most QLIMIT_GROUP_RELEASE_MAX_ROUNDS (5) failed rounds, and the order is the bus order, so the result is deterministic and cannot oscillate. Released one by one or all without the revert, a group of mutually supporting machines diverged (spcase118, outage of branch 68-81); kept at their limits after the first failure, the members that would have held stayed clamped with the voltage on the release side (caseACTIVSg10k).
A bus set in narrow_band_mask (a machine of the Q-limit guard's narrow-range rule, band below qlimit_guard_min_q_range_pu, under narrow_range_mode = :lock_pq) is released by the voltage rule alone and only on a converged iterate. A band that narrow is crossed by small voltage changes, so in an unsettled iterate its voltage side says nothing and a release there would chatter; the converged voltage is the solution the clamp has to agree with. After the release the bus follows the rules above: one-retry, then the shrinking group of a converged iterate. Without the voltage callbacks such a bus is not released.
Under qlimit_guard_violation_mode = :lock_pq a PV bus also switches when its Q leaves the band by more than qlimit_guard_violation_threshold_pct percent of its band width Qmax - Qmin, before the hysteresis margin is reached. A zero band switches on any overshoot; a band with one infinite limit has no finite width and switches only on the hysteresis margin.
Callbacks:
- getqreqpu(bus) -> Float64
- getvmpu(bus) -> Float64, getvsetpu(bus) -> Float64 (voltage-side release)
- 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 row shows the iteration, the bus, the side (:min or :max) and the change: PV->PQ for a limit hit, PV->PQ (group) for the revert of a jointly released group, PQ->PV for a release (the side is the limit the bus was clamped at).
Sparlectra.printQLimitStabilityLine — Method
printQLimitStabilityLine(net; io=stdout, converged=true) -> StringPrint the line of the Q-limit stability check (qlimit_stability_line) and return it. A run through run_sparlectra stores its line in the solver status, with the lock reasons of its configuration; on a network solved by runpf! alone the check runs here on the solved state, with the default margins of qlimitStabilityReport. Part of the result print. The Q-V characteristic line printed before it (printQVCharacteristicCheck) uses the fixed tolerances, not the solver margins, so a machine within the release margin on the wrong side of its set point appears there and not here.
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.qlimitStabilityReport — Method
qlimitStabilityReport(net; locked_by = Dict{Int,Symbol}(), q_hyst_pu = net.q_hyst_pu,
v_hyst_pu = net.reenable_v_hyst_pu,
violation_threshold_pct = DEFAULT_QLIMIT_CONFIG.guard_violation_threshold_pct) -> Vector{NamedTuple}The stability conditions of Zhao, Chiang, Li, Ju (PSCC 2008) checked on the solved network, one row per voltage-regulated generator bus (a generator with a voltage regulator and a set point, no reference unit on the bus or on a bus joined to it by a closed link, not the reference the solver gives an island without a slack), whether it ended PV or PQ, switched or locked:
- (6)
(U - U_set)(Q_max - Q) >= 0: holds atQ_max(the factor is zero) and fails for a machine atQ_minbelow its set point; - (7)
(U - U_set)(Q - Q_min) <= 0: holds atQ_minand fails for a machine atQ_maxabove its set point.
A bus inside its band (neither at a limit) meets both only at its set point. A bus that ended PV is ok when Q_min <= Q <= Q_max; a bus that ended PQ when (6), (7) and the band hold.
The tolerances are the decision margins of the solver, so the check reports only states the active set would change itself:
- U against Uset: the release margin `vhystpu
(powerflow.qlimits.reenablevhyst_pu`); a clamped machine is released only beyond it; - Q beyond a limit: the switching margin of the bus,
q_hyst_pu(power_flow.qlimits.hysteresis_pu), or the smaller of it andviolation_threshold_pctpercent of the bandQ_max - Q_minwhen thelock_pqviolation rule acts (violation_threshold_pct = nothingwhen it does not). A machine over its limit by less sits on that limit and is within its band, as the final Q check accepts it (within_hysteresis); - Q inside a limit:
QLIMIT_STABILITY_TOL_Q_MVAR(1e-3 MVAr), within which a machine sits on the limit.
QLIMIT_STABILITY_TOL_U_PU (1e-6 pu) and QLIMIT_STABILITY_TOL_Q_MVAR are lower bounds of the two margins. q_hyst_pu and v_hyst_pu default to the margins the last configured solve stamped onto the net (net.q_hyst_pu, net.reenable_v_hyst_pu). The net does not carry the enforcement mode or the guard settings, so violation_threshold_pct defaults to the value of the default configuration (active set with the lock_pq rule); on a net solved under a classic mode or another threshold the defaults can differ from the margins of that solve. A run through run_sparlectra passes the values of its configuration and enforcement mode.
qvCharacteristicViolations reads this report with the lower bounds alone, not with the solver margins.
Q is the generator Q of the bus (MVAr) as the result report shows it (q_source = :report). On a net with a closed link, and at a bus that carries a Q(U) generator, it comes from the solved voltages instead (q_source = :voltages): the injection of the bus on the contracted network the solver works on plus what it draws itself (loads and voltage-dependent shunts), minus the generation of the other buses of its link cluster, with a Q(U) unit of the bus at its Q at the held voltage, as the bus band counts it. The report value is kept as q_report_MVar; it differs at a Q(U) bus, where the report keeps the scheduled Q of the regulating machine. Qmin and Qmax are the bus bands of getQLimits_pu. Uset is the regulator set point (`busvoltagesetpointsfromprosumers), not the start voltage.end_typeis:PQ` for a bus that ended PQ or carries a Q-limit event.
Row fields: bus, bus_name, end_type, q_MVar, qmin_MVar, qmax_MVar, u_pu, uset_pu, reached_limit (:max, :min, :none), check_6, check_7, in_band, ok, locked_by (from the locked_by lookup, :none for a bus not in it), q_source and q_report_MVar. The rows are in bus order. The caller decides whether the state is a solution; the function reads it as it is.
Sparlectra.qlimit_stability_line — Method
qlimit_stability_line(status, rows) -> StringThe Q-limit stability check of a run in one line, for the result print, run.log, the result metadata and the Web UI result page: "Q-limit stability violations: n", followed by the buses that fail when n > 0. status is :ok or :violations for a checked run, :not_checked for a run without a converged solution, :last_iterate for a run stopped at power_flow.max_iter (the check of its last iterate, which is no solution; after power_flow.dc.fallback the net no longer holds that iterate and the run is :not_checked) and :qlimits_disabled for a run without Q-limit handling.
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(condition (7) ofqlimitStabilityReportfails), orQ = QminwithVm < Vset(condition (6) fails).
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.
The rows come from qlimitStabilityReport with its fixed tolerances only: 1e-3 MVAr for Q against a limit, 1e-6 pu for U against Uset. They are the buses with a Q-limit event whose row sits on the limit of that event and fails the condition of that limit. Q and the set point are those of the stability report, the tolerances are not: the stability check of a run follows the decision margins of the solver (switching margin, release margin `reenablevhystpu) and reports what the solver would change itself. This check is the definition of the literature and does not depend on the configuration: a run with the voltage-side release switched off (reenablevhyst_pu = 1.0`) can end without a stability violation and still with non-physical machines here.
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 set point, so a bus close to its set point 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. The caller decides whether the state comes 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
ACLineSegmentAn AC line between two buses of one voltage level.
A physical line (built by addACLine! or addACLinePerKm!) stores the totals of the whole line: r and x in ohm, b and g in siemens. A PI-model line (built by addPIModelACLine!) stores per-unit values on the bus voltage and the network base. getLineRXBG_pu returns per unit for both kinds.
Fields
comp::AbstractComponent: the component record.length_km::Union{Nothing,Float64}: line length in km, information only (used byshowand as CGMESConductor.lengthin the export); it never scalesr,x,borg.r::Float64,x::Float64: series resistance and reactance, ohm (physical) or per unit (PI model).b::Float64,g::Float64: total shunt susceptance and conductance, siemens (physical) or per unit (PI model).ratedS::Union{Nothing,Float64}: rated power in MVA._isPIModel::Bool:truewhen the values are per unit.
Constructor
ACLineSegment(; vn_kv, from, to, r, x, b = 0.0, g = 0.0, length_km = nothing, ratedS = nothing, isPIModel)isPIModel has no default: the caller states the unit of the four values.
Sparlectra.getLineRXBG — Method
getLineRXBG(o::ACLineSegment) -> NTuple{4,Float64}The stored values (r, x, b, g) of the line: totals in ohm and siemens for a physical line, per unit for a PI-model line (see isLinePIModel). Use getLineRXBG_pu for per-unit values of either kind.
Sparlectra.getLineRXBG_pu — Method
getLineRXBG_pu(o, vn_kV, baseMVA) -> (r, x, b, g)The line parameters in per unit on vn_kV and baseMVA. A physical line is converted with toPU_RXBG; a PI-model line already holds per unit and is returned unchanged.
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.Net — Type
NetThe 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.
Fields (selection)
name::String: Name of the network.baseMVA::Float64: Base MVA of the network.nominal_frequency_hz::Float64: System frequency in Hz. Read where a value given per capacitance becomes a susceptance (addACLinePerKm!, the linec1of an SCF or PGM file). Set by an SCF file (meta.f_nom), otherwise bymodel.nominal_frequency_hzat import (default 50)._frequency_used::Bool:trueonce a nonzero capacitance became a susceptance withnominal_frequency_hz; a network without capacitance in farad (pu values, orc1 = 0) leaves itfalse. Read bynominal_frequency_linefor the run header._sv_vm_pu::Dict{Int,Float64}: bus voltage magnitudes of the imported state in pu by bus index (theSvVoltageof a CGMES import), empty for other sources; the substitute of the state-estimation range check.slackVec::Vector{Int}: Vector containing indices of slack buses.vmin_pu::Float64: Minimum voltage limit in per unit.vmax_pu::Float64: Maximum voltage limit in per unit.nodeVec::Vector{Node}: Vector containing nodes in the network.linesAC::Vector{ACLineSegment}: Vector containing AC line segments.trafos::Vector{PowerTransformer}: Vector containing power transformers.branchVec::Vector{Branch}: Vector containing branches in the network.linkVec::Vector{BusLink}: impedance-less bus links (busbar couplers), seeaddLink!.prosumpsVec::Vector{ProSumer}: Vector containing prosumers in the network.shuntVec::Vector{Shunt}: Vector containing shunts in the network.busDict::Dict{String,Int}: Dictionary mapping bus names to indices.busOrigIdxDict::Dict{Int,Int}: Dictionary mapping current bus indices to original indices.busOriginalNameDict::Dict{Int,String}: Optional original source-file bus names keyed by current bus index.totalLosses::Vector{Tuple{Float64,Float64}}: Vector containing tuples of total power losses._locked::Bool: Boolean indicating if the network is locked.flatstart::Bool: start mode of the power flow (1 pu, and 0 degrees plus the transformer phase shifts on the path from the reference, instead of the stored bus voltages).bus_shunt_model::Symbol: how bus shunts enter the power flow (:admittanceor:voltage_dependent_injection).measurements::Vector: State-estimation measurements stored on the network.matpower_branch_metadata::Dict{Int,NamedTuple}: Optional MATPOWER branch metadata keyed by imported branch index.for001Contingencies::Vector{String}: Optional FOR001 contingency branch names imported from MATPOWER metadata.matpowerDclineMetadata::Vector{NamedTuple}: Optional imported MATPOWER DC-line terminal-injection metadata.cgmes_ids::Dict{String,String}: CGMES mRIDs keyed by structural identity (e.g."TN|<bus>","ACL|<busA>|<busB>|<k>"); filled by the CGMES importer and reused by the CGMES exporter so exported ids stay stable.equivalent_branch_metadata::Dict{Int,NamedTuple}: The delivered values of every branch built from a CGMESEquivalentBranch, keyed by branch index:r,x,r21,x21in ohm on the basevn_kVof terminal 1, andstampedfor the phase stamp of an asymmetric one. The power flow never reads it; it marks the branch as an equivalent branch in the results and lets the CGMES export write the delivered values.
Constructors
Net(; name::String, baseMVA::Float64, vmin_pu = 0.9, vmax_pu = 1.1, flatstart = false, bus_shunt_model = :admittance, nominal_frequency_hz = model_config().nominal_frequency_hz, ...): Creates an emptyNetwith the given name, base MVA and voltage limits; the remaining keywords set the Q-limit parameters.nominal_frequency_hzmust be positive (ArgumentErrorotherwise).
Functions
addBus!(; net::Net, ...): Adds a bus to the network.addShunt!(; net::Net, ...): Adds a shunt to the network.addBranch!(; net::Net, ...): Adds a branch to the network.addPIModelACLine!(; net::Net, ...): Adds a PI model AC line to the network.addACLine!(; net::Net, ...): Adds an AC line from its totals in ohm and siemens.addACLinePerKm!(; net::Net, ...): Adds an AC line from values per km and its length.addPIModelTrafo!(; net::Net, ...): Adds a transformer with PI model to the network.add2WTrafo!(; net::Net, ...): Adds a two-winding transformer to the network.addProsumer!(; net::Net, ...): Adds a prosumer to the network.addLink!(; net::Net, fromBus::String, toBus::String, status): Adds a bus link to the network.lockNet!(; net::Net, locked::Bool): Locks or unlocks the network.validate!(; net::Net): Validates the network.get_bus_vn_kV(; net::Net, busName::String): Gets the voltage level of a bus by name.get_vn_kV(; net::Net, busIdx::Int): Gets the voltage level of a bus by index.getBusType(; net::Net, busName::String): Gets the type of a bus by name.updateBranchParameters!(; net::Net, branchNr::Int, branch::BranchModel): Updates the parameters of a branch in the network.setNetBranchStatus!(; net::Net, branchNr::Int, status::Int): Sets the status of a branch.setTotalLosses!(; net::Net, pLosses::Float64, qLosses::Float64): Sets the total losses of the network.getTotalLosses(; net::Net): Gets the total losses of the network.getNetOrigBusIdx(; net::Net, busName::String): Gets the original index of a bus in the network.geNetBusIdx(; net::Net, busName::String): Gets the index of a bus in the network.hasBusInNet(; net::Net, busName::String): Checks if a bus exists in the network.addBusGenPower!(; net::Net, busName::String, p::Float64, q::Float64): Adds generator power to a bus.addBusLoadPower!(; net::Net, busName::String, p::Float64, q::Float64): Adds load power to a bus.getNetBranch(; net::Net, fromBus::String, toBus::String): Retrieves the branch between two specified buses in the network.
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 in MVA.vk_percent::Float64: Short-circuit voltage in percent of the rated voltage.vkr_percent::Float64: Resistive part of the short-circuit voltage in percent (0 for a lossless series impedance).pfe_kw::Float64: Iron (no-load) loss in kW; withi0_percentit forms the magnetizing branch (g,bof the winding), 0 for none.i0_percent::Float64: No-load current in percent of the rated current.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!(; net::Net, fromBus::String, toBus::String, r_ohm::Float64, x_ohm::Float64,
b_s::Float64 = 0.0, g_s::Float64 = 0.0, length_km = nothing, ratedS = nothing,
status::Int = 1, from_status = nothing, to_status = nothing)Adds an AC line between two buses of the same voltage level from the totals of the whole line in physical units. The values are converted to per unit on the bus voltage and net.baseMVA with toPU_RXBG; the line keeps the ohm and siemens values (see ACLineSegment).
For data given per km use addACLinePerKm!, for per-unit data addPIModelACLine!.
Arguments
net::Net: The network.fromBus::String,toBus::String: Names of the two buses.r_ohm::Float64,x_ohm::Float64: Series resistance and reactance of the line in ohm.b_s::Float64 = 0.0: Total shunt susceptance in siemens, split half and half onto the two ends.g_s::Float64 = 0.0: Total shunt conductance in siemens, split the same way.length_km::Union{Nothing,Float64} = nothing: Length in km. Information only: used byshowand as CGMESConductor.lengthin the export; it does not scale the values.ratedS::Union{Nothing,Float64} = nothing: Rated power in MVA.status::Int = 1: 1 in service, 0 out of service.from_status,to_status: The switch state of each end (0 or 1);nothing(default) takesstatus.
The keywords of the per-unit form before 0.50.0 (r, x, b, length, c_nf_per_km, tanδ) throw an ArgumentError that names the replacement.
Example
addACLine!(net = net, fromBus = "B1", toBus = "B2", r_ohm = 2.4, x_ohm = 7.8, b_s = 5.7e-5, length_km = 20.0)Sparlectra.addACLinePerKm! — Method
addACLinePerKm!(; net::Net, fromBus::String, toBus::String, length_km::Float64,
r_ohm_per_km::Float64, x_ohm_per_km::Float64, c_nf_per_km::Float64,
g_us_per_km = nothing, tanδ = nothing, ratedS = nothing,
status::Int = 1, from_status = nothing, to_status = nothing)Adds an AC line from values per km (the form of pandapower line types and of most cable and overhead-line data sheets). Every value is multiplied by length_km, then the line takes the same path as addACLine!.
The susceptance comes from the capacitance, b = 2π·f·C, with the system frequency f of the network (net.nominal_frequency_hz; a new Net takes model.nominal_frequency_hz, default 50 Hz). The conductance comes from g_us_per_km or from the loss factor, g = tanδ·b; without either it is zero. Giving both is an error.
Arguments
net::Net: The network.fromBus::String,toBus::String: Names of the two buses.length_km::Float64: Length in km, greater than zero.r_ohm_per_km::Float64,x_ohm_per_km::Float64: Series resistance and reactance in ohm/km.c_nf_per_km::Float64: Capacitance in nF/km (0.0 for a line without charging).g_us_per_km::Union{Nothing,Float64} = nothing: Shunt conductance in µS/km.tanδ::Union{Nothing,Float64} = nothing: Loss factor of the capacitance.ratedS,status,from_status,to_status: as foraddACLine!.
Example
# 20 km of a 110 kV overhead line
addACLinePerKm!(net = net, fromBus = "B1", toBus = "B2", length_km = 20.0, r_ohm_per_km = 0.12, x_ohm_per_km = 0.39, c_nf_per_km = 9.5)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.
busName is the key of net.busDict and the component name of the node. Only an empty busName gives the schematic name Bus_<idx>_<kV> (Aux_<idx>_<kV> for an auxiliary bus).
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: The bus is auxiliary (three-winding star point, internal node of an importer). The node then carries the component typeAuxBus, which marks it auxiliary whatever its name.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.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).referencePriority::Int = 0: reference priority of the source (CGMES semantics, 1 = strongest), forwarded toaddProsumer!.
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). Address links by the returned index, e.g. through setNetLinkStatus!.
Sparlectra.addPIModelACLine! — Method
addPIModelACLine!(; net::Net, fromBus::String, toBus::String, r_pu::Float64, x_pu::Float64, b_pu::Float64, status::Int,
g_pu=nothing, ratedS=nothing, from_status=nothing, to_status=nothing,
g_from_pu=nothing, b_from_pu=nothing, g_to_pu=nothing, b_to_pu=nothing)Adds an AC line branch to the network from PI-model per-unit parameters. Both buses must exist, differ and lie on the same voltage level.
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.status::Int: The status of the line. 1 = in service, 0 = out of service.g_pu::Union{Nothing,Float64}: The per unit total shunt conductance of the line (e.g. CGMESgchafter conversion). Default isnothing(treated as 0.0).ratedS::Union{Nothing,Float64}: The rated power of the line in MVA. Default isnothing.from_status,to_status: The switch state of each end (0 or 1);nothing(default) takesstatus. One open end leaves the line connected at the other.g_from_pu,b_from_pu,g_to_pu,b_to_pu: An explicit split of the shunt admittance onto the two ends, all four together or none (anArgumentErrorotherwise); when given, the stored totalsg_puandb_puare their sums.
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! — 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.referencePriority::Int: Reference priority of the unit, CGMES semantics (0 = no preference, 1 = strongest, larger = weaker). It decides which unit becomes the reference of an AC island without one and which unit replaces an outaged slack; it does not make the unit a slack by itself (that isreferencePri). Default is0. ThrowsArgumentErrorfor a negative value.
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.
The band of a bus bounds its total generator Q. On a bus with a regulating or reference unit it is the sum of the minQ/maxQ of its regulating and reference units (a missing limit makes that end unbounded) plus the fixed Q of every other generator-type unit at both ends: its scheduled qVal, or for a unit with a QUController its Q at the held bus voltage. Such a unit does not widen the range, whatever its own limits. On a bus without a regulating or reference unit the band is the sum of all its units' limits.
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), the external-network and equivalent-injection short-circuit records of the bus are dropped (the new source replaces them), 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). Under a distributed slack a participating unit gets its schedule plus its share of lambda_P; a reference unit gets what the bus delivers beyond the other units at its bus.
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 best injection candidate on a non-isolated bus is promoted to slack (referencePri = 1) and its bus index is returned.
Candidate order: a stated reference priority first (referencePriority, CGMES semantics: the smallest positive value wins, 0 states none), then reference_candidate_rank, the ranking of the importers as well: ExternalNetworkInjection units win over generators and synchronous machines, a unit that regulates the voltage of its own bus wins over one that does not, and then 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 N-1 run uses this promotion when an outage removes the slack (auto_slack, default on there).
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
getNetBranchNumberVec(; net::Net, fromBus::String, toBus::String) -> Vector{Int}The numbers (positions in net.branchVec) of every branch that runs from fromBus to toBus, in this direction; parallel branches give several numbers, none gives an empty vector. An unknown bus name is an error.
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
initialVrect(net; flatstart = net.flatstart, rotate_behind_pst = false) -> (V0, slack_idx)Build the initial complex voltage vector V0 from the network bus data (Vm, Va), and detect the slack bus index.
With flatstart = true every PQ bus starts at the mean voltage setpoint of the slack and PV buses of its AC island (connected over in-service branches and closed links), 1.0 pu in an island without such a bus. PV buses start at their stored magnitude, and the slack keeps its magnitude and angle. Every other bus starts at the slack angle. With rotate_behind_pst = true (power_flow.start_mode.rotate_behind_pst, default false) a bus that the reference reaches only across phase-shifting transformers gets the slack angle plus the sum of the shifts on a path with the fewest shifters (_flat_start_shift_angles); a bus that a path without shifter reaches keeps the slack angle, since in a mesh the parallel path fixes its angle. On a radial net no shifter then carries its shift across its series impedance at the start.
With flatstart = false the stored Vm and Va are used. A stored start that holds no angle (every bus but the slack at 0 degrees, the addBus! default or an unsolved case file, or at the slack angle, the flat start of a model-only MATPOWER export) on a net with phase shifters gets the angles of the flat start when rotate_behind_pst = true, since it puts the whole shift across the transformer impedance in the same way. With rotate_behind_pst = false no bus is turned, and the whole shift of a phase shifter lies across its series impedance at the start.
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, log::Bool = false, links::Bool = false)Finds and marks isolated buses in the network: a bus without an in-service branch becomes Isolated with voltage 0 and is listed in net.isoNodes.
Arguments
net::Net: The network.log::Bool: log every isolated bus with@info.links::Bool: apply the rule of the power flow to closed bus links (net.linkVec, status 1): the buses joined by closed links form one group, the node the power flow contracts them to, and every bus of a group is in service when the group has an in-service branch. A bus that hangs on the rest only through a closed link therefore stays in service, a group of linked buses without any branch is isolated as a whole. Defaultfalse: only branches connect.
A bus this function typed Isolated in an earlier call is typed back to PQ once an in-service branch of its own reaches it again (a closed link alone does not); refreshBusTypesFromProsumers!, which every runpf! runs, then gives it its type from its prosumers. A bus typed Isolated by an import, a bus op or a user call keeps that type; only net.isoNodes is rebuilt for it. An Isolated bus in a closed-link group with a bus that is not Isolated starts at the voltage of the first such bus instead of 0: the power flow contracts the group onto its smallest bus and starts it from there. Returns net.isoNodes, sorted.
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.reference_candidate_rank — Method
reference_candidate_rank(; external, regulates_locally, size) -> TupleThe one ranking for every place that has to choose a reference unit: the slack of an imported network, the unit ensureSlack! promotes, the unit an island takes when an outage removed its reference. The larger tuple wins:
- an external network injection before any other unit (a grid equivalent is the natural reference);
- a unit that regulates the voltage of its OWN bus before one that does not (a reference bus keeps the voltage it starts with, so a unit that regulates elsewhere, or not at all, leaves its own bus wherever the start put it);
- the size of the unit: its rated power where it states one, else its maximum active power, else its scheduled output.
For the units of a network a stated reference priority comes first (ProSumer.referencePriority, CGMES semantics: 1 is the strongest, 0 states none): the unit with the smallest positive priority wins, and this ranking decides between units of equal priority and among units without one. An importer that picks the slack of a file uses the ranking alone.
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 and refreshes the isolated-bus marks of the network afterwards.
Arguments
net::Net: The network.branchNr::Int: The number of the branch (its position innet.branchVec).status::Int: The status of the branch: 1 = in service, any other value = out of service.
Example
setNetBranchStatus!(net = network, branchNr = 1, status = 1)
brVec = getNetBranchNumberVec(net = network, fromBus = "B1", toBus = "B2")
setNetBranchStatus!(net = network, branchNr = brVec[1], status = 0)Sparlectra.setNetLinkStatus! — Method
setNetLinkStatus!(; net::Net, linkNr::Int, status::Int)Sets an existing link status (0/1).
Sparlectra.setNodeAngle! — Method
setNodeAngle!(; 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.
One slack bus per AC island is normal. An island with more than one slack bus gets a warning naming the buses (the power flow rejects it); with log = true the number of slack buses and islands is logged as well.
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, name::AbstractString = "", ): Creates a newNodeinstance.namebecomes the component name; an emptynamegives the schematic name (seegetNodeComp).isAuxgives the component typeAuxBus, the marker of an auxiliary node.
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.GenCost — Type
GenCost(p, q = nothing)Generator cost data of one generating unit in MATPOWER mpc.gencost form, kept so a MATPOWER or SCF export writes it back unchanged. Sparlectra has no OPF: no calculation reads it.
p::Vector{Float64}: the active-power cost row:MODEL,STARTUP,SHUTDOWN,NCOST, thenNCOST(x, y) points for model 1 (piecewise linear) orNCOSTpolynomial coefficients, highest order first, for model 2. Kept as read, trailing zero padding included.q::Union{Nothing,Vector{Float64}}: the reactive-power cost row in the same form,nothingwhen the case has none.
Throws ArgumentError when a row is not a valid model 1 or 2 row (see gencost_row_problem).
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.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.referencePri: marker of the unit that holds the reference (slack) role; it stores a bus index, seeisSlack.referencePriority::Int: reference priority with CGMESreferencePrioritysemantics (0 = no preference, 1 = strongest, larger = weaker). It orders the units that may take over a reference: an AC island without one and the replacement of an outaged slack (ensureSlack!). Default 0.gencost::Union{Nothing,GenCost}: MATPOWER generator cost rows of a generating unit (GenCost), kept for the export; no calculation reads it.nothingwhen the source has none.dynamics::Union{Nothing,DynamicData}: dynamic parameters of the unit (DynamicData): inertia, damping, droop, reserves, unit type. No calculation reads them.nothingwhen the source has none.
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.VoltageCharacteristic — Type
VoltageCharacteristic(points; interpolation = :linear)Characteristic y = f(u) of a Q(U) or P(U) controller, given by ordered (u, y) points and an interpolation mode: :linear (straight segments), :spline (natural cubic spline) or :polynomial (Newton form through the points); make_characteristic builds one from engineering units. Outside the point range, values are clamped to the edge points and the derivative is 0.0.
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.Shunt — Type
ShuntA bus shunt: its admittance in per unit, its model (admittance or voltage-dependent injection), its status and the powers it draws after a solve.
Fields
comp::AbstractComponent: The component of the shunt.vn_kV::Float64: The nominal voltage of the shunt in kV.baseMVA::Float64: The base MVA for per unit calculations.busIdx::Int: The index of the bus.p_shunt::Float64: The active power of the shunt (MW): 0 after construction, the solved draw after a solve.q_shunt::Float64: The reactive power of the shunt (MVar): 0 after construction, the solved draw after a solve.G_shunt::Float64: The conductance of the shunt; the constructor stores the real part ofy_pu_shunt(per unit).B_shunt::Float64: The susceptance of the shunt; the constructor stores the imaginary part ofy_pu_shunt(per unit).y_pu_shunt::ComplexF64: The shunt admittance in per unit (solver-relevant for Y-shunts).model::Symbol: The shunt model -:Yfor admittance-matrix stamping,:VoltageDependentInjectionfor voltage-dependent mismatch terms, or:PQfor legacy constant power.status::Int: The status of the shunt. 1 = in service, 0 = out of service.estimate::Bool: released for susceptance estimation in the state estimation (defaultfalse, seesetShuntEstimation!).
Constructors
Shunt(; fromBus::Int, id::Int, base_MVA::Float64, vn_kV_shunt::Float64, p_shunt::Union{Nothing,Float64} = nothing, q_shunt::Union{Nothing,Float64} = nothing, g_shunt::Union{Nothing,Float64} = nothing, b_shunt::Union{Nothing,Float64} = nothing, y_pu::Union{Nothing,ComplexF64} = nothing, values_are_pu::Bool = false, model::Symbol = :Y, ratio::Float64 = 1.0, status::Int = 1): Creates a newShuntinstance. Provide eithery_puOR (g_shunt,b_shunt) OR (p_shunt,q_shunt).g_shunt/b_shuntare in Siemens unlessvalues_are_pu = true;p_shunt/q_shuntare MW/MVar at 1 pu voltage formodel = :Y, whilemodel = :PQleaves the admittance at zero.
Methods
Base.show(io::IO, shunt::Shunt): Prints theShuntinstance.
Sparlectra.getGBShunt — Method
getGBShunt(o) -> (g, b)The shunt admittance in per unit.
Sparlectra.getPQShunt — Method
getPQShunt(o) -> (p, q)The shunt draw in MW/MVar: 0 after construction, the draw at 1 pu voltage after updatePQShunt!, and the solved draw (scaled with the squared bus voltage) after a power flow.
Sparlectra.updatePQShunt! — Method
updatePQShunt!(o, p, q)Set the shunt from its draw p/q in MW/MVar at 1 pu voltage, the same way the constructor and addShunt! do: the per-unit admittance becomes y_pu_shunt = (p + jq) / baseMVA, G_shunt/B_shunt its real and imaginary part (per unit), and p_shunt/q_shunt hold p/q until the next power flow writes the solved draw.
Sparlectra.TAP_CHANGER_KIND_TABLE — Constant
TAP_CHANGER_KIND_TABLEOne row per source name: source, name, the Sparlectra kind (:symmetrical, :asymmetrical, :tabular for a PhaseTapChangerModel, :ratio for a PowerTransformerTaps, :grid for the branch-level grid without a model), the model family (:phase, :ratio, :grid), the default winding angle psi_deg of an asymmetrical changer (nothing when the nameplate states it), and a note. CGMES PhaseTapChangerLinear is a :tabular model with generated points (there is no fourth kind); the DTF regulator types all map to :asymmetrical with their nameplate angle, the longitudinal regulator included (angle 0), because that is the regulating vector the DTF importer reproduces.
Sparlectra.tap_changer_kind — Method
tap_changer_kind(source::Symbol, name::AbstractString; angle = nothing) -> NamedTupleThe Sparlectra kind of a source's tap changer from TAP_CHANGER_KIND_TABLE: (kind, model, psi_deg). angle supplies the winding angle of an asymmetrical changer when the nameplate states it (CGMES windingConnectionAngle, the DTF angle); without it the table's default applies. Throws an ArgumentError for a name the table does not carry, so an importer cannot silently invent a kind.
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
PowerTransformerA mutable structure representing a power transformer in a power system.
Fields
comp::AbstractComponent: The component of the power transformer.trafoTyp::TrafoTyp: The type of the transformer.isControlled::Bool: Whether the tap changer is enabled.nS::Integer: The number of active sides, >=2.nController::Integer: The number of sides controlled.isBiWinder::Bool: Whether the transformer is a bi-winder.HVSideNumber::Integer: The number of the high voltage side [1,2,3]. For a 3-winding transformer, HV =1, MV=2, LV=3.tapSideNumber::Integer: The number of the tap side [1,2,3]. It is 0 if there is no tap.side1::PowerTransformerWinding: The first winding of the transformer.side2::PowerTransformerWinding: The second winding of the transformer.side3::Union{Nothing,PowerTransformerWinding}: The third winding of the transformer. It can beNothingor aPowerTransformerWindinginstance._equiParms::Integer: The winding side with short-circuit parameters. 1 for side1, 2 for side2, 3 for all sides (3-winding transformer).
Constructors
PowerTransformer(comp::AbstractComponent, tapEnable::Bool, s1::PowerTransformerWinding, s2::PowerTransformerWinding, s3::Union{Nothing,PowerTransformerWinding} = nothing, trafoTyp::TrafoTyp = Sparlectra.Ratio): Creates a newPowerTransformerinstance.
Methods
Base.show(io::IO, x::PowerTransformer): Prints thePowerTransformerinstance.
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.SETapChanger — Type
SETapChangerData of one tap changer of a transformer branch for the tap estimation (state estimation only; power flow, controllers and export do not read it). kind is the changer type: :ratio (in-phase, factor 1 + s du), :asymmetrical (factor 1 + s du e^(j alpha), a quadrature changer is alpha 90), :symmetrical (angle 2 atan(s du / 2), magnitude 1), :tabular (table points, linear in between) or :linear (angle s dphi, magnitude 1). role is :ratio or :phase and decides which release moves it. side is :from when the factor multiplies the branch ratio and :to when it divides it; additive marks the ratio changer of a linear nameplate grid, R = R_n + s step_abs, which must be the first changer of its set. Positions are absolute steps (neutral, low, high, the import position step); the estimator's state is s = step - neutral. outside_du continues a ratio table with 1 + s outside_du beyond its points. x_curve = (x_min, x_max, a_max_deg) is a reactance curve over the changer's own angle in the form x_curve_form (:sin2 of the CGMES import, :tan2 of a typed asymmetrical model). impedance names the per-step impedance data (:none, :table, :x_curve, :tsi for the branch TapStepImpedance), rx_correction the impedance correction of model.tap_changer_model = impedance_correction. step_assumed marks a changer whose import carried no step: step is then the middle position (the neutral step, the band middle without one) and the report row of the tap estimation says so. Optional numbers are nothing. The keyword constructor checks the fields and throws an ArgumentError naming the field.
Sparlectra.SETapChangerSet — Type
SETapChangerSetThe tap changers of one transformer branch for the tap estimation: the branch ratio ratio_n and shift shift_n_deg without the changers' factors (the branch at the neutral steps of the formula kinds), the changers in the composition order of the import, and the origin (:cgmes, :powsybl for a set an import stored on the branch; :typed, :fields for a set derived on demand from the typed models or the branch fields). An empty changers vector stored by an import declares "no tap changer": the transformer is never released. The keyword constructor checks the fields (ArgumentError naming the field), among them that an additive changer comes first.
Sparlectra.SETapPoint — Type
SETapPointOne point of a tap changer table as the state estimation reads it: the absolute step, the changer's own factor at that step (ratio, angle_deg), and the impedance at the step as factors r, x, g, b (1 + percent/100 of a CGMES or IIDM point; the absolute x in pu for a typed table with x_pu; 1.0 without data). Only ratios of the impedance numbers enter the estimator.
Sparlectra.TapStepImpedance — Type
TapStepImpedanceImpedance of a transformer branch per tap step, for tap changer tables whose points carry r, x, g, b deviations (CGMES TapChangerTablePoint). r_pu, x_pu and the four terminal admittances are the branch values without the factors of the tables listed here. ratio_values holds the branch tap_ratio at each step of the ratio table and ratio_factors the factors (r, x, g, b) of that step; phase_values and phase_factors do the same for phase_shift_deg. An empty pair means no table on that actuator. A tap controller that moves the branch calls _apply_tap_step_impedance!, which picks the step nearest to the live tap_ratio and phase_shift_deg.
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"). Two kinds of branch are exempt (_negative_r_allowed_branches): a branch built from a CGMES EquivalentBranch (net.equivalent_branch_metadata), a network equivalent where a negative r or x is normal in Ward and Kron reductions, and a leg of a three-winding star equivalent, where a single leg can be negative and only the sums of two legs are physical.
Sparlectra.has_symmetric_shunt — Method
has_symmetric_shunt(branch::Branch; atol = 1e-12) -> BoolWhether the two terminal shunt arms of branch are equal, the symmetric pi model that MATPOWER writes as one BR_B.
Sparlectra.set_branch_shunt! — Method
set_branch_shunt!(branch::Branch; g_from_pu, b_from_pu, g_to_pu, b_to_pu) -> BranchSet the charging admittance of both terminals of branch in pu and keep the totals g_pu, b_pu equal to their sums. This is the ONE writer of these fields after construction; no code writes a total alone.
Sparlectra.set_branch_shunt_total! — Method
set_branch_shunt_total!(branch::Branch; g_pu, b_pu) -> BranchSet the total charging admittance of branch with the symmetric split, half at each terminal (the MATPOWER form).
Sparlectra.dynamic_unit_type_name — Method
dynamic_unit_type_name(t::DynamicUnitType) -> StringThe SCF spelling of a unit type: "synchronous", "grid_following" or "grid_forming".
Sparlectra.parse_dynamic_unit_type — Method
parse_dynamic_unit_type(s::AbstractString) -> DynamicUnitTypeThe unit type of its SCF spelling (dynamic_unit_type_name). Throws ArgumentError naming the allowed values for anything else.
Sparlectra.calc2WTEndsReferredRXGB — Method
calc2WTEndsReferredRXGB(; r1, x1, g1, b1, r2, x2, g2, b2, U1, U2) -> (r, x, g, b, g_from, b_from, g_to, b_to)Refer the impedance/admittance contributions of both PowerTransformerEnds of a CGMES two-winding transformer to the end-2 voltage base. 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 series values are summed (r, x); the shunt admittance is returned per end on the end-2 base (g_from, b_from for end 1, g_to, b_to for end 2, both in siemens) next to the totals g, b. The CGMES import uses the totals and puts half of them on each terminal arm (since 0.41.0), the placement the SV of the ENTSO-E test configurations is computed with. 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, the from arm behind it).
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.pi_branch_pu_between_levels — Method
pi_branch_pu_between_levels(; r, x, g_from, b_from, g_to, b_to, vn_from_kV, vn_to_kV, baseMVA) -> NamedTupleThe per-unit parameters of a pi branch given in ohm and siemens between two buses, on Sparlectra's branch convention: series admittance and both shunt arms on the TO-side voltage base, and, when the two buses sit on different nominal voltages, the ratio vn_to / vn_from at the from side (the same physical conductor seen through the two bases, so the 2WT formula with equal rated voltages degenerates to that ratio). The from arm is stamped behind that ratio, which is exactly a shunt of g_from, b_from siemens at the from bus on its own voltage: converting both arms with the to-side base is therefore right for both ends. ratio is nothing for equal nominal voltages; b_pu, g_pu are the totals. Shared by the CGMES line mapping and the PowSyBl builder.
Sparlectra.resolve_branch_taps! — Method
resolve_branch_taps!(br::Branch, w::PowerTransformerWinding; tap_changer_model = :ideal) -> Union{Nothing,String}Write the quantities of resolve_winding_taps onto the branch: ratio, angle, the live tap_ratio/phase_shift_deg, the tap grid, and r_pu/x_pu from the equipment base r_base_pu/x_base_pu through the correction factor (or the model's own X(alpha)); marks the branch taps_derived and keeps the winding on it. Called at build for every transformer branch and by the tap controllers after they move a model step; a winding without models leaves the branch untouched with taps_derived = false. Returns the precedence line (one sentence naming branch, old and new values and the step) when the branch held other values than the model gives, nothing when they were equal within 1e-9.
Sparlectra.resolve_winding_taps — Method
resolve_winding_taps(w::PowerTransformerWinding; tap_changer_model = :ideal, ratio_step = nothing, phase_step = nothing) -> Union{Nothing,NamedTuple}The branch quantities the typed tap models of a winding give at a step, without touching anything: ratio, shift_deg, the tap grid (tap_min, tap_max, tap_step, phase_min_deg, phase_max_deg, phase_step_deg), the impedance correction factor rx_factor of model.tap_changer_model (calcTapCorrectedRX at the model's tap fraction and winding angle, 1.0 for :ideal), and x_alpha, the tap-dependent reactance of a model that carries x_min/x_max or a table (nothing otherwise). The winding's ratio (default 1) and shift_degree (default 0) are the neutral point: the ratio-tap correction and the phase model's effective ratio multiply it, the phase model's shift adds to it. ratio_step and phase_step evaluate another step than the models' current one (a controller asking where a step would take the branch). Returns nothing for a winding without models.
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.QLIMIT_STABILITY_TOL_Q_MVAR — Constant
QLIMIT_STABILITY_TOL_Q_MVARReactive power tolerance of the Q-limit stability check on the inside of a limit (1e-3 MVAr): a machine this close below a limit sits on it. Beyond the limit the tolerance is the switching margin of the bus (see qlimitStabilityReport), at least this value, so that round-off of a Q computed from the solved voltages does not count as a violation. qvCharacteristicViolations and the band verdict of an APSLF run use this value alone on both sides.
Sparlectra.QLIMIT_STABILITY_TOL_U_PU — Constant
QLIMIT_STABILITY_TOL_U_PULower bound of the voltage tolerance of the Q-limit stability check (1e-6 pu). The tolerance itself is the release margin reenable_v_hyst_pu; this bound applies when that margin is smaller. qvCharacteristicViolations and the band verdict of an APSLF run use this value alone.
Sparlectra._qv_effective_qgen — Function
_qv_effective_qgen(net, bus, limit_mvar = NaN) -> Float64The reactive power a clamped machine at bus really injects, in MVAr. Two places hold it and each enforcement mode writes only one of them: the active set writes the clamp back to the node (_qƩGen) and leaves the specification alone, the classical outer loop applies the clamp in the specification (what _effective_bus_power_components reads) and leaves the node alone. Reading one of them alone therefore misses every machine the OTHER mode clamped: on the Zeng case the node said 54.17 MVAr at a 50 MVAr limit under the classical loop and the check reported nothing, and the specification said 42.4 under the active set (measured). With a limit_mvar given, the candidate closer to that limit is the one the solver enforced; a re-enabled machine sits on neither, and stays invisible to the check as it should. A Q(U)-controlled machine has its own source, the characteristic.
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_config_net_parameters! — Method
_apply_config_net_parameters!(net, pf_cfg) -> NetStamp the solver-behaviour parameters the configuration owns onto a network: the Q-limit switching parameters (_apply_qlimit_net_parameters!) and the flat-start flag. The method for a full SparlectraConfig also stamps the system frequency (model.nominal_frequency_hz) unless the case file stated one. Every construction path calls this, and no path carries its own copy of the assignments, because four paths setting them differently is exactly how a case file came to run with hysteresis 0 whatever the configuration said.
bus_shunt_model is NOT among them on purpose: it is consumed while the shunts are built (addShuntMatpower! reads it from the network at that moment) and never again, so it has to reach the constructor of the path in question. Setting it afterwards would change the field without changing a single shunt.
Reach of the stamps: a CONFIGURED run overrides both. The solver entry passes opt_flatstart = start.flatstart from the run configuration directly (see rectangular_network_solver.jl), and on CGMES runs the cgmes_import.start_values rewrite wins on that route as intended. The Q-limit switching parameters are stamped again from the run configuration before every configured solve. The import stamp is what makes config-less direct solves (runpf!(net, ...), library use, SE internals) follow the configuration that was in hand at import.
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._apply_qlimit_net_parameters! — Method
_apply_qlimit_net_parameters!(net, qlim::QLimitConfig) -> NetStamp the four Q-limit switching parameters of power_flow.qlimits onto a network: cooldown_iters, hysteresis_pu (field q_hyst_pu), reenable_v_hyst_pu and final_q_accept_pu. The solver reads these four from the network only (active set, classic outer loop and the final Q-limit check), so this function is the one place where the configuration reaches them. Two callers: _apply_config_net_parameters! at import, and every configured solve (_runpf_config_once!) right before it starts, so the run configuration wins over the values the network was imported with.
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 transformer values are in per unit (default is false). Ignored for anACLineSegment, which carries the unit of its values itself.
Sparlectra.nominal_frequency_line — Method
nominal_frequency_line(net::Net) -> StringThe system frequency for the run header (run.log, the result print, the Web UI result page): "50 Hz (case file)" or "60 Hz (configuration)" when a capacitance was converted with it, otherwise "not used (no capacitance in farad)", followed by "; case file states 50 Hz" when the case file names a frequency all the same.
Sparlectra.nominal_frequency_source — Method
nominal_frequency_source(net::Net) -> StringWhere the system frequency of net came from, as the run metadata names it: "case_file" (the case file stated it, SCF meta.f_nom) or "configuration" (model.nominal_frequency_hz, or the nominal_frequency_hz argument of Net in a script) when a capacitance was converted with it, "not_used" when no capacitance in farad entered the model (susceptances in pu, or c1 = 0 on every line).
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.gencost_row_problem — Method
gencost_row_problem(row) -> Union{Nothing,String}What is wrong with one MATPOWER gencost row, or nothing for a valid one: MODEL is 1 (piecewise linear) or 2 (polynomial), NCOST is a non-negative integer (at least 2 points for model 1), the row holds the 2*NCOST (model
- or
NCOST(model 2) values after the four leading columns, and values
beyond them are zero padding.
Sparlectra.calcTransformerRXGB — Method
calcTransformerRXGB(Vn_kV, modelData) -> (rk, xk, gm, bm)The series resistance and reactance in ohm and the magnetizing conductance and susceptance in siemens of a winding from its nameplate data, referred to Vn_kV: z_k = v_k/100 * Vn^2/S_n, r_k = v_kr/100 * Vn^2/S_n (or from the short-circuit loss, r_k = P_k * Vn^2/S_n^2), x_k = sqrt(z_k^2 - r_k^2), g_m = P_fe/Vn^2, b_m = -sqrt((i_0/100 * S_n/Vn^2)^2 - g_m^2) (inductive, hence negative). P_k, P_fe in kW, Vn in kV, S_n in MVA; the unit factors are applied here. Without vkr_percent and pk_kW the winding is lossless (r_k = 0); without p0_kW or i0_percent there is no magnetizing branch. A no-load current too small for the iron loss (|Y_m| < g_m) leaves b_m = 0 with a warning naming the winding data.