Overview
Weeks 4 and 5 used single readings. A battery management system never sees its state of charge, and the control room never sees the true power of a feeder: Both estimate them from several imperfect measurements. This week combines measurements by their uncertainty and tracks a changing state with the Kalman filter [1]. It then estimates the feeders of the campus by weighted least squares, which also finds a faulty meter [2].
flowchart LR A["Combining measurements"] --> B["The Kalman filter"] B --> C["Kalman filter with matrices"] C --> D["State estimation"] D --> E["Bad data"] E --> S["The campus microgrid, stage 6"] S --> FT["In the field: The zero of a sensor"] FT --> H["Learning to estimate"]
Every method on this page is also written as Python code in the Colab notebook of the week. Its code is divided into numbered sections. Each orange box on this page names the section whose code carries out what the text above the box explains. The box says what to run and what to look at in that section, and its button opens the Colab notebook at that place. The virtual laboratories, the practice parts and the self-assessment of the week are in the interactive lab. Each blue box opens one part of the interactive lab. The part ends with a link back to its box on this page, and the Colab notebook is always opened from the orange boxes here.
Python step 6: Matrices and the Kalman filter
Python code in the Colab notebook, right after Section 0 (setup). Open the Colab notebook and run this step cell by cell: It consists of short pieces of Python code with their explanations, a quick check and three exercises. Topics: Vectors and matrices · Matrix products with @ · Transpose and inverse · A filter loop.
The step introduces vectors and matrices in NumPy [3]. It multiplies them with the operator @, transposes and inverts them, and it ends with a running mean, the simplest recursive filter. Students who have never programmed start with the start-here notebook of the course.
Weeks 1 to 5 built the balance, the dynamics, the modes, the measurements and the frequency control of the campus. The reserve of Week 3 relies on the state of charge of the battery, and the dispatch of Week 9 will rely on the power of every feeder.
This week turns noisy and biased readings into estimates that the controllers of the campus can trust.

Estimation: Combining noisy measurements
Two sensors of the same quantity never agree exactly. When their errors are independent and their standard deviations \(\sigma_A\) and \(\sigma_B\) are known, the best linear combination weighs each reading with the inverse of its variance [1]:
The combined standard deviation is always smaller than the smaller of the two. The second form already shows the idea of the Kalman filter: Start from one value and move a fraction \(K\) of the way toward the other.
→ These formulas with numbers, step by step: Lab Part B, calculator, step 1.
A worked example. The calibrated sensor of the library of Week 4 reads 21.4 °C with \(\sigma_A = 0.3\) K. The sensor of the thermostat reads 20.8 °C with \(\sigma_B = 0.5\) K. The gain is \(K = 0.09/(0.09 + 0.25) = 0.2647\), so \(\hat{x} \)\({}= 21.4 \)\({}+ 0.2647 \times (20.8 - 21.4) \)\({}= 21.24\) °C. The combined variance is \(1/(11.11 + 4) = 0.0662\), a standard deviation of 0.257 K.

Check your understanding. A sensor with \(\sigma = 1\) K is combined with a perfect sensor whose \(\sigma\) is 0. What is the combined estimate?
Python code in the Colab notebook, Section 1. Open Section 1 of the Colab notebook and run it. The function combine carries out the weighted mean of this section for any number of sensors. The code checks with 100,000 simulated readings that the weighted mean spreads less than either sensor and less than the plain mean.
- The building meter of the library reads 3 kW more than its meter at the switchboard. How would you decide which one to believe?
- What does the weighted mean assume about the errors of the two sensors, and when does that fail?
The Kalman filter: Predict and correct
A state that changes over time needs a weighted mean at every step. The filter of Kalman alternates two steps [1]. It predicts the state with a model and lets the uncertainty grow. It then corrects the prediction with a measurement, weighted by the two uncertainties.
The battery management system of the campus learns its state of charge from two sources [4]. Coulomb counting integrates the measured power \(u_k\), but its current sensor reads 5 kW too little, so the count drifts. The voltage gives the state of charge through the open-circuit voltage of Week 2, with a noise of 0.01. The filter combines both at every minute:
\(P\) is the variance of the estimate. \(Q\) is the variance that the state gains per step through the errors of the model, and \(R\) is the variance of a measurement, here \(0.01^2 = 10^{-4}\). A large \(Q\) trusts the measurements, a small one the model. For a constant \(Q\) and \(R\), the gain settles at a steady value [5]:
→ These formulas with numbers, step by step: Lab Part B, calculator, steps 2 to 5.
A worked example. At 17:00 the battery management system believes 0.95 with \(P_0 = 0.05^2 = 0.0025\), while the true state is 0.90. In the first minute it measures 50.17 kW, so \(\hat{x}^- = 0.95 \)\({}- 50.17/(60 \times 475) \)\({}= 0.9482\), and \(P^- = 0.002501\) with \(Q = 10^{-6}\). The voltage gives \(z = 0.9008\). The gain is \(K \)\({}= 0.002501/(0.002501 + 0.0001) \)\({}= 0.9616\), and the estimate becomes \(0.9482 \)\({}+ 0.9616 \times (0.9008 - 0.9482) \)\({}= 0.9026\), close to the true 0.8981.
The gain then falls minute by minute and settles at 0.0951. Over the four hours, coulomb counting ends with an error of +0.091. The voltage alone has a root-mean-square (RMS) error of 0.0107, and the filter with \(Q = 10^{-6}\) reaches 0.0037.
Scene: The Kalman filter as a balance. One minute of the battery management system at 19:00, as a balance. The prediction and the measurement sit on a beam at their values of the state of charge, each as heavy as the inverse of its variance. The estimate is the point where the beam balances. The five buttons follow one step of the filter.
Animation. The recorded evening of 17:00 to 21:00 with the chosen \(Q\) and \(R\) of the filter. The grey dots are the voltage readings, the red line is coulomb counting and the blue line is the estimate. The right panel shows the gain. Raise \(Q\) and watch the estimate follow the readings more closely and more nervously.

Check your understanding. What happens to the gain \(K\) when \(R\), the noise of the measurement, grows?
Interactive lab, Part A. The battery management bench in 3D: A module of the battery with its management board, a current sensor with an offset, a programmable load and a reference meter. Replay the evening with coulomb counting, the voltage alone and Kalman filters with several values of \(Q\). The results can be copied into the Colab notebook.
Python code in the Colab notebook, Section 2. Open Section 2 of the Colab notebook and run it. The function kalman_1d carries out the filter of this section, and coulomb keeps only its prediction. The code prints the RMS error of each method for the same recorded evening. Paste the results of Part A into MY_RUNS, and the code computes each of your runs again.
- A new current sensor without offset is installed. Should \(Q\) become larger or smaller, and why?
- What should the battery management system do when its voltage readings stop for an hour?
The Kalman filter with matrices
The offset of the current sensor is constant, and a filter with one state cannot learn it. The Kalman filter extends to a vector of states with matrices [1]. The state becomes \(\mathbf{x} = (SoC, b)\), the state of charge and the offset \(b\) of the sensor in kW:
The offset never appears in a measurement directly. It shows itself as a drift between coulomb counting and the voltage: In one hour, an offset of 5 kW shifts the count by \(5/475 = 0.0105\). The filter attributes this persistent disagreement to \(b\).
A worked example. With a variance of 100 kW² for the offset at the start, the filter estimates it at -5.80 kW by 18:00, -4.71 kW by 19:00 and -5.70 kW by 21:00. Its standard deviation falls to 0.33 kW. The RMS error of the state of charge drops to 0.0030, below the best filter with one state.

Check your understanding. Why can the filter estimate the offset although no sensor measures it?
Interactive lab, Part B. The calculator of the week computes the formulas of this page step by step. It covers the weighted mean of two sensors, one step of the Kalman filter and its steady gain.
Python code in the Colab notebook, Section 3. Open Section 3 of the Colab notebook and run it. The function kalman_2d carries out the filter with matrices of this section with the operator @. The code prints the estimated offset at each full hour and draws it with its uncertainty.
- Which other hidden quantities of the campus could a filter estimate in the same way?
- What would happen if the offset of the sensor changed suddenly at 19:00?
State estimation of the campus
The control room of the campus receives 13 power readings for six feeders at 19:00. Each feeder has a meter at the main switchboard with \(\sigma = 1.5\) kW and a meter in its building, read over the network, with \(\sigma = 2.5\) kW. The main meter adds the sum of all six feeders with \(\sigma = 3\) kW.
State estimation finds the six powers that fit all readings best, each weighted by its uncertainty. Schweppe and Wildes introduced this estimate by weighted least squares (WLS) for power systems [2]:
Here \(H\) has 13 rows: One for each feeder meter, one for each building meter and a row of ones for the main meter. With only two meters of one quantity, the estimate reduces to the weighted mean of the first section.
A worked example. The meters of B3 read 103.3 kW at the switchboard and 107.9 kW in the building. With the weights \(1/1.5^2 = 0.4444\) and \(1/2.5^2 = 0.16\), their weighted mean alone is \((45.91 + 17.26)/0.6044 = 104.52\) kW. The main meter reads 585.5 kW for the sum of all six feeders, and with it the estimate of B3 becomes 103.93 kW.

Check your understanding. How many readings does the state estimate of the campus have beyond its unknowns?
- Which meter of the campus would you add first to make the estimate more robust, and why?
- What does the state estimate need to know about the network that the readings alone do not say?
Bad data: Residuals and the chi-square test
A wrong reading, such as that of an open current transformer, pulls the estimate away and leaves large residuals. If all errors are normal, the weighted sum of the squared residuals follows a chi-square distribution with \(m - n\) degrees of freedom, for \(m\) readings and \(n\) unknowns [6]:
If \(J\) exceeds the 99 percent quantile of this distribution, the readings contain bad data. The meter with the largest normalized residual \(r_i^N\) is the most likely culprit. It is removed, and the estimate is repeated.
A worked example. With 13 readings and 6 unknowns, the threshold is \(\chi^2_{7;\,0.99} = 18.48\). The clean readings give \(J = 8.04\). When the current transformer of the B3 feeder meter opens, the meter reads 0 kW and \(J\) jumps to 1626.32. The largest normalized residual, 40.2, points at that meter. Without it, \(J = 7.50\), and B3 is estimated at 105.22 kW.
An open secondary circuit is more than bad data. Under load, the open winding of a current transformer develops a high voltage that endangers people and insulation. The test terminal block therefore first shorts the secondary circuit with its link, and only then may a meter be removed or a wire be opened.
Small errors hide in the noise. An offset of the B3 feeder meter is detected only from 11 kW on, with \(J = 19.55\), while an offset of 10 kW gives \(J = 17.05\) and passes.

Check your understanding. Why is the meter with the largest normalized residual removed, and not the one with the largest residual?
Interactive lab, Part C. The control room of the campus in 3D. It holds the meters of the main switchboard with a test terminal block, a map with the building meters and the screens of the estimate. Break a meter, run the estimator and find the smallest offset that the test detects. The results can be copied into the Colab notebook.
Python code in the Colab notebook, Section 4. Open Section 4 of the Colab notebook and run it. The function wls carries out the estimate and the test of this section, and identify removes the meter with the largest normalized residual. The code runs four faults and an offset that grows step by step. Paste the results of Part C into MY_METERS, and the code repeats each of your runs.
- Two meters fail in the same way at the same time. Can the test still find them?
- Which faults of a meter would the test of this week never notice?
Development templates of the week
The folder templates/ of the repository collects small working programs that carry out the methods of the course. Week 6 adds two of them, each with a description, its inputs and outputs and an example run.
| Template | What it does |
|---|---|
kalman_filter.py | A Kalman filter for any linear model with the matrices A, B, H, Q and R, written as a class; the example tracks a state of charge and the offset of its sensor |
wls_state_estimation.py | Weighted least squares with the chi-square test and the largest normalized residual, removing bad data one meter at a time; the example is the campus at 19:00 |
The engineering side: Trusting an estimator
An estimator is only as good as its model and its noise values. Engineers check it during operation with its own innovations, the differences \(z - H\hat{\mathbf{x}}^-\) between each reading and its prediction. For a consistent filter, the innovations look like white noise with the variance \(H P^- H^T + R\) that the filter expects.
| Check | What it reveals |
|---|---|
| The mean of the innovations lies far from zero | An offset that the model does not contain |
| The innovations are larger than expected | A value of Q or R that is too small, or a fault |
| The innovations are correlated in time | A missing state or a wrong model |
| The variance P keeps growing | A state that the measurements cannot observe |
Numerical care matters too: The covariance must stay symmetric and positive, which a symmetric form of the update keeps in floating point. In state estimation, every meter needs another meter that checks it. A reading that nothing else checks can be wrong without leaving any residual.
Before satellite navigation, a navigator advanced the position of a ship with its speed and heading, which slowly drifted. Whenever a lighthouse came into view, the navigator corrected the position toward the sighting, the more the clearer the view. This is the predict and correct of a Kalman filter.
- How would you choose Q and R for the battery management system before any data exist?
- Who should be alerted when the test of the control room fails at night?
The campus microgrid, stage 6: Estimating the state of the microgrid
Stage 6 gives the controllers of the campus estimates instead of raw readings. The battery management system tracks its state of charge and the offset of its current sensor. The control room estimates the six feeders and rejects a faulty meter.
| Question | Result | Model |
|---|---|---|
| Coulomb counting with an offset of -5 kW | +0.091 at 21:00: it believes 0.236 instead of 0.144 | Integration |
| The voltage alone | RMS error 0.0107 | Measurement |
| Kalman filter with the best Q | \(Q = 10^{-6}\): RMS error 0.0037 | Kalman filter |
| Kalman filter with the offset | RMS error 0.0030; offset -5.70 kW at 21:00 | Kalman filter with matrices |
| State estimate at 19:00 | J = 8.04 below 18.48; B3 at 103.93 kW | Weighted least squares |
| Open current transformer of B3 | J = 1626.32, meter found; B3 at 105.22 kW without it | Bad data |
| Smallest detected offset of the B3 feeder meter | 11 kW | Chi-square test |
With coulomb counting alone, the reserve rule of Week 3 would count on 0.091 of the battery, about 46 kWh, that does not exist. Week 7 runs these estimators and the controller of Week 5 on one processor, each with its own period and deadline.

Check your understanding. What does the filter with the offset add to the battery management system?
Interactive lab, Part D. Stage 6 by hand: The weighted mean of the two meters of the car park, one Kalman gain and the steady gain of a filter.
Python code in the Colab notebook, Section 5. Open Section 5 of the Colab notebook and run it. The code collects the results of stage 6 in the dictionary STAGE6. A figure draws the errors of the three estimators and the test value against the offset of a meter.
In the field: The zero of a current sensor
The offset of this lecture has a physical source. The current sensor of the battery management system (BMS) shows a small current even when no current flows, and the count of the charge drifts with it. Its zero is calibrated on site at a current of exactly zero, so the inverter goes to 0 kW and the main contactor K1 opens. The idle inverter still draws a little power, and only the open contactor guarantees zero.
The BMS shows the offset in amperes, while the filter of the lecture estimated it in kilowatts. At the pack voltage \(U\), an offset \(I_0\) is the power \(P_0 = U\,I_0\). For example, an offset of -4.0 A at 750 V is \(-4.0 \times 750 = -3000\) W, or -3.0 kW. A clamp meter for direct current then checks the sensor under load. Such a meter also drifts, so it is zeroed away from the cable before it measures.
Interactive lab, Part E. The field task: The master module of the BMS, the energy management system and a clamp meter. Calibrate the zero of the current sensor and check it under load.
Your application
Wherever a quantity changes slowly and is measured with noise, a Kalman filter can track it. The Colab notebook holds an application switch with six signals. They track a satellite position, the temperature of a room, a heart rate, the level of a tank, the pressure of a tyre and the offset of a clock.
Python code in the Colab notebook, Section 6. Open Section 6 of the Colab notebook, set APP to one of the six names in the comment and run the cell. The code simulates the signal with its noisy readings, filters it and compares the errors.
Learning to estimate
A Kalman filter needs a model and the variances \(Q\) and \(R\). When the model is only partly known, the gain can be learned from data instead. KalmanNet keeps the structure of the Kalman filter and computes its gain with a recurrent neural network that is trained on recorded trajectories [7]. Its authors report that it copes with non-linear dynamics and with errors of the model better than classic filters.
For the battery of the campus, a learned estimator could capture the ageing of the cells and the effect of the temperature on the voltage. The linear model of Week 2 ignores both. It still needs the checks of this week: Its innovations must look like noise, and its estimates must pass the same tests.
Suppose that the team records the voltage, the current and the temperature of the battery for a year, with a laboratory measurement of the true state of charge every month. A small recurrent network learns to correct the gain of the filter for cold mornings and for aged cells. The classic filter keeps running beside it as a reference.
- Would you let a learned estimator decide the reserve of the battery before an outage?
- How would you notice that a learned estimator has drifted away from the truth?
Review cards
Select a card to turn it over.
References
[1] Kalman, R. E. (1960). A new approach to linear filtering and prediction problems. Journal of Basic Engineering, 82(1), 35-45. https://doi.org/10.1115/1.3662552
[2] Schweppe, F. C., & Wildes, J. (1970). Power system static-state estimation, Part I: Exact model. IEEE Transactions on Power Apparatus and Systems, PAS-89(1), 120-125. https://doi.org/10.1109/TPAS.1970.292678
[3] Harris, C. R., Millman, K. J., van der Walt, S. J., Gommers, R., Virtanen, P., Cournapeau, D., Wieser, E., Taylor, J., Berg, S., Smith, N. J., Kern, R., Picus, M., Hoyer, S., van Kerkwijk, M. H., Brett, M., Haldane, A., Fernández del Río, J., Wiebe, M., Peterson, P., Gérard-Marchant, P., Sheppard, K., Reddy, T., Weckesser, W., Abbasi, H., Gohlke, C., & Oliphant, T. E. (2020). Array programming with NumPy. Nature, 585(7825), 357-362. https://doi.org/10.1038/s41586-020-2649-2
[4] Plett, G. L. (2004). Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs. Journal of Power Sources, 134(2), 252-261. https://doi.org/10.1016/j.jpowsour.2004.02.031
[5] Åström, K. J., & Wittenmark, B. (1997). Computer-Controlled Systems: Theory and Design (3rd ed.). Prentice Hall.
[6] Handschin, E., Schweppe, F. C., Kohlas, J., & Fiechter, A. (1975). Bad data analysis for power system state estimation. IEEE Transactions on Power Apparatus and Systems, PAS-94(2), 329-337. https://doi.org/10.1109/T-PAS.1975.31858
[7] Revach, G., Shlezinger, N., Ni, X., López Escoriza, A., van Sloun, R. J. G., & Eldar, Y. C. (2022). KalmanNet: Neural network aided Kalman filtering for partially known dynamics. IEEE Transactions on Signal Processing, 70, 1532-1547. https://doi.org/10.1109/TSP.2022.3158588