SFWA UKF · Chapter 1 of 7

SFWA UKF overview

A weight on the end of a half-metre rod swings from a pivot. A camera in front of it reports, twenty times a second, how far the weight is to the side of the pivot, give or take a few centimetres. Where is the weight now, and how fast is it moving? The camera cannot say how fast. Any one frame is also a poor guide to where, because its error is as large as the distance the weight moves in a frame.

This is a state estimation problem. The quantities you want to know, here the rod’s angle and its angular rate, are the state. They change over time, and each reading gives a noisy and partial view of them. SFWA UKF is a C++17 library for estimating a state like this when the way it changes, or the way the sensor sees it, is not a straight-line relationship. This guide uses the pendulum and its camera in every chapter. Its companion, the SFWA NMPC guide, swings the same pendulum up with a motor.

Predict, compare, correct

A Kalman filter carries forward an estimate of the state together with its uncertainty: how far from the truth each part of the estimate may be, and how those errors go together. It uses two models. A process model says how the state changes with time. For the pendulum that is gravity pulling the weight back towards the bottom of its swing. A measurement model says what a sensor should report for a given state. For the camera that is the sideways position of the weight, which is the rod’s length times the sine of its angle.

Each time a reading arrives, the filter does three things. It predicts: the process model carries the last estimate forward by the time that has passed, and the uncertainty grows, since the model is never exact. It compares: the measurement model turns the prediction into the reading the filter expects, and the difference between the actual reading and that expectation is the innovation. It corrects: the estimate moves some way towards agreeing with the reading. How far depends on the two uncertainties. A reading with a small error next to an uncertain prediction moves the estimate a long way. A poor reading next to a confident prediction hardly moves it.

Because the process model links the angle to the rate, a run of position readings also tells the filter about the rate, although no sensor measures it. The quickstart shows this on the pendulum. The Unscented Kalman Filter on this site builds the method up from single measurements, with a drone as its example.

Linear, extended or unscented?

The three kinds of Kalman filter differ in how they push an uncertain estimate through a model. The camera makes the difference easy to see. Suppose the estimate before a frame arrives is an angle with some spread: a bell-shaped distribution of possible angles, assumed here because it is what all three filters assume. What reading should the filter expect, and with what spread?

A linear Kalman filter needs both models to be straight lines. For a small swing the sideways position is close to the rod’s length times the angle, and a linear filter using that rule is exact for that rule. With bell-shaped uncertainty and independent noise it gives the exact mean and covariance. The covariance is the table of how large the errors are and how they vary together.

An extended Kalman filter (EKF) replaces a curved model with its tangent at the current estimate. It suits a model whose slope you can work out cheaply and whose slope changes little across the spread of plausible states.

An unscented Kalman filter (UKF) does not flatten the model at all. It picks a few representative states, called sigma points, which have the same mean and covariance as the estimate. It runs the model on each and takes a weighted mean and covariance of the results. For one uncertain quantity there are three points; for n there are 2n + 1. Use it when the spread of plausible states reaches round a bend in the model, or when the model is easy to run but awkward to differentiate.

In the figure the rod is estimated to be 1.2 rad from hanging, well out to the side, where the sine curve is bending over. The blue fan shows the spread of angles, and for the UKF the three thin rods are its sigma points. The dotted lines drop from each weight to the camera’s image line, where the green bell is the reading the chosen method predicts. The dashed outline is the answer found by adding up over a fine grid of every possible angle, weighted by how likely it is.

Drawing: the pendulum seen from the front. The blue rod is the estimated angle and the fan covers one and two standard deviations either side of it. The thin blue rods are the sigma points. The line below the pendulum is the camera’s image line, marked in metres from the pivot. The green bell and diamond show the predicted reading and its mean. The dashed curve is the reference found by adding up over every angle. Plot: the same calculation as a graph. The neutral curve is the camera model. The blue bell on the angle axis is the spread of angles, and the bells against the reading axis are the predicted reading and the reference. A dashed green line is the straight line that the first two methods use in place of the curve.

Try it

  1. Select Straight line through hanging. This rule expects 0.600 m, further out than the half-metre rod can reach, with a spread of 0.150 m. It is the right rule only for a small swing.
  2. Select Tangent at the estimate (EKF). The mean, 0.466 m, is the camera model run at the estimated angle. The reference is lower, 0.446 m, because the weight cannot be further out than 0.5 m however the angle is spread.
  3. Select Sigma points (UKF). One point is on each side of the top of the curve. Their weighted mean is 0.446 m, and the predicted spread is 0.062 m against the reference’s 0.059 m.
  4. Move the estimated angle down to 0.3 rad. Near the bottom of the swing the curve is nearly straight, and the three predicted means agree to within a centimetre. Narrow the standard deviation and they close up further.

With SFWA UKF the camera model is one C++ function. You write what the camera would report for one state, and the library calls it once for each sigma point. This is the function behind the three thin rods.

pendulum.h

// 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>());
}

A slope is never asked for. The same is true of the process model, which is why a model that is simple to run but hard to differentiate is a good fit for this filter. The price is more model evaluations: 2n + 1 for each prediction and again for each reading, where an EKF runs the model once and its derivative once.

What the library does, and what you supply

You supply four things. The first is the state: named fields, each a number, a vector or an orientation. The second is the process model, as a function giving either the next state or the rate of change of the state. The third is the measurement model, one function per sensor. The fourth is numbers: a first estimate, its uncertainty, the uncertainty of the process model over each interval, and the error of each sensor.

The library draws the sigma points, runs your models on them, and carries out the prediction and correction. Sizes are fixed when the program is compiled, so an update does not ask for memory while it runs. There are three filters, called cores.

The three filter cores
CoreStores uncertainty asUse it for
UKF::CoreA covariance matrixA state which changes with time, when you work with covariances directly
UKF::SquareRootCoreA triangular factor of the covarianceThe same problems, where precision or update time is tight
UKF::SquareRootParameterEstimationCoreA triangular factorCoefficients which stay fixed or drift slowly, such as a calibration

The chapters follow the order in which you would write a filter. Quickstart builds the library and runs a complete tracker for the pendulum. State and process models and Measurement models take that tracker apart. Filter cores and the update cycle follows one update by hand and compares the two ways of storing uncertainty. Parameter estimation and innovation gating calibrates the camera and refuses a bad reading. Filter experiments gives you two things to break and mend.

How it does on recorded motion

The pendulum in this guide is simulated. The library’s authors also publish results on two sets of recordings, with a filter designed for orientation tracking, VQF, run on the same samples for comparison. Both sets use an inertial measurement unit: a gyroscope and an accelerometer, each measuring along three axes. The quantity scored is tilt, the part of orientation that gravity fixes.

The BROAD benchmark follows an object turned by hand. The SFWA estimator and VQF estimate tilt from the six signals with no model of what is carrying the sensor. Against an optical reference, their mean tilt errors were within a tenth of a degree of each other across 34 validation recordings, with VQF slightly ahead.

EuRoC provides the same kinds of reading on a flying multirotor. In flight the accelerometer responds to the forces moving the aircraft, so its reading alone is an ambiguous guide to tilt. The SFWA square-root UKF can use a model of thrust and rotor drag to predict how the aircraft’s motion affects that reading. Both estimators receive the same gyroscope and accelerometer samples. The comparison uses a version of VQF configured for the larger gyroscope bias seen on this aircraft.

Six-axis tilt error in degrees. Lower is better.
Recordings and SFWA modelSFWA UKFVQF
BROAD · hand-held, no vehicle model0.920°0.827°
EuRoC · rotor model off1.543°1.615°
EuRoC · rotor model on1.172°1.615°

For each recording, the authors squared the tilt error at each scored instant, averaged the squares and took the square root. The table gives the mean of these root-mean-square (RMS) errors, counting each recording once. The two EuRoC rows replay the same four validation flights and use the same VQF result. Switching on the rotor model reduced the UKF’s mean error by 24% against its own model-off run. Its mean tilt error was then 27% lower than VQF’s.

The figure shows each recording as a pair of dots joined by a line, so you can see whether a difference in the means comes from every recording or from a few.

Each column is one recording. The filled blue dot is the first estimator named in the legend and the ring is the second. The line joining them shows the gap. Dashed lines mark each estimator’s mean over the recordings shown. The values are the published root-mean-square tilt errors for the validation recordings. Gaps in the BROAD numbering are recordings which the authors used for development.

Try it

  1. With Flights · rotor model on selected, the UKF’s dot is below VQF’s on all four flights.
  2. Select Flights · model on and off to see where the vehicle model itself helps. On three flights it lowers the error. On V2_01 it raises it.
  3. Select Hand-held. With no vehicle model to use, the two filters track each other closely, and VQF is lower on most recordings.

The model-off run keeps the UKF’s aircraft-specific sensor settings, which separates the contribution of the vehicle model from that of the gyroscope bias assumptions. The four flights were scored against a reference combining Vicon motion capture and inertial data. The authors made two design choices after seeing validation results, so the percentages describe the measured improvement on these flights and are not a forecast for others.

BROAD results including heading

Total orientation error includes heading as well as tilt. With six axes, heading can drift after the initial alignment. The nine-axis runs also use a magnetometer, which measures the local magnetic field and supplies a heading reference. The table uses the same 34 BROAD recordings.

BROAD validation recordings · mean total orientation RMS error (°)
EstimatorSix axesNine axes
SFWA UKF6.3742.486
SFWA square-root UKF6.3742.486
Madgwick23.7945.591
Mahony72.62030.444
VQF6.2772.589

The two UKF cores used the same model and settings. VQF had the lowest six-axis total error. With the magnetometer, the UKF had the lowest total error and less than half the error of Madgwick at its tested gain. The separate Sassari validation set gave a nine-axis total of 4.511° for the UKF and 4.580° for VQF across 12 recordings.

BROAD results · per-recording scores · orientation scoring and filter configurations · EuRoC results by flight · per-flight scores · models, reference and evaluation method · BROAD estimator · EuRoC estimator and model switch

Will an update fit in the sampling interval?

At 500 samples a second, a new sample arrives every 2,000 microseconds. The authors timed a complete estimator update and orientation readout on a physical STM32H735 microcontroller running at 550 MHz. The covariance core took 162 µs per update on average and the square-root core 169 µs. Across 12,000 measured updates per core with generated nine-axis readings, the slowest took 189 µs and 200 µs. That left at least 1.8 ms of each interval for reading sensors and running the rest of the application in these tests.

The processor used hardware floating-point arithmetic with 32-bit numbers. The benchmark used the GCC 14.3.1 compiler’s -O2 optimisation setting. Asking the compiler to favour a smaller program with -Os saved about 18 KB of flash memory and raised the mean update times to 391 µs and 379 µs. These figures are for that estimator’s state and sensors. For a different state, sample rate or processor, time the update with the model and compiler settings you plan to use.

Board, timing logs and reproduction commands

Where the library fits

On a desktop or single-board computer, the library needs a C++17 compiler and Eigen for matrix operations. The implementation is in its headers, which you compile with your own models. The project tests GCC and Clang on Linux and Clang on macOS, with both 32-bit and 64-bit floating-point numbers. A desktop replay is the place to check sensor units and compare predicted readings with recorded measurements before moving a model to a smaller target.

On a microcontroller, it helps to know how much memory an update can use. You declare the state size and the largest possible set of readings at compile time, even when individual readings come and go, so Eigen does its work without asking the heap for memory during an update. The library reports a failed update through its return value and can be built with C++ exceptions disabled. Allow stack space for temporary matrices and measure its use on your target. The STM32H735 timings above ran on hardware. The published ESP32-S31 timings came from an emulator.

Build requirements and tested configurations · ESP32-S31 build and measurement conditions

Check your understanding

The camera never reports a rate. How can the filter estimate one?

The process model ties the two together: a rate carries the angle forward between frames. If the predicted positions keep falling short of the frames, the estimated rate was too low, and each correction adjusts it along with the angle. The quickstart’s figure plots the rate estimate against the simulated truth.

With the rod estimated near the bottom of its swing, is there any reason to prefer the UKF for this camera?

Little, as far as this one reading goes. Near hanging, the sine is close to a straight line over the spread of angles, and the figure shows the three predictions within millimetres of each other. The case for the UKF comes from the rest of the swing, from a wide spread after frames are missed, and from not having to write derivatives.

Why is the reference reading lower than the camera model run at the estimated angle?

The sine curve bends downward near the top. Angles either side of 1.2 rad both give readings below a straight-line extension of the curve, and none can exceed 0.5 m. Averaging over the spread therefore gives less than the reading at the middle angle. The tangent cannot show this, because a straight line has no bend.

Reference

Terms used throughout the guide
TermMeaning
StateThe quantities being estimated: here the angle from hanging, in radians, and its rate, in radians per second.
CovarianceThe uncertainty of the state: a variance for each quantity and a covariance for each pair.
Process modelYour function for how the state changes with time.
Measurement modelYour function for what a sensor reports in a given state.
Sigma pointsThe 2n + 1 states the filter runs your models on, for n uncertain quantities.
InnovationA reading minus the reading the filter predicted.

SFWA UKF repository · Models, noise and filter updates · Core.h