{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "mvndist.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# multivariate normal distribution \u2014 Python demo\n\nNumerical companion to the entry [multivariate normal distribution](https://dictionaryofml.org/terms/mvndist.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 'mvndist'. The 366 days of 2024 at Krems are data points with the feature vector (morning minimum temperature, maximum daytime temperature). A multivariate normal distribution is fitted to them by maximum likelihood: its mean vector is the sample mean and its covariance matrix the sample covariance matrix (divisor m). The level sets of the probability density function are ellipses centered at the mean vector, with axes along the eigenvectors of the covariance matrix and half-axes proportional to the square roots of its eigenvalues.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/mvndist.py`](https://dictionaryofml.org/terms/mvndist.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 mvndist.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(), \"mvndist.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"The multivariate normal distribution learned from the days of one year\nat Krems an der Donau: the maximum likelihood estimate of its mean vector\nand covariance matrix, its elliptical level sets, and how many days the\nlevel sets hold against the Gaussian prediction.\n\nPurpose\n-------\nNumerical companion to the glossary entry 'mvndist'.  The 366 days of\n2024 at Krems are data points with the feature vector (morning minimum\ntemperature, maximum daytime temperature).  A multivariate normal\ndistribution is fitted to them by maximum likelihood: its mean vector is\nthe sample mean and its covariance matrix the sample covariance matrix\n(divisor m).  The level sets of the probability density function are\nellipses centered at the mean vector, with axes along the eigenvectors\nof the covariance matrix and half-axes proportional to the square roots\nof its eigenvalues.\n\nThe demo checks the entry's claims: the sample mean and the sample\ncovariance matrix maximize the likelihood; the density integrates to\none and is constant on each ellipse; a Gaussian random vector lies\ninside the level set at c = 1 with probability 1 - exp(-1/2) and inside\nthe level set at c = 2 with probability 1 - exp(-2); the days at Krems\ndeviate from these fractions, because the seasons spread them along the\nmajor axis more evenly than a Gaussian would; an affine map of a Gaussian\nrandom vector is Gaussian, so the daily temperature range has the mean\nand variance the formula predicts; and the conditional distribution of\nthe maximum given the minimum is Gaussian with the mean of the least\nsquares line and a variance that does not depend on the minimum.\n\nDeterministic: the Monte Carlo check of the Gaussian fractions draws\nwith a fixed seed.  Self-contained: numpy + matplotlib only; the\nGeoSphere 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-mle]       The sample mean and the sample covariance matrix (divisor\n              m) are the maximum likelihood estimates: the average log\n              density of the days is largest there.\n[B-density]   The probability density function with these parameters\n              integrates to one over the plane.\n[B-ellipse]   The level sets at c = 1 and c = 2 are ellipses centered at\n              the mean vector; their axes are the eigenvectors of the\n              covariance matrix, their half-axes c times the square\n              roots of the eigenvalues, and the density is constant on\n              each of them.\n[B-coverage]  Fraction of the 366 days inside the level sets at c = 1,\n              2, 3 against the Gaussian prediction 1 - exp(-c^2/2),\n              which a Monte Carlo draw from the fitted distribution\n              confirms.\n[B-linear]    The daily temperature range, an affine map of the feature\n              vector, has mean a^T mu and variance a^T C a; the\n              conditional distribution of the maximum given the minimum\n              has the mean of the least squares line and the variance\n              C22 - C12^2 / C11; the range appended as a third feature\n              gives a singular covariance matrix.\n[B-plot]      Every 18th day for the figure (21 of 366 days), the two\n              ellipses with their axes, the mean vector, and the\n              coverage curve.\n\nOutputs\n-------\nmvndist_weather.csv    : date, tmin, tmax (committed copy).\nmvndist_days_plot.csv  : the 21 drawn days.\nmvndist_mean.csv       : the mean vector, one row.\nmvndist_ellipse1.csv   : the level set at c = 1 as a closed polyline.\nmvndist_ellipse2.csv   : the level set at c = 2 as a closed polyline.\nmvndist_axis1.csv      : the major axis of the level set at c = 2.\nmvndist_axis2.csv      : the minor axis of the level set at c = 2.\nmvndist_coverage.csv   : c, fraction of the days inside the level set\n                         at c, and the Gaussian prediction.\nmvndist.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\nSEED = 20261119\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 / \"mvndist_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, d = X.shape\n\n\n# ---- the probability density function of N(mu, C) on R^d\ndef log_density(x, mu, C):\n    \"\"\"Logarithm of the density of N(mu, C) at the rows of x.\"\"\"\n    diff = x - mu\n    C_inv = np.linalg.inv(C)\n    quad = np.einsum(\"ij,jk,ik->i\", diff, C_inv, diff)\n    _, logdet = np.linalg.slogdet(C)\n    return -0.5 * (d * np.log(2 * np.pi) + logdet + quad)\n\n\ndef mahalanobis_sq(x, mu, C):\n    \"\"\"The quadratic form (x - mu)^T C^{-1} (x - mu) at the rows of x.\"\"\"\n    diff = x - mu\n    return np.einsum(\"ij,jk,ik->i\", diff, np.linalg.inv(C), diff)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-mle]** The sample mean and the sample covariance matrix (divisor m) are the maximum likelihood estimates: the average log density of the days is largest there."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-mle] maximum likelihood estimates of the mean vector and the \"\n      \"covariance matrix\")\nmu_hat = X.mean(axis=0)\nC_hat = (X - mu_hat).T @ (X - mu_hat) / m\navg_loglik = log_density(X, mu_hat, C_hat).mean()\nrng = np.random.default_rng(SEED)\nworse = 0\nfor _ in range(400):\n    mu_try = mu_hat + rng.normal(scale=0.5, size=d)\n    E = rng.normal(scale=0.08, size=(d, d))\n    E = (E + E.T) / 2\n    C_try = C_hat + E @ C_hat + C_hat @ E   # a symmetric perturbation\n    if np.all(np.linalg.eigvalsh(C_try) > 0):\n        worse += log_density(X, mu_try, C_try).mean() < avg_loglik\n    else:\n        worse += 1\ncheck(f\"[B-mle] mean vector ({mu_hat[0]:.1f}, {mu_hat[1]:.1f}) degrees \"\n      f\"Celsius: the sample mean of the {m} days\",\n      np.allclose(mu_hat, X.sum(axis=0) / m))\ncheck(f\"[B-mle] covariance matrix: variances {C_hat[0, 0]:.1f} and \"\n      f\"{C_hat[1, 1]:.1f}, covariance {C_hat[0, 1]:.1f} (squared degrees); \"\n      f\"divisor m, so {m / (m - 1):.4f} times smaller than the unbiased \"\n      f\"version\", np.allclose(C_hat, np.cov(X.T, bias=True)))\ncheck(f\"[B-mle] the average log density {avg_loglik:.3f} at these \"\n      f\"parameters exceeds it at all 400 perturbed parameter pairs\",\n      worse == 400)\ncorr = C_hat[0, 1] / np.sqrt(C_hat[0, 0] * C_hat[1, 1])\ncheck(f\"[B-mle] correlation coefficient of minimum and maximum \"\n      f\"temperature {corr:.2f}\", 0.8 < corr < 0.95)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-density]** The probability density function with these parameters integrates to one over the plane."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-density] the probability density function integrates to one\")\ng1 = np.linspace(mu_hat[0] - 80, mu_hat[0] + 80, 1601)\ng2 = np.linspace(mu_hat[1] - 90, mu_hat[1] + 90, 1801)\nG1, G2 = np.meshgrid(g1, g2, indexing=\"ij\")\ngrid = np.column_stack([G1.ravel(), G2.ravel()])\ndens = np.exp(log_density(grid, mu_hat, C_hat)).reshape(G1.shape)\nintegral = np.trapezoid(np.trapezoid(dens, g2, axis=1), g1)\ncheck(f\"[B-density] integral over the plane {integral:.5f}\",\n      abs(integral - 1) < 1e-4)\npeak = 1 / (2 * np.pi * np.sqrt(np.linalg.det(C_hat)))\ncheck(f\"[B-density] the density is largest at the mean vector, \"\n      f\"{peak:.5f} per squared degree\",\n      np.isclose(np.exp(log_density(mu_hat[None], mu_hat, C_hat))[0], peak)\n      and dens.max() <= peak + 1e-12)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-ellipse]** The level sets at c = 1 and c = 2 are ellipses centered at the mean vector; their axes are the eigenvectors of the covariance matrix, their half-axes c times the square roots of the eigenvalues, and the density is constant on each of them."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-ellipse] level sets of the density at c = 1 and c = 2\")\nlam, V = np.linalg.eigh(C_hat)\norder = np.argsort(lam)[::-1]\nlam, V = lam[order], V[:, order]\nif V[0, 0] < 0:\n    V[:, 0] = -V[:, 0]\nif V[1, 1] < 0:\n    V[:, 1] = -V[:, 1]\ncheck(f\"[B-ellipse] eigenvalues {lam[0]:.1f} and {lam[1]:.1f} squared \"\n      f\"degrees; eigenvector of the larger one ({V[0, 0]:.2f}, \"\n      f\"{V[1, 0]:.2f}), at {np.degrees(np.arctan2(V[1, 0], V[0, 0])):.1f} \"\n      f\"degrees to the horizontal axis\",\n      np.allclose(V @ np.diag(lam) @ V.T, C_hat) and lam[1] > 0)\ntheta = np.linspace(0, 2 * np.pi, 361)\ncircle = np.column_stack([np.cos(theta), np.sin(theta)])\n\n\ndef level_set(c):\n    \"\"\"The ellipse {x : (x - mu)^T C^{-1} (x - mu) = c^2} as a polyline.\"\"\"\n    return mu_hat + c * circle @ (V * np.sqrt(lam)).T\n\n\nellipses = {c: level_set(c) for c in (1, 2)}\nfor c, pts in ellipses.items():\n    md = mahalanobis_sq(pts, mu_hat, C_hat)\n    val = np.exp(log_density(pts, mu_hat, C_hat))\n    check(f\"[B-ellipse] c = {c}: every point of the ellipse has quadratic \"\n          f\"form {c}^2 and the density is constant on it, \"\n          f\"{val.mean() / peak:.3f} of its peak value\",\n          np.allclose(md, c ** 2) and np.ptp(val) < 1e-12\n          and np.isclose(val.mean() / peak, np.exp(-c ** 2 / 2)))\nhalf = 2 * np.sqrt(lam)\ncheck(f\"[B-ellipse] c = 2: half-axes {half[0]:.1f} and {half[1]:.1f} \"\n      f\"degrees along the two eigenvectors\",\n      np.allclose(np.linalg.norm(level_set(2)[[0, 90]] - mu_hat, axis=1),\n                  half))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-coverage]** Fraction of the 366 days inside the level sets at c = 1, 2, 3 against the Gaussian prediction 1 - exp(-c^2/2), which a Monte Carlo draw from the fitted distribution confirms."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-coverage] fraction of the days inside the level sets\")\nd2 = mahalanobis_sq(X, mu_hat, C_hat)\nrng = np.random.default_rng(SEED)\nZ = rng.standard_normal((1_000_000, d))\nY = mu_hat + Z @ (V * np.sqrt(lam)).T\nd2_gauss = mahalanobis_sq(Y, mu_hat, C_hat)\nshares = {}\nfor c in (1, 2, 3):\n    gauss = 1 - np.exp(-c ** 2 / 2)\n    mc = np.mean(d2_gauss <= c ** 2)\n    shares[c] = float(np.mean(d2 <= c ** 2))\n    check(f\"[B-coverage] c = {c}: a Gaussian random vector lies inside \"\n          f\"with probability 1 - exp(-{c}^2/2) = {100 * gauss:.1f} percent \"\n          f\"(Monte Carlo {100 * mc:.1f})\", abs(mc - gauss) < 2e-3)\ncheck(f\"[B-coverage] days inside: c = 1: {100 * shares[1]:.1f} percent \"\n      f\"(Gaussian 39.3); c = 2: {100 * shares[2]:.1f} percent (86.5); \"\n      f\"c = 3: {100 * shares[3]:.1f} percent (98.9)\",\n      shares[1] < 1 - np.exp(-0.5) and shares[2] > 1 - np.exp(-2)\n      and shares[3] == 1.0)\n# the days spread along the major axis more evenly than a Gaussian: the\n# share within one standard deviation of the mean along that axis\nproj = (X - mu_hat) @ V[:, 0] / np.sqrt(lam[0])\nwithin = np.mean(np.abs(proj) <= 1)\ncheck(f\"[B-coverage] along the major axis, {100 * within:.1f} percent of \"\n      f\"the days lie within one standard deviation of the mean, against \"\n      f\"68.3 for a Gaussian\", within < 0.683)\ncheck(f\"[B-coverage] no day has quadratic form above {d2.max():.2f}; \"\n      f\"a Gaussian random vector exceeds 9 with probability 1.1 percent\",\n      d2.max() < 9)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-linear]** The daily temperature range, an affine map of the feature vector, has mean a^T mu and variance a^T C a; the conditional distribution of the maximum given the minimum has the mean of the least squares line and the variance C22 - C12^2 / C11; the range appended as a third feature gives a singular covariance matrix."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-linear] an affine map of the feature vector, and conditioning\")\na = np.array([-1.0, 1.0])              # the daily temperature range\nrng_days = X @ a\ncheck(f\"[B-linear] daily range tmax - tmin: mean a^T mu = {a @ mu_hat:.1f} \"\n      f\"and variance a^T C a = {a @ C_hat @ a:.1f} equal the sample mean \"\n      f\"and variance of the 366 ranges\",\n      np.isclose(a @ mu_hat, rng_days.mean())\n      and np.isclose(a @ C_hat @ a, rng_days.var()))\nslope = C_hat[0, 1] / C_hat[0, 0]\nintercept = mu_hat[1] - slope * mu_hat[0]\ncond_var = C_hat[1, 1] - C_hat[0, 1] ** 2 / C_hat[0, 0]\nA = np.column_stack([np.ones(m), X[:, 0]])\nw_ls, *_ = np.linalg.lstsq(A, X[:, 1], rcond=None)\nresid = X[:, 1] - A @ w_ls\ncheck(f\"[B-linear] conditional mean of tmax given tmin: slope \"\n      f\"C12/C11 = {slope:.2f}, intercept {intercept:.1f}; the least \"\n      f\"squares line through the 366 days has the same coefficients\",\n      np.allclose([intercept, slope], w_ls))\ncheck(f\"[B-linear] conditional variance C22 - C12^2/C11 = {cond_var:.1f} \"\n      f\"squared degrees (standard deviation {np.sqrt(cond_var):.1f}): the \"\n      f\"mean squared residual of the least squares line\",\n      np.isclose(cond_var, np.mean(resid ** 2)))\nX3 = np.column_stack([X, rng_days])          # the range as a third feature\nC3 = np.cov(X3.T, bias=True)\ncheck(f\"[B-linear] with the range appended as a third feature, the \"\n      f\"covariance matrix has rank {np.linalg.matrix_rank(C3)} < 3 and \"\n      f\"determinant {np.linalg.det(C3):.1e}: singular, no density on R^3\",\n      np.linalg.matrix_rank(C3) == 2 and abs(np.linalg.det(C3)) < 1e-6)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-plot]** Every 18th day for the figure (21 of 366 days), the two ellipses with their axes, the mean vector, and the coverage curve."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "print(\"[B-plot] thinned scatter, ellipses, axes, mean, coverage curve\")\nidx = np.arange(0, m, 18)\nwith open(OUT_DIR / \"mvndist_days_plot.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax\\n\")\n    for i in idx:\n        fh.write(f\"{X[i, 0]:.1f},{X[i, 1]:.1f}\\n\")\ncheck(f\"[B-plot] every 18th day: {len(idx)} of the {m} days are drawn\",\n      len(idx) == 21)\nwith open(OUT_DIR / \"mvndist_mean.csv\", \"w\") as fh:\n    fh.write(\"tmin,tmax\\n\")\n    fh.write(f\"{mu_hat[0]:.4f},{mu_hat[1]:.4f}\\n\")\nfor c, pts in ellipses.items():\n    with open(OUT_DIR / f\"mvndist_ellipse{c}.csv\", \"w\") as fh:\n        fh.write(\"tmin,tmax\\n\")\n        for p in pts:\n            fh.write(f\"{p[0]:.4f},{p[1]:.4f}\\n\")\nfor j in (0, 1):\n    ends = np.array([mu_hat - half[j] * V[:, j], mu_hat + half[j] * V[:, j]])\n    with open(OUT_DIR / f\"mvndist_axis{j + 1}.csv\", \"w\") as fh:\n        fh.write(\"tmin,tmax\\n\")\n        for p in ends:\n            fh.write(f\"{p[0]:.4f},{p[1]:.4f}\\n\")\ncs = np.arange(0, 3.51, 0.05)\nwith open(OUT_DIR / \"mvndist_coverage.csv\", \"w\") as fh:\n    fh.write(\"c,days,gauss\\n\")\n    for c in cs:\n        fh.write(f\"{c:.2f},{np.mean(d2 <= c ** 2):.4f},\"\n                 f\"{1 - np.exp(-c ** 2 / 2):.4f}\\n\")\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.2))\nax1.scatter(X[idx, 0], X[idx, 1], marker=\"o\", facecolors=\"none\",\n            edgecolors=\"black\", s=28, label=\"days (every 18th day)\")\nax1.plot(ellipses[1][:, 0], ellipses[1][:, 1], \"k-\", lw=1.4,\n         label=\"level set at c = 1 (solid)\")\nax1.plot(ellipses[2][:, 0], ellipses[2][:, 1], \"k--\", lw=1.4,\n         label=\"level set at c = 2 (dashed)\")\nfor j in (0, 1):\n    ends = np.array([mu_hat - half[j] * V[:, j], mu_hat + half[j] * V[:, j]])\n    ax1.plot(ends[:, 0], ends[:, 1], color=\"0.5\", lw=0.9, ls=\":\",\n             label=\"axes of the level set at c = 2 (dotted)\" if j == 0\n             else None)\nax1.scatter(*mu_hat, marker=\"x\", color=\"black\", s=60, label=\"mean vector\")\nax1.set_xlabel(\"morning minimum temperature (\u00b0C)\")\nax1.set_ylabel(\"maximum daytime temperature (\u00b0C)\")\nax1.set_title(\"maximum likelihood Gaussian for the days of 2024\")\nax1.set_aspect(\"equal\")\nax1.legend(frameon=False, fontsize=7, loc=\"lower right\")\nax2.plot(cs, [np.mean(d2 <= c ** 2) for c in cs], \"k-\", lw=1.4,\n         label=\"fraction of the 366 days inside (solid)\")\nax2.plot(cs, 1 - np.exp(-cs ** 2 / 2), \"k--\", lw=1.4,\n         label=\"Gaussian prediction 1 - exp(-c\u00b2/2) (dashed)\")\nax2.set_xlabel(\"level c of the level set\")\nax2.set_ylabel(\"fraction inside the level set\")\nax2.set_title(\"how many days each level set holds\")\nax2.legend(frameon=False, fontsize=7, loc=\"lower right\")\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"mvndist.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)"
  }
 ]
}