Taps, phasors and topology

Level: Expert, third part of the state-estimation series after the basics notebook and bad data and parameter estimation.

Note: This workshop was created with AI assistance and is reviewed and curated by the maintainer; it is not a fully machine-generated text.

The first two chapters treated the network model as given and asked what the measurements say about the STATE. This one asks the harder question: what if the model itself is wrong? A transformer that is three steps away from where the database thinks it is, a breaker whose status never got updated, a station behind a transformer that nobody measures. Each of those shows up as a large $J$, and each needs a different answer.

Everything below runs on ONE study network. Each section adds a capability to the same case, so the numbers stay comparable: you can see $J$, the degrees of freedom, and the error against the truth move as the measurement set and the released parameters change. The chapter closes with the decision tree that ties the sections together: $J$ is too large, what now?

What you will see, in order:

  1. why $J$ alone means nothing without its degrees of freedom
  2. what each added measurement actually buys
  3. estimating an on-load tap changer, a phase shifter, and both at once
  4. the tap that CANNOT be estimated, and why the estimator freezes it
  5. what current magnitudes can and cannot do
  6. PMU phasors and the reference offset the estimator solves for
  7. the topology advisory: when the model, not the data, is wrong
  8. island-wise estimation with one reference per island
  9. \[J\]

    versus $J_\mathrm{active}$ when rows are suppressed

Warm-up and shared helpers

Julia compiles each function on first use. This cell loads the packages and defines the two helpers of the notebook, the study-network builder and the truth-and-measurements generator; after this cell and the study-network cell below any example can run on its own. A code cell that uses a name from another cell says so in a comment. Random (standard library) seeds the synthetic measurement noise, and Printf formats the comparison tables. Its last line, warmup(), runs every path the notebook exercises once (the power flow and the estimator on a tiny throwaway network, then, on the study network, the tap estimation in all three modes, current and PMU measurements, the observability check, the topology precheck, island-wise estimation and the robust replacement mode), so the real study runs at full speed; its code is in docs/lit/warmup/workshop_se_taps.jl of the package. How long the warm-up takes depends on the machine; every later cell then runs without compile pauses.

using Sparlectra
using Random
using Printf

# the helpers of the notebook, defined here so that any example runs on
# its own after this cell:
#   build_net(; ratio_step, phase_step)     the study network (every example)
#   truth_measurements(; ratio_step, ...)   solved truth plus noisy measurements
#                                           (study network, Examples 3 to 5, 7, 8)
function build_net(; ratio_step = 0.0, phase_step = 0.0)
  net = Net(name = "workshop_se_taps", baseMVA = 100.0)
  for (b, vn) in (("H1", 110.0), ("H2", 110.0), ("L1", 20.0), ("L2", 20.0), ("L3", 20.0))
    addBus!(net = net, busName = b, vn_kV = vn)
  end
  addProsumer!(net = net, busName = "H1", type = "EXTERNALNETWORKINJECTION", referencePri = "H1", vm_pu = 1.02, va_deg = 0.0)
  addProsumer!(net = net, busName = "L1", type = "ENERGYCONSUMER", p = 25.0, q = 8.0)
  addProsumer!(net = net, busName = "L2", type = "ENERGYCONSUMER", p = 15.0, q = 5.0)
  addProsumer!(net = net, busName = "L3", type = "ENERGYCONSUMER", p = 8.0, q = 3.0)
  addPIModelACLine!(net = net, fromBus = "H1", toBus = "H2", r_pu = 0.010, x_pu = 0.080, b_pu = 0.0, status = 1)
  addPIModelACLine!(net = net, fromBus = "L1", toBus = "L2", r_pu = 0.020, x_pu = 0.100, b_pu = 0.0, status = 1)
  addPIModelTrafo!(net = net, fromBus = "H1", toBus = "L1", r_pu = 0.002, x_pu = 0.060, b_pu = 0.0, ratio = 1.0, shift_deg = 0.0, status = 1)
  addPIModelTrafo!(net = net, fromBus = "H2", toBus = "L2", r_pu = 0.002, x_pu = 0.060, b_pu = 0.0, ratio = 1.0, shift_deg = 0.0, status = 1)
  addPIModelTrafo!(net = net, fromBus = "L2", toBus = "L3", r_pu = 0.004, x_pu = 0.070, b_pu = 0.0, ratio = 1.0, shift_deg = 0.0, status = 1)
  # T1 (branch 3) carries BOTH changers; `*_current_step` is where they stand
  applyTapNameplate!(
    net.branchVec[3];
    tap_step = 0.00625, tap_min_step = -16.0, tap_max_step = 16.0, tap_current_step = ratio_step,
    phase_step_deg = 1.25, phase_min_step = -20.0, phase_max_step = 20.0, phase_current_step = phase_step,
  )
  # T3 (branch 5): the radial transformer, at neutral unless stated otherwise
  applyTapNameplate!(net.branchVec[5]; tap_step = 0.0125, tap_min_step = -8.0, tap_max_step = 8.0)
  ok, msg = validate!(net = net)
  ok || error("Network validation failed: $msg")
  return net
end


function truth_measurements(; ratio_step = 0.0, phase_step = 0.0, seed = 7, kwargs...)
  truth = build_net(; ratio_step = ratio_step, phase_step = phase_step)
  _, status = runpf!(truth, 40, 1e-10, 0)
  status == 0 || error("truth power flow did not converge")
  calcNetLosses!(truth)
  std = measurementStdDevs(vm = 1e-3, pinj = 1.0, qinj = 1.0, pflow = 0.7, qflow = 0.7)
  meas = generateMeasurementsFromPF(
    truth;
    includeVm = true, includePinj = true, includeQinj = true, includePflow = true, includeQflow = true,
    noise = true, stddev = std, rng = MersenneTwister(seed), kwargs...,
  )
  return truth, meas
end

# compile every path the examples use once; the warm-up code is in
# docs/lit/warmup/workshop_se_taps.jl of the installed package
include(pkgdir(Sparlectra, "docs", "lit", "warmup", "workshop_se_taps.jl"))
warmup()
warm-up: compiles the paths of this workshop once; how long it takes depends on the machine
warm-up time, first power flow: 0.0 s, first estimation: 0.13 s (both compile)
warm-up time, further paths: 26.8 s (tap estimation, currents, PMU, observability, topology, islands, robust); everything warm

The study network

A substation fed at 110 kV, feeding a 20 kV bus bar, with a second path that closes the loop. The loop matters: a transformer tap is only observable inside a loop or with a voltage measurement behind it, and this chapter is largely about that sentence.

  H1 ============== H2         110 kV (coupler line)
   |                 |
  T1 (OLTC + PST)   T2 (fixed)
   |                 |
  L1 ------------- L2 --- T3 --- L3    20 kV
                            (radial, unmeasured behind)
  • T1 carries both changers on one winding: a ratio tap (0.625 % per step, band ±16) and a phase tap (1.25° per step, band ±20). The estimator gives each changer its own state, the step it stands at.
  • T2 is a plain transformer. It closes the loop that makes T1's tap observable.
  • T3 feeds a radial station, and later on nothing will measure the voltage behind it. That is the case the estimator refuses to guess.

applyTapNameplate! is the one path that declares tap-changer data: step size, position band, and the position the changer currently stands at. Importers use the same function, so a hand-built network and an imported one behave identically.

build_net is defined in the warm-up cell at the top.

The truth is a solved power flow the estimator never sees; the measurement set is derived from it with seeded Gaussian noise of exactly the declared standard deviations. ratio_step and phase_step put the changers of the TRUE network where the estimator will have to find them.

truth_measurements is defined in the warm-up cell at the top.

# uses: truth_measurements (warm-up cell)
truth, full_set = truth_measurements(seed = 3)
vm_true = [getNodeVm(n) for n in truth.nodeVec]
println("study network: ", length(truth.nodeVec), " buses, ", length(truth.branchVec), " branches, ", length(full_set), " measurements")
study network: 5 buses, 5 branches, 35 measurements

A number that proves nothing: J at zero degrees of freedom

Example 1. The state of an $n$-bus network has $2n-1$ unknowns: one magnitude per bus, and one angle per bus except the reference. Five buses means nine states. Feed the estimator exactly nine measurements and it will reproduce them exactly, because it CAN: nine equations, nine unknowns, no room left for a residual.

The values below are deliberately biased (every voltage is 0.004 pu too high, every injection 0.9 MW off). Watch $J$ anyway.

# uses: build_net (warm-up cell); truth (The study network)
@isdefined(truth) || error("Run the section \"The study network\" first: it sets up truth.")
names = ["H1", "H2", "L1", "L2", "L3"]
minimal = Measurement[]
for (i, b) in enumerate(names)
  addVmMeasurement!(minimal; net = truth, busName = b, value = getNodeVm(truth.nodeVec[i]) + 0.004, sigma = 1e-3)
end
for (i, b) in enumerate(names)
  i == 1 && continue                          ## the slack injection is free
  load_p = truth.nodeVec[i]._pƩLoad === nothing ? 0.0 : truth.nodeVec[i]._pƩLoad
  addPinjMeasurement!(minimal; net = truth, busName = b, value = -load_p + 0.9, sigma = 1.0)
end

res_min = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(build_net(), minimal)
end
@printf("exactly determined set: %d measurements, %d states\n", length(minimal), 2 * length(truth.nodeVec) - 1)
@printf("SE quality: J = %.6f, dof = %d\n", res_min.objectiveJ, res_min.dof)
exactly determined set: 9 measurements, 9 states
SE quality: J = 0.000000, dof = 0

\[J = 0\]

with garbage input. This is the single most misread number in state estimation: $J$ measures the CONTRADICTION between measurements, and without redundancy there is nothing to contradict. A set with dof = 0 always fits perfectly, no matter how wrong it is.

Adding the reactive injections gives the estimator something to compare:

# uses: build_net (warm-up cell); minimal, names (Example 1); truth (The study network, Example 1)
(@isdefined(minimal) && @isdefined(names)) || error("Run Example 1 first: it sets up minimal, names.")
@isdefined(truth) || error("Run the section \"The study network\", Example 1 first: they set up truth.")
redundant = deepcopy(minimal)
for (i, b) in enumerate(names)
  i == 1 && continue
  load_q = truth.nodeVec[i]._qƩLoad === nothing ? 0.0 : truth.nodeVec[i]._qƩLoad
  addQinjMeasurement!(redundant; net = truth, busName = b, value = -load_q + 0.7, sigma = 1.0)
end
res_red = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(build_net(), redundant)
end
@printf("redundant set (%d Qinj rows added): %d measurements, %d states\n",
        length(redundant) - length(minimal), length(redundant), 2 * length(truth.nodeVec) - 1)
@printf("SE quality: J = %.3f, dof = %d, J/dof = %.3f\n", res_red.objectiveJ, res_red.dof, res_red.objectiveJ / res_red.dof)
redundant set (4 Qinj rows added): 13 measurements, 9 states
SE quality: J = 1.249, dof = 4, J/dof = 0.312

Reading aid: only now is $J$ a statement about the data. The rule of thumb $J/\mathrm{dof} \approx 1$ needs a denominator, and the denominator is redundancy you have to pay for with measurements.

What each measurement buys

Example 2. Starting from the exactly determined core, one row is added at a time. Two columns matter: J/dof, the statistical health, and the last one, the largest deviation of the estimated voltage magnitude from the truth (a number only this notebook can compute, because only here the truth is known).

# uses: build_net (warm-up cell); full_set, vm_true (The study network)
(@isdefined(full_set) && @isdefined(vm_true)) || error("Run the section \"The study network\" first: it sets up full_set, vm_true.")
core = filter(m -> startswith(m.id, "Vm_") || startswith(m.id, "Pinj_"), deepcopy(full_set))
extra = filter(m -> !(startswith(m.id, "Vm_") || startswith(m.id, "Pinj_")), deepcopy(full_set))
growing = deepcopy(core)
println("SE quality and largest voltage error against the truth, one row added per line (m = measurements):")
println(rpad("row added", 20), "   m  dof        J   J/dof   max |V_est - V_true| [pu]")
for step in 0:6
  step > 0 && push!(growing, extra[step])
  net = build_net()
  res = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
    runse!(net, deepcopy(growing))
  end
  err = maximum(abs.([getNodeVm(n) for n in net.nodeVec] .- vm_true))
  @printf("%-20s  %2d  %3d  %7.3f  %6.3f   %.2e\n",
          step == 0 ? "(core: Vm, Pinj)" : extra[step].id, length(growing), res.dof, res.objectiveJ,
          res.dof > 0 ? res.objectiveJ / res.dof : NaN, err)
end
SE quality and largest voltage error against the truth, one row added per line (m = measurements):
row added              m  dof        J   J/dof   max |V_est - V_true| [pu]
(core: Vm, Pinj)      10    1    0.846   0.846   2.28e-03
Qinj_bus_1            11    2    0.965   0.482   2.17e-03
Qinj_bus_2            12    3    5.466   1.822   1.45e-03
Qinj_bus_3            13    4   11.125   2.781   1.93e-04
Qinj_bus_4            14    5   11.144   2.229   2.12e-04
Qinj_bus_5            15    6   11.146   1.858   2.11e-04
Pflow_branch_1_from   16    7   12.594   1.799   2.27e-04

Reading aid: the accuracy jump comes with the THIRD reactive injection, where the error against the truth drops by an order of magnitude. After that the additional rows buy statistics, not accuracy. Note also how wildly J/dof swings while dof is small: with three degrees of freedom a factor of two is normal, which is why the band test uses the chi-square distribution instead of comparing against 1.

Example 3: the on-load tap changer

Now the model is wrong on purpose. In the true network T1's ratio changer stands four steps up; the estimator's model believes it is at neutral. Nothing else changes.

First, what that costs if the tap is NOT released:

# uses: build_net, truth_measurements (warm-up cell)
truth_oltc, meas_oltc = truth_measurements(ratio_step = 4.0)
res_blind = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(build_net(), deepcopy(meas_oltc))
end
@printf("T1 ratio tap not released: model at step %+d, truth at step %+d\n", 0, 4)
@printf("SE quality: J = %.1f, dof = %d, J inside its 3-sigma band: %s\n",
        res_blind.objectiveJ, res_blind.dof, res_blind.jWithin3Sigma)
T1 ratio tap not released: model at step +0, truth at step +4
SE quality: J = 1493.4, dof = 26, J inside its 3-sigma band: false

A four-step error on one transformer inflates $J$ by a factor of about fifty against the run with the tap released below. The band test fires, the residuals point everywhere at once, and no amount of bad-data elimination will help: the data is fine, the model is wrong.

setTapEstimation! releases the tap changer as an additional state: the step it stands at, counted from its neutral position. Mode :ratio releases the ratio changer only. tapEstimates holds one row per released changer:

# uses: build_net (warm-up cell); meas_oltc (Example 3)
@isdefined(meas_oltc) || error("Run Example 3 first: it sets up meas_oltc.")
model_oltc = build_net()
release = setTapEstimation!(model_oltc; trafo = 3, mode = :ratio)
t1_ratio_before = model_oltc.branchVec[3].tap_ratio
res_oltc = with_state_estimation_config(max_iter = 40, tol = 1e-6, update_taps = false) do
  runse!(model_oltc, deepcopy(meas_oltc))
end
est = only(res_oltc.tapEstimates)                 ## one row per released changer
# the model keeps its step unless update_taps writes the fixed one back
step_after = model_oltc.branchVec[3].tap_ratio == t1_ratio_before ? est.step_model : est.step_fixed
println("T1 ratio tap, position [steps, 0 = neutral]:")
@printf("  true value (used to generate measurements):  %+7.0f\n", 4.0)
@printf("  model before estimation:                     %+7.0f\n", est.step_model)
@printf("  estimated by SE (continuous):                %+7.3f   sigma_s = %.3f steps\n", est.s_est, est.sigma_s)
@printf("  fixed to the nearest step:                   %+7.0f   %.2f sigma_s from the estimate, out of range: %s\n",
        est.step_fixed, est.round_distance_sigma, est.out_of_range)
@printf("  model after run (update_taps = false):       %+7.0f   %s\n",
        step_after, step_after == est.step_model ? "unchanged" : "written back")
@printf("SE quality: J = %.2f, dof = %d\n", res_oltc.objectiveJ, res_oltc.dof)
[ Info: runse!: tap fixation J 31.79 (dof 25) -> J 31.89 (dof 26); notice: tap fixation changed J by 0.09467 (k = 1 step state(s) removed, 95 % quantile of chi2(1) = 3.841)
T1 ratio tap, position [steps, 0 = neutral]:
  true value (used to generate measurements):       +4
  model before estimation:                          +0
  estimated by SE (continuous):                 +4.033   sigma_s = 0.106 steps
  fixed to the nearest step:                        +4   0.31 sigma_s from the estimate, out of range: false
  model after run (update_taps = false):            +0   unchanged
SE quality: J = 31.89, dof = 26

The runse! info line above the result reports what the fixation cost: the free estimate fits marginally better than the grid position (it has one more degree of freedom to spend), and snapping to the mechanical step gives that degree of freedom back. The line puts the change of $J$ next to the 95 % quantile of $\chi^2(k)$, with $k$ the step states removed. A change far above it would be the signal that the data does NOT agree with any real tap position.

Reading aid: the estimator finds 4.03 steps and FIXES that to the nearest mechanical position, +4. The fixation is the point. A tap changer is a discrete device; an estimate of "4.03 steps" is not a physical answer, and reporting it as one would invite an operator to chase a position that does not exist. The continuous value stays visible next to it. Its uncertainty is sigma_s, the standard deviation of the step from the covariance of the estimate. The row field round_distance_sigma is the distance from the estimate to that step in units of sigma_s (0.31 above). A value well below 1 means the data agrees with position 4. A sigma_s of half a step or more means the data cannot tell 4 from 5. The model itself stays at step 0: update_taps (default false, set explicitly above) decides whether the fixed step is written back to the branch.

The main switch of the tap estimation is state_estimation.tap_estimation.enabled (the Web UI box "estimate taps"). Off, no changer becomes a state, even a released one: it keeps its transferred step, and its row says status = not_estimated, reason = disabled. The same block holds exclude (transformers that never become states), include_machine_transformers, fallback and impedance_correction. See State Estimation.

# uses: meas_oltc, model_oltc (Example 3)
(@isdefined(meas_oltc) && @isdefined(model_oltc)) || error("Run Example 3 first: it sets up meas_oltc, model_oltc.")
res_off = with_state_estimation_config(max_iter = 40, tol = 1e-6, tap_estimation = TapEstimationConfig(enabled = false)) do
  runse!(model_oltc, deepcopy(meas_oltc))
end
est_off = only(res_off.tapEstimates)
@printf("tap estimation switched off, T1 ratio tap at its model step %+.0f: status %s, reason %s\n",
        est_off.step_model, est_off.status, est_off.reason)
@printf("SE quality: J = %.1f, dof = %d\n", res_off.objectiveJ, res_off.dof)
tap estimation switched off, T1 ratio tap at its model step +0: status not_estimated, reason disabled
SE quality: J = 1493.4, dof = 26

Example 4: the phase shifter

The same transformer, the same procedure, the other changer. In the true network the phase tap stands three steps out; the model believes neutral. Mode :pst releases the phase changer. T1's phase changer is declared in degrees (1.25° per step), so its row says linear: each step adds the same angle. A phase changer declared as an additional voltage per step also has a direction alpha. That comes from the nameplate or the import and is never estimated; setTapEstimation! accepts alpha_deg only as a check against it.

# uses: build_net, truth_measurements (warm-up cell)
truth_pst, meas_pst = truth_measurements(phase_step = 3.0, seed = 11)
model_pst = build_net()
setTapEstimation!(model_pst; trafo = 3, mode = :pst)
res_pst = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_pst, deepcopy(meas_pst))
end
est_pst = only(res_pst.tapEstimates)
@printf("T1 phase tap (%s), position [steps, 0 = neutral]:\n", est_pst.kind)
@printf("  true value (used to generate measurements):  %+7.0f\n", 3.0)
@printf("  model before estimation:                     %+7.0f\n", est_pst.step_model)
@printf("  estimated by SE (continuous):                %+7.3f\n", est_pst.s_est)
@printf("  fixed to the nearest step:                   %+7.0f\n", est_pst.step_fixed)
@printf("SE quality: J = %.2f, dof = %d\n", res_pst.objectiveJ, res_pst.dof)
[ Info: runse!: tap fixation J 31.71 (dof 25) -> J 31.91 (dof 26); notice: tap fixation changed J by 0.1989 (k = 1 step state(s) removed, 95 % quantile of chi2(1) = 3.841)
T1 phase tap (linear), position [steps, 0 = neutral]:
  true value (used to generate measurements):       +3
  model before estimation:                          +0
  estimated by SE (continuous):                 +3.015
  fixed to the nearest step:                        +3
SE quality: J = 31.91, dof = 26

Example 5: both changers at once

A transformer that regulates voltage AND angle carries two changers on one winding. Mode :both releases both, one step state each. The ratio changer scales the magnitude of the branch ratio, the phase changer adds its angle; the estimator evaluates the branch ratio from both steps together, so each row reports its own step.

The true network now has the ratio changer two steps DOWN and the phase changer two steps up, an ambiguous-looking combination the estimator has to separate:

# uses: build_net, truth_measurements (warm-up cell)
truth_both, meas_both = truth_measurements(ratio_step = -2.0, phase_step = 2.0, seed = 13)
model_both = build_net()
setTapEstimation!(model_both; trafo = 3, mode = :both)
res_both = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_both, deepcopy(meas_both))
end
est_ratio = only(filter(r -> r.role === :ratio, res_both.tapEstimates))
est_phase = only(filter(r -> r.role === :phase, res_both.tapEstimates))
println("T1 changer positions [steps, 0 = neutral]:")
println("  changer   true   model before   estimated by SE   fixed to")
for (row, truth_step) in ((est_ratio, -2.0), (est_phase, 2.0))
  @printf("  %-7s  %+5.0f  %+13.0f  %+16.3f  %+9.0f\n", row.role, truth_step, row.step_model, row.s_est, row.step_fixed)
end
@printf("SE quality: J = %.2f, dof = %d\n", res_both.objectiveJ, res_both.dof)
[ Info: runse!: tap fixation J 23.02 (dof 24) -> J 25.65 (dof 26); notice: tap fixation changed J by 2.63 (k = 2 step state(s) removed, 95 % quantile of chi2(2) = 5.991)
T1 changer positions [steps, 0 = neutral]:
  changer   true   model before   estimated by SE   fixed to
  ratio       -2             +0            -1.939         -2
  phase       +2             +0            +1.948         +2
SE quality: J = 25.65, dof = 26

Reading aid: both positions come back within 0.1 steps of the truth. They are separable because they act differently: the ratio changer moves the voltage magnitude across the transformer, the phase changer moves the active flow through the loop. Without a loop, as on a radial transformer, the flows no longer pin the tap, which is the subject of the next example.

Example 6: the tap that cannot be estimated

T3 feeds a radial station. Its tap changes the voltage behind it, and nothing else. If no measurement sits behind that transformer, the tap and the unknown downstream voltage are the SAME unknown: any tap position can be compensated by a voltage, and the estimator would happily return one of infinitely many solutions.

Here the true T3 stands three steps up, and the voltage measurement at L3 is removed from the set (the station has no voltage transducer):

# uses: build_net (warm-up cell)
truth_bridge = build_net()
applyTapNameplate!(truth_bridge.branchVec[5]; tap_step = 0.0125, tap_min_step = -8.0, tap_max_step = 8.0, tap_current_step = 3.0)
runpf!(truth_bridge, 40, 1e-10, 0)
calcNetLosses!(truth_bridge)
std_bridge = measurementStdDevs(vm = 1e-3, pinj = 1.0, qinj = 1.0, pflow = 0.7, qflow = 0.7)
meas_bridge = generateMeasurementsFromPF(
  truth_bridge;
  includeVm = true, includePinj = true, includeQinj = true, includePflow = true, includeQflow = true,
  noise = true, stddev = std_bridge, rng = MersenneTwister(5),
)
filter!(m -> m.id != "Vm_bus_5", meas_bridge)   ## L3 is bus 5: no voltage behind T3

model_bridge = build_net()
setTapEstimation!(model_bridge; trafo = 5, mode = :ratio)
res_bridge = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_bridge, meas_bridge)
end
est_bridge = only(res_bridge.tapEstimates)
println("T3 ratio tap (radial, no voltage measurement at L3), position [steps, 0 = neutral]:")
@printf("  true value (used to generate measurements):  %+7.0f\n", 3.0)
@printf("  model before estimation:                     %+7.0f\n", est_bridge.step_model)
@printf("  SE result:                                   %+7.0f   status %s, reason %s\n",
        est_bridge.step_fixed, est_bridge.status, est_bridge.reason)
@printf("SE quality: J = %.2f, dof = %d\n", res_bridge.objectiveJ, res_bridge.dof)
println("notice: ", est_bridge.notice)
[ Info: runse!: 1 tap regulator(s) frozen, see tapEstimates[].notice
T3 ratio tap (radial, no voltage measurement at L3), position [steps, 0 = neutral]:
  true value (used to generate measurements):       +3
  model before estimation:                          +0
  SE result:                                        +0   status not_estimated, reason radial_no_voltage_pin
SE quality: J = 21.77, dof = 25
notice: not estimated (rank test): bridge transformer without a voltage measurement on its cut-off side, the tap would absorb the downstream voltage; voltage hint: measured minus estimated |V| at L2 -0.00015 pu

Reading aid: the estimator does NOT return 3, and it does not return a random number either. It FREEZES the released tap at its declared position and says why: the row carries status not_estimated with the reason radial_no_voltage_pin and the notice printed above, and runse! logs that a regulator was frozen. $J$ stays healthy, because nothing in the data contradicts the model: the missing measurement is exactly the information that would have exposed the error.

This is the most important slide of the chapter. A released tap that comes back at its declared position is not a confirmation. Check whether it was estimated at all, and whether the loop or the voltage measurement that makes it observable actually exists.

Example 7: what current magnitudes can and cannot do

A current magnitude is the cheapest measurement in the substation and the most common one in older telemetry. It also carries no direction and linearizes badly near zero. Sparlectra treats it as an AUXILIARY measurement, and the observability check says so outright: it evaluates the system WITHOUT current magnitudes, because a system that is observable only through them is not observable in the sense the estimator needs.

First, what they add to a complete set:

# uses: build_net, truth_measurements (warm-up cell); full_set (The study network)
@isdefined(full_set) || error("Run the section \"The study network\" first: it sets up full_set.")
_, with_currents = truth_measurements(seed = 3, includeImag = true)
net_plain = build_net(); res_plain = with_state_estimation_config(() -> runse!(net_plain, deepcopy(full_set)); max_iter = 40, tol = 1e-6)
net_curr = build_net(); res_curr = with_state_estimation_config(() -> runse!(net_curr, deepcopy(with_currents)); max_iter = 40, tol = 1e-6)
dvm = maximum(abs.([getNodeVm(n) for n in net_plain.nodeVec] .- [getNodeVm(n) for n in net_curr.nodeVec]))
println("complete set, without and with current magnitudes:")
println("  set                measurements   J/dof")
@printf("  without currents   %12d   %5.3f\n", length(full_set), res_plain.objectiveJ / res_plain.dof)
@printf("  with currents      %12d   %5.3f\n", length(with_currents), res_curr.objectiveJ / res_curr.dof)
@printf("largest change of the estimated |V| between the two runs: %.1e pu\n", dvm)
complete set, without and with current magnitudes:
  set                measurements   J/dof
  without currents             35   1.293
  with currents                45   1.114
largest change of the estimated |V| between the two runs: 1.8e-04 pu

Ten extra rows, and the state barely moves. Where the power flows are already measured, currents are redundancy, not information.

Now take the flow measurements off one line and see what is left. The sparse set has no P/Q on the 20 kV tie; the second set adds the current magnitudes of all five branches, the two of the tie included:

# uses: build_net (warm-up cell); full_set, vm_true (The study network); with_currents (Example 7)
(@isdefined(full_set) && @isdefined(vm_true)) || error("Run the section \"The study network\" first: it sets up full_set, vm_true.")
@isdefined(with_currents) || error("Run Example 7 first: it sets up with_currents.")
sparse_set = filter(m -> !occursin("branch_2", m.id), deepcopy(full_set))
net_sparse = build_net(); append!(net_sparse.measurements, deepcopy(sparse_set))
obs_sparse = with_state_estimation_config(flatstart = true, jac_eps = 1e-6) do
  evaluate_global_observability(net_sparse)
end
res_sparse = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(net_sparse)
end
err_sparse = maximum(abs.([getNodeVm(n) for n in net_sparse.nodeVec] .- vm_true))

sparse_curr = filter(m -> !occursin("branch_2", m.id) || startswith(m.id, "Imag"), deepcopy(with_currents))
net_sc = build_net(); append!(net_sc.measurements, deepcopy(sparse_curr))
obs_sc = with_state_estimation_config(flatstart = true, jac_eps = 1e-6) do
  evaluate_global_observability(net_sc)
end
res_sc = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(net_sc)
end
err_sc = maximum(abs.([getNodeVm(n) for n in net_sc.nodeVec] .- vm_true))

println("no P/Q flow rows on the 20 kV tie L1-L2:")
println("  set                    measurements   observability   dof   max |V_est - V_true| [pu]")
@printf("  without currents       %12d   %-13s   %3d   %.2e\n", length(sparse_set), obs_sparse.quality, res_sparse.dof, err_sparse)
@printf("  with all currents      %12d   %-13s   %3d   %.2e\n", length(sparse_curr), obs_sc.quality, res_sc.dof, err_sc)
no P/Q flow rows on the 20 kV tie L1-L2:
  set                    measurements   observability   dof   max |V_est - V_true| [pu]
  without currents                 31   good             22   2.76e-04
  with all currents                41   good             32   1.47e-04

Reading aid, and this is the "for and against" in two numbers: the currents do NOT change the observability verdict (they are excluded from it by construction), but they nearly halve the error against the truth. That is the honest case for cheap current telemetry: it improves an estimate that already stands on its own, and it cannot carry one that does not.

The missing direction is what a PMU adds. addCurrentPhasorMeasurement! contributes the magnitude AND the angle of a branch current, and the angle turns an amount into a flow with a sign.

Example 8: PMU phasors and the reference offset

A PMU reports voltage angles against ITS time base, and that base is not the estimator's slack reference. The difference is a constant offset over all PMU channels. Subtracting a guess would bias every angle; ignoring it would corrupt the state. Sparlectra solves for it: with pmu_ref_offset: auto (the default) the offset becomes an extra state whenever voltage angles are present.

The set below carries PMU angles at H2 and L1, deliberately shifted by 4 degrees against the slack reference:

# uses: build_net, truth_measurements (warm-up cell)
_, pmu_set = truth_measurements(
  seed = 21, includeVa = true, vaBusIdxs = [2, 3], vaRefOffsetDeg = 4.0,
)
res_pmu = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(build_net(), pmu_set)
end
println("reference offset of the PMU angles at H2 and L1 [deg]:")
@printf("  true value (added to the PMU angles):  %+7.3f\n", 4.0)
@printf("  estimated by SE:                       %+7.3f\n", res_pmu.vaRefOffsetDeg === nothing ? NaN : res_pmu.vaRefOffsetDeg)
@printf("SE quality: J = %.2f, dof = %d (%d measurements)\n", res_pmu.objectiveJ, res_pmu.dof, length(pmu_set))
reference offset of the PMU angles at H2 and L1 [deg]:
  true value (added to the PMU angles):   +4.000
  estimated by SE:                        +3.996
SE quality: J = 40.03, dof = 27 (37 measurements)

Reading aid: the offset comes back as 4.0°, and the state is unaffected by it. The cost is one degree of freedom, which is the cheapest possible price for not having to trust a time synchronisation you cannot verify.

Example 9: when the model, not the data, is wrong

A breaker was opened in the field and the status never reached the model. The estimator now believes in a line that carries nothing. The bay's transducers report what they see, about zero, on all four rows. The model carries its own power flow, solved on the wrong topology, as an EMS model does.

# uses: build_net (warm-up cell)
truth_topo = build_net()
for br in (truth_topo.branchVec[2],)                 ## the 20 kV tie is really open
  br.status = 0
  br.from_status = 0
  br.to_status = 0
end
runpf!(truth_topo, 40, 1e-10, 0)
calcNetLosses!(truth_topo)
std_topo = measurementStdDevs(vm = 1e-3, pinj = 1.0, qinj = 1.0, pflow = 0.7, qflow = 0.7)
meas_topo = generateMeasurementsFromPF(
  truth_topo;
  includeVm = true, includePinj = true, includeQinj = true, includePflow = true, includeQflow = true,
  noise = true, stddev = std_topo, rng = MersenneTwister(31),
)
model_topo = build_net()                             ## the model still has it closed
for (dir, val) in ((:from, 0.05), (:to, -0.04))
  addPflowMeasurement!(meas_topo; net = model_topo, fromBus = "L1", toBus = "L2", value = val, sigma = 0.7, direction = dir)
  addQflowMeasurement!(meas_topo; net = model_topo, fromBus = "L1", toBus = "L2", value = val / 3, sigma = 0.7, direction = dir)
end

# the model's own power flow: it gives the pre-check the flow the model
# expects on the tie (a flat start expects none and gives no verdict)
runpf!(model_topo, 40, 1e-10, 0)
pre = validate_topology(model_topo, meas_topo)
for f in pre.findings
  println("pre-check: ", f.kind, " at ", f.location, " (", f.severity, "): ", f.evidence)
end
res_topo = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_topo, meas_topo)
end
@printf("tie closed in the model (wrong):   SE quality J = %.1f, dof = %d, J inside its 3-sigma band: %s\n",
        res_topo.objectiveJ, res_topo.dof, res_topo.jWithin3Sigma)

model_fixed = build_net()
for br in (model_fixed.branchVec[2],)
  br.status = 0
  br.from_status = 0
  br.to_status = 0
end
res_fixed = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_fixed, deepcopy(meas_topo))
end
@printf("tie open in the model (corrected): SE quality J = %.1f, dof = %d, J inside its 3-sigma band: %s\n",
        res_fixed.objectiveJ, res_fixed.dof, res_fixed.jWithin3Sigma)
pre-check: closed_element_without_flow at branch 2 (L1-L2, closed) (warning): 4 flow/current row(s) all below 3.0 sigma while the model state expects Pflow_branch_2_from = 5.741 (8.2 sigma)
┌ Warning: runse!: topology precheck reported 1 finding(s) (advisory, the estimation proceeds)
│   findings = "closed_element_without_flow at branch 2 (L1-L2, closed) (4 flow/current row(s) all below 3.0 sigma while the model state expects Pflow_branch_2_from = 5.741 (8.2 sigma), warning)"
└ @ Sparlectra ~/work/Sparlectra.jl/Sparlectra.jl/src/stateestimation/state_estimation.jl:5186
tie closed in the model (wrong):   SE quality J = 658.6, dof = 26, J inside its 3-sigma band: false
tie open in the model (corrected): SE quality J = 11.7, dof = 26, J inside its 3-sigma band: true

Reading aid: the pre-check names the element and the evidence BEFORE the estimation runs: the tie L1-L2 is closed in the model, its power flow expects about 5.7 MW on it, and all four rows read near zero. runse! runs the same pre-check and repeats the finding as a warning above its result. Without the model's power flow (a flat start) the check expects no flow anywhere and gives no verdict. The estimation still runs. That is deliberate: the findings are advisory, and Sparlectra never switches an element by itself. A topology error looks like bad data in the residuals, so a sequential elimination would happily throw away four healthy measurements, one after another, and never fix the cause. The correction belongs to the operator, and the evidence is there to support it.

Example 10: island-wise estimation

Open the coupler and the tie, and the substation becomes two networks with one feed each. There is no such thing as a common angle reference across them: the estimator partitions the measurement set by AC island and gives each island its own reference.

# uses: build_net (warm-up cell)
iso = build_net()
addProsumer!(net = iso, busName = "H2", type = "EXTERNALNETWORKINJECTION", referencePri = "H2", vm_pu = 1.015, va_deg = 0.0)
for b in (1, 2)                                      ## coupler and tie open
  iso.branchVec[b].status = 0
  iso.branchVec[b].from_status = 0
  iso.branchVec[b].to_status = 0
end
validate!(net = iso)
runpf!(iso, 40, 1e-10, 0; islands_enabled = true)
calcNetLosses!(iso)
std_iso = measurementStdDevs(vm = 1e-3, pinj = 1.0, qinj = 1.0, pflow = 0.7, qflow = 0.7)
meas_iso = generateMeasurementsFromPF(
  iso;
  includeVm = true, includePinj = true, includeQinj = true, includePflow = true, includeQflow = true,
  noise = true, stddev = std_iso, rng = MersenneTwister(41),
)

model_iso = build_net()
addProsumer!(net = model_iso, busName = "H2", type = "EXTERNALNETWORKINJECTION", referencePri = "H2", vm_pu = 1.015, va_deg = 0.0)
for b in (1, 2)
  model_iso.branchVec[b].status = 0
  model_iso.branchVec[b].from_status = 0
  model_iso.branchVec[b].to_status = 0
end
validate!(net = model_iso)
res_iso = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(model_iso, meas_iso)
end
println("SE quality per AC island:")
println("  island  buses  converged        J  dof  J band")
for isl in res_iso.islands
  @printf("  %6d  %5d  %-9s  %7.3f  %3d  %s\n", isl.island, isl.n_bus, isl.converged, isl.objectiveJ, isl.dof, isl.band_reason)
end
@printf("  %6s  %5d  %-9s  %7.3f  %3d\n", "total", sum(isl.n_bus for isl in res_iso.islands), "", res_iso.objectiveJ, res_iso.dof)
SE quality per AC island:
  island  buses  converged        J  dof  J band
       1      2  true         5.985    7  ok
       2      3  true         5.077   12  ok
   total      5              11.062   19

Reading aid: the totals are sums over the islands, and each island carries its own verdict. That matters when one island is well measured and the other is not: a single global $J$ would average the two and hide the weak one.

Example 11: J and J_active

The last number of the chapter. One flow measurement is off by 25 MW, far outside anything noise explains.

# uses: build_net (warm-up cell); full_set (The study network)
@isdefined(full_set) || error("Run the section \"The study network\" first: it sets up full_set.")
bad_set = deepcopy(full_set)
k = findfirst(m -> m.id == "Pflow_branch_1_from", bad_set)
bad_set[k] = Measurement(
  typ = bad_set[k].typ, value = bad_set[k].value + 25.0, sigma = bad_set[k].sigma,
  branchIdx = bad_set[k].branchIdx, direction = bad_set[k].direction, id = bad_set[k].id,
)
res_bad = with_state_estimation_config(max_iter = 40, tol = 1e-6) do
  runse!(build_net(), deepcopy(bad_set))
end
@printf("plain WLS, P flow H1-H2 at H1 off by %+.0f MW: SE quality J = %.1f, dof = %d, J inside its 3-sigma band: %s\n",
        bad_set[k].value - full_set[k].value, res_bad.objectiveJ, res_bad.dof, res_bad.jWithin3Sigma)
┌ Warning: runse!: topology precheck reported 1 finding(s) (advisory, the estimation proceeds)
│   findings = "kcl_violation at bus H1 (P balance misses by 23.58 (16.8 sigma, 2 measured branches), strong)"
└ @ Sparlectra ~/work/Sparlectra.jl/Sparlectra.jl/src/stateestimation/state_estimation.jl:5186
plain WLS, P flow H1-H2 at H1 off by +25 MW: SE quality J = 922.0, dof = 26, J inside its 3-sigma band: false

In replacement mode the estimator keeps the row in the set but pins it to a large sigma during the solve, the way an EMS suppression list does. The statistics stay on the ORIGINAL sigma, so the alarm does not go away:

# uses: build_net (warm-up cell); bad_set (Example 11)
@isdefined(bad_set) || error("Run Example 11 first: it sets up bad_set.")
res_repl = with_state_estimation_config(robust_mode = :replacement, k_suppress = 4.0, suppression_sigma = 2000.0) do
  runse!(build_net(), deepcopy(bad_set))
end
act = res_repl.activeObjective
println("replacement mode:")
@printf("  J over all rows, original sigma (honest):   %8.2f, dof = %d\n", res_repl.objectiveJ, res_repl.dof)
@printf("  J_active over the rows the solve trusted:   %8.2f, dof = %d\n", act.j, act.dof)
@printf("  rows suppressed:                            %5d\n", act.suppressed)
┌ Warning: runse!: topology precheck reported 1 finding(s) (advisory, the estimation proceeds)
│   findings = "kcl_violation at bus H1 (P balance misses by 23.58 (16.8 sigma, 2 measured branches), strong)"
└ @ Sparlectra ~/work/Sparlectra.jl/Sparlectra.jl/src/stateestimation/state_estimation.jl:5186
[ Info: state estimation: down-weighting 6 of 35 eligible row(s) (normalized residual >= 4.0, largest 29.84)
[ Info: state estimation: down-weighting 3 of 35 eligible row(s) (normalized residual >= 4.0, largest 42.99)
[ Info: state estimation: down-weighting 1 of 35 eligible row(s) (normalized residual >= 4.0, largest 40.05)
replacement mode:
  J over all rows, original sigma (honest):    1193.83, dof = 26
  J_active over the rows the solve trusted:      31.59, dof = 25
  rows suppressed:                                1

Note the warning above both runs: the topology pre-check flags a KCL violation at H1, because a 25 MW error on one branch flow does not balance against the injections either. A gross measurement error and a wrong breaker status look similar from the outside, which is precisely why the pre-check reports and never switches.

The three down-weighting info lines come from the replacement mode itself. It runs up to three rounds; each round takes the residuals of the current state and picks anew every row at or above k_suppress. On the plain WLS state, bent by the bad row, six rows pass that limit; in the second round three, in the third one row (rows suppressed 1).

Reading aid: two numbers, two jobs. $J$ answers "is my data healthy?" and must stay loud, because a suppressed row is still a broken transducer somebody has to fix. $J_\mathrm{active}$ answers "how well does the state fit what I actually trusted?" and is the number to judge the ESTIMATE by. Reporting only the second one would turn a suppression list into a way of making alarms disappear, which is exactly how EMS suppression lists go bad in practice.

J is too large. What now?

The sections above are the four branches of one decision:

SymptomLikely causeWhat to do
A few rows carry large normalized residuals, the rest are cleanMeasurement errorBad-data localization and elimination, see the diagnostics chapter
Residuals are large across a whole area, elimination removes healthy rows without curing $J$Model error: a tap or a shuntRelease the parameter (setTapEstimation!, setShuntEstimation!) and check whether $J$ drops
Flow rows near zero on an element the model believes is in service, or flow on one it believes is openTopology errorRead validate_topology, correct the status, never let the estimator switch it
$J$ is small or zero and everything looks perfectToo few measurementsCheck dof: at zero there is nothing to check, and a released tap may have been frozen

The order matters. Topology first (it corrupts everything downstream), then model parameters, then individual measurements. Eliminating rows before checking the model is the most common way to arrive at a beautifully converged estimate of a network that does not exist.

Where to go next