"""
samplecovmtx.py — numerical companion to the glossary entry 'sample
covariance matrix'.

The entry defines the sample covariance matrix of a dataset as the
covariance matrix under the empirical distribution, and discusses the
two divisor conventions, 1/m and 1/(m-1). This demo checks both
readings on the daily weather measurements at Krems an der Donau,
measures how the two conventions behave as the number of data points
grows, and checks what the choice does to the eigenvectors.
Self-contained (numpy/matplotlib only, stdlib urllib for the
download), fixed seed.

Blocks
------
[B-krems]   The days of 2020 to 2024 at Krems an der Donau, each a data
            point whose feature vector is the air temperature at 06:00
            and at 15:00 UTC of that day, from the hourly archive; the
            3 days with a missing reading are dropped, 1824 remain. The
            sample covariance
            matrix with the divisor m, and the same sum with the
            divisor m-1: the two differ by the factor m/(m-1), which is
            1.0005 for this dataset.
[B-uniform] The divisor-m version is exactly the covariance matrix of
            the random vector obtained by selecting a data point of the
            dataset uniformly at random, computed here from the uniform
            probability mass function rather than from the formula.
[B-small]   Treating the 1824 days as the population and drawing small
            datasets from it: averaged over many draws, the divisor-m
            version comes out smaller than the population value by the
            factor (m-1)/m, while the divisor-(m-1) version averages to
            the population value. The gap matters for a handful of data
            points and vanishes for many.
[B-axes]    The two conventions differ by a positive scalar factor, so
            they have the same eigenvectors and their eigenvalues
            differ by that factor: the principal directions a
            dimensionality reduction extracts do not depend on the
            choice.

Outputs
-------
samplecovmtx_bias.csv : for each dataset size, the average estimate of
                        the variance of the 06:00 temperature under
                        both conventions, and the population value.
samplecovmtx.png      : preview figure (checking only).

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

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

import json
import urllib.request

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pathlib import Path

OUT_DIR = Path(__file__).parent
ARCHIVE = "https://dataset.api.hub.geosphere.at/v1/station/historical/"
STATION = 3805                      # Krems an der Donau
HOURS = ("06:00", "15:00")          # the two readings of a day (UTC)
SIZES = [2, 3, 5, 8, 12, 20, 35, 60, 100]
NR_REPEAT = 4000
SEED = 20261029
report = []


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


def fetch_days(start, end):
    """The temperature at HOURS on each day with both readings, from the
    hourly archive of the GeoSphere Austria station."""
    url = (f"{ARCHIVE}klima-v2-1h?parameters=tl"
           f"&station_ids={STATION}&start={start}&end={end}")
    with urllib.request.urlopen(url, timeout=300) as resp:
        payload = json.load(resp)
    temp = np.array(payload["features"][0]["properties"]["parameters"]["tl"]
                    ["data"], dtype=float)
    stamps = [t[:16] for t in payload["timestamps"]]
    by_hour = {h: {s[:10]: v for s, v in zip(stamps, temp) if s[11:] == h}
               for h in HOURS}
    dates = sorted(by_hour[HOURS[0]])
    pairs = np.array([[by_hour[h][d] for h in HOURS] for d in dates])
    complete = ~np.isnan(pairs).any(axis=1)
    return pairs[complete], len(dates)


def sample_covmtx(data, divisor):
    """The sum of outer products of the centered rows over `divisor`."""
    centered = data - data.mean(axis=0)
    return centered.T @ centered / divisor


# ---- [B-krems] the dataset and the two conventions
days, nr_dates = fetch_days("2020-01-01T00:00", "2024-12-31T23:00")
m = days.shape[0]
C_m = sample_covmtx(days, m)
C_m1 = sample_covmtx(days, m - 1)
print(f"[B-krems] {nr_dates} days, {nr_dates - m} dropped for a missing "
      f"reading, {m} kept; divisor m gives [[{C_m[0, 0]:.2f}, "
      f"{C_m[0, 1]:.2f}], [{C_m[1, 0]:.2f}, {C_m[1, 1]:.2f}]], divisor m-1 "
      f"gives [[{C_m1[0, 0]:.2f}, {C_m1[0, 1]:.2f}], [{C_m1[1, 0]:.2f}, "
      f"{C_m1[1, 1]:.2f}]]; factor {m / (m - 1):.4f}")
check("[B-krems]   five full years, two leap years; 1824 days carry both "
      "readings", nr_dates == 1827 and m == 1824 and not np.isnan(days).any())
check("[B-krems]   the two conventions differ by exactly the factor m/(m-1)",
      np.allclose(C_m1, C_m * m / (m - 1)))
check("[B-krems]   the divisor-m version matches numpy with bias=True",
      np.allclose(C_m, np.cov(days.T, bias=True)))
check("[B-krems]   and the divisor-(m-1) version is what numpy returns by "
      "default", np.allclose(C_m1, np.cov(days.T)))
check("[B-krems]   both are symmetric and positive semi-definite",
      np.allclose(C_m, C_m.T) and np.all(np.linalg.eigvalsh(C_m) > 0)
      and np.all(np.linalg.eigvalsh(C_m1) > 0))

# ---- [B-uniform] the covariance matrix of a uniformly selected data point
pmf = np.full(m, 1.0 / m)
mean_pmf = pmf @ days
centered_pmf = days - mean_pmf
C_pmf = (centered_pmf * pmf[:, None]).T @ centered_pmf
print(f"[B-uniform] from the uniform pmf: [[{C_pmf[0, 0]:.2f}, "
      f"{C_pmf[0, 1]:.2f}], [{C_pmf[1, 0]:.2f}, {C_pmf[1, 1]:.2f}]]")
check("[B-uniform] the divisor-m version is the covariance matrix of the "
      "random vector drawn uniformly from the dataset",
      np.allclose(C_pmf, C_m))
check("[B-uniform] whose mean vector is the sample mean",
      np.allclose(mean_pmf, days.mean(axis=0)))

# ---- [B-small] what the two conventions do for few data points
rng = np.random.default_rng(SEED)
population = C_m[0, 0]
rows = []
for size in SIZES:
    draw = days[rng.integers(0, m, size=(NR_REPEAT, size)), 0]
    centered = draw - draw.mean(axis=1, keepdims=True)
    sq = np.sum(centered ** 2, axis=1)
    rows.append((size, float(np.mean(sq / size)),
                 float(np.mean(sq / (size - 1))), population))
    print(f"[B-small] size {size:3d}: divisor m gives {rows[-1][1]:6.2f}, "
          f"divisor m-1 gives {rows[-1][2]:6.2f}, population "
          f"{population:6.2f}")
check("[B-small]   the divisor-m version averages to (m-1)/m times the "
      "population variance",
      all(abs(b - (s - 1) / s * population) < 0.06 * population
          for s, b, _, _ in rows))
check("[B-small]   the divisor-(m-1) version averages to the population "
      "variance", all(abs(u - population) < 0.06 * population
                      for _, _, u, _ in rows))
check("[B-small]   for two data points the divisor-m version is half the "
      "population value", abs(rows[0][1] / population - 0.5) < 0.05)
check("[B-small]   and for one hundred the gap is below two percent",
      abs(rows[-1][1] / population - 1.0) < 0.02)
with open(OUT_DIR / "samplecovmtx_bias.csv", "w") as f:
    f.write("size,divisor_m,divisor_m_minus_1,population\n")
    for r in rows:
        f.write(f"{r[0]},{r[1]:.3f},{r[2]:.3f},{r[3]:.3f}\n")
print(f"[B-small] {len(rows)} dataset sizes written")

# ---- [B-axes] the choice does not move the principal directions
val_m, vec_m = np.linalg.eigh(C_m)
val_m1, vec_m1 = np.linalg.eigh(C_m1)
print(f"[B-axes] eigenvalues {val_m[0]:.3f}, {val_m[1]:.3f} against "
      f"{val_m1[0]:.3f}, {val_m1[1]:.3f}")
check("[B-axes]    the two conventions have the same eigenvectors",
      np.allclose(np.abs(vec_m.T @ vec_m1), np.eye(2)))
check("[B-axes]    and their eigenvalues differ by the factor m/(m-1)",
      np.allclose(val_m1, val_m * m / (m - 1)))

# ------------------------------------------------------------- preview
sizes = np.array([r[0] for r in rows], dtype=float)
fig, ax = plt.subplots(figsize=(6.2, 3.9))
ax.plot(sizes, [r[1] for r in rows], "k-o", ms=4,
        label="divisor m")
ax.plot(sizes, [r[2] for r in rows], "k--s", ms=4, mfc="none",
        label="divisor m - 1")
ax.axhline(population, color="0.6", linewidth=2.0,
           label="population value")
ax.set_xscale("log")
ax.set_xlabel("number of data points in the dataset")
ax.set_ylabel("average estimate (squared degrees Celsius)")
ax.set_title("[B-small] the two divisor conventions for few data points",
             fontsize=10)
ax.legend(frameon=False, fontsize=9, loc="lower right")
fig.tight_layout()
fig.savefig(OUT_DIR / "samplecovmtx.png", dpi=110)
print(f"\n{sum(ok for _, ok in report)}/{len(report)} checks passed")
assert all(ok for _, ok in report)
