State Estimation and Measurements Reference
Public API
Sparlectra.Measurement — Type
MeasurementGeneric state-estimation measurement model.
Fields:
typ: Measurement type.value: Measured value (Vm in p.u., powers in MW/MVar, Va in degrees).sigma: Standard deviation in measurement units.weight: Weight used in WLS (1/sigma^2).active: Iffalse, measurement is ignored by estimator.busIdx: Bus index for bus measurements.branchIdx: Branch index for branch flow measurements.direction: Branch direction:fromor:to, otherwise:none.linkIdx: Bus-link index for link flow measurements. On a closed link the row is a WLS row of the estimator: its flow is a function of the fused state (the nodal balance of the link cluster) plus, on a coupler ring, the estimated circulation; on an open link it is excluded.id: Optional measurement identifier.zero_injection: the row is a zero-injection row, set by the code that creates it (addZeroInjectionMeasurements!, thezero_injectionsource token of a measurement table, thezero_injectionkey of an SCF 1.2 measurement row, the ZI rows of a measurement CSV v1 or an SCF 1.0 case file, which carry no such field). Withstate_estimation.zero_injection = constraintsuch rows are equality constraints, and they are protected from bad-data elimination. The id alone never decides it: a measurement table uses the meter mRID as id.origin: where the value comes from, set by the code that creates the row.:measured(default) is a meter reading,:pseudoa substitute value (a measurement table row whosesourcecarries the tokenpseudo, for example a row ofgeneratePseudoMeasurementTable),:deriveda value computed from other measurements (deriveShuntPseudoMeasurements!),:pseudo_restorea replacement value ofrestore_observability,:last_valuethe last valid value of a meter standing in for a missing one (a measurement table row whosesourcecarries the tokenlast_value, seestate_estimation.last_value),:range_checkthe substitute of the voltage range check for an out-of-range U row on an energized bus. Rows with:derivedor:pseudo_restoreare protected from bad-data elimination like zero-injection rows; the others are not. A copy of a measurement keeps its origin. Any other value is an error.
Sparlectra.MeasurementType — Type
@enum MeasurementTypeSupported measurement types for the first WLS state-estimation implementation.
ImagMeas is a current-magnitude measurement in ampere, in two variants: the branch variant (branchIdx + direction) and the bus-referenced shunt-bay variant (busIdx only, SE phase 2) measuring the current of the shunt bay at that bus. Current magnitudes never carry observability: the observability checks exclude them, and the estimator gates them by iteration count and by the value >= 3 sigma rule (see runse!).
ShuntQMeas is the reactive power of a shunt bay in MVar (busIdx referenced, sign convention identical to the solved q_shunt results). It is the direct measurement that releases a shunt susceptance for estimation (SE phase 2, case A) and the carrier of the derived pseudo-measurements from the shunt back-calculation (case B, deriveShuntPseudoMeasurements!).
IaMeas is a PMU current-phasor ANGLE in degrees at a branch end (or the shunt bay, same variants as ImagMeas), referenced to the PMU time base: the common reference-angle offset alpha applies exactly as for VaMeas. A current angle is meaningless near zero current, so an IaMeas row is active only while the predicted current magnitude passes I >= 3 * sigma_I_ref (the paired ImagMeas sigma at the same end, else the config floor state_estimation.ia_current_floor_A); it shares the ImagMeas iteration gate and, like ImagMeas, never carries observability in this stage (a linear PMU-only estimation that would use current phasors for observability is future work).
Sparlectra.addCurrentPhasorMeasurement! — Method
addCurrentPhasorMeasurement!(measurements; net, i_A, ia_deg, sigmaI=10.0, sigmaIa=0.05, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, busName=nothing, active=true, idPrefix="PMU")Append a full PMU current phasor as the ImagMeas + IaMeas pair (mirror of addPmuPhasorMeasurement! for voltages). Returns (imag, ia).
Sparlectra.addIaMeasurement! — Method
addIaMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, busName=nothing, active=true, id="")Append a PMU current-phasor ANGLE measurement in degrees, PMU-referenced like VaMeas (the common reference-angle offset alpha applies). Same two location variants as addImagMeasurement! (branch end or shunt bay). The row is active in the solve only while the predicted current magnitude passes the floor gate (see IaMeas); like ImagMeas it never carries observability.
Sparlectra.addImagMeasurement! — Method
addImagMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, busName=nothing, active=true, id="")Append a current-magnitude measurement in ampere. Two variants:
- Branch current: identified by
branchNror a uniquefromBus/toBusbranch pair;directionselects the measured branch end (:from/:to). - Shunt-bay current (SE phase 2): identified by
busNamealone (mutually exclusive with the branch keywords); measures the current drawn by the shunt at that bus. Errors when the bus carries no shunt.
Current magnitudes are auxiliary measurements: they must only supplement power measurements, never replace them. The observability checks exclude them, and the estimator activates them only from the configured iteration on (state_estimation.imag_activation_iteration) and only when value >= 3 sigma holds.
Sparlectra.addMeasurement! — Method
addMeasurement!(measurements; typ, value, sigma, active=true, busIdx=nothing, branchIdx=nothing, direction=:none, id="", zero_injection=false, origin=:measured)Append a state-estimation measurement to measurements and return it. origin says where the value comes from (:measured, :pseudo, :derived, :pseudo_restore, :last_value, see Measurement).
Sparlectra.addMeasurementNoise! — Method
addMeasurementNoise!(net::Net; stddev, relativeSigma = true, sigmaFloor, rng, sigmas_from_rows = true) -> Vector{Measurement}Perturb the measurement values net already holds with Gaussian noise, in place, and return the perturbed rows.
This is the counterpart to generating a set: it needs no power flow and no truth state, because it works on the VALUES that are there. That matters for a set delivered with a case file, which is typically noise-free: an estimation on ideal values returns J = 0 by construction, and the only way to a realistic run used to be regenerating the whole set from a fresh solve.
Each row is drawn as value + sigma * randn(rng). sigmas_from_rows = true (the default) uses each row's OWN sigma, which is what the set already declares about its accuracy; with false the sigma comes from stddev (relative to the reading when relativeSigma, with the per-type floor). A row with a virtual sigma (a zero-injection constraint, sigma <= 1e-6) is never touched: it states a physical law, not a reading.
Sparlectra.addPflowMeasurement! — Method
addPflowMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, linkNr=nothing, active=true, id="")Append an active-power flow measurement identified by branchNr or a unique fromBus/toBus branch pair, or, with linkNr, on a bus link (SE phase 3): positive from link.fromBus to link.toBus, direction = :from only. On a closed link it is a WLS row of the estimator (normalized residual, bad-data elimination); calcLinkFlowsSE! gives the link flows after the estimate.
Sparlectra.addPinjMeasurement! — Method
addPinjMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append an active-power injection measurement identified by busName.
Sparlectra.addPmuPhasorMeasurement! — Method
addPmuPhasorMeasurement!(measurements; net, busName, vm_pu, va_deg, sigmaVm=0.002, sigmaVa=0.02, active=true, idPrefix="PMU")Append a complete PMU voltage-phasor measurement (magnitude and angle) for one bus and return the pair (vmMeas, vaMeas).
The magnitude enters as an ordinary VmMeas (p.u.); PMU accuracy is expressed solely through the tight default sigmaVm. The angle enters as a VaMeas (degrees, referenced to the common PMU time base; see the pmu_ref_offset handling in runse!).
Sparlectra.addQflowMeasurement! — Method
addQflowMeasurement!(measurements; net, value, sigma, direction=:from, branchNr=nothing, fromBus=nothing, toBus=nothing, linkNr=nothing, active=true, id="")Append a reactive-power flow measurement identified by branchNr or a unique fromBus/toBus branch pair, or, with linkNr, on a bus link (SE phase 3, see addPflowMeasurement! for the link conventions).
Sparlectra.addQinjMeasurement! — Method
addQinjMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a reactive-power injection measurement identified by busName.
Sparlectra.addShuntQMeasurement! — Method
addShuntQMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a shunt-bay reactive-power measurement in MVar for the shunts at busName: the sum over every in-service shunt at that bus (sign convention identical to the solved q_shunt results). Errors when the bus carries no shunt. This is the direct measurement that releases a shunt susceptance for estimation (SE phase 2, case A; see setShuntEstimation!).
Sparlectra.addVaMeasurement! — Method
addVaMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a bus voltage-angle measurement (PMU synchrophasor) identified by busName. value and sigma are in degrees, referenced to the common PMU time base (see the pmu_ref_offset handling in runse!).
Sparlectra.addVmMeasurement! — Method
addVmMeasurement!(measurements; net, busName, value, sigma, active=true, id="")Append a bus voltage-magnitude measurement identified by busName.
Sparlectra.addZeroInjectionMeasurements! — Method
addZeroInjectionMeasurements!(measurements; net, sigma=<state_estimation.zero_injection_sigma_mva>, busNames=nothing, busIdxs=nothing, active=true, idPrefix="ZI") -> Vector{Measurement}Append active- and reactive-power zero-injection pseudo-measurements for the selected buses and return the newly added measurements. sigma (MW, Mvar) defaults to the active state_estimation.zero_injection_sigma_mva (default ZERO_INJECTION_SIGMA).
Selection rules:
- If
busIdxsis provided, those indices are used. - Else if
busNamesis provided, names are resolved to indices. - Else passive buses are detected automatically via
findPassiveBuses(net).
The rows state P_inj = 0 and Q_inj = 0. With state_estimation.zero_injection = on the estimator weights them with 1/sigma^2, with constraint it solves them as equality constraints and sigma is not used.
Sparlectra.deriveShuntPseudoMeasurements! — Method
deriveShuntPseudoMeasurements!(net; sigmaFloor=nothing) -> Vector{Measurement}Shunt back-calculation (SE phase 2, case B): a measurement-preprocessing step that runs BEFORE runse! and derives a ShuntQMeas pseudo-measurement (id prefix SHDERIV, origin :derived) for every in-service shunt whose bay has
- an active shunt-bay current measurement (bus-referenced
ImagMeas), - NO active direct
ShuntQMeas(a direct measurement takes precedence, case A), and - an active
VmMeasat the bus. The voltage entersQ = -B V^2squared, so a measured voltage is a hard prerequisite; without one the shunt is skipped with a warning, never computed from nominal voltage.
Derivation per shunt: U_kV = vn_kV * vm_meas, S_MVA = sqrt(3) U_kV I_A / 1000, magnitude sqrt(max(S^2 - P^2, 0)) with the sign taken from the model susceptance (reactor versus capacitor, q_shunt convention).
Deliberate 0.10.0 restriction: no bay active-power measurement type exists, so the bay P is always taken as 0 and the propagated sigma is doubled to cover the neglected active part. For reactors and capacitor banks P is small against Q and the error is secondary; for filter circuits with a substantial active component the derived value is biased, use a direct ShuntQMeas (case A) there instead.
The sigma comes from first-order error propagation over sigma_I and sigma_Vm; sigmaFloor optionally sets a minimum sigma so the derived pseudo-measurement cannot outweigh real measurements. Returns the added measurements.
Sparlectra.findPassiveBuses — Method
findPassiveBuses(net; atol=1e-9, includeSlack=false) -> Vector{Int}Return bus indices that have no generation, no load, and no shunt contribution within the given tolerance atol.
This is useful for state-estimation workflows where passive / transit buses are often modeled through zero-injection pseudo-measurements.
Sparlectra.generateMeasurementsFromPF — Method
generateMeasurementsFromPF(net; kwargs...) -> Vector{Measurement}Generate synthetic measurements from the current solved network state. At a bus joined to others by a closed link the injection rows carry the bus's own solved generation minus load, the value a meter there reads, not the Y-bus injection, which includes the link flow.
Keyword options:
includeVm,includePinj,includeQinj,includePflow,includeQflowincludeImag: add branch current-magnitude measurements in ampere for both ends (defaultfalse; auxiliary only, seeaddImagMeasurement!)includeShuntQ: add shunt-bay reactive-power measurements in MVar, one per bus with an in-service shunt, summed over the shunts at that bus (defaultfalse; sign convention of theq_shuntresults)includeVa: add PMU voltage-angle measurements (degrees, defaultfalse)vaBusIdxs: restrict Va measurements to these bus indices (default: all buses)vaRefOffsetDeg: common angle offset added to all generated Va values, emulating a PMU time base that differs from the slack referencenoise: add Gaussian noise iftruestddev: dictionary fromMeasurementType => sigmarelativeSigma: interpret thestddevvalues as FRACTIONS of the true measured value (0.01= 1 percent of reading) instead of absolute units. This keeps one accuracy setting meaningful across voltage levels: 1 percent of a 400 MW flow and of a 4 MW flow both get a class-appropriate sigma, where an absolute 2 MW would be tight at 400 kV and absurd at 30 kV. Per rowsigma = max(fraction * |value|, sigmaFloor[type]); the floor guards near-zero readings (a zero flow must not get weight infinity).VaMeasstays absolute in degrees even in relative mode (an angle passes through zero, a fraction of it is meaningless).sigmaFloor: the per-type floors forrelativeSigma(defaultmeasurementSigmaFloors())rng: random number generatorresolution: round every generated value (after the noise) to a step per measurement type, as an online system delivers it, for exampleDict(VmMeas => 0.1, PflowMeas => 0.1). Steps in table units:VmMeasin kV, P types in MW, Q types (alsoShuntQMeas) in Mvar,ImagMeasin A,VaMeasandIaMeasin degrees. The sigma stays as computed: the rounding is part of the measurement error, and a step coarser than aboutsigma * sqrt(12)adds visible error.nothing(default) or a missing type keeps the value unrounded.
Sparlectra.measurementSigmaFloors — Method
measurementSigmaFloors(; kwargs...) -> Dict{MeasurementType,Float64}Per-type sigma floors for generateMeasurementsFromPF(relativeSigma = true): a relative sigma is max(fraction * |value|, floor), so a near-zero reading never gets a near-zero sigma (weight 1/sigma^2 would explode). Units are the measurement units: pu (vm), MW/MVar (pinj, qinj, pflow, qflow, shuntq), ampere (imag), degrees (va, also the absolute sigma in relative mode).
The power floors model the RANGE term of a transducer class (error = percent of reading plus a range contribution) and double as a numerical guard: a floor that is too small turns every zero-injection bus into a near-constraint and visibly slows the flat-start Gauss-Newton (MiniGrid: 32 iterations at 0.01 MW versus 11 at the 0.05 MW default).
Sparlectra.measurementStdDevs — Method
measurementStdDevs(; vm=0.005, pinj=1.0, qinj=1.0, pflow=1.0, qflow=1.0, va=0.02, imag=10.0, shuntq=1.0)Create default standard-deviation map for synthetic measurement generation. va is the PMU voltage-angle standard deviation in degrees; typical PMU accuracy is 0.01 to 0.05° (IEEE C37.118 TVE < 1 %). imag is the current-magnitude standard deviation in ampere; the 10 A default matches a class 1 instrument on a measuring range of a few hundred ampere (typical HV line current transformer). shuntq is the shunt-bay reactive-power standard deviation in MVar.
Sparlectra.setMeasurementsFromPF! — Method
setMeasurementsFromPF!(net; kwargs...)Replace the network's measurements with a set generated from its solved power flow (see generateMeasurementsFromPF).
Sparlectra.writeMeasurementsCSV — Method
writeMeasurementsCSV(net; file) -> NamedTupleWrite net.measurements as a measurement CSV v1 file:
# sparlectra-measurements v1
type,bus,from_bus,to_bus,link_nr,direction,value,sigma,active,idOne row per measurement; exactly one location group per row (bus for bus measurements including the shunt-bay ImagMeas, from_bus/to_bus plus branch_nr for branch measurements, link_nr for link flow measurements). Buses are written by NAME (matched whitespace-insensitively on read) or, with busReference = :mrid, by their preserved CGMES mRID (ENTSO-E UUID; name fallback where none is recorded; MATPOWER/DTF nets have no mRIDs and always use bus numbers/names). convertMeasurementsV1 resolves names, component ids/names, and mRIDs. Values use round-trip-exact Float64 formatting (UTF-8), so the converter reads back a bitwise-equal measurement vector. The reader readMeasurementsCSV! was removed in 0.50.0; the converter reads every v1 file. format (technical, excel_de, excel_us, default the active output.csv_format) sets the delimiter and the decimal separator like every other CSV a run writes; the numbers keep their shortest round-trip form in every format, and the reader tells the format from the header line. Returns (count = number of rows written,).
branch_nr carries the branch index and disambiguates parallel branches between the same bus pair (routine in CGMES nets); the reader verifies it against the named endpoints. Files written without the column (first-cut v1 header) are still read, with pair-based resolution that rejects parallels (same rule as addPflowMeasurement!). headerComments lines are written as # comments after the version line (free-form metadata, e.g. the transformer tap positions a generated set is based on); the reader skips them. footerComments lines are written as # comments AFTER the data rows (bulky per-row blocks such as the generator's truth values), so the file opens with its data; the reader skips comment lines wherever they stand. extraHeader/extraCells append diagnostic columns behind id; extraCells(i, m) returns the cells of the i-th measurement, and the converter ignores the extra columns.
Sparlectra.MeasurementKeyIndex — Type
MeasurementKeyIndexResolution of measurement-table keys to network locations: built from the mRIDs of a CGMES import (cgmesMeasurementKeys) or from the element names of any net (nameMeasurementKeys). With canonical = true (mRID keys) all keys are in canonical form (_measurement_key: no leading _, no urn:uuid:) and so is every key of a row before the lookup; with canonical = false (name keys) keys and row keys are compared as written, without surrounding whitespace.
terminals: terminal mRID toMeasurementTarget.nodes: TopologicalNode, ConnectivityNode or BusbarSection mRID (or the bus name) to bus index (0: the node exists but is not energized in the model;-n: the key namesnbuses, possible only for names).analogs: Analog mRID to(location, type, detail);locationis a terminal or node key,typeone of"P","Q","I","U"or""for a measurement type the table does not carry (named indetail).groups:(:injection | :shunt, bus)to the terminal keys of every modelled injection or shunt at that bus. A bus value is formed only when every member is measured.bus_kV: nominal voltage per bus index (kV), the base ofUrows.canonical:truefor mRID keys (the default of the five-argument constructor),falsefor name keys.
Sparlectra.MeasurementRow — Type
MeasurementRowOne row of a measurement table as read from the file. value is NaN and sigma is nothing when the cell was empty or not a number; problem is :none for a well-formed row, otherwise the reason the row cannot become a measurement (:field_count, :key_count, :unknown_type, :bad_value, :bad_sigma, :bad_valid, :bad_timestamp), with detail as text. line is the 1-based line number in the file. value_text and sigma_text keep the cells as written (empty for a row built in code); a U cell with more than 17 significant digits is divided by the nominal voltage from this text at 256 bits, so a kV value written by convertMeasurementsV1 gives back the pu value of the measurement CSV v1 bit for bit. The twelve-argument constructor leaves both empty.
Sparlectra.MeasurementSet — Type
MeasurementSetThe measurements of one timestamp of a measurement table, ready for runse!. sources maps each measurement id to the file lines it came from (an injection or shunt sum has several). counts holds :rows, :active and :inactive (measurements created active or inactive), :invalid_rows (resolved rows with valid=false), :merged (redundant values of one group member merged into one), :sigma_lifted (row sigmas read at the floor, the smaller of ZERO_INJECTION_SIGMA and the zero-injection sigma of the import), :zero_injection (rows applyMeasurementSet! added at passive buses, present once the set was applied) and one entry per problem; problems lists every row that did not become a measurement as (line, problem, detail). sigma_origin maps each measurement id to where its sigma came from: :row (the sigma cell of the row), :level (state_estimation.sigma_by_voltage_level) or :default (default_sigmas); a bus sum takes the weakest origin of its members (:default before :level before :row).
Sparlectra.MeasurementTableImport — Type
MeasurementTableImportResult of importMeasurementTable: one MeasurementSet per timestamp in file order of first appearance (an empty timestamp is a set of its own), plus rejected for rows that cannot be assigned to any set (wrong field count, malformed timestamp). last_value holds one entry per set that got last values (state_estimation.last_value): its timestamp, the number of filled values, the oldest timestamp they came from and the filled rows (source last_value;<timestamp of the original>, for writeMeasurementTable). last_value_note is empty, or says why the fill-in was skipped for the whole table.
Sparlectra.MeasurementTarget — Type
MeasurementTargetWhere a terminal mRID points in the network: kind is :branch (a branch end, branchIdx and direction set), :injection (a load, generator or equivalent injection; summed per bus), :shunt (a shunt bay; summed per bus) or :not_modelled (known to the model data but not part of the solved network: a switch, skipped or disconnected equipment, a de-energized node; detail names which). busIdx is the bus of the terminal, 0 when none.
Sparlectra.applyMeasurementSet! — Method
applyMeasurementSet!(net, set; replace = true, zero_injection = <state_estimation.zero_injection is not off>, zero_injection_sigma = <state_estimation.zero_injection_sigma_mva>) -> NetPut the measurements of set into net.measurements (replacing them by default), ready for runse!(net).
With zero_injection (default: the active state_estimation.zero_injection is on or constraint) every passive bus (no generation, load or shunt, not the slack, not isolated) that has no injection measurement in net.measurements afterwards gets a zero-injection pair ZI_PINJ_bus_<k> / ZI_QINJ_bus_<k> with sigma zero_injection_sigma (MW, Mvar), the rows the measurement generator writes for passive buses. The number of rows added is stored in set.counts[:zero_injection] and printed by measurementImportReport. With zero_injection = false no row is added. set.measurements itself is not changed.
Sparlectra.generateMeasurementTableFromPF — Method
generateMeasurementTableFromPF(net::Net; kwargs...) -> Vector{NamedTuple}Synthetic measurement table from the solved state of net (call runpf! first), keyed by element names (nameMeasurementKeys): U at the buses and P and Q at both ends of the branches, computed with the network model at the solved voltages. Works for every net, whatever format it came from; for a CGMES delivery keyed by mRID use generateMeasurementTableFromSV. Rows are sorted by key, so the output does not depend on element order.
Keywords:
timestamp = "": the timestamp column of every row.coverage = 1.0: share of the measurement locations that get a row, drawn separately for the energized buses (U) and the branch ends (P and Q together).1.0measures every location.include_injections = false: also write P and Q of every prosumer (power into the equipment: a load positive, a generator negative; the solved values ofdistributeBusResults!, computed on a copy ofnet) and Q of every shunt (power into the shunt), so the import forms the bus sums.sigma_pq_rel = 0.01,sigma_pq_floor = 0.1: sigma of P and Q asmax(sigma_pq_rel * |value|, sigma_pq_floor)in MW/MVAr.sigma_u_rel = 0.002: sigma of U relative to the reading (kV).sigma_pq_floorandsigma_u_relmust be positive,sigma_pq_relandbad_data_sigmasfinite and at least 0 (anArgumentErrorotherwise), so every row passes the reader.sigma_by_voltage_level(default: the activestate_estimation.sigma_by_voltage_level): where the level of the measuring bus (the bus of the node, of the branch end, of the prosumer or shunt) has a row with a column for the type, that sigma (max(absolute, rel_pct/100 * |value|), MW, MVAr, kV) replaces the three keywords above, for the written sigma and the noise alike.noise = true: add Gaussian noise with that sigma;falsewrites the model values unchanged.bad_data_fraction = 0.0: share of rows that get a gross error ofbad_data_sigmassigma (random sign) instead of the noise. They carrysource = "synthetic;bad_data", all otherssource = "synthetic".bad_data_sigmas = 20.0,seed = 1: size of the gross error and the seed of the random stream (coverage draw, noise, gross errors); equal arguments give equal rows.
Keys that nameMeasurementKeys marks :not_modelled (shared names, open branches) get no row. The rows have the fields of the table header and can be written with writeMeasurementTable.
Sparlectra.generatePseudoMeasurementTable — Method
generatePseudoMeasurementTable(net::Net, rows; sigma, sigma_q = sigma, timestamp = nothing, sigma_by_voltage_level = <configured>) -> Vector{NamedTuple}
generatePseudoMeasurementTable(result::CGMESImportResult, rows; sigma, sigma_q = sigma, timestamp = nothing, sigma_by_voltage_level = <configured>) -> Vector{NamedTuple}Pseudo measurements for the loads and generators that a measurement table does not observe. For every member of an injection bus sum (a load, generator, external grid, equivalent injection or SVC) without a P row in rows, a P row with its scheduled value is written; the same for Q. The scheduled values are the setpoints of the case (pVal, qVal of the prosumer; for a CGMES import the SSH values), as power into the equipment like every table row. A unit without a Q setpoint gets no Q row.
net::Net: keys are element names (nameMeasurementKeys).result::CGMESImportResult: keys are terminal mRIDs (cgmesMeasurementKeys).
rows are the rows of the table (readMeasurementTable or a generator). A row observes a member when it is well formed and carries that terminal key (or an Analog on that terminal) with the same type, valid=false included. Members are filled one by one, so a bus whose sum was partial becomes complete and its real rows are kept.
Keywords:
sigma: sigma of theProws in MW, required, finite and positive (otherwise anArgumentError). Choose it large against the real meters so they win.sigma_q = sigma: sigma of theQrows in MVAr, same check.timestamp = nothing: write rows for every timestamp ofrows(an empty table gives one set with an empty timestamp); a string writes only that timestamp.sigma_by_voltage_level(default: the activestate_estimation.sigma_by_voltage_level): where the level of the bus has a row with ap_mw(q_mvar) column, that sigma (max(absolute, rel_pct/100 * |value|)) replacessigma(sigma_q). Those are the sigmas of the meters at that level; passSESigmaLevel[]to keep the larger pseudo sigmas.
The rows carry source = "pseudo;ssh" and valid = true. Append them to the table (vcat(rows, pseudo) or one writeMeasurementTable call); the import treats them like any other row and adds them to the bus sums. Shunts get no pseudo rows. A member whose name key is shared by several elements, or that has no name, cannot be addressed by a row; such members are named in a warning.
Sparlectra.importMeasurementTable — Method
importMeasurementTable(rows, index; default_sigmas = measurementStdDevs(), sigma_by_voltage_level = <state_estimation.sigma_by_voltage_level>, zero_injection_sigma = <state_estimation.zero_injection_sigma_mva>, last_value = <state_estimation.last_value>) -> MeasurementTableImportTurn the rows of a measurement table into one MeasurementSet per timestamp, resolving every key through index (MeasurementKeyIndex).
Mapping:
- terminal of a branch end:
P,Q,I,IabecomePflowMeas,QflowMeas,ImagMeas,IaMeas(current angle in degrees) at that end. Sign: positive into the equipment at that terminal (the CGMESSvPowerFlowconvention), which is the Sparlectra flow direction from the bus into the branch. - terminals of injections at one bus: the
P(orQ) values of ALL modelled injections at the bus are summed into onePinjMeas(QinjMeas) with the sign turned (network injection = minus the power into the equipment) andsigma = sqrt(sum sigma^2). When every member has a value but not every member a valid one, the sum is created inactive. When a member has no row at all, the rows of the sum are counted as:partial_injection. Several values of one member (redundant Analogs) are first merged to their inverse-variance mean (counted as:merged). - terminals of shunts at one bus:
Qsummed the same way into oneShuntQMeas(power into the shunt, theq_shuntconvention);I(A) becomes the bus-referenced bay currentImagMeaswhen the bus has one shunt (with several, the rows are:unsupported: the bay current is not the sum of the magnitudes).Pat a shunt,Iat an injection andIaat an injection or shunt are counted:unsupported. - node (TopologicalNode, ConnectivityNode, BusbarSection) with
Uin kV:VmMeasin pu of the bus nominal voltage; sigma likewise. - node with
PorQ: the bus balance,PinjMeasorQinjMeaswith the value as it is (MW, MVAr, injection positive: generation minus load at the bus). It stands next to a sum of prosumer rows at the same bus; both enter the set as redundant measurements. A balance row whosesourcecarries the tokenzero_injection(;-separated) is a zero-injection constraint and gets the idZI_PINJ_bus_<k>/ZI_QINJ_bus_<k>ofaddZeroInjectionMeasurements!, so it is protected like one. - node with
Va:VaMeasin degrees. measurement_mrid: type and location from the Analog inindex.- with a name index (
nameMeasurementKeys) the key columns hold names: the bus name innode_mrid,<branch name>:from/:to, the prosumer or shunt name interminal_mrid; the mapping above is the same.
Several keys at one location (two Analogs on one terminal, U at every busbar section of one node) are redundant measurements and all enter the set; only the same key with the same type twice is a :duplicate.
A row whose source carries the token pseudo (;-separated, as generatePseudoMeasurementTable writes pseudo;ssh) becomes a measurement with origin :pseudo, every other row one with origin :measured (see Measurement). A group sum is :pseudo when one of the rows it uses is.
The sigma of a row, in this order: the sigma cell of the row; else the row of sigma_by_voltage_level (default: the active state_estimation.sigma_by_voltage_level) for the nominal voltage of the measuring bus, the bus of the node, of the branch end or of the bus sum (P, Q in MW/MVAr, I in A, U in kV turned into pu of that bus, max(absolute, rel_pct/100 * |value|)); else default_sigmas of the measurement type (pu for VmMeas). set.sigma_origin records which of the three it was. A sigma below the floor, the smaller of ZERO_INJECTION_SIGMA and zero_injection_sigma (default: the active state_estimation.zero_injection_sigma_mva), in the unit of the measurement (pu for VmMeas) is read at the floor and counted as :sigma_lifted, as the measurement CSV v1 reader does. Rows with valid=false become inactive measurements and make a group sum inactive when their member has no valid row; next to a valid row of the same member they are not used and counted as :invalid_unused, also in an inactive sum. Every other row that does not become a measurement is counted by reason: :unknown_key, :not_modelled, :unsupported, :partial_injection, :duplicate, plus the format problems of readMeasurementTable. Nothing is dropped silently.
Last valid value (last_value, a LastValueConfig, default the active state_estimation.last_value, off by default): with enabled and more than one set, the sets are filled in time order. When a key with its type has no valid measured row at a timestamp (no row, only valid=false rows or only pseudo rows), the latest valid measured row of that key and type from an earlier timestamp stands in, if it is at most max_age_min minutes older. The filled row carries the value of the original, its sigma (the sigma the import gave it, in the unit of the table) times sigma_factor, valid=true, the source last_value;<timestamp of the original> (origin :last_value) and the line of the original; it takes the place of the rows it replaces, which are counted :last_value_replaced. A filled value and a zero-injection row are never the original of another one, so an age counts from the reading. The count per set is :last_value in counts, the oldest timestamp used in last_value of the result. When a set has no timestamp that reads as a time, nothing is filled, with one warning and the reason in last_value_note.
Sparlectra.isMeasurementTable — Method
isMeasurementTable(file) -> Booltrue when file carries a measurement-table version line (# sparlectra-measurement-table <version>) among the # lines before its first other line, and that line is the measurement-table header. Decides by content, not by file name. A table of another version counts, so the reader can name the version it refuses; the measurement CSV v1 does not.
Sparlectra.measurementImportReport — Method
measurementImportReport(imp) -> StringPlain-text report of a MeasurementTableImport: per set the row count, the active and inactive measurements, the zero-injection rows added by applyMeasurementSet! (for a set that was applied), the count per problem and the last values with the oldest timestamp they came from, followed by the rejected rows and the reason a fill-in of last values was skipped. Every problem row is listed with its line.
Sparlectra.nameMeasurementKeys — Method
nameMeasurementKeys(net::Net) -> MeasurementKeyIndexThe key index of a net without CGMES identities (MATPOWER, SCF, DTF, PowSyBl, a net built in code) for importMeasurementTable. The table keeps its header; its key columns hold element names:
node_mrid: the bus name. A bus that is not energized resolves to bus 0; a bus that only closed links join to a fed bus counts as energized.terminal_mrid:<branch name>:fromor<branch name>:tofor a branch end, the prosumer name for a load or generator (member of the injection sum at its bus), the shunt name for a shunt (member of the shunt sum).- A branch name that several branches share (parallel lines) is qualified with the branch number,
<branch name>#<k>:from,kbeing the position innet.branchVec(thebranch_nrof the measurement CSV v1). A prosumer or shunt name that several of them share is qualified with its bus,<name>@<bus name>; when several at one bus share that as well, with their order at the bus,<name>@<bus name>#<k>(prosumers first, then shunts, each in model order). Both#<k>forms depend on the element order of the import and are not stable across imports; unique names are. A key that is still not unique resolves to:not_modelledwith the reason, as do branches that are not closed at both ends, shunts out of service and elements at a bus that is not energized. - Every prosumer and in-service shunt at an energized bus is a member of the sum at its bus (
groups), whatever its key; a member without a row leaves the sum partial. That includes an element without a name: it has no key, so its bus sum is always partial. measurement_mriddoes not apply (the index has no Analogs); a row with it is reported as:unknown_key.- A bus link has the keys
<link name>:fromand<link name>:to; P and Q rows on them are link flow measurements (positive from the link's from bus to its to bus), WLS rows of the estimator;calcLinkFlowsSE!gives the link flows after the estimate. An open link resolves to:not_modelled, and a branch or prosumer that already holds the key keeps it.
Names are compared as written, without surrounding whitespace; the mRID canonical form (no leading _, no urn:uuid:) does not apply, so _B9 and B9 are two keys. Bus names that still give one key (B7 and B7) make that key ambiguous: a U row on it is reported as :not_modelled.
Sparlectra.readMeasurementTable! — Method
readMeasurementTable!(net; file, index = nameMeasurementKeys(net), timestamp = nothing, replace = true, zero_injection = <state_estimation.zero_injection is not off>, zero_injection_sigma = <state_estimation.zero_injection_sigma_mva>, last_value = <state_estimation.last_value>) -> MeasurementSetRead a measurement table into net.measurements: readMeasurementTable, then importMeasurementTable with index (element names by default; for a CGMES case cgmesMeasurementKeys(result)), then applyMeasurementSet! of the set with timestamp (the first set when nothing). last_value is passed to the import (last valid values for missing ones, see importMeasurementTable). Returns that set; rows that did not become a measurement are in its problems and in measurementImportReport. Throws ArgumentError when the file is no table the reader accepts, when no row can be assigned to a set, or when the table has no set with timestamp.
Sparlectra.readMeasurementTable — Method
readMeasurementTable(file) -> Vector{MeasurementRow}Read a measurement table: CSV, UTF-8, comma separated, decimal point, LF line ends. Before the header stands the version line # sparlectra-measurement-table v1, then the header timestamp,measurement_mrid,terminal_mrid,node_mrid,type,value,sigma,source,valid. Other lines starting with # before the header are comments, blank lines are skipped. A file without the header, without the version line or with another version is rejected with an ArgumentError that names what was expected. Rows that break a rule of the format are returned with their problem set, never dropped, so the import report can count them.
Sparlectra.writeMeasurementTable — Method
writeMeasurementTable(file, rows; comments = String[])Write rows (a vector of MeasurementRow or of NamedTuples with the header fields) as a measurement table: the version line # sparlectra-measurement-table v1 first, then comments as # lines, then the header. Numbers use the shortest round-trip form, sigma = nothing an empty cell. A MeasurementRow read from a file keeps the number text it was read with, and a number given as a string is written as it is (checked to be a number, ArgumentError otherwise); the converter uses that for U values longer than a Float64 prints. Text cells are written without surrounding blanks, as the reader reads them; one with a comma or a double quote is quoted (RFC 4180); a cell or comment with a line break throws an ArgumentError before the file is written, since the table has one row per line.
Sparlectra.convertMeasurementsV1 — Method
convertMeasurementsV1(v1_file, net; out, index = nameMeasurementKeys(net)) -> NamedTupleWrite the measurement table of a measurement CSV v1 file. net is the case the v1 file belongs to (the v1 file addresses buses and branches by name and number, the table by the keys of index); for a CGMES case pass index = cgmesMeasurementKeys(result) so the table carries mRIDs, as the SE service reads it.
Every v1 row becomes one table row with the same measurement:
VmMeasat a bus:Uat a node key of the bus in kV, value and sigma written so that the import divides them back to the v1 pu values bit for bit (up to 18 digits where a Float64 kV value cannot).VaMeas,PinjMeas,QinjMeasat a bus:Va,P,Qat the node (degrees, bus balance in MW and MVAr, injection positive). A row at an isolated bus is written with the key of that bus; the import reports it asnot_modelled, as the SE service leaves such a v1 row out.PflowMeas,QflowMeas,ImagMeas,IaMeasat a branch end:P,Q,I,Iaat the terminal key of that end.ShuntQMeasand the bayImagMeasat a bus:QandIat the terminal of the one shunt of that bus.- zero-injection rows (id prefix
ZI):source = converted;v1;zero_injection, their sigma kept; every other rowsource = converted;v1.validis theactiveflag of the row.
No unit is converted except U: P and Q stay in MW and MVAr, I in A, angles in degrees. Rows the table cannot carry (a link flow, a shunt bay at a bus with several shunts, a current angle at a shunt bay, a location without a key, a negative U or I, a second row with the same key and type) are not written; they are listed in the result and as comment lines of the table, never dropped silently. The comments of the v1 file are carried over in front of the header, with the row ids in truth_value and critical-row lines rewritten to the ids the import gives, so the SE service still writes se_deltas.csv and reads the tap table.
Returns (file, rows, problems, ids, report): the written path, the number of table rows, the rows not converted as (line, id, problem, detail), the v1 id to table id map and a plain-text report. A file the v1 parse refuses (version line, header, a row) throws an error naming file and line. The v1 reader readMeasurementsCSV! was removed in 0.50.0; this converter still reads every v1 file.
Sparlectra.SEResult — Type
SEResultResult container for the first classical WLS state-estimation run.
voltages are the estimated bus voltages in the angle reference of the model: the slack keeps its stored angle (for example the SV angle of a CGMES import), although the estimate itself runs with the slack at 0.
vaRefOffsetDeg is the estimated common PMU reference-angle offset α in degrees, the angle of the PMU time base against the model angle reference (near 0 when the PMU angles are in the model reference). It is nothing when no offset state was part of the estimation, i.e. when there are no active VaMeas measurements or pmu_ref_offset = :off.
shuntEstimates (SE phase 2, case A) carries one row per shunt released via setShuntEstimation!: (busIdx, busName, B_model, B_est, delta, frozen), susceptances in pu. Frozen rows (no direct measurement, or B column not observable) keep B_est = B_model. nothing when no shunt is released. Each estimated B consumes one degree of freedom (it counts as a state in ν = m − n).
robustRows (SE phase 4, robust = true) lists every measurement that left stage 0 of the two-stage R modification in the FINAL iteration: (measurement_index, id, stage, t, sigma_factor) with t = |z - h|/sigma (original sigma) and sigma_factor = sigma_mod/sigma. nothing when the robust mode is off. The modification changes only the solve weights; objectiveJ, the residuals, and every diagnostic statistic stay on the original sigmas.
linkCirculations holds the estimated circulation states of coupler rings whose links carry flow measurements (MW for P, Mvar for Q); each counts as a state in ν. nothing when there are none, and always on a net with more than one AC island (the islands estimate their circulations, the merged result does not carry them; calcLinkFlowsSE! adds them to the link flows).
conditioning describes the linear system of the last Gauss-Newton step: (zero_injection, matrix, scaling, condition_number, method). zero_injection is the mode of the run (:on, :off, :constraint), matrix is :gain (the gain matrix G = H' W H with the zero-injection rows weighted) or :kkt (the scaled KKT matrix of zero_injection = constraint). The condition number is taken of the Jacobi-scaled matrix D^-1/2 M D^-1/2, D its diagonal (scaling = :jacobi; a KKT constraint row, which has no diagonal, is scaled to a largest entry of 1), so the units of the states (rad, pu, and MW or Mvar for the circulation states of coupler rings) do not enter it. It is the 1-norm estimate of condestJacobian on that sparse matrix (method = :hager_1norm, one extra sparse LU), Inf when the matrix is singular. On a net with several AC islands it is the largest island value. J and the degrees of freedom are objectiveJ and dof.
zeroInjectionMultipliers lists, under zero_injection = constraint, the Lagrange multipliers of the constraint rows at the last step, one entry per bus: (bus, kind, lambda_p, lambda_q) with the bus name, kind :zero_injection for a passive bus or :link_aggregate for the fused bus of a closed-link cluster whose members are all passive (its LINKAGG rows), and the multipliers in 1/MW and 1/Mvar (NaN where the bus has no row of that kind). A multiplier is the pull of the measurements against the balance: the measurement part of the gradient, H_M' W r_M = C' lambda. A large value points at a measurement error near the bus. nothing under on and off; on a multi-island net the rows of all islands.
start names the start of the result run: :flat (flatstart = true), :stored (flatstart = false, the voltages stored in the net) or :stored_after_flat: the run from the flat start did not converge and the start ladder (state_estimation.start_ladder, default on) solved once more from the stored voltages; converged says whether that second try converged.
weakObservability is the weak class at the estimated state (see evaluate_weak_observability): under on_unobservable = abort after a converged run with update_net while state_estimation.observability.weak_check_after_estimation is on, under observable_islands and scheduled after every converged run; else nothing. A report with affected buses marks the estimate unusable (the SE service sets se_result_usable = false and leaves the flows of its branches empty).
observableIslands is set when runse! estimated the observable islands one by one (state_estimation.observability.on_unobservable = observable_islands or scheduled on a set that is not observable, or whose weak buses at the estimate were cut out), else nothing. Then islands has one row per observable island instead of one per network island, with the fields of the network-island rows plus label ("k.j"), network_island, buses, reference_bus, relative_angles and rank_deficit, and reason :estimated, :no_measurements or :not_observable (not of full rank, see runse!). The labels of one network island k run k.1, k.2, ... over its estimation units ("k" for a network island that is one unit and lost no bus). The field itself holds per bus label_of_bus ("" for a bus in no estimated island), estimated and relative_angle, then unobservable_branches (the branches whose flows stay empty) with unobservable_branch_names ("from - to"), dropped_measurements (ids of the rows no observable island uses), removed_buses (the buses taken out before the islands were cut, as (bus, reason): :dark_magnitude for a dark magnitude, :weak for an affected bus of the weak class at the estimate) and report, the ObservableIslands the partition came from.
restoredRows lists, under on_unobservable = scheduled, the replacement values runse! took from the schedule (see restore_observability): (id, bus, bus_name, network_island, quantity, value, sigma, source); an empty vector when none was taken, nothing under the other values.
Sparlectra.evaluate_global_observability — Method
evaluate_global_observability(net, measurements; tol=nothing, observable_islands=true, dense_max_n=2000) -> NamedTupleEvaluate global observability on active measurements using the finite-difference measurement Jacobian.
Includes global redundancy metrics
redundancy = r = m - nredundancy_ratio = ρ = m / ndof = ν = m - n(a COUNT difference: for an observable set it equalsm - rank(H); for an unobservable set it can be negative and then reads as a shortfall, not a redundancy)
Quality classes:
:good: observable and no critical single measurement:critical: observable, but at least one single critical measurement (or ν <= 0):weakly_observable: no null direction in the decoupled models, but a branch flow or magnitude above the weak bounds (below), provisional before the estimation:not_observable: a null direction in the decoupled P-theta or Q-V model
Not observable (concept K2, G4'): the active rows form two decoupled linear models. The P-theta model takes the P injections, P flows and PMU angles against the bus angles (without the slack), the P circulation states of coupler rings and the PMU offset; the Q-V model the Q injections, Q flows and Vm rows against the bus magnitudes and the Q circulation states. Entries are 1/x of the DC power flow, columns normalized, the rank tolerance exact (eps * max(m, n) * sigmamax). `anglerankdeficitandmagnituderankdeficitare their deficits,rankdeficittheir sum,anglesvkeptminandanglesvdroppedmaxthe gap at the P-theta rank cut.numericalobservableis true when neither model has a null direction.numericalrank` stays the rank of the AC Jacobian; the AC model decides the weak class only.
Weakly observable (concept K3, G2, U4): in the covariance of the estimate (G = H' W H of the weighted AC Jacobian, physical units, W = 1/sigma^2) the standard deviation of an active branch flow exceeds state_estimation.observability.weak_flow_sigma_mw (MW) or the one of a voltage magnitude exceeds weak_vm_sigma_pu (pu), see evaluate_weak_observability. Before the estimation the class is provisional, taken at the voltages stored in the net with the same covariance as after it; on a net that stores the flat profile, and for a not-observable set, it is not determined. weakly_observable is true for this class only; weak_observability carries the basis (:stored_state or :not_determined), the branches above the flow bound (with their flow standard deviation in MW) and their count, the affected buses and their count, the largest flow and magnitude standard deviation and one row per network island.
For a not-observable set the result additionally names the dark states in unobservable_state_columns: the angle columns touched by the null space of the P-theta model and the magnitude columns touched by the null space of the Q-V model; empty when observable. This is the rigorous per-state answer that the column-restricted local check cannot give (see evaluate_local_observability). Up to dense_max_n rows or columns the null spaces come from the SVD, above from the gain-matrix iteration (see evaluate_observability_matrix); both paths give the same classification.
observable_islands holds the ObservableIslands of a not-observable set (see identify_observable_islands); it is the empty report for an observable set and for observable_islands = false.
Network islands (topologically separate parts with their own reference, closed links joined) are judged one by one on their own subnet, the way the estimator solves them; islands holds one row per network island. A network island is no gap: it adds nothing to a deficit, and one without measurements is reported as not measured (n_unmeasured_islands) and does not enter the verdict.
Current measurements (ImagMeas, IaMeas) are excluded before the Jacobian is built: they must never carry observability, so the verdict states whether the system is observable from the power and voltage measurements alone. The voltage range check of runse! applies (a row on a de-energized bus is inactive, an out-of-range row on an energized bus is replaced).
The AC Jacobian is built by forward differences, so its error floor is O(jacEps), not machine epsilon. With tol = nothing the rank tolerance of numerical_rank is state_estimation.rank_tol_factor * jacEps * sigma_max (factor default 10.0); an explicitly passed tol wins.
Sparlectra.evaluate_local_observability — Method
evaluate_local_observability(net, measurements, stateCols; kwargs...) -> NamedTupleEvaluate local observability on selected Jacobian columns (stateCols).
Procedure:
- Build global Jacobian
Hfrom currently active measurements. - Keep only rows that have at least one nonzero entry in the selected columns. These rows correspond to measurements that are locally sensitive to the requested states.
- Evaluate observability/redundancy on the reduced matrix
Hlocal.
Returned NamedTuple extends global metrics with:
rows: selected row indices (within global active-Jacobian row numbering)stateCols: copied input state-column selection.
Interpretation:
:goodmeans local states are observable with positive redundancy and no single critical measurement.:criticalmeans still observable but vulnerable to a single outage (or ν <= 0).:not_observablemeans local states cannot be uniquely reconstructed.
Limitation: this column-restricted test is NECESSARY but not sufficient; a positive verdict can be wrong when the touching rows couple the selected states to neighbor states that are themselves undetermined. The rigorous per-state answer is unobservable_state_columns from evaluate_global_observability.
Like the global check, current-magnitude measurements (ImagMeas) are excluded before the Jacobian is built (currents must never carry observability), and with tol = nothing the rank tolerance is FD-aware (rank_tol_factor * jacEps * sigma_max of the local submatrix; see evaluate_global_observability). The structural island stage is deliberately global-only: a column selection inside ONE island is perfectly observable even when the net contains further measured islands.
Sparlectra.evaluate_local_observability_matrix — Method
evaluate_local_observability_matrix(H, stateCols; tol=nothing) -> NamedTupleEvaluate local observability on a matrix H restricted to selected stateCols.
Limitation: this column-restricted submatrix test is NECESSARY but not sufficient; a positive verdict can be wrong when the touching rows couple the selected states to neighbor states that are themselves undetermined (the rigorous per-state answer is unobservable_state_columns from the global check).
Sparlectra.evaluate_observability_matrix — Method
evaluate_observability_matrix(H; tol=nothing, criticality_method=state_estimation_config().criticality_method, rank_method=state_estimation_config().rank_method, dense_max_n=2000) -> NamedTupleEvaluate global observability and single-row criticality directly on a matrix H (without building a network model).
The result includes unobservable_state_columns::Vector{Int}: for a numerically NOT observable H, the state columns with a component above tolerance in the null space, i.e. exactly the states no measurement pins down. Empty for observable systems; computed only on the not-observable path. Up to dense_max_n rows or columns (and for every dense H) the null space comes from the SVD. Above it, for a sparse H, the null space and the deficit come from a subspace inverse iteration on the gain matrix H' H (one Cholesky factorization, orthonormal null vectors), because the column test of the sparse QR is not rank revealing and undercounts the deficit. On both paths a state counts as dark when its row of the orthonormal null basis exceeds a tolerance coupled to the rank tolerance (tol / sigma_max, at least 1e-8). numerical_rank of a not-observable sparse H is then the rank of the iteration, which can be lower than numeric_rank and agrees with the SVD count. Whether H is observable is still the verdict of the sparse QR: an H it finds of full rank is not checked (an observable set costs nothing extra), so a hidden near-singular direction there stays undetected. dense_max_n exists so tests can take the sparse path on small matrices.
Sparlectra.evaluate_weak_observability — Method
evaluate_weak_observability(net, measurements; dense_max_n=2000) -> NamedTuple
evaluate_weak_observability(net; kwargs...) -> NamedTupleThe weak class of the active measurements (concept K3, G2) at the voltages stored in net. After runse! with state_estimation.update_net these are the estimated voltages, and the result is the final weak class of the estimate (what runse! reports in weakObservability); before an estimation it is the provisional class at the stored state (what evaluate_global_observability reports).
The class comes from the covariance of the estimate at that state: G = H' W H of the active rows (physical units, W = 1/sigma^2, the weights of the WLS), its inverse as a sparse selected inverse (Takahashi). Per in-service branch the standard deviation of the active power flow at its from end is sqrt(g G^-1 g') in MW, g the gradient of that flow; per bus the one of the voltage magnitude is the root of the diagonal entry in pu. With state_estimation.zero_injection = constraint the covariance is the one of the constrained estimate, from the KKT matrix of the constraint rows. The set is weakly observable when a branch flow exceeds state_estimation.observability.weak_flow_sigma_mw (MW) or a magnitude exceeds weak_vm_sigma_pu (pu). Where the gain matrix is singular there is no covariance; then the singular directions of W^(1/2) H decide, a null direction counting as weak as soon as it moves a flow or a magnitude (method = :directions in the rows). Each network island is judged on its own subnet, as the estimator solves it; current rows carry no observability, and the range check of runse! applies to the voltage rows.
Returns (weakly_observable, basis, n_branches, n_buses, buses, branches, branch_flow_sigma_mw, max_flow_sigma_mw, max_vm_sigma_pu, pattern_misses, network_islands): basis is :stored_state, or :not_determined when the net stores the flat profile (every |V| 1 pu, every angle at the slack angle), where nothing is computed. branches are the branches whose flow standard deviation exceeds the bound (with that value in MW in branch_flow_sigma_mw), buses the affected buses: the ends of those branches and the buses whose magnitude standard deviation exceeds its bound. max_flow_sigma_mw and max_vm_sigma_pu are the largest values over all branches and buses. pattern_misses counts the flows whose covariance entries were outside the pattern of the selected inverse and took a direct solve. network_islands has one row per measured network island (network_island, basis, method, n_branches, n_buses, buses, branches). Errors like evaluate_global_observability when no active measurement is left.
Sparlectra.identify_observable_islands — Method
identify_observable_islands(net, measurements; tol=nothing, dense_max_n=2000, max_passes=typemax(Int)) -> ObservableIslands
identify_observable_islands(net; kwargs...) -> ObservableIslandsObservable islands of the active measurements on net: per network island the maximal connected parts whose states are fixed once one of their buses is taken as the angle reference. Returns an ObservableIslands report (observable island per bus with its label "k.j", unobservable branches, deficits, removed boundary injections, region and dark magnitudes, one row per network island).
Method (numerical, Monticelli and Wu 1985), on the measurement set of evaluate_global_observability (closed links fused, current rows excluded), on each network island:
- The decoupled linear P-theta model: P injections, P flows and PMU angles against the bus angles, with the magnitudes taken as known (P circulation states of coupler rings and the PMU offset stay unknowns), entries 1/x, exact rank tolerance. The two ends of an in-service branch belong to one group when their rows of the orthonormal null basis, taken as angle shifts, agree; a branch between two groups is unobservable.
- P injections at the end buses of an unobservable branch (boundary injections) and P link-flow rows whose balance contains its flow tie the undetermined flow to flows inside the groups, so they are dropped and the model decomposed again, until no new unobservable branch appears. The observable islands are the connected parts over the branches not found unobservable.
- The region is the set of buses with a share in the null space of the P-theta model of the set before step 2 (the dark angles); it is reported next to the islands.
- Dark magnitudes and the magnitude deficit come from the decoupled Q-V model (Q injections, Q flows and Vm rows against the magnitudes).
The report gives the deficits angle_rank_deficit of the P-theta model, magnitude_rank_deficit of the Q-V model and rank_deficit, their sum (the number of replacement values a restoration needs), per network island and summed.
Up to dense_max_n rows or columns the null spaces come from the SVD, above from the gain-matrix iteration (see evaluate_observability_matrix); dense_max_n exists so tests can take the sparse path on small networks. max_passes = 1 stops after the first decomposition (the plain null-space pass, for diagnostics). An observable set gives one observable island per measured network island and removes nothing. Errors like evaluate_global_observability when no active measurement is left.
Sparlectra.measurement_jacobian — Method
measurement_jacobian(net; flatstart=true, jacEps=1e-6, pmuRefOffset=...) -> NamedTupleBuild the measurement Jacobian H of the ACTIVE measurements on net, labeled for humans: the matrix the observability checks and the WLS normal equations run on, with one described row per measurement and one described column per state.
Returns (H, rows, cols):
H::Matrix{Float64}: m x n finite-difference Jacobian at the flat (or stored) start state, the same evaluationevaluate_global_observabilityuses.rows: one NamedTuple per active measurement,(index, type, location, sigma);indexis the position innet.measurements,locationnames the bus (injections, voltages), the oriented branch (flows) or the link ("link <k>", link flow measurements, which are WLS rows of their own).cols: state-column labels in Jacobian order,"Va(bus)"for every non-slack bus, then"Vm(bus)"for every bus, then"circP(j)"and"circQ(j)"for the circulation states of measured coupler rings, plus"alpha"when PMUVameasurements activate the reference-offset state.
Errors when no active measurement exists. Intended for measurement-matrix reports and placement studies; see the state-estimation suite summary and the workshop's observability deep dive.
Sparlectra.numeric_rank — Method
numeric_rank(A; tol=nothing, dense_max_n=2000) -> IntCompute the numerical matrix rank: the number of singular values above tol for a dense matrix and for a sparse one up to dense_max_n rows or columns, the rank of the sparse QR factorization (SPQR, column tolerance tol) above. dense_max_n exists so tests can run the sparse path on small networks; the default is the measured crossover.
Sparlectra.numerical_observable — Method
numerical_observable(H; tol=nothing) -> BoolNumerical observability test on a Jacobian-like matrix H. Returns true when rank(H) == n (full column rank).
Sparlectra.numerical_row_redundant — Method
numerical_row_redundant(H, i; tol=nothing) -> BoolCheck if row i remains numerically redundant in H.
Sparlectra.print_observable_islands — Method
print_observable_islands([io,] result; max_names = 5)Print the observable islands of result, an ObservableIslands or the result of evaluate_global_observability, per network island: its deficits (full, angles, magnitudes), each observable island with more than one bus with its label "k.j", bus count and first max_names bus names, the number of single-bus observable islands, the region, the unobservable branches (the first max_names) and the dark magnitudes. A network island without measurements prints as not measured. The removed boundary rows close the printout; the full lists stay in the report. An empty report prints one line.
For an SEResult of runse! that estimated the observable islands one by one it prints one line per island: its buses, reference (marked when the angles are relative), J and dof, or why it was not estimated; then the unobservable branches and the measurements no island used.
Sparlectra.print_se_diagnostics — Method
print_se_diagnostics(io, diag; topN=10)Pretty-print diagnostics from validate_measurements or runse_diagnostics including:
- explanation of
global_consistency - tabular measurement ranking
- marker per measurement:
BADfor a row the sequential elimination removed,over kfor a row above the threshold that stayed (smearing of a gross error elsewhere),OK, orconstraint - optional rerun comparison if present
Sparlectra.print_se_view — Method
print_se_view(view; io=stdout, format=:plain)Pretty-print an se_view report (format = :plain or :markdown).
Sparlectra.readSEStateCSV! — Method
readSEStateCSV!(net; file) -> NamedTupleRead an SE state CSV (see writeSEStateCSV, versions 1 and 2) written for the SAME case, write the estimated voltages into net, and register the state so runpf_from_se! can start from it. Buses are matched by name; a bus missing from the file or an unknown bus name aborts with a line-precise error.
A file of an estimate of the observable islands one by one (version 2 with an observable_island label or a bus with estimated = false) is read back as such: a bus not estimated gets NaN voltages, and a closed branch with an end not estimated or with its ends in two observable islands is not estimated either, its flows and losses are set to NaN (its flow follows from no measurement). One warning gives both counts. The state is registered as partial, so runpf_from_se! refuses it exactly like the in-memory estimate. Returns (count, not_estimated_buses, not_estimated_branches, partial).
Sparlectra.restore_observability — Method
restore_observability(net, measurements; dense_max_n=2000) -> NamedTuple
restore_observability(net; kwargs...) -> NamedTupleReplacement values from the schedule that close the rank deficit of a set that is not observable (concept 1.2): zero injections at passive buses, P and Q from the scheduled values of the loads and generators, U by a fixed order. No flow values (the schedule knows no flows). Per network island, never across a network island border; a network island without measurements is left out. The caller's vector is not changed.
Candidates per bus of a network island (none on a bus inside a closed-link cluster of more than one bus):
- a passive bus (
findPassiveBuses: no load, generation or shunt) without an active injection row of a type: the zero injection P = 0 or Q = 0 withstate_estimation.zero_injection_sigma_mva(:passive, a zero-injection row, a constraint underzero_injection = constraint). Underzero_injection = offthey are not inserted;passive_not_insertedlists the ones that would lower a deficit. - P and Q at any other bus without an active injection row of that type: minus the sum of the scheduled power into the equipment of the prosumers at the bus (
pVal,qVal, asgeneratePseudoMeasurementTablereads them; a passive bus or a prosumer without a value gives no candidate). Sigmamax(restore_sigma_rel * |value|, floor), the floor the default P or Q sigma ofmeasurementStdDevs. - U where the bus has no active Vm row, by the first rule that applies: (1) the stored state
net._sv_vm_pu(:stored_state), (2) the set point of a voltage-controlled unit at the bus (:unit_setpoint), both with the default Vm sigma; (3) the median of the measured Vm rows of the network island at the nominal voltage of the bus (:level_median), sigma their standard deviation, at least the default Vm sigma; (4) 1.0 pu withstate_estimation.observability.restore_vm_sigma_nominal_pu(:nominal).
Selection on the decoupled models of the not-observable verdict (concept G4'): a P candidate is taken when it lowers the deficit of the P-theta model by one, a Q or U candidate when it lowers the deficit of the Q-V model by one; so the number taken is at most those deficits. Order: the passive P, then the scheduled P, each by bus; the passive Q, then U of rules 1 and 2, then the scheduled Q, then U of rules 3 and 4, each by bus. A candidate that does not lower the deficit is skipped as redundant.
The taken rows have origin = :pseudo_restore (protected from bad-data elimination) and the id restore_<type>_bus_<bus> (restore_Pinj_bus_8). After the selection the set with the taken rows is checked again (evaluate_global_observability): verdict is :observable when it has no null direction and, at the stored state of the net, no branch or bus above the bounds of the weak class (success); :weakly_observable ("weakly observable after restoring") when one is above them, the branches in weak.branches; :not_observable when a null direction is left; :not_judged on a net that stores the flat profile, where the weak class cannot be judged (weak_judged = false). Neither stops an estimation.
Returns (rows, restored, skipped, passive_not_inserted, network_islands, rank_deficit_before, rank_deficit_after, observable, weak, weak_judged, verdict, success): rows the taken Measurements in the caller's numbering, restored one row per taken value (id, bus, bus_name, network_island, quantity, value, sigma, source) (quantity :P, :Q, :U; source :passive, :schedule, :stored_state, :unit_setpoint, :level_median, :nominal), skipped the redundant candidates (bus, network_island, quantity, source), passive_not_inserted rows (bus, bus_name, network_island, quantity), network_islands one row per measured network island (network_island, angle_rank_deficit, magnitude_rank_deficit, angle_rank_deficit_after, magnitude_rank_deficit_after, n_taken), the summed deficits before and after, observable (no null direction after), weak the weak report after (as in evaluate_global_observability). What the schedule does not close stays in the deficits after.
Sparlectra.runpf_from_se! — Function
runpf_from_se!(net, maxIte, tolerance=1e-8, verbose=0; mode=:se_state, kwargs...) -> NamedTupleRun a power flow that starts from the last state-estimation result of net (the SE-to-PF chain). Requires a preceding runse! (state_estimation.update_net = true) on this net or a state restored via readSEStateCSV!; a clear error otherwise.
Modes:
:se_state(default): the PF starts from the ESTIMATED VOLTAGES; the model injections stay authoritative, so the measurement/model difference goes into the (possibly distributed) slack. This is the semantics of thepower_flow.start_mode.profile_source = state_estimationvalue.:se_snapshot: the PF additionally takes the NODAL BALANCES from the estimation: the bus load aggregates of the WORKING net are replaced bygen_static - inj_estfor the run and restored afterwards; the persistent model is never mutated (same protection philosophy asupdateShunts). With consistent PV setpoints the PF then converges in 0 or 1 iterations and the slack pickup stays below tolerance. Config valueprofile_source = se_snapshot.
kwargs are forwarded to runpf! (the flat start is forced off; the estimated voltages ARE the start). An estimate of the observable islands one by one (relative angles, unestimated buses) is refused like one that did not converge. Returns (iterations, erg, converged, mode, slack_pickup_mw, slack_pickup_mvar); the slack pickup is the PF slack injection minus the estimated injection at the slack bus.
Sparlectra.runse! — Method
runse!(net, measurements) -> SEResult
runse!(net) -> SEResultRun the nonlinear weighted-least-squares state estimation, island by island; runse!(net) uses the measurements stored on the net (net.measurements). The estimated state is written back when state_estimation.update_net is set (default true). The estimator reads every setting from the active configuration (state_estimation_config(), #381); nothing is passed per call. A run with other settings wraps the call:
with_state_estimation_config(max_iter = 12, update_net = false) do
runse!(net)
endWith state_estimation.topology_precheck (default true) an advisory topology check runs first: its findings are warned once per run and attached to the result, and the estimation always proceeds. The tap row of a released changer on a branch of a mesh without P measurement gets that in its notice (the step may not be unique); with the check off the rows carry no such notice.
Before the WLS every active voltage measurement outside 0.5 to 1.5 pu (0 kV and non-finite values included) goes through the range check: on a bus the switching state does not energize (isolated, or in an island without a source) the row and the rows of the bus, its branches and its links are set inactive for the run (log reason deenergized); on an energized bus the value is replaced by a pseudo measurement at the imported state of the bus (the SvVoltage of a CGMES import, else 1.0 pu) with its sigma times state_estimation.bad_data.substitute_sigma_factor (default 3; warning with reason range_check_substituted). The caller's vector is not changed.
State representation:
- bus voltage angles for all non-slack buses (radians), the slack at 0
- bus voltage magnitudes for all buses (p.u.)
- optional PMU reference-angle offset α (radians), appended automatically when active
VaMeasmeasurements exist andpmu_ref_offset = :auto
The start is the flat profile (state_estimation.flatstart, default true: every |V| 1 pu, every angle 0, the slack magnitude from the net; with state_estimation.start_mode.rotate_behind_pst buses behind phase shifters at their shift sum, as in the power flow flat start) or the stored state of the net, taken against the stored slack angle. The result voltages, the write-back and the angle predictions are in the angle reference of the model: the slack keeps its stored angle.
PMU angle measurements (VaMeas, degrees) are modeled as z = θ_i + θ_ref + α + e, with θ_ref the stored slack angle: α is the offset of the PMU time base against the model angle reference. With pmu_ref_offset = :off the offset state is omitted and PMU angles are taken in the model angle reference.
state_estimation.observability.on_unobservable decides what happens to a set that is not observable. Under abort (default) nothing is checked before the estimation and the estimate is the same as without the setting; after a converged run with update_net the weak class at the estimated state (evaluate_weak_observability, basis :estimated_state, from the covariance of the estimate) goes into the result field weakObservability. It only reports and changes no estimated value. state_estimation.observability.weak_check_after_estimation = false switches it off (mass runs); then, and without update_net, the field is nothing.
Under observable_islands the observable islands of evaluate_global_observability refine the network islands, and each observable island is estimated on its own subnet through the network-island path:
- A bus with a dark magnitude (null space of the Q-V model) leaves its observable island before the island is cut; its branches count as unobservable. The connected parts that remain are observable islands of their own, numbered k.1, k.2, ... in their network island k ("k" for a network island that stays one island and loses no bus).
observableIslands.removed_buseslists the removed buses with their reason. - Rows on unobservable branches, rows of removed buses, P and Q injections at the end buses of unobservable branches and link rows of such a fused cluster are not used (they hold an undetermined flow);
observableIslands.dropped_measurementsnames them. - Each island is rank checked (decoupled P-theta and Q-V models) before it is estimated; one that is not of full rank is not estimated (
reason = :not_observable, withrank_deficit). When no island can be estimated, runse! throwsSENotObservableError(the SE service reports it asse_not_observable). - Reference: the island with the Slack (or the promoted reference of its network island) keeps it; any other island takes the bus of its best voltage-controlled unit, else of its best generating unit (the rule of
detect_ac_islands), else its lowest bus. Its angles are relative to that bus and marked (relative_angles,relative_angleper bus). - Unestimated buses have NaN voltages, in the result and with
update_netin the net; closed branches outside every estimated island have NaN flows and losses, and the total losses are NaN.runpf_from_se!refuses such an estimate. A later run that starts from the stored state (flatstart = false) starts these buses flat. - After a converged run the weak class is determined at the estimate, per estimated island, whatever
weak_check_after_estimationsays (weakObservability). While a branch or bus is above the bounds, the affected buses (the ends of the branches whose flow standard deviation exceedsweak_flow_sigma_mwand the buses whose magnitude standard deviation exceedsweak_vm_sigma_pu) leave their island with reason:weak, and the islands are cut and estimated again from the same start, until nothing is above the bounds, no new bus is affected or no bus would be left. This also applies to an observable set that is weakly observable at its estimate. - When the loop ends with buses above the bounds (no island of the cut passes its rank check, no new bus is affected, no bus would be left, or the estimate of the cut does not converge, which keeps the converged estimate before the cut), the estimate is kept with that report in
weakObservability, which marks it unusable as underabort; withupdate_netthe flows and losses of its branches and the total losses are NaN in the net.
Under scheduled restore_observability first adds replacement values from the schedule (field restoredRows); the set with them then runs as under observable_islands, so what the schedule does not close is estimated per observable island.
The result of an estimate per observable island has one islands row per observable island and the field observableIslands (see SEResult); print_observable_islands prints one line per island. An observable set that is not weakly observable at its estimate runs as under abort.
Sparlectra.runse_diagnostics — Method
runse_diagnostics(net, measurements) -> NamedTupleExtended diagnostics workflow around validate_measurements with sequential bad-data elimination (identification stage 1):
While the χ²-like 3σ band test fails, a suspicious measurement (|rn| >= normalizedThreshold) exists, and fewer than max_eliminations measurements have been removed, the top suspicious measurement is deactivated and the diagnostics rerun. Zero-injection rows, rows with origin :derived or :pseudo_restore (see Measurement), near-exact measurements (sigma <= 1e-6) and the pseudo measurements of the range check are never eliminated.
The range check of runse! runs once before the first pass (voltage measurements outside 0.5 to 1.5 pu: replaced on an energized bus, reason range_check_substituted; out of the estimation with the bus and its branches on a bus that is not energized, reason deenergized); every pass works on the checked set. The default budget max_eliminations = 5 is also the round limit of the loop (one row per round).
With state_estimation.observability.on_unobservable set to observable_islands or scheduled, a set that is not observable is diagnosed per observable island, the units runse! estimates under that setting; rows no estimated island uses are not ranked. The removal of weak buses at the estimate is not repeated in the diagnostics.
Returns (diagnostics, rerun, eliminations, reverted, stop_reason, final_diagnostics, topology_findings, range_check):
diagnostics: the initialvalidate_measurementsreporteliminations: one trace row per elimination(elimination, measurement_index, id, typ, normalized_residual_before, residual_before, wii, skipped_unlocalizable, objective_before, objective_after);residual_beforeis the residual of the row in its measurement unit at the state before its removal.wiiis the localizability of the removed row andskipped_unlocalizablecounts the suspects that were passed over in that round BECAUSE they are not localizable, so the trace shows why the largest normalized residual was not the one removed.stop_reason::consistent(band test passed),:band_low(J below the band: the sigmas overstate the errors, not bad data, nothing eliminated),:no_suspicious_left,:no_localizable_suspect(suspects remain, but none of them is localizable: the data cannot say which row is wrong, which points at a measurement gap around those rows rather than at bad data),:max_eliminations, or:not_converged(the base run or a control solve did not converge; a control solve that converged only in the fallback without tap estimation, where the base run estimated the taps, counts as not converged: the row goes back to active and is reported inreverted)reverted: the elimination attempt that was taken back because its control solve did not converge,nothingotherwisefinal_diagnostics: the report after the last elimination (equal todiagnosticswhen nothing was eliminated)rerun: backward-compatible view of the FIRST elimination (deactivated_measurement_index,deactivated_measurement_id,diagnostics),nothingwhen no elimination happenedtopology_findings: the station clusters of the topology classification,nothingunless the loop stopped at:max_eliminationswith J still above the bandrange_check: the counter of the range check,(substituted, deenergized, rows), one row per finding (measurement_index,id,bus,value,reason,substitute,source,sigma,sigma_substitute,deactivated)
Backward compatibility: deactivate_and_rerun = true is kept as an alias for max_eliminations = 1 (exactly one elimination pass, result also in rerun). Unlike the old single pass, the loop only eliminates while the band test fails; a suspicious measurement in an already consistent set is reported but not removed.
Sparlectra.se_view — Method
se_view(net) -> NamedTupleStatic SE view of the network (SE phase 3): reports how the estimator will treat controllers, shunts, links, and measurements, WITHOUT mutating net.
Guarantee: runse! never invokes the outer control loop. Every controller is frozen at its current operating point; the state estimation is a snapshot. The concept transformation table applies: OLTC/PST/Schraegregler act as transformers with fixed taps, SVC/STATCOM and reactors/capacitor banks act as shunts (their susceptance is estimable per phase 2, case A), and series compensation acts as a fixed branch impedance.
Returned fields:
controllers: one row per registered outer controller(name, type, enabled), all frozen during SEshunts: one row per shunt released viasetShuntEstimation!(busIdx, busName, status)withstatus = :released(has an active direct bay measurement),:frozen_no_measurement, or:injection_mode_rejectedlinks:(closed_clusters, open_links); each closed cluster is(representative, members)in original bus indices, and the SE runs on the contracted net that fuses each cluster onto its representativeexcluded_measurements: the notes of the measurement remapping (link-referenced flow measurements, partial-cluster injections, collapsed branches, aggregations), reasons as inrunse!
See print_se_view for a formatted report.
Sparlectra.structural_observable — Method
structural_observable(H) -> BoolStructural observability test on a Jacobian-like matrix H. Returns true when the maximum bipartite matching size equals the number of state columns n.
Sparlectra.structural_row_redundant — Method
structural_row_redundant(H, i) -> BoolCheck if row i remains structurally redundant in H.
Sparlectra.summarize_se_diagnostics — Method
summarize_se_diagnostics(diag) -> NamedTupleCreate a compact interpretation summary for a diagnostics object returned by validate_measurements or runse_diagnostics.
global_consistency is interpreted as:
true: SE converged and objective is inside χ²-like 3σ plausibility bandfalse: either non-convergence or implausibly large objective
Sparlectra.validate_measurements — Method
validate_measurements(net, measurements) -> NamedTupleRun state-estimation diagnostics on currently active measurements and return a machine-readable report with:
- global bad-data consistency check (
global_consistency) - χ²-like objective plausibility summary
- largest-normalized-residual ranking with the residual-sensitivity diagonal
wiiand alocalizableflag (wii > wiiThreshold, default 0.3, the established literature threshold) - suspicious measurement list (threshold-based)
- optional residual-correlation columns (
reportResidualCorrelation, default fromstate_estimation.report_residual_correlation): per row the maximum |k_ij| over all partners plus a warning above 1/sqrt(2) (the result 7, simple-redundant group)
Current-magnitude measurements below their 3 sigma value gate are excluded, matching the estimator's own activation rule, so the report describes the measurement set the estimator actually used. With active ImagMeas rows the residual-sensitivity and correlation figures become load-flow dependent they hold for the estimated operating point.
measurement_index in the ranking rows is the position in the caller's measurement vector, with one sentinel: 0 marks a LINKAGG cluster aggregate (SE phase 3) that has no single source row. Check >= 1 before indexing the measurement vector with it.
The range check of runse! runs first (voltage measurements outside 0.5 to 1.5 pu). The report carries its counter range_check = (substituted, deenergized, rows), and every ranking row the field range_check (:range_check_substituted for a replaced row, :none otherwise).
Sparlectra.writeSEStateCSV — Method
writeSEStateCSV(net; file) -> NamedTupleWrite the last SE start state of net (registered by runse! with state_estimation.update_net = true or readSEStateCSV!) as a CSV artifact:
# sparlectra-se-state v2
bus,vm_pu,va_deg,pinj_MW,qinj_MVar,estimated,observable_island(delimiter and decimal separator follow output.csv_format, format keyword; the reader accepts every format)
One row per bus (bus by name). estimated is true or false; a bus that was not estimated (an estimate of the observable islands one by one, see runse!) has NaN values. observable_island is the label of the observable island of the bus ("1.2") and empty for an estimate of the whole set. This is the persistence half of the SE -> PF chain: a later power-flow run (possibly in another process) restores the state with readSEStateCSV! and starts via runpf_from_se!. Errors when no SE state is registered for net. Returns (count, not_estimated), the number of bus rows and of buses not estimated.
Sparlectra.print_measurement_placement — Method
print_measurement_placement([io,] result)Print the result of suggest_measurement_placement: one header line (kind, target, number of steps, whether the target was reached and why it stopped), then one line per step with its network island, the place and quantity, the angle and magnitude deficits and the unobservable branches before and after, the critical rows in the phase :no_critical, and the run time.
Sparlectra.suggest_measurement_placement — Method
suggest_measurement_placement(net, measurements; kind, target = :observable, max_steps = state_estimation.observability.placement_max_steps, dense_max_n = 2000) -> NamedTuple
suggest_measurement_placement(net; kwargs...) -> NamedTupleWhere to place the next meters so that the set becomes observable (target = :observable) or keeps no critical measurement (target = :no_critical). One meter per step, per network island, never across a network island border; a network island without measurements is left out. The caller's vector is not changed.
Candidates by kind (one candidate per place and quantity):
:injection: P, Q or U (a Vm row) at a bus without an active row of that type, one row each. P closes the P-theta model, Q and U the Q-V model.:flow: P and Q at one end of a closed branch without an active P or Q flow row at that end, two rows.:pmu: a voltage angle (VaMeas) at a bus without one, one row. Underpmu_ref_offset = autothe PMU time base is an extra state, so the first PMU of a set without one fixes only that offset and lowers no deficit (a PMU at the slack fixes nothing else either); the placement counts that step.
No candidate on a bus inside a closed-link cluster of more than one bus.
Target :observable: steps until the P-theta and the Q-V deficit of evaluate_global_observability are both 0. A candidate is valid when it lowers the deficit of its model by one (the rank test of restore_observability, on the null space of the set plus the rows taken so far). With one row per candidate (:injection, :pmu) every valid sequence has as many steps as the deficits sum to (plus the offset step of :pmu), so the number is the minimum; the order is the choice: the valid candidate after which one plain null-space pass finds the fewest unobservable branches (the most removed), ties by bus, then P, Q, U. With :flow the candidate with the largest rank gain (P-theta plus Q-V) is taken, ties by the same branch count, then branch and end; there is no claim of a minimum. A magnitude gap no candidate of the kind closes (:pmu, or :flow without a magnitude anchor) stops with stop_reason = :no_candidate; under :pmu without a step when the P-theta deficit is 0.
Target :no_critical: first as :observable, then steps until no row of the network island is critical in the AC Jacobian (numerical or structural, as numerical_critical_measurement_indices and structural_critical_measurement_indices of evaluate_global_observability): the candidate after which the fewest rows are critical, ties by bus (branch and end), then quantity; a step must lower that number (the offset step of :pmu excepted), else :no_candidate; a set observable in the decoupled models but not in the AC Jacobian stops with :ac_rank_deficit. Each trial is one criticality computation, so the cost grows with candidates times steps.
max_steps caps the number of steps over all network islands (0 allowed); reaching it before the target sets stop_reason = :max_steps. With several network islands stop_reason is the one of the first that does not reach the target. An abort of the surrounding job is checked between steps and every 64 candidates.
Returns (kind, target, max_steps, reached, stop_reason, steps, rows, network_islands, angle_rank_deficit_before, magnitude_rank_deficit_before, angle_rank_deficit_after, magnitude_rank_deficit_after, unobservable_branches_before, unobservable_branches_after, seconds):
steps: one row per step(step, network_island, phase, kind, quantity, bus, bus_name, branch, side, location, angle_rank_deficit_before, angle_rank_deficit_after, magnitude_rank_deficit_before, magnitude_rank_deficit_after, unobservable_branches_before, unobservable_branches_after, critical_before, critical_after, seconds).phaseis:observableor:no_critical;quantity:P,:Q,:U,:Vaor:PQ(a flow);bus(0 for a flow) andbranch(0 otherwise) in the caller's numbering,side:from,:toor:none; the unobservable branches are counted by the boundary iteration ofidentify_observable_islandsbefore and after the step; the critical counts arenothingin the phase:observable;secondsis the run time of the step.rows: the suggestedMeasurements in the caller's numbering (idplacement_<default id>, value 0, 1 pu for U, the default sigma ofmeasurementStdDevs): the places only, for an observability check, no readings.network_islands: one row per measured network island(network_island, n_steps, angle_rank_deficit_before, magnitude_rank_deficit_before, angle_rank_deficit_after, magnitude_rank_deficit_after, reached).- the summed deficits and the unobservable branches (caller's numbering) before and after, and the total run time.
The step times are in the result; the SE service writes them to performance.log. Errors like evaluate_global_observability when no active measurement is left, and on an unknown kind or target or a negative max_steps.
Sparlectra.AreaPartition — Type
AreaPartitionThe areas of a net for the multi-area state estimation.
area_of_bus: area per bus (bus numbering of the net).areas: the area numbers, ascending.area_names: the name per entry ofareas(net.area_names: the operator model or region of a CGMES import, SCFsparlectra.areas); empty strings without names and with an area list.tie_branches: closed branches whose ends lie in two areas.border_buses: the ends of the tie branches, ascending.notes: what the partition changed, e.g. a link group the area list cut, moved to the area of its representative.
Sparlectra.MultiAreaSEResult — Type
MultiAreaSEResultResult of runse_multi_area!.
voltages: estimated complex voltages per bus (bus numbering of the net, slack angle frame of the net).converged,passes: whether the border states settled (no change abovestate_estimation.tol) and after how many passes;border_changeholds the largest change per pass.objectiveJ,dof: J over all rows (the areas' rows are disjoint) and the degrees of freedom of the whole set.areas: one row per area:area,name(seeAreaPartition),buses,border_buses,rows(count of own active rows),janditerationsof its last run,converged, andresult, theSEResultof that run on the extended subnet.borders: one row per border bus:bus,name,area,vm_pu,va_deg.partition: theAreaPartitionused.tapEstimates: the released tap regulators, one row per changer as inSEResult.tapEstimatesplus itsarea(branchin the numbering of the net);nothingwithout released regulators. The passes keep the regulators as continuous states; at the converged border each area fixes them with the rule ofrunse!, and the passes go on with the fixed steps.comparison: withcompare_integrated = truethe integrated estimate on the same rows:rowsper state (bus,name,quantity(:vm in pu or :va in degrees),multi_area,integrated,difference,sigma, the standard deviation of the state in the integrated estimate, anddifference_sigma),max_dvm_pu,max_dva_deg,integrated_converged, and the check of the tap release:tap_release, one row per released regulator (branch,regulator,name,changer,area,multi_areaandintegratedas (status, reason),same) andtap_release_differences, the number of rows that differ (named in a warning);nothingotherwise. Each area decides the release of its own regulators; without the comparison that decision is not checked.
Sparlectra.area_partition — Method
area_partition(net; areas = nothing) -> AreaPartitionAreas of net for the multi-area state estimation. Without areas every bus takes the area stored with it (area of the MATPOWER bus table, SCF extra.area, the area keyword of addBus!); a bus without one is an error that names it. areas is a map bus name => area number and must name every bus.
A group of buses joined by closed links is never cut: when the list puts its members in different areas, the group goes to the area of its representative (the lowest bus index), with a note. Open links and one-sided open branches do not couple areas.
Sparlectra.read_area_list — Method
read_area_list(path) -> Dict{String,Int}Read an area list for area_partition: one line per bus with the bus name and the area number, separated by ;, , or a tab. Empty lines, lines starting with # and a header line (first data line whose second field is not a number) are skipped. A malformed line or a bus named twice is an ArgumentError with the line number.
Sparlectra.runse_multi_area! — Function
runse_multi_area!(net, measurements = net.measurements; areas = nothing,
partition = nothing, max_passes = nothing,
compare_integrated = nothing, update_net = true) -> MultiAreaSEResultMulti-area state estimation, two-level method. The net is split into areas (area_partition: from the map areas bus name => area, from an area list file (read_area_list) when areas is a path, else from state_estimation.multi_area.partition, bus_area (the stored bus areas) by default; or pass a ready partition). max_passes and compare_integrated default to the keys of state_estimation.multi_area. Every row belongs to one area: a bus row to the area of its bus, a branch row to the area of its measured end. Per pass each area estimates its interior with its own rows and the border buses held at the coordinator's values; the coordinator then takes one Gauss-Newton step on the border states from the sum of the area models (Schur complement of each area's gain matrix onto its border columns and its reduced gradient). The fixed point is the integrated estimate on the same rows; the passes stop when no border state moves by more than state_estimation.tol.
An area whose own rows do not determine its interior for given border values is refused before the first pass, with its rank deficits. Not supported (refused with the reason): more than one slack bus, state_estimation.zero_injection = constraint, PMU angle rows in more than one area.
With compare_integrated the result carries the integrated estimate on the same rows and the difference per state, also in units of its standard deviation. With update_net the estimated voltages are written to the buses of net.
Sparlectra.runse_multi_area_diagnostics — Function
runse_multi_area_diagnostics(net, measurements = net.measurements; areas = nothing,
partition = nothing, max_passes = nothing) -> NamedTupleBad-data elimination for the multi-area estimation, by the rule of runse_diagnostics: while J fails the band test above, the row with the largest normalized residual (at least state_estimation.k_eliminate, localizable, not protected from elimination, not a range-check substitute) is switched off and the two-level estimation runs again, one row per round, up to state_estimation.max_eliminations. The normalized residuals use the exact residual covariance of the whole estimate, the border information of every area included, so a row at an area border is judged as in the integrated estimate (decision E6: the largest over all areas wins, its owner removes it).
Returns (result, trace, stop_reason, measurements): the MultiAreaSEResult of the last run, one trace row per elimination (elimination, measurement_index, id, typ, area, normalized_residual_before, residual_before, wii, objective_before, objective_after), the stop reason (:consistent, :band_low, :no_suspicious_left, :no_localizable_suspect, :max_eliminations, :not_converged) and the measurement vector with the eliminated rows inactive.
Sparlectra.calcMachineTrafoTapFromSE — Method
calcMachineTrafoTapFromSE(net; trafo, v_machine_pu = nothing, p_mw = nothing, q_mvar = nothing) -> NamedTupleBack-calculate the tap position of a MACHINE (generator step-up) transformer after a state estimation. Mutually exclusive with a tap release on the same transformer: a released tap is estimated, a machine tap is reconstructed here, never both. A machine transformer has a terminal that connects to nothing but this transformer and carries a generator; the buses closed links tie together count as one terminal, so a generator behind a closed coupler qualifies, and its setpoint and schedule are read from the generators on those buses.
A machine terminal is invisible to the estimator (the AVR sets its voltage, nothing measures it independently), so taking both the terminal voltage AND the terminal injection from the SE would circularly reproduce the model tap. The non-circular information is: the estimated NETWORK-side voltage (from runse! with state_estimation.update_net = true), the known machine terminal voltage magnitude (the AVR setpoint vm_pu of the generator prosumer, or v_machine_pu), the active-power dispatch (prosumer p schedule, or p_mw), and the machine reactive power. CAREFUL with Q: under AVR voltage control the machine's Q is NOT its schedule value; pass the MEASURED machine reactive power (q_mvar, the SCADA telemetry every unit has). The prosumer q value is only a fallback for uncontrolled machines. The function solves the transformer terminal equation for the machine angle (active-power balance) nested inside a scan over the step s of the branch's first ratio tap changer (reactive-power balance; the other changers stay at their start position, the impedance at the live value). Returns s_est (continuous step relative to neutral), electrical_step = neutral + s_est and fixed_step, the nearest physical step on the changer's own band, the changer index regulator and the branch ratio and angle at s_est. Reporting only, no write-back. runse! runs the same calculation by itself for every released machine transformer that state_estimation.tap_estimation.include_machine_transformers = false keeps out of the estimation (tapEstimates row status = :calculated).
Errors: transformer released for estimation, not a machine transformer, no ratio tap changer, no registered SE result, or no machine voltage/injection available.
Sparlectra.setTapEstimation! — Method
setTapEstimation!(net; trafo, mode = :ratio, alpha_deg = nothing, enabled = true)Release the tap changers of a transformer as state-estimation states (0.10.0; one step state per changer since 0.60.0). The changers come from the branch's changer set: what an import stored, the typed models of a resolved winding, or the nameplate fields. mode selects them by role: :ratio the ratio changers, :pst the phase changers, :both all; :pst and :both need a declared phase changer, :ratio a ratio changer (ArgumentError otherwise). The direction alpha of an asymmetrical phase changer comes from the import and is never estimated: alpha_deg is optional and, when given, has to equal it (ArgumentError naming both, or when the selection has no asymmetrical changer). enabled = false clears the release. Neither call writes the stored direction tap_est_alpha_deg.
A branch that does not lie on the curves of its changer data is no error here: the release is recorded and the estimator freezes the regulators with :model_mismatch and a notice. The release does not override the configuration: a transformer named in state_estimation.tap_estimation.exclude stays out (:excluded), and so does a machine transformer unless include_machine_transformers is set (:machine_transformer, calculated after the run).
Returns (branch, mode, alpha_deg, s0): alpha_deg of the first selected asymmetrical changer or nothing, s0 the start positions (steps relative to neutral) of the selected changers in set order, nothing on a model mismatch, empty for enabled = false.
Sparlectra.test_topology_hypotheses — Function
test_topology_hypotheses(net, measurements = net.measurements; candidates = :auto, max_candidates = 5, maxIte = ..., tol = ...) -> NamedTupleStage-3 topology hypothesis test: for each candidate element the service-state is TOGGLED on a working copy of the net, the estimation is re-run, and the chi-square band verdict before versus after decides whether the hypothesis explains the data. The input net is never touched (bitwise, test-enforced); the result is a RANKED RECOMMENDATION LIST and nothing is ever switched automatically.
candidates = :auto collects the stage-2 suspected stations' switchable elements first, then the stage-1 status contradictions, capped at max_candidates (cost guard; per-candidate timing is reported). An explicit vector of (kind = :branch | :link, idx) tuples is also accepted. A hypothesis is :hypothesis_supported only when the toggled run lands inside the Wilson-Hilferty band while the original run failed it :high; several supported hypotheses are flagged ambiguous.
Sparlectra.validate_topology — Function
validate_topology(net, measurements = net.measurements; kwargs...) -> NamedTupleStage-1 topology pre-checks: pure, linear in the measurement count, no state estimation involved. Returns (findings, summary, notes, n_checked_branches, n_checked_links) where each finding is (stage = :precheck, kind, location, evidence, severity) and notes lists the checks that could not judge (also appended to summary). ADVISORY only: nothing is blocked or mutated; the caller decides what to do with the findings. Out-of-service elements are exempt from the plausibility checks; only the status-contradiction check (:open_element_with_flow) looks at them, because a measured flow over an open element IS the topology error.
Checks (thresholds as sigma multiples, keywords mirror the state_estimation.topology_* configuration):
:open_element_with_flow(k_open, default 4.0): an OPEN branch or link carries an active flow/current measurement with|value| > k * sigma.:closed_element_without_flow(k_dead, default 3.0): a CLOSED branch whose present flow/current measurements are all belowk * sigmaat both ends, while the model expects a flow abovek * sigmaon it. The expectation comes from the net's present voltage state (case start values, the last power flow, or the last SE state); a lightly loaded branch that is expected near zero never fires. A state with all bus angles equal (flat start, no stored result) gives no expectation: the rule is skipped and a note says so.:closed_link_voltage_mismatch(k_v, default 4.0): a closed link with voltage-magnitude measurements on both sides disagreeing by more thank * sqrt(sigma_a^2 + sigma_b^2).:kcl_violation(k_kcl, default 4.0): a COMPLETELY measured node (injection measurement present, every closed attached branch carries a flow measurement at this end) whose balance misses by more thank * sqrt(sum sigma^2), for P and Q separately. Partially measured nodes and nodes inside closed-link clusters are skipped, never guessed.:mesh_without_p_measurement(severity:warning): a mesh of the branch graph (closed-link clusters fused as in the estimator) with no active power row on its branches or buses. Q, |I| and Vm rows alone can admit a second converged state with turned-over angle differences, so the solution may not be unique. An injection row on a link cluster counts only when every member is measured, as in the estimator. Structural, no threshold; one finding per group of such meshes, naming its branches (all of them in the extra fieldbranches).:measurement_contradicts_topology(severity:warning): a network island without a source (or an isolated bus) with a voltage measurement above 0.1 pu. The estimator keeps its rows instead of dropping them as a dead part (see the range check in the state estimation docs); a neighbour outside the model or a wrong switch state is the usual cause.
Internals
Sparlectra.MEASUREMENT_CSV_V1_REMOVED — Constant
MEASUREMENT_CSV_V1_REMOVEDThe message for a measurement CSV v1 file where a measurement set is read: its reader readMeasurementsCSV! was removed in 0.50.0. The SE service and the Web UI refuse such a file with it, and the Web UI shows it at the file. It names the converter.
Sparlectra._duplicate_measured_quantities — Method
_duplicate_measured_quantities(ms) -> Dict{String,Int}Count, per measurement type, how many entries repeat a quantity (same type, same bus/branch/link, same direction) that an earlier entry already covers. The first occurrence of each quantity is not counted, so an empty result means the set measures every quantity at most once.
Only ACTIVE rows count: a deactivated row contributes nothing to the objective, so it never competes with the reading it sits next to.
Sparlectra._measurement_key — Method
Canonical form of an mRID key: without urn:uuid: and without a leading _.
Sparlectra._sigma_level_summary — Method
_sigma_level_summary(net, measurements; origins = Dict{String,Symbol}(), levels = <state_estimation.sigma_by_voltage_level>) -> NamedTuplePer nominal voltage of net: how many measurements sit at that level and where their sigma came from (origins, the sigma_origin of a table set; a measurement without an entry carries its own sigma, as every row of a measurement CSV v1 does), plus the absolute sigmas of a configured row in pu: p_mw / baseMVA, q_mvar / baseMVA, u_kv / Vn and i_a / I_base with I_base = baseMVA / (sqrt(3) * Vn) (kA, so i_a * sqrt(3) * Vn / (1000 * baseMVA)). Zero-injection rows (id prefix ZI) are constraints and not counted.
Returns (levels, unused, unlocated): levels one NamedTuple per nominal voltage, highest first, with vn_kv, configured, measurements, row, level, default, rel_pct and sigma_pu = (p, q, i, u) (nothing where the row leaves the type on the default); unused the configured vn_kv that no bus of net has; unlocated the measurements without a bus, branch or link.
Sparlectra.ObservableIslands — Type
ObservableIslandsObservable islands of a measurement set (numerical method after Monticelli and Wu, 1985, on the decoupled P-theta model), in the bus and branch numbering of the caller's net. Returned by identify_observable_islands and carried as observable_islands in the result of evaluate_global_observability, where it is empty (isempty true) for an observable set.
Two kinds of island are kept apart. A network island is a topologically separate part of the net with its own angle reference (the islands rows of evaluate_global_observability). An observable island lies inside one network island: the buses whose states the measurements fix once one of them is taken as the reference. Observable island j of network island k carries the label "k.j", or "k" when network island k is one observable island. A network island is no gap: it adds nothing to a deficit, and one without measurements is listed in unmeasured_network_islands.
Fields:
island_of_bus: observable island per bus of the net, an index intoisland_busesandisland_labels; 0 for a bus outside the estimated state (isolated, or in a network island without measurements).network_island_of_bus: network island per bus, 0 for an isolated bus.n_islands: number of observable islands over all network islands.island_buses: the buses of each observable island, ordered by network island and inside it by first bus.island_labels:"k.j"or"k"per observable island.network_islands: one row per network island,(network_island, n_bus, measured, n_islands, rank_deficit, angle_rank_deficit, magnitude_rank_deficit, region_buses, unobservable_branches); a network island without measurements hasmeasured = false, no observable island and deficit 0.unmeasured_network_islands: the network islands without measurements.unobservable_branches: in-service branches whose ends lie in different observable islands; their flow follows from no measurement.unobservable_branch_names:"from - to"per unobservable branch.region_buses: the buses with a dark angle, those whose row of the orthonormal null basis of the P-theta model of the set (before the iteration) is above the probe tolerance.rank_deficit:angle_rank_deficit + magnitude_rank_deficit, the number of replacement values a restoration needs (angle values for the first, Q or U values for the second).angle_rank_deficit: rank deficit of the P-theta model of the set.magnitude_rank_deficit: rank deficit of the decoupled Q-V model of the set (Q injections, Q flows and Vm rows against the magnitudes).angle_sv_kept_min,angle_sv_dropped_max: the smallest singular value of the column-normalized P-theta matrix above the rank tolerance and the largest one at or below it (0.0 when there is none, NaN when not computed), the gap at the rank cut.removed_boundary_injections: ids of the rows the iteration dropped, as the working net carries them (the injections of a closed-link cluster as itsLINKAGG_...row): P injections at an end bus of an unobservable branch and P link-flow rows whose balance contains the flow of an unobservable branch.dark_magnitude_buses: buses whose magnitude has a share in the null space of the Q-V model.passes: number of decompositions of the P-theta model run (the most over the network islands).bus_names: bus names of the net, for the printout.
Neither deficit is the rank deficit of the AC Jacobian (n_states - numerical_rank of the verdict). The Q rows carry angle information into the AC Jacobian, so a set of injections without flows can leave a P-theta deficit at full AC rank, and a bus seen through one Q flow only is one AC null direction where the decoupled models count its free angle once.
Sparlectra._column_normalized — Method
_column_normalized(H) -> SparseMatrixCSCNormalize every row of H to unit norm, then every column, for the rank test.
Rank does not change under positive row or column scaling, but its NUMERICAL determination does. Unscaled, a voltage column (entries around 1) sits next to an angle column whose entries carry the branch admittances of a 765 kV line, so the columns span orders of magnitude; sigma_max then belongs to the largest scale and genuine small singular values fall below a relative cut. That read as a rank deficit on a 25000-bus network whose set was four times overdetermined; the column normalization fixes it.
Columns alone are not enough when one branch is orders of magnitude stiffer than the rest, a bus coupler entered as a branch with near-zero impedance (case141: buses 86 and 87, x = 1e-5 pu, admittance 1e5 against about 250 for the line that feeds them). The coupler's flow and injection rows dominate both bus columns, the column normalization shrinks the feeding line's entries to about 1e-5, and the common mode of the two buses fell below the cut: rank 279 of 281, "not observable", although the feeding line's flows measure both buses. Normalizing every ROW to unit norm first takes the coupler's magnitude out of its rows, so the column normalization afterwards sees comparable entries: rank 281 there, and unchanged full rank and critical sets on case1354pegase and case13659pegase.
Rows are scaled to unit norm, deliberately NOT by sigma: dividing by sigma lifts zero-injection pseudo-measurements (sigma 1e-6 against 0.01 to 24 for real ones) by six orders of magnitude, they take over sigma_max, and everything else drops below the cut (measured on the 25000-bus network: raw deficit 191, with sigma row scaling 12308, with column normalization alone 0). A unit row norm gives every measurement the same weight in the rank test whatever its sigma or its electrical magnitude.
A row or column of norm zero carries nothing and stays zero, so an unmeasured state keeps producing the rank deficit it should.
Sparlectra._suppression_normalized_residuals — Method
_suppression_normalized_residuals(H, r, w) -> Union{Nothing,Vector{Float64}}Normalized residuals rn = r_i / sqrt(Omega_ii) for one suppression round, through the same _residual_diagnostics the bad-data elimination uses, so both decisions read one scale.
Returns nothing when no verdict is possible: no Jacobian was kept, or the diagnostics refuse this problem size (they error rather than allocate an unaffordable dense inverse). The caller then suppresses NOTHING. Falling back to the raw ratio |r|/sigma is deliberately not offered: it is the measure the normalized residual replaced, and a suppression decided on the wrong scale is worse than none, because nothing downstream shows which scale was used.
Returns rn together with the residual sensitivity wii, because the caller needs both: rn says HOW far the row is off, wii says whether that verdict can be trusted for this row at all.
The wii guard of _residual_diagnostics carries over unchanged: a row whose Omega_ii sits at the numerical floor is not localizable and gets rn = 0, so it can never be suppressed on the strength of a large raw residual.
Sparlectra.numeric_rank_pivots — Method
numeric_rank_pivots(H; tol = nothing, dense_max_n = 2000) -> Tuple{Int,Symbol}Numerical rank of the Jacobian read from the LDLt factorization of the gain matrix G = H' H (unit weights, no column scaling: a column that carries only forward-difference noise must stay below the tolerance, and a normalization would lift it to unit norm), instead of a second decomposition of H: the number of pivots above tol^2, since the pivots of H' H scale like squared singular values and tol is the singular-value bound of numeric_rank. The default tol is the same formula as there. The pivot count is exact for a full-rank Jacobian; on a deficit it can undercount (measured on spcase1354 with eleven unmeasured buses: 2700 pivots against a rank of 2702 from the SVD, since the pivots of an LDLt are not the eigenvalues of G), and a factorization CHOLMOD refuses (a singular G) states no size at all. So any deficit is handed to `numericrank, and the method is reported as:decomposition;:pivotsis reported only for the full-rank answer. Selected withstateestimation.rankmethod = pivots;decomposition(SVD below 2000 states, sparse QR above) is the default, the exact answer at the same cost on every shipped case.densemaxnis handed tonumeric_rankfor the deficit count. Returns the rank and the method that gave it (:pivotsor:decomposition). Throws anArgumentErrornaming the first entry whenHhas a NaN or Inf entry, with or without an explicittol`.
Sparlectra.TapBranchState — Type
TapBranchStateOne released transformer inside one SE (island) run: the snet branch index, its changer set (_effective_tap_changers), the start position s0 of every changer (from the live branch, _tap_s_from_branch), the position spos a changer without a state column sits at (s0 in the estimation, the fixed step in the fixation run), which changers the release selects (released), the state column per changer (cols, 0 = no state), the freeze reason and note per changer, a scratch Branch the overlay rewrites per evaluation, the live impedance z0 = (r, x, g_from, b_from, g_to, b_to) with its factors F0 at s0, the step size sigma per changer (_tap_scale), whether the run applies an impedance source on this branch (impedance: _tap_reactance_source is not :nominal), the branch TapStepImpedance for :tsi sources, and tree_phase, the phase regulators on a tree edge without an angle anchor that the vertex notice watches, weak, the factor of the weak-column hint per changer (0.0 = no hint, see _tap_weak_hints!), and rel_ref, per changer the names of the frozen phase regulators a phase regulator is only relative to ("" = none, set with note :relative_to_frozen by _tap_relative_to_frozen!); such a regulator is never fixed, it stays a state in the fixed run. cause holds per changer the structural cause the guard found (_tap_guard_causes!: :none, :radial_no_voltage_pin, :not_separable, :no_angle_anchor, :symmetric_start; :zero_column marks a column the noise test froze). A cause freezes nothing by itself: it becomes the reason only when the rank test drops the column (_tap_rank_freezes!).
Sparlectra.TapStateMap — Type
TapStateMapState map of the released tap regulators inside one SE (island) run: the released transformers (TapBranchState, branch order), the first tap state column col0 (after the shunt B states, before the PMU offset), the number of tap states ncols, and the impedance_correction mode of the run (:auto or :off). One state per released, unfrozen regulator, the electrical step s relative to the changer's neutral step; columns run in branch order, then in the changer order of the set.
Sparlectra._is_machine_transformer — Method
_is_machine_transformer(net, k) -> BoolMachine (generator step-up) transformer detection for the tap-release guards: one terminal of branch k hangs on this branch alone and carries a generator prosumer. The terminal is its closed-link cluster (the buses closed links tie together count as one node, _link_clusters): a generator behind a closed coupler is at the terminal, and a closed link is no further connection. Estimating such a tap is pointless: the generator terminal voltage behind it is set by the machine, not observed independently, so the tap state absorbs whatever the AVR does. The test of _machine_sides, so the guards, the exclusion and the calculation after the estimation agree.
Sparlectra._resolve_trafo_branch — Method
_resolve_trafo_branch(net, trafo) -> IntResolve a transformer reference to its branch index: an Int branch index, or a String matching the branch component name, component id, or a numeric index. Errors when nothing matches or the branch is not a transformer (ratio == 0 marks a line).
Sparlectra._tap_cut_component — Method
_tap_cut_component(net, k) -> Union{Nothing,Set{Int}}Bridge test for the tap-release guards: connectivity of the two terminal buses of branch k WITHOUT the branch itself, over closed branches and closed links. Returns nothing when the terminals stay connected (the transformer sits in a loop), otherwise the set of buses in the component containing toBus (the side the transformer alone ties to the rest).
Sparlectra._tap_fix_columns — Method
_tap_fix_columns(x, map, fix) -> (fixedMap, xFixed, colmap)Fixation of the tap states in the columns fix: each goes to its nearest physical step (_tap_fixed_position), one frozen with :out_of_range to its transferred step, and leaves the state; the other tap columns stay states, renumbered from map.col0 in their order. Returns the map of the next run (every transformer of map in the same order, a fixed regulator stamped at its step through spos), the state vector without the fixed columns and the old-to-new number of every kept tap column. With all columns in fix the next run has no tap state (the fixed run); a single column per call is one step of the sequential fixation.
Sparlectra._tap_fixed_position — Method
_tap_fixed_position(ch, s) -> Float64Physical step nearest to the continuous estimate s (relative to the changer's neutral step) on the changer's own absolute band (rounded to the nearest physical step, up or down): the formula kinds round with ties away from zero and clamp into low - neutral .. high - neutral; a phase table takes its nearest point; a ratio table takes its nearest point inside the table range and a whole step on the formula outside it. A tie between two points goes to the one farther from neutral.
Sparlectra._tap_guard_causes! — Method
_tap_guard_causes!(net, map, activeMeas, slackIdx, withVaOffset)Structural part of the determinability guard. It freezes nothing: it writes per changer the structural cause (ts.cause) that names a rank deficit when the rank test (_tap_rank_freezes!) finds one, plus the notes of map. The first cause found wins, in this order:
- Bridge rule: a transformer that is a bridge (its removal cuts the net) without an active voltage-magnitude measurement on its cut-off side, its regulators that move the magnitude of the ratio on their band (
_tap_changes_magnitude,:radial_no_voltage_pin): the tap and the downstream voltage cannot be told apart. A pure angle changer there gets its cause from the angle rule (3). - Separability: the released regulators of one transformer, in set order, each have to raise the rank of the real 2 x k matrix of
(dt/ds_c)/tat the start; one that does not gets:not_separable. The ratio plane has two real directions, so a third regulator always gets it, and so does the second of two along one direction (two ratio changers, a ratio changer and an asymmetrical one at alpha 0 or 180, two pure angle changers). - Angle anchors: the transformers with a released regulator that moves the angle are the edges of a graph over the classes of buses that the other closed branches and links tie together; buses with a Va row or at the measured end of an Ia row of
activeMeasare anchors (united, and with the slack bus when the run has no PMU offset state; the caller passes the rows of the rank test, so an Ia row whose current is zero at the start does not count). Walked from the slack class: an edge inside one class is pinned by its loop; on a tree edge to a new class the phase regulators get:no_angle_anchorwhen the transformer has a released ratio regulator, else:symmetric_startwhen the magnitude of their factor does not move at the start (_tap_symmetric_at). A tree-edge phase regulator is watched by the vertex notice (tree_phase) and gets note:sign_from_startwhen the magnitude is not monotonic on its band; the noise test and the rank test clear both on the regulators they freeze (_tap_freeze!). A further edge between two reached classes (a mesh edge) gives its phase regulators note:relative_only. Which of them are only relative to a frozen phase regulator is decided after the freezes (_tap_relative_to_frozen!).
Until 0.60.0 these rules froze the regulators themselves. The rank test replaced that: a regulator whose column the other columns explain is not estimated, and the cause found here only names why.
Sparlectra._tap_relative_to_frozen! — Method
_tap_relative_to_frozen!(net, map, frozenStates, activeMeas, slackIdx, withVaOffset)Last part of the determinability guard, after the rank test, so every freeze reason counts. A phase regulator that is estimated (no freeze reason) and not pinned by its own magnitude effect (tree_phase) gets its angle from the angle difference of the two classes it joins. That difference comes from the phase regulators whose angle is known: the frozen ones (any freeze reason, also the transformers of frozenStates, the ones that left the map, :modelmismatch included) and the estimated ones pinned by their magnitude effect. When the two classes are tied only over a path that runs through a frozen phase regulator, the measurements fix the regulator only against the start position of that frozen one: it gets note `:relativetofrozen,relrefnames the frozen transformers on the shortest such path, and it is not fixed (tapfixable), its continuous value stays in the fit. The classes are those oftapangle_classeswith every transformer that has an estimated or a frozen phase regulator taken out. Writes the notes ofmap` in place; no column changes.
Sparlectra._tap_step_limits — Method
Per-iteration step limit of each tap state, in steps: a quarter of the changer's band (_tap_band). Measured on a CGMES delivery: without a bound one weakly determined transformer ran to -329 electrical steps on a band of about -14 to +18 and took the whole estimation down, but clamping the STATE into the band was worse than no bound at all (five transformers that had converged stuck to the lower bound and diverged). The transient excursion is part of how a weakly determined regulator finds its position, so what is bounded is the distance one iteration may travel. A band of zero width gives no limit.