{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## KF Basics - Part 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Probabilistic Generative Laws\n",
    " \n",
    "#### 1st Law:\n",
    "The belief representing the state $x_{t}$, is conditioned on all past states, measurements and controls. This can be shown mathematically by the conditional probability shown below:\n",
    "\n",
    "$$p(x_{t} | x_{0:t-1},z_{1:t-1},u_{1:t})$$\n",
    "\n",
    "1) $z_{t}$ represents the **measurement**\n",
    "\n",
    "2) $u_{t}$ the **motion command**\n",
    "\n",
    "3) $x_{t}$ the **state** (can be the position, velocity, etc) of the robot or its environment at time t.\n",
    "\n",
    "\n",
    "'If we know the state $x_{t-1}$ and $u_{t}$, then knowing the states $x_{0:t-2}$, $z_{1:t-1}$ becomes immaterial through the property of **conditional independence**'. The state $x_{t-1}$ introduces a conditional independence between $x_{t}$ and $z_{1:t-1}$, $u_{1:t-1}$\n",
    "\n",
    "Therefore the law now holds as:\n",
    "\n",
    "$$p(x_{t} | x_{0:t-1},z_{1:t-1},u_{1:t})=p(x_{t} | x_{t-1},u_{t})$$\n",
    "\n",
    "#### 2nd Law:\n",
    "\n",
    "If $x_{t}$ is complete, then:\n",
    "\n",
    "$$p(z_{t} | x_{0:t},z_{1:t-1},u_{1:t})=p(z_{t} | x_{t})$$\n",
    "\n",
    "$x_{t}$ is **complete** means that the past states, controls or measurements carry no additional information to predict future.\n",
    "\n",
    "$x_{0:t-1}$, $z_{1:t-1}$ and $u_{1:t}$ are **conditionally independent** of $z_{t}$ given $x_{t}$ of complete.\n",
    "\n",
    "The filter works in two parts:\n",
    "\n",
    "$p(x_{t} | x_{t-1},u_{t})$ -> **State Transition Probability**\n",
    "\n",
    "$p(z_{t} | x_{t})$ -> **Measurement Probability**\n",
    "\n",
    "\n",
    "### Conditional dependence and independence example:\n",
    "\n",
    "\n",
    "$\\bullet$**Independent but conditionally dependent**\n",
    "\n",
    "Let's say you flip two fair coins\n",
    "\n",
    "A - Your first coin flip is heads\n",
    "\n",
    "B - Your second coin flip is heads\n",
    "\n",
    "C - Your first two flips were the same\n",
    "\n",
    "\n",
    "A and B here are independent. However, A and B are conditionally dependent given C, since if you know C then your first coin flip will inform the other one.\n",
    "\n",
    "$\\bullet$**Dependent but conditionally independent**\n",
    "\n",
    "A box contains two coins: a regular coin and one fake two-headed coin ((P(H)=1). I choose a coin at random and toss it twice. Define the following events.\n",
    "\n",
    "A= First coin toss results in an H.\n",
    "\n",
    "B= Second coin toss results in an H.\n",
    "\n",
    "C= Coin 1 (regular) has been selected.                                                             \n",
    "\n",
    "If we know A has occurred (i.e., the first coin toss has resulted in heads), we would guess that it is more likely that we have chosen Coin 2 than Coin 1. This in turn increases the conditional probability that B occurs. This suggests that A and B are not independent. On the other hand, given C (Coin 1 is selected), A and B are independent.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bayes Rule:\n",
    "\n",
    "\n",
    "Posterior = $$\\frac{Likelihood*Prior}{Marginal} $$\n",
    "\n",
    "Here,\n",
    "\n",
    "**Posterior** = Probability of an event occurring based on certain evidence.\n",
    "\n",
    "**Likelihood** = How probable is the evidence given the event.\n",
    "\n",
    "**Prior** = Probability of the just the event occurring without having any evidence.\n",
    "\n",
    "**Marginal** = Probability of the evidence given all the instances of events possible.\n",
    "\n",
    "\n",
    "\n",
    "Example:\n",
    "\n",
    "1% of women have breast cancer (and therefore 99% do not).\n",
    "80% of mammograms detect breast cancer when it is there (and therefore 20% miss it).\n",
    "9.6% of mammograms detect breast cancer when its not there (and therefore 90.4% correctly return a negative result).\n",
    "\n",
    "We can turn the process above into an equation, which is Bayes Theorem. Here is the equation:\n",
    "\n",
    "$\\displaystyle{\\Pr(\\mathrm{A}|\\mathrm{X}) = \\frac{\\Pr(\\mathrm{X}|\\mathrm{A})\\Pr(\\mathrm{A})}{\\Pr(\\mathrm{X|A})\\Pr(\\mathrm{A})+ \\Pr(\\mathrm{X | not \\ A})\\Pr(\\mathrm{not \\ A})}}$\n",
    "\n",
    "\n",
    "$\\bullet$Pr(A|X) = Chance of having cancer (A) given a positive test (X). This is what we want to know: How likely is it to have cancer with a positive result? In our case it was 7.8%.\n",
    "\n",
    "$\\bullet$Pr(X|A) = Chance of a positive test (X) given that you had cancer (A). This is the chance of a true positive, 80% in our case.\n",
    "\n",
    "$\\bullet$Pr(A) = Chance of having cancer (1%).\n",
    "\n",
    "$\\bullet$Pr(not A) = Chance of not having cancer (99%).\n",
    "\n",
    "$\\bullet$Pr(X|not A) = Chance of a positive test (X) given that you didn't have cancer (~A). This is a false positive, 9.6% in our case.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bayes Filter Algorithm\n",
    "\n",
    "The basic filter algorithm is:\n",
    "\n",
    "for all $x_{t}$:\n",
    "\n",
    "1. $\\overline{bel}(x_t) = \\int p(x_t | u_t, x_{t-1}) bel(x_{t-1})dx$\n",
    "\n",
    "2. $bel(x_t) = \\eta p(z_t | x_t) \\overline{bel}(x_t)$\n",
    "\n",
    "end.\n",
    "\n",
    "\n",
    "$\\rightarrow$The first step in filter is to calculate the prior for the next step that uses the bayes theorem. This is the **Prediction** step. The belief, $\\overline{bel}(x_t)$, is **before** incorporating measurement($z_{t}$) at time t=t. This is the step where the motion occurs and information is lost because the means and covariances of the gaussians are added. The RHS of the equation incorporates the law of total probability for prior calculation.\n",
    "\n",
    "$\\rightarrow$ This is the **Correction** or update step that calculates the belief of the robot **after** taking into account the measurement($z_{t}$) at time t=t. This is where we incorporate the sensor information for the whereabouts of the robot. We gain information here as the gaussians get multiplied here. (Multiplication of gaussian values allows the resultant to lie in between these numbers and the resultant covariance is smaller.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bayes filter localization example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 1450804 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 3,
     "metadata": {
      "image/png": {
       "width": 400
      }
     },
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.display import Image\n",
    "Image(filename=\"bayes_filter.png\",width=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Given - A robot with a sensor to detect doorways along a hallway. Also, the robot knows how the hallway looks like but doesn't know where it is in the map. \n",
    "\n",
    "\n",
    "1. Initially(first scenario), it doesn't know where it is with respect to the map and hence the belief assigns equal probability to each location in the map.\n",
    "\n",
    "\n",
    "2. The first sensor reading is incorporated and it shows the presence of a door. Now the robot knows how the map looks like but cannot localize yet as map has 3 doors present. Therefore it assigns equal probability to each door present. \n",
    "\n",
    "\n",
    "3. The robot now moves forward. This is the prediction step and the motion causes the robot to lose some of the information and hence the variance of the gaussians increase (diagram 4.). The final belief is **convolution** of posterior from previous step and the current state after motion. Also, the means shift on the right due to the motion.\n",
    "\n",
    "\n",
    "4. Again, incorporating the measurement, the sensor senses a door and this time too the possibility of door is equal for the three door. This is where the filter's magic kicks in. For the final belief (diagram 5.), the posterior calculated after sensing is mixed or **convolution** of previous posterior and measurement. It improves the robot's belief at location near to the second door. The variance **decreases** and **peaks**.\n",
    "\n",
    "\n",
    "5. Finally after series of iterations of motion and correction, the robot is able to localize itself with respect to the environment.(diagram 6.)\n",
    "\n",
    "Do note that the robot knows the map but doesn't know where exactly it is on the map."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bayes and Kalman filter structure\n",
    "\n",
    "The basic structure and the concept remains the same as bayes filter for Kalman. The only key difference is the mathematical representation of Kalman filter. The Kalman filter is nothing but a bayesian filter that uses Gaussians.\n",
    "\n",
    "For a bayes filter to be a Kalman filter, **each term of belief is now a gaussian**, unlike histograms.  The basic formulation for the **bayes filter** algorithm is:\n",
    "\n",
    "$$\\begin{aligned} \n",
    "\\bar {\\mathbf x} &= \\mathbf x \\ast f_{\\mathbf x}(\\bullet)\\, \\, &\\text{Prediction} \\\\\n",
    "\\mathbf x &= \\mathcal L \\cdot \\bar{\\mathbf x}\\, \\, &\\text{Correction}\n",
    "\\end{aligned}$$\n",
    "\n",
    "\n",
    "$\\bar{\\mathbf x}$ is the *prior* \n",
    "\n",
    "$\\mathcal L$ is the *likelihood* of a measurement given the prior $\\bar{\\mathbf x}$\n",
    "\n",
    "$f_{\\mathbf x}(\\bullet)$ is the *process model* or the gaussian term that helps predict the next state like velocity\n",
    "to track position or acceleration.\n",
    "\n",
    "$\\ast$ denotes *convolution*.\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Kalman Gain\n",
    "\n",
    "\n",
    "$$ x = (\\mathcal L \\bar x)$$\n",
    "\n",
    "Where x is posterior and $\\mathcal L$ and $\\bar x$ are gaussians.\n",
    "\n",
    "Therefore the mean of the posterior is given by:\n",
    "\n",
    "$$\n",
    "\\mu=\\frac{\\bar\\sigma^2\\, \\mu_z + \\sigma_z^2 \\, \\bar\\mu} {\\bar\\sigma^2 + \\sigma_z^2}\n",
    "$$\n",
    "\n",
    "\n",
    "$$\\mu = \\left( \\frac{\\bar\\sigma^2}{\\bar\\sigma^2 + \\sigma_z^2}\\right) \\mu_z + \\left(\\frac{\\sigma_z^2}{\\bar\\sigma^2 + \\sigma_z^2}\\right)\\bar\\mu$$\n",
    "\n",
    "In this form it is easy to see that we are scaling the measurement and the prior by weights: \n",
    "\n",
    "$$\\mu = W_1 \\mu_z + W_2 \\bar\\mu$$\n",
    "\n",
    "\n",
    "The weights sum to one because the denominator is a normalization term. We introduce a new term, $K=W_1$, giving us:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "\\mu &= K \\mu_z + (1-K) \\bar\\mu\\\\\n",
    "&= \\bar\\mu + K(\\mu_z - \\bar\\mu)\n",
    "\\end{aligned}$$\n",
    "\n",
    "where\n",
    "\n",
    "$$K = \\frac {\\bar\\sigma^2}{\\bar\\sigma^2 + \\sigma_z^2}$$\n",
    "\n",
    "The variance in terms of the Kalman gain:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "\\sigma^2 &= \\frac{\\bar\\sigma^2 \\sigma_z^2 } {\\bar\\sigma^2 + \\sigma_z^2} \\\\\n",
    "&= K\\sigma_z^2 \\\\\n",
    "&= (1-K)\\bar\\sigma^2 \n",
    "\\end{aligned}$$\n",
    "\n",
    "\n",
    "$K$ is the *Kalman gain*. It's the crux of the Kalman filter. It is a scaling term that chooses a value partway between $\\mu_z$ and $\\bar\\mu$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Kalman Filter - Univariate and Multivariate\n",
    "\n",
    "\n",
    "<u>**Prediction**</u>\n",
    "\n",
    "$\\begin{array}{|l|l|l|}\n",
    "\\hline\n",
    "\\text{Univariate} & \\text{Univariate} & \\text{Multivariate}\\\\\n",
    "& \\text{(Kalman form)} & \\\\\n",
    "\\hline\n",
    "\\bar \\mu = \\mu + \\mu_{f_x} & \\bar x = x + dx & \\bar{\\mathbf x} = \\mathbf{Fx} + \\mathbf{Bu}\\\\\n",
    "\\bar\\sigma^2 = \\sigma_x^2 + \\sigma_{f_x}^2 & \\bar P = P + Q & \\bar{\\mathbf P} = \\mathbf{FPF}^\\mathsf T + \\mathbf Q \\\\\n",
    "\\hline\n",
    "\\end{array}$\n",
    "\n",
    "$\\mathbf x,\\, \\mathbf P$ are the state mean and covariance. They correspond to $x$ and $\\sigma^2$.\n",
    "\n",
    "$\\mathbf F$ is the *state transition function*. When multiplied by $\\bf x$ it computes the prior. \n",
    "\n",
    "$\\mathbf Q$ is the process covariance. It corresponds to $\\sigma^2_{f_x}$.\n",
    "\n",
    "$\\mathbf B$ and $\\mathbf u$ are model control inputs to the system.\n",
    "\n",
    "<u>**Correction**</u>\n",
    "\n",
    "$\\begin{array}{|l|l|l|}\n",
    "\\hline\n",
    "\\text{Univariate} & \\text{Univariate} & \\text{Multivariate}\\\\\n",
    "& \\text{(Kalman form)} & \\\\\n",
    "\\hline\n",
    "& y = z - \\bar x & \\mathbf y = \\mathbf z - \\mathbf{H\\bar x} \\\\\n",
    "& K = \\frac{\\bar P}{\\bar P+R}&\n",
    "\\mathbf K = \\mathbf{\\bar{P}H}^\\mathsf T (\\mathbf{H\\bar{P}H}^\\mathsf T + \\mathbf R)^{-1} \\\\\n",
    "\\mu=\\frac{\\bar\\sigma^2\\, \\mu_z + \\sigma_z^2 \\, \\bar\\mu} {\\bar\\sigma^2 + \\sigma_z^2} & x = \\bar x + Ky & \\mathbf x = \\bar{\\mathbf x} + \\mathbf{Ky} \\\\\n",
    "\\sigma^2 = \\frac{\\sigma_1^2\\sigma_2^2}{\\sigma_1^2+\\sigma_2^2} & P = (1-K)\\bar P &\n",
    "\\mathbf P = (\\mathbf I - \\mathbf{KH})\\mathbf{\\bar{P}} \\\\\n",
    "\\hline\n",
    "\\end{array}$\n",
    "\n",
    "$\\mathbf H$ is the measurement function.\n",
    "\n",
    "$\\mathbf z,\\, \\mathbf R$ are the measurement mean and noise covariance. They correspond to $z$ and $\\sigma_z^2$ in the univariate filter. \n",
    "$\\mathbf y$ and $\\mathbf K$ are the residual and Kalman gain. \n",
    "\n",
    "The details will be different than the univariate filter because these are vectors and matrices, but the concepts are exactly the same: \n",
    "\n",
    "-  Use a Gaussian to represent our estimate of the state and error\n",
    "-  Use a Gaussian to represent the measurement and its error\n",
    "-  Use a Gaussian to represent the process model\n",
    "-  Use the process model to predict the next state (the prior)\n",
    "-  Form an estimate part way between the measurement and the prior"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### References:\n",
    "\n",
    "1. Roger Labbe's [repo](https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python) on Kalman Filters. (Majority of text in the notes are from this)\n",
    "\n",
    "\n",
    "\n",
    "2. Probabilistic Robotics by Sebastian Thrun, Wolfram Burgard and Dieter Fox, MIT Press.\n"
   ]
  }
 ],
 "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.6.6"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}