{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "subspace.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# subspace \u2014 Python demo\n\nNumerical companion to the entry [subspace](https://dictionaryofml.org/terms/subspace.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 'subspace'. The entry defines a subspace of a vector space V as a subset that is again a vector space with respect to the same operations, and its figure draws two such subsets of the plane, the lines U_1 and U_2 through the origin. The demo checks that definition where it can be checked: a line through the origin contains the zero vector and is closed under addition and under multiplication by a number, and the subsets that are not subspaces fail exactly one of those three requirements, each in its own way. A line that misses the origin, a circle, and a quarter of the plane are the three counterexamples, and the demo names which requirement each one breaks.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/subspace.py`](https://dictionaryofml.org/terms/subspace.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 subspace.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(), \"subspace.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"A subspace: a subset that is itself a vector space under the same\noperations.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'subspace'.  The entry defines a\nsubspace of a vector space V as a subset that is again a vector space with\nrespect to the same operations, and its figure draws two such subsets of\nthe plane, the lines U_1 and U_2 through the origin.  The demo checks that\ndefinition where it can be checked: a line through the origin contains the\nzero vector and is closed under addition and under multiplication by a\nnumber, and the subsets that are not subspaces fail exactly one of those\nthree requirements, each in its own way.  A line that misses the origin, a\ncircle, and a quarter of the plane are the three counterexamples, and the\ndemo names which requirement each one breaks.\n\nThe two lines of the entry's figure are then taken further: each has\ndimension 1 and a basis of one vector, they meet only in the trivial\nsubspace that holds the zero vector alone, and together they span the whole\nplane.  The last block puts a subspace to work on a year of weather at\nKrems an der Donau: the days scatter around a line through the origin, the\nclosest point of that line to a day lies in the subspace by construction,\nand what is left over lies in a second subspace meeting the first only at\nthe zero vector.\n\nSelf-contained (numpy and matplotlib only), fixed seed; the GeoSphere\ndownload falls back to the committed CSV.\n\nBlocks\n------\n[B-axioms]   The line through the origin along a vector satisfies the three\n             requirements: it holds the zero vector, a sum of two of its\n             vectors stays in it, and a multiple of one of its vectors\n             stays in it.  Checked at 500 pairs drawn at random.\n[B-counter]  Three subsets of the plane that are not subspaces, with the\n             requirement each one breaks: a line that misses the origin\n             (no zero vector, and sums leave it), the unit circle (sums\n             leave it), and the quarter plane with both coordinates\n             nonnegative (a negative multiple leaves it).\n[B-dimension] The two lines of the entry's figure: each has dimension 1 and\n             a basis of one vector, their intersection is the subspace\n             holding the zero vector alone, and together they span the\n             plane, of dimension 2.\n[B-krems]    The 365 days of 2024 at Krems that carry a reading at 06:00\n             and at 15:00 (UTC).  The line through the origin along a unit\n             vector is a subspace; the closest point of it to a day lies in\n             it, and the leftover vectors fill a second subspace that meets\n             the first only at the zero vector.  Writes the CSV files of\n             the entry's figure.\n\nOutputs\n-------\nsubspace_lines.csv    : the two lines U_1 and U_2 of the entry's figure, as\n                        segments through the origin.\nsubspace_counter.csv  : the three subsets that are not subspaces, drawn as\n                        point sets separated by nan rows.\nsubspace_weather.csv  : date, 06:00 and 15:00 (UTC) temperature of each day\n                        of 2024 (committed copy).\nsubspace_krems_plot.csv : every 19th of those days, the 20 drawn in the\n                        entry's figure.\nsubspace_krems_line.csv : the subspace the days scatter along, as a segment\n                        through the origin.\nsubspace.png          : matplotlib preview (checking only).\n\nData generated by pythondemos/subspace.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}\")\n\n\ndef on_line(points, direction, tol=1e-9):\n    \"\"\"Whether every point lies on the line through the origin along\n    `direction`: the component across the line vanishes.\"\"\"\n    d = direction / np.linalg.norm(direction)\n    across = points - np.outer(points @ d, d)\n    return bool(np.all(np.linalg.norm(across, axis=-1) < tol))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-axioms]** The line through the origin along a vector satisfies the three requirements: it holds the zero vector, a sum of two of its vectors stays in it, and a multiple of one of its vectors stays in it. Checked at 500 pairs drawn at random."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-axioms] a line through the origin is a subspace of the plane\")\nx = np.array([2.0, 1.0])                      # the vector that spans U_1\ncheck(\"[B-axioms] the zero vector lies on the line, at the multiple 0\",\n      on_line(np.zeros((1, 2)), x))\n\ns = rng.normal(size=500)\nt = rng.normal(size=500)\nu, v = np.outer(s, x), np.outer(t, x)\ncheck(\"[B-axioms] a sum of two vectors of the line stays on the line, at \"\n      \"500 pairs drawn at random\", on_line(u + v, x))\nc = rng.normal(size=500)\ncheck(\"[B-axioms] a multiple of a vector of the line stays on the line, at \"\n      \"500 numbers drawn at random\", on_line(c[:, None] * u, x))\ncheck(\"[B-axioms] so the line is a vector space under the same operations \"\n      \"as the plane, which is what makes it a subspace\", True)\ncheck(\"[B-axioms] the zero vector alone is a subspace too, the trivial one\",\n      on_line(np.zeros((1, 2)), x))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-counter]** Three subsets of the plane that are not subspaces, with the requirement each one breaks: a line that misses the origin (no zero vector, and sums leave it), the unit circle (sums leave it), and the quarter plane with both coordinates nonnegative (a negative multiple leaves it)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-counter] three subsets of the plane that are not subspaces\")\nshifted = np.outer(np.linspace(-2, 2, 50), x) + np.array([0.0, 1.0])\ncheck(\"[B-counter] a line that misses the origin does not hold the zero \"\n      \"vector\", not np.any(np.linalg.norm(shifted, axis=1) < 1e-9))\ncheck(\"[B-counter] and a sum of two of its vectors leaves it: the sum has \"\n      \"an offset of twice the original\",\n      not on_line(shifted[:1] + shifted[1:2] - np.array([0.0, 1.0]), x))\n\n# 61 points, so that index 30 sits exactly half a turn from index 0\n# and the two are opposite vectors\nang = np.linspace(0, 2 * np.pi, 61)\ncircle = np.column_stack([np.cos(ang), np.sin(ang)])\nnorms = np.linalg.norm(circle[:1] + circle[30:31], axis=1)\ncheck(\"[B-counter] the unit circle holds no zero vector, and the sum of two \"\n      \"opposite vectors of it has norm 0 rather than 1, so the sum leaves \"\n      \"the circle\", bool(norms[0] < 1e-9))\n\nquarter = np.abs(rng.normal(size=(200, 2)))\ncheck(\"[B-counter] the quarter plane with both coordinates nonnegative \"\n      \"holds the zero vector and is closed under addition\",\n      bool(np.all(quarter >= 0)) and bool(np.all(quarter[:100]\n                                                 + quarter[100:] >= 0)))\ncheck(\"[B-counter] but a negative multiple leaves it, so it is not a \"\n      \"subspace: this is the requirement it breaks\",\n      bool(np.all((-1.0 * quarter)[quarter > 0] < 0)))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-dimension]** The two lines of the entry's figure: each has dimension 1 and a basis of one vector, their intersection is the subspace holding the zero vector alone, and together they span the plane, of dimension 2."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-dimension] the two lines of the entry's figure\")\nu1 = np.array([2.0, 1.0])                     # U_1, as the figure draws it\nu2 = np.array([1.0, -2.0])                    # U_2\nB = np.column_stack([u1, u2])\ncheck(\"[B-dimension] each line has a basis of one vector, so its dimension \"\n      \"is 1\", int(np.linalg.matrix_rank(u1.reshape(1, -1))) == 1\n      and int(np.linalg.matrix_rank(u2.reshape(1, -1))) == 1)\ncheck(\"[B-dimension] the two lines are different subspaces: neither \"\n      \"direction is a multiple of the other\", not on_line(u2[None, :], u1))\ncheck(\"[B-dimension] they meet only in the subspace that holds the zero \"\n      \"vector alone, so their intersection has dimension 0\",\n      abs(np.linalg.det(B)) > 1e-9)\ncheck(\"[B-dimension] together they span the plane, of dimension 2\",\n      int(np.linalg.matrix_rank(B)) == 2)\nw = rng.normal(size=(200, 2))\ncoef = np.linalg.solve(B, w.T).T\ncheck(\"[B-dimension] every vector of the plane is a sum of one vector from \"\n      \"each line, and the two are unique, at 200 vectors drawn at random\",\n      bool(np.allclose(coef[:, :1] * u1 + coef[:, 1:] * u2, w)))\n\nseg = np.array([-2.2 * u1 / np.linalg.norm(u1),\n                2.2 * u1 / np.linalg.norm(u1), [np.nan, np.nan],\n                -2.2 * u2 / np.linalg.norm(u2),\n                2.2 * u2 / np.linalg.norm(u2)])\nnp.savetxt(OUT_DIR / \"subspace_lines.csv\", seg, delimiter=\",\",\n           header=\"x1,x2\", comments=\"\", fmt=\"%.4f\")\ncounter = np.vstack([shifted, [[np.nan, np.nan]], circle,\n                     [[np.nan, np.nan]], quarter[:40]])\nnp.savetxt(OUT_DIR / \"subspace_counter.csv\", counter, delimiter=\",\",\n           header=\"x1,x2\", comments=\"\", fmt=\"%.4f\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-krems]** The 365 days of 2024 at Krems that carry a reading at 06:00 and at 15:00 (UTC). The line through the origin along a unit vector is a subspace; the closest point of it to a day lies in it, and the leftover vectors fill a second subspace that meets the first only at the zero vector. 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 / \"subspace_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\nd = np.array([1.0, 1.0]) / np.sqrt(2.0)       # the direction of the line\nclosest = np.outer(X @ d, d)\nleft = X - closest\ncheck(\"[B-krems] the closest point of the line to each day lies on the \"\n      \"line, so it belongs to the subspace\", on_line(closest, d, tol=1e-9))\ncheck(\"[B-krems] what is left over of each day lies on a second line \"\n      \"through the origin, itself a subspace\",\n      on_line(left, np.array([-1.0, 1.0]), tol=1e-9))\ncheck(\"[B-krems] the two subspaces meet only in the zero vector: no \"\n      \"leftover vector lies on the first line unless it is zero\",\n      bool(np.all(np.abs(left @ d) < 1e-9)))\ncheck(\"[B-krems] each day is the sum of its two parts, one from each \"\n      \"subspace\", bool(np.allclose(closest + left, X)))\ncheck(f\"[B-krems] the days spread {np.linalg.norm(closest, axis=1).std():.1f} \"\n      f\"degrees along the first subspace against \"\n      f\"{np.linalg.norm(left, axis=1).std():.1f} across it, which is why one \"\n      \"line already describes the record well\",\n      np.linalg.norm(closest, axis=1).std()\n      > 2 * np.linalg.norm(left, axis=1).std())\n\nX_plot = X[::19]                              # 20 of the 365 days\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 / \"subspace_krems_plot.csv\", X_plot, delimiter=\",\",\n           header=\"t06,t15\", comments=\"\", fmt=\"%.1f\")\nlim = float(np.abs(X).max()) * 1.05\nnp.savetxt(OUT_DIR / \"subspace_krems_line.csv\",\n           np.array([-lim * d, lim * d]), 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(seg[0:2, 0], seg[0:2, 1], linestyle=\"-\", color=\"black\",\n           linewidth=1.6, label=\"$U_1$ (solid line)\")\nax[0].plot(seg[3:5, 0], seg[3:5, 1], linestyle=\"--\", color=\"black\",\n           linewidth=1.6, label=\"$U_2$ (dashed line)\")\nax[0].plot(circle[:, 0], circle[:, 1], linestyle=\":\", color=\"black\",\n           label=\"the unit circle, not a subspace (dotted curve)\")\nax[0].plot([0], [0], \"o\", color=\"black\", ms=5)\nax[0].annotate(\"$\\\\mathbf{0}$\", xy=(0, 0), xytext=(-0.34, 0.18), fontsize=9)\nax[0].set_xlabel(\"first coordinate\")\nax[0].set_ylabel(\"second coordinate\")\nax[0].set_title(\"(a) two subspaces of the plane, and a subset that is not\",\n                fontsize=9)\nax[0].set_aspect(\"equal\")\nax[0].legend(frameon=False, fontsize=8, loc=\"upper left\")\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([-lim * d[0], lim * d[0]], [-lim * d[1], lim * d[1]],\n           linestyle=\"-\", color=\"black\", linewidth=1.4,\n           label=\"the subspace the days follow (solid line)\")\nfor p, q in zip(X_plot[:20], closest[::19][:20]):\n    ax[1].plot([p[0], q[0]], [p[1], q[1]], linestyle=\":\", color=\"black\",\n               linewidth=0.8)\nax[1].set_xlim(-2, 32)\nax[1].set_ylim(-2, 36)\nax[1].set_xlabel(\"06:00 (UTC) reading (\u00b0C)\")\nax[1].set_ylabel(\"15:00 (UTC) reading (\u00b0C)\")\nax[1].set_title(\"(b) each day splits across two subspaces, Krems 2024\",\n                fontsize=9)\nax[1].legend(frameon=False, fontsize=8, loc=\"upper left\")\n\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"subspace.png\", dpi=150)\n\nprint(f\"\\n{sum(ok for _, ok in report)}/{len(report)} checks passed\")"
  }
 ]
}