{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "spectraldecomp.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# spectral decomposition \u2014 Python demo\n\nNumerical companion to the entry [spectral decomposition](https://dictionaryofml.org/terms/spectraldecomp.html) of the [Dictionary of Applied Machine Learning](https://dictionaryofml.org/): it recomputes what the entry states and prints one line per check.\n\nNumerical companion to the glossary entry 'spectraldecomp'. The demo recomputes every claim the entry makes about the 2-by-2 matrix of its opening display,\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/spectraldecomp.py`](https://dictionaryofml.org/terms/spectraldecomp.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 spectraldecomp.py` (B102,B307,B602,B605 are the exec, eval and shell checks of [bandit](https://bandit.readthedocs.io/)) reports nothing: the script runs no shell command and evaluates no generated code."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# Notebook shim: the script resolves output paths relative to __file__,\n# which a notebook kernel does not define; everything lands in the\n# working directory instead.\nimport os\n__file__ = os.path.join(os.getcwd(), \"spectraldecomp.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"The spectral decomposition of a symmetric matrix: perpendicular\ndirections, each scaled by its own real factor.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'spectraldecomp'.  The demo\nrecomputes every claim the entry makes about the 2-by-2 matrix of its\nopening display,\n\n    A = [[5/2, sqrt(3)/2], [sqrt(3)/2, 3/2]] ,\n\nwhose eigenvalues are 3 and 1 and whose eigenvectors sit at 30 and 120\ndegrees: A maps the unit circle onto an ellipse with its axes along those\ntwo directions and half-lengths 3 and 1.  It then verifies the structural\nclaims of the entry -- that each outer product u u^T is an orthogonal\nprojection onto a line, that the two projections annihilate each other and\nsum to the identity, and that trace, determinant, spectral norm and rank\nare the sum, the product, the largest, and the count of the nonzero\neigenvalues -- and the positive semi-definite square root.  The matrix\n[[0, 1], [0, 0]] shows where a non-symmetric matrix fails: it has one\neigenvector up to scale, and the orthogonal complement of that eigenvector\nis not invariant, so no basis of eigenvectors exists.  Finally the\ndecomposition is applied to the sample covariance matrix of a year of\nweather at Krems an der Donau, the symmetric positive semi-definite matrix\nthat principal component analysis decomposes.\n\nSelf-contained (numpy and matplotlib only), fixed seed; the GeoSphere\ndownload falls back to the committed CSV.\n\nBlocks\n------\n[B-ellipse]     The matrix A of the entry's opening display: its two\n                eigenvalues 3 and 1, its two eigenvectors at 30 and 120\n                degrees, and the image of the unit circle, an ellipse with\n                half-axes 3 and 1 along those directions.\n[B-projections] Each u u^T is an orthogonal projection onto a line\n                (symmetric and idempotent), the two annihilate each other,\n                they sum to the identity, and the scaled sum of the two\n                reproduces A, which is the decomposition itself.\n[B-quantities]  Trace, determinant, spectral norm and rank read off the\n                eigenvalues, and the positive semi-definite square root\n                squares back to A.\n[B-general]     The non-symmetric [[0, 1], [0, 0]] has a single eigenvector\n                up to scale and an orthogonal complement that is not\n                invariant, so it admits no basis of eigenvectors.\n[B-krems]       The sample covariance matrix of the 365 days of 2024 at\n                Krems that carry a reading at 06:00 and at 15:00 (UTC): a\n                symmetric positive semi-definite matrix, its eigenvalues\n                146.5 and 6.9 squared degrees, and the perpendicular\n                directions its decomposition supplies.  Writes the CSV\n                files of the entry's figure.\n\nOutputs\n-------\nspectraldecomp_circle.csv  : the unit circle, 181 points.\nspectraldecomp_ellipse.csv : its image under A, the same 181 points.\nspectraldecomp_axes.csv    : the two eigenvector directions of A, scaled by\n                             their eigenvalues, as segments from the origin.\nspectraldecomp_weather.csv : date, 06:00 and 15:00 (UTC) temperature of each\n                             day of 2024 (committed copy).\nspectraldecomp_krems_plot.csv : every 19th of those days, the 20 drawn in\n                             the entry's figure.\nspectraldecomp_krems_axes.csv : the two principal directions at Krems,\n                             scaled by the square root of their eigenvalues.\nspectraldecomp.png         : matplotlib preview (checking only).\n\nData generated by pythondemos/spectraldecomp.py.\n\"\"\"\n\n# /// script\n# requires-python = \">=3.10\"\n# dependencies = [\"matplotlib==3.10.7\", \"numpy==2.3.4\"]\n# ///\n\nimport json\nimport urllib.request\nfrom pathlib import Path\n\nimport numpy as np\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nOUT_DIR = Path(__file__).parent\n\nrng = np.random.default_rng(42)\nreport = []\n\n\ndef check(name, ok):\n    report.append((name, bool(ok)))\n    print(f\"  [{'ok' if ok else 'FAIL'}] {name}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-ellipse]** The matrix A of the entry's opening display: its two eigenvalues 3 and 1, its two eigenvectors at 30 and 120 degrees, and the image of the unit circle, an ellipse with half-axes 3 and 1 along those directions."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-ellipse] the matrix A of the opening display, and the ellipse\")\nA = np.array([[5 / 2, np.sqrt(3) / 2], [np.sqrt(3) / 2, 3 / 2]])\ncheck(\"[B-ellipse] A is symmetric\", bool(np.allclose(A, A.T)))\n\nlam, U = np.linalg.eigh(A)\norder = np.argsort(lam)[::-1]                 # largest eigenvalue first\nlam, U = lam[order], U[:, order]\nfor j in (0, 1):                              # the sign of an eigenvector is\n    if U[1, j] < 0:                           # arbitrary; orient both upward\n        U[:, j] = -U[:, j]                    # so the angles read 30 and 120\n                                              # degrees, as the entry's figure\n                                              # draws them\ncheck(f\"[B-ellipse] the eigenvalues are {lam[0]:.0f} and {lam[1]:.0f}\",\n      bool(np.allclose(lam, [3.0, 1.0])))\n\nangles = np.degrees(np.arctan2(U[1], U[0]))\ncheck(f\"[B-ellipse] the eigenvectors sit at {angles[0]:.0f} and \"\n      f\"{angles[1]:.0f} degrees\",\n      bool(np.allclose(np.sort(angles), [30.0, 120.0])))\ncheck(\"[B-ellipse] the eigenvectors are orthonormal, so U is an orthogonal \"\n      \"matrix\", bool(np.allclose(U.T @ U, np.eye(2))))\ncheck(\"[B-ellipse] A stretches the first eigenvector by 3 and leaves the \"\n      \"second where it is\",\n      bool(np.allclose(A @ U[:, 0], 3 * U[:, 0]))\n      and bool(np.allclose(A @ U[:, 1], U[:, 1])))\n\ntheta = np.linspace(0, 2 * np.pi, 181)\ncircle = np.column_stack([np.cos(theta), np.sin(theta)])\nellipse = circle @ A.T\nradii = np.linalg.norm(ellipse, axis=1)\ncheck(f\"[B-ellipse] the image of the unit circle reaches out to \"\n      f\"{radii.max():.0f} and in to {radii.min():.0f}, the two eigenvalues\",\n      bool(np.isclose(radii.max(), 3.0)) and bool(np.isclose(radii.min(), 1.0)))\nfar = ellipse[np.argmax(radii)]\ncheck(\"[B-ellipse] the long half-axis of the ellipse points along the first \"\n      \"eigenvector\",\n      bool(np.isclose(abs(far @ U[:, 0]) / np.linalg.norm(far), 1.0)))\n\nnp.savetxt(OUT_DIR / \"spectraldecomp_circle.csv\", circle, delimiter=\",\",\n           header=\"x1,x2\", comments=\"\", fmt=\"%.4f\")\nnp.savetxt(OUT_DIR / \"spectraldecomp_ellipse.csv\", ellipse, delimiter=\",\",\n           header=\"x1,x2\", comments=\"\", fmt=\"%.4f\")\naxes = np.array([[0.0, 0.0], lam[0] * U[:, 0], [np.nan, np.nan],\n                 [0.0, 0.0], lam[1] * U[:, 1]])\nnp.savetxt(OUT_DIR / \"spectraldecomp_axes.csv\", axes, delimiter=\",\",\n           header=\"x1,x2\", comments=\"\", fmt=\"%.4f\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-projections]** Each u u^T is an orthogonal projection onto a line (symmetric and idempotent), the two annihilate each other, they sum to the identity, and the scaled sum of the two reproduces A, which is the decomposition itself."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-projections] each outer product is an orthogonal projection\")\nP = [np.outer(U[:, j], U[:, j]) for j in (0, 1)]\ncheck(\"[B-projections] each u u^T is symmetric and idempotent, so it is the \"\n      \"orthogonal projection onto the line through u\",\n      all(np.allclose(p, p.T) and np.allclose(p @ p, p) for p in P))\ncheck(\"[B-projections] the two projections annihilate each other\",\n      bool(np.allclose(P[0] @ P[1], np.zeros((2, 2)))))\ncheck(\"[B-projections] the two projections sum to the identity\",\n      bool(np.allclose(P[0] + P[1], np.eye(2))))\nrecon = lam[0] * P[0] + lam[1] * P[1]\ncheck(\"[B-projections] the eigenvalue-scaled sum of the projections \"\n      \"reproduces A, which is the spectral decomposition\",\n      bool(np.allclose(recon, A)))\ncheck(\"[B-projections] the same decomposition written with matrices, \"\n      \"U diag(lambda) U^T, agrees\",\n      bool(np.allclose(U @ np.diag(lam) @ U.T, A)))\n\nprobe = rng.normal(size=(500, 2))\nquad = np.einsum(\"ij,jk,ik->i\", probe, A, probe)\nexpand = (lam[0] * (probe @ U[:, 0]) ** 2 + lam[1] * (probe @ U[:, 1]) ** 2)\ncheck(\"[B-projections] at 500 points drawn at random the quadratic form \"\n      \"equals the eigenvalue-weighted sum of the squared components in the \"\n      \"eigenvector basis\", bool(np.allclose(quad, expand)))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-quantities]** Trace, determinant, spectral norm and rank read off the eigenvalues, and the positive semi-definite square root squares back to A."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-quantities] trace, determinant, spectral norm, rank, square root\")\ncheck(f\"[B-quantities] the trace {np.trace(A):.0f} is the sum of the \"\n      \"eigenvalues\", bool(np.isclose(np.trace(A), lam.sum())))\ncheck(f\"[B-quantities] the determinant {np.linalg.det(A):.0f} is their \"\n      \"product\", bool(np.isclose(np.linalg.det(A), lam.prod())))\ncheck(f\"[B-quantities] the spectral norm {np.linalg.norm(A, 2):.0f} is the \"\n      \"largest eigenvalue\", bool(np.isclose(np.linalg.norm(A, 2), lam[0])))\ncheck(\"[B-quantities] the rank counts the nonzero eigenvalues\",\n      int(np.linalg.matrix_rank(A)) == int((np.abs(lam) > 1e-12).sum()))\ncheck(\"[B-quantities] A is positive semi-definite: no eigenvalue is \"\n      \"negative\", bool(lam.min() >= 0))\nroot = sum(np.sqrt(lam[j]) * P[j] for j in (0, 1))\ncheck(\"[B-quantities] the positive semi-definite square root squares back \"\n      \"to A\", bool(np.allclose(root @ root, A)))\ncheck(\"[B-quantities] that square root is itself symmetric positive \"\n      \"semi-definite\",\n      bool(np.allclose(root, root.T))\n      and bool(np.linalg.eigvalsh(root).min() >= -1e-12))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-general]** The non-symmetric [[0, 1], [0, 0]] has a single eigenvector up to scale and an orthogonal complement that is not invariant, so it admits no basis of eigenvectors."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-general] the non-symmetric [[0, 1], [0, 0]]\")\nN = np.array([[0.0, 1.0], [0.0, 0.0]])\ncheck(\"[B-general] N is not symmetric\", not np.allclose(N, N.T))\nnval, nvec = np.linalg.eig(N)\ncheck(\"[B-general] both eigenvalues of N are zero\",\n      bool(np.allclose(nval, 0.0)))\ndirections = {tuple(np.round(np.abs(nvec[:, j]), 9)) for j in (0, 1)}\ncheck(\"[B-general] N has a single eigenvector up to scale, so its \"\n      \"eigenvectors cannot form a basis of the plane\", len(directions) == 1)\ncheck(\"[B-general] the rank of N is 1 while the plane has dimension 2\",\n      int(np.linalg.matrix_rank(N)) == 1)\ne1, e2 = np.array([1.0, 0.0]), np.array([0.0, 1.0])\ncheck(\"[B-general] e1 spans an invariant line, yet N maps e2, which is \"\n      \"orthogonal to e1, back onto e1: the orthogonal complement is not \"\n      \"invariant\",\n      bool(np.allclose(N @ e1, 0.0)) and bool(np.allclose(N @ e2, e1)))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-krems]** The sample covariance matrix of the 365 days of 2024 at Krems that carry a reading at 06:00 and at 15:00 (UTC): a symmetric positive semi-definite matrix, its eigenvalues 146.5 and 6.9 squared degrees, and the perpendicular directions its decomposition supplies. Writes the CSV files of the entry's figure."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-krems] the 06:00 and the 15:00 (UTC) temperature at Krems, 2024\")\nURL = (\"https://dataset.api.hub.geosphere.at/v1/station/historical/\"\n       \"klima-v2-1h?parameters=tl&station_ids=3805\"\n       \"&start=2024-01-01T00:00&end=2024-12-31T23:00\")\nCSV = OUT_DIR / \"spectraldecomp_weather.csv\"\ntry:\n    with urllib.request.urlopen(URL, timeout=120) as resp:\n        payload = json.load(resp)\n    series = payload[\"features\"][0][\"properties\"][\"parameters\"][\"tl\"][\"data\"]\n    byday = {}\n    for stamp, value in zip(payload[\"timestamps\"], series):\n        if value is None:                  # the archive drops whole days\n            continue\n        hour = stamp[11:16]                # the stamps are UTC, and so are\n        if hour in (\"06:00\", \"15:00\"):     # the two times\n            byday.setdefault(stamp[:10], {})[hour] = float(value)\n    kept = [(d, r[\"06:00\"], r[\"15:00\"])\n            for d, r in sorted(byday.items()) if len(r) == 2]\n    stamps = [d for d, _, _ in kept]\n    X = np.array([[a, b] for _, a, b in kept])\n    with open(CSV, \"w\") as fh:\n        fh.write(\"date,t06,t15\\n\")\n        for day, row in zip(stamps, X):\n            fh.write(day + \",\" + \",\".join(f\"{v:g}\" for v in row) + \"\\n\")\n    print(f\"    downloaded {len(X)} days with both readings\")\nexcept (OSError, KeyError, ValueError) as err:\n    print(f\"    download failed ({err}); reading {CSV.name}\")\n    rows = np.genfromtxt(CSV, delimiter=\",\", skip_header=1, dtype=str)\n    stamps = [str(s) for s in rows[:, 0]]\n    X = rows[:, 1:].astype(float)\n\ncheck(\"[B-krems] 365 of the days of 2024 carry both readings (the hourly \"\n      \"record drops 2024-01-12)\", X.shape == (365, 2))\ncheck(\"[B-krems] the record matches the archive (1 January: 4.0 at 06:00 \"\n      \"and 8.0 at 15:00, both UTC)\",\n      stamps[0] == \"2024-01-01\" and bool(np.allclose(X[0], [4.0, 8.0])))\n\nmu = X.mean(axis=0)\nC = (X - mu).T @ (X - mu) / len(X)\ncheck(\"[B-krems] the sample covariance matrix is symmetric\",\n      bool(np.allclose(C, C.T)))\nklam, KU = np.linalg.eigh(C)\nkorder = np.argsort(klam)[::-1]\nklam, KU = klam[korder], KU[:, korder]\nfor j in (0, 1):\n    if KU[0, j] < 0:\n        KU[:, j] = -KU[:, j]\ncheck(f\"[B-krems] the eigenvalues are {klam[0]:.1f} and {klam[1]:.1f} \"\n      \"squared degrees\", bool(np.allclose(np.round(klam, 1), [146.5, 6.9])))\ncheck(\"[B-krems] both are nonnegative, so the sample covariance matrix is \"\n      \"positive semi-definite\", bool(klam.min() >= 0))\ncheck(f\"[B-krems] the leading eigenvector is \"\n      f\"({KU[0, 0]:.2f}, {KU[1, 0]:.2f}), the direction in which the two \"\n      \"readings rise together\",\n      bool(np.allclose(np.round(KU[:, 0], 2), [0.65, 0.76])))\ncheck(\"[B-krems] the decomposition reproduces the sample covariance matrix\",\n      bool(np.allclose(KU @ np.diag(klam) @ KU.T, C)))\ncheck(f\"[B-krems] the two eigenvalues sum to the trace {np.trace(C):.1f}, \"\n      \"the total variance of the two readings\",\n      bool(np.isclose(klam.sum(), np.trace(C))))\n\nproj = (X - mu) @ KU\ncheck(\"[B-krems] in the eigenvector basis the two coordinates are \"\n      \"uncorrelated, which is what the perpendicular directions buy\",\n      abs(np.corrcoef(proj.T)[0, 1]) < 1e-12)\n\nX_plot = X[::19]                               # 20 of the 365 days, so the\ncheck(f\"[B-krems] every 19th day: {len(X_plot)} of the {len(X)} days are \"\n      \"drawn in the entry's figure\", len(X_plot) == 20)\nnp.savetxt(OUT_DIR / \"spectraldecomp_krems_plot.csv\", X_plot, delimiter=\",\",\n           header=\"t06,t15\", comments=\"\", fmt=\"%.1f\")\nkaxes = np.array([mu - np.sqrt(klam[0]) * KU[:, 0],\n                  mu + np.sqrt(klam[0]) * KU[:, 0], [np.nan, np.nan],\n                  mu - np.sqrt(klam[1]) * KU[:, 1],\n                  mu + np.sqrt(klam[1]) * KU[:, 1]])\nnp.savetxt(OUT_DIR / \"spectraldecomp_krems_axes.csv\", kaxes, delimiter=\",\",\n           header=\"t06,t15\", comments=\"\", fmt=\"%.2f\")\n\n# ---- the preview figure\nfig, ax = plt.subplots(1, 2, figsize=(9.4, 4.0))\n\nax[0].plot(circle[:, 0], circle[:, 1], linestyle=\"--\", color=\"black\",\n           label=\"unit circle (dashed curve)\")\nax[0].plot(ellipse[:, 0], ellipse[:, 1], linestyle=\"-\", color=\"black\",\n           linewidth=1.6, label=\"its image under A (solid curve)\")\nfor j, style in ((0, \"-\"), (1, \":\")):\n    ax[0].annotate(\"\", xy=tuple(lam[j] * U[:, j]), xytext=(0, 0),\n                   arrowprops=dict(arrowstyle=\"-|>\", color=\"black\",\n                                   linestyle=style, linewidth=1.2))\nax[0].text(*(lam[0] * U[:, 0] * 1.03), r\"$\\lambda_1 u^{(1)}$\", fontsize=9)\nax[0].text(*(lam[1] * U[:, 1] * 1.12), r\"$\\lambda_2 u^{(2)}$\", fontsize=9,\n           ha=\"right\", va=\"bottom\")\nax[0].set_xlabel(\"first coordinate\")\nax[0].set_ylabel(\"second coordinate\")\nax[0].set_title(\"(a) A scales two perpendicular directions by 3 and 1\",\n                fontsize=9)\nax[0].set_aspect(\"equal\")\nax[0].legend(frameon=False, fontsize=8, loc=\"lower right\")\n\nax[1].plot(X_plot[:, 0], X_plot[:, 1], \"o\", color=\"black\", ms=4.5,\n           label=\"20 of the 365 days (filled circles)\")\nax[1].plot(kaxes[0:2, 0], kaxes[0:2, 1], linestyle=\"-\", color=\"black\",\n           linewidth=1.6, label=\"first principal direction (solid line)\")\nax[1].plot(kaxes[3:5, 0], kaxes[3:5, 1], linestyle=\":\", color=\"black\",\n           linewidth=1.6, label=\"second principal direction (dotted line)\")\nax[1].set_xlabel(\"06:00 (UTC) reading (\u00b0C)\")\nax[1].set_ylabel(\"15:00 (UTC) reading (\u00b0C)\")\nax[1].set_title(\"(b) the same decomposition at Krems, 2024\", fontsize=9)\nax[1].set_aspect(\"equal\")\nax[1].legend(frameon=False, fontsize=8, loc=\"upper left\")\n\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"spectraldecomp.png\", dpi=150)\n\nprint(f\"\\n{sum(ok for _, ok in report)}/{len(report)} checks passed\")"
  }
 ]
}