{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-00",
   "metadata": {},
   "source": [
    "# A covariance square root by matrix Newton iteration\n",
    "A target covariance is fixed in the laboratory axes. Start with a positive matrix whose axes are tilted, use the full matrix derivative, and compare the result with a spectral reference. NumPy and Matplotlib suffice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "anisotropy = 9.0              # larger eigenvalue of target, smaller one is 1\n",
    "initial_angle = 35.0         # tilt of the starting estimate in degrees\n",
    "assert 1 <= anisotropy <= 100 and 0 <= initial_angle <= 90\n",
    "A = np.diag([float(anisotropy), 1.0])\n",
    "a = np.deg2rad(initial_angle)\n",
    "rotation = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])\n",
    "X0 = rotation @ np.diag([2., 1.]) @ rotation.T\n",
    "target_root = np.diag([np.sqrt(anisotropy), 1.0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-02",
   "metadata": {},
   "source": [
    "## Solve the Sylvester equation in the current eigenbasis\n",
    "The derivative of the square at X maps H to XH+HX. In the eigenbasis of a positive X each entry of that sum is an entry of H times a sum of two positive eigenvalues."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "def correction(X, residual):\n",
    "    d, Q = np.linalg.eigh(X)\n",
    "    if np.min(d) <= 0:\n",
    "        raise ValueError(\"The chosen positive branch has been left.\")\n",
    "    transformed = Q.T @ residual @ Q\n",
    "    return Q @ (transformed / (d[:,None] + d[None,:])) @ Q.T\n",
    "\n",
    "history = [X0.copy()]\n",
    "for _ in range(30):\n",
    "    X = history[-1]\n",
    "    R = A-X@X\n",
    "    if np.linalg.norm(R) <= 3e-14*np.linalg.norm(A):\n",
    "        break\n",
    "    H = correction(X, R)\n",
    "    history.append(X+H)\n",
    "    assert np.allclose(H@X + X@H, R, atol=2e-12)\n",
    "assert np.allclose(history[-1], target_root, atol=2e-10)\n",
    "wrong = 0.5*np.linalg.solve(X0, A-X0@X0)\n",
    "print(\"Initial residual of scalar-style derivative solve:\", np.linalg.norm(X0@wrong+wrong@X0-(A-X0@X0)))\n",
    "print(\"Positive square root:\")\n",
    "print(history[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-04",
   "metadata": {},
   "source": [
    "## View the iteration as a change of ellipse\n",
    "A unit circle transformed by the root gives a one-standard-deviation covariance contour (its probability content depends on dimension). The right-hand graph charts the relative residual. Finite precision sets the visible floor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (ellipse, graph) = plt.subplots(1, 2, figsize=(10, 4.0), layout=\"constrained\")\n",
    "theta = np.linspace(0, 2*np.pi, 241)\n",
    "circle = np.array([np.cos(theta), np.sin(theta)])\n",
    "for X, name, color, style in [(history[0], \"initial\", \"#8b6816\",\"--\"), (history[min(1,len(history)-1)], \"first iteration\", \"#b94626\",\":\"), (target_root, \"required\", \"#145c71\",\"-\")]:\n",
    "    coords = X@circle\n",
    "    ellipse.plot(coords[0], coords[1], style, color=color, label=name)\n",
    "ellipse.set(aspect=\"equal\", title=\"Action on a unit circle\", xlabel=\"First coordinate\", ylabel=\"Second coordinate\")\n",
    "ellipse.legend(fontsize=9)\n",
    "errors = [np.linalg.norm(A-X@X)/np.linalg.norm(A) for X in history]\n",
    "graph.semilogy(range(len(errors)), np.maximum(errors, 2e-16), \"o-\", color=\"#145c71\")\n",
    "graph.set(title=\"Residual of the matrix equation\", xlabel=\"Accepted iteration\", ylabel=\"Relative Frobenius residual\")\n",
    "for ax in (ellipse, graph): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nonlinear-eq-06",
   "metadata": {},
   "source": [
    "## Verify the derivative by vectorising it\n",
    "Column stacking converts the Sylvester equation into a four-by-four linear system. Compare the two constructions. In a local OneSimulation environment the explicit system uses its dense linear solver; elsewhere NumPy solves it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nonlinear-eq-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import solve_dense as solve\n",
    "except ImportError:\n",
    "    solve = np.linalg.solve\n",
    "R = A-X0@X0\n",
    "K = np.kron(np.eye(2), X0) + np.kron(X0.T, np.eye(2))\n",
    "H = solve(K, R.ravel(order=\"F\")).reshape((2,2), order=\"F\")\n",
    "assert np.allclose(H, correction(X0, R))\n",
    "print(\"Independent Sylvester check:\", np.linalg.norm(K@H.ravel(order=\"F\")-R.ravel(order=\"F\")))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
