{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Robust Kalman filtering for vehicle tracking\n",
    "\n",
    "We will try to pinpoint the location of a moving vehicle with high accuracy from noisy sensor data. We'll do this by modeling the vehicle state as a discrete-time linear dynamical system. Standard **Kalman filtering** can be used to approach this problem when the sensor noise is assumed to be Gaussian. We'll use **robust Kalman filtering** to get a more accurate estimate of the vehicle state for a non-Gaussian case with outliers.\n",
    "\n",
    "# Problem statement\n",
    " \n",
    "A discrete-time linear dynamical system consists of a sequence of state vectors $x_t \\in \\mathbf{R}^n$, indexed by time $t \\in \\lbrace 0, \\ldots, N-1 \\rbrace$ and dynamics equations\n",
    "\n",
    "\\begin{align}\n",
    "x_{t+1} &= Ax_t + Bw_t\\\\\n",
    "y_t &=Cx_t + v_t,\n",
    "\\end{align}\n",
    "\n",
    "where $w_t \\in \\mathbf{R}^m$ is an input to the dynamical system (say, a drive force on the vehicle), $y_t \\in \\mathbf{R}^r$ is a state measurement, $v_t \\in \\mathbf{R}^r$ is noise, $A$ is the drift matrix, $B$ is the input matrix, and $C$ is the observation matrix.\n",
    "\n",
    "Given $A$, $B$, $C$, and $y_t$ for $t = 0, \\ldots, N-1$, the goal is to estimate $x_t$ for $t = 0, \\ldots, N-1$.\n",
    "\n",
    "# Kalman filtering\n",
    "\n",
    "A Kalman filter estimates $x_t$ by solving the optimization problem\n",
    "\n",
    "\\begin{array}{ll}\n",
    "\\mbox{minimize} & \\sum_{t=0}^{N-1} \\left( \n",
    "\\|w_t\\|_2^2 + \\tau \\|v_t\\|_2^2\\right)\\\\\n",
    "\\mbox{subject to} & x_{t+1} = Ax_t + Bw_t,\\quad t=0,\\ldots, N-1\\\\\n",
    "& y_t = Cx_t+v_t,\\quad t = 0, \\ldots, N-1,\n",
    "\\end{array}\n",
    "\n",
    "where $\\tau$ is a tuning parameter. This problem is actually a least squares problem, and can be solved via linear algebra, without the need for more general convex optimization. Note that since we have no observation $y_{N}$, $x_N$ is only constrained via $x_{N} = Ax_{N-1} + Bw_{N-1}$, which is trivially resolved when $w_{N-1} = 0$ and $x_{N} = Ax_{N-1}$. We maintain this vestigial constraint only because it offers a concise problem statement.\n",
    "\n",
    "This model performs well when $w_t$ and $v_t$ are Gaussian. However, the quadratic objective can be influenced by large outliers, which degrades the accuracy of the recovery. To improve estimation in the presence of outliers, we can use **robust Kalman filtering**.\n",
    "\n",
    "# Robust Kalman filtering\n",
    "\n",
    "To handle outliers in $v_t$, robust Kalman filtering replaces the quadratic cost with a Huber cost, which results in the convex optimization problem\n",
    "\n",
    "\\begin{array}{ll}\n",
    "\\mbox{minimize} & \\sum_{t=0}^{N-1} \\left( \\|w_t\\|^2_2 + \\tau \\phi_\\rho(v_t) \\right)\\\\\n",
    "\\mbox{subject to} & x_{t+1} = Ax_t + Bw_t,\\quad t=0,\\ldots, N-1\\\\\n",
    "& y_t = Cx_t+v_t,\\quad t=0,\\ldots, N-1,\n",
    "\\end{array}\n",
    "\n",
    "where $\\phi_\\rho$ is the Huber function\n",
    "$$\n",
    "\\phi_\\rho(a)= \\left\\{ \\begin{array}{ll} \\|a\\|_2^2 & \\|a\\|_2\\leq \\rho\\\\\n",
    "2\\rho \\|a\\|_2-\\rho^2 & \\|a\\|_2>\\rho.\n",
    "\\end{array}\\right.\n",
    "$$\n",
    "\n",
    "The Huber penalty function penalizes estimation error linearly outside of a ball of radius $\\rho$, whereas in standard Kalman filtering, all errors are penalized quadratically. Thus, large errors are penalized less harshly, making this model more robust to outliers.\n",
    "\n",
    "# Vehicle tracking example\n",
    "\n",
    "We'll apply standard and robust Kalman filtering to a vehicle tracking problem with state $x_t \\in \\mathbf{R}^4$, where\n",
    "$(x_{t,0}, x_{t,1})$ is the position of the vehicle in two dimensions, and $(x_{t,2}, x_{t,3})$ is the vehicle velocity.\n",
    "The vehicle has unknown drive force $w_t$, and we observe noisy measurements of the vehicle's position, $y_t \\in \\mathbf{R}^2$.\n",
    "\n",
    "The matrices for the dynamics are\n",
    "\n",
    "$$\n",
    "A = \\begin{bmatrix}\n",
    "1 & 0 & \\left(1-\\frac{\\gamma}{2}\\Delta t\\right) \\Delta t & 0 \\\\\n",
    "0 & 1 & 0 & \\left(1-\\frac{\\gamma}{2} \\Delta t\\right) \\Delta t\\\\\n",
    "0 & 0 & 1-\\gamma \\Delta t & 0 \\\\\n",
    "0 & 0 & 0 & 1-\\gamma \\Delta t\n",
    "\\end{bmatrix},\n",
    "$$\n",
    "\n",
    "$$\n",
    "B = \\begin{bmatrix}\n",
    "\\frac{1}{2}\\Delta t^2 & 0 \\\\\n",
    "0 & \\frac{1}{2}\\Delta t^2 \\\\\n",
    "\\Delta t & 0 \\\\\n",
    "0 & \\Delta t \\\\\n",
    "\\end{bmatrix},\n",
    "$$\n",
    "\n",
    "$$\n",
    "C = \\begin{bmatrix}\n",
    "1 & 0 & 0 & 0 \\\\\n",
    "0 & 1 & 0 & 0\n",
    "\\end{bmatrix},\n",
    "$$\n",
    "where $\\gamma$ is a velocity damping parameter.\n",
    "\n",
    "# 1D Model\n",
    "The recurrence is derived from the following relations in a single dimension. For this subsection, let $x_t, v_t, w_t$ be the vehicle position, velocity, and input drive force. The resulting acceleration of the vehicle is $w_t - \\gamma v_t$, with $- \\gamma v_t$ is a damping term depending on velocity with parameter $\\gamma$. \n",
    "\n",
    "The discretized dynamics are obtained from numerically integrating:\n",
    "$$\n",
    "\\begin{align}\n",
    "x_{t+1} &= x_t + \\left(1-\\frac{\\gamma \\Delta t}{2}\\right)v_t \\Delta t + \\frac{1}{2}w_{t} \\Delta t^2\\\\\n",
    "v_{t+1} &= \\left(1-\\gamma\\right)v_t + w_t \\Delta t.\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "Extending these relations to two dimensions gives us the dynamics matrices $A$ and $B$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Helper Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "def plot_state(t,actual, estimated=None):\n",
    "    '''\n",
    "    plot position, speed, and acceleration in the x and y coordinates for\n",
    "    the actual data, and optionally for the estimated data\n",
    "    '''\n",
    "    trajectories = [actual]\n",
    "    if estimated is not None:\n",
    "        trajectories.append(estimated)\n",
    "        \n",
    "    fig, ax = plt.subplots(3, 2, sharex='col', sharey='row', figsize=(8,8))\n",
    "    for x, w in trajectories:  \n",
    "        ax[0,0].plot(t,x[0,:-1])\n",
    "        ax[0,1].plot(t,x[1,:-1])\n",
    "        ax[1,0].plot(t,x[2,:-1])\n",
    "        ax[1,1].plot(t,x[3,:-1])\n",
    "        ax[2,0].plot(t,w[0,:])\n",
    "        ax[2,1].plot(t,w[1,:])\n",
    "        \n",
    "    ax[0,0].set_ylabel('x position')\n",
    "    ax[1,0].set_ylabel('x velocity')\n",
    "    ax[2,0].set_ylabel('x input')\n",
    "    \n",
    "    ax[0,1].set_ylabel('y position')\n",
    "    ax[1,1].set_ylabel('y velocity')\n",
    "    ax[2,1].set_ylabel('y input')\n",
    "    \n",
    "    ax[0,1].yaxis.tick_right()\n",
    "    ax[1,1].yaxis.tick_right()\n",
    "    ax[2,1].yaxis.tick_right()\n",
    "    \n",
    "    ax[0,1].yaxis.set_label_position(\"right\")\n",
    "    ax[1,1].yaxis.set_label_position(\"right\")\n",
    "    ax[2,1].yaxis.set_label_position(\"right\")\n",
    "    \n",
    "    ax[2,0].set_xlabel('time')\n",
    "    ax[2,1].set_xlabel('time')\n",
    "\n",
    "def plot_positions(traj, labels, axis=None,filename=None):\n",
    "    '''\n",
    "    show point clouds for true, observed, and recovered positions\n",
    "    '''\n",
    "    matplotlib.rcParams.update({'font.size': 14})\n",
    "    n = len(traj)\n",
    "\n",
    "    fig, ax = plt.subplots(1, n, sharex=True, sharey=True,figsize=(12, 5))\n",
    "    if n == 1:\n",
    "        ax = [ax]\n",
    "    \n",
    "    for i,x in enumerate(traj):\n",
    "        ax[i].plot(x[0,:], x[1,:], 'ro', alpha=.1)\n",
    "        ax[i].set_title(labels[i])\n",
    "        if axis:\n",
    "            ax[i].axis(axis)\n",
    "    \n",
    "    if filename:\n",
    "        fig.savefig(filename, bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem Data\n",
    "\n",
    "We generate the data for the vehicle tracking problem. We'll have $N=1000$, $w_t$ a standard Gaussian, and $v_t$ a standard Guassian, except $20\\%$ of the points will be outliers with $\\sigma = 20$.\n",
    "\n",
    "Below, we set the problem parameters and define the matrices $A$, $B$, and $C$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 1000 # number of timesteps\n",
    "T = 50 # time will vary from 0 to T with step delt\n",
    "ts, delt = np.linspace(0,T,n,endpoint=True, retstep=True)\n",
    "gamma = .05 # damping, 0 is no damping\n",
    "\n",
    "A = np.zeros((4,4))\n",
    "B = np.zeros((4,2))\n",
    "C = np.zeros((2,4))\n",
    "\n",
    "A[0,0] = 1\n",
    "A[1,1] = 1\n",
    "A[0,2] = (1-gamma*delt/2)*delt\n",
    "A[1,3] = (1-gamma*delt/2)*delt\n",
    "A[2,2] = 1 - gamma*delt\n",
    "A[3,3] = 1 - gamma*delt\n",
    "\n",
    "B[0,0] = delt**2/2\n",
    "B[1,1] = delt**2/2\n",
    "B[2,0] = delt\n",
    "B[3,1] = delt\n",
    "\n",
    "C[0,0] = 1\n",
    "C[1,1] = 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simulation\n",
    "\n",
    "We seed $x_0 = 0$ (starting at the origin with zero velocity) and simulate the system forward in time. The results are the true vehicle positions `x_true` (which we will use to judge our recovery) and the observed positions `y`.\n",
    "\n",
    "We plot the position, velocity, and system input $w$ in both dimensions as a function of time.\n",
    "We also plot the sets of true and observed vehicle positions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 53728 characters]\n",
      "text/plain": [
       "<Figure size 576x576 with 6 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 55668 characters]\n",
      "text/plain": [
       "<Figure size 864x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "sigma = 20\n",
    "p = .20\n",
    "np.random.seed(6)\n",
    "\n",
    "x = np.zeros((4,n+1))\n",
    "x[:,0] = [0,0,0,0]\n",
    "y = np.zeros((2,n))\n",
    "\n",
    "# generate random input and noise vectors\n",
    "w = np.random.randn(2,n)\n",
    "v = np.random.randn(2,n)\n",
    "\n",
    "# add outliers to v\n",
    "np.random.seed(0)\n",
    "inds = np.random.rand(n) <= p\n",
    "v[:,inds] = sigma*np.random.randn(2,n)[:,inds]\n",
    "\n",
    "# simulate the system forward in time\n",
    "for t in range(n):\n",
    "    y[:,t] = C.dot(x[:,t]) + v[:,t]\n",
    "    x[:,t+1] = A.dot(x[:,t]) + B.dot(w[:,t])\n",
    "    \n",
    "x_true = x.copy()\n",
    "w_true = w.copy()\n",
    "\n",
    "plot_state(ts,(x_true,w_true))\n",
    "plot_positions([x_true,y], ['True', 'Observed'],[-4,14,-5,20],'rkf1.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Kalman filtering recovery\n",
    "\n",
    "The code below solves the standard Kalman filtering problem using CVXPY. We plot and compare the true and recovered vehicle states. Note that the recovery is distorted by outliers in the measurements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----------------------------------------------------------------\n",
      "           OSQP v0.4.1  -  Operator Splitting QP Solver\n",
      "              (c) Bartolomeo Stellato,  Goran Banjac\n",
      "        University of Oxford  -  Stanford University 2018\n",
      "-----------------------------------------------------------------\n",
      "problem:  variables n = 8004, constraints m = 6000\n",
      "          nnz(P) + nnz(A) = 22000\n",
      "settings: linear system solver = qdldl,\n",
      "          eps_abs = 1.0e-03, eps_rel = 1.0e-03,\n",
      "          eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04,\n",
      "          rho = 1.00e-01 (adaptive),\n",
      "          sigma = 1.00e-06, alpha = 1.60, max_iter = 4000\n",
      "          check_termination: on (interval 25),\n",
      "          scaling: on, scaled_termination: off\n",
      "          warm start: on, polish: on\n",
      "\n",
      "iter   objective    pri res    dua res    rho        time\n",
      "   1   0.0000e+00   6.14e+01   6.14e+03   1.00e-01   1.28e-02s\n",
      "  50   1.1057e+04   3.57e-07   8.27e-08   1.00e-01   3.01e-02s\n",
      "plsh   1.1057e+04   7.11e-15   1.24e-14   --------   3.78e-02s\n",
      "\n",
      "status:               solved\n",
      "solution polish:      successful\n",
      "number of iterations: 50\n",
      "optimal objective:    11057.3550\n",
      "run time:             3.78e-02s\n",
      "optimal rho estimate: 7.70e-02\n",
      "\n",
      "optimal objective value: 11057.354957764113\n",
      "CPU times: user 13 s, sys: 598 ms, total: 13.6 s\n",
      "Wall time: 13.8 s\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 72504 characters]\n",
      "text/plain": [
       "<Figure size 576x576 with 6 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 54836 characters]\n",
      "text/plain": [
       "<Figure size 864x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 29232 characters]\n",
      "text/plain": [
       "<Figure size 864x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%time\n",
    "import cvxpy as cp\n",
    "\n",
    "x = cp.Variable(shape=(4, n+1))\n",
    "w = cp.Variable(shape=(2, n))\n",
    "v = cp.Variable(shape=(2, n))\n",
    "\n",
    "tau = .08\n",
    "    \n",
    "obj = cp.sum_squares(w) + tau*cp.sum_squares(v)\n",
    "obj = cp.Minimize(obj)\n",
    "\n",
    "constr = []\n",
    "for t in range(n):\n",
    "    constr += [ x[:,t+1] == A*x[:,t] + B*w[:,t] ,\n",
    "                y[:,t]   == C*x[:,t] + v[:,t]   ]\n",
    "\n",
    "cp.Problem(obj, constr).solve(verbose=True)\n",
    "\n",
    "x = np.array(x.value)\n",
    "w = np.array(w.value)\n",
    "\n",
    "plot_state(ts,(x_true,w_true),(x,w))\n",
    "plot_positions([x_true,y], ['True', 'Noisy'], [-4,14,-5,20])\n",
    "plot_positions([x_true,x], ['True', 'KF recovery'], [-4,14,-5,20], 'rkf2.pdf')\n",
    "\n",
    "print(\"optimal objective value: {}\".format(obj.value))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Robust Kalman filtering recovery\n",
    "\n",
    "Here we implement robust Kalman filtering with CVXPY. We get a better recovery than the standard Kalman filtering, which can be seen in the plots below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "ECOS 2.0.4 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS\n",
      "\n",
      "It     pcost       dcost      gap   pres   dres    k/t    mu     step   sigma     IR    |   BT\n",
      " 0  +0.000e+00  -2.923e+02  +7e+05  3e-01  3e-02  1e+00  2e+02    ---    ---    1  1  - |  -  - \n",
      " 1  +5.090e+02  +4.360e+02  +2e+05  4e-01  1e-02  3e+01  6e+01  0.8051  2e-01   2  1  1 |  0  0\n",
      " 2  +4.188e+03  +4.134e+03  +2e+05  3e-01  9e-03  3e+01  5e+01  0.4259  6e-01   1  1  1 |  0  0\n",
      " 3  +9.956e+03  +9.923e+03  +1e+05  3e-01  8e-03  4e+01  4e+01  0.5830  5e-01   1  1  2 |  0  0\n",
      " 4  +1.881e+04  +1.880e+04  +7e+04  3e-01  5e-03  3e+01  2e+01  0.7189  3e-01   1  1  1 |  0  0\n",
      " 5  +2.572e+04  +2.572e+04  +4e+04  2e-01  3e-03  2e+01  1e+01  0.5464  3e-01   1  1  1 |  0  0\n",
      " 6  +2.986e+04  +2.985e+04  +3e+04  2e-01  2e-03  1e+01  6e+00  0.5716  3e-01   2  2  1 |  0  0\n",
      " 7  +3.262e+04  +3.262e+04  +1e+04  9e-02  1e-03  7e+00  3e+00  0.6007  2e-01   2  2  2 |  0  0\n",
      " 8  +3.425e+04  +3.425e+04  +8e+03  5e-02  7e-04  5e+00  2e+00  0.5871  3e-01   2  2  2 |  0  0\n",
      " 9  +3.601e+04  +3.601e+04  +4e+03  3e-02  3e-04  2e+00  9e-01  0.6383  2e-01   2  2  2 |  0  0\n",
      "10  +3.728e+04  +3.727e+04  +2e+03  1e-02  2e-04  1e+00  5e-01  0.7925  4e-01   2  2  2 |  0  0\n",
      "11  +3.759e+04  +3.759e+04  +1e+03  1e-02  1e-04  1e+00  3e-01  0.5191  5e-01   2  2  2 |  0  0\n",
      "12  +3.824e+04  +3.824e+04  +6e+02  6e-03  5e-05  5e-01  2e-01  0.9890  4e-01   2  2  2 |  0  0\n",
      "13  +3.860e+04  +3.860e+04  +3e+02  3e-03  2e-05  3e-01  7e-02  0.6740  2e-01   2  2  2 |  0  0\n",
      "14  +3.864e+04  +3.864e+04  +3e+02  3e-03  2e-05  3e-01  7e-02  0.2982  7e-01   2  2  3 |  0  0\n",
      "15  +3.876e+04  +3.876e+04  +2e+02  2e-03  1e-05  2e-01  4e-02  0.9890  6e-01   2  2  2 |  0  0\n",
      "16  +3.889e+04  +3.889e+04  +8e+01  1e-03  4e-06  1e-01  2e-02  0.7740  4e-01   3  3  3 |  0  0\n",
      "17  +3.899e+04  +3.899e+04  +2e+01  4e-04  1e-06  3e-02  6e-03  0.9702  3e-01   3  3  3 |  0  0\n",
      "18  +3.901e+04  +3.901e+04  +1e+01  4e-04  6e-07  3e-02  4e-03  0.6771  5e-01   4  3  3 |  0  0\n",
      "19  +3.903e+04  +3.903e+04  +7e+00  2e-04  3e-07  2e-02  2e-03  0.9383  5e-01   3  2  3 |  0  0\n",
      "20  +3.905e+04  +3.905e+04  +2e+00  1e-04  1e-07  1e-02  6e-04  0.8982  3e-01   4  4  4 |  0  0\n",
      "21  +3.906e+04  +3.906e+04  +9e-01  5e-05  5e-08  5e-03  2e-04  0.9342  3e-01   3  2  3 |  0  0\n",
      "22  +3.907e+04  +3.907e+04  +3e-01  4e-05  3e-08  4e-03  8e-05  0.8457  3e-01   5  4  4 |  0  0\n",
      "23  +3.908e+04  +3.908e+04  +8e-02  1e-05  8e-09  1e-03  2e-05  0.9890  3e-01   3  3  3 |  0  0\n",
      "24  +3.908e+04  +3.908e+04  +1e-02  2e-06  2e-09  2e-04  3e-06  0.9013  5e-02   3  3  3 |  0  0\n",
      "25  +3.908e+04  +3.908e+04  +2e-03  4e-07  4e-10  4e-05  5e-07  0.9207  8e-02   3  2  2 |  0  0\n",
      "26  +3.908e+04  +3.908e+04  +7e-04  2e-07  2e-10  2e-05  2e-07  0.9890  4e-01   2  2  2 |  0  0\n",
      "27  +3.908e+04  +3.908e+04  +8e-05  3e-08  5e-11  2e-06  2e-08  0.9009  2e-02   2  2  2 |  0  0\n",
      "28  +3.908e+04  +3.908e+04  +2e-05  1e-08  2e-11  4e-07  5e-09  0.9890  2e-01   2  2  2 |  0  0\n",
      "29  +3.908e+04  +3.908e+04  +2e-06  3e-09  5e-12  5e-08  5e-10  0.9058  2e-02   2  1  1 |  0  0\n",
      "\n",
      "OPTIMAL (within feastol=3.1e-09, reltol=5.3e-11, abstol=2.1e-06).\n",
      "Runtime: 1.129066 seconds.\n",
      "\n",
      "optimal objective value: 39077.76954636933\n",
      "CPU times: user 3min 37s, sys: 3.44 s, total: 3min 41s\n",
      "Wall time: 3min 55s\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 71924 characters]\n",
      "text/plain": [
       "<Figure size 576x576 with 6 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 54836 characters]\n",
      "text/plain": [
       "<Figure size 864x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 29868 characters]\n",
      "text/plain": [
       "<Figure size 864x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%time\n",
    "import cvxpy as cp\n",
    "\n",
    "x = cp.Variable(shape=(4, n+1))\n",
    "w = cp.Variable(shape=(2, n))\n",
    "v = cp.Variable(shape=(2, n))\n",
    "\n",
    "tau = 2\n",
    "rho = 2\n",
    "    \n",
    "obj = cp.sum_squares(w)\n",
    "obj += cp.sum([tau*cp.huber(cp.norm(v[:,t]),rho) for t in range(n)])\n",
    "obj = cp.Minimize(obj)\n",
    "\n",
    "constr = []\n",
    "for t in range(n):\n",
    "    constr += [ x[:,t+1] == A*x[:,t] + B*w[:,t] ,\n",
    "                y[:,t]   == C*x[:,t] + v[:,t]   ]\n",
    "\n",
    "cp.Problem(obj, constr).solve(verbose=True)\n",
    "\n",
    "x = np.array(x.value)\n",
    "w = np.array(w.value)\n",
    "\n",
    "plot_state(ts,(x_true,w_true),(x,w))\n",
    "plot_positions([x_true,y], ['True', 'Noisy'], [-4,14,-5,20])\n",
    "plot_positions([x_true,x], ['True', 'Robust KF recovery'], [-4,14,-5,20],'rkf3.pdf')\n",
    "\n",
    "print(\"optimal objective value: {}\".format(obj.value))"
   ]
  }
 ],
 "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
