---
title: State estimation
heading: Redundant meters with random errors, the weighted least-squares estimate and its gain matrix, the chi-square test that tells a good set of measurements from a bad one, normalized residuals that point to the bad meter, observability, and a Python estimator
eyebrow: S10 · Lesson 31 · State estimation
xp: 60
---

::: hook
A control room receives tens of thousands of measurements every few seconds: line flows, injections and voltages, sent over telemetry from meters with ordinary errors, plus the occasional gross one when a transducer fails or a breaker status is wrong. A power flow can't use them directly. It takes exactly one input per unknown, it has no place for the extra flow measurements, and a single bad input spoils its answer. What does the control room actually know about the state of its system, and how sure is it?
:::

::: play
- The three-bus DC network of lesson 20 (lines 0.1, 0.2 and 0.25 pu) has five meters: the flows on lines 1–2, 1–3 and 2–3 (σ = 0.01 pu) and the injections at buses 2 and 3 (σ = 0.02 pu). The unknowns are the two bus angles.
- The x axis is the reading of the line 1–3 meter, with the other four fixed at good values. The curves are the weighted sum of squared residuals J and the line 1–3 meter's normalized residual.
- The estimate accepts readings that keep J below the chi-square threshold of 11.34 (3 degrees of freedom, 99%): roughly 0.63 to 0.72 pu. Outside that band the test flags bad data, and the normalized residual, above 3, points at the meter responsible.
:::

```sim plot
view: graph
x: z = 0.3..1.05 pu
y: J = 0..40
plot: 5555.56*(z - 0.675077)^2 + 0.0639 | samples: 400 | label: J
plot: 74.536*abs(z - 0.675077) | samples: 400 | color: ch3 | label: normalized residual, line 1–3
plot: 11.345 + 0*z | dashed | color: ch4 | label: chi-square threshold
plot: 3 + 0*z | dashed | color: ch3 | label: residual threshold
```

::: predict
## Two meters read the same flow: one with σ = 0.01 pu reads 0.80, the other with σ = 0.02 pu reads 0.85. What's the weighted least-squares estimate?

- [ ] 0.825, the average
- [x] 0.81
- [ ] 0.80, the better meter alone
- [ ] 0.833

::: reveal
Each reading is weighted by $1/\sigma^2$: weights 10,000 and 2,500, so the estimate is (10,000 × 0.80 + 2,500 × 0.85)/12,500 = 0.81. The better meter counts four times as much, but the other still contributes. A weight of $1/\sigma$ instead would give 0.8167.
:::
:::

::: nameit
## The measurement model

Collect the m measurements in z and the n unknowns (bus angles and voltage magnitudes) in x. Each measurement is a function of the state plus an error: $z = h(x) + e$. The errors are taken as independent, zero-mean Gaussians with variances $\sigma_i^2$. In the DC model h is linear, $z = Hx + e$; in the AC model H is the Jacobian of h and the solution iterates, just as Newton's power flow does.

## Weighted least squares

The estimate minimizes the weighted sum of squared residuals

$$J(x) = \sum_i \frac{(z_i - h_i(x))^2}{\sigma_i^2} = (z - Hx)^T W (z - Hx), \qquad W = \text{diag}(1/\sigma_i^2)$$

Setting its gradient to zero gives the normal equations and the estimate

$$\hat x = G^{-1}H^TWz, \qquad G = H^TWH$$

G is the **gain matrix**. Its inverse is the covariance of the estimate, so it tells how well each state is known. Each measurement's error spreads into every state through $G^{-1}H^TW$, which is why a gross error can hide in the estimate unless the residuals are tested.

## Is the estimate any good?

If the errors really are Gaussian with the assumed σ, the minimum $J(\hat x)$ follows a **chi-square distribution** with $m - n$ degrees of freedom. Its mean is $m - n$. The test compares J with the value that a chi-square variable exceeds only 1% (or 5%) of the time: for 3 degrees of freedom, 11.34 at 99%. A larger J says some measurement is far worse than its σ claims.

## Which meter is bad?

The residuals $r = z - H\hat x$ have covariance $\Omega = R - HG^{-1}H^T$, where $R = \text{diag}(\sigma_i^2)$. The **normalized residual** $|r_i|/\sqrt{\Omega_{ii}}$ is a standard normal variable for a good meter, so values above about 3 are suspicious, and the largest one usually marks the bad measurement. Remove it, estimate again, and test again.

## Observability and redundancy

The state can be estimated only if G is invertible: the system is **observable**. With exactly n well-placed measurements, J is always zero and nothing can be tested. Redundancy (m well above n, typically 1.5 to 2.5 times) is what makes bad data detectable. A **critical measurement**, one whose loss would make the system unobservable, always has a zero residual, so an error in it can never be detected.
:::

::: example
## Estimate the state of the three-bus network from readings 0.83, 0.67, 0.21, −0.62 and −0.88 pu (flows 1–2, 1–3, 2–3; injections at buses 2 and 3).

::: solution
1. **Measurement functions.** The flows are $-10\theta_2$, $-5\theta_3$ and $4\theta_2 - 4\theta_3$, and the injections $14\theta_2 - 4\theta_3$ and $-4\theta_2 + 9\theta_3$, which give H's rows.
2. **Gain matrix.** With weights 10,000 for the flows and 2,500 for the injections:
   $$G = \begin{pmatrix} 1{,}690{,}000 & -390{,}000 \\ -390{,}000 & 652{,}500 \end{pmatrix}$$
3. **Solve the normal equations.**
   $$\begin{aligned} \hat\theta_2 &= -0.08283\ \text{rad} \\ \hat\theta_3 &= -0.13456\ \text{rad} \end{aligned}$$
4. **Residuals.** The estimated flows are 0.828, 0.673 and 0.207 pu, and the residuals are all a fraction of their σ.
5. **Test J.** J = 0.21, far below the 11.34 threshold for 5 − 2 = 3 degrees of freedom, so the set is accepted.
6. **Compare with the truth.** The true angles, from the loads of 0.6 and 0.9 pu, are −0.08182 and −0.13636: the estimate is within 0.002 rad.

**Answer:** $\hat\theta_2$ = −0.08283 and $\hat\theta_3$ = −0.13456 rad, and J = 0.21 passes the test.
:::
:::

::: example
## The line 1–3 meter's reading is corrupted to 0.50 pu. What do the test and the residuals show?

::: solution
1. **The shifted estimate.** The estimate shifts to −0.0793 and −0.1195 rad: the bad reading has dragged both angles.
2. **Test J.** J rises to 170, far above 11.34, so the set is rejected.
3. **Normalized residuals.** They are 6.5, 13.0, 5.8, 0.8 and 7.4.
4. **Find the bad meter.** Several exceed 3, because the error has spread through the estimate into the other residuals, but the largest, 13.0, belongs to the line 1–3 meter.
5. **Remove it and estimate again.** From the remaining four, J = 0.06, well below the threshold for 2 degrees of freedom (9.21), and the angles are −0.0829 and −0.1350 rad, back near the true values.

**Answer:** J = 170 rejects the set, and the largest normalized residual, 13.0, points to the line 1–3 meter.
:::
:::

::: example
## Three meters read the same flow: 1.00 (σ = 0.01), 1.03 (σ = 0.02) and 0.95 pu (σ = 0.04). Find the WLS estimate, its standard deviation and J, and test J at 95%.

::: solution
1. **Weights.** They are 10 000, 2500 and 625, one over each σ squared.
2. **Estimate.**
   $$\begin{aligned} \hat x &= (10\,000 \times 1.00 \\ &\quad + 2500 \times 1.03 \\ &\quad + 625 \times 0.95)/13\,125 \\ &= 1.0033\ \text{pu} \end{aligned}$$
3. **Its standard deviation.**
   $$\begin{aligned} \sigma &= 1/\sqrt{13\,125} \\ &= 0.0087\ \text{pu} \end{aligned}$$
4. **Weighted squared residuals.**
   $$\begin{aligned} J &= 0.11 + 1.78 + 1.78 \\ &= 3.67 \end{aligned}$$
5. **Test at 95%.** With 3 − 1 = 2 degrees of freedom the 95% threshold is 5.99, so no bad data is flagged; the precise meter dominates the estimate.

**Answer:** $\hat x$ = 1.0033 pu with σ = 0.0087 pu, and J = 3.67 is under the 5.99 threshold, so no bad data is flagged.
:::
:::

::: check
given: a = 0.78 | 0.8 | 0.82; b = 0.84 | 0.86 | 0.9; s = 0.01 | 0.015; t = 0.02 | 0.03 | 0.05
answer: (a/s^2 + b/t^2)/(1/s^2 + 1/t^2)
tolerance: 0.1%

## Meter A (σ = {s} pu) reads {a} and meter B (σ = {t} pu) reads {b} for the same flow. What's the weighted least-squares estimate, in per unit?

::: right
Right. Weights $1/\sigma^2$ give {answer} pu.
:::

::: misses
- [(a + b)/2] Weight each reading by $1/\sigma^2$.
- [(a/s + b/t)/(1/s + 1/t)] The weights are $1/\sigma^2$, not $1/\sigma$.
- [any] Not yet. The weights are $1/\sigma^2$.
:::
:::

::: check
given: s = 0.01 | 0.02; t = 0.02 | 0.03 | 0.05
answer: 1/sqrt(1/s^2 + 1/t^2)
tolerance: 0.5%

## For those two meters (σ = {s} and {t} pu), what's the standard deviation of the estimate, in per unit?

::: right
Right. $G^{-1} = 1/(1/\sigma_1^2 + 1/\sigma_2^2)$ is the variance, so σ = {answer} pu: better than either meter.
:::

::: misses
- [1/(1/s^2 + 1/t^2)] That's the variance. Take its square root.
- [any] Not yet. The estimate's variance is the inverse of the gain, $1/\sum(1/\sigma_i^2)$.
:::
:::

::: check
given: m = 12 | 30 | 80; n = 5 | 9 | 23
answer: m - n
tolerance: 0

## An estimator has {m} measurements and {n} state variables. How many degrees of freedom does its chi-square test have?

::: right
Right. $m - n$ = {answer}, which is also the expected value of J when every meter is good.
:::

::: misses
- [m] Each estimated state uses up one degree of freedom.
- [any] Not yet. Measurements minus states.
:::
:::

::: check
given: r = 0.01 | 0.03 | 0.05; o = 0.006 | 0.008 | 0.012
answer: r/o
tolerance: 0.5%

## A residual is {r} pu and the residual's standard deviation $\sqrt{\Omega_{ii}}$ is {o} pu. What's its normalized residual?

::: right
Right. {answer}. Above about 3 the meter is suspect.
:::

::: misses
- [r/o^2] Divide by the standard deviation, not the variance.
- [any] Not yet. $|r_i|/\sqrt{\Omega_{ii}}$.
:::
:::

::: check
given: s = 0.01 | 0.015; g = 0.005 | 0.007 | 0.009
answer: sqrt(s^2 - g^2)
tolerance: 0.5%

## A meter has σ = {s} pu, and its row of $HG^{-1}H^T$ has diagonal entry {g}² pu². What's the standard deviation of its residual, in per unit?

::: right
Right. $\sqrt{\sigma^2 - (HG^{-1}H^T)_{ii}}$ = {answer} pu, smaller than σ because the estimate partly follows the meter.
:::

::: misses
- [s] The residual varies less than the meter, since the estimate partly follows it.
- [sqrt(s^2 + g^2)] Subtract: $\Omega = R - HG^{-1}H^T$.
- [any] Not yet. $\Omega_{ii} = \sigma_i^2 - (HG^{-1}H^T)_{ii}$.
:::
:::

::: check
given: e = 0.2 | 0.3 | 0.5; s = 0.01 | 0.02 | 0.04
answer: (e/s)^2
tolerance: 0.5%

## A reading is off from its estimate by {e} pu with σ = {s} pu. How much does that one residual add to J?

::: right
Right. $(r/\sigma)^2$ = {answer}.
:::

::: misses
- [e/s] Square it.
- [e^2/s] Divide by σ², not σ.
- [any] Not yet. Each term of J is $(r_i/\sigma_i)^2$.
:::
:::

::: check
kind: python

## Write the estimator: `wls(H, z, sigma)` returns the estimate, the residuals and J, and `find_bad(H, z, sigma)` returns the index of the meter to discard, or None when the set passes the 99% chi-square test.

```python starter
import numpy as np

# 99% points of the chi-square distribution, by degrees of freedom
CHI2_99 = {1: 6.635, 2: 9.210, 3: 11.345, 4: 13.277, 5: 15.086, 6: 16.812, 7: 18.475, 8: 20.090}

def wls(H, z, sigma):
    # H: m x n measurement matrix, z: m readings, sigma: m standard deviations.
    # Return (x, r, J): the weighted least-squares estimate, the residuals z - Hx,
    # and J = sum((r/sigma)**2).
    n = H.shape[1]
    return np.zeros(n), np.array(z, float), 0.0

def find_bad(H, z, sigma):
    # If J passes the test (J <= CHI2_99[m - n]) return None. Otherwise return the
    # index of the largest normalized residual |r_i|/sqrt(Omega_ii), where
    # Omega = diag(sigma**2) - H G^-1 H^T and G = H^T W H.
    return None

H = np.array([[-10, 0], [0, -5], [4, -4], [14, -4], [-4, 9]], float)
s = np.array([0.01, 0.01, 0.01, 0.02, 0.02])
print(wls(H, np.array([0.83, 0.67, 0.21, -0.62, -0.88]), s))
```

```python solution
import numpy as np

CHI2_99 = {1: 6.635, 2: 9.210, 3: 11.345, 4: 13.277, 5: 15.086, 6: 16.812, 7: 18.475, 8: 20.090}

def wls(H, z, sigma):
    sigma = np.asarray(sigma, float)
    W = np.diag(1/sigma**2)
    G = H.T @ W @ H
    x = np.linalg.solve(G, H.T @ W @ z)
    r = z - H @ x
    return x, r, float(np.sum((r/sigma)**2))

def find_bad(H, z, sigma):
    sigma = np.asarray(sigma, float)
    x, r, J = wls(H, z, sigma)
    m, n = H.shape
    if J <= CHI2_99[m - n]:
        return None
    W = np.diag(1/sigma**2)
    Ginv = np.linalg.inv(H.T @ W @ H)
    omega = sigma**2 - np.einsum('ij,jk,ik->i', H, Ginv, H)
    return int(np.argmax(np.abs(r)/np.sqrt(omega)))

H = np.array([[-10, 0], [0, -5], [4, -4], [14, -4], [-4, 9]], float)
s = np.array([0.01, 0.01, 0.01, 0.02, 0.02])
print(wls(H, np.array([0.83, 0.67, 0.21, -0.62, -0.88]), s))
```

```python tests
import numpy as np
H = np.array([[-10, 0], [0, -5], [4, -4], [14, -4], [-4, 9]], float)
s = np.array([0.01, 0.01, 0.01, 0.02, 0.02])
z = np.array([0.83, 0.67, 0.21, -0.62, -0.88])
W = np.diag(1/s**2)
want = np.linalg.solve(H.T @ W @ H, H.T @ W @ z)
x, r, J = wls(H, z, s)
assert np.allclose(x, want, atol=1e-9), f"The estimate should be about (−0.08283, −0.13456) rad; got {np.round(x, 5)}. Weight each reading by 1/σ²."
assert np.allclose(r, z - H @ want, atol=1e-9), "r should be the residuals z − H x̂."
assert abs(J - 0.2071) < 0.001, f"J should be about 0.207 for these readings; got {J:.4f}. J sums (r/σ)²."
assert find_bad(H, z, s) is None, "These readings pass the test (J = 0.21 against 11.345), so find_bad should return None."
zb = z.copy(); zb[1] = 0.50
assert find_bad(H, zb, s) == 1, f"With the line 1–3 reading at 0.50, J is about 170 and the largest normalized residual is meter 1's; got {find_bad(H, zb, s)}."
th = np.linalg.solve(np.array([[14.0, -4], [-4, 9]]), np.array([-0.6, -0.9]))
zt = H @ th
for k in range(5):
    zz = zt.copy(); zz[k] += 20*s[k]
    got = find_bad(H, zz, s)
    assert got == k, f"A 20σ error on meter {k} should be found at index {k}; got {got}. Normalize each residual by √Ω_ii, not by σ."
```

::: right
Right. Your estimator weights the meters, tests the whole set and points to the bad meter, including when the error has spread into the other residuals.
:::
:::

::: check
kind: parts
given: s = 0.01 | 0.02; a = 0.98 | 1.02; t = 0.03 | 0.05; b = 0.9 | 1.1

## Two meters read the same flow: {a} pu (σ = {s}) and {b} pu (σ = {t}).

::: part
answer: (a/s^2 + b/t^2)/(1/s^2 + 1/t^2)
tolerance: 0.5%

### What is the WLS estimate?

::: misses
- [(a + b)/2] Weight by inverse variance.
- [any] $\sum(z_i/\sigma_i^2)/\sum(1/\sigma_i^2)$.
:::
:::

::: part
answer: ((a - (a/s^2 + b/t^2)/(1/s^2 + 1/t^2))/s)^2 + ((b - (a/s^2 + b/t^2)/(1/s^2 + 1/t^2))/t)^2
tolerance: 1%

### What is J?

::: misses
- [any] The weighted sum of squared residuals.
:::
:::
:::

::: check
kind: derivation
vars: s = 0.005..0.1, t = 0.005..0.1, a = 0.5..1.5, b = 0.5..1.5

## Two meters of standard deviations s and t read a and b for the same quantity.

::: step
answer: (a/s^2 + b/t^2)/(1/s^2 + 1/t^2)

### What is the estimate?
:::

::: step
answer: 1/sqrt(1/s^2 + 1/t^2)

### What is its standard deviation?
:::

::: step
answer: (a - b)^2/(s^2 + t^2)

### What is J?
:::

::: right
Right. With two meters, J is the squared difference of the readings over the sum of their variances: a one-degree-of-freedom test.
:::
:::

::: explain
## Why does a state estimator need more measurements than unknowns, and why can't it find an error in a critical measurement?

::: model
With exactly as many independent measurements as unknowns, the estimate fits every reading perfectly, so every residual is zero whatever the errors are, and nothing can be tested. Extra measurements make the readings overdetermined: good meters then agree with each other within their σ, and a bad one leaves residuals that the chi-square test and the normalized residuals can see. A critical measurement is one the system can't do without; remove it and the state is unobservable. That means no other measurement checks it, so the estimate always bends to fit it exactly, its residual is always zero, and an error in it passes straight into the state undetected. Utilities place meters so that redundancy is high everywhere and critical measurements are rare.
:::
:::

::: practice

::: check
given: a = 0.5..1.5; b = 0.5..1.5; s = 0.005..0.03; t = 0.005..0.05
answer: (a/s^2 + b/t^2)/(1/s^2 + 1/t^2)
tolerance: 0.1%

## WLS estimate from {a} (σ = {s}) and {b} (σ = {t})?

::: misses
- [any] Weights $1/\sigma^2$.
:::
:::

::: check
given: r = 0.005..0.08; o = 0.003..0.02
answer: r/o
tolerance: 0.5%

## Normalized residual: r = {r}, $\sqrt{\Omega_{ii}}$ = {o}?

::: misses
- [any] $|r|/\sqrt{\Omega_{ii}}$.
:::
:::

::: check
given: m = 10..200 int; n = 3..9 int
answer: m - n
tolerance: 0

## Degrees of freedom for {m} measurements and {n} states?

::: misses
- [any] $m - n$.
:::
:::
:::
