"""The spectral decomposition of a symmetric matrix: perpendicular
directions, each scaled by its own real factor.

Purpose
-------
Numerical companion to the glossary entry 'spectraldecomp'.  The demo
recomputes every claim the entry makes about the 2-by-2 matrix of its
opening display,

    A = [[5/2, sqrt(3)/2], [sqrt(3)/2, 3/2]] ,

whose eigenvalues are 3 and 1 and whose eigenvectors sit at 30 and 120
degrees: A maps the unit circle onto an ellipse with its axes along those
two directions and half-lengths 3 and 1.  It then verifies the structural
claims of the entry -- that each outer product u u^T is an orthogonal
projection onto a line, that the two projections annihilate each other and
sum to the identity, and that trace, determinant, spectral norm and rank
are the sum, the product, the largest, and the count of the nonzero
eigenvalues -- and the positive semi-definite square root.  The matrix
[[0, 1], [0, 0]] shows where a non-symmetric matrix fails: it has one
eigenvector up to scale, and the orthogonal complement of that eigenvector
is not invariant, so no basis of eigenvectors exists.  Finally the
decomposition is applied to the sample covariance matrix of a year of
weather at Krems an der Donau, the symmetric positive semi-definite matrix
that principal component analysis decomposes.

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

Blocks
------
[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.
[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.
[B-quantities]  Trace, determinant, spectral norm and rank read off the
                eigenvalues, and the positive semi-definite square root
                squares back to A.
[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.
[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.

Outputs
-------
spectraldecomp_circle.csv  : the unit circle, 181 points.
spectraldecomp_ellipse.csv : its image under A, the same 181 points.
spectraldecomp_axes.csv    : the two eigenvector directions of A, scaled by
                             their eigenvalues, as segments from the origin.
spectraldecomp_weather.csv : date, 06:00 and 15:00 (UTC) temperature of each
                             day of 2024 (committed copy).
spectraldecomp_krems_plot.csv : every 19th of those days, the 20 drawn in
                             the entry's figure.
spectraldecomp_krems_axes.csv : the two principal directions at Krems,
                             scaled by the square root of their eigenvalues.
spectraldecomp.png         : matplotlib preview (checking only).

Data generated by pythondemos/spectraldecomp.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}")


# ---- [B-ellipse] the matrix of the entry's opening display
print("[B-ellipse] the matrix A of the opening display, and the ellipse")
A = np.array([[5 / 2, np.sqrt(3) / 2], [np.sqrt(3) / 2, 3 / 2]])
check("[B-ellipse] A is symmetric", bool(np.allclose(A, A.T)))

lam, U = np.linalg.eigh(A)
order = np.argsort(lam)[::-1]                 # largest eigenvalue first
lam, U = lam[order], U[:, order]
for j in (0, 1):                              # the sign of an eigenvector is
    if U[1, j] < 0:                           # arbitrary; orient both upward
        U[:, j] = -U[:, j]                    # so the angles read 30 and 120
                                              # degrees, as the entry's figure
                                              # draws them
check(f"[B-ellipse] the eigenvalues are {lam[0]:.0f} and {lam[1]:.0f}",
      bool(np.allclose(lam, [3.0, 1.0])))

angles = np.degrees(np.arctan2(U[1], U[0]))
check(f"[B-ellipse] the eigenvectors sit at {angles[0]:.0f} and "
      f"{angles[1]:.0f} degrees",
      bool(np.allclose(np.sort(angles), [30.0, 120.0])))
check("[B-ellipse] the eigenvectors are orthonormal, so U is an orthogonal "
      "matrix", bool(np.allclose(U.T @ U, np.eye(2))))
check("[B-ellipse] A stretches the first eigenvector by 3 and leaves the "
      "second where it is",
      bool(np.allclose(A @ U[:, 0], 3 * U[:, 0]))
      and bool(np.allclose(A @ U[:, 1], U[:, 1])))

theta = np.linspace(0, 2 * np.pi, 181)
circle = np.column_stack([np.cos(theta), np.sin(theta)])
ellipse = circle @ A.T
radii = np.linalg.norm(ellipse, axis=1)
check(f"[B-ellipse] the image of the unit circle reaches out to "
      f"{radii.max():.0f} and in to {radii.min():.0f}, the two eigenvalues",
      bool(np.isclose(radii.max(), 3.0)) and bool(np.isclose(radii.min(), 1.0)))
far = ellipse[np.argmax(radii)]
check("[B-ellipse] the long half-axis of the ellipse points along the first "
      "eigenvector",
      bool(np.isclose(abs(far @ U[:, 0]) / np.linalg.norm(far), 1.0)))

np.savetxt(OUT_DIR / "spectraldecomp_circle.csv", circle, delimiter=",",
           header="x1,x2", comments="", fmt="%.4f")
np.savetxt(OUT_DIR / "spectraldecomp_ellipse.csv", ellipse, delimiter=",",
           header="x1,x2", comments="", fmt="%.4f")
axes = np.array([[0.0, 0.0], lam[0] * U[:, 0], [np.nan, np.nan],
                 [0.0, 0.0], lam[1] * U[:, 1]])
np.savetxt(OUT_DIR / "spectraldecomp_axes.csv", axes, delimiter=",",
           header="x1,x2", comments="", fmt="%.4f")

# ---- [B-projections] the outer products are orthogonal projections
print("[B-projections] each outer product is an orthogonal projection")
P = [np.outer(U[:, j], U[:, j]) for j in (0, 1)]
check("[B-projections] each u u^T is symmetric and idempotent, so it is the "
      "orthogonal projection onto the line through u",
      all(np.allclose(p, p.T) and np.allclose(p @ p, p) for p in P))
check("[B-projections] the two projections annihilate each other",
      bool(np.allclose(P[0] @ P[1], np.zeros((2, 2)))))
check("[B-projections] the two projections sum to the identity",
      bool(np.allclose(P[0] + P[1], np.eye(2))))
recon = lam[0] * P[0] + lam[1] * P[1]
check("[B-projections] the eigenvalue-scaled sum of the projections "
      "reproduces A, which is the spectral decomposition",
      bool(np.allclose(recon, A)))
check("[B-projections] the same decomposition written with matrices, "
      "U diag(lambda) U^T, agrees",
      bool(np.allclose(U @ np.diag(lam) @ U.T, A)))

probe = rng.normal(size=(500, 2))
quad = np.einsum("ij,jk,ik->i", probe, A, probe)
expand = (lam[0] * (probe @ U[:, 0]) ** 2 + lam[1] * (probe @ U[:, 1]) ** 2)
check("[B-projections] at 500 points drawn at random the quadratic form "
      "equals the eigenvalue-weighted sum of the squared components in the "
      "eigenvector basis", bool(np.allclose(quad, expand)))

# ---- [B-quantities] what the eigenvalues decide
print("[B-quantities] trace, determinant, spectral norm, rank, square root")
check(f"[B-quantities] the trace {np.trace(A):.0f} is the sum of the "
      "eigenvalues", bool(np.isclose(np.trace(A), lam.sum())))
check(f"[B-quantities] the determinant {np.linalg.det(A):.0f} is their "
      "product", bool(np.isclose(np.linalg.det(A), lam.prod())))
check(f"[B-quantities] the spectral norm {np.linalg.norm(A, 2):.0f} is the "
      "largest eigenvalue", bool(np.isclose(np.linalg.norm(A, 2), lam[0])))
check("[B-quantities] the rank counts the nonzero eigenvalues",
      int(np.linalg.matrix_rank(A)) == int((np.abs(lam) > 1e-12).sum()))
check("[B-quantities] A is positive semi-definite: no eigenvalue is "
      "negative", bool(lam.min() >= 0))
root = sum(np.sqrt(lam[j]) * P[j] for j in (0, 1))
check("[B-quantities] the positive semi-definite square root squares back "
      "to A", bool(np.allclose(root @ root, A)))
check("[B-quantities] that square root is itself symmetric positive "
      "semi-definite",
      bool(np.allclose(root, root.T))
      and bool(np.linalg.eigvalsh(root).min() >= -1e-12))

# ---- [B-general] where a non-symmetric matrix fails
print("[B-general] the non-symmetric [[0, 1], [0, 0]]")
N = np.array([[0.0, 1.0], [0.0, 0.0]])
check("[B-general] N is not symmetric", not np.allclose(N, N.T))
nval, nvec = np.linalg.eig(N)
check("[B-general] both eigenvalues of N are zero",
      bool(np.allclose(nval, 0.0)))
directions = {tuple(np.round(np.abs(nvec[:, j]), 9)) for j in (0, 1)}
check("[B-general] N has a single eigenvector up to scale, so its "
      "eigenvectors cannot form a basis of the plane", len(directions) == 1)
check("[B-general] the rank of N is 1 while the plane has dimension 2",
      int(np.linalg.matrix_rank(N)) == 1)
e1, e2 = np.array([1.0, 0.0]), np.array([0.0, 1.0])
check("[B-general] e1 spans an invariant line, yet N maps e2, which is "
      "orthogonal to e1, back onto e1: the orthogonal complement is not "
      "invariant",
      bool(np.allclose(N @ e1, 0.0)) and bool(np.allclose(N @ e2, e1)))

# ---- [B-krems] the sample covariance matrix of a year at Krems
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 / "spectraldecomp_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])))

mu = X.mean(axis=0)
C = (X - mu).T @ (X - mu) / len(X)
check("[B-krems] the sample covariance matrix is symmetric",
      bool(np.allclose(C, C.T)))
klam, KU = np.linalg.eigh(C)
korder = np.argsort(klam)[::-1]
klam, KU = klam[korder], KU[:, korder]
for j in (0, 1):
    if KU[0, j] < 0:
        KU[:, j] = -KU[:, j]
check(f"[B-krems] the eigenvalues are {klam[0]:.1f} and {klam[1]:.1f} "
      "squared degrees", bool(np.allclose(np.round(klam, 1), [146.5, 6.9])))
check("[B-krems] both are nonnegative, so the sample covariance matrix is "
      "positive semi-definite", bool(klam.min() >= 0))
check(f"[B-krems] the leading eigenvector is "
      f"({KU[0, 0]:.2f}, {KU[1, 0]:.2f}), the direction in which the two "
      "readings rise together",
      bool(np.allclose(np.round(KU[:, 0], 2), [0.65, 0.76])))
check("[B-krems] the decomposition reproduces the sample covariance matrix",
      bool(np.allclose(KU @ np.diag(klam) @ KU.T, C)))
check(f"[B-krems] the two eigenvalues sum to the trace {np.trace(C):.1f}, "
      "the total variance of the two readings",
      bool(np.isclose(klam.sum(), np.trace(C))))

proj = (X - mu) @ KU
check("[B-krems] in the eigenvector basis the two coordinates are "
      "uncorrelated, which is what the perpendicular directions buy",
      abs(np.corrcoef(proj.T)[0, 1]) < 1e-12)

X_plot = X[::19]                               # 20 of the 365 days, so the
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 / "spectraldecomp_krems_plot.csv", X_plot, delimiter=",",
           header="t06,t15", comments="", fmt="%.1f")
kaxes = np.array([mu - np.sqrt(klam[0]) * KU[:, 0],
                  mu + np.sqrt(klam[0]) * KU[:, 0], [np.nan, np.nan],
                  mu - np.sqrt(klam[1]) * KU[:, 1],
                  mu + np.sqrt(klam[1]) * KU[:, 1]])
np.savetxt(OUT_DIR / "spectraldecomp_krems_axes.csv", kaxes, delimiter=",",
           header="t06,t15", comments="", fmt="%.2f")

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

ax[0].plot(circle[:, 0], circle[:, 1], linestyle="--", color="black",
           label="unit circle (dashed curve)")
ax[0].plot(ellipse[:, 0], ellipse[:, 1], linestyle="-", color="black",
           linewidth=1.6, label="its image under A (solid curve)")
for j, style in ((0, "-"), (1, ":")):
    ax[0].annotate("", xy=tuple(lam[j] * U[:, j]), xytext=(0, 0),
                   arrowprops=dict(arrowstyle="-|>", color="black",
                                   linestyle=style, linewidth=1.2))
ax[0].text(*(lam[0] * U[:, 0] * 1.03), r"$\lambda_1 u^{(1)}$", fontsize=9)
ax[0].text(*(lam[1] * U[:, 1] * 1.12), r"$\lambda_2 u^{(2)}$", fontsize=9,
           ha="right", va="bottom")
ax[0].set_xlabel("first coordinate")
ax[0].set_ylabel("second coordinate")
ax[0].set_title("(a) A scales two perpendicular directions by 3 and 1",
                fontsize=9)
ax[0].set_aspect("equal")
ax[0].legend(frameon=False, fontsize=8, loc="lower right")

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(kaxes[0:2, 0], kaxes[0:2, 1], linestyle="-", color="black",
           linewidth=1.6, label="first principal direction (solid line)")
ax[1].plot(kaxes[3:5, 0], kaxes[3:5, 1], linestyle=":", color="black",
           linewidth=1.6, label="second principal direction (dotted line)")
ax[1].set_xlabel("06:00 (UTC) reading (°C)")
ax[1].set_ylabel("15:00 (UTC) reading (°C)")
ax[1].set_title("(b) the same decomposition at Krems, 2024", fontsize=9)
ax[1].set_aspect("equal")
ax[1].legend(frameon=False, fontsize=8, loc="upper left")

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

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