{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "clustercentroid.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# cluster centroid \u2014 Python demo\n\nNumerical companion to the entry [cluster centroid](https://dictionaryofml.org/terms/clustercentroid.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 'clustercentroid'. The 366 days of 2024 at Krems are data points with the feature vector (morning minimum temperature, maximum daytime temperature). k-means with k = 2 splits them into cold days and warm days, and each cluster is represented by a single vector, its cluster centroid. The demo checks the entry's claims: the centroid is the vector that minimizes the summed loss over the data points of its cluster (the mean under the squared Euclidean distance, the geometric median under the Euclidean distance, the coordinate-wise median under the sum of absolute differences); the nearest-centroid assignment is a linear rule whose boundary is the perpendicular bisector of the two centroids; at the fixed point of Lloyd's algorithm each centroid is the mean of the days nearest to it; one corrupted record moves the mean by its displacement divided by the cluster size and moves either median far less; and the centroid of a soft clustering by a Gaussian mixture model is the mean weighted by the degrees of belonging.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/clustercentroid.py`](https://dictionaryofml.org/terms/clustercentroid.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 clustercentroid.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(), \"clustercentroid.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"The cluster centroid of the cold and of the warm days at Krems an der\nDonau: one vector that stands in for a cluster, under three losses.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'clustercentroid'.  The 366\ndays of 2024 at Krems are data points with the feature vector (morning\nminimum temperature, maximum daytime temperature).  k-means with k = 2\nsplits them into cold days and warm days, and each cluster is\nrepresented by a single vector, its cluster centroid.  The demo checks\nthe entry's claims: the centroid is the vector that minimizes the summed\nloss over the data points of its cluster (the mean under the squared\nEuclidean distance, the geometric median under the Euclidean distance,\nthe coordinate-wise median under the sum of absolute differences); the\nnearest-centroid assignment is a linear rule whose boundary is the\nperpendicular bisector of the two centroids; at the fixed point of\nLloyd's algorithm each centroid is the mean of the days nearest to it;\none corrupted record moves the mean by its displacement divided by the\ncluster size and moves either median far less; and the centroid of a\nsoft clustering by a Gaussian mixture model is the mean weighted by the\ndegrees of belonging.\n\nDeterministic: Lloyd's algorithm starts from the means of the colder\nand of the warmer half of the days, Weiszfeld's iteration from the\nmean, and EM from the k-means centroids.  Self-contained: numpy +\nmatplotlib only; the GeoSphere download falls back to the committed CSV.\n\nBlocks\n------\n[B-data]      Download the daily minimum and maximum temperature of 2024\n              at Krems (GeoSphere station 3805) or read the committed\n              copy; 366 days, no missing value.\n[B-lloyd]     Lloyd's algorithm with k = 2 from the colder and the\n              warmer half of the days: cold days and warm days; at the\n              fixed point each centroid is the mean of the days nearest\n              to it, and the mean is the minimizer of the summed squared\n              Euclidean distance over its cluster.\n[B-assign]    The nearest-centroid assignment equals the sign of a\n              linear function of the feature vector; the boundary is\n              the perpendicular bisector of the two centroids, and a\n              new day is assigned by the same rule.\n[B-losses]    The warm cluster under three losses: mean, geometric\n              median (Weiszfeld's fixed-point iteration), coordinate-\n              wise median; each minimizes its own summed loss, and the\n              geometric median satisfies the zero-sum condition on the\n              unit vectors.\n[B-outlier]   One warm day's maximum replaced by the sentinel 999.9:\n              the mean moves by the displacement over the cluster size,\n              the two medians far less.\n[B-gmm]       EM for a Gaussian mixture model with k = 2 from the\n              k-means centroids: at the fixed point each mean is the\n              degree-of-belonging-weighted mean of all days; with\n              degrees of belonging in {0, 1} the weighted mean is the\n              plain mean.\n[B-plot]      Every 18th day for panel (a), the warm days inside the\n              window of panel (b), the centroids, the boundary line,\n              and the preview figure.\n\nOutputs\n-------\nclustercentroid_weather.csv       : date, tmin, tmax (committed copy).\nclustercentroid_points_plot.csv   : the 21 drawn days with their cluster.\nclustercentroid_kmeans.csv        : the two k-means centroids.\nclustercentroid_boundary.csv      : two points of the boundary line.\nclustercentroid_warm_plot.csv     : the warm days inside the window\n                                    of panel (b).\nclustercentroid_centroids.csv     : the warm cluster's centroid under\n                                    each loss, before and after the\n                                    corrupted record (kind, corrupted).\nclustercentroid_shift.csv         : the mean and its displacement by the\n                                    corrupted record (one arrow).\nclustercentroid.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 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 minimum and maximum temperature of 2024 at Krems (GeoSphere station 3805) or read the committed copy; 366 days, no missing value."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-data] daily minimum and maximum temperature at Krems, 2024\")\nURL = (\"https://dataset.api.hub.geosphere.at/v1/station/historical/\"\n       \"klima-v2-1d?parameters=tlmin,tlmax&station_ids=3805\"\n       \"&start=2024-01-01&end=2024-12-31\")\nCSV = OUT_DIR / \"clustercentroid_weather.csv\"\ntry:\n    with urllib.request.urlopen(URL, timeout=120) as resp:\n        payload = json.load(resp)\n    params = payload[\"features\"][0][\"properties\"][\"parameters\"]\n    records = [(stamp[:10], lo, hi)\n               for stamp, lo, hi in zip(payload[\"timestamps\"],\n                                        params[\"tlmin\"][\"data\"],\n                                        params[\"tlmax\"][\"data\"])]\n    with open(CSV, \"w\") as fh:\n        fh.write(\"date,tmin,tmax\\n\")\n        for day, lo, hi in records:\n            fh.write(f\"{day},{lo},{hi}\\n\")\n    print(f\"    downloaded {len(records)} days\")\nexcept OSError as err:\n    print(f\"    download failed ({err}); reading the committed CSV\")\n    rows = CSV.read_text().strip().splitlines()[1:]\n    records = [(d, float(a), float(b))\n               for d, a, b in (r.split(\",\") for r in rows)]\n\ncheck(\"[B-data] 366 days for 2024\", len(records) == 366)\ncheck(\"[B-data] no day is missing a temperature\",\n      all(lo is not None and hi is not None for _, lo, hi in records))\nX = np.array([[lo, hi] for _, lo, hi in records], dtype=float)\nm = len(X)\n\n\n# ---- the three losses: how poorly a vector w stands in for a day x\ndef sq_euclid(x, w):\n    return np.sum((x - w) ** 2, axis=-1)\n\n\ndef euclid(x, w):\n    return np.sqrt(np.sum((x - w) ** 2, axis=-1))\n\n\ndef manhattan(x, w):\n    return np.sum(np.abs(x - w), axis=-1)\n\n\ndef weiszfeld(pts, iters=1000, tol=1e-12):\n    \"\"\"Weiszfeld's fixed-point iteration for the geometric median,\n    started from the mean; returns the point and the iteration count.\"\"\"\n    w = pts.mean(axis=0)\n    for t in range(1, iters + 1):\n        d = np.sqrt(np.sum((pts - w) ** 2, axis=1))\n        if np.any(d < 1e-12):\n            return pts[np.argmin(d)], t\n        wts = 1.0 / d\n        w_new = (wts[:, None] * pts).sum(axis=0) / wts.sum()\n        if np.max(np.abs(w_new - w)) < tol:\n            return w_new, t\n        w = w_new\n    return w, iters\n\n\ndef nearest(X, W, dist=euclid):\n    \"\"\"Index of the nearest centroid for every data point.\"\"\"\n    return np.argmin(np.stack([dist(X, w) for w in W], axis=1), axis=1)\n\n\ndef lloyd(X, W0, max_iter=500):\n    \"\"\"Lloyd's algorithm from the centroids W0; returns the centroids,\n    the assignment, and the number of iterations until it stops.\"\"\"\n    W = np.array(W0, dtype=float)\n    c = nearest(X, W)\n    for t in range(1, max_iter + 1):\n        W = np.array([X[c == j].mean(axis=0) for j in range(len(W))])\n        c_new = nearest(X, W)\n        if np.array_equal(c_new, c):\n            return W, c, t\n        c = c_new\n    return W, c, max_iter"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-lloyd]** Lloyd's algorithm with k = 2 from the colder and the warmer half of the days: cold days and warm days; at the fixed point each centroid is the mean of the days nearest to it, and the mean is the minimizer of the summed squared Euclidean distance over its cluster."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-lloyd] Lloyd's algorithm with k = 2: cold days and warm days\")\norder = np.argsort(X[:, 0])\nW0 = np.array([X[order[: m // 2]].mean(axis=0),\n               X[order[m // 2:]].mean(axis=0)])\nW, c, n_iter = lloyd(X, W0)\ncold, warm = sorted(range(2), key=lambda j: W[j, 1])\nn_cold, n_warm = int(np.sum(c == cold)), int(np.sum(c == warm))\ncheck(f\"[B-lloyd] stops after {n_iter} iterations; cold days: centroid \"\n      f\"({W[cold, 0]:.1f}, {W[cold, 1]:.1f}) for {n_cold} days; warm days: \"\n      f\"centroid ({W[warm, 0]:.1f}, {W[warm, 1]:.1f}) for {n_warm} days\",\n      n_cold + n_warm == m and W[cold, 1] < W[warm, 1])\ncheck(\"[B-lloyd] at the fixed point each centroid is the mean of the days \"\n      \"nearest to it\",\n      all(np.allclose(W[j], X[c == j].mean(axis=0)) for j in range(2))\n      and np.array_equal(nearest(X, W), c))\nrng = np.random.default_rng(3805)\nwarm_days = X[c == warm]\ncands = W[warm] + rng.normal(size=(2000, 2))\nown = sq_euclid(warm_days, W[warm]).sum()\ncheck(\"[B-lloyd] the mean has the smallest summed squared Euclidean \"\n      \"distance over the warm days among 2000 nearby candidates\",\n      all(sq_euclid(warm_days, v).sum() > own for v in cands))\ncheck(\"[B-lloyd] the deviations of the warm days from their mean sum to \"\n      \"zero (the gradient of the summed squared distance vanishes)\",\n      np.allclose((warm_days - W[warm]).sum(axis=0), 0.0))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-assign]** The nearest-centroid assignment equals the sign of a linear function of the feature vector; the boundary is the perpendicular bisector of the two centroids, and a new day is assigned by the same rule."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-assign] the nearest-centroid rule and its boundary\")\nw1, w2 = W[cold], W[warm]\na = w2 - w1\nb = 0.5 * (np.sum(w2 ** 2) - np.sum(w1 ** 2))\nlinear = (X @ a <= b)                    # True: nearer to the cold centroid\ncheck(\"[B-assign] a day is nearer to the cold centroid exactly when a \"\n      \"linear function of its feature vector is at most a threshold\",\n      np.array_equal(linear, c == cold))\nmid = 0.5 * (w1 + w2)\ncheck(f\"[B-assign] the boundary passes through the midpoint ({mid[0]:.1f}, \"\n      f\"{mid[1]:.1f}) of the centroids and is perpendicular to their \"\n      f\"difference\", abs(mid @ a - b) < 1e-9)\n# two points of the boundary line inside the plotting window\ndirection = np.array([-a[1], a[0]]) / np.linalg.norm(a)\nts = np.linspace(-60, 60, 12001)\nline = mid + ts[:, None] * direction\ninside = (line[:, 0] >= -9) & (line[:, 0] <= 23) & (line[:, 1] >= 0) \\\n    & (line[:, 1] <= 50)\nseg = line[inside][[0, -1]]\nnew_day = np.array([5.0, 18.0])\nnew_c = int(nearest(new_day[None, :], W)[0])\ncheck(f\"[B-assign] a new day with features ({new_day[0]:.0f}, \"\n      f\"{new_day[1]:.0f}) is assigned to the \"\n      f\"{'warm' if new_c == warm else 'cold'} days; its distances to the \"\n      f\"two centroids are {euclid(new_day, W[cold]):.1f} and \"\n      f\"{euclid(new_day, W[warm]):.1f}\",\n      (new_day @ a <= b) == (new_c == cold))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-losses]** The warm cluster under three losses: mean, geometric median (Weiszfeld's fixed-point iteration), coordinate- wise median; each minimizes its own summed loss, and the geometric median satisfies the zero-sum condition on the unit vectors."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-losses] the centroid of the warm days under three losses\")\nmean_w = warm_days.mean(axis=0)\ngm_w, n_weisz = weiszfeld(warm_days)\ncwm_w = np.median(warm_days, axis=0)\ncentroids = {\"mean\": (mean_w, sq_euclid), \"geometric median\": (gm_w, euclid),\n             \"coordinate-wise median\": (cwm_w, manhattan)}\nfor kind, (w, dist) in centroids.items():\n    others = [v for k2, (v, _) in centroids.items() if k2 != kind]\n    check(f\"[B-losses] {kind} ({w[0]:.1f}, {w[1]:.1f}): smallest summed \"\n          f\"loss over the warm days among the three centroids\",\n          all(dist(warm_days, w).sum() <= dist(warm_days, v).sum() + 1e-9\n              for v in others))\nunit = (warm_days - gm_w) / euclid(warm_days, gm_w)[:, None]\ncheck(f\"[B-losses] Weiszfeld's iteration stops after {n_weisz} iterations \"\n      f\"at a point where the unit vectors to the warm days sum to zero \"\n      f\"(norm of the sum {np.linalg.norm(unit.sum(axis=0)):.1e})\",\n      np.linalg.norm(unit.sum(axis=0)) < 1e-6)\ncheck(\"[B-losses] the coordinate-wise median minimizes the summed absolute \"\n      \"difference in each feature separately\",\n      all(np.abs(warm_days[:, j] - cwm_w[j]).sum()\n          <= np.abs(warm_days[:, j] - v).sum() + 1e-9\n          for j in range(2) for v in np.linspace(0, 40, 401)))\ncheck(f\"[B-losses] the three centroids of the warm days lie within \"\n      f\"{max(euclid(mean_w, gm_w), euclid(mean_w, cwm_w)):.1f} degrees of \"\n      f\"each other\", max(euclid(mean_w, gm_w), euclid(mean_w, cwm_w)) < 2)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-outlier]** One warm day's maximum replaced by the sentinel 999.9: the mean moves by the displacement over the cluster size, the two medians far less."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-outlier] one warm day's maximum replaced by the sentinel 999.9\")\nSENTINEL = 999.9\ni_bad = int(np.argmax(warm_days[:, 1]))        # the hottest warm day\nbad = warm_days.copy()\nshift_record = SENTINEL - bad[i_bad, 1]\nbad[i_bad, 1] = SENTINEL\nmean_b = bad.mean(axis=0)\ngm_b, _ = weiszfeld(bad)\ncwm_b = np.median(bad, axis=0)\nmoves = {\"mean\": euclid(mean_b, mean_w),\n         \"geometric median\": euclid(gm_b, gm_w),\n         \"coordinate-wise median\": euclid(cwm_b, cwm_w)}\ncheck(f\"[B-outlier] the mean moves by {moves['mean']:.1f} degrees, which \"\n      f\"is the displacement {shift_record:.1f} of the record divided by \"\n      f\"the cluster size {n_warm}\",\n      abs(moves[\"mean\"] - shift_record / n_warm) < 1e-9)\ncheck(f\"[B-outlier] the geometric median moves by \"\n      f\"{moves['geometric median']:.2f} degrees and the coordinate-wise \"\n      f\"median by {moves['coordinate-wise median']:.2f} degrees, each \"\n      f\"less than a tenth of the move of the mean\",\n      max(moves[\"geometric median\"], moves[\"coordinate-wise median\"])\n      < 0.1 * moves[\"mean\"])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-gmm]** EM for a Gaussian mixture model with k = 2 from the k-means centroids: at the fixed point each mean is the degree-of-belonging-weighted mean of all days; with degrees of belonging in {0, 1} the weighted mean is the plain mean."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def normal_pdf(A, mu, sig):\n    d = A.shape[1]\n    diff = A - mu\n    inv = np.linalg.inv(sig)\n    expo = -0.5 * np.einsum(\"ij,jk,ik->i\", diff, inv, diff)\n    return np.exp(expo) / np.sqrt((2 * np.pi) ** d * np.linalg.det(sig))\n\n\ndef em_gmm(A, mu, iters=5000, tol=1e-9):\n    \"\"\"EM for a GMM started from the means mu, equal probabilities and\n    the covariance of the k-means clusters; returns the parameters, the\n    degrees of belonging, and the iteration count.\"\"\"\n    k = len(mu)\n    lab = nearest(A, mu)\n    sig = np.stack([np.cov(A[lab == j].T) for j in range(k)])\n    pk = np.full(k, 1.0 / k)\n    for t in range(1, iters + 1):\n        joint = np.stack([pk[j] * normal_pdf(A, mu[j], sig[j])\n                          for j in range(k)])\n        dob = joint / joint.sum(axis=0)\n        wgt = dob.sum(axis=1)\n        mu_new = (dob @ A) / wgt[:, None]\n        sig = np.stack([(dob[j][:, None] * (A - mu_new[j])).T\n                        @ (A - mu_new[j]) / wgt[j] for j in range(k)])\n        pk = wgt / len(A)\n        done = np.max(np.abs(mu_new - mu)) < tol\n        mu = mu_new\n        if done:\n            break\n    joint = np.stack([pk[j] * normal_pdf(A, mu[j], sig[j]) for j in range(k)])\n    dob = joint / joint.sum(axis=0)\n    return mu, sig, pk, dob, t\n\n\nprint(\"[B-gmm] EM for a Gaussian mixture model with k = 2\")\nmu, sig, pk, dob, n_em = em_gmm(X, W.copy())\ncheck(\"[B-gmm] the degrees of belonging of each day sum to one\",\n      np.allclose(dob.sum(axis=0), 1.0))\nweighted = (dob @ X) / dob.sum(axis=1)[:, None]\ncheck(f\"[B-gmm] after {n_em} iterations each mean is the degree-of-\"\n      f\"belonging-weighted mean of all {m} days\",\n      np.allclose(mu, weighted, atol=1e-6))\nd_cold = euclid(mu[cold], W[cold])\nd_warm = euclid(mu[warm], W[warm])\ncheck(f\"[B-gmm] GMM means ({mu[cold, 0]:.1f}, {mu[cold, 1]:.1f}) and \"\n      f\"({mu[warm, 0]:.1f}, {mu[warm, 1]:.1f}), {d_cold:.1f} and \"\n      f\"{d_warm:.1f} degrees from the k-means centroids\",\n      max(d_cold, d_warm) < 5)\nn_unsure = int(np.sum((dob.max(axis=0) < 0.8)))\ncheck(f\"[B-gmm] {n_unsure} of the {m} days have no degree of belonging \"\n      f\"above 0.8\", 0 < n_unsure < m // 2)\nhard = np.stack([(c == j).astype(float) for j in range(2)])\ncheck(\"[B-gmm] with degrees of belonging in {0, 1} the weighted mean is \"\n      \"the k-means centroid\",\n      np.allclose((hard @ X) / hard.sum(axis=1)[:, None], W))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-plot]** Every 18th day for panel (a), the warm days inside the window of panel (b), the centroids, the boundary line, and the preview figure."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-plot] thinned days, centroids, boundary\")\nidx = np.arange(0, m, 18)\nwith open(OUT_DIR / \"clustercentroid_points_plot.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax,cluster\\n\")\n    for i in idx:\n        fh.write(f\"{X[i, 0]:.1f},{X[i, 1]:.1f},{int(c[i] == warm)}\\n\")\ncheck(f\"[B-plot] every 18th day: {len(idx)} of the {m} days are drawn in \"\n      f\"panel (a)\", len(idx) == 21)\nwith open(OUT_DIR / \"clustercentroid_boundary.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax\\n\")\n    for p in seg:\n        fh.write(f\"{p[0]:.4f},{p[1]:.4f}\\n\")\nwith open(OUT_DIR / \"clustercentroid_kmeans.csv\", \"w\") as fh:\n    fh.write(\"cluster,tmin,tmax\\n\")\n    for j in (cold, warm):\n        fh.write(f\"{int(j == warm)},{W[j, 0]:.4f},{W[j, 1]:.4f}\\n\")\nWIN = ((12.0, 15.5), (23.5, 33.0))        # the window of panel (b)\nin_win = ((warm_days[:, 0] >= WIN[0][0]) & (warm_days[:, 0] <= WIN[0][1])\n          & (warm_days[:, 1] >= WIN[1][0]) & (warm_days[:, 1] <= WIN[1][1]))\nwidx = np.flatnonzero(in_win)\nwith open(OUT_DIR / \"clustercentroid_warm_plot.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax\\n\")\n    for i in widx:\n        fh.write(f\"{warm_days[i, 0]:.1f},{warm_days[i, 1]:.1f}\\n\")\ncheck(f\"[B-plot] {len(widx)} of the {n_warm} warm days fall inside the \"\n      f\"window of panel (b), {WIN[0][0]} to {WIN[0][1]} degrees by \"\n      f\"{WIN[1][0]} to {WIN[1][1]} degrees; the window contains the \"\n      f\"centroids and the moved mean\",\n      len(widx) <= 25 and all(WIN[0][0] <= w[0] <= WIN[0][1]\n                              and WIN[1][0] <= w[1] <= WIN[1][1]\n                              for w in (mean_w, gm_w, cwm_w, mean_b)))\nrows = [(\"mean\", 0, mean_w), (\"geometric median\", 0, gm_w),\n        (\"coordinate-wise median\", 0, cwm_w), (\"mean\", 1, mean_b),\n        (\"geometric median\", 1, gm_b), (\"coordinate-wise median\", 1, cwm_b)]\nwith open(OUT_DIR / \"clustercentroid_centroids.csv\", \"w\") as fh:\n    fh.write(\"kindid,kind,corrupted,tmin,tmax\\n\")\n    for kid, (kind, corr, w) in enumerate(rows):\n        fh.write(f\"{kid % 3},{kind},{corr},{w[0]:.4f},{w[1]:.4f}\\n\")\nwith open(OUT_DIR / \"clustercentroid_shift.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax,dtmin,dtmax\\n\")\n    fh.write(f\"{mean_w[0]:.4f},{mean_w[1]:.4f},{mean_b[0] - mean_w[0]:.4f},\"\n             f\"{mean_b[1] - mean_w[1]:.4f}\\n\")\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.0))\nfor j, mk, lab in ((cold, \"o\", \"cold days\"), (warm, \"s\", \"warm days\")):\n    sel = idx[c[idx] == j]\n    ax1.scatter(X[sel, 0], X[sel, 1], marker=mk, facecolors=\"none\",\n                edgecolors=\"black\", s=28, label=f\"{lab} (every 18th day)\")\nax1.scatter(W[:, 0], W[:, 1], marker=\"x\", color=\"black\", s=70,\n            label=\"cluster centroids (means)\")\nax1.plot(seg[:, 0], seg[:, 1], \"k--\", lw=0.9,\n         label=\"boundary of the nearest-centroid rule\")\nax1.set_xlim(-9, 23)\nax1.set_ylim(0, 50)\nax1.set_xlabel(\"morning minimum temperature (\u00b0C)\")\nax1.set_ylabel(\"maximum daytime temperature (\u00b0C)\")\nax1.set_title(\"(a) each day is assigned to its nearest centroid\")\nax1.legend(frameon=False, fontsize=7.5, loc=\"upper left\")\nax2.scatter(warm_days[widx, 0], warm_days[widx, 1], marker=\"s\",\n            facecolors=\"none\", edgecolors=\"0.5\", s=24,\n            label=\"warm days inside the window\")\nfor (kind, _, w), mk in zip(rows[:3], (\"x\", \"^\", \"D\")):\n    ax2.scatter(w[0], w[1], marker=mk, color=\"black\", s=60, label=kind)\nax2.annotate(\"\", xy=mean_b, xytext=mean_w,\n             arrowprops=dict(arrowstyle=\"->\", ls=\"--\", color=\"0.3\"))\nax2.scatter(mean_b[0], mean_b[1], marker=\"x\", color=\"0.5\", s=60,\n            label=\"mean after one record is replaced by 999.9\")\nax2.set_xlim(*WIN[0])\nax2.set_ylim(*WIN[1])\nax2.set_xlabel(\"morning minimum temperature (\u00b0C)\")\nax2.set_ylabel(\"maximum daytime temperature (\u00b0C)\")\nax2.set_title(\"(b) the warm cluster's centroid under three losses\")\nax2.legend(frameon=False, fontsize=7.5, loc=\"lower right\")\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"clustercentroid.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)"
  }
 ]
}