{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "spectrum.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# spectrum \u2014 Python demo\n\nNumerical companion to the entry [spectrum](https://dictionaryofml.org/terms/spectrum.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 'spectrum'. The entry defines the spectrum of a linear operator T as the set of values lambda for which T - lambda I fails to be invertible, and then extends the notion to any object that carries an associated linear operator -- a square matrix, and a stochastic process through its covariance function. The demo takes that definition literally rather than through a library routine: it sweeps lambda along the line, measures how far A - lambda I is from failing to be invertible, and confirms that the values at which it does fail are exactly the ones a solver reports. Off the spectrum the operator is invertible and the equation (A - lambda I) v = b has one solution; on the spectrum it is not, and the failure is visible as a direction that A - lambda I sends to zero.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/spectrum.py`](https://dictionaryofml.org/terms/spectrum.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 spectrum.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(), \"spectrum.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"The spectrum: the values at which an operator fails to be invertible.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'spectrum'.  The entry defines\nthe spectrum of a linear operator T as the set of values lambda for which\nT - lambda I fails to be invertible, and then extends the notion to any\nobject that carries an associated linear operator -- a square matrix, and\na stochastic process through its covariance function.  The demo takes that\ndefinition literally rather than through a library routine: it sweeps\nlambda along the line, measures how far A - lambda I is from failing to be\ninvertible, and confirms that the values at which it does fail are exactly\nthe ones a solver reports.  Off the spectrum the operator is invertible and\nthe equation (A - lambda I) v = b has one solution; on the spectrum it is\nnot, and the failure is visible as a direction that A - lambda I sends to\nzero.\n\nThe last two blocks are the entry's two extensions.  A rotation of the\nplane shows that the spectrum depends on the field the operator acts over:\nover the real numbers it is empty, over the complex numbers it is not.  A\nyear of air temperature at Krems an der Donau supplies the stochastic\nprocess, whose covariance function builds a linear operator whose spectrum\nis a set of nonnegative numbers.\n\nSelf-contained (numpy and matplotlib only), fixed seed; the GeoSphere\ndownload falls back to the committed CSV.\n\nBlocks\n------\n[B-definition] A 3-by-3 matrix: det(A - lambda I) over a sweep of lambda\n               vanishes at exactly three values, and those are the ones a\n               solver returns.  The definition is applied as written.\n[B-invertible] Off the spectrum, A - lambda I is invertible and\n               (A - lambda I) v = b has exactly one solution.  On the\n               spectrum it is not invertible: it sends a nonzero direction\n               to zero, so a solution either fails to exist or is not\n               unique.  The size of the inverse grows without bound as\n               lambda approaches a value of the spectrum.\n[B-field]      A rotation of the plane by 90 degrees has an empty spectrum\n               over the real numbers and a two-element spectrum over the\n               complex numbers, so the field is part of the question.  A\n               matrix that is not the zero matrix can have the spectrum\n               {0}.\n[B-process]    The 365 days of 2024 at Krems that carry a reading at 15:00\n               (UTC) are one record of a stochastic process.  Its\n               covariance function at lags 0 to 29 builds a linear operator\n               whose spectrum holds 30 nonnegative values.  Writes the CSV\n               files of the entry's figure.\n\nOutputs\n-------\nspectrum_sweep.csv   : lambda, |det(A - lambda I)|, and the size of the\n                       inverse, over 601 values of lambda.\nspectrum_values.csv  : the three values of the spectrum of A.\nspectrum_weather.csv : date and 15:00 (UTC) temperature of each day of 2024\n                       (committed copy).\nspectrum_acf.csv     : lag, covariance function of the record at that lag.\nspectrum_process.csv : index, the 30 values of the spectrum of the operator\n                       the covariance function builds.\nspectrum.png         : matplotlib preview (checking only).\n\nData generated by pythondemos/spectrum.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-definition]** A 3-by-3 matrix: det(A - lambda I) over a sweep of lambda vanishes at exactly three values, and those are the ones a solver returns. The definition is applied as written."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-definition] the values at which A - lambda I fails to be invertible\")\nA = np.array([[4.0, 1.0, 0.0],\n              [1.0, 3.0, 1.0],\n              [0.0, 1.0, 2.0]])\ncheck(\"[B-definition] A is a square matrix, so it carries an associated \"\n      \"linear operator\", A.shape[0] == A.shape[1])\n\n# 600 points rather than 601, so that no value of the spectrum lands\n# exactly on a grid point: a determinant of zero there would be counted as\n# two sign changes rather than one crossing\ngrid = np.linspace(0.0, 6.0, 600)\ndets = np.array([np.linalg.det(A - t * np.eye(3)) for t in grid])\nsign_changes = np.flatnonzero(dets[:-1] * dets[1:] < 0)\ncheck(f\"[B-definition] the determinant of A - lambda I changes sign \"\n      f\"{len(sign_changes)} times over the sweep, so the sweep brackets \"\n      \"three values\", len(sign_changes) == 3)\n\nvalues = np.sort(np.linalg.eigvalsh(A))\ncheck(f\"[B-definition] the spectrum is \"\n      f\"{{{values[0]:.2f}, {values[1]:.2f}, {values[2]:.2f}}}\",\n      len(values) == 3)\nbracketed = sorted(0.5 * (grid[i] + grid[i + 1]) for i in sign_changes)\ncheck(\"[B-definition] each bracketed value agrees with a value the solver \"\n      \"returns, to within the width of the sweep\",\n      bool(np.all(np.abs(np.array(bracketed) - values) < 0.02)))\ncheck(\"[B-definition] the determinant of A - lambda I is zero at every \"\n      \"value of the spectrum, to within 1e-12\",\n      all(abs(np.linalg.det(A - v * np.eye(3))) < 1e-12 for v in values))\ncheck(\"[B-definition] away from the spectrum the determinant is not zero\",\n      all(abs(np.linalg.det(A - t * np.eye(3))) > 1e-6\n          for t in (0.0, 1.0, 6.0)))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-invertible]** Off the spectrum, A - lambda I is invertible and (A - lambda I) v = b has exactly one solution. On the spectrum it is not invertible: it sends a nonzero direction to zero, so a solution either fails to exist or is not unique. The size of the inverse grows without bound as lambda approaches a value of the spectrum."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-invertible] on the spectrum the equation loses its one solution\")\nb = np.array([1.0, 2.0, 3.0])\noff = 1.0                                     # not in the spectrum\nM = A - off * np.eye(3)\nv = np.linalg.solve(M, b)\ncheck(\"[B-invertible] off the spectrum A - lambda I is invertible and the \"\n      \"equation has exactly one solution\", bool(np.allclose(M @ v, b)))\ncheck(\"[B-invertible] that solution is the only one: nothing but the zero \"\n      \"vector is sent to zero\",\n      int(np.linalg.matrix_rank(M)) == 3)\n\non = values[0]\nS = A - on * np.eye(3)\ncheck(f\"[B-invertible] at lambda = {on:.2f}, a value of the spectrum, \"\n      \"A - lambda I has rank 2 rather than 3, so it is not invertible\",\n      int(np.linalg.matrix_rank(S)) == 2)\n_, _, Vt = np.linalg.svd(S)\nnull_dir = Vt[-1]\ncheck(\"[B-invertible] it sends a nonzero direction to zero, which is \"\n      \"exactly the failure the definition names\",\n      np.linalg.norm(null_dir) > 0.5\n      and float(np.linalg.norm(S @ null_dir)) < 1e-12)\n\nsizes = np.array([1.0 / max(np.linalg.svd(A - t * np.eye(3),\n                                          compute_uv=False)[-1], 1e-300)\n                  for t in grid])\nnear = np.argmin(np.abs(grid - values[0]))\ncheck(\"[B-invertible] the size of the inverse grows without bound as lambda \"\n      \"approaches a value of the spectrum\",\n      sizes[near] > 50 * sizes[0])\n\nnp.savetxt(OUT_DIR / \"spectrum_sweep.csv\",\n           np.column_stack([grid, np.abs(dets), np.minimum(sizes, 1e3)]),\n           delimiter=\",\", header=\"lam,absdet,invsize\", comments=\"\",\n           fmt=\"%.6g\")\nnp.savetxt(OUT_DIR / \"spectrum_values.csv\", values.reshape(-1, 1),\n           delimiter=\",\", header=\"lam\", comments=\"\", fmt=\"%.6f\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-field]** A rotation of the plane by 90 degrees has an empty spectrum over the real numbers and a two-element spectrum over the complex numbers, so the field is part of the question. A matrix that is not the zero matrix can have the spectrum {0}."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-field] the spectrum depends on the field the operator acts over\")\nR = np.array([[0.0, -1.0], [1.0, 0.0]])       # a rotation by 90 degrees\nreal_hits = [t for t in np.linspace(-5, 5, 2001)\n             if abs(np.linalg.det(R - t * np.eye(2))) < 1e-9]\ncheck(\"[B-field] over the real numbers no lambda makes R - lambda I fail to \"\n      \"be invertible, so the real spectrum of a 90-degree rotation is \"\n      \"empty\", len(real_hits) == 0)\ncvals = np.linalg.eigvals(R)\ncheck(\"[B-field] over the complex numbers the spectrum holds the two values \"\n      \"i and -i\", bool(np.allclose(np.sort_complex(cvals), [-1j, 1j])))\n\nNmat = np.array([[0.0, 1.0], [0.0, 0.0]])\ncheck(\"[B-field] the spectrum of the matrix [[0, 1], [0, 0]] is the single \"\n      \"value 0, although the matrix itself is not the zero matrix\",\n      bool(np.allclose(np.linalg.eigvals(Nmat), 0.0))\n      and not np.allclose(Nmat, 0.0))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-process]** The 365 days of 2024 at Krems that carry a reading at 15:00 (UTC) are one record of a stochastic process. Its covariance function at lags 0 to 29 builds a linear operator whose spectrum holds 30 nonnegative values. Writes the CSV files of the entry's figure."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-process] the 15:00 (UTC) temperature at Krems, 2024, as a record\")\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 / \"spectrum_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        if stamp[11:16] == \"15:00\":        # the stamps are UTC, and so is\n            byday[stamp[:10]] = float(value)   # the time\n    stamps = sorted(byday)\n    y = np.array([byday[d] for d in stamps])\n    with open(CSV, \"w\") as fh:\n        fh.write(\"date,t15\\n\")\n        for day, val in zip(stamps, y):\n            fh.write(f\"{day},{val:g}\\n\")\n    print(f\"    downloaded {len(y)} days with a 15:00 reading\")\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    y = rows[:, 1].astype(float)\n\ncheck(\"[B-process] 365 of the days of 2024 carry a 15:00 reading (the \"\n      \"hourly record drops 2024-01-12)\", len(y) == 365)\ncheck(\"[B-process] the record matches the archive (1 January: 8.0 at 15:00 \"\n      \"UTC)\", stamps[0] == \"2024-01-01\" and bool(np.isclose(y[0], 8.0)))\n\nLAGS = 30\nz = y - y.mean()\nacf = np.array([float(np.dot(z[:len(z) - k], z[k:]) / len(z))\n                for k in range(LAGS)])\ncheck(f\"[B-process] the covariance function at lag 0 is the variance \"\n      f\"{acf[0]:.1f} squared degrees\", bool(np.isclose(acf[0], z.var())))\ncheck(\"[B-process] the covariance function falls off with the lag: lag 1 \"\n      \"exceeds lag 10\", acf[1] > acf[10])\n\nCop = np.array([[acf[abs(i - j)] for j in range(LAGS)] for i in range(LAGS)])\ncheck(\"[B-process] the covariance function builds a symmetric linear \"\n      \"operator on 30 consecutive days\", bool(np.allclose(Cop, Cop.T)))\nspec = np.sort(np.linalg.eigvalsh(Cop))[::-1]\ncheck(f\"[B-process] its spectrum holds {LAGS} values, the largest \"\n      f\"{spec[0]:.1f} and the smallest {spec[-1]:.1f} squared degrees\",\n      len(spec) == LAGS)\ncheck(\"[B-process] no value of the spectrum is negative, as a covariance \"\n      \"function requires\", bool(spec.min() > -1e-9))\ncheck(\"[B-process] the operator is invertible exactly because 0 is not in \"\n      \"its spectrum\",\n      bool(spec.min() > 1e-9)\n      and int(np.linalg.matrix_rank(Cop)) == LAGS)\n\nnp.savetxt(OUT_DIR / \"spectrum_acf.csv\",\n           np.column_stack([np.arange(LAGS), acf]), delimiter=\",\",\n           header=\"lag,cov\", comments=\"\", fmt=\"%.4f\")\nnp.savetxt(OUT_DIR / \"spectrum_process.csv\",\n           np.column_stack([np.arange(1, LAGS + 1), spec]), delimiter=\",\",\n           header=\"index,lam\", comments=\"\", fmt=\"%.4f\")\n\n# ---- the preview figure\nfig, ax = plt.subplots(1, 2, figsize=(9.4, 3.8))\n\nax[0].plot(grid, np.abs(dets), linestyle=\"-\", color=\"black\",\n           label=\"|det(A - $\\\\lambda$I)| (solid curve)\")\nax[0].plot(values, np.zeros_like(values), \"o\", color=\"black\", ms=7,\n           markerfacecolor=\"white\", label=\"the spectrum (open circles)\")\nax[0].set_xlabel(\"$\\\\lambda$\")\nax[0].set_ylabel(\"|det(A - $\\\\lambda$I)|\")\nax[0].set_title(\"(a) the spectrum is where the determinant vanishes\",\n                fontsize=9)\nax[0].legend(frameon=False, fontsize=8)\n\nax[1].plot(np.arange(1, LAGS + 1), spec, \"s\", color=\"black\", ms=4,\n           label=\"the 30 values (filled squares)\")\nax[1].set_xlabel(\"index, largest value first\")\nax[1].set_yscale(\"log\")          # the largest value is 700 times the\n                                 # smallest, so a linear axis would show\n                                 # one square and 29 on the floor\nax[1].set_ylabel(\"value of the spectrum (\u00b0C$^2$, log scale)\")\nax[1].set_title(\"(b) the spectrum the Krems covariance function builds\",\n                fontsize=9)\nax[1].legend(frameon=False, fontsize=8)\n\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"spectrum.png\", dpi=150)\n\nprint(f\"\\n{sum(ok for _, ok in report)}/{len(report)} checks passed\")"
  }
 ]
}