The camera has just lost sight of the weight behind a post. For the next half second the filter has nothing to go on but its last estimate and its model of the pendulum. Where will it say the rod is when the weight comes back into view, and how sure should it be?
The answer depends on three things you write: what the state holds, how the process model moves it, and how far you allow that model to be wrong. This chapter takes them in that order, using the first half of pendulum.h from the quickstart.
Choose what the state holds
The state holds what you need to know now in order to predict what comes next. For the pendulum that is two numbers. The angle alone is not enough, since a rod at 0.6 rad may be on its way out or on its way back. The angle and the rate together fix the rest of the swing.
// What the filter estimates. Each field has a key, a type and, by convention, a unit.
enum StateKey { Angle, Rate };
using State = UKF::StateVector<
UKF::Field<Angle, real_t>, // rad, from hanging straight down
UKF::Field<Rate, real_t>>; // rad/sEach field has a key, unique within its state, and a type. real_t is the library’s number type, a double or a float according to the CMake target you link. A field can also be a UKF::Vector<N> or a UKF::Quaternion. You read and write a field by its key, as in state.get_field<Angle>() and state.set_field<Rate>(0.0), which keeps the meaning of each number visible where it is used.
Quantities you already know stay out of the state. The rod’s length, the mass of the weight and the friction at the pivot are constants in the same header.
constexpr real_t kLength = 0.5; // m, pivot to the centre of the weight
constexpr real_t kMass = 0.2; // kg, at the end of a massless rod
constexpr real_t kDamping = 0.005; // N m s/rad, friction at the pivot
constexpr real_t kGravity = 9.80665; // m/s^2
constexpr real_t kInertia = kMass * kLength * kLength; // kg m^2
constexpr real_t kWeightTorque = kMass * kGravity * kLength; // N m, with the rod levelLeaving them out keeps the filter small. Its work grows with the number of uncertain quantities, n: it runs your models on 2n + 1 states at every update. For this state that is five.
An estimate is a region
The filter never holds only a best guess. It holds the guess and a covariance: the variance of the angle, the variance of the rate, and one more number, their covariance, which says whether the two errors tend to go together. Drawn on a plane with the angle across and the rate up, the estimate is an ellipse. Its width is the uncertainty of the angle and its height that of the rate. A tilt means the errors are correlated: if the angle is higher than estimated, the rate probably is too.
From this ellipse the library draws five sigma points: the estimate itself and two pairs on opposite sides of it. Together they have the same mean and covariance as the ellipse. They are the only states your models are ever run on. In the figure each one is a dot on the plane and, in the drawing, a rod with an arrow for its rate.
filter.state.set_field<Angle>(0.6); // rad
filter.state.set_field<Rate>(-2.0); // rad/s
filter.covariance << 0.0225, 0.0600, // angle variance, covariance
0.0600, 0.6400; // covariance, rate variance
// At namespace scope, before any filter uses State:
namespace UKF::Parameters {
template <> constexpr real_t Kappa<State> = 3.0;
}filter.state.set_field<Angle>(0.6); // rad
filter.state.set_field<Rate>(-2.0); // rad/s
filter.covariance << 0.0225, 0.0600, // angle variance, covariance
0.0600, 0.6400; // covariance, rate variance
// At namespace scope, before any filter uses State:
namespace UKF::Parameters {
template <> constexpr real_t Kappa<State> = 3.0;
}
Try it
- Set the correlation to zero. The ellipse stands upright and the two covariance entries in the listing become zero. Points 1 and 3 now differ from the estimate only in angle.
- Raise the correlation to 0.9. The ellipse leans, and points 1 and 3 carry a change of rate along with their change of angle. A reading of the angle alone will now say something about the rate.
- Lower Kappa from 3 to 0. The four outer points move in towards the estimate and the centre’s weight falls to zero. The ellipse does not change: the points are a different summary of the same uncertainty.
The distance of the outer points from the estimate is set by two numbers, α² and κ. The library scales the covariance’s square root by √(α² (n + κ)). A third, β, changes how much the centre point counts when a covariance is worked out from the points after a model has bent them. The defaults are α² = 1, β = 0 and κ = 3. You change them by specialising AlphaSquared, Beta and Kappa for your state type, as the last lines of the example do for κ. Keep α² well above 10−6 in single precision: a small value puts the points close together with very large weights, which magnifies rounding error. Filter experiments lets you try all three on the camera’s curve.
Carry every point forward
A process model says how a state changes with time. The pendulum’s is a rate of change. The angle changes at the rate, and the rate changes at the angular acceleration: the torque of the weight and of friction, divided by the rod’s inertia.
// The process model: how fast each field is changing, for any state.
template <>
template <>
inline State State::derivative<>() const {
State rate_of_change;
rate_of_change.set_field<Angle>(get_field<Rate>());
rate_of_change.set_field<Rate>(
(-kDamping * get_field<Rate>() - kWeightTorque * std::sin(get_field<Angle>())) / kInertia);
return rate_of_change;
}The two template <> lines mark this as your version, for your state, of a function the library declares. It goes in namespace UKF. It must give the same answer every time for the same state: the uncertainty is handled outside it.
A rate of change is not yet a prediction. Something has to add it up over the time between frames, and that is an integrator. You name one when you declare the filter.
// The filter: this state, this measurement, and a fourth-order integrator for the model.
using Tracker = UKF::Core<State, Frame, UKF::IntegratorRK4>;The library has three. IntegratorEuler takes the rate at the start and assumes it holds for the whole step: one call of derivative for each sigma point. IntegratorHeun averages the rate at the start with the rate where Euler lands: two calls. IntegratorRK4 samples the rate four times across the step. With five sigma points that is 5, 10 or 20 calls of your function for each prediction.
The figure predicts half a second ahead from a rough estimate: the rod at 0.9 rad and at rest, good to within 0.15 rad and 0.5 rad/s. The grey arrows show which way the model moves a state from each place on the plane. The green lines follow the five sigma points, step by step, and the green ellipse is the prediction. The cloud of small dots is 300 states drawn from the blue ellipse and carried forward with a very fine step, for comparison.
using Predictor = UKF::Core<State, Frame, UKF::IntegratorRK4>;
Predictor filter; // the rod at 0.9 rad and at rest, within 0.15 rad and 0.5 rad/s
const int steps = 5;
const real_t dt = 0.5 / steps;
filter.process_noise_covariance.setZero(); // trust the model, for this comparison
for (int i = 0; i < steps; i++) {
if (!filter.a_priori_step(dt)) return 1; // predict only: there is no frame to compare with
}using Predictor = UKF::Core<State, Frame, UKF::IntegratorRK4>;
Predictor filter; // the rod at 0.9 rad and at rest, within 0.15 rad and 0.5 rad/s
const int steps = 5;
const real_t dt = 0.5 / steps;
filter.process_noise_covariance.setZero(); // trust the model, for this comparison
for (int i = 0; i < steps; i++) {
if (!filter.a_priori_step(dt)) return 1; // predict only: there is no frame to compare with
}
Try it
- Select Euler and set one step. The green lines are straight: each point keeps its starting rate of zero for the whole half second, so the angle does not move at all, while the rate is far too large.
- Raise the number of steps. Euler’s prediction approaches the cloud but still sits to one side of its centre at ten steps.
- Select RK4 and one step. Even the fourth-order integrator misses when the step is a third of the pendulum’s period.
- Give RK4 five steps. The green ellipse now sits on the cloud. The readout shows a difference from the fine step of less than a thousandth of a radian.
predict prints the same comparison from the library. Each row is an integrator; the columns are the predicted angle and rate in one, five and ten steps.
Half a second ahead, in 1, 5 and 10 steps:
Euler 0.9000 rad -7.5962 rad/s -0.4946 rad -5.0762 rad/s -0.4988 rad -4.0481 rad/s
Heun -0.9990 rad -7.2894 rad/s -0.4803 rad -3.1434 rad/s -0.4445 rad -3.1782 rad/s
RK4 -0.2899 rad -2.1885 rad/s -0.4331 rad -3.2011 rad/s -0.4335 rad -3.2008 rad/s
RK4 in 100 steps: -0.4336 rad -3.2007 rad/s
The last line is the reference. RK4 in five steps is within 0.0005 rad of it. Euler in ten steps is still 0.065 rad away. A practical check on your own model is the one this program makes: halve the step and see whether the prediction moves.
// Predict "seconds" ahead in equal steps, with process noise of intensity q for each step.
template <typename Integrator>
Estimate ahead(const Estimate& from, real_t seconds, int steps, real_t q) {
Predictor<Integrator> filter;
filter.state = from.state;
filter.covariance = from.covariance;
const real_t dt = seconds / steps;
filter.process_noise_covariance = interval_noise(dt, q);
for (int i = 0; i < steps; i++) {
if (!filter.a_priori_step(dt)) std::printf("prediction failed\n");
}
return {filter.state, filter.covariance};
}a_priori_step(dt) is the prediction on its own, with no reading. If your model has an exact answer for the next state, you can skip the integrator: leave the third template argument out and specialise State::process_model<>(real_t dt) to return the next state directly. Filter cores has an example.
Allow the model to be wrong
The model above is too tidy. A real pendulum is pushed about by draughts, its friction is not exactly as measured, and the rod flexes. None of that is in derivative. If the filter believed its model completely, its uncertainty would stay small for as long as it predicted, and it would then give a late frame too little weight.
Process noise is how you tell the filter that the model drifts. After carrying the sigma points forward, the library adds a covariance Q to the result. You choose Q for the interval just predicted. For the pendulum, suppose draughts give the weight a random angular acceleration of intensity q, in rad²/s³, for the whole interval. Over dt seconds that adds q·dt to the variance of the rate, q·dt³/3 to the variance of the angle, and q·dt²/2 to their covariance.
// How far the model can be wrong after dt seconds. Draughts push the weight at random:
// an angular acceleration with intensity q, in rad^2/s^3, acting for the whole interval.
inline State::CovarianceMatrix interval_noise(real_t dt, real_t q) {
State::CovarianceMatrix noise;
noise << dt * dt * dt / 3, dt * dt / 2,
dt * dt / 2, dt;
return q * noise;
}Assign it to filter.process_noise_covariance before predicting, and work it out again whenever the interval changes. The library does not rescale it for you. The simulated pendulum of this guide is pushed with an intensity of 0.05, and the tracker is told the same number.
The figure starts from the tracker’s usual confidence, within 0.025 rad and 0.13 rad/s, and predicts for as long as you choose with no frames.
const real_t dt = 0.05; // s, one frame
filter.process_noise_covariance = interval_noise(dt, 0.05); // q in rad^2/s^3
for (int missed = 0; missed < 20; missed++) {
if (!filter.a_priori_step(dt)) return 1;
}const real_t dt = 0.05; // s, one frame
filter.process_noise_covariance = interval_noise(dt, 0.05); // q in rad^2/s^3
for (int missed = 0; missed < 20; missed++) {
if (!filter.a_priori_step(dt)) return 1;
}
Try it
- Set the intensity to zero and change the length of the gap. The green ellipse turns and changes shape as the pendulum swings, but stays about the size of the dashed one: with a perfect model there is nothing to make it grow.
- Set the intensity back to 0.05. After one second the green ellipse is clearly larger than the dashed one, and it covers the cloud.
- Raise the intensity to 0.5. The uncertainty of the rate grows fastest, because the pushes act on the rate directly and reach the angle only through it.
The second half of predict’s output gives the standard deviations as the gap grows, with the model trusted and with draughts allowed.
Standard deviations as a gap grows, in steps of 0.05 s:
gap model trusted, q = 0 draughts allowed, q = 0.05
0.0 s 0.025 rad 0.130 rad/s 0.025 rad 0.130 rad/s
0.5 s 0.028 rad 0.118 rad/s 0.040 rad 0.154 rad/s
1.0 s 0.034 rad 0.088 rad/s 0.052 rad 0.173 rad/s
1.5 s 0.023 rad 0.134 rad/s 0.052 rad 0.234 rad/s
2.0 s 0.024 rad 0.139 rad/s 0.053 rad 0.285 rad/s
After two seconds the trusted model still claims the rate to within 0.14 rad/s. With draughts allowed, the filter says 0.28 rad/s, twice as wide. The uncertainty of the angle does not grow steadily in either column. It rises and falls with the swing, as the ellipse turns.
The square-root core takes a factor of Q in process_noise_root_covariance; see Filter cores. Process noise is also the knob you will tune most. Too little, and the filter ignores readings which disagree with its model. Too much, and it follows every noisy frame.
Tell the model what you already know
Suppose a motor at the pivot applies a torque that your program sets. That torque is not something to estimate: you know it. Pass it to the filter as an input, and both models receive it. An input is any type of your own, and your specialisations name that type.
// An input is any type of your own. The library hands it to both models.
struct Motor {
real_t torque; // N m
};
namespace UKF {
template <>
template <>
State State::derivative<Motor>(const Motor& motor) const {
State rate_of_change;
rate_of_change.set_field<Angle>(get_field<Rate>());
rate_of_change.set_field<Rate>((motor.torque - kDamping * get_field<Rate>() -
kWeightTorque * std::sin(get_field<Angle>())) / kInertia);
return rate_of_change;
}
// The camera takes no notice of the motor, but it is given the same inputs.
template <>
template <>
real_t Frame::expected_measurement<State, BobX, Motor>(const State& state, const Motor&) {
return kLength * std::sin(state.get_field<Angle>());
}
} // namespace UKFInputs follow the measurement in the call.
if (!told.step(dt, frame, motor)) return 1; // inputs follow the measurementdriven runs the tracker on a simulated pendulum whose motor pushes with a steady 0.15 N m, once with the torque passed in and once without.
rate error after 1 s: 0.14 rad/s RMS when the filter is given the torque, 0.40 when it is not
When you do not know the torque, the state has to make room for it. Filter experiments takes that case.
When the state is an orientation
The pendulum turns about one axis, so one number describes its orientation. A body free to turn about any axis needs a UKF::Quaternion field. A unit quaternion stores four numbers, but its length is fixed, so it can only be wrong in three independent ways. The library builds the sigma points and the covariance in those three rotation coordinates, applies a correction as a rotation, and keeps the quaternion at unit length. Ordinary number and vector fields use plain addition.
enum Key { Attitude, AngularRate };
using Turntable = UKF::StateVector<
UKF::Field<Attitude, UKF::Quaternion>, // orientation
UKF::Field<AngularRate, UKF::Vector<3>>>; // rad/s about each axis
static_assert(Turntable::size() == 7, "four quaternion coefficients and three rates");
static_assert(Turntable::covariance_size() == 6, "three rotation errors and three rate errors");
static_assert(Turntable::num_sigma() == 13, "one centre point and two for each uncertain dimension");Size the uncertainty with Turntable::CovarianceMatrix and covariance_size(), which count the uncertain dimensions and not the stored numbers. Set the quaternion to a unit rotation before the first update, and write down which frame it turns into which. An angular rate has three components in rad/s; your derivative supplies the kinematics that turn it into the rate of change of the four quaternion coefficients. The library’s attitude example shows one convention worked through.
Check your understanding
You add the friction coefficient to the state so that the filter can estimate it. How many sigma points are there now?
Seven: 2 × 3 + 1. Every prediction and every reading now runs your models on seven states, and the covariance grows from 2 × 2 to 3 × 3.
In the first figure, why do the rods of sigma points 2 and 4 lie on the estimate’s rod whatever the correlation?
The points are the estimate plus and minus the columns of a triangular square root of the covariance. Its second column has no angle part, so points 2 and 4 change only the rate. The correlation appears in the first column, which gives points 1 and 3 a change of rate along with their change of angle. Filter cores draws the two columns.
The camera runs at 20 frames a second but a frame is sometimes dropped. What must change in the prediction for the frame after a gap?
Two things: the interval passed to the step, 0.1 s and not 0.05 s, and the process noise, worked out for that interval with interval_noise(0.1, q). Check too that your integrator still follows the model over the longer step, or predict twice.
Reference
| Name | What it is |
|---|---|
UKF::StateVector<UKF::Field<Key, Type>…> | A state type. Field types are real_t, UKF::Vector<N> and UKF::Quaternion. |
get_field<Key>(), set_field<Key>(value) | Read and write one field. |
State::derivative<Inputs…>(inputs…) | The process model as a rate of change. Needs an integrator. |
State::process_model<Inputs…>(dt, inputs…) | The process model as the next state. Used when no integrator is named. |
UKF::IntegratorEuler, IntegratorHeun, IntegratorRK4 | One, two or four calls of derivative for each sigma point and step. |
UKF::Parameters::AlphaSquared, Beta, Kappa | Sigma-point settings for a state type. Defaults 1, 0 and 3. |
filter.covariance | The uncertainty of the estimate, State::CovarianceMatrix. |
filter.process_noise_covariance | Q for the interval about to be predicted, added after the sigma points are carried forward. |
filter.a_priori_step(dt, inputs…) | Prediction alone. Returns false and changes nothing if it fails. |
covariance_size(), num_sigma() | The number of uncertain dimensions n, and 2n + 1. |
StateVector.h: fields, weights and defaults · Integrator.h · Process models and inputs · Initialisation and covariance · predict.cpp · driven.cpp · rotation.cpp