SFWA UKF · Chapter 2 of 7

Quickstart: track a pendulum in C++

By the end of this chapter you will have built the library, run a filter that tracks the guide’s pendulum from camera frames, and matched each line it prints to a picture of what happened. Then you will read the program’s four parts, which the next three chapters take in turn.

1. Get the source

Work in a fresh directory, so that the source, the build products and the installed headers are easy to find. The checkout below pins the revision of UKF 1.0.0-dev that every example in this guide was run against.

mkdir ukf-guide
cd ukf-guide
git clone https://github.com/sfwa/ukf.git ukf
git -C ukf checkout --detach 83995d0d26322c56b1c930b12c2ecc528b5fa36f

If you prefer a source download, extract the archive of the same revision into ukf-guide/ukf and continue from ukf-guide.

2. Build the library’s tracking example

UKF is header-only: there is no library to compile, only headers which you compile with your own models. Building one of its examples therefore exercises the compiler, Eigen and the filter together. The first build fetches Eigen 3.2.8 and applies the library’s patches to it. The options skip the unit tests and benchmarks, which need Google Test and Google Benchmark.

cmake -S ukf -B build-ukf -DCMAKE_BUILD_TYPE=Release \
  -DUKF_BUILD_TESTS=OFF -DUKF_BUILD_BENCHMARKS=OFF \
  -DCMAKE_INSTALL_PREFIX="$PWD/ukf-install"
cmake --build build-ukf --target ukf_tracking_example --parallel 2
./build-ukf/examples/tracking/ukf_tracking_example

The example estimates the position and velocity of a body moving along a line, from readings it generates itself. Two of the lines it prints tell you the build is sound.

Position RMSE: raw=1.2913, estimated=0.2335
Injected outliers rejected: 11/11

The executable checks its own estimates and exits with status zero on success.

3. Install the headers

cmake --install build-ukf

This puts the UKF headers, the patched Eigen headers and a CMake package under ukf-install. A project finds them through CMAKE_PREFIX_PATH and links one of two targets. ukf::double makes the library’s number type, real_t, a double. ukf::single makes it a float. Use one of them consistently in everything that shares a model.

find_package(ukf REQUIRED CONFIG)
add_executable(track track.cpp)
target_link_libraries(track PRIVATE ukf::double)

The lookup has no version number because this development revision comes before the 1.0 release. A project which keeps the UKF source in its own tree can use add_subdirectory(ukf) in place of find_package.

4. Build the guide’s examples and run the tracker

Download the examples and save the ZIP in ukf-guide, beside ukf-install. It holds every program in this guide and a CMakeLists.txt with the three lines above for each.

unzip ukf-examples.zip
cmake -S ukf-examples -B build-examples -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_PREFIX_PATH="$PWD/ukf-install"
cmake --build build-examples --parallel 2
./build-examples/track
t 0.25 s  frame  0.216 m  angle  0.419 rad (true  0.480)  rate  -3.24 rad/s (true  -3.18)
t 0.50 s  frame -0.216 m  angle -0.405 rad (true -0.415)  rate  -3.07 rad/s (true  -3.30)
t 0.75 s  frame -0.370 m  angle -0.841 rad (true -0.855)  rate   0.04 rad/s (true  -0.02)
t 1.00 s  frame -0.213 m  angle -0.426 rad (true -0.444)  rate   3.10 rad/s (true   3.17)
t 1.25 s  frame  0.121 m  angle  0.373 rad (true  0.411)  rate   3.00 rad/s (true   2.87)
t 1.50 s  frame  0.395 m  angle  0.828 rad (true  0.768)  rate   0.03 rad/s (true  -0.14)
t 1.75 s  frame  0.183 m  angle  0.375 rad (true  0.308)  rate  -2.99 rad/s (true  -3.11)
t 2.00 s  frame -0.230 m  angle -0.443 rad (true -0.462)  rate  -2.71 rad/s (true  -2.55)
t 2.25 s  frame -0.407 m  angle -0.800 rad (true -0.759)  rate   0.29 rad/s (true   0.44)
t 2.50 s  frame -0.113 m  angle -0.277 rad (true -0.281)  rate   3.11 rad/s (true   2.98)
t 2.75 s  frame  0.167 m  angle  0.482 rad (true  0.438)  rate   2.39 rad/s (true   2.15)
t 3.00 s  frame  0.359 m  angle  0.710 rad (true  0.634)  rate  -0.62 rad/s (true  -0.69)
t 3.25 s  frame  0.149 m  angle  0.189 rad (true  0.154)  rate  -2.87 rad/s (true  -2.90)
t 3.50 s  frame -0.200 m  angle -0.498 rad (true -0.492)  rate  -1.94 rad/s (true  -1.78)
t 3.75 s  frame -0.272 m  angle -0.613 rad (true -0.584)  rate   0.93 rad/s (true   1.07)
t 4.00 s  frame  0.009 m  angle -0.077 rad (true -0.066)  rate   2.75 rad/s (true   2.61)
angle error after 0.5 s: 0.077 rad RMS from single frames, 0.035 rad RMS from the filter
rate error after 0.5 s: 0.15 rad/s RMS from the filter; the camera does not measure rate

The last digits can differ with your compiler and processor. The program exits with status zero if the filter’s angle is closer to the truth than the angle a single frame implies.

5. Read the output

track simulates the pendulum of the overview: a 0.5 m rod released at rest 0.9 rad from hanging, pushed about a little by draughts. A simulated camera reports the sideways position of the weight every 0.05 s, with an error whose standard deviation is 3 cm. The filter is told none of the true motion. It starts by guessing that the rod hangs at rest, and it is unsure of that guess by half a radian.

Each printed line is one frame in five: the time, the frame, and the filter’s estimates of the angle and the rate, with the simulated truth in brackets. The figure replays the recording of this run. Its slider steps through the frames, and under it is the line the program printed for that frame.

Drawing: the simulated pendulum (solid rod), the filter’s estimate (blue rod with a ring) and a blue fan two standard deviations either side of it. The orange diamond on the image line is the camera frame, in metres to the side of the pivot. Upper plot: the angle against time. The neutral line is the simulated pendulum, the blue line and band are the estimate and two standard deviations, and each orange dot is the angle one frame would imply if it were taken at face value. Lower plot: the angular rate, which the camera does not measure, with the same colours. The vertical line marks the selected frame.

Try it

  1. Move the slider to zero. The blue fan is wide: this is the first guess, good to within 0.5 rad. Step forward one frame. The fan closes to 0.074 rad, because a single frame says a good deal about the angle.
  2. Stop at 0.25 s and compare the line under the slider with the first line in your terminal.
  3. Look at the orange dots in the angle plot. They scatter about the neutral line by a few hundredths of a radian, and by more near the ends of the swing, where a centimetre sideways is a larger change of angle. The blue line passes among them.
  4. Look at the rate plot. No orange dots: nothing measures the rate. The estimate still follows the truth, because a wrong rate would make the next predicted position wrong.

The last two printed lines score the run after its first half second. Taking each frame at face value gives an angle wrong by 0.077 rad RMS. The filter’s angle is wrong by 0.035 rad RMS and its rate by 0.15 rad/s RMS. RMS is the root of the mean of the squared errors, so errors in either direction count.

6. The four parts of the program

The tracker is two files. pendulum.h describes the pendulum and the camera to the library. track.cpp sets the filter up and runs it. A third file, simulate.h, stands in for the real pendulum and camera, and you can leave it unread.

The state names what the filter estimates. Each field has a key and a type. State and process models covers the choice of fields and their uncertainty.

pendulum.h

// 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/s

The process model says how the state changes. Here it gives the rate of change of each field, and the library integrates it over the time between frames. The angle changes at the rate. The rate changes because gravity and friction turn the rod.

pendulum.h

// 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 measurement model names each sensor reading and says what it should be for a given state. Measurement models follows one frame through it.

pendulum.h

// 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

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

The filter is a type made from the state, the measurement and an integrator. Before the first update it needs a first estimate, the uncertainty of that estimate, the uncertainty the process model adds over one interval, and the camera’s error as a variance.

pendulum.h

// The filter: this state, this measurement, and a fourth-order integrator for the model.
using Tracker = UKF::Core<State, Frame, UKF::IntegratorRK4>;

track.cpp

const real_t dt = 0.05;             // s between frames
const real_t camera_sigma = 0.03;   // m, standard deviation of the camera's error
const real_t gust_intensity = 0.05; // rad^2/s^3, how hard draughts push the weight

Tracker filter;
filter.state.set_field<Angle>(0.0);  // first guess: hanging at rest
filter.state.set_field<Rate>(0.0);
filter.covariance.setZero();
filter.covariance(0, 0) = 0.5 * 0.5;  // but unsure by about 0.5 rad
filter.covariance(1, 1) = 2.0 * 2.0;  // and by about 2 rad/s
filter.process_noise_covariance = interval_noise(dt, gust_intensity);
filter.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);

The loop then repeats one call for every frame. step predicts, compares and corrects, and returns false if the arithmetic failed, in which case it leaves the estimate as it was. Filter cores and the update cycle opens that call up into its three stages.

track.cpp

for (int k = 1; k <= 80; k++) {
    bench.advance(dt);
    Frame frame;
    frame.set_field<BobX>(bench.camera(camera_sigma));

    if (!filter.step(dt, frame)) return 1;  // predict, compare, correct

    const real_t angle = filter.state.get_field<Angle>();
    const real_t rate = filter.state.get_field<Rate>();
    // The rest of the loop prints one frame in five, records the run and scores it.
}

If your build looks different

Check your understanding

The program gives the camera’s error as camera_sigma * camera_sigma. Why the square?

UKF::Core stores variances, and a variance is a standard deviation squared: 0.03 m becomes 0.0009 m². The square-root core takes the standard deviation itself. Filter cores has the table.

What would you change to track a rod of a different length?

kLength in pendulum.h. It appears in both models: in the process model through the rod’s inertia and the torque of its weight, and in the measurement model as the scale between the sine of the angle and the sideways position.

Near 0.75 s the weight is at the end of its swing. Why do single frames give a worse angle there?

The camera sees sideways position, 0.5 sin(angle). At the end of the swing the rod is further from vertical, the sine curve is flatter, and the same 3 cm of camera error covers more angle. The overview’s figure shows the curve.

Reference

What the tracker uses
NameWhat it isChapter
UKF::StateVector, UKF::FieldThe state, as named fieldsModels
State::derivative<>()The process model, as a rate of changeModels
UKF::FixedMeasurementVectorThe readings of one updateMeasurements
expected_measurementThe measurement model for one sensorMeasurements
UKF::Core, stepThe filter and one whole updateFilters
covariance, process_noise_covariance, measurement_covarianceThe three uncertainties you setFilters

CMake integration options · The library’s tracking example · All of this guide’s examples