{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "inverse-prob-00",
   "metadata": {},
   "source": [
    "# Calibrating two uncertain sensor axes\n",
    "Two instruments observe the same latent calibration settings. Estimate their linear relation when either reading may be in error. Watch the fitted line rotate as you change the stated measurement uncertainties. Noise draws are fixed for repeatable comparisons."
   ]
  },
  {
   "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",
    "sigma_x = .45                       # mV\n",
    "sigma_y = .40                       # K\n",
    "assert .08 <= sigma_x <= 1.5 and .08 <= sigma_y <= 1.5\n",
    "x = np.array([-2.35,-1.02,-1.12,.57,.42,1.36,2.27])\n",
    "y = np.array([-3.53,-2.71,-1.15,.21,1.23,2.54,3.89])\n",
    "P = np.column_stack((x,y))\n",
    "mean = P.mean(axis=0)\n",
    "\n",
    "def orthogonal_fit(points, uncertainties):\n",
    "    center = points.mean(axis=0)\n",
    "    Z = (points-center)/uncertainties\n",
    "    _,singular,vt = np.linalg.svd(Z,full_matrices=False)\n",
    "    normal = vt[-1]\n",
    "    projected = Z - np.outer(Z@normal,normal)\n",
    "    direction = vt[0]*uncertainties\n",
    "    return center,direction,center+projected*uncertainties,singular[-1]**2\n",
    "\n",
    "scales = np.array([sigma_x,sigma_y])\n",
    "center,direction,foot,loss = orthogonal_fit(P,scales)\n",
    "slope = direction[1]/direction[0]\n",
    "intercept = center[1]-slope*center[0]\n",
    "ols = np.polyfit(x,y,1)\n",
    "print(f\"Weighted orthogonal slope {slope:.6f} K/mV, intercept {intercept:.6f} K, loss {loss:.6f}\")\n",
    "print(f\"Vertical least-squares slope {ols[0]:.6f} K/mV\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "inverse-prob-02",
   "metadata": {},
   "source": [
    "## Eliminate a different nuisance coordinate for every reading\n",
    "For a trial slope through the centroid, minimising the squared correction over the unknown true horizontal coordinate leaves a single scalar loss. Plot this independent function and compare its minimum with the singular-vector fit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "inverse-prob-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "def profile(b):\n",
    "    return np.sum(((y-mean[1])-b*(x-mean[0]))**2)/(sigma_y**2+b*b*sigma_x**2)\n",
    "assert np.isclose(loss,profile(slope),rtol=2e-12)\n",
    "assert np.isclose(loss,np.sum(((P-foot)/scales)**2),rtol=2e-12)\n",
    "fig, (data, cost) = plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "data.scatter(x,y,color=\"#145c71\",label=\"readings\",zorder=4)\n",
    "for i,(observation,adjusted) in enumerate(zip(P,foot)):\n",
    "    data.plot([observation[0],adjusted[0]],[observation[1],adjusted[1]],color=\"#9e4429\",lw=2,label=\"adjustments\" if i==0 else None)\n",
    "xx = np.linspace(-2.6,2.55)\n",
    "data.plot(xx,intercept+slope*xx,color=\"#145c71\",label=\"two uncertain axes\")\n",
    "data.plot(xx,np.polyval(ols,xx),color=\"#88522f\",ls=\"--\",label=\"vertical fit\")\n",
    "data.set(xlabel=\"First instrument (mV)\",ylabel=\"Second instrument (K)\",title=\"Where corrections are assigned\")\n",
    "data.legend(fontsize=8)\n",
    "bb = np.linspace(.75,2.75,351)\n",
    "cost.plot(bb,[profile(b) for b in bb],color=\"#145c71\")\n",
    "cost.scatter([slope],[loss],color=\"#b94626\",label=\"whitened SVD solution\")\n",
    "cost.set(xlabel=\"Trial sensitivity (K/mV)\",ylabel=\"Sum of squared scaled distances\",title=\"Profile out the unseen settings\")\n",
    "cost.legend(fontsize=8)\n",
    "for ax in (data,cost): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "inverse-prob-04",
   "metadata": {},
   "source": [
    "## Change units and cross-check the eigensystem\n",
    "Convert the first instrument to volts and scale its uncertainty too. Transforming the fitted slope back must recover the original. In an installed OneSimulation environment its symmetric eigensystem supplies an independently constructed normal vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "inverse-prob-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "factor = np.array([.001,1.])\n",
    "_,converted,_,converted_loss = orthogonal_fit(P*factor,scales*factor)\n",
    "assert np.isclose((converted[1]/converted[0])*factor[0],slope)\n",
    "assert np.isclose(converted_loss,loss)\n",
    "Z = (P-mean)/scales\n",
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigensystem as eigensystem\n",
    "except ImportError:\n",
    "    eigensystem = np.linalg.eigh\n",
    "ev,_ = eigensystem(Z.T@Z)\n",
    "assert np.isclose(ev[0],loss)\n",
    "print(\"Unit conversion and centred-scatter checks passed.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
