Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
The Extended Kalman Filter
At this point in the book we have developed the theory for the linear Kalman filter. Then, in the last two chapters we broached the topic of using Kalman filters for nonlinear problems. I chose to start off with the Unscented Kalman filter, which probably felt like quite a departure from the linear Kalman filter math. It was also a departure from the historical development of the Kalman filter.
Shortly after Dr. Kálmán published his paper on the Kalman filter people recognized that his theory was limited to linear problems and immediately began work on extending the theory to work with nonlinear problems. As I have said elsewhere the only equation we really know how to solve is . That is a slight exaggeration. Many of us have spent years at school learning sophisticated tricks and techniques to handle equations that are not linear. Yet after all that work the vast majority of equations that arise from simple physical systems remain intractable. Certainly there is no way to find general analytic solutions to the Kalman filter equations for nonlinear systems.
In this chapter we will learn the Extended Kalman filter (EKF). The EKF handles nonlinearity by linearizing the system at the point of the current estimate, and then the usual Kalman filter is used to filter this linearized system. It was one of the very first techniques used for nonlinear problems, and it remains the most common technique. Most filters in real world use are EKFs.
The EKF provides significant mathematical challenges to the designer of the filter; this is the most challenging chapter of the book. To be honest, I do everything I can to avoid the EKF in favor of other techniques that have been developed to filter nonlinear problems. However, the topic is unavoidable; all classic papers and a majority of current papers in the field use the EKF. Even if you do not use the EKF in your own work you will need to be familiar with the topic to be able to read the literature.
Linearizing the System Model
The extended Kalman filter (EKF) works by linearizing the system model for each update. For example, consider the problem of tracking a cannonball in flight. Obviously it follows a curved flight path. However, if our update rate is small enough, say 1/10 second, then the trajectory over that time is nearly linear. If we linearize that short segment we will get an answer very close to the actual value, and we can use that value to perform the prediction step of the filter. There are many ways to linearize a set of nonlinear differential equations, and the topic is somewhat beyond the scope of this book. In practice, a Taylor series approximation is frequently used with EKFs, and that is what we will use.
Consider the function . We want a linear approximation of this function so that we can use it in the Kalman filter. We will see how it is used in the Kalman filter in the next section, so don't worry about that yet. We can see that there is no single linear function (line) that gives a close approximation of this function. However, during each innovation (update) of the Kalman filter we know its current state, so if we linearize the function at that value we will have a close approximation. For example, suppose our current state is . What would be a good linearization for this function?
We can use any linear function that passes through the curve at (1.5,-0.75). For example, consider using f(x)=8x−12.75 as the linearization, as in the plot below.
This is not a good linearization for . It is exact for , but quickly diverges when varies by a small amount.
A much better approach is to use the slope of the function at the evaluation point as the linearization. We find the slope by taking the first derivative of the function:
so the slope at 1.5 is . Let's plot that.
Here we can see that this linearization is much better. It is still exactly correct at , but the errors are very small as x varies. Compare the tiny error at vs the very large error at in the previous plot. This does not constitute a formal proof of correctness, but this sort of geometric depiction should be fairly convincing. Certainly it is easy to see that in this case if the line had any other slope the errors would accumulate more quickly.
Linearizing the Kalman Filter
To implement the extended Kalman filter we will leave the linear equations as they are, and use partial derivatives to evaluate the system matrix and the measurement matrix at the state at time t (). In other words we linearize the equations at time t by finding the slope (derivative) of the equations at that time. Since also depends on the control input vector we will need to include that term:
All this means is that at each update step we compute as the partial derivative of our function evaluated at x. We then use a computational technique, such as Taylor expansion, to turn this into a set of linear equations.
For nonlinear problems our function is a set of differential equations. Modeling physical systems with differential equations is well outside the scope of this book. You will need to be reasonably well versed in this branch of applied mathematics to successfully implement the EKF for your problem. If you have not read it yet, please read the section Modeling Dynamic Systems in the Kalman Filter Math chapter as it contains the math that you will need to complete this chapter.
I think the easiest way to understand the EKF is to start off with an example. Perhaps the reason for some of my mathematical choices will not be clear, but trust that the end result will be an EKF.
Example: Tracking a Flying Airplane
We will start by simulating tracking an airplane by using ground based radar. Radars work by emitting a beam of radio waves and scanning for a return bounce. Anything in the beam's path will reflects some of the signal back to the radar. By timing how long it takes for the reflected signal to get back to the radar the system can compute the slant distance - the straight line distance from the radar installation to the object.
For this example we want to take the slant range measurement from the radar and compute the horizontal position (distance of aircraft from the radar measured over the ground) and altitude of the aircraft, as in the diagram below.
As discussed in the introduction, our measurement model is the nonlinear function . Therefore we will need a nonlinear
Predict step:
Update step:
As we can see there are two minor changes to the Kalman filter equations, which I have underlined. The first change replaces the equation with . In the Kalman filter, is how we compute the new state based on the old state. However, in a nonlinear system we cannot use linear algebra to compute this transition. So instead we hypothesize a nonlinear function which performs this function. Likewise, in the Kalman filter we convert the state to a measurement with the linear function . For the extended Kalman filter we replace this with a nonlinear function , giving .
The only question left is how do we implement and use and in the Kalman filter if they are nonlinear? We reach for the single tool that we have available for solving nonlinear equations - we linearize them at the point we want to evaluate the system. For example, consider the function .
The rest of the equations are unchanged, so and must produce a matrix that approximates the values of the matrices and at the current value for . We do this by computing the partial derivatives of the state and measurements functions:
Design the State Variables
So we want to track the position of an aircraft assuming a constant velocity and altitude, and measurements of the slant distance to the aircraft. That means we need 3 state variables - horizontal distance, velocity, and altitude.
Design the System Model
We will model this as a set of differential equations. So we need an equation in the form
where is the system noise.
Let's work out the equation for each of the rows in
The first row is , which is the velocity of the airplane. So we can say
The second row is , which is the acceleration of the airplane. We assume constant velocity, so the acceleration equals zero. However, we also assume system noise due to things like buffeting winds, errors in control inputs, and so on, so we need to add an error to the term, like so
The final row contains , which is the rate of change in the altitude. We assume a constant altitude, so this term is 0, but as with acceleration we need to add in a noise term to account for things like wind, air density, and so on. This gives us
We turn this into matrix form with the following:
Now we have our differential equations for the system we can somehow solve for them to get our familiar Kalman filter state equation
Solving an arbitrary set of differential equations is beyond the scope of this book, however most Kalman filters are amenable to Taylor-series expansion which I will briefly explain here without proof. The section Modeling Dynamic Systems in the Kalman Filter Math chapter contains much more information on this technique.
Given the partial differential equation
the solution is . This is a standard answer learned in a first year partial differential equations course, and is not intuitively obvious from the material presented so far. However, we can compute the exponential matrix using a Taylor-series expansion in the form:
You may expand that equation to as many terms as required for accuracy, however many problems only use the first term
We can then compute the system matrix by substituting in . Thus, is our system matrix.
We cannot use Greek symbols in Python, so the code uses the symbol F
for . This is admittedly confusing. In the math above represents the system of partial differential equations, and is the system matrix. In the Python the partial differential equations are not represented in the code, and the system matrix is F
.
Design the Measurement Model
The measurement function for our filter needs to take the filter state and turn it into a slant range distance. This is nothing more than the Pythagorean theorem.
The relationship between the slant distance and the position on the ground is nonlinear due to the square root term. So what we need to do is linearize the measurement function at some point. As we discussed above, the best way to linearize an equation at a point is to find its slope, which we do by taking its derivative.
The derivative of a matrix is called a Jacobian, which in general takes the form
In other words, each element in the matrix is the partial derivative of the function with respect to the variables . For our problem we have
where as given above.
Solving each in turn:
and
and
giving us
This may seem daunting, so step back and recognize that all of this math is doing something very simple. We have an equation for the slant range to the airplane which is nonlinear. The Kalman filter only works with linear equations, so we need to find a linear equation that approximates As we discussed above, finding the slope of a nonlinear equation at a given point is a good approximation. For the Kalman filter, the 'given point' is the state variable so we need to take the derivative of the slant range with respect to .
To make this more concrete, let's now write a Python function that computes the Jacobian of . The ExtendedKalmanFilter
class will be using this to generate ExtendedKalmanFilter.H
at each step of the process.
Finally, let's provide the code for
Now lets write a simulation for our radar.
Now we can implement our filter. I have not yet designed and which is required to get optimal performance. However, we have already covered a lot of confusing material and I want you to see concrete examples as soon as possible. Therefore I will use 'reasonable' values for and .
The FilterPy
library provides the class ExtendedKalmanFilter
. It works very similar to the KalmanFilter
class we have been using, except that it allows you to provide functions that compute the Jacobian of and the function . We have already written the code for these two functions, so let's get going.
We start by importing the filter and creating it. There are 3 variables in x
and only 1 measurement. At the same time we will create our radar simulator.
We will initialize the filter near the airplane's actual position
We assign the system matrix using the first term of the Taylor series expansion we computed above.
After assigning reasonable values to , , and we can run the filter with a simple loop
Putting that all together along with some boilerplate code to save the results and plot them, we get
Using SymPy to compute Jacobians
Depending on your experience with derivatives you may have found the computation of the Jacobian above either fairly straightforward, or quite difficult. Even if you found it easy, a slightly more difficult problem easily leads to very difficult computations.
As explained in Appendix A, we can use the SymPy package to compute the Jacobian for us.
This result is the same as the result we computed above, and at much less effort on our part!
Designing Q
author's note: ignore this, it to be revised - noise in position and altitude is independent, not dependent
Now we need to design the process noise matrix . From the previous section we have the system equation
where our process noise is
We know from the Kalman filter math chapter that
where is the expected value. We compute the expected value as
Rather than do this by hand, let's use sympy.
Robot Localization
So, time to try a real problem. I warn you that this is far from a simple problem. However, most books choose simple, textbook problems with simple answers, and you are left wondering how to implement a real world solution.
We will consider the problem of robot localization. We already implemented this in the Unscented Kalman Filter chapter, and I recommend you read that first. In this scenario we have a robot that is moving through a landscape with sensors that give range and bearings to various landmarks. This could be a self driving car using computer vision to identify trees, buildings, and other landmarks. Or, it might be one of those small robots that vacuum your house. It could be a search and rescue device meant to go into dangerous areas to search for survivors. It doesn't matter too much.
Our robot is wheeled, which means that it manuevers by turning it's wheels. When it does so, the robot pivots around the rear axle while moving forward. This is nonlinear behavior which we will have to account for. The robot has a sensor that gives it approximate range and bearing to known targets in the landscape. This is nonlinear because computing a position from a range and bearing requires square roots and trigonometry.
Robot Motion Model
At a first approximation n automobile steers by turning the front tires while moving forward. The front of the car moves in the direction that the wheels are pointing while pivoting around the rear tires. This simple description is complicated by issues such as slippage due to friction, the differing behavior of the rubber tires at different speeds, and the need for the outside tire to travel a different radius than the inner tire. Accurately modelling steering requires an ugly set of differential equations. For Kalman filtering, especially for lower speed robotic applications a simpler bicycle model has been found to perform well.
I have depicted this model above. Here we see the front tire is pointing in direction . Over a short time period the car moves forward and the rear wheel ends up further ahead and slightly turned inward, as depicted with the blue shaded tire. Over such a short time frame we can approximate this as a turn around a radius . If you google bicycle model you will find that we can compute the turn angle with
and the turning radius R is given by
where the distance the rear wheel travels given a forward velocity is .
If we let be our current orientation then we can compute the position before the turn starts as
After the move forward for time the new position and orientation of the robot is
Once we substitute in for we get
You don't really need to understand this math in detail, as it is already a simplification of the real motion. The important thing to recognize is that our motion model is nonlinear, and we will need to deal with that with our Kalman filter.
Design the State Variables
For our robot we will maintain the position and orientation of the robot:
I could include velocities into this model, but as you will see the math will already be quite challenging.
Our control input is the velocity and steering angle
Design the System Model
In general we model our system as a nonlinear motion model plus noise.
Using the motion model for a robot that we created above, we can expand this to
We linearize this with a taylor expansion at :
We replace with our state estimate , and the derivative is the Jacobian of .
The Jacobian is
When we calculate these we get
We can double check our work with SymPy.
Now we can turn our attention to the noise. Here, the noise is in our control input, so it is in control space. In other words, we command a specific velocity and steering angle, but we need to convert that into errors in . In a real system this might vary depending on velocity, so it will need to be recomputed for every prediction. I will chose this as the noise model; for a real robot you will need to choose a model that accurately depicts the error in your system.
If this was a linear problem we would convert from control space to state space using the by now familiar form. Since our motion model is nonlinear we do not try to find a closed form solution to this, but instead linearize it with a Jacobian which we will name .
Let's compute that with SymPy:
authors note: explain FPF better
This gives us the final form of our prediction equations:
One final point. This form of linearization is not the only way to predict . For example, we could use a numerical integration technique like Runge Kutta to compute the position of the robot in the future. In fact, if the time step is relatively large you will have to do that. As I am sure you are realizing, things are not as cut and dried with the EKF as it was for the KF. For a real problem you have to very carefully model your system with differential equations and then determine the most appropriate way to solve that system. The correct approach depends on the accuracy you require, how nonlinear the equations are, your processor budget, and numerical stability concerns. These are all topics beyond the scope of this book.
Design the Measurement Model
Now we need to design our measurement model. For this problem we are assuming that we have a sensor that receives a noisy bearing and range to multiple known locations in the landscape. The measurement model must convert the state into a range and bearing to the landmark. Using be the position of a landmark, the range is
We assume that the sensor provides bearing relative to the orientation of the robot, so we must subtract the robot's orientation from the bearing to get the sensor reading, like so:
Thus our function is
This is clearly nonlinear, so we need linearize at by taking its Jacobian. We compute that with SymPy below.
Now we need to write that as a Python function. For example we might write:
We also need to define a function that converts the system state into a measurement.
Design Measurement Noise
This is quite straightforward as we need to specify measurement noise in measurement space, hence it is linear. It is reasonable to assume that the range and bearing measurement noise is independent, hence
Implementation
We will use FilterPy
's ExtendedKalmanFilter
class to implment the filter. The prediction of is nonlinear, so we will have to override the method predict()
to implement this. I'll want to also use this code to simulate the robot, so I'll add a method move()
that computes the position of the robot which both predict()
and my simulation can call. You would not need to do this for a real robot, of course.
The matrices for the prediction step are quite large; while trying to implement this I made several errors before I finally got it working. I only found my errors by using SymPy's evalf
function, which allows you to evaluate a SymPy Matrix
for specific values of the variables. I decided to demonstrate this technique, and to eliminate a possible source of bugs, by using SymPy in the Kalman filter. You'll need to understand a couple of points.
First, evalf
uses a dictionary to pass in the values you want to use. For example, if your matrix contains an x and y, you can write
to evaluate the matrix for x=3
and y=17
.
Second, evalf
returns a sympy.Matrix
object. You can convert it to a numpy array with numpy.array(m)
, but the result uses type object
for the elements in the array. You can convert the array to an array of floats with ``numpy.array(m).astype(float)`.
So, here is the code:
Now we have another issue to handle. The residual is notionally computed as but this will not work because our measurement contains an angle in it. Suppose z has a bearing of and has a bearing of . Naively subtracting them would yield a bearing difference of , which will throw off the computation of the Kalman gain. The correct angle difference in this case is . So we will have to write code to correctly compute the bearing residual.
The rest of the code runs the simulation and plots the results, and shouldn't need too much comment by now. I create a variable landmarks
that contains the coordinates of the landmarks. I update the simulated robot position 10 times a second, but run the EKF only once. This is for two reasons. First, we are not using Runge Kutta to integrate the differental equations of motion, so a narrow time step allows our simulation to be more accurate. Second, it is fairly normal in embedded systems to have limited processing speed. This forces you to run your Kalman filter only as frequently as absolutely needed.
I have plotted the landmarks as solid squares. The path of the robot is drawn with a dashed line, which is admittedly hard to see. The covariance after the predict step is drawn in a very light shade of blue, and the covariance after all of the landmark measurements are incorporated are shown in green. To make them visible at this scale I have set the ellipse boundary at 6$\sigma$.
From this we can see that there is a lot of uncertainty added by our motion model, and that most of the error in in the direction of motion. We can see that from the shape of the blue ellipses. After a few steps we can see that the filter incorporates the landmark measurements.
We can see the fantastic effect that multiple landmarks has on our uncertainty by only using the first two landmarks.
We can see that the covariance gets smaller as it passes through the landmarks but quickly expands once past them. Let's see what happens with only one landmark
As you probably suspected, only one landmark produces a very bad covariance. What is worse, the filter starts to diverge from the robot's path. On the other hand, a large number of landmarks allows us to make very accurate estimates.
Discussion
I said that this was a 'real' problem, and in some ways it is. I've seen alternative presentations that used robot motion models that led to much easier Jacobians. On the other hand, my model of a automobile's movement is itself simplistic in several ways. First, it uses the bicycle model to compute how it moves. A real car has two sets of tires, and each travels on a different radius. The wheels do not grip the surface perfectly. I also assumed that the robot was able to instaneously respond to my control input changes. In fact, I didn't even bother changing the control input during the run. Sebastian Thrun writes in Probabalistic Robots that simplied models are justified because the filters perform well when used to track real vehicles. The lesson here is that while you have to have a reasonably accurate nonlinear model, it does not need to be perfect to operate well. As a designer you will need to balance the fidelity of your model with the difficulty of the math and the computation required to implement the equations.
Another way in which this problem was simplistic is that we assumed that we knew the correspondance between the landmarks and measurements. But suppose we are using radar - how would we know that a specific signal return corresponded to a specific building in the local scene? This question hints at SLAM algorithms - simultaneous localization and mapping. SLAM is not the point of this book, so I will not elaborate on this topic.
However, this example should underscore how difficult EKFs can be. EKF have a well deserved reputation for difficulty. Especially when the problem is highly nonlinear you must design
UKF vs EKF
I implemented this tracking problem using and unscented Kalman filter in the previous chapter. The difference in implementation should be very clear. Computing the Jacobians for the state and measurement models was not trivial and we used a very rudimentary model for the motion of the car. I am justified in using this model because the research resulting from the DARPA car challenges has shown that it works well in practice. Nonetheless, a different problem, such as an aircraft or rocket will yield a very difficult to impossible to compute Jacobian. In contrast, the UKF only requires you to provide a function that computes the system motion model and another for the measurement model. This is will always be easier than deriving a Jacobian analytically. In fact, there are many physical processes for which we cannot find an analytical solution. It is beyond the scope of this book, but in that case you have to design a numerical method to compute the Jacobian. That is a very nontrivial undertaking, and you will spend a significant portion of a master's degree at a STEM school learning various techniques to handle such situations. Even then you'll likely only be able to solve problems related to your field - an aeronautical engineer learns a lot about Navier Stokes equations, but not much about modelling chemical reaction rates.
So, UKFs are easy. Are they accurate? Everything I have read states that there is no way to prove that a UKF will always perform as well or better than an EKF. However, in practice, they do perform better. You can search and find any number of research papers that prove that the UKF outperforms the EKF in various problem domains. It's not hard to understand why this would be true. The EKF works by linearizing the system model and measurement model at a single point.
Let's look at a specific example. I will take the function as our nonlinear function and pass a Gaussian distribution through it. I will compute an accurate answer using a monte carlo simulation. I do this by generating 50,000 points distributed according to the Gaussian, passing each point through the function, and then computing the mean and variance of the result.
First, let's see how the EKF fairs. The EkF linearizes the function by taking the derivative and evaluating it the mean to get the slope tangent to the function at that point. This slope becomes the linear function that we use to transform the Gaussian. Here is a plot of that.
We can see from both the graph and the print out at the bottom that the EKF has introduced quite a bit of error.
In contrast, here is the performance of the UKF evaluated with the same Gaussian and function.b
Here we can see that the computation of the UKF's mean is accurate to 2 decimal places. The standard deviation is slightly off, but you can also fine tune how the UKF computes the distribution by using the , , and parameters for generating the sigma points. Here I used , , and . Feel free to modify them in the function call to see the result - you should be able to get better results than I did. However, ovoid overtuning the UKF for a specific test - it may perform better for your test case, but worse in general.
This is one contrived example, but as I said the literature is filled with detailed studies of real world problems that exhibit similar performance differences between the two filters.