{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "LapMat.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Laplacian matrix \u2014 Python demo\n\nNumerical companion to the entry [Laplacian matrix](https://dictionaryofml.org/terms/LapMat.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 'LapMat'. Twelve GeoSphere weather stations within 45 km of Krems are the nodes of a weighted graph: two stations are connected by an edge if they are at most 35 km apart, and the edge weight exp(-d^2 / (2 * 20^2)) decays with the distance d in km. The mean temperature of 2024 at a station is a number attached to its node. The demo builds the Laplacian matrix L = D - A from the degree matrix D and the adjacency matrix A and checks the entry's claims: the quadratic form x^T L x equals the sum over the edges of the weighted squared differences; L is positive semi-definite with the eigenvalue 0 and the constant eigenvector; the multiplicity of the eigenvalue 0 equals the number of connected components, which the demo varies by shrinking the radius; the normalized Laplacian matrices have eigenvalues in [0, 2]; the Fiedler vector splits the stations by its signs; and Laplacian regularization predicts the mean temperature of a station without a record as the weighted average of its neighbors.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/LapMat.py`](https://dictionaryofml.org/terms/LapMat.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 LapMat.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(), \"LapMat.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"The Laplacian matrix of a weighted graph of twelve weather stations\naround Krems an der Donau: the quadratic form, the zero eigenvalue, the\nnormalized variants, and Laplacian regularization.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'LapMat'.  Twelve GeoSphere\nweather stations within 45 km of Krems are the nodes of a weighted\ngraph: two stations are connected by an edge if they are at most 35 km\napart, and the edge weight exp(-d^2 / (2 * 20^2)) decays with the\ndistance d in km.  The mean temperature of 2024 at a station is a number\nattached to its node.  The demo builds the Laplacian matrix L = D - A\nfrom the degree matrix D and the adjacency matrix A and checks the\nentry's claims: the quadratic form x^T L x equals the sum over the edges\nof the weighted squared differences; L is positive semi-definite with\nthe eigenvalue 0 and the constant eigenvector; the multiplicity of the\neigenvalue 0 equals the number of connected components, which the demo\nvaries by shrinking the radius; the normalized Laplacian matrices have\neigenvalues in [0, 2]; the Fiedler vector splits the stations by its\nsigns; and Laplacian regularization predicts the mean temperature of a\nstation without a record as the weighted average of its neighbors.\n\nDeterministic (the only random draws are test vectors from a fixed\nseed) and self-contained: numpy + matplotlib only; the GeoSphere\ndownload falls back to the committed CSV.\n\nBlocks\n------\n[B-data]        Download the daily mean temperature of 2024 at the twelve\n                stations (GeoSphere, klima-v2-1d, parameter tl_mittel) or\n                read the committed copy; the mean temperature of the year\n                per station; station positions in km east and north of\n                Krems.\n[B-graph]       Edges between stations at most 35 km apart with Gaussian\n                weights; adjacency matrix A, degree matrix D, Laplacian\n                matrix L = D - A: diagonal entries are the degrees, the\n                off-diagonal entries the negated edge weights, every row\n                sums to zero.\n[B-quadform]    x^T L x equals the sum over the edges of\n                A_ij (x_i - x_j)^2, for the temperature vector and for\n                50 test vectors with entries drawn from a fixed seed; it\n                is zero for a constant vector.\n[B-eigenvalues] Eigenvalues of L are nonnegative, the smallest is 0 with\n                the constant eigenvector; the graph is connected and the\n                second-smallest eigenvalue is positive.  Shrinking the\n                radius to 25 km and 20 km disconnects the graph into 2\n                and 6 components, and the eigenvalue 0 then has\n                multiplicity 2 and 6.\n[B-normalized]  The normalized Laplacian matrices L_sym and L_rw: same\n                eigenvalues, all in [0, 2], eigenvalue 0 with eigenvector\n                D^(1/2) 1 and 1, respectively.\n[B-fiedler]     The signs of the Fiedler vector split the three stations\n                more than 20 km east of Krems from the other nine.\n[B-regularize]  Laplacian regularization: leaving one station out, the\n                minimizer of the quadratic form with the other eleven\n                values fixed is the weighted average of its neighbors;\n                error of this prediction against the recorded mean, the\n                mean of the other stations as the baseline.\n[B-plot]        CSVs for the figure (nodes, edges, eigenvalues) and the\n                matplotlib preview.\n\nOutputs\n-------\nLapMat_weather.csv  : date and the daily mean temperature of the twelve\n                      stations (committed copy of the download).\nLapMat_nodes.csv    : station name, position in km east and north of\n                      Krems, altitude, mean temperature, Fiedler-vector\n                      entry and its sign, label anchor for the figure.\nLapMat_edges.csv    : one row per edge: start point, displacement, edge\n                      weight (for a pgfplots quiver).\nLapMat_eigenvalues.csv : index i and the i-th smallest eigenvalue of L\n                      for the radii 35 km, 25 km, and 20 km.\nLapMat.png          : matplotlib preview (checking only).\n\"\"\"\n\n# /// script\n# requires-python = \">=3.10\"\n# dependencies = [\"matplotlib==3.10.7\", \"numpy==2.3.4\"]\n# ///\n\nimport json\nimport math\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\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-data]** Download the daily mean temperature of 2024 at the twelve stations (GeoSphere, klima-v2-1d, parameter tl_mittel) or read the committed copy; the mean temperature of the year per station; station positions in km east and north of Krems."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-data] daily mean temperature of 2024 at twelve stations\")\n# GeoSphere station id, name, latitude, longitude, altitude in m (from the\n# klima-v2-1d station metadata); the short name labels the figure, and the\n# last field is the TikZ anchor of that label (south: label above the node,\n# north: below, east: to the left)\nSTATIONS = [\n    (3805, \"Krems\", 48.41861, 15.62222, 202.0, \"Krems\", \"north\"),\n    (3811, \"Langenlois\", 48.4725, 15.69722, 207.0, \"Langenlois\", \"east\"),\n    (2116, \"Gars am Kamp\", 48.59194, 15.7, 273.0, \"Gars\", \"east\"),\n    (3702, \"Jauerling Gipfel\", 48.33447, 15.33911, 955.0, \"Jauerling\",\n     \"south\"),\n    (5609, \"St. P\u00f6lten Landhaus\", 48.19972, 15.63111, 273.6, \"St. P\u00f6lten\",\n     \"south\"),\n    (2117, \"Horn Wasserwerk\", 48.674999, 15.643888, 308.0, \"Horn\", \"north\"),\n    (5413, \"Melk\", 48.20972, 15.33139, 307.0, \"Melk\", \"south\"),\n    (1906, \"Allentsteig\", 48.69083, 15.36694, 598.8, \"Allentsteig\",\n     \"north\"),\n    (1920, \"Stift Zwettl\", 48.61778, 15.20361, 502.4, \"Zwettl\", \"south\"),\n    (4081, \"Langenlebarn\", 48.32389, 16.11806, 175.3, \"Langenlebarn\",\n     \"south\"),\n    (2207, \"Sch\u00f6ngrabern\", 48.60333, 16.06167, 253.0, \"Sch\u00f6ngrabern\",\n     \"north\"),\n    (905, \"Retz\", 48.76111, 15.94167, 320.0, \"Retz\", \"north\"),\n]\nIDS = [s[0] for s in STATIONS]\nNAMES = [s[5] for s in STATIONS]\nn = len(STATIONS)\nURL = (\"https://dataset.api.hub.geosphere.at/v1/station/historical/\"\n       \"klima-v2-1d?parameters=tl_mittel&station_ids=\"\n       + \",\".join(str(i) for i in IDS) + \"&start=2024-01-01&end=2024-12-31\")\nCSV = OUT_DIR / \"LapMat_weather.csv\"\ntry:\n    with urllib.request.urlopen(URL, timeout=120) as resp:\n        payload = json.load(resp)\n    dates = [stamp[:10] for stamp in payload[\"timestamps\"]]\n    by_id = {int(f[\"properties\"][\"station\"]):\n             f[\"properties\"][\"parameters\"][\"tl_mittel\"][\"data\"]\n             for f in payload[\"features\"]}\n    columns = [by_id[i] for i in IDS]\n    with open(CSV, \"w\") as fh:\n        fh.write(\"date,\" + \",\".join(f\"s{i}\" for i in IDS) + \"\\n\")\n        for r, day in enumerate(dates):\n            fh.write(day + \",\" + \",\".join(f\"{col[r]}\" for col in columns)\n                     + \"\\n\")\n    print(f\"    downloaded {len(dates)} days for {len(columns)} stations\")\nexcept OSError as err:\n    print(f\"    download failed ({err}); reading the committed CSV\")\n    rows = CSV.read_text().strip().splitlines()[1:]\n    dates = [r.split(\",\")[0] for r in rows]\n    table = np.array([[float(v) for v in r.split(\",\")[1:]] for r in rows])\n    columns = [table[:, j].tolist() for j in range(n)]\n\nT = np.array(columns, dtype=float)             # stations x days\ncheck(\"[B-data] 366 days for 2024\", T.shape == (n, 366))\ncheck(\"[B-data] no station is missing a day\", not np.isnan(T).any())\nx = T.mean(axis=1)                             # mean temperature per station\ncheck(\"[B-data] mean temperature of 2024: \"\n      + \", \".join(f\"{nm} {v:.1f}\" for nm, v in zip(NAMES, x)),\n      np.all((x > 8) & (x < 15)))\n# positions in km east and north of Krems (plane approximation)\nlat0, lon0 = STATIONS[0][2], STATIONS[0][3]\neast = np.array([(s[3] - lon0) * 111.32 * math.cos(math.radians(lat0))\n                 for s in STATIONS])\nnorth = np.array([(s[2] - lat0) * 110.57 for s in STATIONS])\naltitude = np.array([s[4] for s in STATIONS])\ndist = np.sqrt((east[:, None] - east[None, :]) ** 2\n               + (north[:, None] - north[None, :]) ** 2)\ncheck(f\"[B-data] every station is within {dist[0].max():.0f} km of Krems\",\n      dist[0].max() < 46)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-graph]** Edges between stations at most 35 km apart with Gaussian weights; adjacency matrix A, degree matrix D, Laplacian matrix L = D - A: diagonal entries are the degrees, the off-diagonal entries the negated edge weights, every row sums to zero."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-graph] edges within 35 km, Gaussian weights, L = D - A\")\nSIGMA = 20.0                                   # km\n\n\ndef laplacian(radius):\n    \"\"\"Adjacency matrix, degrees, and Laplacian matrix of the graph that\n    connects stations at most `radius` km apart.\"\"\"\n    A = np.exp(-dist ** 2 / (2 * SIGMA ** 2)) * (dist <= radius)\n    np.fill_diagonal(A, 0.0)\n    d = A.sum(axis=1)\n    return A, d, np.diag(d) - A\n\n\nRADIUS = 35.0\nA, deg, L = laplacian(RADIUS)\nn_edges = int(np.count_nonzero(np.triu(A)))\ncheck(f\"[B-graph] {n} nodes and {n_edges} edges\", n_edges == 27)\ncheck(\"[B-graph] A is symmetric with zero diagonal and weights in (0, 1)\",\n      np.allclose(A, A.T) and np.all(np.diag(A) == 0)\n      and np.all((A[A > 0] > 0) & (A[A > 0] < 1)))\ncheck(f\"[B-graph] edge weights between {A[A > 0].min():.2f} and \"\n      f\"{A[A > 0].max():.2f}; the Krems-Langenlois edge (8 km) weighs \"\n      f\"{A[0, 1]:.2f}\", abs(A[0, 1] - math.exp(-dist[0, 1] ** 2 / 800)) < 1e-12)\ncheck(\"[B-graph] diagonal of L = degrees, off-diagonal of L = -A\",\n      np.allclose(np.diag(L), deg) and np.allclose(L - np.diag(deg), -A))\ncheck(\"[B-graph] every row of L sums to zero\", np.allclose(L.sum(axis=1), 0))\ncheck(f\"[B-graph] Krems has degree {deg[0]:.2f}, the weighted number of \"\n      f\"its {int(np.count_nonzero(A[0]))} neighbors\", abs(deg[0] - A[0].sum()) < 1e-12)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-quadform]** x^T L x equals the sum over the edges of A_ij (x_i - x_j)^2, for the temperature vector and for 50 test vectors with entries drawn from a fixed seed; it is zero for a constant vector."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-quadform] the quadratic form of L\")\n\n\ndef edge_sum(A, v):\n    \"\"\"Sum over the edges {i, j} of A_ij (v_i - v_j)^2.\"\"\"\n    iu, ju = np.triu_indices(len(v), k=1)\n    return float(np.sum(A[iu, ju] * (v[iu] - v[ju]) ** 2))\n\n\nqf = float(x @ L @ x)\ncheck(f\"[B-quadform] temperature vector: x^T L x = {qf:.2f} equals the \"\n      f\"edge sum {edge_sum(A, x):.2f} (squared degrees Celsius)\",\n      abs(qf - edge_sum(A, x)) < 1e-9)\nrng = np.random.default_rng(2024)\nR = rng.standard_normal((50, n))\ncheck(\"[B-quadform] identity holds for 50 test vectors with entries drawn \"\n      \"from a fixed seed, all values >= 0\",\n      all(abs(r @ L @ r - edge_sum(A, r)) < 1e-9 and r @ L @ r >= 0\n          for r in R))\nones = np.ones(n)\ncheck(\"[B-quadform] constant vector: x^T L x = 0 and L 1 = 0\",\n      abs(ones @ L @ ones) < 1e-12 and np.allclose(L @ ones, 0))\n# the largest single term of the edge sum\niu, ju = np.triu_indices(n, k=1)\nterms = A[iu, ju] * (x[iu] - x[ju]) ** 2\nk = int(np.argmax(terms))\ncheck(f\"[B-quadform] largest term: edge {NAMES[iu[k]]}-{NAMES[ju[k]]}, \"\n      f\"weight {A[iu[k], ju[k]]:.2f}, difference {abs(x[iu[k]] - x[ju[k]]):.1f} \"\n      f\"degrees, term {terms[k]:.2f}\", terms[k] > 0)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-eigenvalues]** Eigenvalues of L are nonnegative, the smallest is 0 with the constant eigenvector; the graph is connected and the second-smallest eigenvalue is positive. Shrinking the radius to 25 km and 20 km disconnects the graph into 2 and 6 components, and the eigenvalue 0 then has multiplicity 2 and 6."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "#      number of connected components\nprint(\"[B-eigenvalues] eigenvalues of L and connected components\")\n\n\ndef components(A):\n    \"\"\"Number of connected components and a label per node (depth-first\n    search over the positive entries of A).\"\"\"\n    label = -np.ones(len(A), dtype=int)\n    c = 0\n    for s in range(len(A)):\n        if label[s] >= 0:\n            continue\n        stack = [s]\n        label[s] = c\n        while stack:\n            u = stack.pop()\n            for v in np.flatnonzero(A[u] > 0):\n                if label[v] < 0:\n                    label[v] = c\n                    stack.append(v)\n        c += 1\n    return c, label\n\n\nTOL = 1e-9\nlam, V = np.linalg.eigh(L)\ncheck(f\"[B-eigenvalues] all {n} eigenvalues are >= 0 (smallest {lam[0]:.1e}, \"\n      f\"largest {lam[-1]:.2f})\", np.all(lam > -TOL))\ncheck(\"[B-eigenvalues] eigenvalue 0 with the constant vector as eigenvector\",\n      abs(lam[0]) < TOL and np.allclose(np.abs(V[:, 0]), 1 / math.sqrt(n)))\nn_comp, _ = components(A)\ncheck(f\"[B-eigenvalues] radius 35 km: connected ({n_comp} component), \"\n      f\"second-smallest eigenvalue {lam[1]:.2f} > 0\",\n      n_comp == 1 and lam[1] > 1e-6)\neigvals = {RADIUS: lam}\nfor radius, expected in ((25.0, 2), (20.0, 6)):\n    A_r, _, L_r = laplacian(radius)\n    lam_r, V_r = np.linalg.eigh(L_r)\n    eigvals[radius] = lam_r\n    n_comp_r, label_r = components(A_r)\n    mult = int(np.sum(np.abs(lam_r) < TOL))\n    check(f\"[B-eigenvalues] radius {radius:.0f} km: {n_comp_r} components, \"\n          f\"eigenvalue 0 with multiplicity {mult}\",\n          n_comp_r == expected == mult)\n    # the indicator vectors of the components span the eigenspace of 0\n    indicators = np.array([(label_r == c).astype(float)\n                           for c in range(n_comp_r)])\n    check(f\"[B-eigenvalues] radius {radius:.0f} km: the indicator vector of \"\n          f\"each component satisfies L x = 0\",\n          all(np.allclose(L_r @ ind, 0) for ind in indicators))\n    if radius == 25.0:\n        alone = [NAMES[i] for i in range(n) if np.count_nonzero(A_r[i]) == 0]\n        check(f\"[B-eigenvalues] radius 25 km: the isolated station is \"\n              f\"{', '.join(alone)}\", alone == [\"Langenlebarn\"])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-normalized]** The normalized Laplacian matrices L_sym and L_rw: same eigenvalues, all in [0, 2], eigenvalue 0 with eigenvector D^(1/2) 1 and 1, respectively."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-normalized] L_sym and L_rw\")\nD_isqrt = np.diag(1 / np.sqrt(deg))\nL_sym = D_isqrt @ L @ D_isqrt\nL_rw = np.diag(1 / deg) @ L\nlam_sym = np.linalg.eigvalsh(L_sym)\nlam_rw = np.sort(np.linalg.eigvals(L_rw).real)\ncheck(f\"[B-normalized] eigenvalues of L_sym lie in [0, 2]: smallest \"\n      f\"{lam_sym[0]:.1e}, largest {lam_sym[-1]:.2f}\",\n      lam_sym[0] > -TOL and lam_sym[-1] <= 2 + TOL)\ncheck(\"[B-normalized] L_rw has the same eigenvalues as L_sym\",\n      np.allclose(lam_sym, lam_rw))\ncheck(\"[B-normalized] L_sym D^(1/2) 1 = 0 and L_rw 1 = 0\",\n      np.allclose(L_sym @ np.sqrt(deg), 0) and np.allclose(L_rw @ ones, 0))\ncheck(\"[B-normalized] L_sym = I - D^(-1/2) A D^(-1/2) and \"\n      \"L_rw = I - D^(-1) A\",\n      np.allclose(L_sym, np.eye(n) - D_isqrt @ A @ D_isqrt)\n      and np.allclose(L_rw, np.eye(n) - np.diag(1 / deg) @ A))\ncheck(\"[B-normalized] x^T L_sym x equals the edge sum of \"\n      \"A_ij (x_i / sqrt(d_i) - x_j / sqrt(d_j))^2\",\n      all(abs(r @ L_sym @ r - edge_sum(A, r / np.sqrt(deg))) < 1e-9\n          for r in R))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-fiedler]** The signs of the Fiedler vector split the three stations more than 20 km east of Krems from the other nine."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-fiedler] signs of the Fiedler vector (radius 35 km)\")\nfiedler = V[:, 1]\nif fiedler[0] < 0:\n    fiedler = -fiedler                         # sign convention: Krems positive\ncheck(\"[B-fiedler] the entries of the Fiedler vector sum to zero\",\n      abs(fiedler @ ones) < 1e-9)\nside = (fiedler >= 0).astype(int)               # 1: with Krems, 0: the rest\nfar_east = [NAMES[i] for i in range(n) if east[i] > 20]\nnegative = [NAMES[i] for i in range(n) if side[i] == 0]\ncheck(f\"[B-fiedler] negative entries: {', '.join(negative)}; these are the \"\n      f\"stations more than 20 km east of Krems\", sorted(negative) == sorted(far_east))\ncheck(\"[B-fiedler] entries: \"\n      + \", \".join(f\"{nm} {v:+.2f}\" for nm, v in zip(NAMES, fiedler)),\n      len(negative) == 3)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-regularize]** Laplacian regularization: leaving one station out, the minimizer of the quadratic form with the other eleven values fixed is the weighted average of its neighbors; error of this prediction against the recorded mean, the mean of the other stations as the baseline."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-regularize] leave one station out, predict by its neighbors\")\npred = np.array([A[i] @ x / deg[i] for i in range(n)])\n# the weighted average minimizes the quadratic form over x_i alone\ni0 = 0\ngrid = pred[i0] + np.linspace(-2, 2, 401)\n\n\ndef qf_with(i, value):\n    v = x.copy()\n    v[i] = value\n    return v @ L @ v\n\n\ncheck(\"[B-regularize] for Krems, the weighted average of its neighbors \"\n      \"minimizes x^T L x over the Krems entry (grid of 401 values)\",\n      all(qf_with(i0, g) >= qf_with(i0, pred[i0]) - 1e-9 for g in grid))\ncheck(\"[B-regularize] for every station, the entry of L x at that station \"\n      \"is 0 once its value is the weighted average of its neighbors\",\n      all(abs((L @ np.where(np.arange(n) == i, pred[i], x))[i]) < 1e-9\n          for i in range(n)))\nerr = pred - x\nbaseline = np.array([np.delete(x, i).mean() - x[i] for i in range(n)])\nmae, mae_base = np.mean(np.abs(err)), np.mean(np.abs(baseline))\ncheck(f\"[B-regularize] mean absolute error {mae:.2f} degrees, against \"\n      f\"{mae_base:.2f} for the mean of the other eleven stations\",\n      mae < mae_base)\nworst = int(np.argmax(np.abs(err)))\ncheck(f\"[B-regularize] largest error at {NAMES[worst]} ({altitude[worst]:.0f} m): \"\n      f\"predicted {pred[worst]:.1f}, recorded {x[worst]:.1f}, error \"\n      f\"{err[worst]:+.1f} degrees\", NAMES[worst] == \"Jauerling\")\nrest = np.delete(np.abs(err), worst)\ncheck(f\"[B-regularize] without {NAMES[worst]} the mean absolute error is \"\n      f\"{rest.mean():.2f} degrees; Krems: predicted {pred[0]:.1f}, recorded \"\n      f\"{x[0]:.1f}\", rest.mean() < 1)\n# the penalized problem (average squared error over the eleven labeled\n# stations plus alpha times the quadratic form) with a small penalty weight\n# alpha tends to the same value; its minimizer solves a linear system\nalpha = 1e-5\nmask = np.ones(n)\nmask[i0] = 0.0\nn_lab = int(mask.sum())\nx_alpha = np.linalg.solve(np.diag(mask) / n_lab + alpha * L, mask * x / n_lab)\ncheck(f\"[B-regularize] penalized problem with alpha = {alpha:g}: the Krems \"\n      f\"entry {x_alpha[i0]:.3f} is within 0.001 of the weighted average \"\n      f\"{pred[i0]:.3f}\", abs(x_alpha[i0] - pred[i0]) < 1e-3)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-plot]** CSVs for the figure (nodes, edges, eigenvalues) and the matplotlib preview."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-plot] nodes, edges, eigenvalues, preview\")\nwith open(OUT_DIR / \"LapMat_nodes.csv\", \"w\") as fh:\n    fh.write(\"name,east,north,altitude,temp,fiedler,side,anchor\\n\")\n    for i, s in enumerate(STATIONS):\n        fh.write(f\"{NAMES[i]},{east[i]:.2f},{north[i]:.2f},{altitude[i]:.0f},\"\n                 f\"{x[i]:.2f},{fiedler[i]:.3f},{side[i]},{s[6]}\\n\")\nwith open(OUT_DIR / \"LapMat_edges.csv\", \"w\") as fh:\n    fh.write(\"x,y,u,v,w\\n\")\n    for i, j in zip(iu, ju):\n        if A[i, j] > 0:\n            fh.write(f\"{east[i]:.2f},{north[i]:.2f},{east[j] - east[i]:.2f},\"\n                     f\"{north[j] - north[i]:.2f},{A[i, j]:.3f}\\n\")\nwith open(OUT_DIR / \"LapMat_eigenvalues.csv\", \"w\") as fh:\n    fh.write(\"i,lam35,lam25,lam20\\n\")\n    for i in range(n):\n        fh.write(f\"{i + 1},{max(eigvals[35.0][i], 0):.4f},\"\n                 f\"{max(eigvals[25.0][i], 0):.4f},\"\n                 f\"{max(eigvals[20.0][i], 0):.4f}\\n\")\ncheck(f\"[B-plot] {n} nodes, {n_edges} edges, {n} eigenvalues per radius \"\n      \"written\", True)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.2))\nfor i, j in zip(iu, ju):\n    if A[i, j] > 0:\n        ax1.plot([east[i], east[j]], [north[i], north[j]], color=\"0.55\",\n                 lw=1.8 if A[i, j] >= 0.5 else 0.6, zorder=1)\nfor s_val, mk, lab in ((1, \"o\", \"Fiedler entry >= 0 (circles)\"),\n                       (0, \"s\", \"Fiedler entry < 0 (squares)\")):\n    sel = side == s_val\n    ax1.scatter(east[sel], north[sel], marker=mk, color=\"black\", s=34,\n                zorder=2, label=lab)\nfor i in range(n):\n    anc = STATIONS[i][6]\n    dy = {\"south\": 2.2, \"north\": -3.6, \"east\": 0.0}[anc]\n    dx = -2.5 if anc == \"east\" else 0.0\n    ax1.annotate(NAMES[i], (east[i] + dx, north[i] + dy), fontsize=7,\n                 ha=\"right\" if anc == \"east\" else \"center\")\nax1.set_xlabel(\"km east of Krems\")\nax1.set_ylabel(\"km north of Krems\")\nax1.set_title(\"stations within 35 km joined (thick: weight >= 0.5)\")\nax1.set_xlim(-38, 50)\nax1.set_ylim(-32, 44)\nax1.set_aspect(\"equal\")\nax1.legend(frameon=False, fontsize=8, loc=\"upper center\",\n           bbox_to_anchor=(0.5, -0.16), ncol=2)\nidx = np.arange(1, n + 1)\nfor radius, mk, lab in ((35.0, \"o\", \"radius 35 km (circles)\"),\n                        (25.0, \"s\", \"radius 25 km (squares)\"),\n                        (20.0, \"^\", \"radius 20 km (triangles)\")):\n    ax2.plot(idx, np.maximum(eigvals[radius], 0), mk, color=\"black\",\n             mfc=\"none\" if radius != 35.0 else \"black\", ms=6, label=lab)\nax2.set_xlabel(\"index i of the eigenvalue\")\nax2.set_ylabel(\"i-th smallest eigenvalue of L\")\nax2.set_title(\"zero eigenvalues = connected components\")\nax2.set_xticks(idx)\nax2.legend(frameon=False, fontsize=8, loc=\"upper left\")\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"LapMat.png\", dpi=110)\n\nn_ok = sum(ok for _, ok in report)\nprint(f\"\\n{n_ok}/{len(report)} checks pass\")\nif n_ok != len(report):\n    raise SystemExit(1)"
  }
 ]
}