{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Table of Contents](http://nbviewer.ipython.org/github/rlabbe/Kalman-and-Bayesian-Filters-in-Python/blob/master/table_of_contents.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Walking through the Kalman Filter code" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#format the book\n", "%matplotlib inline\n", "from __future__ import division, print_function\n", "import matplotlib.pyplot as plt\n", "import book_format\n", "book_format.load_style()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "** author's note: this code is somewhat old. This section needs to be edited; I would not pay a lot of attention to it right now. **\n", "\n", "The kalman filter code that we are using is implemented in my Python library `FilterPy`. If you are interested in the full implementation of the filter you should look in `filterpy\\kalman\\kalman_filter.py`. In the following I will present a simplified implementation of the same code. The code in the library handles issues that are beyond the scope of this chapter, such as numerical stability and support for the extended Kalman filter, subject of a later chapter. \n", "\n", "The code is implemented as the class `KalmanFilter`. Some Python programmers are not a fan of object oriented (OO) Python, and eschew classes. I do not intend to enter into that battle other than to say that I have often seen OO abused. Here I use the class to encapsulate the data that is pertinent to the filter so that you do not have to store and pass around a half dozen variables everywhere.\n", "\n", "The method `__init__()` is used by Python to create the object. Here is the method \n", "\n", " def __init__(self, dim_x, dim_z):\n", " \"\"\" Create a Kalman filter. You are responsible for setting the \n", " various state variables to reasonable values; the defaults below will\n", " not give you a functional filter.\n", " \n", " Parameters\n", " ----------\n", " dim_x : int\n", " Number of state variables for the Kalman filter. For example, if\n", " you are tracking the position and velocity of an object in two\n", " dimensions, dim_x would be 4.\n", " \n", " This is used to set the default size of P, Q, and u\n", " \n", " dim_z : int\n", " Number of of measurement inputs. For example, if the sensor\n", " provides you with position in (x,y), dim_z would be 2. \n", " \"\"\"\n", " \n", " self.dim_x = dim_x\n", " self.dim_z = dim_z\n", "\n", " self.x = np.zeros((dim_x, 1)) # state\n", " self.P = np.eye(dim_x) # uncertainty covariance\n", " self.Q = np.eye(dim_x) # process uncertainty\n", " self.u = 0 # control input vector\n", " self.B = np.zeros((dim_x, 1))\n", " self.F = 0 # state transition matrix\n", " self.H = 0 # Measurement function\n", " self.R = np.eye(dim_z) # state uncertainty\n", "\n", " # identity matrix. Do not alter this.\n", " self._I = np.eye(dim_x)\n", "\n", "More than anything this method exists to document for you what the variable names are in the filter. To do anything useful with this filter you will have to modify most of these values. Some are set to useful values. For example, `R` is set to an identity matrix; if you want the diagonals of `R` to be 10. you may write (as we did earlier in this chapter) `my_filter.R += 10.`.\n", "\n", "The names used for each variable matches the math symbology used in this chapter. Thus, `self.P` is the covariance matrix, `self.x` is the state, and so on.\n", "\n", "The predict function implements the predict step of the Kalman equations, which are \n", "\n", "$$\n", "\\begin{aligned}\n", "\\mathbf{x}^- &= \\mathbf{F x} + \\mathbf{B u} \\\\\n", "\\mathbf{P}^- &= \\mathbf{FP{F}}^\\mathsf{T} + \\mathbf{Q} \n", "\\end{aligned}\n", "$$\n", "\n", "The corresponding code is\n", "\n", " def predict(self): \n", " self.x = self.F.dot(self.x) + self.B.dot(self.u)\n", " self.P = self.F.dot(self.P).dot(self.F.T) + self.Q\n", "\n", "I haven't discussed the use of NumPy much until now, but this method illustrates the power of that package. We use NumPy's `array` class to store our data and perform the linear algebra for our filters. `array` implements matrix multiplication using the `.dot()` method; if you use `*` you will get element-wise multiplication. As a heavy user of linear algebra this design is somewhat distressing as I use matrix multiplication far more often than element-wise multiplication. However, this design is due to historical developments in the library and we must live with it. The Python community has recognized this problem, and in Python 3.5 we will have the `@` operator to implement matrix multiplication. \n", "\n", "With that in mind, the Python code `self.F.dot(self.x)` implements the math expression $\\mathbf{F x}$.\n", "\n", "NumPy's `array` implements matrix transposition by using the `.T` property. Therefore, `F.T` is the python implementation of $\\mathbf{F}^\\mathsf{T}$.\n", "\n", "The `update()` method implements the update equations of the Kalman filter, which are\n", "\n", "$$\n", "\\begin{aligned}\n", "\\mathbf{y} &= \\mathbf{z} - \\mathbf{H}\\mathbf{x^-} \\\\\n", "\\mathbf{K} &= \\mathbf{P} \\mathbf{H}^\\mathsf{T} (\\mathbf{H} \\mathbf{P^-} \\mathbf{H}^\\mathsf{T} +\\mathbf{R})^{-1} \\\\\n", "\\mathbf{x} &= \\mathbf{x}^- + \\mathbf{K} \\mathbf{y} \\\\\n", "\\mathbf{P} &= (\\mathbf{I} - \\mathbf{K} \\mathbf{H})\\mathbf{P^-}\n", "\\end{aligned}\n", "$$\n", "\n", "The corresponding code is:\n", "\n", " def update(self, Z, R=None):\n", " \"\"\"\n", " Add a new measurement (Z) to the kalman filter. If Z is None, nothing\n", " is changed.\n", "\n", " Optionally provide R to override the measurement noise for this\n", " one call, otherwise self.R will be used.\n", "\n", " self.residual, self.S, and self.K are stored in case you want to\n", " inspect these variables. Strictly speaking they are not part of the\n", " output of the Kalman filter, however, it is often useful to know\n", " what these values are in various scenarios.\n", " \"\"\"\n", "\n", " if Z is None:\n", " return\n", "\n", " if R is None:\n", " R = self.R\n", " elif np.isscalar(R):\n", " R = np.eye(self.dim_z) * R\n", "\n", " # error (residual) between measurement and prediction\n", " self.residual = Z - self.H.dot(self.x)\n", "\n", " # project system uncertainty into measurement space\n", " self.S = self.H.dot(self.P).dot(self.H.T) + R\n", "\n", " # map system uncertainty into kalman gain\n", " self.K = self.P.dot(self.H.T).dot(linalg.inv(self.S))\n", "\n", " # predict new x with residual scaled by the kalman gain\n", " self.x += self.K.dot(self.residual)\n", "\n", " KH = self.K.dot(self.H)\n", " I_KH = self._I - KH\n", " self.P = (I_KH.dot(self.P.dot(I_KH.T)) +\n", " self.K.dot(self.R.dot(self.K.T)))\n", "\n", "There are a few more complications in this piece of code compared to `predict()` but it should still be quite clear. \n", "\n", "The first complication are the lines:\n", "\n", " if Z is None:\n", " return\n", " \n", "This just lets you deal with missing data in a natural way. It is typical to use `None` to indicate the absence of data. If there is no data for an update we skip the update equations. This bit of code means you can write something like:\n", "\n", " z = read_sensor() # may return None if no data\n", " my_kf.update(z)\n", " \n", "instead of:\n", " z = read_sensor()\n", " if z is not None:\n", " my_kf.update(z)\n", " \n", "Reasonable people will argue whether my choice is cleaner, or obscures the fact that we do not update if the measurement is `None`. Having written a lot of avionics code my proclivity is always to do the safe thing. If we pass 'None' into the function I do not want an exception to occur; instead, I want the reasonable thing to happen, which is to just return without doing anything. If you feel that my choice obscures that fact, go ahead and write the explicit `if` statement prior to calling `update()` and get the best of both worlds.\n", "\n", "The next bit of code lets you optionally pass in a value to override `R`. It is common for the sensor noise to vary over time; if it does you can pass in the value as the optional parameter `R`.\n", "\n", " if R is None:\n", " R = self.R\n", " elif np.isscalar(R):\n", " R = np.eye(self.dim_z) * R\n", " \n", "This code will use self.R if you do not provide a value for `R`. If you did provide a value, it will check if you provided a scalar (number); if so it constructs a matrix of the correct dimension for you. Otherwise it assumes that you passed in a matrix of the correct dimension.\n", "\n", "The rest of the code implements the Kalman filter equations, with one exception. Instead of implementing \n", "\n", "$$\\mathbf{P} = (\\mathbf{I} - \\mathbf{KH})\\mathbf{P}^-$$\n", "\n", "it implements the somewhat more complicated form \n", "\n", "$$\\mathbf{P} = (\\mathbf{I} - \\mathbf{KH})\\mathbf{P}^-(\\mathbf{I} - \\mathbf{KH})^\\mathsf{T} + \\mathbf{KRK}^\\mathsf{T}$$.\n", "\n", "The reason for this altered equation is that it is more numerically stable than the former equation, at the cost of being a bit more expensive to compute. It is not always possible to find the optimal value for $\\text{K}$, in which case the former equation will not produce good results because it assumes optimality. The longer reformulation used in the code is derived from more general math that does not assume optimality, and hence provides good results for non-optimal filters (such as when we can not correctly model our measurement error).\n", "\n", "Various texts differ as to whether this form of the equation should always be used, or only used when you know you need it. I choose to expend a bit more processing power to ensure stability; if your hardware is very constrained and you are able to prove that the simpler equation is correct for your problem then you might choose to use it instead. Personally, I find that a risky approach and do not recommend it to non-experts. Brown's *Introduction to Random Signals and Applied Kalman Filtering* [3] discusses this issue in some detail, if you are interested." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }