The weight comes back into view after a quarter of a second behind a post, and the camera reports it 26 cm to the side of the pivot. The filter had predicted about 9 cm. Should it believe the frame? All of it, or part? And the camera says nothing about how fast the rod is turning, so should the estimate of the rate change at all?
The filter answers by asking your measurement model what the camera ought to have reported. This chapter follows that one frame through the filter, then adds a second sensor on a different clock, and then a camera whose error has a direction.
What should the camera report?
A measurement has two parts in the library. A measurement vector names the readings of one update, in the same way that a state names its fields. For each reading, a function says what the sensor would report if the pendulum were in a given state.
// What the camera reports in one frame: how far the weight is to the side of the pivot.
enum SensorKey { BobX = 10 };
using Frame = UKF::FixedMeasurementVector<UKF::Field<BobX, real_t>>; // m// The measurement model: what the camera would report if the pendulum were in this state.
template <>
template <>
inline real_t Frame::expected_measurement<State, BobX>(const State& state) {
return kLength * std::sin(state.get_field<Angle>());
}Sensor keys and state keys are separate: BobX is a reading, Angle is a state field, and expected_measurement is the only place they meet. The function returns what an ideal camera would see. The camera’s error is given to the filter separately, as a number.
The filter does not run this function once, on its best estimate. It runs it on every sigma point of the prediction, which gives five expected readings. Their weighted mean is the predicted reading, and their spread, with the camera’s own error added, is how far a real frame can be expected to fall from it. The frame minus the predicted reading is the innovation.
camera prints each of these for the frame in the opening paragraph. The estimate was last good when the weight went behind the post, and five frames have been missed.
// Five frames were missed, so predict five times with nothing to compare against.
for (int missed = 0; missed < 5; missed++) {
if (!filter.a_priori_step(dt)) return 1;
}// What would the camera report for each sigma point of the prediction? The library
// answers by calling expected_measurement once for every column.
const auto& points = filter.get_sigma_points();
const auto expected = Frame().calculate_sigma_point_distribution<State>(points);
for (int i = 0; i < points.cols(); i++) {
const State point(points.col(i));
std::printf("sigma point %d: angle %.3f rad, rate %5.2f rad/s -> expects %.3f m\n", i,
point.get_field<Angle>(), point.get_field<Rate>(), expected(0, i));
}predicted: angle 0.190 +/- 0.137 rad, rate -3.43 +/- 0.46 rad/s, correlation 0.29
sigma point 0: angle 0.190 rad, rate -3.43 rad/s -> expects 0.095 m
sigma point 1: angle 0.497 rad, rate -3.13 rad/s -> expects 0.238 m
sigma point 2: angle 0.190 rad, rate -2.46 rad/s -> expects 0.095 m
sigma point 3: angle -0.116 rad, rate -3.73 rad/s -> expects -0.058 m
sigma point 4: angle 0.190 rad, rate -4.41 rad/s -> expects 0.095 m
frame 0.260 m, predicted reading 0.094 m, innovation 0.166 m (expected spread 0.073 m)
corrected: angle 0.476 +/- 0.057 rad, rate -3.15 +/- 0.44 rad/s
the angle moved by 0.285 rad and the rate, which no sensor measured, by 0.28 rad/s
Points 2 and 4 have the predicted angle and differ only in rate, so they expect the same reading as point 0. The camera cannot tell them apart. The correction to the rate comes another way, through point 1 and point 3: in the prediction, a larger angle goes with a rate nearer zero. A frame which says the angle is larger than predicted therefore also says the rod is turning more slowly than predicted. The filter measures that link as the cross covariance between the sigma points and their expected readings, and corrects every field in proportion.
// The frame that arrives, and how it differs from the predicted reading.
Frame frame;
frame.set_field<BobX>(0.26);
if (!filter.innovation_step(frame)) return 1;
const real_t innovation = filter.innovation.get_field<BobX>();
const real_t innovation_sigma = std::sqrt(filter.innovation_covariance(0, 0));if (!filter.a_posteriori_step()) return 1;The figure draws the same update. The drawing has the five rods and where each expects the weight to appear on the image line. The plot is the phase plane, where the frame is a band: every angle at which the camera would report this reading, give or take its error. It is a vertical band because the camera is silent about rate.
filter.measurement_covariance.set_field<BobX>(0.03 * 0.03); // m^2
Frame frame;
frame.set_field<BobX>(0.26); // m
if (!filter.innovation_step(frame)) return 1; // compare
const real_t innovation = filter.innovation.get_field<BobX>();
if (!filter.a_posteriori_step()) return 1; // correctfilter.measurement_covariance.set_field<BobX>(0.03 * 0.03); // m^2
Frame frame;
frame.set_field<BobX>(0.26); // m
if (!filter.innovation_step(frame)) return 1; // compare
const real_t innovation = filter.innovation.get_field<BobX>();
if (!filter.a_posteriori_step()) return 1; // correct
Try it
- With the opening settings the arrow in the phase plane points right and slightly up: the angle is corrected by 0.285 rad and the rate by 0.28 rad/s, as
cameraprinted. - Move the frame to 0.09 m, the predicted reading. The innovation is nearly zero and the estimate does not move, but its ellipse still narrows. A frame which agrees with the prediction is still information.
- Raise the camera error to 0.10 m. The orange band is now wider than the dashed ellipse. The estimate moves only a third of the way towards it, and its ellipse narrows only a little.
- Lower the camera error to 0.01 m. The corrected ellipse becomes a thin sliver inside the band. Its height hardly changes: this camera can say little about the rate from one frame.
Two limits are worth knowing. First, the camera reports the same position for a rod at an angle θ below level and at the same angle above it. While the sigma points stay on one side of level, the filter is not troubled. If the uncertainty of the angle is so wide that the points reach past level on both sides, the update can settle on the wrong one. Started with a guess good only to within 1 rad, the quickstart’s tracker does exactly that: after four seconds its estimate has wound round to 16.2 rad. Start a filter with an honest but not careless first guess, or take the first angle from the first frame.
Second, read the estimate and not the reading. After an update, filter.state.get_field<Angle>() is the estimate. frame.get_field<BobX>() is still the raw frame.
Two sensors on two clocks
Add a rate gyroscope to the rod. It reports the angular rate a hundred times a second, five times as often as the camera, with a small random error and a constant offset, its bias. The filter should use both sensors, each when it reports, and should work out the bias.
The bias is unknown and it matters to a prediction, so it joins the state. And because the camera has no frame at most updates, the measurement vector becomes a DynamicMeasurementVector: it declares every reading which might arrive, and each update sets only those which did.
// The gyroscope's bias is something to estimate, so it joins the state.
enum BiasKey { GyroBias = 2 };
using BiasedState = UKF::StateVector<
UKF::Field<Angle, real_t>, UKF::Field<Rate, real_t>, UKF::Field<GyroBias, real_t>>;
// A dynamic measurement vector names every sensor that might report.
enum GyroKey { Gyro = 11 };
using Readings = UKF::DynamicMeasurementVector<
UKF::Field<BobX, real_t>, // m, from the camera
UKF::Field<Gyro, real_t>>; // rad/s, from the gyroscope
using Fusion = UKF::Core<BiasedState, Readings, UKF::IntegratorRK4>;template <>
template <>
real_t Readings::expected_measurement<BiasedState, BobX>(const BiasedState& state) {
return kLength * std::sin(state.get_field<Angle>());
}
template <>
template <>
real_t Readings::expected_measurement<BiasedState, Gyro>(const BiasedState& state) {
return state.get_field<Rate>() + state.get_field<GyroBias>();
}The gyroscope’s model is a sum: it reads the true rate plus its bias. On its own that would leave the two inseparable. The camera and the process model separate them, since a rate which is always 0.3 rad/s too high does not fit the positions the camera sees or the way a pendulum swings.
// One update with whatever arrived in the last dt seconds.
bool update(Fusion& filter, real_t dt, std::optional<real_t> camera, std::optional<real_t> gyro) {
Readings readings; // a fresh vector holds no readings at all
if (camera) readings.set_field<BobX>(*camera);
if (gyro) readings.set_field<Gyro>(*gyro);
return filter.step(dt, readings); // with none set, this only predicts
}Build a fresh vector at every update. A vector kept from the last update would still hold the last camera frame, and the filter would count it again as if it were new.
std::optional<real_t> camera, gyro;
gyro = bench.gyro(gyro_sigma, true_bias); // every update
const bool hidden = tick > 100 && tick <= 200; // a post blocks the camera for a second
if (tick % camera_every == 0) {
const real_t picture = bench.camera(camera_sigma);
if (!hidden) camera = picture;
}
if (!update(filter, dt, camera, gyro)) return 1;The figure replays four seconds of this. The camera is hidden behind the post from 1 s to 2 s.
// The update at the selected instant: only the gyroscope field is set.
update(filter, 0.01, std::nullopt, 1.761);// The update at the selected instant: only the gyroscope field is set.
update(filter, 0.01, std::nullopt, 1.761);
Try it
- Step the slider a hundredth of a second at a time near 0.5 s. The call under the figure has a camera value at one update in five and
std::nulloptat the others. - Move into the shaded second. Every update is now the gyroscope alone. The band round the bias keeps narrowing, from 0.040 rad/s at 1 s to 0.015 rad/s at 2 s, because the pendulum model still constrains what the rate can be.
- Set the camera to one frame every 0.20 s. The band round the bias is a little wider at every instant, but not by much: the gyroscope and the pendulum model do most of this work.
- Change the true bias. The neutral line moves and the estimate follows it. Nothing in the filter was told the new value.
t 0.5 s bias 0.103 +/- 0.106 rad/s angle -0.389 +/- 0.026 rad (true -0.415)
t 1.0 s bias 0.264 +/- 0.040 rad/s angle -0.438 +/- 0.022 rad (true -0.444)
t 1.5 s bias 0.248 +/- 0.024 rad/s angle 0.816 +/- 0.022 rad (true 0.768) camera hidden
t 2.0 s bias 0.277 +/- 0.015 rad/s angle -0.430 +/- 0.018 rad (true -0.462) camera hidden
t 2.5 s bias 0.289 +/- 0.010 rad/s angle -0.260 +/- 0.014 rad (true -0.281)
t 3.0 s bias 0.284 +/- 0.008 rad/s angle 0.671 +/- 0.012 rad (true 0.634)
t 3.5 s bias 0.293 +/- 0.006 rad/s angle -0.471 +/- 0.011 rad (true -0.492)
t 4.0 s bias 0.295 +/- 0.005 rad/s angle -0.053 +/- 0.010 rad (true -0.066)
The noise settings of a dynamic vector follow the order in which its fields were declared, whichever of them are present.
// Noise settings follow the order in which the fields were declared.
filter.process_noise_covariance.setZero();
filter.process_noise_covariance.topLeftCorner<2, 2>() = interval_noise(dt, gust_intensity);
filter.process_noise_covariance(2, 2) = 1e-6 * dt; // the bias may drift, slowly
filter.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);
filter.measurement_covariance.set_field<Gyro>(gyro_sigma * gyro_sigma);A few rules come with readings that arrive at different times. Process them in the order of their timestamps, and give each step the time since the last one. When two readings share a timestamp, set both fields and step once. When nothing has arrived, an empty dynamic vector makes step predict only; a_priori_step(dt) says the same thing more plainly. A reading stamped earlier than the filter’s present time needs a decision of your own, such as holding readings briefly before using them. A negative interval is not one of the choices.
Errors with a direction
So far each sensor’s error has been one number, a variance. The default storage, measurement_covariance, holds one variance per reading and assumes the errors of different readings are independent. Sometimes they are not.
Suppose the camera now reports the weight’s position in two directions, sideways and upward. The weight moves during the exposure, so its image is smeared along its path: the detector’s error is several centimetres along the direction of travel and a few millimetres across it. Unless the rod happens to be vertical or level, that long error is partly sideways and partly upward at once. The two errors are correlated, and a pair of variances cannot say so.
// One field holding both coordinates of the weight: sideways, then upward, in metres.
enum SpotKey { BobXY = 12 };
using Spot = UKF::FixedMeasurementVector<UKF::Field<BobXY, UKF::Vector<2>>>;
// Diagonal noise storage is the default. The last argument asks for a full matrix.
using DiagonalFilter = UKF::Core<State, Spot, UKF::IntegratorRK4>;
using DenseFilter = UKF::Core<State, Spot, UKF::IntegratorRK4, Spot::DenseCovarianceMatrix>;// The detector's error where the rod is at "angle": blur_sigma along the path of the
// weight, sharp_sigma across it. Rows and columns are sideways, then upward.
Spot::DenseCovarianceMatrix blurred(real_t angle, real_t blur_sigma, real_t sharp_sigma) {
const UKF::Vector<2> along(std::cos(angle), std::sin(angle)); // direction of travel
const UKF::Vector<2> across(std::sin(angle), -std::cos(angle)); // along the rod
return blur_sigma * blur_sigma * along * along.transpose() +
sharp_sigma * sharp_sigma * across * across.transpose();
}The last template argument of the filter selects full storage. Rows and columns follow the declared order of the readings, with the components of a vector field together.
const Spot::DenseCovarianceMatrix noise = blurred(seen_at, blur_sigma, sharp_sigma);
DenseFilter dense;
start(dense);
dense.measurement_covariance = noise; // variances and the covariance between them
DiagonalFilter diagonal;
start(diagonal);
diagonal.measurement_covariance.set_field<BobXY>(noise.diagonal()); // variances onlyThe figure shows why the difference matters. The detections fall in a long, tilted cloud. The solid ellipse is the whole covariance and fits the cloud. The dashed ellipse is what the two variances alone describe: as wide and as tall, but upright. It is too narrow along the path, which is the direction that tells the filter about the angle.
// blurred(0.6, 0.040, 0.005), in m^2: sideways first, then upward
dense.measurement_covariance << 0.001098, 0.000734,
0.000734, 0.000527;
diagonal.measurement_covariance.set_field<BobXY>(UKF::Vector<2>(0.001098, 0.000527));// blurred(0.6, 0.040, 0.005), in m^2: sideways first, then upward
dense.measurement_covariance << 0.001098, 0.000734,
0.000734, 0.000527;
diagonal.measurement_covariance.set_field<BobXY>(UKF::Vector<2>(0.001098, 0.000527));
Try it
- With the opening settings, the filter given the whole matrix ends within 0.0628 rad. The filter given only the variances claims 0.0500 rad, more confidence than the frame can support.
- Set the rod angle to zero. The path is now sideways, the solid ellipse lies flat, and the off-diagonal numbers in the code are zero. The two filters agree.
- Reduce the error along the path to 0.5 cm, the same as across it. The cloud is round, there is nothing to correlate, and again they agree.
measurement covariance (m^2): [0.001098 0.000734; 0.000734 0.000527]
whole matrix: angle 0.6367 +/- 0.0628 rad
variances only: angle 0.6440 +/- 0.0500 rad
A square-root filter with full storage takes a factor L of the covariance, with R = L LT, in measurement_root_covariance. noise.llt().matrixL() gives one. Taking the square root of each entry does not: it loses the correlation. With a dynamic vector, keep the full matrix in declared order even when only some readings are present; the library picks out the rows and columns it needs.
The camera’s error here changes with the angle of the rod, so the program would set it again before each frame. That is allowed: noise settings belong to the filter object and can change at every update.
How a reading differs from its prediction
For a number or an ordinary vector, the innovation is a subtraction. Two other field types measure directions and orientations, where subtraction is the wrong idea.
| Field type | What the difference means |
|---|---|
real_t or UKF::Vector<N> | Component by component, in the sensor’s units. Use it when the size of the reading matters as well as its direction. |
UKF::FieldVector | The rotation between two directions, for a reading such as gravity or a magnetic field. Give its noise in the sensor’s own coordinates; the library maps it into rotation coordinates. |
UKF::Quaternion | The rotation from the predicted orientation to the measured one. A quaternion and its negative give the same result. Its noise is three rotation variances. The library marks quaternion readings as experimental in 1.0. |
The choice changes what a correction can learn. A light sensor used to find a direction should not be upset when the lamp gets brighter, so it suits a FieldVector. A three-axis force sensor used to weigh a load needs the size of its reading, so it suits a Vector<3>.
Check your understanding
In the first figure, why is the orange band vertical?
The band is every state the frame is consistent with. The camera’s reading depends on the angle and not on the rate, so for a given reading every rate is allowed and only a narrow range of angles is. A gyroscope’s band on the same plane would be horizontal.
The camera drops a frame while the gyroscope keeps reporting. What does your update function do?
Nothing special. It builds a fresh Readings, sets Gyro, leaves BobX unset and calls step. The filter predicts and corrects with the gyroscope alone. Do not set BobX to the last frame or to zero: either would be used as a real reading.
For the blurred camera, would taking only the variances be safe if you made them larger?
It would stop the filter being overconfident about the angle, at a cost. An upright ellipse large enough to cover the smear along the path also claims a large error across it, where the camera is in fact sharp. The filter would then use each frame less than it could. The full covariance says both things at once.
Reference
| Name | What it is |
|---|---|
UKF::FixedMeasurementVector<Field…> | Readings which all arrive at every update. Set every field. |
UKF::DynamicMeasurementVector<Field…> | Readings of which any subset may arrive. Build a fresh one for each update and set what arrived. |
Measurement::expected_measurement<State, Key, Inputs…>(state, inputs…) | The measurement model for one reading. Specialise it in namespace UKF. |
filter.measurement_covariance | Sensor error. By default one variance per reading, set with set_field<Key>, in declared order. |
Measurement::DenseCovarianceMatrix | As the last template argument of a core, makes measurement_covariance a full matrix. |
filter.innovation_step(z, inputs…) | Works out the predicted reading and leaves the result in filter.innovation and filter.innovation_covariance. |
filter.get_sigma_points() | After a prediction, the sigma points the measurement model will be run on, one per column. |
filter.a_posteriori_step() | Applies the correction from the last innovation. |
Fields and measurement mapping · Prediction, correction and missing observations · Dense covariance, field order and root factors · MeasurementVector.h · camera.cpp · sensors.cpp · blur.cpp