Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 77350b8fec | |||
| a9945bc021 | |||
| 3a749ba8d1 | |||
| f369e8f2eb | |||
| f3f79831bf | |||
| 43207fa3a5 | |||
| 7e8e8b44d8 | |||
| 5c781f2a52 | |||
| 8e9da2c73a | |||
| 53e6f77c9e | |||
| 924f662a21 | |||
| 1a46a5ba73 | |||
| 61eb3a30d0 | |||
| 0c78f8cf7d | |||
| 385cc5b80b | |||
| 3546269eaf | |||
| 7b9ae69de2 | |||
| 4ff4a3a7d8 | |||
| 999f0fb926 | |||
| 02aab07a67 | |||
| 44cb0dc894 | |||
| 76eb8cc8af | |||
| f305cdd044 | |||
| e2f7e95e83 | |||
| d3d9cc3950 | |||
| 8c0ec5106c | |||
| b6857dab2a | |||
| bea3e4cd2d | |||
| 77fc039586 | |||
| 0c4706658b | |||
| 61721a8005 | |||
| 8d874736db | |||
| 79a55a7a62 | |||
| f1370d2776 | |||
| 639bbcda19 | |||
| 3558e24a46 |
-12
@@ -1,14 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
|
||||
# MLflow's own default local stores, used only when MLFLOW_TRACKING_URI
|
||||
# isn't set (dev/tests point it elsewhere, e.g. a tmp_path file store).
|
||||
mlflow.db
|
||||
mlruns/
|
||||
mlartifacts/
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "tea"]
|
||||
path = libs/tea
|
||||
url = ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
@@ -1,46 +0,0 @@
|
||||
# models
|
||||
|
||||
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
|
||||
versiones en MLflow con requisitos de promoción, registro de predicciones y
|
||||
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
|
||||
armados del kit de indicadores (`cohorte_armado`, en la base de cada
|
||||
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
|
||||
WebApi.
|
||||
|
||||
| Módulo | Qué hace |
|
||||
|---|---|
|
||||
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
|
||||
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
|
||||
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`), dbt's manifest (`read_queries`), and Persistance repositories (`resolve_repository`, `ReadOnlyRepository`, ML-04). |
|
||||
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the hashes of code, files, tables and models (`code_version`, `model_sha`), and `matches`, the one rule for "already done". |
|
||||
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), environment (ML-02), git commit and `log_model` with its `modelo_sha`. In PROD, only models whose class lives in a module. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). |
|
||||
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
|
||||
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
|
||||
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
|
||||
| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). |
|
||||
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
|
||||
| `steps/report.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks/<scenario>/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it to one HTML page (`io/rendering.py`), and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. With Quarto, `QUARTO_BIN` and a Python with Jupyter (`QUARTO_PYTHON`). |
|
||||
| `io/rendering.py` | Runs a notebook and renders its page. Renderers are classes (`RENDERERS`, `register_renderer`): `quarto` and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
|
||||
| `pipelines/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
|
||||
| `io/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
|
||||
| `io/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. |
|
||||
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
|
||||
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
|
||||
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Training records its five routines (`sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`). Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
|
||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
||||
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
|
||||
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
|
||||
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
|
||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
|
||||
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
|
||||
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
|
||||
guardan sus artefactos.
|
||||
|
||||
```bash
|
||||
uv run pytest -q
|
||||
```
|
||||
-1
Submodule libs/tea deleted from 05ee02990c
@@ -1,479 +0,0 @@
|
||||
"""The package's command line: `python -m models <command>`.
|
||||
|
||||
Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the
|
||||
command that needs them, so `--help` stays immediate.
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||
"""A command without actions yet shows its help and fails, rather than appearing to have run."""
|
||||
parser.print_help()
|
||||
return 2
|
||||
|
||||
|
||||
def _model_module(args: argparse.Namespace, name: str):
|
||||
"""A module of the model's folder; `None` and a message on stderr if there's no such model."""
|
||||
from importlib import import_module
|
||||
|
||||
package = f"models.{args.domain}.{args.scenario}"
|
||||
try:
|
||||
return import_module(f"{package}.{name}")
|
||||
except ModuleNotFoundError as error:
|
||||
if not (error.name or "").startswith(package):
|
||||
raise
|
||||
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _own_steps(args: argparse.Namespace):
|
||||
"""A scenario that isn't trained on a cohort build runs its own steps: its `model.run_steps`, or `None`."""
|
||||
from importlib import import_module
|
||||
|
||||
try:
|
||||
model = import_module(f"models.{args.domain}.{args.scenario}.model")
|
||||
except ModuleNotFoundError:
|
||||
return None
|
||||
return getattr(model, "run_steps", None)
|
||||
|
||||
|
||||
def _cohort_file(args: argparse.Namespace, model):
|
||||
"""The build's exported file; `None` and a message on stderr if it's missing."""
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
|
||||
|
||||
url = model.SETTINGS["cohort"]
|
||||
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
if args.source == "kit":
|
||||
return find_cohort_file(root, url, args.armado)
|
||||
if args.armado is not None:
|
||||
if not (path := dbt_build_path(root, url, args.armado)).exists():
|
||||
raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
if not (latest := latest_dbt_build(root, url)):
|
||||
raise FileNotFoundError(f"no exported dbt builds of {url} under {root}")
|
||||
return latest[1]
|
||||
except (FileNotFoundError, ValueError) as error:
|
||||
print(f"{error}: export it with `{command}`", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Trains the model on the build's file, always as a new version."""
|
||||
if args.environment == "prod" and args.armado is None:
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
|
||||
return 1
|
||||
if not (path := _cohort_file(args, model)):
|
||||
return 1
|
||||
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _estimate_step(args: argparse.Namespace, path) -> int:
|
||||
estimator = _model_module(args, "estimate")
|
||||
if not estimator:
|
||||
return 1
|
||||
try:
|
||||
resolved, written = estimator.estimate(path, args.output, args.version)
|
||||
except LookupError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}")
|
||||
return 0
|
||||
|
||||
|
||||
def _store_step(args: argparse.Namespace, estimate_path) -> int:
|
||||
from models.pipelines.store_risks import store_estimate
|
||||
|
||||
try:
|
||||
batch, written = store_estimate(estimate_path, args.domain)
|
||||
except (LookupError, ValueError, FileNotFoundError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _store(args: argparse.Namespace) -> int:
|
||||
"""Stores an estimate file as a batch of risks in the domain's database."""
|
||||
return _store_step(args, args.input)
|
||||
|
||||
|
||||
def _report_eda(args: argparse.Namespace) -> int:
|
||||
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
|
||||
from pathlib import Path
|
||||
|
||||
from models.io.rendering import RenderError
|
||||
from models.pipelines.report_eda import report_eda
|
||||
|
||||
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
|
||||
return 1
|
||||
notebook = Path(args.notebook) if args.notebook else (
|
||||
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
|
||||
if not notebook.exists():
|
||||
print(f"no notebook at {notebook}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
|
||||
except RenderError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _serve_notebooks(args: argparse.Namespace) -> int:
|
||||
"""The runner container's loop (`models.io.notebook_jobs.serve`)."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from models.io.notebook_jobs import JOBS_DIR_ENV, serve
|
||||
|
||||
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
|
||||
if not folder:
|
||||
print(f"no jobs folder: pass --jobs or set {JOBS_DIR_ENV}", file=sys.stderr)
|
||||
return 2
|
||||
serve(Path(folder), once=args.once)
|
||||
return 0
|
||||
|
||||
|
||||
def _tea_analyze(args: argparse.Namespace) -> int:
|
||||
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
|
||||
from models.eeg_analysis import analyze_pending
|
||||
|
||||
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
|
||||
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
|
||||
return 1 if s.failed else 0
|
||||
|
||||
|
||||
def _estimate(args: argparse.Namespace) -> int:
|
||||
"""Scores the build's file with a registered version and writes the output file."""
|
||||
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
|
||||
return 1
|
||||
return _estimate_step(args, path)
|
||||
|
||||
|
||||
def _promote_step(args: argparse.Namespace, version: str) -> int:
|
||||
"""Promotes through the same gate the WebApi's promote route uses (MLD-01/01b):
|
||||
a version missing its checklist (validation reports, routine records, a saved
|
||||
model) is rejected here exactly as it would be there, rather than set directly."""
|
||||
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
name = registered_name(args.domain, args.scenario)
|
||||
try:
|
||||
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
|
||||
except MlflowException:
|
||||
current = None
|
||||
if str(current) == str(version):
|
||||
print(f"already in production: version {version}")
|
||||
return 0
|
||||
try:
|
||||
registry.promote(args.domain, args.scenario, version)
|
||||
except PromotionBlocked as blocked:
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
|
||||
print(f"not promoted, missing: {failed}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"in production: version {version}")
|
||||
return 0
|
||||
|
||||
|
||||
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
|
||||
if not (args.export or args.train or args.promote or args.estimate or args.store):
|
||||
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
|
||||
if (own := _own_steps(args)) is not None:
|
||||
return own(args)
|
||||
if (args.estimate or args.store) and not args.output:
|
||||
parser.error("--estimate and --store need --output")
|
||||
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if args.export and args.source == "dbt" and not args.manifest:
|
||||
parser.error("--export with --source dbt needs --manifest")
|
||||
if args.export and args.source == "dbt" and args.armado is not None:
|
||||
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
|
||||
if args.train and args.version:
|
||||
parser.error("--version names an existing version: it can't go with --train")
|
||||
if not (model := _model_module(args, "model")):
|
||||
return 1
|
||||
|
||||
if args.export:
|
||||
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
|
||||
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
|
||||
manifest=args.manifest)
|
||||
if args.source == "dbt":
|
||||
export.build = None
|
||||
if code := _cohort_export(export):
|
||||
return code
|
||||
if not (args.train or args.promote or args.estimate):
|
||||
return _store_step(args, args.output) if args.store else 0
|
||||
|
||||
if not (path := _cohort_file(args, model)):
|
||||
return 1
|
||||
version = args.version
|
||||
if args.train or (args.promote and not version):
|
||||
if not (trainer := _model_module(args, "train")):
|
||||
return 1
|
||||
environment = args.environment.upper()
|
||||
version = trainer.find_trained(path, environment)
|
||||
if args.train and version:
|
||||
print(f"already trained: version {version}, from {path}")
|
||||
elif args.train:
|
||||
version = trainer.train(path, environment)
|
||||
print(f"trained: version {version}, from {path}")
|
||||
elif not version:
|
||||
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
|
||||
return 1
|
||||
if args.promote and (code := _promote_step(args, version)):
|
||||
return code
|
||||
if args.estimate and (code := _estimate_step(args, path)):
|
||||
return code
|
||||
return _store_step(args, args.output) if args.store else 0
|
||||
|
||||
|
||||
def _cohort_build(args: argparse.Namespace) -> int:
|
||||
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
from models.io.contracts import CohortDefinitionError
|
||||
from models.io.storage import read_queries
|
||||
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
queries = read_queries(args.manifest, url)
|
||||
if args.graph:
|
||||
print(mermaid(build_driver(queries).graph))
|
||||
return 0
|
||||
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
|
||||
except (FileNotFoundError, CohortDefinitionError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
except DBAPIError as error:
|
||||
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||
return 1
|
||||
print(built.attrition.to_string(index=False))
|
||||
print(f"{url}: {len(built.study_population)} members, not stored")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_export(args: argparse.Namespace) -> int:
|
||||
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.edges.dbt import DbtRelationError
|
||||
from persistance.settings import settings
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from models.io.contracts import CohortDefinitionError
|
||||
from models.io.storage import read_queries
|
||||
from models.io.storage import cohorts_root
|
||||
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
repositories = import_module(f"persistance.{args.domain}")
|
||||
timeline = repositories.timeline_repository
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
if args.source == "dbt":
|
||||
queries = read_queries(args.manifest, url)
|
||||
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
|
||||
else:
|
||||
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
|
||||
except PermissionError as error:
|
||||
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
||||
return 1
|
||||
except DBAPIError as error:
|
||||
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||
return 1
|
||||
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{outcome}: {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_list(args: argparse.Namespace) -> int:
|
||||
"""Prints the cohort's builds: dbt's from their files, the kit's from the database."""
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, list_builds
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
except ValueError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohort_repository
|
||||
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
|
||||
if not rows:
|
||||
print(f"{url}: no builds", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file")
|
||||
for row in rows:
|
||||
print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} "
|
||||
f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_show(args: argparse.Namespace) -> int:
|
||||
"""Prints one build's file, hash and lineage as JSON."""
|
||||
import json
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, describe_build
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
cohorts = import_module(f"persistance.{args.domain}").cohort_repository if args.source == "kit" else None
|
||||
described = describe_build(root, url, args.source, args.build, cohorts)
|
||||
except (ValueError, LookupError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(described, indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
if args.source == "dbt" and not args.manifest:
|
||||
parser.error("--source dbt needs --manifest")
|
||||
if args.source == "dbt" and args.build is not None:
|
||||
parser.error("--build names a kit build: it can't go with --source dbt")
|
||||
return _cohort_export(args)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
||||
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
||||
|
||||
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
||||
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
||||
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
|
||||
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
|
||||
build.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
|
||||
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
|
||||
build.set_defaults(run=_cohort_build)
|
||||
|
||||
export = actions.add_parser("export", help="export a build to its Parquet file, once")
|
||||
export.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
|
||||
help="the kit's stored build, or one built now from dbt's rules")
|
||||
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
|
||||
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
|
||||
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
|
||||
|
||||
listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file")
|
||||
listing.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database")
|
||||
listing.set_defaults(run=_cohort_list)
|
||||
|
||||
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
|
||||
show.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
|
||||
show.add_argument("--build", type=int, required=True, help="the build's number")
|
||||
show.set_defaults(run=_cohort_show)
|
||||
|
||||
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
|
||||
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
train.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
train.set_defaults(run=lambda args: _train(train, args))
|
||||
|
||||
estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version")
|
||||
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
||||
estimate.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
estimate.add_argument("--version", help="the model version; the one in production by default")
|
||||
estimate.set_defaults(run=_estimate)
|
||||
|
||||
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
|
||||
report.set_defaults(run=lambda args: _show_help(report))
|
||||
reports = report.add_subparsers(dest="action", metavar="<report>")
|
||||
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
|
||||
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
eda.add_argument("--notebook", help="the notebook; the scenario's notebooks/<scenario>/01_eda.ipynb by default")
|
||||
eda.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
|
||||
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
|
||||
eda.set_defaults(run=_report_eda)
|
||||
|
||||
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
|
||||
store.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
|
||||
store.set_defaults(run=_store)
|
||||
|
||||
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
|
||||
run.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
|
||||
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
|
||||
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
|
||||
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
|
||||
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
|
||||
run.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
||||
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
||||
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
|
||||
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
|
||||
run.set_defaults(run=lambda args: _run(run, args))
|
||||
|
||||
tea = commands.add_parser("tea", help="TEA's EEG analysis")
|
||||
tea.set_defaults(run=lambda args: _show_help(tea))
|
||||
tea_actions = tea.add_subparsers(dest="action", metavar="<action>")
|
||||
analyze = tea_actions.add_parser(
|
||||
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
|
||||
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
|
||||
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
|
||||
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
|
||||
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
|
||||
analyze.set_defaults(run=_tea_analyze)
|
||||
|
||||
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
|
||||
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
|
||||
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
|
||||
serve = notebook_actions.add_parser("serve", help="run each job left in the jobs folder, one at a time")
|
||||
serve.add_argument("--jobs", help="the jobs folder; NOTEBOOK_JOBS_DIR by default")
|
||||
serve.add_argument("--once", action="store_true", help="run the jobs waiting now and stop")
|
||||
serve.set_defaults(run=_serve_notebooks)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
return args.run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1 +0,0 @@
|
||||
"""CaCu's scenarios and notebooks."""
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
"""Scores a build's file with a registered version and writes the probabilities to a Parquet file."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pyarrow as pa
|
||||
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
|
||||
from models.io.registry import ResolvedVersion, registered_name, registry
|
||||
from models.io.storage import read_cohort, read_metadata, write_once
|
||||
|
||||
|
||||
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
|
||||
"""Whether the output file already holds this version's scores of this build's file."""
|
||||
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
|
||||
|
||||
|
||||
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]:
|
||||
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
|
||||
The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows
|
||||
come from, and the outcome and horizon they estimate (`cin2_12m`, 1.0 years); `modelo_sha` is copied when the
|
||||
version has it, and isn't checked."""
|
||||
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
|
||||
output_path = Path(output_path)
|
||||
resolved = registry.resolve(domain, scenario, version)
|
||||
cohort = cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))
|
||||
if already_estimated(output_path, resolved.version, cohort):
|
||||
return resolved, False
|
||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
|
||||
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
|
||||
window = SETTINGS["outcome_window_months"]
|
||||
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
|
||||
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
|
||||
**cohort}
|
||||
if resolved.modelo_sha:
|
||||
provenance["modelo_sha"] = resolved.modelo_sha
|
||||
table = pa.Table.from_pandas(risks, preserve_index=False)
|
||||
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
|
||||
return resolved, True
|
||||
@@ -1,215 +0,0 @@
|
||||
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
|
||||
|
||||
`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with
|
||||
no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet:
|
||||
it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda
|
||||
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
|
||||
nothing after them is used.
|
||||
|
||||
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from sklearn.compose import ColumnTransformer
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
|
||||
from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256
|
||||
from models.io.registry import registry
|
||||
from models.io.storage import read_cohort, read_metadata
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
|
||||
PREDICTORS = ("bethesda", "vph", "vph_16_18")
|
||||
MISSING = "(none)"
|
||||
DAYS_PER_MONTH = 30.44
|
||||
|
||||
|
||||
def cohort(cohort_path: str) -> pd.DataFrame:
|
||||
return read_cohort(cohort_path)
|
||||
|
||||
|
||||
def lineage(cohort_path: str) -> dict:
|
||||
return read_metadata(cohort_path)
|
||||
|
||||
|
||||
def cohort_sha256(cohort_path: str) -> str:
|
||||
return file_sha256(cohort_path)
|
||||
|
||||
|
||||
def code_sha256() -> str:
|
||||
"""The hash of this folder's steps and settings: what says the model itself changed."""
|
||||
folder = Path(__file__).parent
|
||||
return file_sha256(folder / "model.py", folder / "model.toml")
|
||||
|
||||
|
||||
def cutoff(lineage: dict) -> date:
|
||||
"""The build's cut-off: no event after it is in the file."""
|
||||
return date.fromisoformat(lineage["datos_as_of"])
|
||||
|
||||
|
||||
def predictors(cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none."""
|
||||
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
|
||||
sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])]
|
||||
sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample")
|
||||
results = cohort.merge(sample, left_on="pac_id", right_index=True)
|
||||
results = results[results["fuente_id"] == results["sample"]]
|
||||
genotype = results["tipo"] == "vph_genotipo_16_18"
|
||||
results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"})
|
||||
results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"})
|
||||
wide = results[results["tipo"].isin(PREDICTORS)].pivot_table(
|
||||
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
|
||||
wide = wide.reindex(columns=list(PREDICTORS))
|
||||
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
|
||||
{name: MISSING for name in PREDICTORS})
|
||||
|
||||
|
||||
def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame:
|
||||
"""One row per member: `y`, and `known`, whether the window is complete or the event already happened."""
|
||||
window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH
|
||||
days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
|
||||
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window)
|
||||
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
|
||||
members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int)
|
||||
follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
|
||||
members["known"] = (members["y"] == 1) | (follow_up >= window)
|
||||
return members[["pac_id", "y", "known"]]
|
||||
|
||||
|
||||
def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The members whose outcome is known, with their predictors and `y`."""
|
||||
labelled = predictors.merge(outcome, on="pac_id")
|
||||
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
|
||||
|
||||
|
||||
def split(prepare: pd.DataFrame) -> dict:
|
||||
"""The oldest index dates train and the newest test."""
|
||||
ordered = prepare.sort_values(["fecha_indice", "pac_id"], kind="stable")
|
||||
cut = int(len(ordered) * SETTINGS["train_fraction"])
|
||||
return {"train": ordered.iloc[:cut], "test": ordered.iloc[cut:]}
|
||||
|
||||
|
||||
def train(split: dict) -> pd.DataFrame:
|
||||
return split["train"]
|
||||
|
||||
|
||||
def test(split: dict) -> pd.DataFrame:
|
||||
return split["test"]
|
||||
|
||||
|
||||
def fit(train: pd.DataFrame) -> Pipeline:
|
||||
"""One-hot predictors, an unseen category counted as none of the known ones, and a logistic regression."""
|
||||
encode = ColumnTransformer([("results", OneHotEncoder(handle_unknown="ignore"), list(PREDICTORS))])
|
||||
return Pipeline([("encode", encode), ("logistic", LogisticRegression(max_iter=1000))]).fit(
|
||||
train[list(PREDICTORS)], train["y"])
|
||||
|
||||
|
||||
def predict(fit: Pipeline, test: pd.DataFrame) -> pd.Series:
|
||||
"""The probability of `y` for each row of `test`."""
|
||||
return pd.Series(fit.predict_proba(test[list(PREDICTORS)])[:, 1], index=test.index, name="probabilidad")
|
||||
|
||||
|
||||
def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict:
|
||||
"""Aggregates only: no patient data reaches MLflow."""
|
||||
return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)),
|
||||
"n_train": len(train), "n_test": len(test), "positive_rate_train": float(train["y"].mean()),
|
||||
"positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())}
|
||||
|
||||
|
||||
def _dates(frame: pd.DataFrame) -> dict:
|
||||
if frame.empty:
|
||||
return {"n": 0}
|
||||
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
|
||||
"last_index_date": str(frame["fecha_indice"].max())}
|
||||
|
||||
|
||||
def sampling(outcome: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
|
||||
"""MUESTREO: who could be used, and how they were split."""
|
||||
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
|
||||
"train_fraction": SETTINGS["train_fraction"], "members": len(outcome),
|
||||
"left_out_unknown_outcome": int((~outcome["known"]).sum()), "train": _dates(train), "test": _dates(test)}
|
||||
|
||||
|
||||
def missing_data(predictors: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
|
||||
"""DATOS_FALTANTES: how many lacked each predictor, and what was done about it."""
|
||||
def missing(frame: pd.DataFrame) -> dict:
|
||||
return {name: int((frame[name] == MISSING).sum()) for name in PREDICTORS}
|
||||
|
||||
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
|
||||
"members": missing(predictors), "train": missing(train), "test": missing(test)}
|
||||
|
||||
|
||||
def analytic_method(fit: Pipeline) -> dict:
|
||||
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
|
||||
logistic = fit.named_steps["logistic"]
|
||||
features = fit.named_steps["encode"].get_feature_names_out()
|
||||
return {"method": "regresión logística sobre los predictores codificados one-hot",
|
||||
"estimator": type(logistic).__name__, "settings": logistic.get_params(),
|
||||
"intercept": float(logistic.intercept_[0]),
|
||||
"coefficients": dict(zip(map(str, features), map(float, logistic.coef_[0])))}
|
||||
|
||||
|
||||
def class_balance(train: pd.DataFrame, test: pd.DataFrame, fit: Pipeline) -> dict:
|
||||
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
|
||||
weight = fit.named_steps["logistic"].class_weight
|
||||
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
|
||||
"train": {str(k): int(v) for k, v in train["y"].value_counts().sort_index().items()},
|
||||
"test": {str(k): int(v) for k, v in test["y"].value_counts().sort_index().items()}}
|
||||
|
||||
|
||||
def output_confidence(test: pd.DataFrame, predict: pd.Series) -> dict:
|
||||
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
|
||||
bins = pd.qcut(predict, q=min(SETTINGS.get("calibration_bins", 10), predict.nunique()), duplicates="drop")
|
||||
table = pd.DataFrame({"p": predict, "y": test["y"]}).groupby(bins, observed=True).agg(
|
||||
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
|
||||
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
|
||||
"brier": float(brier_score_loss(test["y"], predict)),
|
||||
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
|
||||
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
|
||||
|
||||
|
||||
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
|
||||
output_confidence: dict) -> dict:
|
||||
"""Each routine's record, by the kind it's stored under (ML-01a)."""
|
||||
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
|
||||
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
|
||||
|
||||
|
||||
class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
||||
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`
|
||||
for every member, whether their outcome is known or not."""
|
||||
|
||||
def __init__(self, fitted: Pipeline):
|
||||
self.fitted = fitted
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
members = predictors(model_input)
|
||||
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
|
||||
|
||||
|
||||
def registered_model(fit: Pipeline, evaluate: dict, routines: dict, lineage: dict, cohort_path: str,
|
||||
cohort_sha256: str, code_sha256: str, environment: str) -> str:
|
||||
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content,
|
||||
and which build it is, from the kit or from dbt's rules."""
|
||||
cohort = cohort_reference(lineage, cohort_sha256)
|
||||
armado_id = int(lineage["armado_id"]) if cohort[COHORT_SOURCE_TAG] == "kit" else None
|
||||
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
|
||||
cohorte_armado_id=armado_id, cohort=cohort)
|
||||
for kind, record in routines.items():
|
||||
run.log_routine(kind, record)
|
||||
run.log_model(Cin2Logistic(fit))
|
||||
run.finish(metrics=evaluate, hyperparameters={
|
||||
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256,
|
||||
"outcome_window_months": SETTINGS["outcome_window_months"], "event_grades": ",".join(SETTINGS["event_grades"]),
|
||||
"horizon_years": SETTINGS["outcome_window_months"] / 12})
|
||||
version = registry.register_run(run)
|
||||
registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"])
|
||||
return version
|
||||
@@ -1,13 +0,0 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_logistic"
|
||||
cohort = "cacu/cohorte_vigilancia"
|
||||
train_fraction = 0.7
|
||||
# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the
|
||||
# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a
|
||||
# complete window; 12 months leaves 5,231 known members, 162 with the event.
|
||||
outcome_window_months = 12
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
description = """
|
||||
Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \
|
||||
a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \
|
||||
validación clínica."""
|
||||
@@ -1,27 +0,0 @@
|
||||
"""The model's Hamilton driver, and what makes repeating a training a no-op."""
|
||||
|
||||
from hamilton import driver
|
||||
|
||||
from models.cacu.cin2_logistic import model
|
||||
from models.io.lineage import matches
|
||||
from models.io.registry import registered_name, registry
|
||||
|
||||
|
||||
def train(cohort_path: str, environment: str = "DEV") -> str:
|
||||
"""Trains on a build's file and returns the registered version."""
|
||||
dr = driver.Builder().with_modules(model).build()
|
||||
inputs = {"cohort_path": str(cohort_path), "environment": environment}
|
||||
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
|
||||
|
||||
|
||||
def find_trained(cohort_path: str, environment: str = "DEV") -> str | None:
|
||||
"""The newest version not retired from the same file, code and environment."""
|
||||
name = registered_name(model.SETTINGS["domain"], model.SETTINGS["scenario"])
|
||||
expected = {"cohort_sha256": model.cohort_sha256(str(cohort_path)), "code_sha256": model.code_sha256()}
|
||||
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
|
||||
for mv in versions:
|
||||
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
|
||||
continue
|
||||
if matches(registry.client.get_run(mv.run_id).data.params, expected):
|
||||
return str(mv.version)
|
||||
return None
|
||||
@@ -0,0 +1,164 @@
|
||||
"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
|
||||
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
|
||||
value_code, value_num, source_table, source_id."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
|
||||
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
|
||||
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
|
||||
MISSING = "(none)"
|
||||
|
||||
|
||||
def prepared(events: pd.DataFrame) -> pd.DataFrame:
|
||||
return events.assign(
|
||||
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
|
||||
)
|
||||
|
||||
|
||||
def days(events: pd.DataFrame) -> pd.Series:
|
||||
return (events["date"] - events["index_date"]).dt.days
|
||||
|
||||
|
||||
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
|
||||
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
|
||||
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
|
||||
names = list(cytology)
|
||||
worst = codes.map(rank).groupby(level=0).max()
|
||||
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
|
||||
|
||||
|
||||
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
|
||||
"""Why she was referred: the worst result in the year before her first colposcopy."""
|
||||
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
|
||||
before = (events["person_id"].map(first) - events["date"]).dt.days
|
||||
near = events[before.between(0, history["lookback_days"])]
|
||||
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
|
||||
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
||||
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
||||
positive = persons.isin(hpv["person_id"])
|
||||
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
|
||||
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
|
||||
& positive.to_numpy()), "low", None)) # fmt: skip
|
||||
return pd.Series(grade, index=persons.index, dtype=object)
|
||||
|
||||
|
||||
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
|
||||
"""Per patient: the cytology category and HPV result of her index sample (the first
|
||||
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
|
||||
when `history` asks for it."""
|
||||
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
|
||||
wide = near.sort_values("date", kind="stable").pivot_table(
|
||||
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||
)
|
||||
members = events.groupby("person_id", as_index=False)["index_date"].first()
|
||||
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
|
||||
codes = wide[["bethesda", "glandular"]].stack()
|
||||
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
|
||||
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
|
||||
if history:
|
||||
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
|
||||
return members
|
||||
|
||||
|
||||
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
|
||||
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
|
||||
negative co-test (the later day of its two results)."""
|
||||
timed = events.assign(days=d.astype(float))[d >= 0]
|
||||
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
|
||||
visits = None
|
||||
for kind, values in cacu.KNOWN_NEGATIVE.items():
|
||||
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
|
||||
found = found[["person_id", "days"]]
|
||||
if visits is None:
|
||||
visits = found
|
||||
continue
|
||||
paired = pd.merge_asof(
|
||||
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
|
||||
left_on="days", right_on=kind, by="person_id", direction="nearest",
|
||||
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
|
||||
).dropna(subset=[kind]) # fmt: skip
|
||||
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
|
||||
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
|
||||
|
||||
|
||||
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
|
||||
history: dict | None = None) -> pd.DataFrame: # fmt: skip
|
||||
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
|
||||
the prevalent window), free at the index (a negative before any outcome), or unknown;
|
||||
and the years between her last negative and her outcome biopsy."""
|
||||
d = days(events)
|
||||
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
|
||||
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
|
||||
negatives = _negatives(events, d, grades)
|
||||
before = ~(negatives["days"] >= negatives["person_id"].map(first))
|
||||
last_negative = negatives[before].groupby("person_id")["days"].max()
|
||||
|
||||
coded = index_results(events, cytology, history)
|
||||
window = cacu.PREVALENT_WINDOW_DAYS
|
||||
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
|
||||
prevalent = event_days <= window
|
||||
free = free_until.notna() & ~prevalent
|
||||
later = event_days.notna() & ~prevalent
|
||||
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
|
||||
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
|
||||
coded["r"] = np.where(prevalent, 0.0,
|
||||
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
|
||||
return coded
|
||||
|
||||
|
||||
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
|
||||
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
|
||||
key = ["person_id", "source_table", "source_id"]
|
||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||
[*key, "date"]] # fmt: skip
|
||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||
has = has.reindex(columns=list(RESULTS))
|
||||
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
|
||||
samples = samples.set_index(key)
|
||||
samples = samples[samples.index.isin(complete.index)].reset_index()
|
||||
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
|
||||
return latest["date"]
|
||||
|
||||
|
||||
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""Temporal: the earliest index dates train, the latest test."""
|
||||
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
|
||||
cut = int(len(ordered) * train_fraction)
|
||||
return ordered.iloc[:cut], ordered.iloc[cut:]
|
||||
|
||||
|
||||
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
|
||||
"""Per patient: each predictor's result on her index sample, MISSING when none."""
|
||||
members = events.groupby(["person_id", "index_date"], as_index=False).size()
|
||||
members = members[["person_id", "index_date"]]
|
||||
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
|
||||
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
|
||||
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
|
||||
genotype = results["type"] == "hpv_16_18"
|
||||
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
|
||||
{1.0: "positive", 0.0: "negative"}
|
||||
)
|
||||
wide = results[results["type"].isin(predictors)].pivot_table(
|
||||
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||
)
|
||||
wide = wide.reindex(columns=list(predictors)).astype(object)
|
||||
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
|
||||
return found.fillna(dict.fromkeys(predictors, MISSING))
|
||||
|
||||
|
||||
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
|
||||
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
|
||||
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
|
||||
window = years * cacu.DAYS_PER_YEAR
|
||||
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
|
||||
outcome &= days(events).between(0, window)
|
||||
members = events.groupby(["person_id", "index_date"], as_index=False).size()
|
||||
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
|
||||
followed = (follow_up_end - members["index_date"]).dt.days
|
||||
members["known"] = (members["y"] == 1) | (followed >= window)
|
||||
return members[["person_id", "y", "known"]]
|
||||
@@ -0,0 +1,8 @@
|
||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
||||
|
||||
from models.cacu import reports
|
||||
from models.cacu.specs import MODELS
|
||||
from models.jobs import Jobs
|
||||
|
||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
||||
train, score = JOBS.train, JOBS.score
|
||||
@@ -1,158 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "# CaCu · CIN2+ · 01 — Exploratory analysis of the cohort\n\nFirst notebook of the `cin2_logistic` scenario: **exploratory only**. It describes the surveillance cohort\n(`cacu/cohorte_vigilancia`) from its build's Parquet file: who is in, what was measured at the index sample, and\nwhat happened afterwards. No outcome is computed and no model is fitted here.\n\n**How it gets its data, as in the deployment**\n\n- The domain's database is `CACU_DATABASE_URL`; the cohort files live next to it, in `<data>/cohorts/`,\n or in `COHORTS_DIR` when the data folder is read-only (as in the deployments).\n- A build's file is written **once**: if it already exists for that build, it's read; if not, it's exported\n from the build's members and dbt's timeline view, then read. Running the notebook again rebuilds nothing.\n- Every read goes through the domain's repositories; the notebook never opens a session.\n- **Locally**, with no `CACU_DATABASE_URL`, it works on a copy of the DEV deployment's simulated data in\n `~/.cache/isssteleon-notebooks/`, outside the repository, kept between runs.\n\n**With real data:** commit this notebook without outputs, and don't share counts below the suppression threshold.\n\nKernel: *ISSSTELEON WebApi env: kit + Persistance + models*.",
|
||||
"id": "cacu-cin2-01-00"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 1. Configuration",
|
||||
"id": "cacu-cin2-01-01"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/notebooks/cin2_logistic → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
|
||||
"id": "cacu-cin2-01-02"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 2. dbt's timeline view\n\nThe export reads each member's history from `cacu_linea_de_tiempo`, the view dbt creates at deployment. If the\ndatabase doesn't have it and it's a local copy, it's created here; in a deployment, it has to be deployed first.",
|
||||
"id": "cacu-cin2-01-03"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "from persistance.edges.silver import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohort_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)",
|
||||
"id": "cacu-cin2-01-04"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 3. The build's file: read it if it exists, export it once if not\n\nProvisional helpers: they will move into the code (a cycle step that exports each build, and the timeline\nquery over dbt's view in Persistance).",
|
||||
"id": "cacu-cin2-01-05"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohort_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"",
|
||||
"id": "cacu-cin2-01-06"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "builds = pd.DataFrame([vars(b) for b in cohort_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]",
|
||||
"id": "cacu-cin2-01-07"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "build = cohort_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)",
|
||||
"id": "cacu-cin2-01-08"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "Running it again reuses the file: nothing is rebuilt and the file, and so its hash, stays the same.",
|
||||
"id": "cacu-cin2-01-09"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "again, what = ensure(build)\nprint(what, \"| same file:\", again == path, \"| same sha256:\",\n hashlib.sha256(again.read_bytes()).hexdigest() == hashlib.sha256(path.read_bytes()).hexdigest())",
|
||||
"id": "cacu-cin2-01-10"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 4. The cohort\n\nOne row per member, variable and date. `fecha_indice` is on every row; the index sample is the member's index\nevent (`fuente_tabla`, `fuente_id`), and its results are dated when they were **reported**, usually after the\nindex date.",
|
||||
"id": "cacu-cin2-01-11"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "cohort = pd.read_parquet(path)\ncohort[\"dias\"] = (pd.to_datetime(cohort.fecha) - pd.to_datetime(cohort.fecha_indice)).dt.days\nmembers = cohort.groupby(\"pac_id\").fecha_indice.first()\nprint(f\"{len(cohort):,} rows · {members.size:,} members · index dates {members.min()} to {members.max()}\")\nmembers.pipe(pd.to_datetime).dt.to_period(\"Q\").value_counts().sort_index().rename(\"members by quarter of the index date\").to_frame().T",
|
||||
"id": "cacu-cin2-01-12"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "cohort[\"momento\"] = pd.cut(cohort.dias, [-10**6, -1, 0, 10**6], labels=[\"before\", \"on the index date\", \"after\"])\ncohort.pivot_table(index=[\"clase\", \"tipo\"], columns=\"momento\", values=\"pac_id\", aggfunc=\"count\", observed=False, fill_value=0)",
|
||||
"id": "cacu-cin2-01-13"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 5. At the index sample\n\nThe results of the member's own index cytology: its Bethesda category and its HPV result, matched by the source\nrow of the index event, not by date.",
|
||||
"id": "cacu-cin2-01-14"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "sample = cohort[cohort.tipo == \"citologia\"].merge(members.rename(\"fi\"), left_on=\"pac_id\", right_index=True)\nsample = sample[sample.fecha == sample.fi].groupby(\"pac_id\").fuente_id.first().rename(\"muestra\")\nat_index = cohort.merge(sample, left_on=\"pac_id\", right_index=True)\nat_index = at_index[at_index.fuente_id == at_index.muestra]\nbaseline = at_index.pivot_table(index=\"pac_id\", columns=\"tipo\", values=\"valor_codigo\", aggfunc=\"first\")\nbaseline = baseline.reindex(members.index)\nprint(\"members without an HPV result at the index sample:\", f\"{baseline.vph.isna().mean():.1%}\")\npd.crosstab(baseline.bethesda.fillna(\"(none)\"), baseline.vph.fillna(\"(none)\"), margins=True)",
|
||||
"id": "cacu-cin2-01-15"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 6. After the index\n\nFollow-up: how long it lasts, how many members had a biopsy and when, and the grades reported.",
|
||||
"id": "cacu-cin2-01-16"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "after = cohort[cohort.dias > 0]\nfollow_up = after.groupby(\"pac_id\").dias.max().reindex(members.index).fillna(0)\nfirst_biopsy = after[after.tipo == \"biopsia\"].groupby(\"pac_id\").dias.min()\nprint(f\"follow-up (days to the last event): median {follow_up.median():.0f}, quartiles {follow_up.quantile(.25):.0f}–{follow_up.quantile(.75):.0f}\")\nprint(f\"members with a biopsy after the index: {first_biopsy.size:,} ({first_biopsy.size / members.size:.1%}); \"\n f\"days to the first one: median {first_biopsy.median():.0f}\")\nafter[after.tipo == \"biopsia\"].valor_codigo.fillna(\"(no grade)\").value_counts().rename(\"biopsy results after the index\").to_frame()",
|
||||
"id": "cacu-cin2-01-17"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 2, figsize=(11, 3.5))\nfollow_up.div(30.44).plot.hist(bins=30, ax=axes[0], title=\"Follow-up per member (months)\")\nfirst_biopsy.div(30.44).plot.hist(bins=30, ax=axes[1], title=\"Index to first biopsy (months)\")\nfor ax in axes:\n ax.set_ylabel(\"members\")\nplt.tight_layout()",
|
||||
"id": "cacu-cin2-01-18"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## Next\n\n- **02 — profiling and hypothesis tests**, and the outcome itself (prevalent CIN2+ and time to it), computed by\n the model from these rows, not by the cohort.\n- The helpers of sections 2 and 3 move into the code: the export into the cycle, and the timeline query over\n dbt's view into Persistance.",
|
||||
"id": "cacu-cin2-01-19"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "ISSSTELEON WebApi env: kit + Persistance + models (feature/model-proto)",
|
||||
"language": "python",
|
||||
"name": "isssteleon-webapi"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
|
||||
|
||||
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
|
||||
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
|
||||
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
|
||||
interval (l, r] in years where an incident outcome happened. No library fits this model, so
|
||||
the likelihood is written here; everything else is scipy.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.interpolate import BSpline
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import expit
|
||||
from scipy.stats import norm
|
||||
from sklearn.base import BaseEstimator
|
||||
|
||||
UNKNOWN = -999
|
||||
TINY = 1e-12 # floor inside every log
|
||||
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
|
||||
HESSIAN_STEP = 1e-4
|
||||
|
||||
|
||||
def ispline_basis(t, degree: int, knots) -> np.ndarray:
|
||||
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
|
||||
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
|
||||
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
|
||||
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
|
||||
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
|
||||
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
|
||||
basis[t >= knots[-1]] = 1.0
|
||||
basis[t <= knots[0]] = 0.0
|
||||
return basis
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ISpline:
|
||||
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
|
||||
|
||||
knots: tuple[float, ...]
|
||||
degree: int
|
||||
|
||||
@classmethod
|
||||
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
|
||||
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
||||
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
|
||||
|
||||
@property
|
||||
def n_params(self) -> int:
|
||||
return len(self.knots) + self.degree - 2
|
||||
|
||||
def cumulative_hazard(self, t, params) -> np.ndarray:
|
||||
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
|
||||
|
||||
def start(self, c, l, r) -> np.ndarray:
|
||||
"""Every coefficient equal, so the hazard is the crude event rate."""
|
||||
at_risk, finite = c != 1, np.isfinite(r)
|
||||
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
|
||||
events = (at_risk & finite & (r > 0)).sum()
|
||||
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
|
||||
# last bit, and this is the start the current models were fitted from.
|
||||
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
|
||||
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
|
||||
|
||||
|
||||
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
||||
t = np.asarray(t, dtype=float)
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
|
||||
found = np.where(t <= 0, 1.0, found)
|
||||
return np.where(np.isinf(t), 0.0, found)
|
||||
|
||||
|
||||
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
|
||||
pi = expit(X @ theta)
|
||||
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
|
||||
interval = np.maximum(interval, TINY)
|
||||
row = np.zeros(len(c))
|
||||
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
|
||||
row[prevalent] = np.log(pi[prevalent] + TINY)
|
||||
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
|
||||
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
||||
return -np.sum(w * row)
|
||||
|
||||
|
||||
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
|
||||
"""Central-difference Hessian of f at x."""
|
||||
p = len(x)
|
||||
out = np.zeros((p, p))
|
||||
for i in range(p):
|
||||
for j in range(i, p):
|
||||
ei, ej = np.zeros(p), np.zeros(p)
|
||||
ei[i], ej[j] = step, step
|
||||
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
|
||||
4 * step * step
|
||||
)
|
||||
out[i, j] = out[j, i] = value
|
||||
return out
|
||||
|
||||
|
||||
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
|
||||
"""Prevalence coefficients from the patients whose index status is known."""
|
||||
known = c != UNKNOWN
|
||||
if not known.any():
|
||||
return np.zeros(X.shape[1])
|
||||
y, Xk = (c[known] == 1).astype(float), X[known]
|
||||
|
||||
def loss(theta):
|
||||
eta = Xk @ theta
|
||||
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
|
||||
|
||||
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fit:
|
||||
n_x: int
|
||||
n_z: int
|
||||
baseline: ISpline
|
||||
params: np.ndarray
|
||||
covariance: np.ndarray # NaN where a parameter is frozen
|
||||
neg_loglik: float
|
||||
converged: bool
|
||||
|
||||
def risk(self, X, Z, years, params=None) -> np.ndarray:
|
||||
"""Cumulative risk at each horizon: prevalent, or incident by then."""
|
||||
p = self.params if params is None else params
|
||||
theta, beta, rest = (
|
||||
p[: self.n_x],
|
||||
p[self.n_x : self.n_x + self.n_z],
|
||||
p[self.n_x + self.n_z :],
|
||||
)
|
||||
pi = expit(X @ theta)
|
||||
return np.column_stack([
|
||||
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
|
||||
for t in years
|
||||
]) # fmt: skip
|
||||
|
||||
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Risk and its delta-method variance (central-difference gradient)."""
|
||||
gradient = np.empty((len(self.params), len(X), len(years)))
|
||||
for k, value in enumerate(self.params):
|
||||
step = 1e-5 * max(1.0, abs(value))
|
||||
up, down = self.params.copy(), self.params.copy()
|
||||
up[k] += step
|
||||
down[k] -= step
|
||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
||||
|
||||
|
||||
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
||||
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
start = baseline.start(c, l, r)
|
||||
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
|
||||
args = (c, l, r, X, Z, baseline, w)
|
||||
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
|
||||
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
|
||||
free = np.abs(best.x) < FROZEN
|
||||
covariance = np.full((len(best.x), len(best.x)), np.nan)
|
||||
h = hessian(lambda p: neg_loglik(p, *args), best.x)
|
||||
try:
|
||||
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
|
||||
except np.linalg.LinAlgError:
|
||||
pass
|
||||
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
|
||||
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
|
||||
|
||||
|
||||
class Mixture(BaseEstimator):
|
||||
"""One mixture per stratum. Categorical features get one dummy per level after the first
|
||||
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
|
||||
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
|
||||
|
||||
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
|
||||
interval_level=0.95): # fmt: skip
|
||||
self.horizons_years = horizons_years
|
||||
self.incidence_features = incidence_features
|
||||
self.strata = strata
|
||||
self.levels = levels
|
||||
self.knots = knots
|
||||
self.degree = degree
|
||||
self.interval_level = interval_level
|
||||
|
||||
def _seen(self, X: pd.DataFrame) -> dict:
|
||||
return {
|
||||
f: [v for v in values if (X[f] == v).any()]
|
||||
for f, values in self.levels.items()
|
||||
if f in X.columns and f not in self.strata
|
||||
}
|
||||
|
||||
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
|
||||
if not seen:
|
||||
return np.ones(len(X), dtype=bool)
|
||||
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
|
||||
|
||||
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
|
||||
columns = []
|
||||
for f in features:
|
||||
if f in self.strata:
|
||||
continue
|
||||
if f in seen:
|
||||
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
|
||||
else:
|
||||
columns.append(X[f].to_numpy(dtype=float))
|
||||
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
|
||||
|
||||
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
||||
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
||||
return prevalence, self._columns(X, self.incidence_features, seen)
|
||||
|
||||
def _groups(self, X: pd.DataFrame):
|
||||
if not self.strata:
|
||||
return [((), np.arange(len(X)))]
|
||||
groups = X.groupby(list(self.strata), sort=True).indices.items()
|
||||
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
|
||||
|
||||
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
|
||||
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
|
||||
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
|
||||
axis=1).assign(w=1.0) # fmt: skip
|
||||
self.fits_, self.seen_ = {}, {}
|
||||
for key, index in self._groups(X):
|
||||
group = rows.iloc[index]
|
||||
seen = self._seen(group)
|
||||
group = group[self._placed(group, seen)]
|
||||
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
|
||||
prevalence, incidence = self._design(group[X.columns], seen)
|
||||
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
|
||||
self.seen_[key] = seen
|
||||
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
|
||||
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
|
||||
self.converged_ = all(f.converged for f in self.fits_.values())
|
||||
return self
|
||||
|
||||
def predict(self, X: pd.DataFrame) -> np.ndarray:
|
||||
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
|
||||
row's stratum or level was never seen."""
|
||||
h = len(self.horizons_years)
|
||||
out = np.full((len(X), 3 * h), np.nan)
|
||||
z = norm.ppf(0.5 + self.interval_level / 2)
|
||||
for key, index in self._groups(X):
|
||||
if key not in self.fits_:
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||
design = np.column_stack([prevalence, incidence])
|
||||
unique, inverse = np.unique(design, axis=0, return_inverse=True)
|
||||
n_x = prevalence.shape[1]
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||
)
|
||||
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
||||
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
||||
out[index[placed]] = band[inverse.ravel()]
|
||||
return out
|
||||
@@ -0,0 +1,172 @@
|
||||
"""The two reports training writes for each model version (the third, the clinical
|
||||
validation, is a document the clinical team adds). Both are data the governance page draws.
|
||||
|
||||
- technical validation: how the version was trained and tested, and its held-out metrics;
|
||||
- interpretability: what drives its predictions. For the mixture, observed against
|
||||
predicted risk per combination of its features: the Turnbull estimate (the
|
||||
nonparametric cumulative risk under interval censoring) with a bootstrap band, the
|
||||
model's curve with its delta-method band, and expected over observed at each horizon.
|
||||
For the logistic regression, its coefficients and calibration by risk decile.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import norm
|
||||
from sklearn.metrics import brier_score_loss
|
||||
|
||||
from models import survival
|
||||
from models.cacu.pim import Mixture
|
||||
from models.cacu.specs import Logistic, Pim
|
||||
|
||||
GRID_STEP = 0.1 # years between points of a curve
|
||||
BOOTSTRAP = 200
|
||||
SEED = 20261122
|
||||
Z = norm.ppf(0.975)
|
||||
|
||||
|
||||
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
|
||||
if isinstance(spec, survival.Spec):
|
||||
return survival.technical_validation(spec, metrics, data)
|
||||
members = data.get("coded", data.get("labelled"))
|
||||
return {
|
||||
"model": spec.name,
|
||||
"method": spec.method,
|
||||
"cohort": spec.cohort,
|
||||
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
|
||||
"members": len(members),
|
||||
"index_dates": [str(members["index_date"].min()), str(members["index_date"].max())],
|
||||
"metrics": metrics,
|
||||
}
|
||||
|
||||
|
||||
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
|
||||
"""Turnbull's EM: support points and cumulative risk at each. A prevalent case's event
|
||||
is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r]."""
|
||||
finite = r[np.isfinite(r)]
|
||||
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
|
||||
low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
|
||||
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
|
||||
patterns, counts = np.unique(inside, axis=0, return_counts=True)
|
||||
p = np.full(len(support), 1 / len(support))
|
||||
for _ in range(iters):
|
||||
weighted = patterns * p
|
||||
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
|
||||
done = np.max(np.abs(new - p)) < tol
|
||||
p = new
|
||||
if done:
|
||||
break
|
||||
return support, np.cumsum(p)
|
||||
|
||||
|
||||
def _at(support, cumulative, t) -> np.ndarray:
|
||||
i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
|
||||
return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)])
|
||||
|
||||
|
||||
def _label(feature: str, value) -> str:
|
||||
if value is None or (isinstance(value, float) and np.isnan(value)):
|
||||
return "NA"
|
||||
if feature == "hpv_positive":
|
||||
return "positive" if float(value) == 1.0 else "negative"
|
||||
return str(value)
|
||||
|
||||
|
||||
def _band(curve, variance) -> tuple[list, list]:
|
||||
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
||||
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||
|
||||
|
||||
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
|
||||
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
|
||||
if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all():
|
||||
return None
|
||||
prevalence, incidence = mixture._design(row, mixture.seen_[key])
|
||||
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
|
||||
return point[0], variance[0]
|
||||
|
||||
|
||||
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
|
||||
if isinstance(spec, survival.Spec):
|
||||
return survival.interpretability(spec, model, data)
|
||||
if isinstance(spec, Logistic):
|
||||
return _logistic(model, data["test"])
|
||||
coded = data["coded"]
|
||||
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
|
||||
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
|
||||
members = coded.reset_index(drop=True)
|
||||
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
|
||||
horizons = np.asarray(spec.horizons, dtype=float)
|
||||
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
|
||||
rng = np.random.default_rng(SEED)
|
||||
groups = []
|
||||
for _, combination in labels.drop_duplicates().iterrows():
|
||||
mask = (labels == combination).all(axis=1).to_numpy()
|
||||
group = members[mask]
|
||||
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||
support, cumulative = turnbull(c, l, r)
|
||||
boot_grid, boot_h = [], []
|
||||
for _ in range(BOOTSTRAP):
|
||||
pick = rng.integers(0, len(group), len(group))
|
||||
s, cum = turnbull(c[pick], l[pick], r[pick])
|
||||
boot_grid.append(_at(s, cum, grid))
|
||||
boot_h.append(_at(s, cum, horizons))
|
||||
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
|
||||
entry = {
|
||||
"combination": combination.to_dict(),
|
||||
"n": int(mask.sum()),
|
||||
"prevalent": int((c == 1).sum()),
|
||||
"incident": int(((c != 1) & np.isfinite(r)).sum()),
|
||||
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
|
||||
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
|
||||
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
|
||||
"predicted": None,
|
||||
"expected_over_observed": [],
|
||||
} # fmt: skip
|
||||
probe = group.iloc[[0]][spec.features]
|
||||
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
|
||||
if at_grid is not None:
|
||||
low, high = _band(*at_grid)
|
||||
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
|
||||
"low": low, "high": high} # fmt: skip
|
||||
for k, h in enumerate(horizons):
|
||||
e = None if at_h is None else float(at_h[0][k])
|
||||
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
|
||||
"ratio": None, "low": None, "high": None} # fmt: skip
|
||||
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
|
||||
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
|
||||
value = e / observed[k]
|
||||
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
|
||||
"high": value * np.exp(Z * se)} # fmt: skip
|
||||
entry["expected_over_observed"].append(ratio)
|
||||
groups.append(entry)
|
||||
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
|
||||
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
|
||||
"groups": groups} # fmt: skip
|
||||
|
||||
|
||||
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
||||
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
|
||||
names = encoder.get_feature_names_out()
|
||||
p = test["p"]
|
||||
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
|
||||
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
|
||||
observed=("y", "mean")) # fmt: skip
|
||||
return {
|
||||
"model": "logistic regression",
|
||||
"kind": "coefficients",
|
||||
"intercept": float(classifier.intercept_[0]),
|
||||
"coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)),
|
||||
"calibration": {
|
||||
"brier": float(brier_score_loss(test["y"], p)),
|
||||
"bins": [
|
||||
{
|
||||
"range": str(k),
|
||||
"n": int(v.n),
|
||||
"predicted": float(v.predicted),
|
||||
"observed": float(v.observed),
|
||||
}
|
||||
for k, v in table.iterrows()
|
||||
],
|
||||
}, # fmt: skip
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
|
||||
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
|
||||
patient timelines of the spec's cohort (see features)."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import features as f
|
||||
from models.cacu.pim import Mixture
|
||||
from models.survival import Spec, age_group
|
||||
|
||||
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
||||
TRAIN_FRACTION = 0.7
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||
|
||||
|
||||
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
||||
"""One row per patient and horizon; patients the model can't score are left out."""
|
||||
h = len(horizons)
|
||||
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
||||
members, risks = members[scored], risks[scored]
|
||||
n = len(members)
|
||||
frame = pd.DataFrame({
|
||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
||||
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
||||
"probability": risks[:, :h].ravel(),
|
||||
}) # fmt: skip
|
||||
if risks.shape[1] == 3 * h:
|
||||
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
||||
else:
|
||||
frame["ci_low"] = frame["ci_high"] = np.nan
|
||||
return frame[OUTPUT]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pim:
|
||||
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
|
||||
|
||||
name: str
|
||||
cohort: str
|
||||
grades: list[str]
|
||||
cytology: dict[str, list[str]]
|
||||
strata: tuple[str, ...]
|
||||
incidence_features: tuple[str, ...]
|
||||
history: dict | None = None # a feature from before the index (the referral grade)
|
||||
predict_at: Literal["index", "last_screening_cytology"] = "index"
|
||||
horizons: tuple[float, ...] = HORIZONS
|
||||
method: str = field(default="prevalence-incidence mixture", init=False)
|
||||
|
||||
@property
|
||||
def features(self) -> list[str]:
|
||||
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
|
||||
|
||||
def _history(self) -> dict | None:
|
||||
return self.history and {**self.history, "cytology": self.cytology}
|
||||
|
||||
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
|
||||
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
|
||||
members it learned from (for the reports)."""
|
||||
events = f.prepared(events)
|
||||
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
|
||||
train, test = f.split(coded, TRAIN_FRACTION)
|
||||
levels = {"cytology": list(self.cytology)}
|
||||
if self.history:
|
||||
levels[self.history["feature"]] = list(self.history["levels"])
|
||||
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
|
||||
mixture.fit(train[self.features], train[["c", "l", "r"]])
|
||||
return mixture, self.metrics(mixture, train, test), {"coded": coded}
|
||||
|
||||
def metrics(self, mixture: Mixture, train, test) -> dict:
|
||||
found = {
|
||||
"n_train": len(train),
|
||||
"n_test": len(test),
|
||||
# outcomes, prevalent or incident, each split learned from or was judged on
|
||||
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
|
||||
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
|
||||
"neg_loglik": mixture.neg_loglik_,
|
||||
"converged": float(mixture.converged_),
|
||||
}
|
||||
risks = mixture.predict(test[self.features])
|
||||
for column, horizon in enumerate(self.horizons):
|
||||
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
|
||||
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
|
||||
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
||||
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
|
||||
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
|
||||
found[f"n_known_{tag}"] = int(known.sum())
|
||||
if known.any():
|
||||
found[f"observed_{tag}"] = float(y.mean())
|
||||
found[f"expected_{tag}"] = float(p.mean())
|
||||
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
|
||||
if len(np.unique(y)) == 2:
|
||||
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
|
||||
return found
|
||||
|
||||
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
|
||||
events = f.prepared(events)
|
||||
if self.predict_at == "last_screening_cytology":
|
||||
chosen = f.last_screening_cytology(events)
|
||||
events = events[events["person_id"].isin(chosen.index)]
|
||||
events = events.assign(index_date=events["person_id"].map(chosen))
|
||||
members = f.index_results(events, self.cytology, self._history())
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Logistic:
|
||||
"""Probability of the outcome within one year of the index sample."""
|
||||
|
||||
name: str
|
||||
cohort: str
|
||||
grades: list[str]
|
||||
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
|
||||
years: float = 1.0
|
||||
method: str = field(default="logistic regression", init=False)
|
||||
|
||||
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
|
||||
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
|
||||
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
|
||||
events = f.prepared(events)
|
||||
found = f.index_sample(events, list(self.predictors))
|
||||
outcome = f.windowed_outcome(events, self.grades, self.years,
|
||||
pd.Timestamp(follow_up_end)) # fmt: skip
|
||||
labelled = found.merge(outcome, on="person_id")
|
||||
labelled = labelled[labelled["known"]].reset_index(drop=True)
|
||||
train, test = f.split(labelled, TRAIN_FRACTION)
|
||||
X = list(self.predictors)
|
||||
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
|
||||
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
|
||||
model.fit(train[X], train["y"])
|
||||
p = model.predict_proba(test[X])[:, 1]
|
||||
metrics = {
|
||||
"n_train": len(train),
|
||||
"n_test": len(test),
|
||||
"events_train": float(train["y"].sum()),
|
||||
"events_test": float(test["y"].sum()),
|
||||
"auc": float(roc_auc_score(test["y"], p)),
|
||||
"brier": float(brier_score_loss(test["y"], p)),
|
||||
"positive_rate_train": float(train["y"].mean()),
|
||||
"positive_rate_test": float(test["y"].mean()),
|
||||
"mean_probability_test": float(p.mean()),
|
||||
}
|
||||
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
|
||||
|
||||
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
|
||||
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
p = model.predict_proba(members[list(self.predictors)])[:, 1]
|
||||
return _rows(members, p[:, None], (self.years,))
|
||||
|
||||
|
||||
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's most recent observations up to her index (that day included): her age
|
||||
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
||||
found = pd.DataFrame(index=members.index)
|
||||
found["age_group"] = age_group(events, members, (35, 45, 55))
|
||||
prior = events[events["date"] <= events["index_date"]]
|
||||
names = list(cacu.KPNC)
|
||||
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
||||
results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()]
|
||||
latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")]
|
||||
ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max()
|
||||
found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)])
|
||||
hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()]
|
||||
hpv = hpv.sort_values(["date", "source_id"])
|
||||
found["hpv"] = hpv.groupby("person_id")["value_code"].last()
|
||||
return found.astype(object)
|
||||
|
||||
|
||||
_REFERRAL = {
|
||||
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
||||
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
||||
"high": ["High Grade"],
|
||||
} # fmt: skip
|
||||
|
||||
MODELS = {
|
||||
m.name: m
|
||||
for m in [
|
||||
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
|
||||
strata=("hpv_positive",), incidence_features=("cytology",),
|
||||
predict_at="last_screening_cytology"),
|
||||
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
|
||||
strata=("hpv_positive",), incidence_features=("cytology",),
|
||||
predict_at="last_screening_cytology"),
|
||||
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
|
||||
cacu.KPNC_3, strata=("referral_grade",),
|
||||
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
||||
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
||||
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
||||
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
||||
interval_level=0.95),
|
||||
]
|
||||
} # fmt: skip
|
||||
@@ -1 +0,0 @@
|
||||
"""CaMa's scenarios and notebooks."""
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""CaMa's training and scoring jobs (models.jobs) over its models and their reports."""
|
||||
|
||||
from models import survival
|
||||
from models.cama.specs import MODELS
|
||||
from models.jobs import Jobs
|
||||
|
||||
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
|
||||
train, score = JOBS.train, JOBS.score
|
||||
@@ -0,0 +1,91 @@
|
||||
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
|
||||
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
|
||||
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
|
||||
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
|
||||
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
|
||||
gives the tables and figures."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||
|
||||
HORIZONS = modeling.HORIZONS # months
|
||||
|
||||
|
||||
@dataclass
|
||||
class Recurrence:
|
||||
"""Per horizon: the LR (intercept and coefficients of its terms) and the HBN (CPT over
|
||||
its parents, keyed by their categories); the recurrence probability is their mean, and an
|
||||
unseen parent configuration takes the horizon's recurrence rate."""
|
||||
|
||||
cohort: str
|
||||
horizons: tuple[int, ...]
|
||||
covariates: list[str]
|
||||
tables: dict[int, dict]
|
||||
|
||||
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The probability of recurrence by each horizon (`recurrence_{H}m`) for each row
|
||||
of `X`, whose covariates are categories as in `cohort()` (missing: UNKNOWN)."""
|
||||
found = X[self.covariates].astype(object)
|
||||
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
|
||||
dummies = pd.get_dummies(found).astype(float)
|
||||
out = {}
|
||||
for h in self.horizons:
|
||||
t = self.tables[h]
|
||||
p_lr = np.full(len(found), t["lr_prior"])
|
||||
if t["lr_terms"]:
|
||||
x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy()
|
||||
logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"])
|
||||
p_lr = 1 / (1 + np.exp(-logit))
|
||||
p_hbn = np.full(len(found), t["hbn_prior"])
|
||||
if t["hbn_parents"]:
|
||||
keys = map(tuple, found[t["hbn_parents"]].to_numpy())
|
||||
p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys])
|
||||
out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2
|
||||
return pd.DataFrame(out, index=X.index)
|
||||
|
||||
|
||||
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
||||
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
|
||||
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
|
||||
factors' stability criterion, are then missing)."""
|
||||
from models.cama.recurrence import site
|
||||
|
||||
return fit({"site": site.prepare(rows)}, "site", "site",
|
||||
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
|
||||
|
||||
|
||||
def fit(found: dict, saved: str, label: str,
|
||||
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
||||
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
||||
the `saved` cohort's is the model kept."""
|
||||
sources = list(found)
|
||||
try:
|
||||
fits = modeling.fit(found, n_bootstrap)
|
||||
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
||||
finally:
|
||||
joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
|
||||
table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True)
|
||||
summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)]
|
||||
auc = [row for s in sources for row in reports.auc_rows(fits[s])]
|
||||
points = [row for s in sources for row in drawn[s][1]]
|
||||
kept = fits[saved]
|
||||
model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept))
|
||||
technical = {
|
||||
"model": "recurrence",
|
||||
"cohort": label,
|
||||
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
|
||||
"rutinas": reports.routines(found, n_bootstrap),
|
||||
"recurrencia_desarrollo": reports.development(auc, table, points, summary),
|
||||
}
|
||||
interpretability = {
|
||||
"model": "recurrence",
|
||||
"kind": "scenarios",
|
||||
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
|
||||
}
|
||||
reports_ = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return model, reports.metrics(auc), reports_
|
||||
@@ -0,0 +1,173 @@
|
||||
"""The recurrence calculator: for clinical scenarios of each cohort, the mean recurrence-free
|
||||
probability the LR + HBN average gives its patients at each horizon, with a 95 % interval from
|
||||
refits on resamples of the whole cohort, next to the scenario's observed survival (Kaplan-Meier)
|
||||
and its classic and fractional Weibull curves.
|
||||
|
||||
The models are refitted on the whole cohort (and on each resample) with the terms and parents
|
||||
the split chose; the HBN's pseudo-count counts every level of the cohort, seen in the
|
||||
(re)sample or not."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
from models import curves
|
||||
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
|
||||
|
||||
RESAMPLES = 200
|
||||
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
||||
CAP_MONTHS = 72 # the Weibull curves' extent
|
||||
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
||||
|
||||
|
||||
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||
return {
|
||||
name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()])
|
||||
for name, cond in scenarios.items()
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Risk:
|
||||
"""The cohort coded once: dummies for the LR, integer codes for the HBN."""
|
||||
|
||||
fitted: CohortFit
|
||||
|
||||
def __post_init__(self):
|
||||
frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
|
||||
self.n = len(frame)
|
||||
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
||||
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
|
||||
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
|
||||
self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
|
||||
|
||||
def _key(self, chosen, rows) -> np.ndarray:
|
||||
key = np.zeros(len(rows), dtype=np.int64)
|
||||
for p in chosen:
|
||||
key = key * self.levels[p] + self.codes[p][rows]
|
||||
return key
|
||||
|
||||
def _combined(self, rows, horizon) -> np.ndarray | None:
|
||||
"""Every patient's (LR + HBN) / 2, fitted on `rows`; None when the LR fails."""
|
||||
t, e = self.time[rows], self.event[rows]
|
||||
recurred = (e == 1) & (t <= horizon)
|
||||
known = recurred | (t > horizon)
|
||||
train, y = rows[known], recurred[known].astype(int)
|
||||
split = self.fitted.horizons[horizon].split
|
||||
p_lr = p_hbn = np.full(self.n, y.mean())
|
||||
if split.terms:
|
||||
m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add")
|
||||
if m is None:
|
||||
return None
|
||||
p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy()
|
||||
if split.parents:
|
||||
q = int(np.prod([self.levels[p] for p in split.parents]))
|
||||
a = ESS / (2 * q)
|
||||
key = self._key(split.parents, train)
|
||||
table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / (
|
||||
pd.Series(1, index=key).groupby(level=0).sum() + 2 * a
|
||||
)
|
||||
everyone = self._key(split.parents, np.arange(self.n))
|
||||
p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy()
|
||||
return (p_lr + p_hbn) / 2
|
||||
|
||||
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None:
|
||||
"""Per scenario, the mean risk at each horizon over its patients in `rows` (repeats
|
||||
counted); None when a refit fails."""
|
||||
out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
|
||||
for j, h in enumerate(HORIZONS):
|
||||
combined = self._combined(rows, h)
|
||||
if combined is None:
|
||||
return None
|
||||
for name, mask in scenario_masks.items():
|
||||
inside = mask[rows]
|
||||
if inside.any():
|
||||
out[name][j] = combined[rows][inside].mean()
|
||||
return out
|
||||
|
||||
|
||||
def _curves(months, event, observed):
|
||||
d, c, _ = curves.life_table(months, event)
|
||||
k, lam = curves.fit_weibull(d, c)
|
||||
fractional = curves.fit_fractional(d, c, k, lam)
|
||||
grid = np.linspace(0, CAP_MONTHS, GRID_POINTS)
|
||||
return {
|
||||
"km": dict(
|
||||
zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True)
|
||||
),
|
||||
"weibull": curves.weibull(grid, k, lam),
|
||||
"weibull_fractional": curves.fractional(grid, k, *fractional),
|
||||
"grid": grid,
|
||||
}
|
||||
|
||||
|
||||
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
|
||||
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
||||
source = fitted.cohort.source
|
||||
scenarios = fitted.cohort.scenarios
|
||||
risk = Risk(fitted)
|
||||
found = masks(fitted.cohort.frame, scenarios)
|
||||
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
||||
samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)]
|
||||
months = np.floor(risk.time).astype(int)
|
||||
event = risk.event == 1
|
||||
drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS}
|
||||
jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()]
|
||||
jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] # the long ones first
|
||||
done = Parallel(n_jobs=-1)(jobs)
|
||||
fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
|
||||
replicas = [r for r in resampled if r is not None]
|
||||
records, rows = [], []
|
||||
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
|
||||
free = 1 - point[name]
|
||||
risks = np.array([r[name] for r in replicas])
|
||||
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
|
||||
observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
|
||||
km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
|
||||
records.append(
|
||||
{
|
||||
"cohorte": source,
|
||||
"cohorte_nombre": fitted.cohort.label,
|
||||
"escenario": name,
|
||||
"condiciones": scenarios[name],
|
||||
"n": n,
|
||||
"recaidas": events,
|
||||
"horizons_months": list(HORIZONS),
|
||||
"observado_hasta": observed,
|
||||
"months_max": CAP_MONTHS,
|
||||
"km": {
|
||||
"months": list(range(observed + 1)),
|
||||
**{k: v.tolist() for k, v in km.items()},
|
||||
},
|
||||
"weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()},
|
||||
"weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()},
|
||||
"points": {
|
||||
"COMB": {
|
||||
"S": free.tolist(),
|
||||
"low": np.clip(low, 0, 1).tolist(),
|
||||
"high": np.clip(high, 0, 1).tolist(),
|
||||
}
|
||||
},
|
||||
"bootstrap_replicas": len(replicas),
|
||||
}
|
||||
)
|
||||
for j, h in enumerate(HORIZONS):
|
||||
rows.append(
|
||||
{
|
||||
"cohorte": source,
|
||||
"subgrupo": name,
|
||||
"n": n,
|
||||
"recaidas": events,
|
||||
"horizonte_meses": h,
|
||||
"S_libre_LR_HBN": free[j],
|
||||
"IC95_inf": low[j],
|
||||
"IC95_sup": high[j],
|
||||
"riesgo_recurrencia": 1 - free[j],
|
||||
"S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan,
|
||||
"replicas_bootstrap": len(replicas),
|
||||
}
|
||||
)
|
||||
return records, rows
|
||||
@@ -0,0 +1,92 @@
|
||||
"""A cohort as one table of categories: the patients with a known recurrence time and status,
|
||||
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates
|
||||
as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed
|
||||
or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one
|
||||
with more unknowns is dropped."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pandas as pd
|
||||
from scipy.stats.contingency import association
|
||||
|
||||
UNKNOWN = "Desconocido"
|
||||
V_MAX = 0.80
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
HORIZONS = (12, 36, 60) # months
|
||||
|
||||
# Bands, closed on the left: [a, b).
|
||||
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||
SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
||||
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
||||
GRADES = {"1": "1", "2": "2", "3": "3"}
|
||||
|
||||
|
||||
def _number(s: pd.Series) -> pd.Series:
|
||||
return pd.to_numeric(s, errors="coerce")
|
||||
|
||||
|
||||
def _text(s: pd.Series) -> pd.Series:
|
||||
"""As text; missing values are UNKNOWN."""
|
||||
return s.astype(object).where(s.notna(), UNKNOWN).astype(str)
|
||||
|
||||
|
||||
def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
|
||||
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
||||
|
||||
|
||||
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
||||
table = pd.crosstab(a, b).to_numpy()
|
||||
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
||||
|
||||
|
||||
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]:
|
||||
"""The covariates to drop: pairs by decreasing V (ties: by decreasing names); of each pair
|
||||
with V >= v_max and neither already dropped, the one with the larger share of unknowns
|
||||
(on a tie, the first of the pair)."""
|
||||
pairs = sorted(
|
||||
(
|
||||
(cramers_v(frame[a], frame[b]), a, b)
|
||||
for i, a in enumerate(candidates)
|
||||
for b in candidates[i + 1 :]
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
unknown = {c: (frame[c] == UNKNOWN).mean() for c in candidates}
|
||||
dropped = []
|
||||
for v, a, b in pairs:
|
||||
if v < v_max:
|
||||
break
|
||||
if a not in dropped and b not in dropped:
|
||||
dropped.append(a if unknown[a] >= unknown[b] else b)
|
||||
return dropped
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Cohort:
|
||||
"""A source's cohort table and what its covariates are."""
|
||||
|
||||
source: str
|
||||
frame: pd.DataFrame # fixed columns, then the kept covariates
|
||||
covariates: list[str]
|
||||
treatment: list[str]
|
||||
eliminated: list[str]
|
||||
label: str # as the reports name it
|
||||
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories
|
||||
sampling: dict # how its patients were chosen (the MUESTREO record)
|
||||
|
||||
@property
|
||||
def intrinsic(self) -> list[str]:
|
||||
return [c for c in self.covariates if c not in self.treatment]
|
||||
|
||||
|
||||
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
||||
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
||||
followed past it), with `y` = recurred by then."""
|
||||
t, event = frame["tiempo_meses"], frame["evento"] == 1
|
||||
found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
|
||||
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
|
||||
return found
|
||||
|
||||
|
||||
def unknown_shares(cohort: Cohort) -> dict[str, float]:
|
||||
return {c: float((cohort.frame[c] == UNKNOWN).mean()) for c in cohort.covariates}
|
||||
@@ -0,0 +1,118 @@
|
||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has
|
||||
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
|
||||
the horizon's HBN parents give (3))."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models import factors as rated
|
||||
from models.cama.recurrence.calculator import masks
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||
from models.cama.recurrence.modeling import CohortFit
|
||||
from models.factors import FREQ_MIN, ORDER
|
||||
|
||||
OR = "OR_recurrencia"
|
||||
SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
|
||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
COLUMNS = [
|
||||
"cohorte",
|
||||
"horizonte_meses",
|
||||
"tipo",
|
||||
"variable",
|
||||
"categoria",
|
||||
"referencia",
|
||||
"n_categoria",
|
||||
OR,
|
||||
"IC95_inf",
|
||||
"IC95_sup",
|
||||
"p",
|
||||
"p_ajustado_BH",
|
||||
"freq_seleccion_bootstrap",
|
||||
"en_manta_markov",
|
||||
*SURVIVAL,
|
||||
"delta_IC95_inf",
|
||||
"delta_IC95_sup",
|
||||
"c1_or",
|
||||
"c2_estabilidad",
|
||||
"c3_manta_markov",
|
||||
"c4_supervivencia",
|
||||
"criterios_cumplidos",
|
||||
"clasificacion",
|
||||
]
|
||||
DESCRIBING = rated.DESCRIBING
|
||||
|
||||
|
||||
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
||||
cohort = fitted.cohort
|
||||
frame = at_horizon(cohort.frame, horizon)
|
||||
data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy()
|
||||
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
|
||||
t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]
|
||||
months = np.floor(np.minimum(t, horizon + 1)).astype(int)
|
||||
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
||||
|
||||
def complete(table, variables):
|
||||
return rated.complete(table, variables, reference, everyone, months, event, horizon,
|
||||
SURVIVAL) # fmt: skip
|
||||
|
||||
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
|
||||
hz = fitted.horizons[horizon]
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
||||
lambda v: np.nan if selection is None else selection.get(v, 0.0)
|
||||
)
|
||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
|
||||
tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
both = intrinsic + treatment
|
||||
tr = rated.odds_ratios(data, y, both, reference, OR)
|
||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||
tr = complete(
|
||||
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
||||
)
|
||||
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
|
||||
tab = pd.concat([tab, tr], ignore_index=True)
|
||||
tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon
|
||||
return tab
|
||||
|
||||
|
||||
def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame:
|
||||
"""Every horizon's table: by horizon, factors before treatments, by class, by odds ratio
|
||||
(decreasing); rounded to 4 places. `selection` (per horizon, the share of bootstrap LRs
|
||||
each covariate entered) defaults to the fit's own bootstrap."""
|
||||
if selection is None:
|
||||
covariates = fitted.cohort.covariates
|
||||
selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()}
|
||||
with warnings.catch_warnings(), np.errstate(over="ignore"):
|
||||
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
|
||||
found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons]
|
||||
tab = pd.concat(found, ignore_index=True)
|
||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
|
||||
keys = ["horizonte_meses", "_kind", "_order", OR]
|
||||
tab = tab.sort_values(keys, ascending=[True, True, True, False])
|
||||
return tab[COLUMNS].round(4)
|
||||
|
||||
|
||||
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
|
||||
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
||||
patients have (definitorios) or most have (mayoritarios)."""
|
||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
||||
scenarios = fitted.cohort.scenarios
|
||||
found = rated.classified(factors[factors["cohorte"] == source])
|
||||
rows = []
|
||||
for name, mask in masks(frame, scenarios).items():
|
||||
if not mask.any() or found.empty:
|
||||
continue
|
||||
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
|
||||
for h in fitted.horizons:
|
||||
rows.append({
|
||||
"cohorte": source, "escenario": name, "definicion": definition,
|
||||
"n_escenario": int(mask.sum()), "horizonte_meses": h,
|
||||
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
@@ -0,0 +1,293 @@
|
||||
"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a
|
||||
stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu
|
||||
search picks, predicting by its conditional probability table. Each is validated on a
|
||||
stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each
|
||||
replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up.
|
||||
|
||||
Resamples are drawn in order from one seeded generator and fitted in parallel, so every
|
||||
replicate is the same however many workers run them."""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from joblib import Parallel, delayed
|
||||
from lifelines import CoxPHFitter
|
||||
from lifelines.utils import concordance_index
|
||||
from pgmpy.structure_score import BDeu
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
|
||||
from models.factors import variable_of
|
||||
|
||||
SEED = 42
|
||||
TEST_SIZE = 0.3
|
||||
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
||||
MAX_PARENTS = 6
|
||||
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
|
||||
MAX_STEPS = 200
|
||||
COX_PENALIZER = 0.05
|
||||
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
||||
N_BOOTSTRAP = {"site": 40}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- logistic regression
|
||||
|
||||
|
||||
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
|
||||
"""Dummies (each covariate's alphabetically first level is the reference), the
|
||||
non-constant ones; a term is `{covariate}_{level}`."""
|
||||
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
||||
return X.loc[:, X.nunique() > 1]
|
||||
|
||||
|
||||
def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
|
||||
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
X = sm.add_constant(X, has_constant=has_constant)
|
||||
return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def stepwise(X: pd.DataFrame, y) -> list[str]:
|
||||
"""Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p >
|
||||
ALPHA_OUT leaves) until nothing changes; the terms in the order they entered."""
|
||||
included = []
|
||||
for _ in range(MAX_STEPS):
|
||||
changed, best, best_p = False, None, ALPHA_IN
|
||||
for c in X.columns:
|
||||
if c in included:
|
||||
continue
|
||||
m = logit(y, X[included + [c]])
|
||||
if m is not None and m.pvalues[c] < best_p:
|
||||
best, best_p = c, m.pvalues[c]
|
||||
if best is not None:
|
||||
included.append(best)
|
||||
changed = True
|
||||
if included and (m := logit(y, X[included])) is not None:
|
||||
p = m.pvalues.drop("const")
|
||||
if p.max() > ALPHA_OUT:
|
||||
included.remove(p.idxmax())
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
return included
|
||||
|
||||
|
||||
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
|
||||
"""The terms selected on `train` (univariate prefilter, then stepwise) and the test
|
||||
rows' predicted probabilities (the training rate when no term is selected)."""
|
||||
X = encode(pd.concat([train, test]), covariates)
|
||||
X_train = X.loc[train.index]
|
||||
X_train = X_train.loc[:, X_train.nunique() > 1]
|
||||
y = train["y"]
|
||||
candidates = [
|
||||
c
|
||||
for c in X_train.columns
|
||||
if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER
|
||||
]
|
||||
terms = stepwise(X_train[candidates], y) if candidates else []
|
||||
if not terms:
|
||||
return [], np.full(len(test), y.mean())
|
||||
m = logit(y, X_train[terms])
|
||||
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
|
||||
return terms, m.predict(X_test).to_numpy()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Bayesian network
|
||||
|
||||
|
||||
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
|
||||
table = frame[covariates].astype(str)
|
||||
table["outcome"] = frame["y"].astype(int).astype(str)
|
||||
return table
|
||||
|
||||
|
||||
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
|
||||
"""Greedy: the covariate whose addition most raises the outcome's BDeu score, while
|
||||
any does (up to MAX_PARENTS); the parents in the order chosen."""
|
||||
score = BDeu(table, equivalent_sample_size=ESS)
|
||||
chosen, current = [], score.local_score("outcome", ())
|
||||
while len(chosen) < MAX_PARENTS:
|
||||
best, gain = None, 0.0
|
||||
for c in [c for c in covariates if c not in chosen]:
|
||||
g = score.local_score("outcome", (*chosen, c)) - current
|
||||
if g > gain:
|
||||
best, gain = c, g
|
||||
if best is None:
|
||||
break
|
||||
chosen.append(best)
|
||||
current += gain
|
||||
return chosen
|
||||
|
||||
|
||||
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
|
||||
"""P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell;
|
||||
`q`, the number of configurations, defaults to the levels seen in `table`."""
|
||||
q = q or int(np.prod([table[p].nunique() for p in chosen]))
|
||||
a = ESS / (2 * q)
|
||||
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
||||
return {
|
||||
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
|
||||
for k, r in counts.iterrows()
|
||||
}
|
||||
|
||||
|
||||
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
|
||||
"""The test rows' probabilities by the CPT of `train`; unseen configurations (or no
|
||||
parents) get the training rate."""
|
||||
rate = (train["outcome"] == "1").mean()
|
||||
if not chosen:
|
||||
return np.full(len(test), rate)
|
||||
table = cpt(train, chosen)
|
||||
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- one split, one cohort
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Split:
|
||||
"""The two models' selection and AUC on one 70/30 split."""
|
||||
|
||||
terms: list[str]
|
||||
parents: list[str]
|
||||
auc_lr: float
|
||||
auc_hbn: float
|
||||
|
||||
|
||||
def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split:
|
||||
train, test = train_test_split(
|
||||
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
|
||||
)
|
||||
terms, p_lr = lr(train, test, covariates)
|
||||
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
|
||||
chosen = parents(bn_train, covariates)
|
||||
p_hbn = hbn(bn_train, bn_test, chosen)
|
||||
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
|
||||
|
||||
|
||||
def _replicate(frame, covariates, rows, b) -> Split | None:
|
||||
"""Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when
|
||||
any fit fails (the replicate is then not counted)."""
|
||||
try:
|
||||
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def c_index(cohort: Cohort) -> float:
|
||||
"""Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split
|
||||
stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out."""
|
||||
time_event = ["tiempo_meses", "evento"]
|
||||
X = pd.get_dummies(
|
||||
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
|
||||
).astype(float)
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"])
|
||||
n = len(train)
|
||||
keep = [
|
||||
c
|
||||
for c in X.columns
|
||||
if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT
|
||||
]
|
||||
cox = CoxPHFitter(penalizer=COX_PENALIZER)
|
||||
cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5})
|
||||
risk = cox.predict_partial_hazard(test[keep])
|
||||
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Horizon:
|
||||
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
||||
covariate entered the LR and the HBN)."""
|
||||
|
||||
n: int
|
||||
events: int
|
||||
split: Split
|
||||
replicates: list[Split] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def aucs(self) -> np.ndarray:
|
||||
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2)
|
||||
|
||||
def selection(self, covariates: list[str]) -> dict[str, float] | None:
|
||||
"""Share of the replicates whose final LR has a term of each covariate."""
|
||||
if not self.replicates:
|
||||
return None
|
||||
counts = {}
|
||||
for r in self.replicates:
|
||||
for v in {variable_of(t, covariates) for t in r.terms}:
|
||||
counts[v] = counts.get(v, 0) + 1
|
||||
return {v: k / len(self.replicates) for v, k in counts.items()}
|
||||
|
||||
|
||||
@dataclass
|
||||
class CohortFit:
|
||||
cohort: Cohort
|
||||
c_index: float
|
||||
horizons: dict[int, Horizon]
|
||||
|
||||
|
||||
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
|
||||
"""Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers.
|
||||
Each horizon's resamples come from a fresh generator seeded SEED."""
|
||||
frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
|
||||
tasks = []
|
||||
for (s, h), frame in frames.items():
|
||||
rng = np.random.default_rng(SEED)
|
||||
rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))]
|
||||
tasks += [
|
||||
((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b))
|
||||
for b, r in enumerate(rows)
|
||||
]
|
||||
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
|
||||
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
|
||||
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
|
||||
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
|
||||
out = {}
|
||||
for s, cohort in cohorts.items():
|
||||
horizons = {}
|
||||
for h in HORIZONS:
|
||||
frame = frames[(s, h)]
|
||||
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
|
||||
horizons[h] = Horizon(
|
||||
len(frame),
|
||||
int(frame["y"].sum()),
|
||||
results[(s, h, "split")],
|
||||
[r for r in reps if r is not None],
|
||||
)
|
||||
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
|
||||
return out
|
||||
|
||||
|
||||
def tables(fitted: CohortFit) -> dict[int, dict]:
|
||||
"""What the saved model keeps per horizon: the split's LR terms refitted on the whole
|
||||
horizon cohort, and the split's HBN parents with their CPT on it."""
|
||||
found = {}
|
||||
for h, hz in fitted.horizons.items():
|
||||
frame = at_horizon(fitted.cohort.frame, h)
|
||||
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
|
||||
prior = float(frame["y"].mean())
|
||||
entry = {
|
||||
"lr_prior": prior,
|
||||
"lr_terms": terms,
|
||||
"lr_constant": 0.0,
|
||||
"lr_coefficients": [],
|
||||
"hbn_parents": chosen,
|
||||
"hbn_prior": prior,
|
||||
"hbn_cpt": {},
|
||||
}
|
||||
if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None:
|
||||
entry["lr_constant"] = float(m.params["const"])
|
||||
entry["lr_coefficients"] = [float(m.params[t]) for t in terms]
|
||||
if chosen:
|
||||
entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen)
|
||||
found[h] = entry
|
||||
return found
|
||||
@@ -0,0 +1,161 @@
|
||||
"""What the governance page draws, as JSON: the development tables (AUC, risk factors,
|
||||
calculator points, scenario summaries) and the scenarios' figures, as v1 published them in
|
||||
`analisis/recurrencia_desarrollo.json` and `analisis/recurrencia.json`, and the five routine
|
||||
records (`rutinas/`)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
|
||||
from models.cama.recurrence.modeling import (
|
||||
ALPHA_IN,
|
||||
ALPHA_OUT,
|
||||
COX_PENALIZER,
|
||||
ESS,
|
||||
HORIZONS,
|
||||
MAX_PARENTS,
|
||||
CohortFit,
|
||||
)
|
||||
|
||||
VERSION = 1
|
||||
AUC_COLUMNS = [
|
||||
"cohorte",
|
||||
"horizonte_meses",
|
||||
"modelo",
|
||||
"n_modelo",
|
||||
"recurrencias",
|
||||
"AUC_validacion_interna",
|
||||
"AUC_bootstrap_medio",
|
||||
"AUC_bootstrap_IC95_inf",
|
||||
"AUC_bootstrap_IC95_sup",
|
||||
"replicas_bootstrap",
|
||||
]
|
||||
|
||||
|
||||
def table(rows, columns=None) -> dict:
|
||||
"""Columns and records; NaN and infinities are null."""
|
||||
frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
return {
|
||||
"columnas": [str(c) for c in frame.columns],
|
||||
"filas": frame.where(frame.notna(), None).to_dict("records"),
|
||||
}
|
||||
|
||||
|
||||
def auc_rows(fitted: CohortFit) -> list[dict]:
|
||||
"""Per horizon and model, the AUC on the internal split and over the bootstrap
|
||||
replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index."""
|
||||
source, rows = fitted.cohort.source, []
|
||||
for h, hz in fitted.horizons.items():
|
||||
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
|
||||
aucs = hz.aucs[:, j]
|
||||
boot = (
|
||||
[np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])]
|
||||
if len(aucs)
|
||||
else [None] * 3
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"cohorte": source,
|
||||
"horizonte_meses": h,
|
||||
"modelo": name,
|
||||
"n_modelo": hz.n,
|
||||
"recurrencias": hz.events,
|
||||
"AUC_validacion_interna": internal,
|
||||
**dict(zip(AUC_COLUMNS[6:9], boot, strict=True)),
|
||||
"replicas_bootstrap": len(aucs) if len(aucs) else None,
|
||||
}
|
||||
)
|
||||
frame = fitted.cohort.frame
|
||||
rows.append(
|
||||
{
|
||||
"cohorte": source,
|
||||
"horizonte_meses": "completo",
|
||||
"modelo": "Cox penalizado (C-index)",
|
||||
"n_modelo": len(frame),
|
||||
"recurrencias": int(frame["evento"].sum()),
|
||||
"AUC_validacion_interna": fitted.c_index,
|
||||
}
|
||||
)
|
||||
return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]
|
||||
|
||||
|
||||
def metrics(auc: list[dict]) -> dict[str, float]:
|
||||
"""v1's metric names: `{cohort}.auc_{LR|HBN}_{H}m` (internal split), with `_bootstrap`
|
||||
(the replicates' mean), and `{cohort}.c_index_cox`."""
|
||||
found = {}
|
||||
for r in auc:
|
||||
if r["horizonte_meses"] == "completo":
|
||||
found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"])
|
||||
continue
|
||||
tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m"
|
||||
found[tag] = float(r["AUC_validacion_interna"])
|
||||
if r.get("AUC_bootstrap_medio") is not None:
|
||||
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
|
||||
return found
|
||||
|
||||
|
||||
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
||||
"""The five routine records a promotion reads."""
|
||||
return {
|
||||
"MUESTREO": {
|
||||
"cohortes": {
|
||||
s: {
|
||||
"pacientes": len(c.frame),
|
||||
"recaidas": int(c.frame["evento"].sum()),
|
||||
"covariables": len(c.covariates),
|
||||
"eliminadas_por_colinealidad": c.eliminated,
|
||||
}
|
||||
for s, c in cohorts.items()
|
||||
},
|
||||
**next(iter(cohorts.values())).sampling,
|
||||
},
|
||||
"DATOS_FALTANTES": {
|
||||
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
||||
"no se imputa ni se descarta",
|
||||
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
|
||||
},
|
||||
"METODO_ANALITICO": {
|
||||
"modelos": "regresión logística con selección stepwise y red bayesiana con padres "
|
||||
"del desenlace por BDeu, uno por horizonte",
|
||||
"horizontes_meses": list(HORIZONS),
|
||||
"alfa_entrada": ALPHA_IN,
|
||||
"alfa_salida": ALPHA_OUT,
|
||||
"ess_bdeu": ESS,
|
||||
"maximo_de_padres": MAX_PARENTS,
|
||||
"cox_penalizado": COX_PENALIZER,
|
||||
"combinacion": "promedio de la LR y la HBN",
|
||||
},
|
||||
"BALANCE_CLASES": {
|
||||
"aplica": False,
|
||||
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
|
||||
"de ella después; no se rebalancea",
|
||||
},
|
||||
"CONFIANZA_SALIDA": {
|
||||
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
|
||||
"bootstrap",
|
||||
"replicas": {
|
||||
**{s: n_bootstrap.get(s, 0) for s in cohorts},
|
||||
"calculadora": RESAMPLES,
|
||||
},
|
||||
"eventos_minimos_por_escenario": MIN_EVENTS,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
|
||||
"""`recurrencia_desarrollo`: the tables behind the figures."""
|
||||
return {
|
||||
"version": VERSION,
|
||||
"tablas": {
|
||||
"auc": table(auc, AUC_COLUMNS),
|
||||
"factores_riesgo": table(factors),
|
||||
"calculadora": table(pd.DataFrame(points).round(4)),
|
||||
"escenarios_resumen": table(summary),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def figures(records: list[dict]) -> dict:
|
||||
"""`recurrencia`: each scenario's curves and calculator points."""
|
||||
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}
|
||||
@@ -0,0 +1,146 @@
|
||||
"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
|
||||
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
|
||||
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
|
||||
from), so the same fits, calculator and risk factors run on it.
|
||||
|
||||
- Time and event: months from the index to her first recurrence (any site) after it, else to
|
||||
her death, else to the cut-off (the site records its recurrences: a patient without one is
|
||||
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
|
||||
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
|
||||
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
|
||||
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
|
||||
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
|
||||
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
|
||||
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence import cohorts
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
|
||||
|
||||
RESULT_DAYS = 30
|
||||
TREATMENT_DAYS = 365
|
||||
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B
|
||||
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
|
||||
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
|
||||
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
|
||||
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
|
||||
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
|
||||
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
||||
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
||||
TREATMENT = ["Cirugia", *TREATMENTS]
|
||||
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
|
||||
SCENARIOS = {
|
||||
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
||||
"Tamano_tumor": ["<=20 mm"]},
|
||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||
"< 45 años": {"Edad": ["<45"]},
|
||||
"≥ 75 años": {"Edad": ["75+"]},
|
||||
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
||||
"HER2+ (luminal B HER2+ o no luminal)": {
|
||||
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
||||
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
||||
"Luminal · 1-3 ganglios · lumpectomía": {
|
||||
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
||||
"Cirugia": ["Lumpectomy"]},
|
||||
"Grado 3": {"Grado_histologico": ["3"]},
|
||||
} # fmt: skip
|
||||
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
|
||||
SAMPLING = {
|
||||
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
|
||||
"libre de ella hasta su defunción o la fecha de corte",
|
||||
"origen": "la sede (sus propias pacientes)",
|
||||
}
|
||||
|
||||
|
||||
def subtype(er, pr, her2, ki67) -> str:
|
||||
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
|
||||
hormone = "positive" in (er, pr)
|
||||
if her2 == "positive":
|
||||
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
|
||||
if her2 != "negative":
|
||||
return UNKNOWN
|
||||
if not hormone:
|
||||
return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN
|
||||
if ki67 is None or ki67 != ki67:
|
||||
return UNKNOWN
|
||||
return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-"
|
||||
|
||||
|
||||
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
||||
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
|
||||
reference cohort's."""
|
||||
events = events.assign(date=pd.to_datetime(events["date"]),
|
||||
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
|
||||
members = events.groupby("person_id")["index_date"].first()
|
||||
days = (events["date"] - events["index_date"]).dt.days
|
||||
cut = pd.Timestamp(as_of)
|
||||
after = events[(days > 0) & (events["date"] <= cut)]
|
||||
first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min()
|
||||
death = events[(events["type"] == "death") & (events["date"] <= cut)]
|
||||
death = death.groupby("person_id")["date"].min().reindex(members.index)
|
||||
end = first_recurrence.reindex(members.index).fillna(death).fillna(cut)
|
||||
out = pd.DataFrame(index=members.index)
|
||||
out["paciente"] = members.index
|
||||
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
|
||||
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
|
||||
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
|
||||
|
||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
|
||||
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
|
||||
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
||||
age = (members - birth.reindex(members.index)).dt.days / 365.25
|
||||
out["Edad"] = _band(age, *cohorts.AGE)
|
||||
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
|
||||
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
|
||||
*cohorts.NODES) # fmt: skip
|
||||
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
|
||||
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
|
||||
ki67 = number("ki67_pct").reindex(members.index)
|
||||
out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR))
|
||||
out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR))
|
||||
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
|
||||
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
|
||||
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
|
||||
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
|
||||
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
|
||||
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
|
||||
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
|
||||
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
|
||||
given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index)
|
||||
given = given.apply(lambda g: g if isinstance(g, set) else set())
|
||||
out["Cirugia"] = given.apply(
|
||||
lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None")
|
||||
)
|
||||
for name, kind in TREATMENTS.items():
|
||||
out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No")
|
||||
return out.reset_index(drop=True)
|
||||
|
||||
|
||||
def scarce(rows: pd.DataFrame) -> str | None:
|
||||
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
|
||||
patients recurred by it, or known free of it), or None."""
|
||||
for h in cohorts.HORIZONS:
|
||||
y = cohorts.at_horizon(rows, h)["y"]
|
||||
fewest = min(int(y.sum()), int((y == 0).sum()))
|
||||
if fewest < MIN_PER_CLASS:
|
||||
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
|
||||
f"{MIN_PER_CLASS} of each needed") # fmt: skip
|
||||
return None
|
||||
|
||||
|
||||
def prepare(rows: pd.DataFrame) -> Cohort:
|
||||
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
||||
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
|
||||
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
|
||||
redundant by construction)."""
|
||||
covariates = [c for c in rows.columns if c not in FIXED]
|
||||
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
||||
kept = [c for c in covariates if c not in dropped]
|
||||
treatment = [c for c in TREATMENT if c in kept]
|
||||
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
|
||||
SCENARIOS, SAMPLING) # fmt: skip
|
||||
@@ -0,0 +1,167 @@
|
||||
"""The CaMa models.
|
||||
|
||||
- Survival: mortality at 6, 12 and 18 months from the first invasive biopsy report, by
|
||||
interval survival (models.survival) over the age at the index, that report's results
|
||||
(stage among them) and the first course of treatment. The first course follows SEER's
|
||||
convention: what the patient received in the TREATMENT_DAYS after the index, taken as
|
||||
known at it. A patient who dies before her treatment counts as untreated (immortal-time
|
||||
bias), which the technical report states.
|
||||
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
|
||||
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
|
||||
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
|
||||
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
|
||||
|
||||
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
|
||||
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
|
||||
RESULT_DAYS = 30
|
||||
TREATMENT_DAYS = 365
|
||||
# Stage groups (AJCC): 0, I, II, III, IV, as the clinical scenarios name them.
|
||||
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
|
||||
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
|
||||
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts
|
||||
|
||||
# The clinical scenarios the survival report draws (as the SEER-trained original named them).
|
||||
STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
|
||||
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
|
||||
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
|
||||
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
|
||||
|
||||
|
||||
def _younger(years):
|
||||
return ("age", "<", years)
|
||||
|
||||
|
||||
def _older(years):
|
||||
return ("age", ">=", years)
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"HER2+ · ≥60 años · estadio III–IV (Alto)": (HER2_POS, _older(60), STAGE_III_IV),
|
||||
"HER2+ · <60 años · estadio 0–II (Bajo)": (HER2_POS, _younger(60), STAGE_0_II),
|
||||
"Estadio IV": (("stage", "in", ("IV",)),),
|
||||
"Estadio I": (("stage", "in", ("I",)),),
|
||||
"≥ 75 años": (_older(75),),
|
||||
"< 45 años": (_younger(45),),
|
||||
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
|
||||
_younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
|
||||
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
|
||||
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
|
||||
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
|
||||
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
|
||||
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
|
||||
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
|
||||
_older(65), HER2_NEG, STAGE_0_II, CONSERVING),
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's age group at the index and her index report's results, in bands where
|
||||
they are numbers (Ki-67 %, tumour size in mm)."""
|
||||
found = pd.DataFrame(index=members.index)
|
||||
found["age_group"] = age_group(events, members, (45, 60, 75))
|
||||
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
||||
found["age"] = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
|
||||
days = (events["date"] - events["index_date"]).dt.days
|
||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||
for kind in RESULTS:
|
||||
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
|
||||
for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
|
||||
("size_group", "size_mm", (20, 50))): # fmt: skip
|
||||
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
||||
found[name] = band(value.reindex(found.index), list(cuts))
|
||||
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
|
||||
found["stage"] = stage.reindex(found.index).map(STAGE_GROUP)
|
||||
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
|
||||
given = course.groupby("person_id")["value_code"].agg(set).reindex(found.index)
|
||||
given = given.apply(lambda g: g if isinstance(g, set) else set())
|
||||
found["surgery"] = given.apply(lambda g: next((s for s in reversed(SURGERY) if s in g), "none"))
|
||||
for name in ("chemotherapy", "radiotherapy"):
|
||||
found[name] = given.apply(lambda g, n=name: "yes" if n in g else "no")
|
||||
return found
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SiteRecurrence:
|
||||
"""The recurrence model on the site's own patients (models.cama.recurrence.site): the
|
||||
cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
|
||||
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
|
||||
|
||||
name: str
|
||||
cohort: str = "cama_cohort_recurrence"
|
||||
reports: bool = True # it writes its own reports (models.jobs)
|
||||
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
||||
|
||||
def train(self, events, as_of=None) -> tuple:
|
||||
from models.cama import recurrence
|
||||
from models.cama.recurrence import site
|
||||
from models.jobs import EmptyCohort
|
||||
|
||||
rows = site.frame(events, as_of or date.today())
|
||||
if reason := site.scarce(rows):
|
||||
raise EmptyCohort(f"cama.recurrence: {reason}")
|
||||
return recurrence.train_site(rows)
|
||||
|
||||
def predict(self, model, events) -> pd.DataFrame:
|
||||
from models.cama.recurrence import calculator, site
|
||||
|
||||
members = site.frame(events, date.today())
|
||||
found = model.predict(members)
|
||||
index = events.groupby("person_id")["index_date"].first()
|
||||
masks = calculator.masks(members, site.SCENARIOS)
|
||||
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
||||
for i in range(len(members))] # fmt: skip
|
||||
rows = []
|
||||
for i, person in enumerate(members["paciente"]):
|
||||
for h in model.horizons:
|
||||
rows.append({"person_id": person,
|
||||
"index_date": pd.Timestamp(index[person]).date(),
|
||||
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
|
||||
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
|
||||
return pd.DataFrame(rows, columns=OUTPUT)
|
||||
|
||||
|
||||
MODELS = {
|
||||
"survival": Spec(
|
||||
name="survival",
|
||||
cohort="cama_cohort_survival",
|
||||
features=(
|
||||
"age_group",
|
||||
*RESULTS,
|
||||
"ki67_group",
|
||||
"size_group",
|
||||
"stage",
|
||||
"surgery",
|
||||
"chemotherapy",
|
||||
"radiotherapy",
|
||||
),
|
||||
covariates=covariates,
|
||||
# As the SEER-trained original: stage, histologic type and the first course, and age.
|
||||
parents=(
|
||||
"stage",
|
||||
"histologic_type",
|
||||
"surgery",
|
||||
"chemotherapy",
|
||||
"radiotherapy",
|
||||
"age_group",
|
||||
),
|
||||
borders=(0, 6, 12, 18),
|
||||
cap_months=24,
|
||||
scenarios=SCENARIOS,
|
||||
scenario_columns=("age",),
|
||||
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
||||
notes=(
|
||||
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
|
||||
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
|
||||
"antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el "
|
||||
"efecto protector del tratamiento aparece mayor de lo que es.",
|
||||
),
|
||||
),
|
||||
"recurrence": SiteRecurrence("recurrence"),
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
|
||||
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
|
||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
|
||||
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
|
||||
task carries its data (a recording), so a cap paces a slow link."""
|
||||
|
||||
import os
|
||||
from collections.abc import Callable, Iterable
|
||||
from importlib.util import find_spec
|
||||
from typing import Any
|
||||
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
|
||||
def jobs() -> int:
|
||||
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
|
||||
return int(os.environ.get("BATCH_JOBS", "-1"))
|
||||
|
||||
|
||||
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
|
||||
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
|
||||
drawn as tasks start, so at most `jobs()` of them are held at once."""
|
||||
if find_spec("distributed") is None:
|
||||
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
|
||||
from distributed import Client, LocalCluster, as_completed
|
||||
|
||||
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
# one process per core, no dashboard port to collide with (8787 is often taken)
|
||||
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
|
||||
try:
|
||||
with Client(where) as client:
|
||||
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
|
||||
pending = iter(enumerate(arguments))
|
||||
results: dict[int, Any] = {}
|
||||
order: dict[Any, int] = {}
|
||||
|
||||
def submit() -> Any | None:
|
||||
if (item := next(pending, None)) is None:
|
||||
return None
|
||||
future = client.submit(task, *item[1], pure=False)
|
||||
order[future] = item[0]
|
||||
return future
|
||||
|
||||
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
|
||||
for done in running:
|
||||
results[order.pop(done)] = done.result()
|
||||
if (future := submit()) is not None:
|
||||
running.add(future)
|
||||
return [results[i] for i in range(len(results))]
|
||||
finally:
|
||||
if not address:
|
||||
where.close()
|
||||
@@ -1,7 +0,0 @@
|
||||
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
|
||||
builds its frame from the patients' timeline (dbt's view, through Persistance).
|
||||
|
||||
definition.py a cohort's definition, read from its TOML
|
||||
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
|
||||
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
|
||||
"""
|
||||
@@ -1,134 +0,0 @@
|
||||
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
|
||||
|
||||
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
|
||||
(`TimelineRepository.query`), recortada al corte y,
|
||||
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
|
||||
versiones de fila es aproximado, ADR-MD-009). La regla de
|
||||
la cohorte es la función que nombra su definición (`expression`).
|
||||
|
||||
Rearmar con la misma definición, los mismos parámetros y los mismos datos no
|
||||
guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están.
|
||||
Si los datos cambiaron, el `marco_sha` cambia y se guarda un armado nuevo.
|
||||
|
||||
`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o
|
||||
valida con este armado: llaves y huellas, nunca filas ni `pac_id`.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
from importlib import import_module
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from models.cohorts.definition import Definition, json_sha
|
||||
|
||||
DECIMALS = 9 # redondeo de los tiempos en la huella del marco
|
||||
|
||||
|
||||
def timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]:
|
||||
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
|
||||
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
|
||||
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
|
||||
|
||||
|
||||
def frame_of(
|
||||
sesion: Session,
|
||||
definicion: Definition,
|
||||
inicio: date,
|
||||
fin: date,
|
||||
corte: date,
|
||||
*,
|
||||
linea,
|
||||
pacientes: list[int] | None = None,
|
||||
conocida_hasta: datetime | None = None,
|
||||
):
|
||||
"""El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente)."""
|
||||
filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta)
|
||||
return definicion.function()(filas, definicion.reglas, inicio, fin, corte)
|
||||
|
||||
|
||||
def frame_sha(miembros, definicion: Definition) -> str:
|
||||
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
|
||||
nombres = [v.nombre for v in definicion.variables]
|
||||
|
||||
def redondo(valor):
|
||||
return round(valor, DECIMALS) if isinstance(valor, float) else valor
|
||||
|
||||
return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)]
|
||||
for m in sorted(miembros, key=lambda m: m.pac_id)])
|
||||
|
||||
|
||||
def code_sha(definicion: Definition) -> str:
|
||||
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
|
||||
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
|
||||
return json_sha(inspect.getsource(modulo))
|
||||
|
||||
|
||||
def build_of(
|
||||
sesion: Session,
|
||||
definicion: Definition,
|
||||
inicio: date,
|
||||
fin: date,
|
||||
corte: date,
|
||||
*,
|
||||
cohortes: TablasCohorte,
|
||||
linea,
|
||||
conocida_hasta: datetime | None = None,
|
||||
ahora: datetime | None = None,
|
||||
):
|
||||
"""El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`).
|
||||
|
||||
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
|
||||
"""
|
||||
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
|
||||
conocida_hasta=conocida_hasta)
|
||||
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
|
||||
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
|
||||
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
|
||||
"codigo": code_sha(definicion), "parametros": parametros})
|
||||
armado = cohortes.CohorteArmado(
|
||||
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
|
||||
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
|
||||
huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros),
|
||||
armado_en=ahora or datetime.now(timezone.utc),
|
||||
)
|
||||
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
|
||||
for orden, (paso, n) in enumerate(atricion, start=1)]
|
||||
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
|
||||
indice_fuente_tabla=m.indice_fuente_tabla,
|
||||
indice_fuente_id=m.indice_fuente_id) for m in miembros]
|
||||
tipos = {v.nombre: v.tipo for v in definicion.variables}
|
||||
variables = [
|
||||
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
|
||||
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
|
||||
else {"valor_numerico": float(valor)}))
|
||||
for m in miembros for nombre, valor in m.variables.items() if valor is not None
|
||||
]
|
||||
return armado, exclusiones, filas_miembro, variables
|
||||
|
||||
|
||||
def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int | None:
|
||||
"""El `armado_id` más reciente de la cohorte `url` (el último que se guardó); nulo si no hay. Solo lee."""
|
||||
armado = cohortes.CohorteArmado
|
||||
return sesion.exec(
|
||||
select(armado.armado_id).where(armado.url == url).order_by(armado.armado_id.desc()).limit(1)
|
||||
).first()
|
||||
|
||||
|
||||
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
|
||||
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
|
||||
nombres = [v.nombre for v in definicion.variables]
|
||||
valores: dict[int, dict] = {}
|
||||
variable = cohortes.CohorteVariable
|
||||
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
|
||||
valores.setdefault(fila.pac_id, {})[fila.variable] = (
|
||||
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
|
||||
)
|
||||
miembro = cohortes.CohorteMiembro
|
||||
filas = [
|
||||
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
|
||||
for m in sesion.exec(select(miembro).where(miembro.armado_id == armado_id).order_by(miembro.pac_id))
|
||||
]
|
||||
return ["pac_id", "fecha_indice", *nombres], filas
|
||||
@@ -1 +0,0 @@
|
||||
"""CaCu's cohorts: the surveillance cohort."""
|
||||
@@ -1,106 +0,0 @@
|
||||
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
|
||||
|
||||
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
|
||||
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
|
||||
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
|
||||
|
||||
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
|
||||
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
|
||||
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
|
||||
|
||||
Quién entra:
|
||||
- la índice es la primera citología de toda la historia, si cae en la ventana;
|
||||
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
|
||||
- y luego a quien no tiene resultado citológico ni de VPH en la índice.
|
||||
|
||||
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
|
||||
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
|
||||
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
DIAS_POR_ANIO = 365.25
|
||||
SIN_ESTADO = -999
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Member:
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
variables: dict # nombre -> valor; un valor nulo no se guarda
|
||||
|
||||
|
||||
def _by_patient(filas):
|
||||
pacientes = defaultdict(list)
|
||||
for fila in filas:
|
||||
pacientes[fila["pac_id"]].append(fila)
|
||||
return pacientes
|
||||
|
||||
|
||||
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
|
||||
"""(miembros, atrición). `filas`: la línea de tiempo de CaCu, ya recortada al corte (`hasta=corte`)."""
|
||||
grados = set(reglas["grados_evento"])
|
||||
ventana = int(reglas["ventana_basal_dias"])
|
||||
pap_negativo = set(reglas["no_prevalente"]["pap"])
|
||||
vph_negativo = set(reglas["no_prevalente"]["vph"])
|
||||
|
||||
candidatas = evento_previo = sin_resultado = 0
|
||||
miembros = []
|
||||
for pac_id, eventos in sorted(_by_patient(filas).items()):
|
||||
eventos = [e for e in eventos if e["fecha"] <= corte]
|
||||
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
|
||||
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
|
||||
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
|
||||
continue
|
||||
indice = tomas[0]
|
||||
llave = (indice["fuente_tabla"], indice["fuente_id"])
|
||||
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
|
||||
candidatas += 1
|
||||
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
|
||||
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
|
||||
evento_previo += 1
|
||||
continue
|
||||
if pap_0 is None and hpv_0 is None:
|
||||
sin_resultado += 1
|
||||
continue
|
||||
|
||||
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
|
||||
for fecha, positiva in biopsias if fecha >= fecha_indice]
|
||||
if reglas["negativo_da_l"]:
|
||||
for toma in tomas[1:]:
|
||||
clave = (toma["fuente_tabla"], toma["fuente_id"])
|
||||
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
|
||||
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
|
||||
positivas = [d for d, positiva, _ in verificaciones if positiva]
|
||||
primera_positiva = min(positivas) if positivas else None
|
||||
negativas = [d for d, positiva, _ in verificaciones
|
||||
if not positiva and (primera_positiva is None or d < primera_positiva)]
|
||||
ultima_negativa = max(negativas) if negativas else None
|
||||
|
||||
if primera_positiva is not None and primera_positiva <= ventana:
|
||||
c = 1
|
||||
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
|
||||
c = 0
|
||||
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
|
||||
c = 0
|
||||
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
|
||||
c = 0
|
||||
else:
|
||||
c = SIN_ESTADO
|
||||
if c == 1:
|
||||
l = r = SIN_ESTADO
|
||||
else:
|
||||
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
|
||||
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
|
||||
miembros.append(Member(pac_id, fecha_indice, *llave,
|
||||
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
|
||||
|
||||
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
|
||||
("sin sin_resultado", len(miembros))]
|
||||
return miembros, atricion
|
||||
@@ -1,78 +0,0 @@
|
||||
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
|
||||
#
|
||||
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
|
||||
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
|
||||
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
|
||||
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
|
||||
#
|
||||
# Cambiar una regla es cambiar la definición: se sube `version`.
|
||||
|
||||
[group]
|
||||
url = "cacu/cohorte_vigilancia"
|
||||
version = "0.2.0"
|
||||
status = "draft"
|
||||
membership = "definitional"
|
||||
title = "Mujeres en vigilancia por citología"
|
||||
expression = "cacu.surveillance:frame"
|
||||
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
|
||||
desenlace = "cin2_mas"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "evento_previo"
|
||||
exclude = true
|
||||
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "sin_resultado"
|
||||
exclude = true
|
||||
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
|
||||
|
||||
[group.reglas]
|
||||
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
ventana_basal_dias = 90
|
||||
negativo_da_l = true
|
||||
negativo_confirma_no_prevalente = true
|
||||
colposcopia_negativa = []
|
||||
|
||||
[group.reglas.no_prevalente]
|
||||
pap = ["NORMAL"]
|
||||
vph = ["NEGATIVO"]
|
||||
description = "Tamizaje completamente negativo: confirma que no es prevalente"
|
||||
|
||||
[group.reglas_estado]
|
||||
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
|
||||
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
|
||||
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
|
||||
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
|
||||
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
|
||||
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "c"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "l"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "r"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "pap_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Categoría citológica de la citología índice"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "hpv_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Resultado de VPH de la misma muestra"
|
||||
@@ -1 +0,0 @@
|
||||
"""CaMa's cohorts: the screening cohort, a proposal the cycle doesn't build yet."""
|
||||
@@ -1,63 +0,0 @@
|
||||
# Cohorte de tamizaje mastográfico de CaMa: quién entra al modelo de riesgo de cáncer de mama y con qué marco.
|
||||
#
|
||||
# PROPUESTA (T-21g, 2026-10-21): MD-Q14 está abierta. El índice, la exclusión, el desenlace, el
|
||||
# horizonte y los predictores son una propuesta del orquestador para que CaMa tenga una cohorte que
|
||||
# armar y estimar, como CaCu y TEA. Todas las reglas están en `sin_definir`. Se lee de la línea de
|
||||
# tiempo de CaMa (`cama/linea_de_tiempo.py`).
|
||||
#
|
||||
# Cambiar una regla es cambiar la definición: se sube `version`.
|
||||
|
||||
[group]
|
||||
url = "cama/cohorte_tamizaje"
|
||||
version = "0.1.0"
|
||||
status = "draft"
|
||||
membership = "definitional"
|
||||
title = "Pacientes con un primer BI-RADS"
|
||||
expression = "cama.screening:frame"
|
||||
indice = "Primer BI-RADS de la historia de la paciente (fecha de su resultado), si cae en la ventana de reclutamiento"
|
||||
desenlace = "cancer_de_mama"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "cancer_previo"
|
||||
exclude = true
|
||||
description = "Cáncer de mama antes de la fecha índice: una nota con un CIE-10 de `cie_antecedente` o una biopsia con grado en `grados_cancer`"
|
||||
|
||||
[group.reglas]
|
||||
grados_cancer = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
|
||||
cie_antecedente = ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
|
||||
horizonte_dias = 365
|
||||
|
||||
[group.reglas_estado]
|
||||
grados_cancer = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.biopsia_cancer` (provisional para CAMA_BIOPSIAS)" }
|
||||
cie_antecedente = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.diagnostico.cie_antecedente` (D05 y C50, como en CaCu)" }
|
||||
horizonte_dias = { estado = "sin_definir", fuente = "Propuesta T-21g: un año desde el BI-RADS índice; decide clínica con modelos (MD-Q14)" }
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "d"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Cáncer de mama por biopsia dentro del horizonte: 1 sí, 0 no (horizonte vencido al corte), -999 en observación"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "t"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Años del índice a la biopsia con cáncer (sin fila = sin cáncer al corte)"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "birads_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "BI-RADS índice"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "calidad_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Calidad de imagen de la mastografía más reciente al índice"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "n_ordenes_previas"
|
||||
role = "covariate"
|
||||
tipo = "numero"
|
||||
title = "Órdenes de estudio antes del índice"
|
||||
@@ -1,81 +0,0 @@
|
||||
"""El marco de la cohorte de tamizaje mastográfico de CaMa, desde la línea de tiempo (`cohorte_tamizaje.toml`). PROPUESTA (MD-Q14).
|
||||
|
||||
Una fila del marco por miembro:
|
||||
|
||||
d 1 = cáncer de mama por biopsia dentro del horizonte; 0 = sin cáncer y el horizonte venció
|
||||
al corte; -999 = sin cáncer y el horizonte todavía no vence (en observación)
|
||||
t años del índice a la biopsia con cáncer (nulo sin cáncer al corte)
|
||||
|
||||
Quién entra:
|
||||
- el índice es el primer BI-RADS con categoría de toda la historia (la fecha de su resultado), si
|
||||
cae en la ventana de reclutamiento;
|
||||
- se excluye a quien tiene cáncer antes del índice: una nota con un CIE-10 de `cie_antecedente` o
|
||||
una biopsia con grado en `grados_cancer`.
|
||||
|
||||
Predictores, todos conocidos a más tardar en el índice: el BI-RADS índice, la calidad de imagen de
|
||||
la mastografía más reciente y cuántas órdenes de estudio hubo antes.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
DIAS_POR_ANIO = 365.25
|
||||
EN_OBSERVACION = -999
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Member:
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
variables: dict # nombre -> valor; un valor nulo no se guarda
|
||||
|
||||
|
||||
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
|
||||
"""(miembros, atrición). `filas`: la línea de tiempo de CaMa, ya recortada al corte (`hasta=corte`)."""
|
||||
grados = set(reglas["grados_cancer"])
|
||||
cie = set(reglas["cie_antecedente"])
|
||||
horizonte = int(reglas["horizonte_dias"])
|
||||
|
||||
por_paciente = defaultdict(list)
|
||||
for fila in filas:
|
||||
if fila["fecha"] is not None and fila["fecha"] <= corte:
|
||||
por_paciente[fila["pac_id"]].append(fila)
|
||||
|
||||
candidatos = cancer_previo = 0
|
||||
miembros = []
|
||||
for pac_id, eventos in sorted(por_paciente.items()):
|
||||
birads = sorted((e for e in eventos if e["tipo"] == "birads" and e["valor_codigo"]),
|
||||
key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not birads or not (inicio <= birads[0]["fecha"] < fin):
|
||||
continue
|
||||
indice = birads[0]
|
||||
fecha_indice = indice["fecha"]
|
||||
candidatos += 1
|
||||
biopsias = sorted(e["fecha"] for e in eventos if e["tipo"] == "biopsia" and e["valor_codigo"] in grados)
|
||||
notas = [e["fecha"] for e in eventos if e["tipo"] == "nota_medica" and e["valor_codigo"] in cie]
|
||||
if any(fecha < fecha_indice for fecha in [*biopsias, *notas]):
|
||||
cancer_previo += 1
|
||||
continue
|
||||
|
||||
posteriores = [(fecha - fecha_indice).days for fecha in biopsias]
|
||||
primero = min(posteriores) if posteriores else None
|
||||
if primero is not None and primero <= horizonte:
|
||||
d = 1
|
||||
elif (corte - fecha_indice).days >= horizonte:
|
||||
d = 0
|
||||
else:
|
||||
d = EN_OBSERVACION
|
||||
|
||||
antes = [e for e in eventos if e["fecha"] <= fecha_indice]
|
||||
mastografias = sorted((e for e in antes if e["tipo"] == "mastografia"), key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
miembros.append(Member(pac_id, fecha_indice, indice["fuente_tabla"], indice["fuente_id"], {
|
||||
"d": d, "t": None if primero is None else primero / DIAS_POR_ANIO, "birads_0": indice["valor_codigo"],
|
||||
"calidad_0": mastografias[-1]["valor_codigo"] if mastografias else None,
|
||||
"n_ordenes_previas": sum(1 for e in antes if e["tipo"] == "orden" and e["fecha"] < fecha_indice),
|
||||
}))
|
||||
|
||||
atricion = [("candidatos", candidatos), ("sin cancer_previo", candidatos - cancer_previo)]
|
||||
return miembros, atricion
|
||||
@@ -1,82 +0,0 @@
|
||||
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
|
||||
|
||||
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
|
||||
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
|
||||
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Variable:
|
||||
nombre: str
|
||||
rol: str # outcome o covariate
|
||||
tipo: str # numero o codigo
|
||||
titulo: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Definition:
|
||||
url: str
|
||||
version: str
|
||||
titulo: str
|
||||
expression: str
|
||||
desenlace: str
|
||||
reglas: dict
|
||||
variables: tuple[Variable, ...]
|
||||
definicion_sha: str # sha256 del TOML
|
||||
|
||||
@property
|
||||
def reglas_sha(self) -> str:
|
||||
return json_sha(self.reglas)
|
||||
|
||||
def function(self):
|
||||
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
|
||||
return function_of(self.expression)
|
||||
|
||||
|
||||
def json_sha(objeto) -> str:
|
||||
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
|
||||
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
|
||||
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
|
||||
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
|
||||
|
||||
|
||||
def read_definition(ruta: Path) -> Definition:
|
||||
texto = ruta.read_text(encoding="utf-8")
|
||||
doc = tomllib.loads(texto)
|
||||
g = doc["group"]
|
||||
reglas = dict(g["reglas"])
|
||||
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
|
||||
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
|
||||
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
|
||||
nombres = [v.nombre for v in variables]
|
||||
if len(set(nombres)) != len(nombres):
|
||||
raise ValueError(f"{g['url']}: variables repetidas.")
|
||||
return Definition(
|
||||
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
|
||||
desenlace=g["desenlace"], reglas=reglas, variables=variables,
|
||||
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
|
||||
)
|
||||
|
||||
|
||||
def function_of(expresion: str):
|
||||
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
|
||||
modulo, nombre = expresion.split(":")
|
||||
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
|
||||
if not callable(function):
|
||||
raise ValueError(f"{modulo} debe definir la función {nombre}.")
|
||||
return function
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Survival curves of a group (free of death, or of recurrence), from whole months of
|
||||
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
|
||||
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
|
||||
events and censorings (an event in month m falls between S(m) and S(m+1); a censoring there
|
||||
survives to m + 1/2). Fits start from several points and run each to the optimizer's
|
||||
convergence; one that doesn't converge is an error, not a curve."""
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize, minimize_scalar
|
||||
from scipy.special import beta as beta_function
|
||||
from scipy.special import betainc, gammaln
|
||||
|
||||
Z = 1.96
|
||||
INVALID = 1e12 # the likelihood outside a model's parameter region
|
||||
|
||||
|
||||
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
|
||||
"""Per month: recurrences, censorings, and patients at risk at its start."""
|
||||
months, event = np.asarray(months, int), np.asarray(event, bool)
|
||||
length = max(length, int(months.max()) + 2)
|
||||
d = np.bincount(months[event], minlength=length)
|
||||
c = np.bincount(months[~event], minlength=length)
|
||||
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
return d, c, at_risk
|
||||
|
||||
|
||||
def kaplan_meier(months, event, until: int):
|
||||
"""S, low, high at the start of months 0..until."""
|
||||
d, _, n = life_table(months, event, until + 1)
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
||||
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
||||
S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1]
|
||||
se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S))
|
||||
inside = (S > 0) & (S < 1)
|
||||
return (
|
||||
S,
|
||||
np.where(inside, S ** np.exp(Z * se), S),
|
||||
np.where(inside, S ** np.exp(-Z * se), S),
|
||||
)
|
||||
|
||||
|
||||
def _nll(survival, d, c) -> float:
|
||||
T = len(d)
|
||||
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
|
||||
S, mid = both[: T + 1], both[T + 1 :]
|
||||
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
|
||||
return INVALID
|
||||
p = np.clip(S[:-1] - S[1:], 1e-300, None)
|
||||
return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
|
||||
|
||||
|
||||
def weibull(t, k, lam):
|
||||
return np.exp(-((np.asarray(t, float) / lam) ** k))
|
||||
|
||||
|
||||
def fit_weibull(d, c) -> tuple[float, float]:
|
||||
"""(k, lambda) of the classic Weibull, best of a 3 x 3 grid of Nelder-Mead starts."""
|
||||
best = None
|
||||
for k0 in (0.7, 1.0, 1.5):
|
||||
for l0 in (50.0, 200.0, 1000.0):
|
||||
r = minimize(
|
||||
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
|
||||
[np.log(k0), np.log(l0)],
|
||||
method="Nelder-Mead",
|
||||
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
|
||||
)
|
||||
r = _converged(r, "Weibull")
|
||||
best = r if best is None or r.fun < best.fun else best
|
||||
k, lam = np.exp(best.x)
|
||||
return float(k), float(lam)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fractional Weibull
|
||||
|
||||
STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
|
||||
|
||||
|
||||
class NotConverged(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _converged(r, what: str):
|
||||
if not r.success:
|
||||
raise NotConverged(f"{what}: {r.message}")
|
||||
return r
|
||||
|
||||
|
||||
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
|
||||
"""S(t) with S(0) = 1 and Caputo derivative D^rho S(t) = -c t^s S(t) (0 < rho <= 1,
|
||||
s + rho > 0): the Kilbas-Saigo function E_{rho, 1+s/rho, s/rho}(-c t^(rho+s)).
|
||||
|
||||
Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du,
|
||||
by product integration in w = t^(rho+s), where S is a power series in z = c w and so
|
||||
smooth: S is linear in w on each step, and the kernel's integrals against u^s and
|
||||
u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z):
|
||||
fine where S starts to fall, wide over its slow tail. No series, no extended precision."""
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
e = rho + s
|
||||
top = float(t.max()) if t.size else 0.0
|
||||
if top <= 0:
|
||||
return np.ones_like(t)
|
||||
w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c
|
||||
w[-1] = top**e
|
||||
grid = w ** (1 / e)
|
||||
y = np.ones(STEPS + 1)
|
||||
kappa = c / np.exp(gammaln(rho))
|
||||
b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
|
||||
dw = np.diff(w)
|
||||
for n in range(1, STEPS + 1):
|
||||
x = grid[: n + 1] / grid[n]
|
||||
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x))
|
||||
ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
|
||||
slope = (ie - w[:n] * i0) / dw[:n]
|
||||
own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j
|
||||
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
|
||||
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
|
||||
return np.interp(t**e, w, y)
|
||||
|
||||
|
||||
def fractional(t, k, alpha, beta, lam) -> np.ndarray:
|
||||
"""The fractional Weibull's survival (Kilbas-Saigo, with the classic Weibull as its
|
||||
alpha = beta = 1 case); NaN outside its parameter region."""
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
s = k + alpha - 2
|
||||
if k + alpha <= 1 or s + beta <= 0:
|
||||
return np.full(t.shape, np.nan)
|
||||
c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2)
|
||||
return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0)
|
||||
|
||||
|
||||
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
|
||||
"""(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s),
|
||||
with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
|
||||
return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
|
||||
|
||||
|
||||
def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
|
||||
"""(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, by
|
||||
maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over
|
||||
every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it.
|
||||
(alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is
|
||||
never worse) and a grid of others, each to Nelder-Mead's convergence."""
|
||||
floor = max(0.0, 1.0 - k) + 1e-6
|
||||
top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
|
||||
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
|
||||
lambdas = (0.0, np.log(1e7))
|
||||
|
||||
def unpack(p):
|
||||
return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
|
||||
|
||||
def profile(p) -> tuple[float, float]:
|
||||
a, b = unpack(p)
|
||||
if k + a <= 1 or k + a + b <= 2:
|
||||
return INVALID, np.nan
|
||||
rho, s, scale = _shape(k, a, b)
|
||||
e = rho + s
|
||||
z_top = scale * top**e # lambda = 1 reaches the farthest
|
||||
z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1))
|
||||
g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0)
|
||||
|
||||
def nll(log_lam: float) -> float:
|
||||
found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g)
|
||||
return _nll(lambda t: found, d, c)
|
||||
|
||||
coarse = np.linspace(*lambdas, 141)
|
||||
i = int(np.argmin([nll(x) for x in coarse]))
|
||||
r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
|
||||
method="bounded", options={"xatol": 1e-9}) # fmt: skip
|
||||
return float(r.fun), float(r.x)
|
||||
|
||||
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]]
|
||||
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
|
||||
best = None
|
||||
for p0 in starts:
|
||||
options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
|
||||
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
|
||||
r = _converged(r, "fractional Weibull")
|
||||
best = r if best is None or r.fun < best.fun else best
|
||||
a, b = unpack(best.x)
|
||||
return float(a), float(b), float(np.exp(profile(best.x)[1]))
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||
|
||||
import importlib
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
|
||||
from models import graph
|
||||
from models.jobs import EmptyCohort
|
||||
from persistance import backup as backups
|
||||
from persistance import config_log, silver
|
||||
|
||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||
|
||||
|
||||
class PipelineRun(dg.Config):
|
||||
pipeline: str
|
||||
version: int | None = None # default: the latest saved
|
||||
|
||||
|
||||
@dg.op
|
||||
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
|
||||
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
|
||||
version, pipeline = config_log.get(config.pipeline, config.version)
|
||||
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
|
||||
graph.run(config.pipeline, pipeline, log=context.log.info)
|
||||
return version
|
||||
|
||||
|
||||
@dg.job(tags=WRITES)
|
||||
def ingest():
|
||||
run_pipeline()
|
||||
|
||||
|
||||
def _jobs(domain: str):
|
||||
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
||||
try:
|
||||
return importlib.import_module(f"models.{domain}.jobs")
|
||||
except ModuleNotFoundError as e:
|
||||
raise ValueError(f"{domain} has no models") from e
|
||||
|
||||
|
||||
class Training(dg.Config):
|
||||
domain: str
|
||||
models: list[str] = [] # default: every model of the domain
|
||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||
|
||||
|
||||
@dg.op
|
||||
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
|
||||
"""A new registered version of each model (MLflow), with its reports."""
|
||||
jobs = _jobs(config.domain)
|
||||
as_of = date.fromisoformat(config.as_of) if config.as_of else None
|
||||
found = {}
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
return found
|
||||
|
||||
|
||||
@dg.job
|
||||
def train():
|
||||
train_models()
|
||||
|
||||
|
||||
class Scoring(dg.Config):
|
||||
domain: str
|
||||
models: list[str] = [] # default: every model of the domain
|
||||
|
||||
|
||||
@dg.op
|
||||
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
|
||||
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
|
||||
jobs = _jobs(config.domain)
|
||||
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()}
|
||||
for name, version in found.items():
|
||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
|
||||
return found
|
||||
|
||||
|
||||
@dg.job(tags=WRITES)
|
||||
def score():
|
||||
score_models()
|
||||
|
||||
|
||||
class Analysis(dg.Config):
|
||||
domain: str
|
||||
|
||||
|
||||
@dg.op
|
||||
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
|
||||
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
|
||||
found = _jobs(config.domain).analyze()
|
||||
context.log.info(f"{config.domain}: {found} analysed")
|
||||
return found
|
||||
|
||||
|
||||
@dg.job(tags=WRITES)
|
||||
def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
@dg.op
|
||||
def make_backup(context: dg.OpExecutionContext) -> str:
|
||||
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
|
||||
folder = backups.create()
|
||||
context.log.info(f"backup {folder}")
|
||||
return str(folder)
|
||||
|
||||
|
||||
@dg.job(tags=WRITES) # holds the writing slot: nothing writes while it copies
|
||||
def backup():
|
||||
make_backup()
|
||||
|
||||
|
||||
# Nightly by default; BACKUP_SCHEDULE is a cron expression (empty: no schedule).
|
||||
nightly = (
|
||||
[
|
||||
dg.ScheduleDefinition(
|
||||
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
|
||||
)
|
||||
] # fmt: skip
|
||||
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
|
||||
else []
|
||||
)
|
||||
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
|
||||
@@ -1,236 +0,0 @@
|
||||
"""TEA's EEG analysis against the database: which EEGs to analyse, the batch, and its results written to bronze.
|
||||
|
||||
An EEG is pending when it has an EDF and was never analysed, or was analysed with another plan or other module
|
||||
versions, or, being valid, against baselines other than those now in production. One that failed with the current
|
||||
plan and versions waits for a new one instead of failing again on every run.
|
||||
|
||||
Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`,
|
||||
`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id
|
||||
from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with
|
||||
its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
|
||||
|
||||
`cluster` is the `tea` library's: "sync" runs in this process, "local" on a LocalCluster, "auto" on the scheduler in
|
||||
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
||||
"""
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlmodel import Session, col, delete, select
|
||||
|
||||
from core.tea.enums import MetricaEeg
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
|
||||
|
||||
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import Settings, settings as model_settings
|
||||
|
||||
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
|
||||
|
||||
|
||||
def checked_settings() -> Settings:
|
||||
"""The analysis's settings, checked against the metric catalog the tables use."""
|
||||
s = model_settings()
|
||||
codes = sorted(m.code for m in s.metrics)
|
||||
if codes != sorted(c.value for c in MetricaEeg):
|
||||
raise ValueError(f"model.toml must map every MetricaEeg code once, not {codes}")
|
||||
return s
|
||||
|
||||
|
||||
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
|
||||
everything: bool = False, limit: int | None = None) -> list[str]:
|
||||
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
|
||||
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
|
||||
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
|
||||
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
|
||||
out, expected = [], None
|
||||
for eeg_id, valid, stored_hash, stored_versions, error in session.exec(query):
|
||||
if everything or stored_hash != plan_hash or stored_versions != versions:
|
||||
out.append(eeg_id)
|
||||
elif valid == 1 and error is None:
|
||||
stored = dict(session.exec(select(EegMetrica.met_codigo, EegMetrica.met_modelo)
|
||||
.where(EegMetrica.met_eeg_id == eeg_id)).all())
|
||||
expected = models() if expected is None else expected
|
||||
if any(stored.get(code) != label for code, label in expected.items()):
|
||||
out.append(eeg_id)
|
||||
if limit is not None and len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def age_months(born, studied, days_per_month: float) -> float | None:
|
||||
if born is None or studied is None or studied < born:
|
||||
return None
|
||||
return round((studied - born).days / days_per_month, 1)
|
||||
|
||||
|
||||
def inputs(session: Session, eeg_id: str, days_per_month: float) -> tuple[bytes, float | None]:
|
||||
eeg = session.get(Eeg, eeg_id)
|
||||
if eeg is None or eeg.eeg_estudio is None:
|
||||
raise LookupError(f"no EDF for EEG {eeg_id!r}")
|
||||
born = session.exec(select(Pacientes.pac_fecha_nacimiento).where(Pacientes.pac_id == eeg.eeg_pac_id)).first()
|
||||
return bytes(eeg.eeg_estudio), age_months(born, eeg.eeg_fecha_estudio, days_per_month)
|
||||
|
||||
|
||||
def row_id(*parts: object) -> str:
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, "tea:eeg/" + "/".join("" if p is None else str(p) for p in parts)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rows:
|
||||
eeg: dict
|
||||
criteria: list[EegCriterio]
|
||||
metrics: list[EegMetrica]
|
||||
electrodes: list[EegMetricaElectrodo]
|
||||
|
||||
|
||||
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
|
||||
eeg = {
|
||||
"eeg_valido": m.valid, "eeg_nivel": m.level, "eeg_fraccion_limpia": m.clean_fraction,
|
||||
"eeg_canales_malos": m.bad_channels, "eeg_ruido_linea_db": m.line_db, "eeg_con_sueno": m.asleep,
|
||||
"eeg_edad_meses": m.age_months, "eeg_plan_hash": m.plan_hash, "eeg_versiones": m.versions,
|
||||
"eeg_analizado_en": at or datetime.now(timezone.utc).replace(tzinfo=None), "eeg_error": m.error,
|
||||
}
|
||||
if m.channels is not None:
|
||||
eeg["eeg_canales"] = m.channels
|
||||
if m.duration_min is not None:
|
||||
eeg["eeg_duracion_min"] = m.duration_min
|
||||
|
||||
seen: dict[tuple[str, str | None], int] = {}
|
||||
criteria = []
|
||||
for c in m.checks:
|
||||
n = seen[c.code, c.electrode] = seen.get((c.code, c.electrode), 0) + 1
|
||||
criteria.append(EegCriterio(
|
||||
cri_id=row_id(m.key, "criterio", c.code, c.electrode, n), cri_eeg_id=m.key, cri_codigo=c.code,
|
||||
cri_electrodo=c.electrode, cri_valor=c.value, cri_valor_texto=c.text, cri_unidad=c.unit,
|
||||
cri_bajo=c.low, cri_alto=c.high, cri_decisivo=int(c.decisive), cri_anormal=int(c.abnormal),
|
||||
))
|
||||
|
||||
by_code = {metric.code: metric for metric in s.metrics}
|
||||
metrics, electrodes = [], []
|
||||
for value in m.metrics:
|
||||
metric = by_code[value.code]
|
||||
met_id = row_id(m.key, "metrica", value.code)
|
||||
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months)
|
||||
used = [metric.scenario] if deviation is not None else []
|
||||
for electrode, raw in sorted(value.electrodes.items()):
|
||||
at_electrode = None
|
||||
if metric.electrode_scenario:
|
||||
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
|
||||
raw, m.age_months)
|
||||
if at_electrode is not None and metric.electrode_scenario not in used:
|
||||
used.append(metric.electrode_scenario)
|
||||
electrodes.append(EegMetricaElectrodo(
|
||||
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode,
|
||||
mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
|
||||
))
|
||||
metrics.append(EegMetrica(
|
||||
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value,
|
||||
met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
|
||||
met_p5=deviation.p5 if deviation else None, met_mediana=deviation.median if deviation else None,
|
||||
met_p95=deviation.p95 if deviation else None,
|
||||
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
|
||||
))
|
||||
return Rows(eeg, criteria, metrics, electrodes)
|
||||
|
||||
|
||||
def save(session: Session, eeg_id: str, new: Rows) -> None:
|
||||
"""Replaces the EEG's analysis in the caller's session; the caller commits."""
|
||||
eeg = session.get(Eeg, eeg_id)
|
||||
if eeg is None:
|
||||
raise LookupError(f"no EEG {eeg_id!r}")
|
||||
for column, value in new.eeg.items():
|
||||
setattr(eeg, column, value)
|
||||
session.add(eeg)
|
||||
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id)
|
||||
session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
|
||||
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
|
||||
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
|
||||
session.flush()
|
||||
session.add_all([*new.criteria, *new.metrics, *new.electrodes])
|
||||
|
||||
|
||||
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
|
||||
if m.error:
|
||||
quality = f"error: {m.error}"
|
||||
elif m.valid:
|
||||
quality = f"valido: {m.level}"
|
||||
else:
|
||||
quality = "no valido: " + "; ".join(c.code for c in m.checks if c.abnormal and c.decisive)
|
||||
return ExtractionRun(
|
||||
domain=s.domain, entity="eeg", entity_pk=m.key, column_extracted=COLUMNS,
|
||||
source_description="eeg.eeg_estudio (EDF)", source_started_at=started, source_ended_at=ended,
|
||||
transform_description=f"tea {s.impl}, plan {s.plan} {m.plan_hash}; {m.versions}",
|
||||
quality_validation=quality,
|
||||
estatus=(EstatusExtraccion.FALLIDA if m.error else EstatusExtraccion.COMPLETADA).value,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Summary:
|
||||
pending: int = 0
|
||||
valid: int = 0
|
||||
not_valid: int = 0
|
||||
failed: int = 0
|
||||
|
||||
|
||||
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
|
||||
out = {}
|
||||
for m in s.metrics:
|
||||
scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario]
|
||||
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
|
||||
return out
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
|
||||
settings: Settings | None = None, baselines: Baselines | None = None,
|
||||
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings or checked_settings()
|
||||
b = baselines or Baselines(s.domain)
|
||||
pipe = pipeline(s)
|
||||
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
||||
with eeg_repository.open_session() as session:
|
||||
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||
everything=everything, limit=limit)
|
||||
summary = Summary(pending=len(ids))
|
||||
|
||||
def write(m: Measurement) -> None:
|
||||
ended = _now()
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, m.key, rows(m, s, b, at=ended))
|
||||
session.commit()
|
||||
if log_runs:
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
|
||||
if m.error:
|
||||
summary.failed += 1
|
||||
elif m.valid:
|
||||
summary.valid += 1
|
||||
else:
|
||||
summary.not_valid += 1
|
||||
|
||||
def lost(args, exc) -> Measurement:
|
||||
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
||||
error=f"{type(exc).__name__}: the batch lost this study")
|
||||
|
||||
for start in range(0, len(ids), batch):
|
||||
argsets = []
|
||||
with eeg_repository.open_session() as session:
|
||||
for eeg_id in ids[start:start + batch]:
|
||||
edf, age = inputs(session, eeg_id, s.days_per_month)
|
||||
argsets.append((eeg_id, edf, age, s))
|
||||
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
|
||||
return summary
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
|
||||
|
||||
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
|
||||
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
|
||||
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
|
||||
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
|
||||
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
|
||||
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
|
||||
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
|
||||
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
|
||||
not effects. Each clinical scenario then lists the classified factors nearly all of its
|
||||
patients have (definitorios) or most have (mayoritarios)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.stats import false_discovery_control
|
||||
|
||||
from models.curves import life_table
|
||||
|
||||
ALPHA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
Z = 1.96
|
||||
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
|
||||
ORDER = {
|
||||
"riesgo robusto": 0,
|
||||
"protector robusto": 1,
|
||||
"riesgo sugerente": 2,
|
||||
"protector sugerente": 3,
|
||||
"no concluyente": 4,
|
||||
}
|
||||
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
|
||||
# Scenario presence: the share of the scenario's patients in the category.
|
||||
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
|
||||
DESCRIBING = ("definitoria", "mayoritaria")
|
||||
|
||||
|
||||
def variable_of(term: str, covariates: list[str]) -> str:
|
||||
"""The covariate a dummy belongs to (the longest name it starts with)."""
|
||||
found = [c for c in covariates if term.startswith(c + "_")]
|
||||
return max(found, key=len) if found else term
|
||||
|
||||
|
||||
def km_at(months, event, horizon) -> tuple[float, float]:
|
||||
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
|
||||
d, _, n = life_table(months, event)
|
||||
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
||||
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
||||
last = min(horizon, len(d) - 1) + 1
|
||||
S = float(np.prod(q[:last]))
|
||||
return S, S * float(np.sqrt(np.sum(v[:last])))
|
||||
|
||||
|
||||
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
|
||||
"""Logistic GLM on every category but each covariate's reference (constant and
|
||||
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
|
||||
X = pd.get_dummies(data[variables]).astype(float)
|
||||
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = np.exp(m.conf_int().loc[X.columns])
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"termino": X.columns,
|
||||
name: np.exp(m.params[X.columns].to_numpy()),
|
||||
"IC95_inf": ci[0].to_numpy(),
|
||||
"IC95_sup": ci[1].to_numpy(),
|
||||
"p": m.pvalues[X.columns].to_numpy(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
|
||||
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
|
||||
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
|
||||
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
|
||||
survival columns)."""
|
||||
table = table.reset_index(drop=True)
|
||||
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
|
||||
table["categoria"] = [
|
||||
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
|
||||
]
|
||||
table["referencia"] = table["variable"].map(reference)
|
||||
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
|
||||
category, ref, delta_name = names
|
||||
rows = []
|
||||
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
|
||||
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
|
||||
sa, ea = km_at(months[a], event[a], horizon)
|
||||
sb, eb = km_at(months[b], event[b], horizon)
|
||||
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
|
||||
rows.append({
|
||||
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
|
||||
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
|
||||
}) # fmt: skip
|
||||
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
|
||||
"delta_IC95_inf", "delta_IC95_sup"])],
|
||||
axis=1) # fmt: skip
|
||||
|
||||
|
||||
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
|
||||
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
|
||||
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
|
||||
for the criteria `evaluated`."""
|
||||
risk = tab[or_name] > 1
|
||||
tab["direccion"] = np.where(risk, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
|
||||
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
|
||||
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1))
|
||||
tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1)
|
||||
robust = min(3, len(evaluated))
|
||||
tab["clasificacion"] = [
|
||||
UNKNOWN_CLASS
|
||||
if cat == unknown
|
||||
else f"{d} robusto"
|
||||
if c1 and k >= robust
|
||||
else f"{d} sugerente"
|
||||
if k >= 2
|
||||
else "no concluyente"
|
||||
for cat, d, c1, k in zip(
|
||||
tab["categoria"],
|
||||
tab["direccion"],
|
||||
tab["c1_or"],
|
||||
tab["criterios_cumplidos"],
|
||||
strict=True,
|
||||
)
|
||||
]
|
||||
return tab
|
||||
|
||||
|
||||
def presence(share: float) -> str:
|
||||
if share >= DEFINING:
|
||||
return "definitoria"
|
||||
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
|
||||
|
||||
|
||||
def listing(part: pd.DataFrame) -> str:
|
||||
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
|
||||
`asociacion`."""
|
||||
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
|
||||
part["clasificacion"].str.split().str[-1]) # fmt: skip
|
||||
return "; ".join(
|
||||
f"{v}={c} ({s}, {p:.0%})"
|
||||
for v, c, s, p in zip(
|
||||
part["variable"], part["categoria"], strength, part["share"], strict=True
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def classified(factors: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
|
||||
riesgo, protector or tratamiento."""
|
||||
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
|
||||
kind = np.where(
|
||||
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
|
||||
)
|
||||
return found.assign(tipo_efecto=kind)
|
||||
|
||||
|
||||
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
|
||||
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
|
||||
the listings by kind and presence, and how many risk factors describe it."""
|
||||
share = [
|
||||
float((frame.loc[mask, v] == c).mean())
|
||||
for v, c in zip(found["variable"], found["categoria"], strict=True)
|
||||
]
|
||||
detail = found.assign(share=share, presence=[presence(s) for s in share])
|
||||
row = {}
|
||||
for k in ("riesgo", "protector", "tratamiento"):
|
||||
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
|
||||
row[f"{k}_{label}"] = listing(
|
||||
detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)]
|
||||
)
|
||||
included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING)
|
||||
row["n_factores_riesgo_incluidos"] = int(included.sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
return row
|
||||
+537
@@ -0,0 +1,537 @@
|
||||
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||
places what the targets staged into silver."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from functools import cache
|
||||
|
||||
import duckdb
|
||||
import ocrmypdf
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pikepdf
|
||||
import splink.comparison_library as cl
|
||||
from markitdown import MarkItDown
|
||||
from openai import OpenAI, OpenAIError
|
||||
from splink import Linker, SettingsCreator, block_on
|
||||
from splink.backends.duckdb import DuckDBAPI
|
||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.pipeline import (
|
||||
HELD,
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
RECORD,
|
||||
Extract,
|
||||
Fhir,
|
||||
Join,
|
||||
Link,
|
||||
Map,
|
||||
Pipeline,
|
||||
Read,
|
||||
Route,
|
||||
Target,
|
||||
answer_schema,
|
||||
apply_patterns,
|
||||
ground,
|
||||
join,
|
||||
map_row,
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from persistance import config_log, files, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
||||
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||
"text": {"data_type": "text", "nullable": True},
|
||||
"ocr": {"data_type": "bool"},
|
||||
"error": {"data_type": "text", "nullable": True},
|
||||
"format": {"data_type": "text", "nullable": True},
|
||||
}
|
||||
|
||||
|
||||
def file_format(content: bytes) -> str:
|
||||
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
|
||||
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
|
||||
version is "0"), or other (whatever MarkItDown reads)."""
|
||||
if content.startswith(b"%PDF"):
|
||||
return "pdf"
|
||||
head = content[:256]
|
||||
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
|
||||
return "edf"
|
||||
return "other"
|
||||
|
||||
|
||||
@cache
|
||||
def _reader() -> MarkItDown:
|
||||
return MarkItDown()
|
||||
|
||||
|
||||
def _lines(text: str) -> str:
|
||||
"""Non-empty lines, with the spacing inside each collapsed."""
|
||||
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
|
||||
|
||||
|
||||
def _text(content: bytes) -> str:
|
||||
"""Files other than PDFs, through MarkItDown."""
|
||||
return _reader().convert_stream(io.BytesIO(content)).text_content
|
||||
|
||||
|
||||
def _pdf_pages(content: bytes) -> list[str]:
|
||||
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
|
||||
on one line each (spacing within a line collapsed)."""
|
||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
|
||||
|
||||
|
||||
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
|
||||
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
|
||||
copied into a PDF of their own: a typed page keeps its own text layer."""
|
||||
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
|
||||
for n in numbers:
|
||||
scans.pages.append(source.pages[n])
|
||||
pages, sidecar = io.BytesIO(), io.BytesIO()
|
||||
scans.save(pages)
|
||||
pages.seek(0)
|
||||
ocrmypdf.ocr(
|
||||
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
|
||||
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
|
||||
) # fmt: skip
|
||||
found = sidecar.getvalue().decode().split("\f")
|
||||
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
|
||||
|
||||
|
||||
def read_file(content: bytes) -> dict:
|
||||
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps
|
||||
its error; a signal recording (EDF) has no text to read."""
|
||||
kind = file_format(content)
|
||||
if kind == "edf":
|
||||
return {"text": None, "ocr": False, "error": None, "format": kind}
|
||||
return {**_read_text(content), "format": kind}
|
||||
|
||||
|
||||
def _read_text(content: bytes) -> dict:
|
||||
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
|
||||
typed form whose second page is a scan, say)."""
|
||||
try:
|
||||
if not content.startswith(b"%PDF"):
|
||||
return {"text": _text(content), "ocr": False, "error": None}
|
||||
pages = _pdf_pages(content)
|
||||
scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
|
||||
if scanned:
|
||||
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
|
||||
pages[i] = page
|
||||
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
|
||||
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
|
||||
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
def run_read(p: str, node: Read):
|
||||
"""The input's rows with their file's text and format beside the file column (which
|
||||
keeps the file, for a study that takes the file itself: an EEG's recording); each file
|
||||
read once."""
|
||||
rows = list(nodes.rows(p, node.inputs[0]))
|
||||
for row in rows: # the source kept the file; the row carries its hash
|
||||
row["key"] = row.get(node.column) or None
|
||||
keys = {r["key"] for r in rows} - {None}
|
||||
found = nodes.cached("read_cache", keys)
|
||||
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats
|
||||
for k in legacy:
|
||||
found[k]["format"] = file_format(files.content(k) or b"")
|
||||
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
|
||||
for k in legacy], READ_COLUMNS) # fmt: skip
|
||||
new = sorted(keys - set(found))
|
||||
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept
|
||||
for start in range(0, len(new), READ_BATCH):
|
||||
batch = new[start : start + READ_BATCH]
|
||||
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
|
||||
strict=True)) # fmt: skip
|
||||
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
|
||||
READ_COLUMNS) # fmt: skip
|
||||
found |= read
|
||||
for row in rows:
|
||||
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||
row |= {k: result[k] for k in READ_COLUMNS}
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
|
||||
|
||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||
"""The input's rows the route takes; an `otherwise` route, those `others` don't."""
|
||||
rows = nodes.rows(p, node.inputs[0])
|
||||
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
|
||||
return nodes.write(p, node.id, taken)
|
||||
|
||||
|
||||
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
|
||||
"""The node's ConceptMap as a translation table per field (none without one)."""
|
||||
if node.concept_map is None:
|
||||
return {}
|
||||
found = config_log.concept_map(node.concept_map)
|
||||
return {f: concept_map.table([found], f) for f in fields}
|
||||
|
||||
|
||||
def run_map(p: str, node: Map):
|
||||
codes = _codes(node, node.fields)
|
||||
rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])]
|
||||
return nodes.write(p, node.id, rows)
|
||||
|
||||
|
||||
def run_fhir(p: str, node: Fhir):
|
||||
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
|
||||
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
|
||||
found: dict[str, dict] = {}
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
bundle = json.loads(row[node.column])
|
||||
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||
found[r[RECORD]] = r
|
||||
return nodes.write(p, node.id, list(found.values()))
|
||||
|
||||
|
||||
def run_join(p: str, node: Join):
|
||||
left, right = (list(nodes.rows(p, i)) for i in node.inputs)
|
||||
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||
|
||||
|
||||
@cache
|
||||
def _llm() -> tuple[OpenAI, str] | None:
|
||||
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
||||
if not (url := os.environ.get("LLM_URL")):
|
||||
return None
|
||||
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
||||
try:
|
||||
client.models.list()
|
||||
except OpenAIError:
|
||||
return None
|
||||
return client, os.environ["LLM_MODEL"]
|
||||
|
||||
|
||||
PROMPT = (
|
||||
"Extract every {entity} record stated in the document. For each field give its value "
|
||||
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
||||
"copied character by character. Leave out fields the document does not state.{hints}"
|
||||
)
|
||||
|
||||
|
||||
def _ask_llm(node: Extract, text: str) -> dict:
|
||||
client, model = _llm()
|
||||
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
||||
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
||||
if found := nodes.cached("llm_cache", {key}):
|
||||
return json.loads(found[key]["answer"])
|
||||
reply = client.chat.completions.create(
|
||||
model=model, temperature=0, seed=7,
|
||||
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||
response_format={"type": "json_schema", "json_schema": {
|
||||
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
||||
) # fmt: skip
|
||||
answer = reply.choices[0].message.content
|
||||
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||
return json.loads(answer)
|
||||
|
||||
|
||||
def run_extract(p: str, node: Extract):
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||
codes = _codes(node, node.patterns)
|
||||
out = []
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
text = node.text(row)
|
||||
if use_llm:
|
||||
found = ground(_ask_llm(node, text), text)
|
||||
elif node.patterns:
|
||||
found = apply_patterns(node, text, codes)
|
||||
else:
|
||||
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
|
||||
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||
out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
|
||||
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
||||
HELD: json.dumps(held) if held else None}) # fmt: skip
|
||||
return nodes.write(p, node.id, out)
|
||||
|
||||
|
||||
def _comparison(field: str):
|
||||
if field == "birth_date":
|
||||
return cl.DateOfBirthComparison(field, input_is_string=True)
|
||||
if field == "full_name":
|
||||
return cl.NameComparison(field)
|
||||
if field in ("record_number", "curp", "nss"):
|
||||
return cl.LevenshteinAtThresholds(field, [1, 2])
|
||||
return cl.ExactMatch(field)
|
||||
|
||||
|
||||
def _plain(identifier: str) -> str:
|
||||
"""An identifier as compared: letters and digits only, upper case."""
|
||||
return "".join(ch for ch in identifier if ch.isalnum()).upper()
|
||||
|
||||
|
||||
def _name(name: str) -> str:
|
||||
"""A name as compared: upper case, without accents, single spaces."""
|
||||
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
|
||||
return " ".join(plain.upper().split())
|
||||
|
||||
|
||||
def _near(identifier: str) -> list[str]:
|
||||
"""The identifier and every version of it with one character left out: two identifiers
|
||||
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
|
||||
return sorted(
|
||||
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))}
|
||||
)
|
||||
|
||||
|
||||
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]:
|
||||
"""One row per record: its identity fields (first value found, reviewers' corrections
|
||||
applied, identifiers plain); records rejected for identity are left out. And the input
|
||||
each record came through (its record number's system), and its name as written."""
|
||||
skip, fixed = nodes.rejected("identity"), nodes.corrections()
|
||||
records: dict[str, dict] = {}
|
||||
sources: dict[str, str] = {}
|
||||
written: dict[str, str] = {} # each record's name as it came (compared normalised)
|
||||
for i in node.inputs:
|
||||
for row in nodes.rows(p, i):
|
||||
if row.get(HELD) or row[RECORD] in skip:
|
||||
continue
|
||||
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
|
||||
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
|
||||
sources.setdefault(row[RECORD], i)
|
||||
for f in node.fields:
|
||||
if row.get(f) is not None and mine.get(f) is None:
|
||||
value = str(row[f])
|
||||
if f == "full_name":
|
||||
written[row[RECORD]] = " ".join(value.split())
|
||||
mine[f] = (
|
||||
_plain(value) if f in IDENTIFIERS
|
||||
else _name(value) if f == "full_name" else value
|
||||
) # fmt: skip
|
||||
frame = pd.DataFrame(list(records.values()))
|
||||
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
|
||||
return frame[["unique_id", *present]], sources, written
|
||||
|
||||
|
||||
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
|
||||
"""Each record's stand-in: one record per identity that the rules join to itself (a
|
||||
patient's 24 reports carrying one record number are one row to compare, not 24² pairs).
|
||||
A record a reviewer judged stands for itself, and so does one the rules would not join
|
||||
to an identical record (nothing compared was read, say)."""
|
||||
fields = [c for c in records.columns if c != "unique_id"]
|
||||
key = records[fields].astype(object).where(records[fields].notna(), None)
|
||||
same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index)
|
||||
stand_in = records.groupby(same, sort=False)["unique_id"].transform("first")
|
||||
stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"])
|
||||
joined = set()
|
||||
if rules:
|
||||
con = duckdb.connect()
|
||||
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
|
||||
joins = " or ".join(f"({r})" for r in rules)
|
||||
joined = set(con.sql(
|
||||
f"select l.unique_id from candidates l join candidates r"
|
||||
f" on l.unique_id = r.unique_id where {joins}"
|
||||
).df()["unique_id"]) # fmt: skip
|
||||
return stand_in.where(stand_in.isin(joined), records["unique_id"])
|
||||
|
||||
|
||||
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
|
||||
clusters = cluster_pairwise_predictions_at_threshold(
|
||||
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
|
||||
)
|
||||
return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records)
|
||||
|
||||
|
||||
def run_link(p: str, node: Link):
|
||||
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
|
||||
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
|
||||
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
|
||||
don't contradict each other are queued for review, with Splink's probability. A person
|
||||
with nothing that names her (no name, birth date or record number read) is held too."""
|
||||
records, sources, written = _identities(p, node)
|
||||
fields = [c for c in records.columns if c != "unique_id"]
|
||||
rules = [r for r in node.rules or node.default_rules()
|
||||
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
|
||||
comparisons = [_comparison(f) for f in fields]
|
||||
decided = nodes.person_decisions()
|
||||
stand_in = _distinct(records, rules, set().union(*decided))
|
||||
distinct = records[records["unique_id"].isin(set(stand_in))]
|
||||
db = DuckDBAPI()
|
||||
linker = Linker(
|
||||
db.register(distinct),
|
||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||
blocking_rules_to_generate_predictions=rules),
|
||||
log_level=None,
|
||||
) # fmt: skip
|
||||
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
||||
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
|
||||
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
|
||||
known = set(distinct.unique_id)
|
||||
edges = pd.DataFrame(
|
||||
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
|
||||
)
|
||||
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
|
||||
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
|
||||
|
||||
facts = [f for f in ("birth_date", "sex") if f in fields]
|
||||
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
|
||||
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
|
||||
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
|
||||
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
|
||||
nameless = set(read[read == 0].index)
|
||||
why = {c: "records of this person disagree on birth date or sex" for c in torn}
|
||||
why |= {c: "no name, birth date or record number was read" for c in nameless - torn}
|
||||
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
|
||||
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
|
||||
linked = [
|
||||
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
|
||||
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
|
||||
**{f: getattr(r, f) for f in fields},
|
||||
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
|
||||
for r in persons.itertuples()
|
||||
] # fmt: skip
|
||||
nodes.write(p, node.id, linked, columns)
|
||||
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person
|
||||
|
||||
# One row per person, so random pairs are different people and Splink's u is honest.
|
||||
ids = [f for f in IDENTIFIERS if f in fields]
|
||||
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
|
||||
for f in ids:
|
||||
near = (
|
||||
persons.dropna(subset=[f])
|
||||
.groupby("cluster_id")[f]
|
||||
.agg(lambda values: sorted({n for v in values for n in _near(v)}))
|
||||
)
|
||||
whole[f"{f}_near"] = near.reindex(whole.index).apply(
|
||||
lambda v: v if isinstance(v, list) else []
|
||||
)
|
||||
whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"})
|
||||
blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids]
|
||||
reasons = [f"{f} one typo apart" for f in ids]
|
||||
if "birth_date" in fields:
|
||||
blocks.append(block_on("birth_date"))
|
||||
reasons.append("same birth date")
|
||||
model = Linker(
|
||||
db.register(whole),
|
||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||
blocking_rules_to_generate_predictions=blocks),
|
||||
log_level=None,
|
||||
) # fmt: skip
|
||||
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
|
||||
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
|
||||
|
||||
known = [f for f in ("birth_date", "sex") if f in fields]
|
||||
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
||||
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
|
||||
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
|
||||
# Answers are kept by record; a person is known by any of hers, whatever joined since.
|
||||
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
|
||||
answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
|
||||
lone = set() # persons whose identifier is carried by one record only
|
||||
for f in ids:
|
||||
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||
lone |= {person for (person, _), n in carried.items() if n == 1}
|
||||
|
||||
def settle(r) -> tuple[str, str] | None:
|
||||
"""(the person to settle, a possible owner), or None when the pair is implausible:
|
||||
they contradict each other, or one typo apart is all they share (with sequential
|
||||
record numbers every patient has such neighbours) unless one side has no
|
||||
demographics and the other's identifier stands on a single record. Names one typo
|
||||
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
|
||||
very same identifier on a record that says nothing else (a scan read only in part)."""
|
||||
a, b = r.unique_id_l, r.unique_id_r
|
||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||
if frozenset((a, b)) in answered or any(
|
||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||
):
|
||||
return None
|
||||
reason = reasons[int(r.match_key)]
|
||||
if not reason.endswith("typo apart"):
|
||||
return a, b
|
||||
field = reason.removesuffix(" one typo apart")
|
||||
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier
|
||||
return (a, b) if a in undated or b not in undated else (b, a)
|
||||
if field == "full_name" and (a in undated) != (b in undated):
|
||||
return (a, b) if a in undated else (b, a) # names are rarely one typo apart
|
||||
if a in orphan and b in lone:
|
||||
return a, b
|
||||
if b in orphan and a in lone:
|
||||
return b, a
|
||||
return None
|
||||
|
||||
side = {r.unique_id: r for r in whole.itertuples()}
|
||||
queue = []
|
||||
for r in found.itertuples():
|
||||
if pair := settle(r):
|
||||
person, owner = pair
|
||||
queue.append(
|
||||
{
|
||||
"person": person,
|
||||
"candidate": owner,
|
||||
"probability": r.match_probability,
|
||||
"reason": reasons[int(r.match_key)],
|
||||
**{f"person_{f}": getattr(side[person], f) for f in fields},
|
||||
**{f"candidate_{f}": getattr(side[owner], f) for f in fields},
|
||||
}
|
||||
)
|
||||
return nodes.write(p, f"{node.id}__review", queue)
|
||||
|
||||
|
||||
def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
"""Rows of one study into silver's staging, each given its person by the link node:
|
||||
a clean row becomes one observation per field it has (long), keyed by its study
|
||||
instance (the study's key values); a row a rule held waits for review, whole."""
|
||||
link = next(i for i in node.inputs if kinds[i] == "link")
|
||||
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
||||
person = {k: r["person_id"] for k, r in linked.items()}
|
||||
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
||||
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
|
||||
observations, held_rows = [], []
|
||||
for i in (i for i in node.inputs if i != link):
|
||||
for row in nodes.rows(p, i):
|
||||
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
||||
values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
|
||||
if f in model.model_fields} # fmt: skip
|
||||
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
||||
if row[RECORD] not in person:
|
||||
held.append("no identity linked to this record")
|
||||
else:
|
||||
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
|
||||
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
|
||||
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
|
||||
if held:
|
||||
raw = json.dumps(values, default=str, ensure_ascii=False)
|
||||
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
|
||||
continue
|
||||
clean = model.model_validate(values)
|
||||
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||
for name, field in study.fields.items():
|
||||
if (value := getattr(clean, name)) is not None:
|
||||
observations.append({**base, "instance": instance, "field": name,
|
||||
catalog.value_column(field): value}) # fmt: skip
|
||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||
|
||||
|
||||
RUNNERS: dict[str, Callable] = {
|
||||
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
|
||||
"join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
|
||||
kinds = {n.id: n.kind for n in pipeline.nodes}
|
||||
for node in pipeline.order():
|
||||
if node.kind == "target":
|
||||
run_target(pipeline_id, node, kinds)
|
||||
elif node.kind == "route" and node.otherwise:
|
||||
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
|
||||
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
|
||||
run_route(pipeline_id, node, others)
|
||||
else:
|
||||
RUNNERS[node.kind](pipeline_id, node)
|
||||
log(f"{node.id} ({node.kind}) done")
|
||||
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||
log(f"silver and gold, from {', '.join(entities)}")
|
||||
@@ -1 +0,0 @@
|
||||
"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes."""
|
||||
@@ -1,134 +0,0 @@
|
||||
"""The shapes of the data the pipelines read and write. Nothing here reads or writes.
|
||||
|
||||
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
|
||||
every row.
|
||||
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
|
||||
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
|
||||
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
|
||||
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
||||
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
|
||||
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
||||
Persistance's `PROVENANCE` expects.
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date
|
||||
from typing import NamedTuple, Protocol, runtime_checkable
|
||||
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
import pyarrow as pa
|
||||
|
||||
COHORT_SCHEMA = pa.schema([
|
||||
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
|
||||
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
|
||||
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
|
||||
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
|
||||
])
|
||||
|
||||
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
|
||||
|
||||
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
|
||||
# schema says which columns and types; these say what a valid row and a valid file are.
|
||||
COHORT_FRAME = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"fecha": pandera.Column(nullable=False),
|
||||
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||
"fuente_tabla": pandera.Column(str, nullable=False),
|
||||
"fuente_id": pandera.Column(str, nullable=False)},
|
||||
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
|
||||
error="a member has more than one index date"),
|
||||
name="cohort build")
|
||||
|
||||
ESTIMATE_FRAME = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
||||
strict=True, ordered=True, name="estimate")
|
||||
|
||||
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
|
||||
|
||||
|
||||
class CohortFileError(ValueError):
|
||||
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
|
||||
`COHORT_FRAME`."""
|
||||
|
||||
|
||||
class EstimateError(ValueError):
|
||||
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
|
||||
|
||||
|
||||
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
|
||||
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
|
||||
try:
|
||||
return schema.validate(frame, lazy=True)
|
||||
except pandera.errors.SchemaErrors as failed:
|
||||
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
|
||||
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
|
||||
|
||||
|
||||
class CohortDefinitionError(ValueError):
|
||||
"""The cohort's queries or their results don't follow the structure a build chains."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExclusionRule:
|
||||
name: str
|
||||
description: str
|
||||
order: int
|
||||
sql: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortQueries:
|
||||
url: str
|
||||
all_patients: str
|
||||
index_date: str
|
||||
rules: tuple[ExclusionRule, ...]
|
||||
cutoff: date
|
||||
parameters: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BuiltCohort:
|
||||
"""The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step."""
|
||||
|
||||
study_population: pd.DataFrame
|
||||
attrition: pd.DataFrame
|
||||
|
||||
|
||||
class Risk(NamedTuple):
|
||||
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
|
||||
|
||||
pac_id: int
|
||||
horizonte_anios: float # years from the index date; 0 = prevalent
|
||||
probabilidad: float # 0 to 1
|
||||
ic_bajo: float | None = None
|
||||
ic_alto: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Provenance:
|
||||
"""Which model the risks come from: the keys a batch stores."""
|
||||
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
mlflow_run_id: str
|
||||
modelo_sha: str
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class RiskEstimator(Protocol):
|
||||
"""What every risk model the orchestration can call provides."""
|
||||
|
||||
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
|
||||
outcome: str # what it predicts ("cin2_mas")
|
||||
|
||||
def provenance(self) -> Provenance: ...
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
|
||||
@@ -1,180 +0,0 @@
|
||||
"""Each domain's extraction ranker (`extraction.nlp.ranking.LearnedRanker`), versioned in the model registry as
|
||||
`<domain>-extraccion` like any other model (ML-01a, ML-01b, ML-02).
|
||||
|
||||
Every batch it learns from, whether an answer key or the corrections made while reviewing an import, becomes a new
|
||||
DEV version. That version continues from the latest one, and its run records the five routines of what it learned.
|
||||
Extraction uses the version in production when there is one, and otherwise the latest. `EXTRACTION_RANKER` changes
|
||||
that: `produccion` only takes a version in production, and `ninguno` turns the ranker off.
|
||||
|
||||
What it stores are weights over how candidates were found, never document text, and the routines carry counts only.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
import mlflow.artifacts
|
||||
import mlflow.pyfunc
|
||||
from extraction.nlp.ranking import TRUST_EXAMPLES, Example, LearnedRanker
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
SCENARIO = "extraccion"
|
||||
RANKER_PATH = "ranker/ranker.json"
|
||||
SELECTION_ENV = "EXTRACTION_RANKER"
|
||||
SOURCE_TAG = "ranker.fuente"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache: dict[tuple[str, str], LearnedRanker] = {}
|
||||
|
||||
|
||||
class RankerModel(mlflow.pyfunc.PythonModel):
|
||||
"""The ranker as a pyfunc: `predict` takes rows of named features (a DataFrame column `features` of dicts, or a
|
||||
list of dicts) and returns the probability that each candidate is the right value."""
|
||||
|
||||
def __init__(self, state: dict[str, Any]):
|
||||
self.state = state
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
ranker = LearnedRanker.from_dict(self.state)
|
||||
rows = model_input["features"].tolist() if hasattr(model_input, "columns") else list(model_input)
|
||||
return [ranker.probability(row) for row in rows]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Batch:
|
||||
"""What one learning step saw: the examples, and counts for its routine records."""
|
||||
|
||||
examples: Sequence[Example]
|
||||
source: str
|
||||
documents: int
|
||||
records: int
|
||||
# Per field, how many records had a right value that no candidate proposed.
|
||||
unreachable: dict[str, int]
|
||||
|
||||
|
||||
def _versions(client: MlflowClient, domain: str) -> list:
|
||||
try:
|
||||
return sorted(client.search_model_versions(f"name='{registered_name(domain, SCENARIO)}'"), key=lambda mv: int(mv.version))
|
||||
except MlflowException:
|
||||
return []
|
||||
|
||||
|
||||
def _selected(client: MlflowClient, domain: str, *, for_learning: bool = False):
|
||||
from models.io.registry import PRODUCTION_ALIAS
|
||||
|
||||
mode = os.environ.get(SELECTION_ENV, "auto").strip().lower()
|
||||
if mode == "ninguno" and not for_learning:
|
||||
return None
|
||||
if not for_learning:
|
||||
try:
|
||||
return client.get_model_version_by_alias(registered_name(domain, SCENARIO), PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
if mode == "produccion":
|
||||
return None
|
||||
versions = _versions(client, domain)
|
||||
return versions[-1] if versions else None
|
||||
|
||||
|
||||
def _load(client: MlflowClient, domain: str, mv) -> LearnedRanker:
|
||||
key = (domain, str(mv.version))
|
||||
if key not in _cache:
|
||||
state = mlflow.artifacts.load_dict(f"runs:/{mv.run_id}/{RANKER_PATH}")
|
||||
_cache[key] = LearnedRanker.from_dict(state, version=f"{SCENARIO}:{mv.version}")
|
||||
return _cache[key].copy()
|
||||
|
||||
|
||||
def current(domain: str) -> LearnedRanker | None:
|
||||
"""The ranker extraction should use for `domain`, or `None` to rank by confidence alone."""
|
||||
if os.environ.get(SELECTION_ENV, "").strip().lower() == "ninguno":
|
||||
return None
|
||||
client = MlflowClient()
|
||||
mv = _selected(client, domain)
|
||||
return _load(client, domain, mv) if mv is not None else None
|
||||
|
||||
|
||||
def learn(domain: str, batch: Batch) -> str | None:
|
||||
"""Continues the latest version with `batch` and registers the result as a new DEV version; returns it, or
|
||||
`None` when the batch has nothing to learn from."""
|
||||
from models.io.registry import registry
|
||||
|
||||
if not batch.examples:
|
||||
return None
|
||||
with _lock:
|
||||
client = MlflowClient()
|
||||
parent = _selected(client, domain, for_learning=True)
|
||||
ranker = _load(client, domain, parent) if parent is not None else LearnedRanker()
|
||||
before = _quality(ranker, batch.examples)
|
||||
ranker.learn(batch.examples)
|
||||
after = _quality(ranker, batch.examples)
|
||||
run = TrainingRun(domain=domain, scenario=SCENARIO, environment="DEV")
|
||||
client.set_tag(run.run_id, SOURCE_TAG, batch.source)
|
||||
state = ranker.to_dict()
|
||||
client.log_dict(run.run_id, state, RANKER_PATH)
|
||||
for kind, record in _routines(ranker, batch, parent, before, after).items():
|
||||
run.log_routine(kind, record)
|
||||
run.log_model(RankerModel(state))
|
||||
run.finish(
|
||||
metrics={"ejemplos": len(batch.examples), "ejemplos_acumulados": ranker.examples,
|
||||
**{f"{k}_antes": v for k, v in before.items()}, **{f"{k}_despues": v for k, v in after.items()}},
|
||||
hyperparameters={"tasa_aprendizaje": ranker.learning_rate, "l2": ranker.l2, "ejemplos_confianza_plena": TRUST_EXAMPLES},
|
||||
)
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def _quality(ranker: LearnedRanker, examples: Iterable[Example]) -> dict[str, float]:
|
||||
"""Brier score, log loss and accuracy at even odds of the ranker's probabilities on `examples`. Measured before
|
||||
learning from them, it is an honest estimate on data the ranker had not seen (prequential evaluation)."""
|
||||
examples = list(examples)
|
||||
brier = loss = right = 0.0
|
||||
for example in examples:
|
||||
p = ranker.probability(example.x)
|
||||
y = 1.0 if example.label else 0.0
|
||||
brier += (p - y) ** 2
|
||||
loss -= math.log(max(1e-12, p if example.label else 1.0 - p))
|
||||
right += float((p >= 0.5) == example.label)
|
||||
n = max(1, len(examples))
|
||||
return {"brier": round(brier / n, 4), "log_loss": round(loss / n, 4), "exactitud": round(right / n, 4)}
|
||||
|
||||
|
||||
def _routines(ranker: LearnedRanker, batch: Batch, parent, before: dict, after: dict) -> dict[str, dict[str, Any]]:
|
||||
by_field: dict[str, dict[str, int]] = {}
|
||||
for example in batch.examples:
|
||||
counts = by_field.setdefault(example.field, {"correctos": 0, "incorrectos": 0})
|
||||
counts["correctos" if example.label else "incorrectos"] += 1
|
||||
positives = sum(1 for e in batch.examples if e.label)
|
||||
negatives = len(batch.examples) - positives
|
||||
return {
|
||||
"MUESTREO": {
|
||||
"fuente": batch.source,
|
||||
"documentos": batch.documents,
|
||||
"registros": batch.records,
|
||||
"ejemplos": len(batch.examples),
|
||||
"criterio": "cada lectura propuesta de un campo cuyo valor correcto se conoce es un ejemplo",
|
||||
"por_campo": by_field,
|
||||
},
|
||||
"DATOS_FALTANTES": {
|
||||
"tratamiento": "un campo sin valor conocido no aporta ejemplos; uno que debe quedar vacío marca como incorrectas todas sus lecturas",
|
||||
"valor_correcto_sin_lectura": batch.unreachable,
|
||||
},
|
||||
"METODO_ANALITICO": {
|
||||
"metodo": "regresión logística en línea (AdaGrad con L2) sobre cómo se encontró cada lectura",
|
||||
"version_previa": parent.version if parent is not None else None,
|
||||
"ejemplos_acumulados": ranker.examples,
|
||||
"pesos_principales": dict(ranker.strongest()),
|
||||
},
|
||||
"BALANCE_CLASES": {
|
||||
"correctos": positives,
|
||||
"incorrectos": negatives,
|
||||
"ponderacion": "los correctos pesan incorrectos/correctos, hasta 5",
|
||||
},
|
||||
"CONFIANZA_SALIDA": {
|
||||
"antes_de_aprender": before,
|
||||
"despues_de_aprender": after,
|
||||
"confianza_en_el_modelo": round(ranker.trust, 3),
|
||||
"nota": "antes de aprender mide lecturas que el modelo no había visto",
|
||||
},
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under,
|
||||
the keys lineage is recorded with, the hashes that identify code, data and models, and the rule that an output already
|
||||
exists when its recorded lineage matches what's expected.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
ARMADO_TAG = "kit.armado_id"
|
||||
MODEL_SHA_TAG = "modelo_sha"
|
||||
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
|
||||
GIT_DIRTY_TAG = "models.git.dirty"
|
||||
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
|
||||
COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source"
|
||||
COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256"
|
||||
|
||||
|
||||
def registered_name(domain: str, scenario: str) -> str:
|
||||
return f"{domain}-{scenario}"
|
||||
|
||||
|
||||
def code_version() -> dict[str, str]:
|
||||
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
|
||||
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
|
||||
nothing is recorded."""
|
||||
root = Path(__file__).resolve().parent
|
||||
try:
|
||||
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
|
||||
check=True).stdout.strip()
|
||||
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
commit = os.environ.get(GIT_COMMIT_ENV)
|
||||
return {GIT_COMMIT_TAG: commit} if commit else {}
|
||||
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
|
||||
|
||||
|
||||
def model_sha(model_dir: str | Path) -> str:
|
||||
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
|
||||
out because it carries ids and dates, so the same model saved twice has the same sha."""
|
||||
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
|
||||
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
|
||||
`dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
|
||||
build, numbered by its `armado_id`."""
|
||||
source = "dbt" if metadata.get("producer") == "dbt" else "kit"
|
||||
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
|
||||
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
|
||||
COHORT_FILE_TAG: file_sha256}
|
||||
|
||||
|
||||
def file_sha256(*paths: str | Path) -> str:
|
||||
"""The hash of these files' bytes, in this order."""
|
||||
digest = hashlib.sha256()
|
||||
for path in paths:
|
||||
digest.update(Path(path).read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def table_sha256(table: pa.Table) -> str:
|
||||
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
|
||||
sink = pa.BufferOutputStream()
|
||||
table = table.replace_schema_metadata(None)
|
||||
with pa.ipc.new_stream(sink, table.schema) as stream:
|
||||
stream.write_table(table)
|
||||
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
|
||||
|
||||
|
||||
def matches(recorded: dict, expected: dict) -> bool:
|
||||
"""Whether an output's recorded lineage has every expected value: then it is already done."""
|
||||
return all(str(recorded.get(key)) == str(value) for key, value in expected.items())
|
||||
|
||||
|
||||
def require_match(recorded: dict, expected: dict, what: str) -> None:
|
||||
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
|
||||
if not matches(recorded, expected):
|
||||
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
|
||||
@@ -1,137 +0,0 @@
|
||||
"""Copies what a notebook trained, in its job's own MLflow store, into the platform's (ML-02, ML-03).
|
||||
|
||||
The notebook wrote that store itself, so nothing in it is taken at its word. Only runs of the job's domain
|
||||
(`<domain>-<scenario>` experiments) come across; each becomes a new run tagged DEV, with the cohort reference of the
|
||||
build the job actually had, the notebook's run (`notebook.run_id`) and the model's hash computed here. Registered
|
||||
versions come across as DEV versions of their run, never with an alias, so a notebook can't put anything in
|
||||
production. Files are copied by walking the job folder without following symbolic links, and the store is opened
|
||||
from a copy, so nothing outside the job folder is ever read.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import Metric, Param
|
||||
|
||||
from models.io.lineage import MODEL_SHA_TAG, code_version, model_sha
|
||||
from models.io.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
|
||||
from models.io.tracking import MODEL_PATH, experiment_id
|
||||
|
||||
NOTEBOOK_RUN_TAG = "notebook.run_id"
|
||||
# Above this many bytes of files across a job's runs, nothing more is copied.
|
||||
MAX_IMPORT_BYTES_ENV = "NOTEBOOK_MAX_IMPORT_MB"
|
||||
MAX_IMPORT_MB = 500
|
||||
KEPT_SYSTEM_TAGS = ("mlflow.note.content",)
|
||||
|
||||
|
||||
def import_job(job: Path, notebook_run_id: str, domain: str, cohort: dict[str, str]) -> dict[str, Any]:
|
||||
"""Imports the job's runs and versions; returns what came across and what was left out, and why."""
|
||||
summary: dict[str, Any] = {"runs": [], "versions": [], "skipped": []}
|
||||
data = read_job_file(job, STORE_FILE)
|
||||
if not data:
|
||||
return summary
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-store-") as tmp:
|
||||
copy = Path(tmp) / STORE_FILE
|
||||
copy.write_bytes(data)
|
||||
local = MlflowClient(tracking_uri=f"sqlite:///{copy}", registry_uri=f"sqlite:///{copy}")
|
||||
target = MlflowClient()
|
||||
budget = int(os.environ.get(MAX_IMPORT_BYTES_ENV, MAX_IMPORT_MB)) * 1024 * 1024
|
||||
runs: dict[str, str] = {}
|
||||
for experiment in local.search_experiments():
|
||||
if not re.fullmatch(rf"{domain}-[\w-]{{1,100}}", experiment.name):
|
||||
summary["skipped"].append({"experiment": experiment.name, "reason": "no es un escenario del dominio"})
|
||||
continue
|
||||
for run in local.search_runs([experiment.experiment_id]):
|
||||
try:
|
||||
new_id, budget = _copy_run(local, target, job, run, experiment.name, notebook_run_id, cohort, budget)
|
||||
except JobError as error:
|
||||
summary["skipped"].append({"run": run.info.run_id, "reason": str(error)})
|
||||
continue
|
||||
runs[run.info.run_id] = new_id
|
||||
summary["runs"].append({"run_id": new_id, "experiment": experiment.name})
|
||||
for model in local.search_registered_models():
|
||||
for version in local.search_model_versions(f"name='{model.name}'"):
|
||||
if version.run_id not in runs or not model.name.startswith(f"{domain}-"):
|
||||
summary["skipped"].append({"version": f"{model.name}:{version.version}",
|
||||
"reason": "su corrida no se importó"})
|
||||
continue
|
||||
summary["versions"].append(_copy_version(target, model.name, runs[version.run_id], notebook_run_id))
|
||||
return summary
|
||||
|
||||
|
||||
def _artifact_dir(job: Path, run) -> Path:
|
||||
uri = run.info.artifact_uri
|
||||
path = Path(unquote(urlparse(uri).path)) if "://" in uri else Path(uri)
|
||||
if not inside(job, path):
|
||||
raise JobError(f"los archivos de la corrida están fuera de la carpeta del trabajo: {uri}")
|
||||
return path
|
||||
|
||||
|
||||
def _files(job: Path, folder: Path) -> list[Path]:
|
||||
"""The regular files under `folder`, refusing any symbolic link."""
|
||||
found = []
|
||||
for base, folders, files in os.walk(folder, followlinks=False):
|
||||
for name in folders + files:
|
||||
path = Path(base) / name
|
||||
if path.is_symlink() or not inside(job, path):
|
||||
raise JobError(f"enlace simbólico en los archivos de la corrida: {path.name}")
|
||||
if name in files:
|
||||
found.append(path)
|
||||
return found
|
||||
|
||||
|
||||
def _copy_run(local: MlflowClient, target: MlflowClient, job: Path, run, experiment: str, notebook_run_id: str,
|
||||
cohort: dict[str, str], budget: int) -> tuple[str, int]:
|
||||
folder = _artifact_dir(job, run)
|
||||
files = _files(job, folder) if folder.exists() else []
|
||||
size = sum(path.stat().st_size for path in files)
|
||||
if size > budget:
|
||||
raise JobError(f"sus archivos ({size // 1_000_000} MB) exceden el límite de {MAX_IMPORT_BYTES_ENV}")
|
||||
tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.") or k in KEPT_SYSTEM_TAGS}
|
||||
tags.update({**cohort, **code_version(), "domain": experiment.split("-", 1)[0],
|
||||
"scenario": experiment.split("-", 1)[1], "environment": "DEV", NOTEBOOK_RUN_TAG: notebook_run_id})
|
||||
tags.pop(MODEL_SHA_TAG, None)
|
||||
tags.pop("kit.armado_id", None)
|
||||
new = target.create_run(experiment_id(target, experiment), tags=tags, run_name=run.info.run_name)
|
||||
new_id = new.info.run_id
|
||||
params = [Param(k, v) for k, v in run.data.params.items()]
|
||||
metrics = [Metric(m.key, m.value, m.timestamp, m.step) for key in run.data.metrics
|
||||
for m in local.get_metric_history(run.info.run_id, key)]
|
||||
for start in range(0, max(len(params), len(metrics)), 100):
|
||||
target.log_batch(new_id, metrics=metrics[start:start + 100], params=params[start:start + 100])
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-files-") as staging:
|
||||
for path in files:
|
||||
destination = Path(staging) / path.relative_to(folder)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination, follow_symlinks=False)
|
||||
if files:
|
||||
target.log_artifacts(new_id, staging)
|
||||
if (Path(staging) / MODEL_PATH / "python_model.pkl").exists():
|
||||
target.set_tag(new_id, MODEL_SHA_TAG, model_sha(Path(staging) / MODEL_PATH))
|
||||
target.set_terminated(new_id, run.info.status if run.info.status in ("FINISHED", "FAILED") else "KILLED")
|
||||
return new_id, budget - size
|
||||
|
||||
|
||||
def _copy_version(target: MlflowClient, name: str, run_id: str, notebook_run_id: str) -> dict[str, str]:
|
||||
from mlflow import MlflowException
|
||||
|
||||
try:
|
||||
target.create_registered_model(name)
|
||||
except MlflowException as error:
|
||||
if error.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
run = target.get_run(run_id)
|
||||
keep = ("domain", "scenario", "environment", MODEL_SHA_TAG, "cohort.url", "cohort.source", "cohort.build",
|
||||
"cohort.file_sha256")
|
||||
tags = {k: run.data.tags[k] for k in keep if k in run.data.tags}
|
||||
tags[NOTEBOOK_RUN_TAG] = notebook_run_id
|
||||
has_model = MODEL_SHA_TAG in run.data.tags
|
||||
source = f"runs:/{run_id}/{MODEL_PATH}" if has_model else f"runs:/{run_id}"
|
||||
version = target.create_model_version(name, source=source, run_id=run_id, tags=tags)
|
||||
return {"name": name, "version": str(version.version), "run_id": run_id}
|
||||
@@ -1,268 +0,0 @@
|
||||
"""Where an uploaded notebook runs: a job folder, a runner and the executors that hand jobs to it (ML-04, ML-05).
|
||||
|
||||
A job is one folder named after the notebook's run, holding everything the notebook may see: the notebook
|
||||
(`notebook.ipynb`), a copy of the cohort build's file (`cohorte.parquet`), the chosen version's saved model
|
||||
(`model/`) and `job.json`. The notebook runs with that folder as its world: its MLflow is a throwaway store inside it
|
||||
(`mlflow.db`, `artefactos/`), and every database URL is an empty in-memory database. The runner writes the page
|
||||
(`page.html`) and `result.json`; what the notebook trained is imported afterwards by trusted code
|
||||
(`models.io.notebook_import`).
|
||||
|
||||
Executors are classes in `EXECUTORS`: `local` runs the job in this process, unsandboxed, for development;
|
||||
`contenedor` leaves it in `NOTEBOOK_JOBS_DIR` for the runner container (`python -m models notebooks serve`), which
|
||||
has no network and sees only that folder, and waits for its result. `NOTEBOOK_EXECUTOR` picks one; with
|
||||
`NOTEBOOK_JOBS_DIR` set the default is `contenedor`, otherwise `local`.
|
||||
|
||||
Whatever the notebook wrote is untrusted: files are read only through `read_job_file`, which refuses symbolic links
|
||||
and anything outside the job folder.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from models.io.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
|
||||
from models.notebook import COHORT_FILE_ENV, DOMAIN_ENV, MODEL_PATH_ENV, SCENARIO_ENV, VERSION_ENV
|
||||
|
||||
JOBS_DIR_ENV = "NOTEBOOK_JOBS_DIR"
|
||||
EXECUTOR_ENV = "NOTEBOOK_EXECUTOR"
|
||||
RUNNER_UID_ENV = "NOTEBOOK_RUNNER_UID"
|
||||
JOB_TIMEOUT_ENV = "NOTEBOOK_JOB_TIMEOUT"
|
||||
JOB_TIMEOUT = 6 * 3600
|
||||
POLL_SECONDS = 2
|
||||
|
||||
JOB_FILE, NOTEBOOK_FILE, COHORT_FILE, MODEL_DIR = "job.json", "notebook.ipynb", "cohorte.parquet", "model"
|
||||
STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos", "page.html", "result.json"
|
||||
CLAIM_DIR, WORK_DIR = "en_curso", "trabajo"
|
||||
KERNEL = "python3"
|
||||
# What a notebook inherits from the runner's environment; everything else is left out.
|
||||
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", "MODELS_GIT_COMMIT", CELL_TIMEOUT_ENV,
|
||||
"MLFLOW_DISABLE_TELEMETRY", "DO_NOT_TRACK", "MLFLOW_DISABLE_AGENT_HINT")
|
||||
DATABASE_ENVS = ("CACU_DATABASE_URL", "CAMA_DATABASE_URL", "TEA_DATABASE_URL", "GOVERNANCE_DATABASE_URL")
|
||||
EMPTY_DATABASE = "sqlite://"
|
||||
|
||||
|
||||
class JobError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _absolute(path: Path) -> str:
|
||||
"""The path as the job folder is reached, without resolving links on the way to it, so the trusted side and the
|
||||
notebook name its files the same way (`inside`)."""
|
||||
return os.path.abspath(path)
|
||||
|
||||
|
||||
def store_uri(job: Path) -> str:
|
||||
return f"sqlite:///{_absolute(job / STORE_FILE)}"
|
||||
|
||||
|
||||
def prepare_job(root: Path, run_id: str, notebook: dict, cohort_path: Path, *, domain: str, scenario: str,
|
||||
version: str | None, model_dir: Path | None = None) -> Path:
|
||||
"""Writes the job folder, complete or not at all: it's assembled beside the others and renamed into place, so the
|
||||
runner never picks up half a job."""
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
partial = Path(tempfile.mkdtemp(prefix=f".{run_id}-", dir=root))
|
||||
try:
|
||||
(partial / NOTEBOOK_FILE).write_text(json.dumps(with_kernel(notebook, KERNEL), ensure_ascii=False))
|
||||
shutil.copyfile(cohort_path, partial / COHORT_FILE)
|
||||
if model_dir is not None:
|
||||
shutil.copytree(model_dir, partial / MODEL_DIR)
|
||||
(partial / JOB_FILE).write_text(json.dumps({"run_id": run_id, "domain": domain, "scenario": scenario,
|
||||
"version": version}))
|
||||
_hand_over(partial)
|
||||
job = root / run_id
|
||||
partial.rename(job)
|
||||
except BaseException:
|
||||
shutil.rmtree(partial, ignore_errors=True)
|
||||
raise
|
||||
return job
|
||||
|
||||
|
||||
def _hand_over(folder: Path) -> None:
|
||||
"""Gives the job to the runner's user (`NOTEBOOK_RUNNER_UID`) when it isn't this one."""
|
||||
uid = os.environ.get(RUNNER_UID_ENV)
|
||||
os.chmod(folder, 0o755)
|
||||
if not uid or int(uid) == os.getuid():
|
||||
return
|
||||
for base, folders, files in os.walk(folder):
|
||||
for name in [base, *(os.path.join(base, f) for f in folders + files)]:
|
||||
os.chown(name, int(uid), int(uid), follow_symlinks=False)
|
||||
|
||||
|
||||
def notebook_env(job: Path) -> dict[str, str]:
|
||||
spec = json.loads((job / JOB_FILE).read_text())
|
||||
private = job / ".entorno"
|
||||
env = {name: os.environ[name] for name in PASSED_ENV if name in os.environ}
|
||||
env.update({name: EMPTY_DATABASE for name in DATABASE_ENVS})
|
||||
env.update({
|
||||
COHORT_FILE_ENV: _absolute(job / COHORT_FILE), DOMAIN_ENV: spec["domain"], SCENARIO_ENV: spec["scenario"],
|
||||
"MLFLOW_TRACKING_URI": store_uri(job), "MLFLOW_ARTIFACT_ROOT": _absolute(job / STORE_ARTIFACTS),
|
||||
"HOME": _absolute(private), "TMPDIR": _absolute(private / "tmp"), "IPYTHONDIR": _absolute(private / "ipython"),
|
||||
"JUPYTER_RUNTIME_DIR": _absolute(private / "jupyter"), "MPLCONFIGDIR": _absolute(private / "matplotlib"),
|
||||
})
|
||||
if spec.get("version"):
|
||||
env[VERSION_ENV] = str(spec["version"])
|
||||
if (job / MODEL_DIR).is_dir():
|
||||
env[MODEL_PATH_ENV] = _absolute(job / MODEL_DIR)
|
||||
return env
|
||||
|
||||
|
||||
def run_job(job: Path) -> bool:
|
||||
"""Runs the job's notebook and writes its page and `result.json`. Returns whether every cell ran."""
|
||||
env = notebook_env(job)
|
||||
for folder in ("HOME", "TMPDIR", "IPYTHONDIR", "JUPYTER_RUNTIME_DIR", "MPLCONFIGDIR"):
|
||||
Path(env[folder]).mkdir(parents=True, exist_ok=True)
|
||||
work = job / WORK_DIR
|
||||
work.mkdir(exist_ok=True)
|
||||
result: dict[str, Any] = {"ok": True, "error": None}
|
||||
page = None
|
||||
try:
|
||||
page = renderer().render(json.loads((job / NOTEBOOK_FILE).read_text()), "notebook", work, env)
|
||||
except RenderError as error:
|
||||
page, result = error.page, {"ok": False, "error": str(error)}
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
if page is not None:
|
||||
_write_atomically(job / PAGE_FILE, page)
|
||||
_write_atomically(job / RESULT_FILE, json.dumps(result, ensure_ascii=False))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _write_atomically(path: Path, text: str) -> None:
|
||||
partial = path.with_name(f".{path.name}.parcial")
|
||||
partial.write_text(text)
|
||||
partial.replace(path)
|
||||
|
||||
|
||||
def read_job_file(job: Path, relative: str) -> bytes | None:
|
||||
"""A file the job left, or `None` if it isn't there. `JobError` for a symbolic link or a path that leaves the job
|
||||
folder: those were planted to make the trusted side read its own files."""
|
||||
path = job / relative
|
||||
if not inside(job, path):
|
||||
raise JobError(f"{relative} sale de la carpeta del trabajo")
|
||||
try:
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as error:
|
||||
raise JobError(f"{relative} no es un archivo regular") from error
|
||||
with os.fdopen(descriptor, "rb") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
raise JobError(f"{relative} no es un archivo regular")
|
||||
return handle.read()
|
||||
|
||||
|
||||
def inside(job: Path, path: Path) -> bool:
|
||||
"""Whether `path` is within `job` with no symbolic link on the way."""
|
||||
base = Path(os.path.abspath(job))
|
||||
try:
|
||||
parts = Path(os.path.abspath(path)).relative_to(base).parts
|
||||
except ValueError:
|
||||
return False
|
||||
current = base
|
||||
for part in parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def result_of(job: Path) -> dict[str, Any] | None:
|
||||
data = read_job_file(job, RESULT_FILE)
|
||||
if data is None:
|
||||
return None
|
||||
try:
|
||||
result = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
return {"ok": False, "error": "result.json ilegible"}
|
||||
return {"ok": result.get("ok") is True, "error": str(result.get("error") or "")[:20000] or None}
|
||||
|
||||
|
||||
class NotebookExecutor(ABC):
|
||||
name: str
|
||||
sandboxed: bool
|
||||
|
||||
@abstractmethod
|
||||
def jobs_root(self) -> Path: ...
|
||||
|
||||
@abstractmethod
|
||||
def run(self, job: Path) -> None:
|
||||
"""Returns once the job has its `result.json`; `JobError` if it never gets one."""
|
||||
|
||||
|
||||
EXECUTORS: dict[str, type[NotebookExecutor]] = {}
|
||||
|
||||
|
||||
def register_executor(cls: type[NotebookExecutor]) -> type[NotebookExecutor]:
|
||||
EXECUTORS[cls.name] = cls
|
||||
return cls
|
||||
|
||||
|
||||
@register_executor
|
||||
class LocalExecutor(NotebookExecutor):
|
||||
"""Runs the job in this process's own kernel: nothing keeps the notebook from this machine's files or network."""
|
||||
|
||||
name, sandboxed = "local", False
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
return Path(os.environ.get(JOBS_DIR_ENV) or Path(tempfile.gettempdir()) / "notebook-jobs")
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
run_job(job)
|
||||
|
||||
|
||||
@register_executor
|
||||
class ContainerExecutor(NotebookExecutor):
|
||||
"""Leaves the job for the runner container and waits for its result (`NOTEBOOK_JOB_TIMEOUT`, 6 h by default)."""
|
||||
|
||||
name, sandboxed = "contenedor", True
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
if not os.environ.get(JOBS_DIR_ENV):
|
||||
raise JobError(f"{JOBS_DIR_ENV} no está configurado: no hay carpeta compartida con el contenedor de notebooks")
|
||||
return Path(os.environ[JOBS_DIR_ENV])
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
deadline = time.monotonic() + int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT))
|
||||
while time.monotonic() < deadline:
|
||||
if result_of(job) is not None:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
raise JobError("el contenedor de notebooks no terminó el trabajo a tiempo (¿está corriendo?)")
|
||||
|
||||
|
||||
def executor() -> NotebookExecutor:
|
||||
chosen = os.environ.get(EXECUTOR_ENV) or ("contenedor" if os.environ.get(JOBS_DIR_ENV) else "local")
|
||||
if chosen not in EXECUTORS:
|
||||
raise JobError(f"{EXECUTOR_ENV}={chosen!r}: use uno de {sorted(EXECUTORS)}")
|
||||
return EXECUTORS[chosen]()
|
||||
|
||||
|
||||
def claim(job: Path) -> bool:
|
||||
"""Takes a ready job for this runner; `False` if it isn't ready or another runner has it."""
|
||||
if not job.is_dir() or job.name.startswith(".") or not (job / JOB_FILE).exists() or (job / RESULT_FILE).exists():
|
||||
return False
|
||||
try:
|
||||
(job / CLAIM_DIR).mkdir()
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def serve(root: Path, *, once: bool = False) -> None:
|
||||
"""The runner's loop: runs each ready job in `root`, oldest first."""
|
||||
while True:
|
||||
for job in sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.stat().st_mtime):
|
||||
if claim(job):
|
||||
try:
|
||||
run_job(job)
|
||||
except Exception as error:
|
||||
_write_atomically(job / RESULT_FILE, json.dumps({"ok": False, "error": f"{type(error).__name__}: {error}"}))
|
||||
if once:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
@@ -1,450 +0,0 @@
|
||||
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
||||
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
||||
about on its own: the promotion checks tied to the cohort a version was
|
||||
trained on and to the validation-report convention, and `PredictionService`,
|
||||
which stores each single prediction with the version in production (MLD-4/5,
|
||||
EL-04b).
|
||||
|
||||
Training, versioning, artifact storage and stage live in MLflow itself
|
||||
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
||||
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
|
||||
of its versions, never stored here and read from MLflow on every call.
|
||||
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
|
||||
database). A version points to its build with the `kit.armado_id` tag, and
|
||||
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from core.governance.models import ModelPrediction
|
||||
import mlflow.artifacts
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.io.lineage import (
|
||||
ARMADO_TAG,
|
||||
COHORT_BUILD_TAG,
|
||||
COHORT_SOURCE_TAG,
|
||||
COHORT_URL_TAG,
|
||||
DOMAINS,
|
||||
MODEL_SHA_TAG,
|
||||
registered_name,
|
||||
)
|
||||
from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, TrainingRun, run_file, run_files
|
||||
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
PRODUCTION_ALIAS = "produccion"
|
||||
REFERENCE_SOURCE = "referencia" # `cohort.source` of a version trained on a cohort outside the platform
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromotionCheck:
|
||||
code: str
|
||||
requirement: str
|
||||
passed: bool
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class PromotionBlocked(Exception):
|
||||
def __init__(self, checks: list[PromotionCheck]):
|
||||
self.checks = checks
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
|
||||
super().__init__(f"la versión no cumple: {failed}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedVersion:
|
||||
"""The version a caller will use, with what it needs to load it and to say where risks came from.
|
||||
`status` is the version's status when it was resolved (`produccion`, `candidata`, `desarrollo` or
|
||||
`retirada`)."""
|
||||
|
||||
domain: str
|
||||
scenario: str
|
||||
version: str
|
||||
run_id: str
|
||||
status: str
|
||||
modelo_sha: str | None
|
||||
|
||||
@property
|
||||
def model_uri(self) -> str:
|
||||
return f"models:/{registered_name(self.domain, self.scenario)}/{self.version}"
|
||||
|
||||
|
||||
class ModelRegistry:
|
||||
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
|
||||
|
||||
def __init__(self, client: MlflowClient | None = None):
|
||||
self._client = client
|
||||
|
||||
@property
|
||||
def client(self) -> MlflowClient:
|
||||
return self._client or MlflowClient()
|
||||
|
||||
def get(self, domain: str, scenario: str, version: str):
|
||||
try:
|
||||
return self.client.get_model_version(registered_name(domain, scenario), version)
|
||||
except MlflowException as exc:
|
||||
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
|
||||
|
||||
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every version, newest first. `scenario` needs `domain`; `domain`
|
||||
alone matches every scenario of that domain (MLflow's own
|
||||
`search_registered_models` LIKE filter); neither matches everything."""
|
||||
if domain and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario and not re.fullmatch(r"[\w-]+", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
if domain and scenario:
|
||||
names = [registered_name(domain, scenario)]
|
||||
elif domain:
|
||||
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
|
||||
else:
|
||||
return [self._describe(mv) for mv in self.client.search_model_versions()]
|
||||
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
|
||||
|
||||
def _status(self, mv) -> str:
|
||||
try:
|
||||
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
|
||||
if str(production.version) == str(mv.version):
|
||||
return "produccion"
|
||||
except MlflowException:
|
||||
pass
|
||||
if mv.tags.get("retirada_en"):
|
||||
return "retirada"
|
||||
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
|
||||
|
||||
def status(self, domain: str, scenario: str, version: str) -> str:
|
||||
return self._status(self.get(domain, scenario, version))
|
||||
|
||||
def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion:
|
||||
"""With no `version`, the one holding the `produccion` alias; with a version, that one, whatever
|
||||
its status (to test or compare a candidate). The status travels with it: confirming risks only
|
||||
accepts versions that were in production."""
|
||||
if version is None:
|
||||
try:
|
||||
mv = self.client.get_model_version_by_alias(registered_name(domain, scenario), PRODUCTION_ALIAS)
|
||||
except MlflowException as exc:
|
||||
raise LookupError(f"({domain}, {scenario}) has no version in production") from exc
|
||||
else:
|
||||
mv = self.get(domain, scenario, version)
|
||||
return ResolvedVersion(domain, scenario, str(mv.version), mv.run_id, self._status(mv),
|
||||
mv.tags.get(MODEL_SHA_TAG))
|
||||
|
||||
def register(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
) -> str:
|
||||
"""For training code that runs elsewhere and reports over the API: a run with these metrics, registered.
|
||||
In-process training opens its own `TrainingRun` and calls `register_run`."""
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
||||
return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports)
|
||||
|
||||
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
|
||||
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
|
||||
cohort link and cohort file, `modelo_sha`, report URIs), and returns the version."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
name = registered_name(run.domain, run.scenario)
|
||||
try:
|
||||
self.client.create_registered_model(name)
|
||||
except MlflowException as exc:
|
||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
|
||||
if run.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
|
||||
version_tags.update(run.cohort)
|
||||
if run.modelo_sha is not None:
|
||||
version_tags[MODEL_SHA_TAG] = run.modelo_sha
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}"
|
||||
return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version)
|
||||
|
||||
def set_description(self, domain: str, scenario: str, version: str, description: str) -> None:
|
||||
self.client.update_model_version(registered_name(domain, scenario), version, description=description)
|
||||
|
||||
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
||||
"""MLD-01/01b/03 documents are usually written after training."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
name = registered_name(domain, scenario)
|
||||
for tag, uri in reports.items():
|
||||
self.client.set_model_version_tag(name, version, tag, uri or "")
|
||||
|
||||
def artifacts(self, domain: str, scenario: str, version: str) -> list[dict[str, Any]]:
|
||||
"""Every file the version's run stored, at any depth (`path`, `size` in bytes)."""
|
||||
return run_files(self.client, self.get(domain, scenario, version).run_id)
|
||||
|
||||
def artifact(self, domain: str, scenario: str, version: str, path: str) -> tuple[str, bytes]:
|
||||
"""ML-01b: one stored artifact as a file name and its bytes; a folder (the saved model) comes as a zip.
|
||||
`LookupError` for a path the run doesn't hold."""
|
||||
return run_file(self.client, self.get(domain, scenario, version).run_id, path)
|
||||
|
||||
def _describe(self, mv) -> dict[str, Any]:
|
||||
run = self.client.get_run(mv.run_id)
|
||||
return {
|
||||
"name": mv.name,
|
||||
"version": str(mv.version),
|
||||
"run_id": mv.run_id,
|
||||
"tags": dict(mv.tags),
|
||||
"metrics": dict(run.data.metrics),
|
||||
"created_at": _iso(mv.creation_timestamp),
|
||||
"status": self._status(mv),
|
||||
}
|
||||
|
||||
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
return self._describe(self.get(domain, scenario, version))
|
||||
|
||||
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
"""Everything a version came from and produced: its cohort build (with
|
||||
its attrition), logged artifacts and predictions."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
return {
|
||||
"model_version": self.describe(domain, scenario, version),
|
||||
"cohorte_armado": armado,
|
||||
"cohorte_exclusiones": exclusiones,
|
||||
"artifacts": run_files(self.client, mv.run_id),
|
||||
"routines": self.routines(mv.run_id),
|
||||
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
|
||||
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
|
||||
}
|
||||
|
||||
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
|
||||
mv = self.get(domain, scenario, version)
|
||||
run = self.client.get_run(mv.run_id)
|
||||
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None
|
||||
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
|
||||
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
|
||||
metrics = run.data.metrics
|
||||
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
|
||||
sha = mv.tags.get(MODEL_SHA_TAG, "")
|
||||
if armado is not None:
|
||||
cohort_detail = f"huella {armado['huella'][:12]}"
|
||||
elif dbt_build is not None:
|
||||
cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}"
|
||||
elif reference:
|
||||
cohort_detail = f"cohorte de referencia {mv.tags.get(COHORT_URL_TAG)}, listado {reference[:12]}"
|
||||
else:
|
||||
cohort_detail = "sin cohorte"
|
||||
return [
|
||||
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
|
||||
PromotionCheck(
|
||||
"ML-03",
|
||||
"enlazada al armado de cohorte con el que se entrenó",
|
||||
armado is not None or dbt_build is not None or bool(reference),
|
||||
cohort_detail,
|
||||
),
|
||||
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
|
||||
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
|
||||
PromotionCheck("ML-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
|
||||
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
|
||||
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
|
||||
]
|
||||
|
||||
def routines(self, run_id: str) -> dict[str, Any]:
|
||||
"""The routine records the run wrote while training (`TrainingRun.log_routine`), by kind."""
|
||||
found = {}
|
||||
for item in self.client.list_artifacts(run_id, ROUTINES_PATH):
|
||||
kind = Path(item.path).stem
|
||||
if not item.is_dir and kind in ArtifactKind.__members__:
|
||||
found[kind] = json.loads(mlflow.artifacts.load_text(f"runs:/{run_id}/{item.path}"))
|
||||
return found
|
||||
|
||||
def promote(self, domain: str, scenario: str, version: str):
|
||||
"""Makes this the production version of its scenario, tagging the
|
||||
previous one `retirada_en`. Promotion is always a manual step
|
||||
(MLD-01/01b)."""
|
||||
checks = self.checks(domain, scenario, version)
|
||||
if not all(check.passed for check in checks):
|
||||
raise PromotionBlocked(checks)
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
if str(previous.version) != str(version):
|
||||
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
|
||||
except MlflowException:
|
||||
pass
|
||||
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
||||
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
def retire(self, domain: str, scenario: str, version: str):
|
||||
"""Withdraws a version from production; its scenario has no active
|
||||
model until another one is promoted, so predictions stop."""
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
active = None
|
||||
if active is None or str(active.version) != str(version):
|
||||
raise ValueError("la versión no está en producción")
|
||||
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
|
||||
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _iso(epoch_millis: int) -> str:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
|
||||
|
||||
|
||||
registry = ModelRegistry()
|
||||
|
||||
|
||||
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
|
||||
"""The kit cohort build a version was trained on, and its attrition steps."""
|
||||
if not armado_id:
|
||||
return None, []
|
||||
cohortes = import_module(f"persistance.{domain}").cohort_repository
|
||||
armado = cohortes.get(int(armado_id))
|
||||
if armado is None:
|
||||
return None, []
|
||||
exclusion = cohortes.cohortes.CohorteExclusion
|
||||
pasos = cohortes.read(lambda sesion: sesion.exec(
|
||||
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
||||
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
|
||||
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
||||
"armado_en": armado.armado_en.isoformat()},
|
||||
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
||||
|
||||
|
||||
class Predictor(Protocol):
|
||||
"""What the service needs from a model."""
|
||||
|
||||
def predict(self, data: Any) -> Any: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class Interpretability:
|
||||
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
||||
Each model fills the ones its method has (odds ratio for a logistic
|
||||
regression, hazard ratio for a survival model)."""
|
||||
|
||||
odds_ratio: float | None = None
|
||||
hazard_ratio: float | None = None
|
||||
probabilidad_acumulada: float | None = None
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"odds_ratio": self.odds_ratio,
|
||||
"hazard_ratio": self.hazard_ratio,
|
||||
"probabilidad_acumulada": self.probabilidad_acumulada,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ApplicabilityRejected(Exception):
|
||||
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
||||
should report it as a client error (4xx), not a server error."""
|
||||
|
||||
|
||||
class PredictionService:
|
||||
"""Runs a model and records its predictions against the
|
||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
||||
|
||||
If `aplicable` is given, each row (a dict of fields) is checked with it
|
||||
(EL-04b). Inapplicable rows are still scored but stored with
|
||||
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: Predictor,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
aplicable: Callable[[dict], bool] | None = None,
|
||||
reject_inapplicable: bool = False,
|
||||
):
|
||||
self.model = model
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.aplicable = aplicable
|
||||
self.reject_inapplicable = reject_inapplicable
|
||||
|
||||
def active_model_version(self):
|
||||
"""The MLflow model version currently holding the `produccion`
|
||||
alias for this (domain, scenario), or `None`."""
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
return None
|
||||
|
||||
def predict_and_record(
|
||||
self,
|
||||
data: Any,
|
||||
*,
|
||||
pac_id_hospital: str,
|
||||
episodio_id: int | None = None,
|
||||
interpretability: Interpretability | None = None,
|
||||
) -> ModelPrediction:
|
||||
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
||||
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
||||
propagated unchanged.
|
||||
"""
|
||||
applicability_passed = True
|
||||
if self.aplicable is not None:
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError("the applicability check needs the input as a dict of fields")
|
||||
applicability_passed = self.aplicable(data)
|
||||
if not applicability_passed and self.reject_inapplicable:
|
||||
raise ApplicabilityRejected(
|
||||
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
||||
)
|
||||
|
||||
# Predict first, so an unimplemented model raises NotImplementedError
|
||||
# even when no version is in production.
|
||||
output = self.model.predict(data)
|
||||
|
||||
model_version = self.active_model_version()
|
||||
if model_version is None:
|
||||
raise RuntimeError(
|
||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
||||
"promueva una con registry.promote antes de predecir"
|
||||
)
|
||||
|
||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
prediction = model_prediction_repository.create(
|
||||
ModelPrediction(
|
||||
mlflow_run_id=model_version.run_id,
|
||||
modelo_nombre=model_version.name,
|
||||
modelo_version=str(model_version.version),
|
||||
domain=self.domain,
|
||||
pac_id_hospital=pac_id_hospital,
|
||||
episodio_id=episodio_id,
|
||||
input_hash=input_hash,
|
||||
output=json.dumps(output, default=str),
|
||||
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
||||
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
||||
interpretability=interpretability.to_json() if interpretability else None,
|
||||
applicability_passed=applicability_passed,
|
||||
)
|
||||
)
|
||||
return prediction
|
||||
@@ -1,152 +0,0 @@
|
||||
"""Runs a notebook and renders it to a self-contained HTML page.
|
||||
|
||||
Two renderers, one class each in `RENDERERS`: `quarto`, and `jupyter`, which runs the cells with `nbclient` and
|
||||
exports the page with `nbconvert` (the `notebooks` extra), so it needs nothing outside Python. `NOTEBOOK_RENDERER`
|
||||
picks one; otherwise Quarto when it's installed, else Jupyter.
|
||||
|
||||
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
|
||||
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
|
||||
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
|
||||
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
|
||||
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
|
||||
first and the source folder is left untouched.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
QUARTO_ENV = "QUARTO_BIN"
|
||||
RENDERER_ENV = "NOTEBOOK_RENDERER"
|
||||
# Seconds a single cell may run under the Jupyter renderer.
|
||||
CELL_TIMEOUT_ENV = "NOTEBOOK_CELL_TIMEOUT"
|
||||
CELL_TIMEOUT = 1800
|
||||
|
||||
|
||||
class RenderError(RuntimeError):
|
||||
"""The notebook couldn't be run: a cell raised, the kernel is missing, or the renderer isn't installed. `page` is
|
||||
the page of the cells that did run, when the renderer could still make one."""
|
||||
|
||||
def __init__(self, message: str, page: str | None = None):
|
||||
super().__init__(message)
|
||||
self.page = page
|
||||
|
||||
|
||||
class NotebookRenderer(ABC):
|
||||
name: str
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def available(cls) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
"""Runs `notebook` in `folder` with exactly `env` as its environment and returns the page's HTML."""
|
||||
|
||||
|
||||
RENDERERS: dict[str, type[NotebookRenderer]] = {}
|
||||
|
||||
|
||||
def register_renderer(cls: type[NotebookRenderer]) -> type[NotebookRenderer]:
|
||||
RENDERERS[cls.name] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def quarto() -> str:
|
||||
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
|
||||
if not found:
|
||||
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
|
||||
return found
|
||||
|
||||
|
||||
@register_renderer
|
||||
class QuartoRenderer(NotebookRenderer):
|
||||
name = "quarto"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
return bool(os.environ.get(QUARTO_ENV) or shutil.which("quarto"))
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
source = folder / f"{name}.ipynb"
|
||||
source.write_text(json.dumps(notebook, ensure_ascii=False))
|
||||
done = subprocess.run([quarto(), "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
|
||||
cwd=folder, env=env, capture_output=True, text=True)
|
||||
page = source.with_suffix(".html")
|
||||
if done.returncode or not page.exists():
|
||||
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
|
||||
return page.read_text()
|
||||
|
||||
|
||||
@register_renderer
|
||||
class JupyterRenderer(NotebookRenderer):
|
||||
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
|
||||
package's own interpreter once `ipykernel` is installed)."""
|
||||
|
||||
name = "jupyter"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
try:
|
||||
import nbclient # noqa: F401
|
||||
import nbconvert # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
import nbformat
|
||||
from nbclient import NotebookClient
|
||||
from nbclient.exceptions import CellExecutionError, DeadKernelError
|
||||
from nbconvert import HTMLExporter
|
||||
|
||||
node = nbformat.reads(json.dumps(notebook), as_version=4)
|
||||
kernel = node.metadata.get("kernelspec", {}).get("name") or "python3"
|
||||
timeout = int(os.environ.get(CELL_TIMEOUT_ENV, CELL_TIMEOUT))
|
||||
client = NotebookClient(node, timeout=timeout, kernel_name=kernel, resources={"metadata": {"path": str(folder)}})
|
||||
try:
|
||||
client.execute(env=env, cwd=str(folder))
|
||||
except (CellExecutionError, DeadKernelError, TimeoutError) as error:
|
||||
raise RenderError(f"{name}: {str(error)[-2000:]}", page=self._page(HTMLExporter, node)) from error
|
||||
except Exception as error:
|
||||
raise RenderError(f"{name}: el kernel {kernel!r} no pudo correr el notebook: {error}") from error
|
||||
return self._page(HTMLExporter, node)
|
||||
|
||||
@staticmethod
|
||||
def _page(exporter, node) -> str:
|
||||
body, _ = exporter(embed_images=True).from_notebook_node(node)
|
||||
return body
|
||||
|
||||
|
||||
def renderer() -> NotebookRenderer:
|
||||
"""The renderer `NOTEBOOK_RENDERER` names; otherwise Quarto if installed, else Jupyter."""
|
||||
if chosen := os.environ.get(RENDERER_ENV):
|
||||
if chosen not in RENDERERS:
|
||||
raise RenderError(f"{RENDERER_ENV}={chosen!r}: use one of {sorted(RENDERERS)}")
|
||||
return RENDERERS[chosen]()
|
||||
for cls in RENDERERS.values():
|
||||
if cls.available():
|
||||
return cls()
|
||||
raise RenderError(f"no notebook renderer is installed: install quarto or the 'notebooks' extra ({sorted(RENDERERS)})")
|
||||
|
||||
|
||||
def with_kernel(notebook: dict, kernel: str | None) -> dict:
|
||||
if not kernel:
|
||||
return notebook
|
||||
return {**notebook, "metadata": {**notebook.get("metadata", {}),
|
||||
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
|
||||
|
||||
|
||||
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
|
||||
kernel: str | None = None) -> Path:
|
||||
"""Runs and renders `notebook` (its JSON) as `name`, with this process's environment plus `env`, and writes the
|
||||
page to `output`."""
|
||||
with tempfile.TemporaryDirectory(prefix="render-") as folder:
|
||||
page = renderer().render(with_kernel(notebook, kernel), name, Path(folder), {**os.environ, **(env or {})})
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(page)
|
||||
return output
|
||||
@@ -1,240 +0,0 @@
|
||||
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
|
||||
manifest, a domain's Persistance repositories, and the batches of risks they store.
|
||||
|
||||
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
|
||||
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
|
||||
repository is used, so a model folder reading its cohort file never loads the database layer.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
|
||||
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
||||
|
||||
|
||||
def cohorts_root(database_url: str) -> Path:
|
||||
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
||||
if configured := os.environ.get("COHORTS_DIR"):
|
||||
return Path(configured)
|
||||
url = make_url(database_url)
|
||||
if url.get_backend_name() != "sqlite" or not url.database:
|
||||
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
||||
return Path(url.database).parent / "cohorts"
|
||||
|
||||
|
||||
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
||||
domain, cohort = url.split("/", 1)
|
||||
return root / domain / cohort / f"{armado_id}.parquet"
|
||||
|
||||
|
||||
def dbt_build_path(root: Path, url: str, number: int) -> Path:
|
||||
return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet"
|
||||
|
||||
|
||||
def _numbers(folder: Path) -> list[int]:
|
||||
return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit())
|
||||
|
||||
|
||||
def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None:
|
||||
"""The highest-numbered build of dbt's rules, or `None` if there's none."""
|
||||
numbers = _numbers(dbt_build_path(root, url, 0).parent)
|
||||
return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None
|
||||
|
||||
|
||||
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
||||
"""The file of that build, or of the cohort's latest build that has a file."""
|
||||
if armado_id is None:
|
||||
builds = _numbers(cohort_path(root, url, 0).parent)
|
||||
if not builds:
|
||||
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
||||
armado_id = max(builds)
|
||||
path = cohort_path(root, url, armado_id)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
|
||||
|
||||
def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
|
||||
"""One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and,
|
||||
with `cohorts` (the domain's `cohort_repository`), the kit's builds and whether each has its file. Without
|
||||
`cohorts` only files are read, never the database."""
|
||||
rows = []
|
||||
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
|
||||
path = dbt_build_path(root, url, number)
|
||||
lineage = read_metadata(path)
|
||||
rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
||||
"n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)})
|
||||
for build in (cohorts.builds(url) if cohorts is not None else []):
|
||||
path = cohort_path(root, url, build.armado_id)
|
||||
rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(),
|
||||
"n_members": str(build.n_miembros), "created": build.armado_en.isoformat(),
|
||||
"file": str(path) if path.exists() else None})
|
||||
return rows
|
||||
|
||||
|
||||
def exported_builds(root: Path, domain: str) -> list[dict]:
|
||||
"""Every build of the domain's cohorts that has its file, newest first within each cohort and source, read from
|
||||
the files alone: `url`, `source`, `build`, `datos_as_of`, `n_members`."""
|
||||
rows = []
|
||||
folder = root / domain
|
||||
for cohort in sorted(p for p in folder.iterdir() if p.is_dir()) if folder.is_dir() else []:
|
||||
url = f"{domain}/{cohort.name}"
|
||||
for source, place in (("kit", cohort), ("dbt", cohort / "dbt")):
|
||||
for number in reversed(_numbers(place)):
|
||||
lineage = read_metadata(place / f"{number}.parquet")
|
||||
rows.append({"url": url, "source": source, "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
||||
"n_members": lineage.get("n_members") or lineage.get("n_miembros")})
|
||||
return rows
|
||||
|
||||
|
||||
def build_file(root: Path, url: str, source: str, build: int) -> Path:
|
||||
"""The file of one exported build; `LookupError` when it isn't there."""
|
||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||
if source not in ("kit", "dbt") or not path.exists():
|
||||
raise LookupError(f"no hay archivo de la construcción {source} {build} de {url}")
|
||||
return path
|
||||
|
||||
|
||||
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
|
||||
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
|
||||
without a file is described from `cohorts` (the domain's `cohort_repository`). `LookupError` if there's no such
|
||||
build."""
|
||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||
if path.exists():
|
||||
lineage = read_metadata(path)
|
||||
for key in ("parametros", "rules", "attrition"):
|
||||
if lineage.get(key):
|
||||
lineage[key] = json.loads(lineage[key])
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage}
|
||||
stored = cohorts.build(build) if source == "kit" and cohorts is not None else None
|
||||
if stored is None or stored.url != url:
|
||||
raise LookupError(f"no {source} build {build} of {url}")
|
||||
return {"source": "kit", "build": build, "file": None, "file_sha256": None,
|
||||
"lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(),
|
||||
"n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}}
|
||||
|
||||
|
||||
def read_cohort(path: str | Path) -> pd.DataFrame:
|
||||
"""The build's rows, after checking the file's schema without reading them."""
|
||||
schema = pq.read_schema(path)
|
||||
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
||||
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
||||
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
|
||||
|
||||
|
||||
def write_once(table: pa.Table, path: Path) -> None:
|
||||
"""The file appears complete or not at all: written beside it, then renamed."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
|
||||
partial = Path(handle.name)
|
||||
try:
|
||||
pq.write_table(table, partial)
|
||||
partial.replace(path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_metadata(path: str | Path) -> dict[str, str]:
|
||||
"""A Parquet file's own metadata, without reading any rows."""
|
||||
metadata = pq.read_metadata(path).metadata or {}
|
||||
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
||||
|
||||
|
||||
def _one(nodes: list[dict], kind: str, url: str) -> dict:
|
||||
found = [node for node in nodes if node["config"]["meta"]["kind"] == kind]
|
||||
if len(found) != 1:
|
||||
raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def _compiled(node: dict) -> str:
|
||||
if not node.get("compiled_code"):
|
||||
raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`")
|
||||
return node["compiled_code"]
|
||||
|
||||
|
||||
def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
||||
"""The cohort's compiled queries, with its exclusions in their `order`.
|
||||
|
||||
An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every
|
||||
rule's excluded members, and the study population, independent of the order.
|
||||
"""
|
||||
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
||||
nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url]
|
||||
if not nodes:
|
||||
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
||||
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
||||
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
|
||||
if not exclusions:
|
||||
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
|
||||
orders = [node["config"]["meta"]["order"] for node in exclusions]
|
||||
if len(set(orders)) != len(orders):
|
||||
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
||||
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
||||
for node in exclusions:
|
||||
if read := steps & set(node["depends_on"]["nodes"]):
|
||||
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
|
||||
meta = population["config"]["meta"]
|
||||
if "cutoff" not in meta:
|
||||
raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta")
|
||||
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
||||
for node in exclusions)
|
||||
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
||||
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
|
||||
|
||||
|
||||
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
|
||||
"""Writes a batch of risks for a kit build through the domain's `cohort_repository`: its `lote_id` and whether it's
|
||||
new. The only write the pipelines make to the database; risks of anyone outside the build are refused."""
|
||||
cohorts = importlib.import_module(f"persistance.{domain}").cohort_repository
|
||||
return cohorts.save_batch(armado_id, provenance, outcome, rows)
|
||||
|
||||
|
||||
def resolve_repository(domain: str, entity: str):
|
||||
"""`entity` is the repository's name in `persistance.<domain>` without
|
||||
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
||||
module = importlib.import_module(f"persistance.{domain}")
|
||||
try:
|
||||
return getattr(module, f"{entity}_repository")
|
||||
except AttributeError as exc:
|
||||
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
||||
|
||||
|
||||
class ReadOnlyRepository:
|
||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
||||
Write methods raise `PermissionError` so a training routine cannot
|
||||
modify clinical data."""
|
||||
|
||||
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
||||
|
||||
def __init__(self, repository):
|
||||
self._repository = repository
|
||||
self.model = repository.model
|
||||
|
||||
def get(self, id_):
|
||||
return self._repository.get(id_)
|
||||
|
||||
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
||||
return self._repository.list(limit=limit, offset=offset, **filters)
|
||||
|
||||
def count(self, **filters) -> int:
|
||||
return self._repository.count(**filters)
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
if name in self._WRITE_METHODS:
|
||||
raise PermissionError(
|
||||
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
||||
)
|
||||
raise AttributeError(name)
|
||||
@@ -1,211 +0,0 @@
|
||||
"""MLflow runs: what happened in one execution (ML-01..ML-05).
|
||||
|
||||
Does not train anything. It opens an MLflow run, records which cohort
|
||||
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
||||
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
||||
stores the run, metrics and artifacts.
|
||||
|
||||
Each routine around training (ML-01a: sampling, missing data, analytic
|
||||
method, class balance, output confidence) records what it did while the run
|
||||
is open, with `log_routine`: one JSON per routine under `rutinas/`, made of
|
||||
counts and settings, never rows. Turning a run into a registered
|
||||
version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped
|
||||
methods instead of the fluent API's global active run, so two runs in one
|
||||
process never interfere.
|
||||
|
||||
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
|
||||
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
|
||||
|
||||
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
|
||||
their own, and `find_run` finds one already made from the same inputs.
|
||||
|
||||
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
|
||||
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
|
||||
model that produced a risk. Which code trained it is recorded apart: every run is
|
||||
tagged with the git commit of this package's repository and whether it had
|
||||
uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
|
||||
delivered images). A PROD run only logs models whose class lives in a module, at a
|
||||
known commit, never one defined in a notebook.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import mlflow.pyfunc
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
|
||||
from models.io.storage import ReadOnlyRepository, resolve_repository
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
MODEL_PATH = "model"
|
||||
ROUTINES_PATH = "rutinas"
|
||||
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
|
||||
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
|
||||
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
|
||||
|
||||
|
||||
def routine_path(kind: ArtifactKind | str) -> str:
|
||||
return f"{ROUTINES_PATH}/{ArtifactKind(kind).value}.json"
|
||||
|
||||
|
||||
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
|
||||
metadata: dict[str, Any] | None = None) -> None:
|
||||
"""ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind."""
|
||||
client.log_artifact(run_id, str(path), artifact_path=kind)
|
||||
if metadata:
|
||||
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
|
||||
|
||||
|
||||
def run_files(client: MlflowClient, run_id: str, folder: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every file a run stored, at any depth: `path` and `size` in bytes."""
|
||||
files = []
|
||||
for item in client.list_artifacts(run_id, folder):
|
||||
files.extend(run_files(client, run_id, item.path) if item.is_dir else [{"path": item.path, "size": item.file_size}])
|
||||
return files
|
||||
|
||||
|
||||
def run_file(client: MlflowClient, run_id: str, path: str) -> tuple[str, bytes]:
|
||||
"""A stored file as its name and bytes, or a stored folder as `<name>.zip`. `LookupError` when the run holds
|
||||
nothing at `path`, which is matched against the run's own listing, never resolved on disk."""
|
||||
path = path.strip("/")
|
||||
files = [item["path"] for item in run_files(client, run_id)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
if path in files:
|
||||
local = Path(client.download_artifacts(run_id, path, tmp))
|
||||
return local.name, local.read_bytes()
|
||||
inside = [name for name in files if name.startswith(f"{path}/")]
|
||||
if not path or not inside:
|
||||
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
|
||||
client.download_artifacts(run_id, path, tmp)
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zipped:
|
||||
for name in inside:
|
||||
zipped.write(Path(tmp) / name, name)
|
||||
return f"{Path(path).name}.zip", archive.getvalue()
|
||||
|
||||
|
||||
def experiment_id(client: MlflowClient, name: str) -> str:
|
||||
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
|
||||
experiment = client.get_experiment_by_name(name)
|
||||
if experiment:
|
||||
return experiment.experiment_id
|
||||
root = os.environ.get(ARTIFACT_ROOT_ENV)
|
||||
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
|
||||
|
||||
|
||||
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
|
||||
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
|
||||
found = client.get_experiment_by_name(experiment)
|
||||
if found is None:
|
||||
return None
|
||||
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
|
||||
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
|
||||
return run.info.run_id
|
||||
return None
|
||||
|
||||
|
||||
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
|
||||
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
|
||||
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
|
||||
try:
|
||||
for kind, path in files.items():
|
||||
log_artifact_file(client, run.info.run_id, kind, path)
|
||||
except Exception:
|
||||
client.set_terminated(run.info.run_id, "FAILED")
|
||||
raise
|
||||
client.set_terminated(run.info.run_id, "FINISHED")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
class TrainingRun:
|
||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
||||
runs name the cohort build they were trained on, so their metrics trace
|
||||
back to that data (ML-03): `cohort`, the reference to its file
|
||||
(`models.io.lineage.cohort_reference`), or `cohorte_armado_id`, a kit build
|
||||
by number; dev runs may omit both.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
cohort: dict[str, str] | None = None,
|
||||
):
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
environment = Environment(environment)
|
||||
if environment is Environment.PROD and cohorte_armado_id is None and cohort is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id o cohort).")
|
||||
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.environment = environment
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.cohort = dict(cohort or {})
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
experiment_id,
|
||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
|
||||
)
|
||||
self.run_id = run.info.run_id
|
||||
self.modelo_sha: str | None = None
|
||||
if cohorte_armado_id is not None:
|
||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
||||
for tag, value in self.cohort.items():
|
||||
self.client.set_tag(self.run_id, tag, value)
|
||||
|
||||
def _experiment_id(self) -> str:
|
||||
return experiment_id(self.client, registered_name(self.domain, self.scenario))
|
||||
|
||||
def repository(self, entity: str) -> ReadOnlyRepository:
|
||||
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
|
||||
return ReadOnlyRepository(resolve_repository(self.domain, entity))
|
||||
|
||||
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
||||
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
||||
named for its kind."""
|
||||
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
|
||||
|
||||
def log_routine(self, kind: ArtifactKind | str, record: dict[str, Any]) -> None:
|
||||
"""ML-01a: what one routine did in this run, as it ran. A routine that was deliberately skipped records
|
||||
that too (for instance a class balance of "none"), so the run still says what happened."""
|
||||
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
||||
|
||||
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
|
||||
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
|
||||
`modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input
|
||||
example, so no patient data reaches MLflow."""
|
||||
if self.modelo_sha is not None:
|
||||
raise RuntimeError("this run already logged its model")
|
||||
if self.environment is Environment.PROD and type(python_model).__module__ == "__main__":
|
||||
raise ValueError("a PROD run only logs models whose class lives in a module; "
|
||||
f"{type(python_model).__name__} was defined in a notebook or script")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / MODEL_PATH
|
||||
mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature)
|
||||
sha = model_sha(path)
|
||||
self.client.log_artifacts(self.run_id, str(path), MODEL_PATH)
|
||||
self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha)
|
||||
self.modelo_sha = sha
|
||||
return sha
|
||||
|
||||
def finish(self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None) -> "TrainingRun":
|
||||
"""Logs metrics and parameters and closes the run. Registering it as a version is the registry's
|
||||
(`models.io.registry.registry.register_run`)."""
|
||||
for key, value in (metrics or {}).items():
|
||||
self.client.log_metric(self.run_id, key, value)
|
||||
for key, value in (hyperparameters or {}).items():
|
||||
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
||||
self.client.set_terminated(self.run_id)
|
||||
return self
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Training and scoring of a domain's models, what the Dagster jobs run. A domain's module
|
||||
`models.<domain>.jobs` binds them to its models (`MODELS`) and its reports: `train(name,
|
||||
as_of)` registers a new version (MLflow) with its two generated reports; `score(name)` writes
|
||||
the champion's risk batch."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
|
||||
from persistance import gold, registry
|
||||
|
||||
|
||||
class EmptyCohort(ValueError):
|
||||
"""The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from."""
|
||||
|
||||
|
||||
class Predictor(mlflow.pyfunc.PythonModel):
|
||||
"""A fitted model as MLflow serves it: patient timelines in (gold `<domain>_events` rows
|
||||
with each patient's index date), one row per patient and horizon out."""
|
||||
|
||||
def __init__(self, spec, fitted):
|
||||
self.spec, self.fitted = spec, fitted
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||
return self.spec.predict(self.fitted, model_input)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jobs:
|
||||
domain: str
|
||||
models: dict
|
||||
technical_validation: Callable[..., dict]
|
||||
interpretability: Callable[..., dict]
|
||||
|
||||
@property
|
||||
def events(self) -> str:
|
||||
return f"{self.domain}_events"
|
||||
|
||||
def routine(self) -> list[str]:
|
||||
"""The models a train run takes when none is named: all of them."""
|
||||
return list(self.models)
|
||||
|
||||
def scored(self) -> list[str]:
|
||||
"""The models a score run takes when none is named: all of them."""
|
||||
return list(self.models)
|
||||
|
||||
def registered(self, name: str) -> str:
|
||||
return f"{self.domain}.{name}"
|
||||
|
||||
def train(self, name: str, as_of: date | None = None) -> int:
|
||||
"""A new registered version of the model, trained on its cohort's timelines up to
|
||||
`as_of` (default: today), with its metrics and its two generated reports."""
|
||||
spec, as_of = self.models[name], as_of or date.today()
|
||||
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, found = spec.train(events, as_of)
|
||||
else:
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, data = spec.train(events, as_of)
|
||||
found = {
|
||||
"technical_validation": self.technical_validation(spec, metrics, data),
|
||||
"interpretability": self.interpretability(spec, fitted, data),
|
||||
}
|
||||
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
||||
# for its idle workers to time out (5 minutes) before it can end.
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
||||
model = Predictor(spec, fitted)
|
||||
return registry.register(self.registered(name), model, params, metrics, found)
|
||||
|
||||
def score(self, name: str) -> int | None:
|
||||
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
||||
batch; None when the model has no champion yet."""
|
||||
found = registry.champion(self.registered(name))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
|
||||
gold.save_scores(self.registered(name), version, risks)
|
||||
return version
|
||||
@@ -1,84 +0,0 @@
|
||||
"""What a notebook run from the platform works with (`models.pipelines.experiment`): the cohort build's file it was
|
||||
run on and, if one was chosen, a registered model version.
|
||||
|
||||
from models.notebook import experiment
|
||||
|
||||
exp = experiment()
|
||||
cohort = exp.cohort() # the build's rows, checked against the cohort contract
|
||||
model = exp.model() # the chosen version, loaded; None if none was chosen
|
||||
run = exp.training_run() # a DEV training run linked to this build's file (ML-02, ML-03)
|
||||
run.log_routine("MUESTREO", {...})
|
||||
run.log_model(MyModel(...))
|
||||
version = exp.register(run.finish(metrics={...}))
|
||||
|
||||
The notebook gets no database connection and no access to the platform's MLflow (ML-04, ML-05): the build's file
|
||||
is its data, and what it trains goes to a store of its own that the platform imports afterwards as DEV. Outside the
|
||||
platform, set `COHORT_FILE`, `MODELS_DOMAIN` and `MODELS_SCENARIO` (and `MODEL_VERSION`) to work the same way.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
COHORT_FILE_ENV = "COHORT_FILE"
|
||||
DOMAIN_ENV = "MODELS_DOMAIN"
|
||||
SCENARIO_ENV = "MODELS_SCENARIO"
|
||||
VERSION_ENV = "MODEL_VERSION"
|
||||
MODEL_PATH_ENV = "MODEL_PATH"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Experiment:
|
||||
domain: str
|
||||
scenario: str
|
||||
cohort_path: Path
|
||||
version: str | None = None
|
||||
|
||||
def cohort(self) -> pd.DataFrame:
|
||||
from models.io.storage import read_cohort
|
||||
|
||||
return read_cohort(self.cohort_path)
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
"""The build's own metadata: its cut-off, parameters, rules and attrition."""
|
||||
from models.io.storage import read_metadata
|
||||
|
||||
return read_metadata(self.cohort_path)
|
||||
|
||||
def model(self):
|
||||
"""The chosen version as an MLflow pyfunc (`.predict(cohort)`), or `None`. On the platform it's a copy of the
|
||||
version's saved model (`MODEL_PATH`); elsewhere it's loaded from the registry."""
|
||||
if self.version is None:
|
||||
return None
|
||||
import mlflow.pyfunc
|
||||
|
||||
if path := os.environ.get(MODEL_PATH_ENV):
|
||||
return mlflow.pyfunc.load_model(path)
|
||||
from models.io.registry import registry
|
||||
|
||||
return mlflow.pyfunc.load_model(registry.resolve(self.domain, self.scenario, self.version).model_uri)
|
||||
|
||||
def training_run(self, scenario: str | None = None):
|
||||
"""A DEV run of this domain, linked to the build's file. On the platform it goes to the job's own MLflow and
|
||||
is copied into the real one, as DEV, when the notebook ends (`models.io.notebook_import`)."""
|
||||
from models.io.lineage import cohort_reference, file_sha256
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
cohort = cohort_reference(self.lineage(), file_sha256(self.cohort_path))
|
||||
return TrainingRun(domain=self.domain, scenario=scenario or self.scenario, environment="DEV", cohort=cohort)
|
||||
|
||||
def register(self, run) -> str:
|
||||
"""Registers a finished run as a new DEV version of its scenario and returns the version."""
|
||||
from models.io.registry import registry
|
||||
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def experiment() -> Experiment:
|
||||
missing = [name for name in (COHORT_FILE_ENV, DOMAIN_ENV, SCENARIO_ENV) if not os.environ.get(name)]
|
||||
if missing:
|
||||
raise RuntimeError(f"this notebook wasn't run from the platform: {', '.join(missing)} not set")
|
||||
return Experiment(os.environ[DOMAIN_ENV], os.environ[SCENARIO_ENV], Path(os.environ[COHORT_FILE_ENV]),
|
||||
os.environ.get(VERSION_ENV) or None)
|
||||
-267
@@ -1,267 +0,0 @@
|
||||
"""Extraction of results from the PDF reports stored with each study
|
||||
(VAR-01..09, VARM-01..05).
|
||||
|
||||
Each `OcrJob` says which table, which stored PDF and which result columns
|
||||
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
|
||||
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
|
||||
entry in `OCR_JOBS`.
|
||||
|
||||
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
|
||||
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
|
||||
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
|
||||
are then located by caption matching tolerant to OCR errors, and by
|
||||
lexicon matching over the narrative with NegEx-style negation handling
|
||||
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
|
||||
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
|
||||
value carries a 0..1 confidence: caption match quality x parse quality x
|
||||
Tesseract's word confidence.
|
||||
"""
|
||||
import json
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlmodel import select
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from core.ocr import OcrEstatus
|
||||
from extraction import FieldKind, FieldSpec, read_document
|
||||
from extraction.nlp import RecordExtractor, SegmentLine
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
||||
from extraction.ocr import TesseractOcr
|
||||
from models.io.storage import resolve_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
# Below this confidence a value is stored but flagged for manual review.
|
||||
REVIEW_THRESHOLD = 0.8
|
||||
|
||||
|
||||
@dataclass
|
||||
class OcrExtractionResult:
|
||||
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
|
||||
|
||||
values: dict[str, Any]
|
||||
confianza: float
|
||||
estatus: OcrEstatus
|
||||
requiere_revision: bool
|
||||
metodo_principal: str
|
||||
metodo_alternativo: str | None = None
|
||||
quality_validation: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class OcrColumnSpec:
|
||||
"""The columns of one extraction on its table: the stored PDF, the
|
||||
five traceability columns, and extractor result key -> result column."""
|
||||
|
||||
blob_field: str
|
||||
confianza_field: str
|
||||
estatus_field: str
|
||||
requiere_revision_field: str
|
||||
metodo_principal_field: str
|
||||
metodo_alternativo_field: str
|
||||
result_field_map: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
class OcrExtractor(ABC):
|
||||
@abstractmethod
|
||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
||||
"""Reads `pdf_blob`. A document that can be read but where nothing
|
||||
is found returns estatus FALLIDO with requiere_revision; an
|
||||
unreadable one may raise, and the driver records FALLIDO."""
|
||||
|
||||
|
||||
class ReportOcrExtractor(OcrExtractor):
|
||||
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
|
||||
|
||||
fields: ClassVar[dict[str, FieldSpec]]
|
||||
|
||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
||||
document = read_document("reporte.pdf", pdf_blob)
|
||||
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
|
||||
found = RecordExtractor(list(self.fields.values())).extract(lines)
|
||||
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
|
||||
|
||||
sources = {page.source for page in document.pages}
|
||||
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
|
||||
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
|
||||
evidence = {key: value.to_dict() for key, value in by_key.items()}
|
||||
missing = [key for key in self.fields if key not in by_key]
|
||||
if missing:
|
||||
evidence["faltantes"] = missing
|
||||
|
||||
if not by_key:
|
||||
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
|
||||
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
|
||||
return OcrExtractionResult(
|
||||
values={key: value.value for key, value in by_key.items()},
|
||||
confianza=confianza,
|
||||
estatus=OcrEstatus.REALIZADO,
|
||||
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
|
||||
metodo_principal=principal,
|
||||
metodo_alternativo=alternativo,
|
||||
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
|
||||
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
|
||||
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
|
||||
|
||||
|
||||
class VphOcrExtractor(ReportOcrExtractor):
|
||||
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
|
||||
|
||||
fields = {
|
||||
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
|
||||
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
|
||||
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
|
||||
}
|
||||
|
||||
|
||||
class CinGradoOcrExtractor(ReportOcrExtractor):
|
||||
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
|
||||
|
||||
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
|
||||
|
||||
|
||||
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
|
||||
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
|
||||
|
||||
fields = {
|
||||
"grado": choice_field(
|
||||
"bx_grado_histologico",
|
||||
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
|
||||
scan_free_text=True,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
|
||||
return OcrColumnSpec(
|
||||
blob_field=blob_field,
|
||||
confianza_field=f"{prefix}_ocr_confianza",
|
||||
estatus_field=f"{prefix}_ocr_estatus",
|
||||
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
|
||||
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
|
||||
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
|
||||
result_field_map=results,
|
||||
)
|
||||
|
||||
|
||||
CIT_VPH_COLUMNS = _ocr_columns(
|
||||
"cit_vph",
|
||||
"cit_vph_pdf_blob",
|
||||
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
|
||||
)
|
||||
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
|
||||
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OcrJob:
|
||||
domain: str
|
||||
entity: str # repository name in persistance.<domain>, without `_repository`
|
||||
label: str
|
||||
columns: OcrColumnSpec
|
||||
extractor: type[OcrExtractor]
|
||||
|
||||
@property
|
||||
def repository(self) -> Repository:
|
||||
"""Resolved on use, so it follows whatever database URL is active."""
|
||||
return resolve_repository(self.domain, self.entity)
|
||||
|
||||
|
||||
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
|
||||
(job.domain, job.entity): job
|
||||
for job in (
|
||||
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
|
||||
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
|
||||
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class OcrRunSummary:
|
||||
processed: int = 0
|
||||
skipped_already_done: int = 0
|
||||
failed: int = 0
|
||||
needs_review: int = 0
|
||||
|
||||
|
||||
def run_pending_extractions(
|
||||
repository: Repository,
|
||||
spec: OcrColumnSpec,
|
||||
extractor: OcrExtractor,
|
||||
*,
|
||||
domain: str,
|
||||
entity: str,
|
||||
governance_repository: Repository | None = None,
|
||||
source_description: str | None = None,
|
||||
limit: int = 500,
|
||||
) -> OcrRunSummary:
|
||||
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
|
||||
persisted result is what prevents duplicate runs. A failing row is
|
||||
stored as FALLIDO and the batch continues. With `governance_repository`,
|
||||
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
|
||||
summary = OcrRunSummary()
|
||||
model = repository.model
|
||||
primary_key = list(model.__table__.primary_key.columns)
|
||||
estatus = getattr(model, spec.estatus_field)
|
||||
with_report = getattr(model, spec.blob_field).is_not(None)
|
||||
done = estatus == OcrEstatus.REALIZADO.value
|
||||
with repository.open_session() as session:
|
||||
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
|
||||
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
|
||||
for tracked in session.exec(pending).all():
|
||||
pk_value = getattr(tracked, primary_key[0].name)
|
||||
started_at = datetime.now(timezone.utc)
|
||||
try:
|
||||
result = extractor.extract(getattr(tracked, spec.blob_field))
|
||||
except NotImplementedError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
|
||||
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
|
||||
|
||||
for result_key, column in spec.result_field_map.items():
|
||||
if result_key in result.values:
|
||||
setattr(tracked, column, result.values[result_key])
|
||||
setattr(tracked, spec.confianza_field, result.confianza)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
|
||||
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
|
||||
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
|
||||
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
|
||||
session.add(tracked)
|
||||
if result.estatus == OcrEstatus.FALLIDO:
|
||||
summary.failed += 1
|
||||
else:
|
||||
summary.processed += 1
|
||||
if result.requiere_revision:
|
||||
summary.needs_review += 1
|
||||
|
||||
if governance_repository is not None:
|
||||
governance_repository.create(
|
||||
ExtractionRun(
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
entity_pk=str(pk_value),
|
||||
column_extracted=",".join(spec.result_field_map.values()),
|
||||
source_description=source_description,
|
||||
source_started_at=started_at,
|
||||
source_ended_at=datetime.now(timezone.utc),
|
||||
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
|
||||
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
|
||||
quality_validation=result.quality_validation,
|
||||
estatus=(
|
||||
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
|
||||
).value,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
return summary
|
||||
@@ -1 +0,0 @@
|
||||
"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge."""
|
||||
@@ -1,70 +0,0 @@
|
||||
"""Builds a cohort: all patients -> index date -> A1 -> ... -> An -> study population.
|
||||
|
||||
Lists the steps of `models.steps.cohort`, gives each rule its own `em_<rule>` and `a_<rule>` node, and runs them.
|
||||
"""
|
||||
|
||||
import types
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
||||
|
||||
from persistance.edges.dbt import DbtQueryRepository
|
||||
|
||||
from models.io.contracts import BuiltCohort, CohortQueries
|
||||
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
||||
|
||||
INPUTS = ("cohort_queries", "dbt_queries")
|
||||
|
||||
|
||||
def _fresh(function):
|
||||
"""A copy to decorate: Hamilton keeps a decorator on the function itself, so decorating the step would carry it into
|
||||
the next build."""
|
||||
copy = types.FunctionType(function.__code__, function.__globals__, function.__name__, function.__defaults__,
|
||||
function.__closure__)
|
||||
copy.__annotations__, copy.__doc__ = dict(function.__annotations__), function.__doc__
|
||||
copy.__module__, copy.__qualname__ = function.__module__, function.__qualname__
|
||||
return copy
|
||||
|
||||
|
||||
def build_driver(queries: CohortQueries) -> driver.Driver:
|
||||
"""The chain for the cohort's rules, in their order."""
|
||||
rules = list(queries.rules)
|
||||
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
||||
nodes = [
|
||||
all_patients,
|
||||
indexed,
|
||||
parameterize(**{f"em_{rule.name}": {"rule": value(rule)} for rule in rules})(_fresh(excluded)),
|
||||
parameterize(**{f"a_{rule.name}": {"population": source(before), "flagged": source(f"em_{rule.name}")}
|
||||
for rule, before in zip(rules, previous)})(_fresh(remaining)),
|
||||
inject(last=source(f"a_{rules[-1].name}"))(_fresh(study_population)),
|
||||
inject(populations=group(*[source(f"a_{rule.name}") for rule in rules]), rules=value(rules))(_fresh(attrition)),
|
||||
]
|
||||
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
||||
|
||||
|
||||
def build_cohort(queries: CohortQueries, dbt_queries: DbtQueryRepository) -> BuiltCohort:
|
||||
"""Runs the chain; `dbt_queries` is the domain's `dbt_query_repository`."""
|
||||
results = build_driver(queries).execute(["study_population", "attrition"],
|
||||
inputs={"cohort_queries": queries, "dbt_queries": dbt_queries})
|
||||
return BuiltCohort(results["study_population"], results["attrition"])
|
||||
|
||||
|
||||
def mermaid(graph) -> str:
|
||||
"""The chain as a Mermaid diagram, read from the graph without running it."""
|
||||
def label(name: str) -> str:
|
||||
if name.startswith("em_"):
|
||||
return f'{name}["EM: {name[3:]}"]'
|
||||
if name.startswith("a_"):
|
||||
return f'{name}["A: {name[2:]}"]'
|
||||
return f"{name}[({name})]" if name in ("all_patients", "study_population") else f"{name}[{name}]"
|
||||
|
||||
lines = ["graph LR"]
|
||||
for node in graph.nodes.values():
|
||||
if node.name in INPUTS or node.name == "attrition":
|
||||
continue
|
||||
if node.name.startswith("em_"):
|
||||
lines.append(f' r_{node.name[3:]}[/"R: {node.name[3:]}"/] --> {label(node.name)}')
|
||||
lines += [f" {dependency.name} --> {label(node.name)}" for dependency in node.dependencies
|
||||
if dependency.name not in INPUTS]
|
||||
lines += [f" {dependency.name} -.-> attrition" for dependency in graph.nodes["attrition"].dependencies]
|
||||
return "\n".join(lines)
|
||||
@@ -1,207 +0,0 @@
|
||||
"""A notebook uploaded to the platform, run on a cohort build's file and kept as an MLflow run (ML-01a, ML-04, ML-05).
|
||||
|
||||
Each run belongs to the experiment `<domain>-<scenario>/experimentos` and is tagged with the notebook's name and
|
||||
content hash, the build's file (`models.io.lineage.cohort_reference`), the model version it was given, if any, the
|
||||
code version and where it ran (`sandbox`: `contenedor` or `local`). It holds the notebook as uploaded (`notebook/`),
|
||||
the page with its outputs (`report/`), what was imported from it (`importado.json`) and, when it failed,
|
||||
`error.txt`. `start` creates the run; `execute` runs the notebook through an executor and closes the run, so a caller
|
||||
can run it in the background and hand out the run's id at once.
|
||||
|
||||
The notebook runs in a job folder of its own (`models.io.notebook_jobs`) with the build's file as its only data and
|
||||
an MLflow store of its own; what it trained is copied into the platform's MLflow as DEV afterwards
|
||||
(`models.io.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view
|
||||
of the server's files, or this process for development.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import RunStatus
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, \
|
||||
cohort_reference, file_sha256, registered_name
|
||||
from models.io.notebook_import import import_job
|
||||
from models.io.notebook_jobs import JOB_TIMEOUT, JOB_TIMEOUT_ENV, PAGE_FILE, executor, prepare_job, read_job_file, \
|
||||
result_of
|
||||
from models.io.storage import read_metadata
|
||||
from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files
|
||||
from models.steps.report import notebook_sha256, without_outputs
|
||||
|
||||
EXPERIMENT_SUFFIX = "experimentos"
|
||||
KIND_TAG, KIND = "experiment", "notebook"
|
||||
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, VERSION_TAG = "notebook", "notebook.sha256", "model.version"
|
||||
DOMAIN_TAG, SCENARIO_TAG, SANDBOX_TAG = "domain", "scenario", "sandbox"
|
||||
ERROR_PATH, IMPORT_PATH = "error.txt", "importado.json"
|
||||
KEEP_JOBS_ENV = "NOTEBOOK_KEEP_JOBS"
|
||||
# A run still marked as running this long after its job's timeout was cut off (a restart, a killed worker).
|
||||
STALE_MARGIN = timedelta(minutes=30)
|
||||
|
||||
|
||||
def experiment_name(domain: str, scenario: str) -> str:
|
||||
return f"{registered_name(domain, scenario)}/{EXPERIMENT_SUFFIX}"
|
||||
|
||||
|
||||
def check_names(domain: str | None, scenario: str | None) -> None:
|
||||
if domain is not None and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario is not None and not re.fullmatch(r"[\w-]{1,100}", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
|
||||
|
||||
def notebook_name(filename: str) -> str:
|
||||
"""The name a notebook's files are stored under: its file name without folders or extension, in safe characters."""
|
||||
stem = Path(filename.replace("\\", "/")).name.removesuffix(".ipynb")
|
||||
return re.sub(r"[^\w.-]+", "_", stem).strip("._")[:80] or "notebook"
|
||||
|
||||
|
||||
def check_notebook(notebook: Any) -> dict:
|
||||
"""A Jupyter notebook (nbformat 4), or `ValueError` saying why not."""
|
||||
if not isinstance(notebook, dict) or not isinstance(notebook.get("cells"), list):
|
||||
raise ValueError("el archivo no es un notebook de Jupyter (.ipynb)")
|
||||
if notebook.get("nbformat") != 4:
|
||||
raise ValueError(f"solo se aceptan notebooks en formato 4, no {notebook.get('nbformat')!r}")
|
||||
return notebook
|
||||
|
||||
|
||||
def start(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> str:
|
||||
"""Creates the run, stores the notebook as uploaded and returns the run's id; the notebook hasn't run yet."""
|
||||
check_names(domain, scenario)
|
||||
check_notebook(notebook)
|
||||
name = notebook_name(name)
|
||||
client = MlflowClient()
|
||||
tags = {KIND_TAG: KIND, NOTEBOOK_TAG: name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook), DOMAIN_TAG: domain,
|
||||
SCENARIO_TAG: scenario, **cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path)),
|
||||
**code_version()}
|
||||
if version:
|
||||
tags[VERSION_TAG] = str(version)
|
||||
run = client.create_run(experiment_id(client, experiment_name(domain, scenario)), tags=tags, run_name=name)
|
||||
client.log_text(run.info.run_id, json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1),
|
||||
f"notebook/{name}.ipynb")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
def execute(run_id: str, notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> bool:
|
||||
"""Runs the notebook through the executor, imports what it trained, stores its page (the cells that ran, when it
|
||||
failed) and closes the run. Returns whether every cell ran."""
|
||||
client = MlflowClient()
|
||||
runner = executor()
|
||||
client.set_tag(run_id, SANDBOX_TAG, runner.name)
|
||||
job = None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-model-") as tmp:
|
||||
model = _model_copy(client, domain, scenario, version, Path(tmp))
|
||||
job = prepare_job(runner.jobs_root(), run_id, notebook, Path(cohort_path), domain=domain,
|
||||
scenario=scenario, version=version, model_dir=model)
|
||||
runner.run(job)
|
||||
result = result_of(job) or {"ok": False, "error": "el notebook terminó sin resultado"}
|
||||
if page := read_job_file(job, PAGE_FILE):
|
||||
client.log_text(run_id, page.decode("utf-8", "replace"), f"report/{name}.html")
|
||||
cohort = {k: v for k, v in client.get_run(run_id).data.tags.items() if k.startswith("cohort.")}
|
||||
client.log_dict(run_id, import_job(job, run_id, domain, cohort), IMPORT_PATH)
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
finally:
|
||||
if job is not None and not os.environ.get(KEEP_JOBS_ENV):
|
||||
shutil.rmtree(job, ignore_errors=True)
|
||||
if not result["ok"]:
|
||||
client.log_text(run_id, result["error"] or "falló", ERROR_PATH)
|
||||
client.set_terminated(run_id, RunStatus.to_string(RunStatus.FINISHED if result["ok"] else RunStatus.FAILED))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _model_copy(client: MlflowClient, domain: str, scenario: str, version: str | None, folder: Path) -> Path | None:
|
||||
"""The chosen version's saved model, downloaded for the job; `None` without a version or a saved model."""
|
||||
if not version:
|
||||
return None
|
||||
from models.io.registry import registry
|
||||
|
||||
resolved = registry.resolve(domain, scenario, version)
|
||||
if not resolved.modelo_sha:
|
||||
return None
|
||||
return Path(client.download_artifacts(resolved.run_id, MODEL_PATH, str(folder)))
|
||||
|
||||
|
||||
def run_notebook(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> tuple[str, bool]:
|
||||
run_id = start(notebook, name, cohort_path, domain, scenario, version)
|
||||
return run_id, execute(run_id, notebook, notebook_name(name), cohort_path, domain, scenario, version)
|
||||
|
||||
|
||||
def _status(run) -> str:
|
||||
status = run.info.status
|
||||
if status == "RUNNING":
|
||||
started = datetime.fromtimestamp(run.info.start_time / 1000, tz=timezone.utc)
|
||||
timeout = timedelta(seconds=int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT)))
|
||||
return "interrumpido" if datetime.now(timezone.utc) - started > timeout + STALE_MARGIN else "en_curso"
|
||||
return {"FINISHED": "terminado", "FAILED": "fallido", "KILLED": "interrumpido"}.get(status, status.lower())
|
||||
|
||||
|
||||
def _iso(epoch_millis: int | None) -> str | None:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat() if epoch_millis else None
|
||||
|
||||
|
||||
def _describe(run) -> dict[str, Any]:
|
||||
tags = run.data.tags
|
||||
return {"run_id": run.info.run_id, "notebook": tags.get(NOTEBOOK_TAG), "domain": tags.get(DOMAIN_TAG),
|
||||
"scenario": tags.get(SCENARIO_TAG), "version": tags.get(VERSION_TAG),
|
||||
"cohort": {"url": tags.get(COHORT_URL_TAG), "source": tags.get(COHORT_SOURCE_TAG),
|
||||
"build": tags.get(COHORT_BUILD_TAG)},
|
||||
"notebook_sha256": tags.get(NOTEBOOK_SHA_TAG), "sandbox": tags.get(SANDBOX_TAG), "status": _status(run),
|
||||
"started_at": _iso(run.info.start_time), "ended_at": _iso(run.info.end_time)}
|
||||
|
||||
|
||||
def experiments(domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Notebook runs, newest first; `scenario` needs `domain`."""
|
||||
check_names(domain, scenario)
|
||||
client = MlflowClient()
|
||||
pattern = f"{registered_name(domain, scenario) if scenario else (domain + '-%' if domain else '%')}/{EXPERIMENT_SUFFIX}"
|
||||
found = client.search_experiments(filter_string=f"name LIKE '{pattern}'")
|
||||
if not found:
|
||||
return []
|
||||
runs = client.search_runs([e.experiment_id for e in found], filter_string=f"tags.{KIND_TAG} = '{KIND}'",
|
||||
order_by=["attributes.start_time DESC"], max_results=500)
|
||||
return [_describe(run) for run in runs]
|
||||
|
||||
|
||||
def _run(client: MlflowClient, run_id: str):
|
||||
try:
|
||||
run = client.get_run(run_id)
|
||||
except Exception as error:
|
||||
raise LookupError(f"no existe la corrida {run_id!r}") from error
|
||||
if run.data.tags.get(KIND_TAG) != KIND:
|
||||
raise LookupError(f"la corrida {run_id!r} no es de un notebook")
|
||||
return run
|
||||
|
||||
|
||||
def describe(run_id: str) -> dict[str, Any]:
|
||||
"""One notebook run with its files and, if it failed, the error."""
|
||||
client = MlflowClient()
|
||||
run = _run(client, run_id)
|
||||
files = run_files(client, run_id)
|
||||
error = None
|
||||
if any(item["path"] == ERROR_PATH for item in files):
|
||||
error = run_file(client, run_id, ERROR_PATH)[1].decode("utf-8", "replace")
|
||||
return {**_describe(run), "artifacts": files, "error": error}
|
||||
|
||||
|
||||
def artifact(run_id: str, path: str) -> tuple[str, bytes]:
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
return run_file(client, run_id, path)
|
||||
|
||||
|
||||
def page(run_id: str) -> str | None:
|
||||
"""The rendered page, or `None` while there's none."""
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
pages = [item["path"] for item in run_files(client, run_id, "report") if item["path"].endswith(".html")]
|
||||
return run_file(client, run_id, pages[0])[1].decode("utf-8") if pages else None
|
||||
@@ -1,73 +0,0 @@
|
||||
"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage.
|
||||
|
||||
The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them:
|
||||
|
||||
- `export_kit_build`: a build the kit stored, written once to `<armado_id>.parquet`;
|
||||
- `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is
|
||||
reused; otherwise the next number is written.
|
||||
|
||||
The timeline comes from the domain's `timeline_repository` (dbt's view `<domain>_linea_de_tiempo`), cut at the
|
||||
build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the
|
||||
database.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
|
||||
from models.io.contracts import CohortQueries
|
||||
from models.io.lineage import matches, require_match
|
||||
from models.io.storage import cohort_path, dbt_build_path, latest_dbt_build, read_metadata, write_once
|
||||
from models.pipelines.cohort_build import build_cohort
|
||||
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
|
||||
|
||||
NODES = [cohort_events, content_sha256, lineage, cohort_table]
|
||||
|
||||
|
||||
def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]:
|
||||
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build()
|
||||
inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage}
|
||||
results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs)
|
||||
return results["cohort_table"], results["content_sha256"]
|
||||
|
||||
|
||||
def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]:
|
||||
"""The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's
|
||||
`cohort_repository` and `timeline_repository`."""
|
||||
build_id = build_id if build_id is not None else cohorts.latest_build(url)
|
||||
build = None if build_id is None else cohorts.build(build_id)
|
||||
if build is None or build.url != url:
|
||||
raise LookupError(f"no such build of {url}: {build_id}")
|
||||
path = cohort_path(root, url, build.armado_id)
|
||||
if path.exists():
|
||||
require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path))
|
||||
return path, "reused"
|
||||
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)],
|
||||
columns=["pac_id", "fecha_indice"])
|
||||
base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit",
|
||||
"parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()}
|
||||
table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base)
|
||||
write_once(table, path)
|
||||
return path, "exported"
|
||||
|
||||
|
||||
def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]:
|
||||
"""Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and
|
||||
`timeline` are the domain's `dbt_query_repository` and `timeline_repository`."""
|
||||
built = build_cohort(queries, dbt_queries)
|
||||
latest = latest_dbt_build(root, queries.url)
|
||||
number = latest[0] + 1 if latest else 1
|
||||
base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt",
|
||||
"parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(),
|
||||
"rules": json.dumps([rule.name for rule in queries.rules]),
|
||||
"attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")}
|
||||
table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base)
|
||||
if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}):
|
||||
return latest[1], "reused"
|
||||
path = dbt_build_path(root, queries.url, number)
|
||||
write_once(table, path)
|
||||
return path, "exported"
|
||||
@@ -1,51 +0,0 @@
|
||||
"""The nodes every model DAG reads through: a cohort build, its members and their timeline.
|
||||
|
||||
Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows
|
||||
which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories
|
||||
are inputs too: whoever builds the driver passes a domain's `cohort_repository` and a
|
||||
`timeline_repository` already bound to its query.
|
||||
|
||||
The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off
|
||||
(`known_until`): the build's `conocida_hasta`, or the moment of the read when the build has none. The run
|
||||
records `known_until`, so the read can be repeated once silver keeps its history.
|
||||
"""
|
||||
|
||||
from dataclasses import fields
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
from persistance.edges.gold import CohortBuild, CohortMember, CohortRepository
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.assets import Asset
|
||||
|
||||
MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember))
|
||||
|
||||
|
||||
class UnknownBuild(LookupError):
|
||||
"""The requested cohort build doesn't exist."""
|
||||
|
||||
|
||||
def cohort_build(cohorte_armado: Asset, cohort_repository: CohortRepository, build_id: int) -> CohortBuild:
|
||||
"""The build's lineage: cohort, version, fingerprints and cut-offs."""
|
||||
build = cohort_repository.build(build_id)
|
||||
if build is None:
|
||||
raise UnknownBuild(f"cohort build {build_id} doesn't exist")
|
||||
return build
|
||||
|
||||
|
||||
def members(cohorte_miembro: Asset, cohort_repository: CohortRepository, cohort_build: CohortBuild) -> pd.DataFrame:
|
||||
"""One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`."""
|
||||
return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS))
|
||||
|
||||
|
||||
def known_until(cohort_build: CohortBuild) -> datetime:
|
||||
"""The load cut-off of the read: the build's `conocida_hasta`, or now (UTC) when the build has none."""
|
||||
return cohort_build.conocida_hasta or datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, known_until: datetime,
|
||||
timeline_repository: TimelineRepository) -> pd.DataFrame:
|
||||
"""The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and at `known_until`."""
|
||||
rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of,
|
||||
known_until=known_until)
|
||||
return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS))
|
||||
@@ -1,48 +0,0 @@
|
||||
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
|
||||
|
||||
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
|
||||
in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its
|
||||
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
|
||||
were already reported together are not rendered again.
|
||||
|
||||
The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the
|
||||
environment it inherits.
|
||||
"""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io.lineage import cohort_reference, file_sha256, registered_name
|
||||
from models.io.rendering import render_notebook
|
||||
from models.io.storage import read_metadata
|
||||
from models.io.tracking import find_run, record_report
|
||||
from models.steps.report import notebook_sha256, without_outputs
|
||||
|
||||
COHORT_FILE_ENV = "COHORT_FILE"
|
||||
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
|
||||
|
||||
|
||||
def report_experiment(domain: str, scenario: str, notebook: Path) -> str:
|
||||
return f"{registered_name(domain, scenario)}/{notebook.stem}"
|
||||
|
||||
|
||||
def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str,
|
||||
kernel: str | None = None) -> tuple[str, bool]:
|
||||
"""Returns the report's run id and whether it was rendered now."""
|
||||
notebook_path, cohort_path = Path(notebook_path), Path(cohort_path)
|
||||
notebook = json.loads(notebook_path.read_text())
|
||||
experiment = report_experiment(domain, scenario, notebook_path)
|
||||
tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook),
|
||||
**cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))}
|
||||
client = MlflowClient()
|
||||
if existing := find_run(client, experiment, tags):
|
||||
return existing, False
|
||||
with tempfile.TemporaryDirectory(prefix="report-") as folder:
|
||||
page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html",
|
||||
env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel)
|
||||
source = Path(folder) / notebook_path.name
|
||||
source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1))
|
||||
return record_report(client, experiment, tags, {"report": page, "notebook": source}), True
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`).
|
||||
|
||||
The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`,
|
||||
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome and its horizon, and the cohort build it scored. A batch
|
||||
points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same
|
||||
estimate again adds nothing: Persistance finds the batch by its content.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
|
||||
from models.io.storage import read_metadata, store_risk_batch
|
||||
from models.steps.risks import risk_rows
|
||||
|
||||
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
REQUIRED = (*PROVENANCE, "desenlace", "horizonte_anios", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
|
||||
|
||||
|
||||
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
|
||||
"""Returns the batch's `lote_id` and whether it was written now."""
|
||||
metadata = read_metadata(estimate_path)
|
||||
if missing := [key for key in REQUIRED if not metadata.get(key)]:
|
||||
raise ValueError(f"{estimate_path} lacks {missing}: write it with `python -m models estimate`")
|
||||
if metadata[COHORT_SOURCE_TAG] != "kit":
|
||||
raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, "
|
||||
"which has no row in cohorte_armado for its batch to point to")
|
||||
rows = risk_rows(pd.read_parquet(estimate_path), float(metadata["horizonte_anios"]))
|
||||
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
|
||||
metadata["desenlace"], rows)
|
||||
@@ -1,4 +0,0 @@
|
||||
"""The plain functions pipelines are built from: each becomes a Hamilton node once a pipeline lists it.
|
||||
|
||||
They neither read nor write on their own: what they read comes in as a parameter, and a pipeline decides when they run.
|
||||
"""
|
||||
@@ -1,52 +0,0 @@
|
||||
"""The steps of a cohort build: all patients, the index date, each rule's excluded members and what remains.
|
||||
|
||||
They know no rule by name: a pipeline gives each rule its own `excluded` and `remaining` node. The queries run through
|
||||
the domain's `dbt_query_repository`.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from persistance.edges.dbt import DbtQueryRepository
|
||||
|
||||
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||
|
||||
|
||||
def _frame(rows: list[dict], columns: list[str]) -> pd.DataFrame:
|
||||
return pd.DataFrame(rows) if rows else pd.DataFrame(columns=columns)
|
||||
|
||||
|
||||
def all_patients(cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||
return _frame(dbt_queries.read(cohort_queries.all_patients), ["pac_id"])
|
||||
|
||||
|
||||
def indexed(all_patients: pd.DataFrame, cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||
"""The patients with an index date. A patient outside `all_patients` is an error, not attrition."""
|
||||
index = _frame(dbt_queries.read(cohort_queries.index_date), ["pac_id", "fecha_indice"])
|
||||
if index["pac_id"].duplicated().any():
|
||||
raise CohortDefinitionError("the index query gives a patient more than one index date")
|
||||
if unknown := len(set(index["pac_id"]) - set(all_patients["pac_id"])):
|
||||
raise CohortDefinitionError(f"the index query gives {unknown} patients outside all patients")
|
||||
return index.assign(fecha_indice=pd.to_datetime(index["fecha_indice"]).dt.date)
|
||||
|
||||
|
||||
def excluded(rule: ExclusionRule, dbt_queries: DbtQueryRepository) -> set:
|
||||
"""Everyone the rule flags."""
|
||||
return {row["pac_id"] for row in dbt_queries.read(rule.sql)}
|
||||
|
||||
|
||||
def remaining(population: pd.DataFrame, flagged: set) -> pd.DataFrame:
|
||||
"""The previous population minus a rule's excluded members."""
|
||||
return population[~population["pac_id"].isin(flagged)]
|
||||
|
||||
|
||||
def study_population(last: pd.DataFrame) -> pd.DataFrame:
|
||||
return last
|
||||
|
||||
|
||||
def attrition(all_patients: pd.DataFrame, indexed: pd.DataFrame, populations: list[pd.DataFrame],
|
||||
rules: list[ExclusionRule]) -> pd.DataFrame:
|
||||
"""Each rule is charged only for those it removes from the population it receives."""
|
||||
sizes = [("all_patients", len(all_patients)), ("indexed", len(indexed)),
|
||||
*[(rule.name, len(population)) for rule, population in zip(rules, populations)]]
|
||||
rows = [(step, n, None if i == 0 else sizes[i - 1][1] - n) for i, (step, n) in enumerate(sizes)]
|
||||
return pd.DataFrame(rows, columns=["step", "n", "excluded"]).astype({"excluded": "Int64"})
|
||||
@@ -1,42 +0,0 @@
|
||||
"""The steps from a study population and the timeline to a build's table, with its lineage."""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
|
||||
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
|
||||
from models.io.lineage import table_sha256
|
||||
|
||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||
TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"]
|
||||
|
||||
|
||||
def cohort_events(timeline_rows: list[dict], study_population: pd.DataFrame, cutoff: date) -> pd.DataFrame:
|
||||
"""The members' events up to `cutoff`, in the file's order. A member without events stops the build."""
|
||||
members = study_population[["pac_id", "fecha_indice"]]
|
||||
frame = pd.DataFrame(timeline_rows, columns=TIMELINE).merge(members, on="pac_id")
|
||||
frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date
|
||||
frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True)
|
||||
frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"])
|
||||
frame = frame[frame["fecha"] <= cutoff]
|
||||
if missing := len(members) - frame["pac_id"].nunique():
|
||||
raise ValueError(f"{missing} members have no events in the timeline")
|
||||
return frame.sort_values(ROW_ORDER, kind="stable")[SCHEMA.names].reset_index(drop=True)
|
||||
|
||||
|
||||
def content_sha256(cohort_events: pd.DataFrame) -> str:
|
||||
"""The hash of the rows alone, so the same content gives the same hash whenever it's built."""
|
||||
return table_sha256(pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False))
|
||||
|
||||
|
||||
def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str) -> dict:
|
||||
return {**base_lineage, "n_members": cohort_events["pac_id"].nunique(), "content_sha256": content_sha256,
|
||||
"built_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
|
||||
"""The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written."""
|
||||
check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}")
|
||||
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
|
||||
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
||||
@@ -1,21 +0,0 @@
|
||||
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
|
||||
def without_outputs(notebook: dict) -> dict:
|
||||
"""The notebook as written: code cells keep their source and lose their outputs."""
|
||||
cleared = copy.deepcopy(notebook)
|
||||
for cell in cleared["cells"]:
|
||||
if cell["cell_type"] == "code":
|
||||
cell["outputs"], cell["execution_count"] = [], None
|
||||
return cleared
|
||||
|
||||
|
||||
def notebook_sha256(notebook: dict) -> str:
|
||||
"""Changes when a cell's type or source changes, not when the notebook is run again."""
|
||||
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
|
||||
for cell in notebook["cells"]]
|
||||
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
|
||||
@@ -1,13 +0,0 @@
|
||||
"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||
|
||||
|
||||
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
|
||||
"""One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a
|
||||
member scored twice or a probability outside 0..1 stops the batch."""
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
|
||||
return [(int(pac_id), float(horizon_years), float(probability), None, None)
|
||||
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
|
||||
@@ -0,0 +1,608 @@
|
||||
"""Interval survival, shared by CaMa and CaCu: the probability of surviving each interval of
|
||||
follow-up, given alive at its start, by a logistic regression and by a Bayesian network with a
|
||||
tabular CPT, mixed per interval; survival to a horizon is the product of the intervals' up to it.
|
||||
|
||||
Each interval's models fit the patients alive at its start (`months >= start`); one censored
|
||||
inside the interval counts as half a risk. The mixture weight of an interval is the one that
|
||||
best predicts patients out of sample (`folds` folds), shrunk toward 50/50 when there are few
|
||||
deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missing value is a
|
||||
category of its own (UNKNOWN).
|
||||
"""
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from itertools import pairwise
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from joblib import Parallel, delayed
|
||||
from scipy.optimize import minimize_scalar
|
||||
from scipy.special import gammaln
|
||||
from sklearn.base import BaseEstimator
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
UNKNOWN = "NA"
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
DAYS_PER_YEAR = 365.25
|
||||
|
||||
|
||||
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
|
||||
"""Whole months from each index to her death or, alive, to `end`, and whether she died;
|
||||
follow-up is cut at `cap_months` (a later death counts as alive)."""
|
||||
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
|
||||
died = (death.notna() & (death <= end)).to_numpy()
|
||||
last = death.where(died, end)
|
||||
days = (last - index).dt.days.to_numpy()
|
||||
months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0)
|
||||
if cap_months:
|
||||
died = died & (months < cap_months)
|
||||
months = np.minimum(months, cap_months)
|
||||
return pd.DataFrame({"months": months, "event": died}, index=index.index)
|
||||
|
||||
|
||||
def band(values: pd.Series, cuts: list) -> pd.Series:
|
||||
"""Values in the bands the cuts make (`<c1`, `c1-(c2-1)`, ..., `≥cn`); empty stays empty."""
|
||||
edges = [-np.inf, *cuts, np.inf]
|
||||
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"]
|
||||
return pd.cut(values, edges, right=False, labels=labels).astype(object)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Constant:
|
||||
"""An interval where everyone at risk had the same outcome: the same probability for all."""
|
||||
|
||||
p: float
|
||||
|
||||
def predict_proba(self, X) -> np.ndarray:
|
||||
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
|
||||
|
||||
|
||||
def _bdeu(code, y, w, q, ess) -> float:
|
||||
"""The outcome's weighted BDeu score given parent configurations `code` (of `q`)."""
|
||||
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
|
||||
aj, ajk = ess / q, ess / q / 2
|
||||
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
|
||||
+ np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
|
||||
|
||||
|
||||
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
|
||||
"""Greedy: the covariate that most improves the outcome's BDeu, until none does."""
|
||||
parents, code, q = [], np.zeros(len(y), int), 1
|
||||
best = _bdeu(code, y, w, q, ess)
|
||||
while len(parents) < max_parents:
|
||||
found = None
|
||||
for j in range(X.shape[1]):
|
||||
if j in parents or q * levels[j] > 200_000:
|
||||
continue
|
||||
c2 = code * levels[j] + X[:, j]
|
||||
score = _bdeu(c2, y, w, q * levels[j], ess)
|
||||
if score > best + 1e-9 and (found is None or score > found[0]):
|
||||
found = (score, j, c2, q * levels[j])
|
||||
if found is None:
|
||||
break
|
||||
best, j, code, q = found
|
||||
parents.append(j)
|
||||
return parents
|
||||
|
||||
|
||||
def _code(X, levels, parents) -> np.ndarray:
|
||||
code = np.zeros(len(X), int)
|
||||
for j in parents:
|
||||
code = code * levels[j] + X[:, j]
|
||||
return code
|
||||
|
||||
|
||||
class IntervalSurvival(BaseEstimator):
|
||||
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
|
||||
|
||||
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
|
||||
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
|
||||
"""
|
||||
|
||||
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
|
||||
folds=5, shrink=20, seed=42): # fmt: skip
|
||||
self.features = features
|
||||
self.borders = borders
|
||||
self.parents = parents
|
||||
self.ess = ess
|
||||
self.max_parents = max_parents
|
||||
self.folds = folds
|
||||
self.shrink = shrink
|
||||
self.seed = seed
|
||||
|
||||
# -- coding: dummies for the LR (first level alphabetically as reference), integer codes
|
||||
# (in order of first appearance) for the HBN; an unseen value takes UNKNOWN's code.
|
||||
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
found = X[list(self.features)].astype(object)
|
||||
return found.where(found.notna(), UNKNOWN).astype(str)
|
||||
|
||||
def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
||||
frame = self._frame(X)
|
||||
columns = []
|
||||
for name in self.features:
|
||||
known = self.categories_[name]
|
||||
codes = pd.Categorical(frame[name], categories=known).codes
|
||||
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
|
||||
columns.append(np.where(codes < 0, fallback, codes))
|
||||
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
|
||||
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
|
||||
|
||||
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
|
||||
fitted = []
|
||||
for a, b in pairwise(self.borders):
|
||||
at_risk = np.where(months >= a)[0]
|
||||
if len(at_risk) == 0:
|
||||
fitted.append((Constant(1.0), ([], np.array([1.0]))))
|
||||
continue
|
||||
m, e = months[at_risk], event[at_risk]
|
||||
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval
|
||||
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk
|
||||
if y.min() == y.max():
|
||||
lr = Constant(float(y[0]))
|
||||
else:
|
||||
lr = LogisticRegression(C=1e6, max_iter=500)
|
||||
lr.fit(X_dum[at_risk], y, sample_weight=w)
|
||||
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
|
||||
return fitted
|
||||
|
||||
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
|
||||
"""The parents and P(survives | parents), smoothed toward the marginal survival."""
|
||||
if self.parents is None:
|
||||
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
|
||||
else:
|
||||
parents = [list(self.features).index(p) for p in self.parents]
|
||||
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
|
||||
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
|
||||
minlength=q * 2).reshape(q, 2) # fmt: skip
|
||||
aj = self.ess / q
|
||||
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
|
||||
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
|
||||
|
||||
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
|
||||
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
|
||||
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
|
||||
return lr, hbn
|
||||
|
||||
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
|
||||
"""Per interval, the LR's weight in the mixture, from out-of-fold predictions."""
|
||||
n = len(months)
|
||||
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
|
||||
oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
|
||||
for k in range(self.folds):
|
||||
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
|
||||
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
|
||||
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
|
||||
weights = []
|
||||
for j, (a, b) in enumerate(pairwise(self.borders)):
|
||||
at_risk = np.where(months >= a)[0]
|
||||
if len(at_risk) == 0:
|
||||
weights.append(0.5)
|
||||
continue
|
||||
m, e = months[at_risk], event[at_risk]
|
||||
y = np.where(e & (m < b), 0, 1)
|
||||
w = np.where(~e & (m < b), 0.5, 1.0)
|
||||
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
|
||||
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
|
||||
|
||||
def loss(x, p1=p1, p2=p2, y=y, w=w):
|
||||
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
|
||||
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||
|
||||
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
|
||||
shrunk = self.shrink / (self.shrink + int((y == 0).sum()))
|
||||
weights.append((1 - shrunk) * best + shrunk * 0.5)
|
||||
return np.array(weights)
|
||||
|
||||
def fit(self, X: pd.DataFrame, months, event):
|
||||
frame = self._frame(X)
|
||||
self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns)
|
||||
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
|
||||
X_dum, X_int = self._encode(X)
|
||||
self.levels_ = X_int.max(axis=0) + 1
|
||||
months, event = np.asarray(months, int), np.asarray(event, bool)
|
||||
if len(X) >= 2 * self.folds:
|
||||
self.weights_ = self._weights(X_dum, X_int, months, event)
|
||||
else:
|
||||
self.weights_ = np.full(len(self.borders) - 1, 0.5)
|
||||
self.fitted_ = self._fit_intervals(X_dum, X_int, months, event)
|
||||
return self
|
||||
|
||||
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Each patient's probability of surviving each interval, by the LR and by the HBN."""
|
||||
return self._predict(self.fitted_, *self._encode(X))
|
||||
|
||||
def survival(self, X: pd.DataFrame) -> np.ndarray:
|
||||
"""Each patient's survival to the end of each interval."""
|
||||
lr, hbn = self.components(X)
|
||||
w = self.weights_[None, :]
|
||||
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- a model over gold timelines
|
||||
|
||||
TRAIN_FRACTION = 0.7
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
|
||||
"scenarios"] # fmt: skip
|
||||
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
|
||||
|
||||
|
||||
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""Temporal: the earliest index dates train, the latest test; ties in the order of the
|
||||
hospital's record numbers, so the split (and every fold after it) is the same on every
|
||||
platform the same data are loaded into."""
|
||||
ordered = members.sort_values(["index_date", "record_number"], kind="stable")
|
||||
cut = int(len(ordered) * train_fraction)
|
||||
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)
|
||||
|
||||
|
||||
def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
|
||||
"""Each member's age at her index (from her birth event), in bands."""
|
||||
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
||||
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
|
||||
return band(age, list(cuts))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Spec:
|
||||
"""Mortality by each horizon from the index (1 minus the interval survival), for the
|
||||
members of a gold cohort, from their timelines (`person_id`, `index_date`, `date`, `type`,
|
||||
`value_code`, `value_num`, `source_table`, `source_id`, `record_number`).
|
||||
|
||||
`covariates(events, members)` gives each member's `features` at her index. With
|
||||
`interval_level`, each combination of the covariates seen in training gets an interval:
|
||||
percentiles of the mortality of `replicas` refits on bootstrap resamples (seed `seed`)."""
|
||||
|
||||
name: str
|
||||
cohort: str
|
||||
features: tuple[str, ...]
|
||||
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame]
|
||||
parents: tuple[str, ...] | None = None
|
||||
borders: tuple[int, ...] = (0, 6, 12, 18) # months
|
||||
cap_months: int = 24
|
||||
interval_level: float | None = None
|
||||
replicas: int = 100
|
||||
seed: int = 0
|
||||
method: str = "interval survival"
|
||||
notes: tuple[str, ...] = () # what the technical report states about the method
|
||||
# Clinical scenarios the report draws: name -> conditions (column, "<" | ">=" | "==" |
|
||||
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
|
||||
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
|
||||
scenario_columns: tuple[str, ...] = ()
|
||||
# Features that are treatments: their odds ratios are reported as associations, unclassified.
|
||||
treatments: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def horizons(self) -> tuple[float, ...]:
|
||||
return tuple(b / 12 for b in self.borders[1:])
|
||||
|
||||
def members(self, events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per member: index date, record number, death date and covariates."""
|
||||
events = events.assign(date=pd.to_datetime(events["date"]),
|
||||
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
|
||||
found = events.groupby("person_id")[["index_date", "record_number"]].first()
|
||||
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
||||
found["death_date"] = death.reindex(found.index)
|
||||
kept = [*self.features, *self.scenario_columns]
|
||||
found = found.join(self.covariates(events, found)[kept])
|
||||
return found.reset_index()
|
||||
|
||||
def _model(self) -> IntervalSurvival:
|
||||
return IntervalSurvival(list(self.features), self.borders, self.parents)
|
||||
|
||||
def _combinations(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
found = X[list(self.features)].astype(object)
|
||||
return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True)
|
||||
|
||||
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
|
||||
combinations = self._combinations(train).drop_duplicates()
|
||||
frame = combinations.replace(UNKNOWN, None)
|
||||
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel
|
||||
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
|
||||
|
||||
def mortality(rows: np.ndarray) -> np.ndarray:
|
||||
sample = train.iloc[rows].reset_index(drop=True)
|
||||
refit = self._model().fit(sample, sample["months"], sample["event"])
|
||||
return 1.0 - refit.survival(frame)
|
||||
|
||||
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
|
||||
tail = 50 * (1 - self.interval_level)
|
||||
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
|
||||
rows = combinations.itertuples(index=False)
|
||||
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
|
||||
|
||||
def train(self, events: pd.DataFrame, as_of) -> tuple:
|
||||
"""Fitted on the earliest members (followed up to `as_of`), with its metrics and what
|
||||
the reports draw."""
|
||||
members = self.members(events)
|
||||
members = members.join(
|
||||
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
|
||||
)
|
||||
train, test = split(members, TRAIN_FRACTION)
|
||||
model = self._model().fit(train, train["months"], train["event"])
|
||||
model.intervals_ = self._intervals(train) if self.interval_level else {}
|
||||
weights = zip(self.borders[1:], model.weights_, strict=True)
|
||||
metrics = {
|
||||
"n_train": float(len(train)), "n_test": float(len(test)),
|
||||
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
|
||||
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
|
||||
} # fmt: skip
|
||||
return model, metrics, {"train": train, "test": test}
|
||||
|
||||
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per member and horizon: her mortality by it, its interval when kept, and
|
||||
the clinical scenarios of the report she falls in (the curves her record draws)."""
|
||||
members = self.members(events)
|
||||
mortality = 1.0 - model.survival(members)
|
||||
n, h = len(members), len(self.horizons)
|
||||
empty = ([np.nan] * h, [np.nan] * h)
|
||||
ends = [model.intervals_.get(tuple(c), empty)
|
||||
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
|
||||
masks = scenario_masks(members, self.scenarios)
|
||||
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
|
||||
for i in range(n)] # fmt: skip
|
||||
return pd.DataFrame({
|
||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
|
||||
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
|
||||
"probability": mortality.ravel(),
|
||||
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
|
||||
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
|
||||
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
||||
})[OUTPUT] # fmt: skip
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reports (curves)
|
||||
|
||||
BOOTSTRAP = 100
|
||||
BOOTSTRAP_SEED = 42
|
||||
|
||||
|
||||
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
|
||||
members = pd.concat([data["train"], data["test"]])
|
||||
return {
|
||||
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
|
||||
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
|
||||
"members": len(members),
|
||||
"index_dates": [str(members["index_date"].min().date()),
|
||||
str(members["index_date"].max().date())],
|
||||
"horizons_months": list(spec.borders[1:]),
|
||||
"follow_up_cap_months": spec.cap_months,
|
||||
"notes": list(spec.notes),
|
||||
"metrics": metrics,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def _curve(fitter, name: str) -> dict:
|
||||
table = fitter.confidence_interval_survival_function_
|
||||
return {
|
||||
"months": fitter.survival_function_.index.tolist(),
|
||||
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
|
||||
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario
|
||||
GRID_POINTS = 200
|
||||
|
||||
|
||||
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||
"""Which members each scenario takes: all of its conditions hold (an unknown value
|
||||
holds none)."""
|
||||
found = {}
|
||||
for name, conditions in scenarios.items():
|
||||
mask = np.ones(len(members), bool)
|
||||
for column, op, value in conditions:
|
||||
v = members[column]
|
||||
if op in ("<", ">="):
|
||||
number = pd.to_numeric(v, errors="coerce")
|
||||
held = number < value if op == "<" else number >= value
|
||||
elif op == "in":
|
||||
held = v.isin(list(value))
|
||||
elif op == "==":
|
||||
held = v == value
|
||||
else:
|
||||
raise ValueError(f"unknown condition {op!r} in scenario {name!r}")
|
||||
mask &= held.fillna(False).to_numpy(bool)
|
||||
found[name] = mask
|
||||
return found
|
||||
|
||||
|
||||
def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict:
|
||||
from models import curves
|
||||
|
||||
d, c, _ = curves.life_table(months, event)
|
||||
k, lam = curves.fit_weibull(d, c)
|
||||
fractional = curves.fit_fractional(d, c, k, lam)
|
||||
grid = np.linspace(0, cap_months, GRID_POINTS)
|
||||
observed = int(months.max())
|
||||
km = curves.kaplan_meier(months, event, observed)
|
||||
return {
|
||||
"observado_hasta": observed,
|
||||
"km": {"months": list(range(observed + 1)),
|
||||
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
|
||||
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
|
||||
"k": k, "lambda": lam},
|
||||
"weibull_fractional": {"t": grid.tolist(),
|
||||
"S": curves.fractional(grid, k, *fractional).tolist(),
|
||||
"alpha": fractional[0], "beta": fractional[1],
|
||||
"lambda": fractional[2]},
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
|
||||
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
|
||||
band, the survival of each combination of the covariates, and each clinical scenario's
|
||||
curves (Kaplan-Meier, Weibull, fractional Weibull) with the model's mean survival over its
|
||||
members and its band. The model's mixture is its own (the original refitted it per
|
||||
scenario): the points show the model as it scores."""
|
||||
from lifelines import KaplanMeierFitter, WeibullFitter
|
||||
|
||||
train = data["train"]
|
||||
months, event = train["months"].to_numpy(), train["event"].to_numpy()
|
||||
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
|
||||
if event.any() and (months > 0).all():
|
||||
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
|
||||
rng = np.random.default_rng(BOOTSTRAP_SEED)
|
||||
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
|
||||
|
||||
# Scenarios: over every member (training first), the observed curves of those with
|
||||
# enough deaths, and the model's mean survival over each, with the same bootstrap band.
|
||||
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
|
||||
masks = scenario_masks(members, spec.scenarios)
|
||||
|
||||
def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]:
|
||||
sample = train.iloc[rows].reset_index(drop=True)
|
||||
refit = spec._model().fit(sample, sample["months"], sample["event"])
|
||||
found = refit.survival(members)
|
||||
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
|
||||
return found[: len(train)].mean(axis=0), by
|
||||
|
||||
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
||||
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
|
||||
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
|
||||
for m in drawn.values()] # fmt: skip
|
||||
jobs += [delayed(mean_survival)(rows) for rows in samples]
|
||||
done = Parallel(n_jobs=-1)(jobs)
|
||||
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
|
||||
band = np.stack([r[0] for r in replicas])
|
||||
point = model.survival(members)
|
||||
scenarios = []
|
||||
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
|
||||
spread = np.array([r[1][name] for r in replicas])
|
||||
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
|
||||
scenarios.append({
|
||||
"escenario": name,
|
||||
"condiciones": [list(c) for c in spec.scenarios[name]],
|
||||
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
|
||||
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
|
||||
**found,
|
||||
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
|
||||
"low": np.clip(low, 0, 1).tolist(),
|
||||
"high": np.clip(high, 0, 1).tolist()}},
|
||||
"bootstrap_replicas": len(replicas),
|
||||
}) # fmt: skip
|
||||
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
|
||||
for n, m in masks.items() if n not in drawn] # fmt: skip
|
||||
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
||||
survival = model.survival(combinations.replace(UNKNOWN, None))
|
||||
return {
|
||||
"model": spec.name,
|
||||
"kind": "curves",
|
||||
"curves": curves,
|
||||
"predicted": {
|
||||
"months": list(spec.borders[1:]),
|
||||
"survival": model.survival(train).mean(axis=0).tolist(),
|
||||
"low": np.percentile(band, 2.5, axis=0).tolist(),
|
||||
"high": np.percentile(band, 97.5, axis=0).tolist(),
|
||||
"name": "LR + HBN combinado (IC 95 % bootstrap)",
|
||||
},
|
||||
"weights_lr": model.weights_.tolist(),
|
||||
"parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_],
|
||||
"combinations": [
|
||||
{**row, "survival": survival[i].tolist()}
|
||||
for i, row in enumerate(combinations.to_dict("records"))
|
||||
],
|
||||
"escenarios": scenarios,
|
||||
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
|
||||
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
|
||||
**risk_factor_report(spec, model, members),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- risk factors
|
||||
|
||||
FACTOR_COLUMNS = (
|
||||
"tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
|
||||
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
|
||||
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
|
||||
"c4_supervivencia", "criterios_cumplidos", "clasificacion",
|
||||
) # fmt: skip
|
||||
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
|
||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
# The model has no variable selection to resample, so stability (2) is not evaluated.
|
||||
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
|
||||
|
||||
|
||||
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The members' risk factors of death by the last horizon (`models.factors`, as the
|
||||
SEER-trained original rates them): odds ratios of dying before it, among those dead before
|
||||
it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at
|
||||
`cap_months`); the Markov blanket is the HBN's parents in any interval."""
|
||||
from models import factors as rated
|
||||
|
||||
horizon = spec.borders[-1]
|
||||
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
||||
died = event & (months < horizon)
|
||||
known = died | (months >= horizon)
|
||||
data = spec._combinations(members)[known].reset_index(drop=True)
|
||||
y, months, event = died[known].astype(int), months[known], event[known]
|
||||
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
|
||||
if len(data) == 0 or y.min() == y.max():
|
||||
return empty
|
||||
features = list(spec.features)
|
||||
treatment = [f for f in features if f in spec.treatments]
|
||||
intrinsic = [f for f in features if f not in spec.treatments]
|
||||
reference = {v: data[v].value_counts().idxmax() for v in features}
|
||||
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
|
||||
|
||||
def complete(table, variables):
|
||||
return rated.complete(table, variables, reference, data, months, event, horizon,
|
||||
SURVIVAL_COLUMNS) # fmt: skip
|
||||
|
||||
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
|
||||
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
|
||||
try:
|
||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
|
||||
intrinsic) # fmt: skip
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
return empty
|
||||
tab["c2_estabilidad"] = np.nan
|
||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket)
|
||||
tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
both = intrinsic + treatment
|
||||
try:
|
||||
tr = rated.odds_ratios(data, y, both, reference, "OR_muerte")
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
tr = None
|
||||
if tr is not None:
|
||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||
tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
|
||||
treatment) # fmt: skip
|
||||
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
|
||||
tab = pd.concat([tab, tr], ignore_index=True)
|
||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
|
||||
tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False])
|
||||
return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True)
|
||||
|
||||
|
||||
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
|
||||
"""Per clinical scenario, the classified factors and treatments nearly all of its
|
||||
members have (definitorios) or most have (mayoritarios)."""
|
||||
from models import factors as rated
|
||||
|
||||
found = rated.classified(table) if len(table) else table
|
||||
data = spec._combinations(members)
|
||||
rows = []
|
||||
for name, mask in scenario_masks(members, spec.scenarios).items():
|
||||
if not mask.any() or found.empty:
|
||||
continue
|
||||
rows.append({
|
||||
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
|
||||
"n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
|
||||
|
||||
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
|
||||
"""The interpretability report's risk factors: the table and each scenario's summary."""
|
||||
table = risk_factors(spec, model, members)
|
||||
rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON
|
||||
return {
|
||||
"factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows},
|
||||
"factores_escenarios": scenario_factors(spec, members, table),
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
"""TEA's models: the EEG analysis (`eeg`)."""
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker,
|
||||
zone and outcome, how a child's deviation from the age curve (z) goes with an altered
|
||||
ADOS-2 item or a high CSS, adjusted for age and module.
|
||||
|
||||
- An item: Firth's penalised logistic regression of "altered" on z (the principal model; its
|
||||
odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a
|
||||
cumulative-logit model of the item's level as sensitivity; the CSS the other way round.
|
||||
- q: Benjamini–Hochberg within each biomarker.
|
||||
- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so
|
||||
its probabilities average to the observed rate), and the reference child's (z = 0, the
|
||||
cohort's mean age, the commonest module).
|
||||
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import optimize, stats
|
||||
from scipy.special import expit
|
||||
from statsmodels.stats.multitest import multipletests
|
||||
|
||||
from core.tea import association as spec
|
||||
|
||||
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
||||
MIN_ROWS = 8
|
||||
TOO_FEW = "too few data or no variation"
|
||||
|
||||
|
||||
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
|
||||
"""Item `number`'s algorithm score for each child whose module administers it."""
|
||||
name, modules = spec.ITEMS[number]
|
||||
if name not in frame or "module" not in frame:
|
||||
return pd.Series(np.nan, index=frame.index)
|
||||
v = pd.to_numeric(frame[name], errors="coerce")
|
||||
v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2)
|
||||
return v.where(frame["module"].isin(modules))
|
||||
|
||||
|
||||
def has_items(frame: pd.DataFrame) -> bool:
|
||||
scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1)
|
||||
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
|
||||
|
||||
|
||||
@dataclass
|
||||
class Design:
|
||||
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
|
||||
the cohort's mean and each categorical one against its commonest level."""
|
||||
|
||||
predictor: str
|
||||
numeric: dict[str, float] = field(default_factory=dict)
|
||||
categorical: dict[str, list[str]] = field(default_factory=dict)
|
||||
reference: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
|
||||
d = cls(predictor)
|
||||
for a in (a for a in spec.ADJUST if a in t):
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
if v.astype(float).std() > 0:
|
||||
d.numeric[a] = float(v.astype(float).mean())
|
||||
continue
|
||||
commonest = v.value_counts().index[0]
|
||||
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
|
||||
return d
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return [
|
||||
"intercept",
|
||||
self.predictor,
|
||||
*self.numeric,
|
||||
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
|
||||
]
|
||||
|
||||
def matrix(self, t: pd.DataFrame) -> np.ndarray:
|
||||
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
|
||||
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
|
||||
known = np.ones(len(t), bool)
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str)
|
||||
cols += [(v == x).to_numpy(float) for x in levels]
|
||||
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
|
||||
X = np.column_stack(cols)
|
||||
X[~known] = np.nan
|
||||
return X
|
||||
|
||||
def state(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
"categorical": self.categorical,
|
||||
"reference": self.reference,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_state(cls, s: dict) -> "Design":
|
||||
return cls(
|
||||
s["predictor"],
|
||||
dict(s["numeric"]),
|
||||
{k: list(v) for k, v in s["categorical"].items()},
|
||||
dict(s["reference"]),
|
||||
)
|
||||
|
||||
|
||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
||||
def _penalised(b, X, y) -> float:
|
||||
eta = X @ b
|
||||
w = expit(eta) * (1 - expit(eta))
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
|
||||
|
||||
|
||||
def _gradient(b, X, y):
|
||||
"""The penalised score and the information at `b`."""
|
||||
p = expit(X @ b)
|
||||
w = p * (1 - p)
|
||||
info = X.T @ (X * w[:, None])
|
||||
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + leverage * (0.5 - p)), info
|
||||
|
||||
|
||||
def _firth_fit(X, y, max_iter=200, tol=1e-10):
|
||||
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
|
||||
b = np.zeros(X.shape[1])
|
||||
best = _penalised(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
score, info = _gradient(b, X, y)
|
||||
step, t = np.linalg.solve(info, score), 1.0
|
||||
while t > 1e-8:
|
||||
trial = _penalised(b + t * step, X, y)
|
||||
if trial >= best - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, best = b + t * step, trial
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, best
|
||||
|
||||
|
||||
def _firth_profile(value, j, X, y, start) -> float:
|
||||
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
|
||||
free = [k for k in range(X.shape[1]) if k != j]
|
||||
|
||||
def negative(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _penalised(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
return -v, -_gradient(b, X, y)[0][free]
|
||||
|
||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
||||
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
|
||||
each side of `centre`, searched in steps of `scale` (infinite if never)."""
|
||||
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
limits = []
|
||||
for sign in (-1, 1):
|
||||
previous, limit = centre, sign * np.inf
|
||||
for k in range(1, 80):
|
||||
v = centre + sign * scale * k
|
||||
if drop(v) > 0:
|
||||
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
|
||||
break
|
||||
previous = v
|
||||
limits.append(limit)
|
||||
return limits[0], limits[1]
|
||||
|
||||
|
||||
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
||||
return {
|
||||
"model": model,
|
||||
"n": n,
|
||||
"coef": round(float(coef), 4),
|
||||
"odds_ratio": round(float(np.exp(coef)), 4),
|
||||
"ci_low": round(float(np.exp(low)), 4),
|
||||
"ci_high": round(float(np.exp(high)), 4),
|
||||
"p": round(p, 5),
|
||||
"adjusted_for": ", ".join(design.names[2:]),
|
||||
"reason": "",
|
||||
**extra,
|
||||
"state": {"design": design.state(), **state},
|
||||
}
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
|
||||
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
||||
y = d[outcome].to_numpy(float)
|
||||
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)
|
||||
b, top = _firth_fit(X, y)
|
||||
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
|
||||
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
|
||||
low, high = _interval(profile, b[1], top, max(se, 0.05))
|
||||
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
|
||||
# FLIC: the intercept refitted so the probabilities add up to the events.
|
||||
eta = X[:, 1:] @ b[1:]
|
||||
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
|
||||
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
|
||||
|
||||
|
||||
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
|
||||
def _ordinal_nll(par, X, y, K) -> float:
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
eta = X @ par[K - 1 :]
|
||||
n = len(y)
|
||||
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
|
||||
return -float(
|
||||
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
|
||||
)
|
||||
|
||||
|
||||
def _ordinal_fit(X, y, K, fixed=None):
|
||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||
if fixed is None:
|
||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def nll(q):
|
||||
par = np.empty(len(start))
|
||||
par[free], par[K - 1 + j] = q, value
|
||||
return _ordinal_nll(par, X, y, K)
|
||||
|
||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
||||
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
||||
levels = np.sort(d[outcome].unique())
|
||||
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
|
||||
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)[:, 1:]
|
||||
K = len(levels)
|
||||
y = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _ordinal_fit(X, y, K)
|
||||
beta = par[K - 1 :]
|
||||
if abs(beta[0]) > 20:
|
||||
return {**out, "reason": "does not converge (separation)"}
|
||||
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
|
||||
low, high_ = _interval(profile, beta[0], -nll, 0.1)
|
||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
k = int(np.searchsorted(levels, high))
|
||||
inside = 0 < k < K
|
||||
state = {
|
||||
"beta": [float(v) for v in beta],
|
||||
"threshold": float(theta[k - 1]) if inside else None,
|
||||
"always": None if inside else float(k == 0),
|
||||
}
|
||||
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K)
|
||||
|
||||
|
||||
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability of the outcome under `fit`, and the reference child's."""
|
||||
s = fit["state"]
|
||||
X = Design.from_state(s["design"]).matrix(t)
|
||||
if fit["model"] == "firth":
|
||||
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
|
||||
expit(s["intercept"])
|
||||
)
|
||||
if s["threshold"] is None:
|
||||
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
|
||||
return (
|
||||
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
|
||||
float(1 - expit(s["threshold"])),
|
||||
)
|
||||
|
||||
|
||||
def _guarded(fit, *args) -> dict:
|
||||
try:
|
||||
return fit(*args)
|
||||
except (np.linalg.LinAlgError, ValueError) as error:
|
||||
model = "firth" if fit is firth else "ordinal"
|
||||
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
|
||||
|
||||
|
||||
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
|
||||
"""Every pair's principal and sensitivity models and its q: what the association is."""
|
||||
if level == "auto":
|
||||
level = "item" if has_items(cohort) else "domain"
|
||||
rows = []
|
||||
for pair in spec.pairs(level):
|
||||
if pair["predictor"] not in cohort:
|
||||
continue
|
||||
d = cohort.copy()
|
||||
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
|
||||
if pair["kind"] == "item":
|
||||
d["_level"] = item_scores(cohort, pair["outcome"])
|
||||
d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna())
|
||||
principal = _guarded(firth, d, "_yes", pair["predictor"])
|
||||
sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED)
|
||||
else:
|
||||
d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce")
|
||||
d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna())
|
||||
principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH)
|
||||
sensitivity = _guarded(firth, d, "_yes", pair["predictor"])
|
||||
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
|
||||
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
|
||||
biomarkers = np.array([r["biomarker"] for r in rows])
|
||||
q = np.full(len(rows), np.nan)
|
||||
for b in dict.fromkeys(biomarkers):
|
||||
mine = (biomarkers == b) & np.isfinite(p)
|
||||
if mine.any():
|
||||
q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5)
|
||||
for r, v in zip(rows, q, strict=True):
|
||||
r["q"] = None if np.isnan(v) else float(v)
|
||||
return {"level": level, "n": len(cohort), "rows": rows}
|
||||
|
||||
|
||||
def outcome_code(row: dict) -> str:
|
||||
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
|
||||
|
||||
|
||||
def associations(fitted: dict) -> list[dict]:
|
||||
"""One row per pair: what the governance report and the record show."""
|
||||
out = []
|
||||
for r in fitted["rows"]:
|
||||
f, s = r["principal"], r["sensitivity"]
|
||||
ratio, other = f.get("odds_ratio"), s.get("odds_ratio")
|
||||
out.append(
|
||||
{
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"kind": r["kind"],
|
||||
"outcome": r["outcome"],
|
||||
"outcome_code": outcome_code(r),
|
||||
"event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}",
|
||||
"model": f["model"],
|
||||
"n": f["n"],
|
||||
"odds_ratio": ratio,
|
||||
"ci_low": f.get("ci_low"),
|
||||
"ci_high": f.get("ci_high"),
|
||||
"p": f.get("p"),
|
||||
"q": r["q"],
|
||||
"sens_model": s["model"],
|
||||
"sens_odds_ratio": other,
|
||||
"same_direction": None
|
||||
if ratio is None or other is None
|
||||
else bool(np.sign(ratio - 1) == np.sign(other - 1)),
|
||||
"reason": f.get("reason", ""),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
|
||||
"""Each child's probability under every estimated pair, and the reference child's."""
|
||||
out = []
|
||||
for r in fitted["rows"]:
|
||||
f = r["principal"]
|
||||
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
continue
|
||||
t = cohort
|
||||
if r["kind"] == "item":
|
||||
t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])]
|
||||
t = t[t[r["predictor"]].notna()]
|
||||
if not len(t):
|
||||
continue
|
||||
found, reference = probability(f, t)
|
||||
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True):
|
||||
if np.isfinite(p):
|
||||
out.append(
|
||||
{
|
||||
"key": key,
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"outcome_code": outcome_code(r),
|
||||
"z": float(z),
|
||||
"probability": round(float(p), 4),
|
||||
"reference_probability": round(reference, 4),
|
||||
}
|
||||
)
|
||||
return out
|
||||
@@ -1,6 +1,2 @@
|
||||
"""TEA's EEG analysis: the `tea` library run on one stored EDF, without the database.
|
||||
|
||||
`settings.py` maps each metric to a library feature (`model.toml`); `analyze.py` measures one EEG; `baselines.py`
|
||||
compares a value with its promoted age baseline. Reading the EDFs and writing the results back to bronze is
|
||||
`models.eeg_analysis` (`python -m models tea analyze`).
|
||||
"""
|
||||
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
|
||||
`curves.py`)."""
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
|
||||
|
||||
analysis = analyze(edf_bytes, birth_date)
|
||||
|
||||
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
|
||||
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
|
||||
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
|
||||
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
|
||||
`error` set, keeping the verdict and checks when validation finished before it. Missing values
|
||||
are None.
|
||||
"""
|
||||
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
|
||||
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
MAINS_HZ = 60.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Metric:
|
||||
code: str
|
||||
value: float | None
|
||||
electrodes: dict[str, float] = field(default_factory=dict) # None where not measured
|
||||
zones: dict[str, float] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Analysis:
|
||||
valid: bool | None
|
||||
level: str
|
||||
age_months: float | None
|
||||
clean_fraction: float | None
|
||||
bad_channels: int | None
|
||||
channels: int | None
|
||||
duration_min: float | None
|
||||
line_noise_db: float | None
|
||||
sleep: bool | None
|
||||
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
|
||||
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
|
||||
# anteroposterior_gradient
|
||||
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
|
||||
error: str | None
|
||||
|
||||
|
||||
def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
|
||||
|
||||
def analyze(
|
||||
edf: bytes,
|
||||
birth_date: date | None = None,
|
||||
*,
|
||||
age_months: float | None = None,
|
||||
mains_hz: float = MAINS_HZ,
|
||||
) -> Analysis:
|
||||
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
|
||||
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
|
||||
out = dict(
|
||||
valid=None,
|
||||
level=checks.NOT_ANALYZABLE,
|
||||
age_months=age_months,
|
||||
clean_fraction=None,
|
||||
bad_channels=None,
|
||||
channels=None,
|
||||
duration_min=None,
|
||||
line_noise_db=None,
|
||||
sleep=None,
|
||||
checks=[],
|
||||
metrics=[],
|
||||
features={},
|
||||
error=None,
|
||||
)
|
||||
try:
|
||||
try:
|
||||
rec = read.read(edf)
|
||||
except read.FileNotValid as exc:
|
||||
verdict = checks.file_not_valid(str(exc))
|
||||
return Analysis(
|
||||
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks)
|
||||
)
|
||||
if age_months is None:
|
||||
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
|
||||
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
|
||||
out["age_months"] = age = header if header is not None else given
|
||||
else:
|
||||
age = age_months
|
||||
verdict = checks.validate(rec, mains_hz)
|
||||
out.update(
|
||||
valid=verdict.valid,
|
||||
level=verdict.level,
|
||||
clean_fraction=verdict.clean_pct / 100,
|
||||
bad_channels=len(verdict.bad),
|
||||
channels=len(rec.names) or None,
|
||||
duration_min=round(rec.duration_s / 60, 2),
|
||||
line_noise_db=_number(verdict.line_db),
|
||||
checks=verdict.checks,
|
||||
)
|
||||
if not verdict.valid:
|
||||
return Analysis(**out)
|
||||
prep = preprocess.prepare(rec, verdict.bad)
|
||||
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
|
||||
states = sleep.states(prep, notes, age)
|
||||
staged = sleep.stages(prep, states)
|
||||
metrics, features = biomarkers.measure(prep, states, staged, notes)
|
||||
out.update(
|
||||
sleep=bool((states == "sleep").any()),
|
||||
metrics=[
|
||||
Metric(
|
||||
code,
|
||||
_number(value),
|
||||
{k: _number(v) for k, v in electrodes.items()},
|
||||
{k: _number(v) for k, v in zones.items()},
|
||||
)
|
||||
for code, (value, electrodes, zones) in metrics.items()
|
||||
],
|
||||
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
|
||||
)
|
||||
return Analysis(**out)
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch
|
||||
return Analysis(**out | dict(error=_error(exc)))
|
||||
@@ -1,273 +0,0 @@
|
||||
"""One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers.
|
||||
|
||||
`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age the
|
||||
patient's rows give, touches no database and returns a `Measurement` with the verdict, every quality check and each
|
||||
metric's raw value. The deviation from the age baselines is added afterwards (`baselines.py`), where the registered
|
||||
models are.
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when the header has both, and the rows' otherwise:
|
||||
the file is written when the study is recorded, the rows' birth date may be missing or mistyped.
|
||||
|
||||
The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Channel codes the library builds from the reason's first words, and the fixed code each is stored as.
|
||||
CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"}
|
||||
# Header and rows further apart than this, in months, are logged.
|
||||
AGE_DISAGREEMENT_MONTHS = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Check:
|
||||
code: str
|
||||
electrode: str | None
|
||||
value: float | None
|
||||
text: str | None
|
||||
unit: str | None
|
||||
low: float | None
|
||||
high: float | None
|
||||
decisive: bool
|
||||
abnormal: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MetricValue:
|
||||
code: str
|
||||
value: float | None
|
||||
electrodes: dict[str, float | None] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Measurement:
|
||||
key: str
|
||||
age_months: float | None # the age the study was analysed at
|
||||
plan_hash: str
|
||||
versions: str
|
||||
valid: int | None = None
|
||||
level: str | None = None
|
||||
clean_fraction: float | None = None
|
||||
bad_channels: int | None = None
|
||||
line_db: float | None = None
|
||||
channels: int | None = None
|
||||
duration_min: float | None = None
|
||||
asleep: int | None = None
|
||||
checks: tuple[Check, ...] = ()
|
||||
metrics: tuple[MetricValue, ...] = ()
|
||||
error: str | None = None
|
||||
seconds: float = 0.0
|
||||
|
||||
|
||||
def pipeline(settings: Settings):
|
||||
from tea.pipeline import Pipeline
|
||||
|
||||
return Pipeline.default(impl=settings.impl)
|
||||
|
||||
|
||||
def plan(settings: Settings) -> dict:
|
||||
from tea.preprocessing import PLANS
|
||||
|
||||
return PLANS[settings.plan].to_dict()
|
||||
|
||||
|
||||
def phase_detector(pipe, phase: str):
|
||||
base = pipe.module("spindle_detection")
|
||||
return type(base)(variant=base.variant, phase=phase)
|
||||
|
||||
|
||||
def processes(pipe, settings: Settings) -> list[str]:
|
||||
"""The processes the metrics need, in dependency order. Spindle detection itself runs once per sleep stage, so
|
||||
the phased biomarkers contribute only what their stage's detector requires."""
|
||||
from tea.pipeline.run_study import order_for
|
||||
|
||||
needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n]
|
||||
requires = {r for n in needs for r in pipe.module(n).requires}
|
||||
for phase in settings.phases:
|
||||
requires.update(phase_detector(pipe, phase).requires)
|
||||
return order_for(["metrics"], {**pipe.modules, "metrics": SimpleNamespace(requires=tuple(sorted(requires)))})
|
||||
|
||||
|
||||
def versions(pipe, settings: Settings) -> str:
|
||||
"""What produced an analysis, as `name=version;...`: a new version of any module analyses every EEG again."""
|
||||
names = ["validation", "preprocessing", *processes(pipe, settings)]
|
||||
if settings.phases:
|
||||
names.append("spindle_detection")
|
||||
names += settings.biomarkers
|
||||
return ";".join(f"{n}={getattr(pipe.module(n), 'version', '?')}" for n in dict.fromkeys(names))
|
||||
|
||||
|
||||
def criterion_code(code: str, text: str, electrode: str | None) -> str:
|
||||
"""The library's channel codes are the first words of the reason, numbers included (`amplitude-4.5-x`)."""
|
||||
if electrode is None:
|
||||
return code
|
||||
if code.startswith("amplitude"):
|
||||
return "aux-amplitude" if "out of range" in text else "amplitude"
|
||||
return CHANNEL_CODES.get(code, code)
|
||||
|
||||
|
||||
def _number(value) -> float | None:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return number if number == number else None
|
||||
|
||||
|
||||
def checks(validation, run: dict) -> tuple[Check, ...]:
|
||||
out = []
|
||||
for c in validation.checks_of(run):
|
||||
text = c.value if isinstance(c.value, str) else None
|
||||
out.append(Check(
|
||||
code=criterion_code(c.code, c.display, c.electrode), electrode=c.electrode,
|
||||
value=None if text is not None else _number(c.value), text=text, unit=c.unit or None,
|
||||
low=_number(c.low), high=_number(c.high), decisive=bool(c.decisive), abnormal=bool(c.abnormal),
|
||||
))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def gate_reasons(summary, plan: dict) -> list[str]:
|
||||
"""The plan's gates on top of the validator's verdict, as the library's own batch applies them."""
|
||||
reasons = list(summary.extra.get("reasons", []))
|
||||
gates = plan.get("gates", {})
|
||||
if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" and not reasons:
|
||||
reasons.append("triage level no_analizable")
|
||||
least = gates.get("min_clean")
|
||||
if least is not None and summary.clean_fraction == summary.clean_fraction and summary.clean_fraction < least:
|
||||
reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * least:.0f}%")
|
||||
return reasons
|
||||
|
||||
|
||||
Features = dict[tuple[str, str | None], dict[str, float | None]]
|
||||
|
||||
|
||||
def features(pipe, study, settings: Settings) -> Features:
|
||||
"""Every feature of each biomarker the metrics read, by biomarker and sleep stage (`None`: no stage), with
|
||||
spindle detection run once per stage."""
|
||||
by_phase = {None: study}
|
||||
for phase in settings.phases:
|
||||
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
|
||||
out: Features = {}
|
||||
for m in settings.metrics:
|
||||
for biomarker in (m.biomarker, m.electrodes):
|
||||
if biomarker and (biomarker, m.phase) not in out:
|
||||
out[biomarker, m.phase] = {k: _number(v) for k, v in
|
||||
pipe.module(biomarker).measure(by_phase[m.phase]).items()}
|
||||
return out
|
||||
|
||||
|
||||
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
|
||||
out = []
|
||||
for m in settings.metrics:
|
||||
electrodes = {}
|
||||
if m.electrodes:
|
||||
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items()
|
||||
if name.startswith(m.electrode_prefix)}
|
||||
out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
|
||||
|
||||
def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | None, line_hz: float):
|
||||
"""Validation, then, for a valid study, preprocessing and the processes: (validation run, summary, verdict,
|
||||
study or None)."""
|
||||
from tea.contracts import Study
|
||||
|
||||
validation = pipe.module("validation")
|
||||
run = validation.run(path, line_hz=line_hz)
|
||||
summary = validation.summary_of(run)
|
||||
valid = int(bool(summary.valid) and not gate_reasons(summary, the_plan))
|
||||
if not valid:
|
||||
return run, summary, valid, None
|
||||
preprocessing = pipe.module("preprocessing")
|
||||
study = Study(preprocessing.run(path, preprocessing.plan_for(summary, the_plan), age_months=age_months))
|
||||
for name in processes(pipe, settings):
|
||||
study = study.with_labels(pipe.module(name).predict(study))
|
||||
return run, summary, valid, study
|
||||
|
||||
|
||||
def study_age(key: str, path: Path, row_age: float | None, days_per_month: float) -> float | None:
|
||||
"""The header's age if it has one, else `row_age`. An unreadable header counts as none: validation reports the
|
||||
file."""
|
||||
from tea.contracts import header_age_months
|
||||
|
||||
try:
|
||||
header = header_age_months(path, days_per_month=days_per_month)
|
||||
except Exception: # noqa: BLE001
|
||||
header = None
|
||||
if header is None:
|
||||
return row_age
|
||||
if row_age is not None and abs(header - row_age) > AGE_DISAGREEMENT_MONTHS:
|
||||
log.warning("EEG %s: the EDF header gives %.1f months and the patient's rows %.1f; using the header",
|
||||
key, header, row_age)
|
||||
return header
|
||||
|
||||
|
||||
def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement:
|
||||
"""`age_months` is the rows' age, used when the EDF header has none (`study_age`). Never raises: a failure is a
|
||||
`Measurement` with `error` set, keeping the verdict and checks if validation finished before it."""
|
||||
started = time.time()
|
||||
pipe = pipeline(settings)
|
||||
the_plan = plan(settings)
|
||||
result = dict(key=key, age_months=age_months, plan_hash=the_plan.get("hash", ""), versions=versions(pipe, settings))
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "study.edf"
|
||||
path.write_bytes(edf)
|
||||
result["age_months"] = age = study_age(key, path, age_months, settings.days_per_month)
|
||||
validation = pipe.module("validation")
|
||||
run, summary, valid, study = _study(pipe, path, settings, the_plan, age, settings.line_hz)
|
||||
result.update(
|
||||
valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction),
|
||||
bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db),
|
||||
channels=len(run.get("channels", [])) or None,
|
||||
duration_min=round(run["duration_s"] / 60, 2) if run.get("duration_s") else None,
|
||||
checks=checks(validation, run),
|
||||
)
|
||||
if study is None:
|
||||
return Measurement(**result, seconds=round(time.time() - started, 1))
|
||||
asleep = int((study.label("sleep_state").per_window == "sueno").any())
|
||||
return Measurement(**result, asleep=asleep, metrics=_metrics(features(pipe, study, settings), settings),
|
||||
seconds=round(time.time() - started, 1))
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop the batch
|
||||
return Measurement(**result, error=_error(exc), seconds=round(time.time() - started, 1))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReferenceStudy:
|
||||
"""One study of a reference cohort, measured for training: its age, verdict, and every feature of each
|
||||
biomarker the metrics read, by biomarker and sleep stage. No path, file name or date."""
|
||||
|
||||
key: str
|
||||
age_months: float
|
||||
valid: int | None = None
|
||||
features: Features = field(default_factory=dict)
|
||||
error: str | None = None
|
||||
|
||||
|
||||
def reference(key: str, path: str, age_months: float, settings: Settings, line_hz: float) -> ReferenceStudy:
|
||||
"""A reference study read from a local or `s3://` path, at the mains frequency of the cohort's country. Never
|
||||
raises: a failure is a `ReferenceStudy` with `error` set."""
|
||||
from tea.pipeline.storage import local_copy
|
||||
|
||||
pipe = pipeline(settings)
|
||||
try:
|
||||
with local_copy(path) as local:
|
||||
_, _, valid, study = _study(pipe, local, settings, plan(settings), age_months, line_hz)
|
||||
measured = features(pipe, study, settings) if study is not None else {}
|
||||
return ReferenceStudy(key, age_months, valid, measured)
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable study must not stop the batch
|
||||
return ReferenceStudy(key, age_months, error=_error(exc))
|
||||
@@ -1,102 +0,0 @@
|
||||
"""The promoted age baselines: a metric's raw value against its curve at the child's age.
|
||||
|
||||
Each baseline is a trained `tea` biomarker module registered as `tea-<scenario>` with the `produccion` alias. Without
|
||||
one in production a metric keeps its raw value and no deviation, the same as a model never configured.
|
||||
"""
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.registry import registry as default_registry
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Deviation:
|
||||
z: float | None
|
||||
outside: int | None
|
||||
p5: float | None
|
||||
median: float | None
|
||||
p95: float | None
|
||||
|
||||
|
||||
def _number(value) -> float | None:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return number if math.isfinite(number) else None
|
||||
|
||||
|
||||
def _feature_baseline(module, feature: str):
|
||||
baselines = getattr(module, "baselines", None)
|
||||
return baselines[feature] if baselines is not None else module.baseline
|
||||
|
||||
|
||||
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
|
||||
"""p5, median and p95 of a centile curve at an age, interpolated on log age as the library's z is; none for a
|
||||
baseline without a curve or an age outside it."""
|
||||
curve = getattr(baseline, "curva", None)
|
||||
if curve is None or age_months is None or age_months <= 0:
|
||||
return None, None, None
|
||||
rows = curve.dropna(subset=["p5", "mediana", "p95"])
|
||||
if not len(rows):
|
||||
return None, None, None
|
||||
log_ages = np.log(rows["edad_meses"].to_numpy(float))
|
||||
at = math.log(age_months)
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return None, None, None
|
||||
return tuple(_number(np.interp(at, log_ages, rows[c].to_numpy(float))) for c in ("p5", "mediana", "p95"))
|
||||
|
||||
|
||||
class Baselines:
|
||||
"""Resolves each scenario's production version once per instance, and loads it the first time it is used."""
|
||||
|
||||
def __init__(self, domain: str = "tea", registry=default_registry, loader=None):
|
||||
self.domain = domain
|
||||
self.registry = registry
|
||||
self._loader = loader
|
||||
self._resolved: dict[str, object | None] = {}
|
||||
self._loaded: dict[str, object] = {}
|
||||
|
||||
def _resolve(self, scenario: str):
|
||||
if scenario not in self._resolved:
|
||||
try:
|
||||
self._resolved[scenario] = self.registry.resolve(self.domain, scenario)
|
||||
except LookupError:
|
||||
self._resolved[scenario] = None
|
||||
return self._resolved[scenario]
|
||||
|
||||
def label(self, scenario: str) -> str | None:
|
||||
"""`tea-<scenario>/<version>` of the version in production, or none."""
|
||||
resolved = self._resolve(scenario)
|
||||
return f"{registered_name(self.domain, scenario)}/{resolved.version}" if resolved else None
|
||||
|
||||
def module(self, scenario: str):
|
||||
"""The trained biomarker module in production, or none."""
|
||||
resolved = self._resolve(scenario)
|
||||
if resolved is None:
|
||||
return None
|
||||
if scenario not in self._loaded:
|
||||
if self._loader is not None:
|
||||
self._loaded[scenario] = self._loader(resolved.model_uri)
|
||||
else:
|
||||
from tea.serving import load_biomarker
|
||||
|
||||
self._loaded[scenario] = load_biomarker(resolved.model_uri)
|
||||
return self._loaded[scenario]
|
||||
|
||||
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None:
|
||||
"""None without a baseline in production; with one, a deviation whose fields are null where the value or
|
||||
the age is missing or the curve doesn't cover the age."""
|
||||
module = self.module(scenario)
|
||||
if module is None:
|
||||
return None
|
||||
baseline = _feature_baseline(module, feature)
|
||||
if value is None or age_months is None:
|
||||
return Deviation(None, None, None, None, None)
|
||||
outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float))
|
||||
z_value = _number(z[0])
|
||||
p5, median, p95 = centiles(baseline, age_months)
|
||||
return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features
|
||||
each age baseline scores (by scenario, `curves.SCENARIOS`).
|
||||
|
||||
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
|
||||
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
|
||||
|
||||
Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-4 Hz) power of
|
||||
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
|
||||
electrode's front-back position (6 electrodes at least).
|
||||
|
||||
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode.
|
||||
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from scipy.fft import rfft, rfftfreq
|
||||
from scipy.signal.windows import hann
|
||||
from scipy.stats import theilslopes
|
||||
|
||||
from models.tea.eeg import signals, spikes, spindles
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
from models.tea.eeg.sleep import POSTERIOR
|
||||
|
||||
MIN_WINDOWS = 15
|
||||
FRONT_BACK = {
|
||||
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
|
||||
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
|
||||
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
|
||||
} # fmt: skip
|
||||
CODES = (
|
||||
"posterior_rhythm",
|
||||
"spindles_n2",
|
||||
"spindles_n3",
|
||||
"paroxysmal_spikes",
|
||||
"anteroposterior_gradient",
|
||||
)
|
||||
|
||||
|
||||
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15."""
|
||||
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
|
||||
if len(starts) < MIN_WINDOWS or not names:
|
||||
return None
|
||||
x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
|
||||
found = []
|
||||
for a in (int(round(float(s) * prep.fs)) for s in starts):
|
||||
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
|
||||
found.append(x[a : a + n].T)
|
||||
return found or None
|
||||
|
||||
|
||||
def posterior_rhythm(prep: Prepared, states) -> float:
|
||||
names = prep.columns(POSTERIOR)
|
||||
segments = _segments(prep, names, states, "wake")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
f, power = signals.periodograms(np.stack(segments), prep.fs)
|
||||
peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))]
|
||||
found = [hz for hz, _, ok in peaks if ok]
|
||||
return float(np.median(found)) if len(found) >= 2 else np.nan
|
||||
|
||||
|
||||
def delta_gradient(prep: Prepared, states) -> float:
|
||||
names = [c for c in prep.names if c in FRONT_BACK]
|
||||
segments = _segments(prep, names, states, "sleep")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
stack = np.stack(segments)
|
||||
n = stack.shape[-1]
|
||||
f = rfftfreq(n, 1 / prep.fs)
|
||||
power = np.abs(rfft((stack - stack.mean(axis=-1, keepdims=True)) * hann(n, sym=True))) ** 2
|
||||
delta = np.median(power[..., (f >= 0.5) & (f < 4)].sum(axis=-1), axis=0)
|
||||
log_power = np.log10(np.maximum(delta, 1e-30))
|
||||
y = np.array([FRONT_BACK[c] for c in names])
|
||||
finite = np.isfinite(log_power)
|
||||
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan
|
||||
|
||||
|
||||
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
|
||||
"""(metrics: code -> (value, electrodes, zones), features by scenario)."""
|
||||
metrics, features = {}, {}
|
||||
rhythm = posterior_rhythm(prep, states)
|
||||
metrics["posterior_rhythm"] = (rhythm, {}, {})
|
||||
features["eeg-posterior-rhythm"] = {"value": rhythm}
|
||||
for stage in ("N2", "N3"):
|
||||
found = spindles.detect(prep, staged, stage)
|
||||
value, zones = spindles.density(found)
|
||||
electrodes = spindles.enhancement(prep, found, states)
|
||||
metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones)
|
||||
features[f"eeg-spindles-{stage.lower()}"] = {
|
||||
"value": value,
|
||||
**{f"zone_{z}": v for z, v in zones.items()},
|
||||
}
|
||||
features[f"eeg-spindle-topography-{stage.lower()}"] = {
|
||||
f"electrode_{e}": v for e, v in electrodes.items()
|
||||
}
|
||||
found = spikes.detect(prep, states, intervals)
|
||||
if found is None:
|
||||
nan = dict.fromkeys
|
||||
found = spikes.Spikes(
|
||||
np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0
|
||||
)
|
||||
metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones)
|
||||
features["eeg-spikes"] = {
|
||||
"value": found.rate,
|
||||
**{f"electrode_{e}": v for e, v in found.electrodes.items()},
|
||||
**{f"zone_{z}": v for z, v in found.zones.items()},
|
||||
"minutes": found.minutes,
|
||||
}
|
||||
gradient = delta_gradient(prep, states)
|
||||
metrics["anteroposterior_gradient"] = (gradient, {}, {})
|
||||
features["eeg-gradient"] = {"value": gradient}
|
||||
return {code: metrics[code] for code in CODES}, features
|
||||
@@ -0,0 +1,349 @@
|
||||
"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates.
|
||||
|
||||
Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD
|
||||
< 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the
|
||||
mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent
|
||||
contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with
|
||||
a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range.
|
||||
|
||||
Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a
|
||||
gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out,
|
||||
over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp
|
||||
electrodes and clean minutes; the gates make the EEG not valid when the level is
|
||||
`not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are
|
||||
usable.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.read import Recording
|
||||
|
||||
NEIGHBOURS = {
|
||||
"Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"),
|
||||
"F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
|
||||
"Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
|
||||
"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"),
|
||||
"T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"),
|
||||
"P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"),
|
||||
"O2": ("T6", "P4", "O1"),
|
||||
} # fmt: skip
|
||||
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
|
||||
MIN_CLEAN_PCT = 60.0
|
||||
MIN_COVERAGE = 0.90
|
||||
MAX_BAD_SCALP = 2
|
||||
MIN_SCALP = 12
|
||||
MAX_LINE_DB = 45.0
|
||||
NOT_ANALYZABLE = "not_analyzable"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Validation:
|
||||
valid: bool
|
||||
level: str
|
||||
bad: dict[str, list[str]] # channel -> reasons, every kind of channel
|
||||
clean_pct: float
|
||||
line_db: float
|
||||
checks: list[dict] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ears_usable(self) -> bool:
|
||||
return all(ear not in self.bad for ear in ("A1", "A2"))
|
||||
|
||||
|
||||
def check(
|
||||
code,
|
||||
*,
|
||||
electrode=None,
|
||||
value=None,
|
||||
text=None,
|
||||
unit=None,
|
||||
low=None,
|
||||
high=None,
|
||||
decisive=False,
|
||||
abnormal=False,
|
||||
) -> dict:
|
||||
return dict(
|
||||
code=code,
|
||||
electrode=electrode,
|
||||
value=value,
|
||||
text=text,
|
||||
unit=unit,
|
||||
low=low,
|
||||
high=high,
|
||||
decisive=decisive,
|
||||
abnormal=abnormal,
|
||||
)
|
||||
|
||||
|
||||
def file_not_valid(reason: str) -> Validation:
|
||||
rows = [check("file", text=reason, decisive=True, abnormal=True)]
|
||||
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows)
|
||||
|
||||
|
||||
def _filtered(x, fs, mains_hz, lo, hi):
|
||||
return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi)
|
||||
|
||||
|
||||
def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
|
||||
"""Rules on a channel's raw samples: (code, reason)."""
|
||||
finite = v[np.isfinite(v)]
|
||||
if len(finite) < 10 or np.std(finite) < 0.5:
|
||||
return [("dead-channel", "dead channel")]
|
||||
out = []
|
||||
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
|
||||
out.append(("frozen", "frozen"))
|
||||
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
|
||||
out.append(("saturated", "saturated"))
|
||||
if np.isinf(v).any():
|
||||
out.append(("inf-values", "Inf values"))
|
||||
return out
|
||||
|
||||
|
||||
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Per channel, the fraction of 10 s blocks silent against the montage and bursting above it
|
||||
(NaN with fewer than 6 blocks)."""
|
||||
size = int(10 * fs)
|
||||
blocks = len(y) // size
|
||||
low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
|
||||
if blocks < 6:
|
||||
return low, high
|
||||
sd = np.full((blocks, y.shape[1]), np.nan)
|
||||
for b in range(blocks):
|
||||
block = y[b * size : (b + 1) * size]
|
||||
if np.isfinite(block).all():
|
||||
sd[b] = block.std(axis=0)
|
||||
with np.errstate(all="ignore"):
|
||||
relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12)
|
||||
for i in range(y.shape[1]):
|
||||
v = relative[:, i]
|
||||
v = v[np.isfinite(v) & (v > 0)]
|
||||
if len(v) >= 6:
|
||||
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35))
|
||||
high[i] = np.mean(v > 4.0)
|
||||
return low, high
|
||||
|
||||
|
||||
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]:
|
||||
"""Scalp channels correlating over 0.99 with a contiguous electrode and with no far one."""
|
||||
finite = np.isfinite(y).all(axis=1)
|
||||
if finite.sum() < 200 or len(scalp) < 2:
|
||||
return {}
|
||||
r = np.abs(np.corrcoef(y[finite][:, scalp].T))
|
||||
index = {names[i]: k for k, i in enumerate(scalp)}
|
||||
out = {}
|
||||
for name, k in index.items():
|
||||
near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index]
|
||||
far = [j for j in index.values() if j != k and j not in near]
|
||||
if not near:
|
||||
continue
|
||||
best = max(near, key=lambda j: r[k, j])
|
||||
if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99):
|
||||
out[name] = next(n for n, j in index.items() if j == best)
|
||||
return out
|
||||
|
||||
|
||||
def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]:
|
||||
"""Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them."""
|
||||
out = {}
|
||||
for ear, around in EAR_NEIGHBOURS.items():
|
||||
present = [n for n in around if n in names]
|
||||
if ear not in names or len(present) < 2:
|
||||
continue
|
||||
cols = [names.index(ear)] + [names.index(n) for n in present]
|
||||
rows = np.isfinite(y[:, cols]).all(axis=1)
|
||||
if rows.sum() < fs * 30:
|
||||
continue
|
||||
r = np.abs(np.corrcoef(y[rows][:, cols].T))
|
||||
between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))]
|
||||
out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between)))
|
||||
return out
|
||||
|
||||
|
||||
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]:
|
||||
"""Channel -> [(code, reason)] of every channel some rule flags."""
|
||||
x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
|
||||
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
|
||||
dead = {
|
||||
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
|
||||
}
|
||||
notched = signals.notch(x, fs, mains_hz)
|
||||
y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9))
|
||||
y40 = signals.bandpass(notched, fs, 1.0, 40.0)
|
||||
scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"]
|
||||
rms = np.nanstd(y45, axis=0)
|
||||
median = float(np.nanmedian(rms[scalp])) if scalp else np.nan
|
||||
ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan)
|
||||
low, burst = _contact(y45, fs)
|
||||
bridges = _bridges(y40, names, scalp)
|
||||
ears = _ears(y40, fs, names)
|
||||
missing = 1 - np.isfinite(x).mean(axis=0)
|
||||
for i, name in enumerate(names):
|
||||
found, k = reasons[name], kinds[name]
|
||||
if missing[i] > missing.min() + 0.02:
|
||||
excess = 100 * (missing[i] - missing.min())
|
||||
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
|
||||
if name in dead:
|
||||
continue
|
||||
if k == "eeg" and name in bridges:
|
||||
found.append(("bridge", f"bridge with {bridges[name]}"))
|
||||
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
|
||||
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
|
||||
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
|
||||
c, e = ears[name]
|
||||
found.append(
|
||||
(
|
||||
"does-not-correlate",
|
||||
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
|
||||
)
|
||||
)
|
||||
if np.isfinite(low[i]) and low[i] > 0.10:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-contact",
|
||||
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
|
||||
)
|
||||
)
|
||||
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-bursts",
|
||||
f"intermittent contact by bursts "
|
||||
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
|
||||
)
|
||||
)
|
||||
if k in ("eog", "ecg"):
|
||||
v = x[:, i][np.isfinite(x[:, i])]
|
||||
if np.sqrt(np.mean(v**2)) > 20000:
|
||||
found.append(
|
||||
(
|
||||
"aux-amplitude",
|
||||
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
|
||||
f"out of range even for {k.upper()}",
|
||||
)
|
||||
)
|
||||
return {name: found for name, found in reasons.items() if found}
|
||||
|
||||
|
||||
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
|
||||
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
|
||||
verdict `gap`, `suspect` or `clean`."""
|
||||
n = int(4 * fs)
|
||||
lines = signals.fixed_lines(y, fs, f_max=44.0)
|
||||
starts = list(range(0, len(y) - n + 1, n))
|
||||
segments = [y[a : a + n] for a in starts]
|
||||
whole = [bool(np.isfinite(s).all()) for s in segments]
|
||||
emg = {}
|
||||
if any(whole):
|
||||
stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok])
|
||||
f, power = signals.periodograms(stack, fs)
|
||||
power = np.moveaxis(power, -1, 0)
|
||||
high = signals.band_power(f, power, 30.0, 45.0, lines)
|
||||
low = signals.band_power(f, power, 4.0, 13.0, lines)
|
||||
ratio = np.median(high / np.maximum(low, 1e-12), axis=1)
|
||||
emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True))
|
||||
out = []
|
||||
for a, s, ok in zip(starts, segments, whole, strict=True):
|
||||
if not ok:
|
||||
out.append((a / fs, (a + n) / fs, "gap"))
|
||||
continue
|
||||
p2p = float(np.max(s.max(axis=0) - s.min(axis=0)))
|
||||
variance = float(np.mean(s.var(axis=0)))
|
||||
common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan
|
||||
muscle = float(emg[a])
|
||||
suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8
|
||||
out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean"))
|
||||
return out
|
||||
|
||||
|
||||
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float):
|
||||
"""(level, bad scalp electrodes by the triage rule)."""
|
||||
x, fs, kinds = rec.x, rec.fs, rec.kinds()
|
||||
columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")]
|
||||
y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0)
|
||||
rms, flat = {}, {}
|
||||
for k, i in enumerate(columns):
|
||||
v = y[:, k][np.isfinite(y[:, k])]
|
||||
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan
|
||||
flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0
|
||||
scalp = rec.of("eeg")
|
||||
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan
|
||||
triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5]
|
||||
minutes = rec.duration_s * clean_pct / 100 / 60
|
||||
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
|
||||
if not (base and clean_pct >= 30 and minutes >= 3):
|
||||
level = NOT_ANALYZABLE
|
||||
elif not (clean_pct >= 50 and minutes >= 3):
|
||||
level = "partial"
|
||||
elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}:
|
||||
level = "no_ear_reference"
|
||||
else:
|
||||
level = "complete"
|
||||
return level, triaged
|
||||
|
||||
|
||||
def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
flagged = bad_channels(rec, mains_hz)
|
||||
scalp = rec.of("eeg")
|
||||
usable = [n for n in scalp if n not in flagged]
|
||||
qc = usable if len(usable) >= 2 else scalp
|
||||
y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0)
|
||||
windows = window_qc(y, rec.fs)
|
||||
clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1)
|
||||
coverage = float(np.isfinite(rec.x).all(axis=1).mean())
|
||||
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None)
|
||||
db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
|
||||
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
|
||||
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
|
||||
|
||||
rows = [
|
||||
check(code, electrode=name, text=reason, abnormal=True)
|
||||
for name, found in flagged.items()
|
||||
for code, reason in found
|
||||
]
|
||||
rows += [
|
||||
check(
|
||||
"clean-windows",
|
||||
value=clean_pct,
|
||||
unit="%",
|
||||
low=MIN_CLEAN_PCT,
|
||||
abnormal=clean_pct < MIN_CLEAN_PCT,
|
||||
decisive=True,
|
||||
),
|
||||
check(
|
||||
"internal-coverage",
|
||||
value=coverage,
|
||||
unit="fraction",
|
||||
low=MIN_COVERAGE,
|
||||
abnormal=coverage < MIN_COVERAGE,
|
||||
decisive=True,
|
||||
),
|
||||
check(
|
||||
"bad-scalp-triage",
|
||||
value=float(len(triaged)),
|
||||
unit="electrodes",
|
||||
high=float(MAX_BAD_SCALP),
|
||||
abnormal=len(triaged) > MAX_BAD_SCALP,
|
||||
decisive=True,
|
||||
),
|
||||
check(
|
||||
"usable-scalp",
|
||||
value=float(len(usable)),
|
||||
unit="electrodes",
|
||||
low=float(MIN_SCALP),
|
||||
abnormal=len(usable) < MIN_SCALP,
|
||||
decisive=True,
|
||||
),
|
||||
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True),
|
||||
]
|
||||
if np.isfinite(line):
|
||||
rows.append(
|
||||
check(
|
||||
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
|
||||
)
|
||||
)
|
||||
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
|
||||
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
|
||||
return Validation(valid, level, bad, clean_pct, line, rows)
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
|
||||
age in a reference cohort.
|
||||
|
||||
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
||||
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
|
||||
its own baseline, plain JSON-able data (`train`), scored by `score`:
|
||||
|
||||
* Centile curves: on 120 ages log-spaced from 1 to 216 months, the p5, p25, median, p75 and p95
|
||||
of the reference weighted by a Gaussian on log age (width 0.2), where the effective number of
|
||||
studies is at least 30 and the age lies within the reference's. A value scores z = (value -
|
||||
median) / ((median - p5 or p95 - median) / 1.645), outside -1 / +1 below p5 / above p95; the
|
||||
centiles are interpolated on log age; ages outside the curve get none.
|
||||
* Count rate (spikes, which most reference children never have): the reference's rate per
|
||||
minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
|
||||
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
|
||||
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
|
||||
median and p95 are the rates at those quantiles of the count in those minutes.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import stats
|
||||
|
||||
QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95}
|
||||
CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120))
|
||||
LOG_WIDTH = 0.2
|
||||
MIN_EFFECTIVE = 30
|
||||
COUNT_AGES = (16.0, 37.0)
|
||||
Z_MAX = 8.0
|
||||
EXPOSURE = "minutes"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Scenario:
|
||||
metric: str # the metric code it scores
|
||||
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
|
||||
stage: str | None = None
|
||||
counts: bool = False # a count against the `minutes` feature, not centile curves
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
|
||||
"eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"),
|
||||
"eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"),
|
||||
"eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"),
|
||||
"eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"),
|
||||
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
|
||||
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
|
||||
}
|
||||
PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
|
||||
|
||||
|
||||
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
|
||||
"""Interpolated between the midpoints of each weight's cumulative share."""
|
||||
order = np.argsort(x)
|
||||
x, w = x[order], w[order]
|
||||
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
|
||||
|
||||
|
||||
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
||||
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
|
||||
v, log_age = values[ok], np.log(ages[ok])
|
||||
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
|
||||
for a in CURVE_AGES:
|
||||
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
|
||||
n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0
|
||||
inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max()
|
||||
curve["age_months"].append(round(float(a), 3))
|
||||
curve["n_effective"].append(round(float(n_effective), 1))
|
||||
for name, q in QUANTILES.items():
|
||||
enough = n_effective >= MIN_EFFECTIVE and inside
|
||||
curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None)
|
||||
return {
|
||||
"kind": "curves",
|
||||
"log_width": LOG_WIDTH,
|
||||
"min_effective": MIN_EFFECTIVE,
|
||||
"curve": curve,
|
||||
}
|
||||
|
||||
|
||||
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict:
|
||||
n = np.round(values * exposure)
|
||||
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
||||
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
||||
n, x = n[keep], exposure[keep]
|
||||
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
|
||||
mu = rate * x
|
||||
excess = float(((n - mu) ** 2 - n).sum())
|
||||
k = float((mu**2).sum() / excess) if excess > 0 else None # None: Poisson
|
||||
return {
|
||||
"kind": "count_rate",
|
||||
"ages": list(COUNT_AGES),
|
||||
"rate": rate,
|
||||
"k": k,
|
||||
"reference": int(keep.sum()),
|
||||
"events": int(n.sum()),
|
||||
}
|
||||
|
||||
|
||||
def train(features: pd.DataFrame, scenario: str) -> dict:
|
||||
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the
|
||||
count's `minutes` excepted)."""
|
||||
counts = SCENARIOS[scenario].counts
|
||||
ages = features["age_months"].to_numpy(float)
|
||||
out = {}
|
||||
for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"):
|
||||
values = pd.to_numeric(features[name]).to_numpy(float)
|
||||
if counts:
|
||||
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float))
|
||||
else:
|
||||
out[name] = _curve(values, ages)
|
||||
return out
|
||||
|
||||
|
||||
def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
||||
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna()
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if not len(curve) or not age > 0:
|
||||
return out
|
||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return out
|
||||
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES}
|
||||
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"]
|
||||
z = (value - q["median"]) / (side / 1.645) if side > 0 else None
|
||||
outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
|
||||
return {
|
||||
"z": _number(z),
|
||||
"outside": outside,
|
||||
"p5": q["p5"],
|
||||
"median": q["median"],
|
||||
"p95": q["p95"],
|
||||
}
|
||||
|
||||
|
||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
rate, k = baseline["rate"], baseline["k"]
|
||||
lo, hi = baseline["ages"]
|
||||
if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
|
||||
return out
|
||||
n, mu = float(np.round(value * exposure)), rate * exposure
|
||||
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
||||
tail, at = law.sf(n - 1), law.pmf(n)
|
||||
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
||||
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
|
||||
|
||||
|
||||
def score(
|
||||
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None
|
||||
) -> dict:
|
||||
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the
|
||||
age or the baseline's coverage is missing."""
|
||||
value, age_months = _number(value), _number(age_months)
|
||||
if value is None or age_months is None:
|
||||
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if baseline["kind"] == "count_rate":
|
||||
return _score_count(baseline, value, age_months, _number(exposure))
|
||||
return _score_curve(baseline, value, age_months)
|
||||
|
||||
|
||||
def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
|
||||
"""Metric code -> {"value": score, "electrodes": {e: score}, "zones": {z: score}} from the
|
||||
trained scenarios in `models` (scenario -> `train`'s output); a scenario without a model
|
||||
leaves its parts out."""
|
||||
out = {m.code: {} for m in analysis.metrics}
|
||||
metrics = {m.code: m for m in analysis.metrics}
|
||||
for name, scenario in SCENARIOS.items():
|
||||
model, metric = models.get(name), metrics.get(scenario.metric)
|
||||
if model is None or metric is None:
|
||||
continue
|
||||
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
||||
for part in scenario.parts:
|
||||
if part == "value":
|
||||
out[metric.code]["value"] = score(
|
||||
model["value"], metric.value, analysis.age_months, exposure
|
||||
)
|
||||
else:
|
||||
out[metric.code][part] = {
|
||||
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure)
|
||||
for key, v in getattr(metric, part).items()
|
||||
}
|
||||
return out
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep",
|
||||
"features": {
|
||||
"delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0},
|
||||
"posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0},
|
||||
"sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7},
|
||||
"muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7},
|
||||
"alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6}
|
||||
},
|
||||
"cuts": [-1.2326590642152986, -0.3031551001049524]
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
"""TEA's EEG baselines as a model of the platform: `python -m models run tea eeg --train [--promote]`.
|
||||
|
||||
A baseline isn't trained on a cohort build of the platform but on the reference cohort (`train.py`), so this
|
||||
scenario runs its own steps (`run_steps`) in place of `run`'s cohort-file ones: training every scenario's baseline,
|
||||
then promoting each through the registry's checks.
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
SETTINGS = settings()
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
|
||||
from models.tea.eeg import train
|
||||
|
||||
if args.export or args.estimate or args.store or args.version:
|
||||
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
|
||||
return 2
|
||||
environment = args.environment.upper()
|
||||
versions: dict[str, str] = {}
|
||||
if args.train:
|
||||
for scenario, (version, new) in train.train_all(SETTINGS, environment).items():
|
||||
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
||||
versions[scenario] = version
|
||||
if not args.promote:
|
||||
return 0
|
||||
code = 0
|
||||
for scenario in SETTINGS.scenarios:
|
||||
version = versions.get(scenario) or getattr(train.latest(scenario, environment), "version", None)
|
||||
if version is None:
|
||||
print(f"{scenario}: no {environment} version to promote; use --train", file=sys.stderr)
|
||||
code = 1
|
||||
continue
|
||||
try:
|
||||
current = registry.client.get_model_version_by_alias(registered_name("tea", scenario), PRODUCTION_ALIAS)
|
||||
except Exception: # noqa: BLE001 -- no version in production yet
|
||||
current = None
|
||||
if current is not None and str(current.version) == str(version):
|
||||
print(f"{scenario}: version {version} already in production")
|
||||
continue
|
||||
try:
|
||||
registry.promote("tea", scenario, str(version))
|
||||
print(f"{scenario}: version {version} promoted")
|
||||
except PromotionBlocked as blocked:
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
|
||||
print(f"{scenario}: version {version} not promoted, missing: {failed}", file=sys.stderr)
|
||||
code = 1
|
||||
return code
|
||||
@@ -1,52 +0,0 @@
|
||||
# The EEG analysis: the `tea` library's plan and modules, and the library feature each stored metric is.
|
||||
domain = "tea"
|
||||
plan = "director-cluster"
|
||||
impl = "modern"
|
||||
line_hz = 60.0
|
||||
# Completed months at the study: days / days_per_month, as the TEA cohort counts them.
|
||||
days_per_month = 30.4375
|
||||
# The baselines' kind (the library's: "curves", centile curves on log age; or "age_blocks").
|
||||
baseline = "curves"
|
||||
|
||||
# The reference cohort the age baselines are trained on: the Helsinki HK1K EEGs (public), its EDFs and the table of
|
||||
# their ages under `prefix` in the cluster's S3, children of `ages` months. Its mains are at `line_hz`.
|
||||
[reference]
|
||||
name = "hk1k"
|
||||
prefix = "raw/eeg-helsinki/"
|
||||
ages_table = "anon_codex_age_sex.csv"
|
||||
line_hz = 50.0
|
||||
ages = [16.0, 36.0]
|
||||
|
||||
# One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the
|
||||
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode.
|
||||
# The feature each metric maps to is provisional until the domain expert confirms it.
|
||||
[[metrics]]
|
||||
code = "RITMO_POSTERIOR"
|
||||
biomarker = "posterior_rhythm"
|
||||
feature = "posterior_rhythm_hz"
|
||||
|
||||
[[metrics]]
|
||||
code = "HUSOS_SUENO_N2"
|
||||
biomarker = "spindles"
|
||||
phase = "N2"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
|
||||
[[metrics]]
|
||||
code = "HUSOS_SUENO_N3"
|
||||
biomarker = "spindles"
|
||||
phase = "N3"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
|
||||
[[metrics]]
|
||||
code = "PICOS_PAROXISTICOS"
|
||||
biomarker = "spikes"
|
||||
feature = "spike_rate_nrem"
|
||||
|
||||
[[metrics]]
|
||||
code = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
biomarker = "gradient"
|
||||
feature = "gradient_delta_sueno"
|
||||
@@ -0,0 +1,66 @@
|
||||
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
|
||||
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
|
||||
|
||||
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
|
||||
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
|
||||
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
|
||||
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
|
||||
channels at 0.5-45 Hz.
|
||||
"""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.checks import window_qc
|
||||
from models.tea.eeg.read import Recording
|
||||
|
||||
NOTCH_HZ = 60.0
|
||||
NOTCH_MIN_DB = 6.0
|
||||
WINDOW_S = 4.0
|
||||
STEP_S = 2.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Prepared:
|
||||
x: np.ndarray # (samples, scalp channels) µV, average reference
|
||||
names: tuple[str, ...] # the kept scalp channels
|
||||
fs: float
|
||||
starts: np.ndarray # window grid starts, s
|
||||
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean
|
||||
annotations: tuple[tuple[float, float, str], ...]
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return len(self.x) / self.fs
|
||||
|
||||
def columns(self, wanted) -> list[str]:
|
||||
"""The kept channels among `wanted`, in `wanted`'s order."""
|
||||
return [name for name in wanted if name in self.names]
|
||||
|
||||
def data(self, names) -> np.ndarray:
|
||||
return self.x[:, [self.names.index(name) for name in names]]
|
||||
|
||||
|
||||
def prepare(rec: Recording, bad) -> Prepared:
|
||||
scalp = [name for name in rec.of("eeg") if name not in bad]
|
||||
x = rec.x[:, [rec.names.index(name) for name in scalp]]
|
||||
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB:
|
||||
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5)
|
||||
gaps = ~np.isfinite(x).all(axis=1)
|
||||
y = signals.bandpass(x, rec.fs, 0.5, 100.0)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
|
||||
referenced = y - np.nanmean(y, axis=1, keepdims=True)
|
||||
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
|
||||
# memory (the layout decides the order of float sums along time).
|
||||
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
|
||||
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
||||
qc[gaps] = np.nan
|
||||
unclean = tuple(
|
||||
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
|
||||
)
|
||||
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
|
||||
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates.
|
||||
|
||||
`edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no
|
||||
recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the
|
||||
majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the
|
||||
kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes.
|
||||
|
||||
Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or
|
||||
to EKG/LOC/ROC; anything else is not a channel the analysis reads.
|
||||
"""
|
||||
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
|
||||
import edfio
|
||||
import mne
|
||||
import numpy as np
|
||||
|
||||
STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz"
|
||||
CANONICAL = {name.upper(): name for name in STANDARD.split()}
|
||||
RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
|
||||
AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC"))
|
||||
EARS = {"A1", "A2"}
|
||||
EOG = {"LOC", "ROC"}
|
||||
# What a header's start date holds when the writer didn't know it.
|
||||
UNKNOWN_START = date(1985, 1, 1)
|
||||
|
||||
|
||||
class FileNotValid(ValueError):
|
||||
"""The bytes are not an EDF the analysis can read."""
|
||||
|
||||
|
||||
def normalize(label: str) -> str | None:
|
||||
"""The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel."""
|
||||
text = str(label).strip()
|
||||
if not text or "ANNOT" in text.upper():
|
||||
return None
|
||||
stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
|
||||
key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper())
|
||||
if key in CANONICAL:
|
||||
name = CANONICAL[key]
|
||||
return RENAMED.get(name, name)
|
||||
return next((name for part, name in AUXILIARY if part in text.upper()), None)
|
||||
|
||||
|
||||
def kind(name: str) -> str:
|
||||
"""`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name."""
|
||||
if name in EARS:
|
||||
return "ear"
|
||||
if name in EOG:
|
||||
return "eog"
|
||||
return "ecg" if name == "EKG" else "eeg"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Recording:
|
||||
x: np.ndarray # (samples, channels) µV, NaN in gaps
|
||||
fs: float
|
||||
names: tuple[str, ...]
|
||||
annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text)
|
||||
start: date | None
|
||||
birthday: date | None
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return len(self.x) / self.fs
|
||||
|
||||
def kinds(self) -> dict[str, str]:
|
||||
return {name: kind(name) for name in self.names}
|
||||
|
||||
def of(self, *kinds: str) -> list[str]:
|
||||
"""The channels of these kinds, in file order."""
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
if len(edf) < 256:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
try:
|
||||
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
if not signals:
|
||||
raise FileNotValid("the EDF declares zero signals")
|
||||
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
||||
named = [(label, name, rate) for label, name, rate in named if name is not None]
|
||||
if not named:
|
||||
raise FileNotValid("no recognised channel")
|
||||
rates = [rate for _, _, rate in named]
|
||||
fs = max(set(rates), key=rates.count)
|
||||
kept, seen = [], set()
|
||||
for label, name, rate in named:
|
||||
if abs(rate - fs) <= 1e-6 and name not in seen:
|
||||
seen.add(name)
|
||||
kept.append((label, name))
|
||||
return kept
|
||||
|
||||
|
||||
def read(edf: bytes) -> Recording:
|
||||
kept = _kept(edf)
|
||||
options = dict(include=[label for label, _ in kept], preload=True, verbose="error")
|
||||
try:
|
||||
raw = mne.io.read_raw_edf(io.BytesIO(edf), **options)
|
||||
except Exception as exc: # notes in a Windows code page
|
||||
if "latin1" not in str(exc):
|
||||
raise
|
||||
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
|
||||
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
|
||||
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
|
||||
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
|
||||
start = raw.info.get("meas_date")
|
||||
born = (raw.info.get("subject_info") or {}).get("birthday")
|
||||
notes = tuple(
|
||||
(float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations
|
||||
)
|
||||
return Recording(
|
||||
x=x,
|
||||
fs=float(raw.info["sfreq"]),
|
||||
names=tuple(names),
|
||||
annotations=notes,
|
||||
start=start.date() if isinstance(start, datetime) else start,
|
||||
birthday=date(*born) if isinstance(born, tuple) else born,
|
||||
)
|
||||
|
||||
|
||||
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None:
|
||||
"""Months from birth to the recording, to one decimal; None when a date is missing or is the
|
||||
unknown-start placeholder, the birth is after the start or the age is over 18 years."""
|
||||
if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
|
||||
return None
|
||||
months = round((start - birthday).days / days_per_month, 1)
|
||||
return months if months <= 216 else None
|
||||
@@ -0,0 +1,60 @@
|
||||
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
||||
children of 16 to 36 months, recorded on 50 Hz mains.
|
||||
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
||||
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
||||
from the valid studies.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models import cluster
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
NAME = "hk1k"
|
||||
MAINS_HZ = 50.0
|
||||
AGES = (16.0, 36.0)
|
||||
|
||||
|
||||
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
||||
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
||||
table = pd.read_csv(ages_table)
|
||||
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
||||
found = []
|
||||
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
|
||||
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
||||
if age is not None and age == age and ages[0] <= age <= ages[1]:
|
||||
found.append((path, age))
|
||||
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
|
||||
|
||||
def _one(key: str, edf: bytes, age: float) -> dict:
|
||||
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
|
||||
return {
|
||||
"key": key,
|
||||
"age_months": age,
|
||||
"valid": a.valid,
|
||||
"error": a.error,
|
||||
"features": a.features,
|
||||
}
|
||||
|
||||
|
||||
def measure(studies) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
||||
(models.cluster)."""
|
||||
# each task carries its recording: workers see no local folder
|
||||
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
"""Scenario -> its training table: the valid studies' features and `age_months`."""
|
||||
usable = [s for s in measured if s["valid"] and s["error"] is None]
|
||||
return {
|
||||
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
|
||||
for name in SCENARIOS
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
"""The analysis's settings (`model.toml`): the plan, the implementation and the metrics with their library features.
|
||||
|
||||
Each trained baseline is a registered model `tea-<scenario>`, one per biomarker and sleep stage
|
||||
(`eeg-spindles-n2`, `eeg-spindle-topography-n2`, `eeg-posterior-rhythm`, ...).
|
||||
"""
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Metric:
|
||||
code: str
|
||||
biomarker: str
|
||||
feature: str
|
||||
phase: str | None = None
|
||||
electrodes: str | None = None
|
||||
electrode_prefix: str = ""
|
||||
|
||||
@property
|
||||
def scenario(self) -> str:
|
||||
return scenario_of(self.biomarker, self.phase)
|
||||
|
||||
@property
|
||||
def electrode_scenario(self) -> str | None:
|
||||
return scenario_of(self.electrodes, self.phase) if self.electrodes else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reference:
|
||||
name: str
|
||||
prefix: str
|
||||
ages_table: str
|
||||
line_hz: float
|
||||
ages: tuple[float, float]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
domain: str
|
||||
plan: str
|
||||
impl: str
|
||||
line_hz: float
|
||||
days_per_month: float
|
||||
baseline: str
|
||||
reference: Reference
|
||||
metrics: tuple[Metric, ...]
|
||||
|
||||
@property
|
||||
def phases(self) -> tuple[str, ...]:
|
||||
return tuple(dict.fromkeys(m.phase for m in self.metrics if m.phase))
|
||||
|
||||
@property
|
||||
def scenarios(self) -> dict[str, tuple[str, str | None]]:
|
||||
"""Each baseline to train, by scenario: (biomarker, sleep stage)."""
|
||||
pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)}
|
||||
|
||||
@property
|
||||
def biomarkers(self) -> tuple[str, ...]:
|
||||
"""Every biomarker a metric reads, its own or its electrodes'."""
|
||||
names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
return tuple(dict.fromkeys(names))
|
||||
|
||||
|
||||
def scenario_of(biomarker: str, phase: str | None) -> str:
|
||||
return "eeg-" + biomarker.replace("_", "-") + (f"-{phase.lower()}" if phase else "")
|
||||
|
||||
|
||||
@cache
|
||||
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
|
||||
raw = tomllib.loads(path.read_text())
|
||||
metrics = tuple(Metric(**m) for m in raw.pop("metrics"))
|
||||
reference = raw.pop("reference")
|
||||
reference = Reference(**{**reference, "ages": tuple(reference["ages"])})
|
||||
codes = [m.code for m in metrics]
|
||||
if len(set(codes)) != len(codes):
|
||||
raise ValueError(f"model.toml maps a metric code twice: {codes}")
|
||||
if raw["impl"] != "modern":
|
||||
raise ValueError("the analysis stores the modern validation's checks: impl must be 'modern'")
|
||||
return Settings(metrics=metrics, reference=reference, **raw)
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Signal primitives every step shares.
|
||||
|
||||
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
|
||||
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
|
||||
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
|
||||
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains
|
||||
notch, the fixed-line search and the dominant peak are small rules of their own: no library
|
||||
computes the same thing (MNE's notch filters change the signal by microvolts).
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from mne.time_frequency import psd_array_welch
|
||||
from scipy import signal
|
||||
from scipy.ndimage import median_filter
|
||||
|
||||
|
||||
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
|
||||
"""`(start, stop)` of each run of True."""
|
||||
edges = np.diff(np.concatenate([[False], np.asarray(valid, bool), [False]]).astype(int))
|
||||
return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True))
|
||||
|
||||
|
||||
def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray:
|
||||
"""`fn` on each gap-free run of rows at least `minimum` long; NaN elsewhere."""
|
||||
x = np.asarray(x, float)
|
||||
out = np.full_like(x, np.nan)
|
||||
for a, b in runs(np.isfinite(x).all(axis=1)):
|
||||
if b - a >= minimum:
|
||||
out[a:b] = fn(x[a:b])
|
||||
return out
|
||||
|
||||
|
||||
def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray:
|
||||
"""Zero-phase Butterworth band-pass of each gap-free run."""
|
||||
sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos")
|
||||
minimum = max(3 * (2 * len(sos) + 1), int(fs))
|
||||
return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
|
||||
|
||||
|
||||
def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray:
|
||||
"""Mains removal by spectrum interpolation: around `f0` and each harmonic below 98 % of
|
||||
Nyquist, the FFT magnitudes within `width` Hz are replaced by a line from the mean magnitude
|
||||
of the `2 width` Hz on the left to that on the right, keeping the phase."""
|
||||
centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
|
||||
|
||||
def interpolate(run):
|
||||
f = np.fft.rfftfreq(len(run), 1 / fs)
|
||||
spectrum = np.fft.rfft(run, axis=0)
|
||||
for c in centres:
|
||||
inside = (f >= c - width) & (f <= c + width)
|
||||
left = (f >= c - 3 * width) & (f < c - width)
|
||||
right = (f > c + width) & (f <= c + 3 * width)
|
||||
if not (inside.any() and left.any() and right.any()):
|
||||
continue
|
||||
k = np.linspace(0, 1, int(inside.sum()))[:, None]
|
||||
target = (
|
||||
np.abs(spectrum[left]).mean(axis=0)[None, :] * (1 - k)
|
||||
+ np.abs(spectrum[right]).mean(axis=0)[None, :] * k
|
||||
)
|
||||
current = spectrum[inside]
|
||||
magnitude = np.abs(current)
|
||||
phase = np.where(magnitude > 0, current / np.maximum(magnitude, 1e-30), 1.0)
|
||||
spectrum[inside] = target * phase
|
||||
return np.fft.irfft(spectrum, n=len(run), axis=0)
|
||||
|
||||
return by_runs(x, interpolate, max(int(2 * fs), 256))
|
||||
|
||||
|
||||
def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
|
||||
"""Per channel, dB of the mains peak (`f0` ± 0.6 Hz) over its neighbourhood (2-6 Hz away),
|
||||
from one Hann-tapered FFT of the rows finite in every channel."""
|
||||
finite = np.isfinite(x).all(axis=1)
|
||||
if not finite.any():
|
||||
return np.full(x.shape[1], np.nan)
|
||||
run = x[finite] - x[finite].mean(axis=0)
|
||||
f = np.fft.rfftfreq(len(run), 1 / fs)
|
||||
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2
|
||||
peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0)
|
||||
around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6))
|
||||
near = power[around].mean(axis=0)
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
|
||||
|
||||
|
||||
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
|
||||
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
|
||||
n = segments.shape[-1]
|
||||
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
return f, power
|
||||
|
||||
|
||||
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
|
||||
"""Frequencies of narrow fixed lines of a recording (artefacts, not EEG): the power of 8 s
|
||||
Hann segments, averaged and its median taken over channels, in dB above a 4 Hz running
|
||||
median; local maxima in [1, f_max] Hz at least 6 dB up and at most 0.5 Hz wide at -3 dB,
|
||||
the most prominent kept where two lie within 0.5 Hz."""
|
||||
n = int(round(8 * fs))
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
taper = np.hanning(n)[:, None]
|
||||
total, count = None, 0
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
segment = x[a : a + n]
|
||||
if np.isfinite(segment).all():
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
total = power if total is None else total + power
|
||||
count += 1
|
||||
if not count:
|
||||
return []
|
||||
db = 10 * np.log10(np.maximum(np.median(total / count, axis=1), 1e-30))
|
||||
df = float(f[1] - f[0])
|
||||
half = max(1, int(round(2 / df)))
|
||||
prominence = db - median_filter(db, size=2 * half + 1, mode="nearest")
|
||||
f_max = min(f_max, fs / 2 - 2)
|
||||
found = []
|
||||
for i in range(1, len(f) - 1):
|
||||
p = prominence[i]
|
||||
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]:
|
||||
continue
|
||||
a = b = i
|
||||
while a > 0 and prominence[a - 1] >= p - 3:
|
||||
a -= 1
|
||||
while b < len(f) - 1 and prominence[b + 1] >= p - 3:
|
||||
b += 1
|
||||
if (b - a + 1) * df <= 0.5:
|
||||
found.append((round(float(f[i]), 3), round(float(p), 1)))
|
||||
kept = []
|
||||
for hz, db_up in sorted(found, key=lambda line: -line[1]):
|
||||
if all(abs(hz - other) > 0.5 for other, _ in kept):
|
||||
kept.append((hz, db_up))
|
||||
return [hz for hz, _ in kept]
|
||||
|
||||
|
||||
def band_power(f, power, lo, hi, lines=(), include_hi=False):
|
||||
"""Power summed over [lo, hi) Hz (`include_hi`: [lo, hi]) along the first axis of `power`,
|
||||
without the bins within 1 Hz of a fixed line, rescaled to the band's full width."""
|
||||
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
|
||||
clean = band.copy()
|
||||
for line in lines:
|
||||
clean &= np.abs(f - line) > 1.0
|
||||
if not clean.any():
|
||||
return np.full(power.shape[1:], np.nan) if power.ndim > 1 else np.nan
|
||||
return power[clean].sum(axis=0) * (band.sum() / clean.sum())
|
||||
|
||||
|
||||
def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]:
|
||||
"""The largest 3-14 Hz peak over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz:
|
||||
(Hz, prominence in dB, found). Found when at least 1.5 dB up and not at the band's edge."""
|
||||
usable = (f >= 1.5) & (f <= 45) & (power > 0)
|
||||
background = usable & ~((f >= 4) & (f <= 16))
|
||||
if background.sum() < 5:
|
||||
return np.nan, np.nan, False
|
||||
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1)
|
||||
residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
|
||||
fu = f[usable]
|
||||
band = (fu >= 3) & (fu <= 14)
|
||||
if not band.any():
|
||||
return np.nan, np.nan, False
|
||||
i = int(np.argmax(residual[band]))
|
||||
prominence = float(residual[band][i])
|
||||
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
|
||||
return (float(fu[band][i]) if found else np.nan), prominence, bool(found)
|
||||
@@ -0,0 +1,223 @@
|
||||
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
|
||||
|
||||
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
|
||||
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
|
||||
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
|
||||
disconnection, photic stimulation and hyperventilation are masked.
|
||||
|
||||
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
|
||||
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
|
||||
muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by
|
||||
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
|
||||
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
|
||||
posterior electrode leaves that feature out of the mean.
|
||||
|
||||
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
|
||||
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
|
||||
20 % of the 30 s centred on it, else N2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
|
||||
NOTE_WORDS = {
|
||||
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"),
|
||||
"hyperventilation": ("hv", "hipervent", "hypervent"),
|
||||
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
|
||||
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
|
||||
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
|
||||
"n1", "n2", "n3"),
|
||||
"awake": ("despierta", "despierto", "arousal", "vigilia"),
|
||||
"crying": ("llanto", "llora", "cry"),
|
||||
"movement": ("movimiento", "movement", "artefacto de movimiento"),
|
||||
"feeding": ("come", "alimenta", "biberon", "lactancia"),
|
||||
} # fmt: skip
|
||||
EXCLUDED = ("crying", "movement", "disconnection")
|
||||
MASKED = (*EXCLUDED, "photic", "hyperventilation")
|
||||
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
|
||||
BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16),
|
||||
"beta": (16, 30), "high": (20, 40)} # fmt: skip
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
CENTRAL = ("C3", "C4", "Cz")
|
||||
FRONTAL = ("F3", "F4", "Fz")
|
||||
|
||||
|
||||
def note_state(text: str) -> str | None:
|
||||
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
|
||||
plain = "".join(
|
||||
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
|
||||
)
|
||||
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
|
||||
return next(
|
||||
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
|
||||
)
|
||||
|
||||
|
||||
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
|
||||
"""(onset s, duration s, state) covering the record: the notes' states and `unmarked`."""
|
||||
notes = sorted(annotations, key=lambda note: note[0])
|
||||
found = []
|
||||
for i, (t0, length, text) in enumerate(notes):
|
||||
state = note_state(text)
|
||||
if state is None:
|
||||
continue
|
||||
if length > 0:
|
||||
t1 = t0 + length
|
||||
else:
|
||||
following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None)
|
||||
t1 = min(t0 + 60.0, following if following else t0 + 60.0)
|
||||
if t1 - t0 >= 1:
|
||||
found.append((t0, t1, state))
|
||||
found.sort(key=lambda piece: piece[0])
|
||||
full, cursor = [], 0.0
|
||||
for t0, t1, state in found:
|
||||
if t0 - cursor >= 1:
|
||||
full.append((cursor, t0, "unmarked"))
|
||||
full.append((t0, t1, state))
|
||||
cursor = max(cursor, t1)
|
||||
if duration_s - cursor >= 1:
|
||||
full.append((cursor, duration_s, "unmarked"))
|
||||
pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full]
|
||||
return [(t0, t1 - t0, state) for t0, t1, state in pieces]
|
||||
|
||||
|
||||
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
|
||||
"""The state covering most of [t0, t1) and whether it covers less than 80 % of it."""
|
||||
overlap = {}
|
||||
for onset, length, state in intervals:
|
||||
lo, hi = max(t0, onset), min(t1, onset + length)
|
||||
if hi > lo:
|
||||
overlap[state] = overlap.get(state, 0) + (hi - lo)
|
||||
if not overlap:
|
||||
return "unlabelled", False
|
||||
dominant = max(overlap, key=overlap.get)
|
||||
return dominant, overlap[dominant] < 0.8 * (t1 - t0)
|
||||
|
||||
|
||||
def mask(prep: Prepared, intervals) -> np.ndarray:
|
||||
"""Samples of the QC spans and of the masked notes."""
|
||||
out = np.zeros(len(prep.x), bool)
|
||||
spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)]
|
||||
for onset, length in spans:
|
||||
out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True
|
||||
return out
|
||||
|
||||
|
||||
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
|
||||
"""Start samples of the usable windows and their features."""
|
||||
fs, x, names = prep.fs, prep.x, list(prep.names)
|
||||
n, step = int(WINDOW_S * fs), int(2 * fs)
|
||||
starts = [
|
||||
a
|
||||
for a in range(0, len(x) - n + 1, step)
|
||||
if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
|
||||
]
|
||||
if not starts:
|
||||
return [], {}
|
||||
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
|
||||
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
|
||||
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
|
||||
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
|
||||
posterior = [names.index(c) for c in POSTERIOR if c in names]
|
||||
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
|
||||
features = {
|
||||
"delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
|
||||
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
|
||||
"muscle": np.median(
|
||||
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
|
||||
),
|
||||
"alpha": np.median(band["alpha"] / total, axis=1),
|
||||
}
|
||||
if posterior:
|
||||
peaks = [
|
||||
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
|
||||
]
|
||||
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
|
||||
return starts, features
|
||||
|
||||
|
||||
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
|
||||
"""The weighted mean of the standardised features, clipped to ±6."""
|
||||
z, weights = [], []
|
||||
for name, ref in REFERENCE["features"].items():
|
||||
if name not in features:
|
||||
continue
|
||||
if "slope" in ref and age_months and age_months > 0:
|
||||
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
|
||||
else:
|
||||
median = ref["median"]
|
||||
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
|
||||
weights.append(ref["weight"])
|
||||
w = np.array(weights, float)
|
||||
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
|
||||
|
||||
|
||||
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
|
||||
"""`wake`, `drowsy`, `sleep` or `` (not scored) per grid window."""
|
||||
starts, features = _features(prep, mask(prep, intervals))
|
||||
out = np.full(len(prep.starts), "", dtype=object)
|
||||
if not starts:
|
||||
return out
|
||||
labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])]
|
||||
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
|
||||
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
|
||||
return out
|
||||
|
||||
|
||||
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
|
||||
"""(onset s, duration s) of the slow waves of one channel."""
|
||||
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
|
||||
sign = np.sign(y)
|
||||
sign[sign == 0] = 1
|
||||
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
|
||||
waves = []
|
||||
for j, c0 in enumerate(crossings):
|
||||
if not y[c0] < 0:
|
||||
continue
|
||||
if j + 2 >= len(crossings):
|
||||
break
|
||||
c1, c2 = crossings[j + 1], crossings[j + 2]
|
||||
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
|
||||
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
|
||||
continue
|
||||
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
|
||||
if 75.0 <= p2p <= 300.0:
|
||||
waves.append((round(c0 / fs, 3), round(total, 3)))
|
||||
return waves
|
||||
|
||||
|
||||
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
|
||||
if not waves:
|
||||
return np.empty((0, 2))
|
||||
a = np.array([onset for onset, _ in waves])
|
||||
b = a + np.array([length for _, length in waves])
|
||||
order = np.argsort(a)
|
||||
out = [[a[order[0]], b[order[0]]]]
|
||||
for i in order[1:]:
|
||||
if a[i] <= out[-1][1]:
|
||||
out[-1][1] = max(out[-1][1], b[i])
|
||||
else:
|
||||
out.append([a[i], b[i]])
|
||||
return np.array(out)
|
||||
|
||||
|
||||
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
|
||||
"""`N3` or `N2` per sleep window (`` elsewhere)."""
|
||||
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
|
||||
covered = _merged(waves)
|
||||
out = np.full(len(prep.starts), "", dtype=object)
|
||||
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
|
||||
if label != "sleep":
|
||||
continue
|
||||
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
|
||||
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
|
||||
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
|
||||
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
|
||||
return out
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Paroxysmal spikes in sleep: candidates per channel, merged into discharges, counted against
|
||||
the clean minutes of sleep.
|
||||
|
||||
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
|
||||
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
|
||||
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
|
||||
one. Each kept window adds its 2 s to the state of its midpoint.
|
||||
|
||||
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
|
||||
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
|
||||
flanks at least 6 x the MAD of the channel's slope; inside a kept window. Its field is the
|
||||
number of 10-20 neighbours with a same-sign candidate within 25 ms.
|
||||
|
||||
Discharge: candidates closer than 180 ms are one; the largest (in MADs) gives its channel, state
|
||||
and width. A useful discharge has field and is not a vertex wave (asleep, max on Cz/Fz/Pz, a
|
||||
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
|
||||
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
|
||||
|
||||
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode
|
||||
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.checks import NEIGHBOURS
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
from models.tea.eeg.sleep import EXCLUDED, window_note
|
||||
from models.tea.eeg.spindles import ZONES
|
||||
|
||||
ELECTRODES = tuple(NEIGHBOURS)
|
||||
GATE_S = 2.0
|
||||
VERTEX = ("Cz", "Fz", "Pz")
|
||||
POSTS = ("O1", "O2")
|
||||
OCULAR = ("Fp1", "Fp2", "F7", "F8")
|
||||
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
|
||||
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
|
||||
ASLEEP = ("N2", "N3", "sleep")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Spikes:
|
||||
rate: float # useful discharges per minute of clean sleep
|
||||
electrodes: dict[str, float]
|
||||
zones: dict[str, float]
|
||||
minutes: float # clean sleep minutes, the rate's exposure
|
||||
|
||||
|
||||
def _mad(v: np.ndarray) -> float:
|
||||
v = v[np.isfinite(v)]
|
||||
if not len(v):
|
||||
return np.nan
|
||||
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
|
||||
|
||||
|
||||
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
||||
"""(start, end) s of the 2 s windows the detector reads."""
|
||||
n = int(GATE_S * fs)
|
||||
top = min(45, fs / 2 * 0.9)
|
||||
lines = signals.fixed_lines(x, fs, f_max=top)
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
taper = np.hanning(n)[:, None]
|
||||
kept = []
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
t0, t1 = a / fs, a / fs + GATE_S
|
||||
state, mixed = window_note(t0, t1, intervals)
|
||||
segment = x[a : a + n]
|
||||
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
||||
continue
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
power = power.mean(axis=1)
|
||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||
muscle = float(high / max(low, 1e-12))
|
||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
||||
if not (muscle > 1.5 or frozen > 0.5):
|
||||
kept.append((round(t0, 2), round(t1, 2)))
|
||||
return kept
|
||||
|
||||
|
||||
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
|
||||
"""(slower flank's slope µV/s, width ms) of the transient peaking at `i`, at half height."""
|
||||
n = len(y)
|
||||
if i <= 0 or i >= n - 1:
|
||||
return np.nan, np.nan
|
||||
w = int(500 * fs / 1000)
|
||||
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
|
||||
peak = float(y[i]) - base
|
||||
if peak == 0.0:
|
||||
return np.nan, np.nan
|
||||
sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
|
||||
a, low = i, max(0, i - reach)
|
||||
while a > low and sign * (y[a] - base) >= half:
|
||||
a -= 1
|
||||
b, high = i, min(n - 1, i + reach)
|
||||
while b < high and sign * (y[b] - base) >= half:
|
||||
b += 1
|
||||
if b <= a:
|
||||
return np.nan, np.nan
|
||||
rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)
|
||||
return float(min(rise, fall)), float((b - a) / fs * 1000.0)
|
||||
|
||||
|
||||
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
|
||||
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
|
||||
if np.isfinite(y).sum() < fs * 2:
|
||||
return []
|
||||
slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
|
||||
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
|
||||
return []
|
||||
v = np.abs(y)
|
||||
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
|
||||
after = int(100 * fs / 1000), int(500 * fs / 1000)
|
||||
out = []
|
||||
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
|
||||
slope, width = _flanks(y, int(i), fs)
|
||||
if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
|
||||
continue
|
||||
if slope < 6.0 * slope_mad:
|
||||
continue
|
||||
a, b = int(i) + after[0], min(int(i) + after[1], len(y))
|
||||
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
|
||||
out.append(
|
||||
dict(
|
||||
channel=channel,
|
||||
t=float(i) / fs,
|
||||
sign=int(np.sign(y[i])),
|
||||
width=width,
|
||||
size=float(abs(y[i]) / amplitude_mad),
|
||||
post=post,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _field(c: pd.DataFrame) -> np.ndarray:
|
||||
"""Per candidate, its 10-20 neighbours with a same-sign candidate within 25 ms."""
|
||||
times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
|
||||
out = np.zeros(len(c), int)
|
||||
for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)):
|
||||
for other in NEIGHBOURS.get(ch, ()):
|
||||
near = times.get((other, s))
|
||||
if near is None:
|
||||
continue
|
||||
j = np.searchsorted(near, t)
|
||||
close = near[max(j - 1, 0) : j + 1]
|
||||
out[k] += bool(np.any(np.abs(close - t) <= 0.025))
|
||||
return out
|
||||
|
||||
|
||||
def _merge(c: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per discharge: candidates closer than 180 ms."""
|
||||
c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True)
|
||||
groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1)
|
||||
rows = []
|
||||
for g in groups:
|
||||
part = c.iloc[g]
|
||||
top = c.loc[part["size"].idxmax()]
|
||||
asleep = top.state in ASLEEP
|
||||
signs = dict(zip(part.channel, part.sign, strict=True))
|
||||
frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
|
||||
opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
|
||||
vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0
|
||||
posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0
|
||||
rows.append(
|
||||
dict(
|
||||
channel=top.channel,
|
||||
state=top.state,
|
||||
field=int(part.field.max()),
|
||||
useful=not (vertex or posts or frontal_only or opposite),
|
||||
)
|
||||
)
|
||||
return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"])
|
||||
|
||||
|
||||
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
||||
"""None with fewer than 4 10-20 channels."""
|
||||
channels = [c for c in prep.names if c in ELECTRODES]
|
||||
if len(channels) < 4:
|
||||
return None
|
||||
fs = prep.fs
|
||||
x = np.array(prep.data(channels), dtype=np.float64)
|
||||
labelled = [
|
||||
(s, s + WINDOW_S, label)
|
||||
for s, label in zip(prep.starts, states, strict=True)
|
||||
if label in ("wake", "drowsy", "sleep")
|
||||
]
|
||||
|
||||
def state_at(t: np.ndarray) -> np.ndarray:
|
||||
"""The state of the first labelled window holding each time."""
|
||||
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
|
||||
for t0, t1, label in labelled:
|
||||
hit = open_ & (t0 <= t) & (t < t1)
|
||||
out[hit], open_ = label, open_ & ~hit
|
||||
return out
|
||||
|
||||
gate = _gate(x, fs, intervals)
|
||||
minutes = {}
|
||||
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
||||
for (t0, t1), state in zip(gate, middles, strict=True):
|
||||
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
||||
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
|
||||
counts = dict.fromkeys(channels, 0)
|
||||
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
||||
if candidates and gate:
|
||||
c = pd.DataFrame(candidates)
|
||||
t = c.t.to_numpy(float)
|
||||
inside = np.zeros(len(t), bool)
|
||||
for t0, t1 in gate:
|
||||
inside |= (t >= t0) & (t < t1)
|
||||
c = c[inside]
|
||||
if len(c):
|
||||
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
|
||||
found = _merge(c)
|
||||
found = found[found.useful & (found.field > 0) & (found.state == "sleep")]
|
||||
for channel, n in found.channel.value_counts().items():
|
||||
counts[channel] = int(n)
|
||||
rounded = round(sleep_minutes, 2)
|
||||
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan
|
||||
electrodes = {
|
||||
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
|
||||
for e in ELECTRODES
|
||||
}
|
||||
zones = {}
|
||||
for zone, members in ZONES.items():
|
||||
present = [e for e in members if e in counts]
|
||||
total = sum(counts[e] for e in present)
|
||||
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
|
||||
sigma envelope per electrode.
|
||||
|
||||
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
|
||||
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
|
||||
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
|
||||
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
|
||||
envelope peaks 3 x over the median.
|
||||
|
||||
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
|
||||
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
|
||||
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
|
||||
the episode ± 0.25 s, over the median envelope in sleep.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy.signal import hilbert, welch
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
|
||||
SIGMA = (11.0, 16.0)
|
||||
ZONES = {
|
||||
"frontal_left": ("Fp1", "F3", "F7"),
|
||||
"frontal_right": ("Fp2", "F4", "F8"),
|
||||
"frontal_midline": ("Fz",),
|
||||
"central": ("C3", "Cz", "C4"),
|
||||
"parietal": ("P3", "Pz", "P4"),
|
||||
"temporal_left": ("T3", "T5"),
|
||||
"temporal_right": ("T4", "T6"),
|
||||
"occipital": ("O1", "O2"),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Spindles:
|
||||
events: list[tuple[float, float, str]] # (onset s, duration s, channel)
|
||||
minutes: float
|
||||
channels: list[str] # the channels searched (none when under a minute of the stage)
|
||||
|
||||
|
||||
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
y = signals.bandpass(x, fs, *SIGMA)
|
||||
envelope = np.abs(hilbert(np.nan_to_num(y), axis=0))
|
||||
k = max(1, int(0.2 * fs))
|
||||
envelope = np.apply_along_axis(
|
||||
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
|
||||
)
|
||||
envelope[~np.isfinite(y)] = np.nan
|
||||
return y, envelope
|
||||
|
||||
|
||||
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
|
||||
edges = np.diff(extent.astype(np.int8), prepend=0, append=0)
|
||||
out = []
|
||||
for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True):
|
||||
if not core[a:b].any():
|
||||
continue
|
||||
if 0.5 <= (b - a) / fs <= 3.0:
|
||||
out.append((int(a), int(b)))
|
||||
elif (b - a) / fs > 3.0:
|
||||
step = int(3.0 * fs)
|
||||
for c in range(a, b, step):
|
||||
e = min(c + step, b)
|
||||
if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any():
|
||||
out.append((int(c), int(e)))
|
||||
return out
|
||||
|
||||
|
||||
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
|
||||
"""Sigma over its flanks, and an instantaneous frequency in band."""
|
||||
if not np.isfinite(x).all():
|
||||
return False
|
||||
nperseg = min(len(x), int(fs))
|
||||
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
|
||||
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
|
||||
flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
|
||||
if not inside.any() or not flanks.any():
|
||||
return False
|
||||
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
|
||||
return False
|
||||
frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi)
|
||||
frequency = frequency[np.isfinite(frequency)]
|
||||
in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)]
|
||||
if len(in_band) < 0.5 * max(len(frequency), 1):
|
||||
return False
|
||||
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
|
||||
|
||||
|
||||
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
|
||||
"""The spindles in the grid windows staged `stage`."""
|
||||
fs, n = prep.fs, int(WINDOW_S * prep.fs)
|
||||
asleep = np.zeros(len(prep.x), bool)
|
||||
for start, s in zip(prep.starts, staged, strict=True):
|
||||
if s == stage:
|
||||
a = int(round(float(start) * fs))
|
||||
asleep[a : a + n] = True
|
||||
minutes = float(asleep.sum() / fs / 60)
|
||||
names = prep.columns([c for c in prep.names if c in CHANNELS])
|
||||
if minutes < 1 or not names:
|
||||
return Spindles([], minutes, [])
|
||||
x = prep.data(names)
|
||||
y, envelope = _envelope(x, fs)
|
||||
events = []
|
||||
for i, name in enumerate(names):
|
||||
in_stage = np.where(asleep, envelope[:, i], np.nan)
|
||||
values = in_stage[np.isfinite(in_stage)]
|
||||
if len(values) < fs * 30:
|
||||
continue
|
||||
median = float(np.median(values)) or 1e-9
|
||||
core = max(float(np.percentile(values, 95)), 3 * median)
|
||||
extent = max(float(np.percentile(values, 70)), 1.6 * median)
|
||||
finite = np.isfinite(in_stage)
|
||||
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs):
|
||||
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
|
||||
events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
|
||||
return Spindles(events, minutes, names)
|
||||
|
||||
|
||||
def density(found: Spindles) -> tuple[float, dict[str, float]]:
|
||||
"""Spindles per minute and channel (rounded to 3), and per zone; NaN when none."""
|
||||
zones = dict.fromkeys(ZONES, np.nan)
|
||||
if not found.events or found.minutes <= 0:
|
||||
return np.nan, zones
|
||||
counts = {}
|
||||
for _, _, channel in found.events:
|
||||
counts[channel] = counts.get(channel, 0) + 1
|
||||
for zone, electrodes in ZONES.items():
|
||||
searched = [e for e in electrodes if e in found.channels]
|
||||
if searched:
|
||||
total = sum(counts.get(e, 0) for e in searched)
|
||||
zones[zone] = total / (found.minutes * len(searched))
|
||||
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
|
||||
return round(per_channel, 3), zones
|
||||
|
||||
|
||||
def _episodes(events) -> list[list[float]]:
|
||||
if not events:
|
||||
return []
|
||||
a = np.array([onset for onset, _, _ in events], float)
|
||||
b = a + np.array([length for _, length, _ in events], float)
|
||||
order = np.argsort(a)
|
||||
out = [[a[order[0]], b[order[0]]]]
|
||||
for i in order[1:]:
|
||||
if a[i] <= out[-1][1]:
|
||||
out[-1][1] = max(out[-1][1], b[i])
|
||||
else:
|
||||
out.append([a[i], b[i]])
|
||||
return out
|
||||
|
||||
|
||||
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]:
|
||||
"""Per spindle electrode, the envelope's median peak over episodes against its sleep median
|
||||
(NaN for an absent electrode, or without spindles)."""
|
||||
out = dict.fromkeys(CHANNELS, np.nan)
|
||||
use = prep.columns(CHANNELS)
|
||||
episodes = _episodes(found.events)
|
||||
if not use or not episodes:
|
||||
return out
|
||||
fs = prep.fs
|
||||
y = signals.bandpass(prep.data(use), fs, *SIGMA)
|
||||
envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs))
|
||||
asleep = np.zeros(len(envelope), bool)
|
||||
for start, label in zip(prep.starts, states, strict=True):
|
||||
if label == "sleep":
|
||||
asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True
|
||||
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
|
||||
peaks = np.full((len(episodes), len(use)), np.nan)
|
||||
for k, (t0, t1) in enumerate(episodes):
|
||||
a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
|
||||
if b - a >= 3:
|
||||
peaks[k] = np.nanmax(envelope[a:b], axis=0)
|
||||
for j, name in enumerate(use):
|
||||
if np.isfinite(median[j]) and median[j] > 0:
|
||||
out[name] = float(np.nanmedian(peaks[:, j]) / median[j])
|
||||
return out
|
||||
@@ -1,217 +0,0 @@
|
||||
"""The age baselines: trained on the reference cohort and registered, one version per scenario (biomarker and sleep
|
||||
stage), as `tea-<scenario>`.
|
||||
|
||||
1. `listing`: the reference cohort's EDFs and ages, within `[reference] ages`, read from the cluster's S3 in a worker
|
||||
(only the workers reach it). Its hash identifies the cohort a version was trained on (ML-03).
|
||||
2. `measure`: each study through the analysis's own unit of work (`analyze.reference`), as a Dask batch.
|
||||
3. `train_scenario`: a fresh library module trained on the valid studies' features and ages, logged with the
|
||||
library's MLflow model (`tea.serving.log_biomarker`, whose guard refuses groups under 5 and anything per child),
|
||||
then its run and version given what the registry's promotion checks read: environment, the reference cohort,
|
||||
the model's hash, the five routine records and its metrics.
|
||||
|
||||
Promotion is the registry's (`registry.promote`), as for every model: it waits for the technical, clinical and
|
||||
interpretability reports, so the domain expert's validation is what puts a baseline in production.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.lineage import (
|
||||
COHORT_BUILD_TAG,
|
||||
COHORT_SOURCE_TAG,
|
||||
COHORT_URL_TAG,
|
||||
MODEL_SHA_TAG,
|
||||
code_version,
|
||||
registered_name,
|
||||
)
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
from models.io.tracking import routine_path
|
||||
from models.tea.eeg.analyze import ReferenceStudy, pipeline, plan, reference
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
DOMAIN = "tea"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The reference studies to measure, (key, path, age in months), and the hash that identifies them. Keys are
|
||||
positions, never file names."""
|
||||
|
||||
studies: tuple[tuple[str, str, float], ...]
|
||||
sha256: str
|
||||
|
||||
@classmethod
|
||||
def of(cls, name: str, paths_and_ages: list[tuple[str, float]]) -> "Listing":
|
||||
ordered = sorted(paths_and_ages)
|
||||
digest = hashlib.sha256("\n".join(f"{p}|{a}" for p, a in ordered).encode()).hexdigest()
|
||||
return cls(tuple((f"{name}-{k:04d}", p, a) for k, (p, a) in enumerate(ordered, 1)), digest)
|
||||
|
||||
|
||||
def list_reference(s: Settings) -> list[tuple[str, float]]:
|
||||
"""In a worker: (s3 path, age in months) of each reference EDF with an age inside `[reference] ages`."""
|
||||
from tea.pipeline.storage import s3
|
||||
|
||||
r = s.reference
|
||||
fs = s3()
|
||||
paths = fs.find(r.prefix)
|
||||
tables = [p for p in paths if p.endswith(r.ages_table)]
|
||||
if not tables:
|
||||
raise FileNotFoundError(f"no {r.ages_table} under {r.prefix}")
|
||||
with fs.open(tables[0], "rb") as f:
|
||||
ages = pd.read_csv(f)
|
||||
ages.columns = ["archivo", "edad_anos", *ages.columns[2:]]
|
||||
edfs = {Path(p).name: p for p in paths if p.endswith(".edf")}
|
||||
found = [("s3://" + edfs[row.archivo], round(float(row.edad_anos) * 12, 1))
|
||||
for row in ages.itertuples() if row.archivo in edfs]
|
||||
return [(p, a) for p, a in found if r.ages[0] <= a <= r.ages[1]]
|
||||
|
||||
|
||||
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
|
||||
return Listing.of(s.reference.name, found)
|
||||
|
||||
|
||||
def measure(found: Listing, s: Settings, cluster: str = "auto") -> list[ReferenceStudy]:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
def lost(args, exc):
|
||||
return ReferenceStudy(args[0], args[2], error=f"{type(exc).__name__}: the batch lost this study")
|
||||
|
||||
return run_batch(reference, [(k, p, a, s, s.reference.line_hz) for k, p, a in found.studies], cluster=cluster,
|
||||
on_error=lost)
|
||||
|
||||
|
||||
def table(studies: list[ReferenceStudy], biomarker: str, phase: str | None) -> pd.DataFrame:
|
||||
"""The valid studies' features of one biomarker and stage, with their ages: what a baseline is trained on."""
|
||||
rows = [{**st.features[biomarker, phase], "age_months": st.age_months} for st in studies
|
||||
if st.valid == 1 and st.error is None and (biomarker, phase) in st.features]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _module_state(module) -> tuple[str, dict]:
|
||||
"""The trained module's hash (its saved parameters and baselines) and its baselines' state, by feature."""
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
module.save(folder)
|
||||
files = sorted(Path(folder).glob("*.json"))
|
||||
digest = hashlib.sha256(b"".join(f.name.encode() + f.read_bytes() for f in files)).hexdigest()
|
||||
baselines = json.loads((Path(folder) / "baseline.json").read_text())
|
||||
return digest, baselines
|
||||
|
||||
|
||||
def _covered(state: dict, n_min: float) -> tuple[float, float] | None:
|
||||
"""The ages every feature's curve covers with at least `n_min` effective studies."""
|
||||
spans = []
|
||||
for baseline in (state.values() if "name" not in state else [state]):
|
||||
curve = baseline.get("curva") or {}
|
||||
ages = [a for a, n in zip(curve.get("edad_meses", []), curve.get("n_efectivo", [])) if n and n >= n_min]
|
||||
if not ages:
|
||||
return None
|
||||
spans.append((min(ages), max(ages)))
|
||||
return (max(lo for lo, _ in spans), min(hi for _, hi in spans)) if spans else None
|
||||
|
||||
|
||||
def find_trained(scenario: str, expected: dict[str, str]):
|
||||
"""The newest version of the scenario whose tags hold every expected value, or `None`."""
|
||||
from mlflow import MlflowClient
|
||||
|
||||
found = MlflowClient().search_model_versions(f"name='{registered_name(DOMAIN, scenario)}'")
|
||||
matching = [mv for mv in found if all(mv.tags.get(k) == v for k, v in expected.items())]
|
||||
return max(matching, key=lambda mv: int(mv.version), default=None)
|
||||
|
||||
|
||||
def expected_tags(scenario: str, found: Listing, s: Settings, environment: str) -> dict[str, str]:
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
module = pipeline(s).module(biomarker)
|
||||
return {"environment": environment, COHORT_BUILD_TAG: found.sha256, "plan_hash": plan(s).get("hash", ""),
|
||||
"module": biomarker, "module_version": getattr(module, "version", "?"), "phase": phase or "",
|
||||
"baseline": s.baseline}
|
||||
|
||||
|
||||
def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing, s: Settings, environment: str) -> str:
|
||||
"""Trains, logs and registers one scenario's baseline; returns its version."""
|
||||
from mlflow import MlflowClient
|
||||
from tea.serving import log_biomarker
|
||||
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
data = table(studies, biomarker, phase)
|
||||
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
||||
module.train(data)
|
||||
sha, state = _module_state(module)
|
||||
name = registered_name(DOMAIN, scenario)
|
||||
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
||||
experiment=name)
|
||||
client, run_id, version = MlflowClient(), mv.run_id, str(mv.version)
|
||||
|
||||
tags = {"domain": DOMAIN, "scenario": scenario, MODEL_SHA_TAG: sha,
|
||||
COHORT_URL_TAG: f"{DOMAIN}/{REFERENCE_SOURCE}/{s.reference.name}", COHORT_SOURCE_TAG: REFERENCE_SOURCE,
|
||||
**expected_tags(scenario, found, s, environment)}
|
||||
for key, value in {**tags, **code_version()}.items():
|
||||
client.set_tag(run_id, key, value)
|
||||
for key, value in tags.items():
|
||||
client.set_model_version_tag(name, version, key, value)
|
||||
|
||||
features = [c for c in data.columns if c != "age_months"]
|
||||
present = {f: int(data[f].notna().sum()) for f in features}
|
||||
params = getattr(module, "baseline_params", {}) or {}
|
||||
n_min = float(params.get("n_min", 30))
|
||||
covered = _covered(state, n_min) if s.baseline == "curves" else None
|
||||
measured = [st for st in studies if st.error is None]
|
||||
routines = {
|
||||
"MUESTREO": {"cohorte": s.reference.name, "edades_meses": list(s.reference.ages),
|
||||
"estudios_listados": len(found.studies), "medidos": len(measured),
|
||||
"validos": sum(st.valid == 1 for st in measured), "con_error": len(studies) - len(measured),
|
||||
"usados": len(data), "fase_de_sueno": phase},
|
||||
"DATOS_FALTANTES": {"criterio": "cada curva usa los estudios con ese rasgo medido; los demás se omiten",
|
||||
"estudios_con_valor_por_rasgo": present},
|
||||
"METODO_ANALITICO": {"modulo": biomarker, "version_modulo": tags["module_version"], "linea_base": s.baseline,
|
||||
"parametros": params, "plan": s.plan, "plan_hash": tags["plan_hash"],
|
||||
"red_electrica_hz": s.reference.line_hz},
|
||||
"BALANCE_CLASES": {"aplica": False, "motivo": "una curva de referencia por edad no tiene clases"},
|
||||
"CONFIANZA_SALIDA": {"salida": "z contra la curva a la edad del niño; -1/+1 debajo del p5 / arriba del p95",
|
||||
"edades_cubiertas_meses": list(covered) if covered else None,
|
||||
"n_efectivo_minimo": n_min},
|
||||
}
|
||||
for kind, record in routines.items():
|
||||
client.log_text(run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
||||
client.log_metric(run_id, "n_referencia", len(data))
|
||||
for feature, n in present.items():
|
||||
client.log_metric(run_id, f"n.{feature}", n)
|
||||
if covered:
|
||||
client.log_metric(run_id, "edad_min_cubierta", covered[0])
|
||||
client.log_metric(run_id, "edad_max_cubierta", covered[1])
|
||||
client.update_model_version(name, version, description=(
|
||||
f"Curva de referencia por edad de {biomarker}{f' en sueño {phase}' if phase else ''}, entrenada en "
|
||||
f"{s.reference.name} ({len(data)} estudios de {s.reference.ages[0]:g} a {s.reference.ages[1]:g} meses). "
|
||||
"Pendiente de validación clínica."))
|
||||
return version
|
||||
|
||||
|
||||
def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Listing | None = None,
|
||||
studies: list[ReferenceStudy] | None = None) -> dict[str, tuple[str, bool]]:
|
||||
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
||||
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
||||
scenario needs it."""
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
studies = studies if studies is not None else measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
|
||||
|
||||
def latest(scenario: str, environment: str):
|
||||
"""The newest version of the scenario trained in `environment`, or `None`."""
|
||||
return find_trained(scenario, {"environment": environment})
|
||||
@@ -0,0 +1,236 @@
|
||||
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
|
||||
(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
|
||||
children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every
|
||||
analysed EEG against the child's age. The math is the old platform's, proved on its HK1K
|
||||
cohort by models/tests/test_eeg.py."""
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
|
||||
from core.tea import ados2
|
||||
from core.tea import association as relation
|
||||
from models import cluster
|
||||
from models.jobs import EmptyCohort
|
||||
from models.tea import association
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
from persistance import eeg, registry, silver
|
||||
|
||||
CURVES = curves.SCENARIOS
|
||||
ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted
|
||||
MODELS = [*CURVES, ASSOCIATION]
|
||||
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
|
||||
|
||||
|
||||
class Baseline(mlflow.pyfunc.PythonModel):
|
||||
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z,
|
||||
outside, p5, median and p95 out, for one of its features."""
|
||||
|
||||
def __init__(self, scenario: str, baseline: dict):
|
||||
self.scenario, self.baseline = scenario, baseline
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||
feature = (params or {}).get("feature", "value")
|
||||
rows = model_input.to_dict("records")
|
||||
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
|
||||
r.get("age_months"), r.get("exposure"))
|
||||
for r in rows]) # fmt: skip
|
||||
|
||||
|
||||
def analyze() -> int:
|
||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||||
pending = eeg.pending()
|
||||
done = cluster.run(
|
||||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
||||
) # one task per EEG
|
||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||
eeg.save_analyses(found)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
return len(found)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jobs:
|
||||
"""The domain's model jobs (models.definitions): every curve is routine."""
|
||||
|
||||
def routine(self) -> list[str]:
|
||||
return list(MODELS)
|
||||
|
||||
def scored(self) -> list[str]:
|
||||
return list(MODELS) # the curves, then the association on their scores
|
||||
|
||||
|
||||
JOBS = Jobs()
|
||||
|
||||
|
||||
def registered(name: str) -> str:
|
||||
return f"tea.{name}"
|
||||
|
||||
|
||||
def train(name: str, as_of: date | None = None) -> int:
|
||||
if name == ASSOCIATION:
|
||||
return _train_association(as_of)
|
||||
return _train_curve(name, as_of)
|
||||
|
||||
|
||||
def _train_curve(name: str, as_of: date | None = None) -> int:
|
||||
"""A new version of one age curve, trained on the site's reference group as known on
|
||||
`as_of` (today by default), with its two reports: the group it learned from, and its
|
||||
centile curves."""
|
||||
day = as_of or date.today()
|
||||
measured = eeg.ruled_out(day)
|
||||
if not measured:
|
||||
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
|
||||
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
|
||||
table = reference.tables(measured)[name]
|
||||
baseline = curves.train(table, name)
|
||||
ages = [m["age_months"] for m in measured]
|
||||
technical = {
|
||||
"model": name, "method": "age curves (weighted centiles on log age)",
|
||||
"cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
|
||||
"studies": len(measured), "valid_studies": len(measured),
|
||||
"ages_months": [min(ages), max(ages)], "features": sorted(baseline),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||||
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
||||
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
|
||||
|
||||
|
||||
def score(name: str) -> int | None:
|
||||
if name == ASSOCIATION:
|
||||
return _score_association()
|
||||
return _score_curve(name)
|
||||
|
||||
|
||||
def _score_curve(name: str) -> int | None:
|
||||
"""The champion curve's scores of every analysed EEG: the metric's value, and each
|
||||
electrode and zone it measures; None without a champion."""
|
||||
found = registry.champion(registered(name))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
baseline = model.unwrap_python_model().baseline
|
||||
scenario, label = CURVES[name], f"{registered(name)}/{version}"
|
||||
rows = []
|
||||
for one in eeg.analysed():
|
||||
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
||||
if metric is None:
|
||||
continue
|
||||
exposure = (
|
||||
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None
|
||||
)
|
||||
for part in scenario.parts:
|
||||
sites = {"": metric["value"]} if part == "value" else metric[part]
|
||||
prefix = "" if part == "value" else curves.PREFIX[part]
|
||||
for site, value in sites.items():
|
||||
feature = "value" if part == "value" else prefix + site
|
||||
if feature not in baseline:
|
||||
continue
|
||||
s = curves.score(baseline[feature], value, one["age_months"], exposure)
|
||||
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
|
||||
"scenario": name, "model": label, "metric": scenario.metric,
|
||||
"part": part, "site": site or None, **s}) # fmt: skip
|
||||
eeg.save_scores(name, rows)
|
||||
return version
|
||||
|
||||
|
||||
class Association(mlflow.pyfunc.PythonModel):
|
||||
"""The fitted association as MLflow serves it: a cohort in, each child's probabilities."""
|
||||
|
||||
def __init__(self, fitted: dict):
|
||||
self.fitted = fitted
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||
return pd.DataFrame(association.score(self.fitted, model_input))
|
||||
|
||||
|
||||
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
|
||||
module, items, CSS and the z of each biomarker; fitted on each child's first EEG with
|
||||
any z, every EEG scored."""
|
||||
day = str(as_of) if as_of else None
|
||||
rows = []
|
||||
for r in eeg.association_inputs(relation.BIOMARKERS):
|
||||
a = r["ados2"]
|
||||
evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None
|
||||
if day and (r["study_date"] > day or (evaluated and evaluated > day)):
|
||||
continue
|
||||
css = None
|
||||
if evaluated and r["birth_date"]:
|
||||
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
||||
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
||||
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
|
||||
"module": a.get("module"), "css": css,
|
||||
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
|
||||
**{k: v for k, v in r.items() if k.startswith("z_")}}) # fmt: skip
|
||||
scored = pd.DataFrame(rows)
|
||||
if scored.empty:
|
||||
return scored, scored
|
||||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||||
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
|
||||
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
|
||||
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
|
||||
|
||||
|
||||
def _train_association(as_of: date | None = None) -> int:
|
||||
"""A new version of the association, fitted on the site's children, with its reports:
|
||||
the cohort and pairs it estimated, and the pairs themselves."""
|
||||
fit, _ = association_cohort(as_of)
|
||||
if fit.empty:
|
||||
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
|
||||
fitted = association.fit(fit)
|
||||
pairs = association.associations(fitted)
|
||||
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
||||
technical = {
|
||||
"model": ASSOCIATION, "method": "Firth logistic (items) / cumulative logit (CSS), "
|
||||
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
|
||||
"cohort": "site: children with an ADOS-2 and a valid EEG",
|
||||
"as_of": str(as_of or date.today()),
|
||||
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
|
||||
"estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"],
|
||||
"children": int(fitted["n"]), "rows": pairs} # fmt: skip
|
||||
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
|
||||
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports)
|
||||
|
||||
|
||||
def _score_association() -> int | None:
|
||||
"""The champion association's probabilities for every scored EEG; None without one."""
|
||||
found = registry.champion(registered(ASSOCIATION))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
fitted = model.unwrap_python_model().fitted
|
||||
label = f"{registered(ASSOCIATION)}/{version}"
|
||||
_, scored = association_cohort()
|
||||
kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low",
|
||||
"ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip
|
||||
pairs = [{**{k: p[k] for k in kept}, "model": label,
|
||||
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
|
||||
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
|
||||
"sensitivity": p["sens_model"]}
|
||||
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
|
||||
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, or the CSS
|
||||
if not scored.empty:
|
||||
keys = scored["key"].tolist()
|
||||
for n in relation.ITEMS:
|
||||
items = association.item_scores(scored, n).tolist()
|
||||
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
|
||||
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True))
|
||||
scores = []
|
||||
for one in association.score(fitted, scored) if not scored.empty else []:
|
||||
seen = observed.get(one["outcome_code"], {}).get(one["key"])
|
||||
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
|
||||
shown = None if seen is None or seen != seen else float(seen)
|
||||
scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}",
|
||||
"observed": shown}) # fmt: skip
|
||||
eeg.save_association(label, pairs, scores)
|
||||
return version
|
||||
@@ -1,52 +0,0 @@
|
||||
"""Helpers for other code's tests: a known `RiskEstimator` to run the risk chain without a trained model.
|
||||
|
||||
`CacuStandIn` gives a fixed, predictable probability from two baseline predictors, without MLflow, so a
|
||||
test of estimating, storing, confirming or publishing risks can assert exact values. It isn't a clinical
|
||||
model and isn't used outside tests; it has no tests of its own.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from models.io.contracts import Provenance, Risk
|
||||
|
||||
# A base probability and what each baseline predictor adds, capped at `tope`.
|
||||
CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
||||
NORMAL_PAPS = ("NORMAL",)
|
||||
|
||||
|
||||
class CacuStandIn:
|
||||
"""A deterministic estimator over the frame of `cacu/cohorte_vigilancia`.
|
||||
|
||||
The probability is `CACU_RULE["base"]`, plus `pap_anormal` if `pap_0` is neither `NORMAL` nor null,
|
||||
plus `vph_positivo` if `hpv_0` is `POSITIVO`, capped at `tope`. One `Risk` per member and horizon, in
|
||||
the frame's order, with no interval. `modelo_sha` is the sha256 of the rule, so changing it changes
|
||||
the provenance.
|
||||
"""
|
||||
|
||||
def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas",
|
||||
horizons: tuple[float, ...] = (0.0,)):
|
||||
self.cohort_url = cohort_url
|
||||
self.outcome = outcome
|
||||
self.horizons = tuple(horizons)
|
||||
|
||||
def provenance(self) -> Provenance:
|
||||
rule = {"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons}
|
||||
sha = hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]:
|
||||
missing = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columns]
|
||||
if missing:
|
||||
raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.")
|
||||
i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
|
||||
risks = []
|
||||
for row in rows:
|
||||
p = CACU_RULE["base"]
|
||||
if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS:
|
||||
p += CACU_RULE["pap_anormal"]
|
||||
if row[i_hpv] == "POSITIVO":
|
||||
p += CACU_RULE["vph_positivo"]
|
||||
p = min(p, CACU_RULE["tope"])
|
||||
risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons]
|
||||
return risks
|
||||
+31
-40
@@ -1,51 +1,42 @@
|
||||
[project]
|
||||
name = "models"
|
||||
version = "0.1.0"
|
||||
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
|
||||
version = "0.0.0"
|
||||
description = "Dagster assets and jobs; one module per model."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"core",
|
||||
"persistance",
|
||||
"extraction",
|
||||
"mlflow>=2.9",
|
||||
# The model DAGs (`models/pipelines`): each function a node, each parameter an edge.
|
||||
"apache-hamilton>=1.90",
|
||||
# Cohort builds are Parquet files, read and written as frames.
|
||||
"pandas>=2.0",
|
||||
"pyarrow>=15",
|
||||
"scikit-learn>=1.4",
|
||||
# The values of the cohort and estimate files (`models.io.contracts`).
|
||||
"pandera>=0.20",
|
||||
"tea",
|
||||
"dagster",
|
||||
"dagster-webserver",
|
||||
"mlflow-skinny",
|
||||
"openai>=3.59.0",
|
||||
"splink>=5.0.0",
|
||||
"duckdb>=2.0.1",
|
||||
"markitdown[docx,xlsx]>=0.1.9",
|
||||
"ocrmypdf>=17.14.2",
|
||||
"pikepdf>=10.0",
|
||||
"pdfplumber>=0.11.11",
|
||||
"scikit-learn>=1.9.1",
|
||||
"scipy>=1.18.1",
|
||||
"joblib>=1.6.0",
|
||||
"lifelines>=0.30.0",
|
||||
"mne>=1.13.2",
|
||||
"edfio>=0.4.18",
|
||||
"statsmodels>=0.15.0",
|
||||
"pgmpy>=1.1.2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Reading the EEG baselines' reference cohort from the cluster's S3 (`models.tea.eeg.train`).
|
||||
eeg-reference = ["tea[s3]"]
|
||||
# Running uploaded notebooks without Quarto (models.io.rendering.JupyterRenderer, models.pipelines.experiment).
|
||||
notebooks = [
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
tea = { path = "libs/tea", editable = true }
|
||||
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
|
||||
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["models"]
|
||||
exclude = ["**/notebooks"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
[tool.uv.build-backend]
|
||||
module-name = "models"
|
||||
module-root = ""
|
||||
[tool.uv.sources]
|
||||
core = { workspace = true }
|
||||
persistance = { workspace = true }
|
||||
|
||||
@@ -1,437 +0,0 @@
|
||||
"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members
|
||||
whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on
|
||||
a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run`
|
||||
commands over it, repeating no step.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
||||
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2
|
||||
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow; `cacu_db` (conftest), an empty CaCu database for
|
||||
the promotion checks.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
from models.cacu.cin2_logistic import model
|
||||
from models.cacu.cin2_logistic.train import find_trained, train
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
|
||||
from models.io.registry import PRODUCTION_ALIAS, registry
|
||||
|
||||
CUTOFF = date(2027, 6, 30)
|
||||
|
||||
|
||||
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
|
||||
clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion")
|
||||
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo,
|
||||
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60):
|
||||
"""The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given."""
|
||||
sample = f"S{pac_id}"
|
||||
rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample),
|
||||
_row(pac_id, index, 7, "vph", vph, sample)]
|
||||
if biopsy:
|
||||
rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy))
|
||||
return rows
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_frame():
|
||||
"""Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members:
|
||||
NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore."""
|
||||
rows = []
|
||||
for pac_id in range(1, 21):
|
||||
index = date(2025, 1, 1) + timedelta(days=pac_id)
|
||||
if pac_id % 2:
|
||||
rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG")
|
||||
else:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
|
||||
rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"),
|
||||
_row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")]
|
||||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
|
||||
def _write(frame, path, metadata):
|
||||
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata}
|
||||
pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
"""The frame as build 7's file."""
|
||||
return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
|
||||
_write(cohort_frame, folder / "7.parquet", {"armado_id": 7})
|
||||
_write(cohort_frame, folder / "12.parquet", {"armado_id": 12})
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_predictors_are_the_index_sample_results(cohort_frame):
|
||||
"""Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a
|
||||
result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is
|
||||
taken, or a missing result becomes NaN, which the encoder would reject."""
|
||||
found = model.predictors(cohort_frame).set_index("pac_id")
|
||||
|
||||
assert len(found) == 20
|
||||
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
|
||||
assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"]
|
||||
|
||||
|
||||
def test_the_genotype_is_read_from_its_number():
|
||||
"""Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails
|
||||
if the genotype is read from `valor_codigo`, which is empty for it."""
|
||||
index = date(2025, 1, 1)
|
||||
frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO")
|
||||
+ [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names)
|
||||
|
||||
assert model.predictors(frame).loc[0, "vph_16_18"] == "POSITIVO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
|
||||
("LIEAG", 400, 0)])
|
||||
def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
|
||||
"""Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if
|
||||
a lower grade counts, or a biopsy after the window does."""
|
||||
frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day),
|
||||
columns=SCHEMA.names)
|
||||
|
||||
assert model.outcome(frame, CUTOFF).loc[0, "y"] == expected
|
||||
|
||||
|
||||
def test_a_member_without_a_complete_window_is_scored_but_not_trained_on():
|
||||
"""Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out
|
||||
of `prepare`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives,
|
||||
which biases the risk down."""
|
||||
late = date(2027, 3, 1)
|
||||
frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS",
|
||||
biopsy_day=30), columns=SCHEMA.names)
|
||||
outcome = model.outcome(frame, CUTOFF).set_index("pac_id")
|
||||
|
||||
assert outcome["known"].tolist() == [False, True]
|
||||
assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2]
|
||||
|
||||
|
||||
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
|
||||
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
|
||||
is random or follows another column."""
|
||||
parts = model.split(model.prepare(model.predictors(cohort_frame), model.outcome(cohort_frame, CUTOFF)))
|
||||
|
||||
assert (len(parts["train"]), len(parts["test"])) == (14, 6)
|
||||
assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min()
|
||||
|
||||
|
||||
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
|
||||
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's
|
||||
window and the note that it's a prototype, and an artifact that holds `predictors`, so it takes the long frame. Fails
|
||||
if any is lost, or if the driver stops reaching `registered_model`."""
|
||||
version = train(cohort_file)
|
||||
|
||||
resolved = registry.resolve("cacu", "cin2_logistic", version)
|
||||
stored = registry.get("cacu", "cin2_logistic", version)
|
||||
run = registry.client.get_run(stored.run_id).data
|
||||
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
|
||||
assert "Prototipo" in stored.description and run.params["outcome_window_months"] == "12"
|
||||
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
|
||||
assert len(run.params["cohort_sha256"]) == 64
|
||||
|
||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
||||
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||
|
||||
|
||||
def test_training_records_each_routine_as_it_ran(cohort_file, cacu_db, mlflow_tracking):
|
||||
"""ML-01a: the run holds what sampling, missing data, the method, class balance and calibration actually did, in
|
||||
counts that add up to the split. Fails if a routine node stops being logged by `registered_model` or records
|
||||
something other than this training's own numbers."""
|
||||
version = train(cohort_file)
|
||||
routines = registry.routines(registry.get("cacu", "cin2_logistic", version).run_id)
|
||||
assert set(routines) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
|
||||
assert routines["MUESTREO"]["train"]["n"] == 14 and routines["MUESTREO"]["test"]["n"] == 6
|
||||
assert sum(routines["BALANCE_CLASES"]["train"].values()) == 14
|
||||
assert sum(b["n"] for b in routines["CONFIANZA_SALIDA"]["bins"]) == 6
|
||||
assert routines["METODO_ANALITICO"]["coefficients"]
|
||||
failed = {check.code for check in registry.checks("cacu", "cin2_logistic", version) if not check.passed}
|
||||
assert "ML-01a" not in failed and "ML-01b" not in failed
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
|
||||
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
|
||||
assert "version 1" in capsys.readouterr().out
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV"
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking):
|
||||
"""Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option
|
||||
is ignored."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--armado", "7", "--environment", "prod"]) == 0
|
||||
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
|
||||
|
||||
|
||||
def test_prod_without_a_build_is_refused(capsys):
|
||||
"""Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls
|
||||
back to the latest file."""
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(["train", "cacu", "cin2_logistic", "--environment", "prod"])
|
||||
|
||||
assert stopped.value.code == 2 and "--build" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arguments, message", [
|
||||
(["cacu", "ninguno"], "no such model: cacu/ninguno"),
|
||||
(["cacu", "cin2_logistic", "--armado", "99"], "export it"),
|
||||
])
|
||||
def test_what_is_missing_is_named(exported, arguments, message, capsys):
|
||||
"""Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no
|
||||
version. Fails if the command lets the import error through, or trains on another file."""
|
||||
assert main(["train", *arguments]) == 1
|
||||
assert message in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per
|
||||
member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest
|
||||
version instead of the alias, or the output can't be matched to members."""
|
||||
main(["train", "cacu", "cin2_logistic"])
|
||||
main(["train", "cacu", "cin2_logistic"])
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
||||
output = tmp_path / "risks" / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 0
|
||||
|
||||
assert "version 1" in capsys.readouterr().out
|
||||
risks = pd.read_parquet(output)
|
||||
assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"]
|
||||
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"modelo_version"] == b"1" and metadata[b"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit"
|
||||
|
||||
|
||||
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the
|
||||
alias becomes mandatory."""
|
||||
main(["train", "cacu", "cin2_logistic"])
|
||||
output = tmp_path / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0
|
||||
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||
|
||||
|
||||
def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes
|
||||
nothing. Fails if it falls back to another version or lets the error through."""
|
||||
main(["train", "cacu", "cin2_logistic"])
|
||||
output = tmp_path / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1
|
||||
|
||||
assert "no version in production" in capsys.readouterr().err and not output.exists()
|
||||
|
||||
|
||||
RUN = ["run", "cacu", "cin2_logistic"]
|
||||
|
||||
|
||||
def _versions():
|
||||
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
|
||||
|
||||
|
||||
def _armado(armado_id: int) -> None:
|
||||
"""A `CohorteArmado` row at this exact id, matching a build fixture's `armado_id` metadata: `registry.checks`'s
|
||||
ML-03 looks the tag up by id, so promoting a kit-sourced version needs the row to exist, not just the tag."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
session.add(CohorteArmado(
|
||||
armado_id=armado_id, url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella=f"huella-{armado_id}", marco_sha="m",
|
||||
n_miembros=20, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)))
|
||||
session.commit()
|
||||
|
||||
|
||||
def _promotable(domain: str, scenario: str, version: str) -> None:
|
||||
"""The three reports a fresh training run never carries (MLD-01/01b/03: attached by a human after training,
|
||||
not by the training code), so the version clears every promotion check."""
|
||||
registry.attach_reports(domain, scenario, version, technical_validation_report_uri="docs/tecnica.pdf",
|
||||
clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html")
|
||||
|
||||
|
||||
def test_run_without_a_step_is_refused(capsys):
|
||||
"""Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running
|
||||
steps."""
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(RUN)
|
||||
|
||||
assert stopped.value.code == 2 and "--export" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without
|
||||
its option."""
|
||||
assert main([*RUN, "--train"]) == 0
|
||||
|
||||
assert len(_versions()) == 1
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve("cacu", "cin2_logistic")
|
||||
|
||||
|
||||
def test_repeating_every_step_changes_nothing(exported, cacu_db, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops
|
||||
looking for the existing version, or `--estimate` stops reading the output's metadata."""
|
||||
output = tmp_path / "output.parquet"
|
||||
steps = [*RUN, "--train", "--armado", "12", "--environment", "prod", "--promote", "--estimate", "--output",
|
||||
str(output)]
|
||||
_armado(12)
|
||||
assert main([*RUN, "--train", "--armado", "12", "--environment", "prod"]) == 0
|
||||
_promotable("cacu", "cin2_logistic", "1")
|
||||
capsys.readouterr()
|
||||
|
||||
assert main(steps) == 0
|
||||
written = output.stat().st_mtime_ns
|
||||
capsys.readouterr()
|
||||
|
||||
assert main(steps) == 0
|
||||
|
||||
assert len(_versions()) == 1 and output.stat().st_mtime_ns == written
|
||||
out = capsys.readouterr().out
|
||||
assert "already trained" in out and "already in production" in out and "already estimated" in out
|
||||
|
||||
|
||||
def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
|
||||
"""Pins down: what says a training is the same is the file and the environment, so a build with other content or a
|
||||
PROD run gets its own version. Fails if the check ignores either and reuses a version from something else."""
|
||||
assert main([*RUN, "--train", "--armado", "7"]) == 0
|
||||
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
|
||||
frame = pd.read_parquet(exported / "12.parquet")
|
||||
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12})
|
||||
assert main([*RUN, "--train", "--armado", "12"]) == 0
|
||||
|
||||
assert len(_versions()) == 3
|
||||
|
||||
|
||||
def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch):
|
||||
"""Pins down: a version trained by other code isn't reused. Fails if the check stops comparing `code_sha256`."""
|
||||
assert main([*RUN, "--train"]) == 0
|
||||
assert find_trained(exported / "12.parquet") == "1"
|
||||
|
||||
monkeypatch.setattr(model, "code_sha256", lambda: "other")
|
||||
|
||||
assert find_trained(exported / "12.parquet") is None
|
||||
|
||||
|
||||
def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if
|
||||
`--estimate` skips because the file exists. The alias is moved directly (not through `--promote`, which needs its
|
||||
own promotion checklist satisfied, covered separately): this test is about `--estimate`'s own version tracking."""
|
||||
output = tmp_path / "output.parquet"
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
||||
assert main([*RUN, "--estimate", "--output", str(output)]) == 0
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "2")
|
||||
assert main([*RUN, "--estimate", "--output", str(output)]) == 0
|
||||
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
|
||||
|
||||
|
||||
def test_promote_needs_a_version(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias.
|
||||
Fails if it promotes some other version."""
|
||||
assert main([*RUN, "--promote"]) == 1
|
||||
assert "use --train or --version" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch):
|
||||
"""Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if
|
||||
the cohort or the build change, or training continues on a stale file."""
|
||||
calls = []
|
||||
|
||||
def refuse(cohorts, read_timeline, root, domain, url, build_id=None):
|
||||
calls.append((domain, url, build_id))
|
||||
raise LookupError(f"no such build of {url}: {build_id}")
|
||||
|
||||
monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse)
|
||||
|
||||
assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1
|
||||
|
||||
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
|
||||
assert not _versions()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dbt_exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
|
||||
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
|
||||
path = folder / f"{number}.parquet"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_write(frame, path, {"build": number, "producer": "dbt"})
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys):
|
||||
"""Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source,
|
||||
number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is
|
||||
ignored, or the version loses its cohort file."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt"]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert ARMADO_TAG not in tags
|
||||
assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia")
|
||||
assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating
|
||||
it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the
|
||||
dbt file. Also pins down that ML-03 (`registry.checks`) accepts a dbt cohort link, not only the kit's
|
||||
`armado_id`: without that, `--promote` below would always be refused for a dbt-trained version."""
|
||||
output = tmp_path / "output.parquet"
|
||||
base = ["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod"]
|
||||
|
||||
assert main([*base, "--train"]) == 0
|
||||
_promotable("cacu", "cin2_logistic", "1")
|
||||
assert main([*base, "--promote", "--estimate", "--output", str(output)]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1"
|
||||
assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"]
|
||||
|
||||
|
||||
def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys):
|
||||
"""Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's
|
||||
command is suggested or another build is used."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt", "--build", "9"]) == 1
|
||||
assert "--source dbt" in capsys.readouterr().err
|
||||
@@ -1,110 +0,0 @@
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
|
||||
import importlib
|
||||
|
||||
from persistance import db as persistance_db
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
|
||||
engine = getattr(persistance_db, f"get_{domain}_engine")
|
||||
engine.cache_clear()
|
||||
importlib.import_module(f"core.{domain}.models")
|
||||
if domain != "governance":
|
||||
importlib.import_module(f"core.{domain}.indicadores.models")
|
||||
base = getattr(importlib.import_module(base_module), base_class)
|
||||
base.metadata.create_all(engine())
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def governance_db(tmp_path, monkeypatch):
|
||||
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
|
||||
yield
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_db(tmp_path, monkeypatch):
|
||||
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
|
||||
yield
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tea_db(tmp_path, monkeypatch):
|
||||
engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel")
|
||||
yield
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mlflow_tracking(tmp_path, monkeypatch):
|
||||
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
|
||||
import mlflow
|
||||
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||
mlflow.set_tracking_uri(uri)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
yield
|
||||
|
||||
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
"""A model whose class lives in a module, as a PROD run requires: it returns its input."""
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True):
|
||||
"""A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some)
|
||||
and, with `model`, a saved model."""
|
||||
from core.governance.enums import Environment
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id)
|
||||
for kind in ROUTINE_KINDS if routines is None else routines:
|
||||
run.log_routine(kind, {"method": "prueba", "n": 8})
|
||||
if model:
|
||||
run.log_model(Echo())
|
||||
return run.finish(metrics=metrics)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def production_ready(governance_db, cacu_db, mlflow_tracking):
|
||||
"""Factory: registers a PROD version whose run recorded every routine and its model, with the three reports,
|
||||
so it passes every promotion check; returns (domain, scenario, version)."""
|
||||
from models.io.registry import registry
|
||||
|
||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
||||
run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8})
|
||||
version = registry.register_run(
|
||||
run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html",
|
||||
)
|
||||
return domain, scenario, version
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def armado(huella: str) -> int:
|
||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
fila = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(fila)
|
||||
session.flush()
|
||||
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
|
||||
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
|
||||
session.commit()
|
||||
return fila.armado_id
|
||||
@@ -1,95 +0,0 @@
|
||||
"""What this module covers: listing and describing a cohort's builds (`models.io.storage.list_builds`,
|
||||
`describe_build`) and the `models cohorts list` and `cohorts show` commands.
|
||||
|
||||
Fixtures: `root`, a cohorts folder with dbt builds 1 and 2 and kit build 7's file; `kit`, a stand-in of the cohort
|
||||
repository with kit builds 7 (exported) and 8 (not exported).
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
from models.io.storage import cohort_path, dbt_build_path, describe_build, list_builds
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
ATTRITION = [{"step": "all_patients", "n": 3, "excluded": None}, {"step": "indexed", "n": 2, "excluded": 1}]
|
||||
|
||||
|
||||
def _file(path, **metadata):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
pq.write_table(pa.table({"pac_id": [1]}).replace_schema_metadata({k: str(v) for k, v in metadata.items()}), path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path):
|
||||
for number in (1, 2):
|
||||
_file(dbt_build_path(tmp_path, URL, number), producer="dbt", build=number, datos_as_of="2026-12-31",
|
||||
n_members=2, built_at=f"2026-11-0{number}T00:00:00+00:00", rules=json.dumps(["prior_event"]),
|
||||
parametros=json.dumps({"cutoff": "2026-12-31"}), attrition=json.dumps(ATTRITION))
|
||||
_file(cohort_path(tmp_path, URL, 7), producer="kit", armado_id=7, datos_as_of="2026-12-31", n_members=2)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _kit_build(armado_id):
|
||||
return SimpleNamespace(armado_id=armado_id, url=URL, version="0.2.0", datos_as_of=date(2026, 12, 31), n_miembros=2,
|
||||
huella="h", armado_en=datetime(2026, 10, armado_id, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit():
|
||||
builds = {8: _kit_build(8), 7: _kit_build(7)}
|
||||
return SimpleNamespace(builds=lambda url: list(builds.values()) if url == URL else [], build=builds.get)
|
||||
|
||||
|
||||
def test_both_sources_are_listed_newest_first_with_their_files(root, kit):
|
||||
"""Pins down: dbt's builds come from their files, newest first, and the kit's from the repository, each saying
|
||||
whether its file exists. Fails if a source is dropped, the order is by name, or an unexported build shows a file."""
|
||||
rows = list_builds(root, URL, kit)
|
||||
|
||||
assert [(r["source"], r["build"]) for r in rows] == [("dbt", 2), ("dbt", 1), ("kit", 8), ("kit", 7)]
|
||||
assert rows[2]["file"] is None and rows[3]["file"].endswith("7.parquet")
|
||||
assert rows[0]["created"] == "2026-11-02T00:00:00+00:00"
|
||||
|
||||
|
||||
def test_without_the_repository_only_files_are_read(root):
|
||||
"""Pins down: listing dbt's builds needs no database. Fails if `list_builds` reaches for the kit's builds anyway."""
|
||||
assert [r["source"] for r in list_builds(root, URL)] == ["dbt", "dbt"]
|
||||
|
||||
|
||||
def test_a_dbt_build_is_described_with_its_lineage_decoded(root):
|
||||
"""Pins down: `describe_build` gives the file, its hash, and the parameters, rules and attrition as JSON values,
|
||||
not strings. Fails if the hash is missing or the lineage stays encoded."""
|
||||
described = describe_build(root, URL, "dbt", 2)
|
||||
|
||||
assert len(described["file_sha256"]) == 64
|
||||
assert described["lineage"]["attrition"] == ATTRITION and described["lineage"]["rules"] == ["prior_event"]
|
||||
assert described["lineage"]["parametros"] == {"cutoff": "2026-12-31"}
|
||||
|
||||
|
||||
def test_an_unexported_kit_build_is_described_from_the_database(root, kit):
|
||||
"""Pins down: a kit build without a file still has its lineage, from the repository; an unknown build is a
|
||||
`LookupError`. Fails if an unexported build is reported as missing, or a missing one as empty."""
|
||||
described = describe_build(root, URL, "kit", 8, kit)
|
||||
|
||||
assert described["file"] is None and described["lineage"]["n_members"] == "2"
|
||||
with pytest.raises(LookupError):
|
||||
describe_build(root, URL, "kit", 9, kit)
|
||||
with pytest.raises(LookupError):
|
||||
describe_build(root, URL, "dbt", 9)
|
||||
|
||||
|
||||
def test_the_commands_print_the_dbt_builds(root, monkeypatch, capsys):
|
||||
"""Pins down: `cohorts list --source dbt` and `cohorts show` work from the files alone. Fails if either opens the
|
||||
database for dbt's builds, or `show` prints something other than JSON."""
|
||||
monkeypatch.setenv("COHORTS_DIR", str(root))
|
||||
|
||||
assert main(["cohorts", "list", "cacu", "cohorte_vigilancia", "--source", "dbt"]) == 0
|
||||
listed = capsys.readouterr().out
|
||||
assert "dbt/2.parquet" in listed and "dbt/1.parquet" in listed
|
||||
assert main(["cohorts", "show", "cacu", "cohorte_vigilancia", "--build", "1"]) == 0
|
||||
assert json.loads(capsys.readouterr().out)["build"] == 1
|
||||
@@ -1,63 +0,0 @@
|
||||
"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it
|
||||
returns, `Risk` and `Provenance`.
|
||||
|
||||
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
||||
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
||||
"""
|
||||
|
||||
from models.io.contracts import Provenance, Risk, RiskEstimator
|
||||
|
||||
|
||||
class ConstantEstimator:
|
||||
"""Meets the contract with a fixed probability for every member and horizon."""
|
||||
|
||||
cohort_url = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2_mas"
|
||||
|
||||
def provenance(self) -> Provenance:
|
||||
return Provenance(modelo_nombre="constant", modelo_version="1", mlflow_run_id="none", modelo_sha="sha")
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]:
|
||||
i_pac = columns.index("pac_id")
|
||||
return [Risk(row[i_pac], h, 0.1) for row in rows for h in (0.0, 1.0)]
|
||||
|
||||
|
||||
class Incomplete:
|
||||
"""Has everything but `provenance`."""
|
||||
|
||||
cohort_url = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2_mas"
|
||||
|
||||
def estimate(self, columns, rows):
|
||||
return []
|
||||
|
||||
|
||||
def test_a_class_with_the_four_members_meets_the_contract():
|
||||
"""Pins down: `RiskEstimator` is checked at run time by its members (`cohort_url`, `outcome`,
|
||||
`provenance`, `estimate`), not by inheritance; missing one fails the check.
|
||||
|
||||
Fails if the protocol stops being `runtime_checkable` or a member is renamed.
|
||||
"""
|
||||
assert isinstance(ConstantEstimator(), RiskEstimator)
|
||||
assert not isinstance(Incomplete(), RiskEstimator)
|
||||
|
||||
|
||||
def test_provenance_has_the_four_keys_a_batch_stores():
|
||||
"""Pins down: `Provenance.as_dict()` has exactly the four keys of the risk batch's provenance columns.
|
||||
|
||||
Fails if a field is renamed or added: the batch columns wouldn't match.
|
||||
"""
|
||||
assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id",
|
||||
"modelo_sha"}
|
||||
|
||||
|
||||
def test_a_risk_keeps_the_column_names_and_its_interval_is_optional():
|
||||
"""Pins down: `Risk` fields are named after the columns they're saved to, in that order, and the
|
||||
interval defaults to `None`.
|
||||
|
||||
Fails if a field is renamed or reordered, or the interval becomes required.
|
||||
"""
|
||||
risk = Risk(1, 0.0, 0.25)
|
||||
|
||||
assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
|
||||
assert (risk.ic_bajo, risk.ic_alto) == (None, None)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""Each domain's extraction ranker in the model registry
|
||||
(`models.io.extraction_ranker`): every batch it learns from is a new DEV
|
||||
version continuing the latest, with its five routine records and its saved
|
||||
model; extraction takes the version in production, else the latest, and
|
||||
`EXTRACTION_RANKER` can restrict or turn that off.
|
||||
|
||||
Fixtures: `mlflow_tracking` (a SQLite MLflow per test) and `_fresh_cache`
|
||||
(an empty ranker cache and no `EXTRACTION_RANKER`). Batches are built
|
||||
inline by `_batch` from candidates with the features an extractor gives
|
||||
them; no document is read.
|
||||
"""
|
||||
import json
|
||||
|
||||
import mlflow.artifacts
|
||||
import pytest
|
||||
from extraction.document import BBox
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue
|
||||
from extraction.nlp.ranking import examples_for
|
||||
|
||||
from models.io import extraction_ranker
|
||||
from models.io.extraction_ranker import Batch, current, learn
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINES_PATH
|
||||
|
||||
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
|
||||
|
||||
|
||||
def _batch(right: str = "LIEBG") -> Batch:
|
||||
evidence = Evidence("reporte.pdf", 1, "Diagnóstico: NIC I", BBox(0, 0, 1, 0.1).as_list())
|
||||
candidates = [
|
||||
ExtractedValue("LIEBG", 0.5, "etiqueta", "NIC I", evidence, {"assertion": "afirmado", "section": "resultado"}),
|
||||
ExtractedValue("LIEAG", 0.6, "texto_libre", "NIC II", evidence, {"assertion": "afirmado", "section": "general"}),
|
||||
]
|
||||
examples = examples_for([GRADO], {"bx_cin_grado": candidates}, {"bx_cin_grado": right})
|
||||
return Batch(examples, "revision", documents=1, records=1, unreachable={})
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_cache(monkeypatch):
|
||||
"""No ranker cached from another test, and the default selection."""
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.delenv(extraction_ranker.SELECTION_ENV, raising=False)
|
||||
|
||||
|
||||
def test_each_batch_is_a_new_dev_version_with_its_routines(mlflow_tracking):
|
||||
"""Fails if learning stops registering a DEV version, its run loses one
|
||||
of the five routine records or its saved model, which ML-01a and ML-01b
|
||||
require to promote it."""
|
||||
version = learn("cacu", _batch())
|
||||
described = registry.get("cacu", extraction_ranker.SCENARIO, version)
|
||||
assert described.tags["environment"] == "DEV"
|
||||
checks = {c.code: c.passed for c in registry.checks("cacu", extraction_ranker.SCENARIO, version)}
|
||||
assert checks["ML-01a"] and checks["ML-01b"]
|
||||
|
||||
|
||||
def test_routine_records_hold_counts_never_document_text(mlflow_tracking):
|
||||
"""What a ranker stores can be shared: weights and counts. Fails if a
|
||||
routine record or the ranker's state carries a raw reading or the line
|
||||
it came from."""
|
||||
version = learn("cacu", _batch())
|
||||
run_id = registry.get("cacu", extraction_ranker.SCENARIO, version).run_id
|
||||
stored = json.dumps(mlflow.artifacts.load_dict(f"runs:/{run_id}/{extraction_ranker.RANKER_PATH}"))
|
||||
for kind in ("MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"):
|
||||
stored += mlflow.artifacts.load_text(f"runs:/{run_id}/{ROUTINES_PATH}/{kind}.json")
|
||||
assert "NIC I" not in stored and "Diagnóstico" not in stored and "reporte.pdf" not in stored
|
||||
|
||||
|
||||
def test_learning_continues_from_the_latest_version(mlflow_tracking):
|
||||
"""Fails if a new batch starts from scratch instead of the latest
|
||||
version, which would forget every earlier correction."""
|
||||
learn("cacu", _batch())
|
||||
second = learn("cacu", _batch())
|
||||
ranker = current("cacu")
|
||||
assert ranker.version == f"{extraction_ranker.SCENARIO}:{second}"
|
||||
assert ranker.examples == 2 * len(_batch().examples)
|
||||
|
||||
|
||||
def test_extraction_takes_production_first_and_can_be_turned_off(mlflow_tracking, monkeypatch):
|
||||
"""With a version in production that one is used even when newer DEV
|
||||
versions exist; `produccion` refuses DEV-only registries and `ninguno`
|
||||
turns the ranker off. Fails if the selection order changes."""
|
||||
assert current("cacu") is None
|
||||
first = learn("cacu", _batch())
|
||||
learn("cacu", _batch())
|
||||
registry.client.set_registered_model_alias("cacu-extraccion", "produccion", first)
|
||||
assert current("cacu").version == f"{extraction_ranker.SCENARIO}:{first}"
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "ninguno")
|
||||
assert current("cacu") is None
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "produccion")
|
||||
assert current("tea") is None
|
||||
|
||||
|
||||
def test_an_empty_batch_registers_nothing(mlflow_tracking):
|
||||
"""Fails if a review without usable examples creates a version."""
|
||||
assert learn("cacu", Batch([], "revision", 0, 0, {})) is None
|
||||
assert registry.versions("cacu", extraction_ranker.SCENARIO) == []
|
||||
@@ -1,75 +0,0 @@
|
||||
"""What this module covers: the value checks of the cohort and estimate files (`COHORT_FRAME`, `ESTIMATE_FRAME`,
|
||||
`check_frame` in `models.io.contracts`), and that reading a cohort file and building one apply them.
|
||||
|
||||
Fixtures: none; `_events` makes a valid two-member frame and each test breaks one rule.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, ESTIMATE_FRAME, CohortFileError, EstimateError,
|
||||
check_frame)
|
||||
from models.io.storage import read_cohort
|
||||
from models.steps.cohort_file import cohort_table
|
||||
|
||||
|
||||
def _events(**changes):
|
||||
frame = pd.DataFrame({"pac_id": [1, 1, 2], "fecha_indice": [date(2025, 1, 1)] * 2 + [date(2025, 2, 1)],
|
||||
"fecha": [date(2025, 1, 1), date(2025, 3, 1), date(2025, 2, 1)],
|
||||
"conocida_en": [datetime(2025, 4, 1, tzinfo=timezone.utc)] * 3,
|
||||
"clase": ["procedimiento", "medicion", "procedimiento"],
|
||||
"tipo": ["citologia", "bethesda", "citologia"], "codigo": ["c", "b", "c"],
|
||||
"valor_codigo": [None, "NORMAL", None], "valor_numerico": [None, None, None],
|
||||
"fuente_tabla": ["citologiacervical"] * 3, "fuente_id": ["a", "a", "b"]})
|
||||
for column, (row, value) in changes.items():
|
||||
frame.loc[row, column] = value
|
||||
return frame
|
||||
|
||||
|
||||
def test_a_valid_build_passes():
|
||||
"""Pins down: a well-formed frame comes back unchanged. Fails if a check rejects valid data, which would stop every
|
||||
export and training."""
|
||||
assert check_frame(COHORT_FRAME, _events(), CohortFileError, "test").equals(_events())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes, check", [
|
||||
({"fecha_indice": (1, date(2025, 1, 5))}, "more than one index date"),
|
||||
({"pac_id": (2, 0)}, "greater_than"),
|
||||
({"fecha": (0, None)}, "not_nullable"),
|
||||
({"tipo": (1, "")}, "str_length"),
|
||||
])
|
||||
def test_a_broken_build_names_what_failed(changes, check):
|
||||
"""Pins down: two index dates for a member, a non-positive id, a missing date or an empty type are refused, and
|
||||
the error names the check. Fails if a broken file reaches a model, where it would train on wrong rows."""
|
||||
with pytest.raises(CohortFileError, match=check):
|
||||
check_frame(COHORT_FRAME, _events(**changes), CohortFileError, "test")
|
||||
|
||||
|
||||
def test_reading_and_building_a_file_apply_the_checks(tmp_path):
|
||||
"""Pins down: `read_cohort` refuses a file whose rows break `COHORT_FRAME`, and `cohort_table` refuses to build
|
||||
one. Fails if either path skips the check."""
|
||||
broken = _events(fecha_indice=(1, date(2025, 1, 5)))
|
||||
path = tmp_path / "1.parquet"
|
||||
pq.write_table(pa.Table.from_pandas(broken, schema=COHORT_SCHEMA, preserve_index=False), path)
|
||||
|
||||
with pytest.raises(CohortFileError):
|
||||
read_cohort(path)
|
||||
with pytest.raises(CohortFileError):
|
||||
cohort_table(broken, {"build": 1})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("estimate", [
|
||||
pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "probabilidad": [0.1, 0.2]}),
|
||||
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [1.2]}),
|
||||
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [0.1], "extra": [1]}),
|
||||
pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "probabilidad": [0.1]}),
|
||||
])
|
||||
def test_an_estimate_is_one_probability_per_member_in_its_columns(estimate):
|
||||
"""Pins down: a member twice, a probability outside 0..1, an extra column or another column order are refused.
|
||||
Fails if a malformed output can be written or stored as risks."""
|
||||
with pytest.raises(EstimateError):
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
|
||||
@@ -1,64 +0,0 @@
|
||||
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with: the
|
||||
hashes of files and tables, and the rule that decides an output is already done.
|
||||
|
||||
Fixtures: none; each test builds its own small table or file.
|
||||
"""
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from models.io.lineage import cohort_reference, file_sha256, matches, registered_name, require_match, table_sha256
|
||||
|
||||
|
||||
def test_a_table_hashes_by_its_rows_not_its_metadata():
|
||||
"""Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash.
|
||||
Fails if metadata such as `built_at` enters the hash, so every rebuild would look new."""
|
||||
table = pa.table({"pac_id": [1, 2]})
|
||||
|
||||
assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"}))
|
||||
assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]}))
|
||||
|
||||
|
||||
def test_files_hash_in_order(tmp_path):
|
||||
"""Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails
|
||||
if a file is skipped or the order stops mattering."""
|
||||
a, b = tmp_path / "a", tmp_path / "b"
|
||||
a.write_bytes(b"one")
|
||||
b.write_bytes(b"two")
|
||||
|
||||
assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a)
|
||||
|
||||
|
||||
def test_an_output_is_done_when_its_lineage_has_every_expected_value():
|
||||
"""Pins down: recorded lineage matches when every expected key has its value, compared as text since files and
|
||||
MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text."""
|
||||
recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"}
|
||||
|
||||
assert matches(recorded, {"armado_id": 7, "n_members": 2})
|
||||
assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"})
|
||||
|
||||
|
||||
def test_a_mismatch_is_refused_with_both_sides():
|
||||
"""Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently."""
|
||||
with pytest.raises(ValueError, match="doesn't belong.*armado_id"):
|
||||
require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet")
|
||||
|
||||
|
||||
def test_models_are_registered_as_domain_and_scenario():
|
||||
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
|
||||
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metadata, expected", [
|
||||
({"url": "u", "producer": "dbt", "build": "4"}, ("dbt", "4")),
|
||||
({"url": "u", "producer": "kit", "armado_id": "2"}, ("kit", "2")),
|
||||
({"url": "u", "producer": "kit build, timeline from dbt view", "armado_id": "1"}, ("kit", "1")),
|
||||
({"url": "u", "armado_id": "3"}, ("kit", "3")),
|
||||
])
|
||||
def test_a_file_is_dbts_only_when_its_producer_says_dbt(metadata, expected):
|
||||
"""Pins down: a cohort file's source is dbt only for `producer: dbt`; any other producer, or none, is a kit build
|
||||
numbered by `armado_id`. Fails if an older kit file with a descriptive producer is read as dbt's and loses its
|
||||
`armado_id`."""
|
||||
reference = cohort_reference(metadata, "f" * 64)
|
||||
|
||||
assert (reference["cohort.source"], reference["cohort.build"]) == expected
|
||||
@@ -1,184 +0,0 @@
|
||||
"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`), the
|
||||
code version every run records (`code_version`), and choosing the version to use (`registry.resolve`).
|
||||
|
||||
Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready`
|
||||
(from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a
|
||||
pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a
|
||||
logged model; `_git` asks git about this repository, to compare with what the run recorded.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from core.governance.enums import Environment
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io import lineage
|
||||
from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
|
||||
class Constant(mlflow.pyfunc.PythonModel):
|
||||
"""Returns `p` for every row."""
|
||||
|
||||
def __init__(self, p: float):
|
||||
self.p = p
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> list[float]:
|
||||
return [self.p] * len(model_input)
|
||||
|
||||
|
||||
def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[TrainingRun, str]:
|
||||
"""A dev run of `cacu/<scenario>` that logs `model` (if any) and is registered; returns the run and
|
||||
its version."""
|
||||
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
|
||||
if model is not None:
|
||||
run.log_model(model)
|
||||
return run, registry.register_run(run.finish(metrics={"auc": 0.7}))
|
||||
|
||||
|
||||
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
|
||||
"""Pins down: a run that logs a model registers `runs:/<run_id>/model`, and loading the version gives
|
||||
back that model, tagged with its `modelo_sha` on the run and on the version.
|
||||
|
||||
Fails if `finish` registers the run instead of its model folder, or the sha isn't tagged.
|
||||
"""
|
||||
run, version = _train(Constant(0.25))
|
||||
|
||||
loaded = mlflow.pyfunc.load_model(registry.resolve("cacu", "tamizaje", version).model_uri)
|
||||
mv = registry.get("cacu", "tamizaje", version)
|
||||
|
||||
assert list(loaded.predict(pd.DataFrame({"x": [1, 2]}))) == [0.25, 0.25]
|
||||
assert mv.source == f"runs:/{run.run_id}/model"
|
||||
assert mv.tags[MODEL_SHA_TAG] == run.modelo_sha
|
||||
assert MlflowClient().get_run(run.run_id).data.tags[MODEL_SHA_TAG] == run.modelo_sha
|
||||
|
||||
|
||||
def test_the_sha_is_the_model_not_the_run(mlflow_tracking):
|
||||
"""Pins down: the same model logged in two runs has the same `modelo_sha`; a different model has
|
||||
another one.
|
||||
|
||||
Fails if `model_sha` starts covering files with ids or dates (`MLmodel`), or stops covering the model.
|
||||
"""
|
||||
first, _ = _train(Constant(0.25))
|
||||
second, _ = _train(Constant(0.25))
|
||||
other, _ = _train(Constant(0.30))
|
||||
|
||||
assert first.modelo_sha == second.modelo_sha != other.modelo_sha
|
||||
|
||||
|
||||
def test_a_run_logs_one_model(mlflow_tracking):
|
||||
"""Pins down: a second `log_model` in the same run is refused.
|
||||
|
||||
Fails if a run could hold two models, so its version wouldn't say which one it is.
|
||||
"""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
run.log_model(Constant(0.25))
|
||||
|
||||
with pytest.raises(RuntimeError, match="already logged"):
|
||||
run.log_model(Constant(0.30))
|
||||
|
||||
|
||||
def test_a_run_without_a_model_still_registers_the_run(mlflow_tracking):
|
||||
"""Pins down: a run that doesn't log a model registers `runs:/<run_id>` with no `modelo_sha`, as
|
||||
before `log_model` existed.
|
||||
|
||||
Fails if `finish` requires a model.
|
||||
"""
|
||||
run, version = _train()
|
||||
|
||||
resolved = registry.resolve("cacu", "tamizaje", version)
|
||||
assert registry.get("cacu", "tamizaje", version).source == f"runs:/{run.run_id}"
|
||||
assert resolved.modelo_sha is None
|
||||
|
||||
|
||||
def test_without_a_version_resolve_takes_production(production_ready):
|
||||
"""Pins down: with no version, `resolve` returns the one holding `produccion`, with that status; with
|
||||
none in production it raises `LookupError`.
|
||||
|
||||
Fails if `resolve` falls back to the latest version instead of failing.
|
||||
"""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
with pytest.raises(LookupError, match="no version in production"):
|
||||
registry.resolve(domain, scenario)
|
||||
|
||||
registry.promote(domain, scenario, version)
|
||||
resolved = registry.resolve(domain, scenario)
|
||||
|
||||
assert (resolved.version, resolved.status) == (version, "produccion")
|
||||
assert resolved.model_uri == f"models:/{domain}-{scenario}/{version}"
|
||||
|
||||
|
||||
def test_an_explicit_version_is_returned_with_its_status(production_ready):
|
||||
"""Pins down: with a version, `resolve` returns it whatever its status (a candidate can be tested),
|
||||
and says which status it has; an unknown version raises `LookupError`.
|
||||
|
||||
Fails if an explicit version is refused for not being in production, or its status is lost.
|
||||
"""
|
||||
domain, scenario, first = production_ready("v1")
|
||||
_, _, second = production_ready("v2")
|
||||
registry.promote(domain, scenario, first)
|
||||
|
||||
assert registry.resolve(domain, scenario, second).status == "candidata"
|
||||
assert registry.resolve(domain, scenario, first).status == "produccion"
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve(domain, scenario, "99")
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
return subprocess.run(["git", "-C", str(Path(lineage.__file__).parent), *args], capture_output=True, text=True,
|
||||
check=True).stdout.strip()
|
||||
|
||||
|
||||
def test_every_run_records_the_commit_of_the_code(mlflow_tracking):
|
||||
"""Pins down: a run is tagged with the git commit of the `models` repository (MLflow's own tag name) and
|
||||
whether tracked files had uncommitted changes; untracked files (notebooks, data) don't count.
|
||||
|
||||
Fails if the tags are dropped or renamed, or the dirty flag counts untracked files.
|
||||
"""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
tags = MlflowClient().get_run(run.run_id).data.tags
|
||||
|
||||
assert tags[GIT_COMMIT_TAG] == _git("rev-parse", "HEAD")
|
||||
assert tags[GIT_DIRTY_TAG] == str(bool(_git("status", "--porcelain", "--untracked-files=no"))).lower()
|
||||
|
||||
|
||||
def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_tracking, monkeypatch):
|
||||
"""Pins down: where git or the repository is missing (a delivered image), the commit is read from
|
||||
`MODELS_GIT_COMMIT`, with no dirty flag; with neither, the run records no commit rather than a guess.
|
||||
|
||||
Fails if a missing repository raises, or a commit is invented.
|
||||
"""
|
||||
def no_git(*args, **kwargs):
|
||||
raise FileNotFoundError("git")
|
||||
|
||||
monkeypatch.setattr(lineage.subprocess, "run", no_git)
|
||||
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
|
||||
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
|
||||
environment=Environment.DEV).run_id).data.tags
|
||||
assert tags[GIT_COMMIT_TAG] == "abc123" and GIT_DIRTY_TAG not in tags
|
||||
|
||||
monkeypatch.delenv(GIT_COMMIT_ENV)
|
||||
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
|
||||
environment=Environment.DEV).run_id).data.tags
|
||||
assert GIT_COMMIT_TAG not in tags
|
||||
|
||||
|
||||
def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking):
|
||||
"""Pins down: a PROD run only logs a model whose class lives in a module; one defined in a notebook or
|
||||
script (`__main__`) is refused, because its code has no commit to trace. A dev run accepts it.
|
||||
|
||||
Fails if the check is dropped, or starts refusing dev runs or module classes.
|
||||
"""
|
||||
InNotebook = type("InNotebook", (Constant,), {"__module__": "__main__"})
|
||||
prod = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD, cohorte_armado_id=1)
|
||||
|
||||
with pytest.raises(ValueError, match="defined in a notebook"):
|
||||
prod.log_model(InNotebook(0.25))
|
||||
prod.log_model(Constant(0.25))
|
||||
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).log_model(InNotebook(0.25))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user