SFWA UKF · Chapter 6 of 7

Parameter estimation and innovation gating

Two things were taken for granted in the earlier chapters. The camera reported the weight’s position in metres, as if someone had already worked out how many pixels make a metre and which pixel column lies under the pivot. And every frame was a view of the weight. A real detector now and then locks on to something else, such as a reflection, and reports that.

The library has a tool for each. A third filter core estimates fixed coefficients, such as a calibration. A gate lets your program refuse a reading which the filter finds too surprising. The chapter ends with a note on calling a filter from C or Python.

Make the coefficients the state

The camera really reports a pixel column. If the pivot appears at column c and one metre covers s pixels, a rod at angle θ puts the weight at column c + s × 0.5 sin(θ). To find s and c, clamp the rod at angles read from a protractor and note the column each time.

This is estimation again, with a difference. The unknowns do not move. There is no process model and no time step: the state is the pair of coefficients, and between readings it is expected to stay as it is. SquareRootParameterEstimationCore is the filter for that case. Its measurement model takes the coefficients as the state and the known clamp angle as an input.

calibrate.cpp

// The coefficients are the state. They do not change while the camera stays put.
enum Coefficient { Scale, Centre };
using Lens = UKF::StateVector<
    UKF::Field<Scale, real_t>,    // pixels per metre
    UKF::Field<Centre, real_t>>;  // pixel column of the pivot
enum Channel { Column = 10 };
using Pixel = UKF::FixedMeasurementVector<UKF::Field<Column, real_t>>;
using Calibrator = UKF::SquareRootParameterEstimationCore<Lens, Pixel>;

calibrate.cpp

// The measurement model takes the coefficients and the known clamp angle as an input.
template <>
template <>
real_t Pixel::expected_measurement<Lens, Column>(const Lens& lens, const real_t& clamp_angle) {
    return lens.get_field<Centre>() + lens.get_field<Scale>() * kLength * std::sin(clamp_angle);
}

The first guess is rough: 600 pixels per metre, give or take 300, and column 300, give or take 100. This core stores a factor of the covariance, so those spreads go straight into root_covariance as standard deviations. A process noise of zero says the coefficients are fixed.

calibrate.cpp

Calibrator filter;
filter.state << 600.0, 300.0;                       // a rough first guess
filter.root_covariance.setZero();
filter.root_covariance.diagonal() << 300.0, 100.0;  // standard deviations of that guess
filter.process_noise_root_covariance.setZero();     // the coefficients stay fixed
filter.measurement_root_covariance.set_field<Column>(pixel_sigma);

calibrate.cpp

for (int i = 0; i < 6; i++) {
    Pixel reading;
    reading.set_field<Column>(columns[i]);
    if (!filter.step(reading, clamp_angles[i])) return 1;  // no time step: a reading and its input
}

With the rod clamped at −0.6, 0 and 0.6 rad, twice each, the simulated camera’s 800 pixels per metre and column 320 are found within a few pixels.

clamp -0.60 rad, column   94.7 px -> scale  653.1 +/- 228.9 px/m, centre 279.1 +/- 64.6 px
clamp  0.00 rad, column  318.4 px -> scale  791.9 +/-   7.5 px/m, centre 318.3 +/-  1.5 px
clamp  0.60 rad, column  546.9 px -> scale  800.8 +/-   3.8 px/m, centre 320.0 +/-  0.9 px
clamp -0.60 rad, column   93.7 px -> scale  801.0 +/-   3.2 px/m, centre 320.0 +/-  0.8 px
clamp  0.00 rad, column  321.9 px -> scale  801.5 +/-   3.2 px/m, centre 320.4 +/-  0.7 px
clamp  0.60 rad, column  544.7 px -> scale  799.7 +/-   2.7 px/m, centre 320.0 +/-  0.6 px
predicted column at -0.3 rad: 201.9 +/- 0.7 px

Why one clamp angle is not enough

Look at what a single reading says. With the rod at 0.6 rad the camera reports column 546.5. Many pairs of coefficients predict exactly that: a larger scale with a centre further left, or a smaller scale with a centre further right. On a plane with the scale across and the centre up, those pairs lie on a straight line. A reading does not give you a point on that plane. It gives you a line, blurred by the camera’s error.

A second reading at the same angle gives the same line again. The filter becomes sure which line the coefficients are on and stays ignorant of where along it. A reading at another angle gives a line with a different slope, and two lines which cross fix a point.

filter.measurement_root_covariance.set_field<Column>(1.5);  // pixels
const real_t clamp_angles[] = {-0.6, 0.0, 0.6, -0.6, 0.0, 0.6};  // rad
const real_t columns[] = {94.7, 318.4, 546.9, 93.7, 321.9, 544.7};  // pixels
for (int i = 0; i < 6; i++) {
    Pixel reading;
    reading.set_field<Column>(columns[i]);
    if (!filter.step(reading, clamp_angles[i])) return 1;
}
Drawing: the rod at each clamp angle used so far, and on the image line, now marked in pixels, an orange dot for each column the camera reported. Plot: the plane of the two coefficients, scale across and centre up. Each orange line is the set of pairs which would produce one reading exactly, and its pale band allows for the camera’s error. The blue ellipse holds the estimate out to two standard deviations. The cross marks the simulated camera’s true coefficients.

Try it

  1. Set the readings used to 1. There is one line, and the estimate is a long ellipse lying along it, cut off only by the rough first guess.
  2. Add the second reading, at 0 rad. Its line is horizontal, since with the rod hanging the scale does not matter. The two lines cross and the ellipse shrinks to their crossing.
  3. Select 0.6 rad only with all six readings. Six lines lie on top of each other. The ellipse is as long as it was after one.
  4. Raise the camera error with three angles selected. The bands widen and so does the ellipse, but it stays compact.

With one clamp angle the program still prints a confident-looking fit to its own readings.

clamp  0.60 rad, column  546.5 px -> scale  714.0 +/- 228.9 px/m, centre 344.9 +/- 64.6 px
clamp  0.60 rad, column  544.2 px -> scale  712.3 +/- 228.9 px/m, centre 344.2 +/- 64.6 px
clamp  0.60 rad, column  546.9 px -> scale  713.1 +/- 228.9 px/m, centre 344.5 +/- 64.6 px
clamp  0.60 rad, column  545.4 px -> scale  713.0 +/- 228.9 px/m, centre 344.5 +/- 64.6 px
clamp  0.60 rad, column  547.8 px -> scale  713.6 +/- 228.9 px/m, centre 344.7 +/- 64.6 px
clamp  0.60 rad, column  544.7 px -> scale  713.2 +/- 228.9 px/m, centre 344.6 +/- 64.6 px
predicted column at -0.3 rad: 239.2 +/- 98.5 px

The last line gives it away. Asked where the weight would appear with the rod at −0.3 rad, an angle it has not seen, this calibration answers to within 98 pixels. The calibration from three angles answers to within 0.7 pixels. The uncertainty of that prediction comes from the whole covariance, including the link between the two coefficients.

calibrate.cpp

// How well does the calibration predict the column at an angle it has not seen?
// The predicted column is centre + scale * h, so its variance is d^T L L^T d with d = [h, 1].
const real_t unseen = -0.3;  // rad
const Eigen::Matrix<real_t, 2, 1> direction(kLength * std::sin(unseen), 1.0);
const real_t column_sigma = (filter.root_covariance.transpose() * direction).norm();

For an instrument whose coefficients drift, set process_noise_root_covariance to a factor of the drift expected between readings. The core adds it once at each prediction, so if the drift grows with time, work the factor out for the time that has passed. For coefficients which follow dynamics of their own, use one of the state filters and give them a process model.

Refuse a reading which does not fit

Back to the tracker. At 2.5 s the detector reports a reflection: 0.14 m to the right of the pivot, when the weight is really at −0.14 m. An ordinary update would move the estimate most of the way towards it.

The filter has the means to notice. Before correcting, it knows the innovation and also how large an innovation to expect. Dividing the squared innovation by its variance gives the normalised innovation squared, or NIS: the innovation in units of its own expected spread, squared. A reading one standard deviation from the prediction scores 1. One three standard deviations away scores 9. The reflection scores 70.

step_with_gate takes a function of yours. The library predicts, works out the innovation, and calls your function with the filter in that state. Return true and the correction is applied. Return false and the estimate is left at the prediction.

gate.cpp

// Normalised innovation squared: the innovation in units of its expected spread, squared.
real_t nis = 0.0;
const real_t limit = 3.0;  // accept readings within three standard deviations
auto within_limit = [&nis, limit](const Tracker& predicted, const Frame&) {
    const real_t variance = predicted.innovation_covariance(0, 0);
    if (!std::isfinite(variance) || variance <= 0.0) return false;
    const real_t innovation = predicted.innovation.get_field<BobX>();
    nis = innovation * innovation / variance;
    return std::isfinite(nis) && nis <= limit * limit;
};

gate.cpp

const bool applied = gated ? filter.step_with_gate(dt, frame, within_limit)
                           : filter.step_with_gate(dt, frame, accept_all);
t 2.40 s  frame -0.238 m  NIS   1.89  used      angle error -0.037 rad
t 2.45 s  frame -0.162 m  NIS   3.27  used      angle error -0.012 rad
t 2.50 s  frame  0.137 m  NIS  69.97  rejected  angle error -0.007 rad
t 2.55 s  frame -0.069 m  NIS   0.03  used      angle error -0.002 rad
t 2.60 s  frame  0.044 m  NIS   0.64  used      angle error  0.017 rad
t 2.65 s  frame  0.137 m  NIS   1.06  used      angle error  0.038 rad
t 2.70 s  frame  0.170 m  NIS   0.14  used      angle error  0.049 rad
gate at 3 standard deviations: 1 reading rejected, angle error on the frame with the reflection -0.007 rad

The same run with the gate removed (./build-examples/gate off) shows the damage one frame can do, and how many frames it takes to undo.

t 2.40 s  frame -0.238 m  NIS   1.89  used      angle error -0.037 rad
t 2.45 s  frame -0.162 m  NIS   3.27  used      angle error -0.012 rad
t 2.50 s  frame  0.137 m  NIS  69.97  used      angle error  0.103 rad
t 2.55 s  frame -0.069 m  NIS   3.48  used      angle error  0.091 rad
t 2.60 s  frame  0.044 m  NIS   0.31  used      angle error  0.091 rad
t 2.65 s  frame  0.137 m  NIS   0.00  used      angle error  0.093 rad
t 2.70 s  frame  0.170 m  NIS   0.99  used      angle error  0.086 rad
no gate: 0 readings rejected, angle error on the frame with the reflection 0.103 rad

A gate has to be judged against the right spread. In the figure the filter has just come out from behind the post, as in Measurement models, so its prediction is uncertain and the gate is wide.

const real_t limit = 3.00;  // standard deviations
const bool applied = filter.step_with_gate(dt, frame, within_limit);
Drawing: the predicted estimate and its sigma points (pale blue), the predicted reading as a green bell on the image line, and along the line a green bar with a mark at each end showing the gate: the readings the function will accept. The orange diamond is the frame, filled if it is accepted and hollow if it is refused. The solid blue rod is the estimate afterwards. Plot: the phase plane, with the prediction as a dashed ellipse, the frame as an orange band and the estimate afterwards as a filled ellipse. When the frame is refused the filled ellipse is the prediction.

Try it

  1. The opening frame, 0.34 m, scores above 9 and is refused. Move it left until the diamond fills. The estimate jumps: a gate is all or nothing.
  2. Put the frame back at 0.34 m and raise the angle uncertainty before the gap to 0.2 rad. The green bell widens, the bracket widens with it, and the same frame is accepted. Whether a reading is surprising depends on how sure the filter was.
  3. Raise the camera error. The gate widens again, and an accepted frame moves the estimate less. A gate decides whether to use a reading. The camera’s error decides how much.
  4. Narrow the gate to 1 standard deviation. About a third of honest frames from a well-behaved camera would fall outside it. A gate that tight starves the filter.

A few points of behaviour. A refusal keeps the predicted state and its uncertainty, and leaves the innovation available for your log. step_with_gate also returns false for an empty dynamic measurement and for a numerical failure, which rolls the whole step back as step does. To tell these apart, record the gate’s decision in the function, as the example does with nis, or use the split stages and the gated form of a_posteriori_step.

For more than one reading at a time, the score uses the whole innovation covariance: solve S w = innovation and take the dot product of the innovation with w. A square-root filter holds a factor L of S in innovation_root_covariance; solve L w = innovation and take w·w. Choose the limit for the number of readings and for the share of honest readings you can afford to lose, from a chi-square table if the errors are close to bell-shaped. A gate accepts or refuses the whole measurement vector. Fit each sensor’s error to its measured behaviour before you tune a gate, because a gate cannot repair noise settings which are wrong.

Call a filter from another language

A filter is a C++ template until its state, sensors, precision and core are chosen. After that it is an ordinary type, and a C or Python program can use it through a small compiled interface. The repository’s AHRS example builds a shared library, publishes a C header for its particular state and sensors, and calls it from Python with ctypes. For the pendulum the same pattern would be a function which takes a frame and a time step and returns the angle, the rate and a status. Keep matrix layout, units and precision explicit at that boundary.

Example C interface · Example Python binding

Check your understanding

In the calibration figure, why is the line for a reading at 0 rad horizontal?

With the rod hanging, the weight is directly below the pivot and appears at the centre column whatever the scale. The reading fixes the centre and says nothing about the scale, which is a horizontal line on a plane with the centre on its vertical axis.

You may clamp the rod at only two angles. Which two?

Two far apart, such as −0.6 and 0.6 rad. Their lines cross at the widest angle, so the crossing is pinned down best. Two angles close together give nearly parallel lines and a long, thin ellipse.

After a long gap the first frame is honest but far from the prediction. Will a gate at 3 standard deviations refuse it?

Probably not. The gate compares the innovation with its expected spread, and after a long gap the prediction is uncertain, so the spread is wide. That is the reason to gate on NIS and not on the size of the innovation in metres. If the process noise is set too low, though, the filter will be overconfident after a gap and will refuse frames it should take.

Reference

Parameter estimation and gating
NameWhat it is
UKF::SquareRootParameterEstimationCore<State, Measurement>A filter for coefficients. No process model and no time step.
filter.step(z, inputs…)One reading and the inputs its measurement model needs.
root_covariance, process_noise_root_covariance, measurement_root_covarianceFactors and standard deviations, as for SquareRootCore.
step_with_gate(dt, z, gate, inputs…)For the state filters. The parameter core’s form omits dt. Returns whether a correction was applied.
gate(const Filter&, const Measurement&, const Inputs&…)Your function. It sees the predicted state, innovation and the innovation’s covariance or factor.
a_posteriori_step(gate, context…)The gated correction after separate prediction and innovation steps.

Gate signatures, factor solves and return values · Confidence and outliers · Covariance and parameter noise · calibrate.cpp · gate.cpp