An encoder on the pendulum’s shaft reads 21°. A second ago the best estimate of the angle was 20°. How far should the estimate move? Not all the way, since the encoder has an error. Not nowhere, since the old estimate had one too. The filter’s answer is a fraction, and for a case this small you can work it out by hand and check the library against it.
This chapter opens the single call filter.step(…) into its three stages, then looks at the two ways the library stores uncertainty, at what to do when no reading arrives, and at what happens when a step fails.
One update by hand
For this section only, simplify the pendulum until the arithmetic fits on a line. Hold the rod in a stiff clutch, so that its angle barely changes, and read the angle directly with an encoder. The state is one number, the angle in degrees. The process model says the angle stays where it was. The measurement model says the encoder reads the angle. Both are straight lines, so the sigma points give exactly what the textbook formulas give.
Start from an estimate of 20° with a standard deviation of 1°, so a variance of 1 deg². Allow the clutch to creep: 0.04 deg² of extra variance for each second. The encoder’s error has a standard deviation of 0.5°, a variance of 0.25 deg². One second later it reads 21°.
- Predict. The angle is still expected to be 20°. Its variance grows by the creep, to 1 + 0.04 = 1.04 deg².
- Compare. The filter expected the encoder to read 20°. The innovation is 21 − 20 = 1°. A difference of that kind has two causes, the uncertainty of the prediction and the encoder’s error, so its variance is 1.04 + 0.25 = 1.29 deg².
- Correct. The prediction’s share of that variance is 1.04 / 1.29 = 0.806. The estimate moves that fraction of the innovation, to 20.806°. Its variance falls to (1 − 0.806) × 1.04 = 0.2016 deg², a standard deviation of 0.449°.
The library’s step does all three. They are also separate calls, which lets a program look at the innovation before deciding whether to apply it.
Filter filter;
filter.state.set_field<ShaftAngle>(20.0); // the last estimate
filter.covariance(0, 0) = prior_sigma * prior_sigma; // its variance
const real_t dt = 1.0; // s since that estimate
filter.process_noise_covariance(0, 0) = creep * dt; // the clutch may have crept
filter.measurement_covariance.set_field<Encoder>(encoder_sigma * encoder_sigma);
Reading reading;
reading.set_field<Encoder>(encoder_reading);if (!filter.a_priori_step(dt)) return 1; // 1. predict
const real_t predicted = filter.state.get_field<ShaftAngle>();
const real_t predicted_variance = filter.covariance(0, 0);
if (!filter.innovation_step(reading)) return 1; // 2. compare with the reading
const real_t innovation = filter.innovation.get_field<Encoder>();
const real_t innovation_variance = filter.innovation_covariance(0, 0);
if (!filter.a_posteriori_step()) return 1; // 3. correct
const real_t corrected = filter.state.get_field<ShaftAngle>();
const real_t corrected_sigma = std::sqrt(filter.covariance(0, 0));1. predicted 20.000 deg, variance 1.040 deg^2
2. innovation 1.000 deg, variance 1.290 deg^2
3. corrected 20.806 deg, standard deviation 0.449 deg
the estimate moved 80.6% of the way to the reading
after 3 s without a reading: 20.806 deg, standard deviation 0.567 deg
The program exits with an error if the library’s corrected angle differs from the hand calculation. In the figure the three stages are three bells on a scale of angle: the prediction, the reading with the encoder’s error about it, and the corrected estimate, which lies between them and is narrower than either.
// ./build-examples/encoder 21.0 0.5 1.0 0.04
filter.state.set_field<ShaftAngle>(20.0);
filter.covariance(0, 0) = 1.0 * 1.0; // deg^2
filter.process_noise_covariance(0, 0) = 0.04 * dt; // deg^2, with dt = 1 s
filter.measurement_covariance.set_field<Encoder>(0.5 * 0.5);
reading.set_field<Encoder>(21.0);// ./build-examples/encoder 21.0 0.5 1.0 0.04
filter.state.set_field<ShaftAngle>(20.0);
filter.covariance(0, 0) = 1.0 * 1.0; // deg^2
filter.process_noise_covariance(0, 0) = 0.04 * dt; // deg^2, with dt = 1 s
filter.measurement_covariance.set_field<Encoder>(0.5 * 0.5);
reading.set_field<Encoder>(21.0);
Try it
- Raise the encoder error to 1.5°. The orange bell flattens, and the estimate moves less than a third of the way. More of the disagreement can now be blamed on the encoder.
- Put the encoder error back and reduce the spread of the last estimate to 0.2°. The filter is now more sure of its prediction than of the reading, and again moves little.
- Raise the creep to 0.5. The prediction widens and the estimate follows the reading more closely. Process noise makes a filter pay more attention to its readings.
- Whatever you choose, the blue bell is narrower than both the others. Two uncertain sources together are better than either alone.
For the pendulum and its camera the same three stages run with a curved model, as in Measurement models. The sigma points replace the simple sums, and the fraction becomes a gain for each field of the state. The order of the stages and the reason for each do not change.
Two ways to store uncertainty
The library has two filters for a state which changes with time. UKF::Core stores the covariance P. UKF::SquareRootCore stores a lower triangular matrix L, with P = L LT. They run the same models and, in exact arithmetic, give the same estimates.
L is to a covariance what a standard deviation is to a variance, and it has a direct picture. The filter makes its sigma points by adding and subtracting the columns of L, scaled by √(n + κ), which is √5 for two fields and the default settings. So the columns of L are the arrows from the estimate to its first sigma points. The square-root core stores those arrows. The covariance core stores the ellipse and takes the root when it needs the points.
// UKF::Core stores the covariance P.
filter.covariance << 0.0225, 0.0600,
0.0600, 0.6400;
// UKF::SquareRootCore stores a lower triangular L, with P = L * L.transpose().
root.root_covariance << 0.1500, 0.0,
0.4000, 0.6928;// UKF::Core stores the covariance P.
filter.covariance << 0.0225, 0.0600,
0.0600, 0.6400;
// UKF::SquareRootCore stores a lower triangular L, with P = L * L.transpose().
root.root_covariance << 0.1500, 0.0,
0.4000, 0.6928;
Try it
- Set the correlation to zero. L becomes diagonal: its entries are the two standard deviations, and the arrows lie along the axes.
- Raise the correlation. The first arrow tilts, taking some rate with it, and the bottom-left entry of L grows. The second arrow stays vertical and shortens.
- Compare the two listings. The entries of
covarianceare in squared units. The entries ofroot_covarianceare in the units of the state.
Everything you set before the first update has a covariance form and a root form.
| Quantity | Core | SquareRootCore |
|---|---|---|
| Uncertainty of the first estimate | covariance holds P | root_covariance holds a lower factor of P |
| Process noise for this interval | process_noise_covariance holds Q | process_noise_root_covariance holds a factor of Q |
| Independent sensor errors | measurement_covariance holds variances | measurement_root_covariance holds standard deviations |
CovarianceFilter filter;
filter.state << 0.0, 0.0;
filter.covariance.setZero();
filter.covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0; // variances
filter.process_noise_covariance = interval_noise(dt, gust_intensity); // Q for one frame
filter.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);RootFilter root;
root.state << 0.0, 0.0;
root.root_covariance.setZero();
root.root_covariance.diagonal() << 0.5, 2.0; // standard deviations
root.process_noise_root_covariance =
interval_noise(dt, gust_intensity).llt().matrixL(); // a factor of Q
root.measurement_root_covariance.set_field<BobX>(camera_sigma);For a diagonal matrix the factor is the square root of each entry. For any other, take a factor with a matrix factorisation, as the line for the process noise does with llt().matrixL(). The square root of each entry is not a factor once there are off-diagonal terms.
The square-root core propagates the factor itself, with QR factorisation and rank-one updates. That avoids subtracting nearly equal covariance matrices, which is where a covariance filter loses precision in 32-bit arithmetic, and it can be quicker. Use the covariance core when your application works with covariances directly. Consider the square-root core when precision or update time is tight. Choose between them by replaying the same recorded readings through both on your target.
When no frame arrives
A post stands in front of part of the swing, and for a second the camera cannot see the weight. The filter’s clock should not stop. Each time a frame would have been due, it predicts and does not correct. The estimate keeps swinging with the model, and its uncertainty grows by the process noise of each interval.
if (hidden) {
// No frame: move the clock on, and let the uncertainty grow.
if (!filter.a_priori_step(dt) || !root.a_priori_step(dt)) return 1;
} else {
Frame frame;
frame.set_field<BobX>(picture);
if (!filter.step(dt, frame) || !root.step(dt, frame)) return 1;
}cores runs the quickstart’s tracker through such a gap with both filters, on the same frames.
t 0.25 s frame angle 0.419 +/- 0.050 rad (true 0.480) rate -3.24 +/- 0.43 rad/s
t 0.50 s frame angle -0.405 +/- 0.034 rad (true -0.415) rate -3.07 +/- 0.17 rad/s
t 0.75 s frame angle -0.841 +/- 0.033 rad (true -0.855) rate 0.04 +/- 0.14 rad/s
t 1.00 s frame angle -0.426 +/- 0.029 rad (true -0.444) rate 3.10 +/- 0.14 rad/s
t 1.25 s frame angle 0.373 +/- 0.025 rad (true 0.411) rate 3.00 +/- 0.14 rad/s
t 1.50 s frame angle 0.828 +/- 0.030 rad (true 0.768) rate 0.03 +/- 0.13 rad/s
t 1.75 s hidden angle 0.419 +/- 0.041 rad (true 0.308) rate -3.02 +/- 0.13 rad/s
t 2.00 s hidden angle -0.412 +/- 0.037 rad (true -0.462) rate -2.95 +/- 0.19 rad/s
t 2.25 s hidden angle -0.797 +/- 0.044 rad (true -0.759) rate 0.11 +/- 0.19 rad/s
t 2.50 s hidden angle -0.372 +/- 0.057 rad (true -0.281) rate 2.99 +/- 0.17 rad/s
t 2.75 s frame angle 0.465 +/- 0.028 rad (true 0.438) rate 2.43 +/- 0.19 rad/s
t 3.00 s frame angle 0.713 +/- 0.033 rad (true 0.634) rate -0.54 +/- 0.14 rad/s
t 3.25 s frame angle 0.194 +/- 0.027 rad (true 0.154) rate -2.82 +/- 0.13 rad/s
t 3.50 s frame angle -0.492 +/- 0.025 rad (true -0.492) rate -1.93 +/- 0.14 rad/s
t 3.75 s frame angle -0.611 +/- 0.028 rad (true -0.584) rate 0.92 +/- 0.13 rad/s
t 4.00 s frame angle -0.078 +/- 0.025 rad (true -0.066) rate 2.73 +/- 0.13 rad/s
forecast for 5.00 s: angle -0.524 +/- 0.044 rad
largest difference between the two filters, in any state or covariance entry: 2.2e-15
P from Core: [0.000629 0.000813; 0.000813 0.016828]
L from SquareRootCore: [0.025080 0.000000; 0.032407 0.125608]
Before the gap the angle is known to within 0.030 rad. By its end the filter claims only 0.057 rad, and the first frame afterwards brings it back to 0.042 rad. The two filters agree in every entry to about fifteen decimal places.
UKF::Core<State, Frame, UKF::IntegratorRK4> filter;
filter.measurement_covariance.set_field<BobX>(0.03 * 0.03);
for (int k = 1; k <= 80; k++) {
const bool hidden = k > 30 && k <= 50; // frames lost behind the post
if (hidden) {
if (!filter.a_priori_step(dt)) return 1; // predict only
} else {
if (!filter.step(dt, frame)) return 1; // predict, compare, correct
}
}UKF::Core<State, Frame, UKF::IntegratorRK4> filter;
filter.measurement_covariance.set_field<BobX>(0.03 * 0.03);
for (int k = 1; k <= 80; k++) {
const bool hidden = k > 30 && k <= 50; // frames lost behind the post
if (hidden) {
if (!filter.a_priori_step(dt)) return 1; // predict only
} else {
if (!filter.step(dt, frame)) return 1; // predict, compare, correct
}
}
Try it
- Move the time slider through the shaded interval. No orange dots arrive, the blue band widens, and the estimate drifts a little from the truth. At the first frame after the gap the band snaps back.
- Lengthen the gap to two seconds. The estimate keeps swinging in step with the pendulum, since the model is doing all the work, but it drifts further from the truth as the gap goes on.
- Raise the camera error to 0.08 m. The band is wider everywhere, and the gap matters less by comparison, since each frame was telling the filter less.
- Switch the filter to SquareRootCore. The plot does not change. The line under the controls shows
root_covariancein place ofcovariance, and the listing sets a standard deviation where it set a variance.
Work out the process noise for each interval you predict over. If a reading arrives part of the way through an interval you have already predicted, advance by the remainder only. Applying a whole interval’s noise twice counts the same disturbance twice.
Prediction changes the filter. To ask where the rod will be in a second without disturbing the live estimate, predict on a copy.
// Where will the rod be in one second? Predict on a copy, so the live filter is undisturbed.
CovarianceFilter forecast = filter;
for (int k = 0; k < 20; k++) { // in steps the integrator can follow, each with its own noise
if (!forecast.a_priori_step(dt)) return 1;
}The forecast is made in steps of one frame. A single one-second step would ask the integrator to cross most of a swing at once, which it cannot do accurately.
When a step fails
Every step returns a Boolean, and the library never throws. A step fails when a covariance is not finite, or is so far from a valid covariance that rounding cannot explain it. What a failure leaves behind depends on which call you made.
| Call | On failure |
|---|---|
step(dt, z, inputs…) | Returns false and restores the state, the uncertainty and the innovation to what they were before the call, even if only the correction failed. |
a_priori_step(dt, inputs…) | Returns false and changes nothing. |
innovation_step(z, inputs…) | Returns false if there is no successful prediction to build on, or the innovation is not finite. The prediction is kept. |
a_posteriori_step() | Returns false if there is no successful innovation to build on, or the corrected values are not valid. The prediction is kept. |
So step is all or nothing, and the split stages let a program keep a good prediction when a reading cannot be applied. After a failure, later stages also return false until the next successful prediction. Check every result before you use the estimate.
After a successful prediction, get_sigma_points() gives the points the measurement model will be run on, one per column, with the process noise included. A correction does not change them; read state and the covariance or its factor for the corrected estimate. When a stage fails, record the inputs and the interval, look for values which are not finite, and check the units and validity of the covariances you supplied. Then carry on from a successful prediction.
Check your understanding
With the opening numbers, what would the estimate be if the encoder had read 19° instead?
The innovation would be −1° and its variance the same 1.29 deg², so the estimate would move the same fraction the other way: 20 − 0.806 = 19.194°. The standard deviation afterwards would still be 0.449°. In this linear case the uncertainty after an update does not depend on what the reading was, only on how good it was.
You have a process noise covariance with off-diagonal terms and want to use SquareRootCore. What do you assign?
A factor of it: Q.llt().matrixL(), assigned to process_noise_root_covariance. The square roots of the individual entries would describe a different, and usually invalid, covariance.
During the gap the angle estimate drifted 0.09 rad from the truth while the filter claimed 0.057 rad. Is the filter broken?
No. A standard deviation is not a limit. Errors of one and a half standard deviations are common, and the plot’s band, drawn at two, still covers the truth. If errors were regularly three or four times the claimed spread, the process noise would be too small.
Reference
| Name | What it is |
|---|---|
UKF::Core<State, Measurement, Integrator, Noise> | Stores P. The last two arguments are optional: no integrator means a direct process_model, and the noise type defaults to one variance per reading. |
UKF::SquareRootCore<…> | Stores a factor of P. Same arguments and steps. |
step(dt, z, inputs…) | Predict, compare and correct in one call. |
a_priori_step, innovation_step, a_posteriori_step | The three stages on their own. |
innovation, innovation_covariance or innovation_root_covariance | The last innovation and its uncertainty, for inspection and for gating. |
get_sigma_points() | The predicted sigma points, one per column. |
Core.h: the three filters · Initialisation and covariance · Step failure and rollback · Prediction, correction and missing observations · encoder.cpp · cores.cpp