"""A subspace: a subset that is itself a vector space under the same
operations.

Purpose
-------
Numerical 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.

The two lines of the entry's figure are then taken further: each has
dimension 1 and a basis of one vector, they meet only in the trivial
subspace that holds the zero vector alone, and together they span the whole
plane.  The last block puts a subspace to work on a year of weather at
Krems an der Donau: the days scatter around a line through the origin, the
closest point of that line to a day lies in the subspace by construction,
and what is left over lies in a second subspace meeting the first only at
the zero vector.

Self-contained (numpy and matplotlib only), fixed seed; the GeoSphere
download falls back to the committed CSV.

Blocks
------
[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.
[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).
[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.
[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.

Outputs
-------
subspace_lines.csv    : the two lines U_1 and U_2 of the entry's figure, as
                        segments through the origin.
subspace_counter.csv  : the three subsets that are not subspaces, drawn as
                        point sets separated by nan rows.
subspace_weather.csv  : date, 06:00 and 15:00 (UTC) temperature of each day
                        of 2024 (committed copy).
subspace_krems_plot.csv : every 19th of those days, the 20 drawn in the
                        entry's figure.
subspace_krems_line.csv : the subspace the days scatter along, as a segment
                        through the origin.
subspace.png          : matplotlib preview (checking only).

Data generated by pythondemos/subspace.py.
"""

# /// script
# requires-python = ">=3.10"
# dependencies = ["matplotlib==3.10.7", "numpy==2.3.4"]
# ///

import json
import urllib.request
from pathlib import Path

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

OUT_DIR = Path(__file__).parent

rng = np.random.default_rng(42)
report = []


def check(name, ok):
    report.append((name, bool(ok)))
    print(f"  [{'ok' if ok else 'FAIL'}] {name}")


def on_line(points, direction, tol=1e-9):
    """Whether every point lies on the line through the origin along
    `direction`: the component across the line vanishes."""
    d = direction / np.linalg.norm(direction)
    across = points - np.outer(points @ d, d)
    return bool(np.all(np.linalg.norm(across, axis=-1) < tol))


# ---- [B-axioms] the three requirements, on a line through the origin
print("[B-axioms] a line through the origin is a subspace of the plane")
x = np.array([2.0, 1.0])                      # the vector that spans U_1
check("[B-axioms] the zero vector lies on the line, at the multiple 0",
      on_line(np.zeros((1, 2)), x))

s = rng.normal(size=500)
t = rng.normal(size=500)
u, v = np.outer(s, x), np.outer(t, x)
check("[B-axioms] a sum of two vectors of the line stays on the line, at "
      "500 pairs drawn at random", on_line(u + v, x))
c = rng.normal(size=500)
check("[B-axioms] a multiple of a vector of the line stays on the line, at "
      "500 numbers drawn at random", on_line(c[:, None] * u, x))
check("[B-axioms] so the line is a vector space under the same operations "
      "as the plane, which is what makes it a subspace", True)
check("[B-axioms] the zero vector alone is a subspace too, the trivial one",
      on_line(np.zeros((1, 2)), x))

# ---- [B-counter] three subsets that are not subspaces
print("[B-counter] three subsets of the plane that are not subspaces")
shifted = np.outer(np.linspace(-2, 2, 50), x) + np.array([0.0, 1.0])
check("[B-counter] a line that misses the origin does not hold the zero "
      "vector", not np.any(np.linalg.norm(shifted, axis=1) < 1e-9))
check("[B-counter] and a sum of two of its vectors leaves it: the sum has "
      "an offset of twice the original",
      not on_line(shifted[:1] + shifted[1:2] - np.array([0.0, 1.0]), x))

# 61 points, so that index 30 sits exactly half a turn from index 0
# and the two are opposite vectors
ang = np.linspace(0, 2 * np.pi, 61)
circle = np.column_stack([np.cos(ang), np.sin(ang)])
norms = np.linalg.norm(circle[:1] + circle[30:31], axis=1)
check("[B-counter] the unit circle holds no zero vector, and the sum of two "
      "opposite vectors of it has norm 0 rather than 1, so the sum leaves "
      "the circle", bool(norms[0] < 1e-9))

quarter = np.abs(rng.normal(size=(200, 2)))
check("[B-counter] the quarter plane with both coordinates nonnegative "
      "holds the zero vector and is closed under addition",
      bool(np.all(quarter >= 0)) and bool(np.all(quarter[:100]
                                                 + quarter[100:] >= 0)))
check("[B-counter] but a negative multiple leaves it, so it is not a "
      "subspace: this is the requirement it breaks",
      bool(np.all((-1.0 * quarter)[quarter > 0] < 0)))

# ---- [B-dimension] the two lines of the entry's figure
print("[B-dimension] the two lines of the entry's figure")
u1 = np.array([2.0, 1.0])                     # U_1, as the figure draws it
u2 = np.array([1.0, -2.0])                    # U_2
B = np.column_stack([u1, u2])
check("[B-dimension] each line has a basis of one vector, so its dimension "
      "is 1", int(np.linalg.matrix_rank(u1.reshape(1, -1))) == 1
      and int(np.linalg.matrix_rank(u2.reshape(1, -1))) == 1)
check("[B-dimension] the two lines are different subspaces: neither "
      "direction is a multiple of the other", not on_line(u2[None, :], u1))
check("[B-dimension] they meet only in the subspace that holds the zero "
      "vector alone, so their intersection has dimension 0",
      abs(np.linalg.det(B)) > 1e-9)
check("[B-dimension] together they span the plane, of dimension 2",
      int(np.linalg.matrix_rank(B)) == 2)
w = rng.normal(size=(200, 2))
coef = np.linalg.solve(B, w.T).T
check("[B-dimension] every vector of the plane is a sum of one vector from "
      "each line, and the two are unique, at 200 vectors drawn at random",
      bool(np.allclose(coef[:, :1] * u1 + coef[:, 1:] * u2, w)))

seg = np.array([-2.2 * u1 / np.linalg.norm(u1),
                2.2 * u1 / np.linalg.norm(u1), [np.nan, np.nan],
                -2.2 * u2 / np.linalg.norm(u2),
                2.2 * u2 / np.linalg.norm(u2)])
np.savetxt(OUT_DIR / "subspace_lines.csv", seg, delimiter=",",
           header="x1,x2", comments="", fmt="%.4f")
counter = np.vstack([shifted, [[np.nan, np.nan]], circle,
                     [[np.nan, np.nan]], quarter[:40]])
np.savetxt(OUT_DIR / "subspace_counter.csv", counter, delimiter=",",
           header="x1,x2", comments="", fmt="%.4f")

# ---- [B-krems] a subspace the weather picks out
print("[B-krems] the 06:00 and the 15:00 (UTC) temperature at Krems, 2024")
URL = ("https://dataset.api.hub.geosphere.at/v1/station/historical/"
       "klima-v2-1h?parameters=tl&station_ids=3805"
       "&start=2024-01-01T00:00&end=2024-12-31T23:00")
CSV = OUT_DIR / "subspace_weather.csv"
try:
    with urllib.request.urlopen(URL, timeout=120) as resp:
        payload = json.load(resp)
    series = payload["features"][0]["properties"]["parameters"]["tl"]["data"]
    byday = {}
    for stamp, value in zip(payload["timestamps"], series):
        if value is None:                  # the archive drops whole days
            continue
        hour = stamp[11:16]                # the stamps are UTC, and so are
        if hour in ("06:00", "15:00"):     # the two times
            byday.setdefault(stamp[:10], {})[hour] = float(value)
    kept = [(d, r["06:00"], r["15:00"])
            for d, r in sorted(byday.items()) if len(r) == 2]
    stamps = [d for d, _, _ in kept]
    X = np.array([[a, b] for _, a, b in kept])
    with open(CSV, "w") as fh:
        fh.write("date,t06,t15\n")
        for day, row in zip(stamps, X):
            fh.write(day + "," + ",".join(f"{v:g}" for v in row) + "\n")
    print(f"    downloaded {len(X)} days with both readings")
except (OSError, KeyError, ValueError) as err:
    print(f"    download failed ({err}); reading {CSV.name}")
    rows = np.genfromtxt(CSV, delimiter=",", skip_header=1, dtype=str)
    stamps = [str(s) for s in rows[:, 0]]
    X = rows[:, 1:].astype(float)

check("[B-krems] 365 of the days of 2024 carry both readings (the hourly "
      "record drops 2024-01-12)", X.shape == (365, 2))
check("[B-krems] the record matches the archive (1 January: 4.0 at 06:00 "
      "and 8.0 at 15:00, both UTC)",
      stamps[0] == "2024-01-01" and bool(np.allclose(X[0], [4.0, 8.0])))

d = np.array([1.0, 1.0]) / np.sqrt(2.0)       # the direction of the line
closest = np.outer(X @ d, d)
left = X - closest
check("[B-krems] the closest point of the line to each day lies on the "
      "line, so it belongs to the subspace", on_line(closest, d, tol=1e-9))
check("[B-krems] what is left over of each day lies on a second line "
      "through the origin, itself a subspace",
      on_line(left, np.array([-1.0, 1.0]), tol=1e-9))
check("[B-krems] the two subspaces meet only in the zero vector: no "
      "leftover vector lies on the first line unless it is zero",
      bool(np.all(np.abs(left @ d) < 1e-9)))
check("[B-krems] each day is the sum of its two parts, one from each "
      "subspace", bool(np.allclose(closest + left, X)))
check(f"[B-krems] the days spread {np.linalg.norm(closest, axis=1).std():.1f} "
      f"degrees along the first subspace against "
      f"{np.linalg.norm(left, axis=1).std():.1f} across it, which is why one "
      "line already describes the record well",
      np.linalg.norm(closest, axis=1).std()
      > 2 * np.linalg.norm(left, axis=1).std())

X_plot = X[::19]                              # 20 of the 365 days
check(f"[B-krems] every 19th day: {len(X_plot)} of the {len(X)} days are "
      "drawn in the entry's figure", len(X_plot) == 20)
np.savetxt(OUT_DIR / "subspace_krems_plot.csv", X_plot, delimiter=",",
           header="t06,t15", comments="", fmt="%.1f")
lim = float(np.abs(X).max()) * 1.05
np.savetxt(OUT_DIR / "subspace_krems_line.csv",
           np.array([-lim * d, lim * d]), delimiter=",",
           header="t06,t15", comments="", fmt="%.2f")

# ---- the preview figure
fig, ax = plt.subplots(1, 2, figsize=(9.4, 4.0))

ax[0].plot(seg[0:2, 0], seg[0:2, 1], linestyle="-", color="black",
           linewidth=1.6, label="$U_1$ (solid line)")
ax[0].plot(seg[3:5, 0], seg[3:5, 1], linestyle="--", color="black",
           linewidth=1.6, label="$U_2$ (dashed line)")
ax[0].plot(circle[:, 0], circle[:, 1], linestyle=":", color="black",
           label="the unit circle, not a subspace (dotted curve)")
ax[0].plot([0], [0], "o", color="black", ms=5)
ax[0].annotate("$\\mathbf{0}$", xy=(0, 0), xytext=(-0.34, 0.18), fontsize=9)
ax[0].set_xlabel("first coordinate")
ax[0].set_ylabel("second coordinate")
ax[0].set_title("(a) two subspaces of the plane, and a subset that is not",
                fontsize=9)
ax[0].set_aspect("equal")
ax[0].legend(frameon=False, fontsize=8, loc="upper left")

ax[1].plot(X_plot[:, 0], X_plot[:, 1], "o", color="black", ms=4.5,
           label="20 of the 365 days (filled circles)")
ax[1].plot([-lim * d[0], lim * d[0]], [-lim * d[1], lim * d[1]],
           linestyle="-", color="black", linewidth=1.4,
           label="the subspace the days follow (solid line)")
for p, q in zip(X_plot[:20], closest[::19][:20]):
    ax[1].plot([p[0], q[0]], [p[1], q[1]], linestyle=":", color="black",
               linewidth=0.8)
ax[1].set_xlim(-2, 32)
ax[1].set_ylim(-2, 36)
ax[1].set_xlabel("06:00 (UTC) reading (°C)")
ax[1].set_ylabel("15:00 (UTC) reading (°C)")
ax[1].set_title("(b) each day splits across two subspaces, Krems 2024",
                fontsize=9)
ax[1].legend(frameon=False, fontsize=8, loc="upper left")

fig.tight_layout()
fig.savefig(OUT_DIR / "subspace.png", dpi=150)

print(f"\n{sum(ok for _, ok in report)}/{len(report)} checks passed")
