{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This is an [jupyter](http://jupyter.org) notebook.\n", "Lectures about Python, useful both for beginners and experts, can be found at http://scipy-lectures.github.io." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Open the notebook by (1) copying this file into a directory, (2) in that directory typing \n", "jupyter-notebook\n", "and (3) selecting the notebook.\n", "\n", "***\n", "Written By: **Riddhish Bhalodia**\n", "***\n", "\n", "In this exercise, we will learn and code about Kalman Filtering and look at few of it's applications." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Kalman Filtering\n", "## Motivation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let me start it this way that before Rudolf Kalman (co-inventor of Kalman filtering), problems were divided in two distinct classes *Control Problems* (what value of acceleration should be provided to the car so that it climbs a certain incline with constant speed) and *Filtering Problem* (damn this noisy accelerometer, I can't get a clear value even at a fixed point). \n", "\n", "You might have guessed (if you care to read the brackets :P) that the two problems are not uncorrelated. To the un-initiated, take a scenario that the car has a noisy accelerometer and you want to control it's speed on the incline, so two problems in one. One way is to solve them independently, but that is too situation dependent and so there was a need for a *dynamic solution* for *filtering while controlling and vice versa*, essentially bringing the two separate problems under one roof.\n", "\n", "This is precisely what Kalman Filter does! Kalman Filter and it's non-linear extensions are essential elements in modern control theory. Lot of different applications ranging from filtering noisy sensor output to autonomous robot navigation uses Kalman Filter.\n", "\n", "In this tutorial we will first start off with an application, which we will code (yay!) and then move on to build Kalman filtering theory.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Faulty Voltmeter\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A classic example to start with and very intuitive. We have to measure a DC voltage from a faulty (noisy) voltmeter, it cant get any simpler than this.\n", "First off let's import certain packages" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%matplotlib inline \n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now for solving any computational problem we need to model the *system* (in layman terms, set of equations which is used to describe the overall situation and how it varies with physical inputs and parameters).\n", "The simplest way to model the noisy voltmeter at *every measurements instant* is through the following equation\n", "\\begin{equation}\n", "V_m = V_{m-1} + \\omega_m \\qquad (1)\n", "\\end{equation}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, $V_m$ : Voltage at current time,\n", " $V_{m-1}$ : Voltage at previous time instant,\n", " $\\omega_m$ : Random Noise (process noise)\n", " \n", "We also have measurements taken at each instance m which is given by $Z_m$ and is corrupted by some sensor (measurements) noise $\\nu_m$\n", "\n", "$$Z_m = V_m + \\nu_m \\qquad (2)$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Usually in such cases as $\\nu_m$ is introduced due to faults in voltmeter (sensor) and hence we usually know it's characteristics (least count, precision ... ring any bells?). So here we will model $\\nu_m$ as a Gaussian Random Variable (as it is usually done) with zero mean and standard deviation $\\sigma_{\\nu} = 0.3$ (for simulation sake). $\\omega_m$ is more difficult to predict and is introduced by error due to non-ideality (we know it's constant DC voltage, but is it really!) of our process equations but we still assume that we know it. Again, $\\omega_m$ is to be modeled by a Gaussian Random Variable with zero mean and standard deviation $\\sigma_{\\omega} = 0.01$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So before solving this let's model this voltmeter, What are the parameters to give. The true constant voltage lets say variable `true_voltage = 1`, and we need a noise level as well (this is voltmeter's error so will feature in measurements error), say variable `noise_level_sig = 0.2` (KF works when noise estimate are off by a mark...). Let's take measurements for 50 instances store it in `iter_max` and we will generate the measurements for each instant which will be just $~ \\mathcal{N}(true\\_voltage,noise\\_level\\_sig)$ (Think about this :)) \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "true_voltage = 1\n", "noise_level_sig = 0.2\n", "iter_max = 50\n", "measurements = []\n", "true_voltage_mat = []\n", "\n", "for i in range(iter_max):\n", " measured = random.gauss(true_voltage , noise_level_sig)\n", " measurements.append(measured)\n", " true_voltage_mat.append(true_voltage)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's plot how the measurements look as compared to the true voltage" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.plot(range(iter_max),true_voltage_mat,'b',range(iter_max), measurements,'r')\n", "plt.xlabel('Time Instances')\n", "plt.ylabel('Voltage')\n", "plt.legend(('true voltage', 'measured'), loc=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now starts the actual thing, we want to filter this :D, by using Kalman Filtering. But first we need to derive, so do get ready for a chunk load of theory, but but please be patient as once we are done with this, the standard Kalman Filter will be a piece of cake\n", ":)\n", "\n", "### Filtering!!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Math Math Math.\n", "\n", "That being said, to solve this problem iteratively we need two major step\n", "\n", "* Predict the voltage at next instance using the previous estimate (1)\n", "* Correct the estimate based on the measurements at that instant \n", "\n", "So we define two variables, $\\hat{V}^-_m :$ *prior* estimate of the voltage given only the knowledge of the process (the equation (1)) and $\\hat{V}_m :$ *posterior* estimate of the voltage at step m given the knowledge of the measurements $Z_m$ " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So lets' start the firing of equations, just one comment before this, we will also estimate the error in the estimate at every iteration along with the estimate itself.\n", "\n", "$$e_m = V_m - \\hat{V}_m \\quad \\textrm{and} \\quad \\sigma^2_m = \\mathbb{E}[e_m^2]$$\n", "\n", "and \n", "\n", "$$e^-_m = V_m - \\hat{V}^-_m \\quad \\textrm{and} \\quad \\sigma^{2-}_m = \\mathbb{E}[e_m^{2-}]$$\n", "\n", "We have to minimize this $\\sigma^2_m$. So now as any sane person (ok statistician) would do we would model the *posterior* estimate $\\hat{V}_m$ as the linear combination of the *prior* estimate $\\hat{V}^-_m$ and the deviation of the estimate from the measurements (also called as *innovation term*) given as\n", "\n", "$$y_m = Z_m - \\hat{V}^-_m \\qquad (3)$$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Putting the above ramble in equation we have \n", "\n", "$$\\hat{V}_m = \\hat{V}^-_m + k_my_m \\qquad (4)$$\n", "\n", "subtracting $V_m$ from both sides we get\n", "\n", "$$\\hat{V}_m - V_m = \\hat{V}^-_m - V_m + k_m(Z_m - \\hat{V}^-_m)$$\n", "\n", "To compute $k_m$ we take the square and it's expectation and then differentiate the quadratic in $k_m$ to get something like (try this your self)\n", "\n", "$$k_m = \\frac{\\mathbb{E}[(V_m - \\hat{V}^-_m)(y_m)]}{\\mathbb{E}[y_m^2]}$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The numerator and denominator when expanded and taking into the account for independence of the R.V $Z_m$, $V_m$, and $\\hat{V}^-_m$ (think about this too) we get \n", "\n", "$$k_m = \\frac{\\sigma^{2-}_m}{\\sigma^{2-}_m + \\sigma^2_{\\nu}} \\qquad (5)$$\n", "\n", "along with this we also have from equation(1) \n", "\n", "$$\\sigma_m^{2-} = \\sigma_{m-1}^2 + \\sigma_\\omega^2 \\qquad (6)$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now substituting this (5) in the quadratic for $\\mathbb{E}[e^2_m]$ we get the variance as\n", "\n", "$$\\sigma^2_m = (1 - k_m)\\sigma_m^{2-} \\qquad (7)$$\n", "\n", "Now we have everything :D, already! It will be clear when you look at the summary below\n", "* Start with an initial guess for $V = V_0$\n", "* Get the *prior* estimate of voltage and it's error ($\\hat{V}^-_m$ and $\\sigma_m^{2-}$) from the process equation (1) and (6)\n", "* Using the *prior* estimates and the measurements data at instant m we get the *posterior* (read corrected) estimates of the voltage and it's error at instant m ($\\hat{V}_m$ and $\\sigma_m^2$)\n", "* Repeat this for several instances and we will converge to a solution (Yes! there exist a proof for convergence, you can google it up)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So hopefully you would have got a hang of how this works. So let's code it up" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Initialize the parameters\n", "\n", "initial_guess = 3\n", "initial_guess_error = 1\n", "sig_nu = 0.3\n", "sig_omega = 0.01\n", "estimate_vector = []\n", "estimate_vector.append(initial_guess)\n", "error_estimate_vector = []\n", "error_estimate_vector.append(initial_guess_error)\n", "\n", "# Run the Filter\n", "\n", "for i in range(iter_max-1):\n", " # first the prior estimation step\n", " \n", " volt_prior_est = estimate_vector[i]\n", " error_prior_est = error_estimate_vector[i] + sig_omega * sig_omega\n", " \n", " # estimate correction\n", " \n", " k = error_prior_est/(error_prior_est + sig_nu * sig_nu)\n", " volt_corrected_est = volt_prior_est + k * (measurements[i+1] - volt_prior_est)\n", " error_corrected_est = (1 - k) * error_prior_est\n", " estimate_vector.append(volt_corrected_est)\n", " error_estimate_vector.append(error_corrected_est)\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us plot the things" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(range(iter_max),true_voltage_mat,'b',range(iter_max), measurements,'r', range(iter_max), estimate_vector,'g')\n", "plt.xlabel('Time Instances')\n", "plt.ylabel('Voltage')\n", "plt.legend(('true voltage', 'measured', 'filtered'), loc=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Did you have your voila moment? :D\n", "Lets also look at the error for the estimate, lets plot it.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(range(iter_max),error_estimate_vector)\n", "plt.xlabel('Time Instances')\n", "plt.ylabel('Voltage Error')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Kalman Filter\n", "\n", "You might be wondering where is the control in all this. So now that's easily introduced in the actual formulation of Kalman filter which we will look at now. In the actual Kalman Filter we deal with multi-variable setting unlike that of the voltmeter example. So let me describe the inputs and the outputs and the parameters\n", "\n", "**Inputs**\n", "* $\\textbf{Z}_m : $ The measurements vector at each instant m\n", "* $\\textbf{U}_m : $ *This is new!*, it denotes the controls provided to the system at instance m (this is just like force being the control for velocity of the car)\n", "\n", "**Outputs**\n", "* $\\textbf{X}_m : $ Newest estimate of the current state (state can be thought of as a parameter vector)\n", "* $P_m :$ The newest estimate for the average error of the state\n", "\n", "**Parameters**\n", "* A : State transition matrix, basically the constant matrix multiplied to the previous estimate in the process equation\n", "* B : Control matrix, one to be multiplied to the control vector in the process equation\n", "* H : Observation matrix, the proportionality factor for state to be equal to the measurements\n", "* Q : Covariance matrix for the process error (this is again assumed to be known)\n", "* R : Covariance matrix for the measurements error (again known)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we are ready to write the basic equations for the KF, don't worry much of the above will be cleared as you look at the equation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lets start with the two basic equations, first is the process equation\n", "\n", "$$\\textbf{X}_m = A\\textbf{X}_{m-1} + B\\textbf{U}_{m-1} + \\pmb{\\omega}_m \\qquad (8)$$\n", "\n", "and then we have the measurements equation\n", "\n", "$$\\textbf{Z}_m = H\\textbf{X}_m + \\pmb{\\nu}_m \\qquad (9)$$\n", "\n", "Here, we model the two error terms $\\pmb{\\omega}_m$ and $\\pmb{\\nu}_m$ as multi-variate Gaussian distributions with zero mean and covariance matrices Q and P respectively, i.e. $\\pmb{\\omega}_m \\textrm{~} \\mathcal{N}(0,Q)$\n", "and $\\pmb{\\nu}_m \\textrm{~} \\mathcal{N}(0,P)$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So now following the exact same philosophy of that we followed for the derivation in voltmeter example we get the update equations for the general Kalman Filter. I will just list it down, if people are interested they can look up the references given below\n", "\n", "$$ P_m^- = AP_{m-1}A^T + Q \\qquad (10) $$\n", "\n", "$$ K_m = P_m^-H^T(HP_m^-H^T + R) \\qquad (11) $$\n", "\n", "$$\\pmb{y}_m = \\pmb{Z}_m - H\\hat{\\pmb{X}_m^-} \\qquad (12)$$\n", "\n", "$$ \\hat{\\pmb{X}}_m = \\hat{\\pmb{X}_m^-} + K_m\\pmb{y}_m \\qquad (13)$$\n", "\n", "$$ P_m = (I - K_mH)P_m^- \\qquad (14)$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again summarizing\n", "\n", "* Start with an initial guess for $\\pmb{X} = \\pmb{X}_0$\n", "* Get the *prior* estimate of state and it's error ($\\hat{\\pmb{X}}^-_m$ and $P_m^{-}$) from the process equation (1) and (6)\n", "* Using the *prior* estimates and the measurements data at instant m we get the *posterior* (read corrected) estimates of the voltage and it's error at instant m ($\\hat{V}_m$ and $\\sigma_m^2$)\n", "* Repeat this for several instances and we will converge to a solution (Yes! there exist a proof for convergence, you can google it up)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Now enough of this rambling, I do hope you get this but we are going to make a kalman filter class and then try to see how this fits with our voltmeter example. So lets first create a class" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class kalmanFilter:\n", " def __init__(self, X0, P0, A, B, H, Q, R):\n", " self.A = A # State Transition Matrix\n", " self.B = B # Control Matrix\n", " self.H = H # Observation Matrix\n", " self.Q = Q # Covariance for the process error\n", " self.R = R # Covariance for the measurements error\n", " self.current_estimate = X0 # this is the initial guess of the state\n", " self.current_error_estimate = P0 # initial guess for the state estimate error\n", " \n", " def getEstimate(self):\n", " # returns the current state estimate\n", " return self.current_estimate\n", " \n", " def getErrorEstimate(self):\n", " # returns the current state error estimate\n", " return self.current_error_estimate\n", " \n", " def iteration(self, U, Z):\n", " # here is where the updates happen\n", " # U = control vector\n", " # Z = measurements vector\n", " \n", " # prior prediction step\n", " prior_estimate = self.A * self.current_estimate + self.B * U\n", " prior_error_estimate = (self.A * self.current_error_estimate) * np.transpose(self.A) + self.Q\n", " \n", " # intermediate observation\n", " y = Z - self.H * prior_estimate\n", " y_covariance = self.H * prior_error_estimate * np.transpose(self.H) + self.R\n", " \n", " # Correction Step\n", " K = prior_error_estimate * np.transpose(self.H) * np.linalg.inv(y_covariance)\n", " self.current_estimate = prior_estimate + K * y\n", " # We need the size of the matrix so we can make an identity matrix.\n", " size = self.current_error_estimate.shape[0]\n", " # eye(n) = nxn identity matrix.\n", " self.current_error_estimate = (np.eye(size) - K * self.H) * prior_error_estimate\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we have this nice class set up, let's test it's correctness by applying it to the Voltmeter problem. First things in the voltmeter problem we set the parameters first." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "A = np.matrix([1])\n", "B = np.matrix([0])\n", "H = np.matrix([1])\n", "Q = np.matrix([0.0001]) # the sigmas gets squared\n", "R = np.matrix([0.09])\n", "X0 = np.matrix([3])\n", "P0 = np.matrix([1])\n", "\n", "KF = kalmanFilter(X0, P0, A, B, H, Q, R)\n", "estimate_vector_new = []\n", "estimate_vector_new.append(initial_guess)\n", "error_estimate_vector_new = []\n", "error_estimate_vector_new.append(initial_guess_error)\n", "\n", "# Run the Filter\n", "\n", "for i in range(iter_max-1):\n", " U = np.matrix([0]) # there is no control here\n", " Z = np.matrix([measurements[i+1]])\n", " estimate_vector_new.append(KF.getEstimate()[0,0])\n", " error_estimate_vector_new.append(KF.getErrorEstimate()[0,0])\n", " KF.iteration(U,Z)\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now lets plot again to see weather we are good to go or not." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(range(iter_max),true_voltage_mat,'b',range(iter_max), measurements,'r', range(iter_max), estimate_vector_new,'g')\n", "plt.xlabel('Time Instances')\n", "plt.ylabel('Voltage')\n", "plt.legend(('true voltage', 'measured', 'filtered'), loc=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Well it should exactly match with the previous plot :P duh, big deal. But now as we have this nice class we can start dealing with cooler application. So now after much search I have come up with this application to end this hopefully interesting notebook :D" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Well a simple but I guess not with real wow factor example is that we have a ball thrown in a projectile and we can measure it's (x,y) position with camera system and also it's velocity (vx,vy) by the sensors on the ball (used in cricket for LBW system without the velocity part). Now we know that these cameras are noisy so we need a filtered estimate of the state of the ball finally (here the state is a vector of x,y,vx,vy). So let's get on with the system modeling first." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember projectiles! Remember JEE physics which you all did. All right I am not going to explain the kinematics equations just have a look and you will understand. We project at an initial velocity u and angle $\\theta$ wrt horizontal. we divide into intervals of measurements into time intervals of $\\Delta t$. \n", "\n", "$$Vx_{t} = Vx_{t-1}$$\n", "\n", "$$Vy_{t} = Vy_{t-1} - g\\Delta t$$\n", "\n", "$$x_{t} = x_{t-1} + Vx_{t-1}\\Delta t$$\n", "\n", "$$y_{t} = y_{t-1} + Vy_{t-1}\\Delta t - 0.5g\\Delta t^2$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The state of the equations at instance t is given by the vector $\\pmb{X}_t = (x_t,Vx_t,y_t,Vy_t)$, and the control vector is the additional term $\\pmb{u}_t = (0,0,-0.5g\\Delta t^2, -g\\Delta t)$. Think about this! Now we start defining matrices." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "\\begin{equation}\n", "\\pmb{X}_t = A\\pmb{X}_{t-1} + B\\pmb{u}_t \\\\\n", "A=\\left(\\begin{array}{cccc}\n", " 1 & \\Delta t & 0 & 0 \\\\ \n", " 0 & 1 & 0 & 0 \\\\\n", " 0 & 0 & 1 & \\Delta t \\\\\n", " 0 & 0 & 0 & 1\n", "\\end{array}\\right)\n", "B = \\left(\\begin{array}{cccc}\n", "0 & 0 & 0 & 0 \\\\\n", "0 & 0 & 0 & 0 \\\\\n", "0 & 0 & 1 & 0 \\\\\n", "0 & 0 & 0 & 1\n", "\\end{array}\\right)\n", "\\end{equation}\n", "\n", "As our measurements are directly the state there is no proportionality and hence the H matrix is an identity matrix (H = $I_4$). Also we assume that our process has an error covariance as $Q = 0.0001*I_4$ and the measurements has an error covariance of $R = 0.3*I_4$ (all the errors are not necessary to be equal, but taken here for convenience :D). Also we need the values for $\\theta$ and $u$, lets say $\\theta = 45$ and $u = 100m/s$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we have all the matrices and so lets start with solving this using our kalmanFilter class. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Physics\n", "# 1) sin(45)*100 = 70.710 and cos(45)*100 = 70.710\n", "# vf = vo + at\n", "# 0 = 70.710 + (-9.81)t\n", "# t = 70.710/9.81 = 7.208 seconds for half\n", "# 14.416 seconds for full journey\n", "# distance = 70.710 m/s * 14.416 sec = 1019.36796 m\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "due to the above calculations we have to be careful choosing $\\Delta t$ and number of iterations. $\\Delta t = 0.1$ and max_iter = 145 makes sense (think). So now we create our simulated data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "del_t = 0.1\n", "max_iter = 145\n", "added_noise = 25\n", "init_vel = 100\n", "theta = np.pi/4\n", "\n", "# now we define the measurement matrix\n", "measurements = np.zeros((4,max_iter))\n", "true_value = np.zeros((4,max_iter))\n", "ux0 = init_vel * np.cos(theta)\n", "uy0 = init_vel * np.sin(theta)\n", "\n", "for i in range(max_iter):\n", " # we generate this by projectile equations and adding noise to it\n", " t = i * del_t\n", " true_value[0,i] = ux0 * t\n", " true_value[1,i] = ux0\n", " true_value[2,i] = uy0 * t - 0.5 * 9.8 * t * t\n", " true_value[3,i] = uy0 - 9.8 * t\n", " measurements[0,i] = random.gauss(true_value[0,i],added_noise)\n", " measurements[1,i] = random.gauss(true_value[1,i],added_noise)\n", " measurements[2,i] = random.gauss(true_value[2,i],added_noise)\n", " measurements[3,i] = random.gauss(true_value[3,i],added_noise)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lets plot the position data and measurements" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(true_value[0,:],true_value[2,:],'b',measurements[0,:],measurements[2,:],'r')\n", "plt.xlabel('X Position')\n", "plt.ylabel('Y Position')\n", "plt.legend(('true trajectory', 'measured trajectory'), loc=2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So this is how the cricket ball's trajectory is measured, now we go to the filtering part" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "A = np.matrix([[1,del_t,0,0],[0,1,0,0],[0,0,1,del_t],[0,0,0,1]])\n", "B = np.matrix([[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,1]])\n", "u = np.matrix([[0],[0],[-0.5*9.8*del_t*del_t],[-9.8*del_t]]) # control vector is constant does not depend on t\n", "H = np.eye(4)\n", "Q = 0.0001 * np.eye(4)\n", "R = 0.3 * np.eye(4)\n", "X0 = np.matrix([[0],[ux0],[500],[uy0]]) # set it little different than the orig initial just to show that KF will still work\n", "P0 = np.eye(4) # set arbitrary as identity\n", "\n", "estimate_matrix = np.zeros((4,max_iter))\n", "estimate_matrix[:,0] = np.asarray(X0)[:,0]\n", "estimate_error = P0\n", "KF = kalmanFilter(X0, P0, A, B, H, Q, R)\n", " \n", "for i in range(max_iter-1):\n", " Z = np.matrix([[measurements[0,i+1]],[measurements[1,i+1]],[measurements[2,i+1]],[measurements[3,i+1]]])\n", " estimate_matrix[:,i+1] = np.asarray(KF.getEstimate())[:,0]\n", " KF.iteration(u,Z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(true_value[0,:],true_value[2,:],'b',measurements[0,:],measurements[2,:],'r',estimate_matrix[0,:],estimate_matrix[2,:],'g')\n", "plt.xlabel('X Position')\n", "plt.ylabel('Y Position')\n", "plt.legend(('true trajectory', 'measured trajectory', 'filtered trajectory'), loc=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Zoom and see if you are not able to. Now I think you can also look at the error terms and velocity estimates by changing the code little bit.\n", "\n", "This concludes it! Hopefully well :D\n", "\n", "Here are some references\n", "\n", "## References" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* [This one is real cool](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf). I took most of the stuff from here.\n", "* [Bit involved but good](https://www.cl.cam.ac.uk/~rmf25/papers/Understanding%20the%20Basis%20of%20the%20Kalman%20Filter.pdf).\n", "* [Beginner](http://biorobotics.ri.cmu.edu/papers/sbp_papers/integrated3/kleeman_kalman_basics.pdf)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }