{ "cells": [ { "cell_type": "markdown", "id": "a271707c6234", "metadata": {}, "source": [ "# CTG Agent Challenge (ICASSP 2027 GC-9) — Week 14: consolidation before writing and before the official validation phase\n", "\n", "Single, resumable notebook that closes the experimental programme. It **must run in FULL mode**: the setup cell refuses `CTG_SMOKE=1`. Attach the output of the weeks 11–13 run as an input; every earlier stage is restored and skipped, and the locked holdout stays closed.\n", "\n", "| # | Item | Stage | What is done | Gate (pre-registered in the code) |\n", "|---|---|---|---|---|\n", "| 1 | Interval coverage was measured with bounds at 1-bpm bin centres, inconsistent with the PIT | s55 | Quantiles interpolated on the same continuous CDF as the PIT. A built-in check shows that interval coverage equals PIT coverage. C1 is re-evaluated with the unchanged criterion. The weeks 3–13 calibration tables are recomputed (3-seed ensemble per stratum, 5-seed ensemble, single TCN, raw / temperature / isotonic) | **C1 v2** |\n", "| 4 | Sharp-target ensemble | s45 seeds 1–4, s55 | 5-seed TCN with σ = 0.5 (20 trainings): CRPS, PIT error, coverage, accuracy, p_far ranking, paired against the recalibrated σ = 1.5 ensemble | part of C1 v2 |\n", "| 2 | Uncertainty → label shortcut | s56 | Out-of-fold AUROC for: DUS quality alone, reference physiology alone, reference missingness, uncertainty alone, and their combinations. Also uncertainty residualised on quality, and uncertainty within quality terciles. Paired increments | **SC**: physiology proxy vs. quality shortcut |\n", "| 3 | Small fixes | s52, s58 | CC gate read correctly (no more `None`); the B0 correction and all corrected interpretations are written to `SUMMARY_FINAL.md` | – |\n", "| – | R share | s37 (rerun once) | R / (R + E) with CI per metric and seed, for the « reconstruction explains ≈ 78 % » claim | – |\n", "| 5 | Package and validation | s50, s51, s57 | Re-selection including the sharp ensemble. Package v2: two dry runs with the network blocked at the socket level must give identical outputs. Also produced: `build_and_test.sh` (docker build + run with `--network none` + comparison with expected outputs), tests, `.dockerignore`, `ctg_package.tar.gz`. The official validation set is detected automatically (or via `CTG_VALIDATION_DIR`) and the submission is written to `/kaggle/working/submission(.zip)`; before 1 January a template is written instead | **S12** (offline + deterministic) |\n", "| – | Final synthesis | s52, s58 | Paper tables (calibration v2 and strata, shortcut, R share, T1 selection), reproducibility manifest, `SUMMARY_FINAL.md`: full gate timeline, decision log, consolidated claims for both articles, open risks | – |\n", "\n", "**Docker.** Kaggle has no Docker daemon. On a machine with Docker, download `ctg_package.tar.gz` from the notebook output, extract it and run `bash build_and_test.sh`. The script builds the image, runs it on GPU (CPU fallback) with the network disabled, and checks the outputs against `tests/expected`.\n", "\n", "**Run.** *2 × T4*, internet ON, *Save & Run All*. With the weeks 11–13 output attached, expect about 2.5–3 h, of which about 1.5 h is the 20 sharp-target TCN trainings. The cache is exported after each block and on any failure, and failed cells are listed at the end." ] }, { "cell_type": "code", "execution_count": 1, "id": "acac4ae01f07", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:26.606368Z", "iopub.status.busy": "2026-11-28T14:17:26.606029Z", "iopub.status.idle": "2026-11-28T14:17:32.599836Z", "shell.execute_reply": "2026-11-28T14:17:32.597987Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.10.12 torch 2.9.1+cu129 numpy 2.2.6 scipy 1.15.3 pywt 1.8.0 sklearn 1.7.2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "GPUs: []\n", "/kaggle/tmp free 86.1 GiB\n", "/kaggle/working free 86.1 GiB\n", "RAM 29.4 GiB, CPUs 8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/torch/cuda/__init__.py:827: UserWarning: Can't initialize NVML\n", " warnings.warn(\"Can't initialize NVML\")\n" ] } ], "source": [ "import os, sys, shutil, subprocess, json, platform, time\n", "os.environ.setdefault(\"CTG_T0\", str(time.time()))\n", "os.environ.setdefault(\"CTG_SMOKE\", \"0\")\n", "os.environ.setdefault(\"CTG_T1_SEEDS\", \"3\")\n", "os.environ.setdefault(\"CTG_T1_SEEDS_FAMILY\", \"5\")\n", "os.environ.setdefault(\"CTG_PRUNE_PROBS\", \"1\")\n", "os.environ.setdefault(\"CTG_HOLDOUT_REOPEN\", \"0\")\n", "os.environ.setdefault(\"CTG_DEADLINE_H\", \"11.25\")\n", "os.environ.setdefault(\"CTG_EXPORT_CACHE\", \"1\")\n", "os.environ.setdefault(\"CTG_DL_THREADS\", \"16\")\n", "os.environ.setdefault(\"CTG_T1_PRIMARY\", \"tcn\")\n", "os.environ.setdefault(\"CTG_PRUNE_FEATURES\", \"1\")\n", "os.environ.setdefault(\"CTG_UNLOCK_HOLDOUT\", \"0\")\n", "CODE_DIR = \"/kaggle/tmp/ctg_code\"\n", "os.makedirs(f\"{CODE_DIR}/ctglib\", exist_ok=True)\n", "for mod in (\"pywt\", \"skimage\", \"sklearn\", \"psutil\", \"requests\", \"matplotlib\"):\n", " try:\n", " __import__(mod)\n", " except ImportError:\n", " subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", {\"pywt\": \"PyWavelets\", \"skimage\": \"scikit-image\", \"sklearn\": \"scikit-learn\"}.get(mod, mod)], check=True)\n", "import torch, numpy, scipy, pywt, sklearn\n", "print(platform.python_version(), \"torch\", torch.__version__, \"numpy\", numpy.__version__, \"scipy\", scipy.__version__, \"pywt\", pywt.__version__, \"sklearn\", sklearn.__version__)\n", "print(\"GPUs:\", [torch.cuda.get_device_name(i) + f\" {torch.cuda.get_device_properties(i).total_memory / 2**30:.1f} GiB\" for i in range(torch.cuda.device_count())])\n", "for p in (\"/kaggle/tmp\", \"/kaggle/working\"):\n", " os.makedirs(p, exist_ok=True)\n", " u = shutil.disk_usage(p)\n", " print(p, f\"free {u.free / 2**30:.1f} GiB\")\n", "import psutil\n", "print(f\"RAM {psutil.virtual_memory().total / 2**30:.1f} GiB, CPUs {os.cpu_count()}\")" ] }, { "cell_type": "markdown", "id": "5a4a5f52602b", "metadata": {}, "source": [ "## Library\n", "Each cell writes one module of `ctglib` to `/kaggle/tmp/ctg_code`. Stages run as isolated subprocesses so that a crash or an out-of-memory error never kills the kernel, and every stage resumes from its last completed unit." ] }, { "cell_type": "code", "execution_count": 2, "id": "c98ad9b83971", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.603786Z", "iopub.status.busy": "2026-11-28T14:17:32.603289Z", "iopub.status.idle": "2026-11-28T14:17:32.610019Z", "shell.execute_reply": "2026-11-28T14:17:32.608491Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/__init__.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/__init__.py\n", "__version__ = \"1.0.0\"" ] }, { "cell_type": "code", "execution_count": 3, "id": "023399f8319a", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.613601Z", "iopub.status.busy": "2026-11-28T14:17:32.613265Z", "iopub.status.idle": "2026-11-28T14:17:32.621164Z", "shell.execute_reply": "2026-11-28T14:17:32.619445Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/config.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/config.py\n", "import os\n", "from pathlib import Path\n", "import numpy as np\n", "\n", "SMOKE = int(os.environ.get(\"CTG_SMOKE\", \"0\"))\n", "_SFX = \"_smoke\" if SMOKE else \"\"\n", "DATA = Path(os.environ.get(\"CTG_DATA\", f\"/kaggle/tmp/ctg{_SFX}\"))\n", "OUT = Path(os.environ.get(\"CTG_OUT\", f\"/kaggle/working/ctg_runs{_SFX}\"))\n", "UNLOCK_HOLDOUT = int(os.environ.get(\"CTG_UNLOCK_HOLDOUT\", \"0\"))\n", "REPO_URL = \"https://github.com/wenlizeng/ctg-agent-fetal-assessment-baseline.git\"\n", "LFS_MEDIA = \"https://media.githubusercontent.com/media/wenlizeng/ctg-agent-fetal-assessment-baseline/main/\"\n", "REPO = DATA / \"repo\"\n", "RAW = REPO / \"data\"\n", "CACHE = DATA / \"cache\"\n", "FEAT = DATA / \"dus_features\"\n", "STATE = OUT / \"state\"\n", "LOGS = OUT / \"logs\"\n", "RES = OUT / \"results\"\n", "FIG = OUT / \"figures\"\n", "MODELS = OUT / \"models\"\n", "PRED = OUT / \"predictions\"\n", "\n", "FS_DUS = 1000\n", "FS_FHR = 4\n", "N = 4800\n", "FHR_MIN = 50.0\n", "FHR_MAX = 210.0\n", "BPM = np.arange(50, 211, dtype=np.float32)\n", "NB = BPM.size\n", "ENV_FS = 200\n", "SEED = 2026\n", "N_FOLDS = 5\n", "HOLDOUT_FRAC = 0.15\n", "BIG_ERR = 10.0\n", "COVERAGES = (0.9, 0.8, 0.7)\n", "FP_KS = (120, 240, 480)\n", "FP_K_MAIN = 240\n", "FP_WINNOW = 40\n", "FP_MIN_SHARED = 3\n", "\n", "LIMITS = {\"t1\": 24, \"t2\": 300, \"t3\": 600} if SMOKE else {}\n", "BOOT = 100 if SMOKE else 2000\n", "EPOCHS_T1 = 2 if SMOKE else 40\n", "EPOCHS_T2 = 2 if SMOKE else 60\n", "EPOCHS_FT = 2 if SMOKE else 25\n", "EPOCHS_T3D = 2 if SMOKE else 30\n", "EPOCHS_T4D = 2 if SMOKE else 30\n", "T1_SEEDS = int(os.environ.get(\"CTG_T1_SEEDS\", \"3\"))\n", "K_MC = 4 if SMOKE else 8\n", "POINTS_PER_RECORD = 120 if SMOKE else 300\n", "ALPHA_ESTIMATE = 0.005\n", "ALPHA_FLAG = 0.02\n", "POLICY_MIN_RUN_S = 5\n", "BRADY = 110.0\n", "DEADLINE_H = float(os.environ.get(\"CTG_DEADLINE_H\", \"11.25\"))\n", "EXPORT_CACHE = int(os.environ.get(\"CTG_EXPORT_CACHE\", \"1\"))\n", "RESTORE_FROM = os.environ.get(\"CTG_RESTORE_FROM\", \"\")\n", "PATIENCE = 8\n", "DL_THREADS = int(os.environ.get(\"CTG_DL_THREADS\", \"16\"))\n", "CPU = max(1, (os.cpu_count() or 2))\n", "T1_PRIMARY = os.environ.get(\"CTG_T1_PRIMARY\", \"tcn\")\n", "T1_SEEDS_FAMILY = int(os.environ.get(\"CTG_T1_SEEDS_FAMILY\", \"5\"))\n", "EPOCHS_PROB = 2 if SMOKE else 40\n", "K_FM = 4 if SMOKE else 16\n", "FM_STEPS = 4 if SMOKE else 16\n", "K_EVENTS = 2 if SMOKE else 8\n", "ES_WIN = 240\n", "SHIFT_S = 15\n", "FALLBACK_INTERP_MAX_S = 15\n", "S6_REL = 0.15\n", "S8_REDUCTION = 0.30\n", "FM_TIME_RATIO = 3.0\n", "COVER_LEVELS = (0.5, 0.8, 0.9)\n", "REPORT_COVERAGES = (0.9, 0.8)\n", "PRUNE_PROBS = int(os.environ.get(\"CTG_PRUNE_PROBS\", \"1\"))\n", "HOLDOUT_REOPEN = int(os.environ.get(\"CTG_HOLDOUT_REOPEN\", \"0\"))\n", "UCB_BOOT = 50 if SMOKE else 200\n", "POLICY_MIN_RECORDS = 3 if SMOKE else 30\n", "ALPHA_SWEEP = (0.0025, 0.005, 0.01, 0.02)\n", "FP_PAIRS = 30 if SMOKE else 300\n", "FP_NULL_PAIRS = 200 if SMOKE else 3000\n", "DRYRUN_RECORDS = 2 if SMOKE else 8\n", "T1_TIME_BUDGET_S = float(os.environ.get(\"CTG_T1_TIME_BUDGET_S\", \"5\"))\n", "PACKAGE_DIR = OUT / \"package\"" ] }, { "cell_type": "code", "execution_count": 4, "id": "9e6402934b54", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.624762Z", "iopub.status.busy": "2026-11-28T14:17:32.624427Z", "iopub.status.idle": "2026-11-28T14:17:32.635801Z", "shell.execute_reply": "2026-11-28T14:17:32.634101Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/utils.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/utils.py\n", "import gc\n", "import hashlib\n", "import json\n", "import logging\n", "import os\n", "import random\n", "import shutil\n", "import sys\n", "import time\n", "import traceback\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "\n", "\n", "def ensure_dirs():\n", " for d in (C.DATA, C.CACHE, C.FEAT, C.OUT, C.STATE, C.LOGS, C.RES, C.FIG, C.MODELS, C.PRED):\n", " d.mkdir(parents=True, exist_ok=True)\n", "\n", "\n", "def get_logger(name):\n", " ensure_dirs()\n", " lg = logging.getLogger(name)\n", " if not lg.handlers:\n", " lg.setLevel(logging.INFO)\n", " fmt = logging.Formatter(\"%(asctime)s pid=%(process)d %(name)s %(levelname)s %(message)s\")\n", " for h in (logging.StreamHandler(sys.stdout), logging.FileHandler(C.LOGS / f\"{name}.log\")):\n", " h.setFormatter(fmt)\n", " lg.addHandler(h)\n", " lg.propagate = False\n", " return lg\n", "\n", "\n", "def to_jsonable(o):\n", " if isinstance(o, (np.integer,)):\n", " return int(o)\n", " if isinstance(o, (np.floating,)):\n", " v = float(o)\n", " return None if not np.isfinite(v) else v\n", " if isinstance(o, np.ndarray):\n", " return [to_jsonable(x) for x in o.tolist()]\n", " if isinstance(o, (np.bool_,)):\n", " return bool(o)\n", " if isinstance(o, Path):\n", " return str(o)\n", " if isinstance(o, float) and not np.isfinite(o):\n", " return None\n", " if isinstance(o, dict):\n", " return {str(k): to_jsonable(v) for k, v in o.items()}\n", " if isinstance(o, (list, tuple)):\n", " return [to_jsonable(v) for v in o]\n", " return o\n", "\n", "\n", "def _tmp(path):\n", " path = Path(path)\n", " path.parent.mkdir(parents=True, exist_ok=True)\n", " return path.parent / f\".{path.name}.{os.getpid()}.tmp\"\n", "\n", "\n", "def save_json(path, obj):\n", " t = _tmp(path)\n", " with open(t, \"w\") as f:\n", " json.dump(to_jsonable(obj), f, indent=2)\n", " os.replace(t, path)\n", "\n", "\n", "def load_json(path, default=None):\n", " path = Path(path)\n", " if not path.exists():\n", " return default\n", " with open(path) as f:\n", " return json.load(f)\n", "\n", "\n", "def save_npz(path, **arrays):\n", " path = Path(path)\n", " t = _tmp(path)\n", " with open(t, \"wb\") as f:\n", " np.savez(f, **arrays)\n", " os.replace(t, path)\n", "\n", "\n", "def load_npz(path):\n", " with np.load(path, allow_pickle=False) as z:\n", " return {k: z[k] for k in z.files}\n", "\n", "\n", "def save_df(path, df):\n", " t = _tmp(path)\n", " df.to_pickle(t)\n", " os.replace(t, path)\n", "\n", "\n", "def load_df(path):\n", " return pd.read_pickle(path)\n", "\n", "\n", "def save_npy(path, arr):\n", " t = _tmp(path)\n", " with open(t, \"wb\") as f:\n", " np.save(f, arr)\n", " os.replace(t, path)\n", "\n", "\n", "def open_memmap_new(path, shape, dtype, fill=None):\n", " path = Path(path)\n", " t = path.parent / (path.stem + \".partial.npy\")\n", " m = np.lib.format.open_memmap(t, mode=\"w+\", dtype=dtype, shape=shape)\n", " if fill is not None:\n", " m[:] = fill\n", " return m, t, path\n", "\n", "\n", "def finalize_memmap(m, t, path):\n", " m.flush()\n", " del m\n", " os.replace(t, path)\n", "\n", "\n", "def mm(path, mode=\"r\"):\n", " return np.load(path, mmap_mode=mode)\n", "\n", "\n", "def seed_all(s=C.SEED):\n", " random.seed(s)\n", " np.random.seed(s)\n", " try:\n", " import torch\n", " torch.manual_seed(s)\n", " torch.cuda.manual_seed_all(s)\n", " except Exception:\n", " pass\n", "\n", "\n", "def params_hash(params):\n", " return hashlib.sha1(json.dumps(to_jsonable(params), sort_keys=True).encode()).hexdigest()[:12]\n", "\n", "\n", "def marker(name):\n", " return C.STATE / f\"{name}.done.json\"\n", "\n", "\n", "def portable(p):\n", " p = Path(p)\n", " for tag, root in ((\"{DATA}\", C.DATA), (\"{OUT}\", C.OUT)):\n", " try:\n", " return tag + \"/\" + str(p.resolve().relative_to(root.resolve()))\n", " except ValueError:\n", " continue\n", " return str(p)\n", "\n", "\n", "def resolve_output(s):\n", " s = str(s)\n", " for tag, root in ((\"{DATA}\", C.DATA), (\"{OUT}\", C.OUT)):\n", " if s.startswith(tag + \"/\"):\n", " return root / s[len(tag) + 1:]\n", " return Path(s)\n", "\n", "\n", "def is_done(name, params=None):\n", " m = load_json(marker(name))\n", " if not m or m.get(\"hash\") != params_hash(params or {}):\n", " return False\n", " return all(resolve_output(o).exists() for o in m.get(\"outputs\", []))\n", "\n", "\n", "def mark_done(name, params=None, info=None, outputs=()):\n", " save_json(marker(name), {\"hash\": params_hash(params or {}), \"time\": time.strftime(\"%Y-%m-%d %H:%M:%S\"), \"info\": info or {}, \"outputs\": [portable(o) for o in outputs]})\n", "\n", "\n", "def clear_done(name):\n", " p = marker(name)\n", " if p.exists():\n", " p.unlink()\n", "\n", "\n", "def retry(fn, tries=5, base=2.0, cap=120.0, exceptions=(Exception,), log=None):\n", " for i in range(tries):\n", " try:\n", " return fn()\n", " except exceptions as e:\n", " if i == tries - 1:\n", " raise\n", " w = min(cap, base * 2 ** i) * (0.5 + random.random())\n", " if log:\n", " log.warning(f\"retry {i + 1}/{tries} after {type(e).__name__}: {e}; sleeping {w:.1f}s\")\n", " time.sleep(w)\n", "\n", "\n", "def free_mem():\n", " gc.collect()\n", " try:\n", " import torch\n", " if torch.cuda.is_available():\n", " torch.cuda.empty_cache()\n", " except Exception:\n", " pass\n", "\n", "\n", "def mem_report():\n", " out = {}\n", " try:\n", " import psutil\n", " vm = psutil.virtual_memory()\n", " out[\"ram_used_gb\"] = round(vm.used / 2 ** 30, 2)\n", " out[\"ram_avail_gb\"] = round(vm.available / 2 ** 30, 2)\n", " except Exception:\n", " pass\n", " try:\n", " import torch\n", " for i in range(torch.cuda.device_count()):\n", " out[f\"gpu{i}_alloc_gb\"] = round(torch.cuda.memory_allocated(i) / 2 ** 30, 2)\n", " except Exception:\n", " pass\n", " out[\"disk_data_free_gb\"] = round(shutil.disk_usage(C.DATA).free / 2 ** 30, 2)\n", " out[\"disk_out_free_gb\"] = round(shutil.disk_usage(C.OUT).free / 2 ** 30, 2)\n", " return out\n", "\n", "\n", "def device():\n", " import torch\n", " return torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "\n", "def is_oom(e):\n", " s = str(e).lower()\n", " return \"out of memory\" in s or \"cuda error: out of memory\" in s or type(e).__name__ == \"OutOfMemoryError\"\n", "\n", "\n", "def adaptive_batches(n, fn, start, minimum=1, log=None):\n", " bs = start\n", " i = 0\n", " out = []\n", " while i < n:\n", " j = min(n, i + bs)\n", " try:\n", " out.append(fn(i, j))\n", " i = j\n", " except RuntimeError as e:\n", " if not is_oom(e) or bs <= minimum:\n", " raise\n", " free_mem()\n", " bs = max(minimum, bs // 2)\n", " if log:\n", " log.warning(f\"OOM, batch size -> {bs}\")\n", " return out\n", "\n", "\n", "def bootstrap(stat, units, B=None, seed=C.SEED, alpha=0.05):\n", " B = B or C.BOOT\n", " units = np.asarray(units)\n", " uniq = np.unique(units)\n", " idx_by = {u: np.flatnonzero(units == u) for u in uniq}\n", " rng = np.random.default_rng(seed)\n", " point = stat(np.arange(len(units)))\n", " vals = []\n", " for _ in range(B):\n", " pick = rng.choice(uniq, size=uniq.size, replace=True)\n", " idx = np.concatenate([idx_by[u] for u in pick])\n", " try:\n", " vals.append(stat(idx))\n", " except Exception:\n", " continue\n", " vals = np.asarray([v for v in vals if v is not None and np.all(np.isfinite(v))], dtype=float)\n", " if vals.size == 0:\n", " return {\"point\": point, \"lo\": np.nan, \"hi\": np.nan, \"n_boot\": 0}\n", " lo, hi = np.quantile(vals, [alpha / 2, 1 - alpha / 2], axis=0)\n", " return {\"point\": point, \"lo\": lo, \"hi\": hi, \"n_boot\": int(len(vals))}\n", "\n", "\n", "def holdout_guard(df_or_mask, what=\"evaluation\"):\n", " mask = df_or_mask\n", " if isinstance(df_or_mask, pd.DataFrame):\n", " mask = (df_or_mask[\"fold\"] < 0).values\n", " if np.any(mask) and not C.UNLOCK_HOLDOUT:\n", " raise PermissionError(f\"Locked holdout records requested for {what}; set CTG_UNLOCK_HOLDOUT=1 only for the final, pre-registered evaluation\")\n", "\n", "\n", "def stage(name, params=None, outputs=()):\n", " def deco(fn):\n", " def wrapped(force=False, **kw):\n", " log = get_logger(name)\n", " p = dict(params or {}, smoke=C.SMOKE, **kw)\n", " outs = [o() if callable(o) else o for o in outputs]\n", " if not force and is_done(name, p) and all(Path(o).exists() for o in outs):\n", " log.info(f\"skip {name}: already done\")\n", " return load_json(marker(name))[\"info\"]\n", " t0 = time.time()\n", " log.info(f\"start {name} {p} {mem_report()}\")\n", " try:\n", " info = fn(log=log, **kw) or {}\n", " except Exception:\n", " log.error(traceback.format_exc())\n", " raise\n", " info[\"seconds\"] = round(time.time() - t0, 1)\n", " mark_done(name, p, info, outs)\n", " log.info(f\"done {name} in {info['seconds']}s {mem_report()}\")\n", " return info\n", " wrapped.stage_name = name\n", " wrapped.params = dict(params or {})\n", " return wrapped\n", " return deco" ] }, { "cell_type": "code", "execution_count": 5, "id": "f4964dea1472", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.639272Z", "iopub.status.busy": "2026-11-28T14:17:32.638881Z", "iopub.status.idle": "2026-11-28T14:17:32.646773Z", "shell.execute_reply": "2026-11-28T14:17:32.645055Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/io.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/io.py\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from scipy.io import wavfile\n", "\n", "from . import config as C\n", "\n", "\n", "def is_lfs_pointer(path):\n", " path = Path(path)\n", " if not path.exists() or path.stat().st_size > 1024:\n", " return False\n", " with open(path, \"rb\") as f:\n", " return f.read(40).startswith(b\"version https://git-lfs\")\n", "\n", "\n", "def parse_pointer(path):\n", " out = {}\n", " for line in Path(path).read_text().splitlines():\n", " if line.startswith(\"oid sha256:\"):\n", " out[\"oid\"] = line.split(\":\", 1)[1].strip()\n", " elif line.startswith(\"size \"):\n", " out[\"size\"] = int(line.split()[1])\n", " return out\n", "\n", "\n", "def load_fetal(path):\n", " path = Path(path)\n", " if is_lfs_pointer(path):\n", " raise IOError(f\"LFS pointer not downloaded: {path}\")\n", " b = path.read_bytes()\n", " if len(b) < 9:\n", " raise ValueError(f\"empty fetal file {path}\")\n", " version, k = b[0], b[1]\n", " if k < 1:\n", " raise ValueError(f\"bad channel count {path}\")\n", " if version == 1:\n", " rec = 8 + (k - 1) * 4\n", " if (len(b) - 8) % rec:\n", " raise ValueError(f\"partial record {path}\")\n", " n = (len(b) - 8) // rec\n", " elif version == 0:\n", " rec = k + 2\n", " n = int.from_bytes(b[2:6], \"little\")\n", " if 8 + n * rec > len(b):\n", " raise ValueError(f\"inconsistent legacy length {path}\")\n", " else:\n", " raise ValueError(f\"unsupported version {version} {path}\")\n", " x = np.frombuffer(b[8:8 + n * rec], dtype=np.uint8).reshape(n, rec)[:, 0].astype(np.float32)\n", " x[(x < C.FHR_MIN) | (x > C.FHR_MAX)] = np.nan\n", " return x\n", "\n", "\n", "def fit_len(x, n=C.N):\n", " x = np.asarray(x, dtype=np.float32)\n", " if x.size >= n:\n", " return x[:n]\n", " return np.concatenate([x, np.full(n - x.size, np.nan, np.float32)])\n", "\n", "\n", "def valid(x):\n", " x = np.asarray(x)\n", " return np.isfinite(x) & (x >= C.FHR_MIN) & (x <= C.FHR_MAX)\n", "\n", "\n", "def clean_fhr(x):\n", " x = np.asarray(x, dtype=np.float32).copy()\n", " x[~valid(x)] = np.nan\n", " return x\n", "\n", "\n", "def fill_linear(x, default=140.0):\n", " x = np.asarray(x, dtype=np.float32)\n", " v = valid(x)\n", " if not v.any():\n", " return np.full(x.shape, default, np.float32)\n", " i = np.arange(x.size)\n", " out = x.copy()\n", " out[~v] = np.interp(i[~v], i[v], x[v])\n", " return out\n", "\n", "\n", "def wav_header(path):\n", " sr, x = wavfile.read(path, mmap=True)\n", " return int(sr), int(x.shape[0]), str(x.dtype), int(x.ndim)\n", "\n", "\n", "def read_wav(path):\n", " sr, x = wavfile.read(path, mmap=True)\n", " if x.ndim > 1:\n", " x = x[:, 0]\n", " raw = np.asarray(x)\n", " if raw.dtype == np.uint8:\n", " lo, hi = 0, 255\n", " elif np.issubdtype(raw.dtype, np.integer):\n", " lo, hi = np.iinfo(raw.dtype).min, np.iinfo(raw.dtype).max\n", " else:\n", " lo, hi = -1.0, 1.0\n", " clip = (raw <= lo) | (raw >= hi)\n", " return int(sr), raw.astype(np.float32), clip\n", "\n", "\n", "def read_csv(path, cols):\n", " df = pd.read_csv(path, usecols=lambda c: c in cols)\n", " return {c: pd.to_numeric(df[c], errors=\"coerce\").to_numpy(np.float32) for c in cols if c in df}\n", "\n", "\n", "def events(labels, value):\n", " m = np.asarray(labels) == value\n", " if not m.any():\n", " return np.zeros((0, 2), np.int64)\n", " d = np.diff(np.concatenate([[0], m.astype(np.int8), [0]]))\n", " return np.stack([np.flatnonzero(d == 1), np.flatnonzero(d == -1)], 1)" ] }, { "cell_type": "code", "execution_count": 6, "id": "44b90f4f5cb5", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.650276Z", "iopub.status.busy": "2026-11-28T14:17:32.649871Z", "iopub.status.idle": "2026-11-28T14:17:32.661344Z", "shell.execute_reply": "2026-11-28T14:17:32.659722Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/metrics.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/metrics.py\n", "import numpy as np\n", "from scipy.optimize import linear_sum_assignment\n", "from scipy.stats import spearmanr\n", "from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n", "\n", "from . import config as C\n", "from .io import events, valid\n", "\n", "\n", "def fhr_abs_errors(pred, ref):\n", " pred = np.asarray(pred, np.float64)\n", " ref = np.asarray(ref, np.float64)\n", " rv = valid(ref)\n", " r = ref[rv]\n", " p = pred[rv]\n", " pv = np.isfinite(p) & (p >= C.FHR_MIN) & (p <= C.FHR_MAX)\n", " worst = np.maximum(r - C.FHR_MIN, C.FHR_MAX - r)\n", " return np.where(pv, np.abs(p - r), worst), rv\n", "\n", "\n", "def t1_scores(preds, refs):\n", " errs = [fhr_abs_errors(p, r)[0] for p, r in zip(preds, refs)]\n", " allerr = np.concatenate(errs) if errs else np.zeros(0)\n", " per_rmse = np.array([np.sqrt(np.mean(e ** 2)) if e.size else np.nan for e in errs])\n", " per_mae = np.array([np.mean(e) if e.size else np.nan for e in errs])\n", " return {\n", " \"rmse_pooled\": float(np.sqrt(np.mean(allerr ** 2))),\n", " \"mae_pooled\": float(np.mean(allerr)),\n", " \"rmse_record_mean\": float(np.nanmean(per_rmse)),\n", " \"mae_record_mean\": float(np.nanmean(per_mae)),\n", " \"n_points\": int(allerr.size),\n", " \"n_records\": int(len(errs)),\n", " }\n", "\n", "\n", "def sanitize_labels(pred):\n", " p = np.asarray(pred).astype(np.float64)\n", " ok = np.isfinite(p) & np.isin(p, (-1, 0, 1))\n", " return np.where(ok, p, 99).astype(np.int64)\n", "\n", "\n", "def dice_counts(pred, ref, ignore=None):\n", " p = sanitize_labels(pred)\n", " r = np.asarray(ref).astype(np.int64)\n", " keep = np.ones(r.shape, bool) if ignore is None else ~ignore\n", " out = {}\n", " for k in (0, 1, -1):\n", " a = (p == k) & keep\n", " b = (r == k) & keep\n", " out[k] = (int((a & b).sum()), int(a.sum()), int(b.sum()))\n", " return out\n", "\n", "\n", "def dice_from_counts(counts_list):\n", " res = {}\n", " for k in (0, 1, -1):\n", " inter = sum(c[k][0] for c in counts_list)\n", " s = sum(c[k][1] + c[k][2] for c in counts_list)\n", " res[f\"pooled_{k}\"] = 2 * inter / s if s else np.nan\n", " per = []\n", " per_empty1 = []\n", " for c in counts_list:\n", " i, a, b = c[k]\n", " if a + b:\n", " per.append(2 * i / (a + b))\n", " per_empty1.append(2 * i / (a + b))\n", " else:\n", " per_empty1.append(1.0)\n", " res[f\"record_{k}\"] = float(np.mean(per)) if per else np.nan\n", " res[f\"record_empty1_{k}\"] = float(np.mean(per_empty1)) if per_empty1 else np.nan\n", " for agg in (\"pooled\", \"record\", \"record_empty1\"):\n", " res[f\"{agg}_macro\"] = float(np.nanmean([res[f\"{agg}_{k}\"] for k in (0, 1, -1)]))\n", " return res\n", "\n", "\n", "def sanitize_probs(y, p):\n", " y = np.asarray(y).astype(int)\n", " p = np.asarray(p, np.float64)\n", " bad = ~np.isfinite(p) | (p < 0) | (p > 1)\n", " return np.where(bad, 1.0 - y, p), int(bad.sum())\n", "\n", "\n", "def binary_scores(y, p, thr=0.5):\n", " y = np.asarray(y).astype(int)\n", " p, nbad = sanitize_probs(y, p)\n", " yhat = (p >= thr).astype(int)\n", " auc = roc_auc_score(y, p) if len(np.unique(y)) == 2 else np.nan\n", " mcc = matthews_corrcoef(y, yhat) if len(np.unique(y)) == 2 else 0.0\n", " return {\n", " \"auroc\": float(auc),\n", " \"f1\": float(f1_score(y, yhat, zero_division=0)),\n", " \"f1_macro\": float(f1_score(y, yhat, average=\"macro\", zero_division=0)),\n", " \"nmcc\": float((mcc + 1) / 2),\n", " \"brier\": float(np.mean((p - y) ** 2)),\n", " \"ece\": float(ece(y, p)),\n", " \"n_invalid\": nbad,\n", " \"n\": int(y.size),\n", " \"prevalence\": float(y.mean()),\n", " }\n", "\n", "\n", "def ece(y, p, bins=10):\n", " y = np.asarray(y)\n", " p = np.asarray(p)\n", " edges = np.linspace(0, 1, bins + 1)\n", " tot = 0.0\n", " for a, b in zip(edges[:-1], edges[1:]):\n", " m = (p >= a) & ((p < b) | (b == 1))\n", " if m.any():\n", " tot += m.mean() * abs(p[m].mean() - y[m].mean())\n", " return tot\n", "\n", "\n", "def iou_matrix(a, b):\n", " if len(a) == 0 or len(b) == 0:\n", " return np.zeros((len(a), len(b)))\n", " s = np.maximum(a[:, None, 0], b[None, :, 0])\n", " e = np.minimum(a[:, None, 1], b[None, :, 1])\n", " inter = np.clip(e - s, 0, None)\n", " union = (a[:, 1] - a[:, 0])[:, None] + (b[:, 1] - b[:, 0])[None, :] - inter\n", " return np.where(union > 0, inter / union, 0.0)\n", "\n", "\n", "def match_events(pred_iv, ref_iv, thr=0.3):\n", " m = iou_matrix(np.asarray(pred_iv), np.asarray(ref_iv))\n", " if m.size == 0:\n", " return 0, len(pred_iv), len(ref_iv)\n", " r, c = linear_sum_assignment(-m)\n", " tp = int((m[r, c] >= thr).sum())\n", " return tp, len(pred_iv) - tp, len(ref_iv) - tp\n", "\n", "\n", "def event_counts(pred_labels, ref_labels, thr=0.3):\n", " p = sanitize_labels(pred_labels)\n", " out = {}\n", " for k, name in ((1, \"acc\"), (-1, \"dec\")):\n", " out[name] = match_events(events(p, k), events(ref_labels, k), thr)\n", " return out\n", "\n", "\n", "def evidence_f1(counts_list):\n", " res = {}\n", " for name in (\"acc\", \"dec\"):\n", " tp = sum(c[name][0] for c in counts_list)\n", " fp = sum(c[name][1] for c in counts_list)\n", " fn = sum(c[name][2] for c in counts_list)\n", " res[f\"{name}_tp\"], res[f\"{name}_fp\"], res[f\"{name}_fn\"] = tp, fp, fn\n", " res[f\"{name}_f1\"] = 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) else np.nan\n", " res[\"macro_f1\"] = float(np.nanmean([res[\"acc_f1\"], res[\"dec_f1\"]]))\n", " return res\n", "\n", "\n", "def risk_coverage(score, loss, coverages=C.COVERAGES):\n", " score = np.asarray(score, float)\n", " loss = np.asarray(loss, float)\n", " order = np.argsort(score, kind=\"stable\")\n", " l = loss[order]\n", " cum = np.cumsum(l) / np.arange(1, l.size + 1)\n", " cov = np.arange(1, l.size + 1) / l.size\n", " aurc = float(np.trapezoid(cum, cov)) if hasattr(np, \"trapezoid\") else float(np.trapz(cum, cov))\n", " out = {\"aurc\": aurc, \"risk_full\": float(l.mean())}\n", " oracle = np.cumsum(np.sort(loss)) / np.arange(1, l.size + 1)\n", " out[\"aurc_oracle\"] = float(np.trapezoid(oracle, cov)) if hasattr(np, \"trapezoid\") else float(np.trapz(oracle, cov))\n", " for c in coverages:\n", " k = max(1, int(round(c * l.size)))\n", " out[f\"risk@{c}\"] = float(l[:k].mean())\n", " return out\n", "\n", "\n", "def crps_discrete(probs, y, grid=C.BPM):\n", " cdf = np.cumsum(probs, axis=-1)\n", " step = (grid[None, :] >= y[:, None]).astype(np.float64)\n", " return np.sum((cdf - step) ** 2, axis=-1) * float(grid[1] - grid[0])\n", "\n", "\n", "def spearman(a, b):\n", " a = np.asarray(a, float)\n", " b = np.asarray(b, float)\n", " m = np.isfinite(a) & np.isfinite(b)\n", " if m.sum() < 3:\n", " return np.nan\n", " return float(spearmanr(a[m], b[m]).correlation)\n", "\n", "\n", "def self_test():\n", " rng = np.random.default_rng(0)\n", " ref = rng.uniform(110, 160, 4800).astype(np.float32)\n", " ref[:10] = np.nan\n", " assert t1_scores([ref], [ref])[\"rmse_pooled\"] == 0\n", " bad = ref.copy()\n", " bad[100] = np.nan\n", " e, _ = fhr_abs_errors(bad, ref)\n", " assert e.max() >= 50\n", " lab = np.zeros(4800, int)\n", " lab[100:200] = 1\n", " lab[300:500] = -1\n", " d = dice_from_counts([dice_counts(lab, lab)])\n", " assert abs(d[\"pooled_macro\"] - 1) < 1e-12\n", " d2 = dice_from_counts([dice_counts(np.full(4800, np.nan), lab)])\n", " assert d2[\"pooled_macro\"] == 0\n", " assert evidence_f1([event_counts(lab, lab)])[\"macro_f1\"] == 1\n", " shifted = np.roll(lab, 30)\n", " ec = event_counts(shifted, lab)\n", " assert ec[\"acc\"][0] == 1 and ec[\"dec\"][0] == 1\n", " far = np.roll(lab, 90)\n", " assert event_counts(far, lab)[\"acc\"][0] == 0\n", " y = np.array([0, 1, 0, 1])\n", " s = binary_scores(y, np.array([np.nan, np.nan, 2.0, -1.0]))\n", " assert s[\"auroc\"] == 0 and s[\"n_invalid\"] == 4\n", " assert binary_scores(y, np.array([0.1, 0.9, 0.2, 0.8]))[\"auroc\"] == 1\n", " rc = risk_coverage(np.arange(10), np.r_[np.zeros(5), np.ones(5)])\n", " assert rc[\"risk@0.7\"] < rc[\"risk_full\"]\n", " p = np.zeros((1, C.NB))\n", " p[0, 90] = 1\n", " assert crps_discrete(p, np.array([140.0]))[0] == 0\n", " return True" ] }, { "cell_type": "code", "execution_count": 7, "id": "f3b0892eed21", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.664591Z", "iopub.status.busy": "2026-11-28T14:17:32.664290Z", "iopub.status.idle": "2026-11-28T14:17:32.670808Z", "shell.execute_reply": "2026-11-28T14:17:32.669006Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/selftest.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/selftest.py\n", "from .metrics import self_test\n", "from .utils import stage\n", "\n", "\n", "@stage(\"s05_metrics_selftest\")\n", "def run(log):\n", " self_test()\n", " return {\"metrics_selftest\": \"passed\"}" ] }, { "cell_type": "code", "execution_count": 8, "id": "bb3cb740bad3", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.674615Z", "iopub.status.busy": "2026-11-28T14:17:32.674296Z", "iopub.status.idle": "2026-11-28T14:17:32.685061Z", "shell.execute_reply": "2026-11-28T14:17:32.683087Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/acquire.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/acquire.py\n", "import hashlib\n", "import os\n", "import shutil\n", "import subprocess\n", "import threading\n", "import time\n", "from concurrent.futures import ThreadPoolExecutor, as_completed\n", "from pathlib import Path\n", "\n", "import pandas as pd\n", "import requests\n", "\n", "from . import config as C\n", "from .io import is_lfs_pointer, parse_pointer\n", "from .utils import load_json, save_json, stage\n", "\n", "LEDGER = C.CACHE / \"lfs_ledger.json\"\n", "_lock = threading.Lock()\n", "_local = threading.local()\n", "\n", "\n", "def clone(log):\n", " if (C.REPO / \".git\").exists():\n", " log.info(\"repository present, keeping working tree (no reset: it would overwrite downloaded LFS content)\")\n", " else:\n", " C.REPO.parent.mkdir(parents=True, exist_ok=True)\n", " env = dict(os.environ, GIT_LFS_SKIP_SMUDGE=\"1\")\n", " subprocess.run([\"git\", \"clone\", \"--depth\", \"1\", C.REPO_URL, str(C.REPO)], check=True, env=env, stdout=subprocess.DEVNULL)\n", " head = subprocess.run([\"git\", \"-C\", str(C.REPO), \"rev-parse\", \"HEAD\"], capture_output=True, text=True, check=True).stdout.strip()\n", " return head\n", "\n", "\n", "def manifests():\n", " r = C.RAW\n", " m = {\n", " \"t1\": pd.read_csv(r / \"task1/manifests/train.csv\"),\n", " \"t2\": pd.read_csv(r / \"task2/manifests/train_windows.csv\"),\n", " \"t3\": pd.read_csv(r / \"task3/manifests/train.csv\"),\n", " \"t4\": pd.read_csv(r / \"task4/manifests/train.csv\"),\n", " }\n", " if C.SMOKE:\n", " m[\"t1\"] = m[\"t1\"].head(C.LIMITS[\"t1\"])\n", " m[\"t4\"] = m[\"t4\"][m[\"t4\"].record_id.str[3:].isin(m[\"t1\"].record_id.str[3:])]\n", " keep_files = m[\"t2\"].fhr_path.drop_duplicates().head(max(1, C.LIMITS[\"t2\"] // 4))\n", " m[\"t2\"] = m[\"t2\"][m[\"t2\"].fhr_path.isin(keep_files)].head(C.LIMITS[\"t2\"])\n", " m[\"t3\"] = m[\"t3\"].head(C.LIMITS[\"t3\"])\n", " return m\n", "\n", "\n", "def targets(m):\n", " paths = set()\n", " paths.update(m[\"t1\"].wav_path)\n", " paths.update(m[\"t1\"].fetal_path)\n", " paths.update(m[\"t2\"].fhr_path)\n", " paths.update(m[\"t3\"].fhr_path)\n", " paths.update(m[\"t4\"].wav_path)\n", " paths.update(m[\"t4\"].fetal_path)\n", " paths.update(m[\"t4\"].segmentation_path)\n", " return sorted(paths)\n", "\n", "\n", "def build_ledger(rel_paths, log):\n", " led = load_json(LEDGER, {})\n", " missing = []\n", " for rp in rel_paths:\n", " p = C.RAW / rp\n", " if rp in led:\n", " continue\n", " if is_lfs_pointer(p):\n", " led[rp] = dict(parse_pointer(p), status=\"pending\")\n", " elif p.exists():\n", " missing.append(rp)\n", " else:\n", " raise FileNotFoundError(p)\n", " for rp in missing:\n", " out = subprocess.run([\"git\", \"-C\", str(C.REPO), \"show\", f\"HEAD:data/{rp}\"], capture_output=True)\n", " txt = out.stdout[:200]\n", " if txt.startswith(b\"version https://git-lfs\"):\n", " tmp = C.CACHE / \".ptr\"\n", " tmp.write_bytes(out.stdout)\n", " led[rp] = dict(parse_pointer(tmp), status=\"pending\")\n", " else:\n", " led[rp] = {\"oid\": None, \"size\": (C.RAW / rp).stat().st_size, \"status\": \"regular\"}\n", " save_json(LEDGER, led)\n", " log.info(f\"ledger entries: {len(led)} (recovered {len(missing)} via git show)\")\n", " return led\n", "\n", "\n", "def sha256_file(p):\n", " h = hashlib.sha256()\n", " with open(p, \"rb\") as f:\n", " for b in iter(lambda: f.read(1 << 22), b\"\"):\n", " h.update(b)\n", " return h.hexdigest()\n", "\n", "\n", "def session():\n", " if not hasattr(_local, \"s\"):\n", " s = requests.Session()\n", " s.headers[\"User-Agent\"] = \"ctg-research-pipeline\"\n", " _local.s = s\n", " return _local.s\n", "\n", "\n", "def download(rp, oid, size, tries=10):\n", " dst = C.RAW / rp\n", " part = dst.with_name(dst.name + \".part\")\n", " url = C.LFS_MEDIA + \"data/\" + rp\n", " for i in range(tries):\n", " try:\n", " with session().get(url, stream=True, timeout=(20, 120)) as r:\n", " if r.status_code in (429, 500, 502, 503, 504):\n", " wait = float(r.headers.get(\"Retry-After\", 0) or 0) or min(120, 2 ** i)\n", " time.sleep(wait + 0.5 * i)\n", " continue\n", " r.raise_for_status()\n", " h = hashlib.sha256()\n", " n = 0\n", " with open(part, \"wb\") as f:\n", " for chunk in r.iter_content(1 << 20):\n", " f.write(chunk)\n", " h.update(chunk)\n", " n += len(chunk)\n", " if n != size or h.hexdigest() != oid:\n", " raise IOError(f\"verification failed {rp}: size {n}/{size}\")\n", " os.replace(part, dst)\n", " return True\n", " except (requests.RequestException, IOError) as e:\n", " if part.exists():\n", " part.unlink()\n", " if i == tries - 1:\n", " raise\n", " time.sleep(min(120, 2 ** i))\n", " return False\n", "\n", "\n", "def place_duplicate(src, dst):\n", " tmp = dst.with_name(dst.name + \".link\")\n", " if tmp.exists():\n", " tmp.unlink()\n", " try:\n", " os.link(src, tmp)\n", " except OSError:\n", " shutil.copyfile(src, tmp)\n", " os.replace(tmp, dst)\n", "\n", "\n", "@stage(\"s01_acquire\", outputs=[lambda: C.CACHE / \"lfs_ledger.json\", lambda: C.REPO / \".git\", lambda: C.REPO / \"checkpoints\" / \"task1_autofhr.pt\", lambda: C.REPO / \"ctg_baseline\" / \"tools.py\", lambda: C.DATA / \"raw_verified.flag\"])\n", "def run(log):\n", " head = clone(log)\n", " m = manifests()\n", " rel = targets(m)\n", " led = build_ledger(rel, log)\n", " todo = {}\n", " for rp in rel:\n", " e = led[rp]\n", " p = C.RAW / rp\n", " if e[\"status\"] == \"verified\" and (not p.exists() or is_lfs_pointer(p) or p.stat().st_size != e[\"size\"]):\n", " e[\"status\"] = \"pending\"\n", " if e[\"status\"] in (\"verified\", \"regular\"):\n", " continue\n", " p = C.RAW / rp\n", " if p.exists() and not is_lfs_pointer(p) and p.stat().st_size == e[\"size\"] and sha256_file(p) == e[\"oid\"]:\n", " e[\"status\"] = \"verified\"\n", " continue\n", " todo.setdefault(e[\"oid\"], []).append(rp)\n", " need = sum(led[v[0]][\"size\"] for v in todo.values())\n", " free = shutil.disk_usage(C.DATA).free\n", " log.info(f\"to download: {len(todo)} unique objects, {need / 2 ** 30:.2f} GiB; free {free / 2 ** 30:.2f} GiB\")\n", " if need > free - 2 * 2 ** 30:\n", " raise OSError(f\"not enough disk space in {C.DATA}: need {need / 2 ** 30:.1f} GiB + 2 GiB margin\")\n", " done = 0\n", " t0 = time.time()\n", " failures = []\n", "\n", " def job(oid, rps):\n", " first = rps[0]\n", " download(first, oid, led[first][\"size\"])\n", " for other in rps[1:]:\n", " place_duplicate(C.RAW / first, C.RAW / other)\n", " return rps\n", "\n", " with ThreadPoolExecutor(C.DL_THREADS) as ex:\n", " futs = {ex.submit(job, oid, rps): oid for oid, rps in todo.items()}\n", " for f in as_completed(futs):\n", " try:\n", " rps = f.result()\n", " with _lock:\n", " for rp in rps:\n", " led[rp][\"status\"] = \"verified\"\n", " done += 1\n", " if done % 200 == 0:\n", " save_json(LEDGER, led)\n", " log.info(f\"{done}/{len(todo)} objects, {time.time() - t0:.0f}s\")\n", " except Exception as e:\n", " failures.append((futs[f], repr(e)))\n", " save_json(LEDGER, led)\n", " if failures:\n", " raise RuntimeError(f\"{len(failures)} downloads failed, rerun to resume: {failures[:5]}\")\n", " for rp in rel:\n", " if led[rp][\"status\"] != \"regular\" and is_lfs_pointer(C.RAW / rp):\n", " raise RuntimeError(f\"pointer still present: {rp}\")\n", " dup = sum(len(v) - 1 for v in todo.values())\n", " (C.DATA / \"raw_verified.flag\").write_text(time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n", " return {\"commit\": head, \"files\": len(rel), \"downloaded_objects\": len(todo), \"deduplicated_paths\": dup, \"smoke\": C.SMOKE}" ] }, { "cell_type": "code", "execution_count": 9, "id": "279952435929", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.688703Z", "iopub.status.busy": "2026-11-28T14:17:32.688371Z", "iopub.status.idle": "2026-11-28T14:17:32.697480Z", "shell.execute_reply": "2026-11-28T14:17:32.695850Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/consolidate.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/consolidate.py\n", "import hashlib\n", "from concurrent.futures import ProcessPoolExecutor\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .acquire import manifests\n", "from .io import fit_len, load_fetal, read_csv\n", "from .utils import finalize_memmap, open_memmap_new, save_df, save_json, stage\n", "\n", "\n", "def _t2_file(path):\n", " d = read_csv(C.RAW / path, [\"fhr\", \"baseline\", \"accAndDec\"])\n", " return path, d\n", "\n", "\n", "def _t3_file(path):\n", " d = read_csv(C.RAW / path, [\"FHR\", \"UC\"])\n", " return fit_len(d.get(\"FHR\", np.full(C.N, np.nan))), fit_len(d.get(\"UC\", np.full(C.N, np.nan))), int(d[\"FHR\"].size if \"FHR\" in d else 0)\n", "\n", "\n", "def _t4_rec(args):\n", " fetal, seg = args\n", " x = load_fetal(C.RAW / fetal)\n", " with np.load(C.RAW / seg) as z:\n", " s = z[\"accAndDec\"].astype(np.int8)\n", " return fit_len(x), x.size, s, s.size\n", "\n", "\n", "def _fetal_hash(path):\n", " x = load_fetal(C.RAW / path)\n", " return hashlib.sha1(np.nan_to_num(x, nan=-1).tobytes()).hexdigest(), x.size\n", "\n", "\n", "def build_t4(log):\n", " m = manifests()[\"t4\"].reset_index(drop=True)\n", " n = len(m)\n", " fhr, tf, pf = open_memmap_new(C.CACHE / \"t4_fhr.npy\", (n, C.N), np.float16)\n", " seg, ts, ps = open_memmap_new(C.CACHE / \"t4_seg.npy\", (n, C.N), np.int8)\n", " lens = np.zeros(n, int)\n", " slens = np.zeros(n, int)\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " for i, (x, ln, s, sl) in enumerate(ex.map(_t4_rec, zip(m.fetal_path, m.segmentation_path), chunksize=32)):\n", " fhr[i] = x\n", " seg[i, :min(sl, C.N)] = s[:C.N]\n", " if sl < C.N:\n", " seg[i, sl:] = -9\n", " lens[i], slens[i] = ln, sl\n", " finalize_memmap(fhr, tf, pf)\n", " finalize_memmap(seg, ts, ps)\n", " meta = pd.DataFrame({\"record_id\": m.record_id, \"num\": m.record_id.str[3:], \"wav_path\": m.wav_path, \"y\": m.risk_label.astype(int), \"fhr_len\": lens, \"seg_len\": slens})\n", " save_df(C.CACHE / \"t4_meta.pkl\", meta)\n", " return meta\n", "\n", "\n", "def t1_vs_t4(meta, log):\n", " m1 = manifests()[\"t1\"].reset_index(drop=True)\n", " m1[\"num\"] = m1.record_id.str[3:]\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " h1 = dict(zip(m1.num, (h for h, _ in ex.map(_fetal_hash, m1.fetal_path, chunksize=32))))\n", " h4 = dict(zip(meta.num, (h for h, _ in ex.map(_fetal_hash, manifests()[\"t4\"].fetal_path, chunksize=32))))\n", " same_num = sum(1 for k in h1 if h4.get(k) == h1[k])\n", " rev4 = {v: k for k, v in h4.items()}\n", " cross = sum(1 for k, v in h1.items() if v in rev4 and rev4[v] != k)\n", " m1.to_csv(C.CACHE / \"t1_manifest_used.csv\", index=False)\n", " return {\"t1_records\": len(h1), \"t4_records\": len(h4), \"identical_same_number\": same_num, \"identical_other_number\": cross, \"t1_equals_t4\": same_num == len(h1) == len(h4)}\n", "\n", "\n", "def build_t2(log):\n", " m = manifests()[\"t2\"].reset_index(drop=True)\n", " files = m.fhr_path.unique().tolist()\n", " data = {}\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " for p, d in ex.map(_t2_file, files, chunksize=8):\n", " data[p] = d\n", " n = len(m)\n", " fhr, tf, pf = open_memmap_new(C.CACHE / \"t2_fhr.npy\", (n, C.N), np.float16)\n", " base, tb, pb = open_memmap_new(C.CACHE / \"t2_base.npy\", (n, C.N), np.float16)\n", " lab, tl, pl = open_memmap_new(C.CACHE / \"t2_lab.npy\", (n, C.N), np.int8)\n", " issues = []\n", " for i, r in m.iterrows():\n", " d = data[r.fhr_path]\n", " a, b = int(r.window_start_sample), int(r.window_end_sample)\n", " x = d[\"fhr\"][a:b]\n", " y = d[\"accAndDec\"][a:b]\n", " bl = d.get(\"baseline\", np.full(d[\"fhr\"].size, np.nan))[a:b]\n", " if b - a != C.N or x.size != C.N:\n", " issues.append(r.record_id)\n", " fhr[i] = fit_len(x)\n", " base[i] = fit_len(bl)\n", " yy = np.full(C.N, -9, np.int8)\n", " yv = np.where(np.isfinite(y), y, -9).astype(np.int8)\n", " yy[:min(C.N, yv.size)] = yv[:C.N]\n", " lab[i] = yy\n", " finalize_memmap(fhr, tf, pf)\n", " finalize_memmap(base, tb, pb)\n", " finalize_memmap(lab, tl, pl)\n", " src = {p: k for k, p in enumerate(files)}\n", " meta = pd.DataFrame({\"record_id\": m.record_id, \"source\": m.fhr_path.map(src).astype(int), \"start\": m.window_start_sample, \"end\": m.window_end_sample})\n", " meta[\"file_len\"] = m.fhr_path.map({p: d[\"fhr\"].size for p, d in data.items()})\n", " save_df(C.CACHE / \"t2_meta.pkl\", meta)\n", " return meta, issues\n", "\n", "\n", "def build_t3(log):\n", " m = manifests()[\"t3\"].reset_index(drop=True)\n", " n = len(m)\n", " fhr, tf, pf = open_memmap_new(C.CACHE / \"t3_fhr.npy\", (n, C.N), np.float16)\n", " uc, tu, pu = open_memmap_new(C.CACHE / \"t3_uc.npy\", (n, C.N), np.float16)\n", " lens = np.zeros(n, int)\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " for i, (x, u, ln) in enumerate(ex.map(_t3_file, m.fhr_path, chunksize=64)):\n", " fhr[i] = x\n", " uc[i] = np.clip(u, -1000, 60000)\n", " lens[i] = ln\n", " if i % 5000 == 0:\n", " log.info(f\"t3 {i}/{n}\")\n", " finalize_memmap(fhr, tf, pf)\n", " finalize_memmap(uc, tu, pu)\n", " meta = pd.DataFrame({\"record_id\": m.record_id, \"y\": m.label.astype(int), \"len\": lens})\n", " save_df(C.CACHE / \"t3_meta.pkl\", meta)\n", " return meta\n", "\n", "\n", "@stage(\"s02_consolidate\", outputs=[C.CACHE / \"t4_fhr.npy\", C.CACHE / \"t4_seg.npy\", C.CACHE / \"t2_fhr.npy\", C.CACHE / \"t2_lab.npy\", C.CACHE / \"t3_fhr.npy\", C.CACHE / \"t3_uc.npy\", C.CACHE / \"t4_meta.pkl\"])\n", "def run(log):\n", " meta4 = build_t4(log)\n", " ident = t1_vs_t4(meta4, log)\n", " log.info(f\"T1 vs T4: {ident}\")\n", " meta2, issues2 = build_t2(log)\n", " meta3 = build_t3(log)\n", " info = {\"t4\": len(meta4), \"t2\": len(meta2), \"t3\": len(meta3), \"t1_vs_t4\": ident, \"t2_window_issues\": len(issues2)}\n", " save_json(C.RES / \"s02_consolidate.json\", info)\n", " return info" ] }, { "cell_type": "code", "execution_count": 10, "id": "75e495ff7e2b", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.701050Z", "iopub.status.busy": "2026-11-28T14:17:32.700655Z", "iopub.status.idle": "2026-11-28T14:17:32.713348Z", "shell.execute_reply": "2026-11-28T14:17:32.711762Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/audit.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/audit.py\n", "from concurrent.futures import ProcessPoolExecutor\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from numpy.lib.stride_tricks import sliding_window_view\n", "\n", "from . import config as C\n", "from .acquire import manifests\n", "from .io import events, valid, wav_header\n", "from .utils import bootstrap, load_df, mm, save_json, save_npz, stage\n", "\n", "EXPECTED = {\"t1\": 3016, \"t2\": 5296, \"t3\": 26294, \"t4\": 3016}\n", "SENT = np.iinfo(np.uint64).max\n", "MIX = np.uint64(0x9E3779B97F4A7C15)\n", "\n", "\n", "def sources():\n", " return [(\"t4\", C.CACHE / \"t4_fhr.npy\"), (\"t2\", C.CACHE / \"t2_fhr.npy\"), (\"t3\", C.CACHE / \"t3_fhr.npy\")]\n", "\n", "\n", "def weights(k):\n", " rng = np.random.default_rng(C.SEED + k)\n", " return rng.integers(1, 2 ** 20, size=k, dtype=np.int64), rng.integers(1, 2 ** 20, size=k, dtype=np.int64)\n", "\n", "\n", "def fingerprints(x, k, w1, w2, w=C.FP_WINNOW):\n", " v = valid(x)\n", " if x.size < k + w:\n", " return np.zeros(0, np.uint64)\n", " xi = np.where(v, np.rint(np.nan_to_num(x)), 0).astype(np.int64)\n", " h1 = np.correlate(xi, w1, \"valid\").astype(np.uint64)\n", " h2 = np.correlate(xi, w2, \"valid\").astype(np.uint64)\n", " fp = (h1 * MIX) ^ h2\n", " bad = np.convolve((~v).astype(np.int32), np.ones(k, np.int32), \"valid\") > 0\n", " sw = sliding_window_view(xi, k)\n", " bad |= (sw.max(1) - sw.min(1)) < 5\n", " fp[bad] = SENT\n", " win = sliding_window_view(fp, w)\n", " pos = np.unique(win.argmin(1) + np.arange(win.shape[0]))\n", " sel = fp[pos]\n", " return np.unique(sel[sel != SENT])\n", "\n", "\n", "def _fp_chunk(args):\n", " path, lo, hi, k = args\n", " arr = mm(path)\n", " w1, w2 = weights(k)\n", " out_fp, out_id = [], []\n", " for i in range(lo, hi):\n", " f = fingerprints(np.asarray(arr[i], np.float32), k, w1, w2)\n", " out_fp.append(f)\n", " out_id.append(np.full(f.size, i, np.int64))\n", " return lo, np.concatenate(out_fp) if out_fp else np.zeros(0, np.uint64), np.concatenate(out_id) if out_id else np.zeros(0, np.int64)\n", "\n", "\n", "class DSU:\n", " def __init__(self, n):\n", " self.p = np.arange(n)\n", "\n", " def find(self, a):\n", " r = a\n", " while self.p[r] != r:\n", " r = self.p[r]\n", " while self.p[a] != r:\n", " self.p[a], a = r, self.p[a]\n", " return r\n", "\n", " def union(self, a, b):\n", " ra, rb = self.find(a), self.find(b)\n", " if ra != rb:\n", " self.p[max(ra, rb)] = min(ra, rb)\n", "\n", "\n", "def link_groups(k, log):\n", " offs, sizes, fps, ids = {}, {}, [], []\n", " base = 0\n", " for name, path in sources():\n", " n = mm(path).shape[0]\n", " offs[name], sizes[name] = base, n\n", " step = max(16, n // (C.CPU * 8) or 16)\n", " jobs = [(path, lo, min(n, lo + step), k) for lo in range(0, n, step)]\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " for lo, f, i in ex.map(_fp_chunk, jobs):\n", " fps.append(f)\n", " ids.append(i + base)\n", " base += n\n", " fp = np.concatenate(fps)\n", " rid = np.concatenate(ids)\n", " order = np.lexsort((rid, fp))\n", " fp, rid = fp[order], rid[order]\n", " starts = np.flatnonzero(np.r_[True, fp[1:] != fp[:-1]])\n", " ends = np.r_[starts[1:], fp.size]\n", " multi = np.flatnonzero((ends - starts >= 2) & (ends - starts <= 50))\n", " counts = {}\n", " for g in multi:\n", " r = rid[starts[g]:ends[g]]\n", " for a in range(r.size):\n", " for b in range(a + 1, r.size):\n", " key = (int(r[a]), int(r[b]))\n", " counts[key] = counts.get(key, 0) + 1\n", " dsu = DSU(base)\n", " links = 0\n", " for (a, b), c in counts.items():\n", " if c >= C.FP_MIN_SHARED:\n", " dsu.union(a, b)\n", " links += 1\n", " comp = np.array([dsu.find(i) for i in range(base)])\n", " log.info(f\"k={k}: anchors {fp.size}, linked pairs {links}\")\n", " return comp, offs, sizes, links\n", "\n", "\n", "def group_report(comp, offs, sizes):\n", " rep = {}\n", " task_of = np.empty(comp.size, object)\n", " for t in offs:\n", " task_of[offs[t]:offs[t] + sizes[t]] = t\n", " s = pd.Series(comp)\n", " csize = s.map(s.value_counts())\n", " for t in offs:\n", " sl = slice(offs[t], offs[t] + sizes[t])\n", " rep[f\"{t}_records_in_multi_groups\"] = int((csize.values[sl] > 1).sum())\n", " rep[f\"{t}_n_groups\"] = int(np.unique(comp[sl]).size)\n", " df = pd.DataFrame({\"c\": comp, \"t\": task_of})\n", " tasks_per = df.groupby(\"c\").t.agg(lambda v: tuple(sorted(set(v))))\n", " for a, b in ((\"t2\", \"t3\"), (\"t2\", \"t4\"), (\"t3\", \"t4\")):\n", " cs = tasks_per[tasks_per.map(lambda v: a in v and b in v)].index\n", " rep[f\"cross_{a}_{b}_groups\"] = int(cs.size)\n", " rep[\"largest_group\"] = int(csize.max())\n", " return rep\n", "\n", "\n", "def t3_pair_rule(log):\n", " x = mm(C.CACHE / \"t3_fhr.npy\")\n", " y = load_df(C.CACHE / \"t3_meta.pkl\").y.values\n", " n = x.shape[0]\n", " half = C.N // 2\n", "\n", " def match(i, j):\n", " a = np.asarray(x[i][half:], np.float32)\n", " b = np.asarray(x[j][:half], np.float32)\n", " v = valid(a) & valid(b)\n", " return float(np.mean(a[v] == b[v])) if v.sum() > 240 else np.nan\n", "\n", " even = np.array([match(i, i + 1) for i in range(0, n - 1, 2)])\n", " odd = np.array([match(i, i + 1) for i in range(1, n - 1, 2)])\n", " lab_eq = np.mean(y[0:n - 1:2] == y[1:n:2])\n", " return {\n", " \"pairs_checked\": int(even.size),\n", " \"pairs_with_600s_overlap\": float(np.nanmean(even >= 0.99)),\n", " \"odd_boundary_overlap\": float(np.nanmean(odd >= 0.99)) if odd.size else np.nan,\n", " \"pair_label_agreement\": float(lab_eq),\n", " \"pairs_unmeasurable\": int(np.isnan(even).sum()),\n", " }\n", "\n", "\n", "def gap_lengths(x):\n", " bad = ~valid(x)\n", " if not bad.any():\n", " return np.zeros(0)\n", " d = np.diff(np.r_[0, bad.astype(np.int8), 0])\n", " return (np.flatnonzero(d == -1) - np.flatnonzero(d == 1)) / C.FS_FHR\n", "\n", "\n", "def missing_stats(arr, labels=None, name=\"\"):\n", " n = arr.shape[0]\n", " rate = np.zeros(n)\n", " gaps = []\n", " for i in range(n):\n", " x = np.asarray(arr[i], np.float32)\n", " rate[i] = 1 - valid(x).mean()\n", " gaps.append(gap_lengths(x))\n", " g = np.concatenate(gaps) if gaps else np.zeros(0)\n", " out = {\n", " \"missing_rate_mean\": float(rate.mean()),\n", " \"missing_rate_median\": float(np.median(rate)),\n", " \"frac_any_missing\": float((rate > 0).mean()),\n", " \"frac_over_5pct\": float((rate > 0.05).mean()),\n", " \"frac_over_20pct\": float((rate > 0.2).mean()),\n", " \"frac_fully_missing\": float((rate >= 0.999).mean()),\n", " \"n_gaps\": int(g.size),\n", " }\n", " if g.size:\n", " out.update({\n", " \"gap_median_s\": float(np.median(g)),\n", " \"gap_p90_s\": float(np.quantile(g, 0.9)),\n", " \"gap_frac_ge15s\": float((g >= 15).mean()),\n", " \"gap_frac_ge30s\": float((g >= 30).mean()),\n", " \"gap_frac_ge60s\": float((g >= 60).mean()),\n", " \"missing_time_share_ge30s\": float(g[g >= 30].sum() / g.sum()),\n", " })\n", " if labels is not None:\n", " for v in np.unique(labels):\n", " out[f\"missing_rate_mean_label{int(v)}\"] = float(rate[labels == v].mean())\n", " return out, rate\n", "\n", "\n", "def near_event_missing(log):\n", " x = mm(C.CACHE / \"t4_fhr.npy\")\n", " s = mm(C.CACHE / \"t4_seg.npy\")\n", " n = x.shape[0]\n", " rows = []\n", " for i in range(n):\n", " bad = ~valid(np.asarray(x[i], np.float32))\n", " for val, nm in ((-1, \"dec\"), (1, \"acc\")):\n", " near = np.zeros(C.N, bool)\n", " for a, b in events(np.asarray(s[i]), val):\n", " near[max(0, a - 120):min(C.N, b + 120)] = True\n", " rows.append((i, nm, bad[near].sum(), near.sum(), bad[~near].sum(), (~near).sum()))\n", " df = pd.DataFrame(rows, columns=[\"rec\", \"ev\", \"bn\", \"nn\", \"bf\", \"nf\"])\n", " out = {}\n", " for nm in (\"dec\", \"acc\"):\n", " d = df[df.ev == nm].reset_index(drop=True)\n", "\n", " def ratio(idx, d=d):\n", " dd = d.iloc[idx]\n", " a = dd.bn.sum() / max(1, dd.nn.sum())\n", " b = dd.bf.sum() / max(1, dd.nf.sum())\n", " return a / b if b > 0 else np.nan\n", "\n", " out[f\"{nm}_missing_near\"] = float(d.bn.sum() / max(1, d.nn.sum()))\n", " out[f\"{nm}_missing_far\"] = float(d.bf.sum() / max(1, d.nf.sum()))\n", " out[f\"{nm}_ratio\"] = bootstrap(ratio, d.rec.values)\n", " return out\n", "\n", "\n", "def wav_audit(log):\n", " m = manifests()[\"t1\"]\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " h = list(ex.map(wav_header, [C.RAW / p for p in m.wav_path], chunksize=32))\n", " sr = np.array([a[0] for a in h])\n", " ln = np.array([a[1] for a in h])\n", " return {\"n\": len(h), \"sr_values\": sorted(set(sr.tolist())), \"len_values\": sorted(set(ln.tolist()))[:10], \"dtypes\": sorted(set(a[2] for a in h)), \"channels\": sorted(set(a[3] for a in h)), \"all_1khz_20min\": bool((sr == C.FS_DUS).all() and (ln == C.FS_DUS * 1200).all())}\n", "\n", "\n", "@stage(\"s03_audit\", outputs=[C.CACHE / \"missing_rates.npz\", C.CACHE / f\"fp_groups_k{C.FP_K_MAIN}.npz\"])\n", "def run(log):\n", " rep = {\"smoke\": C.SMOKE}\n", " m4 = load_df(C.CACHE / \"t4_meta.pkl\")\n", " m2 = load_df(C.CACHE / \"t2_meta.pkl\")\n", " m3 = load_df(C.CACHE / \"t3_meta.pkl\")\n", " counts = {\"t1\": len(pd.read_csv(C.CACHE / \"t1_manifest_used.csv\")), \"t2\": len(m2), \"t3\": len(m3), \"t4\": len(m4)}\n", " rep[\"counts\"] = counts\n", " rep[\"count_check\"] = {k: (v == EXPECTED[k]) for k, v in counts.items()} if not C.SMOKE else \"skipped in smoke mode\"\n", " rep[\"wav\"] = wav_audit(log)\n", " rep[\"t4_fhr_len_values\"] = sorted(set(m4.fhr_len.tolist()))\n", " rep[\"t4_seg_len_values\"] = sorted(set(m4.seg_len.tolist()))\n", " s4 = mm(C.CACHE / \"t4_seg.npy\")\n", " l2 = mm(C.CACHE / \"t2_lab.npy\")\n", " rep[\"t4_seg_values\"] = {int(v): int(c) for v, c in zip(*np.unique(np.asarray(s4), return_counts=True))}\n", " rep[\"t2_label_values\"] = {int(v): int(c) for v, c in zip(*np.unique(np.asarray(l2), return_counts=True))}\n", " rep[\"t4_prevalence\"] = float(m4.y.mean())\n", " rep[\"t3_prevalence\"] = float(m3.y.mean())\n", " rep[\"t3_len_values\"] = sorted(set(m3.len.tolist()))[:10]\n", " rep[\"t2_window_len_ok\"] = float(((m2.end - m2.start) == C.N).mean())\n", " rep[\"t2_window_in_file\"] = float((m2.end <= m2.file_len).mean())\n", " ov = 0\n", " for _, g in m2.sort_values([\"source\", \"start\"]).groupby(\"source\"):\n", " ov += int((g.start.values[1:] < g.end.values[:-1]).sum())\n", " rep[\"t2_overlapping_windows_within_file\"] = ov\n", " rep[\"t2_baseline_annotated_frac\"] = float(np.mean(np.isfinite(np.asarray(mm(C.CACHE / \"t2_base.npy\"), np.float32))))\n", " rep[\"missing\"] = {}\n", " rates = {}\n", " for t, path, lab in ((\"t4\", \"t4_fhr.npy\", m4.y.values), (\"t2\", \"t2_fhr.npy\", None), (\"t3\", \"t3_fhr.npy\", m3.y.values)):\n", " rep[\"missing\"][t], rates[t] = missing_stats(mm(C.CACHE / path), lab, t)\n", " save_npz(C.CACHE / \"missing_rates.npz\", **rates)\n", " rep[\"t4_missing_near_events\"] = near_event_missing(log)\n", " rep[\"t3_pair_rule\"] = t3_pair_rule(log)\n", " rep[\"fingerprints\"] = {}\n", " for k in C.FP_KS:\n", " comp, offs, sizes, links = link_groups(k, log)\n", " rep[\"fingerprints\"][str(k)] = dict(group_report(comp, offs, sizes), linked_pairs=links)\n", " save_npz(C.CACHE / f\"fp_groups_k{k}.npz\", comp=comp, **{f\"off_{t}\": np.array([offs[t], sizes[t]]) for t in offs})\n", " save_json(C.RES / \"s03_audit.json\", rep)\n", " return {\"t3_pairs_600s\": rep[\"t3_pair_rule\"][\"pairs_with_600s_overlap\"], \"fp_main\": rep[\"fingerprints\"][str(C.FP_K_MAIN)]}" ] }, { "cell_type": "code", "execution_count": 11, "id": "cc315ef1ecb3", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.717196Z", "iopub.status.busy": "2026-11-28T14:17:32.716778Z", "iopub.status.idle": "2026-11-28T14:17:32.726232Z", "shell.execute_reply": "2026-11-28T14:17:32.724153Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/folds.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/folds.py\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.model_selection import StratifiedGroupKFold\n", "\n", "from . import config as C\n", "from .audit import DSU\n", "from .utils import load_df, load_npz, mm, save_df, save_json, stage\n", "\n", "\n", "def components(k):\n", " z = load_npz(C.CACHE / f\"fp_groups_k{k}.npz\")\n", " out = {}\n", " for t in (\"t4\", \"t2\", \"t3\"):\n", " o, n = z[f\"off_{t}\"]\n", " out[t] = z[\"comp\"][o:o + n]\n", " return out\n", "\n", "\n", "def assign(groups, strat, seed):\n", " n = len(groups)\n", " fold = np.full(n, -2, int)\n", " sg = StratifiedGroupKFold(n_splits=int(round(1 / C.HOLDOUT_FRAC)), shuffle=True, random_state=seed)\n", " _, hold = next(sg.split(np.zeros(n), strat, groups))\n", " fold[hold] = -1\n", " rest = np.flatnonzero(fold != -1)\n", " sg5 = StratifiedGroupKFold(n_splits=C.N_FOLDS, shuffle=True, random_state=seed + 1)\n", " for f, (_, te) in enumerate(sg5.split(np.zeros(rest.size), strat[rest], groups[rest])):\n", " fold[rest[te]] = f\n", " assert (fold >= -1).all()\n", " return fold\n", "\n", "\n", "def merge(*labels):\n", " n = len(labels[0])\n", " d = DSU(n)\n", " for lab in labels:\n", " first = {}\n", " for i, g in enumerate(lab):\n", " if g in first:\n", " d.union(i, first[g])\n", " else:\n", " first[g] = i\n", " return np.array([d.find(i) for i in range(n)])\n", "\n", "\n", "def tercile(x):\n", " x = np.asarray(x, float)\n", " if np.unique(x).size < 3:\n", " return np.zeros(x.size, int)\n", " return np.digitize(x, np.quantile(x, [1 / 3, 2 / 3]))\n", "\n", "\n", "def check(fold, groups, strat):\n", " rep = {\"n\": int(len(fold)), \"holdout\": int((fold == -1).sum())}\n", " leak = 0\n", " for g in np.unique(groups):\n", " if np.unique(fold[groups == g]).size > 1:\n", " leak += 1\n", " rep[\"groups_split_across_folds\"] = leak\n", " rep[\"fold_sizes\"] = {int(f): int((fold == f).sum()) for f in np.unique(fold)}\n", " rep[\"fold_prevalence\"] = {int(f): float(np.mean(strat[fold == f])) for f in np.unique(fold)}\n", " return rep\n", "\n", "\n", "def inner_split(meta, fold, frac=0.12, seed=C.SEED):\n", " tr = meta.index[(meta.fold >= 0) & (meta.fold != fold)].values\n", " g = meta.group.values[tr]\n", " s = meta.strat.values[tr]\n", " n_splits = max(2, int(round(1 / frac)))\n", " for strat in (s, s % 3 if s.max() > 2 else s, None):\n", " try:\n", " if strat is None:\n", " from sklearn.model_selection import GroupShuffleSplit\n", " a, b = next(GroupShuffleSplit(n_splits=1, test_size=frac, random_state=seed + 100 + fold).split(np.zeros(tr.size), groups=g))\n", " else:\n", " sg = StratifiedGroupKFold(n_splits=n_splits, shuffle=True, random_state=seed + 100 + fold)\n", " a, b = next(sg.split(np.zeros(tr.size), strat, g))\n", " if a.size and b.size:\n", " return tr[a], tr[b]\n", " except ValueError:\n", " continue\n", " raise ValueError(\"cannot build an inner validation split\")\n", "\n", "\n", "@stage(\"s04_folds\", outputs=[C.CACHE / \"folds_t4.pkl\", C.CACHE / \"folds_t2.pkl\", C.CACHE / \"folds_t3.pkl\"])\n", "def run(log):\n", " comp = components(C.FP_K_MAIN)\n", " rates = load_npz(C.CACHE / \"missing_rates.npz\")\n", " rep = {}\n", " m4 = load_df(C.CACHE / \"t4_meta.pkl\")\n", " g4 = merge(m4.num.values, comp[\"t4\"])\n", " s4 = m4.y.values * 3 + tercile(rates[\"t4\"])\n", " m4[\"group\"], m4[\"strat\"] = g4, s4\n", " m4[\"fold\"] = assign(g4, s4, C.SEED)\n", " rep[\"t4_t1\"] = check(m4.fold.values, g4, m4.y.values)\n", " save_df(C.CACHE / \"folds_t4.pkl\", m4)\n", " m2 = load_df(C.CACHE / \"t2_meta.pkl\")\n", " lab = mm(C.CACHE / \"t2_lab.npy\")\n", " burden = np.array([np.mean(np.asarray(lab[i]) == -1) for i in range(len(m2))])\n", " g2 = merge(m2.source.values, comp[\"t2\"])\n", " s2 = tercile(burden)\n", " m2[\"group\"], m2[\"strat\"], m2[\"dec_burden\"] = g2, s2, burden\n", " m2[\"fold\"] = assign(g2, s2, C.SEED)\n", " rep[\"t2\"] = check(m2.fold.values, g2, burden)\n", " save_df(C.CACHE / \"folds_t2.pkl\", m2)\n", " m3 = load_df(C.CACHE / \"t3_meta.pkl\")\n", " pair = np.arange(len(m3)) // 2\n", " g3 = merge(pair, comp[\"t3\"])\n", " s3 = m3.y.values\n", " m3[\"group\"], m3[\"strat\"], m3[\"pair\"] = g3, s3, pair\n", " m3[\"fold\"] = assign(g3, s3, C.SEED)\n", " rep[\"t3\"] = check(m3.fold.values, g3, s3)\n", " alt = {}\n", " for k in C.FP_KS:\n", " ck = components(k)[\"t3\"]\n", " gk = merge(pair, ck)\n", " alt[str(k)] = {\"n_groups\": int(np.unique(gk).size), \"groups_split_by_main_folds\": int(sum(np.unique(m3.fold.values[gk == g]).size > 1 for g in np.unique(gk)))}\n", " rep[\"t3_sensitivity_by_k\"] = alt\n", " m3[\"fold_random\"] = np.random.default_rng(C.SEED).integers(0, C.N_FOLDS, len(m3))\n", " m3.loc[m3.fold == -1, \"fold_random\"] = -1\n", " save_df(C.CACHE / \"folds_t3.pkl\", m3)\n", " for t, r in rep.items():\n", " if isinstance(r, dict) and r.get(\"groups_split_across_folds\", 0):\n", " raise AssertionError(f\"group leakage in {t}: {r}\")\n", " save_json(C.RES / \"s04_folds.json\", rep)\n", " return {k: {kk: vv for kk, vv in v.items() if kk in (\"n\", \"holdout\", \"groups_split_across_folds\")} for k, v in rep.items() if \"n\" in v}" ] }, { "cell_type": "code", "execution_count": 12, "id": "0034ca0522d6", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.729933Z", "iopub.status.busy": "2026-11-28T14:17:32.729605Z", "iopub.status.idle": "2026-11-28T14:17:32.745078Z", "shell.execute_reply": "2026-11-28T14:17:32.743279Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/dus.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/dus.py\n", "import inspect\n", "import math\n", "import sys\n", "import time\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import pywt\n", "import torch\n", "import torch.nn.functional as F\n", "from scipy.signal import butter, find_peaks, hilbert, resample_poly, sosfiltfilt\n", "\n", "from . import config as C\n", "from .io import fit_len, read_wav\n", "from .utils import adaptive_batches, mark_done, device, finalize_memmap, free_mem, get_logger, load_df, load_json, load_npz, open_memmap_new, save_json, save_npz, stage\n", "\n", "T1 = {\"sr\": 1000, \"seg\": 3.75, \"stride\": 0.75, \"tb\": 1000, \"fb\": 40, \"min_peak_distance\": 60}\n", "NQ = 6\n", "\n", "\n", "def official():\n", " if str(C.REPO) not in sys.path:\n", " sys.path.insert(0, str(C.REPO))\n", " from ctg_baseline.config import TASK1_CONFIG\n", " from ctg_baseline.models import build_task1_model\n", " return TASK1_CONFIG, build_task1_model\n", "\n", "\n", "def cwt_filters(scales=range(1, 41)):\n", " w = pywt.ContinuousWavelet(\"morl\")\n", " prec = inspect.signature(pywt.cwt).parameters.get(\"precision\")\n", " prec = prec.default if prec is not None and prec.default is not inspect.Parameter.empty else 10\n", " int_psi, x = pywt.integrate_wavelet(w, precision=prec)\n", " int_psi = np.asarray(int_psi, np.float64)\n", " x = np.asarray(x, np.float64)\n", " out = []\n", " for s in scales:\n", " step = x[1] - x[0]\n", " j = (np.arange(s * (x[-1] - x[0]) + 1) / (s * step)).astype(int)\n", " if j[-1] >= int_psi.size:\n", " j = np.extract(j < int_psi.size, j)\n", " out.append(int_psi[j][::-1].copy())\n", " return out\n", "\n", "\n", "def gauss_kernel(sigma, truncate=4.0):\n", " r = int(truncate * sigma + 0.5)\n", " t = np.arange(-r, r + 1, dtype=np.float64)\n", " k = np.exp(-0.5 * (t / sigma) ** 2)\n", " return k / k.sum()\n", "\n", "\n", "class AutoFHRGPU:\n", " def __init__(self, dev):\n", " cfg, build = official()\n", " self.cfg = cfg\n", " self.dev = dev\n", " self.model = build((cfg[\"time_bins\"], cfg[\"freq_bins\"]), cfg).to(dev).eval()\n", " st = torch.load(C.REPO / \"checkpoints/task1_autofhr.pt\", map_location=dev, weights_only=True)\n", " self.model.load_state_dict(st.get(\"model\", st) if isinstance(st, dict) else st)\n", " att = self.model.attention\n", " base_forward = att.forward\n", " att.forward = lambda q, k, v, **kw: base_forward(q, k, v, need_weights=False)\n", " self.start_bs = 64 if dev.type == \"cuda\" else 8\n", " self.filters = [torch.tensor(f[::-1].copy(), dtype=torch.float32, device=dev).view(1, 1, -1) for f in cwt_filters(range(1, cfg[\"freq_bins\"] + 1))]\n", " self.flen = [f.shape[-1] for f in self.filters]\n", " self.gk = torch.tensor(gauss_kernel((3750 / cfg[\"time_bins\"] - 1) / 2), dtype=torch.float32, device=dev).view(1, 1, -1)\n", " nyq = 0.5 * cfg[\"target_sr\"]\n", " lo, hi = min(50.0, nyq - 2.0), min(600.0, nyq - 1.0)\n", " self.sos = butter(4, [lo / nyq, hi / nyq], btype=\"bandpass\", output=\"sos\")\n", "\n", " @torch.no_grad()\n", " def scalogram(self, w):\n", " n = w.shape[-1]\n", " x = w.unsqueeze(1)\n", " rows = []\n", " for s, (f, L) in enumerate(zip(self.filters, self.flen), start=1):\n", " full = F.conv1d(F.pad(x, (L - 1, L - 1)), f)\n", " coef = -math.sqrt(s) * torch.diff(full, dim=-1)\n", " d = (coef.shape[-1] - n) / 2.0\n", " coef = coef[..., math.floor(d): coef.shape[-1] - math.ceil(d)]\n", " rows.append(coef.abs())\n", " a = torch.cat(rows, 1)\n", " b, fb, t = a.shape\n", " r = self.gk.shape[-1] // 2\n", " sm = F.conv1d(F.pad(a.reshape(b * fb, 1, t), (r, r)), self.gk).reshape(b, fb, t)\n", " z = F.interpolate(sm, size=self.cfg[\"time_bins\"], mode=\"linear\", align_corners=False)\n", " z = z.transpose(1, 2)\n", " lo = z.amin(dim=(1, 2), keepdim=True)\n", " hi = z.amax(dim=(1, 2), keepdim=True)\n", " return torch.where(hi > lo, (z - lo) / (hi - lo).clamp_min(1e-12), z)\n", "\n", " def bpm_from_mask(self, m):\n", " peaks, _ = find_peaks(m, height=0.5, distance=self.cfg[\"min_peak_distance\"])\n", " if len(peaks) < 2:\n", " return np.nan\n", " iv = np.diff(peaks).astype(np.float64)\n", " med = np.median(iv)\n", " keep = (iv >= 0.7 * med) & (iv <= 1.3 * med)\n", " mi = np.mean(iv[keep if keep.any() else np.ones_like(keep, bool)])\n", " bpm = 60.0 / (mi * self.cfg[\"segment_duration\"] / self.cfg[\"time_bins\"])\n", " return float(bpm) if C.FHR_MIN <= bpm <= C.FHR_MAX else np.nan\n", "\n", " def windows(self, sig, sr):\n", " win = int(self.cfg[\"segment_duration\"] * sr)\n", " stride = int(self.cfg[\"segment_stride\"] * sr)\n", " starts = np.arange(0, max(1, len(sig) - win + 1), stride)\n", " idx = starts[:, None] + np.arange(win)[None, :]\n", " return starts, sosfiltfilt(self.sos, sig[idx].astype(np.float64), axis=-1).astype(np.float32)\n", "\n", " def scalograms(self, wins, log=None):\n", " def fn(i, j):\n", " return self.scalogram(torch.from_numpy(np.ascontiguousarray(wins[i:j])).to(self.dev)).cpu().numpy()\n", "\n", " return np.concatenate(adaptive_batches(len(wins), fn, self.start_bs * 4, log=log))\n", "\n", " def masks(self, wins, log=None, from_scalogram=False):\n", " def fn(i, j):\n", " x = torch.from_numpy(np.ascontiguousarray(wins[i:j])).to(self.dev)\n", " with torch.no_grad():\n", " z = x if from_scalogram else self.scalogram(x)\n", " return torch.sigmoid(self.model(z)).squeeze(-1).float().cpu().numpy()\n", "\n", " return np.concatenate(adaptive_batches(len(wins), fn, self.start_bs, log=log))\n", "\n", " def run(self, sig, sr, log=None):\n", " starts, wins = self.windows(sig, sr)\n", " masks = self.masks(wins, log)\n", " wb = np.array([self.bpm_from_mask(m) for m in masks], np.float32)\n", " n = int(math.ceil(len(sig) / sr * C.FS_FHR))\n", " tot = np.zeros(n)\n", " sq = np.zeros(n)\n", " cnt = np.zeros(n, np.int32)\n", " span = int(self.cfg[\"segment_duration\"] * C.FS_FHR)\n", " for s, b in zip(starts, wb):\n", " if not np.isfinite(b):\n", " continue\n", " a = int(s / sr * C.FS_FHR)\n", " e = min(a + span, n)\n", " tot[a:e] += b\n", " sq[a:e] += b * b\n", " cnt[a:e] += 1\n", " with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n", " mean = np.where(cnt > 0, tot / np.maximum(cnt, 1), np.nan)\n", " sd = np.where(cnt > 1, np.sqrt(np.maximum(sq / np.maximum(cnt, 1) - mean ** 2, 0)), np.nan)\n", " return mean.astype(np.float32), sd.astype(np.float32), cnt.astype(np.int16), wb, starts\n", "\n", "\n", "class Autocorrelogram:\n", " def __init__(self, dev):\n", " self.dev = dev\n", " self.sos = butter(4, [50 / 500, 400 / 500], btype=\"bandpass\", output=\"sos\")\n", " self.wl = int(round(T1[\"seg\"] * C.ENV_FS))\n", " self.hop = C.ENV_FS // C.FS_FHR\n", " self.nfft = 2048\n", " win = torch.hann_window(self.wl, periodic=False, dtype=torch.float64)\n", " wac = torch.fft.irfft(torch.fft.rfft(win, self.nfft).abs() ** 2, self.nfft)[: self.wl]\n", " self.win = win.float().to(dev)\n", " self.wac = (wac / wac[0]).float().to(dev)\n", " lags = C.ENV_FS * 60.0 / C.BPM.astype(np.float64)\n", " self.l0 = torch.tensor(np.floor(lags).astype(np.int64), device=dev)\n", " self.fr = torch.tensor((lags - np.floor(lags)).astype(np.float32), device=dev)\n", " b = C.BPM\n", " self.harm = [np.flatnonzero((np.abs(b - 2 * x) <= 3) | (np.abs(b - x / 2) <= 2)) for x in b]\n", "\n", " def envelope(self, x):\n", " y = sosfiltfilt(self.sos, x.astype(np.float64))\n", " e = np.abs(hilbert(y))\n", " return resample_poly(e, C.ENV_FS, C.FS_DUS).astype(np.float32)\n", "\n", " @torch.no_grad()\n", " def run(self, x, clip):\n", " env = self.envelope(x)\n", " n = C.N\n", " half = self.wl // 2\n", " e = torch.from_numpy(env).to(self.dev)\n", " need = n * self.hop + self.wl\n", " e = F.pad(e, (half, max(0, need - e.numel() - half)))\n", " fr = e.unfold(0, self.wl, self.hop)[:n]\n", " rms = fr.pow(2).mean(1).sqrt()\n", " z = (fr - fr.mean(1, keepdim=True)) * self.win\n", " p = torch.fft.rfft(z, self.nfft).abs() ** 2\n", " ac = torch.fft.irfft(p, self.nfft)[:, : self.wl]\n", " ac = ac / ac[:, :1].clamp_min(1e-12)\n", " ac = ac / self.wac.clamp_min(1e-3)\n", " g = ac[:, self.l0] * (1 - self.fr) + ac[:, (self.l0 + 1).clamp_max(self.wl - 1)] * self.fr\n", " g = g.clamp(-1, 1).cpu().numpy().astype(np.float32)\n", " top = g.argmax(1)\n", " top1 = g.max(1)\n", " med = np.median(g, 1)\n", " g2 = g.copy()\n", " for i in range(n):\n", " t = top[i]\n", " g2[i, max(0, t - 5):t + 6] = -np.inf\n", " g2[i, self.harm[t]] = -np.inf\n", " top2 = np.where(np.isfinite(g2.max(1)), g2.max(1), 0)\n", " cc = np.cumsum(np.r_[0, clip.astype(np.int64)])\n", " centers = (np.arange(n) * C.FS_DUS / C.FS_FHR).astype(int)\n", " a = np.clip(centers - 1875, 0, clip.size)\n", " b = np.clip(centers + 1875, 0, clip.size)\n", " clipf = (cc[b] - cc[a]) / np.maximum(1, b - a)\n", " q = np.stack([np.log(rms.cpu().numpy() + 1e-6), top1, top1 - med, top1 - top2, clipf, C.BPM[top]], 1).astype(np.float32)\n", " return g, q\n", "\n", "\n", "def record_list():\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " return m\n", "\n", "\n", "def out_path(rid):\n", " return C.FEAT / f\"{rid}.npz\"\n", "\n", "\n", "def ok_file(p):\n", " try:\n", " z = load_npz(p)\n", " return z[\"ac\"].shape == (C.N, C.NB) and z[\"q\"].shape == (C.N, NQ) and z[\"af_mean\"].shape == (C.N,)\n", " except Exception:\n", " return False\n", "\n", "\n", "def official_windows(path, k_windows=None):\n", " if str(C.REPO) not in sys.path:\n", " sys.path.insert(0, str(C.REPO))\n", " from ctg_baseline.tools import Task1Tool\n", " tool = Task1Tool(torch.device(\"cpu\"))\n", " sr, sig, _ = read_wav(path)\n", " cfg = tool_cfg = official()[0]\n", " win = int(cfg[\"segment_duration\"] * sr)\n", " stride = int(cfg[\"segment_stride\"] * sr)\n", " starts = list(range(0, max(1, len(sig) - win + 1), stride))\n", " if k_windows:\n", " starts = starts[:: max(1, len(starts) // k_windows)][:k_windows]\n", " feats = np.asarray([tool._scalogram(sig[s:s + win], sr) for s in starts])\n", " with torch.no_grad():\n", " masks = torch.sigmoid(tool.model(torch.from_numpy(feats))).numpy()\n", " return np.array(starts), feats, np.array([tool._fhr_from_mask(m) for m in masks], np.float32)\n", "\n", "\n", "@stage(\"s06_autofhr_equivalence\")\n", "def equivalence(log):\n", " m = record_list()\n", " m = m[m.fold >= 0]\n", " k = 3 if C.SMOKE else 8\n", " kw = 60 if C.SMOKE else 400\n", " dev = device()\n", " port = AutoFHRGPU(dev)\n", " rows = []\n", " for rid, wav in zip(m.record_id.values[:k], m.wav_path.values[:k]):\n", " starts, feats, ref_bpm = official_windows(C.RAW / wav, kw)\n", " sr, sig, _ = read_wav(C.RAW / wav)\n", " _, wins = port.windows(sig, sr)\n", " sel = (starts // int(port.cfg[\"segment_stride\"] * sr)).astype(int)\n", " mine = port.scalograms(wins[sel], log)\n", " masks = port.masks(mine, log, from_scalogram=True)\n", " free_mem()\n", " bpm = np.array([port.bpm_from_mask(x) for x in masks], np.float32)\n", " both_nan = np.isnan(bpm) & np.isnan(ref_bpm)\n", " both = np.isfinite(bpm) & np.isfinite(ref_bpm)\n", " agree = both_nan | (both & (np.abs(bpm - ref_bpm) <= 0.5))\n", " rows.append({\"record_id\": rid, \"windows\": int(len(starts)), \"scalogram_max_abs_diff\": float(np.abs(mine - feats).max()), \"scalogram_mean_abs_diff\": float(np.abs(mine - feats).mean()), \"bpm_agreement\": float(agree.mean()), \"bpm_mae_both_finite\": float(np.abs(bpm - ref_bpm)[both].mean()) if both.any() else np.nan, \"nan_mismatch\": int((np.isnan(bpm) ^ np.isnan(ref_bpm)).sum())})\n", " log.info(rows[-1])\n", " df = pd.DataFrame(rows)\n", " res = {\"records\": rows, \"min_agreement\": float(df.bpm_agreement.min()), \"mean_agreement\": float(df.bpm_agreement.mean()), \"max_scalogram_diff\": float(df.scalogram_max_abs_diff.max())}\n", " res[\"equivalent\"] = bool(res[\"min_agreement\"] >= 0.99)\n", " save_json(C.RES / \"s06_autofhr_equivalence.json\", res)\n", " if not res[\"equivalent\"]:\n", " log.warning(\"GPU AutoFHR port is NOT equivalent to the official pipeline; AutoFHR results will be flagged\")\n", " return {\"equivalent\": res[\"equivalent\"], \"mean_agreement\": res[\"mean_agreement\"]}\n", "\n", "\n", "def extract_one(rid, wav, af, acg, log):\n", " sr, sig, clip = read_wav(C.RAW / wav)\n", " if sr != C.FS_DUS:\n", " raise ValueError(f\"{rid}: sampling rate {sr}\")\n", " mean, sd, cnt, wb, _ = af.run(sig, sr, log)\n", " mean, sd = fit_len(mean), fit_len(sd)\n", " cnt = np.concatenate([cnt, np.zeros(max(0, C.N - cnt.size), np.int16)])[: C.N]\n", " g, q = acg.run(sig, clip)\n", " save_npz(out_path(rid), ac=g.astype(np.float16), q=q.astype(np.float16), af_mean=mean, af_sd=sd, af_cnt=cnt, af_win=wb)\n", "\n", "\n", "def mm_rows(p):\n", " try:\n", " return np.load(p, mmap_mode=\"r\").shape[0]\n", " except Exception:\n", " return -1\n", "\n", "\n", "def extract(force=False, shard=0, nshards=1):\n", " log = get_logger(f\"s07_dus_extract_{shard}\")\n", " m = record_list()\n", " if not force and mm_rows(C.CACHE / \"t1_ac.npy\") == len(m):\n", " log.info(\"packed features already present, nothing to extract\")\n", " mark_done(f\"s07_dus_extract_{shard}\", {\"shard\": shard, \"nshards\": nshards, \"smoke\": C.SMOKE}, {\"records\": 0, \"seconds\": 0.0, \"reused_packed\": True})\n", " return\n", " ids = m.record_id.values[shard::nshards]\n", " wavs = m.wav_path.values[shard::nshards]\n", " todo = [(r, w) for r, w in zip(ids, wavs) if force or not ok_file(out_path(r))]\n", " log.info(f\"shard {shard}/{nshards}: {len(todo)} of {len(ids)} records to process on {device()}\")\n", " if not todo:\n", " return\n", " dev = device()\n", " if dev.type == \"cpu\":\n", " torch.set_num_threads(max(1, C.CPU // max(1, nshards)))\n", " af = AutoFHRGPU(dev)\n", " acg = Autocorrelogram(dev)\n", " fails = []\n", " t0 = time.time()\n", " for i, (r, w) in enumerate(todo):\n", " try:\n", " extract_one(r, w, af, acg, log)\n", " except Exception as e:\n", " fails.append((r, repr(e)))\n", " log.error(f\"{r}: {e!r}\")\n", " free_mem()\n", " if (i + 1) % 25 == 0:\n", " el = time.time() - t0\n", " log.info(f\"{i + 1}/{len(todo)} {el / (i + 1):.2f}s/record eta {el / (i + 1) * (len(todo) - i - 1) / 60:.1f} min\")\n", " save_json(C.STATE / f\"s07_failures_{shard}.json\", fails)\n", " if fails:\n", " raise RuntimeError(f\"{len(fails)} records failed in shard {shard}; rerun resumes\")\n", " mark_done(f\"s07_dus_extract_{shard}\", {\"shard\": shard, \"nshards\": nshards, \"smoke\": C.SMOKE}, {\"records\": len(todo), \"seconds\": round(time.time() - t0, 1), \"device\": str(dev)})\n", "\n", "\n", "@stage(\"s08_dus_pack\", outputs=[C.CACHE / \"t1_ac.npy\", C.CACHE / \"t1_q.npy\", C.CACHE / \"t1_af.npy\"])\n", "def pack(log):\n", " m = record_list()\n", " if all((C.CACHE / f).exists() for f in (\"t1_ac.npy\", \"t1_q.npy\", \"t1_af.npy\")) and mm_rows(C.CACHE / \"t1_ac.npy\") == len(m):\n", " return {\"records\": len(m), \"reused\": True}\n", " missing = [r for r in m.record_id if not ok_file(out_path(r))]\n", " if missing:\n", " raise RuntimeError(f\"{len(missing)} feature files missing, run s07 first: {missing[:5]}\")\n", " n = len(m)\n", " ac, ta, pa = open_memmap_new(C.CACHE / \"t1_ac.npy\", (n, C.N, C.NB), np.float16)\n", " q, tq, pq = open_memmap_new(C.CACHE / \"t1_q.npy\", (n, C.N, NQ), np.float16)\n", " af, tf, pf = open_memmap_new(C.CACHE / \"t1_af.npy\", (n, C.N, 3), np.float32)\n", " for i, r in enumerate(m.record_id):\n", " z = load_npz(out_path(r))\n", " ac[i] = z[\"ac\"]\n", " q[i] = z[\"q\"]\n", " af[i] = np.stack([z[\"af_mean\"], z[\"af_sd\"], z[\"af_cnt\"].astype(np.float32)], 1)\n", " finalize_memmap(ac, ta, pa)\n", " finalize_memmap(q, tq, pq)\n", " finalize_memmap(af, tf, pf)\n", " if int(__import__(\"os\").environ.get(\"CTG_PRUNE_FEATURES\", \"1\")):\n", " for r in m.record_id:\n", " out_path(r).unlink(missing_ok=True)\n", " return {\"records\": n}" ] }, { "cell_type": "code", "execution_count": 13, "id": "80999e329b46", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.748898Z", "iopub.status.busy": "2026-11-28T14:17:32.748575Z", "iopub.status.idle": "2026-11-28T14:17:32.768153Z", "shell.execute_reply": "2026-11-28T14:17:32.766540Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/t1.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/t1.py\n", "import itertools\n", "import math\n", "import time\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "from . import config as C\n", "from .folds import inner_split\n", "from .io import events, fill_linear, valid\n", "from .metrics import crps_discrete, fhr_abs_errors, risk_coverage, spearman, t1_scores\n", "from .utils import (adaptive_batches, bootstrap, device, finalize_memmap, free_mem, get_logger, is_done, load_df, load_json, mark_done, mm,\n", " open_memmap_new, save_json, save_npy, seed_all, stage)\n", "\n", "FLOOR_COLS = [\"viterbi\", \"post_median\", \"post_mean\", \"p_far\", \"entropy\", \"q10\", \"q90\"]\n", "TCN_COLS = [\"median\", \"mean\", \"p_far\", \"entropy\", \"q10\", \"q90\"]\n", "\n", "\n", "def meta():\n", " return load_df(C.CACHE / \"folds_t4.pkl\")\n", "\n", "\n", "def ref_fhr():\n", " return np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", "\n", "\n", "def ref_bins(ref):\n", " v = valid(ref)\n", " b = np.clip(np.rint(np.nan_to_num(ref, nan=140.0)) - C.BPM[0], 0, C.NB - 1).astype(np.int64)\n", " return b, v\n", "\n", "\n", "def transition(lam, cap=25, jump=1.0):\n", " d = np.abs(np.arange(C.NB)[:, None] - np.arange(C.NB)[None, :]).astype(np.float32)\n", " return -(lam * np.minimum(d, cap) + jump * (d > cap))\n", "\n", "\n", "def emissions(g, beta, alpha, logprior, rho):\n", " e = beta * g\n", " if alpha:\n", " idx = torch.as_tensor(np.clip(np.rint(2 * C.BPM) - C.BPM[0], 0, C.NB - 1).astype(np.int64), device=g.device)\n", " ok = torch.as_tensor(2 * C.BPM <= C.BPM[-1], device=g.device)\n", " e = e + beta * alpha * torch.where(ok, g[..., idx], torch.zeros((), device=g.device))\n", " return e + rho * logprior\n", "\n", "\n", "@torch.no_grad()\n", "def viterbi(e, T):\n", " B, n, K = e.shape\n", " v = e[:, 0]\n", " bp = torch.empty((B, n, K), dtype=torch.int16, device=e.device)\n", " for t in range(1, n):\n", " s = v[:, :, None] + T[None]\n", " v, a = s.max(1)\n", " bp[:, t] = a.to(torch.int16)\n", " v = v + e[:, t]\n", " path = torch.empty((B, n), dtype=torch.long, device=e.device)\n", " path[:, -1] = v.argmax(1)\n", " for t in range(n - 1, 0, -1):\n", " path[:, t - 1] = bp[:, t].gather(1, path[:, t:t + 1]).squeeze(1).long()\n", " return path\n", "\n", "\n", "@torch.no_grad()\n", "def posterior(e, T):\n", " B, n, K = e.shape\n", " la = torch.empty_like(e)\n", " la[:, 0] = e[:, 0] - torch.logsumexp(e[:, 0], 1, keepdim=True)\n", " for t in range(1, n):\n", " x = torch.logsumexp(la[:, t - 1, :, None] + T[None], 1) + e[:, t]\n", " la[:, t] = x - torch.logsumexp(x, 1, keepdim=True)\n", " lb = torch.zeros_like(e)\n", " for t in range(n - 2, -1, -1):\n", " x = torch.logsumexp(T[None] + (e[:, t + 1] + lb[:, t + 1])[:, None, :], 2)\n", " lb[:, t] = x - torch.logsumexp(x, 1, keepdim=True)\n", " lp = la + lb\n", " return torch.softmax(lp, -1)\n", "\n", "\n", "def summarize(p):\n", " grid = torch.as_tensor(C.BPM, device=p.device)\n", " cdf = p.cumsum(-1)\n", " med = grid[(cdf < 0.5).sum(-1).clamp_max(C.NB - 1)]\n", " q10 = grid[(cdf < 0.1).sum(-1).clamp_max(C.NB - 1)]\n", " q90 = grid[(cdf < 0.9).sum(-1).clamp_max(C.NB - 1)]\n", " mean = (p * grid).sum(-1)\n", " far = ((grid[None, None, :] - med[..., None]).abs() > C.BIG_ERR).float()\n", " pfar = (p * far).sum(-1)\n", " ent = -(p.clamp_min(1e-12).log() * p).sum(-1)\n", " return med, mean, pfar, ent, q10, q90\n", "\n", "\n", "def load_g(idx, dev):\n", " ac = mm(C.CACHE / \"t1_ac.npy\")\n", " return torch.from_numpy(np.asarray(ac[np.sort(idx)], np.float32)).to(dev)\n", "\n", "\n", "def log_prior(ref_tr):\n", " b, v = ref_bins(ref_tr)\n", " h = np.bincount(b[v], minlength=C.NB).astype(np.float64) + 1.0\n", " from scipy.ndimage import gaussian_filter1d\n", " h = gaussian_filter1d(h, 3)\n", " return np.log(h / h.sum()).astype(np.float32)\n", "\n", "\n", "def grid():\n", " if C.SMOKE:\n", " return list(itertools.product([6.0, 12.0], [0.15, 0.4], [0.0, 1.0], [0.0, -0.5]))\n", " return list(itertools.product([4.0, 8.0, 16.0], [0.05, 0.15, 0.4], [0.0, 1.0], [0.0, -0.5, 0.5]))\n", "\n", "\n", "def rmse_of(path, ref):\n", " pred = C.BPM[path]\n", " e = np.concatenate([fhr_abs_errors(p, r)[0] for p, r in zip(pred, ref)])\n", " return float(np.sqrt(np.mean(e ** 2)))\n", "\n", "\n", "@stage(\"s09_t1_floor\", outputs=[C.CACHE / \"t1_floor.npy\", C.CACHE / \"t1_floor_crps.npy\"])\n", "def floor(log):\n", " m = meta()\n", " ref = ref_fhr()\n", " dev = device()\n", " n = len(m)\n", " out, tp, pp = open_memmap_new(C.CACHE / \"t1_floor.npy\", (n, C.N, len(FLOOR_COLS)), np.float32, np.nan)\n", " crps_rec = np.full(n, np.nan)\n", " chosen = {}\n", " bs = 64 if dev.type == \"cuda\" else 8\n", " for f in range(C.N_FOLDS):\n", " tr = np.flatnonzero((m.fold.values >= 0) & (m.fold.values != f))\n", " te = np.flatnonzero(m.fold.values == f)\n", " rng = np.random.default_rng(C.SEED + f)\n", " sub = np.sort(rng.choice(tr, size=min(tr.size, 48 if C.SMOKE else 400), replace=False))\n", " lp = torch.from_numpy(log_prior(ref[tr])).to(dev)\n", " best = None\n", " g = load_g(sub, torch.device(\"cpu\"))\n", " for beta, lam, rho, alpha in grid():\n", " T = torch.from_numpy(transition(lam, jump=beta * 0.5)).to(dev)\n", "\n", " def tune_batch(i, j, T=T, beta=beta, alpha=alpha, rho=rho):\n", " return viterbi(emissions(g[i:j].to(dev), beta, alpha, lp, rho), T).cpu().numpy()\n", "\n", " paths = adaptive_batches(sub.size, tune_batch, bs, log=log)\n", " r = rmse_of(np.concatenate(paths), ref[sub])\n", " if best is None or r < best[0]:\n", " best = (r, beta, lam, rho, alpha)\n", " del g\n", " free_mem()\n", " r, beta, lam, rho, alpha = best\n", " chosen[f] = {\"train_rmse\": r, \"beta\": beta, \"lam\": lam, \"rho\": rho, \"alpha\": alpha}\n", " log.info(f\"fold {f}: {chosen[f]}\")\n", " T = torch.from_numpy(transition(lam, jump=beta * 0.5)).to(dev)\n", "\n", " def run_batch(i, j, te=te, T=T, beta=beta, alpha=alpha, lp=lp, rho=rho):\n", " idx = te[i:j]\n", " g = load_g(idx, dev)\n", " e = emissions(g, beta, alpha, lp, rho)\n", " path = viterbi(e, T)\n", " p = posterior(e, T)\n", " med, mean, pfar, ent, q10, q90 = summarize(p)\n", " pn = p.cpu().numpy().astype(np.float64)\n", " res = np.stack([C.BPM[path.cpu().numpy()], med.cpu().numpy(), mean.cpu().numpy(), pfar.cpu().numpy(), ent.cpu().numpy(), q10.cpu().numpy(), q90.cpu().numpy()], -1)\n", " cr = []\n", " for k, rec in enumerate(np.sort(idx)):\n", " b, v = ref_bins(ref[rec])\n", " cr.append(crps_discrete(pn[k][v], ref[rec][v]).mean() if v.any() else np.nan)\n", " return np.sort(idx), res, np.array(cr)\n", "\n", " for idx, res, cr in adaptive_batches(te.size, run_batch, bs, log=log):\n", " out[idx] = res\n", " crps_rec[idx] = cr\n", " free_mem()\n", " finalize_memmap(out, tp, pp)\n", " save_npy(C.CACHE / \"t1_floor_crps.npy\", crps_rec)\n", " save_json(C.RES / \"s09_t1_floor_params.json\", chosen)\n", " return {\"folds\": chosen}\n", "\n", "\n", "class Block(nn.Module):\n", " def __init__(self, ch, k, d, drop):\n", " super().__init__()\n", " self.c1 = nn.Conv1d(ch, ch, k, padding=d * (k - 1) // 2, dilation=d)\n", " self.n = nn.GroupNorm(8, ch)\n", " self.c2 = nn.Conv1d(ch, ch, 1)\n", " self.drop = nn.Dropout(drop)\n", "\n", " def forward(self, x):\n", " return x + self.c2(self.drop(F.gelu(self.n(self.c1(x)))))\n", "\n", "\n", "class TCN(nn.Module):\n", " def __init__(self, cin=C.NB + 6, ch=128, k=5, dil=(1, 2, 4, 8, 16, 32, 1, 2, 4, 8), drop=0.1):\n", " super().__init__()\n", " self.inp = nn.Conv1d(cin, ch, 1)\n", " self.blocks = nn.Sequential(*[Block(ch, k, d, drop) for d in dil])\n", " self.out = nn.Conv1d(ch, C.NB, 1)\n", "\n", " def forward(self, x):\n", " return self.out(self.blocks(self.inp(x)))\n", "\n", "\n", "class Data:\n", " def __init__(self, idx, stats=None):\n", " self.ac = mm(C.CACHE / \"t1_ac.npy\")\n", " self.q = mm(C.CACHE / \"t1_q.npy\")\n", " self.ref = ref_fhr()\n", " self.idx = np.asarray(idx)\n", " if stats is None:\n", " qs = np.concatenate([np.asarray(self.q[i], np.float32)[::8] for i in self.idx[:400]])\n", " stats = (np.nanmean(qs, 0), np.nanstd(qs, 0) + 1e-6)\n", " self.mu, self.sd = (np.asarray(s, np.float32) for s in stats)\n", "\n", " def x(self, i, a=0, b=C.N):\n", " g = np.asarray(self.ac[i, a:b], np.float32)\n", " q = (np.asarray(self.q[i, a:b], np.float32) - self.mu) / self.sd\n", " return np.nan_to_num(np.concatenate([g, q], 1).T)\n", "\n", " def y(self, i, a=0, b=C.N):\n", " return ref_bins(self.ref[i, a:b])\n", "\n", " def batch(self, rng, bs, L):\n", " xs, ys, ms = [], [], []\n", " for i in rng.choice(self.idx, bs):\n", " a = int(rng.integers(0, C.N - L + 1))\n", " b, v = self.y(i, a, a + L)\n", " xs.append(self.x(i, a, a + L))\n", " ys.append(b)\n", " ms.append(v)\n", " return torch.from_numpy(np.stack(xs)), torch.from_numpy(np.stack(ys)), torch.from_numpy(np.stack(ms))\n", "\n", "\n", "def soft_ce(logits, y, m, sigma=1.5):\n", " k = torch.arange(C.NB, device=logits.device)[None, :, None]\n", " t = torch.exp(-0.5 * ((k - y[:, None, :]) / sigma) ** 2)\n", " t = t / t.sum(1, keepdim=True)\n", " l = -(t * F.log_softmax(logits.float(), 1)).sum(1)\n", " return (l * m).sum() / m.sum().clamp_min(1)\n", "\n", "\n", "@torch.no_grad()\n", "def predict(model, data, idx, dev, log=None):\n", " model.eval()\n", " out = {}\n", "\n", " def fn(i, j):\n", " xs = torch.from_numpy(np.stack([data.x(r) for r in idx[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " lo = model(xs)\n", " return torch.softmax(lo.float(), 1).transpose(1, 2)\n", "\n", " k = 0\n", " for p in adaptive_batches(len(idx), fn, 8, log=log):\n", " for r in range(p.shape[0]):\n", " out[idx[k]] = p[r]\n", " k += 1\n", " return out\n", "\n", "\n", "def val_rmse(probs, data, idx):\n", " errs = []\n", " for i in idx:\n", " med = summarize(probs[i][None])[0][0].cpu().numpy()\n", " errs.append(fhr_abs_errors(med, data.ref[i])[0])\n", " e = np.concatenate(errs)\n", " return float(np.sqrt(np.mean(e ** 2)))\n", "\n", "\n", "def sfx(seed):\n", " return \"\" if not seed else f\"_s{seed}\"\n", "\n", "\n", "def train_tcn_sharp(force=False, fold=0, seed=0):\n", " train_tcn(force, fold, seed, sigma=0.5, tag=\"sharp\")\n", "\n", "\n", "def train_tcn(force=False, fold=0, seed=0, sigma=1.5, tag=\"\"):\n", " name = f\"s10_t1_tcn_f{fold}{sfx(seed)}\" if not tag else f\"s45_t1_tcn_{tag}_f{fold}{sfx(seed)}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T1} if not seed else {\"fold\": fold, \"seed\": seed, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T1}\n", " if tag:\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T1, \"tag\": tag, \"sigma\": sigma} if not seed else {\"fold\": fold, \"seed\": seed, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T1, \"tag\": tag, \"sigma\": sigma}\n", " prefix = \"t1_tcn\" if not tag else f\"t1_tcn{tag}\"\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " seed_all(C.SEED + fold + 1000 * seed)\n", " dev = device()\n", " m = meta()\n", " tr, va = inner_split(m, fold)\n", " v_ok = np.array([valid(r).mean() for r in ref_fhr()])\n", " tr = tr[v_ok[tr] > 0.3]\n", " data = Data(tr)\n", " vdata = Data(va, (data.mu, data.sd))\n", " model = TCN().to(dev)\n", " opt = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-2)\n", " steps = max(20, int(len(tr) * 4 / 32)) if not C.SMOKE else 10\n", " sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=2e-3, total_steps=C.EPOCHS_T1 * steps, pct_start=0.1)\n", " scaler = torch.amp.GradScaler(enabled=dev.type == \"cuda\")\n", " d = C.MODELS / (\"t1_tcn\" if not tag else f\"t1_tcn_{tag}\") / f\"fold{fold}{sfx(seed)}\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " st = {\"epoch\": 0, \"best\": math.inf, \"bad\": 0, \"bs\": 32, \"hist\": []}\n", " if (d / \"last.pt\").exists() and not force:\n", " ck = torch.load(d / \"last.pt\", map_location=dev, weights_only=False)\n", " model.load_state_dict(ck[\"model\"])\n", " opt.load_state_dict(ck[\"opt\"])\n", " sched.load_state_dict(ck[\"sched\"])\n", " scaler.load_state_dict(ck[\"scaler\"])\n", " st = ck[\"state\"]\n", " log.info(f\"resumed at epoch {st['epoch']}\")\n", " rng = np.random.default_rng(C.SEED + fold + 1000 * seed + st[\"epoch\"])\n", " L = 1024\n", " while st[\"epoch\"] < C.EPOCHS_T1 and st[\"bad\"] < C.PATIENCE:\n", " model.train()\n", " t0 = time.time()\n", " tot = 0.0\n", " for _ in range(steps):\n", " x, y, mk = data.batch(rng, st[\"bs\"], L)\n", " x, y, mk = x.to(dev), y.to(dev), mk.to(dev).float()\n", " try:\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " loss = soft_ce(model(x), y, mk, sigma)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " sched.step()\n", " tot += float(loss)\n", " except RuntimeError as e:\n", " if \"out of memory\" not in str(e).lower() or st[\"bs\"] <= 2:\n", " raise\n", " opt.zero_grad(set_to_none=True)\n", " free_mem()\n", " st[\"bs\"] //= 2\n", " log.warning(f\"OOM: batch -> {st['bs']}\")\n", " probs = predict(model, vdata, va, dev, log)\n", " vr = val_rmse(probs, vdata, va)\n", " del probs\n", " st[\"epoch\"] += 1\n", " st[\"hist\"].append({\"epoch\": st[\"epoch\"], \"train_loss\": tot / steps, \"val_rmse\": vr, \"sec\": time.time() - t0})\n", " if vr < st[\"best\"] - 1e-3:\n", " st[\"best\"], st[\"bad\"] = vr, 0\n", " torch.save({\"model\": model.state_dict(), \"stats\": (data.mu, data.sd)}, d / \"best.tmp\")\n", " (d / \"best.tmp\").replace(d / \"best.pt\")\n", " else:\n", " st[\"bad\"] += 1\n", " torch.save({\"model\": model.state_dict(), \"opt\": opt.state_dict(), \"sched\": sched.state_dict(), \"scaler\": scaler.state_dict(), \"state\": st}, d / \"last.tmp\")\n", " (d / \"last.tmp\").replace(d / \"last.pt\")\n", " log.info(st[\"hist\"][-1])\n", " ck = torch.load(d / \"best.pt\", map_location=dev, weights_only=False)\n", " model.load_state_dict(ck[\"model\"])\n", " te = np.flatnonzero(m.fold.values == fold)\n", " tdata = Data(te, ck[\"stats\"])\n", " probs = predict(model, tdata, te, dev, log)\n", " res = np.full((te.size, C.N, len(TCN_COLS)), np.nan, np.float32)\n", " crps = np.full(te.size, np.nan)\n", " pr = np.zeros((te.size, C.N, C.NB), np.float16)\n", " for k, i in enumerate(te):\n", " p = probs[i]\n", " med, mean, pfar, ent, q10, q90 = (a.cpu().numpy() for a in summarize(p[None]))\n", " res[k] = np.stack([med[0], mean[0], pfar[0], ent[0], q10[0], q90[0]], -1)\n", " b, v = ref_bins(tdata.ref[i])\n", " pn = p.cpu().numpy().astype(np.float64)\n", " crps[k] = crps_discrete(pn[v], tdata.ref[i][v]).mean() if v.any() else np.nan\n", " pr[k] = pn.astype(np.float16)\n", " s = sfx(seed)\n", " np.savez(C.CACHE / f\"{prefix}_oof_f{fold}{s}.tmp.npz\", idx=te, res=res, crps=crps)\n", " (C.CACHE / f\"{prefix}_oof_f{fold}{s}.tmp.npz\").replace(C.CACHE / f\"{prefix}_oof_f{fold}{s}.npz\")\n", " np.save(C.CACHE / f\"{prefix}_probs_f{fold}{s}.tmp.npy\", pr)\n", " (C.CACHE / f\"{prefix}_probs_f{fold}{s}.tmp.npy\").replace(C.CACHE / f\"{prefix}_probs_f{fold}{s}.npy\")\n", " mark_done(name, params, {\"best_val_rmse\": st[\"best\"], \"epochs\": st[\"epoch\"], \"history\": st[\"hist\"], \"seconds\": round(sum(h[\"sec\"] for h in st[\"hist\"]), 1)}, [d / \"best.pt\", C.CACHE / f\"{prefix}_oof_f{fold}{s}.npz\", C.CACHE / f\"{prefix}_probs_f{fold}{s}.npy\"])\n", "\n", "\n", "def gather_tcn(seed=0, prefix=\"t1_tcn\"):\n", " m = meta()\n", " res = np.full((len(m), C.N, len(TCN_COLS)), np.nan, np.float32)\n", " crps = np.full(len(m), np.nan)\n", " have = False\n", " for f in range(C.N_FOLDS):\n", " p = C.CACHE / f\"{prefix}_oof_f{f}{sfx(seed)}.npz\"\n", " if p.exists():\n", " with np.load(p) as z:\n", " res[z[\"idx\"]] = z[\"res\"]\n", " crps[z[\"idx\"]] = z[\"crps\"]\n", " have = True\n", " return (res, crps) if have else (None, None)\n", "\n", "\n", "def method_preds():\n", " m = meta()\n", " af = np.asarray(mm(C.CACHE / \"t1_af.npy\"), np.float32)\n", " fl = np.asarray(mm(C.CACHE / \"t1_floor.npy\"), np.float32)\n", " out = {\"autofhr\": {\"pred\": np.stack([fill_linear(x) for x in af[..., 0]]), \"scores\": {\"window_sd\": np.nan_to_num(af[..., 1], nan=50.0), \"neg_window_count\": -af[..., 2]}},\n", " \"floor\": {\"pred\": fl[..., 1], \"scores\": {\"p_far\": fl[..., 3], \"entropy\": fl[..., 4], \"width80\": fl[..., 6] - fl[..., 5]}}}\n", " q = np.asarray(mm(C.CACHE / \"t1_q.npy\"), np.float32)\n", " out[\"floor\"][\"scores\"][\"neg_ac_prominence\"] = -q[..., 2]\n", " tr, _ = gather_tcn()\n", " if tr is not None:\n", " out[\"tcn\"] = {\"pred\": tr[..., 0], \"scores\": {\"p_far\": tr[..., 2], \"entropy\": tr[..., 3], \"width80\": tr[..., 5] - tr[..., 4]}}\n", " return out\n", "\n", "\n", "def strata(m, ref):\n", " seg = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " q = np.asarray(mm(C.CACHE / \"t1_q.npy\"), np.float32)\n", " near_dec = np.zeros(ref.shape, bool)\n", " near_acc = np.zeros(ref.shape, bool)\n", " near_gap = np.zeros(ref.shape, bool)\n", " for i in range(ref.shape[0]):\n", " for a, b in events(seg[i], -1):\n", " near_dec[i, max(0, a - 120):b + 120] = True\n", " for a, b in events(seg[i], 1):\n", " near_acc[i, max(0, a - 120):b + 120] = True\n", " bad = ~valid(ref[i])\n", " if bad.any():\n", " from scipy.ndimage import binary_dilation\n", " near_gap[i] = binary_dilation(bad, iterations=40) & ~bad\n", " prom = q[..., 2]\n", " qbin = np.full(prom.shape, -1)\n", " fin = np.isfinite(prom)\n", " edges = np.nanquantile(prom[fin], np.linspace(0, 1, 6)[1:-1])\n", " qbin[fin] = np.digitize(prom[fin], edges)\n", " lvl = np.digitize(np.nan_to_num(ref, nan=0), [110, 160])\n", " return {\"near_dec\": near_dec, \"near_acc\": near_acc, \"near_ref_gap\": near_gap, \"quality_quintile\": qbin, \"fhr_level\": lvl}\n", "\n", "\n", "@stage(\"s11_t1_analysis\", params={\"v\": 2})\n", "def analysis(log):\n", " m = meta()\n", " ok = m.fold.values >= 0\n", " ref = ref_fhr()\n", " eq = load_json(C.RES / \"s06_autofhr_equivalence.json\", {})\n", " st = strata(m, ref)\n", " preds = method_preds()\n", " rep = {\"n_records\": int(ok.sum()), \"autofhr_port_equivalent\": eq.get(\"equivalent\"), \"independence\": {\"autofhr\": \"unknown: official checkpoint may have been trained on these records\", \"floor\": \"out-of-fold (hyperparameters tuned on training folds)\", \"tcn\": \"out-of-fold (inner validation split for early stopping)\"}}\n", " rec = np.flatnonzero(ok)\n", " rng = np.random.default_rng(C.SEED)\n", " for name, d in preds.items():\n", " P = d[\"pred\"][rec]\n", " R = ref[rec]\n", " if not np.isfinite(P).any():\n", " continue\n", " r = {\"official\": t1_scores(list(P), list(R))}\n", " E, V = zip(*[fhr_abs_errors(p, q) for p, q in zip(P, R)])\n", " sq_big = np.array([np.sum(e[e > C.BIG_ERR] ** 2) for e in E])\n", " sq = np.array([np.sum(e ** 2) for e in E])\n", " nb = np.array([np.sum(e > C.BIG_ERR) for e in E])\n", " nn_ = np.array([e.size for e in E])\n", " r[\"share_sq_err_big\"] = bootstrap(lambda i: sq_big[i].sum() / sq[i].sum(), np.arange(rec.size))\n", " r[\"frac_points_big\"] = bootstrap(lambda i: nb[i].sum() / nn_[i].sum(), np.arange(rec.size))\n", " e_all = np.concatenate(E)\n", " ratio = np.concatenate([p[v] / q[v] for p, q, v in zip(P, R, V)])\n", " r[\"frac_doubling\"] = float(np.mean(np.abs(ratio - 2) < 0.12))\n", " r[\"frac_halving\"] = float(np.mean(np.abs(ratio - 0.5) < 0.03))\n", " r[\"strata\"] = {}\n", " for sname, s in st.items():\n", " sv = np.concatenate([s[i][valid(ref[i])] for i in rec])\n", " r[\"strata\"][sname] = {str(int(k)): {\"n\": int((sv == k).sum()), \"rmse\": float(np.sqrt(np.mean(e_all[sv == k] ** 2))), \"frac_big\": float(np.mean(e_all[sv == k] > C.BIG_ERR))} for k in np.unique(sv)}\n", " r[\"uncertainty\"] = {}\n", " pick = [rng.choice(e.size, size=min(400, e.size), replace=False) if e.size else np.zeros(0, int) for e in E]\n", " sub_e = np.concatenate([e[pk] for e, pk in zip(E, pick)])\n", " sub_u = np.concatenate([np.full(pk.size, k) for k, pk in enumerate(pick)])\n", " loss = (e_all > C.BIG_ERR).astype(float)\n", " keys = [\"aurc\", \"risk@0.9\", \"risk@0.8\", \"risk@0.7\", \"rel@0.9\", \"rel@0.8\", \"rel@0.7\", \"rel_aurc\"]\n", "\n", " def rc_vec(s, l):\n", " rc = risk_coverage(s, l)\n", " full = max(rc[\"risk_full\"], 1e-12)\n", " return np.array([rc[\"aurc\"], rc[\"risk@0.9\"], rc[\"risk@0.8\"], rc[\"risk@0.7\"], rc[\"risk@0.9\"] / full, rc[\"risk@0.8\"] / full, rc[\"risk@0.7\"] / full, rc[\"aurc\"] / full])\n", "\n", " for sname, S in d[\"scores\"].items():\n", " Sv = [np.nan_to_num(S[i][v], nan=np.inf) for i, v in zip(rec, V)]\n", " s_all = np.concatenate(Sv)\n", " sub_s = np.concatenate([s[pk] for s, pk in zip(Sv, pick)])\n", " rc = risk_coverage(s_all, loss)\n", " rc2 = risk_coverage(s_all, e_all ** 2)\n", " boot = bootstrap(lambda i: rc_vec(sub_s[i], (sub_e[i] > C.BIG_ERR).astype(float)), sub_u, B=min(C.BOOT, 300))\n", " r[\"uncertainty\"][sname] = {\"big_error\": rc, \"squared_error\": rc2, \"big_error_ci\": {\"keys\": keys, \"lo\": boot[\"lo\"], \"hi\": boot[\"hi\"]}, \"spearman_abs_err\": spearman(np.where(np.isfinite(sub_s), sub_s, np.nan), sub_e)}\n", " rep[name] = r\n", " log.info(f\"{name}: {r['official']} share_big={r['share_sq_err_big']}\")\n", " fcr = np.load(C.CACHE / \"t1_floor_crps.npy\")\n", " rep[\"floor\"][\"crps_record_mean\"] = float(np.nanmean(fcr[rec]))\n", " _, tcr = gather_tcn()\n", " if tcr is not None and \"tcn\" in rep:\n", " rep[\"tcn\"][\"crps_record_mean\"] = float(np.nanmean(tcr[rec]))\n", " prim = C.T1_PRIMARY if C.T1_PRIMARY in rep else \"floor\"\n", " pr = rep[prim]\n", " sh, fp = pr[\"share_sq_err_big\"], pr[\"frac_points_big\"]\n", " best = min(pr[\"uncertainty\"], key=lambda s: pr[\"uncertainty\"][s][\"big_error\"][\"aurc\"])\n", " u = pr[\"uncertainty\"][best]\n", " ci = dict(zip(u[\"big_error_ci\"][\"keys\"], zip(u[\"big_error_ci\"][\"lo\"], u[\"big_error_ci\"][\"hi\"])))\n", " concentrated = bool(sh[\"lo\"] > 0.5 and fp[\"hi\"] < 0.2)\n", " selective = bool(ci[\"rel@0.9\"][1] <= 0.7)\n", " rep[\"gate_S3\"] = {\n", " \"primary_method\": prim,\n", " \"n_records\": rep[\"n_records\"],\n", " \"n_records_ok\": bool(rep[\"n_records\"] >= 200 or C.SMOKE),\n", " \"frac_points_big_error\": fp,\n", " \"share_sq_err_from_big_errors\": sh,\n", " \"criterion_concentration\": \"lower 95% CI of share > 0.5 AND upper 95% CI of fraction of points with |e|>10 bpm < 0.2\",\n", " \"concentrated\": concentrated,\n", " \"best_training_free_score\": best,\n", " \"relative_big_error_rate_at_90pct_coverage\": {\"point\": u[\"big_error\"][\"risk@0.9\"] / max(u[\"big_error\"][\"risk_full\"], 1e-12), \"lo\": ci[\"rel@0.9\"][0], \"hi\": ci[\"rel@0.9\"][1]},\n", " \"criterion_selectivity\": \"upper 95% CI of (big-error rate at 90% coverage / rate at full coverage) <= 0.7\",\n", " \"selective\": selective,\n", " \"passed\": bool(concentrated and selective and (rep[\"n_records\"] >= 200 or C.SMOKE)),\n", " }\n", " rep[\"gate_S3\"][\"decision\"] = \"Article 2 stays selective (three-action policy)\" if rep[\"gate_S3\"][\"passed\"] else (\"Article 2 switches to purely probabilistic estimation\" if not selective else \"Errors are diffuse: Article 2 targets calibration of the whole distribution\")\n", " rep[\"S8_reference\"] = {\n", " \"method\": prim,\n", " \"score\": best,\n", " \"aurc\": {\"point\": u[\"big_error\"][\"aurc\"], \"lo\": ci[\"aurc\"][0], \"hi\": ci[\"aurc\"][1]},\n", " \"risk_full\": u[\"big_error\"][\"risk_full\"],\n", " \"risk@0.9\": {\"point\": u[\"big_error\"][\"risk@0.9\"], \"lo\": ci[\"risk@0.9\"][0], \"hi\": ci[\"risk@0.9\"][1]},\n", " \"risk@0.8\": {\"point\": u[\"big_error\"][\"risk@0.8\"], \"lo\": ci[\"risk@0.8\"][0], \"hi\": ci[\"risk@0.8\"][1]},\n", " \"risk@0.7\": {\"point\": u[\"big_error\"][\"risk@0.7\"], \"lo\": ci[\"risk@0.7\"][0], \"hi\": ci[\"risk@0.7\"][1]},\n", " \"pre_registered_S8_criterion\": \"a learned residual-risk model passes only if, on the same out-of-fold points, the paired bootstrap upper 95% CI of its relative AURC change versus this reference is below -10%, on at least 4 of 5 folds, with selective risk at alpha=5% within +-1 point on the reserved calibration fold\",\n", " }\n", " save_json(C.RES / \"s11_t1_analysis.json\", rep)\n", " return rep[\"gate_S3\"]" ] }, { "cell_type": "code", "execution_count": 14, "id": "7ad8343cf5d8", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.771884Z", "iopub.status.busy": "2026-11-28T14:17:32.771554Z", "iopub.status.idle": "2026-11-28T14:17:32.789428Z", "shell.execute_reply": "2026-11-28T14:17:32.788027Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/t2.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/t2.py\n", "import itertools\n", "import math\n", "import sys\n", "import time\n", "from concurrent.futures import ProcessPoolExecutor\n", "\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from scipy.ndimage import median_filter\n", "\n", "from . import config as C\n", "from .folds import inner_split\n", "from .io import events, fill_linear, valid\n", "from .metrics import dice_counts, dice_from_counts, event_counts, evidence_f1\n", "from .utils import (adaptive_batches, bootstrap, device, free_mem, get_logger, is_done, load_df, load_json, load_npz, mark_done, mm, save_json,\n", " save_npy, seed_all, stage)\n", "\n", "LAB2IDX = {0: 0, 1: 1, -1: 2}\n", "IDX2LAB = np.array([0, 1, -1], np.int8)\n", "\n", "\n", "def t2_meta():\n", " return load_df(C.CACHE / \"folds_t2.pkl\")\n", "\n", "\n", "def t4_meta():\n", " return load_df(C.CACHE / \"folds_t4.pkl\")\n", "\n", "\n", "def arr(name):\n", " return np.asarray(mm(C.CACHE / name), np.float32 if \"fhr\" in name or \"base\" in name else np.int8)\n", "\n", "\n", "def _baseline(args):\n", " x, w = args\n", " return median_filter(fill_linear(x), size=int(w * 60 * C.FS_FHR) | 1, mode=\"nearest\").astype(np.float32)\n", "\n", "\n", "def baselines(X, w):\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " return np.stack(list(ex.map(_baseline, [(x, w) for x in X], chunksize=32)))\n", "\n", "\n", "def rule_seg(x, base, core, ext, mind):\n", " d = fill_linear(x) - base\n", " out = np.zeros(x.size, np.int8)\n", " for val, sgn in ((1, 1), (-1, -1)):\n", " e = sgn * d\n", " cand = events((e >= ext).astype(np.int8), 1)\n", " for a, b in cand:\n", " if (e[a:b] >= core).sum() >= mind * C.FS_FHR:\n", " out[a:b] = val\n", " return out\n", "\n", "\n", "RULE_GRID = list(itertools.product([5, 10], [10, 15], [5, 10, 15], [10, 15]))\n", "\n", "\n", "def score(pred, lab, groups=None, ci=False):\n", " ign = lab == -9\n", " dc = [dice_counts(p, l, i) for p, l, i in zip(pred, lab, ign)]\n", " ec = [event_counts(np.where(i, 0, p), np.where(i, 0, l)) for p, l, i in zip(pred, lab, ign)]\n", " res = {\"dice\": dice_from_counts(dc), \"evidence\": evidence_f1(ec)}\n", " if ci and groups is not None:\n", " res[\"ci_dice_macro\"] = bootstrap(lambda i: dice_from_counts([dc[k] for k in i])[\"pooled_macro\"], groups)\n", " res[\"ci_dice_dec\"] = bootstrap(lambda i: dice_from_counts([dc[k] for k in i])[\"pooled_-1\"], groups)\n", " res[\"ci_evidence_macro\"] = bootstrap(lambda i: evidence_f1([ec[k] for k in i])[\"macro_f1\"], groups)\n", " return res\n", "\n", "\n", "def tune_rules(X, Y, B, idx):\n", " best = None\n", " for w, core, ext, mind in RULE_GRID:\n", " if ext > core:\n", " continue\n", " pred = [rule_seg(X[i], B[w][i], core, ext, mind) for i in idx]\n", " s = score(pred, Y[idx])[\"dice\"][\"pooled_macro\"]\n", " if best is None or s > best[0]:\n", " best = (s, (w, core, ext, mind))\n", " return best[1]\n", "\n", "\n", "def crossfit_rules(X, Y, B, fold):\n", " pred = np.zeros_like(Y)\n", " params = {}\n", " for f in range(C.N_FOLDS):\n", " tr = np.flatnonzero((fold >= 0) & (fold != f))\n", " te = np.flatnonzero(fold == f)\n", " p = tune_rules(X, Y, B, tr)\n", " params[f] = p\n", " for i in te:\n", " pred[i] = rule_seg(X[i], B[p[0]][i], *p[1:])\n", " return pred, params\n", "\n", "\n", "@stage(\"s12_t2_rules\", outputs=[C.CACHE / \"t2_rules_pred_t4.npy\"])\n", "def rules(log):\n", " m2, m4 = t2_meta(), t4_meta()\n", " X2, Y2 = arr(\"t2_fhr.npy\"), arr(\"t2_lab.npy\")\n", " X4, Y4 = arr(\"t4_fhr.npy\"), arr(\"t4_seg.npy\")\n", " B2 = {w: baselines(X2, w) for w in (5, 10)}\n", " B4 = {w: baselines(X4, w) for w in (5, 10)}\n", " rep = {}\n", " p2, par2 = crossfit_rules(X2, Y2, B2, m2.fold.values)\n", " ok2 = m2.fold.values >= 0\n", " rep[\"t2_rules_t2tuned_on_t2\"] = dict(score(p2[ok2], Y2[ok2], m2.group.values[ok2], ci=True), params=par2)\n", " p4, par4 = crossfit_rules(X4, Y4, B4, m4.fold.values)\n", " ok4 = m4.fold.values >= 0\n", " rep[\"t2_rules_t4tuned_on_t4\"] = dict(score(p4[ok4], Y4[ok4], m4.group.values[ok4], ci=True), params=par4)\n", " allp = tune_rules(X2, Y2, B2, np.flatnonzero(ok2))\n", " q4 = np.stack([rule_seg(X4[i], B4[allp[0]][i], *allp[1:]) for i in range(len(m4))])\n", " rep[\"t2_rules_t2tuned_on_t4\"] = dict(score(q4[ok4], Y4[ok4], m4.group.values[ok4], ci=True), params=allp)\n", " save_npy(C.CACHE / \"t2_rules_pred_t4.npy\", p4)\n", " save_json(C.RES / \"s12_t2_rules.json\", rep)\n", " return {k: v[\"dice\"][\"pooled_macro\"] for k, v in rep.items()}\n", "\n", "\n", "class Down(nn.Module):\n", " def __init__(self, a, b, k=7):\n", " super().__init__()\n", " self.c = nn.Sequential(nn.Conv1d(a, b, k, padding=k // 2), nn.GroupNorm(8, b), nn.GELU(), nn.Conv1d(b, b, k, padding=k // 2), nn.GroupNorm(8, b), nn.GELU())\n", "\n", " def forward(self, x):\n", " return self.c(x)\n", "\n", "\n", "class UNet1D(nn.Module):\n", " def __init__(self, cin=2, base=32, depth=4):\n", " super().__init__()\n", " ch = [base * 2 ** i for i in range(depth + 1)]\n", " self.enc = nn.ModuleList([Down(cin if i == 0 else ch[i - 1], ch[i]) for i in range(depth)])\n", " self.mid = Down(ch[depth - 1], ch[depth])\n", " self.up = nn.ModuleList([nn.ConvTranspose1d(ch[i + 1], ch[i], 2, stride=2) for i in reversed(range(depth))])\n", " self.dec = nn.ModuleList([Down(ch[i] * 2, ch[i]) for i in reversed(range(depth))])\n", " self.seg = nn.Conv1d(base, 3, 1)\n", " self.base = nn.Conv1d(base, 1, 1)\n", "\n", " def forward(self, x):\n", " n = x.shape[-1]\n", " pad = (-n) % 16\n", " x = F.pad(x, (0, pad), mode=\"replicate\")\n", " skips = []\n", " for e in self.enc:\n", " x = e(x)\n", " skips.append(x)\n", " x = F.max_pool1d(x, 2)\n", " x = self.mid(x)\n", " for u, d, s in zip(self.up, self.dec, reversed(skips)):\n", " x = d(torch.cat([u(x), s], 1))\n", " return self.seg(x)[..., :n], self.base(x)[..., :n]\n", "\n", "\n", "def inputs(x):\n", " v = valid(x)\n", " f = fill_linear(x)\n", " return np.stack([np.clip((f - 110) / 50, -1.2, 2.0), v.astype(np.float32)]), f\n", "\n", "\n", "class T2Data:\n", " def __init__(self, idx, X=None, Y=None, B=None):\n", " self.X = arr(\"t2_fhr.npy\") if X is None else X\n", " self.Y = arr(\"t2_lab.npy\") if Y is None else Y\n", " self.B = (arr(\"t2_base.npy\") if X is None else np.full(self.X.shape, np.nan, np.float32)) if B is None else B\n", " self.idx = np.asarray(idx)\n", "\n", " def item(self, i, rng=None):\n", " x = self.X[i].copy()\n", " b = self.B[i].copy()\n", " if rng is not None:\n", " s = rng.uniform(0.95, 1.05)\n", " o = rng.uniform(-5, 5)\n", " ctr = np.nanmedian(x) if np.isfinite(x).any() else 140.0\n", " x = (x - ctr) * s + ctr + o\n", " b = (b - ctr) * s + ctr + o\n", " if rng.random() < 0.3:\n", " L = int(rng.integers(8, 120))\n", " a = int(rng.integers(0, C.N - L))\n", " x[a:a + L] = np.nan\n", " inp, _ = inputs(x)\n", " yr = np.asarray(self.Y[i])\n", " y = np.full(yr.shape, -100, np.int64)\n", " y[yr == 0], y[yr == 1], y[yr == -1] = 0, 1, 2\n", " bt = (b - 110) / 50\n", " bm = np.isfinite(bt) & (y >= 0)\n", " return inp, y, np.nan_to_num(bt).astype(np.float32), bm.astype(np.float32)\n", "\n", " def batch(self, ids, rng=None):\n", " it = [self.item(i, rng) for i in ids]\n", " return [torch.from_numpy(np.stack(z)) for z in zip(*it)]\n", "\n", "\n", "def class_weights(Y):\n", " c = np.array([(Y == 0).sum(), (Y == 1).sum(), (Y == -1).sum()], float) + 1\n", " w = (c.sum() / c) ** 0.5\n", " return torch.tensor(w / w.mean(), dtype=torch.float32)\n", "\n", "\n", "def loss_fn(seg, base, y, bt, bm, w):\n", " ce = F.cross_entropy(seg.float(), y, weight=w.to(seg.device), ignore_index=-100)\n", " p = torch.softmax(seg.float(), 1)\n", " m = (y >= 0).float()[:, None]\n", " oh = F.one_hot(y.clamp_min(0), 3).transpose(1, 2).float() * m\n", " inter = (p * oh * m).sum((0, 2))\n", " den = (p * m).sum((0, 2)) + oh.sum((0, 2))\n", " dice = 1 - ((2 * inter + 1) / (den + 1)).mean()\n", " bl = (F.smooth_l1_loss(base.squeeze(1).float(), bt, reduction=\"none\") * bm).sum() / bm.sum().clamp_min(1)\n", " return ce + dice + 0.1 * bl\n", "\n", "\n", "@torch.no_grad()\n", "def predict_probs(model, X, dev, log=None):\n", " model.eval()\n", "\n", " def fn(i, j):\n", " xs = torch.from_numpy(np.stack([inputs(x)[0] for x in X[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " s, _ = model(xs)\n", " return torch.softmax(s.float(), 1).cpu().numpy().astype(np.float16)\n", "\n", " return np.concatenate(adaptive_batches(len(X), fn, 64, log=log))\n", "\n", "\n", "def fit_seg(name, params, data, tr, va, outdir, epochs, lr, log, seed, init=None, force=False):\n", " seed_all(seed)\n", " dev = device()\n", " w = class_weights(data.Y[tr])\n", " model = UNet1D().to(dev)\n", " if init is not None:\n", " model.load_state_dict(torch.load(init, map_location=dev, weights_only=True)[\"model\"])\n", " opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)\n", " bs0 = 32\n", " steps = max(1, math.ceil(len(tr) / bs0))\n", " sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * steps * 2 + 10, pct_start=0.1)\n", " scaler = torch.amp.GradScaler(enabled=dev.type == \"cuda\")\n", " d = outdir\n", " d.mkdir(parents=True, exist_ok=True)\n", " st = {\"epoch\": 0, \"best\": -1.0, \"bad\": 0, \"bs\": bs0, \"hist\": [], \"t0\": time.time()}\n", " if (d / \"last.pt\").exists() and not force:\n", " ck = torch.load(d / \"last.pt\", map_location=dev, weights_only=False)\n", " for o, k in ((model, \"model\"), (opt, \"opt\"), (sched, \"sched\"), (scaler, \"scaler\")):\n", " o.load_state_dict(ck[k])\n", " st = ck[\"state\"]\n", " log.info(f\"resumed at epoch {st['epoch']}\")\n", " rng = np.random.default_rng(seed + st[\"epoch\"])\n", " Xva, Yva = data.X[va], data.Y[va]\n", " while st[\"epoch\"] < epochs and st[\"bad\"] < C.PATIENCE:\n", " model.train()\n", " t0 = time.time()\n", " order = rng.permutation(tr)\n", " tot, k, nb = 0.0, 0, 0\n", " while k < order.size:\n", " ids = order[k:k + st[\"bs\"]]\n", " inp, y, bt, bm = (t.to(dev) for t in data.batch(ids, rng))\n", " try:\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " s, b = model(inp)\n", " loss = loss_fn(s, b, y, bt, bm, w)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " if sched.last_epoch < sched.total_steps - 1:\n", " sched.step()\n", " tot += float(loss)\n", " nb += 1\n", " k += ids.size\n", " except RuntimeError as e:\n", " if \"out of memory\" not in str(e).lower() or st[\"bs\"] <= 2:\n", " raise\n", " opt.zero_grad(set_to_none=True)\n", " free_mem()\n", " st[\"bs\"] //= 2\n", " log.warning(f\"OOM: batch -> {st['bs']}\")\n", " pv = predict_probs(model, Xva, dev, log)\n", " sc = score(IDX2LAB[pv.argmax(1)], Yva)[\"dice\"]\n", " vd = sc[\"pooled_macro\"]\n", " st[\"epoch\"] += 1\n", " st[\"hist\"].append({\"epoch\": st[\"epoch\"], \"train_loss\": tot / max(1, nb), \"val_dice_macro\": vd, \"val_dice_dec\": sc[\"pooled_-1\"], \"sec\": time.time() - t0})\n", " if vd > st[\"best\"] + 1e-4:\n", " st[\"best\"], st[\"bad\"] = vd, 0\n", " torch.save({\"model\": model.state_dict()}, d / \"best.tmp\")\n", " (d / \"best.tmp\").replace(d / \"best.pt\")\n", " else:\n", " st[\"bad\"] += 1\n", " torch.save({\"model\": model.state_dict(), \"opt\": opt.state_dict(), \"sched\": sched.state_dict(), \"scaler\": scaler.state_dict(), \"state\": st}, d / \"last.tmp\")\n", " (d / \"last.tmp\").replace(d / \"last.pt\")\n", " log.info(st[\"hist\"][-1])\n", " if not (d / \"best.pt\").exists():\n", " torch.save({\"model\": model.state_dict()}, d / \"best.pt\")\n", " mark_done(name, params, {\"best_val_dice_macro\": st[\"best\"], \"epochs\": st[\"epoch\"], \"history\": st[\"hist\"], \"seconds\": round(time.time() - st[\"t0\"], 1)}, [d / \"best.pt\"])\n", "\n", "\n", "def train_unet(force=False, fold=0):\n", " name = f\"s13_t2_unet_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T2}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " m = t2_meta()\n", " tr, va = inner_split(m, fold)\n", " fit_seg(name, params, T2Data(tr), tr, va, C.MODELS / \"t2_unet\" / f\"fold{fold}\", C.EPOCHS_T2, 1e-3, log, C.SEED + fold, force=force)\n", "\n", "\n", "def finetune_t4(force=False, fold=0):\n", " name = f\"s13b_t2_ft4_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_FT}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " m4 = t4_meta()\n", " tr, va = inner_split(m4, fold)\n", " data = T2Data(tr, arr(\"t4_fhr.npy\"), arr(\"t4_seg.npy\"))\n", " init = C.MODELS / \"t2_unet\" / f\"fold{fold}\" / \"best.pt\"\n", " fit_seg(name, params, data, tr, va, C.MODELS / \"t2_ft4\" / f\"fold{fold}\", C.EPOCHS_FT, 3e-4, log, C.SEED + 50 + fold, init=init, force=force)\n", "\n", "\n", "def load_ft4(fold, dev):\n", " model = UNet1D().to(dev)\n", " model.load_state_dict(torch.load(C.MODELS / \"t2_ft4\" / f\"fold{fold}\" / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " return model.eval()\n", "\n", "\n", "def ft4_oof_probs(X4, dev, log=None):\n", " m4 = t4_meta()\n", " safe = safe_models_for_t4()\n", " out = np.full((len(X4), 3, C.N), np.nan, np.float32)\n", " ok = np.zeros(len(X4), bool)\n", " for f in range(C.N_FOLDS):\n", " idx = np.flatnonzero((m4.fold.values == f) & np.array([f in s for s in safe]))\n", " if idx.size:\n", " out[idx] = predict_probs(load_ft4(f, dev), X4[idx], dev, log)\n", " ok[idx] = True\n", " return out, ok\n", "\n", "\n", "def load_unet(fold, dev):\n", " model = UNet1D().to(dev)\n", " model.load_state_dict(torch.load(C.MODELS / \"t2_unet\" / f\"fold{fold}\" / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " return model.eval()\n", "\n", "\n", "def safe_models_for_t4():\n", " m4 = t4_meta()\n", " m2 = t2_meta()\n", " try:\n", " z = load_npz(C.CACHE / f\"fp_groups_k{C.FP_K_MAIN}.npz\")\n", " o4, n4 = z[\"off_t4\"]\n", " o2, n2 = z[\"off_t2\"]\n", " c4, c2 = z[\"comp\"][o4:o4 + n4], z[\"comp\"][o2:o2 + n2]\n", " except FileNotFoundError:\n", " c4, c2 = np.arange(len(m4)), np.arange(len(m2)) + 10 ** 9\n", " folds2 = m2.fold.values\n", " safe = []\n", " for i in range(len(m4)):\n", " linked = folds2[c2 == c4[i]]\n", " linked = linked[linked >= 0]\n", " if linked.size == 0:\n", " safe.append(list(range(C.N_FOLDS)))\n", " elif np.unique(linked).size == 1:\n", " safe.append([int(linked[0])])\n", " else:\n", " safe.append([])\n", " return safe\n", "\n", "\n", "def unet_t4_probs(X4, dev, log=None):\n", " safe = safe_models_for_t4()\n", " out = np.zeros((len(X4), 3, C.N), np.float32)\n", " cnt = np.zeros(len(X4))\n", " for f in range(C.N_FOLDS):\n", " idx = np.array([i for i, s in enumerate(safe) if f in s])\n", " if idx.size == 0:\n", " continue\n", " p = predict_probs(load_unet(f, dev), X4[idx], dev, log)\n", " out[idx] += p\n", " cnt[idx] += 1\n", " ok = cnt > 0\n", " out[ok] /= cnt[ok, None, None]\n", " out[~ok] = np.nan\n", " return out, ok\n", "\n", "\n", "def clean(labels, min_points, merge_gap):\n", " labels = np.asarray(labels, np.int8).copy()\n", " for v in (1, -1):\n", " idx = np.flatnonzero(labels == v)\n", " if not idx.size:\n", " continue\n", " for g in np.split(idx, np.flatnonzero(np.diff(idx) > merge_gap + 1) + 1):\n", " a, b = int(g[0]), int(g[-1]) + 1\n", " if b - a >= min_points:\n", " labels[a:b] = np.where(labels[a:b] == -v, labels[a:b], v)\n", " else:\n", " labels[g] = 0\n", " return labels\n", "\n", "\n", "PP_GRID = list(itertools.product([0, 40, 60, 80], [0, 20, 40]))\n", "\n", "\n", "def post(probs, mp, mg):\n", " return np.stack([clean(IDX2LAB[p.argmax(0)], mp, mg) for p in probs])\n", "\n", "\n", "def crossfit_post(P, Y, fold):\n", " out = np.zeros(Y.shape, np.int8)\n", " params = {}\n", " for f in range(C.N_FOLDS):\n", " tr = np.flatnonzero((fold >= 0) & (fold != f))\n", " te = np.flatnonzero(fold == f)\n", " best = max(PP_GRID, key=lambda g: score(post(P[tr], *g), Y[tr])[\"dice\"][\"pooled_macro\"])\n", " params[f] = best\n", " out[te] = post(P[te], *best)\n", " return out, params\n", "\n", "\n", "def official_t2(X, dev):\n", " if str(C.REPO) not in sys.path:\n", " sys.path.insert(0, str(C.REPO))\n", " from ctg_baseline.tools import Task2Tool\n", " tool = Task2Tool(dev)\n", " return np.stack([tool.run(x)[\"labels\"] for x in X])\n", "\n", "\n", "BURDEN_BINS = np.array([0.0, 1e-9, 0.02, 0.05, 0.1, 0.2, 1.01])\n", "\n", "\n", "def dec_burden(Y):\n", " return np.array([np.mean(np.asarray(y) == -1) for y in Y])\n", "\n", "\n", "def matched_weights(src_burden, tgt_burden):\n", " bs = np.digitize(src_burden, BURDEN_BINS) - 1\n", " bt = np.digitize(tgt_burden, BURDEN_BINS) - 1\n", " k = BURDEN_BINS.size - 1\n", " ps = np.bincount(bs, minlength=k) / bs.size\n", " pt = np.bincount(bt, minlength=k) / bt.size\n", " w = np.where(ps[bs] > 0, pt[bs] / np.maximum(ps[bs], 1e-12), 0.0)\n", " cover = float(pt[ps > 0].sum())\n", " return w, cover\n", "\n", "\n", "def weighted_dice(dc, w, k=-1):\n", " inter = sum(wi * c[k][0] for wi, c in zip(w, dc))\n", " s = sum(wi * (c[k][1] + c[k][2]) for wi, c in zip(w, dc))\n", " return 2 * inter / s if s else np.nan\n", "\n", "\n", "def full_score(pred, lab, groups):\n", " ign = lab == -9\n", " dc = [dice_counts(p, l, i) for p, l, i in zip(pred, lab, ign)]\n", " ec = [event_counts(np.where(i, 0, p), np.where(i, 0, l)) for p, l, i in zip(pred, lab, ign)]\n", " res = {\"dice\": dice_from_counts(dc), \"evidence\": evidence_f1(ec)}\n", " for agg in (\"pooled\", \"record\"):\n", " for k, nm in ((-1, \"dec\"), (1, \"acc\"), (\"macro\", \"macro\")):\n", " key = f\"{agg}_{k}\"\n", " res[f\"ci_{agg}_dice_{nm}\"] = bootstrap(lambda i, key=key: dice_from_counts([dc[j] for j in i])[key], groups)\n", " res[\"ci_evidence_dec_f1\"] = bootstrap(lambda i: evidence_f1([ec[j] for j in i])[\"dec_f1\"], groups)\n", " res[\"ci_evidence_macro\"] = bootstrap(lambda i: evidence_f1([ec[j] for j in i])[\"macro_f1\"], groups)\n", " return res, dc, ec\n", "\n", "\n", "@stage(\"s14_t2_eval\", params={\"v\": 2}, outputs=[C.CACHE / \"t2_unet_t4ref_probs.npy\", C.CACHE / \"t2_unet_pred_t4ref.npy\", C.CACHE / \"t2_ft4_pred_t4ref.npy\"])\n", "def evaluate(log):\n", " dev = device()\n", " m2, m4 = t2_meta(), t4_meta()\n", " X2, Y2 = arr(\"t2_fhr.npy\"), arr(\"t2_lab.npy\")\n", " X4, Y4 = arr(\"t4_fhr.npy\"), arr(\"t4_seg.npy\")\n", " P2 = np.full((len(m2), 3, C.N), np.nan, np.float32)\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(m2.fold.values == f)\n", " P2[te] = predict_probs(load_unet(f, dev), X2[te], dev, log)\n", " save_npy(C.CACHE / \"t2_unet_oof_probs.npy\", P2.astype(np.float16))\n", " P4, safe_ok = unet_t4_probs(X4, dev, log)\n", " save_npy(C.CACHE / \"t2_unet_t4ref_probs.npy\", P4.astype(np.float16))\n", " F4, ft_ok = ft4_oof_probs(X4, dev, log)\n", " ok2 = m2.fold.values >= 0\n", " ok4 = (m4.fold.values >= 0) & safe_ok & ft_ok\n", " f2 = np.where(ok2, m2.fold.values, -1)\n", " f4 = np.where(ok4, m4.fold.values, -1)\n", " g2, g4 = m2.group.values, m4.group.values\n", " rep = {\"n_t2\": int(ok2.sum()), \"n_t4\": int(ok4.sum()), \"t4_records_excluded_for_leakage\": int(((m4.fold.values >= 0) & ~(safe_ok & ft_ok)).sum())}\n", " rep[\"unet_raw_on_t2\"], _, _ = full_score(IDX2LAB[np.nan_to_num(P2).argmax(1)][ok2], Y2[ok2], g2[ok2])\n", " pp2, par2 = crossfit_post(P2, Y2, f2)\n", " s, dc2, _ = full_score(pp2[ok2], Y2[ok2], g2[ok2])\n", " rep[\"unet_t2_on_t2\"] = dict(s, params=par2)\n", " best_t2 = max(PP_GRID, key=lambda g: score(post(P2[ok2], *g), Y2[ok2])[\"dice\"][\"pooled_macro\"])\n", " q4 = post(np.nan_to_num(P4), *best_t2)\n", " s, _, _ = full_score(q4[ok4], Y4[ok4], g4[ok4])\n", " rep[\"unet_t2_on_t4_t2post\"] = dict(s, params=best_t2)\n", " pp4, par4 = crossfit_post(np.nan_to_num(P4), Y4, f4)\n", " s, _, _ = full_score(pp4[ok4], Y4[ok4], g4[ok4])\n", " rep[\"unet_t2_on_t4_t4post\"] = dict(s, params=par4, identical_to_t2post=bool(np.array_equal(pp4[ok4], q4[ok4])))\n", " ft4, parf = crossfit_post(np.nan_to_num(F4), Y4, f4)\n", " s, _, _ = full_score(ft4[ok4], Y4[ok4], g4[ok4])\n", " rep[\"unet_ft4_on_t4\"] = dict(s, params=parf)\n", " save_npy(C.CACHE / \"t2_unet_pred_t4ref.npy\", pp4)\n", " save_npy(C.CACHE / \"t2_ft4_pred_t4ref.npy\", ft4)\n", " b2, b4 = dec_burden(Y2[ok2]), dec_burden(Y4[ok4])\n", " w, cover = matched_weights(b2, b4)\n", " matched = weighted_dice(dc2, w)\n", " gg = g2[ok2]\n", " ci = bootstrap(lambda i: weighted_dice([dc2[j] for j in i], w[i]), gg)\n", " rep[\"prevalence\"] = {\"dec_point_frac_t2\": float(np.mean(Y2[ok2] == -1)), \"dec_point_frac_t4\": float(np.mean(Y4[ok4] == -1)), \"frac_windows_without_dec_t2\": float(np.mean(b2 == 0)), \"frac_windows_without_dec_t4\": float(np.mean(b4 == 0)), \"t4_burden_mass_covered_by_t2\": cover}\n", " rep[\"unet_t2_on_t2_matched_to_t4_burden\"] = {\"pooled_dec_dice\": matched, \"ci\": ci}\n", " try:\n", " o2 = official_t2(X2[ok2], dev)\n", " o4 = official_t2(X4[ok4], dev)\n", " rep[\"official_on_t2_independence_unknown\"], _, _ = full_score(o2, Y2[ok2], g2[ok2])\n", " rep[\"official_on_t4_independence_unknown\"], _, _ = full_score(o4, Y4[ok4], g4[ok4])\n", " except Exception as e:\n", " rep[\"official_error\"] = repr(e)\n", " d = lambda k: rep[k][\"dice\"][\"pooled_-1\"]\n", " r = lambda k: rep[k][\"dice\"][\"record_-1\"]\n", " e = lambda k: rep[k][\"evidence\"][\"dec_f1\"]\n", " rep[\"convention_shift\"] = {\n", " \"pooled_dec_dice\": {\"t2\": d(\"unet_t2_on_t2\"), \"t2_matched_to_t4_burden\": matched, \"t4_t2model\": d(\"unet_t2_on_t4_t2post\"), \"t4_t4post\": d(\"unet_t2_on_t4_t4post\"), \"t4_finetuned\": d(\"unet_ft4_on_t4\")},\n", " \"record_dec_dice\": {\"t2\": r(\"unet_t2_on_t2\"), \"t4_t2model\": r(\"unet_t2_on_t4_t2post\"), \"t4_finetuned\": r(\"unet_ft4_on_t4\")},\n", " \"event_dec_f1\": {\"t2\": e(\"unet_t2_on_t2\"), \"t4_t2model\": e(\"unet_t2_on_t4_t2post\"), \"t4_finetuned\": e(\"unet_ft4_on_t4\")},\n", " \"raw_gap\": d(\"unet_t2_on_t2\") - d(\"unet_t2_on_t4_t2post\"),\n", " \"prevalence_part\": d(\"unet_t2_on_t2\") - matched,\n", " \"residual_convention_or_domain\": matched - d(\"unet_t2_on_t4_t2post\"),\n", " \"recovered_by_postprocessing\": d(\"unet_t2_on_t4_t4post\") - d(\"unet_t2_on_t4_t2post\"),\n", " \"recovered_by_finetuning\": d(\"unet_ft4_on_t4\") - d(\"unet_t2_on_t4_t2post\"),\n", " }\n", " save_json(C.RES / \"s14_t2_eval.json\", rep)\n", " return {k: v for k, v in rep[\"convention_shift\"].items() if not isinstance(v, dict)}" ] }, { "cell_type": "code", "execution_count": 15, "id": "8f06031a361a", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.793823Z", "iopub.status.busy": "2026-11-28T14:17:32.793453Z", "iopub.status.idle": "2026-11-28T14:17:32.806002Z", "shell.execute_reply": "2026-11-28T14:17:32.804374Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/t3.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/t3.py\n", "import sys\n", "from concurrent.futures import ProcessPoolExecutor\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from scipy.ndimage import binary_dilation, median_filter\n", "from scipy.signal import find_peaks, welch\n", "from sklearn.ensemble import HistGradientBoostingClassifier\n", "from sklearn.metrics import roc_auc_score\n", "\n", "from . import config as C\n", "from .io import events, fill_linear, valid\n", "from .metrics import binary_scores\n", "from .utils import bootstrap, device, load_df, mm, save_df, save_json, stage\n", "\n", "MISS = [\"miss_rate\", \"miss_longest_s\", \"miss_n_gaps\", \"miss_n_gaps15\"]\n", "\n", "\n", "def gaps(bad):\n", " if not bad.any():\n", " return np.zeros(0)\n", " d = np.diff(np.r_[0, bad.astype(np.int8), 0])\n", " return (np.flatnonzero(d == -1) - np.flatnonzero(d == 1)) / C.FS_FHR\n", "\n", "\n", "def ev_feats(d, thr, mind, prefix):\n", " out = {}\n", " for v, nm in ((1, \"acc\"), (-1, \"dec\")):\n", " e = v * d\n", " evs = [(a, b) for a, b in events((e >= thr).astype(np.int8), 1) if b - a >= mind * C.FS_FHR]\n", " out[f\"{prefix}{nm}_n\"] = len(evs)\n", " out[f\"{prefix}{nm}_dur\"] = sum(b - a for a, b in evs) / C.FS_FHR\n", " out[f\"{prefix}{nm}_area\"] = float(sum(e[a:b].sum() for a, b in evs) / C.FS_FHR)\n", " out[f\"{prefix}{nm}_max\"] = float(max([e[a:b].max() for a, b in evs], default=0.0))\n", " out[f\"{prefix}{nm}_prolonged\"] = sum(1 for a, b in evs if b - a >= 120 * C.FS_FHR)\n", " return out\n", "\n", "\n", "def fhr_features(x, uc=None):\n", " x = np.asarray(x, np.float32)\n", " v = valid(x)\n", " g = gaps(~v)\n", " f = {\"miss_rate\": 1 - v.mean(), \"miss_longest_s\": g.max() if g.size else 0.0, \"miss_n_gaps\": g.size, \"miss_n_gaps15\": int((g >= 15).sum())}\n", " xf = fill_linear(x)\n", " xv = x[v] if v.any() else xf\n", " f.update({\"mean\": xv.mean(), \"std\": xv.std(), **{f\"p{q}\": np.percentile(xv, q) for q in (5, 25, 50, 75, 95)}})\n", " base = median_filter(xf, size=2401, mode=\"nearest\")\n", " t = np.arange(C.N) / (C.FS_FHR * 60)\n", " f[\"base_median\"] = float(np.median(base))\n", " f[\"base_slope\"] = float(np.polyfit(t, base, 1)[0])\n", " f[\"base_range\"] = float(base.max() - base.min())\n", " d = xf - base\n", " m10 = xf[: C.N // 10 * 10].reshape(-1, 10).mean(1)\n", " f[\"stv\"] = float(np.mean(np.abs(np.diff(m10))))\n", " mins = xf.reshape(-1, 240)\n", " f[\"ltv_range_med\"] = float(np.median(mins.max(1) - mins.min(1)))\n", " f[\"ltv_iqr_med\"] = float(np.median(np.percentile(mins, 75, 1) - np.percentile(mins, 25, 1)))\n", " f[\"diff_std\"] = float(np.std(np.diff(xf)))\n", " f.update(ev_feats(d, 15, 15, \"e15_\"))\n", " f.update(ev_feats(d, 10, 10, \"e10_\"))\n", " fr, pw = welch(xf - base, fs=C.FS_FHR, nperseg=1024)\n", " for lo, hi, nm in ((0.03, 0.15, \"lf\"), (0.15, 0.5, \"mf\"), (0.5, 1.0, \"hf\")):\n", " f[f\"pow_{nm}\"] = float(np.log(pw[(fr >= lo) & (fr < hi)].sum() + 1e-6))\n", " f[\"lf_hf\"] = f[\"pow_lf\"] - f[\"pow_hf\"]\n", " if uc is not None:\n", " u = np.nan_to_num(np.asarray(uc, np.float32))\n", " f[\"uc_zero_frac\"] = float(np.mean(u <= 0))\n", " f[\"uc_mean\"], f[\"uc_std\"], f[\"uc_p95\"] = float(u.mean()), float(u.std()), float(np.percentile(u, 95))\n", " pk, _ = find_peaks(u, prominence=10, distance=60 * C.FS_FHR)\n", " f[\"uc_n_contractions\"] = int(pk.size)\n", " if u.std() > 1e-3 and d.std() > 1e-3:\n", " lags = np.arange(0, 60 * C.FS_FHR + 1, 4)\n", " cc = [np.corrcoef(-d[lag:], u[: C.N - lag])[0, 1] for lag in lags]\n", " k = int(np.nanargmax(cc))\n", " f[\"uc_xcorr_max\"], f[\"uc_xcorr_lag_s\"] = float(cc[k]), float(lags[k] / C.FS_FHR)\n", " else:\n", " f[\"uc_xcorr_max\"], f[\"uc_xcorr_lag_s\"] = 0.0, 0.0\n", " return f\n", "\n", "\n", "def _feat(args):\n", " x, u = args\n", " return fhr_features(x, u)\n", "\n", "\n", "def feature_table(X, U=None):\n", " jobs = [(X[i], None if U is None else U[i]) for i in range(len(X))]\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " rows = list(ex.map(_feat, jobs, chunksize=64))\n", " return pd.DataFrame(rows).astype(np.float32)\n", "\n", "\n", "def _default_rule(x):\n", " from .t2 import rule_seg\n", " return rule_seg(x, median_filter(fill_linear(x), 2401, mode=\"nearest\"), 15, 5, 15)\n", "\n", "\n", "def miss_rate_outside(X, S, val=-1, pad=120):\n", " out = np.zeros(len(X))\n", " for i in range(len(X)):\n", " bad = ~valid(X[i])\n", " near = np.zeros(C.N, bool)\n", " for a, b in events(S[i], val):\n", " near[max(0, a - pad):b + pad] = True\n", " out[i] = bad[~near].mean() if (~near).any() else np.nan\n", " return out\n", "\n", "\n", "@stage(\"s15_t3_features\", outputs=[C.CACHE / \"t3_features.pkl\", C.CACHE / \"t4_ref_features.pkl\"])\n", "def features(log):\n", " X3 = np.asarray(mm(C.CACHE / \"t3_fhr.npy\"), np.float32)\n", " U3 = np.asarray(mm(C.CACHE / \"t3_uc.npy\"), np.float32)\n", " F3 = feature_table(X3, U3)\n", " save_df(C.CACHE / \"t3_features.pkl\", F3)\n", " X4 = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " F4 = feature_table(X4)\n", " q = np.asarray(mm(C.CACHE / \"t1_q.npy\"), np.float32) if (C.CACHE / \"t1_q.npy\").exists() else None\n", " if q is not None:\n", " F4[\"dus_log_rms\"] = np.nanmean(q[..., 0], 1)\n", " F4[\"dus_prominence\"] = np.nanmean(q[..., 2], 1)\n", " F4[\"dus_clip\"] = np.nanmean(q[..., 4], 1)\n", " save_df(C.CACHE / \"t4_ref_features.pkl\", F4)\n", " return {\"t3_features\": F3.shape, \"t4_features\": F4.shape}\n", "\n", "\n", "def model(n=10 ** 6):\n", " return HistGradientBoostingClassifier(max_iter=300, learning_rate=0.05, max_leaf_nodes=31, min_samples_leaf=int(min(40, max(3, n // 25))), l2_regularization=0.1, early_stopping=False, random_state=C.SEED)\n", "\n", "\n", "def degenerate(p, fold):\n", " out = []\n", " for f in range(C.N_FOLDS):\n", " q = p[fold == f]\n", " if q.size and np.nanstd(q) < 1e-6:\n", " out.append(f)\n", " return out\n", "\n", "\n", "def oof(F, y, fold, cols):\n", " p = np.full(len(y), np.nan)\n", " for f in range(C.N_FOLDS):\n", " tr = (fold >= 0) & (fold != f)\n", " te = fold == f\n", " if te.any():\n", " p[te] = model(int(tr.sum())).fit(F.loc[tr, cols].values, y[tr]).predict_proba(F.loc[te, cols].values)[:, 1]\n", " return p\n", "\n", "\n", "def threshold_shift(p, y, fold):\n", " out = p.copy()\n", " from scipy.special import logit, expit\n", " grid = np.linspace(0.2, 0.8, 61)\n", " for f in range(C.N_FOLDS):\n", " tr = (fold >= 0) & (fold != f) & np.isfinite(p)\n", " te = fold == f\n", " if not te.any():\n", " continue\n", " best = max(grid, key=lambda t: binary_scores(y[tr], p[tr], t)[\"nmcc\"])\n", " out[te] = expit(logit(np.clip(p[te], 1e-6, 1 - 1e-6)) - logit(best))\n", " return out\n", "\n", "\n", "def evaluate_sets(F, y, fold, groups, sets):\n", " ok = fold >= 0\n", " res, preds = {}, {}\n", " for nm, cols in sets.items():\n", " cols = [c for c in cols if c in F]\n", " if not cols:\n", " continue\n", " p = oof(F, y, fold, cols)\n", " preds[nm] = p\n", " r = binary_scores(y[ok], p[ok])\n", " r[\"degenerate_folds\"] = degenerate(p, fold)\n", " r[\"ci_auroc\"] = bootstrap(lambda i, p=p: roc_auc_score(y[ok][i], p[ok][i]), groups[ok])\n", " r[\"after_threshold_shift\"] = binary_scores(y[ok], threshold_shift(p, y, fold)[ok])\n", " res[nm] = r\n", " return res, preds\n", "\n", "\n", "def paired_diff(y, pa, pb, groups):\n", " return bootstrap(lambda i: roc_auc_score(y[i], pa[i]) - roc_auc_score(y[i], pb[i]), groups)\n", "\n", "\n", "def official_t3(X, dev, which):\n", " if str(C.REPO) not in sys.path:\n", " sys.path.insert(0, str(C.REPO))\n", " from ctg_baseline.config import CHECKPOINTS\n", " from ctg_baseline.tools import Task2Tool, Task3Tool\n", " t2 = Task2Tool(dev)\n", " t3 = Task3Tool(dev, CHECKPOINTS[which])\n", " return np.array([t3.run(x, t2.run(x)[\"probabilities\"])[\"risk_probability\"] for x in X])\n", "\n", "\n", "@stage(\"s16_t3_models\")\n", "def models(log):\n", " dev = device()\n", " F3 = load_df(C.CACHE / \"t3_features.pkl\")\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " y3, f3, g3 = m3.y.values, m3.fold.values, m3.group.values\n", " fh = [c for c in F3 if c not in MISS and not c.startswith(\"uc_\")]\n", " uc = [c for c in F3 if c.startswith(\"uc_\")]\n", " sets = {\"a_missingness_only\": MISS, \"b_fhr_only\": fh, \"c_fhr_plus_missingness\": fh + MISS, \"d_fhr_missingness_quality\": fh + MISS + uc}\n", " rep = {\"t3\": {}, \"t4\": {}}\n", " res, pr = evaluate_sets(F3, y3, f3, g3, sets)\n", " rep[\"t3\"][\"controls\"] = res\n", " ok = f3 >= 0\n", " rep[\"t3\"][\"diff_c_minus_b\"] = paired_diff(y3[ok], pr[\"c_fhr_plus_missingness\"][ok], pr[\"b_fhr_only\"][ok], g3[ok])\n", " rep[\"t3\"][\"diff_b_minus_a\"] = paired_diff(y3[ok], pr[\"b_fhr_only\"][ok], pr[\"a_missingness_only\"][ok], g3[ok])\n", " fr = m3.fold_random.values\n", " pr_rand = oof(F3, y3, fr, fh + MISS + uc)\n", " pg = pr[\"d_fhr_missingness_quality\"]\n", " okr = ok & (fr >= 0)\n", " rep[\"t3\"][\"random_vs_grouped_cv\"] = {\"grouped\": binary_scores(y3[okr], pg[okr]), \"random\": binary_scores(y3[okr], pr_rand[okr]), \"optimism_auroc\": bootstrap(lambda i: roc_auc_score(y3[okr][i], pr_rand[okr][i]) - roc_auc_score(y3[okr][i], pg[okr][i]), g3[okr])}\n", " X3 = np.asarray(mm(C.CACHE / \"t3_fhr.npy\"), np.float32)\n", " with ProcessPoolExecutor(C.CPU) as ex:\n", " S3 = np.stack(list(ex.map(_default_rule, X3, chunksize=64)))\n", " out3 = miss_rate_outside(X3, S3)\n", " rep[\"t3\"][\"removal_test_auroc_missing_outside_decel\"] = binary_scores(y3[ok], np.nan_to_num(out3[ok]))[\"auroc\"]\n", " try:\n", " po = official_t3(X3[ok], dev, \"task3_native\")\n", " rep[\"t3\"][\"official_native_in_sample_unknown\"] = binary_scores(y3[ok], po)\n", " except Exception as e:\n", " rep[\"t3\"][\"official_error\"] = repr(e)\n", " F4 = load_df(C.CACHE / \"t4_ref_features.pkl\")\n", " m4 = load_df(C.CACHE / \"folds_t4.pkl\")\n", " y4, f4, g4 = m4.y.values, m4.fold.values, m4.group.values\n", " fh4 = [c for c in F4 if c not in MISS and not c.startswith(\"dus_\")]\n", " sets4 = {\"a_missingness_only\": MISS, \"b_fhr_only\": fh4, \"c_fhr_plus_missingness\": fh4 + MISS, \"d_fhr_missingness_quality\": fh4 + MISS + [c for c in F4 if c.startswith(\"dus_\")]}\n", " res4, pr4 = evaluate_sets(F4, y4, f4, g4, sets4)\n", " rep[\"t4\"][\"controls\"] = res4\n", " ok4 = f4 >= 0\n", " rep[\"t4\"][\"diff_c_minus_b\"] = paired_diff(y4[ok4], pr4[\"c_fhr_plus_missingness\"][ok4], pr4[\"b_fhr_only\"][ok4], g4[ok4])\n", " X4 = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " S4 = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " out4 = miss_rate_outside(X4, S4)\n", " rep[\"t4\"][\"removal_test_auroc_missing_outside_decel\"] = binary_scores(y4[ok4], np.nan_to_num(out4[ok4]))[\"auroc\"]\n", " try:\n", " for which in (\"task3_native\", \"task3_flow\"):\n", " rep[\"t4\"][f\"official_{which}_on_reference_fhr\"] = binary_scores(y4[ok4], official_t3(X4[ok4], dev, which))\n", " except Exception as e:\n", " rep[\"t4\"][\"official_error\"] = repr(e)\n", " save_json(C.RES / \"s16_t3_models.json\", rep)\n", " return {\"t3_grouped_auroc\": res[\"d_fhr_missingness_quality\"][\"auroc\"], \"t3_optimism\": rep[\"t3\"][\"random_vs_grouped_cv\"][\"optimism_auroc\"][\"point\"], \"t4_fhr_auroc\": res4[\"b_fhr_only\"][\"auroc\"]}" ] }, { "cell_type": "code", "execution_count": 16, "id": "c2c912112066", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.809810Z", "iopub.status.busy": "2026-11-28T14:17:32.809458Z", "iopub.status.idle": "2026-11-28T14:17:32.821743Z", "shell.execute_reply": "2026-11-28T14:17:32.819807Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/t4.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/t4.py\n", "import json\n", "import sys\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from scipy.ndimage import median_filter\n", "\n", "from . import config as C\n", "from .io import events, fill_linear\n", "from .metrics import binary_scores, dice_counts, dice_from_counts, event_counts, evidence_f1\n", "from .t1 import gather_tcn\n", "from .t2 import ft4_oof_probs, post, unet_t4_probs\n", "from .t3 import degenerate, feature_table, model\n", "from .utils import bootstrap, device, load_df, load_json, mm, save_json, stage\n", "\n", "CONFIGS = [(0, 0), (0, 1), (1, 0), (1, 1)]\n", "DOWN = (\"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\")\n", "SEGM = (\"flow_dice\", \"evidence_f1\")\n", "METRICS = SEGM + DOWN\n", "\n", "\n", "def name(cfg):\n", " return f\"R{cfg[0]}E{cfg[1]}\"\n", "\n", "\n", "def estimated_fhr(log):\n", " res, _ = gather_tcn()\n", " if C.T1_PRIMARY == \"tcn\" and res is not None and np.isfinite(res[..., 0]).any():\n", " est, src = res[..., 0], \"tcn_median\"\n", " else:\n", " est, src = np.asarray(mm(C.CACHE / \"t1_floor.npy\"), np.float32)[..., 1], \"floor_post_median\"\n", " log.info(f\"estimated FHR source: {src}\")\n", " return np.stack([fill_linear(x) for x in est]), src\n", "\n", "\n", "def seg_features(X, S):\n", " rows = []\n", " for x, s in zip(X, S):\n", " xf = fill_linear(x)\n", " d = xf - median_filter(xf, 2401, mode=\"nearest\")\n", " r = {}\n", " for v, nm in ((1, \"acc\"), (-1, \"dec\")):\n", " ev = events(s, v)\n", " r[f\"seg_{nm}_n\"] = len(ev)\n", " r[f\"seg_{nm}_dur\"] = float(sum(b - a for a, b in ev) / C.FS_FHR)\n", " r[f\"seg_{nm}_mean_dur\"] = r[f\"seg_{nm}_dur\"] / max(1, len(ev))\n", " r[f\"seg_{nm}_depth\"] = float(max([np.abs(d[a:b]).max() for a, b in ev], default=0.0))\n", " r[f\"seg_{nm}_area\"] = float(sum(np.abs(d[a:b]).sum() for a, b in ev) / C.FS_FHR)\n", " rows.append(r)\n", " return pd.DataFrame(rows).astype(np.float32)\n", "\n", "\n", "def crossfit(Ftr, Fte, y, fold):\n", " p = np.full(len(y), np.nan)\n", " for f in range(C.N_FOLDS):\n", " tr = (fold >= 0) & (fold != f)\n", " te = fold == f\n", " if te.any():\n", " p[te] = model(int(tr.sum())).fit(Ftr[tr], y[tr]).predict_proba(Fte[te])[:, 1]\n", " return p\n", "\n", "\n", "def report(rid, seg, p, xf):\n", " acc = [{\"start_sec\": a / C.FS_FHR, \"end_sec\": b / C.FS_FHR} for a, b in events(seg, 1)]\n", " dec = [{\"start_sec\": a / C.FS_FHR, \"end_sec\": b / C.FS_FHR} for a, b in events(seg, -1)]\n", " cls = int(p >= 0.5)\n", " return {\"record_id\": rid, \"baseline_fhr\": float(np.median(xf)), \"acceleration_count\": len(acc), \"acceleration_intervals\": acc, \"deceleration_count\": len(dec), \"deceleration_intervals\": dec, \"risk_probability\": float(p), \"risk_class\": cls, \"conclusion\": \"abnormal\" if cls else \"normal\", \"evidence\": [f\"Acceleration {a['start_sec']:.2f}-{a['end_sec']:.2f} s\" for a in acc] + [f\"Deceleration {d['start_sec']:.2f}-{d['end_sec']:.2f} s\" for d in dec]}\n", "\n", "\n", "def metric_values(y, p, dc, ec, idx):\n", " b = binary_scores(y[idx], p[idx])\n", " return {\"flow_dice\": dice_from_counts([dc[i] for i in idx])[\"pooled_macro\"], \"flow_dice_record\": dice_from_counts([dc[i] for i in idx])[\"record_macro\"], \"auroc\": b[\"auroc\"], \"f1\": b[\"f1\"], \"nmcc\": b[\"nmcc\"], \"evidence_f1\": evidence_f1([ec[i] for i in idx])[\"macro_f1\"], \"conclusion_f1\": b[\"f1_macro\"]}\n", "\n", "\n", "def shapley2(v):\n", " r = 0.5 * ((v[(1, 0)] - v[(0, 0)]) + (v[(1, 1)] - v[(0, 1)]))\n", " e = 0.5 * ((v[(0, 1)] - v[(0, 0)]) + (v[(1, 1)] - v[(1, 0)]))\n", " return {\"R\": r, \"E\": e, \"interaction\": v[(1, 1)] - v[(1, 0)] - v[(0, 1)] + v[(0, 0)], \"total_gain\": v[(1, 1)] - v[(0, 0)]}\n", "\n", "\n", "def official_chain(Xaf, idx, dev):\n", " if str(C.REPO) not in sys.path:\n", " sys.path.insert(0, str(C.REPO))\n", " from ctg_baseline.config import CHECKPOINTS\n", " from ctg_baseline.tools import Task2Tool, Task3Tool\n", " t2 = Task2Tool(dev)\n", " t3 = Task3Tool(dev, CHECKPOINTS[\"task3_flow\"])\n", " S = np.zeros((len(Xaf), C.N), np.int8)\n", " p = np.full(len(Xaf), np.nan)\n", " for i in idx:\n", " o = t2.run(Xaf[i])\n", " S[i] = o[\"labels\"]\n", " p[i] = t3.run(Xaf[i], o[\"probabilities\"])[\"risk_probability\"]\n", " return S, p\n", "\n", "\n", "def all_values(y, probs, dcs, ecs, sel):\n", " return {k: metric_values(y, probs[k], dcs[k], ecs[k], sel) for k in probs}\n", "\n", "\n", "def derive(vals):\n", " out = {}\n", " for met in DOWN:\n", " s = shapley2({cfg: vals[(\"m\",) + cfg][met] for cfg in CONFIGS})\n", " for k, v in s.items():\n", " out[f\"shapley_{met}_{k}\"] = v\n", " for cfg in CONFIGS[1:]:\n", " out[f\"mismatch_cost_{met}_{name(cfg)}\"] = vals[(\"m\",) + cfg][met] - vals[(\"x\",) + cfg][met]\n", " for met in SEGM:\n", " out[f\"R_effect_{met}\"] = vals[(\"m\", 1, 0)][met] - vals[(\"m\", 0, 0)][met]\n", " if (\"official\",) in vals:\n", " for met in METRICS:\n", " out[f\"ours_minus_official_{met}\"] = vals[(\"m\", 0, 0)][met] - vals[(\"official\",)][met]\n", " return out\n", "\n", "\n", "@stage(\"s17_t4_chain\", params={\"v\": 2})\n", "def chain(log):\n", " dev = device()\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " fold_all = m.fold.values\n", " y = m.y.values\n", " Xref = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " Xest, src = estimated_fhr(log)\n", " ev = load_json(C.RES / \"s14_t2_eval.json\")\n", " use_ft = \"unet_ft4_on_t4\" in ev\n", " pp = ev[\"unet_ft4_on_t4\" if use_ft else \"unet_t2_on_t4_t4post\"][\"params\"]\n", " ok = fold_all >= 0\n", " seg_model = {}\n", " for r, X in ((0, Xest), (1, Xref)):\n", " P, safe = ft4_oof_probs(X, dev, log) if use_ft else unet_t4_probs(X, dev, log)\n", " ok &= safe\n", " S = np.zeros((len(X), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " te = (fold_all == f) & safe\n", " if te.any():\n", " S[te] = post(np.nan_to_num(P[te]), *pp[str(f)])\n", " seg_model[r] = S\n", " fold = np.where(ok, fold_all, -1)\n", " idx = np.flatnonzero(ok)\n", " log.info(f\"records evaluated: {idx.size}; segmentation model: {'T4 fine-tuned' if use_ft else 'T2'}\")\n", " base = {0: feature_table(Xest), 1: feature_table(Xref)}\n", " feats = {cfg: pd.concat([base[cfg[0]], seg_features(Xest if cfg[0] == 0 else Xref, Sref if cfg[1] else seg_model[cfg[0]])], axis=1).values for cfg in CONFIGS}\n", " probs, dcs, ecs = {}, {}, {}\n", " for cfg in CONFIGS:\n", " S = Sref if cfg[1] else seg_model[cfg[0]]\n", " dc = [dice_counts(S[i], Sref[i]) for i in range(len(m))]\n", " ec = [event_counts(S[i], Sref[i]) for i in range(len(m))]\n", " probs[(\"m\",) + cfg] = crossfit(feats[cfg], feats[cfg], y, fold)\n", " dcs[(\"m\",) + cfg], ecs[(\"m\",) + cfg] = dc, ec\n", " if cfg != (0, 0):\n", " probs[(\"x\",) + cfg] = crossfit(feats[(0, 0)], feats[cfg], y, fold)\n", " dcs[(\"x\",) + cfg], ecs[(\"x\",) + cfg] = dc, ec\n", " rep = {\"estimated_fhr_source\": src, \"segmentation_model\": \"unet_finetuned_on_t4\" if use_ft else \"unet_t2\", \"n_records\": int(idx.size), \"notes\": {\"E_on_segmentation_metrics\": \"not attributable: replacing the segmentation by the reference gives 1.0 by construction; only the R effect at E=0 is reported\", \"classifier\": \"matched = gradient boosting cross-fitted on the same input type it is applied to; mismatched = trained on the deployed input (R0E0)\", \"official_chain\": \"AutoFHR (GPU port) + official Task2Tool + official task3_fused_flow; independence unknown\"}}\n", " try:\n", " Xaf = np.asarray(mm(C.CACHE / \"t1_af.npy\"), np.float32)[..., 0]\n", " So, po = official_chain(Xaf, idx, dev)\n", " probs[(\"official\",)] = po\n", " dcs[(\"official\",)] = [dice_counts(So[i], Sref[i]) for i in range(len(m))]\n", " ecs[(\"official\",)] = [event_counts(So[i], Sref[i]) for i in range(len(m))]\n", " except Exception as e:\n", " rep[\"official_error\"] = repr(e)\n", " log.warning(f\"official chain failed: {e!r}\")\n", " rep[\"degenerate_folds\"] = {\"_\".join(map(str, k)): degenerate(probs[k], fold) for k in probs if k[0] != \"official\"}\n", " vals = all_values(y, probs, dcs, ecs, idx)\n", " rep[\"configs\"] = {\"_\".join(map(str, k)): v for k, v in vals.items()}\n", " point = derive(vals)\n", " groups = m.group.values[idx]\n", " keys = list(point)\n", " b = bootstrap(lambda i: np.array([derive(all_values(y, probs, dcs, ecs, idx[i]))[k] for k in keys]), groups, B=min(C.BOOT, 500))\n", " lo, hi = (np.atleast_1d(b[\"lo\"]), np.atleast_1d(b[\"hi\"])) if b[\"n_boot\"] else (None, None)\n", " rep[\"derived\"] = {k: {\"point\": point[k], \"lo\": float(lo[j]) if lo is not None else None, \"hi\": float(hi[j]) if hi is not None else None} for j, k in enumerate(keys)}\n", " dep = (\"m\", 0, 0)\n", " C.PRED.mkdir(parents=True, exist_ok=True)\n", " tmp = C.PRED / \"t4_reports_deployed.jsonl.tmp\"\n", " with open(tmp, \"w\") as fh:\n", " for i in idx:\n", " fh.write(json.dumps(report(m.record_id.values[i], seg_model[0][i], probs[dep][i], Xest[i])) + \"\\n\")\n", " tmp.replace(C.PRED / \"t4_reports_deployed.jsonl\")\n", " save_json(C.RES / \"s17_t4_chain.json\", rep)\n", " return {\"deployed\": vals[dep], \"official\": vals.get((\"official\",))}" ] }, { "cell_type": "code", "execution_count": 17, "id": "07ea15d4198f", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.825868Z", "iopub.status.busy": "2026-11-28T14:17:32.825505Z", "iopub.status.idle": "2026-11-28T14:17:32.842313Z", "shell.execute_reply": "2026-11-28T14:17:32.840669Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/summary.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/summary.py\n", "import json\n", "\n", "import numpy as np\n", "\n", "from . import config as C\n", "from .utils import load_json, save_json, stage\n", "\n", "\n", "def g(d, *keys, default=None):\n", " for k in keys:\n", " if not isinstance(d, dict) or k not in d:\n", " return default\n", " d = d[k]\n", " return d\n", "\n", "\n", "def f(x, n=3):\n", " if x is None:\n", " return \"–\"\n", " try:\n", " x = float(x)\n", " except (TypeError, ValueError):\n", " return str(x)\n", " return \"–\" if not np.isfinite(x) else f\"{x:.{n}f}\"\n", "\n", "\n", "def ci(d, n=3):\n", " if not isinstance(d, dict):\n", " return f(d, n)\n", " return f\"{f(d.get('point'), n)} [{f(d.get('lo'), n)}, {f(d.get('hi'), n)}]\"\n", "\n", "\n", "def table(header, rows):\n", " out = [\"| \" + \" | \".join(header) + \" |\", \"|\" + \"---|\" * len(header)]\n", " out += [\"| \" + \" | \".join(str(c) for c in r) + \" |\" for r in rows]\n", " return out\n", "\n", "\n", "def figures(res):\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", " out = []\n", " t1 = res[\"s11_t1_analysis\"]\n", " meths = [m for m in (\"autofhr\", \"floor\", \"tcn\") if m in t1]\n", " if meths:\n", " fig, ax = plt.subplots(1, len(meths), figsize=(5 * len(meths), 3.6), squeeze=False)\n", " for a, m in zip(ax[0], meths):\n", " for s, u in t1[m][\"uncertainty\"].items():\n", " be = u[\"big_error\"]\n", " a.plot([1.0] + list(C.COVERAGES), [be[\"risk_full\"]] + [be[f\"risk@{c}\"] for c in C.COVERAGES], marker=\"o\", label=s)\n", " a.set_title(f\"{m}: rate of |e|>10 bpm vs coverage\")\n", " a.set_xlabel(\"coverage\")\n", " a.invert_xaxis()\n", " a.legend(fontsize=7)\n", " fig.tight_layout()\n", " p = C.FIG / \"t1_risk_coverage.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " der = g(res, \"s17_t4_chain\", \"derived\", default={})\n", " if der:\n", " mets = [\"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\"]\n", " fig, axs = plt.subplots(1, 2, figsize=(12, 3.8))\n", " w = 0.35\n", " for j, pl in enumerate((\"R\", \"E\")):\n", " d = [der.get(f\"shapley_{m}_{pl}\", {}) for m in mets]\n", " pts = np.array([x.get(\"point\", np.nan) for x in d], float)\n", " lo = np.array([x.get(\"lo\") if x.get(\"lo\") is not None else np.nan for x in d], float)\n", " hi = np.array([x.get(\"hi\") if x.get(\"hi\") is not None else np.nan for x in d], float)\n", " axs[0].bar(np.arange(len(mets)) + (j - 0.5) * w, pts, w, yerr=np.nan_to_num(np.vstack([pts - lo, hi - pts])), capsize=3, label={\"R\": \"reconstruction (R)\", \"E\": \"segmentation (E)\"}[pl])\n", " axs[0].set_xticks(range(len(mets)))\n", " axs[0].set_xticklabels(mets)\n", " axs[0].axhline(0, color=\"k\", lw=0.6)\n", " axs[0].set_title(\"Exact 2-player Shapley, matched classifier (95% CI)\")\n", " axs[0].legend(fontsize=8)\n", " cfgs = [\"R1E0\", \"R0E1\", \"R1E1\"]\n", " for j, c in enumerate(cfgs):\n", " d = [der.get(f\"mismatch_cost_{m}_{c}\", {}) for m in mets]\n", " pts = np.array([x.get(\"point\", np.nan) for x in d], float)\n", " lo = np.array([x.get(\"lo\") if x.get(\"lo\") is not None else np.nan for x in d], float)\n", " hi = np.array([x.get(\"hi\") if x.get(\"hi\") is not None else np.nan for x in d], float)\n", " axs[1].bar(np.arange(len(mets)) + (j - 1) * 0.27, pts, 0.27, yerr=np.nan_to_num(np.vstack([pts - lo, hi - pts])), capsize=3, label=c)\n", " axs[1].set_xticks(range(len(mets)))\n", " axs[1].set_xticklabels(mets)\n", " axs[1].axhline(0, color=\"k\", lw=0.6)\n", " axs[1].set_title(\"Cost of a mismatched classifier (matched - mismatched)\")\n", " axs[1].legend(fontsize=8)\n", " fig.tight_layout()\n", " p = C.FIG / \"t4_attribution.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " cs = g(res, \"s14_t2_eval\", \"convention_shift\", \"pooled_dec_dice\", default={})\n", " if cs:\n", " labels = [\"t2\", \"t2_matched_to_t4_burden\", \"t4_t2model\", \"t4_t4post\", \"t4_finetuned\"]\n", " vals = [cs.get(k, np.nan) for k in labels]\n", " fig, ax = plt.subplots(figsize=(8, 3.4))\n", " ax.bar(range(len(vals)), vals, color=[\"#888\", \"#bbb\", \"#d62728\", \"#ff9896\", \"#2ca02c\"])\n", " ax.set_xticks(range(len(vals)))\n", " ax.set_xticklabels([\"T2\", \"T2 matched\\nto T4 burden\", \"T4\\nT2 model\", \"T4\\nT4 post-proc.\", \"T4\\nfine-tuned\"], fontsize=8)\n", " ax.set_ylabel(\"pooled deceleration Dice\")\n", " ax.set_title(\"Deceleration Dice: prevalence vs convention\")\n", " fig.tight_layout()\n", " p = C.FIG / \"t2_convention_shift.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " return out\n", "\n", "\n", "def section_run():\n", " L = [\"\", \"## Run\", \"\"]\n", " rows = []\n", " tot = 0.0\n", " for p in sorted(C.STATE.glob(\"*.done.json\")):\n", " d = load_json(p)\n", " s = g(d, \"info\", \"seconds\")\n", " tot += float(s or 0)\n", " rows.append([p.name.replace(\".done.json\", \"\"), d.get(\"time\"), f(s, 0)])\n", " L += table([\"stage\", \"finished\", \"seconds\"], rows)\n", " L += [\"\", f\"Sum of stage times: {tot / 3600:.2f} h (GPU jobs run in parallel, wall time is lower). Holdout locked: {'no (UNLOCKED)' if C.UNLOCK_HOLDOUT else 'yes'}.\"]\n", " return L\n", "\n", "\n", "def section_s2(res, gate2):\n", " a = res[\"s03_audit\"]\n", " L = [\"\", \"## Gate S2 · data and evaluation\", \"\"] + [f\"- {k}: **{v}**\" for k, v in gate2.items()]\n", " fp = g(a, \"fingerprints\", str(C.FP_K_MAIN), default={})\n", " L += [\"\", f\"- Prevalence: T4 {f(a.get('t4_prevalence'))}, T3 {f(a.get('t3_prevalence'))}\", f\"- T3 pair rule: {g(a, 't3_pair_rule')}\", f\"- Fingerprint groups (k={C.FP_K_MAIN}): {fp}\"]\n", " nm = g(a, \"t4_missing_near_events\", default={})\n", " if nm:\n", " L += [f\"- T4 missing rate within 30 s of a deceleration {f(nm.get('dec_missing_near'), 4)} vs elsewhere {f(nm.get('dec_missing_far'), 4)}; ratio {ci(nm.get('dec_ratio'), 2)} (association, not causation)\", f\"- Same for accelerations: ratio {ci(nm.get('acc_ratio'), 2)}\"]\n", " for t in (\"t4\", \"t2\", \"t3\"):\n", " m = g(a, \"missing\", t, default={})\n", " if m:\n", " L.append(f\"- {t} missingness: mean {f(m.get('missing_rate_mean'), 4)}, records with any gap {f(m.get('frac_any_missing'))}, gap median {f(m.get('gap_median_s'), 2)} s, gaps >= 30 s {f(m.get('gap_frac_ge30s'))} of gaps / {f(m.get('missing_time_share_ge30s'))} of missing time\")\n", " eq = res[\"s06_autofhr_equivalence\"]\n", " L.append(f\"- AutoFHR GPU port: mean window agreement {f(eq.get('mean_agreement'), 4)}, min {f(eq.get('min_agreement'), 4)}, max scalogram diff {f(eq.get('max_scalogram_diff'), 8)}\")\n", " return L\n", "\n", "\n", "def section_t1(res):\n", " t1 = res[\"s11_t1_analysis\"]\n", " L = [\"\", \"## T1 · Doppler to FHR (out-of-fold unless stated)\", \"\"]\n", " rows = []\n", " for m in (\"autofhr\", \"floor\", \"tcn\"):\n", " if m in t1:\n", " o = t1[m][\"official\"]\n", " rows.append([m, t1[\"independence\"][m], f(o[\"rmse_pooled\"], 2), f(o[\"mae_pooled\"], 2), f(o[\"rmse_record_mean\"], 2), ci(t1[m][\"frac_points_big\"]), ci(t1[m][\"share_sq_err_big\"]), f(t1[m].get(\"crps_record_mean\"), 2), f(t1[m].get(\"frac_doubling\"), 4), f(t1[m].get(\"frac_halving\"), 4)])\n", " L += table([\"method\", \"independence\", \"RMSE\", \"MAE\", \"RMSE per record\", \"points with abs err > 10\", \"share of sq. error\", \"CRPS\", \"doubling\", \"halving\"], rows)\n", " L += [\"\", \"### Uncertainty scores (selective prediction on |e| > 10 bpm)\", \"\"]\n", " rows = []\n", " for m in (\"autofhr\", \"floor\", \"tcn\"):\n", " for s, u in g(t1, m, \"uncertainty\", default={}).items():\n", " be = u[\"big_error\"]\n", " c = dict(zip(u[\"big_error_ci\"][\"keys\"], zip(u[\"big_error_ci\"][\"lo\"], u[\"big_error_ci\"][\"hi\"])))\n", " rel = lambda k: f\"{f(be[f'risk@{k}'] / max(be['risk_full'], 1e-12), 3)} [{f(c[f'rel@{k}'][0])}, {f(c[f'rel@{k}'][1])}]\"\n", " rows.append([m, s, f(be[\"risk_full\"], 4), f(be[\"aurc\"], 4), f(be[\"aurc_oracle\"], 4), rel(0.9), rel(0.8), rel(0.7), f(u.get(\"spearman_abs_err\"))])\n", " L += table([\"method\", \"score\", \"rate at 100%\", \"AURC\", \"oracle AURC\", \"relative rate at 90%\", \"at 80%\", \"at 70%\", \"Spearman vs abs err\"], rows)\n", " prim = g(t1, \"gate_S3\", \"primary_method\")\n", " st = g(t1, prim, \"strata\", default={})\n", " if st:\n", " L += [\"\", f\"### Error by stratum ({prim})\", \"\"]\n", " rows = [[s, k, v[\"n\"], f(v[\"rmse\"], 2), f(v[\"frac_big\"])] for s, d in st.items() for k, v in d.items()]\n", " L += table([\"stratum\", \"level\", \"points\", \"RMSE\", \"abs err > 10\"], rows)\n", " gate = g(t1, \"gate_S3\", default={})\n", " L += [\"\", \"## Gate S3\", \"\"] + [f\"- {k}: {ci(v) if isinstance(v, dict) else v}\" for k, v in gate.items()]\n", " s8 = g(t1, \"S8_reference\", default={})\n", " if s8:\n", " L += [\"\", \"### Pre-registered reference for gate S8\", \"\"] + [f\"- {k}: {ci(v, 4) if isinstance(v, dict) else v}\" for k, v in s8.items()]\n", " return L\n", "\n", "\n", "def seg_row(nm, r):\n", " if not r:\n", " return None\n", " return [nm, f(g(r, \"dice\", \"pooled_0\")), ci(r.get(\"ci_pooled_dice_acc\")), ci(r.get(\"ci_pooled_dice_dec\")), ci(r.get(\"ci_pooled_dice_macro\")), ci(r.get(\"ci_record_dice_dec\")), ci(r.get(\"ci_record_dice_macro\")), f(g(r, \"evidence\", \"acc_f1\")), ci(r.get(\"ci_evidence_dec_f1\"))]\n", "\n", "\n", "def section_t2(res):\n", " ev = res[\"s14_t2_eval\"]\n", " ru = res[\"s12_t2_rules\"]\n", " L = [\"\", \"## T2 · segmentation\", \"\", \"Pooled Dice sums intersections over all records; record Dice averages per-record Dice over records where the class occurs. The official aggregation is not published, so both are reported.\", \"\"]\n", " rows = []\n", " for nm, key in ((\"U-Net T2 → T2\", \"unet_t2_on_t2\"), (\"U-Net T2 → T4 (T2 post-processing)\", \"unet_t2_on_t4_t2post\"), (\"U-Net T2 → T4 (T4 post-processing)\", \"unet_t2_on_t4_t4post\"), (\"U-Net fine-tuned on T4 → T4\", \"unet_ft4_on_t4\"), (\"Official → T2 (independence unknown)\", \"official_on_t2_independence_unknown\"), (\"Official → T4 (independence unknown)\", \"official_on_t4_independence_unknown\")):\n", " r = seg_row(nm, ev.get(key))\n", " if r:\n", " rows.append(r)\n", " for nm, key in ((\"Rules T2-tuned → T2\", \"t2_rules_t2tuned_on_t2\"), (\"Rules T2-tuned → T4\", \"t2_rules_t2tuned_on_t4\"), (\"Rules T4-tuned → T4\", \"t2_rules_t4tuned_on_t4\")):\n", " r = ru.get(key)\n", " if r:\n", " rows.append([nm, f(g(r, \"dice\", \"pooled_0\")), f(g(r, \"dice\", \"pooled_1\")), ci(r.get(\"ci_dice_dec\")), ci(r.get(\"ci_dice_macro\")), f(g(r, \"dice\", \"record_-1\")), f(g(r, \"dice\", \"record_macro\")), f(g(r, \"evidence\", \"acc_f1\")), f(g(r, \"evidence\", \"dec_f1\"))])\n", " L += table([\"model\", \"baseline Dice\", \"acc Dice (pooled)\", \"dec Dice (pooled)\", \"macro (pooled)\", \"dec Dice (record)\", \"macro (record)\", \"acc event F1\", \"dec event F1\"], rows)\n", " cs = ev.get(\"convention_shift\", {})\n", " if cs:\n", " L += [\"\", \"### Deceleration shift between T2 and T4\", \"\", f\"- Prevalence: {ev.get('prevalence')}\", f\"- Matched-burden T2 Dice: {ci(g(ev, 'unet_t2_on_t2_matched_to_t4_burden', 'ci'))}\"]\n", " L += [f\"- {k}: {f(v) if not isinstance(v, dict) else {kk: round(vv, 3) for kk, vv in v.items() if vv is not None}}\" for k, v in cs.items()]\n", " L.append(f\"- T4 post-processing identical to T2 post-processing: {g(ev, 'unet_t2_on_t4_t4post', 'identical_to_t2post')}\")\n", " return L\n", "\n", "\n", "def section_risk(res):\n", " t3 = res[\"s16_t3_models\"]\n", " L = [\"\", \"## T3 / T4 risk · missingness controls (grouped CV)\", \"\"]\n", " rows = []\n", " for task in (\"t3\", \"t4\"):\n", " for nm, r in g(t3, task, \"controls\", default={}).items():\n", " a = r.get(\"after_threshold_shift\", {})\n", " rows.append([task, nm, ci(dict(point=r[\"auroc\"], lo=g(r, \"ci_auroc\", \"lo\"), hi=g(r, \"ci_auroc\", \"hi\"))), f(r[\"f1\"]), f(r[\"nmcc\"]), f(a.get(\"f1\")), f(a.get(\"nmcc\")), f(r[\"brier\"]), f(r[\"ece\"]), r.get(\"degenerate_folds\")])\n", " L += table([\"task\", \"features\", \"AUROC [95% CI]\", \"F1@0.5\", \"nMCC@0.5\", \"F1 after shift\", \"nMCC after shift\", \"Brier\", \"ECE\", \"degenerate folds\"], rows)\n", " L += [\"\"]\n", " for task in (\"t3\", \"t4\"):\n", " for k in (\"diff_c_minus_b\", \"diff_b_minus_a\"):\n", " if g(t3, task, k):\n", " L.append(f\"- {task} paired AUROC difference {k}: {ci(g(t3, task, k))}\")\n", " rt = g(t3, task, \"removal_test_auroc_missing_outside_decel\")\n", " if rt is not None:\n", " L.append(f\"- {task} AUROC of missingness located > 30 s away from decelerations: {f(rt)}\")\n", " for k, v in (g(t3, task, default={}) or {}).items():\n", " if k.startswith(\"official\") and isinstance(v, dict):\n", " L.append(f\"- {task} {k}: AUROC {f(v.get('auroc'))}, F1 {f(v.get('f1'))}, nMCC {f(v.get('nmcc'))}\")\n", " opt = g(t3, \"t3\", \"random_vs_grouped_cv\", \"optimism_auroc\")\n", " if opt:\n", " L.append(f\"- T3 optimism of random over grouped CV: {ci(opt)}\")\n", " return L\n", "\n", "\n", "def section_t4(res):\n", " t4 = res[\"s17_t4_chain\"]\n", " if not t4:\n", " return []\n", " L = [\"\", \"## T4 chain\", \"\", f\"Records: {t4.get('n_records')} · estimated FHR: {t4.get('estimated_fhr_source')} · segmentation: {t4.get('segmentation_model')}\", \"\"]\n", " lab = {\"m_0_0\": \"deployed (R0E0)\", \"m_0_1\": \"oracle segmentation (R0E1)\", \"m_1_0\": \"oracle FHR (R1E0)\", \"m_1_1\": \"oracle FHR + segmentation (R1E1)\", \"x_0_1\": \"R0E1, mismatched classifier\", \"x_1_0\": \"R1E0, mismatched classifier\", \"x_1_1\": \"R1E1, mismatched classifier\", \"official\": \"official baseline chain\"}\n", " mets = [\"flow_dice\", \"flow_dice_record\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\"]\n", " rows = [[lab.get(k, k)] + [f(v.get(m)) for m in mets] for k, v in t4.get(\"configs\", {}).items()]\n", " L += table([\"configuration\"] + mets, rows)\n", " der = t4.get(\"derived\", {})\n", " L += [\"\", \"### Attribution (exact 2-player Shapley, matched classifier, 95% CI)\", \"\"]\n", " rows = [[m] + [ci(der.get(f\"shapley_{m}_{k}\")) for k in (\"R\", \"E\", \"interaction\", \"total_gain\")] for m in (\"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\")]\n", " L += table([\"metric\", \"R (reconstruction)\", \"E (segmentation)\", \"interaction\", \"total gain\"], rows)\n", " L += [\"\", \"Segmentation metrics: E is not attributable (oracle segmentation scores 1.0 by construction). Effect of the reference FHR at E=0:\", \"\"]\n", " L += [f\"- {m}: {ci(der.get(f'R_effect_{m}'))}\" for m in (\"flow_dice\", \"evidence_f1\")]\n", " L += [\"\", \"### Cost of a mismatched classifier (matched − mismatched)\", \"\"]\n", " rows = [[m] + [ci(der.get(f\"mismatch_cost_{m}_{c}\")) for c in (\"R1E0\", \"R0E1\", \"R1E1\")] for m in (\"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\")]\n", " L += table([\"metric\", \"R1E0\", \"R0E1\", \"R1E1\"], rows)\n", " off = [m for m in (\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\") if f\"ours_minus_official_{m}\" in der]\n", " if off:\n", " L += [\"\", \"### Deployed chain minus official baseline chain (paired)\", \"\"] + [f\"- {m}: {ci(der[f'ours_minus_official_{m}'])}\" for m in off]\n", " if t4.get(\"official_error\"):\n", " L.append(f\"- official chain error: {t4['official_error']}\")\n", " L += [\"\", f\"Notes: {json.dumps(t4.get('notes', {}), indent=1)}\", f\"Degenerate folds: {t4.get('degenerate_folds')}\"]\n", " return L\n", "\n", "\n", "def section_training():\n", " L = [\"\", \"## Training curves (best validation, epochs run)\", \"\"]\n", " rows = []\n", " for pat, key in ((\"s10_t1_tcn_f\", \"best_val_rmse\"), (\"s13_t2_unet_f\", \"best_val_dice_macro\"), (\"s13b_t2_ft4_f\", \"best_val_dice_macro\")):\n", " for p in sorted(C.STATE.glob(f\"{pat}*.done.json\")):\n", " info = load_json(p)[\"info\"]\n", " val = info.get(key, info.get(\"best_val_dice\"))\n", " rows.append([p.name.replace(\".done.json\", \"\"), key, f(val), info.get(\"epochs\"), f(info.get(\"seconds\"), 0)])\n", " return L + table([\"job\", \"metric\", \"best\", \"epochs\", \"seconds\"], rows)\n", "\n", "\n", "@stage(\"s18_summary\", params={\"v\": 2})\n", "def run(log):\n", " names = [\"s02_consolidate\", \"s03_audit\", \"s04_folds\", \"s06_autofhr_equivalence\", \"s11_t1_analysis\", \"s12_t2_rules\", \"s14_t2_eval\", \"s16_t3_models\", \"s17_t4_chain\"]\n", " res = {n: load_json(C.RES / f\"{n}.json\", {}) for n in names}\n", " audit, folds = res[\"s03_audit\"], res[\"s04_folds\"]\n", " split_ok = all(v.get(\"groups_split_across_folds\", 1) == 0 for v in folds.values() if isinstance(v, dict) and \"n\" in v)\n", " counts_ok = C.SMOKE or all(g(audit, \"count_check\", default={}).values())\n", " gate2 = {\n", " \"counts_match_expected\": bool(counts_ok),\n", " \"wav_1khz_20min\": bool(g(audit, \"wav\", \"all_1khz_20min\", default=False)),\n", " \"t3_pair_rule_verified\": bool((g(audit, \"t3_pair_rule\", \"pairs_with_600s_overlap\", default=0) or 0) >= 0.99),\n", " \"no_group_split_across_folds\": bool(split_ok),\n", " \"metrics_selftest_passed\": bool((C.STATE / \"s05_metrics_selftest.done.json\").exists()),\n", " \"autofhr_port_equivalent\": bool(g(res[\"s06_autofhr_equivalence\"], \"equivalent\", default=False)),\n", " }\n", " gate2[\"passed\"] = all(gate2.values())\n", " gate3 = g(res[\"s11_t1_analysis\"], \"gate_S3\", default={})\n", " lines = [f\"# CTG weeks 1-3 summary ({'SMOKE' if C.SMOKE else 'FULL'} run)\", \"\"]\n", " for sec in (section_s2(res, gate2), section_t1(res), section_t2(res), section_risk(res), section_t4(res), section_training(), section_run()):\n", " lines += sec\n", " figs = figures(res)\n", " lines += [\"\", \"## Figures\", \"\"] + [f\"- {p}\" for p in figs]\n", " (C.OUT / \"SUMMARY.md\").write_text(\"\\n\".join(lines))\n", " save_json(C.RES / \"s18_gates.json\", {\"S2\": gate2, \"S3\": gate3, \"S8_reference\": g(res[\"s11_t1_analysis\"], \"S8_reference\")})\n", " return {\"S2\": gate2[\"passed\"], \"S3\": gate3.get(\"passed\")}" ] }, { "cell_type": "code", "execution_count": 18, "id": "a4260f4bc1b9", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.847076Z", "iopub.status.busy": "2026-11-28T14:17:32.846629Z", "iopub.status.idle": "2026-11-28T14:17:32.873987Z", "shell.execute_reply": "2026-11-28T14:17:32.872376Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/sel.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/sel.py\n", "import json\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from scipy.ndimage import binary_closing, binary_opening, gaussian_filter1d, maximum_filter1d, uniform_filter1d\n", "from scipy.special import ndtr\n", "from sklearn.ensemble import HistGradientBoostingClassifier\n", "\n", "from . import config as C\n", "from .io import events, fill_linear, valid\n", "from .metrics import binary_scores, crps_discrete, dice_counts, event_counts, fhr_abs_errors, risk_coverage, spearman, t1_scores\n", "from .t1 import gather_tcn, meta, ref_fhr, sfx, strata\n", "from .utils import bootstrap, device, finalize_memmap, free_mem, load_df, load_json, mm, open_memmap_new, save_df, save_json, save_npy, stage\n", "\n", "ENS_COLS = [\"median\", \"mean\", \"p_far\", \"entropy\", \"q10\", \"q90\", \"q25\", \"q75\", \"member_sd\", \"mutual_info\", \"aleatoric\"]\n", "E = {c: i for i, c in enumerate(ENS_COLS)}\n", "GRID = C.BPM.astype(np.float64)\n", "\n", "\n", "def seeds_available():\n", " out = []\n", " for s in range(C.T1_SEEDS):\n", " if all((C.CACHE / f\"t1_tcn_probs_f{f}{sfx(s)}.npy\").exists() for f in range(C.N_FOLDS)):\n", " out.append(s)\n", " return out\n", "\n", "\n", "def quant(cdf, q):\n", " return GRID[np.minimum((cdf < q).sum(-1), C.NB - 1)]\n", "\n", "\n", "def summarize_np(P):\n", " S = P.shape[0]\n", " mix = P.mean(0)\n", " mix = mix / mix.sum(-1, keepdims=True)\n", " cdf = np.cumsum(mix, -1)\n", " med = quant(cdf, 0.5)\n", " mean = (mix * GRID).sum(-1)\n", " far = np.abs(GRID[None, :] - med[:, None]) > C.BIG_ERR\n", " pfar = (mix * far).sum(-1)\n", " H = lambda p: -(p * np.log(np.clip(p, 1e-12, None))).sum(-1)\n", " ent = H(mix)\n", " ale = np.mean([H(P[s]) for s in range(S)], 0)\n", " mmed = np.stack([quant(np.cumsum(P[s], -1), 0.5) for s in range(S)])\n", " msd = mmed.std(0) if S > 1 else np.zeros_like(med)\n", " return np.stack([med, mean, pfar, ent, quant(cdf, 0.1), quant(cdf, 0.9), quant(cdf, 0.25), quant(cdf, 0.75), msd, ent - ale, ale], -1).astype(np.float32), mix\n", "\n", "\n", "def fold_probs(f, seeds):\n", " return [np.load(C.CACHE / f\"t1_tcn_probs_f{f}{sfx(s)}.npy\", mmap_mode=\"r\") for s in seeds]\n", "\n", "\n", "def ens():\n", " return np.asarray(mm(C.CACHE / \"t1_ens.npy\"), np.float32)\n", "\n", "\n", "def est_filled(arr=None):\n", " a = ens() if arr is None else arr\n", " return np.stack([fill_linear(x) for x in a[..., E[\"median\"]]])\n", "\n", "\n", "@stage(\"s19_t1_ensemble\", params={\"v\": 1}, outputs=[C.CACHE / \"t1_ens.npy\"])\n", "def ensemble(log):\n", " m = meta()\n", " seeds = seeds_available()\n", " if seeds != list(range(C.T1_SEEDS)):\n", " raise RuntimeError(f\"incomplete TCN seeds: found {seeds}, expected {list(range(C.T1_SEEDS))}; rerun the s10 jobs (inference resumes from saved weights)\")\n", " log.info(f\"seeds used: {seeds}\")\n", " n = len(m)\n", " out, tp, pp = open_memmap_new(C.CACHE / \"t1_ens.npy\", (n, C.N, len(ENS_COLS)), np.float32, np.nan)\n", " ref = ref_fhr()\n", " crps_e = np.full(n, np.nan)\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(m.fold.values == f)\n", " Ps = fold_probs(f, seeds)\n", " for a in range(0, te.size, 16):\n", " P = np.stack([np.asarray(p[a:a + 16], np.float32) for p in Ps])\n", " for k in range(P.shape[1]):\n", " summ, mix = summarize_np(P[:, k])\n", " i = te[a + k]\n", " out[i] = summ\n", " v = valid(ref[i])\n", " crps_e[i] = crps_discrete(mix[v].astype(np.float64), ref[i][v]).mean() if v.any() else np.nan\n", " free_mem()\n", " finalize_memmap(out, tp, pp)\n", " save_npy(C.CACHE / \"t1_ens_crps.npy\", crps_e)\n", " A = ens()\n", " ok = np.flatnonzero(m.fold.values >= 0)\n", " r0, c0 = gather_tcn(0)\n", " rep = {\"seeds\": seeds, \"n_records\": int(ok.size)}\n", " errs = {}\n", " for nm, P in ((\"seed0\", r0[..., 0]), (\"ensemble\", A[..., E[\"median\"]])):\n", " pr = [fill_linear(P[i]) for i in ok]\n", " rep[nm] = t1_scores(pr, [ref[i] for i in ok])\n", " errs[nm] = [fhr_abs_errors(p, ref[i])[0] for p, i in zip(pr, ok)]\n", " rep[\"seed0\"][\"crps_record_mean\"] = float(np.nanmean(c0[ok]))\n", " rep[\"ensemble\"][\"crps_record_mean\"] = float(np.nanmean(crps_e[ok]))\n", " se0 = np.array([np.sum(e ** 2) for e in errs[\"seed0\"]])\n", " se1 = np.array([np.sum(e ** 2) for e in errs[\"ensemble\"]])\n", " b0 = np.array([np.sum(e > C.BIG_ERR) for e in errs[\"seed0\"]])\n", " b1 = np.array([np.sum(e > C.BIG_ERR) for e in errs[\"ensemble\"]])\n", " nn_ = np.array([e.size for e in errs[\"seed0\"]])\n", " g = m.group.values[ok]\n", " rep[\"diff_rmse_ens_minus_seed0\"] = bootstrap(lambda i: np.sqrt(se1[i].sum() / nn_[i].sum()) - np.sqrt(se0[i].sum() / nn_[i].sum()), g)\n", " rep[\"diff_big_rate_ens_minus_seed0\"] = bootstrap(lambda i: (b1[i].sum() - b0[i].sum()) / nn_[i].sum(), g)\n", " rep[\"diff_crps_ens_minus_seed0\"] = bootstrap(lambda i: np.nanmean(crps_e[ok][i]) - np.nanmean(c0[ok][i]), g)\n", " st = strata(m, ref)\n", " cov = {}\n", " for sname, s in list(st.items()) + [(\"all\", np.zeros(ref.shape, int))]:\n", " cov[sname] = {}\n", " for lvl in np.unique(s[ok]):\n", " sel_pts = [(s[i] == lvl) & valid(ref[i]) for i in ok]\n", " npts = int(sum(x.sum() for x in sel_pts))\n", " if npts < 1000:\n", " continue\n", " c80 = sum(((ref[i] >= A[i, :, E[\"q10\"]]) & (ref[i] <= A[i, :, E[\"q90\"]]))[x].sum() for i, x in zip(ok, sel_pts)) / npts\n", " c50 = sum(((ref[i] >= A[i, :, E[\"q25\"]]) & (ref[i] <= A[i, :, E[\"q75\"]]))[x].sum() for i, x in zip(ok, sel_pts)) / npts\n", " cov[sname][str(int(lvl))] = {\"points\": npts, \"coverage80\": float(c80), \"coverage50\": float(c50)}\n", " rep[\"interval_coverage\"] = cov\n", " big = [(k, l, v) for k, d in cov.items() for l, v in d.items() if v[\"points\"] >= 0.01 * sum(x[\"points\"] for x in cov[\"all\"].values())]\n", " worst = max((max(abs(v[\"coverage80\"] - 0.8), abs(v[\"coverage50\"] - 0.5)), k, l) for k, l, v in big)\n", " rep[\"gate_FM_prerequisite\"] = {\"criterion\": \"marginal 50% and 80% intervals within +-0.02 of nominal in every stratum holding >= 1% of points\", \"worst_deviation\": worst[0], \"worst_stratum\": f\"{worst[1]}={worst[2]}\", \"marginals_calibrated\": bool(worst[0] <= 0.02), \"decision\": \"flow matching not needed for marginal calibration; only for joint trajectories\" if worst[0] <= 0.02 else \"marginal miscalibration found: flow matching or recalibration is a candidate at S6\"}\n", " save_json(C.RES / \"s19_t1_ensemble.json\", rep)\n", " return {\"rmse_seed0\": rep[\"seed0\"][\"rmse_pooled\"], \"rmse_ens\": rep[\"ensemble\"][\"rmse_pooled\"], \"fm\": rep[\"gate_FM_prerequisite\"][\"marginals_calibrated\"]}\n", "\n", "\n", "def episodes(mask):\n", " return events(mask.astype(np.int8), 1)\n", "\n", "\n", "def boundary_jump(r, a, side):\n", " idx = range(a - 1, max(-1, a - 9), -1) if side == \"entry\" else range(a, min(r.size, a + 8))\n", " inside = r[a] if side == \"entry\" else r[a - 1]\n", " for j in idx:\n", " if np.isfinite(r[j]):\n", " return float(abs(r[j] - inside)), j == (a - 1 if side == \"entry\" else a)\n", " return np.nan, False\n", "\n", "\n", "@stage(\"s20_reference_audit\", params={\"v\": 1}, outputs=[C.CACHE / \"t1_ref_suspect.npy\"])\n", "def reference_audit(log):\n", " m = meta()\n", " ref = ref_fhr()\n", " A = ens()\n", " ac = mm(C.CACHE / \"t1_ac.npy\")\n", " ok = np.flatnonzero(m.fold.values >= 0)\n", " suspect = np.zeros(ref.shape, bool)\n", " rows = []\n", " jumps = 0\n", " for i in ok:\n", " r = ref[i]\n", " est = A[i, :, E[\"median\"]]\n", " g = np.asarray(ac[i], np.float32)\n", " d = np.abs(np.diff(r))\n", " st = np.flatnonzero(d >= 25)\n", " for s in st:\n", " seg = r[s + 1:s + 1 + 32]\n", " if np.isfinite(seg).sum() >= 24 and np.nanstd(seg) < 6:\n", " jumps += 1\n", " lo = valid(r) & (r < C.BRADY)\n", " for a, b in episodes(lo):\n", " if b - a < 4:\n", " continue\n", " ej, ec = boundary_jump(r, a, \"entry\")\n", " xj, xc = boundary_jump(r, b, \"exit\") if b < r.size else (np.nan, False)\n", " rb = np.clip(np.rint(r[a:b]) - C.BPM[0], 0, C.NB - 1).astype(int)\n", " eb = np.clip(np.rint(np.nan_to_num(est[a:b], nan=140)) - C.BPM[0], 0, C.NB - 1).astype(int)\n", " t = np.arange(a, b)\n", " sup_ref = float(np.mean(g[t, rb]))\n", " sup_est = float(np.mean(g[t, eb]))\n", " diff = float(np.nanmedian(np.abs(est[a:b] - r[a:b])))\n", " ratio = float(np.nanmedian(est[a:b] / r[a:b]))\n", " abrupt = bool((np.nan_to_num(ej) >= 20) or (np.nan_to_num(xj) >= 20))\n", " gap_bounded = bool(np.isnan(ej) or np.isnan(xj) or not ec or not xc)\n", " halving = bool(1.8 <= ratio <= 2.2)\n", " sus = bool(diff > 15 and sup_est - sup_ref > 0.1 and (abrupt or gap_bounded or halving))\n", " if sus:\n", " suspect[i, a:b] = True\n", " rows.append({\"record_id\": m.record_id.values[i], \"rec\": int(i), \"start_s\": a / 4, \"dur_s\": (b - a) / 4, \"ref_median\": float(np.nanmedian(r[a:b])), \"est_median\": float(np.nanmedian(est[a:b])), \"ratio_est_ref\": ratio, \"entry_jump\": ej, \"exit_jump\": xj, \"abrupt\": abrupt, \"gap_bounded\": gap_bounded, \"ac_support_ref\": sup_ref, \"ac_support_est\": sup_est, \"halving_pattern\": halving, \"suspect\": sus})\n", " save_npy(C.CACHE / \"t1_ref_suspect.npy\", suspect)\n", " ep = pd.DataFrame(rows)\n", " ep.to_csv(C.RES / \"s20_brady_episodes.csv\", index=False)\n", " rep = {\"records\": int(ok.size), \"brady_episodes\": int(len(ep)), \"persistent_jumps_ge25bpm\": int(jumps), \"rule\": \"suspect = median |est-ref| > 15 bpm AND autocorrelogram support(est) - support(ref) > 0.1 AND (abrupt boundary >= 20 bpm OR gap-bounded OR est/ref in [1.8, 2.2]); heuristic, for sensitivity analysis only\"}\n", " if len(ep):\n", " rep[\"episodes_suspect_frac\"] = float(ep.suspect.mean())\n", " rep[\"brady_seconds\"] = float(ep.dur_s.sum())\n", " rep[\"brady_seconds_suspect_frac\"] = float(ep.dur_s[ep.suspect].sum() / ep.dur_s.sum())\n", " rep[\"episodes_abrupt_frac\"] = float(ep.abrupt.mean())\n", " rep[\"episodes_halving_frac\"] = float(ep.halving_pattern.mean())\n", " rep[\"median_ref_in_suspect\"] = float(ep.ref_median[ep.suspect].median()) if ep.suspect.any() else None\n", " rep[\"median_est_in_suspect\"] = float(ep.est_median[ep.suspect].median()) if ep.suspect.any() else None\n", " est = est_filled(A)\n", " sens = {}\n", " for nm, excl in ((\"all_valid_points\", None), (\"excluding_suspect\", suspect)):\n", " E_all, B_all = [], []\n", " for i in ok:\n", " e, v = fhr_abs_errors(est[i], ref[i])\n", " keep = np.ones(e.size, bool) if excl is None else ~excl[i][v]\n", " br = (ref[i][v] < C.BRADY)\n", " E_all.append((e[keep], br[keep]))\n", " e = np.concatenate([x[0] for x in E_all])\n", " br = np.concatenate([x[1] for x in E_all])\n", " sens[nm] = {\"points\": int(e.size), \"rmse\": float(np.sqrt(np.mean(e ** 2))), \"big_rate\": float(np.mean(e > C.BIG_ERR)), \"brady_points\": int(br.sum()), \"brady_rmse\": float(np.sqrt(np.mean(e[br] ** 2))) if br.any() else None, \"brady_big_rate\": float(np.mean(e[br] > C.BIG_ERR)) if br.any() else None}\n", " rep[\"sensitivity\"] = sens\n", " save_json(C.RES / \"s20_reference_audit.json\", rep)\n", " try:\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", " pick = pd.concat([ep[ep.suspect].nlargest(3, \"dur_s\"), ep[~ep.suspect].nlargest(3, \"dur_s\")]) if len(ep) else ep\n", " if len(pick):\n", " fig, axs = plt.subplots(len(pick), 1, figsize=(11, 2.3 * len(pick)), squeeze=False)\n", " for ax, (_, r) in zip(axs[:, 0], pick.iterrows()):\n", " i = int(r.rec)\n", " a = max(0, int(r.start_s * 4) - 480)\n", " b = min(C.N, int((r.start_s + r.dur_s) * 4) + 480)\n", " t = np.arange(a, b) / 4\n", " ax.fill_between(t, A[i, a:b, E[\"q10\"]], A[i, a:b, E[\"q90\"]], color=\"tab:blue\", alpha=0.2, lw=0)\n", " ax.plot(t, A[i, a:b, E[\"median\"]], color=\"tab:blue\", lw=1, label=\"estimate (ensemble median, 10-90%)\")\n", " ax.plot(t, ref[i, a:b], color=\"k\", lw=1, label=\"reference\")\n", " ax.axhline(C.BRADY, color=\"tab:red\", lw=0.6, ls=\"--\")\n", " ax.set_title(f\"{r.record_id} t={r.start_s:.0f}s suspect={r.suspect} abrupt={r.abrupt} support ref/est={r.ac_support_ref:.2f}/{r.ac_support_est:.2f}\", fontsize=8)\n", " ax.set_ylabel(\"bpm\")\n", " axs[0, 0].legend(fontsize=7, loc=\"upper right\")\n", " fig.tight_layout()\n", " fig.savefig(C.FIG / \"w35_brady_episodes.png\", dpi=110)\n", " plt.close(fig)\n", " except Exception as e:\n", " log.warning(f\"figure failed: {e!r}\")\n", " return {k: rep.get(k) for k in (\"brady_episodes\", \"episodes_suspect_frac\", \"brady_seconds_suspect_frac\")}\n", "\n", "\n", "FEAT_NAMES = [\"med\", \"p_far\", \"entropy\", \"width80\", \"width50\", \"member_sd\", \"mutual_info\", \"aleatoric\", \"q_logrms\", \"q_peak\", \"q_prom\", \"q_sep\", \"q_clip\", \"q_acbpm\", \"af_diff\", \"af_missing\", \"af_sd\", \"af_cnt\", \"floor_diff\", \"floor_pfar\", \"pfar_max5s\", \"pfar_mean30s\", \"med_sd5s\", \"med_absdiff\", \"seg_dec\", \"seg_acc\", \"seg_dec_max30s\", \"brady_pred\", \"tachy_pred\", \"acbpm_diff\"]\n", "\n", "\n", "def point_features(i, core, A, Q, AF, FL, SG):\n", " med, pf, en, q10, q90 = core\n", " q = np.asarray(Q[i], np.float32)\n", " af = np.asarray(AF[i], np.float32)\n", " fl = np.asarray(FL[i], np.float32)\n", " sg = np.asarray(SG[i], np.float32) if SG is not None else np.zeros((3, C.N), np.float32)\n", " medf = fill_linear(med)\n", " afd = af[:, 0] - medf\n", " cols = [medf, pf, en, q90 - q10, A[i, :, E[\"q75\"]] - A[i, :, E[\"q25\"]], A[i, :, E[\"member_sd\"]], A[i, :, E[\"mutual_info\"]], A[i, :, E[\"aleatoric\"]], q[:, 0], q[:, 1], q[:, 2], q[:, 3], q[:, 4], q[:, 5], np.nan_to_num(afd), np.isnan(af[:, 0]).astype(np.float32), np.nan_to_num(af[:, 1], nan=50.0), af[:, 2], fl[:, 1] - medf, fl[:, 3], maximum_filter1d(np.nan_to_num(pf), 41), uniform_filter1d(np.nan_to_num(pf), 241), np.sqrt(np.maximum(uniform_filter1d(medf ** 2, 41) - uniform_filter1d(medf, 41) ** 2, 0)), np.abs(np.diff(medf, prepend=medf[0])), sg[2], sg[1], maximum_filter1d(sg[2], 241), (medf < C.BRADY).astype(np.float32), (medf > 160).astype(np.float32), q[:, 5] - medf]\n", " return np.nan_to_num(np.stack(cols, 1).astype(np.float32))\n", "\n", "\n", "def seg_probs_on_estimate(log):\n", " p = C.CACHE / \"t4_segp_est.npy\"\n", " pm = C.CACHE / \"t4_segp_est_ok.npy\"\n", " if p.exists() and pm.exists():\n", " return np.load(p, mmap_mode=\"r\"), np.load(pm)\n", " from .t2 import ft4_oof_probs\n", " P, ok = ft4_oof_probs(est_filled(), device(), log)\n", " save_npy(p, np.nan_to_num(P).astype(np.float16))\n", " save_npy(pm, ok)\n", " return np.load(p, mmap_mode=\"r\"), ok\n", "\n", "\n", "def hgb():\n", " return HistGradientBoostingClassifier(max_iter=300, learning_rate=0.05, max_leaf_nodes=31, min_samples_leaf=200, l2_regularization=0.1, early_stopping=False, random_state=C.SEED)\n", "\n", "\n", "def crc_threshold(score, y, alpha):\n", " o = np.argsort(score, kind=\"stable\")\n", " s, yy = score[o], y[o]\n", " k = np.arange(1, s.size + 1)\n", " bound = (np.cumsum(yy) + 1) / (k + 1)\n", " cut = np.r_[s[1:] > s[:-1], True]\n", " okk = np.flatnonzero((bound <= alpha) & cut)\n", " if okk.size == 0:\n", " return -np.inf\n", " j = okk.max()\n", " return float(s[j])\n", "\n", "\n", "def observable_strata(F):\n", " c = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " s = np.zeros(F.shape[0], np.int8)\n", " s[F[:, c[\"q_prom\"]] < LOWQ[0]] = 1\n", " s[F[:, c[\"seg_dec_max30s\"]] > 0.5] = 2\n", " s[F[:, c[\"brady_pred\"]] > 0.5] = 3\n", " return s\n", "\n", "\n", "LOWQ = [0.0]\n", "OBS_NAMES = {0: \"normal\", 1: \"low_quality\", 2: \"decel_predicted\", 3: \"brady_predicted\"}\n", "\n", "\n", "MIN_STRATUM_RECORDS = 3 if C.SMOKE else 30\n", "\n", "\n", "def mondrian_thresholds(sc_c, yc, stc, rc, strata):\n", " out = {}\n", " for s_ in np.unique(strata):\n", " mk = stc == s_\n", " enough = mk.sum() >= 50 and np.unique(rc[mk]).size >= MIN_STRATUM_RECORDS\n", " out[int(s_)] = {a: (crc_threshold(sc_c[mk], yc[mk], a) if enough else -np.inf) for a in (C.ALPHA_ESTIMATE, C.ALPHA_FLAG)}\n", " return out\n", "\n", "\n", "def clean_policy(act):\n", " ab = act == 2\n", " ab = binary_closing(ab, structure=np.ones(C.POLICY_MIN_RUN_S * C.FS_FHR))\n", " keep = binary_opening(ab, structure=np.ones(C.POLICY_MIN_RUN_S * C.FS_FHR))\n", " out = act.copy()\n", " out[(act == 2) & ~keep] = 1\n", " out[keep] = 2\n", " return out\n", "\n", "\n", "@stage(\"s21_t1_risk_policy\", params={\"v\": 2}, outputs=[C.CACHE / \"t1_policy.npy\", C.CACHE / \"t1_risk_g.npy\"])\n", "def risk_policy(log):\n", " m = meta()\n", " ref = ref_fhr()\n", " A = ens()\n", " Q = mm(C.CACHE / \"t1_q.npy\")\n", " AF = mm(C.CACHE / \"t1_af.npy\")\n", " FL = mm(C.CACHE / \"t1_floor.npy\")\n", " SG, sg_ok = seg_probs_on_estimate(log)\n", " r0, _ = gather_tcn(0)\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " rng = np.random.default_rng(C.SEED)\n", " scen = {\"seed0\": lambda i: (r0[i, :, 0], r0[i, :, 2], r0[i, :, 3], r0[i, :, 4], r0[i, :, 5]), \"ensemble\": lambda i: (A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]], A[i, :, E[\"entropy\"]], A[i, :, E[\"q10\"]], A[i, :, E[\"q90\"]])}\n", " pick = {}\n", " for i in ok:\n", " v = np.flatnonzero(valid(ref[i]))\n", " pick[i] = np.sort(rng.choice(v, size=min(C.POINTS_PER_RECORD, v.size), replace=False)) if v.size else v\n", " allq = np.concatenate([np.asarray(Q[i, pick[i], 2], np.float32) for i in ok if pick[i].size])\n", " rep = {\"n_records\": int(ok.size), \"points_per_record\": C.POINTS_PER_RECORD, \"amendments\": {\"alphas\": f\"pre-registered alpha=5% is above the measured base big-error rate (3.0%), so it would accept every point; amended before fitting any learned score to alpha_estimate={C.ALPHA_ESTIMATE}, alpha_flag={C.ALPHA_FLAG}\", \"calibration_tolerance\": \"pre-registered +-1 point is vacuous at alpha=0.5%; amended to: upper 95% CI of realized selective risk <= 1.5 x alpha\", \"v2_corrections_before_freeze\": f\"tie-aware conformal cut (scores stored from float16 probabilities can tie, and a threshold falling inside a block of ties accepted more points than calibrated); Mondrian thresholds only for strata with >= {MIN_STRATUM_RECORDS} distinct calibration records (points within a record are not exchangeable), otherwise the stratum never estimates; per-stratum realised risk with record-level CIs. Found on out-of-fold results (predicted-bradycardia stratum: 6.2% realised risk at alpha 0.5%); the holdout was never opened\"}}\n", " G = {}\n", " for sc, core in scen.items():\n", " rows = []\n", " for i in ok:\n", " if pick[i].size == 0:\n", " continue\n", " F = point_features(i, core(i), A, Q, AF, FL, SG)\n", " med = fill_linear(core(i)[0])\n", " e = np.abs(med[pick[i]] - ref[i][pick[i]])\n", " rows.append((F[pick[i]], e, np.full(pick[i].size, i), np.full(pick[i].size, fold[i])))\n", " X = np.concatenate([r[0] for r in rows])\n", " e = np.concatenate([r[1] for r in rows])\n", " rec = np.concatenate([r[2] for r in rows])\n", " fd = np.concatenate([r[3] for r in rows])\n", " y = (e > C.BIG_ERR).astype(np.int8)\n", " g = np.full(y.size, np.nan)\n", " models = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " tr = (fd != f) & (fd != c)\n", " mdl = hgb().fit(X[tr], y[tr])\n", " models[f] = mdl\n", " g[fd == f] = mdl.predict_proba(X[fd == f])[:, 1]\n", " G[sc] = dict(X=X, e=e, y=y, rec=rec, fd=fd, g=g, models=models)\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " scores = {\"p_far\": X[:, cidx[\"p_far\"]], \"entropy\": X[:, cidx[\"entropy\"]], \"width80\": X[:, cidx[\"width80\"]], \"member_sd\": X[:, cidx[\"member_sd\"]], \"mutual_info\": X[:, cidx[\"mutual_info\"]], \"learned_g\": g}\n", " res = {}\n", " grp = m.group.values[rec]\n", " for sn, s in scores.items():\n", " rc = risk_coverage(s, y.astype(float))\n", " res[sn] = {\"aurc\": rc[\"aurc\"], \"aurc_oracle\": rc[\"aurc_oracle\"], \"risk_full\": rc[\"risk_full\"], **{k: rc[k] for k in (\"risk@0.9\", \"risk@0.8\", \"risk@0.7\")}, \"spearman_abs_err\": spearman(s, e)}\n", " ref_s = scores[\"p_far\"]\n", "\n", " def rel(i, a, b):\n", " return risk_coverage(a[i], y[i].astype(float))[\"aurc\"] / max(risk_coverage(b[i], y[i].astype(float))[\"aurc\"], 1e-12) - 1\n", "\n", " for sn in (\"learned_g\", \"mutual_info\", \"member_sd\"):\n", " res[sn][\"rel_aurc_vs_p_far\"] = bootstrap(lambda i, sn=sn: rel(i, scores[sn], ref_s), grp, B=min(C.BOOT, 400))\n", " per = {}\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fd == f)\n", " b = bootstrap(lambda i, sel_=sel_, sn=sn: rel(sel_[i], scores[sn], ref_s), grp[sel_], B=min(C.BOOT, 200))\n", " per[str(f)] = b\n", " res[sn][\"rel_aurc_vs_p_far_per_fold\"] = per\n", " rep[sc] = {\"base_rate\": float(y.mean()), \"points\": int(y.size), \"scores\": res}\n", " s0 = rep[\"seed0\"][\"scores\"][\"learned_g\"]\n", " folds_pass = sum(1 for b in s0[\"rel_aurc_vs_p_far_per_fold\"].values() if b[\"hi\"] is not None and b[\"hi\"] < -0.10)\n", " gate_rank = {\"pooled_rel_aurc\": s0[\"rel_aurc_vs_p_far\"], \"folds_with_upper_ci_below_-10pct\": folds_pass}\n", " se = rep[\"ensemble\"][\"scores\"]\n", " best = min((\"learned_g\", \"mutual_info\", \"member_sd\"), key=lambda k: se[k][\"aurc\"])\n", " s6 = {\"criterion\": \"pre-registered here: the learned residual-risk score g (ensemble estimator) lowers AURC vs the ensemble p_far by >= 10% with upper 95% CI < -10%\", \"best_alternative_score\": best, \"g_rel_aurc_vs_p_far\": se[\"learned_g\"][\"rel_aurc_vs_p_far\"], \"passed\": bool(se[\"learned_g\"][\"rel_aurc_vs_p_far\"][\"hi\"] < -0.10)}\n", " s6[\"policy_score\"] = \"learned_g\" if s6[\"passed\"] else \"p_far\"\n", " s6[\"decision\"] = \"three-action policy uses the learned score g\" if s6[\"passed\"] else \"three-action policy keeps the training-free p_far\"\n", " rep[\"gate_S6\"] = s6\n", " GE = G[\"ensemble\"]\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " LOWQ[0] = float(np.quantile(allq, 0.2))\n", " rep[\"observable_strata\"] = {\"definition\": \"precedence brady_predicted (ensemble median < 110) > decel_predicted (max deceleration probability within +-30 s > 0.5, T4-fine-tuned U-Net on the estimate) > low_quality (autocorrelogram prominence below its 20th percentile, label-free) > normal\", \"low_quality_threshold\": LOWQ[0]}\n", " pol_score = GE[\"g\"] if s6[\"passed\"] else GE[\"X\"][:, cidx[\"p_far\"]]\n", " strat_pts = observable_strata(GE[\"X\"])\n", " cal = {}\n", " realized = {\"marginal\": {}, \"mondrian\": {}}\n", " thr = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " cm = GE[\"fd\"] == c\n", " if s6[\"passed\"]:\n", " sc_c = GE[\"models\"][f].predict_proba(GE[\"X\"][cm])[:, 1]\n", " else:\n", " sc_c = pol_score[cm]\n", " yc = GE[\"y\"][cm]\n", " stc = strat_pts[cm]\n", " thr[f] = {\"marginal\": {a: crc_threshold(sc_c, yc, a) for a in (C.ALPHA_ESTIMATE, C.ALPHA_FLAG)}, \"mondrian\": mondrian_thresholds(sc_c, yc, stc, GE[\"rec\"][cm], strat_pts)}\n", " for kind in (\"marginal\", \"mondrian\"):\n", " for a in (C.ALPHA_ESTIMATE, C.ALPHA_FLAG):\n", " acc = np.zeros(pol_score.size, bool)\n", " for f in range(C.N_FOLDS):\n", " tm = GE[\"fd\"] == f\n", " if kind == \"marginal\":\n", " acc[tm] = pol_score[tm] <= thr[f][\"marginal\"][a]\n", " else:\n", " for s_, d in thr[f][\"mondrian\"].items():\n", " mk = tm & (strat_pts == s_)\n", " acc[mk] = pol_score[mk] <= d[a]\n", " grp = m.group.values[GE[\"rec\"]]\n", " yv = GE[\"y\"].astype(float)\n", " r = {\"alpha\": a, \"coverage\": float(acc.mean()), \"realized_risk\": bootstrap(lambda i: yv[i][acc[i]].mean() if acc[i].any() else np.nan, grp, B=min(C.BOOT, 400)), \"per_observable_stratum\": {}}\n", " for s_ in np.unique(strat_pts):\n", " mk = strat_pts == s_\n", " sel_ = np.flatnonzero(mk)\n", " ci_ = bootstrap(lambda i, sel_=sel_: yv[sel_][i][acc[sel_][i]].mean() if acc[sel_][i].any() else np.nan, grp[sel_], B=min(C.BOOT, 400)) if (mk & acc).any() else None\n", " r[\"per_observable_stratum\"][OBS_NAMES[int(s_)]] = {\"points\": int(mk.sum()), \"records\": int(np.unique(GE[\"rec\"][mk]).size), \"base_rate\": float(yv[mk].mean()), \"coverage\": float(acc[mk].mean()), \"realized_risk\": float(yv[mk & acc].mean()) if (mk & acc).any() else None, \"realized_risk_ci\": ci_, \"calibrated\": None if ci_ is None else bool(ci_[\"hi\"] is not None and ci_[\"hi\"] <= 1.5 * a)}\n", " r[\"calibrated\"] = bool(r[\"realized_risk\"][\"hi\"] <= 1.5 * a)\n", " realized[kind][str(a)] = r\n", " rep[\"selective_risk_control\"] = realized\n", " s8 = rep[\"seed0\"][\"scores\"][\"learned_g\"]\n", " rep[\"gate_S8\"] = {\"pre_registered\": \"learned residual-risk model vs TCN seed-0 p_far on the same out-of-fold points: paired bootstrap upper 95% CI of relative AURC change < -10% on >= 4 of 5 folds (and pooled); selective risk calibrated on the reserved calibration fold\", \"amendments\": rep[\"amendments\"], \"pooled_rel_aurc\": s8[\"rel_aurc_vs_p_far\"], \"folds_passing\": folds_pass, \"ranking_passed\": bool(folds_pass >= 4 and s8[\"rel_aurc_vs_p_far\"][\"hi\"] < -0.10), \"calibration_passed\": bool(all(realized[k][str(C.ALPHA_ESTIMATE)][\"calibrated\"] for k in (\"marginal\",)))}\n", " rep[\"gate_S8\"][\"passed\"] = rep[\"gate_S8\"][\"ranking_passed\"] and rep[\"gate_S8\"][\"calibration_passed\"]\n", " n = len(m)\n", " gfull, tg, pg = open_memmap_new(C.CACHE / \"t1_risk_g.npy\", (n, C.N), np.float32, np.nan)\n", " pol, tp, pp = open_memmap_new(C.CACHE / \"t1_policy.npy\", (n, C.N), np.int8, -1)\n", " polm, tpm, ppm = open_memmap_new(C.CACHE / \"t1_policy_marginal.npy\", (n, C.N), np.int8, -1)\n", " for i in ok:\n", " f = fold[i]\n", " F = point_features(i, scen[\"ensemble\"](i), A, Q, AF, FL, SG)\n", " gi = GE[\"models\"][f].predict_proba(F)[:, 1]\n", " gfull[i] = gi\n", " sc_i = gi if s6[\"passed\"] else F[:, cidx[\"p_far\"]]\n", " so = observable_strata(F)\n", " act = np.full(C.N, 2, np.int8)\n", " actm = np.full(C.N, 2, np.int8)\n", " for s_ in np.unique(so):\n", " mk = so == s_\n", " d = thr[f][\"mondrian\"].get(int(s_), {C.ALPHA_ESTIMATE: -np.inf, C.ALPHA_FLAG: -np.inf})\n", " act[mk & (sc_i <= d[C.ALPHA_FLAG])] = 1\n", " act[mk & (sc_i <= d[C.ALPHA_ESTIMATE])] = 0\n", " actm[sc_i <= thr[f][\"marginal\"][C.ALPHA_FLAG]] = 1\n", " actm[sc_i <= thr[f][\"marginal\"][C.ALPHA_ESTIMATE]] = 0\n", " pol[i] = clean_policy(act)\n", " polm[i] = clean_policy(actm)\n", " finalize_memmap(gfull, tg, pg)\n", " finalize_memmap(pol, tp, pp)\n", " finalize_memmap(polm, tpm, ppm)\n", " rep[\"location\"] = {k: abstention_location(np.asarray(mm(C.CACHE / f), np.int8), m, ref, A) for k, f in ((\"mondrian\", \"t1_policy.npy\"), (\"marginal\", \"t1_policy_marginal.npy\"))}\n", " save_json(C.RES / \"s21_t1_risk_policy.json\", rep)\n", " return {\"S6\": s6[\"passed\"], \"S8\": rep[\"gate_S8\"][\"passed\"], \"abstain_mondrian\": rep[\"location\"][\"mondrian\"][\"action_rates\"][\"abstain\"]}\n", "\n", "\n", "def abstention_location(P, m, ref, A):\n", " ok = np.flatnonzero(m.fold.values >= 0)\n", " est = est_filled(A)\n", " seg = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " st = strata(m, ref)\n", " st[\"brady_ref\"] = np.nan_to_num(ref, nan=200) < C.BRADY\n", " sus = np.load(C.CACHE / \"t1_ref_suspect.npy\") if (C.CACHE / \"t1_ref_suspect.npy\").exists() else np.zeros(ref.shape, bool)\n", " st[\"reference_suspect\"] = sus\n", " out = {\"action_rates\": {}, \"by_true_stratum\": {}, \"big_errors\": {}, \"events\": {}}\n", " acts = np.concatenate([P[i] for i in ok])\n", " for a, nm in ((0, \"estimate\"), (1, \"flag\"), (2, \"abstain\")):\n", " out[\"action_rates\"][nm] = float(np.mean(acts == a))\n", " for sname, s in st.items():\n", " d = {}\n", " cat = np.concatenate([np.asarray(s[i]).astype(int) for i in ok])\n", " for lvl in np.unique(cat):\n", " mk = cat == lvl\n", " d[str(int(lvl))] = {\"points\": int(mk.sum()), \"abstain\": float(np.mean(acts[mk] == 2)), \"flag\": float(np.mean(acts[mk] == 1))}\n", " out[\"by_true_stratum\"][sname] = d\n", " errs, act_v, grp = [], [], []\n", " for i in ok:\n", " e, v = fhr_abs_errors(est[i], ref[i])\n", " errs.append(e)\n", " act_v.append(P[i][v])\n", " grp.append(np.full(e.size, m.group.values[i]))\n", " e = np.concatenate(errs)\n", " av = np.concatenate(act_v)\n", " big = e > C.BIG_ERR\n", " out[\"big_errors\"] = {\"share_in_abstain\": float(np.mean(av[big] == 2)), \"share_in_flag\": float(np.mean(av[big] == 1)), \"share_in_estimate\": float(np.mean(av[big] == 0)), \"risk_estimate_only\": float(np.mean(big[av == 0])) if (av == 0).any() else None, \"risk_estimate_or_flag\": float(np.mean(big[av <= 1])) if (av <= 1).any() else None, \"risk_all\": float(np.mean(big))}\n", " rec_units = np.concatenate([np.full(x.size, k) for k, x in enumerate(errs)])\n", " out[\"big_errors\"][\"risk_estimate_only_ci\"] = bootstrap(lambda i: big[i][av[i] == 0].mean() if (av[i] == 0).any() else 0.0, rec_units, B=min(C.BOOT, 300))\n", " for val, nm in ((-1, \"dec\"), (1, \"acc\")):\n", " fr = []\n", " inside, outside = [], []\n", " for i in ok:\n", " evs = events(seg[i], val)\n", " mk = np.zeros(C.N, bool)\n", " for a, b in evs:\n", " mk[a:b] = True\n", " fr.append(np.mean(P[i][a:b] == 2))\n", " inside.append(P[i][mk] == 2)\n", " outside.append(P[i][~mk] == 2)\n", " fr = np.array(fr)\n", " ins = np.concatenate(inside) if inside else np.zeros(0)\n", " ous = np.concatenate(outside) if outside else np.zeros(0)\n", " out[\"events\"][nm] = {\"n_events\": int(fr.size), \"frac_events_majority_abstained\": float(np.mean(fr > 0.5)) if fr.size else None, \"frac_events_any_abstained\": float(np.mean(fr > 0)) if fr.size else None, \"abstain_rate_inside\": float(ins.mean()) if ins.size else None, \"abstain_rate_outside\": float(ous.mean()) if ous.size else None}\n", " if ins.size and ous.size and ous.mean() > 0:\n", " out[\"events\"][nm][\"inside_over_outside\"] = float(ins.mean() / ous.mean())\n", " return out\n", "\n", "\n", "def smooth_u(rng, k, n, sigma):\n", " z = gaussian_filter1d(rng.standard_normal((k, n + 8 * sigma)), sigma, axis=1)[:, 4 * sigma:4 * sigma + n]\n", " z /= np.sqrt(1.0 / (2.0 * np.sqrt(np.pi) * sigma))\n", " return ndtr(z)\n", "\n", "\n", "def sample_trajectories(mix, k, rng, sigma=40):\n", " cdf = np.cumsum(mix, -1)\n", " u = smooth_u(rng, k, mix.shape[0], sigma)\n", " idx = np.minimum((cdf[None, :, :] < u[:, :, None]).sum(-1), C.NB - 1)\n", " return GRID[idx].astype(np.float32)\n", "\n", "\n", "@stage(\"s22_cascades\", params={\"v\": 2}, outputs=[C.CACHE / \"w35_cascade_probs.npz\"])\n", "def cascades(log):\n", " import torch\n", " from .t2 import load_ft4, post, predict_probs\n", " from .t3 import degenerate, feature_table, model\n", " from .t4 import seg_features\n", " dev = device()\n", " m = meta()\n", " fold_all = m.fold.values\n", " y = m.y.values\n", " ref = ref_fhr()\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " A = ens()\n", " P = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " _, sg_ok = seg_probs_on_estimate(log)\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " seeds = seeds_available()\n", " ok = (fold_all >= 0) & sg_ok\n", " fold = np.where(ok, fold_all, -1)\n", " idx = np.flatnonzero(ok)\n", " Xa = est_filled(A)\n", " Xb = Xa.copy()\n", " Xb[P == 2] = np.nan\n", " Xb_in = Xb.copy()\n", "\n", " def segment(X, recs):\n", " S = np.zeros((len(recs), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold[recs] == f)\n", " if sel_.size:\n", " pr = predict_probs(load_ft4(f, dev), X[sel_], dev, log)\n", " S[sel_] = post(np.nan_to_num(pr.astype(np.float32)), *pp[str(f)])\n", " return S\n", "\n", " def crossfit_rows(Ftr, ytr, ftr, Fte, fte):\n", " p = np.full(len(Fte), np.nan)\n", " for f in range(C.N_FOLDS):\n", " a = (ftr >= 0) & (ftr != f)\n", " b = fte == f\n", " if b.any():\n", " p[b] = model(int(a.sum())).fit(Ftr[a], ytr[a]).predict_proba(Fte[b])[:, 1]\n", " return p\n", "\n", " recs = np.arange(len(m))\n", " out = {}\n", " SA = segment(Xa[idx], idx)\n", " FA = pd.concat([feature_table(Xa[idx]), seg_features(Xa[idx], SA)], axis=1)\n", " pA = np.full(len(m), np.nan)\n", " pA[idx] = crossfit_rows(FA.values, y[idx], fold[idx], FA.values, fold[idx])\n", " SB = segment(Xb_in[idx], idx)\n", " FB = pd.concat([feature_table(Xb[idx]), seg_features(Xa[idx], SB)], axis=1)\n", " FB[\"abstain_frac\"] = np.mean(P[idx] == 2, 1)\n", " FB[\"flag_frac\"] = np.mean(P[idx] == 1, 1)\n", " pB = np.full(len(m), np.nan)\n", " pB[idx] = crossfit_rows(FB.values, y[idx], fold[idx], FB.values, fold[idx])\n", " K = C.K_MC\n", " rng = np.random.default_rng(C.SEED + 7)\n", " samples = np.zeros((K, idx.size, C.N), np.float32)\n", " pos = {r: k for k, r in enumerate(idx)}\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(fold_all == f)\n", " Ps = fold_probs(f, seeds)\n", " for a in range(0, te.size, 16):\n", " Pm = np.stack([np.asarray(p[a:a + 16], np.float32) for p in Ps]).mean(0)\n", " for kk in range(Pm.shape[0]):\n", " r = te[a + kk]\n", " if r in pos:\n", " mix = Pm[kk] / Pm[kk].sum(-1, keepdims=True)\n", " samples[:, pos[r]] = sample_trajectories(mix, K, rng)\n", " SC = np.zeros((K, idx.size, C.N), np.int8)\n", " FCs = []\n", " for k in range(K):\n", " SC[k] = segment(samples[k], idx)\n", " FCs.append(pd.concat([feature_table(samples[k]), seg_features(samples[k], SC[k])], axis=1).values)\n", " log.info(f\"MC sample {k + 1}/{K}\")\n", " FC = np.concatenate(FCs)\n", " yC = np.tile(y[idx], K)\n", " fC = np.tile(fold[idx], K)\n", " pCk = crossfit_rows(FC, yC, fC, FC, fC).reshape(K, idx.size)\n", " pC = np.full(len(m), np.nan)\n", " pC[idx] = pCk.mean(0)\n", " uC = np.full(len(m), np.nan)\n", " uC[idx] = pCk.std(0)\n", " vote = np.zeros((idx.size, C.N), np.int8)\n", " for lab in (1, -1):\n", " vote[(SC == lab).mean(0) > 0.5] = lab\n", " np.savez(C.CACHE / \"w35_cascade_probs.tmp.npz\", idx=idx, pA=pA[idx], pB=pB[idx], pC=pC[idx], uC=uC[idx], pCk=pCk)\n", " (C.CACHE / \"w35_cascade_probs.tmp.npz\").replace(C.CACHE / \"w35_cascade_probs.npz\")\n", " segs = {\"A\": SA, \"B\": SB, \"C\": vote}\n", " probs = {\"A\": pA[idx], \"B\": pB[idx], \"C\": pC[idx]}\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " dcs = {k: [dice_counts(segs[k][j], Sref[r]) for j, r in enumerate(idx)] for k in segs}\n", " ecs = {k: [event_counts(segs[k][j], Sref[r]) for j, r in enumerate(idx)] for k in segs}\n", " from .t4 import metric_values\n", " vals = {k: metric_values(yy, probs[k], dcs[k], ecs[k], np.arange(idx.size)) for k in segs}\n", " for k in segs:\n", " b = binary_scores(yy, probs[k])\n", " vals[k].update({\"brier\": b[\"brier\"], \"ece\": b[\"ece\"]})\n", " err = ((probs[k] >= 0.5).astype(int) != yy).astype(float)\n", " conf = np.abs(probs[k] - 0.5)\n", " vals[k][\"confident_error_rate\"] = float(np.mean(err[conf > 0.3]) if (conf > 0.3).any() else 0.0)\n", " vals[k][\"frac_confident\"] = float(np.mean(conf > 0.3))\n", " vals[k][\"record_aurc_confidence\"] = risk_coverage(-conf, err)[\"aurc\"]\n", " errC = ((pC[idx] >= 0.5).astype(int) != yy).astype(float)\n", " vals[\"C\"][\"record_aurc_spread\"] = risk_coverage(uC[idx], errC)[\"aurc\"]\n", " vals[\"C\"][\"record_aurc_spread_plus_conf\"] = risk_coverage(uC[idx] - np.abs(pC[idx] - 0.5), errC)[\"aurc\"]\n", " out[\"cascades\"] = vals\n", " out[\"degenerate_folds\"] = {k: degenerate(np.where(ok, v, np.nan), fold) for k, v in ((\"A\", pA), (\"B\", pB), (\"C\", pC))}\n", "\n", " def diffs(i, a, b):\n", " sel_ = np.asarray(i)\n", " va = metric_values(yy, probs[a], dcs[a], ecs[a], sel_)\n", " vb = metric_values(yy, probs[b], dcs[b], ecs[b], sel_)\n", " ba, bb = binary_scores(yy[sel_], probs[a][sel_]), binary_scores(yy[sel_], probs[b][sel_])\n", " return np.array([va[\"auroc\"] - vb[\"auroc\"], va[\"f1\"] - vb[\"f1\"], va[\"nmcc\"] - vb[\"nmcc\"], ba[\"brier\"] - bb[\"brier\"], ba[\"ece\"] - bb[\"ece\"], va[\"flow_dice\"] - vb[\"flow_dice\"], va[\"evidence_f1\"] - vb[\"evidence_f1\"]])\n", "\n", " keys = [\"auroc\", \"f1\", \"nmcc\", \"brier\", \"ece\", \"flow_dice\", \"evidence_f1\"]\n", " for a in (\"B\", \"C\"):\n", " bt = bootstrap(lambda i, a=a: diffs(i, a, \"A\"), groups, B=min(C.BOOT, 400))\n", " out[f\"{a}_minus_A\"] = {k: {\"point\": float(np.atleast_1d(bt[\"point\"])[j]), \"lo\": float(np.atleast_1d(bt[\"lo\"])[j]), \"hi\": float(np.atleast_1d(bt[\"hi\"])[j])} for j, k in enumerate(keys)}\n", " errA = ((pA[idx] >= 0.5).astype(int) != yy).astype(float)\n", " out[\"record_selective_C_spread_vs_A_conf\"] = bootstrap(lambda i: risk_coverage(uC[idx][i] - np.abs(pC[idx][i] - 0.5), errC[i])[\"aurc\"] - risk_coverage(-np.abs(pA[idx][i] - 0.5), errA[i])[\"aurc\"], groups, B=min(C.BOOT, 400))\n", " out[\"n_records\"] = int(idx.size)\n", " out[\"K\"] = K\n", " out[\"notes\"] = \"A = point estimate (ensemble median); B = abstained points masked as missing plus abstention fractions as features; C = K Monte-Carlo trajectories from the ensemble mixture with smooth (10 s) rank correlation; every classifier is cross-fitted on its own input type\"\n", " save_json(C.RES / \"s22_cascades.json\", out)\n", " return {k: {kk: round(vv, 3) for kk, vv in v.items() if kk in (\"auroc\", \"f1\", \"flow_dice\", \"ece\")} for k, v in vals.items()}" ] }, { "cell_type": "code", "execution_count": 19, "id": "ad577cffb2c6", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.877773Z", "iopub.status.busy": "2026-11-28T14:17:32.877462Z", "iopub.status.idle": "2026-11-28T14:17:32.890296Z", "shell.execute_reply": "2026-11-28T14:17:32.888717Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/deep.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/deep.py\n", "import math\n", "import time\n", "\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from sklearn.metrics import roc_auc_score\n", "\n", "from . import config as C\n", "from .folds import inner_split\n", "from .io import fill_linear, valid\n", "from .metrics import binary_scores\n", "from .utils import adaptive_batches, bootstrap, device, free_mem, get_logger, is_done, load_df, mark_done, mm, save_json, seed_all, stage\n", "\n", "\n", "class SE(nn.Module):\n", " def __init__(self, ch, r=8):\n", " super().__init__()\n", " self.f = nn.Sequential(nn.Linear(ch, max(4, ch // r)), nn.ReLU(), nn.Linear(max(4, ch // r), ch), nn.Sigmoid())\n", "\n", " def forward(self, x):\n", " return x * self.f(x.mean(-1))[..., None]\n", "\n", "\n", "class ResSE(nn.Module):\n", " def __init__(self, a, b, stride, k=7, drop=0.1):\n", " super().__init__()\n", " self.c1 = nn.Conv1d(a, b, k, stride=stride, padding=k // 2, bias=False)\n", " self.b1 = nn.BatchNorm1d(b)\n", " self.c2 = nn.Conv1d(b, b, k, padding=k // 2, bias=False)\n", " self.b2 = nn.BatchNorm1d(b)\n", " self.se = SE(b)\n", " self.drop = nn.Dropout(drop)\n", " self.skip = nn.Sequential(nn.Conv1d(a, b, 1, stride=stride, bias=False), nn.BatchNorm1d(b)) if (a != b or stride != 1) else nn.Identity()\n", "\n", " def forward(self, x):\n", " h = F.relu(self.b1(self.c1(x)))\n", " h = self.se(self.b2(self.c2(self.drop(h))))\n", " return F.relu(h + self.skip(x))\n", "\n", "\n", "class SEResNet1D(nn.Module):\n", " def __init__(self, cin=4, widths=(32, 64, 128, 128, 192)):\n", " super().__init__()\n", " self.stem = nn.Sequential(nn.Conv1d(cin, widths[0], 9, stride=2, padding=4, bias=False), nn.BatchNorm1d(widths[0]), nn.ReLU())\n", " self.blocks = nn.Sequential(*[ResSE(widths[i], widths[i + 1], 2) for i in range(len(widths) - 1)])\n", " self.head = nn.Sequential(nn.Dropout(0.3), nn.Linear(2 * widths[-1], 1))\n", "\n", " def forward(self, x):\n", " h = self.blocks(self.stem(x))\n", " return self.head(torch.cat([h.mean(-1), h.amax(-1)], 1)).squeeze(-1)\n", "\n", "\n", "def make_input(x, u=None):\n", " v = valid(x)\n", " f = fill_linear(x)\n", " fh = np.clip((f - 140.0) / 25.0, -4, 4)\n", " if u is None:\n", " uc = np.zeros(C.N, np.float32)\n", " ua = np.zeros(C.N, np.float32)\n", " else:\n", " uu = np.nan_to_num(np.asarray(u, np.float32))\n", " uc = np.clip(uu, 0, 127) / 50.0\n", " ua = np.ones(C.N, np.float32)\n", " return np.stack([fh, v.astype(np.float32), uc, ua]).astype(np.float32)\n", "\n", "\n", "class ClsData:\n", " def __init__(self, X, U, y):\n", " self.X, self.U, self.y = X, U, y\n", "\n", " def item(self, i, rng=None):\n", " x = np.asarray(self.X[i], np.float32).copy()\n", " u = None if self.U is None else np.asarray(self.U[i], np.float32).copy()\n", " if rng is not None:\n", " ctr = np.nanmedian(x) if np.isfinite(x).any() else 140.0\n", " x = (x - ctr) * rng.uniform(0.95, 1.05) + ctr + rng.uniform(-5, 5)\n", " for _ in range(int(rng.integers(0, 3))):\n", " L = int(rng.integers(8, 160))\n", " a = int(rng.integers(0, C.N - L))\n", " x[a:a + L] = np.nan\n", " if u is not None:\n", " u = u * rng.uniform(0.8, 1.2)\n", " return make_input(x, u)\n", "\n", " def batch(self, ids, rng=None):\n", " return torch.from_numpy(np.stack([self.item(i, rng) for i in ids])), torch.from_numpy(self.y[ids].astype(np.float32))\n", "\n", "\n", "@torch.no_grad()\n", "def predict(model, data, ids, dev, log=None):\n", " model.eval()\n", "\n", " def fn(i, j):\n", " x = torch.from_numpy(np.stack([data.item(k) for k in ids[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " return torch.sigmoid(model(x).float()).cpu().numpy()\n", "\n", " return np.concatenate(adaptive_batches(len(ids), fn, 256, log=log)) if len(ids) else np.zeros(0)\n", "\n", "\n", "def fit_cls(name, params, data, tr, va, te, outdir, epochs, lr, log, seed, init=None, force=False, oof_path=None):\n", " seed_all(seed)\n", " dev = device()\n", " model = SEResNet1D().to(dev)\n", " if init is not None:\n", " model.load_state_dict(torch.load(init, map_location=dev, weights_only=True)[\"model\"])\n", " opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)\n", " bs0 = 128\n", " steps = max(1, math.ceil(len(tr) / bs0))\n", " sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * steps * 2 + 10, pct_start=0.1)\n", " scaler = torch.amp.GradScaler(enabled=dev.type == \"cuda\")\n", " pos = float(np.mean(data.y[tr]))\n", " pw = torch.tensor((1 - pos) / max(pos, 1e-6), device=dev)\n", " d = outdir\n", " d.mkdir(parents=True, exist_ok=True)\n", " st = {\"epoch\": 0, \"best\": -1.0, \"bad\": 0, \"bs\": bs0, \"hist\": []}\n", " if (d / \"last.pt\").exists() and not force:\n", " ck = torch.load(d / \"last.pt\", map_location=dev, weights_only=False)\n", " for o, k in ((model, \"model\"), (opt, \"opt\"), (sched, \"sched\"), (scaler, \"scaler\")):\n", " o.load_state_dict(ck[k])\n", " st = ck[\"state\"]\n", " log.info(f\"resumed at epoch {st['epoch']}\")\n", " rng = np.random.default_rng(seed + st[\"epoch\"])\n", " while st[\"epoch\"] < epochs and st[\"bad\"] < max(4, C.PATIENCE - 2):\n", " model.train()\n", " t0 = time.time()\n", " order = rng.permutation(tr)\n", " k, tot, nb = 0, 0.0, 0\n", " while k < order.size:\n", " ids = order[k:k + st[\"bs\"]]\n", " x, yb = (t.to(dev) for t in data.batch(ids, rng))\n", " try:\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " loss = F.binary_cross_entropy_with_logits(model(x).float(), yb, pos_weight=pw)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " if sched.last_epoch < sched.total_steps - 1:\n", " sched.step()\n", " tot += float(loss)\n", " nb += 1\n", " k += ids.size\n", " except RuntimeError as e:\n", " if \"out of memory\" not in str(e).lower() or st[\"bs\"] <= 4:\n", " raise\n", " opt.zero_grad(set_to_none=True)\n", " free_mem()\n", " st[\"bs\"] //= 2\n", " log.warning(f\"OOM: batch -> {st['bs']}\")\n", " pv = predict(model, data, va, dev, log)\n", " yv = data.y[va]\n", " auc = roc_auc_score(yv, pv) if np.unique(yv).size == 2 else 0.5\n", " st[\"epoch\"] += 1\n", " st[\"hist\"].append({\"epoch\": st[\"epoch\"], \"train_loss\": tot / max(1, nb), \"val_auroc\": float(auc), \"sec\": time.time() - t0})\n", " if auc > st[\"best\"] + 1e-4:\n", " st[\"best\"], st[\"bad\"] = auc, 0\n", " torch.save({\"model\": model.state_dict()}, d / \"best.tmp\")\n", " (d / \"best.tmp\").replace(d / \"best.pt\")\n", " else:\n", " st[\"bad\"] += 1\n", " torch.save({\"model\": model.state_dict(), \"opt\": opt.state_dict(), \"sched\": sched.state_dict(), \"scaler\": scaler.state_dict(), \"state\": st}, d / \"last.tmp\")\n", " (d / \"last.tmp\").replace(d / \"last.pt\")\n", " log.info(st[\"hist\"][-1])\n", " if not (d / \"best.pt\").exists():\n", " torch.save({\"model\": model.state_dict()}, d / \"best.pt\")\n", " model.load_state_dict(torch.load(d / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " p = predict(model, data, te, dev, log)\n", " np.savez(str(oof_path) + \".tmp.npz\", idx=te, p=p)\n", " (C.CACHE / (oof_path.name + \".tmp.npz\")).replace(str(oof_path) + \".npz\")\n", " mark_done(name, params, {\"best_val_auroc\": st[\"best\"], \"epochs\": st[\"epoch\"], \"history\": st[\"hist\"], \"seconds\": round(sum(h[\"sec\"] for h in st[\"hist\"]), 1)}, [d / \"best.pt\", str(oof_path) + \".npz\"])\n", "\n", "\n", "def t3_arrays():\n", " X = np.asarray(mm(C.CACHE / \"t3_fhr.npy\"))\n", " U = np.asarray(mm(C.CACHE / \"t3_uc.npy\"))\n", " return X, U\n", "\n", "\n", "def train_t3(force=False, fold=0):\n", " name = f\"s23_t3_deep_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T3D}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " m = load_df(C.CACHE / \"folds_t3.pkl\")\n", " tr, va = inner_split(m, fold)\n", " te = np.flatnonzero(m.fold.values == fold)\n", " X, U = t3_arrays()\n", " data = ClsData(X, U, m.y.values.astype(np.int64))\n", " fit_cls(name, params, data, tr, va, te, C.MODELS / \"t3_deep\" / f\"fold{fold}\", C.EPOCHS_T3D, 1e-3, log, C.SEED + 300 + fold, force=force, oof_path=C.CACHE / f\"t3_deep_oof_f{fold}\")\n", "\n", "\n", "def train_t4(force=False, fold=0):\n", " name = f\"s24_t4_deep_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T4D}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " from .sel import est_filled\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " tr, va = inner_split(m, fold)\n", " te = np.flatnonzero(m.fold.values == fold)\n", " data = ClsData(est_filled(), None, m.y.values.astype(np.int64))\n", " init = C.MODELS / \"t3_deep\" / f\"fold{fold}\" / \"best.pt\"\n", " fit_cls(name, params, data, tr, va, te, C.MODELS / \"t4_deep\" / f\"fold{fold}\", C.EPOCHS_T4D, 3e-4, log, C.SEED + 400 + fold, init=init if init.exists() else None, force=force, oof_path=C.CACHE / f\"t4_deep_oof_f{fold}\")\n", "\n", "\n", "def gather(prefix, n):\n", " p = np.full(n, np.nan)\n", " for f in range(C.N_FOLDS):\n", " q = C.CACHE / f\"{prefix}_f{f}.npz\"\n", " if q.exists():\n", " with np.load(q) as z:\n", " p[z[\"idx\"]] = z[\"p\"]\n", " return p\n", "\n", "\n", "def rank(p):\n", " from scipy.stats import rankdata\n", " out = np.full(p.size, np.nan)\n", " ok = np.isfinite(p)\n", " out[ok] = (rankdata(p[ok]) - 0.5) / ok.sum()\n", " return out\n", "\n", "\n", "def compare(y, preds, groups, fold):\n", " from .t3 import threshold_shift\n", " out = {}\n", " for k, p in preds.items():\n", " r = binary_scores(y, p)\n", " r[\"ci_auroc\"] = bootstrap(lambda i, p=p: roc_auc_score(y[i], p[i]), groups)\n", " r[\"after_threshold_shift\"] = binary_scores(y, threshold_shift(p, y, fold))\n", " out[k] = r\n", " ks = list(preds)\n", " out[\"paired_auroc_diffs\"] = {}\n", " for a in ks:\n", " for b in ks:\n", " if a < b:\n", " out[\"paired_auroc_diffs\"][f\"{a}_minus_{b}\"] = bootstrap(lambda i, a=a, b=b: roc_auc_score(y[i], preds[a][i]) - roc_auc_score(y[i], preds[b][i]), groups)\n", " return out\n", "\n", "\n", "@stage(\"s25_risk_models\", params={\"v\": 2})\n", "def risk_models(log):\n", " from .t3 import MISS, oof\n", " rep = {}\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " F3 = load_df(C.CACHE / \"t3_features.pkl\")\n", " ok3 = m3.fold.values >= 0\n", " p_gbm = oof(F3, m3.y.values, m3.fold.values, list(F3.columns))\n", " p_deep = gather(\"t3_deep_oof\", len(m3))\n", " ok3 &= np.isfinite(p_deep) & np.isfinite(p_gbm)\n", " preds = {\"gbm_features\": p_gbm[ok3], \"deep_seresnet\": p_deep[ok3], \"average\": 0.5 * (p_gbm[ok3] + p_deep[ok3]), \"rank_average\": 0.5 * (rank(p_gbm[ok3]) + rank(p_deep[ok3]))}\n", " rep[\"t3\"] = compare(m3.y.values[ok3], preds, m3.group.values[ok3], m3.fold.values[ok3])\n", " rep[\"t3\"][\"n\"] = int(ok3.sum())\n", " m4 = load_df(C.CACHE / \"folds_t4.pkl\")\n", " z = np.load(C.CACHE / \"w35_cascade_probs.npz\")\n", " pA = np.full(len(m4), np.nan)\n", " pA[z[\"idx\"]] = z[\"pA\"]\n", " pC = np.full(len(m4), np.nan)\n", " pC[z[\"idx\"]] = z[\"pC\"]\n", " p4 = gather(\"t4_deep_oof\", len(m4))\n", " ok4 = (m4.fold.values >= 0) & np.isfinite(pA) & np.isfinite(p4)\n", " preds4 = {\"gbm_cascade_A\": pA[ok4], \"gbm_cascade_C\": pC[ok4], \"deep_transfer_t3_to_t4\": p4[ok4], \"average_A_deep\": 0.5 * (pA[ok4] + p4[ok4])}\n", " rep[\"t4\"] = compare(m4.y.values[ok4], preds4, m4.group.values[ok4], m4.fold.values[ok4])\n", " rep[\"t4\"][\"n\"] = int(ok4.sum())\n", " rep[\"notes\"] = \"T3: GBM on all FHR/UC/missingness features vs SE-ResNet on FHR+UC+mask (grouped by 50%-overlap pairs). T4: matched GBM on the estimated FHR (cascade A), Monte-Carlo GBM (cascade C), and the T3 SE-ResNet fine-tuned on the out-of-fold estimated FHR; all out-of-fold\"\n", " save_json(C.RES / \"s25_risk_models.json\", rep)\n", " return {\"t3_auroc\": {k: v[\"auroc\"] for k, v in rep[\"t3\"].items() if isinstance(v, dict) and \"auroc\" in v}, \"t4_auroc\": {k: v[\"auroc\"] for k, v in rep[\"t4\"].items() if isinstance(v, dict) and \"auroc\" in v}}" ] }, { "cell_type": "code", "execution_count": 20, "id": "2a1a2dd2fdae", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.893740Z", "iopub.status.busy": "2026-11-28T14:17:32.893442Z", "iopub.status.idle": "2026-11-28T14:17:32.903112Z", "shell.execute_reply": "2026-11-28T14:17:32.901504Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/a1.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/a1.py\n", "import zlib\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .io import events, valid\n", "from .metrics import dice_counts, event_counts\n", "from .utils import bootstrap, device, load_df, load_json, mm, save_json, stage\n", "\n", "\n", "def conditions():\n", " c = [(\"clean\", None)]\n", " c += [(f\"noise_sd{s}\", (\"noise\", s)) for s in (2, 5, 10)]\n", " c += [(f\"bias_{b:+d}\", (\"bias\", b)) for b in (-10, -5, 5, 10)]\n", " c += [(f\"halving_{d}s\", (\"halve\", d)) for d in (10, 30, 60)]\n", " c += [(f\"doubling_{d}s\", (\"double\", d)) for d in (10, 30, 60)]\n", " c += [(f\"gap_{L}s_{w}\", (\"gap\", L, w)) for L in (15, 30, 60, 120) for w in (\"during_decel\", \"away\")]\n", " c += [(f\"estimate_mix_{int(p * 100)}pct\", (\"mix\", p)) for p in (0.1, 0.25, 0.5)]\n", " return c if not C.SMOKE else c[:1] + c[1:2] + c[4:5] + c[8:9] + c[14:16] + c[-1:]\n", "\n", "\n", "def perturb(x, seg, kind, rng, est=None, pfar=None):\n", " x = x.copy()\n", " v = valid(x)\n", " if kind[0] == \"noise\":\n", " x[v] = x[v] + rng.normal(0, kind[1], v.sum())\n", " elif kind[0] == \"bias\":\n", " x[v] = x[v] + kind[1]\n", " elif kind[0] in (\"halve\", \"double\"):\n", " L = int(kind[1] * C.FS_FHR)\n", " for _ in range(3):\n", " a = int(rng.integers(0, C.N - L))\n", " x[a:a + L] = x[a:a + L] * (0.5 if kind[0] == \"halve\" else 2.0)\n", " elif kind[0] == \"gap\":\n", " L = int(kind[1] * C.FS_FHR)\n", " ev = events(seg, -1)\n", " if kind[2] == \"during_decel\" and len(ev):\n", " a, b = ev[int(rng.integers(0, len(ev)))]\n", " s = int(np.clip((a + b) // 2 - L // 2, 0, C.N - L))\n", " else:\n", " busy = np.zeros(C.N, bool)\n", " for v_ in (1, -1):\n", " for a, b in events(seg, v_):\n", " busy[max(0, a - 240):b + 240] = True\n", " free = np.flatnonzero(~np.convolve(busy, np.ones(L), \"same\").astype(bool))\n", " free = free[(free >= L // 2) & (free < C.N - L // 2)]\n", " c = int(rng.choice(free)) if free.size else int(rng.integers(L // 2, C.N - L // 2))\n", " s = c - L // 2\n", " x[s:s + L] = np.nan\n", " elif kind[0] == \"mix\":\n", " k = int(kind[1] * C.N)\n", " top = np.argsort(-np.nan_to_num(pfar))[:k]\n", " x[top] = est[top]\n", " x[(x < C.FHR_MIN) | (x > C.FHR_MAX)] = np.nan\n", " return x.astype(np.float32)\n", "\n", "\n", "@stage(\"s26_a1_perturbation\", params={\"v\": 1})\n", "def perturbation(log):\n", " from .sel import E, ens\n", " from .t2 import load_ft4, post, predict_probs\n", " from .t3 import feature_table, model\n", " from .t4 import metric_values, seg_features\n", " dev = device()\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " y = m.y.values\n", " Xref = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " A = ens()\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " from .t2 import safe_models_for_t4\n", " safe = safe_models_for_t4()\n", " fold = m.fold.values\n", " ok = (fold >= 0) & np.array([fold[i] in safe[i] for i in range(len(m))])\n", " idx = np.flatnonzero(ok)\n", " fold_ok = np.where(ok, fold, -1)\n", " models = {f: load_ft4(f, dev) for f in range(C.N_FOLDS)}\n", "\n", " def pipeline_features(X, recs):\n", " S = np.zeros((len(recs), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold_ok[recs] == f)\n", " if sel_.size:\n", " pr = predict_probs(models[f], X[sel_], dev, log)\n", " S[sel_] = post(np.nan_to_num(pr.astype(np.float32)), *pp[str(f)])\n", " F = pd.concat([feature_table(X), seg_features(X, S)], axis=1).values\n", " return S, F\n", "\n", " S0, F0 = pipeline_features(Xref[idx], idx)\n", " clfs = {}\n", " for f in range(C.N_FOLDS):\n", " tr = (fold_ok[idx] >= 0) & (fold_ok[idx] != f)\n", " clfs[f] = model(int(tr.sum())).fit(F0[tr], y[idx][tr])\n", " res = {}\n", " store = {}\n", " for name, kind in conditions():\n", " rng = np.random.default_rng(zlib.crc32(name.encode()) + C.SEED)\n", " if kind is None:\n", " S, F = S0, F0\n", " else:\n", " Xp = np.stack([perturb(Xref[i], Sref[i], kind, rng, A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]]) for i in idx])\n", " S, F = pipeline_features(Xp, idx)\n", " p = np.full(idx.size, np.nan)\n", " for f in range(C.N_FOLDS):\n", " te = fold_ok[idx] == f\n", " if te.any():\n", " p[te] = clfs[f].predict_proba(F[te])[:, 1]\n", " dc = [dice_counts(S[j], Sref[r]) for j, r in enumerate(idx)]\n", " ec = [event_counts(S[j], Sref[r]) for j, r in enumerate(idx)]\n", " store[name] = (p, dc, ec)\n", " res[name] = metric_values(y[idx], p, dc, ec, np.arange(idx.size))\n", " log.info(f\"{name}: {res[name]}\")\n", " keys = [\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\"]\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " p0, dc0, ec0 = store[\"clean\"]\n", " deltas = {}\n", " for name in res:\n", " if name == \"clean\":\n", " continue\n", " p, dc, ec = store[name]\n", "\n", " def stat(i, p=p, dc=dc, ec=ec):\n", " a = metric_values(yy, p, dc, ec, i)\n", " b = metric_values(yy, p0, dc0, ec0, i)\n", " return np.array([a[k] - b[k] for k in keys])\n", "\n", " bt = bootstrap(stat, groups, B=min(C.BOOT, 300))\n", " deltas[name] = {k: {\"point\": float(np.atleast_1d(bt[\"point\"])[j]), \"lo\": float(np.atleast_1d(bt[\"lo\"])[j]), \"hi\": float(np.atleast_1d(bt[\"hi\"])[j])} for j, k in enumerate(keys)}\n", " rep = {\"n_records\": int(idx.size), \"pipeline\": \"T4-fine-tuned U-Net + post-processing + gradient boosting trained on clean reference FHR (cross-fitted); perturbations applied to test-fold reference FHR only\", \"metrics\": res, \"delta_vs_clean\": deltas, \"n_records_with_decel\": int(sum(len(events(Sref[i], -1)) > 0 for i in idx))}\n", " save_json(C.RES / \"s26_a1_perturbation.json\", rep)\n", " return {k: {kk: round(v[kk][\"point\"], 3) for kk in (\"flow_dice\", \"auroc\")} for k, v in list(deltas.items())[:4]}" ] }, { "cell_type": "code", "execution_count": 21, "id": "d5afb2511a9d", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.906871Z", "iopub.status.busy": "2026-11-28T14:17:32.906551Z", "iopub.status.idle": "2026-11-28T14:17:32.922473Z", "shell.execute_reply": "2026-11-28T14:17:32.920737Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/summary35.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/summary35.py\n", "import json\n", "\n", "import numpy as np\n", "\n", "from . import config as C\n", "from .summary import ci, f, g, section_run, table\n", "from .utils import load_json, save_json, stage\n", "\n", "\n", "def gates(r):\n", " s19, s21 = r[\"s19_t1_ensemble\"], r[\"s21_t1_risk_policy\"]\n", " L = [\"## Gates\", \"\"]\n", " s6 = s21.get(\"gate_S6\", {})\n", " L += [f\"- **S6** (learned score beats training-free p_far): passed = **{s6.get('passed')}** · relative AURC of g vs p_far {ci(s6.get('g_rel_aurc_vs_p_far'))} · {s6.get('decision')}\"]\n", " s8 = s21.get(\"gate_S8\", {})\n", " L += [f\"- **S8** (pre-registered, seed-0 reference): passed = **{s8.get('passed')}** · ranking {s8.get('ranking_passed')} (pooled relative AURC {ci(s8.get('pooled_rel_aurc'))}, folds passing {s8.get('folds_passing')}/5) · calibration {s8.get('calibration_passed')}\"]\n", " fm = s19.get(\"gate_FM_prerequisite\", {})\n", " L += [f\"- **Flow-matching prerequisite**: marginals calibrated = **{fm.get('marginals_calibrated')}** · worst deviation {f(fm.get('worst_deviation'))} in {fm.get('worst_stratum')} · {fm.get('decision')}\"]\n", " am = s21.get(\"amendments\", {})\n", " if am:\n", " L += [\"\", \"Protocol amendments (written before any learned score was fitted):\"] + [f\"- {k}: {v}\" for k, v in am.items()]\n", " return L\n", "\n", "\n", "def sec_ensemble(r):\n", " s = r[\"s19_t1_ensemble\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## T1 · seed ensemble\", \"\", f\"Seeds: {s.get('seeds')} · records: {s.get('n_records')}\", \"\"]\n", " rows = [[k, f(s[k][\"rmse_pooled\"], 2), f(s[k][\"mae_pooled\"], 2), f(s[k][\"rmse_record_mean\"], 2), f(s[k].get(\"crps_record_mean\"), 3)] for k in (\"seed0\", \"ensemble\")]\n", " L += table([\"estimator\", \"RMSE\", \"MAE\", \"RMSE per record\", \"CRPS\"], rows)\n", " L += [\"\", f\"- ensemble − seed0 RMSE: {ci(s.get('diff_rmse_ens_minus_seed0'))}\", f\"- ensemble − seed0 big-error rate: {ci(s.get('diff_big_rate_ens_minus_seed0'), 4)}\", f\"- ensemble − seed0 CRPS: {ci(s.get('diff_crps_ens_minus_seed0'))}\", \"\", \"### Interval calibration (nominal 80% and 50%)\", \"\"]\n", " rows = [[k, l, v[\"points\"], f(v[\"coverage80\"]), f(v[\"coverage50\"])] for k, d in s.get(\"interval_coverage\", {}).items() for l, v in d.items()]\n", " return L + table([\"stratum\", \"level\", \"points\", \"80% coverage\", \"50% coverage\"], rows)\n", "\n", "\n", "def sec_audit(r):\n", " s = r[\"s20_reference_audit\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## Reference audit · FHR below 110 bpm\", \"\", f\"- rule: {s.get('rule')}\"]\n", " L += [f\"- {k}: {f(v) if isinstance(v, float) else v}\" for k, v in s.items() if k not in (\"rule\", \"sensitivity\")]\n", " rows = [[k, v[\"points\"], f(v[\"rmse\"], 2), f(v[\"big_rate\"], 4), v[\"brady_points\"], f(v[\"brady_rmse\"], 2), f(v[\"brady_big_rate\"])] for k, v in s.get(\"sensitivity\", {}).items()]\n", " return L + [\"\"] + table([\"evaluation set\", \"points\", \"RMSE\", \"abs err > 10\", \"brady points\", \"brady RMSE\", \"brady abs err > 10\"], rows) + [\"\", \"Per-episode table: results/s20_brady_episodes.csv\"]\n", "\n", "\n", "def sec_risk(r):\n", " s = r[\"s21_t1_risk_policy\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## T1 · error-risk scores (point level, out-of-fold)\", \"\"]\n", " rows = []\n", " for sc in (\"seed0\", \"ensemble\"):\n", " for k, v in g(s, sc, \"scores\", default={}).items():\n", " rows.append([sc, k, f(v[\"risk_full\"], 4), f(v[\"aurc\"], 5), f(v[\"aurc_oracle\"], 5), ci(v.get(\"rel_aurc_vs_p_far\")) if \"rel_aurc_vs_p_far\" in v else \"reference\" if k == \"p_far\" else \"–\", f(v[\"risk@0.9\"], 4), f(v[\"risk@0.8\"], 4), f(v[\"risk@0.7\"], 4), f(v[\"spearman_abs_err\"])])\n", " L += table([\"estimator\", \"score\", \"rate at 100%\", \"AURC\", \"oracle AURC\", \"relative AURC vs p_far\", \"rate at 90%\", \"at 80%\", \"at 70%\", \"Spearman\"], rows)\n", " pf = g(s, \"seed0\", \"scores\", \"learned_g\", \"rel_aurc_vs_p_far_per_fold\", default={})\n", " if pf:\n", " L += [\"\", \"S8 per fold (seed-0 estimator, g vs p_far): \" + \", \".join(f\"fold {k}: {ci(v)}\" for k, v in pf.items())]\n", " L += [\"\", f\"Observable strata: {s.get('observable_strata')}\", \"\", \"### Conformal selective risk control (calibration fold reserved per outer fold)\", \"\"]\n", " rows = []\n", " for kind, d in s.get(\"selective_risk_control\", {}).items():\n", " for a, v in d.items():\n", " strat = \"; \".join(f\"{k}: cov {f(x['coverage'], 2)}, risk {f(x['realized_risk'], 4)} (base {f(x['base_rate'], 3)})\" for k, x in v[\"per_observable_stratum\"].items())\n", " rows.append([kind, a, f(v[\"coverage\"]), ci(v[\"realized_risk\"], 4), v[\"calibrated\"], strat])\n", " L += table([\"thresholds\", \"alpha\", \"coverage\", \"realized risk [95% CI]\", \"calibrated\", \"per observable stratum\"], rows)\n", " for kind, loc in s.get(\"location\", {}).items():\n", " L += [\"\", f\"### Where the three-action policy abstains ({kind} thresholds)\", \"\", f\"- action rates: {json.dumps({k: round(v, 4) for k, v in loc['action_rates'].items()})}\"]\n", " be = loc[\"big_errors\"]\n", " L += [f\"- big errors falling in abstain / flag / estimate: {f(be['share_in_abstain'])} / {f(be['share_in_flag'])} / {f(be['share_in_estimate'])}\", f\"- big-error rate: all {f(be['risk_all'], 4)}, estimate only {ci(be['risk_estimate_only_ci'], 4)}, estimate or flag {f(be['risk_estimate_or_flag'], 4)}\"]\n", " for nm, ev in loc[\"events\"].items():\n", " L.append(f\"- {nm} events: {ev}\")\n", " rows = [[sn, lvl, v[\"points\"], f(v[\"abstain\"], 4), f(v[\"flag\"], 4)] for sn, d in loc[\"by_true_stratum\"].items() for lvl, v in d.items()]\n", " L += [\"\"] + table([\"true stratum\", \"level\", \"points\", \"abstain rate\", \"flag rate\"], rows)\n", " return L\n", "\n", "\n", "def sec_cascades(r):\n", " s = r[\"s22_cascades\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## Uncertainty propagation to T2/T3 (cascades A/B/C)\", \"\", s.get(\"notes\", \"\"), f\"Records: {s.get('n_records')} · Monte-Carlo samples: {s.get('K')}\", \"\"]\n", " mets = [\"flow_dice\", \"flow_dice_record\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"brier\", \"ece\", \"frac_confident\", \"confident_error_rate\", \"record_aurc_confidence\"]\n", " rows = [[k] + [f(v.get(mm)) for mm in mets] for k, v in s.get(\"cascades\", {}).items()]\n", " L += table([\"cascade\"] + mets, rows)\n", " for k in (\"B_minus_A\", \"C_minus_A\"):\n", " if k in s:\n", " L += [\"\", f\"{k}: \" + \", \".join(f\"{m}: {ci(v)}\" for m, v in s[k].items())]\n", " L += [\"\", f\"- record-level selective classification, C (spread − |p−0.5|) minus A (−|p−0.5|) AURC: {ci(s.get('record_selective_C_spread_vs_A_conf'), 4)}\", f\"- C extra: spread-only AURC {f(g(s, 'cascades', 'C', 'record_aurc_spread'), 4)}, combined {f(g(s, 'cascades', 'C', 'record_aurc_spread_plus_conf'), 4)}\"]\n", " return L\n", "\n", "\n", "def sec_models(r):\n", " s = r[\"s25_risk_models\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## Risk models (competition T3 and T4)\", \"\", s.get(\"notes\", \"\")]\n", " for t in (\"t3\", \"t4\"):\n", " d = s.get(t, {})\n", " rows = [[k, ci(dict(point=v[\"auroc\"], lo=g(v, \"ci_auroc\", \"lo\"), hi=g(v, \"ci_auroc\", \"hi\"))), f(v[\"f1\"]), f(v[\"nmcc\"]), f(g(v, \"after_threshold_shift\", \"f1\")), f(g(v, \"after_threshold_shift\", \"nmcc\")), f(v[\"brier\"]), f(v[\"ece\"])] for k, v in d.items() if isinstance(v, dict) and \"auroc\" in v]\n", " L += [\"\", f\"### {t.upper()} (n = {d.get('n')})\", \"\"] + table([\"model\", \"AUROC [95% CI]\", \"F1@0.5\", \"nMCC@0.5\", \"F1 after shift\", \"nMCC after shift\", \"Brier\", \"ECE\"], rows)\n", " L += [\"\"] + [f\"- {k}: {ci(v)}\" for k, v in d.get(\"paired_auroc_diffs\", {}).items()]\n", " return L\n", "\n", "\n", "def sec_a1(r):\n", " s = r[\"s26_a1_perturbation\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## Article 1 · controlled perturbations of the reference FHR\", \"\", s.get(\"pipeline\", \"\"), f\"Records: {s.get('n_records')} (with ≥1 deceleration: {s.get('n_records_with_decel')})\", \"\"]\n", " c = s[\"metrics\"].get(\"clean\", {})\n", " L += [f\"Clean: \" + \", \".join(f\"{k} {f(v)}\" for k, v in c.items()), \"\"]\n", " keys = [\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\"]\n", " rows = [[k] + [ci(v[m]) for m in keys] for k, v in s.get(\"delta_vs_clean\", {}).items()]\n", " return L + table([\"perturbation\"] + [f\"Δ {k}\" for k in keys], rows)\n", "\n", "\n", "def sec_training():\n", " L = [\"\", \"## Training (best validation, epochs)\", \"\"]\n", " rows = []\n", " for pat, key in ((\"s10_t1_tcn_f\", \"best_val_rmse\"), (\"s23_t3_deep_f\", \"best_val_auroc\"), (\"s24_t4_deep_f\", \"best_val_auroc\")):\n", " for p in sorted(C.STATE.glob(f\"{pat}*.done.json\")):\n", " info = load_json(p)[\"info\"]\n", " rows.append([p.name.replace(\".done.json\", \"\"), key, f(info.get(key)), info.get(\"epochs\"), f(info.get(\"seconds\"), 0)])\n", " return L + table([\"job\", \"metric\", \"best\", \"epochs\", \"seconds\"], rows)\n", "\n", "\n", "def figures(r):\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", " out = []\n", " s = r[\"s21_t1_risk_policy\"]\n", " if s:\n", " fig, axs = plt.subplots(1, 2, figsize=(12, 3.8))\n", " for ax, sc in zip(axs, (\"seed0\", \"ensemble\")):\n", " for k, v in g(s, sc, \"scores\", default={}).items():\n", " ax.plot([1.0, 0.9, 0.8, 0.7], [v[\"risk_full\"], v[\"risk@0.9\"], v[\"risk@0.8\"], v[\"risk@0.7\"]], marker=\"o\", label=k)\n", " ax.set_yscale(\"log\")\n", " ax.invert_xaxis()\n", " ax.set_xlabel(\"coverage\")\n", " ax.set_title(f\"{sc} estimator: rate of |e|>10 bpm\")\n", " ax.legend(fontsize=7)\n", " fig.tight_layout()\n", " p = C.FIG / \"w35_risk_coverage.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " loc = g(s, \"location\", \"mondrian\", \"by_true_stratum\", default={})\n", " if loc:\n", " labels, ab, fl = [], [], []\n", " for sn in (\"near_dec\", \"near_acc\", \"brady_ref\", \"near_ref_gap\", \"reference_suspect\", \"quality_quintile\"):\n", " for lvl, v in loc.get(sn, {}).items():\n", " labels.append(f\"{sn}={lvl}\")\n", " ab.append(v[\"abstain\"])\n", " fl.append(v[\"flag\"])\n", " fig, ax = plt.subplots(figsize=(10, 3.8))\n", " x = np.arange(len(labels))\n", " ax.bar(x, ab, label=\"abstain\")\n", " ax.bar(x, fl, bottom=ab, label=\"flag\")\n", " ax.set_xticks(x)\n", " ax.set_xticklabels(labels, rotation=60, ha=\"right\", fontsize=7)\n", " ax.set_ylabel(\"rate\")\n", " ax.set_title(\"Where the Mondrian three-action policy abstains or flags\")\n", " ax.legend()\n", " fig.tight_layout()\n", " p = C.FIG / \"w35_abstention_location.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " a1 = r[\"s26_a1_perturbation\"]\n", " if a1:\n", " d = a1[\"delta_vs_clean\"]\n", " names = list(d)\n", " fig, axs = plt.subplots(1, 3, figsize=(14, 0.32 * len(names) + 1.5), sharey=True)\n", " for ax, met in zip(axs, (\"flow_dice\", \"evidence_f1\", \"auroc\")):\n", " pts = np.array([d[n][met][\"point\"] for n in names])\n", " lo = np.array([d[n][met][\"lo\"] for n in names])\n", " hi = np.array([d[n][met][\"hi\"] for n in names])\n", " ax.errorbar(pts, np.arange(len(names)), xerr=np.vstack([pts - lo, hi - pts]), fmt=\"o\", ms=3, capsize=2)\n", " ax.axvline(0, color=\"k\", lw=0.6)\n", " ax.set_title(f\"Δ {met} vs clean\")\n", " axs[0].set_yticks(np.arange(len(names)))\n", " axs[0].set_yticklabels(names, fontsize=7)\n", " axs[0].invert_yaxis()\n", " fig.tight_layout()\n", " p = C.FIG / \"w35_perturbations.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " return out\n", "\n", "\n", "@stage(\"s27_summary_w35\", params={\"v\": 2})\n", "def run(log):\n", " names = [\"s19_t1_ensemble\", \"s20_reference_audit\", \"s21_t1_risk_policy\", \"s22_cascades\", \"s25_risk_models\", \"s26_a1_perturbation\"]\n", " r = {n: load_json(C.RES / f\"{n}.json\", {}) for n in names}\n", " lines = [f\"# CTG weeks 3-5 summary ({'SMOKE' if C.SMOKE else 'FULL'} run)\", \"\", f\"Holdout locked: {'no (UNLOCKED)' if C.UNLOCK_HOLDOUT else 'yes'}\", \"\"]\n", " for sec in (gates(r), sec_ensemble(r), sec_audit(r), sec_risk(r), sec_cascades(r), sec_models(r), sec_a1(r), sec_training(), section_run()):\n", " lines += sec\n", " figs = figures(r)\n", " lines += [\"\", \"## Figures\", \"\"] + [f\"- {p}\" for p in figs] + ([f\"- {C.FIG / 'w35_brady_episodes.png'}\"] if (C.FIG / \"w35_brady_episodes.png\").exists() else [])\n", " (C.OUT / \"SUMMARY_W3_5.md\").write_text(\"\\n\".join(lines))\n", " save_json(C.RES / \"s27_gates.json\", {\"S6\": g(r, \"s21_t1_risk_policy\", \"gate_S6\"), \"S8\": g(r, \"s21_t1_risk_policy\", \"gate_S8\"), \"FM\": g(r, \"s19_t1_ensemble\", \"gate_FM_prerequisite\")})\n", " return {\"S6\": g(r, \"s21_t1_risk_policy\", \"gate_S6\", \"passed\"), \"S8\": g(r, \"s21_t1_risk_policy\", \"gate_S8\", \"passed\")}" ] }, { "cell_type": "code", "execution_count": 22, "id": "497ae6938fff", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.926050Z", "iopub.status.busy": "2026-11-28T14:17:32.925663Z", "iopub.status.idle": "2026-11-28T14:17:32.935011Z", "shell.execute_reply": "2026-11-28T14:17:32.933197Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/fastm.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/fastm.py\n", "import numpy as np\n", "from scipy.stats import rankdata\n", "\n", "from . import config as C\n", "from .metrics import sanitize_probs\n", "\n", "KEYS = [\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\"]\n", "\n", "\n", "def auroc(y, p):\n", " pos = y == 1\n", " n1 = int(pos.sum())\n", " n0 = y.size - n1\n", " if n1 == 0 or n0 == 0:\n", " return np.nan\n", " r = rankdata(p)\n", " return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))\n", "\n", "\n", "def counts_matrix(dc):\n", " return np.array([[c[k][j] for k in (0, 1, -1) for j in range(3)] for c in dc], np.int64).reshape(len(dc), 9)\n", "\n", "\n", "def events_matrix(ec):\n", " return np.array([[c[n][j] for n in (\"acc\", \"dec\") for j in range(3)] for c in ec], np.int64).reshape(len(ec), 6)\n", "\n", "\n", "def dice_macro(D):\n", " s = D.sum(0).reshape(3, 3)\n", " den = s[:, 1] + s[:, 2]\n", " with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n", " d = np.where(den > 0, 2 * s[:, 0] / np.maximum(den, 1), np.nan)\n", " return float(np.nanmean(d)) if np.isfinite(d).any() else np.nan\n", "\n", "\n", "def evidence_macro(Ev):\n", " s = Ev.sum(0).reshape(2, 3)\n", " den = 2 * s[:, 0] + s[:, 1] + s[:, 2]\n", " f = np.where(den > 0, 2 * s[:, 0] / np.maximum(den, 1), np.nan)\n", " return float(np.nanmean(f)) if np.isfinite(f).any() else np.nan\n", "\n", "\n", "def binary(y, p):\n", " yh = p >= 0.5\n", " tp = float(np.sum(yh & (y == 1)))\n", " fp = float(np.sum(yh & (y == 0)))\n", " fn = float(np.sum(~yh & (y == 1)))\n", " tn = float(np.sum(~yh & (y == 0)))\n", " f1 = 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) else 0.0\n", " f1n = 2 * tn / (2 * tn + fp + fn) if (2 * tn + fp + fn) else 0.0\n", " present = [c for c in (0, 1) if np.any(y == c) or np.any(yh.astype(int) == c)]\n", " macro = np.mean([f1n if c == 0 else f1 for c in present]) if present else 0.0\n", " den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))\n", " mcc = (tp * tn - fp * fn) / den if den > 0 and np.unique(y).size == 2 else 0.0\n", " return f1, float(macro), (mcc + 1) / 2\n", "\n", "\n", "class Pack:\n", " def __init__(self, y, p, dc=None, ec=None, D=None, Ev=None):\n", " self.y = np.asarray(y).astype(int)\n", " self.p = sanitize_probs(self.y, p)[0]\n", " self.D = counts_matrix(dc) if D is None else D\n", " self.Ev = events_matrix(ec) if Ev is None else Ev\n", "\n", " def values(self, idx=None):\n", " idx = np.arange(self.y.size) if idx is None else np.asarray(idx)\n", " y, p = self.y[idx], self.p[idx]\n", " f1, macro, nmcc = binary(y, p)\n", " return {\"flow_dice\": dice_macro(self.D[idx]), \"evidence_f1\": evidence_macro(self.Ev[idx]), \"auroc\": auroc(y, p), \"f1\": f1, \"nmcc\": nmcc, \"conclusion_f1\": macro}\n", "\n", " def vec(self, idx=None):\n", " v = self.values(idx)\n", " return np.array([v[k] for k in KEYS])\n", "\n", "\n", "def boot_idx(groups, B, seed, strata=None):\n", " groups = np.asarray(groups)\n", " rng = np.random.default_rng(seed)\n", " if strata is None:\n", " uniq, inv = np.unique(groups, return_inverse=True)\n", " members = [np.flatnonzero(inv == k) for k in range(uniq.size)]\n", " for _ in range(B):\n", " pick = rng.integers(0, uniq.size, uniq.size)\n", " yield np.concatenate([members[k] for k in pick])\n", " return\n", " strata = np.asarray(strata)\n", " blocks = []\n", " for s in np.unique(strata):\n", " sel = np.flatnonzero(strata == s)\n", " uniq, inv = np.unique(groups[sel], return_inverse=True)\n", " blocks.append([sel[inv == k] for k in range(uniq.size)])\n", " for _ in range(B):\n", " out = []\n", " for members in blocks:\n", " pick = rng.integers(0, len(members), len(members))\n", " out.extend(members[k] for k in pick)\n", " yield np.concatenate(out)\n", "\n", "\n", "def ci_from(samples, point, alpha=0.05):\n", " a = np.asarray(samples, float)\n", " if a.ndim == 1:\n", " a = a[:, None]\n", " ok = np.all(np.isfinite(a), 1)\n", " a = a[ok]\n", " point = np.atleast_1d(np.asarray(point, float))\n", " if not a.shape[0]:\n", " return [{\"point\": float(p), \"lo\": None, \"hi\": None, \"n_boot\": 0} for p in point]\n", " lo, hi = np.quantile(a, [alpha / 2, 1 - alpha / 2], axis=0)\n", " return [{\"point\": float(point[j]), \"lo\": float(lo[j]), \"hi\": float(hi[j]), \"n_boot\": int(a.shape[0])} for j in range(point.size)]\n", "\n", "\n", "def boot(stat, groups, B=None, seed=C.SEED, strata=None):\n", " B = B or C.BOOT\n", " point = stat(np.arange(len(groups)))\n", " vals = []\n", " for idx in boot_idx(groups, B, seed, strata):\n", " try:\n", " vals.append(np.atleast_1d(stat(idx)))\n", " except Exception:\n", " continue\n", " return ci_from(np.asarray(vals) if vals else np.zeros((0, np.atleast_1d(point).size)), point)\n", "\n", "\n", "def excludes_zero(d):\n", " return d.get(\"lo\") is not None and (d[\"lo\"] > 0 or d[\"hi\"] < 0)\n", "\n", "\n", "def self_check():\n", " from .metrics import dice_counts, event_counts\n", " from .t4 import metric_values\n", " rng = np.random.default_rng(0)\n", " n = 40\n", " y = rng.integers(0, 2, n)\n", " p = rng.random(n)\n", " S = rng.integers(-1, 2, (n, 400))\n", " R = rng.integers(-1, 2, (n, 400))\n", " R[:, 100:160] = -1\n", " S[:, 110:170] = -1\n", " dc = [dice_counts(a, b) for a, b in zip(S, R)]\n", " ec = [event_counts(a, b) for a, b in zip(S, R)]\n", " ref = metric_values(y, p, dc, ec, np.arange(n))\n", " fast = Pack(y, p, dc, ec).values()\n", " for k in KEYS:\n", " assert abs(ref[k] - fast[k]) < 1e-9 or (np.isnan(ref[k]) and np.isnan(fast[k])), (k, ref[k], fast[k])\n", " return True" ] }, { "cell_type": "code", "execution_count": 23, "id": "90730f99a643", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.939537Z", "iopub.status.busy": "2026-11-28T14:17:32.939190Z", "iopub.status.idle": "2026-11-28T14:17:32.965914Z", "shell.execute_reply": "2026-11-28T14:17:32.964268Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/prob.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/prob.py\n", "import math\n", "import time\n", "\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "from scipy.optimize import linear_sum_assignment\n", "\n", "from . import config as C\n", "from .fastm import boot\n", "from .folds import inner_split\n", "from .io import events, fill_linear, valid\n", "from .metrics import crps_discrete, fhr_abs_errors, iou_matrix, risk_coverage, spearman\n", "from .t1 import Block, Data, meta, ref_fhr, sfx, summarize\n", "from .utils import (adaptive_batches, device, finalize_memmap, free_mem, get_logger, is_done, load_json, mark_done, mm, open_memmap_new,\n", " save_json, save_npz, seed_all, stage)\n", "\n", "MU0, SC0 = 140.0, 25.0\n", "QS = (0.05, 0.1, 0.25, 0.75, 0.9, 0.95)\n", "GRID = C.BPM.astype(np.float64)\n", "\n", "\n", "class LapNet(nn.Module):\n", " def __init__(self, cin=C.NB + 6, ch=128, k=5, dil=(1, 2, 4, 8, 16, 32, 1, 2, 4, 8), drop=0.1):\n", " super().__init__()\n", " self.inp = nn.Conv1d(cin, ch, 1)\n", " self.blocks = nn.Sequential(*[Block(ch, k, d, drop) for d in dil])\n", " self.out = nn.Conv1d(ch, 2, 1)\n", "\n", " def forward(self, x):\n", " o = self.out(self.blocks(self.inp(x)))\n", " return o[:, 0], o[:, 1].clamp(-6.0, 2.0)\n", "\n", "\n", "def fourier(t, n=16):\n", " f = torch.exp(torch.linspace(0, math.log(1000.0), n, device=t.device))\n", " a = t[:, None] * f[None] * 2 * math.pi\n", " return torch.cat([a.sin(), a.cos()], 1)\n", "\n", "\n", "class FlowNet(nn.Module):\n", " def __init__(self, cin=C.NB + 6, hc=64, ch=96, enc_dil=(1, 2, 4, 8, 16, 32), dil=(1, 2, 4, 8, 16, 32, 1, 2, 4, 8)):\n", " super().__init__()\n", " self.enc_in = nn.Conv1d(cin, 128, 1)\n", " self.enc = nn.Sequential(*[Block(128, 5, d, 0.1) for d in enc_dil])\n", " self.enc_out = nn.Conv1d(128, hc, 1)\n", " self.temb = nn.Sequential(nn.Linear(32, ch), nn.GELU(), nn.Linear(ch, ch))\n", " self.inp = nn.Conv1d(1 + hc, ch, 1)\n", " self.blocks = nn.ModuleList([Block(ch, 5, d, 0.0) for d in dil])\n", " self.film = nn.ModuleList([nn.Linear(ch, 2 * ch) for _ in dil])\n", " self.out = nn.Conv1d(ch, 1, 1)\n", " nn.init.zeros_(self.out.weight)\n", " nn.init.zeros_(self.out.bias)\n", "\n", " def encode(self, c):\n", " return self.enc_out(self.enc(self.enc_in(c)))\n", "\n", " def velocity(self, x, t, h):\n", " e = self.temb(fourier(t))\n", " z = self.inp(torch.cat([x, h], 1))\n", " for blk, fl in zip(self.blocks, self.film):\n", " g, b = fl(e).chunk(2, -1)\n", " z = blk(z) * (1 + g[..., None]) + b[..., None]\n", " return self.out(z)\n", "\n", "\n", "def batch_cont(data, rng, bs, L):\n", " xs, zs, ms = [], [], []\n", " for i in rng.choice(data.idx, bs):\n", " a = int(rng.integers(0, C.N - L + 1))\n", " r = data.ref[i, a:a + L]\n", " xs.append(data.x(i, a, a + L))\n", " zs.append((fill_linear(r) - MU0) / SC0)\n", " ms.append(valid(r))\n", " return torch.from_numpy(np.stack(xs)), torch.from_numpy(np.stack(zs).astype(np.float32)), torch.from_numpy(np.stack(ms))\n", "\n", "\n", "def lap_loss(model, x, z, mk):\n", " mu, lb = model(x)\n", " nll = (z - mu.float()).abs() / lb.float().exp() + lb.float()\n", " return (nll * mk).sum() / mk.sum().clamp_min(1)\n", "\n", "\n", "def fm_loss(model, x, z, mk):\n", " h = model.encode(x)\n", " x0 = torch.randn(z.shape, device=z.device)[:, None]\n", " t = torch.rand(z.shape[0], device=z.device)\n", " xt = (1 - t)[:, None, None] * x0 + t[:, None, None] * z[:, None]\n", " v = model.velocity(xt, t, h).float()\n", " l = ((v - (z[:, None] - x0)) ** 2)[:, 0]\n", " return (l * mk).sum() / mk.sum().clamp_min(1)\n", "\n", "\n", "@torch.no_grad()\n", "def lap_predict(model, data, idx, dev, log=None):\n", " model.eval()\n", "\n", " def fn(i, j):\n", " xs = torch.from_numpy(np.stack([data.x(r) for r in idx[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " mu, lb = model(xs)\n", " return (MU0 + SC0 * mu.float()).cpu().numpy(), (SC0 * lb.float().exp()).cpu().numpy()\n", "\n", " out = adaptive_batches(len(idx), fn, 8, log=log)\n", " return np.concatenate([o[0] for o in out]), np.concatenate([o[1] for o in out])\n", "\n", "\n", "@torch.no_grad()\n", "def fm_sample(model, x, K, steps, gen):\n", " B, _, n = x.shape\n", " h = model.encode(x).repeat_interleave(K, 0)\n", " z = torch.randn((B * K, 1, n), generator=gen, device=x.device)\n", " for s in range(steps):\n", " t = torch.full((B * K,), s / steps, device=x.device)\n", " z = z + model.velocity(z, t, h).float() / steps\n", " return (MU0 + SC0 * z[:, 0]).clamp(C.FHR_MIN, C.FHR_MAX).view(B, K, n)\n", "\n", "\n", "def fm_predict(model, data, idx, dev, K, steps, seed, log=None):\n", " model.eval()\n", " gen = torch.Generator(device=dev.type)\n", " gen.manual_seed(int(seed))\n", "\n", " def fn(i, j):\n", " xs = torch.from_numpy(np.stack([data.x(r) for r in idx[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " return fm_sample(model, xs, K, steps, gen).float().cpu().numpy().astype(np.float16)\n", "\n", " return np.concatenate(adaptive_batches(len(idx), fn, 4, log=log))\n", "\n", "\n", "def fm_val_loss(model, vdata, dev):\n", " model.eval()\n", " rng = np.random.default_rng(123)\n", " torch.manual_seed(123)\n", " tot, n = 0.0, 0\n", " with torch.no_grad():\n", " for _ in range(4 if C.SMOKE else 16):\n", " x, z, mk = batch_cont(vdata, rng, 8, 1024)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " tot += float(fm_loss(model, x.to(dev), z.to(dev), mk.to(dev).float()))\n", " n += 1\n", " return tot / max(1, n)\n", "\n", "\n", "def lap_val_rmse(model, vdata, va, dev, log):\n", " mu, _ = lap_predict(model, vdata, va, dev, log)\n", " e = np.concatenate([fhr_abs_errors(mu[k], vdata.ref[i])[0] for k, i in enumerate(va)])\n", " return float(np.sqrt(np.mean(e ** 2)))\n", "\n", "\n", "def train_prob(kind, force=False, fold=0):\n", " name = f\"s{'28_t1_laplace' if kind == 'laplace' else '29_t1_flow'}_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_PROB, \"kind\": kind, \"K\": C.K_FM, \"steps\": C.FM_STEPS}\n", " oof = C.CACHE / f\"t1_{kind}_oof_f{fold}.npz\"\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " seed_all(C.SEED + 500 + fold + (0 if kind == \"laplace\" else 50))\n", " dev = device()\n", " m = meta()\n", " tr, va = inner_split(m, fold)\n", " v_ok = np.array([valid(r).mean() for r in ref_fhr()])\n", " tr = tr[v_ok[tr] > 0.3]\n", " data = Data(tr)\n", " vdata = Data(va, (data.mu, data.sd))\n", " model = (LapNet() if kind == \"laplace\" else FlowNet()).to(dev)\n", " lossf = lap_loss if kind == \"laplace\" else fm_loss\n", " lr = 2e-3 if kind == \"laplace\" else 1e-3\n", " opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)\n", " steps = max(20, int(len(tr) * 4 / 32)) if not C.SMOKE else 10\n", " sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=C.EPOCHS_PROB * steps + 10, pct_start=0.1)\n", " scaler = torch.amp.GradScaler(enabled=dev.type == \"cuda\")\n", " d = C.MODELS / f\"t1_{kind}\" / f\"fold{fold}\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " st = {\"epoch\": 0, \"best\": math.inf, \"bad\": 0, \"bs\": 32, \"hist\": []}\n", " if (d / \"last.pt\").exists() and not force:\n", " ck = torch.load(d / \"last.pt\", map_location=dev, weights_only=False)\n", " for o, k in ((model, \"model\"), (opt, \"opt\"), (sched, \"sched\"), (scaler, \"scaler\")):\n", " o.load_state_dict(ck[k])\n", " st = ck[\"state\"]\n", " log.info(f\"resumed at epoch {st['epoch']}\")\n", " rng = np.random.default_rng(C.SEED + 700 + fold + st[\"epoch\"])\n", " while st[\"epoch\"] < C.EPOCHS_PROB and st[\"bad\"] < C.PATIENCE:\n", " model.train()\n", " t0 = time.time()\n", " tot = 0.0\n", " for _ in range(steps):\n", " x, z, mk = batch_cont(data, rng, st[\"bs\"], 1024)\n", " x, z, mk = x.to(dev), z.to(dev), mk.to(dev).float()\n", " try:\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " loss = lossf(model, x, z, mk)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " if sched.last_epoch < sched.total_steps - 1:\n", " sched.step()\n", " tot += float(loss)\n", " except RuntimeError as e:\n", " if \"out of memory\" not in str(e).lower() or st[\"bs\"] <= 2:\n", " raise\n", " opt.zero_grad(set_to_none=True)\n", " free_mem()\n", " st[\"bs\"] //= 2\n", " log.warning(f\"OOM: batch -> {st['bs']}\")\n", " vs = lap_val_rmse(model, vdata, va, dev, log) if kind == \"laplace\" else fm_val_loss(model, vdata, dev)\n", " st[\"epoch\"] += 1\n", " st[\"hist\"].append({\"epoch\": st[\"epoch\"], \"train_loss\": tot / steps, \"val\": vs, \"sec\": time.time() - t0})\n", " if vs < st[\"best\"] - 1e-4:\n", " st[\"best\"], st[\"bad\"] = vs, 0\n", " torch.save({\"model\": model.state_dict(), \"stats\": (data.mu, data.sd)}, d / \"best.tmp\")\n", " (d / \"best.tmp\").replace(d / \"best.pt\")\n", " else:\n", " st[\"bad\"] += 1\n", " torch.save({\"model\": model.state_dict(), \"opt\": opt.state_dict(), \"sched\": sched.state_dict(), \"scaler\": scaler.state_dict(), \"state\": st}, d / \"last.tmp\")\n", " (d / \"last.tmp\").replace(d / \"last.pt\")\n", " log.info(st[\"hist\"][-1])\n", " ck = torch.load(d / \"best.pt\", map_location=dev, weights_only=False)\n", " model.load_state_dict(ck[\"model\"])\n", " te = np.flatnonzero(m.fold.values == fold)\n", " tdata = Data(te, ck[\"stats\"])\n", " t0 = time.time()\n", " if kind == \"laplace\":\n", " mu, b = lap_predict(model, tdata, te, dev, log)\n", " save_npz(oof, idx=te, mu=mu.astype(np.float32), b=b.astype(np.float32))\n", " else:\n", " S = fm_predict(model, tdata, te, dev, C.K_FM, C.FM_STEPS, C.SEED + 900 + fold, log)\n", " save_npz(oof, idx=te, samples=S)\n", " inf_s = (time.time() - t0) / max(1, te.size)\n", " mark_done(name, params, {\"best_val\": st[\"best\"], \"epochs\": st[\"epoch\"], \"history\": st[\"hist\"], \"inference_s_per_record\": inf_s, \"seconds\": round(sum(h[\"sec\"] for h in st[\"hist\"]), 1)}, [d / \"best.pt\", oof])\n", "\n", "\n", "def train_laplace(force=False, fold=0):\n", " train_prob(\"laplace\", force, fold)\n", "\n", "\n", "def train_flow(force=False, fold=0):\n", " train_prob(\"flow\", force, fold)\n", "\n", "\n", "def lap_cdf(y, mu, b):\n", " z = (y - mu) / b\n", " return np.where(z < 0, 0.5 * np.exp(np.minimum(z, 0)), 1 - 0.5 * np.exp(-np.maximum(z, 0)))\n", "\n", "\n", "def lap_pmf(mu, b):\n", " edges = np.r_[-np.inf, GRID[:-1] + 0.5, np.inf]\n", " c = lap_cdf(edges[None, :], mu[:, None].astype(np.float64), np.maximum(b[:, None].astype(np.float64), 1e-3))\n", " p = np.diff(c, axis=1)\n", " p = np.clip(p, 0, None)\n", " return p / p.sum(1, keepdims=True)\n", "\n", "\n", "def quantiles_from_cdf(cdf, qs=QS):\n", " return np.stack([GRID[np.minimum((cdf < q).sum(-1), C.NB - 1)] for q in qs])\n", "\n", "\n", "def smooth_u(rng, k, n, sigma=40):\n", " from scipy.ndimage import gaussian_filter1d\n", " from scipy.special import ndtr\n", " z = gaussian_filter1d(rng.standard_normal((k, n + 8 * sigma)), sigma, axis=1)[:, 4 * sigma:4 * sigma + n]\n", " z /= np.sqrt(1.0 / (2.0 * np.sqrt(np.pi) * sigma))\n", " return ndtr(z)\n", "\n", "\n", "def copula_samples(cdf, u):\n", " return GRID[np.minimum((cdf[None] < u[:, :, None]).sum(-1), C.NB - 1)].astype(np.float32)\n", "\n", "\n", "def crps_samples(S, y):\n", " K = S.shape[0]\n", " a = np.abs(S - y[None]).mean(0)\n", " Ss = np.sort(S, 0)\n", " w = (2 * np.arange(1, K + 1) - K - 1)[:, None]\n", " b = (w * Ss).sum(0) * 2 / (K * (K - 1))\n", " return a - 0.5 * b\n", "\n", "\n", "def energy_score(S, y, v, win=C.ES_WIN):\n", " K = S.shape[0]\n", " out = []\n", " for a in range(0, y.size - win + 1, win):\n", " if not v[a:a + win].all():\n", " continue\n", " X = S[:, a:a + win].astype(np.float64)\n", " t = y[a:a + win].astype(np.float64)\n", " d1 = np.sqrt(((X - t[None]) ** 2).sum(1)).mean()\n", " D = np.sqrt(((X[:, None] - X[None]) ** 2).sum(-1))\n", " out.append(d1 - D.sum() / (2 * K * (K - 1)))\n", " return float(np.sum(out)), len(out)\n", "\n", "\n", "def event_detail(pred, ref, thr=0.3):\n", " out = []\n", " for k in (1, -1):\n", " P, R = events(pred, k), events(ref, k)\n", " mt = iou_matrix(np.asarray(P), np.asarray(R))\n", " tp, sh = 0, 0\n", " if mt.size:\n", " r, c = linear_sum_assignment(-mt)\n", " ok = mt[r, c] >= thr\n", " tp = int(ok.sum())\n", " sh = int((np.abs(P[r[ok], 0] - R[c[ok], 0]) / C.FS_FHR > C.SHIFT_S).sum())\n", " out += [tp, len(P) - tp, len(R) - tp, sh]\n", " return out\n", "\n", "\n", "EV_NAMES = [\"acc_tp\", \"acc_invented\", \"acc_lost\", \"acc_shifted\", \"dec_tp\", \"dec_invented\", \"dec_lost\", \"dec_shifted\"]\n", "\n", "\n", "TEMPS = np.exp(np.linspace(np.log(0.25), np.log(4.0), 33))\n", "\n", "\n", "def temper(P, T):\n", " Q = np.power(np.clip(P.astype(np.float64), 1e-12, None), 1.0 / T)\n", " return Q / Q.sum(1, keepdims=True)\n", "\n", "\n", "def pk_metrics(P, y):\n", " cdf = np.cumsum(P, 1)\n", " q = quantiles_from_cdf(cdf)\n", " cov = np.stack([(y >= q[lo]) & (y <= q[hi]) for lo, hi in ((2, 3), (1, 4), (0, 5))], 1)\n", " return crps_discrete(P, y), cov\n", "\n", "\n", "def recalibration(PK, R, fold, groups_all, log):\n", " y = np.concatenate(PK[\"y\"]).astype(np.float64)\n", " fd = fold[R]\n", " rng = np.random.default_rng(C.SEED + 31)\n", " out = {\"crps\": {}, \"cov\": {}}\n", " rep = {\"method\": \"temperature scaling p^(1/T) per outer fold, T chosen on the calibration fold (f+1) mod 5 by minimum CRPS on <= 100k points; evaluated on the same 300 points per record as the AURC\", \"temperature\": {}}\n", " for fam in (\"ens5\", \"tcn_seed0\"):\n", " P = np.concatenate(PK[f\"pm_{fam}\"]).astype(np.float64)\n", " P /= P.sum(1, keepdims=True)\n", " out[\"crps\"][fam], out[\"cov\"][fam] = pk_metrics(P, y)\n", " cr = np.zeros(y.size)\n", " cv = np.zeros((y.size, 3), bool)\n", " rep[\"temperature\"][fam] = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " cm = np.flatnonzero(fd == c)\n", " if cm.size > 100000:\n", " cm = rng.choice(cm, 100000, replace=False)\n", " te = np.flatnonzero(fd == f)\n", " if not cm.size or not te.size:\n", " continue\n", " best = min(TEMPS, key=lambda T: crps_discrete(temper(P[cm], T), y[cm]).mean())\n", " rep[\"temperature\"][fam][str(f)] = float(best)\n", " for a in range(0, te.size, 200000):\n", " s_ = te[a:a + 200000]\n", " cr[s_], cv[s_] = pk_metrics(temper(P[s_], best), y[s_])\n", " out[\"crps\"][f\"{fam}_recalibrated\"], out[\"cov\"][f\"{fam}_recalibrated\"] = cr, cv\n", " out[\"crps\"][\"laplace\"] = np.concatenate(PK[\"crps_laplace\"])\n", " out[\"crps\"][\"flow\"] = np.concatenate(PK[\"crps_flow\"])\n", " out[\"cov\"][\"laplace\"] = np.concatenate(PK[\"cov_laplace\"])\n", " out[\"cov\"][\"flow\"] = np.concatenate(PK[\"cov_flow\"])\n", " rep[\"on_points\"] = {k: {\"crps\": float(out[\"crps\"][k].mean()), **{f\"coverage{int(100 * l)}\": float(out[\"cov\"][k][:, j].mean()) for j, l in enumerate(C.COVER_LEVELS)}} for k in out[\"crps\"]}\n", " uniq, inv = np.unique(R, return_inverse=True)\n", " cnt = np.bincount(inv)\n", " rec_mean = {k: np.bincount(inv, weights=v) / cnt for k, v in out[\"crps\"].items()}\n", " g = groups_all[uniq]\n", " best_ens = min((\"ens5\", \"ens5_recalibrated\"), key=lambda k: rec_mean[k].mean())\n", " rep[\"best_ensemble_variant\"] = best_ens\n", " rep[\"paired_crps_vs_best_ensemble\"] = {k: boot(lambda i, k=k: rec_mean[k][i].mean() - rec_mean[best_ens][i].mean(), g)[0] for k in rec_mean if k != best_ens}\n", " log.info(f\"recalibration: {rep['temperature']} best {best_ens}\")\n", " return {\"report\": rep, \"flow_minus_best_ensemble\": rep[\"paired_crps_vs_best_ensemble\"][\"flow\"], \"best_ensemble_crps\": float(rec_mean[best_ens].mean())}\n", "\n", "\n", "def load_oof(kind, n):\n", " out = {}\n", " for f in range(C.N_FOLDS):\n", " p = C.CACHE / f\"t1_{kind}_oof_f{f}.npz\"\n", " if p.exists():\n", " with np.load(p) as z:\n", " arrs = {kk: z[kk] for kk in z.files}\n", " for k, i in enumerate(arrs[\"idx\"]):\n", " out[int(i)] = {kk: v[k] for kk, v in arrs.items() if kk != \"idx\"}\n", " return out\n", "\n", "\n", "@torch.no_grad()\n", "def timing(dev, log):\n", " from .t1 import TCN as T\n", " m = meta()\n", " te = np.flatnonzero(m.fold.values == 0)[:16]\n", " if not te.size:\n", " return {}\n", " res = {}\n", "\n", " def sync():\n", " if dev.type == \"cuda\":\n", " torch.cuda.synchronize()\n", "\n", " def bench(fn, label):\n", " if dev.type == \"cuda\":\n", " torch.cuda.reset_peak_memory_stats()\n", " fn()\n", " sync()\n", " t0 = time.time()\n", " fn()\n", " sync()\n", " res[label] = {\"s_per_record\": (time.time() - t0) / te.size, \"peak_gpu_gb\": torch.cuda.max_memory_allocated() / 2 ** 30 if dev.type == \"cuda\" else None}\n", "\n", " members = []\n", " for s in range(C.T1_SEEDS_FAMILY):\n", " p = C.MODELS / \"t1_tcn\" / f\"fold0{sfx(s)}\" / \"best.pt\"\n", " if p.exists():\n", " ck = torch.load(p, map_location=dev, weights_only=False)\n", " mdl = T().to(dev).eval()\n", " mdl.load_state_dict(ck[\"model\"])\n", " members.append((mdl, Data(te, ck[\"stats\"])))\n", " if not members:\n", " return {}\n", " xs = [torch.from_numpy(np.stack([d.x(r) for r in te])).to(dev) for _, d in members]\n", "\n", " def run_members(k):\n", " for (mdl, _), x in zip(members[:k], xs):\n", " for a in range(0, te.size, 4):\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " p = torch.softmax(mdl(x[a:a + 4]).float(), 1).transpose(1, 2)\n", " summarize(p)\n", "\n", " bench(lambda: run_members(1), \"tcn_single\")\n", " bench(lambda: run_members(len(members)), f\"tcn_ensemble_{len(members)}\")\n", " for kind, cls in ((\"laplace\", LapNet), (\"flow\", FlowNet)):\n", " p = C.MODELS / f\"t1_{kind}\" / \"fold0\" / \"best.pt\"\n", " if not p.exists():\n", " continue\n", " ck = torch.load(p, map_location=dev, weights_only=False)\n", " mdl = cls().to(dev).eval()\n", " mdl.load_state_dict(ck[\"model\"])\n", " x = torch.from_numpy(np.stack([Data(te, ck[\"stats\"]).x(r) for r in te])).to(dev)\n", " if kind == \"laplace\":\n", " def fn(mdl=mdl, x=x):\n", " for a in range(0, te.size, 4):\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " mdl(x[a:a + 4])\n", " else:\n", " gen = torch.Generator(device=dev.type)\n", " gen.manual_seed(0)\n", "\n", " def fn(mdl=mdl, x=x, gen=gen):\n", " for a in range(0, te.size, 2):\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " fm_sample(mdl, x[a:a + 2], C.K_FM, C.FM_STEPS, gen)\n", " bench(fn, kind)\n", " res[\"n_members\"] = len(members)\n", " return res\n", "\n", "\n", "@stage(\"s30_t1_families\", params={\"v\": 3}, outputs=[C.CACHE / \"t1_ens5.npy\"])\n", "def families(log):\n", " from .sel import ENS_COLS, E, ens, summarize_np\n", " from .t2 import load_ft4, post, predict_probs\n", " dev = device()\n", " m = meta()\n", " n = len(m)\n", " ref = ref_fhr()\n", " seeds = [s for s in range(C.T1_SEEDS_FAMILY) if all((C.CACHE / f\"t1_tcn_probs_f{f}{sfx(s)}.npy\").exists() for f in range(C.N_FOLDS))]\n", " if seeds != list(range(C.T1_SEEDS_FAMILY)):\n", " raise RuntimeError(f\"incomplete TCN seeds for the family comparison: found {seeds}, expected {list(range(C.T1_SEEDS_FAMILY))}\")\n", " A3 = ens()\n", " AF = np.asarray(mm(C.CACHE / \"t1_af.npy\"), np.float32)\n", " G = np.asarray(mm(C.CACHE / \"t1_risk_g.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " sg_ok = np.load(C.CACHE / \"t4_segp_est_ok.npy\")\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " LAP = load_oof(\"laplace\", n)\n", " FM = load_oof(\"flow\", n)\n", " fold = m.fold.values\n", " ok = np.flatnonzero((fold >= 0) & np.isin(np.arange(n), list(LAP)) & np.isin(np.arange(n), list(FM)))\n", " if ok.size < (fold >= 0).sum():\n", " log.warning(f\"{(fold >= 0).sum() - ok.size} out-of-fold records lack Laplace or flow predictions\")\n", " out, tp_, pp_ = open_memmap_new(C.CACHE / \"t1_ens5.npy\", (n, C.N, len(ENS_COLS)), np.float32, np.nan)\n", " EST = [\"autofhr\", \"tcn_seed0\", \"ens3\", \"ens5\", \"laplace\", \"flow\"]\n", " DIST = [\"tcn_seed0\", \"ens5\", \"laplace\", \"flow\"]\n", " SCORES = [\"disagreement_window_sd\", \"seed0_p_far\", \"ens3_p_far\", \"ens5_member_sd\", \"ens5_mutual_info\", \"ens5_p_far\", \"laplace_p_far\", \"laplace_scale\", \"flow_p_far\", \"flow_sd\", \"residual_g\"]\n", " OWN = {\"disagreement_window_sd\": \"autofhr\", \"seed0_p_far\": \"tcn_seed0\", \"ens3_p_far\": \"ens3\", \"ens5_member_sd\": \"ens5\", \"ens5_mutual_info\": \"ens5\", \"ens5_p_far\": \"ens5\", \"laplace_p_far\": \"laplace\", \"laplace_scale\": \"laplace\", \"flow_p_far\": \"flow\", \"flow_sd\": \"flow\", \"residual_g\": \"ens3\"}\n", " rec = {k: np.full(n, np.nan) for k in [f\"{e}_{s}\" for e in EST for s in (\"sse\", \"sae\", \"nbig\", \"npts\")] + [f\"{d}_{s}\" for d in DIST for s in (\"crps\", \"crps_k\", \"es\", \"nes\") + tuple(f\"cov{int(100 * l)}\" for l in C.COVER_LEVELS) + tuple(f\"wid{int(100 * l)}\" for l in C.COVER_LEVELS)]}\n", " evn = {k: np.full((n, 8), np.nan) for k in [f\"{d}_traj\" for d in DIST] + [f\"{d}_point\" for d in DIST]}\n", " pts_s, pts_l, pts_own, pts_rec = [], [], [], []\n", " PK = {\"pm_ens5\": [], \"pm_tcn_seed0\": [], \"y\": [], \"crps_laplace\": [], \"crps_flow\": [], \"cov_laplace\": [], \"cov_flow\": []}\n", " rng = np.random.default_rng(C.SEED + 30)\n", " models = {}\n", " ok_set = set(ok.tolist())\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(fold == f)\n", " Ps = [np.load(C.CACHE / f\"t1_tcn_probs_f{f}{sfx(s)}.npy\", mmap_mode=\"r\") for s in seeds]\n", " if f not in models and (C.MODELS / \"t2_ft4\" / f\"fold{f}\" / \"best.pt\").exists():\n", " models = {f: load_ft4(f, dev)}\n", " for a in range(0, te.size, 16):\n", " P = np.stack([np.asarray(p[a:a + 16], np.float32) for p in Ps])\n", " seqs, owners = [], []\n", " for k in range(P.shape[1]):\n", " i = int(te[a + k])\n", " summ, mix = summarize_np(P[:, k])\n", " out[i] = summ\n", " if i not in ok_set:\n", " continue\n", " r = ref[i]\n", " v = valid(r)\n", " if not v.any():\n", " continue\n", " pick = np.sort(rng.choice(np.flatnonzero(v), size=min(C.POINTS_PER_RECORD, int(v.sum())), replace=False))\n", " lap = LAP[i]\n", " fm = FM[i][\"samples\"].astype(np.float32)\n", " p0 = P[0, k] / P[0, k].sum(-1, keepdims=True)\n", " pl = lap_pmf(lap[\"mu\"], lap[\"b\"])\n", " pmfs = {\"tcn_seed0\": p0, \"ens5\": mix, \"laplace\": pl}\n", " u = smooth_u(rng, C.K_FM, C.N)\n", " samples, medians, qd, pfar = {}, {}, {}, {}\n", " for d, pm in pmfs.items():\n", " cdf = np.cumsum(pm, -1)\n", " q = quantiles_from_cdf(cdf)\n", " medians[d] = GRID[np.minimum((cdf < 0.5).sum(-1), C.NB - 1)].astype(np.float32)\n", " qd[d] = q\n", " far = np.abs(GRID[None, :] - medians[d][:, None]) > C.BIG_ERR\n", " pfar[d] = (pm * far).sum(-1)\n", " samples[d] = copula_samples(cdf, u)\n", " rec[f\"{d}_crps\"][i] = float(crps_discrete(pm[v].astype(np.float64), r[v]).mean())\n", " samples[\"flow\"] = fm\n", " medians[\"flow\"] = np.median(fm, 0)\n", " qd[\"flow\"] = np.quantile(fm, QS, axis=0)\n", " pfar[\"flow\"] = np.mean(np.abs(fm - medians[\"flow\"][None]) > C.BIG_ERR, 0)\n", " rec[\"flow_crps\"][i] = float(crps_samples(fm[:, v], r[v]).mean())\n", " for d in DIST:\n", " S = samples[d]\n", " rec[f\"{d}_crps_k\"][i] = float(crps_samples(S[:, v], r[v]).mean())\n", " es, nes = energy_score(S, np.nan_to_num(r), v)\n", " rec[f\"{d}_es\"][i], rec[f\"{d}_nes\"][i] = es, nes\n", " for lvl, (lo_q, hi_q) in zip(C.COVER_LEVELS, ((2, 3), (1, 4), (0, 5))):\n", " lo, hi = qd[d][lo_q][v], qd[d][hi_q][v]\n", " rec[f\"{d}_cov{int(100 * lvl)}\"][i] = float(np.mean((r[v] >= lo) & (r[v] <= hi)))\n", " rec[f\"{d}_wid{int(100 * lvl)}\"][i] = float(np.mean(hi - lo))\n", " est = {\"autofhr\": AF[i, :, 0], \"tcn_seed0\": medians[\"tcn_seed0\"], \"ens3\": A3[i, :, E[\"median\"]], \"ens5\": summ[:, E[\"median\"]], \"laplace\": lap[\"mu\"], \"flow\": medians[\"flow\"]}\n", " errs = {}\n", " for e_, x in est.items():\n", " e, _ = fhr_abs_errors(fill_linear(x), r)\n", " errs[e_] = e\n", " rec[f\"{e_}_sse\"][i], rec[f\"{e_}_sae\"][i], rec[f\"{e_}_nbig\"][i], rec[f\"{e_}_npts\"][i] = float((e ** 2).sum()), float(e.sum()), float((e > C.BIG_ERR).sum()), float(e.size)\n", " vi = np.flatnonzero(v)\n", " pos = np.searchsorted(vi, pick)\n", " sc = {\"disagreement_window_sd\": np.nan_to_num(AF[i, :, 1], nan=50.0), \"seed0_p_far\": pfar[\"tcn_seed0\"], \"ens3_p_far\": A3[i, :, E[\"p_far\"]], \"ens5_member_sd\": summ[:, E[\"member_sd\"]], \"ens5_mutual_info\": summ[:, E[\"mutual_info\"]], \"ens5_p_far\": summ[:, E[\"p_far\"]], \"laplace_p_far\": pfar[\"laplace\"], \"laplace_scale\": lap[\"b\"], \"flow_p_far\": pfar[\"flow\"], \"flow_sd\": fm.std(0), \"residual_g\": np.nan_to_num(G[i], nan=1.0)}\n", " pts_s.append(np.stack([np.asarray(sc[s_], np.float32)[pick] for s_ in SCORES], 1))\n", " pts_l.append(errs[\"ens3\"][pos])\n", " pts_own.append(np.stack([errs[OWN[s_]][pos] for s_ in SCORES], 1))\n", " pts_rec.append(np.full(pick.size, i))\n", " PK[\"pm_ens5\"].append(mix[pick].astype(np.float16))\n", " PK[\"pm_tcn_seed0\"].append(p0[pick].astype(np.float16))\n", " PK[\"y\"].append(r[pick].astype(np.float32))\n", " PK[\"crps_laplace\"].append(crps_discrete(pl[pick].astype(np.float64), r[pick]))\n", " PK[\"crps_flow\"].append(crps_samples(fm[:, pick], r[pick]))\n", " for d in (\"laplace\", \"flow\"):\n", " PK[f\"cov_{d}\"].append(np.stack([(r[pick] >= qd[d][lo_q][pick]) & (r[pick] <= qd[d][hi_q][pick]) for lo_q, hi_q in ((2, 3), (1, 4), (0, 5))], 1))\n", " if sg_ok[i] and f in models:\n", " for d in DIST:\n", " for kk in range(min(C.K_EVENTS, samples[d].shape[0])):\n", " seqs.append(samples[d][kk])\n", " owners.append((i, f\"{d}_traj\"))\n", " seqs.append(medians[d])\n", " owners.append((i, f\"{d}_point\"))\n", " if seqs:\n", " pr = predict_probs(models[f], np.stack(seqs).astype(np.float32), dev, log)\n", " lab = post(np.nan_to_num(pr.astype(np.float32)), *pp[str(f)])\n", " acc = {}\n", " for (i, key), L in zip(owners, lab):\n", " acc.setdefault((i, key), []).append(event_detail(L, Sref[i]))\n", " for (i, key), rows in acc.items():\n", " evn[key][i] = np.mean(rows, 0)\n", " log.info(f\"fold {f} records {a + P.shape[1]}/{te.size}\")\n", " del Ps\n", " free_mem()\n", " finalize_memmap(out, tp_, pp_)\n", " X = np.concatenate(pts_s)\n", " recal = recalibration(PK, np.concatenate(pts_rec), fold, m.group.values, log)\n", " Lc = np.concatenate(pts_l)\n", " Lo = np.concatenate(pts_own)\n", " R = np.concatenate(pts_rec)\n", " grp = m.group.values[R]\n", " fd = fold[R]\n", " yc = (Lc > C.BIG_ERR).astype(float)\n", " yo = (Lo > C.BIG_ERR).astype(float)\n", " rep = {\"seeds\": seeds, \"n_records\": int(ok.size), \"points_for_aurc\": int(R.size), \"K_samples\": C.K_FM, \"flow_steps\": C.FM_STEPS, \"K_event_trajectories\": C.K_EVENTS, \"families\": {\"disagreement\": \"AutoFHR window SD (dispersion of overlapping-window estimates)\", \"ensemble\": f\"{len(seeds)}-seed TCN ensemble: member SD, mutual information, mixture p_far\", \"probabilistic\": \"161-class TCN (seed 0), heteroscedastic Laplace TCN, conditional flow matching (K trajectories)\", \"residual_risk\": \"out-of-fold learned g (weeks 3-5, frozen)\"}, \"notes\": \"intervals of the 161-class, ensemble and Laplace distributions use exact quantiles; flow-matching intervals use empirical quantiles of its K trajectories, which narrows them when K is small; CRPS (K samples) and the energy score use the same K for every family\"}\n", " recs = ok\n", " rg = m.group.values[recs]\n", " pt = {}\n", " for e_ in EST:\n", " sse, sae, nb, npts = (rec[f\"{e_}_{s}\"][recs] for s in (\"sse\", \"sae\", \"nbig\", \"npts\"))\n", " pt[e_] = {\"rmse\": float(np.sqrt(np.nansum(sse) / np.nansum(npts))), \"mae\": float(np.nansum(sae) / np.nansum(npts)), \"big_rate\": float(np.nansum(nb) / np.nansum(npts))}\n", " rep[\"point_accuracy\"] = pt\n", " pr_ = {}\n", " for d in DIST:\n", " r_ = {\"crps_exact_or_sample\": float(np.nanmean(rec[f\"{d}_crps\"][recs])), \"crps_sample_K\": float(np.nanmean(rec[f\"{d}_crps_k\"][recs])), \"energy_score_60s\": float(np.nansum(rec[f\"{d}_es\"][recs]) / max(1, np.nansum(rec[f\"{d}_nes\"][recs])))}\n", " for lvl in C.COVER_LEVELS:\n", " r_[f\"coverage{int(100 * lvl)}\"] = float(np.nanmean(rec[f\"{d}_cov{int(100 * lvl)}\"][recs]))\n", " r_[f\"width{int(100 * lvl)}\"] = float(np.nanmean(rec[f\"{d}_wid{int(100 * lvl)}\"][recs]))\n", " pr_[d] = r_\n", " rep[\"probabilistic_quality\"] = pr_\n", "\n", " def crps_diff(i, a, b):\n", " return np.nanmean(rec[f\"{a}_crps_k\"][recs][i]) - np.nanmean(rec[f\"{b}_crps_k\"][recs][i])\n", "\n", " def es_diff(i, a, b):\n", " return np.nansum(rec[f\"{a}_es\"][recs][i]) / max(1, np.nansum(rec[f\"{a}_nes\"][recs][i])) - np.nansum(rec[f\"{b}_es\"][recs][i]) / max(1, np.nansum(rec[f\"{b}_nes\"][recs][i]))\n", "\n", " rep[\"paired_vs_ens5\"] = {d: {\"crps_sample_K\": boot(lambda i, d=d: crps_diff(i, d, \"ens5\"), rg)[0], \"energy_score\": boot(lambda i, d=d: es_diff(i, d, \"ens5\"), rg)[0]} for d in DIST if d != \"ens5\"}\n", " rc = {}\n", " for j, s_ in enumerate(SCORES):\n", " a = risk_coverage(X[:, j], yc)\n", " b = risk_coverage(X[:, j], yo[:, j])\n", " rc[s_] = {\"common_estimator_ens3\": {k: a[k] for k in (\"aurc\", \"aurc_oracle\", \"risk_full\", \"risk@0.9\", \"risk@0.8\", \"risk@0.7\")}, \"own_estimator\": {\"estimator\": OWN[s_], **{k: b[k] for k in (\"aurc\", \"aurc_oracle\", \"risk_full\", \"risk@0.9\", \"risk@0.8\", \"risk@0.7\")}}, \"spearman_abs_err_common\": spearman(X[:, j], Lc)}\n", " rep[\"selective\"] = rc\n", " ref_j = SCORES.index(\"disagreement_window_sd\")\n", "\n", " def rel(i, j, jr, y):\n", " return risk_coverage(X[i, j], y[i])[\"aurc\"] / max(risk_coverage(X[i, jr], y[i])[\"aurc\"], 1e-12) - 1\n", "\n", " Bsel = min(C.BOOT, 400)\n", " s6 = {\"criterion\": f\"programme S6: AURC (common estimator, |e|>10 bpm) of the residual-risk score or of the ensemble score at least {int(100 * C.S6_REL)}% below that of the disagreement score; passed when the upper 95% CI of the relative change is below -{C.S6_REL} pooled and in >= 4 of 5 folds\", \"candidates\": {}}\n", " for s_ in (\"residual_g\", \"ens5_member_sd\", \"ens5_mutual_info\", \"ens5_p_far\"):\n", " j = SCORES.index(s_)\n", " pooled = boot(lambda i, j=j: rel(i, j, ref_j, yc), grp, B=Bsel)[0]\n", " per = {}\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fd == f)\n", " if sel_.size:\n", " per[str(f)] = boot(lambda i, j=j, sel_=sel_: rel(sel_[i], j, ref_j, yc), grp[sel_], B=min(Bsel, 200))[0]\n", " nf = sum(1 for b in per.values() if b[\"hi\"] is not None and b[\"hi\"] < -C.S6_REL)\n", " s6[\"candidates\"][s_] = {\"pooled_rel_aurc_vs_disagreement\": pooled, \"per_fold\": per, \"folds_passing\": nf, \"passed\": bool(pooled[\"hi\"] is not None and pooled[\"hi\"] < -C.S6_REL and nf >= 4)}\n", " s6[\"passed\"] = bool(any(v[\"passed\"] for v in s6[\"candidates\"].values()))\n", " s6[\"decision\"] = \"a learned or ensemble score beats the disagreement baseline by the pre-registered margin\" if s6[\"passed\"] else \"no learned or ensemble score beats the disagreement baseline by 15%: Article 2 reports the disagreement score with its limits\"\n", " rep[\"gate_S6_programme\"] = s6\n", " ev = {}\n", " for key, arr in evn.items():\n", " sel_ = np.isfinite(arr[:, 0])\n", " if not sel_.any():\n", " continue\n", " s = np.nansum(arr[sel_], 0)\n", " d = dict(zip(EV_NAMES, s.tolist()))\n", " hours = sel_.sum() * C.N / C.FS_FHR / 3600\n", " for c in (\"acc\", \"dec\"):\n", " nref = d[f\"{c}_tp\"] + d[f\"{c}_lost\"]\n", " d[f\"{c}_invented_per_hour\"] = d[f\"{c}_invented\"] / hours\n", " d[f\"{c}_lost_frac\"] = d[f\"{c}_lost\"] / nref if nref else None\n", " d[f\"{c}_shifted_frac_of_matched\"] = d[f\"{c}_shifted\"] / d[f\"{c}_tp\"] if d[f\"{c}_tp\"] else None\n", " den = 2 * d[f\"{c}_tp\"] + d[f\"{c}_invented\"] + d[f\"{c}_lost\"]\n", " d[f\"{c}_f1\"] = 2 * d[f\"{c}_tp\"] / den if den else None\n", " d[\"records\"] = int(sel_.sum())\n", " ev[key] = d\n", " rep[\"events\"] = ev\n", "\n", " def ev_err(i, key):\n", " arr = evn[key][recs][i]\n", " s = np.nansum(arr, 0)\n", " return (s[1] + s[2] + s[5] + s[6]) / max(1.0, s[0] + s[2] + s[4] + s[6])\n", "\n", " has_ev = np.isfinite(evn[\"flow_traj\"][recs][:, 0]) & np.isfinite(evn[\"ens5_traj\"][recs][:, 0])\n", " ev_cmp = None\n", " if has_ev.sum() >= 4:\n", " sel_ = np.flatnonzero(has_ev)\n", " ev_cmp = boot(lambda i: ev_err(sel_[i], \"flow_traj\") - ev_err(sel_[i], \"ens5_traj\"), rg[sel_])[0]\n", " rep[\"events_flow_minus_ens5_error_per_ref_event\"] = ev_cmp\n", " tm = timing(dev, log)\n", " rep[\"inference_cost\"] = tm\n", " tr_s = {}\n", " for pat in (\"s10_t1_tcn_f\", \"s28_t1_laplace_f\", \"s29_t1_flow_f\"):\n", " tr_s[pat.split(\"_\", 1)[1].rstrip(\"_f\")] = float(sum((load_json(p) or {}).get(\"info\", {}).get(\"seconds\", 0) or 0 for p in C.STATE.glob(f\"{pat}*.done.json\")))\n", " rep[\"training_seconds_total\"] = tr_s\n", " ens_key = [k for k in tm if k.startswith(\"tcn_ensemble\")]\n", " ratio = tm[\"flow\"][\"s_per_record\"] / max(tm[ens_key[0]][\"s_per_record\"], 1e-9) if (\"flow\" in tm and ens_key) else None\n", " best_ens = min((\"ens5_member_sd\", \"ens5_mutual_info\", \"ens5_p_far\"), key=lambda s_: rc[s_][\"common_estimator_ens3\"][\"aurc\"])\n", " jf, je = SCORES.index(\"flow_p_far\"), SCORES.index(best_ens)\n", " fm_aurc = boot(lambda i: rel(i, jf, je, yc), grp, B=Bsel)[0]\n", " rep[\"recalibration\"] = recal[\"report\"]\n", " crps_fm = recal[\"flow_minus_best_ensemble\"]\n", " wins = {\"crps\": bool(crps_fm and crps_fm[\"hi\"] is not None and crps_fm[\"hi\"] < 0), \"aurc\": bool(fm_aurc[\"hi\"] is not None and fm_aurc[\"hi\"] < 0), \"events\": bool(ev_cmp and ev_cmp[\"hi\"] is not None and ev_cmp[\"hi\"] < 0)}\n", " crps_ref = recal[\"best_ensemble_crps\"]\n", " noninf = {\"crps\": bool(crps_fm and crps_fm[\"hi\"] is not None and crps_fm[\"hi\"] <= 0.05 * crps_ref), \"aurc\": bool(fm_aurc[\"hi\"] is not None and fm_aurc[\"hi\"] <= 0.05), \"events\": bool(ev_cmp is None or (ev_cmp[\"hi\"] is not None and ev_cmp[\"hi\"] <= 0.05))}\n", " dominates = bool(any(wins.values()) and all(noninf.values()))\n", " rep[\"gate_S6_flow_matching\"] = {\"criterion\": f\"flow matching retained only if it dominates the {len(seeds)}-seed ensemble on the quality-cost frontier: better CRPS than the best of the raw and the temperature-recalibrated ensemble (exact CRPS for distributions, unbiased K-sample CRPS for flow matching, same points), or AURC (p_far vs best ensemble score), or event errors on sampled trajectories (upper 95% CI < 0), with inference time <= {C.FM_TIME_RATIO} x the ensemble. Amendment fixed before the full run: domination also requires non-inferiority on the other two axes (upper CI of the degradation <= 5% of the ensemble CRPS, <= +5% relative AURC, <= +0.05 event errors per reference event)\", \"flow_vs_ensemble_time_ratio\": ratio, \"crps_diff\": crps_fm, \"rel_aurc_vs_best_ensemble_score\": fm_aurc, \"best_ensemble_score\": best_ens, \"event_error_diff\": ev_cmp, \"wins\": wins, \"non_inferior\": noninf, \"time_ok\": bool(ratio is not None and ratio <= C.FM_TIME_RATIO), \"retained\": bool(dominates and ratio is not None and ratio <= C.FM_TIME_RATIO)}\n", " rep[\"gate_S6_flow_matching\"][\"decision\"] = \"flow matching retained as the probabilistic estimator of Article 2\" if rep[\"gate_S6_flow_matching\"][\"retained\"] else \"flow matching reported as tried (paragraph only)\"\n", " save_json(C.RES / \"s30_t1_families.json\", rep)\n", " return {\"S6_programme\": s6[\"passed\"], \"FM_retained\": rep[\"gate_S6_flow_matching\"][\"retained\"], \"rmse\": {k: round(v[\"rmse\"], 3) for k, v in pt.items()}}" ] }, { "cell_type": "code", "execution_count": 24, "id": "a1d190c7844e", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.970480Z", "iopub.status.busy": "2026-11-28T14:17:32.970078Z", "iopub.status.idle": "2026-11-28T14:17:32.988686Z", "shell.execute_reply": "2026-11-28T14:17:32.987054Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/sel2.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/sel2.py\n", "import pickle\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .fastm import Pack, boot\n", "from .folds import inner_split\n", "from .io import events, fill_linear, valid\n", "from .metrics import binary_scores, dice_counts, event_counts, fhr_abs_errors, t1_scores\n", "from .t1 import meta, ref_fhr\n", "from .utils import device, get_logger, is_done, load_df, load_json, mm, save_json, save_npy, stage\n", "\n", "FB_NAMES = [\"interpolation\", \"autocorrelation\", \"ensemble_median\"]\n", "FB_FEATS = [\"zone_len_s\", \"pos_frac\", \"dist_edge_s\", \"p_far\", \"member_sd\", \"q_prom\", \"q_peak\", \"d_interp_med\", \"d_acorr_med\", \"d_interp_acorr\", \"brady_pred\", \"g\", \"acorr_missing\", \"interp_missing\"]\n", "STATUS = {0: \"estimate\", 1: \"flag\", 2: \"abstain_reliable_fallback\", 3: \"abstain_no_reliable_fallback\"}\n", "\n", "\n", "def zone_fallbacks(est, acbpm, ab):\n", " n = est.size\n", " fi = np.full(n, np.nan, np.float32)\n", " zl = np.zeros(n, np.float32)\n", " pf = np.zeros(n, np.float32)\n", " de = np.zeros(n, np.float32)\n", " for a, b in events(ab.astype(np.int8), 1):\n", " L = b - a\n", " zl[a:b] = L / C.FS_FHR\n", " t = np.arange(L)\n", " pf[a:b] = (t + 0.5) / L\n", " de[a:b] = np.minimum(t + 1, L - t) / C.FS_FHR\n", " if L <= C.FALLBACK_INTERP_MAX_S * C.FS_FHR:\n", " lv = est[a - 1] if a > 0 else (est[b] if b < n else np.nan)\n", " rv = est[b] if b < n else lv\n", " fi[a:b] = lv + (rv - lv) * (t + 1) / (L + 1)\n", " fa = np.asarray(acbpm, np.float32).copy()\n", " fa[~valid(fa)] = np.nan\n", " return fi, fa, zl, pf, de\n", "\n", "\n", "def zone_features(i, ab, est, A, Q, G):\n", " from .sel import E\n", " q = np.asarray(Q[i], np.float32)\n", " fi, fa, zl, pf, de = zone_fallbacks(est, q[:, 5], ab)\n", " fm = est\n", " cols = [zl, pf, de, A[i, :, E[\"p_far\"]], A[i, :, E[\"member_sd\"]], q[:, 2], q[:, 1], np.nan_to_num(np.abs(fi - fm), nan=-1), np.nan_to_num(np.abs(fa - fm), nan=-1), np.nan_to_num(np.abs(fi - fa), nan=-1), (fm < C.BRADY).astype(np.float32), np.nan_to_num(G[i], nan=1.0), np.isnan(fa).astype(np.float32), np.isnan(fi).astype(np.float32)]\n", " return np.nan_to_num(np.stack(cols, 1).astype(np.float32)), np.stack([fi, fa, fm], 1)\n", "\n", "\n", "def fit_fallback_models(X, Y, AV, fd, log):\n", " from .sel import crc_threshold, hgb\n", " models, thr = {}, {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " models[f], thr[f] = {}, {}\n", " for k in range(len(FB_NAMES)):\n", " tr = (fd != f) & (fd != c) & AV[:, k]\n", " cm = (fd == c) & AV[:, k]\n", " if tr.sum() < 200 or np.unique(Y[tr, k]).size < 2:\n", " base = float(Y[tr, k].mean()) if tr.any() else 1.0\n", " models[f][k] = (\"constant\", base)\n", " thr[f][k] = base if (cm.any() and Y[cm, k].mean() <= C.ALPHA_FLAG) else -np.inf\n", " continue\n", " mdl = hgb().fit(X[tr], Y[tr, k])\n", " models[f][k] = (\"hgb\", mdl)\n", " thr[f][k] = crc_threshold(mdl.predict_proba(X[cm])[:, 1], Y[cm, k], C.ALPHA_FLAG) if cm.sum() >= 50 else -np.inf\n", " return models, thr\n", "\n", "\n", "def predict_risk(entry, X):\n", " kind, obj = entry\n", " return np.full(len(X), obj) if kind == \"constant\" else obj.predict_proba(X)[:, 1]\n", "\n", "\n", "def apply_fallback(models_f, thr_f, X, FB, act):\n", " ab = act == 2\n", " n = act.size\n", " risk = np.full((n, len(FB_NAMES)), np.inf)\n", " for k in range(len(FB_NAMES)):\n", " av = ab & np.isfinite(FB[:, k])\n", " if av.any():\n", " risk[av, k] = predict_risk(models_f[k], X[av])\n", " choice = np.full(n, -1, np.int8)\n", " choice[ab] = np.argmin(risk[ab], 1)\n", " chosen_risk = np.where(ab, risk[np.arange(n), np.maximum(choice, 0)], np.inf)\n", " chosen_thr = np.array([thr_f[int(c)] if c >= 0 else -np.inf for c in choice])\n", " status = act.astype(np.int8).copy()\n", " status[ab] = np.where(chosen_risk[ab] <= chosen_thr[ab], 2, 3)\n", " return choice, status, chosen_risk\n", "\n", "\n", "@stage(\"s31_t1_fallbacks\", params={\"v\": 1}, outputs=[C.CACHE / \"t1_status.npy\", C.CACHE / \"t1_final_fhr.npy\", C.MODELS / \"policy\" / \"fallback.pkl\"])\n", "def fallbacks(log):\n", " from .sel import E, ens\n", " m = meta()\n", " ref = ref_fhr()\n", " A = ens()\n", " Q = mm(C.CACHE / \"t1_q.npy\")\n", " G = np.asarray(mm(C.CACHE / \"t1_risk_g.npy\"), np.float32)\n", " P = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " rows = []\n", " zones = []\n", " for i in ok:\n", " act = P[i]\n", " ab = act == 2\n", " if not ab.any():\n", " continue\n", " est = fill_linear(A[i, :, E[\"median\"]])\n", " X, FB = zone_features(i, ab, est, A, Q, G)\n", " v = valid(ref[i])\n", " sel_ = np.flatnonzero(ab & v)\n", " if sel_.size:\n", " err = np.abs(FB[sel_] - ref[i][sel_, None])\n", " av = np.isfinite(FB[sel_])\n", " rows.append((X[sel_], (np.nan_to_num(err, nan=999) > C.BIG_ERR).astype(np.int8), av, np.full(sel_.size, fold[i]), np.full(sel_.size, i), np.nan_to_num(err, nan=np.nan)))\n", " for a, b in events(ab.astype(np.int8), 1):\n", " zones.append((b - a) / C.FS_FHR)\n", " rep = {\"policy\": \"Mondrian three-action policy of weeks 3-5 (frozen)\", \"fallbacks\": {\"interpolation\": f\"linear between the estimates bounding the zone, only for zones <= {C.FALLBACK_INTERP_MAX_S} s\", \"autocorrelation\": \"autocorrelogram peak (label-free DUS estimate)\", \"ensemble_median\": \"3-seed ensemble median\"}, \"risk_model\": \"per fallback, gradient boosting of P(|fallback - ref| > 10 bpm) on abstained points of folds not in {f, c}; threshold on fold c = (f+1) mod 5 by conformal risk control at alpha_flag; the fallback with the lowest predicted risk is chosen; status 'no reliable fallback' when its risk exceeds its threshold\"}\n", " zones = np.asarray(zones)\n", " rep[\"zones\"] = {\"n\": int(zones.size), \"median_s\": float(np.median(zones)) if zones.size else None, \"p90_s\": float(np.quantile(zones, 0.9)) if zones.size else None, \"frac_le_interp_max\": float(np.mean(zones <= C.FALLBACK_INTERP_MAX_S)) if zones.size else None}\n", " n = len(m)\n", " status = np.full((n, C.N), -1, np.int8)\n", " final = np.full((n, C.N), np.nan, np.float32)\n", " choice_all = np.full((n, C.N), -1, np.int8)\n", " for i in ok:\n", " final[i] = fill_linear(A[i, :, E[\"median\"]])\n", " status[i] = P[i]\n", " if not rows:\n", " rep[\"note\"] = \"no abstained points with a valid reference: fallbacks not assessable\"\n", " models, thr = {f: {k: (\"constant\", 1.0) for k in range(3)} for f in range(C.N_FOLDS)}, {f: {k: -np.inf for k in range(3)} for f in range(C.N_FOLDS)}\n", " else:\n", " X = np.concatenate([r[0] for r in rows])\n", " Y = np.concatenate([r[1] for r in rows])\n", " AV = np.concatenate([r[2] for r in rows])\n", " fd = np.concatenate([r[3] for r in rows])\n", " ERR = np.concatenate([r[5] for r in rows])\n", " models, thr = fit_fallback_models(X, Y, AV, fd, log)\n", " per = {}\n", " for k, nm in enumerate(FB_NAMES):\n", " a = AV[:, k]\n", " per[nm] = {\"available_frac\": float(a.mean()), \"rmse\": float(np.sqrt(np.nanmean(ERR[a, k] ** 2))) if a.any() else None, \"big_rate\": float(Y[a, k].mean()) if a.any() else None}\n", " common = AV.all(1)\n", " per[\"common_points\"] = int(common.sum())\n", " for k, nm in enumerate(FB_NAMES):\n", " per[f\"{nm}_on_common_rmse\"] = float(np.sqrt(np.mean(ERR[common, k] ** 2))) if common.any() else None\n", " rep[\"fallback_error_in_abstained_points\"] = per\n", " for i in ok:\n", " ab = P[i] == 2\n", " if not ab.any():\n", " continue\n", " est = final[i].copy()\n", " X_i, FB = zone_features(i, ab, est, A, Q, G)\n", " f = fold[i]\n", " ch, st, _ = apply_fallback(models[f], thr[f], X_i, FB, P[i])\n", " status[i] = st\n", " choice_all[i] = ch\n", " z = np.flatnonzero(ch >= 0)\n", " final[i, z] = FB[z, ch[z]]\n", " save_npy(C.CACHE / \"t1_status.npy\", status)\n", " save_npy(C.CACHE / \"t1_final_fhr.npy\", final)\n", " save_npy(C.CACHE / \"t1_fallback_choice.npy\", choice_all)\n", " errs_m, errs_f, st_v, ch_v = [], [], [], []\n", " for i in ok:\n", " e0, v = fhr_abs_errors(fill_linear(A[i, :, E[\"median\"]]), ref[i])\n", " e1, _ = fhr_abs_errors(final[i], ref[i])\n", " errs_m.append(e0)\n", " errs_f.append(e1)\n", " st_v.append(status[i][v])\n", " ch_v.append(choice_all[i][v])\n", " e0 = np.concatenate(errs_m)\n", " e1 = np.concatenate(errs_f)\n", " sv = np.concatenate(st_v)\n", " cv = np.concatenate(ch_v)\n", " rep[\"status_rates\"] = {STATUS[k]: float(np.mean(sv == k)) for k in STATUS}\n", " rep[\"big_rate_by_status\"] = {STATUS[k]: (float(np.mean(e1[sv == k] > C.BIG_ERR)) if (sv == k).any() else None) for k in STATUS}\n", " rep[\"rmse_by_status\"] = {STATUS[k]: (float(np.sqrt(np.mean(e1[sv == k] ** 2))) if (sv == k).any() else None) for k in STATUS}\n", " rep[\"chosen_fallback_share\"] = {nm: float(np.mean(cv[cv >= 0] == k)) if (cv >= 0).any() else None for k, nm in enumerate(FB_NAMES)}\n", " rep[\"no_reliable_fallback_captures_big_errors_of_abstained\"] = float(np.mean(sv[(sv >= 2) & (e1 > C.BIG_ERR)] == 3)) if ((sv >= 2) & (e1 > C.BIG_ERR)).any() else None\n", " preds_m = [fill_linear(A[i, :, E[\"median\"]]) for i in ok]\n", " rep[\"competition_t1\"] = {\"ensemble_median_everywhere\": t1_scores(preds_m, [ref[i] for i in ok]), \"policy_with_fallbacks\": t1_scores([final[i] for i in ok], [ref[i] for i in ok]), \"all_finite_in_range\": bool(all(np.isfinite(final[i]).all() and (final[i] >= C.FHR_MIN).all() and (final[i] <= C.FHR_MAX).all() for i in ok))}\n", " s0 = np.array([np.sum(e ** 2) for e in errs_m])\n", " s1 = np.array([np.sum(e ** 2) for e in errs_f])\n", " nn_ = np.array([e.size for e in errs_m])\n", " rep[\"rmse_fallbacks_minus_median\"] = boot(lambda i: np.sqrt(s1[i].sum() / nn_[i].sum()) - np.sqrt(s0[i].sum() / nn_[i].sum()), m.group.values[ok])[0]\n", " (C.MODELS / \"policy\").mkdir(parents=True, exist_ok=True)\n", " tmp = C.MODELS / \"policy\" / \"fallback.pkl.tmp\"\n", " with open(tmp, \"wb\") as fh:\n", " pickle.dump({\"models\": models, \"thr\": thr, \"names\": FB_NAMES, \"features\": FB_FEATS}, fh)\n", " tmp.replace(C.MODELS / \"policy\" / \"fallback.pkl\")\n", " save_json(C.RES / \"s31_t1_fallbacks.json\", rep)\n", " return {\"status_rates\": rep[\"status_rates\"], \"rmse_diff\": rep[\"rmse_fallbacks_minus_median\"][\"point\"]}\n", "\n", "\n", "def est_inputs(mask):\n", " from .sel import est_filled\n", " X = est_filled().astype(np.float32)\n", " if mask:\n", " P = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " X[P == 2] = np.nan\n", " return X\n", "\n", "\n", "def train_t2_est(force=False, fold=0, mask=False):\n", " from .t2 import T2Data, arr, fit_seg, t4_meta\n", " name = f\"s32{'b_t2_estmask' if mask else '_t2_est'}_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_FT, \"mask\": mask}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " m4 = t4_meta()\n", " tr, va = inner_split(m4, fold)\n", " data = T2Data(tr, est_inputs(mask), arr(\"t4_seg.npy\"))\n", " init = C.MODELS / \"t2_ft4\" / f\"fold{fold}\" / \"best.pt\"\n", " fit_seg(name, params, data, tr, va, C.MODELS / (\"t2_estmask\" if mask else \"t2_est\") / f\"fold{fold}\", C.EPOCHS_FT, 3e-4, log, C.SEED + 60 + fold + (7 if mask else 0), init=init, force=force)\n", "\n", "\n", "def train_t2_est_plain(force=False, fold=0):\n", " train_t2_est(force, fold, False)\n", "\n", "\n", "def train_t2_est_mask(force=False, fold=0):\n", " train_t2_est(force, fold, True)\n", "\n", "\n", "def train_t4_mask(force=False, fold=0):\n", " from .deep import ClsData, fit_cls\n", " name = f\"s33_t4_deep_mask_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_T4D}\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " tr, va = inner_split(m, fold)\n", " te = np.flatnonzero(m.fold.values == fold)\n", " data = ClsData(est_inputs(True), None, m.y.values.astype(np.int64))\n", " init = C.MODELS / \"t3_deep\" / f\"fold{fold}\" / \"best.pt\"\n", " fit_cls(name, params, data, tr, va, te, C.MODELS / \"t4_deep_mask\" / f\"fold{fold}\", C.EPOCHS_T4D, 3e-4, log, C.SEED + 400 + fold, init=init if init.exists() else None, force=force, oof_path=C.CACHE / f\"t4_deepmask_oof_f{fold}\")\n", "\n", "\n", "def load_seg(kind, fold, dev):\n", " import torch\n", " from .t2 import UNet1D\n", " mdl = UNet1D().to(dev)\n", " mdl.load_state_dict(torch.load(C.MODELS / kind / f\"fold{fold}\" / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " return mdl.eval()\n", "\n", "\n", "def oof_seg_probs(kind, X, fold, recs, dev, log):\n", " from .t2 import predict_probs\n", " P = np.full((len(recs), 3, C.N), np.nan, np.float32)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold[recs] == f)\n", " if sel_.size:\n", " P[sel_] = predict_probs(load_seg(kind, f, dev), X[recs[sel_]], dev, log)\n", " return P\n", "\n", "\n", "@stage(\"s34_cascade_mask\", params={\"v\": 1})\n", "def cascade_mask(log):\n", " from .deep import gather\n", " from .t2 import crossfit_post, post\n", " from .t3 import feature_table\n", " from .t4 import crossfit, seg_features\n", " dev = device()\n", " m = meta()\n", " y = m.y.values\n", " fold_all = m.fold.values\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " P = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " sg_ok = np.load(C.CACHE / \"t4_segp_est_ok.npy\")\n", " d0 = gather(\"t4_deep_oof\", len(m))\n", " d1 = gather(\"t4_deepmask_oof\", len(m))\n", " ok = (fold_all >= 0) & sg_ok & np.isfinite(d0) & np.isfinite(d1)\n", " idx = np.flatnonzero(ok)\n", " fold = np.where(ok, fold_all, -1)\n", " Xa = est_inputs(False)\n", " Xb = est_inputs(True)\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " segs, probs_seg = {}, {}\n", " for key, kind, X in ((\"A\", \"t2_ft4\", Xa), (\"B_s22\", \"t2_ft4\", Xb), (\"B0_trained_on_estimate\", \"t2_est\", Xa), (\"B1_trained_with_mask\", \"t2_estmask\", Xb)):\n", " Pr = oof_seg_probs(kind, X, fold, idx, dev, log)\n", " probs_seg[key] = Pr\n", " if kind == \"t2_ft4\":\n", " S = np.zeros((idx.size, C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold[idx] == f)\n", " if sel_.size:\n", " S[sel_] = post(np.nan_to_num(Pr[sel_]), *pp[str(f)])\n", " segs[key] = S\n", " else:\n", " segs[key], _ = crossfit_post(np.nan_to_num(Pr), Sref[idx], fold[idx])\n", " segs[\"A_retuned_post\"], _ = crossfit_post(np.nan_to_num(probs_seg[\"A\"]), Sref[idx], fold[idx])\n", " FA = feature_table(Xa[idx])\n", " FB = feature_table(Xb[idx])\n", " abf = np.mean(P[idx] == 2, 1)\n", " flf = np.mean(P[idx] == 1, 1)\n", " risk = {}\n", " for key, S in segs.items():\n", " base = FB if key.startswith(\"B\") else FA\n", " Fx = pd.concat([base, seg_features(Xa[idx], S)], axis=1)\n", " if key.startswith(\"B\"):\n", " Fx[\"abstain_frac\"] = abf\n", " Fx[\"flag_frac\"] = flf\n", " risk[f\"gbm_{key}\"] = crossfit(Fx.values, Fx.values, y[idx], fold[idx])\n", " risk[\"deep_D0_no_mask\"] = d0[idx]\n", " risk[\"deep_D1_mask_channel\"] = d1[idx]\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " dc = {k: [dice_counts(S[j], Sref[r]) for j, r in enumerate(idx)] for k, S in segs.items()}\n", " ec = {k: [event_counts(S[j], Sref[r]) for j, r in enumerate(idx)] for k, S in segs.items()}\n", " rep = {\"n_records\": int(idx.size), \"notes\": \"A = T4-fine-tuned U-Net on the estimate; B_s22 = same model with abstained points masked (weeks 3-5); B0 = U-Net fine-tuned on the out-of-fold estimate without mask; B1 = same recipe with abstained points masked, so the validity channel carries the abstention mask. B1 - B0 isolates the mask; B0 - A isolates training on the estimate. Deep D1 vs D0: SE-ResNet transferred from T3 with and without the mask in its validity channel. Leakage note: the residual-risk model that defines training masks used reference FHR of other folds (not their risk labels or segmentations).\"}\n", " seg_vals = {k: Pack(yy, risk[\"gbm_\" + k], dc[k], ec[k]).values() for k in segs}\n", " rep[\"segmentation_and_gbm_risk\"] = seg_vals\n", " for k in risk:\n", " b = binary_scores(yy, risk[k])\n", " rep.setdefault(\"risk_calibration\", {})[k] = {kk: b[kk] for kk in (\"auroc\", \"f1\", \"nmcc\", \"brier\", \"ece\")}\n", " packs = {k: Pack(yy, risk[\"gbm_\" + k], dc[k], ec[k]) for k in segs}\n", " keys = [\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\"]\n", " diffs = {}\n", " for a_, b_ in ((\"B_s22\", \"A\"), (\"B0_trained_on_estimate\", \"A\"), (\"B1_trained_with_mask\", \"B0_trained_on_estimate\"), (\"B1_trained_with_mask\", \"A\"), (\"A_retuned_post\", \"A\")):\n", " res = boot(lambda i, a_=a_, b_=b_: packs[a_].vec(i) - packs[b_].vec(i), groups)\n", " diffs[f\"{a_}_minus_{b_}\"] = dict(zip(keys, res))\n", " from .fastm import auroc as fauc\n", " res = boot(lambda i: np.array([fauc(yy[i], risk[\"deep_D1_mask_channel\"][i]) - fauc(yy[i], risk[\"deep_D0_no_mask\"][i]), np.mean((risk[\"deep_D1_mask_channel\"][i] - yy[i]) ** 2) - np.mean((risk[\"deep_D0_no_mask\"][i] - yy[i]) ** 2)]), groups)\n", " diffs[\"deep_D1_minus_D0\"] = dict(zip([\"auroc\", \"brier\"], res))\n", " rep[\"paired_diffs\"] = diffs\n", " sel = {}\n", " fo = fold[idx]\n", " for key in (\"gbm_A\", \"gbm_B1_trained_with_mask\", \"deep_D1_mask_channel\"):\n", " p = risk[key]\n", " err = ((p >= 0.5).astype(int) != yy).astype(float)\n", " conf = -np.abs(p - 0.5)\n", " out = {}\n", " for cov in C.REPORT_COVERAGES:\n", " keep_ab = np.zeros(idx.size, bool)\n", " keep_cf = np.zeros(idx.size, bool)\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " te, cm = fo == f, fo == c\n", " if not te.any() or not cm.any():\n", " continue\n", " keep_ab[te] = abf[te] <= np.quantile(abf[cm], cov)\n", " keep_cf[te] = conf[te] <= np.quantile(conf[cm], cov)\n", " out[str(cov)] = {\"coverage_abstain_rule\": float(keep_ab.mean()), \"coverage_confidence_rule\": float(keep_cf.mean()), \"error_all\": float(err.mean()), \"error_reported_abstain_rule\": float(err[keep_ab].mean()) if keep_ab.any() else None, \"error_reported_confidence_rule\": float(err[keep_cf].mean()) if keep_cf.any() else None, \"diff_abstain_minus_confidence\": boot(lambda i, ka=keep_ab, kc=keep_cf: (err[i][ka[i]].mean() if ka[i].any() else 0.0) - (err[i][kc[i]].mean() if kc[i].any() else 0.0), groups)[0]}\n", " sel[key] = out\n", " rep[\"record_level_abstention\"] = sel\n", " save_json(C.RES / \"s34_cascade_mask.json\", rep)\n", " return {k: {kk: round(v[kk], 3) for kk in (\"flow_dice\", \"auroc\")} for k, v in seg_vals.items()}\n", "\n", "\n", "@stage(\"s34b_cascade_c_control\", params={\"v\": 1})\n", "def cascade_c_control(log):\n", " from scipy.ndimage import gaussian_filter1d\n", " from .fastm import auroc as fauc\n", " from .sel import E, ens, est_filled\n", " from .t2 import load_ft4, post, predict_probs\n", " from .t3 import feature_table, model\n", " from .t4 import seg_features\n", " dev = device()\n", " m = meta()\n", " y = m.y.values\n", " fold_all = m.fold.values\n", " z = np.load(C.CACHE / \"w35_cascade_probs.npz\")\n", " idx, pA, pC, pCk = z[\"idx\"], z[\"pA\"], z[\"pC\"], z[\"pCk\"]\n", " K = pCk.shape[0]\n", " A = ens()\n", " med = est_filled(A)\n", " ok_all = np.flatnonzero(fold_all >= 0)\n", " w = np.nanmean([np.nanmean(A[i, :, E[\"q90\"]] - A[i, :, E[\"q10\"]]) for i in ok_all])\n", " sd = float(w / 2.563)\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " fo = fold_all[idx]\n", " models = {f: load_ft4(f, dev) for f in range(C.N_FOLDS)}\n", " rng = np.random.default_rng(C.SEED + 70)\n", " sig = 40\n", " feats = []\n", " for k in range(K):\n", " zz = gaussian_filter1d(rng.standard_normal((idx.size, C.N + 8 * sig)), sig, axis=1)[:, 4 * sig:4 * sig + C.N]\n", " zz /= np.sqrt(1.0 / (2.0 * np.sqrt(np.pi) * sig))\n", " X = np.clip(med[idx] + sd * zz, C.FHR_MIN, C.FHR_MAX).astype(np.float32)\n", " S = np.zeros((idx.size, C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fo == f)\n", " if sel_.size:\n", " S[sel_] = post(np.nan_to_num(predict_probs(models[f], X[sel_], dev, log).astype(np.float32)), *pp[str(f)])\n", " feats.append(pd.concat([feature_table(X), seg_features(X, S)], axis=1).values)\n", " log.info(f\"control sample {k + 1}/{K}\")\n", " FC = np.concatenate(feats)\n", " yC = np.tile(y[idx], K)\n", " fC = np.tile(fo, K)\n", " p0k = np.full(FC.shape[0], np.nan)\n", " for f in range(C.N_FOLDS):\n", " a, b = (fC >= 0) & (fC != f), fC == f\n", " if b.any():\n", " p0k[b] = model(int(a.sum())).fit(FC[a], yC[a]).predict_proba(FC[b])[:, 1]\n", " p0 = p0k.reshape(K, idx.size).mean(0)\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " keys = [\"auroc\", \"brier\", \"ece\", \"f1\", \"nmcc\"]\n", "\n", " def vals(p, i):\n", " b = binary_scores(yy[i], p[i])\n", " return np.array([fauc(yy[i], p[i]), b[\"brier\"], b[\"ece\"], b[\"f1\"], b[\"nmcc\"]])\n", "\n", " rep = {\"n_records\": int(idx.size), \"K\": int(K), \"control\": f\"K trajectories = ensemble median + smooth Gaussian noise of constant SD {sd:.2f} bpm (mean predictive 10-90% width / 2.563) with the same 10-s rank correlation as cascade C, so it has the same augmentation and averaging but no record- or point-specific uncertainty\", \"values\": {nm: dict(zip(keys, vals(p, np.arange(idx.size)).tolist())) for nm, p in ((\"A\", pA), (\"C\", pC), (\"C0_control\", p0))}}\n", " rep[\"C_minus_C0\"] = dict(zip(keys, boot(lambda i: vals(pC, i) - vals(p0, i), groups)))\n", " rep[\"C0_minus_A\"] = dict(zip(keys, boot(lambda i: vals(p0, i) - vals(pA, i), groups)))\n", " rep[\"interpretation_rule\"] = \"the gain of C over A is attributed to propagated uncertainty only for the part where C - C0 has a CI excluding zero; C0 - A measures augmentation and averaging\"\n", " save_json(C.RES / \"s34b_cascade_c_control.json\", rep)\n", " return {k: {kk: round(v[kk], 3) for kk in (\"auroc\", \"brier\", \"ece\")} for k, v in rep[\"values\"].items()}" ] }, { "cell_type": "code", "execution_count": 25, "id": "f9507cf0a00a", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:32.992554Z", "iopub.status.busy": "2026-11-28T14:17:32.992225Z", "iopub.status.idle": "2026-11-28T14:17:33.012578Z", "shell.execute_reply": "2026-11-28T14:17:33.010527Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/holdout.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/holdout.py\n", "import hashlib\n", "import json\n", "import pickle\n", "import time\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "\n", "from . import config as C\n", "from .fastm import Pack, boot\n", "from .io import fill_linear, valid\n", "from .metrics import binary_scores, dice_counts, event_counts, fhr_abs_errors, risk_coverage, t1_scores\n", "from .t1 import meta, ref_fhr, sfx\n", "from .utils import device, free_mem, load_json, mm, portable, save_json, stage\n", "\n", "FROZEN = C.MODELS / \"policy\" / \"frozen.pkl\"\n", "SEEDS3 = 3\n", "\n", "\n", "def sha(p):\n", " h = hashlib.sha256()\n", " with open(p, \"rb\") as fh:\n", " for b in iter(lambda: fh.read(2 ** 22), b\"\"):\n", " h.update(b)\n", " return h.hexdigest()\n", "\n", "\n", "def frozen_files():\n", " fs = [C.MODELS / \"t1_tcn\" / f\"fold{f}{sfx(s)}\" / \"best.pt\" for f in range(C.N_FOLDS) for s in range(SEEDS3)]\n", " fs += [C.MODELS / \"t2_ft4\" / f\"fold{f}\" / \"best.pt\" for f in range(C.N_FOLDS)]\n", " fs += [C.MODELS / \"t4_deep\" / f\"fold{f}\" / \"best.pt\" for f in range(C.N_FOLDS)]\n", " fs += [FROZEN, C.MODELS / \"policy\" / \"fallback.pkl\"]\n", " fs += [C.RES / n for n in (\"s09_t1_floor_params.json\", \"s14_t2_eval.json\", \"s21_t1_risk_policy.json\", \"s31_t1_fallbacks.json\")]\n", " code = Path(__file__).resolve().parent\n", " fs += [code / f\"{n}.py\" for n in (\"holdout\", \"sel2\", \"sel\", \"t1\", \"t2\", \"t3\", \"t4\", \"deep\", \"fastm\", \"metrics\", \"io\", \"config\")]\n", " return fs\n", "\n", "\n", "def manifest():\n", " files = {portable(p): sha(p) for p in frozen_files()}\n", " h = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest()\n", " return files, h\n", "\n", "\n", "def policy_actions(F, sc, thr_f):\n", " from .sel import clean_policy, observable_strata\n", " so = observable_strata(F)\n", " act = np.full(F.shape[0], 2, np.int8)\n", " for s_ in np.unique(so):\n", " mk = so == s_\n", " d = thr_f[\"mondrian\"].get(int(s_), {C.ALPHA_ESTIMATE: -np.inf, C.ALPHA_FLAG: -np.inf})\n", " act[mk & (sc <= d[C.ALPHA_FLAG])] = 1\n", " act[mk & (sc <= d[C.ALPHA_ESTIMATE])] = 0\n", " return clean_policy(act)\n", "\n", "\n", "def design(log):\n", " from .sel import E, FEAT_NAMES, LOWQ, crc_threshold, ens, hgb, mondrian_thresholds, observable_strata, point_features, seg_probs_on_estimate\n", " m = meta()\n", " ref = ref_fhr()\n", " A = ens()\n", " Q = mm(C.CACHE / \"t1_q.npy\")\n", " AF = mm(C.CACHE / \"t1_af.npy\")\n", " FL = mm(C.CACHE / \"t1_floor.npy\")\n", " SG, _ = seg_probs_on_estimate(log)\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " rng = np.random.default_rng(C.SEED)\n", " pick = {}\n", " for i in ok:\n", " v = np.flatnonzero(valid(ref[i]))\n", " pick[i] = np.sort(rng.choice(v, size=min(C.POINTS_PER_RECORD, v.size), replace=False)) if v.size else v\n", " allq = np.concatenate([np.asarray(Q[i, pick[i], 2], np.float32) for i in ok if pick[i].size])\n", " core = lambda i: (A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]], A[i, :, E[\"entropy\"]], A[i, :, E[\"q10\"]], A[i, :, E[\"q90\"]])\n", " rows = []\n", " for i in ok:\n", " if pick[i].size == 0:\n", " continue\n", " F = point_features(i, core(i), A, Q, AF, FL, SG)\n", " med = fill_linear(core(i)[0])\n", " e = np.abs(med[pick[i]] - ref[i][pick[i]])\n", " rows.append((F[pick[i]], e, np.full(pick[i].size, fold[i]), np.full(pick[i].size, i)))\n", " X = np.concatenate([r[0] for r in rows])\n", " y = (np.concatenate([r[1] for r in rows]) > C.BIG_ERR).astype(np.int8)\n", " fd = np.concatenate([r[2] for r in rows])\n", " rec = np.concatenate([r[3] for r in rows])\n", " models = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " tr = (fd != f) & (fd != c)\n", " models[f] = hgb().fit(X[tr], y[tr])\n", " s21 = load_json(C.RES / \"s21_t1_risk_policy.json\")\n", " s6 = bool(s21[\"gate_S6\"][\"passed\"])\n", " LOWQ[0] = float(np.quantile(allq, 0.2))\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " strat_pts = observable_strata(X)\n", " thr = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " cm = fd == c\n", " sc_c = models[f].predict_proba(X[cm])[:, 1] if s6 else X[cm][:, cidx[\"p_far\"]]\n", " yc = y[cm]\n", " stc = strat_pts[cm]\n", " thr[f] = {\"marginal\": {a: crc_threshold(sc_c, yc, a) for a in (C.ALPHA_ESTIMATE, C.ALPHA_FLAG)}, \"mondrian\": mondrian_thresholds(sc_c, yc, stc, rec[cm], strat_pts)}\n", " return {\"g_models\": models, \"thr\": thr, \"lowq\": LOWQ[0], \"s6_passed\": s6, \"lowq_s21\": s21[\"observable_strata\"][\"low_quality_threshold\"]}\n", "\n", "\n", "def verify(D, log):\n", " from .sel import E, FEAT_NAMES, LOWQ, ens, point_features, seg_probs_on_estimate\n", " m = meta()\n", " A = ens()\n", " Q = mm(C.CACHE / \"t1_q.npy\")\n", " AF = mm(C.CACHE / \"t1_af.npy\")\n", " FL = mm(C.CACHE / \"t1_floor.npy\")\n", " SG, _ = seg_probs_on_estimate(log)\n", " G0 = np.asarray(mm(C.CACHE / \"t1_risk_g.npy\"), np.float32)\n", " P0 = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " LOWQ[0] = D[\"lowq\"]\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " fold = m.fold.values\n", " gd, agree, n = 0.0, 0, 0\n", " for i in np.flatnonzero(fold >= 0):\n", " core = (A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]], A[i, :, E[\"entropy\"]], A[i, :, E[\"q10\"]], A[i, :, E[\"q90\"]])\n", " F = point_features(i, core, A, Q, AF, FL, SG)\n", " g = D[\"g_models\"][fold[i]].predict_proba(F)[:, 1]\n", " gd = max(gd, float(np.nanmax(np.abs(g - G0[i]))))\n", " sc = g if D[\"s6_passed\"] else F[:, cidx[\"p_far\"]]\n", " act = policy_actions(F, sc, D[\"thr\"][fold[i]])\n", " agree += int((act == P0[i]).sum())\n", " n += act.size\n", " return {\"g_max_abs_diff\": gd, \"policy_agreement\": agree / max(1, n), \"lowq_diff\": abs(D[\"lowq\"] - D[\"lowq_s21\"])}\n", "\n", "\n", "def segment_fold(X, recs, fold, pp, dev, log, kind=\"t2_ft4\"):\n", " from .sel2 import load_seg\n", " from .t2 import post, predict_probs\n", " S = np.zeros((len(recs), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold == f)\n", " if sel_.size:\n", " pr = predict_probs(load_seg(kind, f, dev), X[sel_], dev, log)\n", " S[sel_] = post(np.nan_to_num(pr.astype(np.float32)), *pp[str(f)])\n", " return S\n", "\n", "\n", "def t4_features(Xin, Xseg, S, P=None):\n", " from .t3 import feature_table\n", " from .t4 import seg_features\n", " F = pd.concat([feature_table(Xin), seg_features(Xseg, S)], axis=1)\n", " if P is not None:\n", " F[\"abstain_frac\"] = np.mean(P == 2, 1)\n", " F[\"flag_frac\"] = np.mean(P == 1, 1)\n", " return F\n", "\n", "\n", "@stage(\"s35_freeze\", params={\"v\": 2}, outputs=[FROZEN])\n", "def freeze(log):\n", " from .sel import est_filled\n", " from .t3 import model\n", " dev = device()\n", " D = design(log)\n", " chk = verify(D, log)\n", " log.info(f\"freeze reproduction check: {chk}\")\n", " if chk[\"policy_agreement\"] < 0.995 or chk[\"lowq_diff\"] > 1e-6:\n", " raise RuntimeError(f\"the frozen policy does not reproduce the weeks 3-5 policy ({chk}); rerun s21 with --force in this environment before freezing\")\n", " m = meta()\n", " fold_all = m.fold.values\n", " sg_ok = np.load(C.CACHE / \"t4_segp_est_ok.npy\")\n", " ok = (fold_all >= 0) & sg_ok\n", " idx = np.flatnonzero(ok)\n", " P = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " Xa = est_filled().astype(np.float32)\n", " Xb = Xa.copy()\n", " Xb[P == 2] = np.nan\n", " SA = segment_fold(Xa[idx], idx, fold_all[idx], pp, dev, log)\n", " SB = segment_fold(Xb[idx], idx, fold_all[idx], pp, dev, log)\n", " FA = t4_features(Xa[idx], Xa[idx], SA)\n", " FB = t4_features(Xb[idx], Xa[idx], SB, P[idx])\n", " y = m.y.values[idx]\n", " D[\"t4_gbm_A\"] = model(idx.size).fit(FA.values, y)\n", " D[\"t4_gbm_B\"] = model(idx.size).fit(FB.values, y)\n", " D[\"t4_cols_A\"], D[\"t4_cols_B\"] = list(FA.columns), list(FB.columns)\n", " D[\"pp_ft4\"] = pp\n", " D[\"reproduction_check\"] = chk\n", " D[\"alphas\"] = (C.ALPHA_ESTIMATE, C.ALPHA_FLAG)\n", " FROZEN.parent.mkdir(parents=True, exist_ok=True)\n", " tmp = FROZEN.with_suffix(\".tmp\")\n", " with open(tmp, \"wb\") as fh:\n", " pickle.dump(D, fh)\n", " tmp.replace(FROZEN)\n", " files, h = manifest()\n", " plan = {\n", " \"unit\": \"each of the 5 replicates applies the complete frozen pipeline of outer fold f (3-seed TCN ensemble of fold f, floor of fold f, T4-fine-tuned U-Net of fold f, residual-risk model g_f, conformal thresholds calibrated on fold (f+1) mod 5, fallback models of fold f) to every holdout record\",\n", " \"S8_criterion\": f\"for a replicate: at 90% and 80% coverage, the rate of |e| > 10 bpm is reduced by at least {int(100 * C.S8_REDUCTION)}% versus estimating everywhere (upper 95% CI of risk@coverage / risk_full <= {1 - C.S8_REDUCTION:.2f}), and the realised selective risk of the 'estimate' zone (at least 1% of points estimated) has upper 95% CI <= 1.5 x alpha_estimate ({1.5 * C.ALPHA_ESTIMATE:.4f}); point estimates use every valid point, CIs a group bootstrap on up to 1000 points per record; S8 passes when >= 4 of 5 replicates pass\",\n", " \"secondary\": \"T1 RMSE/MAE (ensemble median and policy with fallbacks), T4 cascades A and B with frozen classifiers, deep T4 model; reported without gates\",\n", " \"ci\": \"group bootstrap over holdout records\",\n", " }\n", " save_json(C.RES / \"s35_freeze.json\", {\"files\": files, \"freeze_hash\": h, \"reproduction_check\": chk, \"s6_passed\": D[\"s6_passed\"], \"holdout_plan\": plan, \"time\": time.strftime(\"%Y-%m-%d %H:%M:%S\")})\n", " return {\"freeze_hash\": h[:16], \"check\": chk}\n", "\n", "\n", "def floor_on(idx, f, dev, log):\n", " from .t1 import FLOOR_COLS, emissions, log_prior, posterior, summarize, transition, viterbi\n", " m = meta()\n", " ref = ref_fhr()\n", " par = load_json(C.RES / \"s09_t1_floor_params.json\")[str(f)]\n", " tr = np.flatnonzero((m.fold.values >= 0) & (m.fold.values != f))\n", " lp = torch.from_numpy(log_prior(ref[tr])).to(dev)\n", " T = torch.from_numpy(transition(par[\"lam\"], jump=par[\"beta\"] * 0.5)).to(dev)\n", " ac = mm(C.CACHE / \"t1_ac.npy\")\n", " out = np.full((idx.size, C.N, len(FLOOR_COLS)), np.nan, np.float32)\n", " for a in range(0, idx.size, 8):\n", " g = torch.from_numpy(np.asarray(ac[idx[a:a + 8]], np.float32)).to(dev)\n", " e = emissions(g, par[\"beta\"], par[\"alpha\"], lp, par[\"rho\"])\n", " path = viterbi(e, T)\n", " p = posterior(e, T)\n", " med, mean, pfar, ent, q10, q90 = summarize(p)\n", " out[a:a + 8] = np.stack([C.BPM[path.cpu().numpy()], med.cpu().numpy(), mean.cpu().numpy(), pfar.cpu().numpy(), ent.cpu().numpy(), q10.cpu().numpy(), q90.cpu().numpy()], -1)\n", " del g, e, p\n", " free_mem()\n", " return out\n", "\n", "\n", "def ensemble_on(idx, f, dev, log):\n", " from .sel import ENS_COLS, summarize_np\n", " from .t1 import TCN, Data, predict\n", " mods = []\n", " for s in range(SEEDS3):\n", " ck = torch.load(C.MODELS / \"t1_tcn\" / f\"fold{f}{sfx(s)}\" / \"best.pt\", map_location=dev, weights_only=False)\n", " mdl = TCN().to(dev)\n", " mdl.load_state_dict(ck[\"model\"])\n", " mods.append((mdl.eval(), ck[\"stats\"]))\n", " out = np.full((idx.size, C.N, len(ENS_COLS)), np.nan, np.float32)\n", " for a in range(0, idx.size, 16):\n", " chunk = idx[a:a + 16]\n", " P = []\n", " for mdl, stats in mods:\n", " pr = predict(mdl, Data(chunk, stats), chunk, dev, log)\n", " P.append(np.stack([pr[r].cpu().numpy().astype(np.float32) for r in chunk]))\n", " P = np.stack(P)\n", " for k in range(P.shape[1]):\n", " out[a + k], _ = summarize_np(P[:, k])\n", " del P\n", " free_mem()\n", " return out\n", "\n", "\n", "def rep_metrics(e, sc, act, grp, sub):\n", " loss = (e > C.BIG_ERR).astype(float)\n", " rc = risk_coverage(sc, loss)\n", " out = {\"risk_full\": rc[\"risk_full\"], \"aurc\": rc[\"aurc\"], \"points\": int(e.size), \"points_for_ci\": int(sub.size)}\n", " ls, ss, as_, gs = loss[sub], sc[sub], act[sub], grp[sub]\n", " B = min(C.BOOT, 1000)\n", " for cov in C.REPORT_COVERAGES:\n", " out[f\"risk@{cov}\"] = rc[f\"risk@{cov}\"]\n", " b = boot(lambda i, cov=cov: risk_coverage(ss[i], ls[i])[f\"risk@{cov}\"] / max(ls[i].mean(), 1e-12), gs, B=B)[0]\n", " b[\"point_subsample\"] = b[\"point\"]\n", " b[\"point\"] = rc[f\"risk@{cov}\"] / max(rc[\"risk_full\"], 1e-12)\n", " out[f\"ratio@{cov}\"] = b\n", " est = act == 0\n", " out[\"coverage_estimate\"] = float(est.mean())\n", " out[\"coverage_estimate_or_flag\"] = float((act <= 1).mean())\n", " b = boot(lambda i: ls[i][as_[i] == 0].mean() if (as_[i] == 0).any() else np.nan, gs, B=B)[0]\n", " b[\"point\"] = float(loss[est].mean()) if est.any() else None\n", " out[\"selective_risk_estimate\"] = b\n", " b = boot(lambda i: ls[i][as_[i] <= 1].mean() if (as_[i] <= 1).any() else np.nan, gs, B=B)[0]\n", " b[\"point\"] = float(loss[act <= 1].mean()) if (act <= 1).any() else None\n", " out[\"selective_risk_estimate_or_flag\"] = b\n", " out[\"abstain_rate\"] = float(np.mean(act == 2))\n", " out[\"big_errors_in_abstain\"] = float(np.mean(act[loss > 0] == 2)) if loss.any() else None\n", " red_ok = all(out[f\"ratio@{cov}\"][\"hi\"] is not None and out[f\"ratio@{cov}\"][\"hi\"] <= 1 - C.S8_REDUCTION for cov in C.REPORT_COVERAGES)\n", " cal_ok = bool(est.mean() >= 0.01) and out[\"selective_risk_estimate\"][\"hi\"] is not None and out[\"selective_risk_estimate\"][\"hi\"] <= 1.5 * C.ALPHA_ESTIMATE\n", " out[\"calibration_note\"] = None if est.mean() >= 0.01 else \"fewer than 1% of points estimated: calibration is vacuous and counted as failed\"\n", " out[\"reduction_ok\"], out[\"calibration_ok\"], out[\"passed\"] = bool(red_ok), bool(cal_ok), bool(red_ok and cal_ok)\n", " return out\n", "\n", "\n", "@stage(\"s36_holdout\", params={\"v\": 2})\n", "def holdout(log):\n", " from .deep import ClsData, SEResNet1D\n", " from .deep import predict as dpredict\n", " from .sel import E, FEAT_NAMES, LOWQ, OBS_NAMES, observable_strata, point_features\n", " from .sel2 import apply_fallback, zone_features\n", " from .t2 import safe_models_for_t4\n", " from .t4 import report\n", " if not C.UNLOCK_HOLDOUT:\n", " raise PermissionError(\"s36_holdout needs CTG_UNLOCK_HOLDOUT=1 (set only for this stage by the orchestrator)\")\n", " fz = load_json(C.RES / \"s35_freeze.json\")\n", " if not fz:\n", " raise RuntimeError(\"no freeze manifest: run s35_freeze first\")\n", " files, h = manifest()\n", " access = load_json(C.RES / \"holdout_access.json\", {\"accesses\": []})\n", " deviation = None\n", " if h != fz[\"freeze_hash\"]:\n", " changed = [k for k in set(files) | set(fz[\"files\"]) if files.get(k) != fz[\"files\"].get(k)]\n", " if not C.HOLDOUT_REOPEN:\n", " raise RuntimeError(f\"frozen artefacts changed since the freeze ({changed[:5]}); the holdout is one-shot. Set CTG_HOLDOUT_REOPEN=1 only to record a protocol deviation\")\n", " deviation = {\"changed\": changed}\n", " prev = [a for a in access[\"accesses\"] if a.get(\"completed\")]\n", " if prev and prev[-1][\"freeze_hash\"] != h and not C.HOLDOUT_REOPEN:\n", " raise RuntimeError(\"the holdout was already evaluated with a different frozen pipeline; set CTG_HOLDOUT_REOPEN=1 to record a deviation\")\n", " access[\"accesses\"].append({\"time\": time.strftime(\"%Y-%m-%d %H:%M:%S\"), \"freeze_hash\": h, \"deviation\": deviation, \"completed\": False})\n", " save_json(C.RES / \"holdout_access.json\", access)\n", " with open(FROZEN, \"rb\") as fh:\n", " D = pickle.load(fh)\n", " with open(C.MODELS / \"policy\" / \"fallback.pkl\", \"rb\") as fh:\n", " FBK = pickle.load(fh)\n", " LOWQ[0] = D[\"lowq\"]\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " dev = device()\n", " m = meta()\n", " ref = ref_fhr()\n", " hidx = np.flatnonzero(m.fold.values == -1)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " Q = np.asarray(mm(C.CACHE / \"t1_q.npy\")[hidx], np.float32)\n", " AF = np.asarray(mm(C.CACHE / \"t1_af.npy\")[hidx], np.float32)\n", " safe = safe_models_for_t4()\n", " grp = m.group.values[hidx]\n", " y = m.y.values[hidx]\n", " pp = D[\"pp_ft4\"]\n", " rep = {\"n_holdout_records\": int(hidx.size), \"freeze_hash\": h, \"deviation\": deviation, \"replicates\": {}}\n", " probs = {\"A\": [], \"B\": [], \"deep\": []}\n", " t_start = time.time()\n", " store = {}\n", " for f in range(C.N_FOLDS):\n", " t0 = time.time()\n", " A = ensemble_on(hidx, f, dev, log)\n", " FLh = floor_on(hidx, f, dev, log)\n", " med = np.stack([fill_linear(A[k, :, E[\"median\"]]) for k in range(hidx.size)])\n", " seg_ok = np.array([f in safe[i] for i in hidx])\n", " SG = np.zeros((hidx.size, 3, C.N), np.float32)\n", " if seg_ok.any():\n", " from .sel2 import load_seg\n", " from .t2 import predict_probs\n", " SG[seg_ok] = np.nan_to_num(predict_probs(load_seg(\"t2_ft4\", f, dev), med[seg_ok], dev, log).astype(np.float32))\n", " acts = np.zeros((hidx.size, C.N), np.int8)\n", " status = np.zeros((hidx.size, C.N), np.int8)\n", " final = med.copy()\n", " scores = np.zeros((hidx.size, C.N), np.float32)\n", " G = np.zeros((hidx.size, C.N), np.float32)\n", " pf_ref = np.zeros((hidx.size, C.N), np.float32)\n", " strat = np.zeros((hidx.size, C.N), np.int8)\n", " for k in range(hidx.size):\n", " core = (A[k, :, E[\"median\"]], A[k, :, E[\"p_far\"]], A[k, :, E[\"entropy\"]], A[k, :, E[\"q10\"]], A[k, :, E[\"q90\"]])\n", " F = point_features(k, core, A, Q, AF, FLh, SG)\n", " g = D[\"g_models\"][f].predict_proba(F)[:, 1]\n", " G[k] = g\n", " sc = g if D[\"s6_passed\"] else F[:, cidx[\"p_far\"]]\n", " scores[k] = sc\n", " pf_ref[k] = F[:, cidx[\"p_far\"]]\n", " strat[k] = observable_strata(F)\n", " act = policy_actions(F, sc, D[\"thr\"][f])\n", " acts[k] = act\n", " status[k] = act\n", " if (act == 2).any():\n", " Xz, FB = zone_features(k, act == 2, med[k], A, Q, G)\n", " ch, st, _ = apply_fallback(FBK[\"models\"][f], FBK[\"thr\"][f], Xz, FB, act)\n", " status[k] = st\n", " z = np.flatnonzero(ch >= 0)\n", " final[k, z] = FB[z, ch[z]]\n", " E_, S_, Ac_, Pf_, Gp, Sub, St_ = [], [], [], [], [], [], []\n", " off = 0\n", " prng = np.random.default_rng(C.SEED + 36)\n", " for k, i in enumerate(hidx):\n", " e, v = fhr_abs_errors(med[k], ref[i])\n", " Sub.append(off + np.sort(prng.choice(e.size, size=min(1000, e.size), replace=False)) if e.size else np.zeros(0, int))\n", " off += e.size\n", " E_.append(e)\n", " S_.append(scores[k][v])\n", " Ac_.append(acts[k][v])\n", " Pf_.append(pf_ref[k][v])\n", " St_.append(strat[k][v])\n", " Gp.append(np.full(e.size, grp[k]))\n", " e = np.concatenate(E_)\n", " gp = np.concatenate(Gp)\n", " r = rep_metrics(e, np.concatenate(S_), np.concatenate(Ac_), gp, np.concatenate(Sub))\n", " st_all, ac_all = np.concatenate(St_), np.concatenate(Ac_)\n", " lb = (e > C.BIG_ERR).astype(float)\n", " r[\"per_observable_stratum\"] = {}\n", " for s_ in np.unique(st_all):\n", " mk = np.flatnonzero((st_all == s_) & (ac_all == 0))\n", " r[\"per_observable_stratum\"][OBS_NAMES[int(s_)]] = {\"points\": int((st_all == s_).sum()), \"coverage_estimate\": float(np.mean(ac_all[st_all == s_] == 0)), \"risk_estimate\": boot(lambda i, mk=mk: lb[mk][i].mean(), gp[mk], B=min(C.BOOT, 500))[0] if mk.size else None}\n", " r[\"training_free_p_far_reference\"] = {f\"risk@{cov}\": risk_coverage(np.concatenate(Pf_), (e > C.BIG_ERR).astype(float))[f\"risk@{cov}\"] for cov in C.REPORT_COVERAGES}\n", " r[\"t1_ensemble_median\"] = t1_scores(list(med), [ref[i] for i in hidx])\n", " r[\"t1_policy_with_fallbacks\"] = t1_scores(list(final), [ref[i] for i in hidx])\n", " r[\"status_rates\"] = {nm: float(np.mean(status == s)) for s, nm in ((0, \"estimate\"), (1, \"flag\"), (2, \"abstain_reliable_fallback\"), (3, \"abstain_no_reliable_fallback\"))}\n", " r[\"segmentation_safe_records\"] = int(seg_ok.sum())\n", " Xb = med.copy()\n", " Xb[acts == 2] = np.nan\n", " SA = segment_fold(med, hidx, np.full(hidx.size, f), pp, dev, log)\n", " SB = segment_fold(Xb, hidx, np.full(hidx.size, f), pp, dev, log)\n", " FA = t4_features(med, med, SA)[D[\"t4_cols_A\"]]\n", " FB_ = t4_features(Xb, med, SB, acts)[D[\"t4_cols_B\"]]\n", " pA = D[\"t4_gbm_A\"].predict_proba(FA.values)[:, 1]\n", " pB = D[\"t4_gbm_B\"].predict_proba(FB_.values)[:, 1]\n", " dm = SEResNet1D().to(dev)\n", " dm.load_state_dict(torch.load(C.MODELS / \"t4_deep\" / f\"fold{f}\" / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " pD = dpredict(dm, ClsData(med, None, y), np.arange(hidx.size), dev, log)\n", " probs[\"A\"].append(pA)\n", " probs[\"B\"].append(pB)\n", " probs[\"deep\"].append(pD)\n", " so = np.flatnonzero(seg_ok)\n", " r[\"t4_records_segmentation_safe\"] = int(so.size)\n", " if so.size:\n", " for key, p, S in ((\"A\", pA, SA), (\"B\", pB, SB), (\"deep\", pD, SA)):\n", " dc = [dice_counts(S[k], Sref[hidx[k]]) for k in so]\n", " ec = [event_counts(S[k], Sref[hidx[k]]) for k in so]\n", " pk = Pack(y[so], p[so], dc, ec)\n", " r.setdefault(\"t4\", {})[key] = {**pk.values(), **{kk: binary_scores(y[so], p[so])[kk] for kk in (\"brier\", \"ece\")}}\n", " r[\"seconds\"] = time.time() - t0\n", " rep[\"replicates\"][str(f)] = r\n", " store[f] = (med, final, status, SA)\n", " log.info(f\"replicate {f}: passed={r['passed']} ratio@0.9={r['ratio@0.9']} sel_risk={r['selective_risk_estimate']}\")\n", " free_mem()\n", " npass = sum(1 for r in rep[\"replicates\"].values() if r[\"passed\"])\n", " rep[\"gate_S8_holdout\"] = {\"criterion\": load_json(C.RES / \"s35_freeze.json\")[\"holdout_plan\"][\"S8_criterion\"], \"replicates_passing\": npass, \"replicates\": len(rep[\"replicates\"]), \"passed\": bool(npass >= 4)}\n", " rep[\"gate_S8_holdout\"][\"decision\"] = \"Article 2 confirmed on the locked holdout; axis 3 possible\" if rep[\"gate_S8_holdout\"][\"passed\"] else \"Article 2 becomes a negative study on the holdout; axis 3 dropped\"\n", " from .fastm import auroc as fauc\n", " allsafe = np.flatnonzero([len(safe[i]) == C.N_FOLDS for i in hidx])\n", " bag = {\"records_safe_for_all_replicates\": int(allsafe.size)}\n", " if allsafe.size:\n", " for key in probs:\n", " p = np.mean(probs[key], 0)[allsafe]\n", " yy = y[allsafe]\n", " b = binary_scores(yy, p)\n", " bag[key] = {kk: b[kk] for kk in (\"auroc\", \"f1\", \"nmcc\", \"f1_macro\", \"brier\", \"ece\")}\n", " bag[key][\"auroc_ci\"] = boot(lambda i, p=p, yy=yy: fauc(yy[i], p[i]), grp[allsafe])[0]\n", " rep[\"t4_bagged_over_replicates\"] = bag\n", " med0, final0, status0, SA0 = store[0]\n", " fin_ok = bool(np.isfinite(final0).all() and (final0 >= C.FHR_MIN).all() and (final0 <= C.FHR_MAX).all())\n", " lab_ok = bool(np.isin(SA0, (-1, 0, 1)).all())\n", " reps = [report(m.record_id.values[i], SA0[k], float(np.mean([p[k] for p in probs[\"A\"]])), med0[k]) for k, i in enumerate(hidx)]\n", " keys_ok = all(set((\"record_id\", \"baseline_fhr\", \"acceleration_intervals\", \"deceleration_intervals\", \"risk_probability\", \"conclusion\", \"evidence\")) <= set(r_) for r_ in reps)\n", " rep[\"competition_format_checks\"] = {\"t1_4800_finite_in_range\": fin_ok, \"t1_length\": int(final0.shape[1]), \"t2_labels_valid\": lab_ok, \"t4_report_keys\": keys_ok, \"seconds_per_record_per_replicate\": (time.time() - t_start) / max(1, hidx.size * len(rep[\"replicates\"])), \"note\": \"timing excludes DUS feature extraction (cached by s07); check the official submission schema when the validation phase opens\"}\n", " C.PRED.mkdir(parents=True, exist_ok=True)\n", " np.savez(C.PRED / \"holdout_t1.npz\", record_id=m.record_id.values[hidx], median_rep0=med0.astype(np.float32), final_rep0=final0.astype(np.float32), status_rep0=status0)\n", " with open(C.PRED / \"holdout_t4_reports.jsonl\", \"w\") as fh:\n", " for r_ in reps:\n", " fh.write(json.dumps(r_) + \"\\n\")\n", " access[\"accesses\"][-1][\"completed\"] = True\n", " save_json(C.RES / \"holdout_access.json\", access)\n", " save_json(C.RES / \"s36_holdout.json\", rep)\n", " return {\"S8_holdout\": rep[\"gate_S8_holdout\"][\"passed\"], \"replicates_passing\": npass}" ] }, { "cell_type": "code", "execution_count": 26, "id": "c97f0ebe223f", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.017822Z", "iopub.status.busy": "2026-11-28T14:17:33.017425Z", "iopub.status.idle": "2026-11-28T14:17:33.044814Z", "shell.execute_reply": "2026-11-28T14:17:33.042861Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/a1x.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/a1x.py\n", "import itertools\n", "import math\n", "import time\n", "import zlib\n", "from math import factorial\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "from . import config as C\n", "from .fastm import KEYS, Pack, boot, excludes_zero\n", "from .folds import inner_split\n", "from .io import events, fill_linear, valid\n", "from .metrics import dice_counts, dice_from_counts, event_counts, evidence_f1\n", "from .utils import adaptive_batches, device, free_mem, get_logger, is_done, load_df, load_json, mark_done, mm, save_json, save_npz, seed_all, stage\n", "\n", "CONFIGS = [(0, 0), (0, 1), (1, 0), (1, 1)]\n", "DOWN = (\"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\")\n", "SEGM = (\"flow_dice\", \"evidence_f1\")\n", "\n", "\n", "def shapley3(v):\n", " n = 3\n", " out = []\n", " for i in range(n):\n", " s = 0.0\n", " others = [j for j in range(n) if j != i]\n", " for k in range(n):\n", " for S in itertools.combinations(others, k):\n", " a = tuple(1 if (j in S) else 0 for j in range(n))\n", " b = tuple(1 if (j in S or j == i) else 0 for j in range(n))\n", " s += factorial(k) * factorial(n - k - 1) / factorial(n) * (v[b] - v[a])\n", " out.append(s)\n", " return out\n", "\n", "\n", "def derive(vals):\n", " out = {}\n", " for met in DOWN:\n", " v = {cfg: vals[(\"m\",) + cfg][met] for cfg in CONFIGS}\n", " out[f\"shapley_{met}_R\"] = 0.5 * ((v[(1, 0)] - v[(0, 0)]) + (v[(1, 1)] - v[(0, 1)]))\n", " out[f\"shapley_{met}_E\"] = 0.5 * ((v[(0, 1)] - v[(0, 0)]) + (v[(1, 1)] - v[(1, 0)]))\n", " out[f\"interaction_{met}_RxE\"] = v[(1, 1)] - v[(1, 0)] - v[(0, 1)] + v[(0, 0)]\n", " for cfg in CONFIGS[1:]:\n", " out[f\"mismatch_cost_{met}_R{cfg[0]}E{cfg[1]}\"] = vals[(\"m\",) + cfg][met] - vals[(\"x\",) + cfg][met]\n", " v3 = {}\n", " for r, e, k in itertools.product((0, 1), repeat=3):\n", " key = (\"m\", r, e) if (k or (r, e) == (0, 0)) else (\"x\", r, e)\n", " v3[(r, e, k)] = vals[key][met]\n", " for nm, val in zip((\"R\", \"E\", \"K\"), shapley3(v3)):\n", " out[f\"shapley3_{met}_{nm}\"] = val\n", " rr, ee = out[f\"shapley_{met}_R\"], out[f\"shapley_{met}_E\"]\n", " out[f\"R_share_{met}\"] = rr / (rr + ee) if abs(rr + ee) > 1e-9 else 0.5\n", " for met in SEGM:\n", " out[f\"R_effect_{met}\"] = vals[(\"m\", 1, 0)][met] - vals[(\"m\", 0, 0)][met]\n", " return out\n", "\n", "\n", "PRIMARY = [f\"shapley_{m}_{p}\" for m in DOWN for p in (\"R\", \"E\")] + [f\"R_effect_{m}\" for m in SEGM]\n", "\n", "\n", "@stage(\"s37_a1_shapley\", params={\"v\": 2})\n", "def shapley(log):\n", " from .t1 import gather_tcn\n", " from .t2 import ft4_oof_probs, post\n", " from .t3 import feature_table\n", " from .fastm import self_check\n", " from .t4 import crossfit, seg_features\n", " self_check()\n", " dev = device()\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " y = m.y.values\n", " fold_all = m.fold.values\n", " Xref = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " sus = np.load(C.CACHE / \"t1_ref_suspect.npy\") if (C.CACHE / \"t1_ref_suspect.npy\").exists() else np.zeros(Xref.shape, bool)\n", " Xclean = Xref.copy()\n", " Xclean[sus] = np.nan\n", " inputs = {\"reference\": Xref, \"reference_without_suspect\": Xclean}\n", " seeds = [s for s in range(C.T1_SEEDS) if gather_tcn(s)[0] is not None]\n", " for s in seeds:\n", " inputs[f\"estimate_seed{s}\"] = np.stack([fill_linear(x) for x in gather_tcn(s)[0][..., 0]])\n", " ok = fold_all >= 0\n", " segm = {}\n", " for k, X in inputs.items():\n", " P, safe = ft4_oof_probs(X, dev, log)\n", " ok &= safe\n", " S = np.zeros((len(X), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " te = (fold_all == f) & safe\n", " if te.any():\n", " S[te] = post(np.nan_to_num(P[te]), *pp[str(f)])\n", " segm[k] = S\n", " free_mem()\n", " idx = np.flatnonzero(ok)\n", " fold = fold_all[idx]\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " base = {k: feature_table(X[idx]) for k, X in inputs.items()}\n", " rep = {\"n_records\": int(idx.size), \"seeds\": seeds, \"players\": {\"R\": \"reference FHR instead of the out-of-fold estimate\", \"E\": \"reference segmentation instead of the T4-fine-tuned U-Net output\", \"K\": \"classifier matched to its input (3-player game reported for completeness; primary attribution is the 2-player matched game, amended after weeks 1-3)\"}, \"bootstrap\": f\"{C.BOOT} group resamples stratified by fold (pooled); {C.BOOT} group resamples within each fold\", \"variants\": {}}\n", " for ref_name in (\"reference\", \"reference_without_suspect\"):\n", " rv = {}\n", " for s in seeds:\n", " est = f\"estimate_seed{s}\"\n", " feats = {}\n", " for r, e in CONFIGS:\n", " xk = est if r == 0 else ref_name\n", " S = Sref[idx] if e else segm[xk][idx]\n", " feats[(r, e)] = pd.concat([base[xk], seg_features(inputs[xk][idx], S)], axis=1).values\n", " packs = {}\n", " for r, e in CONFIGS:\n", " xk = est if r == 0 else ref_name\n", " S = Sref[idx] if e else segm[xk][idx]\n", " dc = [dice_counts(S[j], Sref[i]) for j, i in enumerate(idx)]\n", " ec = [event_counts(S[j], Sref[i]) for j, i in enumerate(idx)]\n", " pm = crossfit(feats[(r, e)], feats[(r, e)], yy, fold)\n", " packs[(\"m\", r, e)] = Pack(yy, pm, dc, ec)\n", " if (r, e) != (0, 0):\n", " px = crossfit(feats[(0, 0)], feats[(r, e)], yy, fold)\n", " packs[(\"x\", r, e)] = Pack(yy, px, D=packs[(\"m\", r, e)].D, Ev=packs[(\"m\", r, e)].Ev)\n", " keys = list(derive({k: p.values() for k, p in packs.items()}))\n", "\n", " def stat(i):\n", " d = derive({k: p.values(i) for k, p in packs.items()})\n", " return np.array([d[k] for k in keys])\n", "\n", " pooled = boot(stat, groups, strata=fold)\n", " per_fold = {}\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fold == f)\n", " if sel_.size:\n", " res = boot(lambda i, sel_=sel_: stat(sel_[i]), groups[sel_])\n", " per_fold[str(f)] = {k: r_ for k, r_ in zip(keys, res)}\n", " rv[f\"seed{s}\"] = {\"configs\": {\"_\".join(map(str, k)): p.values() for k, p in packs.items()}, \"pooled\": dict(zip(keys, pooled)), \"per_fold\": per_fold}\n", " log.info(f\"{ref_name} seed {s} done\")\n", " rep[\"variants\"][ref_name] = rv\n", " prim = rep[\"variants\"][\"reference\"]\n", " robust = {}\n", " for k in PRIMARY:\n", " signs, fold_ok = [], []\n", " for s in seeds:\n", " d = prim[f\"seed{s}\"][\"pooled\"][k]\n", " signs.append(np.sign(d[\"point\"]) if excludes_zero(d) else 0)\n", " pf = [prim[f\"seed{s}\"][\"per_fold\"][str(f)][k][\"point\"] for f in range(C.N_FOLDS) if str(f) in prim[f\"seed{s}\"][\"per_fold\"]]\n", " fold_ok.append(sum(np.sign(p) == np.sign(d[\"point\"]) for p in pf) >= 4)\n", " robust[k] = {\"ci_excludes_zero_all_seeds_same_sign\": bool(all(x != 0 for x in signs) and len(set(signs)) == 1), \"fold_sign_consistent_all_seeds\": bool(all(fold_ok)), \"sign\": int(signs[0]) if signs else 0}\n", " robust[k][\"robust\"] = robust[k][\"ci_excludes_zero_all_seeds_same_sign\"] and robust[k][\"fold_sign_consistent_all_seeds\"]\n", " n_rob = sum(v[\"robust\"] for v in robust.values())\n", " rep[\"gate_S10_shapley\"] = {\"criterion\": \"pre-registered: an attribution (2-player Shapley R or E for AUROC, F1, nMCC, conclusion F1; R effect for Flow Dice and Evidence F1) is robust when its pooled 95% CI excludes zero with the same sign for every TCN seed and its per-fold point estimate has that sign in >= 4 of 5 folds for every seed; part 1 of S10 needs >= 3 robust attributions\", \"attributions\": robust, \"n_robust\": int(n_rob), \"passed\": bool(n_rob >= 3)}\n", " save_json(C.RES / \"s37_a1_shapley.json\", rep)\n", " return {\"n_robust\": n_rob, \"passed\": rep[\"gate_S10_shapley\"][\"passed\"]}\n", "\n", "\n", "def prop_conditions():\n", " c = [(\"clean\", None, \"all\")]\n", " c += [(f\"noise_sd{s}\", (\"noise\", s), \"all\") for s in (2, 5, 10)]\n", " c += [(f\"bias_{b:+d}\", (\"bias\", b), \"all\") for b in (-10, -5, 5, 10)]\n", " c += [(f\"halving_{d}s\", (\"halve\", d), \"all\") for d in (10, 30, 60)]\n", " c += [(f\"doubling_{d}s\", (\"double\", d), \"all\") for d in (10, 30, 60)]\n", " c += [(f\"gap_{L}s_{w}\", (\"gap\", L, w), \"decel\") for w in (\"before\", \"during\", \"after\", \"away\") for L in (15, 30, 60, 120)]\n", " c += [(f\"mix_{loc}_{int(p * 100)}pct_seed{s}\", (\"mix\", p, loc, s), \"all\") for loc in (\"p_far\", \"true_error\") for s in range(C.T1_SEEDS) for p in (0.1, 0.25, 0.5)]\n", " if C.SMOKE:\n", " keep = {\"clean\", \"noise_sd5\", \"bias_+10\", \"halving_30s\", \"gap_30s_during\", \"gap_30s_before\", \"gap_30s_away\", \"mix_p_far_25pct_seed0\", \"mix_true_error_25pct_seed0\"}\n", " c = [x for x in c if x[0] in keep]\n", " return c\n", "\n", "\n", "FAMILIES = {\"noise\": (\"noise_sd\", (2, 5, 10)), \"bias_pos\": (\"bias_+\", (5, 10)), \"bias_neg\": (\"bias_-\", (5, 10)), \"halving\": (\"halving_\", (10, 30, 60)), \"doubling\": (\"doubling_\", (10, 30, 60))}\n", "\n", "\n", "def perturb2(x, seg, kind, rng, est=None, pfar=None, ref=None):\n", " from .a1 import perturb\n", " if kind[0] == \"gap\" and kind[2] in (\"before\", \"during\", \"after\"):\n", " x = x.copy()\n", " L = int(kind[1] * C.FS_FHR)\n", " ev = events(seg, -1)\n", " a, b = ev[int(rng.integers(0, len(ev)))]\n", " s = {\"before\": a - L, \"during\": (a + b) // 2 - L // 2, \"after\": b}[kind[2]]\n", " s = int(np.clip(s, 0, C.N - L))\n", " x[s:s + L] = np.nan\n", " return x.astype(np.float32)\n", " if kind[0] == \"gap\":\n", " return perturb(x, seg, (\"gap\", kind[1], \"away\"), rng)\n", " if kind[0] == \"double\":\n", " x = x.copy()\n", " L = int(kind[1] * C.FS_FHR)\n", " for _ in range(3):\n", " a = int(rng.integers(0, C.N - L))\n", " x[a:a + L] = np.minimum(x[a:a + L] * 2.0, C.FHR_MAX)\n", " return x.astype(np.float32)\n", " if kind[0] == \"mix\":\n", " x = x.copy()\n", " k = int(kind[1] * C.N)\n", " key = np.nan_to_num(pfar) if kind[2] == \"p_far\" else np.nan_to_num(np.abs(est - ref), nan=-1)\n", " top = np.argsort(-key)[:k]\n", " x[top] = est[top]\n", " x[(x < C.FHR_MIN) | (x > C.FHR_MAX)] = np.nan\n", " return x.astype(np.float32)\n", " return perturb(x, seg, kind, rng)\n", "\n", "\n", "@stage(\"s38_a1_propagation\", params={\"v\": 2})\n", "def propagation(log):\n", " from .t1 import gather_tcn\n", " from .t2 import load_ft4, post, predict_probs, safe_models_for_t4\n", " from .t3 import feature_table, model\n", " from .t4 import seg_features\n", " dev = device()\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " y = m.y.values\n", " Xref = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " safe = safe_models_for_t4()\n", " fold = m.fold.values\n", " ok = (fold >= 0) & np.array([fold[i] in safe[i] for i in range(len(m))])\n", " idx = np.flatnonzero(ok)\n", " fo = fold[idx]\n", " has_dec = np.array([len(events(Sref[i], -1)) > 0 for i in idx])\n", " ests = {}\n", " for s in range(C.T1_SEEDS):\n", " r, _ = gather_tcn(s)\n", " if r is not None:\n", " ests[s] = (r[..., 0], r[..., 2])\n", " models = {f: load_ft4(f, dev) for f in range(C.N_FOLDS)}\n", "\n", " def pipeline_features(X):\n", " S = np.zeros((len(X), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " sel_ = np.flatnonzero(fo == f)\n", " if sel_.size:\n", " pr = predict_probs(models[f], X[sel_], dev, log)\n", " S[sel_] = post(np.nan_to_num(pr.astype(np.float32)), *pp[str(f)])\n", " Fx = pd.concat([feature_table(X), seg_features(X, S)], axis=1).values\n", " return S, Fx\n", "\n", " S0, F0 = pipeline_features(Xref[idx])\n", " clfs = {f: model(int(((fo >= 0) & (fo != f)).sum())).fit(F0[fo != f], y[idx][fo != f]) for f in range(C.N_FOLDS)}\n", " yy = y[idx]\n", " groups = m.group.values[idx]\n", " packs = {}\n", " subset = {}\n", " for name, kind, sub in prop_conditions():\n", " if kind is not None and kind[0] == \"mix\" and kind[3] not in ests:\n", " continue\n", " rng = np.random.default_rng(zlib.crc32(name.encode()) + C.SEED)\n", " rows = np.arange(idx.size) if sub == \"all\" else np.flatnonzero(has_dec)\n", " if kind is None:\n", " S, Fx = S0, F0\n", " else:\n", " Xp = Xref[idx].copy()\n", " for j in rows:\n", " i = idx[j]\n", " if kind[0] == \"mix\":\n", " e, pf = ests[kind[3]]\n", " Xp[j] = perturb2(Xref[i], Sref[i], kind, rng, fill_linear(e[i]), pf[i], Xref[i])\n", " else:\n", " Xp[j] = perturb2(Xref[i], Sref[i], kind, rng)\n", " S, Fx = pipeline_features(Xp)\n", " p = np.full(idx.size, np.nan)\n", " for f in range(C.N_FOLDS):\n", " te = fo == f\n", " if te.any():\n", " p[te] = clfs[f].predict_proba(Fx[te])[:, 1]\n", " dc = [dice_counts(S[j], Sref[i]) for j, i in enumerate(idx)]\n", " ec = [event_counts(S[j], Sref[i]) for j, i in enumerate(idx)]\n", " packs[name] = Pack(yy, p, dc, ec)\n", " subset[name] = rows\n", " log.info(f\"{name}: {packs[name].values(rows)}\")\n", " res = {}\n", " for name in packs:\n", " if name == \"clean\":\n", " continue\n", " rows = subset[name]\n", " stat = lambda i, name=name, rows=rows: packs[name].vec(rows[i]) - packs[\"clean\"].vec(rows[i])\n", " pooled = boot(stat, groups[rows], B=min(C.BOOT, 1000), strata=fo[rows])\n", " per_fold = {}\n", " for f in range(C.N_FOLDS):\n", " sel_ = rows[fo[rows] == f]\n", " if sel_.size:\n", " per_fold[str(f)] = (packs[name].vec(sel_) - packs[\"clean\"].vec(sel_)).tolist()\n", " res[name] = {\"records\": int(rows.size), \"subset\": \"records with >= 1 reference deceleration\" if rows.size < idx.size else \"all\", \"pooled\": dict(zip(KEYS, pooled)), \"per_fold\": per_fold}\n", " stab = {}\n", " sig = 0\n", " stable = 0\n", " for name, r in res.items():\n", " for j, k in enumerate(KEYS):\n", " d = r[\"pooled\"][k]\n", " if not excludes_zero(d):\n", " continue\n", " sig += 1\n", " pf = [v[j] for v in r[\"per_fold\"].values() if np.isfinite(v[j])]\n", " same = sum(np.sign(v) == np.sign(d[\"point\"]) for v in pf)\n", " ok_ = same >= 4\n", " stable += int(ok_)\n", " stab[f\"{name}:{k}\"] = {\"same_sign_folds\": int(same), \"folds\": len(pf), \"stable\": bool(ok_)}\n", " mono = {}\n", " fams = dict(FAMILIES)\n", " for w in (\"before\", \"during\", \"after\", \"away\"):\n", " fams[f\"gap_{w}\"] = (\"gap_\", (15, 30, 60, 120), f\"s_{w}\")\n", " for loc in (\"p_far\", \"true_error\"):\n", " for s in range(C.T1_SEEDS):\n", " fams[f\"mix_{loc}_seed{s}\"] = (f\"mix_{loc}_\", (10, 25, 50), f\"pct_seed{s}\")\n", " for fam, spec in fams.items():\n", " names = [f\"{spec[0]}{v}{spec[2] if len(spec) > 2 else ('s' if fam in ('halving', 'doubling') else '')}\" for v in spec[1]]\n", " names = [n for n in names if n in res]\n", " if len(names) < 2:\n", " continue\n", " mono[fam] = {}\n", " for j, k in enumerate(KEYS):\n", " pts = [res[n][\"pooled\"][k][\"point\"] for n in names]\n", " if not all(np.isfinite(pts)):\n", " continue\n", " d = np.diff(pts)\n", " mono[fam][k] = {\"conditions\": names, \"deltas\": pts, \"monotone\": bool(np.all(d <= 1e-12) or np.all(d >= -1e-12))}\n", " frac = stable / sig if sig else None\n", " rep = {\"n_records\": int(idx.size), \"n_records_with_decel\": int(has_dec.sum()), \"pipeline\": \"T4-fine-tuned U-Net + post-processing + gradient boosting trained on clean reference FHR (cross-fitted); perturbations applied to test-fold reference FHR; gap positions relative to a random reference deceleration; doubling saturates at 210 bpm (in weeks 3-5, doubled values above 210 bpm were set to missing, so that condition measured gaps, not doubling); estimate substitution located by the TCN p_far (realistic) or by the true error (oracle), for each TCN seed\", \"deltas\": res, \"stability\": stab, \"monotonicity\": mono, \"gate_S10_propagation\": {\"criterion\": \"pre-registered: among (condition, metric) deltas whose pooled CI excludes zero, at least 80% have the same sign in >= 4 of 5 folds\", \"significant\": sig, \"stable\": stable, \"fraction_stable\": frac, \"passed\": bool(frac is not None and frac >= 0.8)}}\n", " save_json(C.RES / \"s38_a1_propagation.json\", rep)\n", " return rep[\"gate_S10_propagation\"]\n", "\n", "\n", "class UNet2H(nn.Module):\n", " def __init__(self):\n", " super().__init__()\n", " from .t2 import UNet1D\n", " self.u = UNet1D()\n", " self.seg4 = nn.Conv1d(32, 3, 1)\n", "\n", " def forward(self, x):\n", " u = self.u\n", " n = x.shape[-1]\n", " x = F.pad(x, (0, (-n) % 16), mode=\"replicate\")\n", " skips = []\n", " for e in u.enc:\n", " x = e(x)\n", " skips.append(x)\n", " x = F.max_pool1d(x, 2)\n", " x = u.mid(x)\n", " for up, d, s in zip(u.up, u.dec, reversed(skips)):\n", " x = d(torch.cat([up(x), s], 1))\n", " return u.seg(x)[..., :n], u.base(x)[..., :n], self.seg4(x)[..., :n]\n", "\n", "\n", "@torch.no_grad()\n", "def probs2h(model, X, dev, head, log=None):\n", " from .t2 import inputs\n", " model.eval()\n", "\n", " def fn(i, j):\n", " xs = torch.from_numpy(np.stack([inputs(x)[0] for x in X[i:j]])).to(dev)\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " s2, _, s4 = model(xs)\n", " return torch.softmax((s4 if head == 4 else s2).float(), 1).cpu().numpy().astype(np.float16)\n", "\n", " return np.concatenate(adaptive_batches(len(X), fn, 64, log=log)) if len(X) else np.zeros((0, 3, C.N), np.float16)\n", "\n", "\n", "def train_twohead(force=False, fold=0):\n", " from .t2 import IDX2LAB, T2Data, arr, class_weights, loss_fn, score, t2_meta, t4_meta\n", " name = f\"s39_t2_twohead_f{fold}\"\n", " log = get_logger(name)\n", " params = {\"fold\": fold, \"smoke\": C.SMOKE, \"epochs\": C.EPOCHS_FT}\n", " oof = C.CACHE / f\"t2_twohead_oof_f{fold}.npz\"\n", " if not force and is_done(name, params):\n", " log.info(\"skip: done\")\n", " return\n", " seed_all(C.SEED + 80 + fold)\n", " dev = device()\n", " m2, m4 = t2_meta(), t4_meta()\n", " tr2, va2 = inner_split(m2, fold)\n", " tr4, va4 = inner_split(m4, fold)\n", " d2 = T2Data(tr2)\n", " d4 = T2Data(tr4, arr(\"t4_fhr.npy\"), arr(\"t4_seg.npy\"))\n", " w2, w4 = class_weights(d2.Y[tr2]), class_weights(d4.Y[tr4])\n", " model = UNet2H().to(dev)\n", " init = C.MODELS / \"t2_unet\" / f\"fold{fold}\" / \"best.pt\"\n", " if init.exists():\n", " model.u.load_state_dict(torch.load(init, map_location=dev, weights_only=True)[\"model\"])\n", " model.seg4.load_state_dict(model.u.seg.state_dict())\n", " lr = 3e-4\n", " opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)\n", " steps = max(1, math.ceil(len(tr4) / 16))\n", " sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=C.EPOCHS_FT * steps * 2 + 10, pct_start=0.1)\n", " scaler = torch.amp.GradScaler(enabled=dev.type == \"cuda\")\n", " d = C.MODELS / \"t2_twohead\" / f\"fold{fold}\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " st = {\"epoch\": 0, \"best\": -1.0, \"bad\": 0, \"bs\": 16, \"hist\": [], \"t0\": time.time()}\n", " if (d / \"last.pt\").exists() and not force:\n", " ck = torch.load(d / \"last.pt\", map_location=dev, weights_only=False)\n", " for o, k in ((model, \"model\"), (opt, \"opt\"), (sched, \"sched\"), (scaler, \"scaler\")):\n", " o.load_state_dict(ck[k])\n", " st = ck[\"state\"]\n", " log.info(f\"resumed at epoch {st['epoch']}\")\n", " rng = np.random.default_rng(C.SEED + 80 + fold + st[\"epoch\"])\n", " X4, Y4 = arr(\"t4_fhr.npy\"), arr(\"t4_seg.npy\")\n", " while st[\"epoch\"] < C.EPOCHS_FT and st[\"bad\"] < C.PATIENCE:\n", " model.train()\n", " t0 = time.time()\n", " o4 = rng.permutation(tr4)\n", " tot, nb, k = 0.0, 0, 0\n", " while k < o4.size:\n", " b4 = o4[k:k + st[\"bs\"]]\n", " b2 = rng.choice(tr2, b4.size)\n", " try:\n", " i2, y2, bt2, bm2 = (t.to(dev) for t in d2.batch(b2, rng))\n", " i4, y4, bt4, bm4 = (t.to(dev) for t in d4.batch(b4, rng))\n", " with torch.autocast(dev.type, enabled=dev.type == \"cuda\"):\n", " s2, bs2, _ = model(i2)\n", " _, bs4, s4 = model(i4)\n", " loss = loss_fn(s2, bs2, y2, bt2, bm2, w2) + loss_fn(s4, bs4, y4, bt4, bm4 * 0, w4)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " if sched.last_epoch < sched.total_steps - 1:\n", " sched.step()\n", " tot += float(loss)\n", " nb += 1\n", " k += b4.size\n", " except RuntimeError as e:\n", " if \"out of memory\" not in str(e).lower() or st[\"bs\"] <= 2:\n", " raise\n", " opt.zero_grad(set_to_none=True)\n", " free_mem()\n", " st[\"bs\"] //= 2\n", " log.warning(f\"OOM: batch -> {st['bs']}\")\n", " pv = probs2h(model, X4[va4], dev, 4, log)\n", " sc = score(IDX2LAB[pv.astype(np.float32).argmax(1)], Y4[va4])[\"dice\"]\n", " vd = sc[\"pooled_macro\"]\n", " st[\"epoch\"] += 1\n", " st[\"hist\"].append({\"epoch\": st[\"epoch\"], \"train_loss\": tot / max(1, nb), \"val_t4_dice_macro\": vd, \"sec\": time.time() - t0})\n", " if vd > st[\"best\"] + 1e-4:\n", " st[\"best\"], st[\"bad\"] = vd, 0\n", " torch.save({\"model\": model.state_dict()}, d / \"best.tmp\")\n", " (d / \"best.tmp\").replace(d / \"best.pt\")\n", " else:\n", " st[\"bad\"] += 1\n", " torch.save({\"model\": model.state_dict(), \"opt\": opt.state_dict(), \"sched\": sched.state_dict(), \"scaler\": scaler.state_dict(), \"state\": st}, d / \"last.tmp\")\n", " (d / \"last.tmp\").replace(d / \"last.pt\")\n", " log.info(st[\"hist\"][-1])\n", " if not (d / \"best.pt\").exists():\n", " torch.save({\"model\": model.state_dict()}, d / \"best.pt\")\n", " model.load_state_dict(torch.load(d / \"best.pt\", map_location=dev, weights_only=True)[\"model\"])\n", " te4 = np.flatnonzero(m4.fold.values == fold)\n", " te2 = np.flatnonzero(m2.fold.values == fold)\n", " p4 = probs2h(model, X4[te4], dev, 4, log)\n", " p2 = probs2h(model, arr(\"t2_fhr.npy\")[te2], dev, 2, log)\n", " save_npz(oof, idx4=te4, p4=p4, idx2=te2, p2=p2)\n", " mark_done(name, params, {\"best_val_t4_dice_macro\": st[\"best\"], \"epochs\": st[\"epoch\"], \"history\": st[\"hist\"], \"seconds\": round(time.time() - st[\"t0\"], 1)}, [d / \"best.pt\", oof])\n", "\n", "\n", "def seg_scores(pred, lab, groups):\n", " dc = [dice_counts(p, l) for p, l in zip(pred, lab)]\n", " ec = [event_counts(p, l) for p, l in zip(pred, lab)]\n", " d = dice_from_counts(dc)\n", " e = evidence_f1(ec)\n", " D = np.array([[c[k][j] for k in (0, 1, -1) for j in range(3)] for c in dc])\n", " Ev = np.array([[c[n][j] for n in (\"acc\", \"dec\") for j in range(3)] for c in ec])\n", " return {\"dice_dec_pooled\": d[\"pooled_-1\"], \"dice_acc_pooled\": d[\"pooled_1\"], \"dice_macro_pooled\": d[\"pooled_macro\"], \"dice_dec_record\": d[\"record_-1\"], \"evidence_dec_f1\": e[\"dec_f1\"], \"evidence_acc_f1\": e[\"acc_f1\"], \"evidence_macro_f1\": e[\"macro_f1\"]}, D, Ev\n", "\n", "\n", "def seg_vec(D, Ev, i):\n", " s = D[i].sum(0).reshape(3, 3)\n", " dice = [2 * s[k, 0] / (s[k, 1] + s[k, 2]) if (s[k, 1] + s[k, 2]) else np.nan for k in range(3)]\n", " e = Ev[i].sum(0).reshape(2, 3)\n", " f1 = [2 * e[k, 0] / (2 * e[k, 0] + e[k, 1] + e[k, 2]) if (2 * e[k, 0] + e[k, 1] + e[k, 2]) else np.nan for k in range(2)]\n", " return np.array([dice[2], np.nanmean(dice), f1[1], np.nanmean(f1)])\n", "\n", "\n", "@stage(\"s40_a1_annotation_shift\", params={\"v\": 1})\n", "def annotation_shift(log):\n", " from .t2 import crossfit_post, post, safe_models_for_t4, t2_meta, t4_meta\n", " m4, m2 = t4_meta(), t2_meta()\n", " ev = load_json(C.RES / \"s14_t2_eval.json\")\n", " Y4 = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " P4 = np.asarray(mm(C.CACHE / \"t2_unet_t4ref_probs.npy\"), np.float32)\n", " safe = safe_models_for_t4()\n", " fold = m4.fold.values\n", " th4 = np.full((len(m4), 3, C.N), np.nan, np.float32)\n", " th2 = {}\n", " for f in range(C.N_FOLDS):\n", " p = C.CACHE / f\"t2_twohead_oof_f{f}.npz\"\n", " if p.exists():\n", " with np.load(p) as z:\n", " arrs = {kk: z[kk] for kk in z.files}\n", " th4[arrs[\"idx4\"]] = arrs[\"p4\"].astype(np.float32)\n", " for k, i in enumerate(arrs[\"idx2\"]):\n", " th2[int(i)] = arrs[\"p2\"][k].astype(np.float32)\n", " ok = (fold >= 0) & np.array([fold[i] in safe[i] for i in range(len(m4))]) & np.isfinite(P4[:, 0, 0]) & np.isfinite(th4[:, 0, 0])\n", " idx = np.flatnonzero(ok)\n", " fo = np.where(ok, fold, -1)\n", " S = {}\n", " S[\"1_t2_model_t2_post\"] = post(np.nan_to_num(P4[idx]), *ev[\"unet_t2_on_t4_t2post\"][\"params\"])\n", " S[\"2_t2_model_t4_tuned_post\"] = np.asarray(mm(C.CACHE / \"t2_unet_pred_t4ref.npy\"))[idx]\n", " S[\"3_finetuned_on_t4\"] = np.asarray(mm(C.CACHE / \"t2_ft4_pred_t4ref.npy\"))[idx]\n", " S[\"4_two_head_t4_head\"], _ = crossfit_post(np.nan_to_num(th4[idx]), Y4[idx], fo[idx])\n", " groups = m4.group.values[idx]\n", " rep = {\"n_records\": int(idx.size), \"convention\": \"all scored against the T4 reference segmentation\", \"segmentations\": {}}\n", " DE = {}\n", " for k, s in S.items():\n", " sc, D, Ev = seg_scores(s, Y4[idx], groups)\n", " rep[\"segmentations\"][k] = sc\n", " DE[k] = (D, Ev)\n", " names = [\"dice_dec_pooled\", \"dice_macro_pooled\", \"evidence_dec_f1\", \"evidence_macro_f1\"]\n", " diffs = {}\n", " for a, b in ((\"2_t2_model_t4_tuned_post\", \"1_t2_model_t2_post\"), (\"3_finetuned_on_t4\", \"1_t2_model_t2_post\"), (\"4_two_head_t4_head\", \"3_finetuned_on_t4\"), (\"4_two_head_t4_head\", \"1_t2_model_t2_post\")):\n", " res = boot(lambda i, a=a, b=b: seg_vec(*DE[a], i) - seg_vec(*DE[b], i), groups)\n", " diffs[f\"{a}_minus_{b}\"] = dict(zip(names, res))\n", " rep[\"paired_diffs\"] = diffs\n", " rep[\"prevalence_matched_reference\"] = {\"t2_matched_to_t4_burden\": ev.get(\"unet_t2_on_t2_matched_to_t4_burden\"), \"convention_shift\": ev.get(\"convention_shift\")}\n", " ok2 = np.array(sorted(th2))\n", " if ok2.size:\n", " Y2 = np.asarray(mm(C.CACHE / \"t2_lab.npy\"))\n", " f2 = m2.fold.values\n", " if not (C.CACHE / \"t2_unet_oof_probs.npy\").exists():\n", " from .t2 import load_unet, predict_probs\n", " from .utils import save_npy\n", " dev = device()\n", " X2 = np.asarray(mm(C.CACHE / \"t2_fhr.npy\"), np.float32)\n", " Pn = np.full((len(m2), 3, C.N), np.nan, np.float32)\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(f2 == f)\n", " if te.size:\n", " Pn[te] = predict_probs(load_unet(f, dev), X2[te], dev, log)\n", " save_npy(C.CACHE / \"t2_unet_oof_probs.npy\", Pn.astype(np.float16))\n", " P2u = np.asarray(mm(C.CACHE / \"t2_unet_oof_probs.npy\"), np.float32)\n", " if P2u is not None:\n", " Ph = np.stack([th2[i] for i in ok2])\n", " fo2 = np.full(len(m2), -1)\n", " fo2[ok2] = f2[ok2]\n", " Sa, _ = crossfit_post(np.nan_to_num(P2u[ok2]), Y2[ok2], fo2[ok2])\n", " Sb, _ = crossfit_post(np.nan_to_num(Ph), Y2[ok2], fo2[ok2])\n", " g2 = m2.group.values[ok2]\n", " sa, Da, Ea = seg_scores(Sa, Y2[ok2], g2)\n", " sb, Db, Eb = seg_scores(Sb, Y2[ok2], g2)\n", " rep[\"t2_retention\"] = {\"n_windows\": int(ok2.size), \"t2_unet\": sa, \"two_head_t2_head\": sb, \"diff_two_head_minus_t2_unet\": dict(zip(names, boot(lambda i: seg_vec(Db, Eb, i) - seg_vec(Da, Ea, i), g2)))}\n", " save_json(C.RES / \"s40_a1_annotation_shift.json\", rep)\n", " return {k: round(v[\"dice_dec_pooled\"], 3) for k, v in rep[\"segmentations\"].items()}\n", "\n", "\n", "def near_mask(seg, val, pad):\n", " mk = np.zeros(C.N, bool)\n", " for a, b in events(seg, val):\n", " mk[max(0, a - pad):min(C.N, b + pad)] = True\n", " return mk\n", "\n", "\n", "def miss_counts(X, S, val, pad, recs):\n", " rows = np.zeros((len(recs), 4))\n", " for k, i in enumerate(recs):\n", " bad = ~valid(X[i])\n", " near = near_mask(S[i], val, pad)\n", " rows[k] = (bad[near].sum(), near.sum(), bad[~near].sum(), (~near).sum())\n", " return rows\n", "\n", "\n", "def ratio_of(r, i=None):\n", " r = r if i is None else r[i]\n", " a = r[:, 0].sum() / max(1, r[:, 1].sum())\n", " b = r[:, 2].sum() / max(1, r[:, 3].sum())\n", " return a / b if b > 0 else np.nan\n", "\n", "\n", "def mh_ratio(r, i=None):\n", " r = r if i is None else r[i]\n", " N = r[:, 1] + r[:, 3]\n", " keep = (r[:, 1] > 0) & (r[:, 3] > 0)\n", " num = np.sum(r[keep, 0] * r[keep, 3] / N[keep])\n", " den = np.sum(r[keep, 2] * r[keep, 1] / N[keep])\n", " return num / den if den > 0 else np.nan\n", "\n", "\n", "@stage(\"s41_a1_missingness\", params={\"v\": 1})\n", "def missingness(log):\n", " from .t3 import MISS, feature_table, model\n", " from .fastm import auroc as fauc\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " X = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " S = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " fold = m.fold.values\n", " recs = np.flatnonzero(fold >= 0)\n", " groups = m.group.values[recs]\n", " y = m.y.values[recs]\n", " rep = {\"n_records\": int(recs.size), \"wording\": \"temporal association between signal loss and proximity of decelerations; no causal claim (no motion or transducer-position data)\"}\n", " main = {}\n", " for pad_s in (30, 60, 120):\n", " for val, nm in ((-1, \"dec\"), (1, \"acc\")):\n", " r = miss_counts(X, S, val, pad_s * C.FS_FHR, recs)\n", " main[f\"{nm}_pad{pad_s}s\"] = {\"pooled_ratio\": boot(lambda i, r=r: ratio_of(r, i), groups)[0], \"mantel_haenszel_within_record\": boot(lambda i, r=r: mh_ratio(r, i), groups)[0], \"missing_near\": float(r[:, 0].sum() / max(1, r[:, 1].sum())), \"missing_far\": float(r[:, 2].sum() / max(1, r[:, 3].sum()))}\n", " rep[\"a_window_and_b_within_record\"] = main\n", " r30 = miss_counts(X, S, -1, 30 * C.FS_FHR, recs)\n", " obs = ratio_of(r30)\n", " rng = np.random.default_rng(C.SEED + 41)\n", " R = 30 if C.SMOKE else 300\n", " BAD = np.stack([~valid(X[i]) for i in recs])\n", " NEAR = np.stack([near_mask(S[i], -1, 30 * C.FS_FHR) for i in recs])\n", " null = []\n", " lo_sh, hi_sh = (5 * 60 * C.FS_FHR, C.N - 5 * 60 * C.FS_FHR) if C.N > 10 * 60 * C.FS_FHR else (1, C.N)\n", " cols = np.arange(C.N)\n", " for _ in range(R):\n", " sh = rng.integers(lo_sh, hi_sh, recs.size)\n", " near = NEAR[np.arange(recs.size)[:, None], (cols[None, :] - sh[:, None]) % C.N]\n", " rr = np.stack([(BAD & near).sum(1), near.sum(1), (BAD & ~near).sum(1), (~near).sum(1)], 1).astype(float)\n", " null.append(ratio_of(rr))\n", " null = np.asarray(null)\n", " rep[\"c_permutation_null_circular_shift\"] = {\"observed_ratio_pad30s\": obs, \"null_median\": float(np.nanmedian(null)), \"null_p95\": float(np.nanquantile(null, 0.95)), \"p_value\": float((1 + np.sum(null >= obs)) / (1 + np.isfinite(null).sum())), \"draws\": int(R)}\n", " strata = {}\n", " mr = np.array([1 - valid(X[i]).mean() for i in recs])\n", " terc = np.digitize(mr, np.quantile(mr, [1 / 3, 2 / 3])) if np.unique(mr).size >= 3 else np.zeros(mr.size, int)\n", " for nm, lab in ((\"label\", y), (\"missing_rate_tercile\", terc)):\n", " strata[nm] = {}\n", " for v in np.unique(lab):\n", " sel_ = lab == v\n", " if sel_.sum() >= 5:\n", " strata[nm][str(int(v))] = {\"records\": int(sel_.sum()), \"ratio\": boot(lambda i, s=sel_: ratio_of(r30[s], i), groups[sel_])[0]}\n", " rep[\"b_strata\"] = strata\n", " bins = np.arange(-120, 121, 5)\n", " prof = {}\n", " for val, nm in ((-1, \"dec\"), (1, \"acc\")):\n", " for anchor in (\"onset\", \"end\"):\n", " num = np.zeros(bins.size - 1)\n", " den = np.zeros(bins.size - 1)\n", " for i in recs:\n", " bad = ~valid(X[i])\n", " for a, b in events(S[i], val):\n", " t0 = a if anchor == \"onset\" else b\n", " for j in range(bins.size - 1):\n", " lo, hi = t0 + bins[j] * C.FS_FHR, t0 + bins[j + 1] * C.FS_FHR\n", " lo, hi = max(0, lo), min(C.N, hi)\n", " if hi > lo:\n", " num[j] += bad[lo:hi].sum()\n", " den[j] += hi - lo\n", " prof[f\"{nm}_{anchor}\"] = {\"bin_start_s\": bins[:-1].tolist(), \"missing_rate\": (num / np.maximum(den, 1)).tolist()}\n", " rep[\"d_temporal_profile\"] = prof\n", " pad = 30 * C.FS_FHR\n", "\n", " def fill_near(i):\n", " x = X[i].copy()\n", " bad = ~valid(x)\n", " near = near_mask(S[i], -1, pad)\n", " tgt = bad & near\n", " if tgt.any():\n", " f = fill_linear(x)\n", " x[tgt] = f[tgt]\n", " return x, int(tgt.sum())\n", "\n", " Xn, nfill = [], []\n", " for i in recs:\n", " x, k = fill_near(i)\n", " Xn.append(x)\n", " nfill.append(k)\n", " Xn = np.stack(Xn)\n", " nfill = np.asarray(nfill)\n", "\n", " def fill_random(seed):\n", " r_ = np.random.default_rng(seed)\n", " out = []\n", " for k, i in enumerate(recs):\n", " x = X[i].copy()\n", " bad = np.flatnonzero(~valid(x) & ~near_mask(S[i], -1, pad))\n", " if nfill[k] and bad.size:\n", " pick = r_.choice(bad, size=min(nfill[k], bad.size), replace=False)\n", " x[pick] = fill_linear(x)[pick]\n", " out.append(x)\n", " return np.stack(out)\n", "\n", " fo = fold[recs]\n", "\n", " def oof_p(F):\n", " p = np.full(recs.size, np.nan)\n", " for f in range(C.N_FOLDS):\n", " tr, te = fo != f, fo == f\n", " if te.any():\n", " p[te] = model(int(tr.sum())).fit(F[tr], y[tr]).predict_proba(F[te])[:, 1]\n", " return p\n", "\n", " F0 = feature_table(X[recs])\n", " Fn = feature_table(Xn)\n", " preds = {\"original_all_features\": oof_p(F0.values), \"original_missingness_only\": oof_p(F0[MISS].values), \"filled_near_decel_all_features\": oof_p(Fn.values), \"filled_near_decel_missingness_only\": oof_p(Fn[MISS].values)}\n", " for s in range(1 if C.SMOKE else 3):\n", " Fr = feature_table(fill_random(C.SEED + 410 + s))\n", " preds[f\"filled_random_matched_{s}_all_features\"] = oof_p(Fr.values)\n", " preds[f\"filled_random_matched_{s}_missingness_only\"] = oof_p(Fr[MISS].values)\n", " rep[\"removal_test\"] = {\"filled_points_frac\": float(nfill.sum() / (recs.size * C.N)), \"auroc\": {k: fauc(y, p) for k, p in preds.items()}}\n", " d = {}\n", " for feat in (\"all_features\", \"missingness_only\"):\n", " d[f\"near_minus_original_{feat}\"] = boot(lambda i, feat=feat: fauc(y[i], preds[f\"filled_near_decel_{feat}\"][i]) - fauc(y[i], preds[f\"original_{feat}\"][i]), groups)[0]\n", " d[f\"near_minus_random_{feat}\"] = boot(lambda i, feat=feat: fauc(y[i], preds[f\"filled_near_decel_{feat}\"][i]) - np.mean([fauc(y[i], preds[k][i]) for k in preds if k.startswith(\"filled_random\") and k.endswith(feat)]), groups)[0]\n", " rep[\"removal_test\"][\"paired_auroc_diffs\"] = d\n", " save_json(C.RES / \"s41_a1_missingness.json\", rep)\n", " return {\"ratio_pad30\": main[\"dec_pad30s\"][\"pooled_ratio\"][\"point\"], \"p_perm\": rep[\"c_permutation_null_circular_shift\"][\"p_value\"]}\n", "\n", "\n", "@stage(\"s42_t3_fp_sensitivity\", params={\"v\": 1})\n", "def t3_fp_sensitivity(log):\n", " from sklearn.model_selection import StratifiedGroupKFold\n", " from .fastm import auroc as fauc\n", " from .folds import components, merge\n", " from .t3 import oof\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " F3 = load_df(C.CACHE / \"t3_features.pkl\")\n", " y = m3.y.values\n", " pair = np.arange(len(m3)) // 2\n", " hold = m3.fold.values == -1\n", " cols = list(F3.columns)\n", " allg = merge(pair, *[components(k)[\"t3\"] for k in C.FP_KS])\n", " rep = {\"segment_seconds\": {str(k): k / C.FS_FHR for k in C.FP_KS}, \"main_k\": C.FP_K_MAIN, \"by_k\": {}}\n", " preds = {}\n", " for k in C.FP_KS:\n", " g = merge(pair, components(k)[\"t3\"])\n", " leak = int(sum(np.unique(hold[g == gg]).size > 1 for gg in np.unique(g)))\n", " fold = np.full(len(m3), -1)\n", " rest = np.flatnonzero(~hold)\n", " sg = StratifiedGroupKFold(n_splits=C.N_FOLDS, shuffle=True, random_state=C.SEED + 1)\n", " for f, (_, te) in enumerate(sg.split(np.zeros(rest.size), y[rest], g[rest])):\n", " fold[rest[te]] = f\n", " if k == C.FP_K_MAIN:\n", " fold = m3.fold.values.copy()\n", " p = oof(F3, y, fold, cols)\n", " preds[str(k)] = p\n", " rep[\"by_k\"][str(k)] = {\"n_groups\": int(np.unique(g[~hold]).size), \"groups_linking_holdout_and_training\": leak, \"auroc\": fauc(y[~hold], p[~hold])}\n", " pr = oof(F3, y, m3.fold_random.values, cols)\n", " preds[\"random\"] = pr\n", " rep[\"random_cv_auroc\"] = fauc(y[~hold], pr[~hold])\n", " nh = np.flatnonzero(~hold)\n", " rep[\"paired_vs_main\"] = {kk: boot(lambda i, kk=kk: fauc(y[nh][i], preds[kk][nh][i]) - fauc(y[nh][i], preds[str(C.FP_K_MAIN)][nh][i]), allg[nh], B=min(C.BOOT, 1000))[0] for kk in preds if kk != str(C.FP_K_MAIN)}\n", " rep[\"note\"] = \"paired bootstrap over the union of all fingerprint groups (most conservative grouping); holdout membership fixed to the main folds\"\n", " save_json(C.RES / \"s42_t3_fp_sensitivity.json\", rep)\n", " return {k: round(v[\"auroc\"], 4) for k, v in rep[\"by_k\"].items()}" ] }, { "cell_type": "code", "execution_count": 27, "id": "cfc48e64a4ad", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.049471Z", "iopub.status.busy": "2026-11-28T14:17:33.049103Z", "iopub.status.idle": "2026-11-28T14:17:33.068157Z", "shell.execute_reply": "2026-11-28T14:17:33.066438Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/summary610.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/summary610.py\n", "import numpy as np\n", "\n", "from . import config as C\n", "from .summary import ci, f, g, section_run, table\n", "from .utils import load_json, save_json, stage\n", "\n", "NAMES = [\"s21_t1_risk_policy\", \"s30_t1_families\", \"s31_t1_fallbacks\", \"s34_cascade_mask\", \"s34b_cascade_c_control\", \"s35_freeze\", \"s36_holdout\", \"s37_a1_shapley\", \"s38_a1_propagation\", \"s40_a1_annotation_shift\", \"s41_a1_missingness\", \"s42_t3_fp_sensitivity\"]\n", "\n", "\n", "def s10(r):\n", " a = g(r, \"s37_a1_shapley\", \"gate_S10_shapley\", default={})\n", " b = g(r, \"s38_a1_propagation\", \"gate_S10_propagation\", default={})\n", " p = bool(a.get(\"passed\")) and bool(b.get(\"passed\"))\n", " return {\"shapley\": a.get(\"passed\"), \"n_robust\": a.get(\"n_robust\"), \"propagation\": b.get(\"passed\"), \"fraction_stable\": b.get(\"fraction_stable\"), \"passed\": p, \"decision\": \"Article 1 submitted to EMBC\" if p else \"reduced version for the 2-page ICASSP paper\"}\n", "\n", "\n", "def gates(r):\n", " L = [\"## Gates\", \"\"]\n", " s6p = g(r, \"s30_t1_families\", \"gate_S6_programme\", default={})\n", " rows = [[\"S6 (programme): learned or ensemble score beats disagreement by 15%\", s6p.get(\"passed\"), \"; \".join(f\"{k}: {ci(v.get('pooled_rel_aurc_vs_disagreement'))}, folds {v.get('folds_passing')}/5\" for k, v in s6p.get(\"candidates\", {}).items()), s6p.get(\"decision\")]]\n", " fm = g(r, \"s30_t1_families\", \"gate_S6_flow_matching\", default={})\n", " rows.append([\"S6: flow matching on the quality-cost frontier\", fm.get(\"retained\"), f\"time ratio {f(fm.get('flow_vs_ensemble_time_ratio'), 2)}; wins {fm.get('wins')}\", fm.get(\"decision\")])\n", " s6w = g(r, \"s21_t1_risk_policy\", \"gate_S6\", default={})\n", " rows.append([\"S6 (weeks 3-5): g beats ensemble p_far by 10%\", s6w.get(\"passed\"), ci(s6w.get(\"g_rel_aurc_vs_p_far\")), s6w.get(\"decision\")])\n", " s8o = g(r, \"s21_t1_risk_policy\", \"gate_S8\", default={})\n", " rows.append([\"S8 out-of-fold (pre-registered ranking + calibration)\", s8o.get(\"passed\"), f\"ranking {s8o.get('ranking_passed')}, calibration {s8o.get('calibration_passed')}\", \"\"])\n", " s8h = g(r, \"s36_holdout\", \"gate_S8_holdout\", default={})\n", " rows.append([\"S8 locked holdout (>= 4/5 frozen replicates)\", s8h.get(\"passed\"), f\"{s8h.get('replicates_passing')}/{s8h.get('replicates')} replicates\", s8h.get(\"decision\")])\n", " t = s10(r)\n", " rows.append([\"S10 Article 1 (robust Shapley >= 3 and stable propagation)\", t[\"passed\"], f\"robust attributions {t['n_robust']}, stable fraction {f(t['fraction_stable'], 2)}\", t[\"decision\"]])\n", " return L + table([\"gate\", \"passed\", \"evidence\", \"decision\"], rows)\n", "\n", "\n", "def sec_w6(r):\n", " s = r[\"s30_t1_families\"]\n", " if not s:\n", " return []\n", " L = [\"\", \"## Week 6 · Four families of uncertainty scores, probabilistic estimators, flow matching\", \"\", f\"Records {s.get('n_records')} · points for AURC {s.get('points_for_aurc')} · K = {s.get('K_samples')} samples · {s.get('flow_steps')} flow steps\", \"\"]\n", " L += table([\"estimator\", \"RMSE\", \"MAE\", \"|e|>10 rate\"], [[k, f(v[\"rmse\"], 2), f(v[\"mae\"], 2), f(v[\"big_rate\"], 4)] for k, v in s.get(\"point_accuracy\", {}).items()])\n", " L += [\"\"] + table([\"distribution\", \"CRPS\", \"CRPS (K samples)\", \"energy score 60 s\", \"cov50\", \"cov80\", \"cov90\", \"width80\"], [[k, f(v[\"crps_exact_or_sample\"]), f(v[\"crps_sample_K\"]), f(v[\"energy_score_60s\"], 2), f(v[\"coverage50\"]), f(v[\"coverage80\"]), f(v[\"coverage90\"]), f(v[\"width80\"], 2)] for k, v in s.get(\"probabilistic_quality\", {}).items()])\n", " L += [\"\", \"Paired differences versus the ensemble (negative = better):\"] + [f\"- {k}: CRPS {ci(v['crps_sample_K'], 4)} · energy score {ci(v['energy_score'], 3)}\" for k, v in s.get(\"paired_vs_ens5\", {}).items()]\n", " L += [\"\"] + table([\"score\", \"AURC (common estimator)\", \"risk@0.9\", \"risk@0.8\", \"AURC (own estimator)\", \"own estimator\", \"Spearman\"], [[k, f(v[\"common_estimator_ens3\"][\"aurc\"], 5), f(v[\"common_estimator_ens3\"][\"risk@0.9\"], 4), f(v[\"common_estimator_ens3\"][\"risk@0.8\"], 4), f(v[\"own_estimator\"][\"aurc\"], 5), v[\"own_estimator\"][\"estimator\"], f(v[\"spearman_abs_err_common\"])] for k, v in s.get(\"selective\", {}).items()])\n", " rc = s.get(\"recalibration\")\n", " if rc:\n", " L += [\"\", f\"Recalibration (temperature per fold, {rc.get('method')}): T = {rc.get('temperature')}; best ensemble variant: {rc.get('best_ensemble_variant')}\", \"\"]\n", " L += table([\"distribution\", \"CRPS (same points)\", \"cov50\", \"cov80\", \"cov90\"], [[k, f(v[\"crps\"]), f(v[\"coverage50\"]), f(v[\"coverage80\"]), f(v[\"coverage90\"])] for k, v in rc.get(\"on_points\", {}).items()])\n", " L += [\"\", \"Paired CRPS differences versus the best ensemble variant (negative = better):\"] + [f\"- {k}: {ci(v, 4)}\" for k, v in rc.get(\"paired_crps_vs_best_ensemble\", {}).items()]\n", " ev = s.get(\"events\", {})\n", " if ev:\n", " L += [\"\", \"Events on sampled trajectories versus point estimates (reference segmentation):\", \"\"]\n", " L += table([\"source\", \"records\", \"dec F1\", \"dec invented/h\", \"dec lost\", \"dec shifted\", \"acc F1\", \"acc invented/h\", \"acc lost\"], [[k, v[\"records\"], f(v.get(\"dec_f1\")), f(v.get(\"dec_invented_per_hour\"), 2), f(v.get(\"dec_lost_frac\")), f(v.get(\"dec_shifted_frac_of_matched\")), f(v.get(\"acc_f1\")), f(v.get(\"acc_invented_per_hour\"), 2), f(v.get(\"acc_lost_frac\"))] for k, v in ev.items()])\n", " tm = s.get(\"inference_cost\", {})\n", " if tm:\n", " L += [\"\", \"Inference cost (fold-0 models, same device):\", \"\"] + table([\"method\", \"s / record\", \"peak GPU GB\"], [[k, f(v[\"s_per_record\"], 4), f(v.get(\"peak_gpu_gb\"), 2)] for k, v in tm.items() if isinstance(v, dict)])\n", " return L\n", "\n", "\n", "def sec_w7(r):\n", " L = []\n", " s = r[\"s31_t1_fallbacks\"]\n", " if s:\n", " L += [\"\", \"## Week 7 · Fallbacks for abstained zones (competition needs 4 800 finite values)\", \"\"]\n", " L += [f\"- zones: {s.get('zones')}\", f\"- status rates: {s.get('status_rates')}\", f\"- |e|>10 rate by status: {s.get('big_rate_by_status')}\", f\"- chosen fallback share: {s.get('chosen_fallback_share')}\", f\"- share of abstained big errors flagged 'no reliable fallback': {f(s.get('no_reliable_fallback_captures_big_errors_of_abstained'))}\", f\"- RMSE with fallbacks minus ensemble median everywhere: {ci(s.get('rmse_fallbacks_minus_median'), 4)}\"]\n", " ct = s.get(\"competition_t1\", {})\n", " if ct:\n", " L += table([\"T1 output\", \"RMSE\", \"MAE\"], [[k, f(v[\"rmse_pooled\"], 3), f(v[\"mae_pooled\"], 3)] for k, v in ct.items() if isinstance(v, dict)])\n", " fe = s.get(\"fallback_error_in_abstained_points\")\n", " if fe:\n", " L += [\"\", f\"Fallback errors inside abstained zones: {fe}\"]\n", " c = r[\"s34_cascade_mask\"]\n", " if c:\n", " L += [\"\", \"## Week 7 · Abstention mask as an input channel (cascade B)\", \"\", c.get(\"notes\", \"\"), \"\"]\n", " L += table([\"segmentation\", \"Flow Dice\", \"Evidence F1\", \"AUROC (GBM)\", \"F1\", \"nMCC\"], [[k, f(v[\"flow_dice\"]), f(v[\"evidence_f1\"]), f(v[\"auroc\"]), f(v[\"f1\"]), f(v[\"nmcc\"])] for k, v in c.get(\"segmentation_and_gbm_risk\", {}).items()])\n", " L += [\"\", \"Paired differences:\"] + [f\"- {k}: \" + \", \".join(f\"{kk} {ci(vv)}\" for kk, vv in v.items()) for k, v in c.get(\"paired_diffs\", {}).items()]\n", " rl = c.get(\"record_level_abstention\", {})\n", " for k, v in rl.items():\n", " for cov, d in v.items():\n", " L += [f\"- record-level abstention {k} @ {cov}: error all {f(d['error_all'])}, abstention rule {f(d['error_reported_abstain_rule'])}, confidence rule {f(d['error_reported_confidence_rule'])}, diff {ci(d['diff_abstain_minus_confidence'])}\"]\n", " cc = r[\"s34b_cascade_c_control\"]\n", " if cc:\n", " L += [\"\", \"## Week 7 · Is the gain of cascade C due to propagated uncertainty?\", \"\", cc.get(\"control\", \"\"), \"\"]\n", " L += table([\"cascade\", \"AUROC\", \"Brier\", \"ECE\", \"F1\", \"nMCC\"], [[k, f(v[\"auroc\"]), f(v[\"brier\"]), f(v[\"ece\"]), f(v[\"f1\"]), f(v[\"nmcc\"])] for k, v in cc.get(\"values\", {}).items()])\n", " L += [\"\", \"- C − C0: \" + \", \".join(f\"{k} {ci(v)}\" for k, v in cc.get(\"C_minus_C0\", {}).items()), \"- C0 − A: \" + \", \".join(f\"{k} {ci(v)}\" for k, v in cc.get(\"C0_minus_A\", {}).items()), f\"- {cc.get('interpretation_rule')}\"]\n", " return L\n", "\n", "\n", "def sec_w8(r):\n", " L = []\n", " fz = r[\"s35_freeze\"]\n", " if fz:\n", " L += [\"\", \"## Week 8 · Freeze and locked holdout\", \"\", f\"Freeze hash `{str(fz.get('freeze_hash'))[:16]}` · reproduction check {fz.get('reproduction_check')} · files frozen {len(fz.get('files', {}))}\", \"\", f\"Plan: {fz.get('holdout_plan', {}).get('S8_criterion')}\"]\n", " h = r[\"s36_holdout\"]\n", " if h:\n", " rows = []\n", " for k, v in h.get(\"replicates\", {}).items():\n", " rows.append([k, f(v[\"risk_full\"], 4), ci(v[\"ratio@0.9\"]), ci(v[\"ratio@0.8\"]), ci(v[\"selective_risk_estimate\"], 4), f(v[\"coverage_estimate\"]), v[\"passed\"], f(v[\"t1_ensemble_median\"][\"rmse_pooled\"], 2), f(v[\"t1_policy_with_fallbacks\"][\"rmse_pooled\"], 2)])\n", " L += [\"\", f\"Holdout records: {h.get('n_holdout_records')}\", \"\"] + table([\"replicate\", \"risk full\", \"risk@0.9 / full\", \"risk@0.8 / full\", \"selective risk (estimate)\", \"coverage estimate\", \"passed\", \"RMSE median\", \"RMSE with fallbacks\"], rows)\n", " b = h.get(\"t4_bagged_over_replicates\", {})\n", " if b:\n", " L += [\"\", f\"T4 on the holdout (bagged over replicates, records safe for every replicate: {b.get('records_safe_for_all_replicates')}):\"] + [f\"- {k}: AUROC {ci(v.get('auroc_ci'))}, F1 {f(v.get('f1'))}, nMCC {f(v.get('nmcc'))}, Brier {f(v.get('brier'))}, ECE {f(v.get('ece'))}\" for k, v in b.items() if isinstance(v, dict)]\n", " for k, v in h.get(\"replicates\", {}).items():\n", " ps = v.get(\"per_observable_stratum\")\n", " if ps:\n", " L += [f\"- replicate {k} risk in the estimate zone by observable stratum: \" + \"; \".join(f\"{s}: coverage {f(d['coverage_estimate'])}, risk {ci(d['risk_estimate'], 4)}\" for s, d in ps.items())]\n", " L += [\"\", f\"Competition-format checks: {h.get('competition_format_checks')}\"]\n", " return L\n", "\n", "\n", "def sec_a1(r):\n", " L = []\n", " s = r[\"s37_a1_shapley\"]\n", " if s:\n", " L += [\"\", \"## Weeks 9-10 · Article 1: attribution (2-player Shapley, 3 TCN seeds)\", \"\", f\"Records {s.get('n_records')} · seeds {s.get('seeds')} · {s.get('bootstrap')}\", \"\"]\n", " rob = g(s, \"gate_S10_shapley\", \"attributions\", default={})\n", " rows = []\n", " for k in rob:\n", " cells = [k]\n", " for sd in s.get(\"seeds\", []):\n", " cells.append(ci(g(s, \"variants\", \"reference\", f\"seed{sd}\", \"pooled\", k)))\n", " cells.append(ci(g(s, \"variants\", \"reference_without_suspect\", \"seed0\", \"pooled\", k)))\n", " cells.append(rob[k][\"robust\"])\n", " rows.append(cells)\n", " L += table([\"attribution\"] + [f\"seed {sd}\" for sd in s.get(\"seeds\", [])] + [\"seed 0, suspect reference removed\", \"robust\"], rows)\n", " L += [\"\", \"3-player game (R, E, K), seed 0, reported for completeness:\"] + [f\"- {k}: {ci(v)}\" for k, v in g(s, \"variants\", \"reference\", \"seed0\", \"pooled\", default={}).items() if k.startswith(\"shapley3_\")]\n", " p = r[\"s38_a1_propagation\"]\n", " if p:\n", " gp = p.get(\"gate_S10_propagation\", {})\n", " L += [\"\", \"## Article 1: propagation curves\", \"\", f\"Records {p.get('n_records')} (with decelerations {p.get('n_records_with_decel')}) · significant deltas {gp.get('significant')} · stable {gp.get('stable')} · fraction {f(gp.get('fraction_stable'), 2)}\", \"\"]\n", " rows = [[k, v[\"records\"]] + [ci(v[\"pooled\"][m]) for m in (\"flow_dice\", \"evidence_f1\", \"auroc\")] for k, v in p.get(\"deltas\", {}).items()]\n", " L += table([\"condition\", \"records\", \"Δ Flow Dice\", \"Δ Evidence F1\", \"Δ AUROC\"], rows)\n", " mono = p.get(\"monotonicity\", {})\n", " if mono:\n", " L += [\"\", \"Monotone dose-response (pooled deltas): \" + \"; \".join(f\"{fam}: \" + \", \".join(f\"{k}={v['monotone']}\" for k, v in d.items()) for fam, d in mono.items())]\n", " a = r[\"s40_a1_annotation_shift\"]\n", " if a:\n", " L += [\"\", \"## Article 1: annotation shift (scored on the T4 convention)\", \"\"]\n", " L += table([\"segmentation\", \"Dice dec (pooled)\", \"Dice macro\", \"Dice dec (record)\", \"Evidence dec F1\", \"Evidence macro F1\"], [[k, f(v[\"dice_dec_pooled\"]), f(v[\"dice_macro_pooled\"]), f(v[\"dice_dec_record\"]), f(v[\"evidence_dec_f1\"]), f(v[\"evidence_macro_f1\"])] for k, v in a.get(\"segmentations\", {}).items()])\n", " L += [\"\", \"Paired differences:\"] + [f\"- {k}: \" + \", \".join(f\"{kk} {ci(vv)}\" for kk, vv in v.items()) for k, v in a.get(\"paired_diffs\", {}).items()]\n", " if a.get(\"t2_retention\"):\n", " L += [\"- T2 retention of the two-head model: \" + \", \".join(f\"{kk} {ci(vv)}\" for kk, vv in a[\"t2_retention\"][\"diff_two_head_minus_t2_unet\"].items())]\n", " mi = r[\"s41_a1_missingness\"]\n", " if mi:\n", " L += [\"\", \"## Article 1: missingness near decelerations\", \"\", mi.get(\"wording\", \"\"), \"\"]\n", " L += table([\"window\", \"pooled ratio\", \"Mantel-Haenszel (within record)\", \"near\", \"far\"], [[k, ci(v[\"pooled_ratio\"], 2), ci(v[\"mantel_haenszel_within_record\"], 2), f(v[\"missing_near\"], 4), f(v[\"missing_far\"], 4)] for k, v in mi.get(\"a_window_and_b_within_record\", {}).items()])\n", " L += [\"\", f\"Permutation null (circular shift): {mi.get('c_permutation_null_circular_shift')}\", \"Strata: \" + \"; \".join(f\"{k}: \" + \", \".join(f\"{kk} {ci(vv['ratio'], 2)}\" for kk, vv in v.items()) for k, v in mi.get(\"b_strata\", {}).items()), f\"Removal test AUROC: {mi.get('removal_test', {}).get('auroc')}\"] + [f\"- {k}: {ci(v)}\" for k, v in g(mi, \"removal_test\", \"paired_auroc_diffs\", default={}).items()]\n", " t3 = r[\"s42_t3_fp_sensitivity\"]\n", " if t3:\n", " L += [\"\", \"## T3 fingerprint-length sensitivity\", \"\"] + table([\"segment k (s)\", \"groups\", \"groups linking holdout\", \"AUROC\"], [[f\"{k} ({t3['segment_seconds'][k]:.0f})\", v[\"n_groups\"], v[\"groups_linking_holdout_and_training\"], f(v[\"auroc\"], 4)] for k, v in t3.get(\"by_k\", {}).items()])\n", " L += [f\"- random CV AUROC {f(t3.get('random_cv_auroc'), 4)}\"] + [f\"- {k} minus main: {ci(v, 4)}\" for k, v in t3.get(\"paired_vs_main\", {}).items()]\n", " return L\n", "\n", "\n", "def sec_training():\n", " L = [\"\", \"## Training (weeks 6-10)\", \"\"]\n", " rows = []\n", " for pat, key in ((\"s10_t1_tcn_f\", \"best_val_rmse\"), (\"s28_t1_laplace_f\", \"best_val\"), (\"s29_t1_flow_f\", \"best_val\"), (\"s32_t2_est_f\", \"best_val_dice_macro\"), (\"s32b_t2_estmask_f\", \"best_val_dice_macro\"), (\"s33_t4_deep_mask_f\", \"best_val_auroc\"), (\"s39_t2_twohead_f\", \"best_val_t4_dice_macro\")):\n", " for p in sorted(C.STATE.glob(f\"{pat}*.done.json\")):\n", " info = load_json(p)[\"info\"]\n", " rows.append([p.name.replace(\".done.json\", \"\"), key, f(info.get(key)), info.get(\"epochs\"), f(info.get(\"seconds\"), 0)])\n", " return L + table([\"job\", \"metric\", \"best\", \"epochs\", \"seconds\"], rows)\n", "\n", "\n", "def figures(r):\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", " out = []\n", " s = r[\"s30_t1_families\"]\n", " if s:\n", " fig, axs = plt.subplots(1, 2, figsize=(13, 4))\n", " for k, v in s.get(\"selective\", {}).items():\n", " c = v[\"common_estimator_ens3\"]\n", " axs[0].plot([1.0, 0.9, 0.8, 0.7], [c[\"risk_full\"], c[\"risk@0.9\"], c[\"risk@0.8\"], c[\"risk@0.7\"]], marker=\"o\", ms=3, label=k)\n", " axs[0].set_yscale(\"log\")\n", " axs[0].invert_xaxis()\n", " axs[0].set_xlabel(\"coverage\")\n", " axs[0].set_title(\"Rate of |e|>10 bpm of the 3-seed ensemble, ranked by each score\")\n", " axs[0].legend(fontsize=6)\n", " pq = s.get(\"probabilistic_quality\", {})\n", " ks = list(pq)\n", " x = np.arange(len(ks))\n", " for j, lvl in enumerate(C.COVER_LEVELS):\n", " axs[1].bar(x + 0.25 * (j - 1), [pq[k][f\"coverage{int(100 * lvl)}\"] - lvl for k in ks], width=0.25, label=f\"{int(100 * lvl)}%\")\n", " axs[1].axhline(0, color=\"k\", lw=0.6)\n", " axs[1].set_xticks(x)\n", " axs[1].set_xticklabels(ks, fontsize=8)\n", " axs[1].set_title(\"Interval coverage minus nominal\")\n", " axs[1].legend(fontsize=7)\n", " fig.tight_layout()\n", " p = C.FIG / \"w610_families.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " h = r[\"s36_holdout\"]\n", " if h and h.get(\"replicates\"):\n", " fig, ax = plt.subplots(figsize=(8, 3.5))\n", " for j, cov in enumerate(C.REPORT_COVERAGES):\n", " ks = sorted(h[\"replicates\"])\n", " pts = np.array([h[\"replicates\"][k][f\"ratio@{cov}\"][\"point\"] for k in ks])\n", " lo = np.array([h[\"replicates\"][k][f\"ratio@{cov}\"][\"lo\"] or np.nan for k in ks])\n", " hi = np.array([h[\"replicates\"][k][f\"ratio@{cov}\"][\"hi\"] or np.nan for k in ks])\n", " xs = np.arange(len(ks)) + 0.15 * (j - 0.5)\n", " ax.errorbar(xs, pts, yerr=np.clip(np.nan_to_num(np.vstack([pts - lo, hi - pts])), 0, None), fmt=\"o\", capsize=3, label=f\"coverage {cov}\")\n", " ax.axhline(1 - C.S8_REDUCTION, color=\"tab:red\", ls=\"--\", lw=0.8, label=\"S8 threshold\")\n", " ax.set_xticks(np.arange(len(ks)))\n", " ax.set_xticklabels([f\"replicate {k}\" for k in ks])\n", " ax.set_ylabel(\"big-error rate / rate without abstention\")\n", " ax.set_title(\"Locked holdout: frozen policy per replicate\")\n", " ax.legend(fontsize=7)\n", " fig.tight_layout()\n", " p = C.FIG / \"w610_holdout.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " s = r[\"s37_a1_shapley\"]\n", " if s:\n", " keys = list(g(s, \"gate_S10_shapley\", \"attributions\", default={}))\n", " if keys:\n", " fig, ax = plt.subplots(figsize=(9, 0.4 * len(keys) + 1.5))\n", " for j, sd in enumerate(s.get(\"seeds\", [])):\n", " d = g(s, \"variants\", \"reference\", f\"seed{sd}\", \"pooled\", default={})\n", " pts = np.array([d[k][\"point\"] for k in keys])\n", " lo = np.array([d[k][\"lo\"] if d[k][\"lo\"] is not None else np.nan for k in keys])\n", " hi = np.array([d[k][\"hi\"] if d[k][\"hi\"] is not None else np.nan for k in keys])\n", " ax.errorbar(pts, np.arange(len(keys)) + 0.2 * (j - 1), xerr=np.clip(np.nan_to_num(np.vstack([pts - lo, hi - pts])), 0, None), fmt=\"o\", ms=3, capsize=2, label=f\"seed {sd}\")\n", " ax.axvline(0, color=\"k\", lw=0.6)\n", " ax.set_yticks(np.arange(len(keys)))\n", " ax.set_yticklabels(keys, fontsize=7)\n", " ax.invert_yaxis()\n", " ax.legend(fontsize=7)\n", " ax.set_title(\"Attributions with 95% CI (group bootstrap stratified by fold)\")\n", " fig.tight_layout()\n", " p = C.FIG / \"w610_shapley.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " pr = r[\"s38_a1_propagation\"]\n", " if pr and pr.get(\"monotonicity\"):\n", " fams = [k for k in pr[\"monotonicity\"] if \"flow_dice\" in pr[\"monotonicity\"][k]][:8]\n", " if fams:\n", " fig, axs = plt.subplots(1, 3, figsize=(15, 4))\n", " for ax, met in zip(axs, (\"flow_dice\", \"evidence_f1\", \"auroc\")):\n", " j = [\"flow_dice\", \"evidence_f1\", \"auroc\", \"f1\", \"nmcc\", \"conclusion_f1\"].index(met)\n", " for fam in fams:\n", " d = pr[\"monotonicity\"][fam].get(met)\n", " if not d:\n", " continue\n", " ln, = ax.plot(range(len(d[\"deltas\"])), d[\"deltas\"], marker=\"o\", label=fam)\n", " for fo in range(C.N_FOLDS):\n", " pf = [pr[\"deltas\"][n][\"per_fold\"].get(str(fo), [np.nan] * 6)[j] for n in d[\"conditions\"]]\n", " ax.plot(range(len(pf)), pf, color=ln.get_color(), lw=0.4, alpha=0.5)\n", " ax.axhline(0, color=\"k\", lw=0.6)\n", " ax.set_xlabel(\"intensity level\")\n", " ax.set_title(f\"Δ {met} (thin lines: folds)\")\n", " axs[0].legend(fontsize=6)\n", " fig.tight_layout()\n", " p = C.FIG / \"w610_propagation.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " mi = r[\"s41_a1_missingness\"]\n", " if mi and mi.get(\"d_temporal_profile\"):\n", " fig, ax = plt.subplots(figsize=(8, 3.5))\n", " for k, v in mi[\"d_temporal_profile\"].items():\n", " ax.plot(v[\"bin_start_s\"], v[\"missing_rate\"], label=k)\n", " ax.axvline(0, color=\"k\", lw=0.6)\n", " ax.set_xlabel(\"seconds from event onset or end\")\n", " ax.set_ylabel(\"missing rate\")\n", " ax.set_title(\"Signal loss around reference events (T4)\")\n", " ax.legend(fontsize=7)\n", " fig.tight_layout()\n", " p = C.FIG / \"w610_missing_profile.png\"\n", " fig.savefig(p, dpi=130)\n", " plt.close(fig)\n", " out.append(p)\n", " return out\n", "\n", "\n", "@stage(\"s43_summary_w610\", params={\"v\": 1})\n", "def run(log):\n", " r = {n: load_json(C.RES / f\"{n}.json\", {}) for n in NAMES}\n", " lines = [f\"# CTG weeks 6-10 summary ({'SMOKE' if C.SMOKE else 'FULL'} run)\", \"\", \"Independence levels: T1/T4 results are N2 (record, fingerprint-merged groups); T3 results are N2 (pairs + fingerprints); no patient-level (N3) guarantee exists for GC-9 data.\", \"\"]\n", " for sec in (gates(r), sec_w6(r), sec_w7(r), sec_w8(r), sec_a1(r), sec_training(), section_run()):\n", " lines += sec\n", " figs = figures(r)\n", " lines += [\"\", \"## Figures\", \"\"] + [f\"- {p}\" for p in figs]\n", " (C.OUT / \"SUMMARY_W6_10.md\").write_text(\"\\n\".join(str(x) for x in lines))\n", " gs = {\"S6_programme\": g(r, \"s30_t1_families\", \"gate_S6_programme\"), \"S6_flow_matching\": g(r, \"s30_t1_families\", \"gate_S6_flow_matching\"), \"S8_holdout\": g(r, \"s36_holdout\", \"gate_S8_holdout\"), \"S10\": s10(r)}\n", " save_json(C.RES / \"s43_gates.json\", gs)\n", " return {\"S6\": g(gs, \"S6_programme\", \"passed\"), \"FM\": g(gs, \"S6_flow_matching\", \"retained\"), \"S8_holdout\": g(gs, \"S8_holdout\", \"passed\"), \"S10\": gs[\"S10\"][\"passed\"]}" ] }, { "cell_type": "code", "execution_count": 28, "id": "c3c9edc333b4", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.072531Z", "iopub.status.busy": "2026-11-28T14:17:33.072178Z", "iopub.status.idle": "2026-11-28T14:17:33.092812Z", "shell.execute_reply": "2026-11-28T14:17:33.090972Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/w11.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/w11.py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .fastm import auroc as fauc\n", "from .fastm import boot\n", "from .io import events, fill_linear, valid\n", "from .metrics import binary_scores, crps_discrete, fhr_abs_errors, risk_coverage\n", "from .t1 import meta, ref_fhr, sfx, strata\n", "from .utils import device, free_mem, load_json, mm, open_memmap_new, finalize_memmap, save_json, save_npz, stage\n", "\n", "GRID = C.BPM.astype(np.float64)\n", "EDGES = np.r_[GRID - 0.5, GRID[-1] + 0.5]\n", "LEVELS = {0.5: (0.25, 0.75), 0.8: (0.1, 0.9), 0.9: (0.05, 0.95)}\n", "\n", "\n", "def cdf_at(P, y):\n", " cdf = np.cumsum(P, 1)\n", " k = np.clip(np.floor(y - GRID[0] + 0.5).astype(int), 0, C.NB - 1)\n", " lo = np.where(k > 0, cdf[np.arange(y.size), np.maximum(k - 1, 0)], 0.0)\n", " frac = np.clip(y - (GRID[k] - 0.5), 0, 1)\n", " return np.clip(lo + P[np.arange(y.size), k] * frac, 0, 1)\n", "\n", "\n", "def quant(cdf, q):\n", " return GRID[np.minimum((cdf < q).sum(1), C.NB - 1)]\n", "\n", "\n", "def dist_metrics(P, y):\n", " cdf = np.cumsum(P, 1)\n", " out = {\"crps\": crps_discrete(P, y)}\n", " for lvl, (a, b) in LEVELS.items():\n", " lo, hi = quant(cdf, a), quant(cdf, b)\n", " out[f\"cov{int(100 * lvl)}\"] = (y >= lo) & (y <= hi)\n", " out[f\"wid{int(100 * lvl)}\"] = hi - lo\n", " out[\"pit\"] = cdf_at(P, y)\n", " return out\n", "\n", "\n", "def temper(P, T):\n", " Q = np.power(np.clip(P, 1e-12, None), 1.0 / T)\n", " return Q / Q.sum(1, keepdims=True)\n", "\n", "\n", "def isotonic_map(pit_cal):\n", " s = np.sort(pit_cal)\n", " xs = np.r_[0.0, s, 1.0]\n", " ys = np.r_[0.0, (np.arange(1, s.size + 1) - 0.5) / s.size, 1.0]\n", " return xs, ys\n", "\n", "\n", "def apply_iso(P, xs, ys):\n", " cdf = np.cumsum(P, 1)\n", " r = np.interp(np.clip(cdf, 0, 1), xs, ys)\n", " r[:, -1] = 1.0\n", " Q = np.diff(np.c_[np.zeros(len(P)), r], axis=1)\n", " Q = np.clip(Q, 0, None)\n", " return Q / Q.sum(1, keepdims=True)\n", "\n", "\n", "def pit_ece(pit):\n", " u = np.linspace(0.05, 0.95, 19)\n", " return float(np.mean(np.abs(np.mean(pit[:, None] <= u[None], 0) - u)))\n", "\n", "\n", "@stage(\"s44_t1_recalibration\", params={\"v\": 1})\n", "def recalibration(log):\n", " from .sel import ens\n", " m = meta()\n", " ref = ref_fhr()\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " rng = np.random.default_rng(C.SEED + 44)\n", " st = strata(m, ref)\n", " fams = {\"ens5\": [s for s in range(C.T1_SEEDS_FAMILY)], \"tcn_seed0\": [0], \"tcn_sharp\": [\"sharp\"]}\n", " have = {k: all((C.CACHE / (f\"t1_tcnsharp_probs_f{f}.npy\" if s == \"sharp\" else f\"t1_tcn_probs_f{f}{sfx(s)}.npy\")).exists() for f in range(C.N_FOLDS) for s in v) for k, v in fams.items()}\n", " fams = {k: v for k, v in fams.items() if have[k]}\n", " if \"ens5\" not in fams:\n", " raise RuntimeError(\"161-bin probabilities of the 5 TCN seeds are missing; the orchestrator regenerates them before this stage\")\n", " picks = {}\n", " for i in ok:\n", " v = np.flatnonzero(valid(ref[i]))\n", " picks[i] = np.sort(rng.choice(v, size=min(C.POINTS_PER_RECORD, v.size), replace=False)) if v.size else v\n", " PM = {k: [] for k in fams}\n", " Y, R, FD, SF = [], [], [], []\n", " FMS = []\n", " from .prob import load_oof\n", " FM = load_oof(\"flow\", len(m))\n", " A3 = ens()\n", " for f in range(C.N_FOLDS):\n", " te = np.flatnonzero(fold == f)\n", " files = {k: [np.load(C.CACHE / (f\"t1_tcnsharp_probs_f{f}.npy\" if s == \"sharp\" else f\"t1_tcn_probs_f{f}{sfx(s)}.npy\"), mmap_mode=\"r\") for s in v] for k, v in fams.items()}\n", " for k_, i in enumerate(te):\n", " pk = picks.get(int(i))\n", " if pk is None or not pk.size:\n", " continue\n", " for name, lst in files.items():\n", " P = np.mean([np.asarray(p[k_][pk], np.float32) for p in lst], 0).astype(np.float64)\n", " PM[name].append((P / P.sum(1, keepdims=True)).astype(np.float32))\n", " Y.append(ref[i][pk].astype(np.float64))\n", " R.append(np.full(pk.size, i))\n", " FD.append(np.full(pk.size, f))\n", " SF.append(np.stack([np.asarray(st[s][i])[pk] for s in (\"near_dec\", \"fhr_level\", \"quality_quintile\", \"near_ref_gap\")], 1))\n", " if int(i) in FM:\n", " smp = FM[int(i)][\"samples\"].astype(np.float32)[:, pk]\n", " FMS.append(np.stack([smp.std(0), np.abs(np.median(smp, 0) - ref[i][pk]), A3[i, pk, 2], np.abs(fill_linear(A3[i, :, 0])[pk] - ref[i][pk])], 1))\n", " else:\n", " FMS.append(np.full((pk.size, 4), np.nan))\n", " log.info(f\"fold {f} loaded\")\n", " free_mem()\n", " y = np.concatenate(Y)\n", " rec = np.concatenate(R)\n", " fd = np.concatenate(FD)\n", " sf = np.concatenate(SF)\n", " uniq, inv = np.unique(rec, return_inverse=True)\n", " groups = m.group.values[uniq]\n", " rep = {\"points\": int(y.size), \"records\": int(uniq.size), \"families\": list(fams), \"methods\": {\"raw\": \"as trained\", \"temperature\": \"p^(1/T), T by minimum CRPS on the calibration fold\", \"isotonic_pit\": \"Kuleshov-style recalibration: calibrated CDF = empirical CDF of calibration-fold PIT values applied to the predicted CDF\", \"conformal_80\": \"additive widening/narrowing of the 10-90% interval so that the calibration fold covers 80% (interval only)\"}, \"results\": {}}\n", " per_rec = {}\n", " TEMPS = np.exp(np.linspace(np.log(0.25), np.log(4.0), 33))\n", " for name in fams:\n", " P = np.concatenate(PM[name]).astype(np.float64)\n", " out = {\"raw\": {k: np.zeros(y.size) for k in (\"crps\", \"pit\")}, \"temperature\": {k: np.zeros(y.size) for k in (\"crps\", \"pit\")}, \"isotonic_pit\": {k: np.zeros(y.size) for k in (\"crps\", \"pit\")}}\n", " for meth in out:\n", " for lvl in LEVELS:\n", " out[meth][f\"cov{int(100 * lvl)}\"] = np.zeros(y.size, bool)\n", " out[meth][f\"wid{int(100 * lvl)}\"] = np.zeros(y.size)\n", " conf80 = np.zeros(y.size, bool)\n", " confw = np.zeros(y.size)\n", " params = {}\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " cm = np.flatnonzero(fd == c)\n", " te = np.flatnonzero(fd == f)\n", " if not cm.size or not te.size:\n", " continue\n", " sub = cm if cm.size <= 100000 else rng.choice(cm, 100000, replace=False)\n", " T = float(min(TEMPS, key=lambda t: crps_discrete(temper(P[sub], t), y[sub]).mean()))\n", " xs, ys = isotonic_map(cdf_at(P[cm], y[cm]))\n", " cdf_c = np.cumsum(P[cm], 1)\n", " lo_c, hi_c = quant(cdf_c, 0.1), quant(cdf_c, 0.9)\n", " sc = np.maximum(lo_c - y[cm], y[cm] - hi_c)\n", " qm = float(np.quantile(sc, min(1.0, 0.8 * (1 + 1 / cm.size))))\n", " params[str(f)] = {\"T\": T, \"conformal_margin_80\": qm}\n", " for a in range(0, te.size, 200000):\n", " s_ = te[a:a + 200000]\n", " for meth, Q in ((\"raw\", P[s_]), (\"temperature\", temper(P[s_], T)), (\"isotonic_pit\", apply_iso(P[s_], xs, ys))):\n", " d = dist_metrics(Q, y[s_])\n", " for k_, v_ in d.items():\n", " out[meth][k_][s_] = v_\n", " cdf_t = np.cumsum(P[s_], 1)\n", " lo, hi = quant(cdf_t, 0.1) - qm, quant(cdf_t, 0.9) + qm\n", " conf80[s_] = (y[s_] >= lo) & (y[s_] <= hi)\n", " confw[s_] = hi - lo\n", " res = {\"params\": params}\n", " for meth, d in out.items():\n", " r_ = {\"crps\": float(d[\"crps\"].mean()), \"pit_ece\": pit_ece(d[\"pit\"])}\n", " for lvl in LEVELS:\n", " r_[f\"coverage{int(100 * lvl)}\"] = float(d[f\"cov{int(100 * lvl)}\"].mean())\n", " r_[f\"width{int(100 * lvl)}\"] = float(d[f\"wid{int(100 * lvl)}\"].mean())\n", " r_[\"coverage80_by_stratum\"] = {}\n", " for j, s in enumerate((\"near_dec\", \"fhr_level\", \"quality_quintile\", \"near_ref_gap\")):\n", " for lvl_ in np.unique(sf[:, j]):\n", " mk = sf[:, j] == lvl_\n", " if mk.sum() >= 500:\n", " r_[\"coverage80_by_stratum\"][f\"{s}={int(lvl_)}\"] = float(d[\"cov80\"][mk].mean())\n", " res[meth] = r_\n", " per_rec[(name, meth)] = np.bincount(inv, weights=d[\"crps\"]) / np.bincount(inv)\n", " res[\"conformal_80\"] = {\"coverage80\": float(conf80.mean()), \"width80\": float(confw.mean()), \"coverage80_by_stratum\": {f\"{s}={int(l_)}\": float(conf80[sf[:, j] == l_].mean()) for j, s in enumerate((\"near_dec\", \"fhr_level\", \"quality_quintile\", \"near_ref_gap\")) for l_ in np.unique(sf[:, j]) if (sf[:, j] == l_).sum() >= 500}}\n", " rep[\"results\"][name] = res\n", " log.info(f\"{name}: \" + \", \".join(f\"{k} {res[k]['crps']:.4f}\" for k in (\"raw\", \"temperature\", \"isotonic_pit\")))\n", " pr = {}\n", " for name in fams:\n", " for meth in (\"temperature\", \"isotonic_pit\"):\n", " pr[f\"{name}_{meth}_minus_raw\"] = boot(lambda i, a=per_rec[(name, meth)], b=per_rec[(name, \"raw\")]: a[i].mean() - b[i].mean(), groups)[0]\n", " if \"tcn_sharp\" in fams:\n", " pr[\"tcn_sharp_raw_minus_tcn_seed0_raw\"] = boot(lambda i: per_rec[(\"tcn_sharp\", \"raw\")][i].mean() - per_rec[(\"tcn_seed0\", \"raw\")][i].mean(), groups)[0]\n", " pr[\"tcn_sharp_isotonic_minus_ens5_isotonic\"] = boot(lambda i: per_rec[(\"tcn_sharp\", \"isotonic_pit\")][i].mean() - per_rec[(\"ens5\", \"isotonic_pit\")][i].mean(), groups)[0]\n", " rep[\"paired_crps\"] = pr\n", " best = min((\"temperature\", \"isotonic_pit\"), key=lambda k: rep[\"results\"][\"ens5\"][k][\"crps\"])\n", " b = rep[\"results\"][\"ens5\"][best]\n", " dev_ = max(abs(b[f\"coverage{int(100 * l)}\"] - l) for l in LEVELS)\n", " rep[\"gate_C1_calibration\"] = {\"criterion\": \"pre-registered: the best recalibration of the 5-seed ensemble covers 50/80/90% within +-0.02 marginally and does not worsen CRPS (paired upper 95% CI <= 0)\", \"best_method\": best, \"max_marginal_deviation\": dev_, \"crps_change\": pr[f\"ens5_{best}_minus_raw\"], \"worst_stratum_coverage80\": min(b[\"coverage80_by_stratum\"].items(), key=lambda kv: kv[1]) if b[\"coverage80_by_stratum\"] else None, \"passed\": bool(dev_ <= 0.02 and pr[f\"ens5_{best}_minus_raw\"][\"hi\"] is not None and pr[f\"ens5_{best}_minus_raw\"][\"hi\"] <= 0)}\n", " F = np.concatenate(FMS)\n", " okf = np.all(np.isfinite(F), 1)\n", " if okf.sum() > 1000:\n", " yb = (F[okf, 3] > C.BIG_ERR).astype(float)\n", " a = risk_coverage(F[okf, 0], yb)[\"aurc\"]\n", " b_ = risk_coverage(F[okf, 2], yb)[\"aurc\"]\n", " gk = m.group.values[rec[okf]]\n", " rep[\"flow_sd_ranking\"] = {\"note\": \"flow-matching trajectory SD used as an error score for the 3-seed ensemble estimate (the p_far of an under-dispersed sampler is ill-defined)\", \"aurc_flow_sd\": a, \"aurc_ens3_p_far\": b_, \"rel_aurc\": boot(lambda i: risk_coverage(F[okf][i, 0], yb[i])[\"aurc\"] / max(risk_coverage(F[okf][i, 2], yb[i])[\"aurc\"], 1e-12) - 1, gk, B=min(C.BOOT, 300))[0]}\n", " save_json(C.RES / \"s44_t1_recalibration.json\", rep)\n", " return {\"C1\": rep[\"gate_C1_calibration\"][\"passed\"], \"best\": best}\n", "\n", "\n", "def record_counts(score, y, rec, qs):\n", " ur, inv = np.unique(rec, return_inverse=True)\n", " pos = np.searchsorted(qs, score, side=\"left\")\n", " A = np.zeros((ur.size, qs.size + 1))\n", " E = np.zeros((ur.size, qs.size + 1))\n", " np.add.at(A, (inv, pos), 1.0)\n", " np.add.at(E, (inv, pos), y.astype(float))\n", " return np.cumsum(A, 1)[:, :qs.size], np.cumsum(E, 1)[:, :qs.size]\n", "\n", "\n", "def ucb_threshold(score, y, rec, alpha, rng, B=None, grid=200):\n", " B = B or C.UCB_BOOT\n", " if score.size == 0 or np.unique(rec).size < C.POLICY_MIN_RECORDS:\n", " return -np.inf\n", " qs = np.unique(np.quantile(score, np.linspace(0.002, 1.0, grid)))\n", " A, E = record_counts(score, y, rec, qs)\n", " n = A.shape[0]\n", " W = rng.multinomial(n, np.full(n, 1.0 / n), size=B).astype(float)\n", " acc = W @ A\n", " err = W @ E\n", " ratio = np.where(acc > 0, err / np.maximum(acc, 1), 1.0)\n", " ucb = np.quantile(ratio, 0.95, axis=0)\n", " okj = np.flatnonzero((ucb <= alpha) & (A.sum(0) > 0))\n", " return float(qs[okj.max()]) if okj.size else -np.inf\n", "\n", "\n", "def thresholds(variant, sc, y, st, rec, alpha_e, alpha_f, rng):\n", " out = {}\n", " for s_ in range(4):\n", " mk = st == s_\n", " te = ucb_threshold(sc[mk], y[mk], rec[mk], alpha_e, rng)\n", " tf = ucb_threshold(sc[mk], y[mk], rec[mk], alpha_f, rng)\n", " if variant in (\"P3b_no_brady_estimate\", \"P3c_event_aware\") and s_ == 3:\n", " te = -np.inf\n", " out[s_] = {\"e\": te, \"f\": max(tf, te)}\n", " return out\n", "\n", "\n", "def actions(F, sc, thr, variant):\n", " from .sel import clean_policy, observable_strata\n", " so = observable_strata(F)\n", " act = np.full(F.shape[0], 2, np.int8)\n", " for s_ in np.unique(so):\n", " mk = so == s_\n", " d = thr.get(int(s_), {\"e\": -np.inf, \"f\": -np.inf})\n", " act[mk & (sc <= d[\"f\"])] = 1\n", " act[mk & (sc <= d[\"e\"])] = 0\n", " act = clean_policy(act)\n", " if variant == \"P3c_event_aware\":\n", " act[(act == 2) & (so == 2)] = 1\n", " return act\n", "\n", "\n", "VARIANTS = [\"P2_point_crc\", \"P3a_record_ucb\", \"P3b_no_brady_estimate\", \"P3c_event_aware\"]\n", "\n", "\n", "@stage(\"s46_t1_policy_v3\", params={\"v\": 1}, outputs=[C.CACHE / \"t1_policy_v3.npy\"])\n", "def policy_v3(log):\n", " from .holdout import design\n", " from .sel import E, FEAT_NAMES, LOWQ, OBS_NAMES, ens, observable_strata, point_features, seg_probs_on_estimate\n", " D = design(log)\n", " LOWQ[0] = D[\"lowq\"]\n", " m = meta()\n", " ref = ref_fhr()\n", " A = ens()\n", " Q = mm(C.CACHE / \"t1_q.npy\")\n", " AF = mm(C.CACHE / \"t1_af.npy\")\n", " FL = mm(C.CACHE / \"t1_floor.npy\")\n", " SG, _ = seg_probs_on_estimate(log)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " cidx = {n: k for k, n in enumerate(FEAT_NAMES)}\n", " rng = np.random.default_rng(C.SEED)\n", " pick = {}\n", " for i in ok:\n", " v = np.flatnonzero(valid(ref[i]))\n", " pick[i] = np.sort(rng.choice(v, size=min(C.POINTS_PER_RECORD, v.size), replace=False)) if v.size else v\n", " rows = []\n", " for i in ok:\n", " if not pick[i].size:\n", " continue\n", " core = (A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]], A[i, :, E[\"entropy\"]], A[i, :, E[\"q10\"]], A[i, :, E[\"q90\"]])\n", " F = point_features(i, core, A, Q, AF, FL, SG)\n", " e = np.abs(fill_linear(core[0])[pick[i]] - ref[i][pick[i]])\n", " rows.append((F[pick[i]], e, np.full(pick[i].size, fold[i]), np.full(pick[i].size, i)))\n", " X = np.concatenate([r[0] for r in rows])\n", " yb = (np.concatenate([r[1] for r in rows]) > C.BIG_ERR).astype(np.int8)\n", " fd = np.concatenate([r[2] for r in rows])\n", " rc = np.concatenate([r[3] for r in rows])\n", " stp = observable_strata(X)\n", " score_of = lambda f, Fm: D[\"g_models\"][f].predict_proba(Fm)[:, 1] if D[\"s6_passed\"] else Fm[:, cidx[\"p_far\"]]\n", " configs = [(v, C.ALPHA_ESTIMATE, C.ALPHA_FLAG) for v in VARIANTS] + [(\"P3c_event_aware\", a, max(C.ALPHA_FLAG, 2.5 * a)) for a in C.ALPHA_SWEEP if a != C.ALPHA_ESTIMATE]\n", " thr = {}\n", " trng = np.random.default_rng(C.SEED + 46)\n", " for v, ae, af in configs:\n", " for f in range(C.N_FOLDS):\n", " c = (f + 1) % C.N_FOLDS\n", " cm = fd == c\n", " sc_c = score_of(f, X[cm])\n", " if v == \"P2_point_crc\":\n", " from .sel import mondrian_thresholds\n", " mt = mondrian_thresholds(sc_c, yb[cm], stp[cm], rc[cm], np.arange(4))\n", " thr[(v, ae, f)] = {s_: {\"e\": d[C.ALPHA_ESTIMATE], \"f\": d[C.ALPHA_FLAG]} for s_, d in mt.items()}\n", " else:\n", " thr[(v, ae, f)] = thresholds(v, sc_c, yb[cm], stp[cm], rc[cm], ae, af, trng)\n", " n = len(m)\n", " acts = {cfg: np.full((n, C.N), -1, np.int8) for cfg in [(v, ae) for v, ae, _ in configs]}\n", " sobs = np.full((n, C.N), -1, np.int8)\n", " for i in ok:\n", " core = (A[i, :, E[\"median\"]], A[i, :, E[\"p_far\"]], A[i, :, E[\"entropy\"]], A[i, :, E[\"q10\"]], A[i, :, E[\"q90\"]])\n", " F = point_features(i, core, A, Q, AF, FL, SG)\n", " sc = score_of(fold[i], F)\n", " sobs[i] = observable_strata(F)\n", " for v, ae, af in configs:\n", " acts[(v, ae)][i] = actions(F, sc, thr[(v, ae, fold[i])], v)\n", " log.info(\"actions computed for every configuration\")\n", " est = np.stack([fill_linear(A[i, :, E[\"median\"]]) for i in range(n)])\n", " E_, V_ = {}, {}\n", " for i in ok:\n", " e, v = fhr_abs_errors(est[i], ref[i])\n", " E_[i], V_[i] = e > C.BIG_ERR, v\n", " units = np.concatenate([np.full(V_[i].sum(), k) for k, i in enumerate(ok)])\n", " big = np.concatenate([E_[i] for i in ok])\n", " so_v = np.concatenate([sobs[i][V_[i]] for i in ok])\n", " grp_rec = m.group.values[ok]\n", " res = {}\n", " for (v, ae), P in acts.items():\n", " av = np.concatenate([P[i][V_[i]] for i in ok])\n", " est_m = av == 0\n", " r = {\"variant\": v, \"alpha_estimate\": ae, \"coverage_estimate\": float(est_m.mean()), \"coverage_estimate_or_flag\": float((av <= 1).mean()), \"abstain_rate\": float((av == 2).mean())}\n", " cnt_e = np.bincount(units, weights=est_m.astype(float), minlength=ok.size)\n", " err_e = np.bincount(units, weights=(est_m & big).astype(float), minlength=ok.size)\n", " r[\"risk_estimate\"] = boot(lambda i: err_e[i].sum() / max(cnt_e[i].sum(), 1), grp_rec)[0]\n", " r[\"big_errors_hidden_or_flagged\"] = float(np.mean(av[big] >= 1)) if big.any() else None\n", " r[\"per_stratum\"] = {}\n", " for s_ in range(4):\n", " mk = so_v == s_\n", " recs_s = np.unique(units[mk])\n", " ce = np.bincount(units[mk], weights=est_m[mk].astype(float), minlength=ok.size)\n", " ee = np.bincount(units[mk], weights=(est_m & big)[mk].astype(float), minlength=ok.size)\n", " r[\"per_stratum\"][OBS_NAMES[s_]] = {\"records\": int(recs_s.size), \"coverage_estimate\": float(est_m[mk].mean()) if mk.any() else None, \"risk_estimate\": boot(lambda i, ce=ce, ee=ee: ee[i].sum() / max(ce[i].sum(), 1), grp_rec)[0] if est_m[mk].any() else None}\n", " hid, flg, kept = [], [], []\n", " for i in ok:\n", " for a, b in events(Sref[i], -1):\n", " seg = P[i][a:b]\n", " hid.append(np.mean(seg == 2) > 0.5)\n", " flg.append(np.mean(seg >= 1) > 0.5)\n", " kept.append(np.mean(seg == 0) > 0.5)\n", " r[\"decelerations\"] = {\"n\": len(hid), \"majority_abstained\": float(np.mean(hid)) if hid else None, \"majority_flagged_or_abstained\": float(np.mean(flg)) if flg else None, \"majority_estimated\": float(np.mean(kept)) if kept else None}\n", " res[f\"{v}@{ae}\"] = r\n", " elig = {}\n", " for v in VARIANTS:\n", " r = res[f\"{v}@{C.ALPHA_ESTIMATE}\"]\n", " marg = r[\"risk_estimate\"][\"hi\"] is not None and r[\"risk_estimate\"][\"hi\"] <= 1.5 * C.ALPHA_ESTIMATE\n", " strat_ok = all(d[\"risk_estimate\"] is None or d[\"records\"] < C.POLICY_MIN_RECORDS or (d[\"coverage_estimate\"] or 0) <= 0.01 or (d[\"risk_estimate\"][\"hi\"] is not None and d[\"risk_estimate\"][\"hi\"] <= 2 * C.ALPHA_ESTIMATE) for d in r[\"per_stratum\"].values())\n", " elig[v] = {\"marginal_ok\": bool(marg), \"strata_ok\": bool(strat_ok), \"eligible\": bool(marg and strat_ok), \"decelerations_majority_abstained\": r[\"decelerations\"][\"majority_abstained\"], \"coverage_estimate\": r[\"coverage_estimate\"]}\n", " cands = [v for v in VARIANTS if elig[v][\"eligible\"]]\n", " chosen = min(cands, key=lambda v: (elig[v][\"decelerations_majority_abstained\"] or 0, -elig[v][\"coverage_estimate\"])) if cands else \"P2_point_crc\"\n", " rep = {\"score\": \"learned g\" if D[\"s6_passed\"] else \"p_far (training-free; S6 failed)\", \"calibration_unit\": \"P2: points (conformal risk control, weeks 3-5 v2); P3: records (95% upper bound of the selective risk from a record bootstrap of the calibration fold, i.e. cluster-aware)\", \"variants\": {\"P3b_no_brady_estimate\": \"P3a + the predicted-bradycardia stratum never estimates\", \"P3c_event_aware\": \"P3b + inside the predicted-deceleration stratum, abstention becomes a flag so decelerations stay visible\"}, \"results\": res, \"eligibility\": elig, \"selection_rule\": f\"pre-registered: eligible = estimate-zone selective risk UCB <= 1.5 alpha and, for every observable stratum with >= {C.POLICY_MIN_RECORDS} records that estimates > 1% of its points, UCB <= 2 alpha; choose the eligible variant hiding the fewest reference decelerations, then the highest coverage\", \"chosen\": chosen, \"status\": \"post-holdout correction validated out-of-fold only; the locked holdout is not reused\", \"trade_off_P3c\": {f\"{a}\": {k: res[f\"P3c_event_aware@{a}\"][k] for k in (\"coverage_estimate\", \"risk_estimate\", \"decelerations\")} for a in C.ALPHA_SWEEP if f\"P3c_event_aware@{a}\" in res}}\n", " out, tp, pp = open_memmap_new(C.CACHE / \"t1_policy_v3.npy\", (n, C.N), np.int8, -1)\n", " out[:] = acts[(chosen, C.ALPHA_ESTIMATE)]\n", " finalize_memmap(out, tp, pp)\n", " P0 = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)\n", " rep[\"P2_reproduces_frozen_policy\"] = float(np.mean(acts[(\"P2_point_crc\", C.ALPHA_ESTIMATE)][ok] == P0[ok]))\n", " rep[\"gate_P3\"] = {\"criterion\": rep[\"selection_rule\"], \"eligible_variants\": cands, \"chosen\": chosen, \"passed\": bool(cands)}\n", " save_json(C.RES / \"s46_t1_policy_v3.json\", rep)\n", " return {\"chosen\": chosen, \"eligible\": cands}\n", "\n", "\n", "def u_features(med, pfar, w80, msd):\n", " return {\"u_pfar_mean\": float(np.mean(pfar)), \"u_pfar_p95\": float(np.quantile(pfar, 0.95)), \"u_pfar_gt01\": float(np.mean(pfar > 0.1)), \"u_pfar_gt03\": float(np.mean(pfar > 0.3)), \"u_width80_mean\": float(np.mean(w80)), \"u_member_sd_mean\": float(np.mean(msd)), \"u_brady_frac\": float(np.mean(med < C.BRADY)), \"u_tachy_frac\": float(np.mean(med > 160))}\n", "\n", "\n", "def u_table(A, idx):\n", " from .sel import E\n", " return pd.DataFrame([u_features(fill_linear(A[i, :, E[\"median\"]]), A[i, :, E[\"p_far\"]], A[i, :, E[\"q90\"]] - A[i, :, E[\"q10\"]], A[i, :, E[\"member_sd\"]]) for i in idx]).astype(np.float32)\n", "\n", "\n", "@stage(\"s47_cascade_controls\", params={\"v\": 1}, outputs=[C.CACHE / \"w11_t4_candidates.npz\", C.CACHE / \"w11_t4_features.pkl\"])\n", "def cascade_controls(log):\n", " from .deep import gather\n", " from .sel import ens, est_filled\n", " from .sel2 import oof_seg_probs\n", " from .t2 import crossfit_post, post\n", " from .t3 import feature_table\n", " from .t4 import crossfit, seg_features\n", " dev = device()\n", " m = meta()\n", " y = m.y.values\n", " fold_all = m.fold.values\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " sg_ok = np.load(C.CACHE / \"t4_segp_est_ok.npy\")\n", " z = np.load(C.CACHE / \"w35_cascade_probs.npz\")\n", " pC = np.full(len(m), np.nan)\n", " pC[z[\"idx\"]] = z[\"pC\"]\n", " d0 = gather(\"t4_deep_oof\", len(m))\n", " d1 = gather(\"t4_deepmask_oof\", len(m))\n", " ok = (fold_all >= 0) & sg_ok & np.isfinite(pC) & np.isfinite(d0) & np.isfinite(d1)\n", " idx = np.flatnonzero(ok)\n", " fo = fold_all[idx]\n", " A = ens()\n", " Xa = est_filled(A)[idx]\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " PA = oof_seg_probs(\"t2_ft4\", est_filled(A), np.where(ok, fold_all, -1), idx, dev, log)\n", " SA = np.zeros((idx.size, C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " s_ = np.flatnonzero(fo == f)\n", " if s_.size:\n", " SA[s_] = post(np.nan_to_num(PA[s_]), *pp[str(f)])\n", " PB = oof_seg_probs(\"t2_est\", est_filled(A), np.where(ok, fold_all, -1), idx, dev, log)\n", " SB, ppB = crossfit_post(np.nan_to_num(PB), Sref[idx], fo)\n", " base = feature_table(Xa)\n", " U = u_table(A, idx)\n", " P2 = np.asarray(mm(C.CACHE / \"t1_policy.npy\"), np.int8)[idx]\n", " U2 = pd.DataFrame({\"policy_abstain_frac\": np.mean(P2 == 2, 1), \"policy_flag_frac\": np.mean(P2 == 1, 1)}).astype(np.float32)\n", " FA = pd.concat([base, seg_features(Xa, SA)], axis=1)\n", " FB = pd.concat([base, seg_features(Xa, SB)], axis=1)\n", " sets = {\"A\": FA, \"A+U\": pd.concat([FA, U], axis=1), \"A+U2_policy\": pd.concat([FA, U2], axis=1), \"U_only\": U, \"U2_policy_only\": U2, \"B0\": FB, \"B0+U\": pd.concat([FB, U], axis=1)}\n", " yy = y[idx]\n", " probs = {k: crossfit(v.values, v.values, yy, fo) for k, v in sets.items()}\n", " probs[\"C\"] = pC[idx]\n", " probs[\"D0_deep\"] = d0[idx]\n", " probs[\"D1_deep_mask\"] = d1[idx]\n", " groups = m.group.values[idx]\n", " keys = [\"auroc\", \"brier\", \"ece\", \"f1\", \"nmcc\"]\n", "\n", " def vals(p, i):\n", " b = binary_scores(yy[i], p[i])\n", " return np.array([fauc(yy[i], p[i]), b[\"brier\"], b[\"ece\"], b[\"f1\"], b[\"nmcc\"]])\n", "\n", " rep = {\"n_records\": int(idx.size), \"U_features\": list(U.columns), \"values\": {k: dict(zip(keys, vals(p, np.arange(idx.size)).tolist())) for k, p in probs.items()}}\n", " comps = [(\"C\", \"A+U\"), (\"C\", \"A\"), (\"A+U\", \"A\"), (\"A+U2_policy\", \"A\"), (\"B0+U\", \"B0\"), (\"C\", \"B0+U\"), (\"B0\", \"A\")]\n", " rep[\"paired\"] = {f\"{a}_minus_{b}\": dict(zip(keys, boot(lambda i, a=a, b=b: vals(probs[a], i) - vals(probs[b], i), groups))) for a, b in comps}\n", " cu = rep[\"paired\"][\"C_minus_A+U\"][\"auroc\"]\n", " rep[\"gate_CC\"] = {\"criterion\": \"pre-registered: the discrimination gain of cascade C is attributed to propagated uncertainty only if C - (A + uncertainty summaries as features) has an AUROC CI above zero; otherwise uncertainty acts as a record-level feature (pathology marker)\", \"C_minus_AplusU_auroc\": cu, \"propagation_beyond_features\": bool(cu[\"lo\"] is not None and cu[\"lo\"] > 0), \"U_only_auroc\": rep[\"values\"][\"U_only\"][\"auroc\"], \"U2_policy_only_auroc\": rep[\"values\"][\"U2_policy_only\"][\"auroc\"]}\n", " from .utils import save_df\n", " save_df(C.CACHE / \"w11_t4_features.pkl\", pd.concat([FB.reset_index(drop=True), U.reset_index(drop=True)], axis=1).assign(_idx=idx))\n", " save_npz(C.CACHE / \"w11_t4_candidates.npz\", idx=idx, y=yy, **{k.replace(\"+\", \"p\"): np.asarray(p, np.float32) for k, p in probs.items()})\n", " save_json(C.RES / \"s47_cascade_controls.json\", dict(rep, post_params_B0={str(k): list(v) for k, v in ppB.items()}))\n", " return {\"C_minus_AU\": cu[\"point\"], \"beyond\": rep[\"gate_CC\"][\"propagation_beyond_features\"]}" ] }, { "cell_type": "code", "execution_count": 29, "id": "c3e96576bb07", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.096697Z", "iopub.status.busy": "2026-11-28T14:17:33.096315Z", "iopub.status.idle": "2026-11-28T14:17:33.106738Z", "shell.execute_reply": "2026-11-28T14:17:33.105243Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/w12.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/w12.py\n", "import zlib\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .fastm import KEYS, Pack, boot\n", "from .io import events, fill_linear, valid\n", "from .metrics import dice_counts, event_counts\n", "from .utils import device, load_df, load_json, mm, save_json, stage\n", "\n", "\n", "def shared(fa, fb):\n", " return int(np.intersect1d(fa, fb, assume_unique=True).size)\n", "\n", "\n", "@stage(\"s48_fp_positive_control\", params={\"v\": 1})\n", "def fp_positive_control(log):\n", " from .audit import fingerprints, weights\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " X = np.asarray(mm(C.CACHE / \"t3_fhr.npy\"), np.float32)\n", " n = len(m3)\n", " rng = np.random.default_rng(C.SEED + 48)\n", " q = np.array([valid(X[i]).mean() for i in range(n)])\n", " pool = np.flatnonzero(q > 0.8)\n", " rep = {\"min_shared\": C.FP_MIN_SHARED, \"winnow\": C.FP_WINNOW, \"by_k\": {}}\n", " src = rng.choice(pool, size=min(C.FP_PAIRS, pool.size), replace=False)\n", " other = rng.choice(pool, size=src.size, replace=True)\n", " pairs_real = np.arange(0, n - 1, 2)\n", " pairs_real = pairs_real[(m3.pair.values[pairs_real] == m3.pair.values[pairs_real + 1])] if \"pair\" in m3 else pairs_real\n", " pairs_real = rng.choice(pairs_real, size=min(C.FP_PAIRS, pairs_real.size), replace=False)\n", " g = m3.group.values\n", " null_a = rng.choice(pool, size=C.FP_NULL_PAIRS)\n", " null_b = rng.choice(pool, size=C.FP_NULL_PAIRS)\n", " keep = g[null_a] != g[null_b]\n", " null_a, null_b = null_a[keep], null_b[keep]\n", " for k in C.FP_KS:\n", " w1, w2 = weights(k)\n", " fp = lambda x: fingerprints(np.asarray(x, np.float32), k, w1, w2)\n", " res = {}\n", " for ov in (0.25, 0.5, 0.75, 1.0):\n", " for noise in (0.0, 0.3):\n", " det = []\n", " for a, b in zip(src, other):\n", " shift = int(round((1 - ov) * C.N))\n", " syn = np.concatenate([X[a][shift:], X[b][:shift]])\n", " if noise:\n", " syn = np.where(np.isfinite(syn), np.round((syn + rng.normal(0, noise, syn.size)) * 4) / 4, syn)\n", " det.append(shared(fp(X[a]), fp(syn)) >= C.FP_MIN_SHARED)\n", " res[f\"overlap{int(100 * ov)}_noise{noise}\"] = float(np.mean(det))\n", " real = [shared(fp(X[i]), fp(X[i + 1])) >= C.FP_MIN_SHARED for i in pairs_real]\n", " res[\"real_t3_pairs_50pct_detected\"] = float(np.mean(real))\n", " fpr = [shared(fp(X[a]), fp(X[b])) >= C.FP_MIN_SHARED for a, b in zip(null_a, null_b)]\n", " res[\"false_positive_rate_unrelated_groups\"] = float(np.mean(fpr))\n", " rep[\"by_k\"][str(k)] = res\n", " log.info(f\"k={k}: {res}\")\n", " main = rep[\"by_k\"][str(C.FP_K_MAIN)]\n", " exact = bool(min(main[\"overlap50_noise0.0\"], main[\"real_t3_pairs_50pct_detected\"]) >= 0.95 and main[\"false_positive_rate_unrelated_groups\"] <= 0.01)\n", " noisy = bool(main[\"overlap50_noise0.3\"] >= 0.95)\n", " rep[\"gate_FP\"] = {\"criterion\": \"pre-registered: at the main segment length, >= 95% of exact copies sharing >= 50% of their samples and of real T3 pairs are linked, with <= 1% false links between unrelated groups (exact); robustness: the same detection with 0.3 bpm noise and 0.25 bpm re-quantisation (noisy)\", \"passed\": exact, \"exact_copies\": exact, \"noisy_copies\": noisy}\n", " rep[\"interpretation\"] = (\"exact copies are detected, so identical grouping across segment lengths means that no exact residual overlap exists beyond the known pairs; \" if exact else \"exact copies are NOT reliably detected: the fingerprint grouping is not a valid N2 guarantee; \") + (\"re-quantised copies are detected too.\" if noisy else \"re-quantised or re-sampled copies escape the integer-bpm fingerprint, so the N2 claim for T3 holds for exact duplicates only and must be stated that way.\")\n", " save_json(C.RES / \"s48_fp_positive_control.json\", rep)\n", " return rep[\"gate_FP\"]\n", "\n", "\n", "MATCHED = [(\"noise_sd5\", (\"noise\", 5), \"all\"), (\"gap_60s_during\", (\"gap\", 60, \"during\"), \"decel\"), (\"mix_p_far_25pct_seed0\", (\"mix\", 0.25, \"p_far\", 0), \"all\")]\n", "\n", "\n", "@stage(\"s49_a1_matched_propagation\", params={\"v\": 1})\n", "def matched_propagation(log):\n", " from .a1x import perturb2\n", " from .t1 import gather_tcn\n", " from .t2 import load_ft4, post, predict_probs, safe_models_for_t4\n", " from .t3 import feature_table, model\n", " from .t4 import seg_features\n", " dev = device()\n", " m = load_df(C.CACHE / \"folds_t4.pkl\")\n", " y = m.y.values\n", " Xref = np.asarray(mm(C.CACHE / \"t4_fhr.npy\"), np.float32)\n", " Sref = np.asarray(mm(C.CACHE / \"t4_seg.npy\"))\n", " pp = load_json(C.RES / \"s14_t2_eval.json\")[\"unet_ft4_on_t4\"][\"params\"]\n", " safe = safe_models_for_t4()\n", " fold = m.fold.values\n", " ok = (fold >= 0) & np.array([fold[i] in safe[i] for i in range(len(m))])\n", " idx = np.flatnonzero(ok)\n", " fo = fold[idx]\n", " yy = y[idx]\n", " has_dec = np.array([len(events(Sref[i], -1)) > 0 for i in idx])\n", " r0, _ = gather_tcn(0)\n", " models = {f: load_ft4(f, dev) for f in range(C.N_FOLDS)}\n", "\n", " def feats(X):\n", " S = np.zeros((len(X), C.N), np.int8)\n", " for f in range(C.N_FOLDS):\n", " s_ = np.flatnonzero(fo == f)\n", " if s_.size:\n", " S[s_] = post(np.nan_to_num(predict_probs(models[f], X[s_], dev, log).astype(np.float32)), *pp[str(f)])\n", " return S, pd.concat([feature_table(X), seg_features(X, S)], axis=1).values\n", "\n", " S0, F0 = feats(Xref[idx])\n", " clean = {f: model(int((fo != f).sum())).fit(F0[fo != f], yy[fo != f]) for f in range(C.N_FOLDS)}\n", " groups = m.group.values[idx]\n", "\n", " def pack(S, Fx, clfs):\n", " p = np.full(idx.size, np.nan)\n", " for f in range(C.N_FOLDS):\n", " te = fo == f\n", " p[te] = clfs[f].predict_proba(Fx[te])[:, 1]\n", " return Pack(yy, p, [dice_counts(S[j], Sref[i]) for j, i in enumerate(idx)], [event_counts(S[j], Sref[i]) for j, i in enumerate(idx)])\n", "\n", " p_clean = pack(S0, F0, clean)\n", " rep = {\"n_records\": int(idx.size), \"design\": \"deployed = classifier trained on clean reference FHR (as in s38); matched = classifier retrained on the same perturbation applied to the training folds; both evaluated on the perturbed test fold\", \"conditions\": {}}\n", " for name, kind, sub in MATCHED:\n", " rng = np.random.default_rng(zlib.crc32(name.encode()) + C.SEED)\n", " rows = np.arange(idx.size) if sub == \"all\" else np.flatnonzero(has_dec)\n", " Xp = Xref[idx].copy()\n", " for j in rows:\n", " i = idx[j]\n", " if kind[0] == \"mix\":\n", " Xp[j] = perturb2(Xref[i], Sref[i], kind, rng, fill_linear(r0[i, :, 0]), r0[i, :, 2], Xref[i])\n", " else:\n", " Xp[j] = perturb2(Xref[i], Sref[i], kind, rng)\n", " S, Fx = feats(Xp)\n", " matched = {f: model(int((fo != f).sum())).fit(Fx[fo != f], yy[fo != f]) for f in range(C.N_FOLDS)}\n", " pd_, pm_ = pack(S, Fx, clean), pack(S, Fx, matched)\n", " d = {\"records_evaluated\": int(rows.size)}\n", " d[\"deployed_minus_clean\"] = dict(zip(KEYS, boot(lambda i: pd_.vec(rows[i]) - p_clean.vec(rows[i]), groups[rows], strata=fo[rows])))\n", " d[\"matched_minus_clean\"] = dict(zip(KEYS, boot(lambda i: pm_.vec(rows[i]) - p_clean.vec(rows[i]), groups[rows], strata=fo[rows])))\n", " d[\"matched_minus_deployed\"] = dict(zip(KEYS, boot(lambda i: pm_.vec(rows[i]) - pd_.vec(rows[i]), groups[rows], strata=fo[rows])))\n", " rep[\"conditions\"][name] = d\n", " log.info(f\"{name}: matched-deployed auroc {d['matched_minus_deployed']['auroc']}\")\n", " rep[\"reading\"] = \"segmentation metrics are identical by construction (same segmentation); for risk metrics, the share of the deployed degradation removed by retraining is the classifier-mismatch part, the rest is information lost in the input\"\n", " save_json(C.RES / \"s49_a1_matched_propagation.json\", rep)\n", " return {k: round(v[\"matched_minus_deployed\"][\"auroc\"][\"point\"], 4) for k, v in rep[\"conditions\"].items()}" ] }, { "cell_type": "code", "execution_count": 30, "id": "449415371d36", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.110363Z", "iopub.status.busy": "2026-11-28T14:17:33.110029Z", "iopub.status.idle": "2026-11-28T14:17:33.120955Z", "shell.execute_reply": "2026-11-28T14:17:33.119553Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/infer.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/infer.py\n", "import json\n", "import pickle\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "\n", "from . import config as C\n", "from .io import fill_linear, fit_len, read_wav\n", "\n", "\n", "def shift_prob(p, thr):\n", " from scipy.special import expit, logit\n", " return expit(logit(np.clip(p, 1e-6, 1 - 1e-6)) - logit(np.clip(thr, 1e-6, 1 - 1e-6)))\n", "\n", "\n", "class Package:\n", " def __init__(self, root, dev=None):\n", " self.root = Path(root)\n", " self.cfg = json.load(open(self.root / \"config.json\"))\n", " with open(self.root / \"artefacts.pkl\", \"rb\") as fh:\n", " self.art = pickle.load(fh)\n", " self.dev = dev or torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", " self._acg = None\n", " self._cache = {}\n", "\n", " def path(self, rel):\n", " return self.root / rel\n", "\n", " def models(self, key):\n", " if key in self._cache:\n", " return self._cache[key]\n", " out = []\n", " for rel in self.cfg[\"models\"].get(key, []):\n", " ck = torch.load(self.path(rel), map_location=self.dev, weights_only=False)\n", " if key in (\"t1_tcn\", \"t1_tcn_sharp\"):\n", " from .t1 import TCN\n", " mdl = TCN()\n", " elif key == \"t1_flow\":\n", " from .prob import FlowNet\n", " mdl = FlowNet()\n", " elif key in (\"t2_unet\", \"t2_est\"):\n", " from .t2 import UNet1D\n", " mdl = UNet1D()\n", " elif key == \"t2_twohead\":\n", " from .a1x import UNet2H\n", " mdl = UNet2H()\n", " else:\n", " from .deep import SEResNet1D\n", " mdl = SEResNet1D()\n", " mdl.load_state_dict(ck[\"model\"])\n", " out.append((mdl.to(self.dev).eval(), ck.get(\"stats\")))\n", " self._cache[key] = out\n", " return out\n", "\n", " def t1_features(self, wav):\n", " from .dus import Autocorrelogram\n", " if self._acg is None:\n", " self._acg = Autocorrelogram(self.dev)\n", " sr, sig, clip = read_wav(wav)\n", " if sr != C.FS_DUS:\n", " from scipy.signal import resample_poly\n", " sig = resample_poly(sig, C.FS_DUS, sr).astype(np.float32)\n", " clip = np.zeros(sig.size, bool)\n", " g, q = self._acg.run(sig, clip)\n", " return np.asarray(g, np.float16).astype(np.float32), np.asarray(q, np.float16).astype(np.float32)\n", "\n", " @staticmethod\n", " def x_input(g, q, stats):\n", " mu, sd = (np.asarray(s, np.float32) for s in stats)\n", " return np.nan_to_num(np.concatenate([g, (q - mu) / sd], 1).T)[None].astype(np.float32)\n", "\n", " @staticmethod\n", " def seed_of(rel):\n", " st = Path(rel).stem\n", " return int(st.split(\"_s\")[1]) if \"_s\" in st else 0\n", "\n", " @torch.no_grad()\n", " def mixture(self, key, g, q, seeds=None):\n", " amp = self.dev.type == \"cuda\"\n", " P = []\n", " for (mdl, stats), rel in zip(self.models(key), self.cfg[\"models\"].get(key, [])):\n", " if seeds is not None and self.seed_of(rel) not in seeds:\n", " continue\n", " x = torch.from_numpy(self.x_input(g, q, stats)).to(self.dev)\n", " with torch.autocast(self.dev.type, enabled=amp):\n", " lo = mdl(x)\n", " P.append(torch.softmax(lo.float(), 1)[0].T.cpu().numpy())\n", " return np.stack(P) if P else None\n", "\n", " @torch.no_grad()\n", " def t1(self, wav):\n", " from .sel import summarize_np\n", " g, q = self.t1_features(wav)\n", " choice = self.cfg[\"t1\"][\"choice\"]\n", " parts, out = [], {}\n", " if \"t1_tcn\" in self.cfg[\"models\"]:\n", " Pe = self.mixture(\"t1_tcn\", g, q)\n", " se, _ = summarize_np(Pe)\n", " if \"ens\" in choice:\n", " parts.append(se[:, 0])\n", " us = self.cfg[\"t1\"].get(\"u_seeds\") or None\n", " Pu = self.mixture(\"t1_tcn\", g, q, set(us)) if us else Pe\n", " su, _ = summarize_np(Pu)\n", " out.update({\"median_ens\": su[:, 0], \"p_far\": su[:, 2], \"q10\": su[:, 4], \"q90\": su[:, 5], \"member_sd\": su[:, 8]})\n", " if \"t1_tcn_sharp\" in self.cfg[\"models\"]:\n", " ss, _ = summarize_np(self.mixture(\"t1_tcn_sharp\", g, q))\n", " parts.append(ss[:, 0])\n", " if \"p_far\" not in out:\n", " out.update({\"median_ens\": ss[:, 0], \"p_far\": ss[:, 2], \"q10\": ss[:, 4], \"q90\": ss[:, 5], \"member_sd\": ss[:, 8]})\n", " if \"t1_flow\" in self.cfg[\"models\"]:\n", " from .prob import fm_sample\n", " flows = self.models(\"t1_flow\")\n", " k = max(1, int(round(C.K_FM / max(1, len(flows)))))\n", " gen = torch.Generator(device=self.dev.type)\n", " gen.manual_seed(C.SEED)\n", " S = []\n", " for mdl, stats in flows:\n", " x = torch.from_numpy(self.x_input(g, q, stats)).to(self.dev)\n", " with torch.autocast(self.dev.type, enabled=self.dev.type == \"cuda\"):\n", " S.append(fm_sample(mdl, x, k, C.FM_STEPS, gen)[0].float().cpu().numpy())\n", " parts.append(np.median(np.concatenate(S), 0))\n", " comb = np.mean(parts, 0)\n", " out[\"fhr\"] = np.clip(fill_linear(comb), C.FHR_MIN, C.FHR_MAX).astype(np.float32)\n", " if \"p_far\" not in out:\n", " out.update({\"median_ens\": comb, \"p_far\": np.zeros(C.N), \"q10\": comb, \"q90\": comb, \"member_sd\": np.zeros(C.N)})\n", " return out\n", "\n", " @torch.no_grad()\n", " def seg_probs(self, key, x, head=None):\n", " from .t2 import inputs\n", " inp = torch.from_numpy(inputs(np.asarray(x, np.float32))[0][None]).to(self.dev)\n", " ps = []\n", " for mdl, _ in self.models(key):\n", " with torch.autocast(self.dev.type, enabled=self.dev.type == \"cuda\"):\n", " o = mdl(inp)\n", " s = o[2] if (key == \"t2_twohead\" and head == 4) else o[0]\n", " ps.append(torch.softmax(s.float(), 1)[0].cpu().numpy())\n", " return np.mean(ps, 0)\n", "\n", " def t2(self, fhr):\n", " from .t2 import post\n", " key = self.cfg[\"t2\"][\"model\"]\n", " p = self.seg_probs(key, fhr, head=2)\n", " return post(np.nan_to_num(p)[None], *self.art[\"t2_post\"])[0].astype(np.int8)\n", "\n", " @torch.no_grad()\n", " def deep_prob(self, key, x, u=None):\n", " from .deep import make_input\n", " inp = torch.from_numpy(make_input(np.asarray(x, np.float32), u)[None]).to(self.dev)\n", " ps = []\n", " for mdl, _ in self.models(key):\n", " with torch.autocast(self.dev.type, enabled=self.dev.type == \"cuda\"):\n", " ps.append(float(torch.sigmoid(mdl(inp).float())[0]))\n", " return float(np.mean(ps))\n", "\n", " def t3(self, fhr, uc):\n", " from .t3 import fhr_features\n", " x = fit_len(np.asarray(fhr, np.float32))\n", " u = np.clip(fit_len(np.asarray(uc, np.float32)), -1000, 60000)\n", " parts = []\n", " if \"gbm\" in self.cfg[\"t3\"][\"mode\"]:\n", " row = pd.DataFrame([fhr_features(x, u)]).astype(np.float32).reindex(columns=self.art[\"t3_cols\"])\n", " parts.append(float(self.art[\"t3_gbm\"].predict_proba(row.values)[:, 1][0]))\n", " if \"deep\" in self.cfg[\"t3\"][\"mode\"]:\n", " parts.append(self.deep_prob(\"t3_deep\", x, u))\n", " p = float(np.mean(parts))\n", " pa = float(shift_prob(p, self.art[\"t3_thr\"]))\n", " return p, int(pa >= 0.5)\n", "\n", " def t4(self, wav, rid):\n", " from .t2 import post\n", " from .t3 import fhr_features\n", " from .t4 import report, seg_features\n", " from .w11 import u_features\n", " r = self.t1(wav)\n", " est = r[\"fhr\"]\n", " S = post(np.nan_to_num(self.seg_probs(\"t2_est\", est))[None], *self.art[\"t4_post\"])[0].astype(np.int8)\n", " feats = dict(fhr_features(est, None))\n", " feats.update(seg_features(est[None], S[None]).iloc[0].to_dict())\n", " feats.update(u_features(r[\"median_ens\"], r[\"p_far\"], r[\"q90\"] - r[\"q10\"], r[\"member_sd\"]))\n", " parts = []\n", " mode = self.cfg[\"t4\"][\"mode\"]\n", " if \"gbm\" in mode:\n", " row = pd.DataFrame([feats]).astype(np.float32).reindex(columns=self.art[\"t4_cols\"])\n", " parts.append(float(self.art[\"t4_gbm\"].predict_proba(row.values)[:, 1][0]))\n", " if \"deep\" in mode:\n", " parts.append(self.deep_prob(\"t4_deep\", est))\n", " p = float(np.mean(parts))\n", " pa = float(shift_prob(p, self.art[\"t4_thr\"]))\n", " rep = report(rid, S, pa, est)\n", " rep[\"risk_probability_uncalibrated\"] = p\n", " rep[\"t1_low_reliability_fraction\"] = float(np.mean(r[\"p_far\"] > 0.3))\n", " return rep" ] }, { "cell_type": "code", "execution_count": 31, "id": "0b31dcf8fc8e", "metadata": { "execution": { "iopub.execute_input": "2026-11-28T14:17:33.125249Z", "iopub.status.busy": "2026-11-28T14:17:33.124856Z", "iopub.status.idle": "2026-11-28T14:17:33.149789Z", "shell.execute_reply": "2026-11-28T14:17:33.147716Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /kaggle/tmp/ctg_code/ctglib/w13.py\n" ] } ], "source": [ "%%writefile /kaggle/tmp/ctg_code/ctglib/w13.py\n", "import json\n", "import os\n", "import pickle\n", "import shutil\n", "import subprocess\n", "import sys\n", "import time\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "from . import config as C\n", "from .fastm import auroc as fauc\n", "from .fastm import boot\n", "from .io import fill_linear\n", "from .metrics import binary_scores, fhr_abs_errors\n", "from .t1 import meta, ref_fhr, sfx\n", "from .utils import load_df, load_json, mm, save_json, stage\n", "\n", "\n", "def nmcc_threshold(y, p):\n", " grid = np.linspace(0.2, 0.8, 61)\n", " return float(max(grid, key=lambda t: binary_scores(y, p, t)[\"nmcc\"]))\n", "\n", "\n", "def mode_params(d):\n", " vals = [tuple(v) for v in d.values()]\n", " return list(max(set(vals), key=vals.count))\n", "\n", "\n", "@stage(\"s50_competition_selection\", params={\"v\": 2})\n", "def selection(log):\n", " from .a1x import seg_scores, seg_vec\n", " from .deep import gather\n", " from .prob import load_oof\n", " from .sel import ens\n", " from .t1 import gather_tcn\n", " from .t2 import crossfit_post\n", " from .t3 import oof\n", " m = meta()\n", " ref = ref_fhr()\n", " fold = m.fold.values\n", " ok = np.flatnonzero(fold >= 0)\n", " rep = {\"rules\": {\"t1\": f\"lowest RMSE among candidates whose RMSE gain versus the 5-seed ensemble has an upper 95% CI < 0, whose MAE change has an upper CI <= 0.02 and whose estimated model time <= {C.T1_TIME_BUDGET_S} s per record; otherwise the 5-seed ensemble\", \"t2\": \"two-head model only if its macro Dice gain on T2 has a CI above zero, otherwise the T2 U-Net\", \"t3\": \"average of GBM and SE-ResNet only if it beats the better single model (AUROC CI above zero)\", \"t4\": \"simplest package-feasible candidate (B0 GBM), replaced by a more complex one only if its AUROC gain has a CI above zero; thresholds tuned out-of-fold for nMCC\"}}\n", " A3 = ens()\n", " A5 = np.load(C.CACHE / \"t1_ens5.npy\", mmap_mode=\"r\")\n", " FM = load_oof(\"flow\", len(m))\n", " rs, _ = gather_tcn(0, \"t1_tcnsharp\")\n", " S5 = np.load(C.CACHE / \"t1_sharp5.npy\", mmap_mode=\"r\") if (C.CACHE / \"t1_sharp5.npy\").exists() else None\n", " cands = {\"ens3\": lambda i: A3[i, :, 0], \"ens5\": lambda i: np.asarray(A5[i, :, 0])}\n", " if S5 is not None:\n", " cands[\"sharp5\"] = lambda i: np.asarray(S5[i, :, 0])\n", " cands[\"ens5+sharp5\"] = lambda i: 0.5 * (np.asarray(A5[i, :, 0]) + np.asarray(S5[i, :, 0]))\n", " if FM:\n", " cands[\"sharp5+flow\"] = lambda i: 0.5 * (np.asarray(S5[i, :, 0]) + np.median(FM[int(i)][\"samples\"].astype(np.float32), 0))\n", " if FM:\n", " cands[\"flow\"] = lambda i: np.median(FM[int(i)][\"samples\"].astype(np.float32), 0)\n", " cands[\"ens5+flow\"] = lambda i: 0.5 * (np.asarray(A5[i, :, 0]) + np.median(FM[int(i)][\"samples\"].astype(np.float32), 0))\n", " if rs is not None:\n", " cands[\"sharp\"] = lambda i: rs[i, :, 0]\n", " cands[\"ens5+sharp\"] = lambda i: 0.5 * (np.asarray(A5[i, :, 0]) + rs[i, :, 0])\n", " recs = np.array([i for i in ok if (not FM or int(i) in FM)])\n", " sse = {k: np.zeros(recs.size) for k in cands}\n", " sae = {k: np.zeros(recs.size) for k in cands}\n", " nn_ = np.zeros(recs.size)\n", " for j, i in enumerate(recs):\n", " for k, fn in cands.items():\n", " e, _ = fhr_abs_errors(fill_linear(fn(i)), ref[i])\n", " sse[k][j], sae[k][j] = (e ** 2).sum(), e.sum()\n", " nn_[j] = e.size\n", " g = m.group.values[recs]\n", " cost = load_json(C.RES / \"s30_t1_families.json\", {}).get(\"inference_cost\", {})\n", " tcn1 = cost.get(\"tcn_single\", {}).get(\"s_per_record\", 0.005)\n", " flow1 = cost.get(\"flow\", {}).get(\"s_per_record\", 0.7)\n", " t_est = {\"ens3\": 15 * tcn1, \"ens5\": 25 * tcn1, \"flow\": flow1, \"ens5+flow\": 25 * tcn1 + flow1, \"sharp\": 5 * tcn1, \"ens5+sharp\": 30 * tcn1, \"sharp5\": 25 * tcn1, \"ens5+sharp5\": 50 * tcn1, \"sharp5+flow\": 25 * tcn1 + flow1}\n", " t1 = {}\n", " for k in cands:\n", " t1[k] = {\"rmse\": float(np.sqrt(sse[k].sum() / nn_.sum())), \"mae\": float(sae[k].sum() / nn_.sum()), \"model_seconds_per_record_estimate\": t_est.get(k)}\n", " if k != \"ens5\":\n", " t1[k][\"rmse_minus_ens5\"] = boot(lambda i, k=k: np.sqrt(sse[k][i].sum() / nn_[i].sum()) - np.sqrt(sse[\"ens5\"][i].sum() / nn_[i].sum()), g)[0]\n", " t1[k][\"mae_minus_ens5\"] = boot(lambda i, k=k: sae[k][i].sum() / nn_[i].sum() - sae[\"ens5\"][i].sum() / nn_[i].sum(), g)[0]\n", " ok1 = [k for k in cands if k != \"ens5\" and t1[k][\"rmse_minus_ens5\"][\"hi\"] is not None and t1[k][\"rmse_minus_ens5\"][\"hi\"] < 0 and t1[k][\"mae_minus_ens5\"][\"hi\"] <= 0.02 and (t_est.get(k) or 99) <= C.T1_TIME_BUDGET_S]\n", " t1_choice = min(ok1, key=lambda k: t1[k][\"rmse\"]) if ok1 else \"ens5\"\n", " rep[\"t1\"] = {\"candidates\": t1, \"chosen\": t1_choice}\n", " m2 = load_df(C.CACHE / \"folds_t2.pkl\")\n", " Y2 = np.asarray(mm(C.CACHE / \"t2_lab.npy\"))\n", " th = {}\n", " for f in range(C.N_FOLDS):\n", " p = C.CACHE / f\"t2_twohead_oof_f{f}.npz\"\n", " if p.exists():\n", " with np.load(p) as z:\n", " arrs = {k: z[k] for k in z.files}\n", " for k_, i in enumerate(arrs[\"idx2\"]):\n", " th[int(i)] = arrs[\"p2\"][k_].astype(np.float32)\n", " P2u = np.asarray(mm(C.CACHE / \"t2_unet_oof_probs.npy\"), np.float32)\n", " w = np.array(sorted(i for i in th if m2.fold.values[i] >= 0 and np.isfinite(P2u[i, 0, 0])))\n", " t2 = {}\n", " if w.size:\n", " f2 = m2.fold.values[w]\n", " Su, pu = crossfit_post(np.nan_to_num(P2u[w]), Y2[w], f2)\n", " Sh, ph = crossfit_post(np.nan_to_num(np.stack([th[i] for i in w])), Y2[w], f2)\n", " g2 = m2.group.values[w]\n", " su, Du, Eu = seg_scores(Su, Y2[w], g2)\n", " sh, Dh, Eh = seg_scores(Sh, Y2[w], g2)\n", " d = boot(lambda i: seg_vec(Dh, Eh, i) - seg_vec(Du, Eu, i), g2)\n", " t2 = {\"t2_unet\": su, \"two_head\": sh, \"two_head_minus_unet\": dict(zip([\"dice_dec_pooled\", \"dice_macro_pooled\", \"evidence_dec_f1\", \"evidence_macro_f1\"], d))}\n", " use_h = d[1][\"lo\"] is not None and d[1][\"lo\"] > 0\n", " t2[\"chosen\"] = \"t2_twohead\" if use_h else \"t2_unet\"\n", " t2[\"post\"] = mode_params(ph if use_h else pu)\n", " else:\n", " t2 = {\"chosen\": \"t2_unet\", \"post\": list(load_json(C.RES / \"s14_t2_eval.json\")[\"unet_t2_on_t2\"][\"params\"][\"0\"])}\n", " rep[\"t2\"] = t2\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " F3 = load_df(C.CACHE / \"t3_features.pkl\")\n", " y3 = m3.y.values\n", " pg = oof(F3, y3, m3.fold.values, list(F3.columns))\n", " pdp = gather(\"t3_deep_oof\", len(m3))\n", " k3 = (m3.fold.values >= 0) & np.isfinite(pg) & np.isfinite(pdp)\n", " pa = 0.5 * (pg + pdp)\n", " g3 = m3.group.values[k3]\n", " a_g, a_d, a_a = fauc(y3[k3], pg[k3]), fauc(y3[k3], pdp[k3]), fauc(y3[k3], pa[k3])\n", " best_single = \"gbm\" if a_g >= a_d else \"deep\"\n", " ps = pg if best_single == \"gbm\" else pdp\n", " dd = boot(lambda i: fauc(y3[k3][i], pa[k3][i]) - fauc(y3[k3][i], ps[k3][i]), g3)[0]\n", " mode3 = [\"gbm\", \"deep\"] if dd[\"lo\"] is not None and dd[\"lo\"] > 0 else [best_single]\n", " p3 = pa if len(mode3) == 2 else ps\n", " f3 = m3.fold.values[k3]\n", " rep[\"t3\"] = {\"auroc\": {\"gbm\": a_g, \"deep\": a_d, \"average\": a_a}, \"average_minus_best_single\": dd, \"mode\": mode3, \"threshold_nmcc\": nmcc_threshold(y3[k3], p3[k3]), \"threshold_per_fold\": {str(f): nmcc_threshold(y3[k3][f3 == f], p3[k3][f3 == f]) for f in range(C.N_FOLDS) if (f3 == f).any()}, \"n\": int(k3.sum())}\n", " z = np.load(C.CACHE / \"w11_t4_candidates.npz\")\n", " y4 = z[\"y\"]\n", " g4 = m.group.values[z[\"idx\"]]\n", " P = {k: z[k] for k in z.files if k not in (\"idx\", \"y\")}\n", " P[\"B0+D0\"] = 0.5 * (P[\"B0\"] + P[\"D0_deep\"])\n", " P[\"B0pU+D0\"] = 0.5 * (P[\"B0pU\"] + P[\"D0_deep\"])\n", " feasible = [\"B0\", \"B0pU\", \"B0+D0\", \"B0pU+D0\"]\n", " t4 = {\"auroc\": {k: fauc(y4, p) for k, p in P.items()}}\n", " chosen = \"B0\"\n", " steps = []\n", " for k in feasible[1:]:\n", " d = boot(lambda i, k=k, c=chosen: fauc(y4[i], P[k][i]) - fauc(y4[i], P[c][i]), g4)[0]\n", " steps.append({\"candidate\": k, \"versus\": chosen, \"auroc_gain\": d})\n", " if d[\"lo\"] is not None and d[\"lo\"] > 0:\n", " chosen = k\n", " t4[\"selection_steps\"] = steps\n", " t4[\"chosen\"] = chosen\n", " t4[\"C_minus_chosen\"] = boot(lambda i: fauc(y4[i], P[\"C\"][i]) - fauc(y4[i], P[chosen][i]), g4)[0]\n", " t4[\"threshold_nmcc\"] = nmcc_threshold(y4, P[chosen])\n", " t4[\"at_threshold\"] = binary_scores(y4, P[chosen], t4[\"threshold_nmcc\"])\n", " f4 = m.fold.values[z[\"idx\"]]\n", " t4[\"threshold_per_fold\"] = {str(f): nmcc_threshold(y4[f4 == f], P[chosen][f4 == f]) for f in range(C.N_FOLDS) if (f4 == f).any()}\n", " mode4 = ([\"gbm\"] if chosen.startswith(\"B0\") else []) + ([\"deep\"] if \"D0\" in chosen else [])\n", " t4[\"mode\"] = mode4\n", " t4[\"use_U\"] = \"B0pU\" in chosen\n", " t4[\"post\"] = mode_params(load_json(C.RES / \"s47_cascade_controls.json\")[\"post_params_B0\"])\n", " rep[\"t4\"] = t4\n", " save_json(C.RES / \"s50_competition_selection.json\", rep)\n", " return {\"t1\": t1_choice, \"t2\": t2[\"chosen\"], \"t3\": mode3, \"t4\": chosen}\n", "\n", "\n", "PREDICT = '''import argparse\n", "import json\n", "import sys\n", "import time\n", "import traceback\n", "from pathlib import Path\n", "\n", "HERE = Path(__file__).resolve().parent\n", "sys.path.insert(0, str(HERE))\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "\n", "def main():\n", " ap = argparse.ArgumentParser()\n", " ap.add_argument(\"--input\", required=True)\n", " ap.add_argument(\"--output\", required=True)\n", " ap.add_argument(\"--tasks\", default=\"1,2,3,4\")\n", " a = ap.parse_args()\n", " import ctglib\n", " from ctglib.infer import Package\n", " pk = Package(HERE)\n", " inp, out = Path(a.input), Path(a.output)\n", " out.mkdir(parents=True, exist_ok=True)\n", " man = {\"ctglib\": ctglib.__file__, \"device\": str(pk.dev), \"tasks\": {}}\n", " for t in a.tasks.split(\",\"):\n", " d = inp / f\"task{t}\"\n", " if not d.is_dir():\n", " continue\n", " od = out / f\"task{t}\"\n", " od.mkdir(parents=True, exist_ok=True)\n", " t0 = time.time()\n", " n, errors, rows = 0, [], []\n", " files = sorted(d.glob(\"*.wav\")) if t in (\"1\", \"4\") else sorted(d.glob(\"*.csv\"))\n", " for f in files:\n", " try:\n", " if t == \"1\":\n", " r = pk.t1(f)\n", " pd.DataFrame({\"fhr\": r[\"fhr\"], \"p_far\": r[\"p_far\"]}).to_csv(od / f\"{f.stem}.csv\", index=False)\n", " elif t == \"2\":\n", " lab = pk.t2(pd.read_csv(f)[\"fhr\"].to_numpy(np.float32))\n", " pd.DataFrame({\"label\": lab}).to_csv(od / f\"{f.stem}.csv\", index=False)\n", " elif t == \"3\":\n", " df = pd.read_csv(f)\n", " p, c = pk.t3(df[\"FHR\"].to_numpy(np.float32), df[\"UC\"].to_numpy(np.float32))\n", " rows.append({\"record_id\": f.stem, \"risk_probability\": p, \"risk_class\": c})\n", " else:\n", " json.dump(pk.t4(f, f.stem), open(od / f\"{f.stem}.json\", \"w\"), indent=1)\n", " n += 1\n", " except Exception:\n", " errors.append({\"file\": f.name, \"error\": traceback.format_exc()[-800:]})\n", " if t == \"3\":\n", " pd.DataFrame(rows).to_csv(od / \"predictions.csv\", index=False)\n", " man[\"tasks\"][t] = {\"n\": n, \"files\": len(files), \"seconds\": time.time() - t0, \"errors\": errors}\n", " json.dump(man, open(out / \"run_manifest.json\", \"w\"), indent=1)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()\n", "'''\n", "\n", "DOCKER = '''FROM pytorch/pytorch:{torch}-cuda12.4-cudnn9-runtime\n", "WORKDIR /app\n", "COPY requirements.txt /app/requirements.txt\n", "RUN pip install --no-cache-dir -r /app/requirements.txt\n", "COPY . /app\n", "ENTRYPOINT [\"python\", \"-I\", \"/app/predict.py\", \"--input\", \"/input\", \"--output\", \"/output\"]\n", "'''\n", "\n", "\n", "OFFLINE = '''import runpy\n", "import socket\n", "import sys\n", "\n", "\n", "def blocked(*a, **k):\n", " raise OSError(\"network disabled for the offline check\")\n", "\n", "\n", "socket.socket.connect = blocked\n", "socket.socket.connect_ex = blocked\n", "socket.create_connection = blocked\n", "script = sys.argv[1]\n", "sys.argv = sys.argv[1:]\n", "runpy.run_path(script, run_name=\"__main__\")\n", "'''\n", "\n", "COMPARE = '''import json\n", "import sys\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "\n", "def main(exp, out):\n", " exp, out = Path(exp), Path(out)\n", " bad = []\n", " for f in sorted((exp / \"task1\").glob(\"*.csv\")):\n", " a, b = pd.read_csv(f)[\"fhr\"].to_numpy(), pd.read_csv(out / \"task1\" / f.name)[\"fhr\"].to_numpy()\n", " if a.shape != b.shape or np.max(np.abs(a - b)) > 1.0:\n", " bad.append((\"task1\", f.name, float(np.max(np.abs(a - b))) if a.shape == b.shape else \"shape\"))\n", " for f in sorted((exp / \"task2\").glob(\"*.csv\")):\n", " a, b = pd.read_csv(f)[\"label\"].to_numpy(), pd.read_csv(out / \"task2\" / f.name)[\"label\"].to_numpy()\n", " if a.shape != b.shape or np.mean(a == b) < 0.99:\n", " bad.append((\"task2\", f.name, float(np.mean(a == b)) if a.shape == b.shape else \"shape\"))\n", " if (exp / \"task3\" / \"predictions.csv\").exists():\n", " a, b = pd.read_csv(exp / \"task3\" / \"predictions.csv\"), pd.read_csv(out / \"task3\" / \"predictions.csv\")\n", " if len(a) != len(b) or np.max(np.abs(a.risk_probability.values - b.risk_probability.values)) > 0.01:\n", " bad.append((\"task3\", \"predictions.csv\", \"probabilities differ\"))\n", " for f in sorted((exp / \"task4\").glob(\"*.json\")):\n", " a, b = json.load(open(f)), json.load(open(out / \"task4\" / f.name))\n", " if abs(a[\"risk_probability\"] - b[\"risk_probability\"]) > 0.01 or a[\"risk_class\"] != b[\"risk_class\"]:\n", " bad.append((\"task4\", f.name, \"risk differs\"))\n", " print(json.dumps({\"ok\": not bad, \"differences\": bad}, indent=1))\n", " sys.exit(0 if not bad else 1)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main(sys.argv[1], sys.argv[2])\n", "'''\n", "\n", "BUILD = '''#!/usr/bin/env bash\n", "set -euo pipefail\n", "cd \"$(dirname \"$0\")\"\n", "docker build -t ctg-gc9 .\n", "rm -rf tests/out\n", "mkdir -p tests/out\n", "if docker run --rm --gpus all --network none -v \"$PWD/tests/input:/input:ro\" -v \"$PWD/tests/out:/output\" ctg-gc9; then\n", " echo \"ran on GPU\"\n", "else\n", " rm -rf tests/out\n", " mkdir -p tests/out\n", " docker run --rm --network none -v \"$PWD/tests/input:/input:ro\" -v \"$PWD/tests/out:/output\" ctg-gc9\n", " echo \"ran on CPU\"\n", "fi\n", "python3 tests/compare.py tests/expected tests/out\n", "'''\n", "\n", "\n", "def compare_outputs(a, b):\n", " diffs = {\"task1_max_abs\": 0.0, \"task2_min_agreement\": 1.0, \"task3_max_abs\": 0.0, \"task4_max_abs\": 0.0}\n", " for f in sorted((a / \"task1\").glob(\"*.csv\")):\n", " x, y = pd.read_csv(f)[\"fhr\"].to_numpy(), pd.read_csv(b / \"task1\" / f.name)[\"fhr\"].to_numpy()\n", " diffs[\"task1_max_abs\"] = max(diffs[\"task1_max_abs\"], float(np.max(np.abs(x - y))))\n", " for f in sorted((a / \"task2\").glob(\"*.csv\")):\n", " x, y = pd.read_csv(f)[\"label\"].to_numpy(), pd.read_csv(b / \"task2\" / f.name)[\"label\"].to_numpy()\n", " diffs[\"task2_min_agreement\"] = min(diffs[\"task2_min_agreement\"], float(np.mean(x == y)))\n", " p3 = a / \"task3\" / \"predictions.csv\"\n", " if p3.exists():\n", " diffs[\"task3_max_abs\"] = float(np.max(np.abs(pd.read_csv(p3).risk_probability.values - pd.read_csv(b / \"task3\" / \"predictions.csv\").risk_probability.values)))\n", " for f in sorted((a / \"task4\").glob(\"*.json\")):\n", " diffs[\"task4_max_abs\"] = max(diffs[\"task4_max_abs\"], abs(json.load(open(f))[\"risk_probability\"] - json.load(open(b / \"task4\" / f.name))[\"risk_probability\"]))\n", " diffs[\"ok\"] = bool(diffs[\"task1_max_abs\"] <= 1.0 and diffs[\"task2_min_agreement\"] >= 0.99 and diffs[\"task3_max_abs\"] <= 0.01 and diffs[\"task4_max_abs\"] <= 0.01)\n", " return diffs\n", "\n", "\n", "def versions():\n", " from importlib.metadata import version\n", " out = {}\n", " for p in (\"numpy\", \"scipy\", \"pandas\", \"scikit-learn\", \"PyWavelets\", \"torch\"):\n", " try:\n", " out[p] = version(p)\n", " except Exception:\n", " out[p] = None\n", " return out\n", "\n", "\n", "def copy_model(src, dst_root, rel):\n", " d = dst_root / rel\n", " d.parent.mkdir(parents=True, exist_ok=True)\n", " shutil.copy2(src, d)\n", " return str(rel)\n", "\n", "\n", "@stage(\"s51_package\", params={\"v\": 2})\n", "def package(log):\n", " from .t3 import model as gbm\n", " sel = load_json(C.RES / \"s50_competition_selection.json\")\n", " P = C.PACKAGE_DIR\n", " if P.exists():\n", " shutil.rmtree(P)\n", " (P / \"ctglib\").mkdir(parents=True)\n", " for f in Path(__file__).resolve().parent.glob(\"*.py\"):\n", " shutil.copy2(f, P / \"ctglib\" / f.name)\n", " cfg = {\"t1\": {\"choice\": sel[\"t1\"][\"chosen\"], \"members\": []}, \"t2\": {\"model\": sel[\"t2\"][\"chosen\"]}, \"t3\": {\"mode\": sel[\"t3\"][\"mode\"]}, \"t4\": {\"mode\": sel[\"t4\"][\"mode\"], \"candidate\": sel[\"t4\"][\"chosen\"]}, \"models\": {}, \"notes\": \"test-time models are bagged over the five outer folds; selection and thresholds come from out-of-fold predictions (s50); output schema to align with the official specification when released\"}\n", " ch = sel[\"t1\"][\"chosen\"]\n", " seeds = list(range(C.T1_SEEDS_FAMILY)) if \"ens5\" in ch else (list(range(C.T1_SEEDS)) if ch == \"ens3\" else [])\n", " if sel[\"t4\"].get(\"use_U\") and not seeds:\n", " seeds = list(range(C.T1_SEEDS))\n", " mods = {}\n", " if seeds:\n", " mods[\"t1_tcn\"] = [(C.MODELS / \"t1_tcn\" / f\"fold{f}{sfx(s)}\" / \"best.pt\", f\"models/t1_tcn/fold{f}{sfx(s)}.pt\") for f in range(C.N_FOLDS) for s in seeds]\n", " cfg[\"t1\"][\"ens_members_for_output\"] = \"ens\" in ch\n", " if \"sharp\" in ch:\n", " ss = list(range(5)) if \"sharp5\" in ch else [0]\n", " mods[\"t1_tcn_sharp\"] = [(C.MODELS / \"t1_tcn_sharp\" / f\"fold{f}{sfx(s)}\" / \"best.pt\", f\"models/t1_tcn_sharp/fold{f}{sfx(s)}.pt\") for f in range(C.N_FOLDS) for s in ss]\n", " if \"flow\" in ch:\n", " mods[\"t1_flow\"] = [(C.MODELS / \"t1_flow\" / f\"fold{f}\" / \"best.pt\", f\"models/t1_flow/fold{f}.pt\") for f in range(C.N_FOLDS)]\n", " cfg[\"t1\"][\"members\"] = [k for k in (\"t1_tcn\", \"t1_tcn_sharp\", \"t1_flow\") if k in mods and (k != \"t1_tcn\" or \"ens\" in ch)]\n", " cfg[\"t1\"][\"u_basis\"] = \"t1_tcn_seeds_0_2\" if \"t1_tcn\" in mods else None\n", " cfg[\"t1\"][\"u_seeds\"] = [s for s in seeds if s < C.T1_SEEDS]\n", " k2 = sel[\"t2\"][\"chosen\"]\n", " mods[k2] = [(C.MODELS / k2 / f\"fold{f}\" / \"best.pt\", f\"models/{k2}/fold{f}.pt\") for f in range(C.N_FOLDS)]\n", " mods[\"t2_est\"] = [(C.MODELS / \"t2_est\" / f\"fold{f}\" / \"best.pt\", f\"models/t2_est/fold{f}.pt\") for f in range(C.N_FOLDS)]\n", " if \"deep\" in sel[\"t3\"][\"mode\"]:\n", " mods[\"t3_deep\"] = [(C.MODELS / \"t3_deep\" / f\"fold{f}\" / \"best.pt\", f\"models/t3_deep/fold{f}.pt\") for f in range(C.N_FOLDS)]\n", " if \"deep\" in sel[\"t4\"][\"mode\"]:\n", " mods[\"t4_deep\"] = [(C.MODELS / \"t4_deep\" / f\"fold{f}\" / \"best.pt\", f\"models/t4_deep/fold{f}.pt\") for f in range(C.N_FOLDS)]\n", " missing = [str(s) for v in mods.values() for s, _ in v if not s.exists()]\n", " if missing:\n", " raise FileNotFoundError(f\"models missing for the package: {missing[:5]}\")\n", " for k, v in mods.items():\n", " cfg[\"models\"][k] = [copy_model(s, P, r) for s, r in v]\n", " art = {\"t2_post\": sel[\"t2\"][\"post\"], \"t4_post\": sel[\"t4\"][\"post\"], \"t3_thr\": sel[\"t3\"][\"threshold_nmcc\"], \"t4_thr\": sel[\"t4\"][\"threshold_nmcc\"]}\n", " m3 = load_df(C.CACHE / \"folds_t3.pkl\")\n", " F3 = load_df(C.CACHE / \"t3_features.pkl\")\n", " tr3 = m3.fold.values >= 0\n", " if \"gbm\" in sel[\"t3\"][\"mode\"]:\n", " art[\"t3_gbm\"] = gbm(int(tr3.sum())).fit(F3.values[tr3], m3.y.values[tr3])\n", " art[\"t3_cols\"] = list(F3.columns)\n", " if \"gbm\" in sel[\"t4\"][\"mode\"]:\n", " T4F = load_df(C.CACHE / \"w11_t4_features.pkl\")\n", " idx = T4F.pop(\"_idx\").values\n", " cols = [c for c in T4F.columns if sel[\"t4\"][\"use_U\"] or not c.startswith(\"u_\")]\n", " art[\"t4_gbm\"] = gbm(idx.size).fit(T4F[cols].values, meta().y.values[idx])\n", " art[\"t4_cols\"] = cols\n", " with open(P / \"artefacts.pkl\", \"wb\") as fh:\n", " pickle.dump(art, fh)\n", " vers = versions()\n", " cfg[\"versions\"] = vers\n", " json.dump(cfg, open(P / \"config.json\", \"w\"), indent=1)\n", " (P / \"predict.py\").write_text(PREDICT)\n", " (P / \"Dockerfile\").write_text(DOCKER.format(torch=\"2.5.1\"))\n", " (P / \"requirements.txt\").write_text(\"\\n\".join(f\"{p}=={v}\" for p, v in vers.items() if v and p != \"torch\") + \"\\n\")\n", " (P / \"README.md\").write_text(\"# CTG GC-9 inference package\\n\\nRun: `python -I predict.py --input
| \n", " | stage | \n", "time | \n", "seconds | \n", "outputs_present | \n", "
|---|---|---|---|---|
| 0 | \n", "s01_acquire | \n", "2026-11-27 13:51:18 | \n", "825.4 | \n", "True | \n", "
| 1 | \n", "s02_consolidate | \n", "2026-11-27 13:51:39 | \n", "19.3 | \n", "True | \n", "
| 2 | \n", "s03_audit | \n", "2026-11-27 13:53:42 | \n", "122.8 | \n", "True | \n", "
| 3 | \n", "s04_folds | \n", "2026-11-27 13:53:56 | \n", "12.1 | \n", "True | \n", "
| 4 | \n", "s05_metrics_selftest | \n", "2026-11-27 13:53:59 | \n", "1.5 | \n", "True | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| 138 | \n", "s53_summary_w1113 | \n", "2026-11-28 14:17:07 | \n", "4.6 | \n", "True | \n", "
| 139 | \n", "s55_t1_calibration_v2 | \n", "2026-11-28 09:13:35 | \n", "1305.6 | \n", "True | \n", "
| 140 | \n", "s56_shortcut_control | \n", "2026-11-28 09:15:50 | \n", "114.7 | \n", "True | \n", "
| 141 | \n", "s57_validation_submission | \n", "2026-11-28 09:15:59 | \n", "0.2 | \n", "True | \n", "
| 142 | \n", "s58_summary_final | \n", "2026-11-28 14:17:13 | \n", "4.4 | \n", "True | \n", "
143 rows × 4 columns
\n", "