{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "inverse-prob-00",
   "metadata": {},
   "source": [
    "# Testing an adjoint for sensors between grid points\n",
    "Build a forward instrument response from smoothing and interpolation. Derive its transpose by reversing the operations and by scattering a residual to both neighbouring grid nodes. The notebook catches a plausible wrong adjoint using inner products and a Taylor test."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "inverse-prob-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "cells=12\n",
    "fraction=.35                     # position between two grid nodes\n",
    "assert 6 <= cells <= 100 and .05 <= fraction <= .95\n",
    "rng=np.random.default_rng(4)\n",
    "I=np.eye(cells)\n",
    "S=.6*I+.25*np.roll(I,1,axis=1)+.15*np.roll(I,-1,axis=1)\n",
    "left=np.arange(0,cells,2)\n",
    "B=np.zeros((len(left),cells))\n",
    "B[np.arange(len(left)),left]=1-fraction\n",
    "B[np.arange(len(left)),(left+1)%cells]=fraction\n",
    "A=B@S\n",
    "m=rng.normal(size=cells);direction=rng.normal(size=cells)\n",
    "y=rng.normal(size=len(left));obs=rng.normal(size=len(left))\n",
    "def forward(v):return B@(S@v)\n",
    "def adjoint(w):return S.T@(B.T@w)\n",
    "def wrong(w):return S@(B.T@w)   # the smoothing stencil is not symmetric\n",
    "gap=abs(forward(direction)@y-direction@adjoint(y))\n",
    "assert gap < 1e-12\n",
    "print(\"Dot-product error with exact transpose:\",gap)\n",
    "print(\"Dot-product error with unreversed smoothing:\", abs(forward(direction)@y-direction@wrong(y)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "inverse-prob-02",
   "metadata": {},
   "source": [
    "## Use an impulse and a Taylor-remainder test\n",
    "A single sensor residual shows which parameter nodes it influences. The cost is half the squared measurement error. Subtract the predicted directional derivative and examine the remainder as the step is halved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "inverse-prob-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,(footprint,rate)=plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "sensor=np.zeros(len(left));sensor[len(left)//2]=1\n",
    "n=np.arange(cells)\n",
    "footprint.plot(n,adjoint(sensor),\"o-\",color=\"#145c71\",label=\"adjoint\")\n",
    "footprint.plot(n,wrong(sensor),\"s--\",ms=4,color=\"#b94626\",label=\"unreversed stencil\")\n",
    "footprint.set(xlabel=\"Parameter node\",ylabel=\"Sensitivity\",title=\"Unit residual at one sensor\")\n",
    "footprint.legend()\n",
    "def cost(v):return np.linalg.norm(forward(v)-obs)**2/2\n",
    "residual=forward(m)-obs\n",
    "d1=direction@adjoint(residual); d2=direction@wrong(residual)\n",
    "hh=2.**(-np.arange(2,17))\n",
    "for d,c,label in [(d1,\"#145c71\",\"exact transpose\"),(d2,\"#b94626\",\"wrong transpose\")]:\n",
    "    rate.loglog(hh,[abs(cost(m+h*direction)-cost(m)-h*d) for h in hh],\"o-\",ms=3,color=c,label=label)\n",
    "rate.set(xlabel=\"Perturbation size h\",ylabel=\"Absolute Taylor remainder\",title=\"Second order or first order?\")\n",
    "rate.legend()\n",
    "for ax in (footprint,rate):ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "inverse-prob-04",
   "metadata": {},
   "source": [
    "## Check the coefficient as well as the slope\n",
    "For a linear measurement the exact remainder is half the squared length of the change in the predicted measurements. This supplies a stronger independent test than inspecting a graph by eye."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "inverse-prob-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "h=.02\n",
    "remainder=cost(m+h*direction)-cost(m)-h*d1\n",
    "assert np.isclose(remainder,.5*h*h*(forward(direction)@forward(direction)),atol=1e-12)\n",
    "print(\"Remainder at h = 0.02:\",remainder)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
