The Unscented Kalman Filter

A multirotor drone needs to know which way it is tilted to keep its balance. To follow a path, it also needs estimates of its speed and position. Its sensors do not provide all of these quantities directly, and their readings contain errors.

Two sensors are central to this task. A gyroscope measures how fast the drone turns about each of its three axes. In a typical small gyroscope, tiny masses vibrate inside a chip. Turning the chip produces a sideways motion of those masses, which an electrical circuit measures. The faster the turn, the larger that motion.

An accelerometer contains a tiny mass held by flexible supports. When the drone is pushed, the supports push the mass along with it. The sensor measures the small displacement that results. It measures the effect of forces such as rotor thrust or a supporting hand, per unit mass. Gravity acts on both the mass and its surroundings, so in free fall it reads zero. We will return to why this matters in flight.

A filter combines these imperfect readings with a mathematical model: a set of equations that describes how the drone moves and what its sensors should read. For example, if we know its current position and speed, a model can predict its position a short time later. The filter compares its prediction with the next reading and updates its estimate. This article develops that idea into an unscented Kalman filter.

Here is the filter running on readings from a real flight. It estimates the drone’s attitude, or orientation. The ghosted blue drone shows that estimate. The solid drone shows a separate reference, built from motion capture and sensor data after the flight, so we can compare the two. The dial shows their tilt: how far, and in which direction, they lean from upright. Drag the figure to turn the view.

Recording V1_02_medium of the EuRoC dataset. The blue ghost and dot show the filter’s attitude estimate; the solid drone and ring show the reference. The filter reads only the gyroscope and accelerometer. Both drones follow the recorded reference position, because this filter does not estimate position.

Over this flight, the filter’s tilt error relative to the reference is 0.86 degrees. This is the root mean square error: square the error at each moment, average those squares, then take the square root. It gives a measure of error over the flight, with more weight on large errors. The filter achieves this using only the gyroscope and accelerometer.

The figures use three colours. Blue shows the estimate and its uncertainty. Orange shows sensor readings, or samples drawn from their assumed uncertainty. Green shows predictions from the model. White or dark marks, depending on your display theme, show a known value or a separate reference.

We will start with repeated measurements of height and learn how to combine a reading with a prediction. Then we will track a moving drone, see how position readings reveal speed, and handle models that involve angles and curves. Finally, we will use those ideas to follow a complete update of the filter running on this flight.

A reading is not the truth

For our first example, imagine a quadcopter—a drone with four rotors—hovering one metre above the floor. A range sensor on its underside measures the distance to the floor repeatedly. The quadcopter stays at the same height, but small random errors make the readings vary. We call this variation sensor noise.

For this example, we assume that the errors follow a bell curve, also called a normal distribution. Errors near zero are common; large errors are less common, with positive and negative errors equally likely. Real sensor noise does not always have this shape. Vibration, occasional bad readings, and persistent offsets can all break the assumption.

In the figure, each orange dot is a reading. The bars count readings in small height intervals. As more readings arrive, the bars approach the bell shape we assumed. Move the slider to change the noise and watch the range of readings widen or narrow.

The width of the bell describes the spread of the readings. Here, “spread” means one standard deviation, a measure of uncertainty. For a bell curve, about two readings in three lie within one spread of the true height, and about 99.7% lie within three. A smaller spread means less random error.

Each dot is one reading. The line is the true height. The bars on the right count how often each height was read.

A bell curve is described by its mean—the average at its centre—and its spread. For a single quantity, the filter uses these two numbers to describe its estimate and uncertainty. A narrow bell expresses greater certainty; a wide bell expresses greater uncertainty.

Two estimates are better than one

Suppose our quadcopter is moving along a line. The filter’s last position estimate was 2.5 metres, and its estimated speed was 1 metre per second. A model that assumes constant speed predicts a position of 3.5 metres one second later. That prediction is uncertain because the earlier position and speed were uncertain, and the speed may have changed.

Now a position sensor reports 6.5 metres. We have two sources of information about the same position: the prediction, which carries forward earlier information, and a new reading. We will represent each with a bell curve and assume their errors are independent, so the new reading does not count information we already used.

Combining them gives an estimate between the two centres, nearer the one with less uncertainty. Give the filter and the estimate moves almost all the way to the reading. Give it and it stays near the prediction.

The fraction of the distance from the prediction to the reading is called the gain. A gain of 0 ignores the reading; a gain of 1 moves all the way to it. The filter calculates the gain from the two spreads:

gain = p² / (p² + r²)

Here p is the prediction’s spread and r is the reading’s spread. Their squares are called variances. We choose or measure the uncertainties; the filter then calculates the gain from them. In the figure below, drag the two centres and change the spreads to see how the combined estimate responds.

Drag the prediction and the reading, and change their spreads. The combined estimate follows.

The combined bell is narrower than either input bell. Under our assumptions, the new reading reduces uncertainty even when it is quite noisy. If the errors share a common cause, or the spreads are set too low, the filter can become more certain than the evidence supports.

Things move

The filter must keep predicting as the quadcopter moves between readings. The part of the model that describes this motion is called the process model. Our constant-speed example used a simple one:

new position = old position + speed × elapsed time

That model cannot predict every change in motion. Even a gradual change in speed will move the quadcopter away from its predicted position. The filter accounts for effects missing from its model by adding uncertainty at each update. This added uncertainty is called process noise, or model noise. More model noise makes the prediction widen faster.

The white quadcopter below changes speed smoothly, while the model continues at a constant speed. The green quadcopters are estimates of where it could be now. Their spread grows as time passes without another reading. Change the model noise to see how much uncertainty the filter allows for.

The filter knows the position well at the start. The green quadcopters are estimates of where it could be now. Their bell curve is the prediction. The white quadcopter (dark in the light theme) is where it really is.

Predict, then correct

Now put the two operations together. The filter predicts the next position and increases its uncertainty. When a reading arrives, it combines the reading with the prediction and reduces its uncertainty. Repeating this loop gives a Kalman filter, named after Rudolf Kalman, who published the method in 1960.

For the next example, the filter also uses an accelerometer to predict changes in speed between position readings. We assume the drone stays level, so we can use its horizontal acceleration directly. Switch that input off and the model assumes constant speed. The blue band shows the position estimate plus or minus two spreads; the lower plot shows the spread alone.

A quadcopter flies back and forth along a line. Top: its true position, the readings of a position sensor, and the filter's estimate with its uncertainty as a band. Bottom: the uncertainty alone.

The lower plot shows the loop as a row of saw teeth. Each tooth rises while the filter predicts and drops when a reading arrives.

The estimate generally stays closer to the true path than individual position readings do. Of course, the filter has no access to that path; it combines each reading with a prediction based on earlier readings and the motion model.

If the assumptions and uncertainty settings match the motion and sensors, a band of two spreads should contain the true position about 95% of the time. for a few seconds. The band widens as the filter continues to predict without position corrections.

What a reading says about other things

The previous filter estimated both position and speed, although each position reading measured only one of them. To see how a position reading can also correct speed, we need to look at their uncertainty together. The quantities that a filter estimates form its state. Here the state has two parts: position and speed.

Imagine a cloud of possible states. Each dot gives a position along the horizontal axis and a speed along the vertical axis. At the start, position and speed are independently uncertain, so the cloud has no lean. An ellipse outlines its spread in both directions.

A Kalman filter does not keep this cloud of dots. It stores the centre and a table called the covariance. The entries describe the uncertainty in each quantity and how their errors are linked. In two dimensions, they determine the width and lean of the ellipse. That lean lets a reading of one quantity correct an estimate of another.

Each dot is one possible quadcopter: where it is (left to right) and how fast it moves (bottom to top). The cross is the real one.

Now . Every dot moves to the right by its own speed. The fast dots move further than the slow dots, so the cloud leans over. Position and speed are now linked: if the quadcopter is far to the right, it must be one of the fast ones.

Then . Dots far from the reading become less likely. Because the cloud leans, the remaining likely dots also occupy a smaller range of speeds. The position reading has reduced uncertainty in both parts of the state.

Curves

So far our models have been linear: changing an input changes the output in proportion. Position plus speed times time is one example. A linear model takes a bell-shaped distribution to another bell-shaped distribution. With linear models and independent bell-shaped noise, the Kalman filter can calculate the mean and covariance exactly.

Angles introduce models that are not linear. Suppose a quadcopter flies two metres above the floor, looking at a marker. Its camera measures the angle from straight down to that marker. A triangle relates the angle to the horizontal distance: distance = height × tan(angle). The tangent function curves upward, so an extra degree changes the distance much more at a large angle than at a small one.

If the angle is uncertain by a few degrees, how uncertain is the distance? We can approximate the answer by taking thousands of angles from the assumed bell curve and converting each to a distance. The resulting distribution has a long tail towards larger distances. It is no longer a bell curve.

The filter still needs a mean and a spread. An extended Kalman filter approximates the curved model with a straight line that touches it at the mean angle and has the same slope there. This uses little computation, but here it underestimates both the mean distance and its spread when the angle uncertainty is wide.

The unscented Kalman filter instead chooses a few test values called sigma points. For one uncertain angle, it uses one point at the mean and one on each side. Their positions and weights represent the original mean and spread. The filter passes each point through the curved model, then calculates a weighted mean and spread from the results.

Under the plot: what the filter believes about the angle. The solid neutral line converts angle to distance. On the right: what follows for the distance. The orange bars count distances calculated from thousands of sampled angles. These are samples from the assumed sensor uncertainty, not measurements of the true distance.

The figure compares both approximations with the distribution from thousands of angles. Three well-placed sigma points give a close estimate here, though they cannot preserve every detail of the curved distribution. Make the input bell and both methods agree. Make it and the difference becomes clear.

Sigma points also avoid the need to calculate the model’s slopes. The filter only has to evaluate the model at each point. For a model as complex as the motion of an aircraft, this can remove substantial work and reduce opportunities for mistakes.

Sigma points in more dimensions

A real filter estimates several quantities together. For two quantities, sigma points represent the centre, widths and lean of an uncertainty ellipse. Consider a ground station that measures a drone’s distance and direction. Both readings are uncertain. Converting them to map coordinates bends the distribution into an arc, especially when the direction is uncertain.

On the map below, the five green dots are the transformed sigma points. The green ring marks their weighted mean. The many orange dots are possible positions calculated from sampled distance and direction readings; the orange × marks their average. Neither the × nor the dots mark a known drone position. The small dot at the centre of the dashed ellipse is the straight-line approximation’s mean. The dashed ellipse and its centre are neutral grey in both themes.

Left: the uncertainty in distance and direction, with five sigma points. Right: the same five points on the map, and the ellipse they give. The orange dots and × show the sampled positions and their average. The square is the ground station.

The green ring stays near the centre of the sampled arc. The straight-line approximation places its mean further from the station. to see the difference grow.

The recipe is the same for any number of dimensions:

  1. Put one sigma point at the mean of the state estimate.
  2. Use the covariance to place pairs of points around the mean, with one pair for each dimension of the state.
  3. Pass every point through the model.
  4. Calculate the weighted mean and covariance of the results.

Two uncertain quantities need five sigma points. The flight filter represents uncertainty in 9 dimensions, so it uses 19 points. With its chosen settings, each outer point sits 3.46 spreads from the centre along its covariance direction. The centre point has a weight of 1/4, and each outer point has a weight of 1/24. These weights and distances can differ in other filters.

Which way is up

The first thing the aircraft must know is its attitude: how it is turned. It helps to split the attitude in two. The tilt says how far the aircraft leans away from upright. The heading says which way its nose points.

The filter stores the attitude as four numbers called a quaternion. These are a little mind-bending but luckily the details are not needed here. What matters is that a small error in attitude takes only three numbers: a small turn about each of three axes. Two of them are tilt and one is heading.

The aircraft is drawn at the filter's estimate. The blue arrows show "up" for four sigma points that differ in tilt. The blue wedge on the floor reaches from one heading sigma point to the other. Drag to turn the view.

Gravity always points down (alternatively: down is the direction in which gravity points), so a filter can find the tilt. Nothing in this aircraft points north. A gyroscope and an accelerometer cannot see the heading at all. The filter can follow changes in heading, but it has no independent heading measurement to correct accumulated drift.

In the flight at the top of the page, the filter's tilt uncertainty is about 0.5 degrees. Its heading uncertainty is about 4 degrees halfway through, and still rising.

This implementation limits that rise to keep its small-angle calculations well behaved. Sigma points sit a fixed number of spreads from the middle. With a very large heading spread, the heading sigma points would reach half a turn away. The arithmetic for small turns would then fail. So this filter never lets its heading uncertainty pass 17 degrees.

The sensors

The drone in these recordings carries its gyroscope and accelerometer in an inertial measurement unit, or IMU. Each sensor reports along three axes and gives 200 readings per second. We have seen how the sensors work; now we can examine the errors that the filter must handle.

The gyroscope

Starting from a known attitude, we can use the gyroscope’s turn rates and the time between readings to track changes in orientation. Small errors in those rates accumulate, so even a steady sensor offset eventually produces a large attitude error.

At the start of the recording the aircraft stands still. Its gyroscope should read zero. Instead, this one reads a steady turn of 4.6 degrees per second. This constant error is called the bias. Gyroscope bias can depend on temperature, mechanical stresses introduced during assembly, and various other factors; each individual part will have different bias characteristics.

The first 14 seconds of the recording. Top: the tilt you get from the gyroscope alone, from the filter, and from the motion capture system. Bottom: the filter's estimate of the bias on one axis, with its uncertainty. Drag to move the time.

Add up the gyroscope readings and you add up the bias too. After the gyroscope alone says that the aircraft leans over by 50 degrees. At that moment it has only just taken off.

The filter treats the bias as three more numbers to estimate, one for each axis. Its state is now complete: attitude, velocity and gyroscope bias.

The lower plot shows how the filter finds the bias. When the readings have been quiet for a second and a half, the filter decides that the aircraft is at rest. An aircraft at rest does not turn, so whatever the gyroscope reads is bias. The estimate jumps to the right value and its uncertainty collapses.

The accelerometer

The accelerometer measures force per unit mass from thrust, drag or support, rather than gravity itself. Recall the mass inside the sensor: in free fall, it falls along with the drone and does not load its supports. When a hand holds the drone still, the supports must hold the mass up against gravity, and the sensor reports that upward support force.

. Gravity pulls it down and your hand pushes it up. The accelerometer feels only your hand. That push points straight up, so the reading shows where up is. Tilt the aircraft and the reading shows the tilt. The accelerometer works as a spirit level.

Now . The rotors supply thrust, a force along their shared axis. That axis tilts with the drone, so the largest accelerometer reading stays along the same body axis even when the drone leans. Air also resists sideways motion through the rotors: this smaller force is called rotor drag. The figure shows these forces and the velocity, meaning speed with a direction.

An aircraft seen from the side. The accelerometer feels the orange forces. It does not feel gravity.

The recording shows this clearly:

The true tilt of the aircraft, and the tilt that the accelerometer would show if it were used as a spirit level.

In flight the aircraft leans by up to 31 degrees. The accelerometer never shows more than 4. A second recording begins with the aircraft . There the accelerometer follows the true tilt. It does not follow exactly, because a moving hand also pushes sideways.

Rotor drag

The small orange arrow in the force diagram shows rotor drag. Its direction opposes sideways motion through the air. Although it is much weaker than thrust, the accelerometer can measure it, which gives the filter information about velocity.

Rotor drag grows with speed, and it points against the motion. For speeds like those in this flight, a simple model approximates it:

sideways reading = − drag rate × sideways speed

Here “sideways” means across the rotor axes, at a right angle to thrust. The drag rate relates velocity to the accelerometer reading and has units of inverse seconds. This model lets the filter use sideways acceleration as an indirect measurement of velocity relative to the air. For these indoor flights, it assumes the air is approximately still.

The recording lets us check the model. The motion capture system gives the true speed of the aircraft, and the accelerometer gives its reading:

Each dot is half a second of flight. The green line is the model with the drag rate on the slider. The dashed line is the straight line that fits the dots best.

The dots roughly follow a line through the origin, as the model predicts. They do not lie exactly on it. The filter uses a drag rate of 0.25 per second for every recording. The line that fits this recording best gives a drag rate of 0.18 per second. The model is approximate, so the filter allows a generous spread around its predicted reading.

This idea comes from a paper by Leishman, Macdonald, Beard and McLain, listed at the end.

The process model

We can now build the flight filter’s state from three parts:

The process model says how each part changes during one time step of 5 thousandths of a second:

The push of the rotors comes from the accelerometer reading along the thrust axis. The drag comes from the model above. The model does not use the sideways reading of the accelerometer. The filter keeps that reading back, to check the result.

One line in that list matters more than the others: gravity pulls. Gravity pulls straight down, but the velocity is measured along the aircraft's own axes. To know which way down is, the model must use the attitude.

So a wrong tilt gives a wrong velocity. Suppose the filter's tilt is wrong by one degree. The model then puts gravity one degree off. The sideways velocity goes wrong by 0.17 metres per second, every second.

The next figure shows this with the real filter. It takes the 19 sigma points at one moment of the flight. Each one is a complete state: an attitude, a velocity and a bias. The figure then runs each of them forward through the process model, without measurement corrections. The model still uses the recorded gyroscope and thrust-axis accelerometer readings as inputs.

Left: the tilt of each sigma point, compared with the middle one. Right: the sideways velocity of each sigma point, from now to a moment later, and the true velocity over the same time. Point at a dot to find it in both plots.

The four sigma points that differ in tilt start with different velocities, and they drift further apart. to see how far. They cannot all be right, and the true velocity shows which ones are wrong.

That is the lean from the figure with the dots, in a real filter. Tilt and sideways velocity are linked. Information about sideways velocity can therefore also reduce uncertainty in tilt.

Now show the sigma points that differ in . They do not separate at all. Rotor drag and gravity look the same whichever way the nose points. These body-axis velocity measurements provide no absolute heading reference.

What the filter reads

A measurement model predicts what a sensor should read for a given state. Comparing that prediction with the actual reading gives the correction. This filter uses three measurement models or assumptions at different times:

The filter must decide which measurements apply, and it has only the IMU to decide with. Turning rotors shake the aircraft, and the accelerometer feels the shaking. Another recording shows this well. It starts with the aircraft carried by hand. Then it stands on the ground, and its rotors start and stop three times. Then it takes off.

The first minute of recording MH_01_easy. Top: the vibration of the accelerometer. Middle: the measurements in use. Bottom: the speed that the filter believes, and the speed from the reference. Drag to move the time.

The figure also shows where the model is wrong. Go to . The rotors turn, so the filter switches to the rotor drag model. But the aircraft still stands on the ground. The model assumes free flight. The filter's speed climbs to more than two metres per second while the aircraft does not move.

The filter recovers when the rotors stop. This illustrates a limit of the method: a model is an approximation with conditions under which it applies. If those conditions fail, the filter can report an incorrect estimate without increasing its uncertainty enough to cover the error.

Inside a filter update

For each pair of readings from the IMU, the filter completes one update. We can divide that update into six stages.

  1. Place 19 sigma points around the estimate.
  2. Run each sigma point through the process model.
  3. Calculate their weighted mean and covariance. Add the process-noise covariance to account for motion the model does not predict.
  4. Place 19 new sigma points. For each one, work out what the sensors should read.
  5. Compare the weighted mean of those expected readings with the actual reading. Include sensor noise when calculating their uncertainty and the gain.
  6. Move the estimate by the gain times the difference, and reduce the uncertainty.

Stages 1 to 3 are the prediction. Stages 4 to 6 are the correction. The gain in stage 6 is the same idea as the gain for two bell curves. It is now a table of numbers, with one row for each part of the state. The lean of the covariance decides how much each part moves.

The next figure shows stages 4 to 6, slowed down twenty times. Its two axes are the two sideways accelerometer components. The rings show uncertainty around the expected reading at one and two spreads. The table shows whether the rotor model is active and the correction from the current update; entries stay blank when that measurement is not used at the selected time.

The plane of the sideways accelerometer reading. Green: what the filter expected, with rings at one and two spreads. Orange: what the accelerometer read, and its readings over the last half second.

Press play. The reading jumps around much more than the drag could change in so short a time. Most of that is the shaking of the rotors. The filter knows this, so it trusts each reading very little. One update corrects the tilt by a few hundredths of a degree.

The filter completes 200 updates per second, so small corrections accumulate. Rapid vibration tends to average out over many readings, while the more persistent effect of drag provides information about velocity and tilt.

One detail of the library: it does not store the covariance itself. It stores a square root of it. The results are the same, and the arithmetic is more stable.

Try it

The next figure reruns the filter over a complete recording when you change its settings. The blue line uses your settings. In the tilt and heading views, it shows error relative to the reference, while the grey line shows the error with the benchmark settings. In the velocity and bias views, the neutral line shows the recorded reference. Velocity view shows one sideways component in the drone’s own axes. Bias view shows the estimated gyroscope bias about one axis, compared with the reference. Drag the white time marker (dark in the light theme) to read the plotted values at that moment; changing the marker does not rerun the filter.

The 3D view below the chart shows the drone at the selected time. The ghosted blue drone is the central attitude estimate. The six fainter blue drones are the sigma points for attitude: three pairs that show the filter’s uncertainty about orientation. Their angles are shown at their actual size, so the drones may overlap closely when uncertainty is small. The solid drone shows the reference attitude. All share the recorded reference position, because this filter does not estimate position. Press play to move through the flight with the chart and 3D view together, or pause to inspect a moment.

The settings mean the following.

Press play, or drag the time marker to read the plotted values and see the drone’s attitude at that moment. The blue ghost is the central estimate; the fainter blue ghosts show its six attitude sigma points. Drag the 3D view to turn it. The table summarises the whole recording.

Some things to try:

With the benchmark's settings, the tilt error in the table is the number in the library's benchmark results. The page and the benchmark run the same code on the same readings.

And what about position?

This filter estimates attitude, velocity and gyroscope bias, but not position. A small, inexpensive IMU alone cannot determine an absolute position or heading. Its readings describe forces and changes in motion, rather than where the drone is in a room.

If we start at a known position, we can accumulate velocity over time to estimate a path. This is called dead reckoning. The figure compares two versions. The blue path uses the filter’s velocity estimate. The orange path first uses the uncorrected gyroscope to track attitude, then uses that attitude and the accelerometer to calculate acceleration, velocity and position. Both paths start at the reference position. The raw calculation also starts with the reference attitude and velocity. The filtered calculation uses its own attitude estimate, with a fixed heading alignment for comparison.

The room seen from above. The neutral line is the true path. Blue is the filter's velocity, added up. Orange is the raw IMU, added up with no filter at all. Both start from the true position.

The uncorrected IMU estimate quickly drifts away. Two seconds after the start, its position error is 1.1 metres. After ten seconds it is 101 metres, although the room is only a few metres wide. Gyroscope bias tilts the estimated direction of gravity. The calculation then mistakes part of gravity for horizontal acceleration, and the position error grows rapidly.

The filter does much better. After ten seconds it is about 3 metres away. But its error grows too, and it does not stop. to see.

The reason is in the figure with the dots. A reading can only correct what it is linked to. Rotor drag is linked to sideways velocity, and through it to tilt. Nothing that the IMU reads is linked to position. Errors in velocity accumulate into position errors, and these readings cannot correct the accumulated position error.

To hold a position, the aircraft needs a reading of position from outside: a satellite receiver outdoors, or a camera indoors. The filter needs no new idea for that. Add three numbers to the state for the position, and a measurement model for the new sensor. The loop stays the same: predict, then correct.

Sources

The filter in this article is the multirotor estimator from the sfwa/ukf library, in the file examples/euroc_benchmark/mav_estimator.h. This page compiles it to WebAssembly without changes to how it works. The library's benchmark report describes the estimator and its limits in full.

The recordings are from the EuRoC MAV dataset: M. Burri and others, The EuRoC micro aerial vehicle datasets, International Journal of Robotics Research, 2016. The aircraft is an AscTec Firefly, which has six rotors. ETH Zurich publishes the dataset for non-commercial use. This page uses the IMU readings and the reference trajectory of a few recordings.

The reference trajectory is itself an estimate. It was made after the flights from motion capture or laser tracker measurements together with the same IMU readings. This page treats it as the truth.

For the sensor mechanisms, see Analog Devices’ Accelerometer and Gyroscopes Sensors: Operation, Sensing, and Applications.

Papers behind the method:

Article inspired by the works of Bartosz Ciechanowski, including his explanation of GPS.