{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "outlier.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# outlier \u2014 Python demo\n\nNumerical companion to the entry [outlier](https://dictionaryofml.org/terms/outlier.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 'outlier'. The data are the 366 days of 2024 at Krems an der Donau (GeoSphere station 3805), each day a data point with eight daily measurements. The demo recomputes the four numbers the entry states. First, a screen that calls a day unusual when its maximum daytime temperature lies more than two standard deviations from the mean gives one answer under a Gaussian model for the whole year and a different answer under a Gaussian model for the day's calendar month; the two answers disagree on most of the days either flags. Second, a bivariate Gaussian model over the morning minimum and the maximum daytime temperature ranks as the most deviating day of the year a day that neither temperature singles out on its own. Third, the eight measurements are standardized and reduced to two learned features by principal component analysis, in which the wettest day of the year sits far from every other day. Fourth, the wrong reading of one label moves a hypothesis learned by least squares much further than one learned with the absolute error loss, and the precipitation column shows that a deviating value need not be a deviating day at all: no precipitation is coded as -1 mm on 199 of the 366 days.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/outlier.py`](https://dictionaryofml.org/terms/outlier.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 outlier.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(), \"outlier.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"Outliers among the daily weather records of Krems an der Donau: the same\nday is an outlier under one probabilistic model and typical under another,\nand two learned features make the far-out days visible.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'outlier'.  The data are the 366\ndays of 2024 at Krems an der Donau (GeoSphere station 3805), each day a\ndata point with eight daily measurements.  The demo recomputes the four\nnumbers the entry states.  First, a screen that calls a day unusual when\nits maximum daytime temperature lies more than two standard deviations\nfrom the mean gives one answer under a Gaussian model for the whole year\nand a different answer under a Gaussian model for the day's calendar\nmonth; the two answers disagree on most of the days either flags.  Second,\na bivariate Gaussian model over the morning minimum and the maximum\ndaytime temperature ranks as the most deviating day of the year a day that\nneither temperature singles out on its own.  Third, the eight measurements\nare standardized and reduced to two learned features by principal\ncomponent analysis, in which the wettest day of the year sits far from\nevery other day.  Fourth, the wrong reading of one label moves a\nhypothesis learned by least squares much further than one learned with the\nabsolute error loss, and the precipitation column shows that a deviating\nvalue need not be a deviating day at all: no precipitation is coded as\n-1 mm on 199 of the 366 days.\n\nSelf-contained (numpy and matplotlib only), fixed seeds; the GeoSphere\ndownload falls back to the committed CSV.\n\nBlocks\n------\n[B-data]     The 366 days of 2024 at Krems, eight daily measurements per\n             day, no missing cell.\n[B-sentinel] The precipitation column codes no precipitation as -1 mm on\n             199 days: what a plausibility screen flags, and what the\n             code does to the annual total if it is read as an amount.\n[B-model]    The maximum daytime temperature of a day under two Gaussian\n             models, one for the whole year and one for its calendar\n             month, with a two standard deviation screen under each.\n[B-joint]    A bivariate Gaussian model over the morning minimum and the\n             maximum daytime temperature: the squared Mahalanobis\n             distance of each day, against the two per-feature scores.\n[B-learn]    The eight standardized measurements reduced to two learned\n             features by principal component analysis, and the days that\n             sit apart in them.\n[B-loss]     Least squares against the absolute error loss when the label\n             of one day carries a transposed decimal point.\n\nOutputs\n-------\noutlier_weather.csv       : date and the eight measurements (committed).\noutlier_season.csv        : day of year, maximum daytime temperature, and\n                            the two screen bands (year-wide, month-wise).\noutlier_season_marked.csv : the two days the entry names in Fig. 1.\noutlier_scores_plot.csv   : the two learned features of every 18th day,\n                            21 of the 366, for the scatterplot.\noutlier_scores_far.csv    : the two learned features of the three days\n                            farthest from the bulk.\noutlier.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]** The 366 days of 2024 at Krems, eight daily measurements per day, no missing cell."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-data] the 366 days of 2024 at Krems, eight measurements per day\")\nNAMES = [\"tlmin\", \"tlmax\", \"tl_mittel\", \"rr\", \"rf_mittel\", \"so_h\",\n         \"vv_mittel\", \"p_mittel\"]\nURL = (\"https://dataset.api.hub.geosphere.at/v1/station/historical/\"\n       \"klima-v2-1d?parameters=\" + \",\".join(NAMES) +\n       \"&station_ids=3805&start=2024-01-01&end=2024-12-31\")\nCSV = OUT_DIR / \"outlier_weather.csv\"\ntry:\n    with urllib.request.urlopen(URL, timeout=120) as resp:\n        payload = json.load(resp)\n    par = payload[\"features\"][0][\"properties\"][\"parameters\"]\n    dates = [stamp[:10] for stamp in payload[\"timestamps\"]]\n    raw = np.array([par[n][\"data\"] for n in NAMES], dtype=float).T\n    with open(CSV, \"w\") as fh:\n        fh.write(\"date,\" + \",\".join(NAMES) + \"\\n\")\n        for day, row in zip(dates, raw):\n            fh.write(day + \",\" + \",\".join(f\"{v:g}\" for v in row) + \"\\n\")\n    print(f\"    downloaded {len(dates)} days\")\nexcept OSError as err:\n    print(f\"    download failed ({err}); reading the committed CSV\")\n    lines = CSV.read_text().strip().splitlines()[1:]\n    cells = [line.split(\",\") for line in lines]\n    dates = [c[0] for c in cells]\n    raw = np.array([[float(v) for v in c[1:]] for c in cells])\n\nm = len(dates)\ncheck(f\"[B-data] {m} days, {raw.shape[1]} measurements each\", m == 366)\ncheck(\"[B-data] no cell is missing\", bool(np.isfinite(raw).all()))\ntmin = raw[:, NAMES.index(\"tlmin\")]\ntmax = raw[:, NAMES.index(\"tlmax\")]\nrain = raw[:, NAMES.index(\"rr\")]\nmonth = np.array([int(d[5:7]) for d in dates])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-sentinel]** The precipitation column codes no precipitation as -1 mm on 199 days: what a plausibility screen flags, and what the code does to the annual total if it is read as an amount."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-sentinel] the precipitation column codes no precipitation as -1 mm\")\nn_sentinel = int((rain < 0).sum())\ncheck(f\"[B-sentinel] {n_sentinel} of the {m} days carry the code -1 mm, \"\n      f\"{100 * n_sentinel / m:.0f} percent of the year; a screen that \"\n      f\"rejects a negative amount flags every one of them\",\n      n_sentinel == 199)\ncheck(f\"[B-sentinel] the smallest value of the column is {rain.min():g} mm \"\n      f\"and the largest {rain.max():g} mm\", rain.min() == -1.0)\nclean = np.where(rain < 0, 0.0, rain)\ncheck(f\"[B-sentinel] read as an amount, the code lowers the annual total \"\n      f\"from {clean.sum():.1f} mm to {rain.sum():.1f} mm, by \"\n      f\"{clean.sum() - rain.sum():.0f} mm\", clean.sum() > rain.sum())\nz_dry = (-1.0 - rain.mean()) / rain.std()\nz_wet = (rain.max() - rain.mean()) / rain.std()\ncheck(f\"[B-sentinel] a two standard deviation screen on the column as it \"\n      f\"stands does not flag a dry day (score {z_dry:.2f}) but does flag \"\n      f\"the wettest day (score {z_wet:.2f})\", abs(z_dry) < 2 < z_wet)\nwettest = int(np.argmax(rain))\ncheck(f\"[B-sentinel] the wettest day is {dates[wettest]} with \"\n      f\"{rain[wettest]:g} mm\", dates[wettest] == \"2024-09-14\")\nX = raw.copy()\nX[:, NAMES.index(\"rr\")] = clean"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-model]** The maximum daytime temperature of a day under two Gaussian models, one for the whole year and one for its calendar month, with a two standard deviation screen under each."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-model] the same day under a year-wide and a month-wise model\")\ny_mean, y_sd = float(tmax.mean()), float(tmax.std())\nz_year = (tmax - y_mean) / y_sd\nz_month = np.zeros(m)\nmon_mean = np.zeros(m)\nmon_sd = np.zeros(m)\nfor k in range(1, 13):\n    sel = month == k\n    mu, sd = float(tmax[sel].mean()), float(tmax[sel].std())\n    mon_mean[sel], mon_sd[sel] = mu, sd\n    z_month[sel] = (tmax[sel] - mu) / sd\ncheck(f\"[B-model] year-wide model: mean {y_mean:.2f} and standard \"\n      f\"deviation {y_sd:.2f} degrees\", y_sd > 9.0)\nflag_y = np.abs(z_year) > 2.0\nflag_m = np.abs(z_month) > 2.0\nboth = flag_y & flag_m\ncheck(f\"[B-model] a two standard deviation screen flags \"\n      f\"{int(flag_y.sum())} days under the year-wide model and \"\n      f\"{int(flag_m.sum())} under the month-wise model, and only \"\n      f\"{int(both.sum())} day(s) under both\",\n      int(both.sum()) < min(flag_y.sum(), flag_m.sum()))\nj = int(np.argmin(np.where(np.abs(z_year) < 1.0, z_month, 0.0)))\ncheck(f\"[B-model] {dates[j]} has a maximum daytime temperature of \"\n      f\"{tmax[j]:.1f} degrees: score {z_year[j]:+.2f} under the year-wide \"\n      f\"model, {z_month[j]:+.2f} under the model for its month \"\n      f\"(mean {mon_mean[j]:.1f}, standard deviation {mon_sd[j]:.2f}), so \"\n      f\"only the month-wise screen flags it\",\n      abs(z_year[j]) < 1.0 and z_month[j] < -2.0 and flag_m[j] and\n      not flag_y[j])\ni = int(np.argmin(np.where(flag_y & ~flag_m, z_year, 0.0)))\ncheck(f\"[B-model] {dates[i]} runs the other way: {tmax[i]:.1f} degrees, \"\n      f\"the coldest maximum of the year, score {z_year[i]:+.2f} under the \"\n      f\"year-wide model and {z_month[i]:+.2f} under the model for its \"\n      f\"month (mean {mon_mean[i]:.1f}, standard deviation \"\n      f\"{mon_sd[i]:.2f}), so only the year-wide screen flags it\",\n      flag_y[i] and not flag_m[i] and tmax[i] == tmax.min())\ncheck(f\"[B-model] {int((flag_y | flag_m).sum())} days are flagged by at \"\n      f\"least one of the two screens and only {dates[int(np.argmax(both))]} \"\n      f\"by both\", int((flag_y | flag_m).sum()) == 12)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-joint]** A bivariate Gaussian model over the morning minimum and the maximum daytime temperature: the squared Mahalanobis distance of each day, against the two per-feature scores."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-joint] a bivariate Gaussian model over the two temperatures\")\nT = np.column_stack([tmin, tmax])\nt_mean = T.mean(axis=0)\nt_cov = np.cov(T.T, bias=True)\ncorr = t_cov[0, 1] / np.sqrt(t_cov[0, 0] * t_cov[1, 1])\ndev = T - t_mean\nmaha = np.einsum(\"ij,jk,ik->i\", dev, np.linalg.inv(t_cov), dev)\nper_feature = np.abs(dev) / np.sqrt(np.diag(t_cov))\ncheck(f\"[B-joint] the two temperatures have correlation {corr:.3f}, so the \"\n      f\"model expects them to rise and fall together\", corr > 0.8)\nf = int(np.argmax(maha))\ncheck(f\"[B-joint] the largest squared Mahalanobis distance of the year, \"\n      f\"{maha[f]:.1f}, belongs to {dates[f]}: morning minimum \"\n      f\"{tmin[f]:.1f}, maximum {tmax[f]:.1f} degrees\", maha[f] > 6.0)\ncheck(f\"[B-joint] on that day neither temperature is unusual on its own: \"\n      f\"per-feature scores {per_feature[f, 0]:.2f} and \"\n      f\"{per_feature[f, 1]:.2f}, both below 1\",\n      per_feature[f].max() < 1.0)\ncheck(f\"[B-joint] its daily range of {tmax[f] - tmin[f]:.1f} degrees is \"\n      f\"the {int((tmax - tmin > tmax[f] - tmin[f]).sum()) + 1}-largest of \"\n      f\"the {m} days\", tmax[f] - tmin[f] > 20.0)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-learn]** The eight standardized measurements reduced to two learned features by principal component analysis, and the days that sit apart in them."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-learn] the eight measurements reduced to two learned features\")\nZ = (X - X.mean(axis=0)) / X.std(axis=0)\ncov = Z.T @ Z / m\nevals, evecs = np.linalg.eigh(cov)\norder = np.argsort(evals)[::-1]\nevals, evecs = evals[order], evecs[:, order]\nscores = Z @ evecs[:, :2]\nkept = evals[:2].sum() / evals.sum()\ncheck(f\"[B-learn] the two learned features keep {100 * kept:.1f} percent \"\n      f\"of the variance of the eight standardized measurements\",\n      0.6 < kept < 0.7)\ncheck(\"[B-learn] the first learned feature is a temperature direction \"\n      f\"(largest weight on {NAMES[int(np.argmax(np.abs(evecs[:, 0])))]}), \"\n      f\"the second a wetness direction (largest weight on \"\n      f\"{NAMES[int(np.argmax(np.abs(evecs[:, 1])))]})\",\n      NAMES[int(np.argmax(np.abs(evecs[:, 1])))] == \"rr\")\n# squared distance from the bulk in the plane of the two learned features\nr2 = (scores ** 2 / evals[:2]).sum(axis=1)\nfar = np.argsort(r2)[::-1][:3]\ncheck(f\"[B-learn] the farthest day in the two learned features is \"\n      f\"{dates[far[0]]} at squared distance {r2[far[0]]:.1f}, against \"\n      f\"{r2[far[1]]:.1f} for {dates[far[1]]} and {r2[far[2]]:.1f} for \"\n      f\"{dates[far[2]]}\", r2[far[0]] > 2 * r2[far[1]])\ncheck(f\"[B-learn] that day is the wettest day {dates[wettest]}, which the \"\n      f\"screen on the precipitation column also flags\",\n      far[0] == wettest)\ncheck(f\"[B-learn] the remaining {m - 3} days all sit at squared distance \"\n      f\"below {np.sort(r2)[-4]:.1f}\", np.sort(r2)[-4] < r2[far[2]])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-loss]** Least squares against the absolute error loss when the label of one day carries a transposed decimal point."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-loss] least squares against the absolute error loss\")\nA = np.column_stack([np.ones(m), tmin])\n\n\ndef least_squares(labels):\n    return np.linalg.lstsq(A, labels, rcond=None)[0]\n\n\ndef least_abs_dev(labels):\n    \"\"\"Exact minimizer of the average absolute error loss over a line.\n\n    An optimal line through two of the data points always exists, so the\n    minimum over all pairs is the minimum over all lines.\n    \"\"\"\n    best, best_val = None, np.inf\n    for a in range(m):\n        for b in range(a + 1, m):\n            if tmin[a] == tmin[b]:\n                continue\n            slope = (labels[b] - labels[a]) / (tmin[b] - tmin[a])\n            inter = labels[a] - slope * tmin[a]\n            val = np.abs(labels - (inter + slope * tmin)).mean()\n            if val < best_val - 1e-12:\n                best, best_val = (inter, slope), val\n    return np.array(best)\n\n\nw_ls = least_squares(tmax)\nw_ad = least_abs_dev(tmax)\ncheck(f\"[B-loss] on the record as it stands, least squares learns \"\n      f\"h(x) = {w_ls[0]:.2f} + {w_ls[1]:.3f} x and the absolute error loss \"\n      f\"h(x) = {w_ad[0]:.2f} + {w_ad[1]:.3f} x\",\n      abs(w_ls[1] - w_ad[1]) < 0.1)\ncold = int(np.argmin(tmin))\nspoiled = tmax.copy()\nspoiled[cold] = tmax[cold] * 10.0            # 3.5 degrees typed as 35\nv_ls = least_squares(spoiled)\nv_ad = least_abs_dev(spoiled)\nmove_ls = float(np.max(np.abs(A @ v_ls - A @ w_ls)))\nmove_ad = float(np.max(np.abs(A @ v_ad - A @ w_ad)))\ncheck(f\"[B-loss] the coldest day {dates[cold]} has morning minimum \"\n      f\"{tmin[cold]:.1f} and maximum {tmax[cold]:.1f} degrees; recorded as \"\n      f\"{spoiled[cold]:.1f}, it is the warmest reading of the year\",\n      spoiled[cold] > tmax.max())\ncheck(f\"[B-loss] that one wrong label moves the predictions of the \"\n      f\"hypothesis learned by least squares by up to {move_ls:.2f} degrees \"\n      f\"and leaves the one learned with the absolute error loss unchanged \"\n      f\"(by {move_ad:.2f} degrees)\", move_ls > 0.5 and move_ad < 1e-9)\nhuge = tmax.copy()\nhuge[cold] = 1000.0\nu_ls = least_squares(huge)\nu_ad = least_abs_dev(huge)\ncheck(f\"[B-loss] pushing the same label to 1000 degrees moves least \"\n      f\"squares by {np.max(np.abs(A @ u_ls - A @ w_ls)):.1f} degrees, while \"\n      f\"the hypothesis learned with the absolute error loss is still the \"\n      f\"one learned from the correct record \"\n      f\"({np.max(np.abs(A @ u_ad - A @ w_ad)):.2f} degrees)\",\n      np.max(np.abs(A @ u_ad - A @ w_ad)) < 1e-9)\n\n# ---- CSVs for the figures\ndoy = np.arange(1, m + 1)\nwith open(OUT_DIR / \"outlier_season.csv\", \"w\") as fh:\n    fh.write(\"doy,tmax,mlo,mhi,ylo,yhi\\n\")\n    for t in range(m):\n        fh.write(f\"{doy[t]},{tmax[t]:.1f},{mon_mean[t] - 2 * mon_sd[t]:.3f},\"\n                 f\"{mon_mean[t] + 2 * mon_sd[t]:.3f},\"\n                 f\"{y_mean - 2 * y_sd:.3f},{y_mean + 2 * y_sd:.3f}\\n\")\nwith open(OUT_DIR / \"outlier_season_marked.csv\", \"w\") as fh:\n    fh.write(\"doy,tmax,label\\n\")\n    for t in (j, i):\n        fh.write(f\"{doy[t]},{tmax[t]:.1f},{dates[t]}\\n\")\nthin = np.arange(0, m, 18)                   # every 18th day, 21 of the 366\nwith open(OUT_DIR / \"outlier_scores_plot.csv\", \"w\") as fh:\n    fh.write(\"z1,z2,date\\n\")\n    for t in thin:\n        fh.write(f\"{scores[t, 0]:.4f},{scores[t, 1]:.4f},{dates[t]}\\n\")\nwith open(OUT_DIR / \"outlier_scores_far.csv\", \"w\") as fh:\n    fh.write(\"z1,z2,date\\n\")\n    for t in far:\n        fh.write(f\"{scores[t, 0]:.4f},{scores[t, 1]:.4f},{dates[t]}\\n\")\ncheck(f\"[B-learn] the scatterplot CSV thins the year to every 18th day, \"\n      f\"{len(thin)} of the {m}, and the three far days are kept separately\",\n      len(thin) == 21)\n\n# ---- preview\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.0))\nax1.plot(doy, tmax, color=\"0.6\", lw=0.7, ls=\"-\",\n         label=\"maximum daytime temperature (solid curve)\")\nax1.step(doy, mon_mean + 2 * mon_sd, where=\"mid\", color=\"black\", lw=1.1,\n         ls=\":\", label=\"month-wise band (dotted curves)\")\nax1.step(doy, mon_mean - 2 * mon_sd, where=\"mid\", color=\"black\", lw=1.1,\n         ls=\":\")\nax1.axhline(y_mean + 2 * y_sd, color=\"black\", ls=\"--\", lw=1.0,\n            label=\"year-wide band (dashed lines)\")\nax1.axhline(y_mean - 2 * y_sd, color=\"black\", ls=\"--\", lw=1.0)\nax1.plot(doy[[j, i]], tmax[[j, i]], \"ko\", ms=6,\n         label=\"the two days named (filled circles)\")\nax1.set_xlabel(\"day of 2024\")\nax1.set_ylabel(\"maximum daytime temperature (degrees)\")\nax1.set_title(\"the same record under two models\")\nax1.legend(frameon=False, fontsize=7, loc=\"lower center\")\nax2.plot(scores[thin, 0], scores[thin, 1], \"ko\", ms=4, mfc=\"none\",\n         label=\"every 18th day, 21 of 366 (open circles)\")\nax2.plot(scores[far, 0], scores[far, 1], \"kx\", ms=8, mew=1.6,\n         label=\"the three days farthest from the bulk (crosses)\")\nfor t in far:\n    ax2.annotate(dates[t], (scores[t, 0], scores[t, 1]), fontsize=7,\n                 textcoords=\"offset points\", xytext=(6, -2))\nax2.set_xlabel(\"first learned feature $z_1$ (temperature)\")\nax2.set_ylabel(\"second learned feature $z_2$ (wetness)\")\nax2.set_title(\"two learned features, then look\")\nax2.legend(frameon=False, fontsize=7, loc=\"upper left\")\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"outlier.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)"
  }
 ]
}