{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Optimizations with Physical Gradients\n",
    "\n",
    "The previous section has made many comments about the advantages and disadvantages of different optimization methods. Below we'll show with a practical example how much differences these properties actually make.\n",
    "\n",
    "\n",
    "## Problem formulation\n",
    "\n",
    "We'll consider a very simple setup to clearly illustrate what's happening: we have a two-dimensional input space $\\mathbf{x}$, a mock \"physical model\" likewise with two dimensions $\\mathbf{z}$, and a scalar loss $L$, i.e. \n",
    "$\\mathbf{x} \\in \\mathbb{R}^2$, \n",
    "$\\mathbf{z}:  \\mathbb{R}^2 \\rightarrow  \\mathbb{R}^2 $, and \n",
    "$L:  \\mathbb{R}^2 \\rightarrow  \\mathbb{R} $.\n",
    "The components of a vector like $\\mathbf{x}$ are denoted with $x_i$, and to be in sync with python arrays the indices start at 0.\n",
    "\n",
    "Specifically, we'll use the following  $\\mathbf{z}$ and $L$:\n",
    "\n",
    "$\\quad \\mathbf{z}(\\mathbf{x}) = \\mathbf{z}(x_0,x_1) = \\begin{bmatrix} x_0 \\\\ x_1^2 \\end{bmatrix}$, \n",
    "i.e. $\\mathbf{z}$ only squares the second component of its input, and\n",
    "\n",
    "$\\quad L(\\mathbf{z}) = |\\mathbf{z}|^2 = z_0^2 + z_1^2  \\  $ \n",
    "represents a simple squared $L^2$ loss.\n",
    "\n",
    "As starting point for some example optimizations we'll use \n",
    "$\\mathbf{x} = \\begin{bmatrix} \n",
    "  3 \\\\ 3\n",
    "\\end{bmatrix}$ as initial guess for solving the following simple minimization problem:\n",
    "\n",
    "$\\quad \\text{arg min}_{\\mathbf{x}} \\ L(\\mathbf{x}).$\n",
    "\n",
    "For us as humans it's quite obvious that $[0 \\ 0]^T$ is the right answer, but let's see how quickly the different optimization algorithms discussed in the previous section can find that solution. And while $\\mathbf{z}$ is a very simple function, it is nonlinear due to its $x_1^2$.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 3 Spaces\n",
    "\n",
    "In order to understand the following examples, it's important to keep in mind that we're dealing with mappings between the three _spaces_ we've introduced here:\n",
    "$\\mathbf{x}$, $\\mathbf{z}$ and $L$. A regular forward pass maps an\n",
    "$\\mathbf{x}$ to $L$, while for the optimization we'll need to associate values\n",
    "and changes in $L$ with positions in $\\mathbf{x}$. While doing this, it will \n",
    "be interesting how this influences the positions in $\\mathbf{z}$ that develop while searching for\n",
    "the right position in $\\mathbf{x}$.\n",
    "\n",
    "```{figure} resources/placeholder.png\n",
    "---\n",
    "height: 220px\n",
    "name: pg-three-spaces\n",
    "---\n",
    "TODO, visual overview of 3 spaces\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Implementation\n",
    "\n",
    "For this example we'll use the [JAX framework](https://github.com/google/jax), which represents a nice alternative to pytorch and tensorflow for efficiently working with differentiable functions.\n",
    "JAX also has a nice numpy wrapper that implements most of numpy's functions. Below we'll use this wrapper as `np`, and the _original_ numpy as `onp`.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "import jax\n",
    "import jax.numpy as np\n",
    "import numpy as onp\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll start by defining the $\\mathbf{z}$ and $L$ functions, together with a single composite function `fun` which calls L and z. Having a single native python function is necessary for many of the JAX operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting point x = [3. 3.]\n",
      "\n",
      "Some test calls of the functions we defined so far, from top to bottom, z, Lz (manual), Lz:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(DeviceArray([3., 9.], dtype=float32),\n",
       " DeviceArray(90., dtype=float32),\n",
       " DeviceArray(90., dtype=float32))"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# \"physics\" function z\n",
    "def fun_z(x):\n",
    "    return np.array( [x[0], x[1]*x[1]] )\n",
    "\n",
    "# simple L2 loss\n",
    "def fun_L(z):\n",
    "    #return z[0]*z[0] + z[1]*z[1] # \"manual version\"\n",
    "    return np.sum( np.square(z) )\n",
    "\n",
    "# composite function with L & z\n",
    "def fun(x):\n",
    "    return fun_L(fun_z(x))\n",
    "\n",
    "\n",
    "x = np.asarray([3,3], dtype=np.float32)\n",
    "print(\"Starting point x = \"+format(x) +\"\\n\")\n",
    "\n",
    "print(\"Some test calls of the functions we defined so far, from top to bottom, z, Lz (manual), Lz:\") \n",
    "fun_z(x) , fun_L( fun_z(x) ), fun(x) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can evaluate the derivatives of our function via `jax.grad`. E.g., `jax.grad(fun_L)(fun_z(x))` evaluates the Jacobian $\\partial L / \\partial \\mathbf{z}$. The cell below evaluates this and a few variants, together with a sanity check for the inverse of the Jacobian of $\\mathbf{z}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jacobian L(z): [ 6. 18.]\n",
      "\n",
      "Jacobian z(x): \n",
      "[[1. 0.]\n",
      " [0. 6.]]\n",
      "\n",
      "Sanity check with inverse Jacobian of z, this should give x again: [3. 3.]\n",
      "\n",
      "Gradient for full L(x): [  6. 108.]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# this works:\n",
    "print(\"Jacobian L(z): \" + format(jax.grad(fun_L)(fun_z(x))) +\"\\n\")\n",
    "\n",
    "# the following would give an error as z (and hence fun_z) is not scalar\n",
    "#jax.grad(fun_z)(x) \n",
    "\n",
    "# computing the jacobian of z is a valid operation:\n",
    "J = jax.jacobian(fun_z)(x)\n",
    "print( \"Jacobian z(x): \\n\" + format(J) ) \n",
    "\n",
    "# the following also gives error, JAX grad needs a single function object\n",
    "#jax.grad( fun_L(fun_z) )(x) \n",
    "\n",
    "print( \"\\nSanity check with inverse Jacobian of z, this should give x again: \" + format(np.linalg.solve(J, np.matmul(J,x) )) +\"\\n\")\n",
    "\n",
    "# instead use composite 'fun' from above\n",
    "print(\"Gradient for full L(x): \" + format( jax.grad(fun)(x) )  +\"\\n\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line is worth a closer look: here we print the gradient $\\partial L / \\partial \\mathbf{x}$ at our initial position. And while we know that we should just move diagonally towards the origin (with the zero vector being the minimizer), this gradient is not very diagonal - it has a strongly dominant component along $x_1$ with an entry of 108.\n",
    "\n",
    "Let's see how the different methods cope with this situation. We'll compare \n",
    "\n",
    "* the first order method _gradient descent_ (i.e., regular, non-stochastic, \"steepest gradient descent\"), \n",
    "\n",
    "* _Newton's method_ as a representative of the second order methods, \n",
    "\n",
    "* and _physical gradients_.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Gradient descent\n",
    "\n",
    "For gradient descent, the simple gradient based update from equation {eq}`GD-update`\n",
    "in our setting gives the following update step in $\\mathbf{x}$:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "\\Delta \\mathbf{x} \n",
    "&= \n",
    "- \\eta ( J_{L} J_{\\mathbf{z}} )^T  \\\\\n",
    "&=\n",
    "- \\eta ( \\frac{\\partial L }{ \\partial \\mathbf{z} } \\frac{\\partial \\mathbf{z} }{ \\partial \\mathbf{x} }  )^T\n",
    "\\end{aligned}$$\n",
    "\n",
    "where $\\eta$ denotes the step size parameter .\n",
    "\n",
    "Let's start the optimization via gradient descent at $x=[3,3]$, and update our solution ten times with\n",
    "$\\eta = 0.01$:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GD iter 0: [2.94      1.9200001]\n",
      "GD iter 1: [2.8812    1.6368846]\n",
      "GD iter 2: [2.823576  1.4614503]\n",
      "GD iter 3: [2.7671044 1.3365935]\n",
      "GD iter 4: [2.7117622 1.2410815]\n",
      "GD iter 5: [2.657527  1.1646168]\n",
      "GD iter 6: [2.6043763 1.1014326]\n",
      "GD iter 7: [2.5522888 1.0479842]\n",
      "GD iter 8: [2.501243  1.0019454]\n",
      "GD iter 9: [2.4512184  0.96171147]\n"
     ]
    }
   ],
   "source": [
    "x = np.asarray([3.,3.])\n",
    "eta = 0.01\n",
    "historyGD = [x]; updatesGD = []\n",
    "\n",
    "for i in range(10):\n",
    "    G = jax.grad(fun)(x)\n",
    "    x += -eta * G\n",
    "    historyGD.append(x); updatesGD.append(G)\n",
    "    print( \"GD iter %d: \"%i + format(x) )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we've already printed the resulting positions in $\\mathbf{x}$, and they seem to be going down, i.e. moving in the right direction. The last point, $[2.451 \\  0.962]$ still has a fair distance of 2.63 to the origin.\n",
    "\n",
    "Let's take a look at the progression over the course of the iterations (the evolution was stored in the `history` list above). The blue points denote the positions in $\\mathbf{x}$ from the GD iterations, with the target at the origin shown with a thin black cross."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'x1')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 9764 characters]\n",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "axes = plt.figure(figsize=(4, 4), dpi=100).gca()\n",
    "historyGD = onp.asarray(historyGD)\n",
    "updatesGD = onp.asarray(updatesGD) # for later\n",
    "axes.scatter(historyGD[:,0], historyGD[:,1], lw=0.5, color='blue')\n",
    "axes.scatter([0], [0], lw=0.25, color='black', marker='x') # target at 0,0\n",
    "axes.set_xlabel('x0')\n",
    "axes.set_ylabel('x1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No surprise here: the initial step mostly moves downwards along $x_1$ (in top right corner), and the updates afterwards curve towards the origin. But they don't get very far. It's still quite a distance to the solution in the bottom left corner."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Newton\n",
    "\n",
    "For Newton's method, the update step is given by\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\Delta \\mathbf{x} &= \n",
    "- \\eta \\left( \\frac{\\partial^2 L }{ \\partial \\mathbf{x}^2 }  \\right)^{-1}\n",
    "  \\frac{\\partial L }{ \\partial \\mathbf{x} }\n",
    "\\\\\n",
    "&=\n",
    "- \\eta \\ H_L^{-1} \\ ( J_{L} J_{\\mathbf{z}} )^T\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Hence, in addition to the same gradient as for GD, we now need to evaluate and invert the Hessian of $\\frac{\\partial^2 L }{ \\partial \\mathbf{x}^2 }$.\n",
    "\n",
    "This is quite straightforward in JAX: we can call `jax.jacobian` two times, and then use the JAX version of `linalg.inv` to invert the resulting matrix.\n",
    "\n",
    "For the optimization with Newton's method we'll use a larger step size of $\\eta =1/3$. For this example and the following one, we've chosen the step size such that the magnitude of the first update step is roughly the same as the one of GD. In this way, we can compare the trajectories of all three methods relative to each other. Note that this is by no means meant to illustrate or compare the stability of the methods here. Stability and upper limits for $\\eta$  are separate topics. Here we're focusing on convergence properties.\n",
    "\n",
    "In the next cell, we apply the Newton updates ten times starting from the same initial guess:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Newton iter 0: [2.        2.6666667]\n",
      "Newton iter 1: [1.3333333 2.3703704]\n",
      "Newton iter 2: [0.88888884 2.1069958 ]\n",
      "Newton iter 3: [0.59259254 1.8728852 ]\n",
      "Newton iter 4: [0.39506167 1.6647868 ]\n",
      "Newton iter 5: [0.26337445 1.4798105 ]\n",
      "Newton iter 6: [0.17558296 1.315387  ]\n",
      "Newton iter 7: [0.1170553 1.1692328]\n",
      "Newton iter 8: [0.07803687 1.0393181 ]\n",
      "Newton iter 9: [0.05202458 0.92383826]\n"
     ]
    }
   ],
   "source": [
    "x = np.asarray([3.,3.])\n",
    "eta = 1./3.\n",
    "historyNt = [x]; updatesNt = []\n",
    "\n",
    "for i in range(10):\n",
    "    G = jax.grad(fun)(x)\n",
    "    H = jax.jacobian(jax.jacobian(fun))(x)\n",
    "    #H = jax.jacfwd(jax.jacrev(fun_Lz))(x) # alternative\n",
    "    Hinv = np.linalg.inv(H)\n",
    "    \n",
    "    x += -eta * np.matmul( Hinv , G)\n",
    "    historyNt.append(x); updatesNt.append( np.matmul( Hinv , G) )\n",
    "    print( \"Newton iter %d: \"%i + format(x) )\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line already indicates: Newton's method does quite a bit better. The last point $[0.052 \\ 0.924]$ only has a distance of 0.925 to the origin (compared to 2.63 for GD)\n",
    "\n",
    "Below, we plot the Newton trajectory in orange next to the GD version in blue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'x1')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 11340 characters]\n",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "axes = plt.figure(figsize=(4, 4), dpi=100).gca()\n",
    "historyNt = onp.asarray(historyNt)\n",
    "updatesNt = onp.asarray(updatesNt) \n",
    "axes.scatter(historyGD[:,0], historyGD[:,1], lw=0.5, color='blue')\n",
    "axes.scatter(historyNt[:,0], historyNt[:,1], lw=0.5, color='orange')\n",
    "axes.scatter([0], [0], lw=0.25, color='black', marker='x') # target at 0,0\n",
    "axes.set_xlabel('x0')\n",
    "axes.set_ylabel('x1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not completely surprising: for this simple example we can reliably evaluate the Hessian, and Newtons's method profits from the second order information. It's trajectory is much more diagonal (that would be the ideal, shortest path to the solution), and does not slow down as much as GD."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Physical Gradients\n",
    "\n",
    "Now we also use inverse physics, i.e. the inverse of z:\n",
    "$\\mathbf{z}^{-1}(\\mathbf{x}) = [x_0 \\ x_1^{1/2}]^T$, to compute the _physical gradient_. As a slight look-ahead to the next section, we'll use a Newton's step for $L$, and combine it with the inverse physics function to get an overall update. This gives an update step:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "\\Delta \\mathbf{x} &= \n",
    "\\mathbf{z}^{-1} \\left( \\mathbf{z}(\\mathbf{x}) - \\eta\n",
    "  \\left( \\frac{\\partial^2 L }{ \\partial \\mathbf{z}^2 }  \\right)^{-1}\n",
    "  \\frac{\\partial L }{ \\partial \\mathbf{z} }\n",
    "\\right) - \\mathbf{x}\n",
    "\\end{aligned}$$\n",
    "\n",
    "Below, we define our inverse function `fun_z_inv_analytic` (we'll come to a variant below), and then evaluate an optimization with the physical gradient for ten steps:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PG iter 0: [2.1       2.5099802]\n",
      "PG iter 1: [1.4699999 2.1000001]\n",
      "PG iter 2: [1.0289999 1.7569861]\n",
      "PG iter 3: [0.72029996 1.47      ]\n",
      "PG iter 4: [0.50421   1.2298902]\n",
      "PG iter 5: [0.352947 1.029   ]\n",
      "PG iter 6: [0.24706289 0.86092323]\n",
      "PG iter 7: [0.17294402 0.7203    ]\n",
      "PG iter 8: [0.12106082 0.60264623]\n",
      "PG iter 9: [0.08474258 0.50421   ]\n"
     ]
    }
   ],
   "source": [
    "x = np.asarray([3.,3.])\n",
    "eta = 0.3\n",
    "historyPG = [x]; historyPGz = []; updatesPG = []\n",
    "\n",
    "def fun_z_inv_analytic(y):\n",
    "    return np.array( [y[0], np.power(y[1],0.5)] )\n",
    "\n",
    "for i in range(10):\n",
    "    \n",
    "    # Newton step for L(z)\n",
    "    zForw = fun_z(x)\n",
    "    GL = jax.grad(fun_L)(zForw)\n",
    "    HL = jax.jacobian(jax.jacobian(fun_L))(zForw)\n",
    "    HLinv = np.linalg.inv(HL)\n",
    "    \n",
    "    # step in z space\n",
    "    zBack = zForw -eta * np.matmul( HLinv , GL)\n",
    "    historyPGz.append(zBack)\n",
    "\n",
    "    # \"inverse physics\" step via z-inverse\n",
    "    x = fun_z_inv_analytic(zBack)\n",
    "    historyPG.append(x)\n",
    "    updatesPG.append( historyPG[-2] - historyPG[-1] )\n",
    "    print( \"PG iter %d: \"%i + format(x) )\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we obtain $[0.084 \\  0.504]$ as the final position, with a distance of only 0.51! This is clearly better than both Newton and GD.\n",
    "\n",
    "Let's directly visualize how the PGs (in red) fare in comparison to Newton's method (orange) and GD (blue)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'x1')"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 12088 characters]\n",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "historyPG = onp.asarray(historyPG)\n",
    "updatesPG = onp.asarray(updatesPG) \n",
    "\n",
    "axes = plt.figure(figsize=(4, 4), dpi=100).gca()\n",
    "axes.scatter(historyGD[:,0], historyGD[:,1], lw=0.5, color='blue')\n",
    "axes.scatter(historyNt[:,0], historyNt[:,1], lw=0.5, color='orange')\n",
    "axes.scatter(historyPG[:,0], historyPG[:,1], lw=0.5, color='red')\n",
    "axes.scatter([0], [0], lw=0.25, color='black', marker='x') # target at 0,0\n",
    "axes.set_xlabel('x0')\n",
    "axes.set_ylabel('x1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This illustrates that the PG variant does significantly better than Newton's method. It yields a trajectory that is better aligned with the _diagonal_, and its final state is closer to the origin. A key ingredient here is the inverse function for $\\mathbf{z}$, which yielded higher order terms than the second-order approximation for Newton's method. Despite the simplicity of the problem, Newton's method has problems finding the right search direction. For PG, on the other hand, the higher order information yields an improved direction for the optimization.\n",
    "\n",
    "This difference also shows in first update step for each method: below we measure how well it is aligned with the diagonal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Diagonal lengths (larger is better): GD 1.053930, Nt 1.264911, PG 1.356443 \n"
     ]
    }
   ],
   "source": [
    "def mag(x):\n",
    "    return np.sqrt(np.sum(np.square(x)))\n",
    "\n",
    "def one_len(x):\n",
    "    return np.dot( x/mag(x), np.array([1,1])) \n",
    "\n",
    "print(\"Diagonal lengths (larger is better): GD %f, Nt %f, PG %f \" % \n",
    "      (one_len(updatesGD[0]) , one_len(updatesNt[0]) , one_len(updatesPG[0])) )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The largest value of 1.356 for PG confirms what we've seen above: the PG gradient was the closest one to the diagonal direction from our starting point to the origin."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "---\n",
    "\n",
    "<br>\n",
    "\n",
    "## Z Space\n",
    "\n",
    "To understand the behavior and differences of the methods here, it's important to keep in mind that we're not dealing with a black box that maps between $\\mathbf{x}$ and $L$, but rather there are spaces in between that matter. In our case, we only have a single $\\mathbf{z}$ space, but for DL settings, we might have a large number of latent spaces, over which we have a certain amount of control. We will return to NNs soon, but for now let's focus on $\\mathbf{z}$. \n",
    "\n",
    "A first thing to note is that for PG, we explicitly map from $L$ to $\\mathbf{z}$, and then continue with a mapping to $\\mathbf{x}$. Thus we already obtained the trajectory in $\\mathbf{z}$ space, and not coincidentally, we already stored it in the `historyPGz` list above.\n",
    "\n",
    "Let's directly take a look what PG did in $\\mathbf{z}$ space:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'z1')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 10020 characters]\n",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "historyPGz = onp.asarray(historyPGz)\n",
    "\n",
    "axes = plt.figure(figsize=(4, 4), dpi=100).gca()\n",
    "axes.set_title('z space')\n",
    "axes.scatter(historyPGz[:,0], historyPGz[:,1], lw=0.5, color='red', marker='*')\n",
    "axes.scatter([0], [0], lw=0.25, color='black', marker='*') \n",
    "axes.set_xlabel('z0')\n",
    "axes.set_ylabel('z1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For PG we're making explicit steps in $\\mathbf{z}$ space, which progress in a straight diagonal line to the origin  (which is likewise the solution in $\\mathbf{z}$ space).\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Interestingly, neither GD nor Newton's method give us information about progress in intermediate spaces (like the $\\mathbf{z}$ space). \n",
    "\n",
    "For **GD** we're concatenating the Jacobians, so we're moving in directions that locally should decrease the loss. However, the $\\mathbf{z}$ position is influenced by $\\mathbf{x}$, and hence we don't know where we end up in $\\mathbf{z}$ space until we have the definite point there. (For NNs in general we won't know at which latent-space points we end up after a GD update until we've actually computed all updated weights.)\n",
    "\n",
    "More specifically, we have an update $-\\eta \\frac{\\partial L}{\\partial \\mathbf{x}}$ for GD, which means we arrive at $\\mathbf{z}(\\mathbf{x} -\\eta \\frac{\\partial L}{\\partial \\mathbf{x}})$ in $\\mathbf{z}$ space. A Taylor expansion with \n",
    "$h = \\eta \\frac{\\partial L}{\\partial \\mathbf{x}}$ yields \n",
    "\n",
    "$\n",
    "\\quad\n",
    "\\mathbf{z}(\\mathbf{x} - h) = \n",
    "\\mathbf{z}(\\mathbf{x}) - h \\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{x}} + \\mathcal{O}( h^2 )\n",
    "= \\mathbf{z}(x) - \\eta \\frac{\\partial L}{\\partial \\mathbf{z}} (\\frac{\\partial \\mathbf{z}}{\\partial x})^2 + \\mathcal{O}( h^2 )\n",
    "$.\n",
    "\n",
    "And $\\frac{\\partial L}{\\partial \\mathbf{z}} (\\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{x}})^2$ clearly differs from the step $\\frac{\\partial L}{\\partial \\mathbf{z}}$ we would compute during the backpropagation pass in GD for $\\mathbf{z}$.\n",
    "\n",
    "**Newton's method** does not fare much better: we compute first-order derivatives like for GD, and the second-order derivatives for the Hessian for the full process. But since both are approximations, the actual intermediate states resulting from an update step are unknown until the full chain is evaluated. In the _Consistency in function compositions_ paragraph for Newton's method in {doc}`physgrad` the squared $\\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{x}}$ term for the Hessian already indicated this dependency.\n",
    "\n",
    "With **PGs** we do not have this problem: PGs can directly map points in $\\mathbf{z}$ to $\\mathbf{x}$ via the inverse function. Hence we know eactly where we started in $\\mathbf{z}$ space, as this position is crucial for evaluating the inverse.\n",
    "\n",
    "In the simple setting of this section, we only have a single latent space, and we already stored all values in  $\\mathbf{x}$ space during the optimization (in the `history` lists). Hence, now we can go back and re-evaluate `fun_z` to obtain the positions in $\\mathbf{z}$ space."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.asarray([3.,3.])\n",
    "eta = 0.01\n",
    "historyGDz = []\n",
    "historyNtz = []\n",
    "\n",
    "for i in range(1,10):\n",
    "    historyGDz.append(fun_z(historyGD[i]))\n",
    "    historyNtz.append(fun_z(historyNt[i]))\n",
    "\n",
    "historyGDz = onp.asarray(historyGDz)\n",
    "historyNtz = onp.asarray(historyNtz)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'z1')"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 13020 characters]\n",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "axes = plt.figure(figsize=(4, 4), dpi=100).gca()\n",
    "axes.set_title('z space')\n",
    "axes.scatter(historyGDz[:,0], historyGDz[:,1], lw=0.5, marker='*', color='blue')\n",
    "axes.scatter(historyNtz[:,0], historyNtz[:,1], lw=0.5, marker='*', color='orange')\n",
    "axes.scatter(historyPGz[:,0], historyPGz[:,1], lw=0.5, marker='*', color='red')\n",
    "axes.scatter([0], [0], lw=0.25, color='black', marker='*') \n",
    "axes.set_xlabel('z0')\n",
    "axes.set_ylabel('z1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These trajectories confirm the intuition outlined in the previous sections: GD in blue gives a very sub-optimal trajectory in $\\mathbf{z}$. Newton (in orange) does better, but is still clearly curved, in contrast to the straight, and diagonal red trajectory for the PG-based optimization.\n",
    "\n",
    "The behavior in intermediate spaces becomes especially important when they're not only abstract latent spaces as in this example, but when they have actual physical meanings."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusions \n",
    "\n",
    "That concludes our simple example. Despite its simplicity, it already showed surprisingly large differences between gradient descent, Newton's method, and the physical gradients.\n",
    "\n",
    "The main takeaways of this section are:\n",
    "* GD easily yields \"unbalanced\" updates\n",
    "* Newtons method does better, but is far from optimal\n",
    "* PGs outperform both if an inverse function is available\n",
    "* The choice of optimizer strongly affects progress in latent spaces\n",
    "    \n",
    "In the next sections we can build on these observations to use PGs for training NNs via invertible physical models."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "---\n",
    "\n",
    "## Approximate inversions\n",
    "\n",
    "If an analytic inverse like the `fun_z_inv_analytic` above is not readily available, we can actually resort to optimization schemes like Newton's method or BFGS to approximate it numerically. This is a topic that is orthogonal to the comparison of different optimization methods, but it can be easily illustrated based on the PG example above.\n",
    "\n",
    "Below, we'll use the BFGS variant `fmin_l_bfgs_b` from `scipy` to compute the inverse. It's not very complicated, but we'll use numpy and scipy directly here, which makes the code a bit messier than it should be."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BFGS optimization test run, find x such that y=[2,2]:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([2.00000003, 1.41421353])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def fun_z_inv_opt(target_y, x_ini):\n",
    "    # a bit ugly, we switch to pure scipy here inside each iteration for BFGS\n",
    "    import numpy as np\n",
    "    from scipy.optimize import fmin_l_bfgs_b\n",
    "    target_y = onp.array(target_y)\n",
    "    x_ini    = onp.array(x_ini)\n",
    "\n",
    "    def fun_z_opt(x,target_y=[2,2]):\n",
    "        y = onp.array( [x[0], x[1]*x[1]] ) # we cant use fun_z from JAX here\n",
    "        ret = onp.sum( onp.square(y-target_y) )\n",
    "        return ret\n",
    "    \n",
    "    ret = fmin_l_bfgs_b(lambda x: fun_z_opt(x,target_y), x_ini, approx_grad=True )\n",
    "    #print( ret ) # return full BFGS details\n",
    "    return ret[0]\n",
    "\n",
    "print(\"BFGS optimization test run, find x such that y=[2,2]:\")\n",
    "fun_z_inv_opt([2,2], [3,3])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nonetheless, we can now use this numerically inverted $\\mathbf{z}$ function to perform the PG optimization. Apart from calling `fun_z_inv_opt`, the rest of the code is unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PG iter 0: [2.09999967 2.50998022]\n",
      "PG iter 1: [1.46999859 2.10000011]\n",
      "PG iter 2: [1.02899871 1.75698602]\n",
      "PG iter 3: [0.72029824 1.4699998 ]\n",
      "PG iter 4: [0.50420733 1.22988982]\n",
      "PG iter 5: [0.35294448 1.02899957]\n",
      "PG iter 6: [0.24705997 0.86092355]\n",
      "PG iter 7: [0.17294205 0.72030026]\n",
      "PG iter 8: [0.12106103 0.60264817]\n",
      "PG iter 9: [0.08474171 0.50421247]\n"
     ]
    }
   ],
   "source": [
    "x = np.asarray([3.,3.])\n",
    "eta = 0.3\n",
    "history = [x]; updates = []\n",
    "\n",
    "for i in range(10):    \n",
    "    # same as before, Newton step for L(y)\n",
    "    y = fun_z(x)\n",
    "    GL = jax.grad(fun_L)(y)\n",
    "    y += -eta * np.matmul( np.linalg.inv( jax.jacobian(jax.jacobian(fun_L))(y) ) , GL)\n",
    "\n",
    "    # optimize for inverse physics, assuming we dont have access to an inverse for fun_z\n",
    "    x = fun_z_inv_opt(y,x)\n",
    "    history.append(x)\n",
    "    updates.append( history[-2] - history[-1] )\n",
    "    print( \"PG iter %d: \"%i + format(x) )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nice! It works, just like PG. Not much point plotting this, it's basically the PG version, but let's measure the difference. Below, we compute the MAE, which for this simple example turns out to be on the order of our floating point accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MAE difference between analytic PG and approximate inversion: 0.000001\n"
     ]
    }
   ],
   "source": [
    "historyPGa = onp.asarray(history)\n",
    "updatesPGa = onp.asarray(updates) \n",
    "\n",
    "print(\"MAE difference between analytic PG and approximate inversion: %f\" % (np.average(np.abs(historyPGa-historyPG))) )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br>\n",
    "\n",
    "---\n",
    "\n",
    "## Next steps\n",
    "\n",
    "Based on this code example you can try the following modifications:\n",
    "\n",
    "- Instead of the simple L(z(x)) function above, try other, more complicated functions.\n",
    "\n",
    "- Replace the simple \"regular\" gradient descent with another optimizer, e.g., commonly used DL optimizers such as AdaGrad, RmsProp or Adam. Compare the versions above with the new trajectories."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
