Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c42f544173 | |||
| 305e855a15 | |||
| 76d6b96409 | |||
| 7b2eae2782 | |||
| fc77fd625e | |||
| 55f036b53a | |||
| 572b7561fa | |||
| bd3d6fb199 | |||
| 9ba7bdddb6 | |||
| 11e768893e | |||
| 1b45bc61d7 | |||
| c50c3a081e | |||
| ae2310754f | |||
| a4ddad5c8e | |||
| 55dd971a1f | |||
| a8bbdc88af | |||
| 5d65730b98 | |||
| 71e77f0c7e | |||
| 15ffeb3efe | |||
| 761b5b03bc | |||
| 22d1fda0f3 | |||
| f070d9f037 | |||
| 3853cc5522 | |||
| 9808701c46 | |||
| 0fdab3651c | |||
| 37fb292a4f | |||
| 1f6e2df051 | |||
| 122f71105a | |||
| 27e29804aa | |||
| 34de6e9348 | |||
| 29fa8def2a | |||
| 2d22409e1f | |||
| ec85cae5aa | |||
| b06ff5ce52 | |||
| f08b249eae | |||
| 0489475b86 | |||
| ec36df6a2c | |||
| dd94aba1eb | |||
| 449c67b19d | |||
| d6f7acc1fa | |||
| 5fa931d92d | |||
| bc15cc3e04 | |||
| c8bca59334 | |||
| c11575f656 | |||
| 28ff4605f3 | |||
| 2b855be12d | |||
| 92c5c69c2d | |||
| ee1c307d57 | |||
| e5526b9ec3 | |||
| 86b508cba8 | |||
| 04c8cbafd1 | |||
| 4c5bccb805 |
@@ -9,13 +9,31 @@ WebApi.
|
||||
|
||||
| Módulo | Qué hace |
|
||||
|---|---|
|
||||
| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. |
|
||||
| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. |
|
||||
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
|
||||
| `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 el alias `produccion`. |
|
||||
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
||||
| `__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). |
|
||||
| `cama/seer_survival/` | CaMa's SEER survival pipeline, ported from six scripts into Hamilton DAGs, one per stage (extra `seer-survival`). Settings in `model.toml` (`settings.py`); paths are inputs, never settings. Each stage is a module of nodes plus, where the routine is heavy, a module of plain functions apart (as `tea/eeg/analyze.py`): `depuration.py` + `depuration_stats.py` (01: Theil's U and GVIF redundancy screen and its threshold calibration), `balancing.py` + `balancing_stats.py` and `categorization.py` + `categorization_stats.py` (02: 18-month outcome, MCA undersampling, Bayesian change-point grouping of age and tumor size, categorization proposals), `bootstrap.py` (03: resample indices), `modeling.py` + `lr_selection.py`, `hbn.py`, `natural.py`, `resampling.py` + `replica.py` (04: stepwise LR, hybrid Bayesian network, natural-population LR, bootstrap and proposal replicas), `survival_curves.py` + `survival_models.py`, `fractional_weibull.py` (05: Kaplan-Meier, classic and Kilbas-Saigo Weibull, stacked LR + HBN survival, subgroups) and `risk_factors.py` + `risk_factor_stats.py` (06: four-criteria risk factors). `run.py` writes each stage's files; `pipeline.py` runs them in order, skipping the current ones: `python -m models.cama.seer_survival --data DIR [--solo 05] [--desde 02] [--forzar 02 04] [--todo]`. |
|
||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||
| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
||||
| `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
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
"""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 _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 _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 (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))
|
||||
|
||||
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,41 +0,0 @@
|
||||
import importlib
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
def resolve_repository(domain: str, entity: str) -> Repository:
|
||||
"""`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 ScreeningModel(ABC):
|
||||
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
|
||||
|
||||
Data is read through the same `persistance.<domain>.<entity>_repository`
|
||||
objects WebApi writes with, so anything loaded through the import flow
|
||||
is visible here. `train` may also be given rows fetched by the caller.
|
||||
"""
|
||||
|
||||
domain: ClassVar[str]
|
||||
|
||||
def repository(self, entity: str) -> Repository:
|
||||
return resolve_repository(self.domain, entity)
|
||||
|
||||
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
|
||||
"""Every row of `entity` as plain dicts, read in batches."""
|
||||
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
|
||||
|
||||
@abstractmethod
|
||||
def train(self, data: Any = None) -> None:
|
||||
"""Fit the model, optionally on `data` passed in by the caller."""
|
||||
|
||||
@abstractmethod
|
||||
def predict(self, data: Any) -> Any:
|
||||
"""Score `data` and return predictions."""
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaCuModel(ScreeningModel):
|
||||
"""Scaffold for the CaCu (cervical cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cacu`'s
|
||||
repositories (`paciente_repository`, `citologia_cervical_repository`,
|
||||
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet; this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaCu training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaCu's scenarios and notebooks."""
|
||||
@@ -0,0 +1,41 @@
|
||||
"""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
|
||||
@@ -0,0 +1,215 @@
|
||||
"""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
|
||||
@@ -0,0 +1,13 @@
|
||||
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."""
|
||||
@@ -0,0 +1,27 @@
|
||||
"""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,158 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaMaModel(ScreeningModel):
|
||||
"""Scaffold for the CaMa (breast cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cama`'s
|
||||
repositories (`paciente_repository`, `mastografia_repository`,
|
||||
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet; this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "cama"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaMa training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaMa prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaMa's scenarios and notebooks."""
|
||||
@@ -0,0 +1,443 @@
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import os, json, itertools
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
INPUT_CSV = "./dataframe_recodificado.csv"
|
||||
OUTPUT_CSV = "./dataframe_depurado.csv"
|
||||
OUT_DIR = "./depuracion_resultados_1"
|
||||
|
||||
EXCLUDE = ["Outcome_cat"] # nunca se analiza ni se toca
|
||||
AUTO_EXTRA = ["Age_group", "Tumor_group"] # se incluyen si existen
|
||||
EXTRA_COLS = []
|
||||
PROTEGIDAS = [] # p. ej. ["Estadio_cat"]: nunca se eliminan
|
||||
PREFERIR = ["Tumor_group", "Age_group"] # en un empate/duplicada, gana la que esté aquí (son las discretizaciones propias del proyecto)
|
||||
DROP_RAW_SOURCES = True # también quita la columna cruda de SEER de la variable eliminada (evita que el balanceo la reintroduzca por palabra clave)
|
||||
MAPEO_JSON = "./mapeo_columnas_recodificadas.json"
|
||||
UNKNOWN_LABEL = "Desconocido"
|
||||
|
||||
DUP_U = 0.90 # paso A
|
||||
U_REDUND = 0.80 # paso B
|
||||
GVIF_DROP = 2.24 # paso C: GVIF^(1/2gl) (equivale a VIF 5)
|
||||
MAX_ITER_GVIF = 20
|
||||
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
df_raw = pd.read_csv(INPUT_CSV, dtype=str)
|
||||
cols = [c for c in df_raw.columns if c.endswith("_cat") and c not in EXCLUDE]
|
||||
for c in AUTO_EXTRA + EXTRA_COLS:
|
||||
if c in df_raw.columns and c not in cols and c not in EXCLUDE:
|
||||
cols.append(c)
|
||||
df = df_raw[cols].fillna(UNKNOWN_LABEL)
|
||||
cols = [c for c in cols if df[c].nunique() >= 2]
|
||||
df = df[cols]
|
||||
|
||||
|
||||
def theil_u_matrix(d, columnas):
|
||||
U = pd.DataFrame(np.nan, index=columnas, columns=columnas)
|
||||
H = {}
|
||||
for c in columnas:
|
||||
p = d[c].value_counts(normalize=True).values
|
||||
H[c] = float(-(p * np.log(p)).sum())
|
||||
for a, b in itertools.combinations(columnas, 2):
|
||||
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
|
||||
pxy /= pxy.sum()
|
||||
nz = pxy[pxy > 0]
|
||||
hxy = float(-(nz * np.log(nz)).sum())
|
||||
mi = H[a] + H[b] - hxy
|
||||
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
|
||||
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
|
||||
return U
|
||||
|
||||
|
||||
def design(d, columnas):
|
||||
bloques = {}
|
||||
for c in columnas:
|
||||
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
|
||||
ind = ind.drop(columns=ind.sum().idxmax())
|
||||
ind = ind.loc[:, ind.std() > 0]
|
||||
if ind.shape[1] > 0:
|
||||
bloques[c] = ind
|
||||
X = pd.concat(bloques.values(), axis=1)
|
||||
return X, bloques
|
||||
|
||||
|
||||
def gvif_table(d, columnas):
|
||||
X, bloques = design(d, columnas)
|
||||
R = np.corrcoef(X.values, rowvar=False)
|
||||
pos = {n: i for i, n in enumerate(X.columns)}
|
||||
s, ld = np.linalg.slogdet(R)
|
||||
if not (s > 0 and np.isfinite(ld) and ld > -30):
|
||||
cand = []
|
||||
for c, b in bloques.items():
|
||||
otros = [x for x in X.columns if x not in b.columns]
|
||||
A = np.column_stack([X[otros].values, np.ones(len(X))])
|
||||
for x in b.columns:
|
||||
y = X[x].values
|
||||
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
|
||||
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
|
||||
if r2 >= 0.9999:
|
||||
cand.append((b.shape[1], c)); break
|
||||
return None, sorted(cand)
|
||||
filas = []
|
||||
for c, b in bloques.items():
|
||||
idx = [pos[n] for n in b.columns]
|
||||
resto = [i for i in range(len(pos)) if i not in set(idx)]
|
||||
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
|
||||
s2, l2 = np.linalg.slogdet(R[np.ix_(resto, resto)]) if resto else (1, 0.0)
|
||||
gv = float(np.exp(l1 + l2 - ld))
|
||||
filas.append({"variable": c, "gl": len(idx), "GVIF": gv,
|
||||
"GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
|
||||
return pd.DataFrame(filas).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
|
||||
|
||||
|
||||
import itertools, json, datetime
|
||||
from scipy.cluster.hierarchy import linkage, cophenet, fcluster
|
||||
from scipy.spatial.distance import squareform
|
||||
|
||||
# ===================== PARÁMETROS DE LA CALIBRACIÓN (independientes de los datos) =====================
|
||||
UMBRALES_AUTO = False # True: aplica las sugerencias a DUP_U / U_REDUND / GVIF_DROP / clustering
|
||||
N_MAX_CAL = 300_000 # si hay más filas, se calibra sobre una submuestra reproducible
|
||||
NULL_PERM = 100 # permutaciones para el piso por azar de U
|
||||
K_AZAR = 5 # U_REDUND debe ser >= K_AZAR x (U máximo por azar)
|
||||
U_CONVENCIONAL = 0.80 # valor de respaldo si los datos no permiten calibrar
|
||||
U_GAP_DESDE = 0.70 # se buscan brechas cuyo borde superior sea >= este U
|
||||
U_GAP_MIN_BRECHA = 0.10 # brecha mínima para considerarla "natural"
|
||||
U_RANGO_PLAUSIBLE = (0.60, 0.95) # límites del umbral sugerido
|
||||
VIF_CORTE = 5 # 5 (R2=0.80) o 10 (R2=0.90)
|
||||
R_GRANDE = 0.5 # Cohen (1988): |phi| 0.1 pequeño, 0.3 mediano, 0.5 grande
|
||||
MIN_N_CAT = 30 # categorías con menos pacientes se excluyen del clustering
|
||||
MAX_CAT_CLUSTER = 400 # tope de columnas (categorías) en la matriz del clustering
|
||||
CLUSTER_DIST = "signed" # "signed": d = 1-r | "abs": d = 1-|r|
|
||||
SEMILLA_CAL = 0
|
||||
|
||||
GVIF_GRID = sorted({round(1.5, 2), 2.0, round(float(np.sqrt(VIF_CORTE)), 2), 2.5, round(float(np.sqrt(10)), 2)})
|
||||
CLUSTER_METODO = "average" # se recalcula abajo
|
||||
PAR_R_MIN = R_GRANDE
|
||||
CLUSTER_CORTE = round(1 - R_GRANDE, 2)
|
||||
rng_cal = np.random.default_rng(SEMILLA_CAL)
|
||||
|
||||
REPORTE = {"fecha": datetime.datetime.now().isoformat(timespec="seconds"), "advertencias": [], "parametros": {
|
||||
"NULL_PERM": NULL_PERM, "K_AZAR": K_AZAR, "U_CONVENCIONAL": U_CONVENCIONAL, "U_GAP_DESDE": U_GAP_DESDE,
|
||||
"U_GAP_MIN_BRECHA": U_GAP_MIN_BRECHA, "U_RANGO_PLAUSIBLE": list(U_RANGO_PLAUSIBLE), "VIF_CORTE": VIF_CORTE,
|
||||
"R_GRANDE": R_GRANDE, "MIN_N_CAT": MIN_N_CAT, "SEMILLA": SEMILLA_CAL}}
|
||||
def _aviso(msg):
|
||||
REPORTE["advertencias"].append(msg)
|
||||
|
||||
# ===================== preparación y diagnóstico de los datos =====================
|
||||
if len(cols) < 2:
|
||||
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
|
||||
df_cal = df if len(df) <= N_MAX_CAL else df.sample(N_MAX_CAL, random_state=SEMILLA_CAL)
|
||||
CODES = {c: pd.factorize(df_cal[c])[0] for c in cols}
|
||||
KCAT = {c: int(df_cal[c].nunique()) for c in cols}
|
||||
n_cal = len(df_cal)
|
||||
celdas_med = float(np.median([n_cal / (KCAT[a] * KCAT[b]) for a, b in itertools.combinations(cols, 2)]))
|
||||
if n_cal < 1000: _aviso(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
|
||||
if celdas_med < 5: _aviso(f"tablas de contingencia dispersas (mediana {celdas_med:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
|
||||
if len(cols) < 4: _aviso("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
|
||||
if max(KCAT.values()) > 30: _aviso(f"variable con {max(KCAT.values())} categorías: considera agruparlas antes de depurar.")
|
||||
REPORTE["datos"] = {"n": int(len(df)), "n_calibracion": int(n_cal), "n_variables": len(cols), "categorias_por_variable": KCAT,
|
||||
"pacientes_por_celda_mediana": celdas_med}
|
||||
|
||||
# ===================== 1. U de Theil: pares, exactitud y piso por azar =====================
|
||||
def _h(p):
|
||||
p = p[p > 0]; return float(-(p * np.log(p)).sum())
|
||||
def info_par(cx, cy, kx, ky):
|
||||
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
|
||||
n = j.sum(); px = j.sum(1) / n; py = j.sum(0) / n
|
||||
hxy = _h((j / n).ravel()); hx = _h(px); hy = _h(py)
|
||||
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
|
||||
base_x=px.max(), base_y=py.max())
|
||||
|
||||
filas, techo = [], []
|
||||
for a, b in itertools.combinations(cols, 2):
|
||||
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
|
||||
mi_null = np.array([info_par(CODES[a], rng_cal.permutation(CODES[b]), KCAT[a], KCAT[b])["mi"] for _ in range(NULL_PERM)])
|
||||
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]), (b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
|
||||
u = ip["mi"] / hx if hx > 0 else np.nan
|
||||
u_null = mi_null.max() / hx if hx > 0 else np.nan
|
||||
filas.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null, "exactitud_X_desde_Y": acc, "exactitud_base_X": base})
|
||||
techo.append(u_null)
|
||||
PARES_U = pd.DataFrame(filas).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
|
||||
PARES_U["brecha_al_siguiente"] = PARES_U["U(X|Y)"] - PARES_U["U(X|Y)"].shift(-1)
|
||||
techo_azar = float(np.nanmax(techo))
|
||||
PARES_U.to_csv(f"{OUT_DIR}/calibracion_U_pares.csv", index=False)
|
||||
|
||||
# ---- regla de sugerencia para U_REDUND (piso por azar + brecha natural + respaldo convencional)
|
||||
def sugerir_U(pares_u, techo_azar, gap_desde=None, gap_min=None):
|
||||
gap_desde = U_GAP_DESDE if gap_desde is None else gap_desde
|
||||
gap_min = U_GAP_MIN_BRECHA if gap_min is None else gap_min
|
||||
v = np.sort(pares_u["U(X|Y)"].dropna().round(4).unique())[::-1]
|
||||
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
|
||||
mejor = None
|
||||
for i in range(len(v) - 1):
|
||||
if v[i] >= gap_desde and (mejor is None or v[i] - v[i + 1] > mejor[0]):
|
||||
mejor = (v[i] - v[i + 1], v[i], v[i + 1])
|
||||
if mejor is not None and mejor[0] >= gap_min:
|
||||
mid = float(np.clip((mejor[1] + mejor[2]) / 2, *U_RANGO_PLAUSIBLE))
|
||||
out.update(metodo="brecha natural", U=mid, brecha=round(float(mejor[0]), 3), borde_sup=round(float(mejor[1]), 3),
|
||||
borde_inf=round(float(mejor[2]), 3), confianza="alta")
|
||||
else:
|
||||
out["U"] = U_CONVENCIONAL
|
||||
out["motivo"] = ("no hay pares con U >= %.2f" % gap_desde) if mejor is None else ("la mayor brecha (%.3f) < %.2f" % (mejor[0], gap_min))
|
||||
piso = K_AZAR * techo_azar
|
||||
if out["U"] < piso:
|
||||
out["U"] = float(min(piso, 0.99)); out["metodo"] += " + piso por azar"; out["confianza"] = "revisar"
|
||||
out["U"] = round(float(out["U"]), 2)
|
||||
return out
|
||||
SUG_U = sugerir_U(PARES_U, techo_azar)
|
||||
|
||||
|
||||
|
||||
# ===================== 2. Sensibilidad: ¿qué variables se eliminan al mover cada umbral, y con qué regla? =====================
|
||||
_pct_unk = {c: float((df_cal[c] == UNKNOWN_LABEL).mean()) for c in cols}
|
||||
_ncat = {c: int(df_cal[c].nunique()) for c in cols}
|
||||
_orden = {c: i for i, c in enumerate(cols)}
|
||||
def _perdedora(a, b):
|
||||
if a in PROTEGIDAS and b in PROTEGIDAS: return None
|
||||
if a in PROTEGIDAS: return b, a
|
||||
if b in PROTEGIDAS: return a, b
|
||||
if a in PREFERIR and b not in PREFERIR: return b, a
|
||||
if b in PREFERIR and a not in PREFERIR: return a, b
|
||||
k = lambda c: (_pct_unk[c], _ncat[c], _orden[c])
|
||||
return (a, b) if k(a) > k(b) else (b, a)
|
||||
|
||||
_cacheU, _cacheG = {}, {}
|
||||
def _Umat(cols_t):
|
||||
if cols_t not in _cacheU:
|
||||
M_ = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
|
||||
for a, b in itertools.combinations(cols_t, 2):
|
||||
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
|
||||
M_.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
|
||||
M_.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
|
||||
_cacheU[cols_t] = M_
|
||||
return _cacheU[cols_t]
|
||||
def _Gtab(cols_t):
|
||||
if cols_t not in _cacheG: _cacheG[cols_t] = gvif_table(df_cal, list(cols_t))
|
||||
return _cacheG[cols_t]
|
||||
|
||||
_chk = theil_u_matrix(df_cal, cols); _fast = _Umat(tuple(cols))
|
||||
assert np.allclose(_chk.values.astype(float), _fast.loc[cols, cols].values.astype(float), equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
|
||||
|
||||
def depurar_con(dup_u, u_redund, gvif_drop):
|
||||
# Reproduce A, B y C con otros umbrales. Devuelve ({variable: paso}, activas).
|
||||
activas, out = list(cols), {}
|
||||
U = _Umat(tuple(activas)) # A
|
||||
for a, b in itertools.combinations(list(activas), 2):
|
||||
if a not in activas or b not in activas: continue
|
||||
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
|
||||
r = _perdedora(a, b)
|
||||
if r: activas.remove(r[0]); out[r[0]] = "A"
|
||||
U = _Umat(tuple(activas)); cand = [] # B
|
||||
for x in activas:
|
||||
for y in activas:
|
||||
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund: cand.append((U.loc[x, y], x, y))
|
||||
for u, x, y in sorted(cand, reverse=True):
|
||||
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
|
||||
activas.remove(x); out[x] = "B"
|
||||
for _ in range(MAX_ITER_GVIF): # C
|
||||
if len(activas) < 3: break
|
||||
tabla, exactas = _Gtab(tuple(activas))
|
||||
if tabla is None:
|
||||
ex = [c for _, c in exactas if c not in PROTEGIDAS]
|
||||
if not ex: break
|
||||
activas.remove(ex[0]); out[ex[0]] = "C"; continue
|
||||
cd = tabla[(tabla["GVIF_ajustado"] >= gvif_drop) & (~tabla["variable"].isin(PROTEGIDAS))]
|
||||
if cd.empty: break
|
||||
v_ = cd.iloc[0]["variable"]; activas.remove(v_); out[v_] = "C"
|
||||
return out, activas
|
||||
|
||||
def _etq(d): return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
|
||||
|
||||
base_out, base_act = depurar_con(DUP_U, U_REDUND, GVIF_DROP)
|
||||
|
||||
|
||||
|
||||
# decisión del umbral sugerido y su estabilidad
|
||||
dup_sug = round(min(max(0.90, SUG_U["U"] + 0.05), 0.99), 2)
|
||||
out_sug, _ = depurar_con(dup_sug, SUG_U["U"], GVIF_DROP)
|
||||
mismo = set(out_sug) == set(base_out)
|
||||
SUG_U["misma_decision_que_config"] = bool(mismo)
|
||||
if not mismo and SUG_U["confianza"] == "alta": SUG_U["confianza"] = "revisar"
|
||||
if not mismo: _aviso("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
|
||||
|
||||
|
||||
# ---- D) Barrido de los parámetros de la REGLA de brecha: U_GAP_DESDE y U_GAP_MIN_BRECHA son CONVENCIONES (no salen de los datos).
|
||||
# Se verifica si cambiarlos modifica el umbral sugerido o las variables que se eliminan.
|
||||
GAP_DESDE_GRID = [0.50, 0.60, 0.70, 0.80, 0.90]
|
||||
GAP_MIN_GRID = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30]
|
||||
_filas_gap = []
|
||||
for gd in GAP_DESDE_GRID:
|
||||
for gm in GAP_MIN_GRID:
|
||||
s_ = sugerir_U(PARES_U, techo_azar, gd, gm)
|
||||
dup_s = round(min(max(0.90, s_["U"] + 0.05), 0.99), 2)
|
||||
o_, _ = depurar_con(dup_s, s_["U"], GVIF_DROP)
|
||||
_filas_gap.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": s_["U"], "método": s_["metodo"],
|
||||
"misma decisión": set(o_) == set(base_out), "elimina [regla]": _etq(o_)})
|
||||
SENS_GAP = pd.DataFrame(_filas_gap)
|
||||
_frac = float(SENS_GAP["misma decisión"].mean())
|
||||
_umin, _umax = float(SENS_GAP["U_REDUND sugerido"].min()), float(SENS_GAP["U_REDUND sugerido"].max())
|
||||
_dist = SENS_GAP[~SENS_GAP["misma decisión"]]
|
||||
if len(_dist):
|
||||
_aviso(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(_dist)} de {len(SENS_GAP)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
|
||||
REPORTE["sensibilidad_regla_brecha"] = {"grilla_U_GAP_DESDE": GAP_DESDE_GRID, "grilla_U_GAP_MIN_BRECHA": GAP_MIN_GRID,
|
||||
"proporcion_misma_decision": _frac, "U_sugerido_min": _umin, "U_sugerido_max": _umax}
|
||||
|
||||
|
||||
# ===================== 3. GVIF: equivalencia con VIF y R^2, y margen =====================
|
||||
GVIF_DROP_SUG = round(float(np.sqrt(VIF_CORTE)), 2)
|
||||
eq = pd.DataFrame({"GVIF ajustado (umbral)": GVIF_GRID})
|
||||
eq["VIF = GVIF_aj^2"] = eq["GVIF ajustado (umbral)"] ** 2
|
||||
eq["R^2 de la variable con las demás"] = 1 - 1 / eq["VIF = GVIF_aj^2"]
|
||||
tab_k, _ = _Gtab(tuple(base_act))
|
||||
margen_g = None
|
||||
if tab_k is not None and len(tab_k):
|
||||
tab_k = tab_k.copy(); tab_k["margen_al_umbral"] = GVIF_DROP - tab_k["GVIF_ajustado"]
|
||||
margen_g = float(tab_k["margen_al_umbral"].min())
|
||||
if margen_g < 0.15: _aviso("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
|
||||
|
||||
# ===================== 4. Clustering: método de enlace (cofenética) y corte (Cohen) =====================
|
||||
def _cat_matrix(d, columnas, min_n):
|
||||
X = pd.get_dummies(d[columnas], prefix_sep="=", dtype=np.float32); s = X.sum()
|
||||
X = X.loc[:, (s >= min_n) & (s <= len(X) - min_n)]
|
||||
if X.shape[1] > MAX_CAT_CLUSTER:
|
||||
X = X[X.sum().sort_values(ascending=False).index[:MAX_CAT_CLUSTER]]
|
||||
_aviso(f"demasiadas categorías para el clustering: se usan las {MAX_CAT_CLUSTER} más frecuentes.")
|
||||
return X
|
||||
min_n_eff = MIN_N_CAT
|
||||
_X = _cat_matrix(df_cal, cols, min_n_eff)
|
||||
if _X.shape[1] < 6:
|
||||
min_n_eff = max(5, int(0.005 * n_cal)); _X = _cat_matrix(df_cal, cols, min_n_eff)
|
||||
_aviso(f"muy pocas categorías con >= {MIN_N_CAT} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
|
||||
CLUSTER_OK = _X.shape[1] >= 4
|
||||
metodo_sug, coph, CLUSTER_CORTE_SIL, tab_corte = CLUSTER_METODO, {}, None, pd.DataFrame()
|
||||
if not CLUSTER_OK:
|
||||
_aviso("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
|
||||
else:
|
||||
_nom = list(_X.columns); _var = np.array([c.split("=", 1)[0] for c in _nom])
|
||||
_V = _X.values.astype(np.float32); _V -= _V.mean(0); _cov = _V.T @ _V; _sd = np.sqrt(np.diag(_cov)); _R = (_cov / np.outer(_sd, _sd)).astype(float)
|
||||
_D = 1 - _R if CLUSTER_DIST == "signed" else 1 - np.abs(_R)
|
||||
_D = np.clip((_D + _D.T) / 2, 0, None); np.fill_diagonal(_D, 0); _cond = squareform(_D, checks=False)
|
||||
for m_ in ["single", "complete", "average", "weighted"]:
|
||||
coph[m_] = float(cophenet(linkage(_cond, method=m_), _cond)[0])
|
||||
metodo_sug = max(coph, key=coph.get)
|
||||
try:
|
||||
from sklearn.metrics import silhouette_score; _hay_sil = True
|
||||
except Exception:
|
||||
_hay_sil = False
|
||||
Zc = linkage(_cond, method=metodo_sug); filas = []
|
||||
for t_ in np.round(np.arange(0.30, 1.01, 0.05), 2):
|
||||
lab = fcluster(Zc, t=float(t_), criterion="distance"); ng = len(set(lab))
|
||||
multi = sum(1 for g in set(lab) if len(set(_var[lab == g])) >= 2)
|
||||
sil = float(silhouette_score(_D, lab, metric="precomputed")) if _hay_sil and 2 <= ng <= len(lab) - 1 else np.nan
|
||||
filas.append({"corte (dist.)": t_, "r medio exigido": round(1 - t_, 2), "n_grupos": ng, "grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
|
||||
tab_corte = pd.DataFrame(filas)
|
||||
if tab_corte["silueta"].notna().any(): CLUSTER_CORTE_SIL = float(tab_corte.loc[tab_corte["silueta"].idxmax(), "corte (dist.)"])
|
||||
tab_corte.to_csv(f"{OUT_DIR}/calibracion_clustering_corte.csv", index=False)
|
||||
|
||||
# ===================== 5. Resumen, decisión y reporte JSON =====================
|
||||
resumen = pd.DataFrame([
|
||||
{"parámetro": "U_REDUND", "configurado": U_REDUND, "sugerido": SUG_U["U"], "criterio": SUG_U["metodo"], "confianza": SUG_U["confianza"]},
|
||||
{"parámetro": "DUP_U", "configurado": DUP_U, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)", "confianza": SUG_U["confianza"]},
|
||||
{"parámetro": "GVIF_DROP", "configurado": GVIF_DROP, "sugerido": GVIF_DROP_SUG, "criterio": f"sqrt(VIF {VIF_CORTE}) (R2={1-1/VIF_CORTE:.2f})",
|
||||
"confianza": "alta" if (margen_g is None or margen_g >= 0.15) else "revisar"},
|
||||
{"parámetro": "CLUSTER_METODO", "configurado": CLUSTER_METODO, "sugerido": metodo_sug, "criterio": "máx. correlación cofenética", "confianza": "alta" if CLUSTER_OK else "revisar"},
|
||||
{"parámetro": "CLUSTER_CORTE", "configurado": CLUSTER_CORTE, "sugerido": round(1 - R_GRANDE, 2), "criterio": f"Cohen: r medio >= {R_GRANDE}", "confianza": "alta"},
|
||||
{"parámetro": "PAR_R_MIN", "configurado": PAR_R_MIN, "sugerido": R_GRANDE, "criterio": "Cohen: efecto grande", "confianza": "alta"}])
|
||||
|
||||
if UMBRALES_AUTO:
|
||||
U_REDUND, DUP_U, GVIF_DROP, CLUSTER_METODO = SUG_U["U"], dup_sug, GVIF_DROP_SUG, metodo_sug
|
||||
CLUSTER_CORTE = round(1 - R_GRANDE, 2); PAR_R_MIN = R_GRANDE
|
||||
|
||||
def _jsonable(o):
|
||||
if isinstance(o, (np.floating,)): return float(o)
|
||||
if isinstance(o, (np.integer,)): return int(o)
|
||||
if isinstance(o, (set, tuple)): return list(o)
|
||||
return str(o)
|
||||
REPORTE.update({"piso_azar_U": techo_azar, "sugerencia_U": SUG_U, "resumen": resumen.to_dict(orient="records"),
|
||||
"umbrales_en_uso": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP, "CLUSTER_METODO": CLUSTER_METODO,
|
||||
"CLUSTER_CORTE": CLUSTER_CORTE, "PAR_R_MIN": PAR_R_MIN, "AUTO": bool(UMBRALES_AUTO)},
|
||||
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
|
||||
with open(f"{OUT_DIR}/calibracion_umbrales.json", "w", encoding="utf-8") as fh:
|
||||
json.dump(REPORTE, fh, ensure_ascii=False, indent=2, default=_jsonable)
|
||||
|
||||
|
||||
eliminadas = [] # (variable, paso, motivo, a_favor_de)
|
||||
activas = list(cols)
|
||||
pct_unk = {c: float((df[c] == UNKNOWN_LABEL).mean()) for c in cols}
|
||||
ncat = {c: int(df[c].nunique()) for c in cols}
|
||||
orden = {c: i for i, c in enumerate(cols)}
|
||||
|
||||
|
||||
def quitar(var, paso, motivo, favor):
|
||||
activas.remove(var)
|
||||
eliminadas.append({"variable": var, "paso": paso, "motivo": motivo, "a_favor_de": favor})
|
||||
|
||||
|
||||
def elegir_perdedora(a, b):
|
||||
if a in PROTEGIDAS and b in PROTEGIDAS: return None
|
||||
if a in PROTEGIDAS: return b, a
|
||||
if b in PROTEGIDAS: return a, b
|
||||
if a in PREFERIR and b not in PREFERIR: return b, a
|
||||
if b in PREFERIR and a not in PREFERIR: return a, b
|
||||
clave = lambda c: (pct_unk[c], ncat[c], orden[c])
|
||||
return (a, b) if clave(a) > clave(b) else (b, a)
|
||||
|
||||
|
||||
# ---------------- PASO A: duplicadas ----------------
|
||||
U = theil_u_matrix(df, activas)
|
||||
for a, b in itertools.combinations(list(activas), 2):
|
||||
if a not in activas or b not in activas: continue
|
||||
if U.loc[a, b] >= DUP_U and U.loc[b, a] >= DUP_U:
|
||||
r = elegir_perdedora(a, b)
|
||||
if r:
|
||||
quitar(r[0], "A duplicada", f"U({a}|{b})={U.loc[a,b]:.2f}, U({b}|{a})={U.loc[b,a]:.2f}", r[1])
|
||||
|
||||
# ---------------- PASO B: derivadas ----------------
|
||||
U = theil_u_matrix(df, activas)
|
||||
cand = []
|
||||
for x in activas:
|
||||
for y in activas:
|
||||
if x != y and U.loc[x, y] >= U_REDUND and U.loc[y, x] < U_REDUND:
|
||||
cand.append((U.loc[x, y], x, y))
|
||||
for u, x, y in sorted(cand, reverse=True):
|
||||
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
|
||||
quitar(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y,x]:.2f}", y)
|
||||
|
||||
for it in range(MAX_ITER_GVIF):
|
||||
if len(activas) < 3: break
|
||||
tabla, exactas = gvif_table(df, activas)
|
||||
if tabla is None:
|
||||
exactas = [c for _, c in exactas if c not in PROTEGIDAS]
|
||||
if not exactas: break
|
||||
quitar(exactas[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
|
||||
continue
|
||||
cand = tabla[(tabla["GVIF_ajustado"] >= GVIF_DROP) & (~tabla["variable"].isin(PROTEGIDAS))]
|
||||
if cand.empty: break
|
||||
v = cand.iloc[0]
|
||||
quitar(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {GVIF_DROP}", "(el resto)")
|
||||
|
||||
conservadas = list(activas)
|
||||
rep = pd.DataFrame(eliminadas, columns=["variable", "paso", "motivo", "a_favor_de"])
|
||||
|
||||
|
||||
# ---------------- Verificación final ----------------
|
||||
tabla, exactas = gvif_table(df, conservadas)
|
||||
|
||||
U_fin = theil_u_matrix(df, conservadas)
|
||||
|
||||
|
||||
# ---------------- Guardar ----------------
|
||||
a_quitar = [c for c in rep["variable"]]
|
||||
crudas = []
|
||||
if DROP_RAW_SOURCES and os.path.exists(MAPEO_JSON):
|
||||
with open(MAPEO_JSON, encoding="utf-8") as f:
|
||||
_map = json.load(f)
|
||||
crudas = [_map[v] for v in a_quitar if v in _map and _map[v] in df_raw.columns]
|
||||
out = df_raw.drop(columns=a_quitar + crudas)
|
||||
out.to_csv(OUTPUT_CSV, index=False)
|
||||
rep.to_csv(f"{OUT_DIR}/variables_eliminadas.csv", index=False)
|
||||
with open(f"{OUT_DIR}/variables_conservadas.json", "w", encoding="utf-8") as f:
|
||||
json.dump({"entrada": INPUT_CSV, "conservadas": conservadas, "eliminadas": a_quitar, "crudas_eliminadas": crudas,
|
||||
"umbrales": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP}},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
RANDOM_STATE = 42
|
||||
rng = np.random.default_rng(RANDOM_STATE)
|
||||
|
||||
CSV_PATH = "./dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
|
||||
|
||||
df = pd.read_csv(CSV_PATH, dtype=str)
|
||||
n = len(df)
|
||||
|
||||
|
||||
N_BOOTSTRAP = 200
|
||||
|
||||
bootstrap_indices = np.empty((N_BOOTSTRAP, n), dtype=np.int64)
|
||||
for b in range(N_BOOTSTRAP):
|
||||
bootstrap_indices[b] = rng.integers(0, n, size=n)
|
||||
|
||||
|
||||
import json
|
||||
|
||||
np.save("./bootstrap_indices.npy", bootstrap_indices)
|
||||
|
||||
metadata = {
|
||||
"source_csv": CSV_PATH,
|
||||
"n_filas": int(n),
|
||||
"n_bootstrap": int(N_BOOTSTRAP),
|
||||
"random_state": int(RANDOM_STATE),
|
||||
}
|
||||
with open("./bootstrap_metadata.json", "w") as f:
|
||||
json.dump(metadata, f, indent=2)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,828 @@
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import os
|
||||
os.environ.setdefault("TQDM_DISABLE", "1")
|
||||
import sys, subprocess, time, re, warnings
|
||||
import numpy as np, pandas as pd
|
||||
warnings.filterwarnings("ignore")
|
||||
try:
|
||||
from tqdm.auto import tqdm
|
||||
except ImportError:
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "tqdm"]); from tqdm.auto import tqdm
|
||||
|
||||
INPUT_CSV = "./dataframe_depurado.csv" # salida de 03 (cohorte completa; debe traer meses de seguimiento y estado vital)
|
||||
EDAD_MODO = "categorizada" # cómo entra la edad a la LR: "categorizada" | "continua" (lineal) | "continua_cuadratica". La edad numérica es el punto medio del grupo de 5 años de SEER.
|
||||
# (la HBN solo usa variables discretas: con la edad continua, la HBN no incluye la edad)
|
||||
INCLUIR_EDAD = True # agrega la edad agrupada (Edad_cat) a las covariables si no hay ya una columna de edad categórica
|
||||
CORTES_EDAD = [45, 60, 75] # cortes de la edad agrupada
|
||||
HBN_PADRES_FIJOS = ["Estadio", "Tipo_histologico", "Tratamiento_quirurgico", "Quimioterapia", "Radioterapia"] # padres del desenlace en la HBN ya aprendida en 06 (se buscan por palabra clave entre las covariables); None = aprenderlos aquí (BDeu)
|
||||
HBN_EDAD_PADRE = True # True: agrega la edad agrupada como padre del desenlace en la HBN (decisión de experto / conocimiento previo; el algoritmo de 06 no la eligió). False: solo los padres de HBN_PADRES_FIJOS
|
||||
HBN_PADRES = "fijos" # "fijos": los padres de la HBN se aprenden una vez y se mantienen en el bootstrap (IC más estable) | "reaprender": se buscan de nuevo en cada réplica
|
||||
COVARIABLES = None # None = todas las columnas que terminan en "_cat" (menos el desenlace); o una lista explícita de columnas
|
||||
HORIZONTES = [6, 12, 18] # meses en los que se muestran los puntos de LR y HBN
|
||||
CENSURA_MODELOS = "riesgo" # "riesgo": un modelo por intervalo (0-6, 6-12, 12-18) que usa todo el seguimiento | "ipcw": pondera | "excluir": descarta las vivas con seguimiento < h (definición del proyecto)
|
||||
COMBINAR = True # un solo indicador LR+HBN (combinación por intervalo con pesos de apilamiento fuera de muestra); solo con CENSURA_MODELOS = "riesgo"
|
||||
MOSTRAR_INDIVIDUALES = False # además del combinado, dibuja LR y HBN por separado
|
||||
STACK_FOLDS = 5 # pliegues de la validación cruzada que decide los pesos
|
||||
STACK_SHRINK = 20 # contracción hacia 50/50 con pocas muertes: lambda = STACK_SHRINK / (STACK_SHRINK + muertes del intervalo)
|
||||
DIAGNOSTICO = True # imprime los puntos con los tres tratamientos de la censura (sin bootstrap) junto a Kaplan-Meier
|
||||
B_BOOT = 100 # réplicas bootstrap para el IC de LR y HBN (200 = más fino, más lento)
|
||||
SEMILLA = 42
|
||||
HBN_ESS = 1000 # tamaño de muestra equivalente del prior BDeu
|
||||
HBN_MAX_PADRES = 5 # máximo de padres del desenlace en la HBN
|
||||
K_IDENT = "clasico" # k fijo del Weibull fraccional: "clasico" = k del Weibull clásico | o un número
|
||||
CURVAS = "ajustada" # "ajustada": KM y Weibull fraccional estandarizados por las mismas covariables que LR/HBN (Cox) | "cruda": KM y Weibull sin ajustar
|
||||
PASO_AJUSTE = 3 # meses por intervalo de la curva ajustada (más corto = más fina y más lenta)
|
||||
MOSTRAR_KM_CRUDO = True # dibuja además, en gris fino, el KM sin ajustar como referencia
|
||||
YLIM_PRINCIPAL = None # p. ej. (0.94, 1.0) para hacer zoom en el eje y de la figura principal; None = automático
|
||||
INSET_ZOOM = False # recuadro con zoom a los primeros INSET_MESES meses (donde están los puntos de LR y HBN)
|
||||
INSET_MESES = 18 # tope del panel de zoom (último horizonte)
|
||||
TOPE_MESES = 24 # el análisis de las curvas llega solo hasta este mes: el seguimiento se trunca ahí (muertes posteriores y seguimiento restante cuentan como vivas/censuradas en TOPE_MESES). None = sin tope
|
||||
MESES_MAX = TOPE_MESES or 60 # hasta dónde se dibuja el eje de tiempo
|
||||
SUF = "" if EDAD_MODO == "categorizada" else f"_edad_{EDAD_MODO}" # sufijo de los archivos de salida para no sobrescribir
|
||||
TAG = "" if EDAD_MODO == "categorizada" else f" [edad {EDAD_MODO.replace('_', ' ')}]"
|
||||
SALIDA_PNG = f"./curva_supervivencia_KM_KS_LR_HBN{SUF}.png"
|
||||
SALIDA_CSV = f"./curva_supervivencia_puntos_LR_HBN{SUF}.csv"
|
||||
|
||||
|
||||
df = pd.read_csv(INPUT_CSV, dtype=str)
|
||||
|
||||
def find_col(df, keywords, exclude=()):
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords) and not any(e in d for e in exclude):
|
||||
return col
|
||||
return None
|
||||
|
||||
COL_MESES = find_col(df, ["survival months"])
|
||||
COL_VITAL = find_col(df, ["vital status"])
|
||||
assert COL_MESES and COL_VITAL, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
|
||||
df["meses"] = pd.to_numeric(df[COL_MESES], errors="coerce")
|
||||
df["evento"] = df[COL_VITAL].astype(str).str.lower().str.contains("dead")
|
||||
df = df[df["meses"].notna()].reset_index(drop=True)
|
||||
df["meses_int"] = df["meses"].astype(int)
|
||||
if TOPE_MESES: # truncar el seguimiento en TOPE_MESES: solo cuentan las muertes ocurridas antes del tope
|
||||
df["evento"] = df["evento"] & (df["meses_int"] < TOPE_MESES)
|
||||
df["meses_int"] = np.minimum(df["meses_int"], TOPE_MESES)
|
||||
|
||||
def _edad(v):
|
||||
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
|
||||
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
|
||||
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
|
||||
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
|
||||
_hay_edad_cat = any(re.search(r"(^|_)age(_|$)|edad", c.lower()) for c in df.columns if c.endswith("_cat")) # (no confundir con "Stage")
|
||||
if INCLUIR_EDAD and not _hay_edad_cat:
|
||||
if df["_edad"].notna().mean() > 0.5:
|
||||
_b = [-np.inf] + list(CORTES_EDAD) + [np.inf]
|
||||
_l = [f"<{CORTES_EDAD[0]}"] + [f"{a}-{b-1}" for a, b in zip(CORTES_EDAD[:-1], CORTES_EDAD[1:])] + [f"≥{CORTES_EDAD[-1]}"]
|
||||
df["Edad_cat"] = pd.cut(df["_edad"], _b, right=False, labels=_l).astype(object)
|
||||
if COVARIABLES is None:
|
||||
COVARIABLES = [c for c in df.columns if c.endswith("_cat") and "outcome" not in c.lower()]
|
||||
elif INCLUIR_EDAD and "Edad_cat" in df.columns and "Edad_cat" not in COVARIABLES:
|
||||
COVARIABLES = list(COVARIABLES) + ["Edad_cat"]
|
||||
def _edad_media(v):
|
||||
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
|
||||
if not n_: return np.nan
|
||||
return n_[0] + 2.5 if "+" in str(v) else float(np.mean(n_[:2]))
|
||||
_ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
|
||||
df["_edad_z"] = ((_ed - _ed.mean()) / _ed.std()).fillna(0.0); df["_edad_cuad"] = df["_edad_z"] ** 2
|
||||
COLS_NUM = []
|
||||
if EDAD_MODO != "categorizada":
|
||||
assert _ed.notna().mean() > 0.5, "EDAD_MODO continua: no se pudo leer la edad numérica de la columna de edad."
|
||||
COVARIABLES = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())] # la edad categórica sale de las covariables
|
||||
COLS_NUM = ["_edad_z"] + (["_edad_cuad"] if EDAD_MODO == "continua_cuadratica" else [])
|
||||
def construir_X_dum():
|
||||
M_ = pd.get_dummies(df[COVARIABLES], drop_first=True).values.astype(np.float32) # referencia = primera categoría
|
||||
return np.column_stack([M_, df[COLS_NUM].values.astype(np.float32)]) if COLS_NUM else M_
|
||||
assert COVARIABLES, "No hay covariables: define COVARIABLES con los nombres de columna."
|
||||
for c in COVARIABLES:
|
||||
df[c] = df[c].fillna("NA").astype(str).str.strip()
|
||||
|
||||
|
||||
import sys, subprocess, numpy as np
|
||||
try:
|
||||
import mpmath as mp
|
||||
except ImportError: # el kernel de Jupyter no lo trae: se instala solo
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
|
||||
import mpmath as mp
|
||||
from functools import lru_cache
|
||||
from scipy.special import gammaln
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _coefs(rho, m, l, N, dps):
|
||||
mp.mp.dps = dps
|
||||
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
|
||||
c = [mp.mpf(1)]
|
||||
for i in range(N - 1):
|
||||
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
|
||||
return tuple(c)
|
||||
|
||||
def _log_terms(az, rho, m, l, N):
|
||||
i = np.arange(N - 1)
|
||||
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
|
||||
n = np.arange(N)
|
||||
with np.errstate(divide="ignore"):
|
||||
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
|
||||
return lt
|
||||
|
||||
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
|
||||
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
|
||||
out = np.full(z.shape, np.nan)
|
||||
az = np.abs(z)
|
||||
N = 400
|
||||
lt = _log_terms(az, rho, m, l, N)
|
||||
lmax, llast = lt.max(axis=1), lt[:, -1]
|
||||
zero = az == 0
|
||||
out[zero] = 1.0
|
||||
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
|
||||
if okf.any():
|
||||
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
|
||||
terms[:, 0] = 1.0
|
||||
out[okf] = terms.sum(axis=1)
|
||||
rest = np.where(~zero & ~okf)[0]
|
||||
if rest.size:
|
||||
with np.errstate(over="ignore"):
|
||||
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
|
||||
est = np.maximum(est, lmax[rest])
|
||||
use = rest[est <= logmax_cap]
|
||||
if use.size:
|
||||
est_u = est[est <= logmax_cap]
|
||||
dps = 30 + int(est_u.max() / 2.3) + 10
|
||||
zmax = float(az[use].max())
|
||||
with np.errstate(over="ignore"):
|
||||
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
|
||||
N2 = max(N2, 60)
|
||||
while True:
|
||||
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
|
||||
mp.mp.dps = dps
|
||||
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
|
||||
if last < tol or N2 >= nmax:
|
||||
break
|
||||
N2 *= 2
|
||||
if last < tol:
|
||||
cr = list(c)[::-1]
|
||||
for j in use:
|
||||
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
|
||||
return out
|
||||
|
||||
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
|
||||
tau1 = lam if tau1 is None else tau1
|
||||
tau2 = lam if tau2 is None else tau2
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
s = k + alpha - 2
|
||||
if k + alpha <= 1 or s + beta <= 0:
|
||||
return np.full_like(t, np.nan)
|
||||
m = s/beta + 1; l = s/beta
|
||||
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
|
||||
z = np.where(t > 0, z, 0.0)
|
||||
res = np.ones_like(t)
|
||||
pos = t > 0
|
||||
if pos.any():
|
||||
res[pos] = kilbas_saigo(z[pos], beta, m, l)
|
||||
return np.clip(res, 0.0, 1.0)
|
||||
|
||||
|
||||
def S_weibull(t, k, lam):
|
||||
t = np.asarray(t, float)
|
||||
return np.exp(-(t/lam)**k)
|
||||
|
||||
|
||||
import time
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize
|
||||
|
||||
def tabla_eventos(meses, evento):
|
||||
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
|
||||
T = int(meses.max()) + 2
|
||||
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
|
||||
return d, c
|
||||
|
||||
def _nll_from_S(Sfun, d, c):
|
||||
T = len(d)
|
||||
grid = np.arange(0, T + 1, dtype=float)
|
||||
Sg = Sfun(grid)
|
||||
mid = Sfun(np.arange(T) + 0.5)
|
||||
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
|
||||
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
|
||||
return 1e12 # región inválida / no calculable
|
||||
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
|
||||
|
||||
def ajustar_weibull(d, c):
|
||||
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
|
||||
best = None
|
||||
for k0 in (0.7, 1.0, 1.5):
|
||||
for l0 in (50., 200., 1000.):
|
||||
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
|
||||
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
|
||||
if best is None or r.fun < best.fun: best = r
|
||||
k, lam = np.exp(best.x)
|
||||
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
|
||||
S=lambda t: S_weibull(t, k, lam))
|
||||
|
||||
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
|
||||
amin = max(0.0, 1.0 - k_fijo) + 1e-6
|
||||
def unpack(p):
|
||||
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
|
||||
T_max = float(len(d))
|
||||
t_fin = time.time() + max_seg
|
||||
agotado = [False]
|
||||
def f(p):
|
||||
if time.time() > t_fin:
|
||||
agotado[0] = True
|
||||
return 1e12
|
||||
a, b, lam = unpack(p)
|
||||
# penaliza regiones degeneradas (|z| enorme en el último mes -> serie costosa e inestable)
|
||||
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
|
||||
return 1e12
|
||||
try:
|
||||
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
|
||||
except Exception:
|
||||
return 1e12
|
||||
lams = [lam_ref] if lam_ref else []
|
||||
lams += [100., 500.]
|
||||
best = None
|
||||
inicios = []
|
||||
if lam_ref: # primero el punto que reproduce el Weibull clásico (alpha=1, beta~1): como el clásico es un caso particular, el fraccional nunca queda peor
|
||||
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
|
||||
for l0 in lams:
|
||||
for a0 in (0.3, 1.0):
|
||||
for b0 in (0.5, 0.9):
|
||||
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
|
||||
for p0 in inicios:
|
||||
if time.time() > t_fin and best is not None: break
|
||||
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
|
||||
if best is None or r.fun < best.fun: best = r
|
||||
a, b, lam = unpack(best.x)
|
||||
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
|
||||
S=lambda t: S_ks(t, k_fijo, a, b, lam))
|
||||
|
||||
|
||||
def km_curva(meses_int, evento, T):
|
||||
d, c = tabla_eventos(meses_int, evento)
|
||||
L = max(len(d), T + 1)
|
||||
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
|
||||
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
|
||||
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
|
||||
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
|
||||
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
se = np.sqrt(V) / np.abs(np.log(S))
|
||||
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
|
||||
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
|
||||
return S, lo, hi
|
||||
|
||||
T_KM = max(MESES_MAX, max(HORIZONTES))
|
||||
S_km, lo_km, hi_km = km_curva(df["meses_int"].values, df["evento"].values, T_KM)
|
||||
|
||||
d_t, c_t = tabla_eventos(df["meses_int"].values, df["evento"].values)
|
||||
w_fit = ajustar_weibull(d_t, c_t)
|
||||
k_f = w_fit["k"] if K_IDENT == "clasico" else float(K_IDENT)
|
||||
ks_fit = ajustar_ks(d_t, c_t, k_fijo=k_f, lam_ref=w_fit["lam"])
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
|
||||
X_dum = construir_X_dum()
|
||||
|
||||
def curva_ajustada(idx, T, paso=PASO_AJUSTE):
|
||||
m, e = MESES_V[idx], EV_V[idx]
|
||||
bordes = list(range(0, T + 1, paso))
|
||||
if bordes[-1] < T: bordes.append(T)
|
||||
S_i = np.ones(len(idx)); S_b = [1.0]
|
||||
for a, b in zip(bordes[:-1], bordes[1:]):
|
||||
sel = np.where(m >= a)[0]
|
||||
y = np.where(e[sel] & (m[sel] < b), 0, 1); w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
|
||||
if y.min() == y.max():
|
||||
S_i = S_i * y.mean()
|
||||
else:
|
||||
lr = LogisticRegression(C=10.0, max_iter=300).fit(X_dum[idx][sel], y, sample_weight=w)
|
||||
S_i = S_i * lr.predict_proba(X_dum[idx])[:, 1]
|
||||
S_b.append(S_i.mean())
|
||||
S_b = np.minimum.accumulate(np.array(S_b))
|
||||
S = np.interp(np.arange(T + 1), bordes, np.log(np.maximum(S_b, 1e-12)))
|
||||
return np.exp(S)
|
||||
|
||||
S_aj = curva_ajustada(np.arange(len(df)), T_KM)
|
||||
|
||||
def ajustar_a_curva(S, N_eq):
|
||||
d = np.maximum(N_eq * (S[:-1] - S[1:]), 0.0); T = len(d)
|
||||
d = np.concatenate([d, [0.0, 0.0]]); c = np.zeros(T + 2); c[T] = N_eq * S[-1]
|
||||
w = ajustar_weibull(d, c)
|
||||
ks = ajustar_ks(d, c, k_fijo=(w["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w["lam"])
|
||||
return w, ks
|
||||
|
||||
if CURVAS == "ajustada":
|
||||
S_base = S_aj; lo_base = hi_base = None
|
||||
_, ks_plot = ajustar_a_curva(S_aj, len(df))
|
||||
else:
|
||||
S_base, lo_base, hi_base, ks_plot = S_km, lo_km, hi_km, ks_fit
|
||||
|
||||
|
||||
from scipy.special import gammaln
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
def pesos_y(meses, evento, h, modo):
|
||||
m = np.asarray(meses, int); e = np.asarray(evento, bool)
|
||||
conocido = e | (m >= h)
|
||||
y = (m >= h).astype(int)
|
||||
w = np.ones(len(m))
|
||||
if modo == "ipcw":
|
||||
T = int(m.max()) + 2
|
||||
cen = np.bincount(m[~e], minlength=T); mu = np.bincount(m, minlength=T)
|
||||
nr = len(m) - np.concatenate([[0], np.cumsum(mu)[:-1]])
|
||||
G = np.concatenate([[1.0], np.cumprod(1 - cen / np.maximum(nr, 1))]) # G[t] = P(no censurada antes del mes t)
|
||||
G = np.clip(G, 0.05, 1.0)
|
||||
w = 1.0 / G[np.minimum(m, h)]
|
||||
return conocido, y, w
|
||||
|
||||
# Matriz de covariables: codificación entera por covariable y dummies para la LR
|
||||
X_int = np.column_stack([pd.factorize(df[c])[0] for c in COVARIABLES]).astype(int)
|
||||
niv = X_int.max(axis=0) + 1
|
||||
X_dum = construir_X_dum()
|
||||
|
||||
def bdeu(codigo, y, w, q, ess):
|
||||
n = np.bincount(codigo * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
|
||||
nj = n.sum(1); aj = ess / q; ajk = aj / 2
|
||||
return float(np.sum(gammaln(aj) - gammaln(aj + nj) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)))
|
||||
|
||||
def buscar_padres(X, niv, y, w, ess=HBN_ESS, max_padres=HBN_MAX_PADRES):
|
||||
padres, cod, q = [], np.zeros(len(y), int), 1
|
||||
mejor = bdeu(cod, y, w, q, ess)
|
||||
while len(padres) < max_padres:
|
||||
cand = None
|
||||
for j in range(X.shape[1]):
|
||||
if j in padres or q * niv[j] > 200_000: continue
|
||||
c2 = cod * niv[j] + X[:, j]; s = bdeu(c2, y, w, q * niv[j], ess)
|
||||
if s > mejor + 1e-9 and (cand is None or s > cand[0]): cand = (s, j, c2, q * niv[j])
|
||||
if cand is None: break
|
||||
mejor, j, cod, q = cand; padres.append(j)
|
||||
return padres
|
||||
|
||||
PADRES_FIJOS_IDX = None
|
||||
if HBN_PADRES_FIJOS:
|
||||
PADRES_FIJOS_IDX = []
|
||||
_kws = list(HBN_PADRES_FIJOS) + (["Edad"] if HBN_EDAD_PADRE and not any(re.search(r"(^|_)age(_|$)|edad", k.lower()) for k in HBN_PADRES_FIJOS) else [])
|
||||
for kw in _kws:
|
||||
hit = [j for j, c in enumerate(COVARIABLES) if kw.lower() in c.lower()]
|
||||
assert hit, f"HBN_PADRES_FIJOS: no hay una covariable que contenga '{kw}' en {COVARIABLES}"
|
||||
PADRES_FIJOS_IDX.append(hit[0])
|
||||
|
||||
def ajustar_hbn(X, niv, y, w, ess=HBN_ESS, pad=None):
|
||||
if pad is None and PADRES_FIJOS_IDX is not None: pad = PADRES_FIJOS_IDX
|
||||
pad = buscar_padres(X, niv, y, w, ess) if pad is None else list(pad)
|
||||
q = int(np.prod([niv[j] for j in pad])) if pad else 1
|
||||
cod = np.zeros(len(y), int)
|
||||
for j in pad: cod = cod * niv[j] + X[:, j]
|
||||
n = np.bincount(cod * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
|
||||
aj = ess / q
|
||||
pbar = (n[:, 1].sum() + 0.5) / (n.sum() + 1) # prior centrado en la supervivencia marginal (evita sesgar hacia 0.5)
|
||||
return pad, (n[:, 1] + aj * pbar) / (n.sum(1) + aj) # P(Y=1 | padres), suavizada hacia la marginal
|
||||
|
||||
def predecir_hbn(modelo, X, niv):
|
||||
pad, cpt = modelo
|
||||
cod = np.zeros(len(X), int)
|
||||
for j in pad: cod = cod * niv[j] + X[:, j]
|
||||
return cpt[cod]
|
||||
|
||||
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
|
||||
|
||||
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
|
||||
|
||||
def pred_h(idx, h, modo, pad=None):
|
||||
m, e = MESES_V[idx], EV_V[idx]
|
||||
kn, y, w = pesos_y(m, e, h, modo)
|
||||
sel = np.where(kn)[0]
|
||||
lr = LogisticRegression(C=1e6, max_iter=500)
|
||||
lr.fit(X_dum[idx][sel], y[sel], sample_weight=w[sel])
|
||||
mod = ajustar_hbn(X_int[idx][sel], niv, y[sel], w[sel], pad=pad)
|
||||
return lr.predict_proba(X_dum[idx])[:, 1], predecir_hbn(mod, X_int[idx], niv), list(mod[0])
|
||||
|
||||
BORDES = [0] + list(HORIZONTES)
|
||||
|
||||
def pred_riesgo_int(idx, padres=None, test=None):
|
||||
test = idx if test is None else test
|
||||
m, e = MESES_V[idx], EV_V[idx]
|
||||
P_lr, P_hb, pads = [], [], []
|
||||
for i_, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
|
||||
sel = np.where(m >= a)[0] # llegan vivas al inicio del intervalo
|
||||
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = sobrevive el intervalo
|
||||
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censura dentro del intervalo: medio riesgo
|
||||
lr = LogisticRegression(C=1e6, max_iter=500).fit(X_dum[idx][sel], y, sample_weight=w)
|
||||
mod = ajustar_hbn(X_int[idx][sel], niv, y, w, pad=None if padres is None else padres[i_])
|
||||
P_lr.append(lr.predict_proba(X_dum[test])[:, 1]); P_hb.append(predecir_hbn(mod, X_int[test], niv)); pads.append(list(mod[0]))
|
||||
return np.column_stack(P_lr), np.column_stack(P_hb), pads
|
||||
|
||||
def pred_riesgo(idx, padres=None):
|
||||
Pl, Ph, pads = pred_riesgo_int(idx, padres)
|
||||
return np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1), pads
|
||||
|
||||
def predecir_pacientes(idx, modo, padres=None):
|
||||
if modo == "riesgo":
|
||||
return pred_riesgo(idx, padres)
|
||||
r = [pred_h(idx, h, modo, None if padres is None else padres[i_]) for i_, h in enumerate(HORIZONTES)]
|
||||
return np.column_stack([x[0] for x in r]), np.column_stack([x[1] for x in r]), [x[2] for x in r]
|
||||
|
||||
def estimar(idx, modo, padres=None):
|
||||
P_lr, P_hb, pads = predecir_pacientes(idx, modo, padres)
|
||||
return P_lr.mean(axis=0), P_hb.mean(axis=0), pads
|
||||
|
||||
from scipy.optimize import minimize_scalar
|
||||
ESTILO_MOD = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
|
||||
N = len(df); todas = np.arange(N)
|
||||
COMB_ACTIVO = bool(COMBINAR) and CENSURA_MODELOS == "riesgo"
|
||||
MODS_PLOT = (["LR", "HBN", "COMB"] if MOSTRAR_INDIVIDUALES else ["COMB"]) if COMB_ACTIVO else ["LR", "HBN"]
|
||||
|
||||
# ---- Robustez fuera de muestra: predicciones por pliegues (cada paciente se predice con modelos que no la vieron)
|
||||
if COMB_ACTIVO:
|
||||
_fold = np.random.default_rng(SEMILLA + 7).permutation(N) % STACK_FOLDS
|
||||
OOF_lr = np.zeros((N, len(HORIZONTES))); OOF_hb = np.zeros_like(OOF_lr)
|
||||
for k in range(STACK_FOLDS):
|
||||
te = np.where(_fold == k)[0]; tr = np.where(_fold != k)[0]
|
||||
Pl_, Ph_, _ = pred_riesgo_int(tr, None, te); OOF_lr[te] = Pl_; OOF_hb[te] = Ph_
|
||||
|
||||
def pesos_apilados(mask, shrink=STACK_SHRINK):
|
||||
filas_ = []
|
||||
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
|
||||
idx_ = np.where(mask & (MESES_V >= a))[0]
|
||||
e_, m_ = EV_V[idx_], MESES_V[idx_]
|
||||
y = np.where(e_ & (m_ < b), 0, 1); wt = np.where((~e_) & (m_ < b), 0.5, 1.0)
|
||||
p1 = np.clip(OOF_lr[idx_, j], 1e-9, 1 - 1e-9); p2 = np.clip(OOF_hb[idx_, j], 1e-9, 1 - 1e-9)
|
||||
muertes = int((y == 0).sum())
|
||||
if len(idx_) == 0:
|
||||
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=0, muertes=0, w_LR=0.5, w_LR_sin_contraer=0.5, dLL_LR_menos_HBN=0.0, z=0.0, decision="mezcla")); continue
|
||||
def nll(w_):
|
||||
p = np.clip(w_ * p1 + (1 - w_) * p2, 1e-9, 1 - 1e-9)
|
||||
return -np.sum(wt * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||
w_star = float(minimize_scalar(nll, bounds=(0, 1), method="bounded").x)
|
||||
lam = shrink / (shrink + muertes); w_fin = (1 - lam) * w_star + lam * 0.5
|
||||
d = wt * (y * (np.log(p1) - np.log(p2)) + (1 - y) * (np.log1p(-p1) - np.log1p(-p2))) # log-score LR - HBN por paciente
|
||||
z = d.sum() / (np.sqrt(len(d)) * d.std(ddof=1)) if len(d) > 2 and d.std(ddof=1) > 0 else 0.0
|
||||
dec = "solo LR" if w_fin >= 0.95 else "solo HBN" if w_fin <= 0.05 else "mezcla"
|
||||
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=len(idx_), muertes=muertes, w_LR=w_fin, w_LR_sin_contraer=w_star,
|
||||
dLL_LR_menos_HBN=float(d.sum()), z=float(z), decision=dec))
|
||||
return pd.DataFrame(filas_)
|
||||
|
||||
def estimar4(idx, padres, W):
|
||||
Pl, Ph, pads_ = pred_riesgo_int(idx, padres)
|
||||
Sc = np.cumprod(W[None, :] * Pl + (1 - W[None, :]) * Ph, axis=1)
|
||||
return np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), Sc.mean(0), pads_
|
||||
|
||||
rng = np.random.default_rng(SEMILLA)
|
||||
if COMB_ACTIVO:
|
||||
TAB_W_ALL = pesos_apilados(np.ones(N, bool)); W_ALL = TAB_W_ALL["w_LR"].values
|
||||
p_lr, p_hbn, p_cmb, pads = estimar4(todas, None, W_ALL)
|
||||
else:
|
||||
p_lr, p_hbn, pads = estimar(todas, CENSURA_MODELOS); p_cmb = None
|
||||
PADRES_REF = pads if HBN_PADRES == "fijos" else None # padres de la HBN aprendidos en la cohorte completa
|
||||
if DIAGNOSTICO: # mismos puntos con los otros tratamientos de la censura (sin bootstrap), para ver cuánto depende el resultado de él
|
||||
diag = {"KM crudo": [S_km[h] for h in HORIZONTES], "KM ajustada": [S_aj[h] for h in HORIZONTES]}
|
||||
for modo in ("riesgo", "ipcw", "excluir"):
|
||||
r = estimar(todas, modo); diag[f"LR ({modo})"] = r[0]; diag[f"HBN ({modo})"] = r[1]
|
||||
boots = []
|
||||
for b in tqdm(range(B_BOOT), desc="Bootstrap"):
|
||||
idx_b = rng.integers(0, N, N)
|
||||
if COMB_ACTIVO:
|
||||
r = estimar4(idx_b, PADRES_REF, W_ALL); boots.append(np.concatenate([r[0], r[1], r[2]]))
|
||||
else:
|
||||
r = estimar(idx_b, CENSURA_MODELOS, PADRES_REF); boots.append(np.concatenate([r[0], r[1]]))
|
||||
SERIES = [("LR", p_lr), ("HBN", p_hbn)] + ([("COMB", p_cmb)] if COMB_ACTIVO else [])
|
||||
nh = len(HORIZONTES)
|
||||
boots = np.array(boots) if B_BOOT > 0 else np.full((1, len(SERIES) * nh), np.nan)
|
||||
ic = np.nanpercentile(boots, [2.5, 97.5], axis=0)
|
||||
filas = []
|
||||
for j, (nom, vals_) in enumerate(SERIES):
|
||||
for i, h in enumerate(HORIZONTES):
|
||||
filas.append(dict(modelo=nom, meses=h, S=vals_[i], IC_inf=ic[0, j * nh + i], IC_sup=ic[1, j * nh + i]))
|
||||
tabla = pd.DataFrame(filas)
|
||||
tabla["KM_crudo"] = [S_km[h] for h in tabla["meses"]]
|
||||
tabla["KM_ajustada"] = [S_aj[h] for h in tabla["meses"]]
|
||||
tabla.to_csv(SALIDA_CSV, index=False)
|
||||
if COMB_ACTIVO: TAB_W_ALL.to_csv(f"./pesos_combinacion_cohorte{SUF}.csv", index=False)
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
tt = np.arange(0, MESES_MAX + 1)
|
||||
tc = np.linspace(0, MESES_MAX, 600)
|
||||
if INSET_ZOOM:
|
||||
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.6), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
|
||||
else:
|
||||
fig, ax = plt.subplots(figsize=(9.5, 5.6))
|
||||
xx = np.arange(T_KM + 1)
|
||||
if CURVAS == "ajustada":
|
||||
if MOSTRAR_KM_CRUDO: ax.step(xx, S_km, where="post", color="#9aa5b1", lw=1.0, ls=":", label="Kaplan-Meier crudo (referencia)")
|
||||
ax.step(xx, S_aj, where="post", color="#3d4852", lw=1.8, label="Kaplan-Meier ajustada por covariables")
|
||||
lbl_ks = "Weibull fraccional (ajustado a la curva ajustada)"
|
||||
else:
|
||||
ax.fill_between(xx, lo_km, hi_km, step="post", color="#9aa5b1", alpha=.35, lw=0, label="Kaplan-Meier (IC 95 % Greenwood)")
|
||||
ax.step(xx, S_km, where="post", color="#3d4852", lw=1.6, label="Kaplan-Meier")
|
||||
lbl_ks = "Weibull fraccional (Kilbas-Saigo)"
|
||||
ax.plot(tc, ks_plot["S"](tc), color="#d1495b", lw=2.4, label=lbl_ks)
|
||||
for nom in MODS_PLOT:
|
||||
col, mk, lb = ESTILO_MOD[nom]
|
||||
s = tabla[tabla["modelo"] == nom]
|
||||
ax.errorbar(s["meses"], s["S"], yerr=[np.clip(s["S"] - s["IC_inf"], 0, None), np.clip(s["IC_sup"] - s["S"], 0, None)], fmt=mk, color=col, ms=9 if nom == "COMB" else 8,
|
||||
capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
|
||||
tabla_p = tabla[tabla["modelo"].isin(MODS_PLOT)]
|
||||
ax.set_xlim(0, MESES_MAX + (0.8 if TOPE_MESES else 0)); ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)")
|
||||
vals = np.concatenate([S_base[:MESES_MAX + 1], tabla_p["IC_inf"].values, [ks_plot["S"](np.array([float(MESES_MAX)]))[0]]])
|
||||
ax.set_ylim(max(0.0, np.nanmin(vals) - 0.03), 1.005)
|
||||
if YLIM_PRINCIPAL: ax.set_ylim(*YLIM_PRINCIPAL)
|
||||
ax.set_xticks(range(0, MESES_MAX + 1, 3 if TOPE_MESES else 6)); ax.grid(alpha=.25)
|
||||
if INSET_ZOOM:
|
||||
xi = np.arange(INSET_MESES + 1)
|
||||
axi.step(xi, S_aj[:INSET_MESES + 1] if CURVAS == "ajustada" else S_km[:INSET_MESES + 1], where="post", color="#3d4852", lw=1.4)
|
||||
if CURVAS == "ajustada" and MOSTRAR_KM_CRUDO: axi.step(xi, S_km[:INSET_MESES + 1], where="post", color="#9aa5b1", lw=1.0, ls=":")
|
||||
tci = np.linspace(0, INSET_MESES, 200); axi.plot(tci, ks_plot["S"](tci), color="#d1495b", lw=2)
|
||||
for nom in MODS_PLOT:
|
||||
col, mk, lb = ESTILO_MOD[nom]; s_ = tabla[tabla["modelo"] == nom]
|
||||
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
|
||||
fmt=mk, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
|
||||
_v = np.concatenate([S_base[:INSET_MESES + 1], tabla_p["IC_inf"].values, tabla_p["IC_sup"].values]); _m = (_v.max() - _v.min()) * .08
|
||||
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(_v.min() - _m, min(1.002, _v.max() + _m)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
|
||||
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
|
||||
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
|
||||
ax.set_title(f"Supervivencia de la cohorte completa (n = {N:,}){TAG}"); ax.legend(loc="lower left", frameon=False)
|
||||
for s in ("top", "right"): ax.spines[s].set_visible(False)
|
||||
fig.tight_layout(); fig.savefig(SALIDA_PNG, dpi=200)
|
||||
import matplotlib.pyplot as _p; _p.close("all")
|
||||
|
||||
|
||||
MESES_EXTRAP = TOPE_MESES or 120 # hasta dónde se extrapola (punteado) fuera del seguimiento observado
|
||||
YLIM_SUB = {} # zoom manual en y por subgrupo, p. ej. {"Estadio I": (0.97, 1.0)}; los que no estén usan el automático
|
||||
XLIM_SUB = None # p. ej. (0, 72) para no mostrar la extrapolación; None = (0, MESES_EXTRAP)
|
||||
MIN_EVENTOS_SUB = 5 # mínimo de fallecimientos para ajustar un subgrupo
|
||||
B_BOOT_SUB = B_BOOT # réplicas bootstrap de los modelos en los subgrupos (es otro bucle completo; baja el número si tarda mucho)
|
||||
|
||||
COL_EST = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
|
||||
COL_SUB = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
|
||||
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
|
||||
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
|
||||
|
||||
def _edad(v):
|
||||
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
|
||||
def _estadio(v):
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS": return 0
|
||||
for p_, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(p_): return val
|
||||
return np.nan
|
||||
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
|
||||
df["_estadio"] = df[COL_EST].map(_estadio) if COL_EST else np.nan
|
||||
COL_CX = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
|
||||
df["_her2neg"] = df[COL_SUB].astype(str).str.contains("HER2-", regex=False) if COL_SUB else False # sin HER2+ (HER2 negativo)
|
||||
df["_triple_neg"] = df[COL_SUB].astype(str).str.contains("HR-/HER2-", regex=False) if COL_SUB else False # HR− / HER2−
|
||||
df["_cons"] = df[COL_CX].astype(str).str.lower().str.contains("conserv") if COL_CX else False # cirugía conservadora
|
||||
df["_her2pos"] = df[COL_SUB].astype(str).str.contains("HER2+", regex=False) if COL_SUB else False
|
||||
|
||||
# Edita aquí los subgrupos (nombre -> máscara booleana sobre df)
|
||||
SUBGRUPOS = {
|
||||
"HER2+ · ≥60 años · estadio III–IV (Alto)": lambda d: d["_her2pos"] & (d["_edad"] >= 60) & d["_estadio"].isin([3, 4]),
|
||||
"HER2+ · <60 años · estadio 0–II (Bajo)": lambda d: d["_her2pos"] & (d["_edad"] < 60) & d["_estadio"].isin([0, 1, 2]),
|
||||
"Estadio IV": lambda d: d["_estadio"] == 4,
|
||||
"Estadio I": lambda d: d["_estadio"] == 1,
|
||||
"≥ 75 años": lambda d: d["_edad"] >= 75,
|
||||
"< 45 años": lambda d: d["_edad"] < 45,
|
||||
# --- combinaciones adicionales ---
|
||||
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] < 45) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
|
||||
"HER2− · estadio 0–II · cirugía conservadora": lambda d: d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
|
||||
"HER2+ · estadio 0–II · cirugía conservadora": lambda d: d["_her2pos"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
|
||||
"Jóvenes (<45) · estadio 0–II": lambda d: (d["_edad"] < 45) & d["_estadio"].isin([0, 1, 2]),
|
||||
"Jóvenes (<45) · HER2−": lambda d: (d["_edad"] < 45) & d["_her2neg"],
|
||||
"Triple negativo (HR−/HER2−) · estadio 0–II": lambda d: d["_triple_neg"] & d["_estadio"].isin([0, 1, 2]),
|
||||
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] >= 65) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
|
||||
}
|
||||
MASCARAS = {n: np.asarray(f(df).fillna(False), dtype=bool) for n, f in SUBGRUPOS.items()}
|
||||
|
||||
|
||||
# LR, HBN y su combinación en los subgrupos: se ajustan en la cohorte completa y se promedian las predicciones dentro de cada subgrupo
|
||||
rng_sub = np.random.default_rng(SEMILLA + 1)
|
||||
MODELOS_SUB = ["LR", "HBN"] + (["COMB"] if COMB_ACTIVO else [])
|
||||
nm = len(MODELOS_SUB)
|
||||
if COMB_ACTIVO: # pesos de la combinación por subgrupo (robustez fuera de muestra dentro del subgrupo)
|
||||
W_SUB = {n: pesos_apilados(mk) for n, mk in MASCARAS.items()}
|
||||
else:
|
||||
W_SUB = {}
|
||||
|
||||
def medias_subgrupo(idx, padres):
|
||||
out = {}
|
||||
if COMB_ACTIVO:
|
||||
Pl, Ph, _ = pred_riesgo_int(idx, padres)
|
||||
Sl, Sh = np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1)
|
||||
for n, mk in MASCARAS.items():
|
||||
mm = mk[idx]
|
||||
if not mm.any(): out[n] = np.full(nm * nh, np.nan); continue
|
||||
W_ = W_SUB[n]["w_LR"].values[None, :]
|
||||
Sc = np.cumprod(W_ * Pl[mm] + (1 - W_) * Ph[mm], axis=1)
|
||||
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0), Sc.mean(0)])
|
||||
else:
|
||||
Sl, Sh, _ = predecir_pacientes(idx, CENSURA_MODELOS, padres)
|
||||
for n, mk in MASCARAS.items():
|
||||
mm = mk[idx]
|
||||
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0)]) if mm.any() else np.full(nm * nh, np.nan)
|
||||
return out
|
||||
|
||||
PT_SUB = medias_subgrupo(todas, None)
|
||||
_boots = {n: [] for n in MASCARAS}
|
||||
for b in tqdm(range(B_BOOT_SUB), desc="Bootstrap subgrupos"):
|
||||
r_ = medias_subgrupo(rng_sub.integers(0, N, N), PADRES_REF)
|
||||
for n in MASCARAS: _boots[n].append(r_[n])
|
||||
MOD_SUB = {}
|
||||
for n, mk in MASCARAS.items():
|
||||
B_ = np.array(_boots[n]) if B_BOOT_SUB > 0 else np.full((1, nm * nh), np.nan)
|
||||
ic_ = np.nanpercentile(B_, [2.5, 97.5], axis=0) if mk.any() else np.full((2, nm * nh), np.nan)
|
||||
pt = PT_SUB[n]
|
||||
MOD_SUB[n] = pd.DataFrame([dict(modelo=nom, meses=h, S=pt[j * nh + i], IC_inf=ic_[0, j * nh + i], IC_sup=ic_[1, j * nh + i])
|
||||
for j, nom in enumerate(MODELOS_SUB) for i, h in enumerate(HORIZONTES)])
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
def aic(nll, k): return 2 * k + 2 * nll
|
||||
RES_SUB = {}
|
||||
|
||||
def ajustar_subgrupo(nombre):
|
||||
mk = MASCARAS[nombre]; sub = df[mk]
|
||||
n_, ev_ = len(sub), int(sub["evento"].sum())
|
||||
if n_ == 0 or ev_ < MIN_EVENTOS_SUB:
|
||||
return None
|
||||
d_, c_ = tabla_eventos(sub["meses_int"].values, sub["evento"].values)
|
||||
w_ = ajustar_weibull(d_, c_)
|
||||
ks_ = ajustar_ks(d_, c_, k_fijo=(w_["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w_["lam"], max_seg=180)
|
||||
Tm = int(sub["meses_int"].max())
|
||||
Sk, lok, hik = km_curva(sub["meses_int"].values, sub["evento"].values, Tm)
|
||||
grid = np.arange(0, Tm + 1, dtype=float)
|
||||
fila = {"subgrupo": nombre, "n": n_, "fallecidos": ev_, "seguim. máx. (m)": Tm, "k Weibull": w_["k"],
|
||||
"k KS / α / β": f"{ks_['k']:.2f} / {ks_['alpha']:.2f} / {ks_['beta']:.2f}",
|
||||
"AIC Weibull": aic(w_["nll"], 2), "AIC fraccional": aic(ks_["nll"], 3), "ΔAIC (W − F)": aic(w_["nll"], 2) - aic(ks_["nll"], 3),
|
||||
"máx|KM−Weibull|": np.abs(w_["S"](grid) - Sk).max(), "máx|KM−fracc.|": np.abs(ks_["S"](grid) - Sk).max()}
|
||||
return dict(nombre=nombre, n=n_, ev=ev_, w=w_, ks=ks_, Sk=Sk, lok=lok, hik=hik, Tm=Tm, fila=fila, modelos=MOD_SUB[nombre], pesos=W_SUB.get(nombre))
|
||||
|
||||
def graficar_subgrupo(a):
|
||||
if a is None: return
|
||||
mp = a["modelos"][a["modelos"]["modelo"].isin(MODS_PLOT)]
|
||||
Tm = a["Tm"]; tt = np.arange(Tm + 1)
|
||||
if INSET_ZOOM:
|
||||
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.2), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
|
||||
else:
|
||||
fig, ax = plt.subplots(figsize=(9, 5.2))
|
||||
ax.fill_between(tt, a["lok"], a["hik"], step="post", color="#9aa5b1", alpha=.3, lw=0)
|
||||
ax.step(tt, a["Sk"], where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
|
||||
for key, col, ls, lb in [("w", "#1f77b4", "-", "Weibull"), ("ks", "#d1495b", "--", "Weibull fraccional")]:
|
||||
t_in = np.linspace(0, Tm, 300); t_ex = np.linspace(Tm, MESES_EXTRAP, 200)
|
||||
ax.plot(t_in, a[key]["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
|
||||
ax.plot(t_ex, a[key]["S"](t_ex), color=col, lw=1.4, ls=":")
|
||||
if not TOPE_MESES: ax.axvline(Tm, color="#888", lw=.8, ls=":")
|
||||
for nom in MODS_PLOT:
|
||||
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
|
||||
ax.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
|
||||
fmt=mk_, color=col, ms=9 if nom == "COMB" else 8, capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
|
||||
x0, x1 = XLIM_SUB if XLIM_SUB else (0, MESES_EXTRAP + (0.8 if TOPE_MESES else 0))
|
||||
xs = np.linspace(x0, x1, 400)
|
||||
vis = [a["w"]["S"](xs), a["ks"]["S"](xs), a["Sk"][int(x0):int(min(x1, Tm)) + 1], a["lok"][int(x0):int(min(x1, Tm)) + 1],
|
||||
mp["IC_inf"].values, mp["IC_sup"].values]
|
||||
v = np.concatenate([np.ravel(u) for u in vis]); v = v[np.isfinite(v)]
|
||||
mg = (v.max() - v.min()) * .06
|
||||
ylim = YLIM_SUB.get(a["nombre"], (max(0, v.min() - mg), min(1.005, v.max() + mg)))
|
||||
ax.set_xlim(x0, x1); ax.set_ylim(*ylim)
|
||||
if INSET_ZOOM:
|
||||
xi = np.arange(INSET_MESES + 1)
|
||||
axi.fill_between(xi, a["lok"][:INSET_MESES + 1], a["hik"][:INSET_MESES + 1], step="post", color="#9aa5b1", alpha=.3, lw=0)
|
||||
axi.step(xi, a["Sk"][:INSET_MESES + 1], where="post", color="#222", lw=1.3)
|
||||
tci = np.linspace(0, INSET_MESES, 200)
|
||||
axi.plot(tci, a["w"]["S"](tci), color="#1f77b4", lw=2); axi.plot(tci, a["ks"]["S"](tci), color="#d1495b", lw=2, ls="--")
|
||||
for nom in MODS_PLOT:
|
||||
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
|
||||
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
|
||||
fmt=mk_, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
|
||||
vi = np.concatenate([a["Sk"][:INSET_MESES + 1], a["lok"][:INSET_MESES + 1], mp["IC_inf"].values, mp["IC_sup"].values, a["w"]["S"](tci)])
|
||||
vi = vi[np.isfinite(vi)]; mi = (vi.max() - vi.min()) * .08
|
||||
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(vi.min() - mi, min(1.002, vi.max() + mi)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
|
||||
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
|
||||
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
|
||||
ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)"); ax.grid(alpha=.25)
|
||||
ax.set_title(f"{a['nombre']}{TAG}\nn={a['n']:,}, fallecidos={a['ev']:,}", fontsize=11)
|
||||
ax.legend(frameon=False, loc="lower left", fontsize=9)
|
||||
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
|
||||
fig.tight_layout()
|
||||
nom_arch = re.sub(r"[^A-Za-z0-9]+", "_", a["nombre"].replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt").replace("ñ", "n").replace("–", "-")).strip("_")
|
||||
fig.savefig(f"./subgrupo_{nom_arch}{SUF}.png", dpi=170)
|
||||
import matplotlib.pyplot as _p; _p.close("all")
|
||||
|
||||
|
||||
RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'] = ajustar_subgrupo('HER2+ · ≥60 años · estadio III–IV (Alto)'); graficar_subgrupo(RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'])
|
||||
|
||||
|
||||
RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'] = ajustar_subgrupo('HER2+ · <60 años · estadio 0–II (Bajo)'); graficar_subgrupo(RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'])
|
||||
|
||||
|
||||
RES_SUB['Estadio IV'] = ajustar_subgrupo('Estadio IV'); graficar_subgrupo(RES_SUB['Estadio IV'])
|
||||
|
||||
|
||||
RES_SUB['Estadio I'] = ajustar_subgrupo('Estadio I'); graficar_subgrupo(RES_SUB['Estadio I'])
|
||||
|
||||
|
||||
RES_SUB['≥ 75 años'] = ajustar_subgrupo('≥ 75 años'); graficar_subgrupo(RES_SUB['≥ 75 años'])
|
||||
|
||||
|
||||
RES_SUB['< 45 años'] = ajustar_subgrupo('< 45 años'); graficar_subgrupo(RES_SUB['< 45 años'])
|
||||
|
||||
|
||||
RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'])
|
||||
|
||||
|
||||
RES_SUB['HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2− · estadio 0–II · cirugía conservadora'])
|
||||
|
||||
|
||||
RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2+ · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'])
|
||||
|
||||
|
||||
RES_SUB['Jóvenes (<45) · estadio 0–II'] = ajustar_subgrupo('Jóvenes (<45) · estadio 0–II'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · estadio 0–II'])
|
||||
|
||||
|
||||
RES_SUB['Jóvenes (<45) · HER2−'] = ajustar_subgrupo('Jóvenes (<45) · HER2−'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2−'])
|
||||
|
||||
|
||||
RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'] = ajustar_subgrupo('Triple negativo (HR−/HER2−) · estadio 0–II'); graficar_subgrupo(RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'])
|
||||
|
||||
|
||||
RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'])
|
||||
|
||||
|
||||
tabla_sub = pd.DataFrame([a["fila"] for a in RES_SUB.values() if a is not None])
|
||||
tabla_sub.to_csv(f"./subgrupos_KM_Weibull_fraccional{SUF}.csv", index=False)
|
||||
pd.concat([a["modelos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_puntos_LR_HBN{SUF}.csv", index=False)
|
||||
if COMB_ACTIVO:
|
||||
pd.concat([a["pesos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_pesos_combinacion{SUF}.csv", index=False)
|
||||
|
||||
|
||||
# Prueba: edad como variable numérica (punto medio de su grupo de 5 años) en la LR, frente a la edad categorizada
|
||||
def _edad_media(v):
|
||||
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
|
||||
if not n_: return np.nan
|
||||
if "+" in str(v): return n_[0] + 2.5
|
||||
return float(np.mean(n_[:2]))
|
||||
ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
|
||||
assert ed.notna().mean() > 0.5, "No se pudo leer la edad numérica"
|
||||
z = ((ed - ed.mean()) / ed.std()).fillna(0.0).values # edad estandarizada (faltantes -> media)
|
||||
cols_sin_edad = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())]
|
||||
Xb = pd.get_dummies(df[cols_sin_edad], drop_first=True).values.astype(np.float32)
|
||||
if "Edad_cat" in df.columns:
|
||||
Xcat = np.column_stack([Xb, pd.get_dummies(df[["Edad_cat"]], drop_first=True).values.astype(np.float32)])
|
||||
else:
|
||||
Xcat = X_dum if EDAD_MODO == "categorizada" else None
|
||||
VARIANTES = {
|
||||
"sin edad": Xb,
|
||||
"edad categorizada": Xcat,
|
||||
"edad continua": np.column_stack([Xb, z]).astype(np.float32),
|
||||
"edad continua + cuadrática": np.column_stack([Xb, z, z ** 2]).astype(np.float32),
|
||||
}
|
||||
if Xcat is None: VARIANTES.pop("edad categorizada")
|
||||
REF_V = "edad categorizada" if "edad categorizada" in VARIANTES else "sin edad"
|
||||
|
||||
def lr_int(Xm, idx, test):
|
||||
P = []
|
||||
for a, b in zip(BORDES[:-1], BORDES[1:]):
|
||||
sel = np.where(MESES_V[idx] >= a)[0]
|
||||
y = np.where(EV_V[idx][sel] & (MESES_V[idx][sel] < b), 0, 1); w = np.where((~EV_V[idx][sel]) & (MESES_V[idx][sel] < b), 0.5, 1.0)
|
||||
P.append(LogisticRegression(C=1e6, max_iter=500).fit(Xm[idx][sel], y, sample_weight=w).predict_proba(Xm[test])[:, 1])
|
||||
return np.column_stack(P)
|
||||
|
||||
_fold2 = np.random.default_rng(SEMILLA + 11).permutation(N) % STACK_FOLDS
|
||||
PT, OOF = {}, {}
|
||||
for nom, Xm in VARIANTES.items():
|
||||
PT[nom] = np.cumprod(lr_int(Xm, todas, todas), axis=1) # ajuste en toda la cohorte
|
||||
O = np.zeros((N, len(HORIZONTES)))
|
||||
for k in range(STACK_FOLDS):
|
||||
te = np.where(_fold2 == k)[0]; tr = np.where(_fold2 != k)[0]; O[te] = lr_int(Xm, tr, te)
|
||||
OOF[nom] = O
|
||||
|
||||
def ll_oof(O, mask):
|
||||
tot = 0.0
|
||||
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
|
||||
i_ = np.where(mask & (MESES_V >= a))[0]
|
||||
y = np.where(EV_V[i_] & (MESES_V[i_] < b), 0, 1); w = np.where((~EV_V[i_]) & (MESES_V[i_] < b), 0.5, 1.0)
|
||||
p = np.clip(O[i_, j], 1e-9, 1 - 1e-9); tot += np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||
return tot
|
||||
|
||||
# 1) Supervivencia media predicha por variante vs Kaplan-Meier, por subgrupo
|
||||
filas = []
|
||||
for n_, mk in [("Cohorte completa", np.ones(N, bool))] + list(MASCARAS.items()):
|
||||
if mk.sum() == 0: continue
|
||||
Sk_, _, _ = km_curva(MESES_V[mk], EV_V[mk], max(HORIZONTES))
|
||||
for i, h in enumerate(HORIZONTES):
|
||||
f_ = {"subgrupo": n_, "meses": h, "KM": Sk_[h]}
|
||||
for nom in VARIANTES: f_[nom] = PT[nom][mk, i].mean()
|
||||
filas.append(f_)
|
||||
T1 = pd.DataFrame(filas)
|
||||
# 2) Resumen: error vs KM y verosimilitud fuera de muestra
|
||||
res = []
|
||||
for nom in VARIANTES:
|
||||
err = (T1[nom] - T1["KM"]).abs()
|
||||
ll_c = ll_oof(OOF[nom], np.ones(N, bool)); ll_ref = ll_oof(OOF[REF_V], np.ones(N, bool))
|
||||
res.append({"variante": nom, "error abs. medio vs KM (todos los subgrupos y horizontes)": err.mean(), "error abs. máx.": err.max(),
|
||||
"log-verosimilitud fuera de muestra (cohorte)": ll_c, f"Δ vs {REF_V}": ll_c - ll_ref})
|
||||
T2 = pd.DataFrame(res)
|
||||
T1.to_csv(f"./prueba_edad_continua_vs_categorizada{SUF}.csv", index=False); T2.to_csv(f"./prueba_edad_resumen{SUF}.csv", index=False)
|
||||
@@ -0,0 +1,228 @@
|
||||
import json
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
|
||||
# Definicion de factores de riesgo a partir de cuatro criterios:
|
||||
# c1 OR multivariable en la poblacion natural (IC 95% sin cruzar 1 y p ajustado por Benjamini-Hochberg < ALFA)
|
||||
# c2 estabilidad en bootstrap: la variable entra al stepwise de la LR en al menos FREQ_MIN de las replicas
|
||||
# c3 la variable esta en la manta de Markov del desenlace en la red bayesiana
|
||||
# c4 diferencia absoluta de supervivencia a HORIZONTE meses (Kaplan-Meier) frente a la categoria de referencia
|
||||
# Las variables de tratamiento son una decision clinica: no se clasifican como factores de riesgo
|
||||
# y no entran al modelo de c1; se reportan aparte en asociaciones_tratamiento.csv.
|
||||
|
||||
CSV_NATURAL = "./dataframe_poblacion_natural.csv"
|
||||
CSV_SELECCION = "./seleccion_bootstrap.csv"
|
||||
CSV_ARCOS = "./hbn_arcos.csv"
|
||||
ALFA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
HORIZONTE = 18
|
||||
TOPE_MESES = 24
|
||||
TRATAMIENTO = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
|
||||
|
||||
CANONICAL_MAP = {
|
||||
"Age_group": "Edad", "Tumor_group": "Tamano_tumor", "Tamano_tumor_cat": "Tamano_tumor",
|
||||
"Estadio_cat": "Estadio", "Grado_histologico_cat": "Grado_histologico",
|
||||
"Subtipo_molecular_cat": "Subtipo_molecular", "Receptor_estrogeno_cat": "Receptor_estrogeno",
|
||||
"Receptor_progesterona_cat": "Receptor_progesterona", "Metastasis_cat": "Metastasis",
|
||||
"Localizacion_mama_cat": "Localizacion_mama", "Lateralidad_cat": "Lateralidad",
|
||||
"Tipo_histologico_cat": "Tipo_histologico", "Tratamiento_quirurgico_cat": "Tratamiento_quirurgico",
|
||||
"Radioterapia_cat": "Radioterapia", "Quimioterapia_cat": "Quimioterapia", "Estado_civil_cat": "Estado_civil",
|
||||
"Ganglios_positivos_cat": "Ganglios_positivos", "Invasion_linfovascular_cat": "Invasion_linfovascular",
|
||||
"Margenes_cat": "Margenes", "Densidad_BIRADS_cat": "Densidad_BIRADS", "Masa_espiculada_cat": "Masa_espiculada",
|
||||
"Microcalcificaciones_cat": "Microcalcificaciones", "Multifocalidad_cat": "Multifocalidad",
|
||||
"BRCA_cat": "BRCA", "HER2_IHQ_cat": "HER2_IHQ",
|
||||
}
|
||||
|
||||
|
||||
def find_col(df, keywords):
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
nat = pd.read_csv(CSV_NATURAL, dtype=str)
|
||||
nat = nat[nat["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
|
||||
|
||||
col_meses = find_col(nat, ["survival months"])
|
||||
col_vital = find_col(nat, ["vital status"])
|
||||
col_race = find_col(nat, ["race"])
|
||||
|
||||
datos = pd.DataFrame({v: nat[k].fillna("Desconocido").astype(str) for k, v in CANONICAL_MAP.items() if k in nat.columns})
|
||||
if col_race is not None and col_race not in CANONICAL_MAP:
|
||||
datos["Race"] = nat[col_race].fillna("Desconocido").astype(str)
|
||||
variables = list(datos.columns)
|
||||
intrinsecas = [v for v in variables if v not in TRATAMIENTO]
|
||||
tratamiento = [v for v in variables if v in TRATAMIENTO]
|
||||
|
||||
muerte = (nat["Outcome_cat"] == "Muerte").astype(int).values
|
||||
meses = np.minimum(pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).astype(int).values, TOPE_MESES)
|
||||
evento = nat[col_vital].astype(str).str.lower().str.contains("dead").values & (pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).values < TOPE_MESES)
|
||||
|
||||
|
||||
# ---- c1: OR multivariable (referencia = categoria mas frecuente) ----
|
||||
def referencia(v):
|
||||
return datos[v].value_counts().idxmax()
|
||||
|
||||
|
||||
def ajustar_or(vars_modelo):
|
||||
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
|
||||
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
|
||||
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
modelo = sm.GLM(muerte, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ic = modelo.conf_int()
|
||||
t = pd.DataFrame({"termino": X.columns, "OR_muerte": np.exp(modelo.params[X.columns].values),
|
||||
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
|
||||
"p": modelo.pvalues[X.columns].values})
|
||||
return t
|
||||
|
||||
|
||||
def variable_de(termino, vars_modelo):
|
||||
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
|
||||
|
||||
|
||||
def bh(p):
|
||||
p = np.asarray(p, float)
|
||||
orden = np.argsort(p)
|
||||
aj = np.empty_like(p)
|
||||
m = len(p)
|
||||
prev = 1.0
|
||||
for rango, i in zip(range(m, 0, -1), orden[::-1]):
|
||||
prev = min(prev, p[i] * m / rango)
|
||||
aj[i] = prev
|
||||
return aj
|
||||
|
||||
|
||||
tab = ajustar_or(intrinsecas)
|
||||
tab["variable"] = [variable_de(t, intrinsecas) for t in tab["termino"]]
|
||||
tab["categoria"] = [t[len(v) + 1:] for t, v in zip(tab["termino"], tab["variable"])]
|
||||
tab["referencia"] = [referencia(v) for v in tab["variable"]]
|
||||
tab["p_ajustado_BH"] = bh(tab["p"])
|
||||
tab["direccion"] = np.where(tab["OR_muerte"] > 1, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
|
||||
|
||||
|
||||
# ---- c4: diferencia de supervivencia (Kaplan-Meier) frente a la referencia ----
|
||||
def km_en(m, e, h):
|
||||
T = int(m.max()) + 2
|
||||
d = np.bincount(m[e], minlength=T)
|
||||
c = np.bincount(m[~e], minlength=T)
|
||||
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
|
||||
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
|
||||
h = min(h, T - 1)
|
||||
S = np.prod(q[:h + 1])
|
||||
return S, S * np.sqrt(np.sum(v[:h + 1]))
|
||||
|
||||
|
||||
def delta_s(v, cat, ref):
|
||||
a = (datos[v] == cat).values
|
||||
b = (datos[v] == ref).values
|
||||
Sa, ea = km_en(meses[a], evento[a], HORIZONTE)
|
||||
Sb, eb = km_en(meses[b], evento[b], HORIZONTE)
|
||||
d = Sa - Sb
|
||||
es = np.sqrt(ea ** 2 + eb ** 2)
|
||||
return pd.Series({"n_categoria": int(a.sum()), "S18_categoria": Sa, "S18_referencia": Sb, "delta_S18": d,
|
||||
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
|
||||
|
||||
|
||||
def tabla_delta(filas):
|
||||
return pd.DataFrame([delta_s(v, c, r) for v, c, r in filas])
|
||||
|
||||
|
||||
ds = tabla_delta(zip(tab["variable"], tab["categoria"], tab["referencia"]))
|
||||
tab = pd.concat([tab.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
||||
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
|
||||
(np.sign(tab["delta_S18"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
|
||||
|
||||
|
||||
# ---- c2: estabilidad en bootstrap ----
|
||||
freq = pd.Series(np.nan, index=intrinsecas)
|
||||
try:
|
||||
sel = pd.read_csv(CSV_SELECCION)
|
||||
lr = sel[sel["modelo"] == "LR"]
|
||||
n_rep = (lr["termino"] == "(replica)").sum()
|
||||
if n_rep > 0:
|
||||
por_var = lr[lr["termino"] != "(replica)"].groupby("variable")["replica"].nunique()
|
||||
freq = pd.Series({v: por_var.get(v, 0) / n_rep for v in intrinsecas})
|
||||
except FileNotFoundError:
|
||||
n_rep = 0
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(freq)
|
||||
tab["c2_estabilidad"] = (tab["freq_seleccion_bootstrap"] >= FREQ_MIN).astype(object).where(tab["freq_seleccion_bootstrap"].notna(), np.nan)
|
||||
|
||||
|
||||
# ---- c3: manta de Markov del desenlace en la HBN ----
|
||||
manta = None
|
||||
try:
|
||||
arcos = pd.read_csv(CSV_ARCOS)
|
||||
padres = set(arcos.loc[arcos["destino"] == "outcome", "origen"])
|
||||
hijos = set(arcos.loc[arcos["origen"] == "outcome", "destino"])
|
||||
conyuges = set(arcos.loc[arcos["destino"].isin(hijos) & (arcos["origen"] != "outcome"), "origen"])
|
||||
manta = padres | hijos | conyuges
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
tab["en_manta_markov"] = tab["variable"].map(lambda v: (v in manta) if manta is not None else np.nan)
|
||||
tab["c3_manta_markov"] = tab["en_manta_markov"].astype(object)
|
||||
|
||||
|
||||
# ---- clasificacion ----
|
||||
CRITERIOS = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
disponibles = [c for c in CRITERIOS if tab[c].notna().all()]
|
||||
tab["criterios_cumplidos"] = tab[disponibles].apply(lambda c: c.map(lambda x: x is True or x == True)).sum(axis=1)
|
||||
tab["criterios_evaluados"] = len(disponibles)
|
||||
min_robusto = min(3, len(disponibles))
|
||||
|
||||
|
||||
def clasificar(r):
|
||||
if r["categoria"] == "Desconocido":
|
||||
return "no aplica (categoria desconocida)"
|
||||
if r["c1_or"] and r["criterios_cumplidos"] >= min_robusto:
|
||||
return f"{r['direccion']} robusto"
|
||||
if r["criterios_cumplidos"] >= 2:
|
||||
return f"{r['direccion']} sugerente"
|
||||
return "no concluyente"
|
||||
|
||||
|
||||
tab["clasificacion"] = tab.apply(clasificar, axis=1)
|
||||
columnas = ["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
|
||||
"freq_seleccion_bootstrap", "en_manta_markov", "S18_categoria", "S18_referencia", "delta_S18",
|
||||
"delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
|
||||
"criterios_cumplidos", "criterios_evaluados", "clasificacion"]
|
||||
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
|
||||
tab["_o"] = tab["clasificacion"].map(orden).fillna(5)
|
||||
tab = tab.sort_values(["_o", "OR_muerte"], ascending=[True, False])[columnas]
|
||||
tab.round(4).to_csv("./factores_riesgo.csv", index=False)
|
||||
|
||||
resumen = tab[tab["clasificacion"] != "no aplica (categoria desconocida)"].groupby("variable").agg(
|
||||
categorias_robustas=("clasificacion", lambda s: int(s.str.contains("robusto").sum())),
|
||||
categorias_sugerentes=("clasificacion", lambda s: int(s.str.contains("sugerente").sum())),
|
||||
freq_seleccion_bootstrap=("freq_seleccion_bootstrap", "first"),
|
||||
en_manta_markov=("en_manta_markov", "first"),
|
||||
OR_max=("OR_muerte", "max"), OR_min=("OR_muerte", "min"),
|
||||
).sort_values(["categorias_robustas", "categorias_sugerentes"], ascending=False)
|
||||
resumen.round(4).to_csv("./factores_riesgo_resumen_variables.csv")
|
||||
|
||||
|
||||
# ---- tratamiento: asociaciones descriptivas, sin clasificar (decision clinica) ----
|
||||
if tratamiento:
|
||||
tr = ajustar_or(intrinsecas + tratamiento)
|
||||
tr["variable"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
|
||||
tr = tr[tr["variable"].isin(tratamiento)].copy()
|
||||
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
|
||||
tr["referencia"] = [referencia(v) for v in tr["variable"]]
|
||||
tr["p_ajustado_BH"] = bh(tr["p"])
|
||||
ds_t = tabla_delta(zip(tr["variable"], tr["categoria"], tr["referencia"]))
|
||||
tr = pd.concat([tr.reset_index(drop=True), ds_t.reset_index(drop=True)], axis=1)
|
||||
tr["nota"] = "asociacion ajustada por las demas variables; no implica efecto causal (confusion por indicacion)"
|
||||
tr[["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
|
||||
"S18_categoria", "S18_referencia", "delta_S18", "delta_IC95_inf", "delta_IC95_sup", "nota"]].round(4).to_csv(
|
||||
"./asociaciones_tratamiento.csv", index=False)
|
||||
|
||||
with open("./factores_riesgo_criterios.json", "w", encoding="utf8") as f:
|
||||
json.dump({"alfa": ALFA, "freq_min_bootstrap": FREQ_MIN, "horizonte_meses": HORIZONTE, "tope_meses": TOPE_MESES,
|
||||
"replicas_bootstrap_validas": int(n_rep), "criterios_evaluados": disponibles,
|
||||
"variables_tratamiento_excluidas": tratamiento}, f, indent=2, ensure_ascii=False)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Ejecuta las etapas del pipeline en orden (cada una en su propio proceso).
|
||||
|
||||
Uso (desde la carpeta que contiene los scripts y los datos):
|
||||
python ejecutar_pipeline.py # todas las etapas, saltando las que estan vigentes
|
||||
python ejecutar_pipeline.py --solo 05 # solo esa etapa
|
||||
python ejecutar_pipeline.py --desde 02 # desde esa etapa en adelante
|
||||
python ejecutar_pipeline.py --forzar 02 04 # corre esas aunque esten vigentes
|
||||
python ejecutar_pipeline.py --todo # corre todas, sin saltar ninguna
|
||||
|
||||
Una etapa se salta solo si sus salidas existen y son mas recientes que su script y que sus entradas.
|
||||
Escribe bitacora_pipeline.csv (etapa, estado, segundos). Sin mensajes en pantalla salvo errores.
|
||||
"""
|
||||
import argparse, csv, subprocess, sys, time
|
||||
from pathlib import Path
|
||||
|
||||
BALANCEADO = "dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
|
||||
ETAPAS = [
|
||||
dict(id="01", script="01_depuracion.py", requiere=["dataframe_recodificado.csv", "mapeo_columnas_recodificadas.json"],
|
||||
produce=["dataframe_depurado.csv"]),
|
||||
dict(id="02", script="02_balanceo_categorizacion.py", requiere=["dataframe_depurado.csv"],
|
||||
produce=[BALANCEADO, "propuestas_categorizacion.csv", "dataframe_poblacion_natural.csv"]),
|
||||
dict(id="03", script="03_bootstrapping.py", requiere=[BALANCEADO], produce=["bootstrap_indices.npy", "bootstrap_metadata.json"]),
|
||||
dict(id="04", script="04_modelado.py",
|
||||
requiere=[BALANCEADO, "propuestas_categorizacion.csv", "bootstrap_indices.npy", "bootstrap_metadata.json", "dataframe_poblacion_natural.csv"],
|
||||
produce=[]), # sin salida unica verificable: siempre se corre
|
||||
dict(id="05", script="05_curvas_supervivencia.py", requiere=["dataframe_depurado.csv"],
|
||||
produce=["curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
|
||||
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"]),
|
||||
dict(id="06", script="06_factores_riesgo.py",
|
||||
requiere=["dataframe_poblacion_natural.csv", "seleccion_bootstrap.csv", "hbn_arcos.csv"],
|
||||
produce=["factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"]),
|
||||
]
|
||||
|
||||
def mtime(p): return Path(p).stat().st_mtime
|
||||
|
||||
def vigente(e):
|
||||
if not e["produce"] or not all(Path(p).exists() and Path(p).stat().st_size > 0 for p in e["produce"]): return False
|
||||
ref = max([mtime(e["script"])] + [mtime(p) for p in e["requiere"] if Path(p).exists()])
|
||||
return min(mtime(p) for p in e["produce"]) >= ref
|
||||
|
||||
def guardar(bit):
|
||||
with open("bitacora_pipeline.csv", "w", newline="", encoding="utf8") as f:
|
||||
w = csv.writer(f); w.writerow(["etapa", "estado", "segundos"]); w.writerows(bit)
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--solo", nargs="+"); ap.add_argument("--desde")
|
||||
ap.add_argument("--forzar", nargs="+", default=[]); ap.add_argument("--todo", action="store_true")
|
||||
a = ap.parse_args()
|
||||
sel = [e for e in ETAPAS if (not a.solo or e["id"] in a.solo) and (not a.desde or e["id"] >= a.desde)]
|
||||
bit = []; rehacer = False
|
||||
for e in sel:
|
||||
faltan = [p for p in e["requiere"] if not Path(p).exists()]
|
||||
if faltan: sys.exit(f"Etapa {e['id']}: faltan entradas {faltan}")
|
||||
if not (a.todo or e["id"] in a.forzar or rehacer) and vigente(e):
|
||||
bit.append((e["id"], "saltada", 0)); continue
|
||||
t0 = time.time(); r = subprocess.run([sys.executable, e["script"]])
|
||||
bit.append((e["id"], "ok" if r.returncode == 0 else f"error({r.returncode})", round(time.time() - t0)))
|
||||
guardar(bit)
|
||||
if r.returncode != 0: sys.exit(r.returncode)
|
||||
rehacer = rehacer or bool(e["produce"]) # si una etapa con salidas se rehizo, las siguientes tambien
|
||||
guardar(bit)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
from models.cama.seer_survival.pipeline import main
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Stage 02a, balancing: the 18-month outcome and an informed undersampling of the majority class.
|
||||
|
||||
The patients with a complete record and a known outcome are placed in MCA space (the multiple correspondence analysis
|
||||
of their categorical columns); every patient of the minority class (death) is kept, with the same number of survivors
|
||||
closest to them. Each public function is a Hamilton node and each parameter is the node of that name; the inputs are
|
||||
`depurated_csv`, `labels_json` and `balancing` (its settings). The heavy routines live in `balancing_stats.py`; the
|
||||
age and tumor categorization of the balanced cohort is `categorization.py`.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import balancing_stats as stats
|
||||
from models.cama.seer_survival.columns import find_col
|
||||
from models.cama.seer_survival.settings import BalancingSettings
|
||||
|
||||
MINORITY, MAJORITY = 0, 1
|
||||
|
||||
|
||||
def depurated(depurated_csv: str) -> pd.DataFrame:
|
||||
return pd.read_csv(depurated_csv, dtype=str)
|
||||
|
||||
|
||||
def labels(labels_json: str, depurated: pd.DataFrame) -> dict:
|
||||
"""Column -> its description; when there is no labels file, the column's own name."""
|
||||
path = Path(labels_json)
|
||||
if path.exists():
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
return {c: c.replace("_", " ") for c in depurated.columns}
|
||||
|
||||
|
||||
def age_column(labels: dict, depurated: pd.DataFrame, balancing: BalancingSettings) -> str:
|
||||
col = find_col(labels, balancing.age_keywords)
|
||||
if col is None or col not in depurated.columns:
|
||||
raise ValueError(f"No se encontró la columna de edad (palabras clave {list(balancing.age_keywords)}).")
|
||||
return col
|
||||
|
||||
|
||||
def age_order(depurated: pd.DataFrame, age_column: str) -> pd.DataFrame:
|
||||
"""The age levels with a number in them, youngest first: `nivel` and `mid` (its middle)."""
|
||||
return (pd.Series(depurated[age_column].dropna().unique())
|
||||
.to_frame("nivel")
|
||||
.assign(mid=lambda d: d["nivel"].map(stats.age_midpoint))
|
||||
.dropna(subset=["mid"])
|
||||
.sort_values("mid"))
|
||||
|
||||
|
||||
def age_levels(age_order: pd.DataFrame) -> list[str]:
|
||||
return age_order["nivel"].tolist()
|
||||
|
||||
|
||||
def age_midpoints(age_order: pd.DataFrame) -> list[float]:
|
||||
return age_order["mid"].tolist()
|
||||
|
||||
|
||||
def full_frame(depurated: pd.DataFrame, age_column: str, age_levels: list[str], labels: dict,
|
||||
balancing: BalancingSettings) -> pd.DataFrame:
|
||||
"""The patients with an ordered age level, and their `Outcome_cat`: Sobrevive, Muerte or Desconocido."""
|
||||
df = depurated[depurated[age_column].isin(age_levels)].copy()
|
||||
values = stats.outcome_values(df, labels, balancing)
|
||||
df["Outcome_cat"] = np.where(pd.isna(values), "Desconocido", np.where(values == 1, "Sobrevive", "Muerte"))
|
||||
return df
|
||||
|
||||
|
||||
def categorical_columns(full_frame: pd.DataFrame) -> list[str]:
|
||||
return [c for c in full_frame.columns if c.endswith("_cat") and c != "Outcome_cat"]
|
||||
|
||||
|
||||
def valid_members(full_frame: pd.DataFrame, categorical_columns: list[str], age_column: str) -> pd.Series:
|
||||
"""Patients with every categorical column and the age filled in, and a known outcome: the same subset for both
|
||||
MCA variants."""
|
||||
complete = full_frame[categorical_columns + [age_column]].notna().all(axis=1)
|
||||
return complete & (full_frame["Outcome_cat"] != "Desconocido")
|
||||
|
||||
|
||||
def valid_frame(full_frame: pd.DataFrame, valid_members: pd.Series) -> pd.DataFrame:
|
||||
return full_frame[valid_members].reset_index(drop=True)
|
||||
|
||||
|
||||
def survives(valid_frame: pd.DataFrame) -> np.ndarray:
|
||||
"""1 survives, 0 dies, per valid patient."""
|
||||
return (valid_frame["Outcome_cat"] == "Sobrevive").astype(int).values
|
||||
|
||||
|
||||
def mca(valid_frame: pd.DataFrame, categorical_columns: list[str], age_column: str,
|
||||
balancing: BalancingSettings) -> stats.Mca:
|
||||
"""The MCA of the chosen variant: `con_edad` also takes the age level as a column, `sin_edad` does not."""
|
||||
columns = categorical_columns + ([age_column] if balancing.mca_variant == "con_edad" else [])
|
||||
return stats.fit_mca(valid_frame[columns], n_components=balancing.n_components)
|
||||
|
||||
|
||||
def keep_mask(mca: stats.Mca, survives: np.ndarray, balancing: BalancingSettings) -> np.ndarray:
|
||||
"""Per valid patient: kept by the undersampling (every death, and the survivors nearest to them)."""
|
||||
mask, _ = stats.select_informed_undersample(
|
||||
mca.F, survives, minority_label=MINORITY, majority_label=MAJORITY, target_ratio=balancing.target_ratio,
|
||||
dims=balancing.distance_dims or None)
|
||||
return mask
|
||||
|
||||
|
||||
def balanced_frame(valid_frame: pd.DataFrame, keep_mask: np.ndarray) -> pd.DataFrame:
|
||||
return valid_frame[keep_mask].reset_index(drop=True)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""The heavy routines of the balancing stage, apart from its Hamilton nodes (`balancing.py`): the outcome definition,
|
||||
multiple correspondence analysis (MCA) and the informed undersampling of the majority class around the minority one.
|
||||
Plain functions with no I/O. Ported from `02_balanceo_categorizacion.py`."""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.spatial import cKDTree
|
||||
|
||||
from models.cama.seer_survival.columns import find_col
|
||||
from models.cama.seer_survival.settings import BalancingSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Mca:
|
||||
F: np.ndarray # row coordinates, one row per patient
|
||||
G: np.ndarray # category coordinates
|
||||
eigenvalues: np.ndarray
|
||||
inertia_explained: np.ndarray
|
||||
contributions: pd.DataFrame
|
||||
|
||||
|
||||
def age_midpoint(v) -> float:
|
||||
"""The middle of an age level: "40-44" -> 42, "85+" -> 90, "05" -> 5; NaN when it has no number."""
|
||||
if not isinstance(v, str):
|
||||
return np.nan
|
||||
s = v.strip()
|
||||
m = re.match(r"^(\d+)\s*-\s*(\d+)", s)
|
||||
if m:
|
||||
return (int(m.group(1)) + int(m.group(2))) / 2
|
||||
m = re.match(r"^(\d+)\s*\+", s)
|
||||
if m:
|
||||
return int(m.group(1)) + 5
|
||||
m = re.match(r"^(\d+)", s)
|
||||
return float(m.group(1)) if m else np.nan
|
||||
|
||||
|
||||
def outcome_values(df: pd.DataFrame, labels: dict, s: BalancingSettings) -> np.ndarray:
|
||||
"""1.0 survives the horizon, 0.0 dies before it, NaN unknown. With `censura_excluida`, a patient alive with less
|
||||
follow-up than the horizon is unknown, and so is every patient of a diagnosis year with too much censoring."""
|
||||
if "outcome" in df.columns:
|
||||
return df["outcome"].astype(float).values
|
||||
surv_col = find_col(labels, ["survival months"], exclude=["flag"])
|
||||
assert surv_col is not None, "No se encontró la columna de meses de supervivencia."
|
||||
vital_col = find_col(labels, ["vital status"])
|
||||
year_col = find_col(labels, ["year of diagnosis", "year of dx"])
|
||||
surv = pd.to_numeric(df[surv_col], errors="coerce")
|
||||
ge = surv >= s.horizon_months
|
||||
dead = df[vital_col].astype(str).str.lower().str.contains("dead") if vital_col is not None and vital_col in df.columns else None
|
||||
original = np.where(surv.notna(), ge.astype(float), np.nan)
|
||||
if not (s.outcome_mode == "censura_excluida" and dead is not None):
|
||||
return original
|
||||
values = np.where(surv.isna(), np.nan, np.where(ge, 1.0, np.where(dead, 0.0, np.nan)))
|
||||
if s.exclude_censored_years and year_col is not None and year_col in df.columns:
|
||||
censored = surv.notna() & (~ge) & (~dead)
|
||||
pct = censored.groupby(df[year_col]).mean() * 100
|
||||
years = sorted(pct[pct > s.censoring_max_pct].index.tolist())
|
||||
if years:
|
||||
values = np.where(df[year_col].isin(years), np.nan, values)
|
||||
return values
|
||||
|
||||
|
||||
def fit_mca(df_cat: pd.DataFrame, n_components: int = 10) -> Mca:
|
||||
"""MCA of a frame of categorical columns, by the SVD of the standardized residuals of its indicator matrix."""
|
||||
Z = pd.get_dummies(df_cat, prefix_sep="__").astype(float)
|
||||
n, J = Z.shape
|
||||
Q = df_cat.shape[1]
|
||||
|
||||
P = Z.values / (n * Q)
|
||||
r = P.sum(axis=1)
|
||||
c = P.sum(axis=0)
|
||||
|
||||
Dr_inv_sqrt = 1.0 / np.sqrt(r)
|
||||
Dc_inv_sqrt = 1.0 / np.sqrt(c)
|
||||
S = Dr_inv_sqrt[:, None] * (P - np.outer(r, c)) * Dc_inv_sqrt[None, :]
|
||||
|
||||
U, sigma, Vt = np.linalg.svd(S, full_matrices=False)
|
||||
V = Vt.T
|
||||
K = min(n_components, len(sigma))
|
||||
U, sigma, V = U[:, :K], sigma[:K], V[:, :K]
|
||||
|
||||
F = Dr_inv_sqrt[:, None] * U * sigma[None, :]
|
||||
G = Dc_inv_sqrt[:, None] * V * sigma[None, :]
|
||||
|
||||
eigenvalues = sigma ** 2
|
||||
inertia_total = ((P - np.outer(r, c)) ** 2 / np.outer(r, c)).sum()
|
||||
contrib = (c[:, None] * G ** 2) / eigenvalues[None, :]
|
||||
return Mca(F, G, eigenvalues, eigenvalues / inertia_total,
|
||||
pd.DataFrame(contrib, index=Z.columns, columns=[f"Dim{k + 1}" for k in range(K)]))
|
||||
|
||||
|
||||
def select_informed_undersample(F: np.ndarray, outcome: np.ndarray, minority_label: int, majority_label: int,
|
||||
target_ratio: float = 1.0, dims: int | None = None) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""(keep mask, distance to the nearest minority patient): every minority patient and the `target_ratio` x minority
|
||||
majority patients closest to the minority in MCA space."""
|
||||
if dims is not None:
|
||||
F = F[:, :dims]
|
||||
mask_min = outcome == minority_label
|
||||
dist, _ = cKDTree(F[mask_min]).query(F, k=1)
|
||||
mask_maj = outcome == majority_label
|
||||
n_keep_maj = int(round(mask_min.sum() * target_ratio))
|
||||
|
||||
maj_idx = np.where(mask_maj)[0]
|
||||
order = np.argsort(dist[maj_idx])
|
||||
keep_mask = mask_min.copy()
|
||||
keep_mask[maj_idx[order[:n_keep_maj]]] = True
|
||||
return keep_mask, dist
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Stage 03, bootstrapping: the row indices of each resample of the balanced frame, fixed once so every model stage
|
||||
resamples the same rows. Hamilton nodes; the inputs are `balanced_csv` and `bootstrap` (its settings)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival.settings import BootstrapSettings
|
||||
|
||||
|
||||
def balanced_rows(balanced_csv: str) -> int:
|
||||
"""The balanced frame's number of rows (only the first column is read)."""
|
||||
return len(pd.read_csv(balanced_csv, dtype=str, usecols=[0]))
|
||||
|
||||
|
||||
def bootstrap_indices(balanced_rows: int, bootstrap: BootstrapSettings) -> np.ndarray:
|
||||
"""`(n_bootstrap, rows)` indices drawn with replacement, reproducible from `random_state`."""
|
||||
rng = np.random.default_rng(bootstrap.random_state)
|
||||
out = np.empty((bootstrap.n_bootstrap, balanced_rows), dtype=np.int64)
|
||||
for b in range(bootstrap.n_bootstrap):
|
||||
out[b] = rng.integers(0, balanced_rows, size=balanced_rows)
|
||||
return out
|
||||
|
||||
|
||||
def bootstrap_metadata(balanced_csv: str, balanced_rows: int, bootstrap: BootstrapSettings) -> dict:
|
||||
return {"source_csv": balanced_csv, "n_filas": int(balanced_rows), "n_bootstrap": int(bootstrap.n_bootstrap),
|
||||
"random_state": int(bootstrap.random_state)}
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Stage 02b, categorization: groups the balanced cohort's age and tumor size into ordinal groups where the patients'
|
||||
composition changes, and proposes alternatives (other covariate blocks, fixed clinical cuts, quantiles).
|
||||
|
||||
Each public function is a Hamilton node and each parameter is the node of that name; it continues `balancing.py`
|
||||
(`balanced_frame`, `valid_frame`, `keep_mask`, `labels`, `age_column`, `age_levels`, `age_midpoints`) and takes
|
||||
`categorization` (its settings) as an input. The segmentation itself is in `categorization_stats.py`.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from matplotlib.figure import Figure
|
||||
|
||||
from models.cama.seer_survival import categorization_stats as stats
|
||||
from models.cama.seer_survival.columns import find_col
|
||||
from models.cama.seer_survival.settings import CategorizationSettings
|
||||
|
||||
AGE_GROUP, TUMOR_GROUP, TUMOR_BIN = "Age_group", "Tumor_group", "Tumor_bin"
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class CutDiagnostics:
|
||||
"""What the final cuts of an axis do: sensitivity/specificity per cut, the overlap of deaths and survivors, and
|
||||
their distribution along the axis."""
|
||||
|
||||
table: pd.DataFrame
|
||||
overlap: float
|
||||
figure: Figure
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Proposals:
|
||||
table: pd.DataFrame # row_id and one `<Age|Tumor>_group__<proposal>` column per proposal and axis
|
||||
summary: pd.DataFrame
|
||||
|
||||
|
||||
def min_segment_size(balanced_frame: pd.DataFrame, categorization: CategorizationSettings) -> int:
|
||||
"""The smallest segment, as a share of the balanced cohort."""
|
||||
return max(categorization.min_n_floor, round(categorization.min_n_pct * len(balanced_frame)))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- age
|
||||
|
||||
def age_axis(balanced_frame: pd.DataFrame, age_column: str, age_levels: list[str],
|
||||
age_midpoints: list[float]) -> stats.Axis:
|
||||
return stats.Axis.of(balanced_frame, age_column, age_levels, age_midpoints, "corte_edad")
|
||||
|
||||
|
||||
def age_configurations(balanced_frame: pd.DataFrame, age_axis: stats.Axis, labels: dict,
|
||||
categorization: CategorizationSettings,
|
||||
min_segment_size: int) -> dict[str, stats.Segmentation]:
|
||||
"""The segmentation of age under every combination of covariate blocks."""
|
||||
s = categorization
|
||||
blocks = {"outcome": ["Outcome"], "biología": list(s.biology), "tratamiento": list(s.treatment),
|
||||
"demográfico": list(s.demographic)}
|
||||
return stats.segment_configurations(balanced_frame, age_axis, blocks, labels, s, min_segment_size)
|
||||
|
||||
|
||||
def age_comparison(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis) -> pd.DataFrame:
|
||||
return stats.comparison_table(age_configurations, age_axis)
|
||||
|
||||
|
||||
def age_group_map(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis,
|
||||
categorization: CategorizationSettings) -> dict[str, str]:
|
||||
"""Each age level -> its group, by the final configuration's segments."""
|
||||
return stats.level_to_group(age_configurations[categorization.age_final].segments, list(age_axis.levels))
|
||||
|
||||
|
||||
def age_grouped(balanced_frame: pd.DataFrame, age_column: str, age_group_map: dict[str, str]) -> pd.DataFrame:
|
||||
df = balanced_frame.copy()
|
||||
df[AGE_GROUP] = df[age_column].map(age_group_map)
|
||||
return df
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- tumor size
|
||||
|
||||
def tumor_raw_column(labels: dict, balanced_frame: pd.DataFrame) -> str:
|
||||
col = find_col(labels, ["tumor size"])
|
||||
if col is None or col not in balanced_frame.columns:
|
||||
raise ValueError("No se encontró la columna cruda del tamaño tumoral.")
|
||||
return col
|
||||
|
||||
|
||||
def tumor_binned(age_grouped: pd.DataFrame, tumor_raw_column: str,
|
||||
categorization: CategorizationSettings) -> pd.DataFrame:
|
||||
"""The frame with the tumor size in mm (`tumor_mm`) and its ordinal level (`Tumor_bin`)."""
|
||||
s = categorization
|
||||
df = age_grouped.copy()
|
||||
df["tumor_mm"] = df[tumor_raw_column].map(stats.tumor_size_mm)
|
||||
df[TUMOR_BIN] = df["tumor_mm"].map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
|
||||
return df
|
||||
|
||||
|
||||
def tumor_axis(tumor_binned: pd.DataFrame, categorization: CategorizationSettings) -> stats.Axis:
|
||||
levels, mids = stats.tumor_levels(categorization.bin_width_mm, categorization.tumor_cap_mm)
|
||||
return stats.Axis.of(tumor_binned, TUMOR_BIN, levels, mids, "corte_mm")
|
||||
|
||||
|
||||
def tumor_configurations(tumor_binned: pd.DataFrame, tumor_axis: stats.Axis, labels: dict,
|
||||
categorization: CategorizationSettings,
|
||||
min_segment_size: int) -> dict[str, stats.Segmentation]:
|
||||
"""The segmentation of tumor size under every combination of blocks; age (`Age_group`) is one more block."""
|
||||
s = categorization
|
||||
blocks = {"outcome": ["Outcome"], "biología": [b for b in s.biology if b != "Tamano_tumor"],
|
||||
"tratamiento": list(s.treatment), "demográfico": list(s.demographic), "edad": [AGE_GROUP]}
|
||||
return stats.segment_configurations(tumor_binned, tumor_axis, blocks, labels, s, min_segment_size,
|
||||
direct=(AGE_GROUP,))
|
||||
|
||||
|
||||
def tumor_comparison(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis) -> pd.DataFrame:
|
||||
return stats.comparison_table(tumor_configurations, tumor_axis)
|
||||
|
||||
|
||||
def tumor_group_map(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis,
|
||||
categorization: CategorizationSettings) -> dict[str, str]:
|
||||
return stats.level_to_group(tumor_configurations[categorization.tumor_final].segments, list(tumor_axis.levels))
|
||||
|
||||
|
||||
def categorized(tumor_binned: pd.DataFrame, tumor_group_map: dict[str, str]) -> pd.DataFrame:
|
||||
"""The balanced cohort with `Age_group` and `Tumor_group`."""
|
||||
df = tumor_binned.copy()
|
||||
df[TUMOR_GROUP] = df[TUMOR_BIN].map(tumor_group_map)
|
||||
return df
|
||||
|
||||
|
||||
def balanced_final(categorized: pd.DataFrame, categorization: CategorizationSettings) -> pd.DataFrame:
|
||||
"""The preprocessing's final file, read by bootstrapping and modelling: the recoded tumor size is dropped, since
|
||||
`Tumor_group` carries it."""
|
||||
assert TUMOR_GROUP in categorized.columns, "Falta Tumor_group"
|
||||
return categorized.drop(columns=[c for c in categorization.drop_after if c in categorized.columns])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- diagnostics of the final cuts
|
||||
|
||||
def _distribution_figure(df: pd.DataFrame, axis: stats.Axis, known: pd.Series, bounds: list[int], overlap: float,
|
||||
xlabel: str, title: str) -> Figure:
|
||||
fig = Figure(figsize=(11, 3.5))
|
||||
ax = fig.subplots()
|
||||
for label, color in [("Sobrevive", "steelblue"), ("Muerte", "indianred")]:
|
||||
sub = df.loc[known & (df["Outcome_cat"] == label), axis.column]
|
||||
counts = np.array([(sub == l).sum() for l in axis.levels], dtype=float)
|
||||
ax.plot(axis.mids, counts / max(counts.sum(), 1), marker="o", ms=3, label=label, color=color)
|
||||
for b in bounds:
|
||||
ax.axvline((axis.mids[b - 1] + axis.mids[b]) / 2, color="black", lw=1.5, ls="--")
|
||||
ax.set_xlabel(xlabel)
|
||||
ax.set_ylabel("proporción dentro del grupo")
|
||||
ax.set_title(f"{title} (OVL={overlap:.3f}, líneas = cortes finales)", fontsize=10)
|
||||
ax.legend()
|
||||
fig.tight_layout()
|
||||
return fig
|
||||
|
||||
|
||||
def age_diagnostics(categorized: pd.DataFrame, age_axis: stats.Axis, age_configurations: dict,
|
||||
categorization: CategorizationSettings) -> CutDiagnostics:
|
||||
bounds = age_configurations[categorization.age_final].bounds
|
||||
table, overlap, known = stats.sens_spec_table(categorized, age_axis, bounds)
|
||||
return CutDiagnostics(table, overlap, _distribution_figure(
|
||||
categorized, age_axis, known, bounds, overlap, "Edad (punto medio del nivel)", "Distribución de edad por desenlace"))
|
||||
|
||||
|
||||
def tumor_diagnostics(categorized: pd.DataFrame, tumor_axis: stats.Axis, tumor_configurations: dict,
|
||||
categorization: CategorizationSettings) -> CutDiagnostics:
|
||||
bounds = tumor_configurations[categorization.tumor_final].bounds
|
||||
table, overlap, known = stats.sens_spec_table(categorized, tumor_axis, bounds)
|
||||
return CutDiagnostics(table, overlap, _distribution_figure(
|
||||
categorized, tumor_axis, known, bounds, overlap, "Tamaño tumoral en mm (punto medio del nivel)",
|
||||
"Distribución de tamaño tumoral por desenlace"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- proposals and the natural population
|
||||
|
||||
def proposals(categorized: pd.DataFrame, age_column: str, age_axis: stats.Axis, tumor_axis: stats.Axis,
|
||||
age_configurations: dict, tumor_configurations: dict, categorization: CategorizationSettings) -> Proposals:
|
||||
"""Each proposal fixes how age and tumor size are grouped; the modelling stage runs every one and compares them."""
|
||||
s = categorization
|
||||
table = pd.DataFrame({"row_id": np.arange(len(categorized))})
|
||||
rows = []
|
||||
axes = [("edad", "age", "Age_group", age_column, age_axis, age_configurations, list(s.clinical_age), 0.0),
|
||||
("tumor", "tumor", "Tumor_group", TUMOR_BIN, tumor_axis, tumor_configurations, list(s.clinical_tumor), 0.5)]
|
||||
for pid, spec in s.proposals.items():
|
||||
for eje, key, col_base, col_level, axis, configs, clinical, shift in axes:
|
||||
try:
|
||||
segs = stats.resolve_segments(spec[key], axis, configs, clinical, shift, s.k_quantiles)
|
||||
except KeyError:
|
||||
continue
|
||||
levels = list(axis.levels)
|
||||
mapping = stats.level_to_group(segs, levels)
|
||||
col = f"{col_base}__{pid}"
|
||||
table[col] = categorized[col_level].map(mapping).values
|
||||
# mutually exclusive (each level in one group) and exhaustive (every level covered)
|
||||
assert sorted(t for a, b in segs for t in range(a, b)) == list(range(len(levels))), \
|
||||
f"{pid}/{eje}: segmentos no particionan el eje"
|
||||
order = list(dict.fromkeys(mapping.values()))
|
||||
rows.append({"propuesta": pid, "eje": eje, "especificación": spec[key], "K": table[col].nunique(),
|
||||
"grupos": " | ".join(order),
|
||||
"n_por_grupo": table[col].value_counts().reindex(order).dropna().astype(int).tolist(),
|
||||
"filas_sin_grupo": int(table[col].isna().sum())})
|
||||
return Proposals(table, pd.DataFrame(rows))
|
||||
|
||||
|
||||
def natural_population(valid_frame: pd.DataFrame, keep_mask: np.ndarray, age_column: str, age_group_map: dict,
|
||||
tumor_raw_column: str, tumor_group_map: dict, balanced_final: pd.DataFrame,
|
||||
categorization: CategorizationSettings) -> pd.DataFrame:
|
||||
"""Every patient with a known outcome (before the undersampling), grouped like the final file, with `en_balanceado`
|
||||
= 1 where the undersampling kept them. For the AUC diagnosis; no stage consumes it."""
|
||||
s = categorization
|
||||
df = valid_frame.copy()
|
||||
df["en_balanceado"] = np.asarray(keep_mask).astype(int)
|
||||
df[AGE_GROUP] = df[age_column].map(age_group_map)
|
||||
df[TUMOR_GROUP] = (df[tumor_raw_column].map(stats.tumor_size_mm)
|
||||
.map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
|
||||
.map(tumor_group_map))
|
||||
df = df.drop(columns=[c for c in s.drop_after if c in df.columns])
|
||||
assert int(df["en_balanceado"].sum()) == len(balanced_final), "El balanceado y la población natural no coinciden"
|
||||
return df
|
||||
@@ -0,0 +1,361 @@
|
||||
"""The heavy routines of the categorization stage, apart from its Hamilton nodes (`categorization.py`): the Bayesian
|
||||
change-point segmentation of an ordinal axis (age, tumor size), the choice of segments, the effect sizes across
|
||||
boundaries, the overlap and sensitivity/specificity of a cut, and the fixed and quantile cuts. Plain functions with no
|
||||
I/O. Ported from `02_balanceo_categorizacion.py`.
|
||||
|
||||
An ordinal axis is cut into contiguous segments where the composition of the covariates changes. The marginal
|
||||
likelihood of each segment is a Dirichlet-multinomial per covariate; the best segmentation for K segments is a dynamic
|
||||
programme over those segment scores; K is the largest whose smallest boundary effect (mean total variation between
|
||||
neighbouring segments) reaches `threshold`; segments under `min_n` patients are merged into a neighbour.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.special import gammaln
|
||||
|
||||
from models.cama.seer_survival.columns import resolve_column
|
||||
from models.cama.seer_survival.settings import CategorizationSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Axis:
|
||||
"""An ordinal axis: the column holding the level, the levels (low to high), their middles and the patients per level."""
|
||||
|
||||
column: str
|
||||
levels: tuple[str, ...]
|
||||
mids: tuple[float, ...]
|
||||
n_per_level: np.ndarray
|
||||
cut_name: str # name of the cut's column in the tables: "corte_edad", "corte_mm"
|
||||
|
||||
@property
|
||||
def m(self) -> int:
|
||||
return len(self.levels)
|
||||
|
||||
@classmethod
|
||||
def of(cls, df: pd.DataFrame, column: str, levels, mids, cut_name: str) -> "Axis":
|
||||
return cls(column, tuple(levels), tuple(mids), np.array([int((df[column] == l).sum()) for l in levels]),
|
||||
cut_name)
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Segmentation:
|
||||
covariate_cols: dict
|
||||
counts: dict
|
||||
segments: list[tuple[int, int]]
|
||||
bounds: list[int]
|
||||
merge_log: list[str]
|
||||
effect_sizes: pd.DataFrame
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- segmentation
|
||||
|
||||
def build_counts(df, axis_col, levels, covariate_cols, min_count=0) -> dict:
|
||||
"""Per covariate, the level x category table of counts; categories under `min_count` are dropped when two remain."""
|
||||
counts = {}
|
||||
for name, col in covariate_cols.items():
|
||||
tab = pd.crosstab(df[axis_col], df[col]).reindex(index=levels).fillna(0)
|
||||
if min_count > 0:
|
||||
keep = tab.sum(axis=0) >= min_count
|
||||
if keep.sum() >= 2:
|
||||
tab = tab.loc[:, keep]
|
||||
if tab.shape[1] >= 2:
|
||||
counts[name] = tab
|
||||
return counts
|
||||
|
||||
|
||||
def cumulative_counts(counts: dict) -> dict:
|
||||
return {c: np.vstack([np.zeros((1, t.shape[1])), np.cumsum(t.values.astype(float), axis=0)])
|
||||
for c, t in counts.items()}
|
||||
|
||||
|
||||
def segment_logml(cum, u, v, alpha=1.0) -> float:
|
||||
"""Log marginal likelihood of levels [u, v) forming one segment, summed over the covariates."""
|
||||
total = 0.0
|
||||
for c, cm in cum.items():
|
||||
cj = cm[v] - cm[u]
|
||||
J = len(cj)
|
||||
N = cj.sum()
|
||||
total += (gammaln(J * alpha) - gammaln(N + J * alpha) + (gammaln(cj + alpha) - gammaln(alpha)).sum())
|
||||
return total
|
||||
|
||||
|
||||
def precompute_segments(cum, m, alpha=1.0) -> np.ndarray:
|
||||
S = np.full((m + 1, m + 1), -np.inf)
|
||||
for u in range(m):
|
||||
for v in range(u + 1, m + 1):
|
||||
S[u, v] = segment_logml(cum, u, v, alpha)
|
||||
return S
|
||||
|
||||
|
||||
def best_segmentation(S, m, K):
|
||||
"""(boundaries, log score) of the best segmentation into K segments."""
|
||||
V = np.full((K + 1, m + 1), -np.inf)
|
||||
back = np.zeros((K + 1, m + 1), dtype=int)
|
||||
V[1, 1:] = S[0, 1:]
|
||||
for k in range(2, K + 1):
|
||||
for v in range(k, m + 1):
|
||||
cand = V[k - 1, k - 1:v] + S[k - 1:v, v]
|
||||
j = int(np.argmax(cand))
|
||||
V[k, v] = cand[j]
|
||||
back[k, v] = k - 1 + j
|
||||
bounds, v = [], m
|
||||
for k in range(K, 1, -1):
|
||||
u = back[k, v]
|
||||
bounds.append(int(u))
|
||||
v = u
|
||||
return sorted(bounds), V[K, m]
|
||||
|
||||
|
||||
def compute_effect(counts, seg_a, seg_b) -> float:
|
||||
"""Mean over covariates of the total variation between the category mix of two segments."""
|
||||
tvs = []
|
||||
for c, tab in counts.items():
|
||||
mat = tab.values.astype(float)
|
||||
p = mat[seg_a[0]:seg_a[1]].sum(axis=0)
|
||||
p = p / max(p.sum(), 1)
|
||||
q = mat[seg_b[0]:seg_b[1]].sum(axis=0)
|
||||
q = q / max(q.sum(), 1)
|
||||
tvs.append(0.5 * np.abs(p - q).sum())
|
||||
return float(np.mean(tvs))
|
||||
|
||||
|
||||
def choose_K_by_magnitude(S, counts, m, threshold, kmax):
|
||||
"""(K, boundaries) of the largest K up to `kmax` whose smallest boundary effect is >= `threshold`; (1, []) if none."""
|
||||
best_K, best_bounds = 1, []
|
||||
for K in range(2, kmax + 1):
|
||||
bounds, _ = best_segmentation(S, m, K)
|
||||
segs = list(zip([0] + bounds, bounds + [m]))
|
||||
effects = [compute_effect(counts, segs[i], segs[i + 1]) for i in range(len(segs) - 1)]
|
||||
if min(effects) >= threshold:
|
||||
best_K, best_bounds = K, bounds
|
||||
return best_K, best_bounds
|
||||
|
||||
|
||||
def fix_small_segments(counts, n_per_level, bounds, m, min_n):
|
||||
"""Merges each segment under `min_n` patients into the neighbour whose mix differs least; (segments, log)."""
|
||||
segments = list(zip([0] + bounds, bounds + [m]))
|
||||
log = []
|
||||
while len(segments) > 1:
|
||||
sizes = [n_per_level[a:b].sum() for a, b in segments]
|
||||
below = [i for i, s in enumerate(sizes) if s < min_n]
|
||||
if not below:
|
||||
break
|
||||
i = below[0]
|
||||
effects = [compute_effect(counts, segments[k], segments[k + 1]) for k in range(len(segments) - 1)]
|
||||
if i == 0:
|
||||
j = 0
|
||||
elif i == len(segments) - 1:
|
||||
j = i - 1
|
||||
else:
|
||||
j = i - 1 if effects[i - 1] <= effects[i] else i
|
||||
log.append(f" Fusionando por tamaño insuficiente: segmentos {j} y {j + 1} (n={sizes[i]:.0f} < {min_n})")
|
||||
segments = segments[:j] + [(segments[j][0], segments[j + 1][1])] + segments[j + 2:]
|
||||
return segments, log
|
||||
|
||||
|
||||
def boundary_effect_sizes(counts, bounds, m, levels) -> pd.DataFrame:
|
||||
"""One row per boundary: between which levels, the mean and max change, and the covariate that changes most."""
|
||||
segs = list(zip([0] + list(bounds), list(bounds) + [m]))
|
||||
rows = []
|
||||
for i in range(len(segs) - 1):
|
||||
(u1, v1), (u2, v2) = segs[i], segs[i + 1]
|
||||
tvs = {}
|
||||
for c, tab in counts.items():
|
||||
mat = tab.values.astype(float)
|
||||
p = mat[u1:v1].sum(axis=0)
|
||||
p = p / max(p.sum(), 1)
|
||||
q = mat[u2:v2].sum(axis=0)
|
||||
q = q / max(q.sum(), 1)
|
||||
tvs[c] = 0.5 * np.abs(p - q).sum()
|
||||
rows.append({"entre": f"{levels[v1 - 1]} | {levels[v1]}",
|
||||
"cambio_medio": float(np.mean(list(tvs.values()))),
|
||||
"cambio_max": float(np.max(list(tvs.values()))),
|
||||
"covariable_que_mas_cambia": max(tvs, key=tvs.get)})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def segment(df: pd.DataFrame, axis: Axis, use_list, labels: dict, s: CategorizationSettings, min_n: int,
|
||||
direct=()) -> Segmentation:
|
||||
"""Segments `axis` by the composition of the covariates in `use_list` over the frame's patients."""
|
||||
cols = {}
|
||||
for name in use_list:
|
||||
col = resolve_column(df, name, labels, s.candidate_keywords, direct)
|
||||
if col is not None and col in df.columns:
|
||||
cols[name] = col
|
||||
counts = build_counts(df, axis.column, list(axis.levels), cols, min_count=s.min_count)
|
||||
S = precompute_segments(cumulative_counts(counts), axis.m, alpha=s.alpha)
|
||||
_, b1 = choose_K_by_magnitude(S, counts, axis.m, threshold=s.threshold, kmax=s.kmax)
|
||||
segments, log = fix_small_segments(counts, axis.n_per_level, b1, axis.m, min_n=min_n)
|
||||
bounds = [seg[1] for seg in segments[:-1]]
|
||||
return Segmentation(cols, counts, segments, bounds, log,
|
||||
boundary_effect_sizes(counts, bounds, axis.m, list(axis.levels)))
|
||||
|
||||
|
||||
def configurations(blocks: dict) -> dict[str, list[str]]:
|
||||
"""Every non-empty combination of the blocks: "Solo outcome", "Outcome + biología", ... -> its covariates."""
|
||||
out = {}
|
||||
for r in range(1, len(blocks) + 1):
|
||||
for combo in itertools.combinations(blocks, r):
|
||||
label = f"Solo {combo[0]}" if r == 1 else " + ".join(combo)
|
||||
out[label[0].upper() + label[1:]] = sum((blocks[b] for b in combo), [])
|
||||
return out
|
||||
|
||||
|
||||
def segment_configurations(df, axis, blocks, labels, s, min_n, direct=()) -> dict[str, Segmentation]:
|
||||
return {label: segment(df, axis, use, labels, s, min_n, direct) for label, use in configurations(blocks).items()}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- tables and cuts
|
||||
|
||||
def _cut(axis: Axis, b: int) -> float:
|
||||
return round((axis.mids[b - 1] + axis.mids[b]) / 2, 1)
|
||||
|
||||
|
||||
def boundary_table(result: Segmentation, label: str, axis: Axis) -> pd.DataFrame:
|
||||
cols = ["configuración", axis.cut_name, "entre_niveles", "n_izquierda", "n_derecha", "cambio_medio"]
|
||||
if not result.bounds:
|
||||
return pd.DataFrame(columns=cols)
|
||||
effect = result.effect_sizes.reset_index(drop=True)
|
||||
rows = []
|
||||
for i, b in enumerate(result.bounds):
|
||||
segs = result.segments
|
||||
rows.append({"configuración": label, axis.cut_name: _cut(axis, b),
|
||||
"entre_niveles": f"{axis.levels[b - 1]} | {axis.levels[b]}",
|
||||
"n_izquierda": int(axis.n_per_level[segs[i][0]:segs[i][1]].sum()),
|
||||
"n_derecha": int(axis.n_per_level[segs[i + 1][0]:segs[i + 1][1]].sum()),
|
||||
"cambio_medio": round(float(effect.loc[i, "cambio_medio"]), 3)})
|
||||
return pd.DataFrame(rows, columns=cols)
|
||||
|
||||
|
||||
def segmentation_summary(result: Segmentation, label: str, axis: Axis) -> dict:
|
||||
groups = [f"{axis.levels[a]} a {axis.levels[b - 1]}" if b - a > 1 else axis.levels[a] for a, b in result.segments]
|
||||
sizes = [int(axis.n_per_level[a:b].sum()) for a, b in result.segments]
|
||||
effects = result.effect_sizes["cambio_medio"].tolist() if len(result.bounds) else []
|
||||
return {"configuración": label, "n_covariables": len(result.covariate_cols),
|
||||
"K (nº de grupos)": len(result.segments), axis.cut_name.replace("corte_", "cortes_"):
|
||||
boundary_table(result, label, axis)[axis.cut_name].tolist(),
|
||||
"grupos": " | ".join(groups), "n por grupo": sizes,
|
||||
"efecto mín.": round(min(effects), 3) if effects else None,
|
||||
"efecto máx.": round(max(effects), 3) if effects else None}
|
||||
|
||||
|
||||
def comparison_table(results: dict[str, Segmentation], axis: Axis) -> pd.DataFrame:
|
||||
return pd.DataFrame([segmentation_summary(r, label, axis) for label, r in results.items()])
|
||||
|
||||
|
||||
def level_to_group(segments, levels) -> dict[str, str]:
|
||||
"""Each level -> the label of its segment: the level itself, or "first a last"."""
|
||||
out = {}
|
||||
for a, b in segments:
|
||||
label = levels[a] if b - a == 1 else f"{levels[a]} a {levels[b - 1]}"
|
||||
for t in range(a, b):
|
||||
out[levels[t]] = label
|
||||
return out
|
||||
|
||||
|
||||
def overlap_coefficient(values_a: pd.Series, values_b: pd.Series, levels) -> float:
|
||||
"""Overlap of the level distributions of two groups (1 = identical, 0 = disjoint)."""
|
||||
pa = np.array([(values_a == l).sum() for l in levels], dtype=float)
|
||||
pb = np.array([(values_b == l).sum() for l in levels], dtype=float)
|
||||
pa = pa / max(pa.sum(), 1)
|
||||
pb = pb / max(pb.sum(), 1)
|
||||
return float(np.minimum(pa, pb).sum())
|
||||
|
||||
|
||||
def sens_spec_at_cut(level_index: np.ndarray, is_death: np.ndarray, b: int) -> dict:
|
||||
"""Sensitivity and specificity of calling "high risk" the side of boundary `b` with the higher death rate."""
|
||||
high = level_index >= b
|
||||
rate_high = is_death[high].mean() if high.any() else np.nan
|
||||
rate_low = is_death[~high].mean() if (~high).any() else np.nan
|
||||
high_is_positive = rate_high >= rate_low
|
||||
positive = high if high_is_positive else ~high
|
||||
tp = int((positive & is_death).sum())
|
||||
fn = int((~positive & is_death).sum())
|
||||
tn = int((~positive & ~is_death).sum())
|
||||
fp = int((positive & ~is_death).sum())
|
||||
sens = tp / (tp + fn) if (tp + fn) else np.nan
|
||||
spec = tn / (tn + fp) if (tn + fp) else np.nan
|
||||
return {"lado_alto_riesgo": "arriba del corte" if high_is_positive else "abajo del corte",
|
||||
"tasa_muerte_abajo": round(float(rate_low), 3) if pd.notna(rate_low) else np.nan,
|
||||
"tasa_muerte_arriba": round(float(rate_high), 3) if pd.notna(rate_high) else np.nan,
|
||||
"sensibilidad": round(sens, 3) if pd.notna(sens) else np.nan,
|
||||
"especificidad": round(spec, 3) if pd.notna(spec) else np.nan}
|
||||
|
||||
|
||||
def sens_spec_table(df: pd.DataFrame, axis: Axis, bounds: list[int]) -> tuple[pd.DataFrame, float, pd.Series]:
|
||||
"""(table by final cut, overlap coefficient of deaths vs survivors, mask of the patients used): the patients with a
|
||||
known outcome and a level on the axis."""
|
||||
known = (df["Outcome_cat"] != "Desconocido") & df[axis.column].notna()
|
||||
is_death = (df.loc[known, "Outcome_cat"] == "Muerte").to_numpy()
|
||||
pos = {l: i for i, l in enumerate(axis.levels)}
|
||||
idx = df.loc[known, axis.column].map(pos).to_numpy()
|
||||
ovl = overlap_coefficient(df.loc[known & (df["Outcome_cat"] == "Muerte"), axis.column],
|
||||
df.loc[known & (df["Outcome_cat"] == "Sobrevive"), axis.column], axis.levels)
|
||||
cols = [axis.cut_name, "entre_niveles", "tasa_muerte_abajo", "tasa_muerte_arriba", "lado_alto_riesgo",
|
||||
"sensibilidad", "especificidad"]
|
||||
rows = []
|
||||
for b in bounds:
|
||||
r = sens_spec_at_cut(idx, is_death, b)
|
||||
r[axis.cut_name] = _cut(axis, b)
|
||||
r["entre_niveles"] = f"{axis.levels[b - 1]} | {axis.levels[b]}"
|
||||
rows.append(r)
|
||||
return (pd.DataFrame(rows)[cols] if rows else pd.DataFrame(columns=cols)), ovl, known
|
||||
|
||||
|
||||
def tumor_size_mm(v) -> float:
|
||||
"""A tumor size in mm from SEER's code: 1..899 is the size; 0, 9xx and anything else is unknown."""
|
||||
import re
|
||||
if not isinstance(v, str):
|
||||
return np.nan
|
||||
s = v.strip()
|
||||
if not re.match(r"^\d{1,3}$", s):
|
||||
return np.nan
|
||||
mm = int(s)
|
||||
if mm == 0 or mm >= 900:
|
||||
return np.nan
|
||||
return float(mm)
|
||||
|
||||
|
||||
def tumor_bin_label(mm: float, width: int, cap: int):
|
||||
if pd.isna(mm):
|
||||
return np.nan
|
||||
if mm > cap:
|
||||
return f">{cap} mm"
|
||||
lo = int((mm - 1) // width) * width + 1
|
||||
return f"{lo:03d}-{lo + width - 1:03d} mm"
|
||||
|
||||
|
||||
def tumor_levels(width: int, cap: int) -> tuple[list[str], list[float]]:
|
||||
"""The ordinal levels of tumor size ("001-005 mm", ..., ">100 mm") and their middles."""
|
||||
n_bins = cap // width
|
||||
levels = [f"{1 + i * width:03d}-{(i + 1) * width:03d} mm" for i in range(n_bins)] + [f">{cap} mm"]
|
||||
mids = [1 + i * width + (width - 1) / 2 for i in range(n_bins)] + [cap + width / 2]
|
||||
return levels, mids
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- proposals
|
||||
|
||||
def segments_from_bounds(bounds, n_levels) -> list[tuple[int, int]]:
|
||||
cuts = [0] + sorted(set(int(b) for b in bounds if 0 < b < n_levels)) + [n_levels]
|
||||
return list(zip(cuts[:-1], cuts[1:]))
|
||||
|
||||
|
||||
def quantile_bounds(n_per_level, K) -> list[int]:
|
||||
cum = np.cumsum(n_per_level)
|
||||
tot = cum[-1]
|
||||
return sorted({int(np.searchsorted(cum, tot * q)) + 1 for q in np.linspace(0, 1, K + 1)[1:-1]})
|
||||
|
||||
|
||||
def resolve_segments(spec: str, axis: Axis, configs: dict[str, Segmentation], clinical: list, shift: float,
|
||||
k_quantiles: int) -> list[tuple[int, int]]:
|
||||
"""The segments a proposal's spec means on an axis: fixed clinical cuts, quantiles, or a configuration's own."""
|
||||
if spec == "clinico":
|
||||
return segments_from_bounds([int(np.searchsorted(axis.mids, thr + shift)) for thr in clinical], axis.m)
|
||||
if spec == "cuantiles":
|
||||
return segments_from_bounds(quantile_bounds(axis.n_per_level, k_quantiles), axis.m)
|
||||
if spec not in configs:
|
||||
raise KeyError(f"configuración '{spec}' no existe")
|
||||
return configs[spec].segments
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Finding a covariate's column: by its recoded `<name>_cat` column or, failing that, by keywords in the column's label.
|
||||
Plain functions shared by the balancing and categorization stages (not Hamilton nodes)."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def find_col(labels: dict, keywords, exclude=()) -> str | None:
|
||||
"""The first column whose lower-cased label has any of `keywords` and none of `exclude`."""
|
||||
for col, desc in labels.items():
|
||||
d = str(desc).lower()
|
||||
if any(k in d for k in keywords) and not any(e in d for e in exclude):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
def resolve_column(df: pd.DataFrame, name: str, labels: dict, candidate_keywords: dict, direct=()) -> str | None:
|
||||
"""`<name>_cat` if the frame has it, a `direct` name that is itself a column (e.g. `Age_group`), else the column
|
||||
found by the covariate's keywords; None when there is none."""
|
||||
if name in direct:
|
||||
return name if name in df.columns else None
|
||||
cat_col = f"{name}_cat"
|
||||
if cat_col in df.columns:
|
||||
return cat_col
|
||||
kw = candidate_keywords.get(name, {"include": [], "exclude": []})
|
||||
col = find_col(labels, kw["include"], kw["exclude"])
|
||||
return col if col in df.columns else None
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Stage 01, depuration: drops the redundant categorical variables of the recoded SEER frame.
|
||||
|
||||
A removes duplicates (Theil's U both ways), B derived variables (U one way) and C nested ones (GVIF); the thresholds
|
||||
are calibrated from the data and reported. Each public function is a Hamilton node and each parameter is the node of
|
||||
that name; the inputs are `recoded_csv`, `mapping_json`, `depuration` (its settings) and `generated_at`. The heavy
|
||||
statistics live in `depuration_stats.py`; `run.py` holds the driver and writes the files.
|
||||
"""
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import depuration_stats as stats
|
||||
from models.cama.seer_survival.settings import DepurationSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Elimination:
|
||||
dropped: pd.DataFrame # variable, paso, motivo, a_favor_de
|
||||
kept: tuple[str, ...]
|
||||
raw_sources: tuple[str, ...] # raw SEER columns of the dropped variables, dropped with them
|
||||
|
||||
|
||||
def recoded(recoded_csv: str) -> pd.DataFrame:
|
||||
return pd.read_csv(recoded_csv, dtype=str)
|
||||
|
||||
|
||||
def column_map(mapping_json: str) -> dict:
|
||||
"""Recoded variable -> its raw SEER column; empty when the file isn't there."""
|
||||
path = Path(mapping_json)
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
|
||||
|
||||
def analysis_frame(recoded: pd.DataFrame, depuration: DepurationSettings) -> pd.DataFrame:
|
||||
"""The `_cat` columns (and the project's groupings) with unknowns labelled, minus those with a single value."""
|
||||
s = depuration
|
||||
cols = [c for c in recoded.columns if c.endswith("_cat") and c not in s.exclude]
|
||||
for c in (*s.auto_extra, *s.extra_cols):
|
||||
if c in recoded.columns and c not in cols and c not in s.exclude:
|
||||
cols.append(c)
|
||||
frame = recoded[cols].fillna(s.unknown_label)
|
||||
return frame[[c for c in cols if frame[c].nunique() >= 2]]
|
||||
|
||||
|
||||
def analysis_columns(analysis_frame: pd.DataFrame) -> list[str]:
|
||||
return list(analysis_frame.columns)
|
||||
|
||||
|
||||
def calibration(analysis_frame: pd.DataFrame, analysis_columns: list[str], depuration: DepurationSettings,
|
||||
generated_at: str) -> stats.Calibration:
|
||||
"""Suggested thresholds and how stable the elimination is to them. Reports only: it changes nothing."""
|
||||
return stats.calibrate(analysis_frame, analysis_columns, depuration, generated_at)
|
||||
|
||||
|
||||
def thresholds(calibration: stats.Calibration, depuration: DepurationSettings) -> stats.Thresholds:
|
||||
return stats.thresholds_in_use(calibration, depuration)
|
||||
|
||||
|
||||
def calibration_report(calibration: stats.Calibration, thresholds: stats.Thresholds) -> dict:
|
||||
"""The calibration's JSON report, with the thresholds the elimination used."""
|
||||
return {**calibration.report, "umbrales_en_uso": {
|
||||
"DUP_U": thresholds.dup_u, "U_REDUND": thresholds.u_redund, "GVIF_DROP": thresholds.gvif_drop,
|
||||
"CLUSTER_METODO": thresholds.cluster_method, "CLUSTER_CORTE": thresholds.cluster_cut,
|
||||
"PAR_R_MIN": thresholds.pair_r_min, "AUTO": bool(thresholds.auto)}}
|
||||
|
||||
|
||||
def elimination(analysis_frame: pd.DataFrame, analysis_columns: list[str], thresholds: stats.Thresholds,
|
||||
depuration: DepurationSettings, recoded: pd.DataFrame, column_map: dict) -> Elimination:
|
||||
dropped = stats.eliminate(analysis_frame, analysis_columns, thresholds, depuration)
|
||||
names = list(dropped["variable"])
|
||||
kept = tuple(c for c in analysis_columns if c not in names)
|
||||
raw = ()
|
||||
if depuration.drop_raw_sources:
|
||||
raw = tuple(column_map[v] for v in names if v in column_map and column_map[v] in recoded.columns)
|
||||
return Elimination(dropped, kept, raw)
|
||||
|
||||
|
||||
def depurated(recoded: pd.DataFrame, elimination: Elimination) -> pd.DataFrame:
|
||||
"""The recoded frame without the dropped variables and their raw columns."""
|
||||
return recoded.drop(columns=[*elimination.dropped["variable"], *elimination.raw_sources])
|
||||
|
||||
|
||||
def kept_variables(elimination: Elimination, thresholds: stats.Thresholds, recoded_csv: str) -> dict:
|
||||
return {"entrada": recoded_csv, "conservadas": list(elimination.kept),
|
||||
"eliminadas": list(elimination.dropped["variable"]), "crudas_eliminadas": list(elimination.raw_sources),
|
||||
"umbrales": {"DUP_U": thresholds.dup_u, "U_REDUND": thresholds.u_redund,
|
||||
"GVIF_DROP": thresholds.gvif_drop}}
|
||||
@@ -0,0 +1,469 @@
|
||||
"""The heavy routines of the depuration stage, apart from its Hamilton nodes (`depuration.py`): Theil's U, GVIF, the
|
||||
calibration of the thresholds (chance floor, natural gap, sensitivity sweeps, clustering) and the A/B/C elimination.
|
||||
|
||||
Plain functions with no I/O and no module state, so they run alone and on a Dask worker. Ported from
|
||||
`01_depuracion.py`; the report keys keep the script's Spanish names because downstream files read them.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
|
||||
from scipy.spatial.distance import squareform
|
||||
from sklearn.metrics import silhouette_score
|
||||
|
||||
from models.cama.seer_survival.settings import DepurationSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Thresholds:
|
||||
"""The thresholds in use by the elimination (the configured ones, or the calibration's when `thresholds_auto`)."""
|
||||
|
||||
dup_u: float
|
||||
u_redund: float
|
||||
gvif_drop: float
|
||||
cluster_method: str
|
||||
cluster_cut: float
|
||||
pair_r_min: float
|
||||
auto: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class Calibration:
|
||||
"""What the calibration found: its tables and report, and the suggestions the thresholds may adopt."""
|
||||
|
||||
pairs_u: pd.DataFrame
|
||||
cluster_cut_table: pd.DataFrame # empty when the clustering could not be calibrated
|
||||
report: dict
|
||||
summary: list[dict]
|
||||
u_suggestion: dict
|
||||
dup_u_suggested: float
|
||||
gvif_drop_suggested: float
|
||||
cluster_method_suggested: str
|
||||
config_eliminations: dict
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Theil's U and GVIF
|
||||
|
||||
def theil_u_matrix(d: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
|
||||
"""U(row | column): the share of the row variable's entropy that the column variable explains."""
|
||||
U = pd.DataFrame(np.nan, index=columns, columns=columns)
|
||||
H = {}
|
||||
for c in columns:
|
||||
p = d[c].value_counts(normalize=True).values
|
||||
H[c] = float(-(p * np.log(p)).sum())
|
||||
for a, b in itertools.combinations(columns, 2):
|
||||
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
|
||||
pxy /= pxy.sum()
|
||||
nz = pxy[pxy > 0]
|
||||
hxy = float(-(nz * np.log(nz)).sum())
|
||||
mi = H[a] + H[b] - hxy
|
||||
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
|
||||
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
|
||||
return U
|
||||
|
||||
|
||||
def design(d: pd.DataFrame, columns: list[str]):
|
||||
"""Indicator blocks, one per variable, dropping each one's most frequent category and constant columns."""
|
||||
blocks = {}
|
||||
for c in columns:
|
||||
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
|
||||
ind = ind.drop(columns=ind.sum().idxmax())
|
||||
ind = ind.loc[:, ind.std() > 0]
|
||||
if ind.shape[1] > 0:
|
||||
blocks[c] = ind
|
||||
X = pd.concat(blocks.values(), axis=1)
|
||||
return X, blocks
|
||||
|
||||
|
||||
def gvif_table(d: pd.DataFrame, columns: list[str]):
|
||||
"""(table, []) with each variable's GVIF and `GVIF^(1/2df)`; or (None, candidates) when the design is singular,
|
||||
the candidates being the variables that are an exact combination of the others, fewest categories first."""
|
||||
X, blocks = design(d, columns)
|
||||
R = np.corrcoef(X.values, rowvar=False)
|
||||
pos = {n: i for i, n in enumerate(X.columns)}
|
||||
s, ld = np.linalg.slogdet(R)
|
||||
if not (s > 0 and np.isfinite(ld) and ld > -30):
|
||||
cand = []
|
||||
for c, b in blocks.items():
|
||||
others = [x for x in X.columns if x not in b.columns]
|
||||
A = np.column_stack([X[others].values, np.ones(len(X))])
|
||||
for x in b.columns:
|
||||
y = X[x].values
|
||||
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
|
||||
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
|
||||
if r2 >= 0.9999:
|
||||
cand.append((b.shape[1], c))
|
||||
break
|
||||
return None, sorted(cand)
|
||||
rows = []
|
||||
for c, b in blocks.items():
|
||||
idx = [pos[n] for n in b.columns]
|
||||
rest = [i for i in range(len(pos)) if i not in set(idx)]
|
||||
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
|
||||
s2, l2 = np.linalg.slogdet(R[np.ix_(rest, rest)]) if rest else (1, 0.0)
|
||||
gv = float(np.exp(l1 + l2 - ld))
|
||||
rows.append({"variable": c, "gl": len(idx), "GVIF": gv, "GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
|
||||
return pd.DataFrame(rows).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
|
||||
|
||||
|
||||
def _entropy(p: np.ndarray) -> float:
|
||||
p = p[p > 0]
|
||||
return float(-(p * np.log(p)).sum())
|
||||
|
||||
|
||||
def info_pair(cx: np.ndarray, cy: np.ndarray, kx: int, ky: int) -> dict:
|
||||
"""Entropies, mutual information and the accuracy of predicting each variable from the other, from factor codes."""
|
||||
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
|
||||
n = j.sum()
|
||||
px = j.sum(1) / n
|
||||
py = j.sum(0) / n
|
||||
hxy = _entropy((j / n).ravel())
|
||||
hx, hy = _entropy(px), _entropy(py)
|
||||
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
|
||||
base_x=px.max(), base_y=py.max())
|
||||
|
||||
|
||||
def loser(a: str, b: str, protected, prefer, key) -> tuple[str, str] | None:
|
||||
"""(dropped, kept) of two redundant variables: a protected one is kept, then a preferred one, then the one with
|
||||
more unknowns, more categories, later position (`key`). None when both are protected."""
|
||||
if a in protected and b in protected:
|
||||
return None
|
||||
if a in protected:
|
||||
return b, a
|
||||
if b in protected:
|
||||
return a, b
|
||||
if a in prefer and b not in prefer:
|
||||
return b, a
|
||||
if b in prefer and a not in prefer:
|
||||
return a, b
|
||||
return (a, b) if key(a) > key(b) else (b, a)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- calibration
|
||||
|
||||
def suggest_u(pairs_u: pd.DataFrame, chance_ceiling: float, s: DepurationSettings,
|
||||
gap_from: float | None = None, gap_min: float | None = None) -> dict:
|
||||
"""The U_REDUND suggestion: the natural gap among the pairs' U, floored by chance, else the conventional value."""
|
||||
gap_from = s.u_gap_from if gap_from is None else gap_from
|
||||
gap_min = s.u_gap_min if gap_min is None else gap_min
|
||||
v = np.sort(pairs_u["U(X|Y)"].dropna().round(4).unique())[::-1]
|
||||
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
|
||||
best = None
|
||||
for i in range(len(v) - 1):
|
||||
if v[i] >= gap_from and (best is None or v[i] - v[i + 1] > best[0]):
|
||||
best = (v[i] - v[i + 1], v[i], v[i + 1])
|
||||
if best is not None and best[0] >= gap_min:
|
||||
mid = float(np.clip((best[1] + best[2]) / 2, *s.u_plausible))
|
||||
out.update(metodo="brecha natural", U=mid, brecha=round(float(best[0]), 3), borde_sup=round(float(best[1]), 3),
|
||||
borde_inf=round(float(best[2]), 3), confianza="alta")
|
||||
else:
|
||||
out["U"] = s.u_conventional
|
||||
out["motivo"] = (("no hay pares con U >= %.2f" % gap_from) if best is None
|
||||
else ("la mayor brecha (%.3f) < %.2f" % (best[0], gap_min)))
|
||||
floor = s.k_azar * chance_ceiling
|
||||
if out["U"] < floor:
|
||||
out["U"] = float(min(floor, 0.99))
|
||||
out["metodo"] += " + piso por azar"
|
||||
out["confianza"] = "revisar"
|
||||
out["U"] = round(float(out["U"]), 2)
|
||||
return out
|
||||
|
||||
|
||||
class RedundancyScreen:
|
||||
"""Steps A, B and C on one frame at any thresholds, caching U matrices and GVIF tables by the active columns.
|
||||
The calibration replays the elimination many times, so it uses the fast factor-code U."""
|
||||
|
||||
def __init__(self, frame: pd.DataFrame, columns: list[str], codes: dict, kcat: dict, s: DepurationSettings):
|
||||
self.frame, self.columns, self.codes, self.kcat, self.s = frame, columns, codes, kcat, s
|
||||
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
|
||||
ncat = {c: int(frame[c].nunique()) for c in columns}
|
||||
order = {c: i for i, c in enumerate(columns)}
|
||||
self._key = lambda c: (pct_unknown[c], ncat[c], order[c])
|
||||
self._u, self._g = {}, {}
|
||||
|
||||
def u_matrix(self, cols_t: tuple) -> pd.DataFrame:
|
||||
if cols_t not in self._u:
|
||||
M = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
|
||||
for a, b in itertools.combinations(cols_t, 2):
|
||||
ip = info_pair(self.codes[a], self.codes[b], self.kcat[a], self.kcat[b])
|
||||
M.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
|
||||
M.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
|
||||
self._u[cols_t] = M
|
||||
return self._u[cols_t]
|
||||
|
||||
def gvif(self, cols_t: tuple):
|
||||
if cols_t not in self._g:
|
||||
self._g[cols_t] = gvif_table(self.frame, list(cols_t))
|
||||
return self._g[cols_t]
|
||||
|
||||
def run(self, dup_u: float, u_redund: float, gvif_drop: float) -> tuple[dict, list[str]]:
|
||||
"""({dropped variable: step}, active variables)."""
|
||||
s = self.s
|
||||
active, out = list(self.columns), {}
|
||||
U = self.u_matrix(tuple(active)) # A
|
||||
for a, b in itertools.combinations(list(active), 2):
|
||||
if a not in active or b not in active:
|
||||
continue
|
||||
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
|
||||
r = loser(a, b, s.protected, s.prefer, self._key)
|
||||
if r:
|
||||
active.remove(r[0])
|
||||
out[r[0]] = "A"
|
||||
U = self.u_matrix(tuple(active)) # B
|
||||
cand = []
|
||||
for x in active:
|
||||
for y in active:
|
||||
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund:
|
||||
cand.append((U.loc[x, y], x, y))
|
||||
for u, x, y in sorted(cand, reverse=True):
|
||||
if x in active and y in active and x not in s.protected and x not in s.prefer:
|
||||
active.remove(x)
|
||||
out[x] = "B"
|
||||
for _ in range(s.max_iter_gvif): # C
|
||||
if len(active) < 3:
|
||||
break
|
||||
table, exact = self.gvif(tuple(active))
|
||||
if table is None:
|
||||
ex = [c for _, c in exact if c not in s.protected]
|
||||
if not ex:
|
||||
break
|
||||
active.remove(ex[0])
|
||||
out[ex[0]] = "C"
|
||||
continue
|
||||
cd = table[(table["GVIF_ajustado"] >= gvif_drop) & (~table["variable"].isin(s.protected))]
|
||||
if cd.empty:
|
||||
break
|
||||
v = cd.iloc[0]["variable"]
|
||||
active.remove(v)
|
||||
out[v] = "C"
|
||||
return out, active
|
||||
|
||||
|
||||
def _labels(d: dict) -> str:
|
||||
return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
|
||||
|
||||
|
||||
def _category_matrix(d, columns, min_n, max_cat, warnings):
|
||||
X = pd.get_dummies(d[columns], prefix_sep="=", dtype=np.float32)
|
||||
total = X.sum()
|
||||
X = X.loc[:, (total >= min_n) & (total <= len(X) - min_n)]
|
||||
if X.shape[1] > max_cat:
|
||||
X = X[X.sum().sort_values(ascending=False).index[:max_cat]]
|
||||
warnings.append(f"demasiadas categorías para el clustering: se usan las {max_cat} más frecuentes.")
|
||||
return X
|
||||
|
||||
|
||||
def calibrate(frame: pd.DataFrame, columns: list[str], s: DepurationSettings, generated_at: str) -> Calibration:
|
||||
"""Suggests the thresholds from the data (chance floor and natural gap of U, GVIF margin, clustering linkage and
|
||||
cut) and reports how stable the elimination is to them. It never changes the frame."""
|
||||
rng = np.random.default_rng(s.seed)
|
||||
warnings: list[str] = []
|
||||
report = {"fecha": generated_at, "advertencias": warnings, "parametros": {
|
||||
"NULL_PERM": s.null_perm, "K_AZAR": s.k_azar, "U_CONVENCIONAL": s.u_conventional, "U_GAP_DESDE": s.u_gap_from,
|
||||
"U_GAP_MIN_BRECHA": s.u_gap_min, "U_RANGO_PLAUSIBLE": list(s.u_plausible), "VIF_CORTE": s.vif_cut,
|
||||
"R_GRANDE": s.r_large, "MIN_N_CAT": s.min_n_cat, "SEMILLA": s.seed}}
|
||||
if len(columns) < 2:
|
||||
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
|
||||
df_cal = frame if len(frame) <= s.n_max_cal else frame.sample(s.n_max_cal, random_state=s.seed)
|
||||
codes = {c: pd.factorize(df_cal[c])[0] for c in columns}
|
||||
kcat = {c: int(df_cal[c].nunique()) for c in columns}
|
||||
n_cal = len(df_cal)
|
||||
median_cells = float(np.median([n_cal / (kcat[a] * kcat[b]) for a, b in itertools.combinations(columns, 2)]))
|
||||
if n_cal < 1000:
|
||||
warnings.append(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
|
||||
if median_cells < 5:
|
||||
warnings.append(f"tablas de contingencia dispersas (mediana {median_cells:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
|
||||
if len(columns) < 4:
|
||||
warnings.append("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
|
||||
if max(kcat.values()) > 30:
|
||||
warnings.append(f"variable con {max(kcat.values())} categorías: considera agruparlas antes de depurar.")
|
||||
report["datos"] = {"n": int(len(frame)), "n_calibracion": int(n_cal), "n_variables": len(columns),
|
||||
"categorias_por_variable": kcat, "pacientes_por_celda_mediana": median_cells}
|
||||
|
||||
# 1. U of Theil: pairs, accuracy and chance floor
|
||||
rows, ceiling = [], []
|
||||
for a, b in itertools.combinations(columns, 2):
|
||||
ip = info_pair(codes[a], codes[b], kcat[a], kcat[b])
|
||||
mi_null = np.array([info_pair(codes[a], rng.permutation(codes[b]), kcat[a], kcat[b])["mi"]
|
||||
for _ in range(s.null_perm)])
|
||||
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]),
|
||||
(b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
|
||||
u = ip["mi"] / hx if hx > 0 else np.nan
|
||||
u_null = mi_null.max() / hx if hx > 0 else np.nan
|
||||
rows.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null,
|
||||
"exactitud_X_desde_Y": acc, "exactitud_base_X": base})
|
||||
ceiling.append(u_null)
|
||||
pairs_u = pd.DataFrame(rows).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
|
||||
pairs_u["brecha_al_siguiente"] = pairs_u["U(X|Y)"] - pairs_u["U(X|Y)"].shift(-1)
|
||||
chance_ceiling = float(np.nanmax(ceiling))
|
||||
u_sug = suggest_u(pairs_u, chance_ceiling, s)
|
||||
|
||||
# 2. Sensitivity: which variables go when each threshold moves
|
||||
screen = RedundancyScreen(df_cal, columns, codes, kcat, s)
|
||||
check = theil_u_matrix(df_cal, columns)
|
||||
fast = screen.u_matrix(tuple(columns))
|
||||
assert np.allclose(check.values.astype(float), fast.loc[columns, columns].values.astype(float),
|
||||
equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
|
||||
base_out, base_act = screen.run(s.dup_u, s.u_redund, s.gvif_drop)
|
||||
|
||||
dup_sug = round(min(max(0.90, u_sug["U"] + 0.05), 0.99), 2)
|
||||
out_sug, _ = screen.run(dup_sug, u_sug["U"], s.gvif_drop)
|
||||
same = set(out_sug) == set(base_out)
|
||||
u_sug["misma_decision_que_config"] = bool(same)
|
||||
if not same and u_sug["confianza"] == "alta":
|
||||
u_sug["confianza"] = "revisar"
|
||||
if not same:
|
||||
warnings.append("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
|
||||
|
||||
# D) the gap rule's parameters are conventions: does changing them change the suggestion or what is dropped?
|
||||
gap_rows = []
|
||||
for gd in s.gap_from_grid:
|
||||
for gm in s.gap_min_grid:
|
||||
sg = suggest_u(pairs_u, chance_ceiling, s, gd, gm)
|
||||
dup_s = round(min(max(0.90, sg["U"] + 0.05), 0.99), 2)
|
||||
o, _ = screen.run(dup_s, sg["U"], s.gvif_drop)
|
||||
gap_rows.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": sg["U"],
|
||||
"método": sg["metodo"], "misma decisión": set(o) == set(base_out),
|
||||
"elimina [regla]": _labels(o)})
|
||||
sens_gap = pd.DataFrame(gap_rows)
|
||||
different = sens_gap[~sens_gap["misma decisión"]]
|
||||
if len(different):
|
||||
warnings.append(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(different)} de {len(sens_gap)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
|
||||
report["sensibilidad_regla_brecha"] = {
|
||||
"grilla_U_GAP_DESDE": list(s.gap_from_grid), "grilla_U_GAP_MIN_BRECHA": list(s.gap_min_grid),
|
||||
"proporcion_misma_decision": float(sens_gap["misma decisión"].mean()),
|
||||
"U_sugerido_min": float(sens_gap["U_REDUND sugerido"].min()),
|
||||
"U_sugerido_max": float(sens_gap["U_REDUND sugerido"].max())}
|
||||
|
||||
# 3. GVIF: margin to the threshold
|
||||
gvif_drop_sug = round(float(np.sqrt(s.vif_cut)), 2)
|
||||
tab_k, _ = screen.gvif(tuple(base_act))
|
||||
margin = None
|
||||
if tab_k is not None and len(tab_k):
|
||||
tab_k = tab_k.copy()
|
||||
tab_k["margen_al_umbral"] = s.gvif_drop - tab_k["GVIF_ajustado"]
|
||||
margin = float(tab_k["margen_al_umbral"].min())
|
||||
if margin < 0.15:
|
||||
warnings.append("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
|
||||
|
||||
# 4. Clustering: linkage (cophenetic) and cut (Cohen)
|
||||
min_n_eff = s.min_n_cat
|
||||
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
|
||||
if X.shape[1] < 6:
|
||||
min_n_eff = max(5, int(0.005 * n_cal))
|
||||
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
|
||||
warnings.append(f"muy pocas categorías con >= {s.min_n_cat} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
|
||||
cluster_ok = X.shape[1] >= 4
|
||||
method_sug, coph, cut_table = s.cluster_method, {}, pd.DataFrame()
|
||||
if not cluster_ok:
|
||||
warnings.append("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
|
||||
else:
|
||||
names = list(X.columns)
|
||||
var = np.array([c.split("=", 1)[0] for c in names])
|
||||
V = X.values.astype(np.float32)
|
||||
V -= V.mean(0)
|
||||
cov = V.T @ V
|
||||
sd = np.sqrt(np.diag(cov))
|
||||
R = (cov / np.outer(sd, sd)).astype(float)
|
||||
D = 1 - R if s.cluster_dist == "signed" else 1 - np.abs(R)
|
||||
D = np.clip((D + D.T) / 2, 0, None)
|
||||
np.fill_diagonal(D, 0)
|
||||
cond = squareform(D, checks=False)
|
||||
for m in ["single", "complete", "average", "weighted"]:
|
||||
coph[m] = float(cophenet(linkage(cond, method=m), cond)[0])
|
||||
method_sug = max(coph, key=coph.get)
|
||||
Zc = linkage(cond, method=method_sug)
|
||||
rows = []
|
||||
for t in np.round(np.arange(0.30, 1.01, 0.05), 2):
|
||||
lab = fcluster(Zc, t=float(t), criterion="distance")
|
||||
ng = len(set(lab))
|
||||
multi = sum(1 for g in set(lab) if len(set(var[lab == g])) >= 2)
|
||||
sil = float(silhouette_score(D, lab, metric="precomputed")) if 2 <= ng <= len(lab) - 1 else np.nan
|
||||
rows.append({"corte (dist.)": t, "r medio exigido": round(1 - t, 2), "n_grupos": ng,
|
||||
"grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
|
||||
cut_table = pd.DataFrame(rows)
|
||||
|
||||
summary = [
|
||||
{"parámetro": "U_REDUND", "configurado": s.u_redund, "sugerido": u_sug["U"], "criterio": u_sug["metodo"],
|
||||
"confianza": u_sug["confianza"]},
|
||||
{"parámetro": "DUP_U", "configurado": s.dup_u, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)",
|
||||
"confianza": u_sug["confianza"]},
|
||||
{"parámetro": "GVIF_DROP", "configurado": s.gvif_drop, "sugerido": gvif_drop_sug,
|
||||
"criterio": f"sqrt(VIF {s.vif_cut}) (R2={1 - 1 / s.vif_cut:.2f})",
|
||||
"confianza": "alta" if (margin is None or margin >= 0.15) else "revisar"},
|
||||
{"parámetro": "CLUSTER_METODO", "configurado": s.cluster_method, "sugerido": method_sug,
|
||||
"criterio": "máx. correlación cofenética", "confianza": "alta" if cluster_ok else "revisar"},
|
||||
{"parámetro": "CLUSTER_CORTE", "configurado": round(1 - s.r_large, 2), "sugerido": round(1 - s.r_large, 2),
|
||||
"criterio": f"Cohen: r medio >= {s.r_large}", "confianza": "alta"},
|
||||
{"parámetro": "PAR_R_MIN", "configurado": s.r_large, "sugerido": s.r_large, "criterio": "Cohen: efecto grande",
|
||||
"confianza": "alta"}]
|
||||
report.update({"piso_azar_U": chance_ceiling, "sugerencia_U": u_sug, "resumen": summary,
|
||||
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
|
||||
return Calibration(pairs_u, cut_table, report, summary, u_sug, dup_sug, gvif_drop_sug, method_sug, base_out,
|
||||
warnings)
|
||||
|
||||
|
||||
def thresholds_in_use(c: Calibration, s: DepurationSettings) -> Thresholds:
|
||||
"""The configured thresholds, or the calibration's suggestions when `thresholds_auto`."""
|
||||
cut, r_min = round(1 - s.r_large, 2), s.r_large
|
||||
if s.thresholds_auto:
|
||||
return Thresholds(c.dup_u_suggested, c.u_suggestion["U"], c.gvif_drop_suggested, c.cluster_method_suggested,
|
||||
cut, r_min, True)
|
||||
return Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, cut, r_min, False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- elimination (steps A, B, C on the full frame)
|
||||
|
||||
def eliminate(frame: pd.DataFrame, columns: list[str], t: Thresholds, s: DepurationSettings) -> pd.DataFrame:
|
||||
"""The dropped variables, one row each: `variable`, `paso`, `motivo`, `a_favor_de`. A removes duplicates (U both
|
||||
ways >= dup_u), B derived variables (U one way only >= u_redund), C the nested ones by GVIF."""
|
||||
active = list(columns)
|
||||
dropped: list[dict] = []
|
||||
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
|
||||
ncat = {c: int(frame[c].nunique()) for c in columns}
|
||||
order = {c: i for i, c in enumerate(columns)}
|
||||
key = lambda c: (pct_unknown[c], ncat[c], order[c]) # noqa: E731
|
||||
|
||||
def drop(var, step, reason, favor):
|
||||
active.remove(var)
|
||||
dropped.append({"variable": var, "paso": step, "motivo": reason, "a_favor_de": favor})
|
||||
|
||||
U = theil_u_matrix(frame, active) # A
|
||||
for a, b in itertools.combinations(list(active), 2):
|
||||
if a not in active or b not in active:
|
||||
continue
|
||||
if U.loc[a, b] >= t.dup_u and U.loc[b, a] >= t.dup_u:
|
||||
r = loser(a, b, s.protected, s.prefer, key)
|
||||
if r:
|
||||
drop(r[0], "A duplicada", f"U({a}|{b})={U.loc[a, b]:.2f}, U({b}|{a})={U.loc[b, a]:.2f}", r[1])
|
||||
|
||||
U = theil_u_matrix(frame, active) # B
|
||||
cand = []
|
||||
for x in active:
|
||||
for y in active:
|
||||
if x != y and U.loc[x, y] >= t.u_redund and U.loc[y, x] < t.u_redund:
|
||||
cand.append((U.loc[x, y], x, y))
|
||||
for u, x, y in sorted(cand, reverse=True):
|
||||
if x in active and y in active and x not in s.protected and x not in s.prefer:
|
||||
drop(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y, x]:.2f}", y)
|
||||
|
||||
for _ in range(s.max_iter_gvif): # C
|
||||
if len(active) < 3:
|
||||
break
|
||||
table, exact = gvif_table(frame, active)
|
||||
if table is None:
|
||||
exact = [c for _, c in exact if c not in s.protected]
|
||||
if not exact:
|
||||
break
|
||||
drop(exact[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
|
||||
continue
|
||||
cd = table[(table["GVIF_ajustado"] >= t.gvif_drop) & (~table["variable"].isin(s.protected))]
|
||||
if cd.empty:
|
||||
break
|
||||
v = cd.iloc[0]
|
||||
drop(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {t.gvif_drop}", "(el resto)")
|
||||
return pd.DataFrame(dropped, columns=["variable", "paso", "motivo", "a_favor_de"])
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Survival curves by the classic and the fractional (Kilbas-Saigo) Weibull, and Kaplan-Meier, apart from the stage's
|
||||
nodes (`survival_curves.py`). Plain functions with no I/O. Ported from `05_curvas_supervivencia.py`.
|
||||
|
||||
The fractional Weibull's survival function is a Kilbas-Saigo (Mittag-Leffler type) series, summed in floating point
|
||||
where that is safe and with arbitrary-precision `mpmath` where the terms get large. Both models are fitted by maximum
|
||||
likelihood on monthly counts of events and censorings (`tabla_eventos`), by Nelder-Mead from several starting points.
|
||||
"""
|
||||
|
||||
import time
|
||||
from functools import lru_cache
|
||||
|
||||
import mpmath as mp
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import gammaln
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _coefs(rho, m, l, N, dps):
|
||||
mp.mp.dps = dps
|
||||
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
|
||||
c = [mp.mpf(1)]
|
||||
for i in range(N - 1):
|
||||
c.append(c[-1] * mp.exp(mp.loggamma(rho * (m * i + l) + 1) - mp.loggamma(rho * (m * i + l + 1) + 1)))
|
||||
return tuple(c)
|
||||
|
||||
|
||||
def _log_terms(az, rho, m, l, N):
|
||||
i = np.arange(N - 1)
|
||||
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * i + l) + 1) - gammaln(rho * (m * i + l + 1) + 1))])
|
||||
n = np.arange(N)
|
||||
with np.errstate(divide="ignore"):
|
||||
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
|
||||
return lt
|
||||
|
||||
|
||||
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
|
||||
"""The Kilbas-Saigo function E_{rho,m,l}(z) at each `z`: the plain series when its terms stay small, else a polynomial
|
||||
in `mpmath` with as many digits as the largest term needs; NaN where even that is out of reach."""
|
||||
z = np.atleast_1d(np.asarray(z, float))
|
||||
rho, m, l = float(rho), float(m), float(l)
|
||||
out = np.full(z.shape, np.nan)
|
||||
az = np.abs(z)
|
||||
N = 400
|
||||
lt = _log_terms(az, rho, m, l, N)
|
||||
lmax, llast = lt.max(axis=1), lt[:, -1]
|
||||
zero = az == 0
|
||||
out[zero] = 1.0
|
||||
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
|
||||
if okf.any():
|
||||
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
|
||||
terms[:, 0] = 1.0
|
||||
out[okf] = terms.sum(axis=1)
|
||||
rest = np.where(~zero & ~okf)[0]
|
||||
if rest.size:
|
||||
with np.errstate(over="ignore"):
|
||||
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
|
||||
est = np.maximum(est, lmax[rest])
|
||||
use = rest[est <= logmax_cap]
|
||||
if use.size:
|
||||
est_u = est[est <= logmax_cap]
|
||||
dps = 30 + int(est_u.max() / 2.3) + 10
|
||||
zmax = float(az[use].max())
|
||||
with np.errstate(over="ignore"):
|
||||
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
|
||||
N2 = max(N2, 60)
|
||||
while True:
|
||||
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
|
||||
mp.mp.dps = dps
|
||||
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
|
||||
if last < tol or N2 >= nmax:
|
||||
break
|
||||
N2 *= 2
|
||||
if last < tol:
|
||||
cr = list(c)[::-1]
|
||||
for j in use:
|
||||
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
|
||||
return out
|
||||
|
||||
|
||||
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
|
||||
"""The fractional Weibull's survival function at `t`; NaN outside its parameter region."""
|
||||
tau1 = lam if tau1 is None else tau1
|
||||
tau2 = lam if tau2 is None else tau2
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
s = k + alpha - 2
|
||||
if k + alpha <= 1 or s + beta <= 0:
|
||||
return np.full_like(t, np.nan)
|
||||
m = s / beta + 1
|
||||
l = s / beta
|
||||
pref = float(mp.exp(mp.loggamma(k + 1) - mp.loggamma(k + alpha - 1)))
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
z = -pref * (t / lam) ** k * (t / tau1) ** (alpha - 1) * (t / tau2) ** (beta - 1)
|
||||
z = np.where(t > 0, z, 0.0)
|
||||
res = np.ones_like(t)
|
||||
pos = t > 0
|
||||
if pos.any():
|
||||
res[pos] = kilbas_saigo(z[pos], beta, m, l)
|
||||
return np.clip(res, 0.0, 1.0)
|
||||
|
||||
|
||||
def S_weibull(t, k, lam):
|
||||
t = np.asarray(t, float)
|
||||
return np.exp(-(t / lam) ** k)
|
||||
|
||||
|
||||
def tabla_eventos(meses, evento):
|
||||
"""Per month: the events and the censorings."""
|
||||
meses = np.asarray(meses, int)
|
||||
evento = np.asarray(evento, bool)
|
||||
T = int(meses.max()) + 2
|
||||
return np.bincount(meses[evento], minlength=T), np.bincount(meses[~evento], minlength=T)
|
||||
|
||||
|
||||
def _nll_from_S(Sfun, d, c):
|
||||
T = len(d)
|
||||
Sg = Sfun(np.arange(0, T + 1, dtype=float))
|
||||
mid = Sfun(np.arange(T) + 0.5)
|
||||
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
|
||||
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
|
||||
return 1e12 # invalid region / not computable
|
||||
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
|
||||
|
||||
|
||||
def ajustar_weibull(d, c) -> dict:
|
||||
"""The classic Weibull's maximum likelihood: `k`, `lam`, its negative log-likelihood and its survival function `S`."""
|
||||
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c) # noqa: E731
|
||||
best = None
|
||||
for k0 in (0.7, 1.0, 1.5):
|
||||
for l0 in (50., 200., 1000.):
|
||||
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
|
||||
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
|
||||
if best is None or r.fun < best.fun:
|
||||
best = r
|
||||
k, lam = np.exp(best.x)
|
||||
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
|
||||
S=lambda t: S_weibull(t, k, lam))
|
||||
|
||||
|
||||
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120) -> dict:
|
||||
"""The fractional Weibull's maximum likelihood with `k` fixed. It starts from the point that reproduces the classic
|
||||
Weibull, so the fractional one is never worse; `max_seg` caps the seconds spent."""
|
||||
amin = max(0.0, 1.0 - k_fijo) + 1e-6
|
||||
|
||||
def unpack(p):
|
||||
return amin + np.exp(p[0]), 1 / (1 + np.exp(-p[1])), np.exp(p[2])
|
||||
|
||||
T_max = float(len(d))
|
||||
t_fin = time.time() + max_seg
|
||||
|
||||
def f(p):
|
||||
if time.time() > t_fin:
|
||||
return 1e12
|
||||
a, b, lam = unpack(p)
|
||||
# penalizes degenerate regions (|z| huge in the last month -> costly, unstable series)
|
||||
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
|
||||
return 1e12
|
||||
try:
|
||||
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
|
||||
except Exception:
|
||||
return 1e12
|
||||
|
||||
lams = [lam_ref] if lam_ref else []
|
||||
lams += [100., 500.]
|
||||
best = None
|
||||
starts = []
|
||||
if lam_ref:
|
||||
starts.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
|
||||
for l0 in lams:
|
||||
for a0 in (0.3, 1.0):
|
||||
for b0 in (0.5, 0.9):
|
||||
starts.append([np.log(a0), np.log(b0 / (1 - b0)), np.log(l0)])
|
||||
for p0 in starts:
|
||||
if time.time() > t_fin and best is not None:
|
||||
break
|
||||
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
|
||||
if best is None or r.fun < best.fun:
|
||||
best = r
|
||||
a, b, lam = unpack(best.x)
|
||||
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
|
||||
S=lambda t: S_ks(t, k_fijo, a, b, lam))
|
||||
|
||||
|
||||
def km_curva(meses_int, evento, T):
|
||||
"""(S, lower, upper) of Kaplan-Meier for months 0..T, with the Greenwood 95 % interval on the log-log scale."""
|
||||
d, c = tabla_eventos(meses_int, evento)
|
||||
L = max(len(d), T + 1)
|
||||
d = np.pad(d, (0, L - len(d)))
|
||||
c = np.pad(c, (0, L - len(c)))
|
||||
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
|
||||
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
|
||||
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
|
||||
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
se = np.sqrt(V) / np.abs(np.log(S))
|
||||
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
|
||||
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
|
||||
return S, lo, hi
|
||||
@@ -0,0 +1,130 @@
|
||||
"""The hybrid Bayesian network (HBN) of the modeling stage, apart from its nodes (`modeling.py`): structure learning by
|
||||
hill climbing with bootstrap restarts, a BDeu score and temporal tiers as forbidden arcs; a greedy expansion of the
|
||||
outcome's parents; the fit and the survival probability of each test row. Plain functions with no I/O. Ported from
|
||||
`04_modelado.py` (phase 5).
|
||||
|
||||
Reproducibility: pgmpy's hill climbing breaks score ties by the iteration order of sets of column names, which depends on
|
||||
Python's per-process string hashing. Two runs of the same data can learn slightly different networks (the script
|
||||
behaves the same way) unless `PYTHONHASHSEED` is fixed; with it fixed, the port and the script agree exactly.
|
||||
|
||||
Only the categorical path is ported: the script's discretization of continuous variables (L_DVBN) never runs while
|
||||
`AGE_IS_NUMERIC` and `TUMORSIZE_IS_NUMERIC` are false, which is how the pipeline uses SEER's grouped age and tumor size.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pgmpy.causal_discovery import ExpertKnowledge
|
||||
from pgmpy.estimators import BDeu, HillClimbSearch
|
||||
from pgmpy.inference import VariableElimination
|
||||
from pgmpy.models import DiscreteBayesianNetwork
|
||||
from pgmpy.parameter_estimator import DiscreteBayesianEstimator
|
||||
|
||||
from models.cama.seer_survival.settings import ModelingSettings
|
||||
|
||||
OUTCOME = "outcome"
|
||||
|
||||
|
||||
def temporal_order(available: list[str], s: ModelingSettings) -> list[list[str]]:
|
||||
"""Tiers, earliest first: demography, tumor, treatment, outcome. An arc may not point to an earlier tier. Columns
|
||||
in no tier go first, unrestricted."""
|
||||
tiers = []
|
||||
for tier in [s.tier_demography, s.tier_tumor, s.tier_treatment, [OUTCOME]]:
|
||||
present = [c for c in tier if c in available]
|
||||
if present:
|
||||
tiers.append(present)
|
||||
classified = {c for t in tiers for c in t}
|
||||
unclassified = [c for c in available if c not in classified]
|
||||
if unclassified:
|
||||
tiers.insert(0, unclassified)
|
||||
return tiers
|
||||
|
||||
|
||||
def hill_climb_with_restarts(data: pd.DataFrame, tiers: list[list[str]], ess: int, n_restarts: int,
|
||||
max_indegree: int = 4, random_state: int = 0):
|
||||
"""(edges, score): hill climbing on `n_restarts` bootstrap resamples (shuffling the column order adds no variability
|
||||
in this pgmpy), each candidate structure scored on the WHOLE data, keeping the best."""
|
||||
best_score, best_edges = -np.inf, None
|
||||
scorer = BDeu(data, equivalent_sample_size=ess)
|
||||
expert = ExpertKnowledge(temporal_order=tiers)
|
||||
for i in range(n_restarts):
|
||||
boot = data.sample(n=len(data), replace=True, random_state=random_state + i)
|
||||
structure = HillClimbSearch(boot).estimate(
|
||||
scoring_method=BDeu(boot, equivalent_sample_size=ess), max_indegree=max_indegree,
|
||||
expert_knowledge=expert, show_progress=False)
|
||||
score = scorer.score(structure)
|
||||
if score > best_score:
|
||||
best_score, best_edges = score, list(structure.edges())
|
||||
return best_edges, best_score
|
||||
|
||||
|
||||
def expand_outcome_parents(edges: list[tuple], bn_train: pd.DataFrame, bn_cols: list[str], ess: int,
|
||||
max_parents: int) -> list[tuple]:
|
||||
"""The outcome becomes a terminal node (diagnosis and treatment precede it), then gains parents greedily by the gain
|
||||
of its local BDeu score: with all the evidence observed its prediction depends only on its parents, and the global
|
||||
score may not add them even when they would help THAT prediction."""
|
||||
edges = [(u, v) for (u, v) in edges if u != OUTCOME]
|
||||
parents = [u for (u, v) in edges if v == OUTCOME]
|
||||
others = [(u, v) for (u, v) in edges if v != OUTCOME]
|
||||
score = BDeu(bn_train, equivalent_sample_size=ess).local_score(OUTCOME, parents)
|
||||
candidates = [c for c in bn_cols if c != OUTCOME and c not in parents]
|
||||
improved = True
|
||||
while improved and len(parents) < max_parents and candidates:
|
||||
improved = False
|
||||
best_gain, best = 0, None
|
||||
for cand in candidates:
|
||||
# the score object caches the data it is built on: one new frame and scorer per evaluation
|
||||
trial = bn_train[parents + [OUTCOME]].copy()
|
||||
trial[cand] = bn_train[cand].values
|
||||
gain = BDeu(trial, equivalent_sample_size=ess).local_score(OUTCOME, parents + [cand]) - score
|
||||
if gain > best_gain:
|
||||
best_gain, best = gain, cand
|
||||
if best is not None:
|
||||
parents.append(best)
|
||||
candidates.remove(best)
|
||||
score += best_gain
|
||||
improved = True
|
||||
return others + [(p, OUTCOME) for p in parents]
|
||||
|
||||
|
||||
def fit_network(edges: list[tuple], bn_train: pd.DataFrame) -> DiscreteBayesianNetwork:
|
||||
model = DiscreteBayesianNetwork(edges)
|
||||
model.fit(bn_train, estimator=DiscreteBayesianEstimator(prior_type="BDeu"))
|
||||
return model
|
||||
|
||||
|
||||
def predict_survival(model: DiscreteBayesianNetwork, bn_test: pd.DataFrame) -> list[float]:
|
||||
"""P(outcome = 1 | the row's other columns) by variable elimination; NaN where the query fails."""
|
||||
infer = VariableElimination(model)
|
||||
evidence_cols = [c for c in bn_test.columns if c != OUTCOME]
|
||||
preds = []
|
||||
for _, row in bn_test.iterrows():
|
||||
evidence = {k: v for k, v in row[evidence_cols].to_dict().items() if k in model.nodes()}
|
||||
try:
|
||||
q = infer.query(variables=[OUTCOME], evidence=evidence, show_progress=False)
|
||||
preds.append(q.values[list(q.state_names[OUTCOME]).index("1")])
|
||||
except Exception:
|
||||
preds.append(np.nan)
|
||||
return preds
|
||||
|
||||
|
||||
def learn_structure(bn_train: pd.DataFrame, bn_cols: list[str], s: ModelingSettings, n_restarts: int,
|
||||
random_state: int) -> list[tuple]:
|
||||
"""The arcs: hill climbing with restarts, then the outcome's expanded parents."""
|
||||
tiers = temporal_order(list(bn_cols), s)
|
||||
edges, _ = hill_climb_with_restarts(bn_train, tiers, s.bdeu_ess, n_restarts, s.max_indegree, random_state)
|
||||
return expand_outcome_parents(edges, bn_train, bn_cols, s.bdeu_ess, s.max_outcome_parents)
|
||||
|
||||
|
||||
def arc_strength(model: DiscreteBayesianNetwork, bn_train: pd.DataFrame, ess: int) -> pd.DataFrame:
|
||||
"""The change of the network's score when an arc is REMOVED, the rest fixed (bnlearn's `arc.strength`): very negative
|
||||
= strong arc, near 0 = adds little, positive = removing it would even improve the score."""
|
||||
scorer = BDeu(bn_train, equivalent_sample_size=ess)
|
||||
rows = []
|
||||
for (u, v) in model.edges():
|
||||
parents = [p for (p, c) in model.edges() if c == v]
|
||||
with_arc = scorer.local_score(v, parents)
|
||||
without = scorer.local_score(v, [p for p in parents if p != u])
|
||||
rows.append({"desde": u, "hacia": v, "delta_al_quitar": without - with_arc})
|
||||
out = pd.DataFrame(rows).sort_values("delta_al_quitar").reset_index(drop=True)
|
||||
out["delta_al_quitar"] = out["delta_al_quitar"].round(1)
|
||||
return out
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Logistic regression with stepwise selection, apart from the modeling nodes (`modeling.py`): a univariate chi-square
|
||||
pre-filter, the stepwise search on a stratified subsample and the safe fit. Plain functions with no I/O. Ported from
|
||||
`04_modelado.py` (phases 3-4)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.stats import chi2_contingency
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
|
||||
def univariate_prefilter(X: pd.DataFrame, y: pd.Series, alpha: float = 0.10) -> list[tuple]:
|
||||
"""(column, p, chi2) of the columns whose chi-square against the outcome has p < alpha."""
|
||||
kept = []
|
||||
for col in X.columns:
|
||||
table = pd.crosstab(X[col], y)
|
||||
if table.shape[0] < 2 or table.shape[1] < 2:
|
||||
continue # no variation: nothing to add
|
||||
try:
|
||||
chi2_stat, p, _, _ = chi2_contingency(table)
|
||||
except ValueError:
|
||||
continue
|
||||
if p < alpha:
|
||||
kept.append((col, p, chi2_stat))
|
||||
return kept
|
||||
|
||||
|
||||
def prefiltered_columns(X: pd.DataFrame, y: pd.Series, alpha: float, max_candidates: int,
|
||||
always_sort: bool = True) -> list[str]:
|
||||
"""The pre-filter's columns, at most `max_candidates` and strongest first (by chi-square: with big samples many
|
||||
p-values are exactly 0.0 and can't order them). The main fit only sorts when it must cut; the others always do."""
|
||||
kept = univariate_prefilter(X, y, alpha=alpha)
|
||||
if always_sort or len(kept) > max_candidates:
|
||||
kept = sorted(kept, key=lambda t: t[2], reverse=True)
|
||||
return [c for c, _, _ in kept[:max_candidates]]
|
||||
|
||||
|
||||
def safe_fit_logit(y, X_sub, maxiter: int = 200):
|
||||
"""A BFGS logit; a lightly L2-regularized one if that fails; None if both do."""
|
||||
try:
|
||||
return sm.Logit(y, X_sub).fit(disp=0, method="bfgs", maxiter=maxiter)
|
||||
except Exception:
|
||||
try:
|
||||
return sm.Logit(y, X_sub).fit_regularized(disp=0, alpha=0.01, maxiter=maxiter)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def stepwise_selection(X: pd.DataFrame, y: pd.Series, alpha_in: float = 0.10, alpha_out: float = 0.15) -> list[str]:
|
||||
"""Forward step (the candidate with the lowest p below `alpha_in`), then a backward step (the worst above `alpha_out`),
|
||||
until nothing changes."""
|
||||
included, excluded = [], list(X.columns)
|
||||
while True:
|
||||
changed = False
|
||||
best_pval, best_feature = np.inf, None
|
||||
for col in excluded:
|
||||
model = safe_fit_logit(y, sm.add_constant(X[included + [col]]))
|
||||
if model is None or col not in model.pvalues:
|
||||
continue
|
||||
pval = model.pvalues[col]
|
||||
if pval < best_pval:
|
||||
best_pval, best_feature = pval, col
|
||||
if best_feature is not None and best_pval < alpha_in:
|
||||
included.append(best_feature)
|
||||
excluded.remove(best_feature)
|
||||
changed = True
|
||||
if included:
|
||||
model = safe_fit_logit(y, sm.add_constant(X[included]))
|
||||
if model is not None:
|
||||
pvals = model.pvalues.drop("const", errors="ignore")
|
||||
if len(pvals) > 0 and pvals.max() > alpha_out:
|
||||
worst = pvals.idxmax()
|
||||
included.remove(worst)
|
||||
excluded.append(worst)
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
return included
|
||||
|
||||
|
||||
def search_sample(X_train: pd.DataFrame, y_train: pd.Series, columns: list[str], max_rows: int, random_state: int):
|
||||
"""The stepwise searches on a subsample stratified by outcome (more than enough to decide which variables matter);
|
||||
the final model is refitted on the whole train."""
|
||||
if X_train.shape[0] > max_rows:
|
||||
idx, _ = train_test_split(X_train.index, train_size=max_rows, random_state=random_state, stratify=y_train)
|
||||
return X_train.loc[idx, columns], y_train.loc[idx]
|
||||
return X_train[columns], y_train
|
||||
|
||||
|
||||
def encode(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
|
||||
"""Dummies without the first category; the unknowns are one more category."""
|
||||
enc = df.copy()
|
||||
for c in columns:
|
||||
enc[c] = enc[c].fillna("Desconocido").astype(str)
|
||||
return enc
|
||||
@@ -0,0 +1,322 @@
|
||||
# CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs.
|
||||
|
||||
[depuration]
|
||||
exclude = ["Outcome_cat"] # never analysed or touched
|
||||
auto_extra = ["Age_group", "Tumor_group"] # included when present
|
||||
extra_cols = []
|
||||
protected = [] # e.g. ["Estadio_cat"]: never dropped
|
||||
prefer = ["Tumor_group", "Age_group"] # on a tie or duplicate, the one listed here wins (the project's own groupings)
|
||||
drop_raw_sources = true # also drop the raw SEER column of a dropped variable
|
||||
unknown_label = "Desconocido"
|
||||
|
||||
dup_u = 0.90 # step A
|
||||
u_redund = 0.80 # step B
|
||||
gvif_drop = 2.24 # step C: GVIF^(1/2df) (equals VIF 5)
|
||||
max_iter_gvif = 20
|
||||
|
||||
# Calibration: independent of the data, only reports (thresholds_auto = true applies its suggestions)
|
||||
thresholds_auto = false
|
||||
n_max_cal = 300000 # more rows are calibrated on a reproducible subsample
|
||||
null_perm = 100 # permutations for the chance floor of U
|
||||
k_azar = 5 # U_REDUND must be >= k_azar x (max U by chance)
|
||||
u_conventional = 0.80 # fallback when the data can't calibrate
|
||||
u_gap_from = 0.70 # gaps whose upper edge is >= this U are searched
|
||||
u_gap_min = 0.10 # minimum gap to count as "natural"
|
||||
u_plausible = [0.60, 0.95] # limits of the suggested threshold
|
||||
vif_cut = 5 # 5 (R2=0.80) or 10 (R2=0.90)
|
||||
r_large = 0.5 # Cohen (1988): |phi| 0.1 small, 0.3 medium, 0.5 large
|
||||
min_n_cat = 30 # categories with fewer patients are left out of the clustering
|
||||
max_cat_cluster = 400 # cap of columns (categories) in the clustering matrix
|
||||
cluster_dist = "signed" # "signed": d = 1-r | "abs": d = 1-|r|
|
||||
cluster_method = "average"
|
||||
seed = 0
|
||||
gap_from_grid = [0.50, 0.60, 0.70, 0.80, 0.90]
|
||||
gap_min_grid = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30]
|
||||
|
||||
[balancing]
|
||||
# The outcome is 18-month survival: "Sobrevive" (alive at the horizon), "Muerte" (dead before it), unknown otherwise.
|
||||
outcome_mode = "censura_excluida" # "censura_excluida" (recommended: censored patients are unknown) | "original"
|
||||
horizon_months = 18
|
||||
# Diagnosis years with INCOMPLETE follow-up: when more than this % of a year's patients are censored (alive with
|
||||
# < horizon), the whole year leaves the outcome. Avoids only early deaths "entering" in the cut-off years.
|
||||
exclude_censored_years = true
|
||||
censoring_max_pct = 10.0
|
||||
age_keywords = ["age recode", "age at diagnosis", "age"]
|
||||
n_components = 10
|
||||
target_ratio = 1.0 # 1.0 = exact 50/50
|
||||
distance_dims = 0 # 0 = all the fitted MCA dimensions
|
||||
mca_variant = "con_edad" # "con_edad" | "sin_edad": the MCA that picks the majority patients kept
|
||||
|
||||
[categorization]
|
||||
alpha = 1.0 # Dirichlet prior per category
|
||||
kmax = 8 # most segments considered
|
||||
threshold = 0.08 # least composition change for a boundary to count as real
|
||||
min_count = 50 # categories with fewer patients are dropped from the counts
|
||||
# Smallest segment, as a share of the BALANCED cohort (a fixed number would mean different things as the cohort shrinks)
|
||||
min_n_pct = 0.05
|
||||
min_n_floor = 50
|
||||
bin_width_mm = 5 # tumor size: width of each ordinal level, analogous to the 5-year age bands
|
||||
tumor_cap_mm = 100 # from here on, a single ">100 mm" level
|
||||
k_quantiles = 4
|
||||
clinical_age = [40, 50, 70] # years
|
||||
clinical_tumor = [20, 50] # mm (T1 | T2 | T3+)
|
||||
age_final = "Biología + tratamiento" # the configuration whose cuts become Age_group
|
||||
tumor_final = "Outcome + biología" # the configuration whose cuts become Tumor_group
|
||||
drop_after = ["Tamano_tumor_cat"] # replaced by Tumor_group in the final file: the same datum twice is collinear
|
||||
biology = ["Estadio", "Grado_histologico", "Subtipo_molecular", "Receptor_estrogeno", "Receptor_progesterona",
|
||||
"Metastasis", "Tamano_tumor", "Localizacion_mama", "Lateralidad", "Tipo_histologico"]
|
||||
treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
|
||||
demographic = ["Estado_civil", "Race"]
|
||||
|
||||
# Keywords (in the lower-cased column label) that find the raw column of a covariate with no recoded `_cat` column.
|
||||
[categorization.candidate_keywords]
|
||||
Estadio = { include = ["stage"], exclude = [] }
|
||||
Grado_histologico = { include = ["grade"], exclude = [] }
|
||||
Subtipo_molecular = { include = ["subtype"], exclude = [] }
|
||||
Receptor_estrogeno = { include = ["er status", "estrogen"], exclude = [] }
|
||||
Receptor_progesterona = { include = ["pr status", "progesterone"], exclude = [] }
|
||||
Tamano_tumor = { include = ["tumor size"], exclude = [] }
|
||||
Metastasis = { include = ["eod mets", "mets recode"], exclude = [] }
|
||||
Localizacion_mama = { include = ["primary site"], exclude = [] }
|
||||
Lateralidad = { include = ["laterality"], exclude = [] }
|
||||
Tipo_histologico = { include = ["histologic"], exclude = [] }
|
||||
Tratamiento_quirurgico = { include = ["surg"], exclude = [] }
|
||||
Radioterapia = { include = ["radiation"], exclude = [] }
|
||||
Quimioterapia = { include = ["chemo"], exclude = [] }
|
||||
Estado_civil = { include = ["marital"], exclude = [] }
|
||||
Race = { include = ["race"], exclude = [] }
|
||||
|
||||
# Categorization proposals: how age and tumor size are grouped. A value is a configuration's name (the blocks joined
|
||||
# by " + ": outcome, biología, tratamiento, demográfico, and edad for the tumor axis), "clinico" (fixed cuts) or
|
||||
# "cuantiles" (K groups of equal frequency, without the outcome). The modelling stage runs every proposal.
|
||||
[categorization.proposals.P1_actual]
|
||||
age = "Biología + tratamiento"
|
||||
tumor = "Outcome + biología"
|
||||
[categorization.proposals.P2_solo_outcome]
|
||||
age = "Solo outcome"
|
||||
tumor = "Solo outcome"
|
||||
[categorization.proposals.P3_outcome_biologia]
|
||||
age = "Outcome + biología"
|
||||
tumor = "Outcome + biología"
|
||||
[categorization.proposals.P4_outcome_bio_trat]
|
||||
age = "Outcome + biología + tratamiento"
|
||||
tumor = "Outcome + biología + tratamiento"
|
||||
[categorization.proposals.P5_todos_los_bloques]
|
||||
age = "Outcome + biología + tratamiento + demográfico"
|
||||
tumor = "Outcome + biología + tratamiento + demográfico + edad"
|
||||
[categorization.proposals.P6_clinico_fijo]
|
||||
age = "clinico"
|
||||
tumor = "clinico"
|
||||
[categorization.proposals.P7_cuantiles]
|
||||
age = "cuantiles"
|
||||
tumor = "cuantiles"
|
||||
|
||||
[bootstrap]
|
||||
n_bootstrap = 200
|
||||
random_state = 42
|
||||
|
||||
[survival]
|
||||
# Survival curves of the whole cohort and of subgroups: Kaplan-Meier, the classic and the fractional Weibull, and the
|
||||
# 6/12/18-month survival by LR, HBN and their stacked combination, with bootstrap intervals.
|
||||
age_mode = "categorizada" # how age enters the LR: "categorizada" | "continua" | "continua_cuadratica"
|
||||
include_age = true # adds the grouped age (Edad_cat) when no categorical age column exists
|
||||
age_cuts = [45, 60, 75]
|
||||
hbn_fixed_parents = ["Estadio", "Tipo_histologico", "Tratamiento_quirurgico", "Quimioterapia", "Radioterapia"] # found by keyword; empty = learn them (BDeu)
|
||||
hbn_age_parent = true # adds the grouped age as a parent of the outcome (expert knowledge; stage 04 didn't choose it)
|
||||
hbn_parents = "fijos" # "fijos": learned once and kept in the bootstrap | "reaprender": searched again per replica
|
||||
covariates = [] # empty = every column ending in "_cat" but the outcome
|
||||
horizons = [6, 12, 18] # months where the LR and HBN points are shown
|
||||
censoring = "riesgo" # "riesgo": a model per interval using all the follow-up | "ipcw" | "excluir"
|
||||
combine = true # one LR + HBN indicator (per-interval stacking weights); only with censoring = "riesgo"
|
||||
show_individual = false # also draws LR and HBN apart from the combination
|
||||
stack_folds = 5 # cross-validation folds that decide the weights
|
||||
stack_shrink = 20 # shrink toward 50/50 with few deaths: lambda = shrink / (shrink + the interval's deaths)
|
||||
n_boot = 100 # bootstrap replicas for the intervals
|
||||
n_boot_sub = 100 # and in the subgroups
|
||||
seed = 42
|
||||
hbn_ess = 1000 # equivalent sample size of the BDeu prior
|
||||
hbn_max_parents = 5
|
||||
k_ident = "clasico" # the fractional Weibull's fixed k: "clasico" = the classic Weibull's | or a number
|
||||
curves = "ajustada" # "ajustada": KM and Weibull standardized by the same covariates | "cruda": unadjusted
|
||||
adjust_step = 3 # months per interval of the adjusted curve
|
||||
show_raw_km = true
|
||||
ylim_main = [] # e.g. [0.94, 1.0]; empty = automatic
|
||||
inset_zoom = false
|
||||
inset_months = 18
|
||||
cap_months = 24 # follow-up is truncated here (later deaths and follow-up count as alive / censored); 0 = no cap
|
||||
min_events_sub = 5 # least deaths to fit a subgroup
|
||||
ks_max_seconds = 120 # time caps of the fractional fits (the whole cohort / a subgroup)
|
||||
ks_sub_max_seconds = 180
|
||||
xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty = (0, extrapolation months)
|
||||
|
||||
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
|
||||
|
||||
# Subgroups: every condition present must hold. her2 = "pos" | "neg"; triple_negative (HR-/HER2-); age_min (>=) and
|
||||
# age_max (<) in years; stages (0..4); conservative (conservative surgery).
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
|
||||
her2 = "pos"
|
||||
age_min = 60
|
||||
stages = [3, 4]
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
|
||||
her2 = "pos"
|
||||
age_max = 60
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio IV"
|
||||
stages = [4]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio I"
|
||||
stages = [1]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 75 años"
|
||||
age_min = 75
|
||||
[[survival.subgroups]]
|
||||
name = "< 45 años"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · estadio 0–II · cirugía conservadora"
|
||||
her2 = "pos"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · estadio 0–II"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2−"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
|
||||
triple_negative = true
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_min = 65
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
|
||||
[risk_factors]
|
||||
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
|
||||
# crossing 1 and Benjamini-Hochberg p < alpha), c2 stability: the variable enters the LR stepwise in at least freq_min
|
||||
# of the bootstrap replicas, c3 it is in the outcome's Markov blanket in the HBN, c4 the absolute survival difference at
|
||||
# `horizon` months (Kaplan-Meier) against the reference category. Treatment variables are a clinical decision: they are
|
||||
# not classified and don't enter c1's model; they are reported apart.
|
||||
alpha = 0.05
|
||||
freq_min = 0.80
|
||||
horizon = 18
|
||||
cap_months = 24
|
||||
treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
|
||||
|
||||
[risk_factors.canonical_map]
|
||||
Age_group = "Edad"
|
||||
Tumor_group = "Tamano_tumor"
|
||||
Tamano_tumor_cat = "Tamano_tumor"
|
||||
Estadio_cat = "Estadio"
|
||||
Grado_histologico_cat = "Grado_histologico"
|
||||
Subtipo_molecular_cat = "Subtipo_molecular"
|
||||
Receptor_estrogeno_cat = "Receptor_estrogeno"
|
||||
Receptor_progesterona_cat = "Receptor_progesterona"
|
||||
Metastasis_cat = "Metastasis"
|
||||
Localizacion_mama_cat = "Localizacion_mama"
|
||||
Lateralidad_cat = "Lateralidad"
|
||||
Tipo_histologico_cat = "Tipo_histologico"
|
||||
Tratamiento_quirurgico_cat = "Tratamiento_quirurgico"
|
||||
Radioterapia_cat = "Radioterapia"
|
||||
Quimioterapia_cat = "Quimioterapia"
|
||||
Estado_civil_cat = "Estado_civil"
|
||||
Ganglios_positivos_cat = "Ganglios_positivos"
|
||||
Invasion_linfovascular_cat = "Invasion_linfovascular"
|
||||
Margenes_cat = "Margenes"
|
||||
Densidad_BIRADS_cat = "Densidad_BIRADS"
|
||||
Masa_espiculada_cat = "Masa_espiculada"
|
||||
Microcalcificaciones_cat = "Microcalcificaciones"
|
||||
Multifocalidad_cat = "Multifocalidad"
|
||||
BRCA_cat = "BRCA"
|
||||
HER2_IHQ_cat = "HER2_IHQ"
|
||||
|
||||
[modeling]
|
||||
random_state = 42
|
||||
test_size = 0.3
|
||||
prefilter_alpha = 0.10 # univariate chi-square pre-filter of the dummy columns
|
||||
alpha_in = 0.10 # stepwise: enters below this p
|
||||
alpha_out = 0.15 # stepwise: leaves above this p
|
||||
max_candidates = 40 # hard cap of columns the stepwise receives (by chi-square, strongest first)
|
||||
max_search_rows = 8000 # the stepwise searches on a stratified subsample; the final fit uses the whole train
|
||||
lr_maxiter = 200
|
||||
# Hybrid Bayesian network (hill climbing with restarts, BDeu score, temporal tiers as forbidden arcs)
|
||||
bdeu_ess = 1000 # equivalent sample size: pure K2 (= 1) penalized complexity too hard
|
||||
n_restarts = 10
|
||||
max_indegree = 4
|
||||
max_outcome_parents = 10 # the greedy expansion of the outcome's parents
|
||||
# The covariates that enter the models, by canonical name (Age/Tumor size carry the Age_group/Tumor_group categories)
|
||||
categorical_order = ["Edad", "Tamano_tumor", "Estadio", "Grado_histologico", "Subtipo_molecular", "Receptor_estrogeno",
|
||||
"Receptor_progesterona", "Metastasis", "Localizacion_mama", "Lateralidad", "Tipo_histologico",
|
||||
"Tratamiento_quirurgico", "Radioterapia", "Quimioterapia", "Estado_civil", "Race",
|
||||
"Ganglios_positivos", "Invasion_linfovascular", "Margenes", "Densidad_BIRADS", "Masa_espiculada",
|
||||
"Microcalcificaciones", "Multifocalidad", "BRCA", "HER2_IHQ"]
|
||||
treatment_vars = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
|
||||
tier_demography = ["Edad", "Race", "Estado_civil", "BRCA", "Densidad_BIRADS"]
|
||||
tier_tumor = ["Estadio", "Grado_histologico", "Tipo_histologico", "Subtipo_molecular", "Receptor_estrogeno",
|
||||
"Receptor_progesterona", "Tamano_tumor", "Localizacion_mama", "Lateralidad", "Metastasis",
|
||||
"CS_Lymph_Nodes", "Ganglios_positivos", "Invasion_linfovascular", "Masa_espiculada",
|
||||
"Microcalcificaciones", "Multifocalidad", "HER2_IHQ"]
|
||||
tier_treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia", "Margenes"]
|
||||
# The natural population (every patient with a known outcome, before the undersampling)
|
||||
run_lr_natural = true
|
||||
natural_search_rows = 30000
|
||||
natural_test_size = 0.30
|
||||
natural_maxiter = 300
|
||||
# Bootstrap of the whole pipeline (the indices come from stage 03)
|
||||
n_bootstrap_run = 60 # max 200 (~27 s per replica with the HBN)
|
||||
bootstrap_max_seconds = 2700 # safety cap: the loop stops by itself and uses what it has
|
||||
bootstrap_include_hbn = true # false = LR only (much faster)
|
||||
bootstrap_restarts = 3 # hill-climbing restarts PER REPLICA
|
||||
# Comparison of the categorization proposals (stage 02b), on the same splits
|
||||
n_splits_prop = 5
|
||||
proposals_only = [] # empty = all of the file's proposals
|
||||
proposals_include_hbn = true
|
||||
proposals_max_seconds = 3600
|
||||
|
||||
# Column of the balanced file -> the canonical name the models use. Selected by the ORIGINAL name before renaming, so a
|
||||
# raw SEER column that already has a canonical name is never carried along (a duplicate fails much later, inside pgmpy).
|
||||
[modeling.canonical_map]
|
||||
Age_group = "Edad"
|
||||
Tumor_group = "Tamano_tumor"
|
||||
Estadio_cat = "Estadio"
|
||||
Grado_histologico_cat = "Grado_histologico"
|
||||
Subtipo_molecular_cat = "Subtipo_molecular"
|
||||
Receptor_estrogeno_cat = "Receptor_estrogeno"
|
||||
Receptor_progesterona_cat = "Receptor_progesterona"
|
||||
Metastasis_cat = "Metastasis"
|
||||
Localizacion_mama_cat = "Localizacion_mama"
|
||||
Lateralidad_cat = "Lateralidad"
|
||||
Tipo_histologico_cat = "Tipo_histologico"
|
||||
Tratamiento_quirurgico_cat = "Tratamiento_quirurgico"
|
||||
Radioterapia_cat = "Radioterapia"
|
||||
Quimioterapia_cat = "Quimioterapia"
|
||||
Estado_civil_cat = "Estado_civil"
|
||||
Outcome_cat = "Outcome_cat"
|
||||
Ganglios_positivos_cat = "Ganglios_positivos"
|
||||
Invasion_linfovascular_cat = "Invasion_linfovascular"
|
||||
Margenes_cat = "Margenes"
|
||||
Densidad_BIRADS_cat = "Densidad_BIRADS"
|
||||
Masa_espiculada_cat = "Masa_espiculada"
|
||||
Microcalcificaciones_cat = "Microcalcificaciones"
|
||||
Multifocalidad_cat = "Multifocalidad"
|
||||
BRCA_cat = "BRCA"
|
||||
HER2_IHQ_cat = "HER2_IHQ"
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Stage 04, modeling: the stepwise logistic regression (LR) and the hybrid Bayesian network (HBN) on the balanced
|
||||
cohort, their comparison on the internal test, and the LR on the natural population.
|
||||
|
||||
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `balanced_csv`,
|
||||
`natural_csv` and `modeling` (its settings). The heavy routines live apart: `lr_selection.py`, `hbn.py` and
|
||||
`natural.py`; the bootstrap and the proposal comparison, which repeat this pipeline, are `resampling.py`.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from matplotlib import rc_context
|
||||
from matplotlib.figure import Figure
|
||||
from sklearn.calibration import calibration_curve
|
||||
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.seer_survival import hbn, lr_selection
|
||||
from models.cama.seer_survival.natural import NaturalResults, fit_natural
|
||||
from models.cama.seer_survival.settings import ModelingSettings
|
||||
|
||||
# seaborn's "whitegrid", which the script set globally for its figures
|
||||
WHITEGRID = {"axes.facecolor": "white", "axes.edgecolor": ".8", "axes.grid": True, "grid.color": ".8",
|
||||
"grid.linestyle": "-", "axes.axisbelow": True}
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Design:
|
||||
X: pd.DataFrame
|
||||
y: pd.Series
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Split:
|
||||
X_train: pd.DataFrame
|
||||
X_test: pd.DataFrame
|
||||
y_train: pd.Series
|
||||
y_test: pd.Series
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class HbnFit:
|
||||
model: object # the fitted DiscreteBayesianNetwork
|
||||
edges: list
|
||||
bn_train: pd.DataFrame
|
||||
bn_test: pd.DataFrame
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the data
|
||||
|
||||
def balanced_raw(balanced_csv: str) -> pd.DataFrame:
|
||||
return pd.read_csv(balanced_csv, dtype=str)
|
||||
|
||||
|
||||
def fit_race_column(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> str | None:
|
||||
"""SEER's race column as it comes (the recoding never recodes it), found by keyword; None when it is already one of
|
||||
the canonical map's columns."""
|
||||
race = next((c for c in balanced_raw.columns if "race" in c.lower().replace("_", " ")), None)
|
||||
return None if race in modeling.canonical_map else race
|
||||
|
||||
|
||||
def fit_rename_map(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> dict:
|
||||
"""The columns that exist -> canonical names; the depuration may have kept `Tamano_tumor_cat` instead of
|
||||
`Tumor_group`, and then that one is the tumor size."""
|
||||
mapping = dict(modeling.canonical_map)
|
||||
if "Tumor_group" not in balanced_raw.columns and "Tamano_tumor_cat" in balanced_raw.columns:
|
||||
mapping["Tamano_tumor_cat"] = "Tamano_tumor"
|
||||
return {k: v for k, v in mapping.items() if k in balanced_raw.columns}
|
||||
|
||||
|
||||
def fit_frame(balanced_raw: pd.DataFrame, fit_rename_map: dict, fit_race_column: str | None) -> pd.DataFrame:
|
||||
"""The balanced cohort under the canonical names, with `outcome` (1 = survives). It SELECTS by the original names
|
||||
and only then renames, so a raw SEER column that already has a canonical name is never carried along."""
|
||||
df = balanced_raw[list(fit_rename_map.keys())].rename(columns=fit_rename_map).copy()
|
||||
if fit_race_column:
|
||||
df["Race"] = balanced_raw[fit_race_column]
|
||||
dup = df.columns[df.columns.duplicated()].tolist()
|
||||
assert not dup, f"Columnas duplicadas tras construir df: {dup}. Revisar canonical_map / la columna de raza."
|
||||
assert (df["Outcome_cat"] == "Desconocido").sum() == 0, \
|
||||
"Se esperaba que la cohorte balanceada ya excluyera el desenlace desconocido."
|
||||
df["outcome"] = (df["Outcome_cat"] == "Sobrevive").astype(int)
|
||||
return df
|
||||
|
||||
|
||||
def fit_features(fit_frame: pd.DataFrame, modeling: ModelingSettings) -> list[str]:
|
||||
"""The categorical covariates present, in the settings' order."""
|
||||
return [c for c in modeling.categorical_order if c in fit_frame.columns]
|
||||
|
||||
|
||||
def fit_design(fit_frame: pd.DataFrame, fit_features: list[str]) -> Design:
|
||||
enc = lr_selection.encode(fit_frame, fit_features)
|
||||
X = pd.get_dummies(enc[fit_features], drop_first=True).astype(float)
|
||||
constant = [c for c in X.columns if X[c].nunique() <= 1]
|
||||
return Design(X.drop(columns=constant) if constant else X, enc["outcome"])
|
||||
|
||||
|
||||
def fit_split(fit_design: Design, modeling: ModelingSettings) -> Split:
|
||||
X_train, X_test, y_train, y_test = train_test_split(
|
||||
fit_design.X, fit_design.y, test_size=modeling.test_size, random_state=modeling.random_state,
|
||||
stratify=fit_design.y)
|
||||
constant = [c for c in X_train.columns if X_train[c].nunique() <= 1]
|
||||
if constant:
|
||||
X_train, X_test = X_train.drop(columns=constant), X_test.drop(columns=constant)
|
||||
return Split(X_train, X_test, y_train, y_test)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- stepwise logistic regression
|
||||
|
||||
def lr_selected(fit_split: Split, modeling: ModelingSettings) -> list[str]:
|
||||
"""The stepwise selection over the pre-filtered columns, on a stratified subsample of the train."""
|
||||
s = modeling
|
||||
prefiltered = lr_selection.prefiltered_columns(fit_split.X_train, fit_split.y_train, s.prefilter_alpha,
|
||||
s.max_candidates, always_sort=False)
|
||||
X_search, y_search = lr_selection.search_sample(fit_split.X_train, fit_split.y_train, prefiltered,
|
||||
s.max_search_rows, s.random_state)
|
||||
return lr_selection.stepwise_selection(X_search, y_search, s.alpha_in, s.alpha_out)
|
||||
|
||||
|
||||
def lr_model(fit_split: Split, lr_selected: list[str], modeling: ModelingSettings) -> object:
|
||||
"""The final LR, refitted on the WHOLE train with the selected variables."""
|
||||
return sm.Logit(fit_split.y_train, sm.add_constant(fit_split.X_train[lr_selected])).fit(
|
||||
disp=0, method="bfgs", maxiter=modeling.lr_maxiter)
|
||||
|
||||
|
||||
def lr_odds_ratios(lr_model: object) -> pd.DataFrame:
|
||||
conf = lr_model.conf_int()
|
||||
conf["OR"] = lr_model.params
|
||||
conf.columns = ["2.5%", "97.5%", "OR"]
|
||||
table = np.exp(conf)
|
||||
table["p_value"] = lr_model.pvalues
|
||||
return table.round(3)
|
||||
|
||||
|
||||
def lr_test_prediction(fit_split: Split, lr_model: object, lr_selected: list[str]) -> pd.Series:
|
||||
return lr_model.predict(sm.add_constant(fit_split.X_test[lr_selected], has_constant="add"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- hybrid Bayesian network
|
||||
|
||||
def hbn_fit(fit_frame: pd.DataFrame, fit_features: list[str], modeling: ModelingSettings) -> HbnFit:
|
||||
s = modeling
|
||||
enc = lr_selection.encode(fit_frame, fit_features)
|
||||
bn_cols = [c for c in fit_features if c in enc.columns] + ["outcome"]
|
||||
small = enc[bn_cols].astype(str)
|
||||
bn_train, bn_test = train_test_split(small, test_size=s.test_size, random_state=s.random_state,
|
||||
stratify=small["outcome"])
|
||||
edges = hbn.learn_structure(bn_train, bn_cols, s, s.n_restarts, s.random_state)
|
||||
return HbnFit(hbn.fit_network(edges, bn_train), edges, bn_train, bn_test)
|
||||
|
||||
|
||||
def hbn_test_prediction(hbn_fit: HbnFit) -> pd.DataFrame:
|
||||
"""The HBN's test rows with `pred`, the survival probability; rows whose query failed are dropped."""
|
||||
preds = hbn.predict_survival(hbn_fit.model, hbn_fit.bn_test)
|
||||
return hbn_fit.bn_test.assign(pred=preds).dropna(subset=["pred"])
|
||||
|
||||
|
||||
def hbn_arcs(hbn_fit: HbnFit) -> pd.DataFrame:
|
||||
return pd.DataFrame(list(hbn_fit.model.edges()), columns=["origen", "destino"])
|
||||
|
||||
|
||||
def hbn_arc_strength(hbn_fit: HbnFit, modeling: ModelingSettings) -> pd.DataFrame:
|
||||
return hbn.arc_strength(hbn_fit.model, hbn_fit.bn_train, modeling.bdeu_ess)
|
||||
|
||||
|
||||
def hbn_graph_figure(hbn_fit: HbnFit, modeling: ModelingSettings) -> Figure:
|
||||
import networkx as nx
|
||||
|
||||
with rc_context(WHITEGRID):
|
||||
fig = Figure(figsize=(10, 8))
|
||||
ax = fig.subplots()
|
||||
G = nx.DiGraph(hbn_fit.model.edges())
|
||||
pos = nx.spring_layout(G, seed=modeling.random_state, k=0.8)
|
||||
nx.draw(G, pos, ax=ax, with_labels=True, node_color="lightblue", node_size=2500, font_size=8, arrowsize=15)
|
||||
ax.set_title("Estructura de la Red Bayesiana Híbrida (aproximación)")
|
||||
return fig
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the internal test: LR vs HBN
|
||||
|
||||
def auc_internal(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame:
|
||||
return pd.DataFrame([
|
||||
{"modelo": "LR", "AUC": roc_auc_score(fit_split.y_test, lr_test_prediction)},
|
||||
{"modelo": "HBN", "AUC": roc_auc_score(hbn_test_prediction["outcome"].astype(int), hbn_test_prediction["pred"])},
|
||||
]).round(4)
|
||||
|
||||
|
||||
def roc_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame,
|
||||
auc_internal: pd.DataFrame) -> Figure:
|
||||
hb = hbn_test_prediction
|
||||
fpr_lr, tpr_lr, _ = roc_curve(fit_split.y_test, lr_test_prediction)
|
||||
fpr_hbn, tpr_hbn, _ = roc_curve(hb["outcome"].astype(int), hb["pred"])
|
||||
auc_lr, auc_hbn = auc_internal["AUC"].tolist()
|
||||
with rc_context(WHITEGRID):
|
||||
fig = Figure(figsize=(7, 6))
|
||||
ax = fig.subplots()
|
||||
ax.plot(fpr_lr, tpr_lr, label=f"LR (AUC={auc_lr:.3f})", color="black")
|
||||
ax.plot(fpr_hbn, tpr_hbn, label=f"HBN (AUC={auc_hbn:.3f})", color="crimson")
|
||||
ax.plot([0, 1], [0, 1], linestyle="--", color="gray")
|
||||
ax.set_xlabel("1 - Especificidad")
|
||||
ax.set_ylabel("Sensibilidad")
|
||||
ax.set_title("Curvas ROC -- comparacion LR vs. HBN")
|
||||
ax.legend()
|
||||
return fig
|
||||
|
||||
|
||||
def calibration_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure:
|
||||
hb = hbn_test_prediction
|
||||
true_lr, pred_lr = calibration_curve(fit_split.y_test, lr_test_prediction, n_bins=10)
|
||||
true_hbn, pred_hbn = calibration_curve(hb["outcome"].astype(int), hb["pred"], n_bins=10)
|
||||
with rc_context(WHITEGRID):
|
||||
fig = Figure(figsize=(7, 6))
|
||||
ax = fig.subplots()
|
||||
ax.plot(pred_lr, true_lr, marker="o", label="LR", color="black")
|
||||
ax.plot(pred_hbn, true_hbn, marker="o", label="HBN", color="crimson")
|
||||
ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Calibracion perfecta")
|
||||
ax.set_xlabel("Probabilidad predicha")
|
||||
ax.set_ylabel("Probabilidad observada")
|
||||
ax.set_title("Curvas de calibracion")
|
||||
ax.legend()
|
||||
return fig
|
||||
|
||||
|
||||
def dca_figure(lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure | None:
|
||||
"""The decision-curve (net benefit) figure, or None when `dcurves` isn't installed."""
|
||||
try:
|
||||
import matplotlib.pyplot as plt
|
||||
from dcurves import dca, plot_graphs
|
||||
except ImportError:
|
||||
return None
|
||||
plt.switch_backend("Agg") # `plot_graphs` draws with pyplot and shows: never open a window from a pipeline
|
||||
hb = hbn_test_prediction
|
||||
data = pd.DataFrame({"outcome": hb["outcome"].astype(int).values,
|
||||
"lr_pred": lr_test_prediction.reindex(hb.index).values, "hbn_pred": hb["pred"].values})
|
||||
result = dca(data=data, outcome="outcome", modelnames=["lr_pred", "hbn_pred"])
|
||||
plt.close("all")
|
||||
with rc_context(WHITEGRID):
|
||||
plot_graphs(plot_df=result, graph_type="net_benefit", y_limits=[-0.05, 0.5])
|
||||
fig = plt.gcf()
|
||||
plt.close("all")
|
||||
return fig
|
||||
|
||||
|
||||
def _differentiation(y_true, y_prob, threshold: float) -> dict:
|
||||
tn, fp, fn, tp = confusion_matrix(y_true, (y_prob >= threshold).astype(int)).ravel()
|
||||
return {"ACC": (tp + tn) / (tp + tn + fp + fn), "TPR": tp / (tp + fn), "TNR": tn / (tn + fp),
|
||||
"PPV": tp / (tp + fp) if (tp + fp) > 0 else np.nan, "NPV": tn / (tn + fn) if (tn + fn) > 0 else np.nan}
|
||||
|
||||
|
||||
def _youden(y_true, y_prob) -> float:
|
||||
fpr, tpr, thresholds = roc_curve(y_true, y_prob)
|
||||
return thresholds[np.argmax(tpr - fpr)]
|
||||
|
||||
|
||||
def differentiation_table(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Accuracy, sensitivity, specificity and predictive values of each model at the 0.5 threshold and at its own
|
||||
Youden-optimal one."""
|
||||
y_lr, p_lr = fit_split.y_test.values, lr_test_prediction.values
|
||||
y_hbn, p_hbn = hbn_test_prediction["outcome"].astype(int).values, hbn_test_prediction["pred"].values
|
||||
thr_lr, thr_hbn = _youden(y_lr, p_lr), _youden(y_hbn, p_hbn)
|
||||
rows = [{"Model": "LR", "Umbral": 0.50, **_differentiation(y_lr, p_lr, 0.5)},
|
||||
{"Model": "HBN tabular", "Umbral": 0.50, **_differentiation(y_hbn, p_hbn, 0.5)},
|
||||
{"Model": "LR", "Umbral": round(thr_lr, 3), **_differentiation(y_lr, p_lr, thr_lr)},
|
||||
{"Model": "HBN tabular", "Umbral": round(thr_hbn, 3), **_differentiation(y_hbn, p_hbn, thr_hbn)}]
|
||||
return pd.DataFrame(rows).set_index(["Model", "Umbral"]).round(2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the natural population
|
||||
|
||||
def natural_raw(natural_csv: str, modeling: ModelingSettings) -> pd.DataFrame | None:
|
||||
"""The natural population's file; None when the phase is off or the file isn't there."""
|
||||
if not modeling.run_lr_natural or not os.path.exists(natural_csv):
|
||||
return None
|
||||
return pd.read_csv(natural_csv, dtype=str)
|
||||
|
||||
|
||||
def natural_results(natural_raw: pd.DataFrame | None, fit_frame: pd.DataFrame, fit_rename_map: dict,
|
||||
fit_race_column: str | None, fit_features: list[str], fit_split: Split, lr_model: object,
|
||||
lr_selected: list[str], modeling: ModelingSettings) -> NaturalResults | None:
|
||||
if natural_raw is None:
|
||||
return None
|
||||
return fit_natural(natural_raw, fit_frame, fit_rename_map, fit_race_column, fit_features, fit_split.X_train,
|
||||
fit_split.y_train, lr_model, lr_selected, modeling)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""The logistic regression on the NATURAL population (every patient with a known outcome, before the undersampling),
|
||||
compared with the balanced model on the same common test set; apart from the modeling nodes (`modeling.py`). Plain
|
||||
functions with no I/O. Ported from `04_modelado.py` (phase 6B).
|
||||
|
||||
The balanced model is compared both with its raw probabilities and with an intercept correction for the prevalence shift;
|
||||
the natural model is fitted with and without the treatment variables. The common test set is the natural test patients
|
||||
that the balanced model did not train on.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.seer_survival import lr_selection
|
||||
from models.cama.seer_survival.settings import ModelingSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class NaturalResults:
|
||||
odds_ratios: pd.DataFrame # LR on the natural population
|
||||
odds_ratios_no_treatment: pd.DataFrame
|
||||
comparison: pd.DataFrame # balanced raw / corrected / natural / natural without treatment
|
||||
auc_by_stage: pd.DataFrame # balanced vs natural
|
||||
auc_by_stage_no_treatment: pd.DataFrame
|
||||
calibration_deciles: pd.DataFrame
|
||||
|
||||
|
||||
def _odds_table(model) -> pd.DataFrame:
|
||||
ci = np.exp(model.conf_int())
|
||||
ci["OR_supervivencia"] = np.exp(model.params)
|
||||
ci.columns = ["2.5%", "97.5%", "OR_supervivencia"]
|
||||
ci["p"] = model.pvalues
|
||||
return ci.round(3)
|
||||
|
||||
|
||||
def _logit(p):
|
||||
p = np.clip(p, 1e-9, 1 - 1e-9)
|
||||
return np.log(p / (1 - p))
|
||||
|
||||
|
||||
def _sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
|
||||
def _stage_aucs(stage, y, preds: dict[str, np.ndarray], min_n: int = 50) -> pd.DataFrame:
|
||||
"""Per stage with at least `min_n` patients and both outcomes: n, deaths and the AUC of each prediction."""
|
||||
rows = []
|
||||
for s in sorted(set(stage)):
|
||||
m = stage == s
|
||||
if m.sum() >= min_n and len(set(y[m])) == 2:
|
||||
rows.append({"Estadio": s, "n": int(m.sum()), "muertes": int((1 - y[m]).sum()),
|
||||
**{name: round(roc_auc_score(y[m], p[m]), 3) for name, p in preds.items()}})
|
||||
return pd.DataFrame(rows).set_index("Estadio")
|
||||
|
||||
|
||||
def _deciles(p_survival, y, name: str) -> pd.DataFrame:
|
||||
risk, death = 1 - p_survival, 1 - y
|
||||
d = pd.DataFrame({"riesgo": risk, "muerte": death})
|
||||
d["decil"] = pd.qcut(d["riesgo"].rank(method="first"), 10, labels=False) + 1
|
||||
t = d.groupby("decil").agg(n=("muerte", "size"), muertes=("muerte", "sum"), riesgo_predicho=("riesgo", "mean"),
|
||||
riesgo_observado=("muerte", "mean")).round(4)
|
||||
t["modelo"] = name
|
||||
return t
|
||||
|
||||
|
||||
def fit_natural(natural_raw: pd.DataFrame, df: pd.DataFrame, rename_map: dict, race_column: str | None,
|
||||
cat_cols: list[str], X_train: pd.DataFrame, y_train: pd.Series, final_lr_model, selected: list[str],
|
||||
s: ModelingSettings) -> NaturalResults:
|
||||
dn_raw = natural_raw[natural_raw["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
|
||||
in_balanced = dn_raw["en_balanceado"].astype(int).values == 1
|
||||
dn = dn_raw[list(rename_map.keys())].rename(columns=rename_map).copy()
|
||||
if race_column and race_column in dn_raw.columns:
|
||||
dn["Race"] = dn_raw[race_column]
|
||||
for c in cat_cols:
|
||||
dn[c] = dn[c].fillna("Desconocido").astype(str)
|
||||
y_nat = (dn["Outcome_cat"] == "Sobrevive").astype(int)
|
||||
|
||||
# the balanced rows of the natural file must be EXACTLY the balanced file's, in the same order
|
||||
idx_b = np.where(in_balanced)[0]
|
||||
assert len(idx_b) == len(df), f"El archivo natural trae {len(idx_b)} filas balanceadas y df tiene {len(df)}"
|
||||
for c in ["Estadio", "Tratamiento_quirurgico", "Outcome_cat"]:
|
||||
assert (dn.loc[idx_b, c].values == df[c].values).all(), \
|
||||
f"Las filas balanceadas no coinciden en {c}: regenera el archivo natural con el balanceo actual"
|
||||
position = pd.Series(idx_b, index=df.index) # row of df -> row of dn
|
||||
train_balanced = set(position.loc[X_train.index]) # natural rows the balanced model trained on
|
||||
|
||||
# encoding (reference = the most frequent category) and the natural split
|
||||
Xn_full = pd.get_dummies(dn[cat_cols], drop_first=False).astype(float)
|
||||
ref_cols = {}
|
||||
for c in cat_cols:
|
||||
cols_c = [k for k in Xn_full.columns if k.startswith(c + "_") and k[len(c) + 1:] in set(dn[c])]
|
||||
ref_cols[c] = Xn_full[cols_c].sum().idxmax()
|
||||
Xn = Xn_full.drop(columns=list(ref_cols.values()))
|
||||
|
||||
tr_n, te_n = train_test_split(np.arange(len(dn)), test_size=s.natural_test_size, random_state=s.random_state,
|
||||
stratify=y_nat)
|
||||
Xn_train, yn_train = Xn.iloc[tr_n], y_nat.iloc[tr_n]
|
||||
common = np.array([i for i in te_n if i not in train_balanced]) # the COMMON test set
|
||||
|
||||
varying = [c for c in Xn_train.columns if Xn_train[c].nunique() > 1]
|
||||
Xn_train = Xn_train[varying]
|
||||
pre_cols = lr_selection.prefiltered_columns(Xn_train, yn_train, s.prefilter_alpha, s.max_candidates)
|
||||
|
||||
# stepwise and final fit on the natural population
|
||||
search_idx = None
|
||||
if len(Xn_train) > s.natural_search_rows:
|
||||
search_idx, _ = train_test_split(Xn_train.index, train_size=s.natural_search_rows,
|
||||
random_state=s.random_state, stratify=yn_train)
|
||||
Xs, ys = Xn_train.loc[search_idx, pre_cols], yn_train.loc[search_idx]
|
||||
else:
|
||||
Xs, ys = Xn_train[pre_cols], yn_train
|
||||
sel_nat = lr_selection.stepwise_selection(Xs, ys, s.alpha_in, s.alpha_out)
|
||||
lr_nat = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nat])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
|
||||
|
||||
# comparison on the common natural test set, with an intercept correction of the balanced model
|
||||
prev_nat, prev_bal = float(y_nat.mean()), float(y_train.mean())
|
||||
shift = np.log(prev_nat / (1 - prev_nat)) - np.log(prev_bal / (1 - prev_bal))
|
||||
Xc, yc, stage_c = Xn.iloc[common], y_nat.iloc[common].values, dn["Estadio"].iloc[common].values
|
||||
p_nat = lr_nat.predict(sm.add_constant(Xc[sel_nat], has_constant="add")).values
|
||||
Xb_c = Xn_full.iloc[common].reindex(columns=X_train.columns, fill_value=0.0)
|
||||
p_bal_raw = final_lr_model.predict(sm.add_constant(Xb_c[selected], has_constant="add")).values
|
||||
p_bal_cor = _sigmoid(_logit(p_bal_raw) + shift)
|
||||
|
||||
def row(name, p):
|
||||
m3 = np.isin(stage_c, ["I", "II", "III"])
|
||||
auc3 = roc_auc_score(yc[m3], p[m3]) if len(set(yc[m3])) == 2 else np.nan
|
||||
return {"modelo": name, "AUC": roc_auc_score(yc, p), "AUC estadios I-III": auc3,
|
||||
"PR-AUC (muerte)": average_precision_score(1 - yc, 1 - p), "Brier": brier_score_loss(yc, p),
|
||||
"prob. media predicha": p.mean(), "prob. media real": yc.mean()}
|
||||
|
||||
comp = pd.DataFrame([row("LR balanceada (probabilidades crudas)", p_bal_raw),
|
||||
row("LR balanceada + corrección de intercepto", p_bal_cor),
|
||||
row("LR población natural", p_nat)]).set_index("modelo").round(3)
|
||||
auc_stage = _stage_aucs(stage_c, yc, {"AUC LR balanceada": p_bal_raw, "AUC LR natural": p_nat})
|
||||
|
||||
# the natural LR WITHOUT treatment
|
||||
cols_nt = [c for c in Xn_train.columns if not any(c.startswith(t + "_") for t in s.treatment_vars)]
|
||||
pre_cols_nt = lr_selection.prefiltered_columns(Xn_train[cols_nt], yn_train, s.prefilter_alpha, s.max_candidates)
|
||||
if len(Xn_train) > s.natural_search_rows:
|
||||
Xs2, ys2 = Xn_train.loc[search_idx, pre_cols_nt], yn_train.loc[search_idx]
|
||||
else:
|
||||
Xs2, ys2 = Xn_train[pre_cols_nt], yn_train
|
||||
sel_nt = lr_selection.stepwise_selection(Xs2, ys2, s.alpha_in, s.alpha_out)
|
||||
lr_nt = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nt])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
|
||||
p_nt = lr_nt.predict(sm.add_constant(Xc[sel_nt], has_constant="add")).values
|
||||
comp2 = pd.concat([comp, pd.DataFrame([row("LR población natural SIN tratamiento", p_nt)]).set_index("modelo").round(3)])
|
||||
auc_stage_nt = _stage_aucs(stage_c, yc, {"AUC natural": p_nat, "AUC natural SIN tratamiento": p_nt})
|
||||
|
||||
deciles = pd.concat([_deciles(p_nat, yc, "natural"), _deciles(p_nt, yc, "natural sin tratamiento")]).reset_index()
|
||||
return NaturalResults(_odds_table(lr_nat), _odds_table(lr_nt), comp2, auc_stage, auc_stage_nt, deciles)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Runs the stages of the SEER survival pipeline in order, in a data folder that holds their inputs and outputs. Replaces
|
||||
`ejecutar_pipeline.py`: the stages are Hamilton DAGs (`run.py`) run in this process, not scripts run one per process.
|
||||
|
||||
python -m models.cama.seer_survival --data DIR # every stage, skipping the ones that are current
|
||||
python -m models.cama.seer_survival --data DIR --solo 05 # only that stage
|
||||
python -m models.cama.seer_survival --data DIR --desde 02 # from that stage on
|
||||
python -m models.cama.seer_survival --data DIR --forzar 02 04 # run those even when current
|
||||
python -m models.cama.seer_survival --data DIR --todo # run all, skipping none
|
||||
|
||||
A stage is skipped only when its outputs exist, are not empty and are newer than its code and its inputs. Writes
|
||||
`bitacora_pipeline.csv` (stage, state, seconds) to the data folder.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from models.cama.seer_survival import run
|
||||
from models.cama.seer_survival.settings import TOML, Settings, load
|
||||
|
||||
PACKAGE = Path(__file__).parent
|
||||
RECODED = "dataframe_recodificado.csv"
|
||||
COLUMN_MAP = "mapeo_columnas_recodificadas.json"
|
||||
LOG = "bitacora_pipeline.csv"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Stage:
|
||||
id: str
|
||||
run: Callable[[Path, Settings], object]
|
||||
requires: tuple[str, ...]
|
||||
produces: tuple[str, ...] # empty: no single output to check, so the stage always runs
|
||||
code: tuple[str, ...] # the package files whose change makes the outputs stale
|
||||
|
||||
|
||||
STAGES = [
|
||||
Stage("01", lambda d, s: run.run_depuration(d / RECODED, d / COLUMN_MAP, d, s), (RECODED, COLUMN_MAP),
|
||||
(run.DEPURATED,), ("depuration.py", "depuration_stats.py", "settings.py", "run.py")),
|
||||
Stage("02", lambda d, s: run.run_balancing(d / run.DEPURATED, d, settings=s), (run.DEPURATED,),
|
||||
(run.BALANCED, run.PROPOSALS, run.NATURAL),
|
||||
("balancing.py", "balancing_stats.py", "categorization.py", "categorization_stats.py", "columns.py",
|
||||
"settings.py", "run.py")),
|
||||
Stage("03", lambda d, s: run.run_bootstrap(d / run.BALANCED, d, s), (run.BALANCED,),
|
||||
(run.BOOTSTRAP_INDICES, run.BOOTSTRAP_METADATA), ("bootstrap.py", "settings.py", "run.py")),
|
||||
Stage("04", lambda d, s: run.run_modeling(d / run.BALANCED, d, settings=s),
|
||||
(run.BALANCED, run.PROPOSALS, run.BOOTSTRAP_INDICES, run.BOOTSTRAP_METADATA, run.NATURAL), (),
|
||||
("modeling.py", "resampling.py", "replica.py", "lr_selection.py", "hbn.py", "natural.py", "settings.py",
|
||||
"run.py")),
|
||||
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
|
||||
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
|
||||
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
|
||||
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "settings.py", "run.py")),
|
||||
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
|
||||
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
|
||||
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"),
|
||||
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")),
|
||||
]
|
||||
|
||||
|
||||
def _mtime(p: Path) -> float:
|
||||
return p.stat().st_mtime
|
||||
|
||||
|
||||
def is_current(stage: Stage, data: Path) -> bool:
|
||||
"""The outputs exist, are not empty and are newer than the stage's code, the settings and its inputs."""
|
||||
outputs = [data / p for p in stage.produces]
|
||||
if not outputs or not all(p.exists() and p.stat().st_size > 0 for p in outputs):
|
||||
return False
|
||||
reference = max([_mtime(TOML)] + [_mtime(PACKAGE / f) for f in stage.code]
|
||||
+ [_mtime(data / p) for p in stage.requires if (data / p).exists()])
|
||||
return min(_mtime(p) for p in outputs) >= reference
|
||||
|
||||
|
||||
def save_log(data: Path, log: list[tuple]) -> None:
|
||||
with open(data / LOG, "w", newline="", encoding="utf8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["etapa", "estado", "segundos"])
|
||||
w.writerows(log)
|
||||
|
||||
|
||||
def run_pipeline(data: Path, only=None, since=None, force=(), everything: bool = False,
|
||||
settings: Settings | None = None) -> list[tuple]:
|
||||
"""Runs the selected stages; returns the log rows (stage, `ok` | `saltada`, seconds). A stage that wrote outputs
|
||||
makes every later one run again."""
|
||||
settings = settings or load()
|
||||
data = Path(data)
|
||||
selected = [e for e in STAGES if (not only or e.id in only) and (not since or e.id >= since)]
|
||||
log, redo = [], False
|
||||
for stage in selected:
|
||||
missing = [p for p in stage.requires if not (data / p).exists()]
|
||||
if missing:
|
||||
raise FileNotFoundError(f"Etapa {stage.id}: faltan entradas {missing}")
|
||||
if not (everything or stage.id in force or redo) and is_current(stage, data):
|
||||
log.append((stage.id, "saltada", 0))
|
||||
continue
|
||||
t0 = time.time()
|
||||
try:
|
||||
stage.run(data, settings)
|
||||
except Exception:
|
||||
log.append((stage.id, "error", round(time.time() - t0)))
|
||||
save_log(data, log)
|
||||
raise
|
||||
log.append((stage.id, "ok", round(time.time() - t0)))
|
||||
save_log(data, log)
|
||||
redo = redo or bool(stage.produces)
|
||||
save_log(data, log)
|
||||
return log
|
||||
|
||||
|
||||
def main(argv=None) -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--data", default=".", help="folder with the stages' inputs and outputs (default: the current one)")
|
||||
ap.add_argument("--solo", nargs="+")
|
||||
ap.add_argument("--desde")
|
||||
ap.add_argument("--forzar", nargs="+", default=[])
|
||||
ap.add_argument("--todo", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
try:
|
||||
run_pipeline(Path(a.data), a.solo, a.desde, a.forzar, a.todo)
|
||||
except FileNotFoundError as e:
|
||||
sys.exit(str(e))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""One replica of the modeling pipeline (outcome, encoding, split, stepwise LR, HBN) on a frame, with the seed that
|
||||
fixes its split: what the bootstrap and the comparison of categorization proposals repeat. Plain functions with no I/O.
|
||||
Ported from `04_modelado.py` (`ejecutar_replica_pipeline`)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.seer_survival import hbn, lr_selection
|
||||
from models.cama.seer_survival.settings import ModelingSettings
|
||||
|
||||
|
||||
def run_replica(df_b: pd.DataFrame, seed: int, cat_cols: list[str], s: ModelingSettings, include_hbn: bool,
|
||||
n_restarts: int) -> dict:
|
||||
"""AUC of the stepwise LR and of the HBN on the replica's 30 % test, how many variables each kept, the LR's
|
||||
coefficients and the HBN's outcome parents. Anything that can't be computed stays NaN / None."""
|
||||
out = {"auc_lr": np.nan, "auc_hbn": np.nan, "n_selected_lr": np.nan, "n_parents_hbn": np.nan,
|
||||
"coefs": None, "padres": None}
|
||||
|
||||
df_b = df_b.copy()
|
||||
df_b["outcome"] = (df_b["Outcome_cat"] == "Sobrevive").astype(int)
|
||||
df_enc_b = lr_selection.encode(df_b, cat_cols)
|
||||
|
||||
X_b = pd.get_dummies(df_enc_b[cat_cols], drop_first=True).astype(float)
|
||||
y_b = df_enc_b["outcome"]
|
||||
constant = [c for c in X_b.columns if X_b[c].nunique() <= 1]
|
||||
if constant:
|
||||
X_b = X_b.drop(columns=constant)
|
||||
if y_b.nunique() < 2:
|
||||
return out
|
||||
|
||||
X_train_b, X_test_b, y_train_b, y_test_b = train_test_split(
|
||||
X_b, y_b, test_size=s.test_size, random_state=seed, stratify=y_b)
|
||||
constant_train = [c for c in X_train_b.columns if X_train_b[c].nunique() <= 1]
|
||||
if constant_train:
|
||||
X_train_b = X_train_b.drop(columns=constant_train)
|
||||
X_test_b = X_test_b.drop(columns=constant_train)
|
||||
|
||||
prefiltered = lr_selection.prefiltered_columns(X_train_b, y_train_b, s.prefilter_alpha, s.max_candidates)
|
||||
if not prefiltered:
|
||||
return out
|
||||
X_search, y_search = lr_selection.search_sample(X_train_b, y_train_b, prefiltered, s.max_search_rows, seed)
|
||||
selected = lr_selection.stepwise_selection(X_search, y_search, s.alpha_in, s.alpha_out)
|
||||
out["n_selected_lr"] = len(selected)
|
||||
if selected:
|
||||
model = lr_selection.safe_fit_logit(y_train_b, sm.add_constant(X_train_b[selected]))
|
||||
if model is not None:
|
||||
out["coefs"] = model.params.drop("const", errors="ignore").to_dict()
|
||||
out["auc_lr"] = roc_auc_score(y_test_b, model.predict(sm.add_constant(X_test_b[selected], has_constant="add")))
|
||||
|
||||
if include_hbn:
|
||||
try:
|
||||
bn_cols = [c for c in cat_cols if c in df_enc_b.columns] + ["outcome"]
|
||||
small = df_enc_b[bn_cols].astype(str)
|
||||
bn_train, bn_test = train_test_split(small, test_size=s.test_size, random_state=seed,
|
||||
stratify=small["outcome"])
|
||||
edges = hbn.learn_structure(bn_train, bn_cols, s, n_restarts, seed)
|
||||
parents = [u for (u, v) in edges if v == "outcome"]
|
||||
out["n_parents_hbn"] = len(parents)
|
||||
out["padres"] = parents
|
||||
model_hbn = hbn.fit_network(edges, bn_train)
|
||||
bn_test = bn_test.assign(pred=hbn.predict_survival(model_hbn, bn_test)).dropna(subset=["pred"])
|
||||
out["auc_hbn"] = roc_auc_score(bn_test["outcome"].astype(int), bn_test["pred"])
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Stage 04, resampling: the pipeline repeated on bootstrap resamples (the indices of stage 03) and on each
|
||||
categorization proposal of stage 02b, to put intervals on the AUCs and compare the proposals on the same splits.
|
||||
|
||||
Each public function is a Hamilton node; it continues `modeling.py` (`fit_frame`, `fit_features`) and takes
|
||||
`bootstrap_indices` (stage 03's array), `proposals_csv` and `modeling` (its settings) as inputs. One replica is
|
||||
`replica.py`. Both loops stop by themselves when their time cap is reached and use what they have.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival.replica import run_replica
|
||||
from models.cama.seer_survival.settings import ModelingSettings
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- bootstrap
|
||||
|
||||
def bootstrap_runs(fit_frame: pd.DataFrame, bootstrap_indices: np.ndarray, fit_features: list[str],
|
||||
modeling: ModelingSettings) -> list[dict]:
|
||||
"""The replica pipeline on each resample, in order, until `n_bootstrap_run` or the time cap."""
|
||||
assert bootstrap_indices.shape[1] == len(fit_frame), (
|
||||
f"bootstrap_indices tiene {bootstrap_indices.shape[1]} filas por réplica, pero el balanceado tiene "
|
||||
f"{len(fit_frame)}: la etapa de bootstrapping debe correr sobre el mismo CSV balanceado.")
|
||||
s = modeling
|
||||
runs, t0 = [], time.time()
|
||||
for b in range(s.n_bootstrap_run):
|
||||
if time.time() - t0 > s.bootstrap_max_seconds:
|
||||
break
|
||||
df_b = fit_frame.iloc[bootstrap_indices[b]].reset_index(drop=True)
|
||||
runs.append(run_replica(df_b, s.random_state + b, fit_features, s, s.bootstrap_include_hbn,
|
||||
s.bootstrap_restarts))
|
||||
return runs
|
||||
|
||||
|
||||
def bootstrap_selection(bootstrap_runs: list[dict], fit_features: list[str]) -> pd.DataFrame:
|
||||
"""The terms each replica's LR kept, and the outcome's parents in each replica's HBN: how stable the selection is."""
|
||||
longest_first = sorted(fit_features, key=len, reverse=True)
|
||||
|
||||
def variable_of(term):
|
||||
return next((c for c in longest_first if term.startswith(c + "_")), term)
|
||||
|
||||
rows = []
|
||||
for b, res in enumerate(bootstrap_runs):
|
||||
if res["coefs"] is not None:
|
||||
rows.append({"replica": b, "modelo": "LR", "variable": "", "termino": "(replica)", "coef": np.nan})
|
||||
rows += [{"replica": b, "modelo": "LR", "variable": variable_of(t), "termino": t, "coef": v}
|
||||
for t, v in res["coefs"].items()]
|
||||
if res["padres"] is not None:
|
||||
rows.append({"replica": b, "modelo": "HBN", "variable": "", "termino": "(replica)", "coef": np.nan})
|
||||
rows += [{"replica": b, "modelo": "HBN", "variable": p, "termino": p, "coef": np.nan} for p in res["padres"]]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _interval(values) -> tuple[float, float, int]:
|
||||
arr = np.array([a for a in values if not np.isnan(a)])
|
||||
if len(arr) == 0:
|
||||
return (np.nan, np.nan, 0)
|
||||
lo, hi = np.percentile(arr, [2.5, 97.5])
|
||||
return (lo, hi, len(arr))
|
||||
|
||||
|
||||
def bootstrap_auc(bootstrap_runs: list[dict]) -> pd.DataFrame:
|
||||
"""Mean AUC and its 95 % percentile interval over the replicas with a valid AUC, per model."""
|
||||
rows = []
|
||||
for name, key in [("LR (stepwise)", "auc_lr"), ("HBN (CPT tabular)", "auc_hbn")]:
|
||||
values = [r[key] for r in bootstrap_runs]
|
||||
lo, hi, n_valid = _interval(values)
|
||||
rows.append({"modelo": name, "AUC medio": np.nanmean(values) if n_valid else np.nan,
|
||||
"IC 95% lo": lo, "IC 95% hi": hi, "replicas validas": n_valid})
|
||||
return pd.DataFrame(rows).round(3)
|
||||
|
||||
|
||||
def bootstrap_auc_difference(bootstrap_runs: list[dict]) -> pd.DataFrame | None:
|
||||
"""The paired difference LR - HBN over the replicas where both exist; None when there is none."""
|
||||
d = np.array([r["auc_lr"] for r in bootstrap_runs]) - np.array([r["auc_hbn"] for r in bootstrap_runs])
|
||||
d = d[~np.isnan(d)]
|
||||
if not len(d):
|
||||
return None
|
||||
return pd.DataFrame([{"dif_AUC_LR_menos_HBN": d.mean(), "IC95_inf": np.percentile(d, 2.5),
|
||||
"IC95_sup": np.percentile(d, 97.5), "pct_replicas_LR_gana": (d > 0).mean() * 100}]).round(4)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- categorization proposals
|
||||
|
||||
def proposal_runs(fit_frame: pd.DataFrame, proposals_csv: str, fit_features: list[str],
|
||||
modeling: ModelingSettings) -> pd.DataFrame:
|
||||
"""The replica pipeline for each proposal on `n_splits_prop` splits (the same seeds for all: a paired comparison)."""
|
||||
s = modeling
|
||||
prop = pd.read_csv(proposals_csv, dtype=str)
|
||||
assert len(prop) == len(fit_frame), (f"propuestas_categorizacion.csv tiene {len(prop)} filas y el balanceado "
|
||||
f"{len(fit_frame)}: deben salir del MISMO balanceo (mismo orden de filas)")
|
||||
ids = sorted({c.split("__", 1)[1] for c in prop.columns if "__" in c})
|
||||
if s.proposals_only:
|
||||
ids = [i for i in ids if i in s.proposals_only]
|
||||
results, t0, stop = [], time.time(), False
|
||||
for pid in ids:
|
||||
df_p = fit_frame.copy()
|
||||
k_age = k_tumor = None
|
||||
if f"Age_group__{pid}" in prop.columns:
|
||||
df_p["Edad"] = prop[f"Age_group__{pid}"].values
|
||||
k_age = df_p["Edad"].nunique()
|
||||
if f"Tumor_group__{pid}" in prop.columns and "Tamano_tumor" in df_p.columns:
|
||||
df_p["Tamano_tumor"] = prop[f"Tumor_group__{pid}"].values
|
||||
k_tumor = df_p["Tamano_tumor"].nunique(dropna=False)
|
||||
for split in range(s.n_splits_prop):
|
||||
if time.time() - t0 > s.proposals_max_seconds:
|
||||
stop = True
|
||||
break
|
||||
res = run_replica(df_p, s.random_state + split, fit_features, s, s.proposals_include_hbn,
|
||||
s.bootstrap_restarts)
|
||||
results.append({"propuesta": pid, "split": split, "K_edad": k_age, "K_tumor": k_tumor, **res})
|
||||
if stop:
|
||||
break
|
||||
return pd.DataFrame(results)
|
||||
|
||||
|
||||
def proposal_summary(proposal_runs: pd.DataFrame) -> pd.DataFrame:
|
||||
summary = (proposal_runs.groupby("propuesta")
|
||||
.agg(K_edad=("K_edad", "first"), K_tumor=("K_tumor", "first"),
|
||||
AUC_LR=("auc_lr", "mean"), sd_LR=("auc_lr", "std"),
|
||||
AUC_HBN=("auc_hbn", "mean"), sd_HBN=("auc_hbn", "std"),
|
||||
vars_LR=("n_selected_lr", "mean"), padres_HBN=("n_parents_hbn", "mean"),
|
||||
n_splits=("split", "count")).round(3))
|
||||
return summary.sort_values("AUC_LR", ascending=False)
|
||||
|
||||
|
||||
def proposal_deltas(proposal_runs: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each proposal's AUC minus the base proposal's (`P1_actual`, else the first), on the same splits."""
|
||||
runs = proposal_runs
|
||||
base = "P1_actual" if "P1_actual" in runs["propuesta"].values else runs["propuesta"].iloc[0]
|
||||
b = runs[runs["propuesta"] == base].set_index("split")
|
||||
rows = []
|
||||
for pid in runs["propuesta"].unique():
|
||||
if pid == base:
|
||||
continue
|
||||
j = b.join(runs[runs["propuesta"] == pid].set_index("split"), lsuffix="_b", rsuffix="_x", how="inner")
|
||||
rows.append({"propuesta": pid, f"ΔAUC_LR vs {base}": (j["auc_lr_x"] - j["auc_lr_b"]).mean(),
|
||||
f"ΔAUC_HBN vs {base}": (j["auc_hbn_x"] - j["auc_hbn_b"]).mean(), "splits_comparados": len(j)})
|
||||
return pd.DataFrame(rows).round(4)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The statistics of the risk-factor stage, apart from its nodes (`risk_factors.py`): the multivariable odds ratios,
|
||||
Benjamini-Hochberg, and the Kaplan-Meier survival difference against a reference category. Plain functions with no
|
||||
I/O. Ported from `06_factores_riesgo.py`."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
|
||||
|
||||
def reference(data: pd.DataFrame, v: str) -> str:
|
||||
"""The reference category of a variable: its most frequent one."""
|
||||
return data[v].value_counts().idxmax()
|
||||
|
||||
|
||||
def fit_odds(data: pd.DataFrame, death: np.ndarray, variables: list[str]) -> pd.DataFrame:
|
||||
"""The multivariable OR of death for each category of `variables` against the reference, by a binomial GLM."""
|
||||
X = pd.get_dummies(data[variables], drop_first=False).astype(float)
|
||||
refs = {v: f"{v}_{reference(data, v)}" for v in variables}
|
||||
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
model = sm.GLM(death, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = model.conf_int()
|
||||
return pd.DataFrame({"termino": X.columns, "OR_muerte": np.exp(model.params[X.columns].values),
|
||||
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
|
||||
"p": model.pvalues[X.columns].values})
|
||||
|
||||
|
||||
def variable_of(term: str, variables: list[str]) -> str:
|
||||
"""The variable a dummy's name belongs to (the longest name that prefixes it)."""
|
||||
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
|
||||
|
||||
|
||||
def benjamini_hochberg(p) -> np.ndarray:
|
||||
p = np.asarray(p, float)
|
||||
order = np.argsort(p)
|
||||
adjusted = np.empty_like(p)
|
||||
m = len(p)
|
||||
prev = 1.0
|
||||
for rank, i in zip(range(m, 0, -1), order[::-1]):
|
||||
prev = min(prev, p[i] * m / rank)
|
||||
adjusted[i] = prev
|
||||
return adjusted
|
||||
|
||||
|
||||
def km_at(months: np.ndarray, event: np.ndarray, horizon: int) -> tuple[float, float]:
|
||||
"""(S(horizon), its Greenwood standard error) from monthly follow-up."""
|
||||
T = int(months.max()) + 2
|
||||
d = np.bincount(months[event], minlength=T)
|
||||
c = np.bincount(months[~event], minlength=T)
|
||||
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
|
||||
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
|
||||
h = min(horizon, T - 1)
|
||||
S = np.prod(q[:h + 1])
|
||||
return S, S * np.sqrt(np.sum(v[:h + 1]))
|
||||
|
||||
|
||||
def survival_difference(data: pd.DataFrame, months: np.ndarray, event: np.ndarray, v: str, cat: str, ref: str,
|
||||
horizon: int) -> pd.Series:
|
||||
"""S(horizon) of the category minus the reference's, with its 95 % interval."""
|
||||
a = (data[v] == cat).values
|
||||
b = (data[v] == ref).values
|
||||
Sa, ea = km_at(months[a], event[a], horizon)
|
||||
Sb, eb = km_at(months[b], event[b], horizon)
|
||||
d = Sa - Sb
|
||||
se = np.sqrt(ea ** 2 + eb ** 2)
|
||||
return pd.Series({"n_categoria": int(a.sum()), "S18_categoria": Sa, "S18_referencia": Sb, "delta_S18": d,
|
||||
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
|
||||
|
||||
|
||||
def survival_differences(data, months, event, rows, horizon) -> pd.DataFrame:
|
||||
"""`survival_difference` for each (variable, category, reference) of `rows`."""
|
||||
return pd.DataFrame([survival_difference(data, months, event, v, c, r, horizon) for v, c, r in rows])
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Stage 06, risk factors: classifies each category of the intrinsic variables as a robust or suggestive risk or
|
||||
protective factor from four criteria (see `model.toml`, `[risk_factors]`): c1 the multivariable OR, c2 stability in the
|
||||
bootstrap, c3 the outcome's Markov blanket in the HBN, c4 the 18-month survival difference. Treatment variables are a
|
||||
clinical decision: they are reported apart, not classified.
|
||||
|
||||
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `natural_csv`,
|
||||
`bootstrap_selection_csv`, `hbn_arcs_csv` (stage 04's outputs) and `risk_factors` (its settings). The statistics are in
|
||||
`risk_factor_stats.py`.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import risk_factor_stats as stats
|
||||
from models.cama.seer_survival.settings import RiskFactorSettings
|
||||
|
||||
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
UNKNOWN_CATEGORY = "no aplica (categoria desconocida)"
|
||||
COLUMNS = ["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
|
||||
"freq_seleccion_bootstrap", "en_manta_markov", "S18_categoria", "S18_referencia", "delta_S18",
|
||||
"delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
|
||||
"criterios_cumplidos", "criterios_evaluados", "clasificacion"]
|
||||
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3,
|
||||
"no concluyente": 4}
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class FollowUp:
|
||||
death: np.ndarray # 1 = Muerte (the outcome at the horizon)
|
||||
months: np.ndarray # follow-up, capped at `cap_months`
|
||||
event: np.ndarray # died before the cap
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class BootstrapFrequency:
|
||||
frequency: pd.Series # per variable: the share of valid replicas whose LR kept it (NaN when there are none)
|
||||
n_replicas: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Classification:
|
||||
table: pd.DataFrame
|
||||
criteria: list[str] # the criteria that could be evaluated
|
||||
|
||||
|
||||
def _find_col(df: pd.DataFrame, keywords) -> str | None:
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the data
|
||||
|
||||
def risk_natural(natural_csv: str) -> pd.DataFrame:
|
||||
nat = pd.read_csv(natural_csv, dtype=str)
|
||||
return nat[nat["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
|
||||
|
||||
|
||||
def risk_data(risk_natural: pd.DataFrame, risk_factors: RiskFactorSettings) -> pd.DataFrame:
|
||||
"""The covariates under canonical names, the unknowns as one more category; race as it comes from SEER."""
|
||||
nat = risk_natural
|
||||
data = pd.DataFrame({v: nat[k].fillna("Desconocido").astype(str)
|
||||
for k, v in risk_factors.canonical_map.items() if k in nat.columns})
|
||||
race = _find_col(nat, ["race"])
|
||||
if race is not None and race not in risk_factors.canonical_map:
|
||||
data["Race"] = nat[race].fillna("Desconocido").astype(str)
|
||||
return data
|
||||
|
||||
|
||||
def risk_intrinsic(risk_data: pd.DataFrame, risk_factors: RiskFactorSettings) -> list[str]:
|
||||
return [v for v in risk_data.columns if v not in risk_factors.treatment]
|
||||
|
||||
|
||||
def risk_treatment(risk_data: pd.DataFrame, risk_factors: RiskFactorSettings) -> list[str]:
|
||||
return [v for v in risk_data.columns if v in risk_factors.treatment]
|
||||
|
||||
|
||||
def risk_follow_up(risk_natural: pd.DataFrame, risk_factors: RiskFactorSettings) -> FollowUp:
|
||||
nat, cap = risk_natural, risk_factors.cap_months
|
||||
months_col, vital_col = _find_col(nat, ["survival months"]), _find_col(nat, ["vital status"])
|
||||
raw = pd.to_numeric(nat[months_col], errors="coerce").fillna(0)
|
||||
return FollowUp(death=(nat["Outcome_cat"] == "Muerte").astype(int).values,
|
||||
months=np.minimum(raw.astype(int).values, cap),
|
||||
event=nat[vital_col].astype(str).str.lower().str.contains("dead").values & (raw.values < cap))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the criteria
|
||||
|
||||
def risk_odds(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
|
||||
risk_factors: RiskFactorSettings) -> pd.DataFrame:
|
||||
"""c1: the multivariable OR of death of each category (reference = the most frequent), significant when its 95 % CI
|
||||
doesn't cross 1 and its Benjamini-Hochberg p is below alpha."""
|
||||
tab = stats.fit_odds(risk_data, risk_follow_up.death, risk_intrinsic)
|
||||
tab["variable"] = [stats.variable_of(t, risk_intrinsic) for t in tab["termino"]]
|
||||
tab["categoria"] = [t[len(v) + 1:] for t, v in zip(tab["termino"], tab["variable"])]
|
||||
tab["referencia"] = [stats.reference(risk_data, v) for v in tab["variable"]]
|
||||
tab["p_ajustado_BH"] = stats.benjamini_hochberg(tab["p"])
|
||||
tab["direccion"] = np.where(tab["OR_muerte"] > 1, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < risk_factors.alpha)
|
||||
return tab
|
||||
|
||||
|
||||
def risk_survival(risk_odds: pd.DataFrame, risk_data: pd.DataFrame, risk_follow_up: FollowUp,
|
||||
risk_factors: RiskFactorSettings) -> pd.DataFrame:
|
||||
"""c4: the survival difference at the horizon against the reference, significant when its interval excludes 0 and it
|
||||
goes the way the OR says."""
|
||||
tab = risk_odds
|
||||
ds = stats.survival_differences(risk_data, risk_follow_up.months, risk_follow_up.event,
|
||||
zip(tab["variable"], tab["categoria"], tab["referencia"]), risk_factors.horizon)
|
||||
tab = pd.concat([tab.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
||||
tab["c4_supervivencia"] = (((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0))
|
||||
& (np.sign(tab["delta_S18"]) == np.where(tab["direccion"] == "riesgo", -1, 1)))
|
||||
return tab
|
||||
|
||||
|
||||
def risk_bootstrap_frequency(risk_intrinsic: list[str], bootstrap_selection_csv: str) -> BootstrapFrequency:
|
||||
"""c2's input: in how many of the bootstrap replicas each variable entered the LR (NaN without the file)."""
|
||||
freq, n_rep = pd.Series(np.nan, index=risk_intrinsic), 0
|
||||
if os.path.exists(bootstrap_selection_csv):
|
||||
sel = pd.read_csv(bootstrap_selection_csv)
|
||||
lr = sel[sel["modelo"] == "LR"]
|
||||
n_rep = int((lr["termino"] == "(replica)").sum())
|
||||
if n_rep > 0:
|
||||
per_var = lr[lr["termino"] != "(replica)"].groupby("variable")["replica"].nunique()
|
||||
freq = pd.Series({v: per_var.get(v, 0) / n_rep for v in risk_intrinsic})
|
||||
return BootstrapFrequency(freq, n_rep)
|
||||
|
||||
|
||||
def risk_stability(risk_survival: pd.DataFrame, risk_bootstrap_frequency: BootstrapFrequency,
|
||||
risk_factors: RiskFactorSettings) -> pd.DataFrame:
|
||||
"""c2: the variable's selection frequency is at least `freq_min`."""
|
||||
tab = risk_survival.copy()
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(risk_bootstrap_frequency.frequency)
|
||||
tab["c2_estabilidad"] = ((tab["freq_seleccion_bootstrap"] >= risk_factors.freq_min).astype(object)
|
||||
.where(tab["freq_seleccion_bootstrap"].notna(), np.nan))
|
||||
return tab
|
||||
|
||||
|
||||
def risk_markov_blanket(hbn_arcs_csv: str) -> set | None:
|
||||
"""The outcome's Markov blanket in the HBN (parents, children and the children's other parents); None without the
|
||||
file."""
|
||||
if not os.path.exists(hbn_arcs_csv):
|
||||
return None
|
||||
arcs = pd.read_csv(hbn_arcs_csv)
|
||||
parents = set(arcs.loc[arcs["destino"] == "outcome", "origen"])
|
||||
children = set(arcs.loc[arcs["origen"] == "outcome", "destino"])
|
||||
spouses = set(arcs.loc[arcs["destino"].isin(children) & (arcs["origen"] != "outcome"), "origen"])
|
||||
return parents | children | spouses
|
||||
|
||||
|
||||
def risk_with_blanket(risk_stability: pd.DataFrame, risk_markov_blanket: set | None) -> pd.DataFrame:
|
||||
"""c3: the variable is in the outcome's Markov blanket."""
|
||||
tab = risk_stability.copy()
|
||||
tab["en_manta_markov"] = tab["variable"].map(
|
||||
lambda v: (v in risk_markov_blanket) if risk_markov_blanket is not None else np.nan)
|
||||
tab["c3_manta_markov"] = tab["en_manta_markov"].astype(object)
|
||||
return tab
|
||||
|
||||
|
||||
def risk_classification(risk_with_blanket: pd.DataFrame) -> Classification:
|
||||
"""Robust: c1 and at least three criteria (or all those evaluated, if fewer); suggestive: at least two; else
|
||||
inconclusive. A category that is "unknown" doesn't apply."""
|
||||
tab = risk_with_blanket.copy()
|
||||
available = [c for c in CRITERIA if tab[c].notna().all()]
|
||||
tab["criterios_cumplidos"] = tab[available].apply(lambda c: c.map(lambda x: bool(x == True))).sum(axis=1) # noqa: E712
|
||||
tab["criterios_evaluados"] = len(available)
|
||||
min_robust = min(3, len(available))
|
||||
|
||||
def classify(r):
|
||||
if r["categoria"] == "Desconocido":
|
||||
return UNKNOWN_CATEGORY
|
||||
if r["c1_or"] and r["criterios_cumplidos"] >= min_robust:
|
||||
return f"{r['direccion']} robusto"
|
||||
if r["criterios_cumplidos"] >= 2:
|
||||
return f"{r['direccion']} sugerente"
|
||||
return "no concluyente"
|
||||
|
||||
tab["clasificacion"] = tab.apply(classify, axis=1)
|
||||
tab["_o"] = tab["clasificacion"].map(ORDER).fillna(5)
|
||||
tab = tab.sort_values(["_o", "OR_muerte"], ascending=[True, False])[COLUMNS]
|
||||
return Classification(tab, available)
|
||||
|
||||
|
||||
def risk_factors_table(risk_classification: Classification) -> pd.DataFrame:
|
||||
return risk_classification.table.round(4)
|
||||
|
||||
|
||||
def risk_variable_summary(risk_classification: Classification) -> pd.DataFrame:
|
||||
tab = risk_classification.table
|
||||
summary = tab[tab["clasificacion"] != UNKNOWN_CATEGORY].groupby("variable").agg(
|
||||
categorias_robustas=("clasificacion", lambda s: int(s.str.contains("robusto").sum())),
|
||||
categorias_sugerentes=("clasificacion", lambda s: int(s.str.contains("sugerente").sum())),
|
||||
freq_seleccion_bootstrap=("freq_seleccion_bootstrap", "first"),
|
||||
en_manta_markov=("en_manta_markov", "first"),
|
||||
OR_max=("OR_muerte", "max"), OR_min=("OR_muerte", "min"),
|
||||
).sort_values(["categorias_robustas", "categorias_sugerentes"], ascending=False)
|
||||
return summary.round(4)
|
||||
|
||||
|
||||
def risk_treatment_associations(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
|
||||
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
|
||||
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by
|
||||
indication); None when there are none."""
|
||||
if not risk_treatment:
|
||||
return None
|
||||
variables = risk_intrinsic + risk_treatment
|
||||
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
|
||||
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
|
||||
tr = tr[tr["variable"].isin(risk_treatment)].copy()
|
||||
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
|
||||
tr["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
|
||||
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"])
|
||||
ds = stats.survival_differences(risk_data, risk_follow_up.months, risk_follow_up.event,
|
||||
zip(tr["variable"], tr["categoria"], tr["referencia"]), risk_factors.horizon)
|
||||
tr = pd.concat([tr.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
||||
tr["nota"] = "asociacion ajustada por las demas variables; no implica efecto causal (confusion por indicacion)"
|
||||
return tr[["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p",
|
||||
"p_ajustado_BH", "S18_categoria", "S18_referencia", "delta_S18", "delta_IC95_inf", "delta_IC95_sup",
|
||||
"nota"]].round(4)
|
||||
|
||||
|
||||
def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency: BootstrapFrequency,
|
||||
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> dict:
|
||||
return {"alfa": risk_factors.alpha, "freq_min_bootstrap": risk_factors.freq_min,
|
||||
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
|
||||
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
|
||||
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
|
||||
@@ -0,0 +1,215 @@
|
||||
"""The pipeline's Hamilton drivers, one per stage, and the files each stage writes. The nodes (`depuration.py`,
|
||||
`bootstrap.py`, ...) are pure; only this module touches the output folder. `pipeline.py` runs the stages in order:
|
||||
`python -m models.cama.seer_survival --data DIR`.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from hamilton import driver
|
||||
|
||||
from models.cama.seer_survival import (balancing, bootstrap, categorization, depuration, modeling, resampling,
|
||||
risk_factors, survival_curves)
|
||||
from models.cama.seer_survival.settings import Settings, load
|
||||
|
||||
DEPURATED = "dataframe_depurado.csv"
|
||||
BOOTSTRAP_INDICES = "bootstrap_indices.npy"
|
||||
BOOTSTRAP_METADATA = "bootstrap_metadata.json"
|
||||
DEPURATION_DIR = "depuracion_resultados_1"
|
||||
FIGURES_DIR = "figuras"
|
||||
BALANCED_MCA = "dataframe_balanceado_mca.csv"
|
||||
BALANCED_AGE = "dataframe_balanceado_con_edad_agrupada.csv"
|
||||
BALANCED = "dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
|
||||
NATURAL = "dataframe_poblacion_natural.csv"
|
||||
PROPOSALS = "propuestas_categorizacion.csv"
|
||||
PROPOSALS_SUMMARY = "propuestas_categorizacion_resumen.csv"
|
||||
LABELS_JSON = "dataframe_construido_labels.json"
|
||||
|
||||
|
||||
def _jsonable(o):
|
||||
"""`default` of `json.dump` for the numpy values and sets the reports carry."""
|
||||
if isinstance(o, np.floating):
|
||||
return float(o)
|
||||
if isinstance(o, np.integer):
|
||||
return int(o)
|
||||
if isinstance(o, (set, tuple)):
|
||||
return list(o)
|
||||
return str(o)
|
||||
|
||||
|
||||
def _dump(path: Path, data: dict, **kwargs) -> None:
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=_jsonable, **kwargs), encoding="utf-8")
|
||||
|
||||
|
||||
def run_depuration(recoded_csv: str, mapping_json: str, output_dir: str, settings: Settings | None = None,
|
||||
generated_at: str | None = None) -> dict:
|
||||
"""Runs stage 01 and writes `dataframe_depurado.csv` and the reports in `depuracion_resultados_1/`."""
|
||||
settings = settings or load()
|
||||
out = Path(output_dir)
|
||||
reports = out / DEPURATION_DIR
|
||||
reports.mkdir(parents=True, exist_ok=True)
|
||||
dr = driver.Builder().with_modules(depuration).build()
|
||||
inputs = {"recoded_csv": str(recoded_csv), "mapping_json": str(mapping_json), "depuration": settings.depuration,
|
||||
"generated_at": generated_at or datetime.datetime.now().isoformat(timespec="seconds")}
|
||||
r = dr.execute(["calibration", "calibration_report", "elimination", "depurated", "kept_variables"], inputs=inputs)
|
||||
r["calibration"].pairs_u.to_csv(reports / "calibracion_U_pares.csv", index=False)
|
||||
if len(r["calibration"].cluster_cut_table):
|
||||
r["calibration"].cluster_cut_table.to_csv(reports / "calibracion_clustering_corte.csv", index=False)
|
||||
_dump(reports / "calibracion_umbrales.json", r["calibration_report"])
|
||||
r["depurated"].to_csv(out / DEPURATED, index=False)
|
||||
r["elimination"].dropped.to_csv(reports / "variables_eliminadas.csv", index=False)
|
||||
_dump(reports / "variables_conservadas.json", r["kept_variables"])
|
||||
return r
|
||||
|
||||
|
||||
def save_figures(figures: list, prefix: str, folder: Path, first: int = 1) -> list[Path]:
|
||||
"""Saves each figure as `<prefix>_<nn>_<slug of its title>.png`, numbered from `first`, as the scripts did."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
paths = []
|
||||
for n, fig in enumerate(figures, first):
|
||||
title = fig._suptitle.get_text() if getattr(fig, "_suptitle", None) is not None else (fig.axes[0].get_title() or "figura")
|
||||
slug = re.sub(r"[^A-Za-z0-9]+", "_", title).strip("_")[:50] or "figura"
|
||||
paths.append(folder / f"{prefix}_{n:02d}_{slug}.png")
|
||||
fig.savefig(paths[-1], dpi=150, bbox_inches="tight")
|
||||
return paths
|
||||
|
||||
|
||||
def run_balancing(depurated_csv: str, output_dir: str, labels_json: str | None = None,
|
||||
settings: Settings | None = None) -> dict:
|
||||
"""Runs stages 02a and 02b: the MCA balancing, then the age and tumor categorization. Writes the balanced files,
|
||||
the cut comparisons and sensitivity/specificity tables, the proposals, the natural population and two figures."""
|
||||
settings = settings or load()
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dr = driver.Builder().with_modules(balancing, categorization).build()
|
||||
inputs = {"depurated_csv": str(depurated_csv), "labels_json": str(labels_json or out / LABELS_JSON),
|
||||
"balancing": settings.balancing, "categorization": settings.categorization}
|
||||
r = dr.execute(["balanced_frame", "age_grouped", "balanced_final", "age_comparison", "tumor_comparison",
|
||||
"age_diagnostics", "tumor_diagnostics", "proposals", "natural_population"], inputs=inputs)
|
||||
r["balanced_frame"].to_csv(out / BALANCED_MCA, index=False)
|
||||
r["age_grouped"].to_csv(out / BALANCED_AGE, index=False)
|
||||
r["age_comparison"].to_csv(out / "comparacion_cortes_edad.csv", index=False)
|
||||
r["tumor_comparison"].to_csv(out / "comparacion_cortes_tumor.csv", index=False)
|
||||
r["balanced_final"].to_csv(out / BALANCED, index=False)
|
||||
r["age_diagnostics"].table.to_csv(out / "sens_esp_edad.csv")
|
||||
r["tumor_diagnostics"].table.to_csv(out / "sens_esp_tumor.csv")
|
||||
save_figures([r["age_diagnostics"].figure, r["tumor_diagnostics"].figure], "02", out / FIGURES_DIR)
|
||||
r["proposals"].table.to_csv(out / PROPOSALS, index=False)
|
||||
r["proposals"].summary.to_csv(out / PROPOSALS_SUMMARY, index=False)
|
||||
r["natural_population"].to_csv(out / NATURAL, index=False)
|
||||
return r
|
||||
|
||||
|
||||
def run_modeling(balanced_csv: str, output_dir: str, natural_csv: str | None = None,
|
||||
bootstrap_indices_path: str | None = None, proposals_csv: str | None = None,
|
||||
settings: Settings | None = None) -> dict:
|
||||
"""Runs stage 04: the stepwise LR and the HBN on the balanced cohort and their comparison, the natural-population
|
||||
LR, and the bootstrap and proposal replicas. Writes their tables and four figures."""
|
||||
import warnings
|
||||
|
||||
settings = settings or load()
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
np.random.seed(settings.modeling.random_state)
|
||||
dr = driver.Builder().with_modules(modeling, resampling).build()
|
||||
inputs = {"balanced_csv": str(balanced_csv), "natural_csv": str(natural_csv or out / NATURAL),
|
||||
"bootstrap_indices": np.load(bootstrap_indices_path or out / BOOTSTRAP_INDICES),
|
||||
"proposals_csv": str(proposals_csv or out / PROPOSALS), "modeling": settings.modeling}
|
||||
wanted = ["lr_odds_ratios", "hbn_arcs", "hbn_graph_figure", "roc_figure", "calibration_figure", "dca_figure",
|
||||
"differentiation_table", "auc_internal", "natural_results", "bootstrap_selection", "bootstrap_auc",
|
||||
"bootstrap_auc_difference", "proposal_runs", "proposal_summary", "proposal_deltas"]
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
r = dr.execute(wanted, inputs=inputs)
|
||||
r["lr_odds_ratios"].to_csv(out / "or_lr_balanceada.csv")
|
||||
r["hbn_arcs"].to_csv(out / "hbn_arcos.csv", index=False)
|
||||
figures = [r[k] for k in ("hbn_graph_figure", "roc_figure", "calibration_figure", "dca_figure") if r[k] is not None]
|
||||
save_figures(figures, "04", out / FIGURES_DIR)
|
||||
r["differentiation_table"].to_csv(out / "metricas_diferenciacion.csv")
|
||||
r["auc_internal"].to_csv(out / "auc_validacion_interna.csv", index=False)
|
||||
nat = r["natural_results"]
|
||||
if nat is not None:
|
||||
nat.odds_ratios.to_csv(out / "or_lr_poblacion_natural.csv")
|
||||
nat.odds_ratios_no_treatment.to_csv(out / "or_lr_poblacion_natural_sin_tratamiento.csv")
|
||||
nat.comparison.to_csv(out / "comparacion_lr_balanceada_vs_natural.csv")
|
||||
nat.auc_by_stage.to_csv(out / "auc_por_estadio_lr_natural.csv")
|
||||
nat.auc_by_stage_no_treatment.to_csv(out / "auc_por_estadio_lr_natural_sin_tratamiento.csv")
|
||||
nat.calibration_deciles.to_csv(out / "calibracion_deciles_lr_natural.csv", index=False)
|
||||
r["bootstrap_selection"].to_csv(out / "seleccion_bootstrap.csv", index=False)
|
||||
r["bootstrap_auc"].to_csv(out / "auc_bootstrap.csv", index=False)
|
||||
if r["bootstrap_auc_difference"] is not None:
|
||||
r["bootstrap_auc_difference"].to_csv(out / "auc_bootstrap_diferencia.csv", index=False)
|
||||
r["proposal_runs"].to_csv(out / "resultados_propuestas_categorizacion.csv", index=False)
|
||||
r["proposal_summary"].to_csv(out / "resumen_propuestas_categorizacion.csv")
|
||||
r["proposal_deltas"].to_csv(out / "delta_auc_propuestas_vs_base.csv", index=False)
|
||||
return r
|
||||
|
||||
|
||||
def _subgroup_file(name: str) -> str:
|
||||
"""`subgrupo_<name>.png` with the name made ASCII, as the script did."""
|
||||
for old, new in [("≥", "ge"), ("≤", "le"), ("<", "lt"), (">", "gt"), ("ñ", "n"), ("–", "-")]:
|
||||
name = name.replace(old, new)
|
||||
return re.sub(r"[^A-Za-z0-9]+", "_", name).strip("_")
|
||||
|
||||
|
||||
def run_survival(depurated_csv: str, output_dir: str, settings: Settings | None = None) -> dict:
|
||||
"""Runs stage 05 on the complete cohort: the main curve and its points, the subgroups' curves, fits and points, the
|
||||
combination's weights and the test of age as a number. Age modes other than `categorizada` write suffixed files."""
|
||||
settings = settings or load()
|
||||
s = settings.survival
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
suffix = s.file_suffix
|
||||
dr = driver.Builder().with_modules(survival_curves).build()
|
||||
r = dr.execute(["sv_table", "sv_main_figure", "sv_weights_cohort", "sv_sub_figures", "sv_sub_fits_table",
|
||||
"sv_sub_points_table", "sv_sub_weights_table", "sv_age_test"],
|
||||
inputs={"depurated_csv": str(depurated_csv), "survival": s})
|
||||
r["sv_table"].to_csv(out / f"curva_supervivencia_puntos_LR_HBN{suffix}.csv", index=False)
|
||||
r["sv_main_figure"].savefig(out / f"curva_supervivencia_KM_KS_LR_HBN{suffix}.png", dpi=200)
|
||||
if r["sv_weights_cohort"] is not None:
|
||||
r["sv_weights_cohort"].to_csv(out / f"pesos_combinacion_cohorte{suffix}.csv", index=False)
|
||||
for name, fig in r["sv_sub_figures"].items():
|
||||
fig.savefig(out / f"subgrupo_{_subgroup_file(name)}{suffix}.png", dpi=170)
|
||||
r["sv_sub_fits_table"].to_csv(out / f"subgrupos_KM_Weibull_fraccional{suffix}.csv", index=False)
|
||||
r["sv_sub_points_table"].to_csv(out / f"subgrupos_puntos_LR_HBN{suffix}.csv", index=False)
|
||||
if r["sv_sub_weights_table"] is not None:
|
||||
r["sv_sub_weights_table"].to_csv(out / f"subgrupos_pesos_combinacion{suffix}.csv", index=False)
|
||||
r["sv_age_test"].by_subgroup.to_csv(out / f"prueba_edad_continua_vs_categorizada{suffix}.csv", index=False)
|
||||
r["sv_age_test"].summary.to_csv(out / f"prueba_edad_resumen{suffix}.csv", index=False)
|
||||
return r
|
||||
|
||||
|
||||
def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv: str | None = None,
|
||||
hbn_arcs_csv: str | None = None, settings: Settings | None = None) -> dict:
|
||||
"""Runs stage 06 and writes the risk factors, their per-variable summary, the treatment associations and the
|
||||
criteria used."""
|
||||
settings = settings or load()
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dr = driver.Builder().with_modules(risk_factors).build()
|
||||
inputs = {"natural_csv": str(natural_csv),
|
||||
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
|
||||
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
|
||||
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria"],
|
||||
inputs=inputs)
|
||||
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
|
||||
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
|
||||
if r["risk_treatment_associations"] is not None:
|
||||
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
|
||||
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
|
||||
return r
|
||||
|
||||
|
||||
def run_bootstrap(balanced_csv: str, output_dir: str, settings: Settings | None = None) -> dict:
|
||||
"""Runs stage 03 and writes `bootstrap_indices.npy` and `bootstrap_metadata.json`."""
|
||||
settings = settings or load()
|
||||
out = Path(output_dir)
|
||||
dr = driver.Builder().with_modules(bootstrap).build()
|
||||
r = dr.execute(["bootstrap_indices", "bootstrap_metadata"],
|
||||
inputs={"balanced_csv": str(balanced_csv), "bootstrap": settings.bootstrap})
|
||||
np.save(out / BOOTSTRAP_INDICES, r["bootstrap_indices"])
|
||||
(out / BOOTSTRAP_METADATA).write_text(json.dumps(r["bootstrap_metadata"], indent=2), encoding="utf-8")
|
||||
return r
|
||||
@@ -0,0 +1,217 @@
|
||||
"""The pipeline's settings, read from `model.toml` into typed groups (one per stage)."""
|
||||
|
||||
import tomllib
|
||||
from dataclasses import dataclass, fields
|
||||
from pathlib import Path
|
||||
|
||||
TOML = Path(__file__).parent / "model.toml"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DepurationSettings:
|
||||
exclude: tuple[str, ...]
|
||||
auto_extra: tuple[str, ...]
|
||||
extra_cols: tuple[str, ...]
|
||||
protected: tuple[str, ...]
|
||||
prefer: tuple[str, ...]
|
||||
drop_raw_sources: bool
|
||||
unknown_label: str
|
||||
dup_u: float
|
||||
u_redund: float
|
||||
gvif_drop: float
|
||||
max_iter_gvif: int
|
||||
thresholds_auto: bool
|
||||
n_max_cal: int
|
||||
null_perm: int
|
||||
k_azar: int
|
||||
u_conventional: float
|
||||
u_gap_from: float
|
||||
u_gap_min: float
|
||||
u_plausible: tuple[float, float]
|
||||
vif_cut: float
|
||||
r_large: float
|
||||
min_n_cat: int
|
||||
max_cat_cluster: int
|
||||
cluster_dist: str
|
||||
cluster_method: str
|
||||
seed: int
|
||||
gap_from_grid: tuple[float, ...]
|
||||
gap_min_grid: tuple[float, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BalancingSettings:
|
||||
outcome_mode: str
|
||||
horizon_months: int
|
||||
exclude_censored_years: bool
|
||||
censoring_max_pct: float
|
||||
age_keywords: tuple[str, ...]
|
||||
n_components: int
|
||||
target_ratio: float
|
||||
distance_dims: int
|
||||
mca_variant: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CategorizationSettings:
|
||||
alpha: float
|
||||
kmax: int
|
||||
threshold: float
|
||||
min_count: int
|
||||
min_n_pct: float
|
||||
min_n_floor: int
|
||||
bin_width_mm: int
|
||||
tumor_cap_mm: int
|
||||
k_quantiles: int
|
||||
clinical_age: tuple[int, ...]
|
||||
clinical_tumor: tuple[int, ...]
|
||||
age_final: str
|
||||
tumor_final: str
|
||||
drop_after: tuple[str, ...]
|
||||
biology: tuple[str, ...]
|
||||
treatment: tuple[str, ...]
|
||||
demographic: tuple[str, ...]
|
||||
candidate_keywords: dict # covariate -> {"include": [...], "exclude": [...]}
|
||||
proposals: dict # id -> {"age": spec, "tumor": spec}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BootstrapSettings:
|
||||
n_bootstrap: int
|
||||
random_state: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelingSettings:
|
||||
random_state: int
|
||||
test_size: float
|
||||
prefilter_alpha: float
|
||||
alpha_in: float
|
||||
alpha_out: float
|
||||
max_candidates: int
|
||||
max_search_rows: int
|
||||
lr_maxiter: int
|
||||
bdeu_ess: int
|
||||
n_restarts: int
|
||||
max_indegree: int
|
||||
max_outcome_parents: int
|
||||
categorical_order: tuple[str, ...]
|
||||
treatment_vars: tuple[str, ...]
|
||||
tier_demography: tuple[str, ...]
|
||||
tier_tumor: tuple[str, ...]
|
||||
tier_treatment: tuple[str, ...]
|
||||
run_lr_natural: bool
|
||||
natural_search_rows: int
|
||||
natural_test_size: float
|
||||
natural_maxiter: int
|
||||
n_bootstrap_run: int
|
||||
bootstrap_max_seconds: int
|
||||
bootstrap_include_hbn: bool
|
||||
bootstrap_restarts: int
|
||||
n_splits_prop: int
|
||||
proposals_only: tuple[str, ...]
|
||||
proposals_include_hbn: bool
|
||||
proposals_max_seconds: int
|
||||
canonical_map: dict # column of the balanced file -> canonical name
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SurvivalSettings:
|
||||
age_mode: str
|
||||
include_age: bool
|
||||
age_cuts: tuple[int, ...]
|
||||
hbn_fixed_parents: tuple[str, ...]
|
||||
hbn_age_parent: bool
|
||||
hbn_parents: str
|
||||
covariates: tuple[str, ...]
|
||||
horizons: tuple[int, ...]
|
||||
censoring: str
|
||||
combine: bool
|
||||
show_individual: bool
|
||||
stack_folds: int
|
||||
stack_shrink: float
|
||||
n_boot: int
|
||||
n_boot_sub: int
|
||||
seed: int
|
||||
hbn_ess: int
|
||||
hbn_max_parents: int
|
||||
k_ident: str | float
|
||||
curves: str
|
||||
adjust_step: int
|
||||
show_raw_km: bool
|
||||
ylim_main: tuple[float, ...]
|
||||
inset_zoom: bool
|
||||
inset_months: int
|
||||
cap_months: int
|
||||
min_events_sub: int
|
||||
ks_max_seconds: int
|
||||
ks_sub_max_seconds: int
|
||||
xlim_sub: tuple[float, ...]
|
||||
ylim_sub: dict
|
||||
subgroups: tuple[dict, ...]
|
||||
|
||||
@property
|
||||
def file_suffix(self) -> str:
|
||||
"""Appended to the output files so the age modes don't overwrite each other."""
|
||||
return "" if self.age_mode == "categorizada" else f"_edad_{self.age_mode}"
|
||||
|
||||
@property
|
||||
def tag(self) -> str:
|
||||
"""The title mark that tells the age modes apart."""
|
||||
return "" if self.age_mode == "categorizada" else f" [edad {self.age_mode.replace('_', ' ')}]"
|
||||
|
||||
@property
|
||||
def combine_active(self) -> bool:
|
||||
"""The stacked combination only exists with a model per interval."""
|
||||
return bool(self.combine) and self.censoring == "riesgo"
|
||||
|
||||
@property
|
||||
def months_max(self) -> int:
|
||||
"""Where the time axis is drawn to."""
|
||||
return self.cap_months or 60
|
||||
|
||||
@property
|
||||
def months_extrapolated(self) -> int:
|
||||
"""Where the fits are extrapolated (dotted) past the observed follow-up."""
|
||||
return self.cap_months or 120
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RiskFactorSettings:
|
||||
alpha: float
|
||||
freq_min: float
|
||||
horizon: int
|
||||
cap_months: int
|
||||
treatment: tuple[str, ...]
|
||||
canonical_map: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
depuration: DepurationSettings
|
||||
balancing: BalancingSettings
|
||||
categorization: CategorizationSettings
|
||||
bootstrap: BootstrapSettings
|
||||
modeling: ModelingSettings
|
||||
survival: SurvivalSettings
|
||||
risk_factors: RiskFactorSettings
|
||||
|
||||
|
||||
def _group(cls, table: dict):
|
||||
"""A dataclass from a TOML table; lists become tuples so the settings stay hashable and immutable."""
|
||||
unknown = set(table) - {f.name for f in fields(cls)}
|
||||
if unknown:
|
||||
raise ValueError(f"{cls.__name__}: unknown settings {sorted(unknown)}")
|
||||
return cls(**{k: tuple(v) if isinstance(v, list) else v for k, v in table.items()})
|
||||
|
||||
|
||||
def load(path: Path = TOML) -> Settings:
|
||||
raw = tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
||||
return Settings(depuration=_group(DepurationSettings, raw["depuration"]),
|
||||
balancing=_group(BalancingSettings, raw["balancing"]),
|
||||
categorization=_group(CategorizationSettings, raw["categorization"]),
|
||||
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
|
||||
modeling=_group(ModelingSettings, raw["modeling"]),
|
||||
survival=_group(SurvivalSettings, {**raw["survival"],
|
||||
"subgroups": tuple(raw["survival"]["subgroups"])}),
|
||||
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
|
||||
@@ -0,0 +1,609 @@
|
||||
"""Stage 05, survival curves: the complete cohort's Kaplan-Meier, the classic and the fractional Weibull, and the 6/12/18
|
||||
month survival by LR, HBN and their stacked combination with bootstrap intervals; the same in subgroups; and a test of
|
||||
age as a continuous variable.
|
||||
|
||||
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `depurated_csv`
|
||||
(the complete cohort, with follow-up months and vital status) and `survival` (its settings). The numeric core is in
|
||||
`fractional_weibull.py` and `survival_models.py`; `run.py` holds the driver and writes the files.
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from matplotlib.figure import Figure
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
from models.cama.seer_survival import fractional_weibull as fw
|
||||
from models.cama.seer_survival import survival_models as sm
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
|
||||
STYLE = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class SurvivalFrame:
|
||||
df: pd.DataFrame # the cohort with `meses_int` and `evento` (capped), and the derived age columns
|
||||
covariates: list[str]
|
||||
age_col: str | None
|
||||
numeric_cols: list[str] # the continuous age columns the LR takes, if any
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class KaplanMeier:
|
||||
S: np.ndarray
|
||||
lo: np.ndarray
|
||||
hi: np.ndarray
|
||||
T: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Oof:
|
||||
lr: np.ndarray
|
||||
hb: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Points:
|
||||
lr: np.ndarray
|
||||
hbn: np.ndarray
|
||||
combined: np.ndarray | None
|
||||
parents: list
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class AgeTest:
|
||||
by_subgroup: pd.DataFrame # mean predicted survival of each variant against Kaplan-Meier
|
||||
summary: pd.DataFrame # error against KM and out-of-sample log-likelihood
|
||||
|
||||
|
||||
def _find_col(df, keywords, exclude=()):
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords) and not any(e in d for e in exclude):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
def _first_number(v):
|
||||
m = re.search(r"\d+", str(v))
|
||||
return float(m.group()) if m else np.nan
|
||||
|
||||
|
||||
def _age_midpoint(v):
|
||||
n = [float(x) for x in re.findall(r"\d+", str(v))]
|
||||
if not n:
|
||||
return np.nan
|
||||
return n[0] + 2.5 if "+" in str(v) else float(np.mean(n[:2]))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the cohort
|
||||
|
||||
def sv_frame(depurated_csv: str, survival: SurvivalSettings) -> SurvivalFrame:
|
||||
"""The cohort with follow-up truncated at `cap_months` (later deaths count as alive), its covariates and, when no
|
||||
categorical age column exists, the grouped age `Edad_cat`."""
|
||||
s = survival
|
||||
df = pd.read_csv(depurated_csv, dtype=str)
|
||||
col_months, col_vital = _find_col(df, ["survival months"]), _find_col(df, ["vital status"])
|
||||
assert col_months and col_vital, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
|
||||
df["meses"] = pd.to_numeric(df[col_months], errors="coerce")
|
||||
df["evento"] = df[col_vital].astype(str).str.lower().str.contains("dead")
|
||||
df = df[df["meses"].notna()].reset_index(drop=True)
|
||||
df["meses_int"] = df["meses"].astype(int)
|
||||
if s.cap_months:
|
||||
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
|
||||
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
|
||||
|
||||
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
|
||||
age_col = (sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
|
||||
if candidates else None)
|
||||
df["_edad"] = df[age_col].map(_first_number) if age_col else np.nan
|
||||
has_age_cat = any(re.search(sm.AGE_PATTERN, c.lower()) for c in df.columns if c.endswith("_cat"))
|
||||
if s.include_age and not has_age_cat and df["_edad"].notna().mean() > 0.5:
|
||||
bins = [-np.inf] + list(s.age_cuts) + [np.inf]
|
||||
labels = [f"<{s.age_cuts[0]}"] + [f"{a}-{b - 1}" for a, b in zip(s.age_cuts[:-1], s.age_cuts[1:])] + [f"≥{s.age_cuts[-1]}"]
|
||||
df["Edad_cat"] = pd.cut(df["_edad"], bins, right=False, labels=labels).astype(object)
|
||||
if not s.covariates:
|
||||
covariates = [c for c in df.columns if c.endswith("_cat") and "outcome" not in c.lower()]
|
||||
else:
|
||||
covariates = list(s.covariates)
|
||||
if s.include_age and "Edad_cat" in df.columns and "Edad_cat" not in covariates:
|
||||
covariates.append("Edad_cat")
|
||||
ed = df[age_col].map(_age_midpoint).astype(float) if age_col else pd.Series(np.nan, index=df.index)
|
||||
df["_edad_z"] = ((ed - ed.mean()) / ed.std()).fillna(0.0)
|
||||
df["_edad_cuad"] = df["_edad_z"] ** 2
|
||||
numeric = []
|
||||
if s.age_mode != "categorizada":
|
||||
assert ed.notna().mean() > 0.5, "age_mode continua: no se pudo leer la edad numérica de la columna de edad."
|
||||
covariates = [c for c in covariates if not re.search(sm.AGE_PATTERN, c.lower())]
|
||||
numeric = ["_edad_z"] + (["_edad_cuad"] if s.age_mode == "continua_cuadratica" else [])
|
||||
assert covariates, "No hay covariables: define `covariates` con los nombres de columna."
|
||||
for c in covariates:
|
||||
df[c] = df[c].fillna("NA").astype(str).str.strip()
|
||||
return SurvivalFrame(df, covariates, age_col, numeric)
|
||||
|
||||
|
||||
def sv_cohort(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> sm.Cohort:
|
||||
df, cov = sv_frame.df, sv_frame.covariates
|
||||
M = pd.get_dummies(df[cov], drop_first=True).values.astype(np.float32) # reference = the first category
|
||||
X_dum = np.column_stack([M, df[sv_frame.numeric_cols].values.astype(np.float32)]) if sv_frame.numeric_cols else M
|
||||
X_int = np.column_stack([pd.factorize(df[c])[0] for c in cov]).astype(int)
|
||||
return sm.Cohort(df["meses_int"].values, df["evento"].values, X_dum, X_int, X_int.max(axis=0) + 1,
|
||||
[0] + list(survival.horizons), sm.fixed_parent_indices(cov, survival))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the curves of the whole cohort
|
||||
|
||||
def sv_km(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> KaplanMeier:
|
||||
T = max(survival.months_max, max(survival.horizons))
|
||||
return KaplanMeier(*fw.km_curva(sv_frame.df["meses_int"].values, sv_frame.df["evento"].values, T), T)
|
||||
|
||||
|
||||
def sv_adjusted(sv_cohort: sm.Cohort, sv_km: KaplanMeier, survival: SurvivalSettings) -> np.ndarray:
|
||||
return sm.adjusted_curve(sv_cohort, np.arange(len(sv_cohort.months)), sv_km.T, survival.adjust_step)
|
||||
|
||||
|
||||
def _fixed_k(w: dict, s: SurvivalSettings) -> float:
|
||||
return w["k"] if s.k_ident == "clasico" else float(s.k_ident)
|
||||
|
||||
|
||||
def _fit_to_curve(S: np.ndarray, n_eq: int, s: SurvivalSettings, max_seg: int):
|
||||
"""The classic and the fractional Weibull fitted to a survival curve, as if it came from `n_eq` patients."""
|
||||
d = np.maximum(n_eq * (S[:-1] - S[1:]), 0.0)
|
||||
T = len(d)
|
||||
d = np.concatenate([d, [0.0, 0.0]])
|
||||
c = np.zeros(T + 2)
|
||||
c[T] = n_eq * S[-1]
|
||||
w = fw.ajustar_weibull(d, c)
|
||||
return w, fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=max_seg)
|
||||
|
||||
|
||||
def sv_fractional_fit(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.ndarray,
|
||||
survival: SurvivalSettings) -> dict:
|
||||
"""The fractional Weibull drawn on the main figure: fitted to the adjusted curve, or to the raw counts."""
|
||||
s = survival
|
||||
if s.curves == "ajustada":
|
||||
return _fit_to_curve(sv_adjusted, len(sv_frame.df), s, s.ks_max_seconds)[1]
|
||||
d, c = fw.tabla_eventos(sv_frame.df["meses_int"].values, sv_frame.df["evento"].values)
|
||||
w = fw.ajustar_weibull(d, c)
|
||||
return fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=s.ks_max_seconds)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- LR, HBN and their combination
|
||||
|
||||
def sv_oof(sv_cohort: sm.Cohort, survival: SurvivalSettings) -> Oof | None:
|
||||
"""Out-of-sample interval probabilities, the stacking's input; None without the combination."""
|
||||
if not survival.combine_active:
|
||||
return None
|
||||
return Oof(*sm.out_of_fold(sv_cohort, survival, len(sv_cohort.months)))
|
||||
|
||||
|
||||
def sv_weights_cohort(sv_cohort: sm.Cohort, sv_oof: Oof | None, survival: SurvivalSettings) -> pd.DataFrame | None:
|
||||
if sv_oof is None:
|
||||
return None
|
||||
return sm.stacking_weights(sv_cohort, survival, np.ones(len(sv_cohort.months), bool), sv_oof.lr, sv_oof.hb)
|
||||
|
||||
|
||||
def sv_points(sv_cohort: sm.Cohort, sv_weights_cohort: pd.DataFrame | None, survival: SurvivalSettings) -> Points:
|
||||
"""The mean survival at each horizon by LR, HBN and the combination, fitted on the whole cohort."""
|
||||
todas = np.arange(len(sv_cohort.months))
|
||||
if survival.combine_active:
|
||||
p_lr, p_hbn, p_cmb, pads = sm.estimate_combined(sv_cohort, survival, todas, None,
|
||||
sv_weights_cohort["w_LR"].values)
|
||||
return Points(p_lr, p_hbn, p_cmb, pads)
|
||||
p_lr, p_hbn, pads = sm.estimate(sv_cohort, survival, todas, survival.censoring)
|
||||
return Points(p_lr, p_hbn, None, pads)
|
||||
|
||||
|
||||
def _reference_parents(points: Points, s: SurvivalSettings):
|
||||
"""The HBN's parents learned on the whole cohort, kept in the bootstrap (a steadier interval), or None to learn
|
||||
them again in each replica."""
|
||||
return points.parents if s.hbn_parents == "fijos" else None
|
||||
|
||||
|
||||
def sv_bootstrap(sv_cohort: sm.Cohort, sv_weights_cohort: pd.DataFrame | None, sv_points: Points,
|
||||
survival: SurvivalSettings) -> np.ndarray:
|
||||
"""One row per replica: the mean survival at each horizon of each model."""
|
||||
s = survival
|
||||
N = len(sv_cohort.months)
|
||||
ref = _reference_parents(sv_points, s)
|
||||
W = sv_weights_cohort["w_LR"].values if s.combine_active else None
|
||||
rng = np.random.default_rng(s.seed)
|
||||
boots = []
|
||||
for _ in range(s.n_boot):
|
||||
idx = rng.integers(0, N, N)
|
||||
if s.combine_active:
|
||||
r = sm.estimate_combined(sv_cohort, s, idx, ref, W)
|
||||
boots.append(np.concatenate([r[0], r[1], r[2]]))
|
||||
else:
|
||||
r = sm.estimate(sv_cohort, s, idx, s.censoring, ref)
|
||||
boots.append(np.concatenate([r[0], r[1]]))
|
||||
n_series = 3 if s.combine_active else 2
|
||||
return np.array(boots) if s.n_boot > 0 else np.full((1, n_series * len(s.horizons)), np.nan)
|
||||
|
||||
|
||||
def sv_table(sv_points: Points, sv_bootstrap: np.ndarray, sv_km: KaplanMeier, sv_adjusted: np.ndarray,
|
||||
survival: SurvivalSettings) -> pd.DataFrame:
|
||||
"""Per model and horizon: S, its bootstrap 95 % interval, and Kaplan-Meier raw and adjusted."""
|
||||
h = list(survival.horizons)
|
||||
series = [("LR", sv_points.lr), ("HBN", sv_points.hbn)] + ([("COMB", sv_points.combined)] if survival.combine_active else [])
|
||||
ic = np.nanpercentile(sv_bootstrap, [2.5, 97.5], axis=0)
|
||||
rows = [dict(modelo=name, meses=m, S=vals[i], IC_inf=ic[0, j * len(h) + i], IC_sup=ic[1, j * len(h) + i])
|
||||
for j, (name, vals) in enumerate(series) for i, m in enumerate(h)]
|
||||
table = pd.DataFrame(rows)
|
||||
table["KM_crudo"] = [sv_km.S[m] for m in table["meses"]]
|
||||
table["KM_ajustada"] = [sv_adjusted[m] for m in table["meses"]]
|
||||
return table
|
||||
|
||||
|
||||
def _plotted_models(s: SurvivalSettings) -> list[str]:
|
||||
if s.combine_active:
|
||||
return ["LR", "HBN", "COMB"] if s.show_individual else ["COMB"]
|
||||
return ["LR", "HBN"]
|
||||
|
||||
|
||||
def _error_bars(ax, table: pd.DataFrame, names, small: bool = False):
|
||||
for name in names:
|
||||
color, marker, label = STYLE[name]
|
||||
s = table[table["modelo"] == name]
|
||||
yerr = [np.clip(s["S"] - s["IC_inf"], 0, None), np.clip(s["IC_sup"] - s["S"], 0, None)]
|
||||
if small:
|
||||
ax.errorbar(s["meses"], s["S"], yerr=yerr, fmt=marker, color=color, ms=6, capsize=3, lw=1.5, mec="white",
|
||||
mew=.8, zorder=5)
|
||||
else:
|
||||
ax.errorbar(s["meses"], s["S"], yerr=yerr, fmt=marker, color=color, ms=9 if name == "COMB" else 8,
|
||||
capsize=4, lw=1.8, mec="white", mew=1, label=f"{label} (IC 95 % bootstrap)", zorder=5)
|
||||
|
||||
|
||||
def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.ndarray, sv_fractional_fit: dict,
|
||||
sv_table: pd.DataFrame, survival: SurvivalSettings) -> Figure:
|
||||
s = survival
|
||||
n_max = s.months_max
|
||||
fig = Figure(figsize=(15, 5.6) if s.inset_zoom else (9.5, 5.6))
|
||||
if s.inset_zoom:
|
||||
ax, axi = fig.subplots(1, 2, gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
|
||||
else:
|
||||
ax = fig.subplots()
|
||||
xx = np.arange(sv_km.T + 1)
|
||||
tc = np.linspace(0, n_max, 600)
|
||||
if s.curves == "ajustada":
|
||||
S_base = sv_adjusted
|
||||
if s.show_raw_km:
|
||||
ax.step(xx, sv_km.S, where="post", color="#9aa5b1", lw=1.0, ls=":", label="Kaplan-Meier crudo (referencia)")
|
||||
ax.step(xx, sv_adjusted, where="post", color="#3d4852", lw=1.8, label="Kaplan-Meier ajustada por covariables")
|
||||
label_ks = "Weibull fraccional (ajustado a la curva ajustada)"
|
||||
else:
|
||||
S_base = sv_km.S
|
||||
ax.fill_between(xx, sv_km.lo, sv_km.hi, step="post", color="#9aa5b1", alpha=.35, lw=0,
|
||||
label="Kaplan-Meier (IC 95 % Greenwood)")
|
||||
ax.step(xx, sv_km.S, where="post", color="#3d4852", lw=1.6, label="Kaplan-Meier")
|
||||
label_ks = "Weibull fraccional (Kilbas-Saigo)"
|
||||
ax.plot(tc, sv_fractional_fit["S"](tc), color="#d1495b", lw=2.4, label=label_ks)
|
||||
names = _plotted_models(s)
|
||||
_error_bars(ax, sv_table, names)
|
||||
plotted = sv_table[sv_table["modelo"].isin(names)]
|
||||
ax.set_xlim(0, n_max + (0.8 if s.cap_months else 0))
|
||||
ax.set_xlabel("Meses desde el diagnóstico")
|
||||
ax.set_ylabel("Supervivencia S(t)")
|
||||
vals = np.concatenate([S_base[:n_max + 1], plotted["IC_inf"].values,
|
||||
[sv_fractional_fit["S"](np.array([float(n_max)]))[0]]])
|
||||
ax.set_ylim(max(0.0, np.nanmin(vals) - 0.03), 1.005)
|
||||
if s.ylim_main:
|
||||
ax.set_ylim(*s.ylim_main)
|
||||
ax.set_xticks(range(0, n_max + 1, 3 if s.cap_months else 6))
|
||||
ax.grid(alpha=.25)
|
||||
if s.inset_zoom:
|
||||
n_in = s.inset_months
|
||||
xi = np.arange(n_in + 1)
|
||||
axi.step(xi, S_base[:n_in + 1], where="post", color="#3d4852", lw=1.4)
|
||||
if s.curves == "ajustada" and s.show_raw_km:
|
||||
axi.step(xi, sv_km.S[:n_in + 1], where="post", color="#9aa5b1", lw=1.0, ls=":")
|
||||
tci = np.linspace(0, n_in, 200)
|
||||
axi.plot(tci, sv_fractional_fit["S"](tci), color="#d1495b", lw=2)
|
||||
_error_bars(axi, sv_table, names, small=True)
|
||||
v = np.concatenate([S_base[:n_in + 1], plotted["IC_inf"].values, plotted["IC_sup"].values])
|
||||
margin = (v.max() - v.min()) * .08
|
||||
axi.set_xlim(0, n_in + 0.8)
|
||||
axi.set_ylim(v.min() - margin, min(1.002, v.max() + margin))
|
||||
axi.set_xticks(range(0, n_in + 1, 6))
|
||||
axi.grid(alpha=.25)
|
||||
axi.set_title(f"Zoom: primeros {n_in} meses", fontsize=10)
|
||||
axi.set_xlabel("Meses desde el diagnóstico")
|
||||
axi.spines[["top", "right"]].set_visible(False)
|
||||
ax.axvspan(0, n_in, color="#888", alpha=.08, lw=0)
|
||||
ax.set_title(f"Supervivencia de la cohorte completa (n = {len(sv_frame.df):,}){s.tag}")
|
||||
ax.legend(loc="lower left", frameon=False)
|
||||
for side in ("top", "right"):
|
||||
ax.spines[side].set_visible(False)
|
||||
fig.tight_layout()
|
||||
return fig
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- subgroups
|
||||
|
||||
def _stage(v):
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS":
|
||||
return 0
|
||||
for prefix, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(prefix):
|
||||
return val
|
||||
return np.nan
|
||||
|
||||
|
||||
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
|
||||
"""Each subgroup's mask over the cohort: every condition of its spec must hold."""
|
||||
df = sv_frame.df
|
||||
n = len(df)
|
||||
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else _find_col(df, ["estadio", "stage"])
|
||||
col_sub = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else _find_col(df, ["subtipo", "subtype"])
|
||||
col_surg = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else _find_col(df, ["quirurg", "surg"])
|
||||
age = df["_edad"].values.astype(float)
|
||||
stage = (df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index)).values.astype(float)
|
||||
sub = df[col_sub].astype(str) if col_sub else None
|
||||
flags = {"her2neg": sub.str.contains("HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"triple_negative": sub.str.contains("HR-/HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"her2pos": sub.str.contains("HER2+", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"conservative": (df[col_surg].astype(str).str.lower().str.contains("conserv").values
|
||||
if col_surg else np.zeros(n, bool))}
|
||||
masks = {}
|
||||
for spec in survival.subgroups:
|
||||
mask = np.ones(n, bool)
|
||||
if spec.get("her2") == "pos":
|
||||
mask &= flags["her2pos"]
|
||||
if spec.get("her2") == "neg":
|
||||
mask &= flags["her2neg"]
|
||||
if spec.get("triple_negative"):
|
||||
mask &= flags["triple_negative"]
|
||||
if spec.get("conservative"):
|
||||
mask &= flags["conservative"]
|
||||
if "age_min" in spec:
|
||||
mask &= age >= spec["age_min"]
|
||||
if "age_max" in spec:
|
||||
mask &= age < spec["age_max"]
|
||||
if "stages" in spec:
|
||||
mask &= np.isin(stage, spec["stages"])
|
||||
masks[spec["name"]] = mask
|
||||
return masks
|
||||
|
||||
|
||||
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
|
||||
survival: SurvivalSettings) -> dict[str, pd.DataFrame]:
|
||||
"""The combination's weights of each subgroup (out-of-sample robustness within the subgroup)."""
|
||||
if sv_oof is None:
|
||||
return {}
|
||||
return {name: sm.stacking_weights(sv_cohort, survival, mk, sv_oof.lr, sv_oof.hb) for name, mk in sv_masks.items()}
|
||||
|
||||
|
||||
def _subgroup_means(c: sm.Cohort, s: SurvivalSettings, idx, parents, masks, weights) -> dict[str, np.ndarray]:
|
||||
nm, nh = (3 if s.combine_active else 2), len(s.horizons)
|
||||
out = {}
|
||||
if s.combine_active:
|
||||
Pl, Ph, _ = sm.interval_predictions(c, s, idx, parents)
|
||||
Sl, Sh = np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1)
|
||||
for name, mk in masks.items():
|
||||
m = mk[idx]
|
||||
if not m.any():
|
||||
out[name] = np.full(nm * nh, np.nan)
|
||||
continue
|
||||
W = weights[name]["w_LR"].values[None, :]
|
||||
Sc = np.cumprod(W * Pl[m] + (1 - W) * Ph[m], axis=1)
|
||||
out[name] = np.concatenate([Sl[m].mean(0), Sh[m].mean(0), Sc.mean(0)])
|
||||
else:
|
||||
Sl, Sh, _ = sm.patient_survival(c, s, idx, s.censoring, parents)
|
||||
for name, mk in masks.items():
|
||||
m = mk[idx]
|
||||
out[name] = np.concatenate([Sl[m].mean(0), Sh[m].mean(0)]) if m.any() else np.full(nm * nh, np.nan)
|
||||
return out
|
||||
|
||||
|
||||
def sv_sub_points(sv_cohort: sm.Cohort, sv_masks: dict, sv_sub_weights: dict, sv_points: Points,
|
||||
survival: SurvivalSettings) -> dict[str, pd.DataFrame]:
|
||||
"""Per subgroup: LR, HBN and combination survival at each horizon with bootstrap intervals; the models are fitted on
|
||||
the whole cohort and their predictions averaged within the subgroup."""
|
||||
s = survival
|
||||
N = len(sv_cohort.months)
|
||||
names = ["LR", "HBN"] + (["COMB"] if s.combine_active else [])
|
||||
nm, nh = len(names), len(s.horizons)
|
||||
point = _subgroup_means(sv_cohort, s, np.arange(N), None, sv_masks, sv_sub_weights)
|
||||
ref = _reference_parents(sv_points, s)
|
||||
rng = np.random.default_rng(s.seed + 1)
|
||||
boots = {n: [] for n in sv_masks}
|
||||
for _ in range(s.n_boot_sub):
|
||||
r = _subgroup_means(sv_cohort, s, rng.integers(0, N, N), ref, sv_masks, sv_sub_weights)
|
||||
for n in sv_masks:
|
||||
boots[n].append(r[n])
|
||||
out = {}
|
||||
for n, mk in sv_masks.items():
|
||||
B = np.array(boots[n]) if s.n_boot_sub > 0 else np.full((1, nm * nh), np.nan)
|
||||
ic = np.nanpercentile(B, [2.5, 97.5], axis=0) if mk.any() else np.full((2, nm * nh), np.nan)
|
||||
pt = point[n]
|
||||
out[n] = pd.DataFrame([dict(modelo=name, meses=h, S=pt[j * nh + i], IC_inf=ic[0, j * nh + i], IC_sup=ic[1, j * nh + i])
|
||||
for j, name in enumerate(names) for i, h in enumerate(s.horizons)])
|
||||
return out
|
||||
|
||||
|
||||
def sv_sub_analyses(sv_frame: SurvivalFrame, sv_masks: dict, sv_sub_points: dict, sv_sub_weights: dict,
|
||||
survival: SurvivalSettings) -> dict[str, dict | None]:
|
||||
"""Each subgroup's Kaplan-Meier and classic / fractional Weibull fits; None where it has too few deaths."""
|
||||
s = survival
|
||||
df = sv_frame.df
|
||||
aic = lambda nll, k: 2 * k + 2 * nll # noqa: E731
|
||||
out = {}
|
||||
for name, mk in sv_masks.items():
|
||||
sub = df[mk]
|
||||
n, deaths = len(sub), int(sub["evento"].sum())
|
||||
if n == 0 or deaths < s.min_events_sub:
|
||||
out[name] = None
|
||||
continue
|
||||
d, c = fw.tabla_eventos(sub["meses_int"].values, sub["evento"].values)
|
||||
w = fw.ajustar_weibull(d, c)
|
||||
ks = fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=s.ks_sub_max_seconds)
|
||||
Tm = int(sub["meses_int"].max())
|
||||
Sk, lok, hik = fw.km_curva(sub["meses_int"].values, sub["evento"].values, Tm)
|
||||
grid = np.arange(0, Tm + 1, dtype=float)
|
||||
row = {"subgrupo": name, "n": n, "fallecidos": deaths, "seguim. máx. (m)": Tm, "k Weibull": w["k"],
|
||||
"k KS / α / β": f"{ks['k']:.2f} / {ks['alpha']:.2f} / {ks['beta']:.2f}",
|
||||
"AIC Weibull": aic(w["nll"], 2), "AIC fraccional": aic(ks["nll"], 3),
|
||||
"ΔAIC (W − F)": aic(w["nll"], 2) - aic(ks["nll"], 3),
|
||||
"máx|KM−Weibull|": np.abs(w["S"](grid) - Sk).max(), "máx|KM−fracc.|": np.abs(ks["S"](grid) - Sk).max()}
|
||||
out[name] = dict(nombre=name, n=n, ev=deaths, w=w, ks=ks, Sk=Sk, lok=lok, hik=hik, Tm=Tm, fila=row,
|
||||
modelos=sv_sub_points[name], pesos=sv_sub_weights.get(name))
|
||||
return out
|
||||
|
||||
|
||||
def _subgroup_figure(a: dict, s: SurvivalSettings) -> Figure:
|
||||
names = _plotted_models(s)
|
||||
plotted = a["modelos"][a["modelos"]["modelo"].isin(names)]
|
||||
Tm, extrapolated = a["Tm"], s.months_extrapolated
|
||||
tt = np.arange(Tm + 1)
|
||||
fig = Figure(figsize=(15, 5.2) if s.inset_zoom else (9, 5.2))
|
||||
if s.inset_zoom:
|
||||
ax, axi = fig.subplots(1, 2, gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
|
||||
else:
|
||||
ax = fig.subplots()
|
||||
ax.fill_between(tt, a["lok"], a["hik"], step="post", color="#9aa5b1", alpha=.3, lw=0)
|
||||
ax.step(tt, a["Sk"], where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
|
||||
for key, color, ls, label in [("w", "#1f77b4", "-", "Weibull"), ("ks", "#d1495b", "--", "Weibull fraccional")]:
|
||||
t_in, t_ex = np.linspace(0, Tm, 300), np.linspace(Tm, extrapolated, 200)
|
||||
ax.plot(t_in, a[key]["S"](t_in), color=color, lw=2.2, ls=ls, label=label)
|
||||
ax.plot(t_ex, a[key]["S"](t_ex), color=color, lw=1.4, ls=":")
|
||||
if not s.cap_months:
|
||||
ax.axvline(Tm, color="#888", lw=.8, ls=":")
|
||||
_error_bars(ax, plotted, names)
|
||||
x0, x1 = s.xlim_sub if s.xlim_sub else (0, extrapolated + (0.8 if s.cap_months else 0))
|
||||
xs = np.linspace(x0, x1, 400)
|
||||
visible = [a["w"]["S"](xs), a["ks"]["S"](xs), a["Sk"][int(x0):int(min(x1, Tm)) + 1],
|
||||
a["lok"][int(x0):int(min(x1, Tm)) + 1], plotted["IC_inf"].values, plotted["IC_sup"].values]
|
||||
v = np.concatenate([np.ravel(u) for u in visible])
|
||||
v = v[np.isfinite(v)]
|
||||
margin = (v.max() - v.min()) * .06
|
||||
ylim = s.ylim_sub.get(a["nombre"], (max(0, v.min() - margin), min(1.005, v.max() + margin)))
|
||||
ax.set_xlim(x0, x1)
|
||||
ax.set_ylim(*ylim)
|
||||
if s.inset_zoom:
|
||||
n_in = s.inset_months
|
||||
xi = np.arange(n_in + 1)
|
||||
axi.fill_between(xi, a["lok"][:n_in + 1], a["hik"][:n_in + 1], step="post", color="#9aa5b1", alpha=.3, lw=0)
|
||||
axi.step(xi, a["Sk"][:n_in + 1], where="post", color="#222", lw=1.3)
|
||||
tci = np.linspace(0, n_in, 200)
|
||||
axi.plot(tci, a["w"]["S"](tci), color="#1f77b4", lw=2)
|
||||
axi.plot(tci, a["ks"]["S"](tci), color="#d1495b", lw=2, ls="--")
|
||||
_error_bars(axi, plotted, names, small=True)
|
||||
vi = np.concatenate([a["Sk"][:n_in + 1], a["lok"][:n_in + 1], plotted["IC_inf"].values, plotted["IC_sup"].values,
|
||||
a["w"]["S"](tci)])
|
||||
vi = vi[np.isfinite(vi)]
|
||||
mi = (vi.max() - vi.min()) * .08
|
||||
axi.set_xlim(0, n_in + 0.8)
|
||||
axi.set_ylim(vi.min() - mi, min(1.002, vi.max() + mi))
|
||||
axi.set_xticks(range(0, n_in + 1, 6))
|
||||
axi.grid(alpha=.25)
|
||||
axi.set_title(f"Zoom: primeros {n_in} meses", fontsize=10)
|
||||
axi.set_xlabel("Meses desde el diagnóstico")
|
||||
axi.spines[["top", "right"]].set_visible(False)
|
||||
ax.axvspan(0, n_in, color="#888", alpha=.08, lw=0)
|
||||
ax.set_xlabel("Meses desde el diagnóstico")
|
||||
ax.set_ylabel("Supervivencia S(t)")
|
||||
ax.grid(alpha=.25)
|
||||
ax.set_title(f"{a['nombre']}{s.tag}\nn={a['n']:,}, fallecidos={a['ev']:,}", fontsize=11)
|
||||
ax.legend(frameon=False, loc="lower left", fontsize=9)
|
||||
for side in ("top", "right"):
|
||||
ax.spines[side].set_visible(False)
|
||||
fig.tight_layout()
|
||||
return fig
|
||||
|
||||
|
||||
def sv_sub_figures(sv_sub_analyses: dict, survival: SurvivalSettings) -> dict[str, Figure]:
|
||||
"""One figure per fitted subgroup, by its name."""
|
||||
return {name: _subgroup_figure(a, survival) for name, a in sv_sub_analyses.items() if a is not None}
|
||||
|
||||
|
||||
def sv_sub_fits_table(sv_sub_analyses: dict) -> pd.DataFrame:
|
||||
return pd.DataFrame([a["fila"] for a in sv_sub_analyses.values() if a is not None])
|
||||
|
||||
|
||||
def sv_sub_points_table(sv_sub_analyses: dict) -> pd.DataFrame:
|
||||
return pd.concat([a["modelos"].assign(subgrupo=a["nombre"]) for a in sv_sub_analyses.values() if a is not None])
|
||||
|
||||
|
||||
def sv_sub_weights_table(sv_sub_analyses: dict, survival: SurvivalSettings) -> pd.DataFrame | None:
|
||||
if not survival.combine_active:
|
||||
return None
|
||||
return pd.concat([a["pesos"].assign(subgrupo=a["nombre"]) for a in sv_sub_analyses.values() if a is not None])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- age as a continuous variable
|
||||
|
||||
def sv_age_test(sv_frame: SurvivalFrame, sv_cohort: sm.Cohort, sv_masks: dict, survival: SurvivalSettings) -> AgeTest:
|
||||
"""Age as a number (the middle of its 5-year group, standardized, linear or quadratic) in the LR against the
|
||||
categorized age: how far each variant's mean survival is from Kaplan-Meier, and its out-of-sample log-likelihood."""
|
||||
s = survival
|
||||
df, c = sv_frame.df, sv_cohort
|
||||
N = len(df)
|
||||
ed = df[sv_frame.age_col].map(_age_midpoint).astype(float) if sv_frame.age_col else pd.Series(np.nan, index=df.index)
|
||||
assert ed.notna().mean() > 0.5, "No se pudo leer la edad numérica"
|
||||
z = ((ed - ed.mean()) / ed.std()).fillna(0.0).values
|
||||
without_age = [v for v in sv_frame.covariates if not re.search(sm.AGE_PATTERN, v.lower())]
|
||||
Xb = pd.get_dummies(df[without_age], drop_first=True).values.astype(np.float32)
|
||||
if "Edad_cat" in df.columns:
|
||||
Xcat = np.column_stack([Xb, pd.get_dummies(df[["Edad_cat"]], drop_first=True).values.astype(np.float32)])
|
||||
else:
|
||||
Xcat = c.X_dum if s.age_mode == "categorizada" else None
|
||||
variants = {"sin edad": Xb, "edad categorizada": Xcat,
|
||||
"edad continua": np.column_stack([Xb, z]).astype(np.float32),
|
||||
"edad continua + cuadrática": np.column_stack([Xb, z, z ** 2]).astype(np.float32)}
|
||||
if Xcat is None:
|
||||
variants.pop("edad categorizada")
|
||||
ref_variant = "edad categorizada" if "edad categorizada" in variants else "sin edad"
|
||||
months, event, borders = c.months, c.event, c.borders
|
||||
|
||||
def lr_interval(Xm, idx, test):
|
||||
P = []
|
||||
for a, b in zip(borders[:-1], borders[1:]):
|
||||
sel = np.where(months[idx] >= a)[0]
|
||||
y = np.where(event[idx][sel] & (months[idx][sel] < b), 0, 1)
|
||||
w = np.where((~event[idx][sel]) & (months[idx][sel] < b), 0.5, 1.0)
|
||||
P.append(LogisticRegression(C=1e6, max_iter=500).fit(Xm[idx][sel], y, sample_weight=w).predict_proba(Xm[test])[:, 1])
|
||||
return np.column_stack(P)
|
||||
|
||||
todas = np.arange(N)
|
||||
fold = np.random.default_rng(s.seed + 11).permutation(N) % s.stack_folds
|
||||
point, oof = {}, {}
|
||||
for name, Xm in variants.items():
|
||||
point[name] = np.cumprod(lr_interval(Xm, todas, todas), axis=1)
|
||||
O = np.zeros((N, len(s.horizons)))
|
||||
for k in range(s.stack_folds):
|
||||
te, tr = np.where(fold == k)[0], np.where(fold != k)[0]
|
||||
O[te] = lr_interval(Xm, tr, te)
|
||||
oof[name] = O
|
||||
|
||||
def loglik(O, mask):
|
||||
total = 0.0
|
||||
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
|
||||
i = np.where(mask & (months >= a))[0]
|
||||
y = np.where(event[i] & (months[i] < b), 0, 1)
|
||||
w = np.where((~event[i]) & (months[i] < b), 0.5, 1.0)
|
||||
p = np.clip(O[i, j], 1e-9, 1 - 1e-9)
|
||||
total += np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||
return total
|
||||
|
||||
rows = []
|
||||
for name, mask in [("Cohorte completa", np.ones(N, bool))] + list(sv_masks.items()):
|
||||
if mask.sum() == 0:
|
||||
continue
|
||||
Sk, _, _ = fw.km_curva(months[mask], event[mask], max(s.horizons))
|
||||
for i, h in enumerate(s.horizons):
|
||||
row = {"subgrupo": name, "meses": h, "KM": Sk[h]}
|
||||
for v in variants:
|
||||
row[v] = point[v][mask, i].mean()
|
||||
rows.append(row)
|
||||
T1 = pd.DataFrame(rows)
|
||||
res = []
|
||||
for v in variants:
|
||||
err = (T1[v] - T1["KM"]).abs()
|
||||
ll, ll_ref = loglik(oof[v], np.ones(N, bool)), loglik(oof[ref_variant], np.ones(N, bool))
|
||||
res.append({"variante": v, "error abs. medio vs KM (todos los subgrupos y horizontes)": err.mean(),
|
||||
"error abs. máx.": err.max(), "log-verosimilitud fuera de muestra (cohorte)": ll,
|
||||
f"Δ vs {ref_variant}": ll - ll_ref})
|
||||
return AgeTest(T1, pd.DataFrame(res))
|
||||
@@ -0,0 +1,246 @@
|
||||
"""The interval models of the survival-curves stage, apart from its nodes (`survival_curves.py`): the logistic regression
|
||||
(LR) and the Bayesian network with a tabular CPT (HBN) fitted per time interval, their cumulative survival, the
|
||||
out-of-sample stacking that combines them, and the covariate-adjusted Kaplan-Meier curve. Plain functions with no I/O.
|
||||
Ported from `05_curvas_supervivencia.py`.
|
||||
|
||||
A patient's survival to a horizon is the product of the survival of each interval up to it. Each interval's models use
|
||||
the patients alive at its start; a censoring inside the interval counts as half a risk (weight 0.5).
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.optimize import minimize_scalar
|
||||
from scipy.special import gammaln
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
|
||||
AGE_PATTERN = r"(^|_)age(_|$)|edad"
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Cohort:
|
||||
"""What the models fit on: the follow-up, the two codings of the covariates (dummies for the LR, integer codes and
|
||||
their levels for the HBN), and the HBN's fixed parents."""
|
||||
|
||||
months: np.ndarray
|
||||
event: np.ndarray
|
||||
X_dum: np.ndarray
|
||||
X_int: np.ndarray
|
||||
levels: np.ndarray
|
||||
borders: list[int]
|
||||
fixed_parents: list[int] | None
|
||||
|
||||
|
||||
def fixed_parent_indices(covariates: list[str], s: SurvivalSettings) -> list[int] | None:
|
||||
"""The HBN's fixed parents as covariate positions, found by keyword; the grouped age is added when asked (expert
|
||||
knowledge: the algorithm didn't choose it). None = learn them."""
|
||||
if not s.hbn_fixed_parents:
|
||||
return None
|
||||
keywords = list(s.hbn_fixed_parents)
|
||||
if s.hbn_age_parent and not any(re.search(AGE_PATTERN, k.lower()) for k in keywords):
|
||||
keywords.append("Edad")
|
||||
out = []
|
||||
for kw in keywords:
|
||||
hit = [j for j, c in enumerate(covariates) if kw.lower() in c.lower()]
|
||||
assert hit, f"hbn_fixed_parents: no hay una covariable que contenga '{kw}' en {covariates}"
|
||||
out.append(hit[0])
|
||||
return out
|
||||
|
||||
|
||||
def censoring_weights(months, event, h, mode):
|
||||
"""(known, y, w) for the horizon `h`: who is known at h, who survives to it, and their weights. `ipcw` weights by the
|
||||
inverse probability of not being censored; `excluir` drops the alive with follow-up under h; `riesgo` is
|
||||
`interval_predictions`'s."""
|
||||
m = np.asarray(months, int)
|
||||
e = np.asarray(event, bool)
|
||||
known = e | (m >= h)
|
||||
y = (m >= h).astype(int)
|
||||
w = np.ones(len(m))
|
||||
if mode == "ipcw":
|
||||
T = int(m.max()) + 2
|
||||
cen = np.bincount(m[~e], minlength=T)
|
||||
mu = np.bincount(m, minlength=T)
|
||||
nr = len(m) - np.concatenate([[0], np.cumsum(mu)[:-1]])
|
||||
G = np.concatenate([[1.0], np.cumprod(1 - cen / np.maximum(nr, 1))]) # G[t] = P(not censored before month t)
|
||||
G = np.clip(G, 0.05, 1.0)
|
||||
w = 1.0 / G[np.minimum(m, h)]
|
||||
return known, y, w
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the HBN with a tabular CPT
|
||||
|
||||
def bdeu(code, y, w, q, ess):
|
||||
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
|
||||
nj = n.sum(1)
|
||||
aj = ess / q
|
||||
ajk = aj / 2
|
||||
return float(np.sum(gammaln(aj) - gammaln(aj + nj) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)))
|
||||
|
||||
|
||||
def search_parents(X, levels, y, w, ess, max_parents) -> list[int]:
|
||||
"""Greedy: the covariate that most improves the BDeu score of the outcome, until none does or `max_parents`."""
|
||||
parents, code, q = [], np.zeros(len(y), int), 1
|
||||
best = bdeu(code, y, w, q, ess)
|
||||
while len(parents) < max_parents:
|
||||
cand = 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]
|
||||
s = bdeu(c2, y, w, q * levels[j], ess)
|
||||
if s > best + 1e-9 and (cand is None or s > cand[0]):
|
||||
cand = (s, j, c2, q * levels[j])
|
||||
if cand is None:
|
||||
break
|
||||
best, j, code, q = cand
|
||||
parents.append(j)
|
||||
return parents
|
||||
|
||||
|
||||
def fit_hbn(X, levels, y, w, s: SurvivalSettings, fixed, parents=None):
|
||||
"""(parents, P(Y=1 | parents)), smoothed toward the marginal survival so the prior doesn't bias to 0.5."""
|
||||
if parents is None and fixed is not None:
|
||||
parents = fixed
|
||||
parents = search_parents(X, levels, y, w, s.hbn_ess, s.hbn_max_parents) if parents is None else list(parents)
|
||||
q = int(np.prod([levels[j] for j in parents])) if parents else 1
|
||||
code = np.zeros(len(y), int)
|
||||
for j in parents:
|
||||
code = code * levels[j] + X[:, j]
|
||||
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
|
||||
aj = s.hbn_ess / q
|
||||
pbar = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
|
||||
return parents, (n[:, 1] + aj * pbar) / (n.sum(1) + aj)
|
||||
|
||||
|
||||
def predict_hbn(model, X, levels):
|
||||
parents, cpt = model
|
||||
code = np.zeros(len(X), int)
|
||||
for j in parents:
|
||||
code = code * levels[j] + X[:, j]
|
||||
return cpt[code]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the models by interval
|
||||
|
||||
def predict_horizon(c: Cohort, s: SurvivalSettings, idx, h, mode, parents=None):
|
||||
"""LR and HBN probabilities of surviving to `h` with a model per horizon (the `ipcw` and `excluir` treatments)."""
|
||||
m, e = c.months[idx], c.event[idx]
|
||||
known, y, w = censoring_weights(m, e, h, mode)
|
||||
sel = np.where(known)[0]
|
||||
lr = LogisticRegression(C=1e6, max_iter=500)
|
||||
lr.fit(c.X_dum[idx][sel], y[sel], sample_weight=w[sel])
|
||||
mod = fit_hbn(c.X_int[idx][sel], c.levels, y[sel], w[sel], s, c.fixed_parents, parents)
|
||||
return lr.predict_proba(c.X_dum[idx])[:, 1], predict_hbn(mod, c.X_int[idx], c.levels), list(mod[0])
|
||||
|
||||
|
||||
def interval_predictions(c: Cohort, s: SurvivalSettings, idx, parents=None, test=None):
|
||||
"""Per interval, the probability of surviving it for the `test` patients (default `idx`) by LR and HBN, fitted on the
|
||||
patients of `idx` alive at its start; and the HBN's parents of each interval."""
|
||||
test = idx if test is None else test
|
||||
m, e = c.months[idx], c.event[idx]
|
||||
P_lr, P_hb, pads = [], [], []
|
||||
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
|
||||
sel = np.where(m >= a)[0] # alive at the start of the interval
|
||||
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
|
||||
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
|
||||
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
|
||||
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
|
||||
P_lr.append(lr.predict_proba(c.X_dum[test])[:, 1])
|
||||
P_hb.append(predict_hbn(mod, c.X_int[test], c.levels))
|
||||
pads.append(list(mod[0]))
|
||||
return np.column_stack(P_lr), np.column_stack(P_hb), pads
|
||||
|
||||
|
||||
def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
|
||||
"""(LR, HBN, parents): each patient's survival at each horizon."""
|
||||
if mode == "riesgo":
|
||||
Pl, Ph, pads = interval_predictions(c, s, idx, parents)
|
||||
return np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1), pads
|
||||
r = [predict_horizon(c, s, idx, h, mode, None if parents is None else parents[i])
|
||||
for i, h in enumerate(s.horizons)]
|
||||
return np.column_stack([x[0] for x in r]), np.column_stack([x[1] for x in r]), [x[2] for x in r]
|
||||
|
||||
|
||||
def estimate(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
|
||||
P_lr, P_hb, pads = patient_survival(c, s, idx, mode, parents)
|
||||
return P_lr.mean(axis=0), P_hb.mean(axis=0), pads
|
||||
|
||||
|
||||
def out_of_fold(c: Cohort, s: SurvivalSettings, n: int):
|
||||
"""Each patient's interval probabilities from models that never saw them (`stack_folds` folds)."""
|
||||
fold = np.random.default_rng(s.seed + 7).permutation(n) % s.stack_folds
|
||||
oof_lr = np.zeros((n, len(s.horizons)))
|
||||
oof_hb = np.zeros_like(oof_lr)
|
||||
for k in range(s.stack_folds):
|
||||
te, tr = np.where(fold == k)[0], np.where(fold != k)[0]
|
||||
Pl, Ph, _ = interval_predictions(c, s, tr, None, te)
|
||||
oof_lr[te], oof_hb[te] = Pl, Ph
|
||||
return oof_lr, oof_hb
|
||||
|
||||
|
||||
def stacking_weights(c: Cohort, s: SurvivalSettings, mask, oof_lr, oof_hb) -> pd.DataFrame:
|
||||
"""Per interval, the weight of the LR in the LR + HBN mixture: the one that maximizes the out-of-sample weighted
|
||||
log-likelihood of the patients in `mask`, shrunk toward 50/50 when there are few deaths
|
||||
(lambda = shrink / (shrink + deaths))."""
|
||||
rows = []
|
||||
for j, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
|
||||
idx = np.where(mask & (c.months >= a))[0]
|
||||
e, m = c.event[idx], c.months[idx]
|
||||
y = np.where(e & (m < b), 0, 1)
|
||||
wt = np.where((~e) & (m < b), 0.5, 1.0)
|
||||
p1 = np.clip(oof_lr[idx, j], 1e-9, 1 - 1e-9)
|
||||
p2 = np.clip(oof_hb[idx, j], 1e-9, 1 - 1e-9)
|
||||
deaths = int((y == 0).sum())
|
||||
if len(idx) == 0:
|
||||
rows.append(dict(intervalo=f"{a}-{b}", n_riesgo=0, muertes=0, w_LR=0.5, w_LR_sin_contraer=0.5,
|
||||
dLL_LR_menos_HBN=0.0, z=0.0, decision="mezcla"))
|
||||
continue
|
||||
|
||||
def nll(w_):
|
||||
p = np.clip(w_ * p1 + (1 - w_) * p2, 1e-9, 1 - 1e-9)
|
||||
return -np.sum(wt * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||
|
||||
w_star = float(minimize_scalar(nll, bounds=(0, 1), method="bounded").x)
|
||||
lam = s.stack_shrink / (s.stack_shrink + deaths)
|
||||
w_fin = (1 - lam) * w_star + lam * 0.5
|
||||
d = wt * (y * (np.log(p1) - np.log(p2)) + (1 - y) * (np.log1p(-p1) - np.log1p(-p2))) # LR - HBN log-score
|
||||
z = d.sum() / (np.sqrt(len(d)) * d.std(ddof=1)) if len(d) > 2 and d.std(ddof=1) > 0 else 0.0
|
||||
decision = "solo LR" if w_fin >= 0.95 else "solo HBN" if w_fin <= 0.05 else "mezcla"
|
||||
rows.append(dict(intervalo=f"{a}-{b}", n_riesgo=len(idx), muertes=deaths, w_LR=w_fin, w_LR_sin_contraer=w_star,
|
||||
dLL_LR_menos_HBN=float(d.sum()), z=float(z), decision=decision))
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def estimate_combined(c: Cohort, s: SurvivalSettings, idx, parents, W):
|
||||
"""(LR, HBN, combined, parents): the mean survival at each horizon; the combination mixes each interval's LR and HBN
|
||||
probabilities with the weights `W` before accumulating."""
|
||||
Pl, Ph, pads = interval_predictions(c, s, idx, parents)
|
||||
Sc = np.cumprod(W[None, :] * Pl + (1 - W[None, :]) * Ph, axis=1)
|
||||
return np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), Sc.mean(0), pads
|
||||
|
||||
|
||||
def adjusted_curve(c: Cohort, idx, T: int, step: int) -> np.ndarray:
|
||||
"""The covariate-adjusted Kaplan-Meier: the mean over patients of the product of their interval survivals (a
|
||||
regularized LR per `step` months), by direct standardization; monotone and interpolated by month."""
|
||||
m, e = c.months[idx], c.event[idx]
|
||||
borders = list(range(0, T + 1, step))
|
||||
if borders[-1] < T:
|
||||
borders.append(T)
|
||||
S_i = np.ones(len(idx))
|
||||
S_b = [1.0]
|
||||
for a, b in zip(borders[:-1], borders[1:]):
|
||||
sel = np.where(m >= a)[0]
|
||||
y = np.where(e[sel] & (m[sel] < b), 0, 1)
|
||||
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
|
||||
if y.min() == y.max():
|
||||
S_i = S_i * y.mean()
|
||||
else:
|
||||
lr = LogisticRegression(C=10.0, max_iter=300).fit(c.X_dum[idx][sel], y, sample_weight=w)
|
||||
S_i = S_i * lr.predict_proba(c.X_dum[idx])[:, 1]
|
||||
S_b.append(S_i.mean())
|
||||
S_b = np.minimum.accumulate(np.array(S_b))
|
||||
return np.exp(np.interp(np.arange(T + 1), borders, np.log(np.maximum(S_b, 1e-12))))
|
||||
@@ -0,0 +1,7 @@
|
||||
"""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
|
||||
"""
|
||||
@@ -0,0 +1,134 @@
|
||||
"""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
|
||||
@@ -0,0 +1 @@
|
||||
"""CaCu's cohorts: the surveillance cohort."""
|
||||
@@ -0,0 +1,106 @@
|
||||
"""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
|
||||
@@ -0,0 +1,78 @@
|
||||
# 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"
|
||||
@@ -0,0 +1 @@
|
||||
"""CaMa's cohorts: the screening cohort, a proposal the cycle doesn't build yet."""
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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"
|
||||
@@ -0,0 +1,81 @@
|
||||
"""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
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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
|
||||
@@ -1,34 +0,0 @@
|
||||
"""ONNX checkpoint inspection (ML-01b, MLD-03).
|
||||
|
||||
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
|
||||
which hands it to MLflow directly — nothing here manages storage paths.
|
||||
`onnx` is an optional dependency (`models[export]`); without it
|
||||
`inspect_onnx_metadata` returns `{"available": False}`.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
||||
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
|
||||
`{"available": False}` when the optional `onnx` package isn't installed;
|
||||
`ValueError` when it is and the file isn't a valid ONNX model."""
|
||||
try:
|
||||
import onnx
|
||||
except ImportError:
|
||||
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
|
||||
|
||||
try:
|
||||
model = onnx.load(str(path))
|
||||
onnx.checker.check_model(model)
|
||||
except Exception as exc:
|
||||
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
|
||||
return {
|
||||
"available": True,
|
||||
"ir_version": model.ir_version,
|
||||
"producer_name": model.producer_name,
|
||||
"producer_version": model.producer_version,
|
||||
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
|
||||
"graph_inputs": [i.name for i in model.graph.input],
|
||||
"graph_outputs": [o.name for o in model.graph.output],
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes."""
|
||||
@@ -0,0 +1,134 @@
|
||||
"""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]: ...
|
||||
@@ -0,0 +1,180 @@
|
||||
"""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",
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"""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}")
|
||||
@@ -0,0 +1,137 @@
|
||||
"""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}
|
||||
@@ -0,0 +1,268 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,445 @@
|
||||
"""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"
|
||||
|
||||
|
||||
@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
|
||||
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)}"
|
||||
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,
|
||||
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
|
||||
@@ -0,0 +1,152 @@
|
||||
"""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
|
||||
@@ -0,0 +1,240 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""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,84 @@
|
||||
"""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)
|
||||
+1
-1
@@ -32,7 +32,7 @@ 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.base import resolve_repository
|
||||
from models.io.storage import resolve_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
# Below this confidence a value is stored but flagged for manual review.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge."""
|
||||
@@ -0,0 +1,70 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""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
|
||||
@@ -0,0 +1,73 @@
|
||||
"""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"
|
||||
@@ -0,0 +1,51 @@
|
||||
"""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))
|
||||
@@ -0,0 +1,48 @@
|
||||
"""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
|
||||
@@ -0,0 +1,31 @@
|
||||
"""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,127 +0,0 @@
|
||||
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
|
||||
produced it. Callers go through `PredictionService` rather than calling
|
||||
`model.predict(...)` directly.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from core.governance.models import ModelPrediction
|
||||
from mlflow import MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||
|
||||
|
||||
@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 `ScreeningModel` 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: ScreeningModel,
|
||||
*,
|
||||
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 models.registry.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,249 +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.
|
||||
|
||||
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 re
|
||||
import tempfile
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.export import inspect_onnx_metadata
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
PRODUCTION_ALIAS = "produccion"
|
||||
ARMADO_TAG = "kit.armado_id"
|
||||
|
||||
|
||||
@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}")
|
||||
|
||||
|
||||
def registered_name(domain: str, scenario: str) -> str:
|
||||
return f"{domain}-{scenario}"
|
||||
|
||||
|
||||
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 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.
|
||||
In-process training uses `models.training.TrainingRun` directly."""
|
||||
from models.training import TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
||||
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
|
||||
|
||||
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 add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
|
||||
"""Logs an artifact file to the run behind an already-registered
|
||||
version (ML-01a/b), e.g. a checkpoint exported after training.
|
||||
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
|
||||
rejected (400) instead of silently stored."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
kind_value = kind.value if hasattr(kind, "value") else str(kind)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / filename
|
||||
path.write_bytes(data)
|
||||
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
|
||||
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
|
||||
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
|
||||
|
||||
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": [a.path for a in self.client.list_artifacts(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))
|
||||
metrics = run.data.metrics
|
||||
artifacts = self.client.list_artifacts(mv.run_id)
|
||||
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,
|
||||
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
|
||||
),
|
||||
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-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
|
||||
]
|
||||
|
||||
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}").cohorte_repository
|
||||
armado = cohortes.get(int(armado_id))
|
||||
if armado is None:
|
||||
return None, []
|
||||
exclusion = cohortes.cohortes.CohorteExclusion
|
||||
pasos = cohortes.leer(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])
|
||||
@@ -0,0 +1,4 @@
|
||||
"""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.
|
||||
"""
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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"})
|
||||
@@ -0,0 +1,42 @@
|
||||
"""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()}})
|
||||
@@ -0,0 +1,21 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,13 @@
|
||||
"""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"])]
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class TeaModel(ScreeningModel):
|
||||
"""Scaffold for the TEA (autism spectrum disorder) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.tea`'s
|
||||
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
|
||||
...) or be handed already-fetched rows. No real model yet; this is
|
||||
interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "tea"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("TEA training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("TEA prediction is not implemented yet.")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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
|
||||
@@ -1,143 +0,0 @@
|
||||
"""Bookkeeping around a training run (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. 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).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.repository import Repository
|
||||
|
||||
from models.base import resolve_repository
|
||||
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
|
||||
|
||||
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: 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)
|
||||
|
||||
|
||||
class TrainingRun:
|
||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
||||
runs require `cohorte_armado_id`, the indicator kit cohort build they were
|
||||
trained on, so their metrics trace back to that data (ML-03); dev runs may
|
||||
omit it.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | 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:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
|
||||
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.environment = environment
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
experiment_id,
|
||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
|
||||
)
|
||||
self.run_id = run.info.run_id
|
||||
if cohorte_armado_id is not None:
|
||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
||||
|
||||
def _experiment_id(self) -> str:
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
experiment = self.client.get_experiment_by_name(name)
|
||||
if experiment:
|
||||
return experiment.experiment_id
|
||||
root = os.environ.get(ARTIFACT_ROOT_ENV)
|
||||
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
|
||||
|
||||
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."""
|
||||
kind = ArtifactKind(kind)
|
||||
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
|
||||
if metadata:
|
||||
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
|
||||
|
||||
def finish(
|
||||
self,
|
||||
*,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
) -> str:
|
||||
"""Logs metrics/params to the run, registers it as a new version of
|
||||
`<domain>-<scenario>` tagged with `models.registry`'s promotion
|
||||
inputs (environment, cohort link, report URIs), and returns the new
|
||||
version string. Call once, after training (and artifact logging)
|
||||
completes."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
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))
|
||||
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
self.client.create_registered_model(name)
|
||||
except MlflowException as exc:
|
||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
|
||||
if self.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
|
||||
self.client.set_terminated(self.run_id)
|
||||
return str(model_version.version)
|
||||
+37
-6
@@ -7,16 +7,37 @@ dependencies = [
|
||||
"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",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
||||
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
|
||||
# requires it, see that module's docstring.
|
||||
export = [
|
||||
"onnx>=1.15",
|
||||
# Running uploaded notebooks without Quarto (models.io.rendering.JupyterRenderer, models.pipelines.experiment).
|
||||
notebooks = [
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
|
||||
# The SEER survival pipeline (`models.cama.seer_survival`): statsmodels for the logistic regressions, pgmpy for the
|
||||
# Bayesian network, mpmath for the fractional Weibull's series, matplotlib for its figures. `dcurves` is optional: without
|
||||
# it the decision-curve figure is skipped.
|
||||
seer-survival = [
|
||||
"scipy>=1.11",
|
||||
"statsmodels>=0.14",
|
||||
"pgmpy>=1.0",
|
||||
"networkx>=3.0",
|
||||
"mpmath>=1.3",
|
||||
"matplotlib>=3.8",
|
||||
]
|
||||
seer-survival-dca = ["dcurves>=1.1"]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
@@ -27,10 +48,20 @@ build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["models"]
|
||||
exclude = ["**/notebooks", "**/experiments"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"onnx>=1.15",
|
||||
"reportlab>=4.0",
|
||||
# the SEER survival pipeline's tests (the `seer-survival` extra)
|
||||
"scipy>=1.11",
|
||||
"statsmodels>=0.14",
|
||||
"pgmpy>=1.0",
|
||||
"networkx>=3.0",
|
||||
"mpmath>=1.3",
|
||||
"matplotlib>=3.8",
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
"""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
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The SEER survival pipeline's stages: depuration (01) and bootstrapping (03), on small synthetic frames."""
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cama.seer_survival import depuration, depuration_stats as stats, run
|
||||
from models.cama.seer_survival.settings import BootstrapSettings, Settings, load
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings() -> Settings:
|
||||
s = load()
|
||||
return dataclasses.replace(s, depuration=dataclasses.replace(s.depuration, null_perm=5))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def recoded() -> pd.DataFrame:
|
||||
"""`B_cat` repeats `A_cat` under other labels; `Tumor_group` repeats `T_cat` and is the preferred of the two; `C_cat`
|
||||
and `D_cat` are independent; `Outcome_cat` is never touched."""
|
||||
rng = np.random.default_rng(1)
|
||||
n = 600
|
||||
a = rng.choice(list("abcd"), n)
|
||||
t = rng.choice(["t1", "t2", "t3"], n)
|
||||
return pd.DataFrame({
|
||||
"A_cat": a, "B_cat": pd.Series(a).map({"a": "w", "b": "x", "c": "y", "d": "z"}).values, "raw_b": a,
|
||||
"T_cat": t, "Tumor_group": pd.Series(t).map({"t1": "g1", "t2": "g2", "t3": "g3"}).values,
|
||||
"C_cat": rng.choice(["u", "v", "w"], n), "D_cat": rng.choice(["p", "q"], n),
|
||||
"Outcome_cat": rng.choice(["0", "1"], n)})
|
||||
|
||||
|
||||
def test_the_duplicate_is_dropped_with_its_raw_column_and_the_preferred_one_is_kept(tmp_path, settings, recoded):
|
||||
recoded.to_csv(tmp_path / "recoded.csv", index=False)
|
||||
(tmp_path / "map.json").write_text(json.dumps({"B_cat": "raw_b"}))
|
||||
|
||||
r = run.run_depuration(tmp_path / "recoded.csv", tmp_path / "map.json", tmp_path, settings, generated_at="t")
|
||||
|
||||
assert sorted(r["elimination"].dropped["variable"]) == ["B_cat", "T_cat"]
|
||||
assert set(r["elimination"].dropped["paso"]) == {"A duplicada"}
|
||||
out = pd.read_csv(tmp_path / run.DEPURATED, dtype=str)
|
||||
assert list(out.columns) == ["A_cat", "Tumor_group", "C_cat", "D_cat", "Outcome_cat"]
|
||||
kept = json.loads((tmp_path / run.DEPURATION_DIR / "variables_conservadas.json").read_text())
|
||||
assert kept["crudas_eliminadas"] == ["raw_b"]
|
||||
for name in ("calibracion_U_pares.csv", "calibracion_umbrales.json", "variables_eliminadas.csv"):
|
||||
assert (tmp_path / run.DEPURATION_DIR / name).exists()
|
||||
|
||||
|
||||
def test_the_analysis_leaves_out_excluded_and_constant_columns(settings, recoded):
|
||||
recoded["K_cat"] = "same"
|
||||
frame = depuration.analysis_frame(recoded, settings.depuration)
|
||||
assert "Outcome_cat" not in frame and "K_cat" not in frame and "raw_b" not in frame
|
||||
assert "Tumor_group" in frame
|
||||
|
||||
|
||||
def test_a_protected_variable_is_never_dropped(settings, recoded):
|
||||
s = dataclasses.replace(settings.depuration, protected=("B_cat",))
|
||||
frame = depuration.analysis_frame(recoded, s)
|
||||
t = stats.Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, 0.5, 0.5, False)
|
||||
dropped = stats.eliminate(frame, list(frame.columns), t, s)
|
||||
assert "B_cat" not in set(dropped["variable"]) and "A_cat" in set(dropped["variable"])
|
||||
|
||||
|
||||
def test_theil_u_of_a_relabelled_copy_is_one_and_of_independent_variables_near_zero(recoded):
|
||||
U = stats.theil_u_matrix(recoded, ["A_cat", "B_cat", "C_cat"])
|
||||
assert U.loc["A_cat", "B_cat"] == pytest.approx(1.0) and U.loc["B_cat", "A_cat"] == pytest.approx(1.0)
|
||||
assert U.loc["A_cat", "C_cat"] < 0.05
|
||||
|
||||
|
||||
def test_auto_thresholds_take_the_calibrations_suggestions(settings, recoded):
|
||||
s = dataclasses.replace(settings.depuration, thresholds_auto=True)
|
||||
frame = depuration.analysis_frame(recoded, s)
|
||||
c = stats.calibrate(frame, list(frame.columns), s, "t")
|
||||
t = stats.thresholds_in_use(c, s)
|
||||
assert t.auto and t.u_redund == c.u_suggestion["U"] and t.dup_u == c.dup_u_suggested
|
||||
|
||||
|
||||
def test_calibration_needs_two_variables(settings):
|
||||
frame = pd.DataFrame({"A_cat": ["a", "b"] * 50})
|
||||
with pytest.raises(ValueError, match="al menos 2"):
|
||||
stats.calibrate(frame, ["A_cat"], settings.depuration, "t")
|
||||
|
||||
|
||||
def test_unknown_settings_are_refused(tmp_path):
|
||||
bad = tmp_path / "model.toml"
|
||||
bad.write_text("[depuration]\nnope = 1\n[bootstrap]\nn_bootstrap = 1\nrandom_state = 0\n")
|
||||
with pytest.raises(ValueError, match="unknown settings"):
|
||||
load(bad)
|
||||
|
||||
|
||||
def test_the_bootstrap_indices_are_reproducible_and_within_the_rows(tmp_path):
|
||||
pd.DataFrame({"x": range(50)}).to_csv(tmp_path / "balanced.csv", index=False)
|
||||
s = dataclasses.replace(load(), bootstrap=BootstrapSettings(n_bootstrap=7, random_state=3))
|
||||
|
||||
first = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
|
||||
again = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
|
||||
|
||||
assert first.shape == (7, 50) and first.min() >= 0 and first.max() < 50
|
||||
assert np.array_equal(first, again) and np.array_equal(np.load(tmp_path / run.BOOTSTRAP_INDICES), first)
|
||||
meta = json.loads((tmp_path / run.BOOTSTRAP_METADATA).read_text())
|
||||
assert (meta["n_filas"], meta["n_bootstrap"], meta["random_state"]) == (50, 7, 3)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""The numeric cores of the SEER survival pipeline's stages 02, 04, 05 and 06, and its runner, on small synthetic data."""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cama.seer_survival import (balancing_stats, categorization_stats as cs, fractional_weibull as fw, hbn,
|
||||
lr_selection, pipeline, risk_factor_stats as rf, survival_models as sm)
|
||||
from models.cama.seer_survival.settings import load
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- settings
|
||||
|
||||
def test_every_stage_has_its_settings():
|
||||
s = load()
|
||||
assert s.balancing.mca_variant in ("con_edad", "sin_edad")
|
||||
assert "Biología + tratamiento" in {s.categorization.age_final}
|
||||
assert set(s.categorization.proposals) >= {"P1_actual", "P6_clinico_fijo", "P7_cuantiles"}
|
||||
assert s.modeling.canonical_map["Age_group"] == "Edad"
|
||||
assert len(s.survival.subgroups) == 13 and s.survival.combine_active and s.survival.months_max == 24
|
||||
assert s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 02a balancing
|
||||
|
||||
def test_age_midpoints():
|
||||
mid = balancing_stats.age_midpoint
|
||||
assert mid("40-44 years") == 42 and mid("85+ years") == 90 and mid("05") == 5 and np.isnan(mid("unknown"))
|
||||
|
||||
|
||||
def test_the_outcome_treats_censoring_and_incomplete_years_as_unknown():
|
||||
s = load().balancing
|
||||
labels = {"m": "Survival months", "v": "Vital status", "y": "Year of diagnosis"}
|
||||
df = pd.DataFrame({"m": ["30", "5", "5", "30", "40"], "v": ["Alive", "Dead", "Alive", "Dead", "Alive"],
|
||||
"y": ["2000", "2000", "2000", "2001", "2001"]})
|
||||
# alive with 5 months is censored: unknown; year 2000 has 1 of 3 censored (> 10 %), so the whole year leaves
|
||||
assert np.isnan(balancing_stats.outcome_values(df, labels, s)).tolist() == [True, True, True, False, False]
|
||||
assert balancing_stats.outcome_values(df, labels, s)[3:].tolist() == [1.0, 1.0]
|
||||
keep = balancing_stats.outcome_values(df, labels, s.__class__(**{**s.__dict__, "exclude_censored_years": False}))
|
||||
assert keep[0] == 1.0 and keep[1] == 0.0 and np.isnan(keep[2]) # only the censored patient stays unknown
|
||||
|
||||
|
||||
def test_the_undersampling_keeps_every_death_and_the_survivors_nearest_to_them():
|
||||
F = np.array([[0.0], [0.1], [5.0], [9.0], [0.2], [8.0]])
|
||||
outcome = np.array([0, 1, 1, 1, 0, 1]) # 0 = death (minority): rows 0 and 4
|
||||
keep, dist = balancing_stats.select_informed_undersample(F, outcome, 0, 1, target_ratio=1.0)
|
||||
assert keep.tolist() == [True, True, True, False, True, False] # 2 deaths + the 2 nearest survivors
|
||||
assert dist[1] == pytest.approx(0.1) and dist[3] == pytest.approx(8.8)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 02b categorization
|
||||
|
||||
def _axis_frame(rng_seed=0):
|
||||
"""Ten levels; the category mix flips between level 4 and 5 (the only real boundary)."""
|
||||
rng = np.random.default_rng(rng_seed)
|
||||
levels = [f"{i:02d}" for i in range(10)]
|
||||
rows = []
|
||||
for i, level in enumerate(levels):
|
||||
for _ in range(300):
|
||||
p = 0.9 if i < 5 else 0.1
|
||||
rows.append({"lvl": level, "X_cat": "a" if rng.random() < p else "b",
|
||||
"Y_cat": "u" if rng.random() < (0.85 if i < 5 else 0.15) else "v"})
|
||||
return pd.DataFrame(rows), levels
|
||||
|
||||
|
||||
def test_segmentation_finds_the_one_boundary_where_the_composition_flips():
|
||||
df, levels = _axis_frame()
|
||||
axis = cs.Axis.of(df, "lvl", levels, list(range(10)), "corte_x")
|
||||
s = load().categorization
|
||||
result = cs.segment(df, axis, ["X", "Y"], {}, s, min_n=100)
|
||||
assert result.bounds == [5] and result.segments == [(0, 5), (5, 10)]
|
||||
assert result.effect_sizes["cambio_medio"].iloc[0] > 0.7
|
||||
assert cs.level_to_group(result.segments, levels)["00"] == "00 a 04"
|
||||
|
||||
|
||||
def test_small_segments_are_merged_into_the_most_similar_neighbour():
|
||||
counts = {"c": pd.DataFrame([[50, 0], [50, 0], [0, 50], [0, 50], [45, 5]], columns=["a", "b"])}
|
||||
segs, log = cs.fix_small_segments(counts, np.array([50, 50, 50, 50, 50]), [2, 4], 5, min_n=80)
|
||||
assert all(sum(50 for _ in range(a, b)) >= 80 for a, b in segs) and log
|
||||
|
||||
|
||||
def test_configurations_are_every_combination_of_blocks():
|
||||
configs = cs.configurations({"outcome": ["Outcome"], "biología": ["A", "B"], "tratamiento": ["T"]})
|
||||
assert set(configs) == {"Solo outcome", "Solo biología", "Solo tratamiento", "Outcome + biología",
|
||||
"Outcome + tratamiento", "Biología + tratamiento", "Outcome + biología + tratamiento"}
|
||||
assert configs["Biología + tratamiento"] == ["A", "B", "T"]
|
||||
|
||||
|
||||
def test_tumor_sizes_and_levels():
|
||||
assert cs.tumor_size_mm("023") == 23.0 and np.isnan(cs.tumor_size_mm("000")) and np.isnan(cs.tumor_size_mm("999"))
|
||||
assert cs.tumor_bin_label(23.0, 5, 100) == "021-025 mm" and cs.tumor_bin_label(101.0, 5, 100) == ">100 mm"
|
||||
levels, mids = cs.tumor_levels(5, 100)
|
||||
assert levels[0] == "001-005 mm" and levels[-1] == ">100 mm" and len(levels) == len(mids) == 21 and mids[0] == 3.0
|
||||
|
||||
|
||||
def test_quantile_and_clinical_cuts_partition_the_axis():
|
||||
assert cs.quantile_bounds(np.array([10, 10, 10, 10, 10, 10, 10, 10]), 4) == [2, 4, 6]
|
||||
segs = cs.segments_from_bounds([3, 3, 0, 99, 5], 8)
|
||||
assert segs == [(0, 3), (3, 5), (5, 8)]
|
||||
|
||||
|
||||
def test_sensitivity_and_specificity_at_a_cut():
|
||||
idx = np.array([0, 0, 1, 1, 2, 2, 3, 3])
|
||||
death = np.array([0, 0, 0, 1, 0, 1, 1, 1], bool)
|
||||
r = cs.sens_spec_at_cut(idx, death, 2)
|
||||
assert r["lado_alto_riesgo"] == "arriba del corte" and r["sensibilidad"] == 0.75 and r["especificidad"] == 0.75
|
||||
|
||||
|
||||
def test_the_overlap_of_identical_distributions_is_one():
|
||||
a = pd.Series(["x", "y", "x", "y"])
|
||||
assert cs.overlap_coefficient(a, a, ["x", "y"]) == 1.0
|
||||
assert cs.overlap_coefficient(pd.Series(["x"] * 4), pd.Series(["y"] * 4), ["x", "y"]) == 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 04 modeling
|
||||
|
||||
def test_the_stepwise_keeps_the_signal_and_drops_the_noise():
|
||||
rng = np.random.default_rng(3)
|
||||
n = 1500
|
||||
signal, noise = rng.normal(size=n), rng.normal(size=n)
|
||||
y = pd.Series((rng.random(n) < 1 / (1 + np.exp(-2 * signal))).astype(int))
|
||||
X = pd.DataFrame({"signal": signal, "noise": noise, "noise2": rng.normal(size=n)})
|
||||
assert lr_selection.stepwise_selection(X, y) == ["signal"]
|
||||
|
||||
|
||||
def test_the_prefilter_sorts_by_chi_square_and_caps_the_columns():
|
||||
rng = np.random.default_rng(4)
|
||||
y = pd.Series(rng.integers(0, 2, 800))
|
||||
X = pd.DataFrame({"weak": ((y.values + (rng.random(800) < 0.4)) > 0).astype(float),
|
||||
"strong": ((y.values + (rng.random(800) < 0.05)) > 0).astype(float),
|
||||
"none": rng.integers(0, 2, 800).astype(float)})
|
||||
assert lr_selection.prefiltered_columns(X, y, 0.10, 40) == ["strong", "weak"]
|
||||
assert lr_selection.prefiltered_columns(X, y, 0.10, 1) == ["strong"]
|
||||
|
||||
|
||||
def test_the_temporal_tiers_order_demography_tumor_treatment_outcome():
|
||||
s = load().modeling
|
||||
tiers = hbn.temporal_order(["Estadio", "Edad", "Radioterapia", "outcome", "Rara"], s)
|
||||
assert tiers == [["Rara"], ["Edad"], ["Estadio"], ["Radioterapia"], ["outcome"]]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 05 survival
|
||||
|
||||
def test_the_classic_weibull_fit_recovers_its_parameters():
|
||||
rng = np.random.default_rng(5)
|
||||
t = 80.0 * rng.weibull(1.4, 6000)
|
||||
months = np.minimum(np.floor(t).astype(int), 40)
|
||||
event = t < 40
|
||||
d, c = fw.tabla_eventos(months, event)
|
||||
w = fw.ajustar_weibull(d, c)
|
||||
assert w["k"] == pytest.approx(1.4, abs=0.15) and w["lam"] == pytest.approx(80.0, rel=0.12)
|
||||
|
||||
|
||||
def test_the_fractional_weibull_is_a_valid_survival_function():
|
||||
t = np.array([0.0, 1.0, 5.0, 12.0, 24.0])
|
||||
S = fw.S_ks(t, k=1.0, alpha=1.0, beta=0.5, lam=60.0)
|
||||
assert S[0] == 1.0 and np.all(np.diff(S) <= 1e-12) and np.all((S >= 0) & (S <= 1))
|
||||
assert fw.kilbas_saigo([0.0], 1.0, 1.0, 0.0)[0] == 1.0
|
||||
assert np.all(np.isnan(fw.S_ks(t, k=0.5, alpha=0.4, beta=1.0, lam=60.0))) # k + alpha <= 1: out of region
|
||||
|
||||
|
||||
def test_kaplan_meier_with_no_censoring_is_the_survivor_fraction():
|
||||
months = np.array([1, 1, 2, 3, 3, 3, 5, 5, 6, 6])
|
||||
S, lo, hi = fw.km_curva(months, np.ones(10, bool), 6)
|
||||
assert S[:7].tolist() == pytest.approx([1.0, 1.0, 0.8, 0.7, 0.4, 0.4, 0.2]) # S[m]: alive at the start of month m
|
||||
assert np.all(lo <= S + 1e-12) and np.all(S <= hi + 1e-12)
|
||||
|
||||
|
||||
def test_the_censoring_weights():
|
||||
m, e = np.array([2, 5, 8, 12]), np.array([True, False, True, False])
|
||||
known, y, w = sm.censoring_weights(m, e, 6, "excluir")
|
||||
assert known.tolist() == [True, False, True, True] and y.tolist() == [0, 0, 1, 1] and w.tolist() == [1, 1, 1, 1]
|
||||
assert sm.censoring_weights(m, e, 6, "ipcw")[2].min() >= 1.0
|
||||
|
||||
|
||||
def test_the_stacking_weight_follows_the_better_model_and_shrinks_with_few_deaths():
|
||||
rng = np.random.default_rng(6)
|
||||
n = 2000
|
||||
c = sm.Cohort(months=np.full(n, 20), event=np.zeros(n, bool), X_dum=np.zeros((n, 1)), X_int=np.zeros((n, 1), int),
|
||||
levels=np.array([1]), borders=[0, 6], fixed_parents=None)
|
||||
truth = rng.random(n) < 0.7 # survives the interval
|
||||
c = sm.Cohort(np.where(truth, 20, 3), ~truth, c.X_dum, c.X_int, c.levels, c.borders, None)
|
||||
good = np.where(truth, 0.9, 0.2)[:, None]
|
||||
bad = np.full((n, 1), 0.7)
|
||||
s = load().survival
|
||||
t = sm.stacking_weights(c, s, np.ones(n, bool), good, bad)
|
||||
assert t["w_LR"].iloc[0] > 0.9 and t["w_LR_sin_contraer"].iloc[0] >= t["w_LR"].iloc[0]
|
||||
assert t["decision"].iloc[0] in ("solo LR", "mezcla")
|
||||
|
||||
|
||||
def test_the_fixed_hbn_parents_are_found_by_keyword_and_age_is_added():
|
||||
s = load().survival
|
||||
cov = ["Estadio_cat", "Tipo_histologico_cat", "Tratamiento_quirurgico_cat", "Quimioterapia_cat", "Radioterapia_cat",
|
||||
"Edad_cat", "Race"]
|
||||
assert sm.fixed_parent_indices(cov, s) == [0, 1, 2, 3, 4, 5]
|
||||
with pytest.raises(AssertionError, match="Estadio"):
|
||||
sm.fixed_parent_indices(["Edad_cat"], s)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 06 risk factors
|
||||
|
||||
def test_benjamini_hochberg():
|
||||
p = [0.01, 0.04, 0.03, 0.005]
|
||||
assert rf.benjamini_hochberg(p).tolist() == pytest.approx([0.02, 0.04, 0.04, 0.02])
|
||||
|
||||
|
||||
def test_the_odds_of_a_risky_category_are_above_one_and_its_survival_lower():
|
||||
rng = np.random.default_rng(7)
|
||||
n = 4000
|
||||
stage = rng.choice(["I", "IV"], n, p=[0.7, 0.3])
|
||||
death = (rng.random(n) < np.where(stage == "IV", 0.5, 0.1)).astype(int)
|
||||
data = pd.DataFrame({"Estadio": stage, "Sexo": rng.choice(["f", "m"], n)})
|
||||
t = rf.fit_odds(data, death, ["Estadio", "Sexo"])
|
||||
row = t[t["termino"] == "Estadio_IV"].iloc[0]
|
||||
assert row["OR_muerte"] > 5 and row["IC95_inf"] > 1 and rf.reference(data, "Estadio") == "I"
|
||||
months = np.where(death == 1, 8, 24)
|
||||
d = rf.survival_difference(data, months, death.astype(bool), "Estadio", "IV", "I", 18)
|
||||
assert d["delta_S18"] < -0.2 and d["delta_IC95_sup"] < 0 and d["n_categoria"] == int((stage == "IV").sum())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the runner
|
||||
|
||||
def test_a_stage_is_current_only_when_its_outputs_are_newer_than_its_code_and_inputs(tmp_path):
|
||||
stage = next(e for e in pipeline.STAGES if e.id == "03")
|
||||
assert not pipeline.is_current(stage, tmp_path) # no outputs
|
||||
for name in stage.requires + stage.produces:
|
||||
(tmp_path / name).write_text("x")
|
||||
future = time.time() + 3600
|
||||
for name in stage.produces:
|
||||
os.utime(tmp_path / name, (future, future))
|
||||
assert pipeline.is_current(stage, tmp_path)
|
||||
os.utime(tmp_path / stage.requires[0], (future + 10, future + 10)) # the input changed after the outputs
|
||||
assert not pipeline.is_current(stage, tmp_path)
|
||||
(tmp_path / stage.produces[0]).write_text("") # an empty output is no output
|
||||
assert not pipeline.is_current(stage, tmp_path)
|
||||
|
||||
|
||||
def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monkeypatch):
|
||||
with pytest.raises(FileNotFoundError, match="faltan entradas"):
|
||||
pipeline.run_pipeline(tmp_path, only=["01"])
|
||||
ran = []
|
||||
stage = pipeline.Stage("99", lambda d, s: ran.append("ok"), (), ("out.csv",), ())
|
||||
monkeypatch.setattr(pipeline, "STAGES", [stage, pipeline.Stage("98", lambda d, s: ran.append("again"), (), (), ())])
|
||||
pipeline.run_pipeline(tmp_path, settings=object())
|
||||
assert ran == ["ok", "again"]
|
||||
(tmp_path / "out.csv").write_text("x")
|
||||
log = pipeline.run_pipeline(tmp_path, settings=object())
|
||||
assert [row[:2] for row in log] == [("99", "saltada"), ("98", "ok")] # 99's output is current; 98 has none to check
|
||||
assert (tmp_path / pipeline.LOG).read_text().splitlines()[0] == "etapa,estado,segundos"
|
||||
+28
-18
@@ -1,3 +1,4 @@
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -44,35 +45,44 @@ def mlflow_tracking(tmp_path, monkeypatch):
|
||||
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 that passes every promotion check,
|
||||
returns (domain, scenario, version)."""
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
"""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):
|
||||
version = registry.register(
|
||||
domain=domain, scenario=scenario, environment=Environment.PROD,
|
||||
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
|
||||
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
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",
|
||||
)
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
|
||||
return domain, scenario, version
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def tiny_onnx() -> bytes:
|
||||
import onnx.helper
|
||||
|
||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
|
||||
|
||||
|
||||
def armado(huella: str) -> int:
|
||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""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
|
||||
@@ -0,0 +1,63 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""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) == []
|
||||
@@ -0,0 +1,75 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,64 @@
|
||||
"""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
|
||||
@@ -0,0 +1,184 @@
|
||||
"""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))
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and
|
||||
what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`).
|
||||
|
||||
Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model;
|
||||
`governance_db`, `cacu_db` and `mlflow_tracking` (from `conftest.py`); `trained_run` and `armado` (from `conftest.py`)
|
||||
build runs missing a routine or the model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from conftest import armado, trained_run
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import PromotionBlocked, registry
|
||||
from models.io.registry import PromotionBlocked, registry
|
||||
|
||||
|
||||
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
|
||||
@@ -9,7 +21,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
|
||||
with pytest.raises(PromotionBlocked) as blocked:
|
||||
registry.promote("cacu", "tamizaje", version)
|
||||
failed = {check.code for check in blocked.value.checks if not check.passed}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"}
|
||||
|
||||
|
||||
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
|
||||
@@ -35,10 +47,44 @@ def test_reports_can_be_attached_after_training(production_ready):
|
||||
registry.attach_reports(domain, scenario, version, metrics="{}")
|
||||
|
||||
|
||||
def test_artifacts_are_logged_to_the_run(production_ready):
|
||||
def test_lineage_lists_every_stored_file_and_each_routine_record(production_ready):
|
||||
"""The lineage lists files inside folders (the saved model) and reads back each routine's record. Fails if
|
||||
`run_files` stops descending into folders or `routines` stops reading `rutinas/`."""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
lineage = registry.lineage(domain, scenario, version)
|
||||
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
|
||||
paths = {item["path"] for item in lineage["artifacts"]}
|
||||
assert "model/MLmodel" in paths and "rutinas/MUESTREO.json" in paths
|
||||
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routines, model, failing", [
|
||||
([ArtifactKind.MUESTREO], True, "ML-01a"),
|
||||
(None, False, "ML-01b"),
|
||||
])
|
||||
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
|
||||
failing):
|
||||
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
|
||||
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
|
||||
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
|
||||
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
|
||||
interpretability_report_uri="i")
|
||||
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
|
||||
assert [check.code for check in failed] == [failing]
|
||||
if failing == "ML-01a":
|
||||
assert "DATOS_FALTANTES" in failed[0].detail
|
||||
|
||||
|
||||
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
|
||||
"""ML-01b: a stored file comes back as itself; the model folder as a zip of its files. Fails if `run_file`
|
||||
stops zipping folders or starts accepting a path the run doesn't list."""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
name, data = registry.artifact(domain, scenario, version, "rutinas/MUESTREO.json")
|
||||
assert name == "MUESTREO.json" and json.loads(data)["n"] == 8
|
||||
name, data = registry.artifact(domain, scenario, version, "model")
|
||||
assert name == "model.zip" and "model/MLmodel" in zipfile.ZipFile(io.BytesIO(data)).namelist()
|
||||
for wrong in ("../mlflow.db", "", "rutinas/OTRO.json"):
|
||||
with pytest.raises(LookupError):
|
||||
registry.artifact(domain, scenario, version, wrong)
|
||||
|
||||
|
||||
def test_retire_and_lineage(production_ready):
|
||||
@@ -55,19 +101,6 @@ def test_retire_and_lineage(production_ready):
|
||||
registry.retire(domain, scenario, second)
|
||||
|
||||
|
||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||
from models.export import inspect_onnx_metadata
|
||||
|
||||
with pytest.raises(ValueError, match="ONNX"):
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "x.onnx"
|
||||
path.write_bytes(b"weights")
|
||||
inspect_onnx_metadata(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
|
||||
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
|
||||
with pytest.raises(ValueError):
|
||||
@@ -2,17 +2,10 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
||||
from models.registry import registry
|
||||
from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry
|
||||
|
||||
|
||||
class StubModel(ScreeningModel):
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data=None):
|
||||
raise NotImplementedError
|
||||
|
||||
class StubModel:
|
||||
def predict(self, data):
|
||||
return {"label": "positivo", "confianza": 0.73}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
|
||||
doesn't import the database layer, since the file is its only input.
|
||||
|
||||
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
|
||||
"""
|
||||
|
||||
import ast
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
import models
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
|
||||
from models.io.storage import read_cohort
|
||||
|
||||
|
||||
def _row(pac_id, fecha_indice, valor, fuente_id):
|
||||
return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice,
|
||||
"conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
|
||||
"codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": fuente_id}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
"""Member 10 has two results; member 20 has one."""
|
||||
rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"),
|
||||
_row(20, date(2025, 2, 1), "LIEBG", "c")]
|
||||
path = tmp_path / "1.parquet"
|
||||
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_a_cohort_file_reads_as_a_frame(cohort_file):
|
||||
"""Pins down: a build's file comes back with all its rows and columns. Fails if `read_cohort` drops rows or
|
||||
columns, or refuses a file with the right schema."""
|
||||
frame = read_cohort(cohort_file)
|
||||
|
||||
assert list(frame.columns) == SCHEMA.names
|
||||
assert frame["pac_id"].tolist() == [10, 10, 20]
|
||||
|
||||
|
||||
def test_a_file_with_other_columns_is_refused(tmp_path):
|
||||
"""Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the
|
||||
schema, which would let a model fail later on a missing column."""
|
||||
path = tmp_path / "other.parquet"
|
||||
pq.write_table(pa.table({"pac_id": [1]}), path)
|
||||
with pytest.raises(CohortFileError, match="cohort build's columns"):
|
||||
read_cohort(path)
|
||||
|
||||
|
||||
def test_model_folders_do_not_import_the_database_layer():
|
||||
"""Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or
|
||||
`core`. Fails when a model's folder imports either."""
|
||||
package = Path(models.__file__).parent
|
||||
offenders = []
|
||||
for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")):
|
||||
for node in ast.walk(ast.parse(path.read_text())):
|
||||
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \
|
||||
[node.module or ""] if isinstance(node, ast.ImportFrom) else []
|
||||
offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")]
|
||||
assert not offenders
|
||||
@@ -0,0 +1,28 @@
|
||||
"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name.
|
||||
|
||||
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from models.io.storage import resolve_repository
|
||||
|
||||
|
||||
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
|
||||
"""A repository found by name reads what was written through it, in batches and with filters. Fails if
|
||||
`resolve_repository` looks in another module or stops returning a working repository."""
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
|
||||
repository = resolve_repository("cacu", "paciente")
|
||||
for i in range(7):
|
||||
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
|
||||
assert [r.pac_id_hospital for r in repository.iter_all(batch_size=3)] == [f"M-{i}" for i in range(7)]
|
||||
assert list(repository.iter_all(pac_id_hospital="M-3"))[0].pac_sexo == "Femenino"
|
||||
|
||||
|
||||
def test_unknown_entity_is_a_clear_error():
|
||||
"""An unknown name raises `ValueError` naming it. Fails if the `AttributeError` is no longer translated."""
|
||||
with pytest.raises(ValueError, match="no nope_repository"):
|
||||
resolve_repository("tea", "nope")
|
||||
@@ -1,10 +1,11 @@
|
||||
import pytest
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
from models.io.registry import registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
from models.training import ReadOnlyRepository, TrainingRun
|
||||
from models.io.storage import ReadOnlyRepository
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
|
||||
def test_prod_run_requires_a_cohort_build():
|
||||
@@ -18,20 +19,20 @@ def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
|
||||
|
||||
|
||||
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
|
||||
checkpoint = tmp_path / "model.onnx"
|
||||
checkpoint.write_bytes(b"fake-onnx-bytes")
|
||||
notes = tmp_path / "notas.json"
|
||||
notes.write_text("{}")
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
||||
version = run.finish(metrics={"auc": 0.81})
|
||||
run.log_artifact(ArtifactKind.OTRO, notes, metadata={"origen": "prueba"})
|
||||
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
|
||||
|
||||
mv = registry.get("cacu", "tamizaje", version)
|
||||
assert mv.tags["environment"] == Environment.DEV.value
|
||||
metrics = registry.client.get_run(mv.run_id).data.metrics
|
||||
assert metrics["auc"] == 0.81
|
||||
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
|
||||
assert any(path.endswith("model.onnx") for path in artifacts)
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.OTRO.value)]
|
||||
assert any(path.endswith("notas.json") for path in artifacts)
|
||||
|
||||
|
||||
def test_read_only_repository_blocks_writes(cacu_db):
|
||||
@@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t
|
||||
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
||||
|
||||
|
||||
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||
def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||
from mlflow import MlflowClient
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert run.finish() == "1"
|
||||
assert registry.register_run(run.finish()) == "1"
|
||||
|
||||
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert second.finish() == "2"
|
||||
assert registry.register_run(second.finish()) == "2"
|
||||
|
||||
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
def unreachable(name):
|
||||
def unreachable(self, name):
|
||||
raise MlflowException("servidor no disponible")
|
||||
|
||||
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
|
||||
monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable)
|
||||
with pytest.raises(MlflowException, match="no disponible"):
|
||||
third.finish()
|
||||
registry.register_run(third.finish())
|
||||
|
||||
|
||||
def test_unknown_domain_is_rejected():
|
||||
with pytest.raises(ValueError, match="dominio desconocido"):
|
||||
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
|
||||
def test_finishing_a_run_registers_nothing(mlflow_tracking):
|
||||
"""Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run
|
||||
can be kept without becoming a model. Fails if `finish` starts registering again."""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5})
|
||||
|
||||
assert registry.client.get_run(run.run_id).info.status == "FINISHED"
|
||||
assert registry.client.search_model_versions("name='cacu-tamizaje'") == []
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user