Compare commits

..

3 Commits

47 changed files with 2284 additions and 521 deletions
+3
View File
@@ -12,3 +12,6 @@ uv.lock
mlflow.db
mlruns/
mlartifacts/
# Jupyter
.ipynb_checkpoints/
+12 -8
View File
@@ -11,9 +11,9 @@ WebApi.
|---|---|
| `__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/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`) and their hashes (`file_sha256`, `table_sha256`, `cohort_reference`), dbt's manifest (`read_queries`), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: `KitBuild`, a kit build read now from the domain's database (nothing written), or `CohortFile`, an exported file, behind one contract (`frame`, `lineage`, `reference`). |
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed `models` package, `code_version`), a model's hash (`model_sha`), and `matches`, the one rule for "already done". |
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). 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). `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. |
| `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. |
@@ -21,16 +21,20 @@ WebApi.
| `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). |
| `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 `cohort_repository`: one preliminary risk per member and 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`. |
| `reports/` (`rendering.py`, `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 `<scenario>/notebooks/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it to one HTML page, 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. Renderers are classes in `rendering.py` (`RENDERERS`, `register_renderer`): `quarto` (`QUARTO_BIN`, and a Python with Jupyter in `QUARTO_PYTHON`) 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). |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` (which refuses a build with no rows or with a member, a date or an event missing: `MODEL_COHORT`, pandera) and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
| `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. |
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit, its metrics and the routine records every classifier shares (`sampling`, `analytic_method`, `class_balance`, `output_confidence`), gathered by `routines` with the scenario's `missing_data` (ML-01a). |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, `fitted_model`: a scikit-learn `Pipeline` that takes the long frame, and its `missing_data` routine record). Training records its five routines. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, 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/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull incidence, `likelihood.py`), fitted to each member's code and interval; the clinical settings (windows, known-negative results) in `model.toml`. Its dataflow records its own five routines. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+70 -44
View File
@@ -14,27 +14,24 @@ def _show_help(parser: argparse.ArgumentParser) -> int:
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
def _scenario(args: argparse.Namespace):
"""The scenario's `model.toml`; `None` and a message on stderr if there's no such model."""
from models.dags.training import Scenario
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 Scenario.load(args.domain, args.scenario)
except LookupError as error:
print(error, file=sys.stderr)
return None
def _cohort_file(args: argparse.Namespace, model):
def _cohort_file(args: argparse.Namespace, scenario):
"""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"]
url = scenario.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"))
@@ -52,28 +49,51 @@ def _cohort_file(args: argparse.Namespace, model):
return None
def _cohort_source(args: argparse.Namespace, scenario):
"""Where the build's rows come from: a kit build from the database (`--read db`, the default), or an exported
file (`--read file`, and always for dbt's builds, which only exist as files). `None` and a message if missing."""
from models.io.storage import CohortFile, KitBuild
if args.source == "kit" and getattr(args, "read", "file") == "db":
from importlib import import_module
cohorts = import_module(f"persistance.{args.domain}").cohort_repository
build_id = args.armado if args.armado is not None else cohorts.latest_build(scenario.cohort)
if build_id is None:
print(f"no kit builds of {scenario.cohort}", file=sys.stderr)
return None
return KitBuild(args.domain, build_id, cohorts=cohorts)
path = _cohort_file(args, scenario)
return CohortFile(path) if path else None
def _describe(source) -> str:
return str(getattr(source, "path", None) or f"kit build {source.build_id}")
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Trains the model on the build's file, always as a new version."""
"""Trains the model on the build, 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")):
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
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}")
from models.dags.training import train
print(f"{args.domain}/{args.scenario} version {train(scenario, source, args.environment.upper())}, "
f"from {_describe(source)}")
return 0
def _estimate_step(args: argparse.Namespace, path) -> int:
estimator = _model_module(args, "estimate")
if not estimator:
return 1
def _estimate_step(args: argparse.Namespace, scenario, source) -> int:
from models.dags.estimation import estimate
try:
resolved, written = estimator.estimate(path, args.output, args.version)
resolved, written = estimate(scenario, source, 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}")
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {_describe(source)}, "
f"to {args.output}")
return 0
@@ -98,13 +118,12 @@ 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
from models.reports.eda import report_eda
from models.reports.rendering import RenderError
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
if not (scenario := _scenario(args)) or not (path := _cohort_file(args, scenario)):
return 1
notebook = Path(args.notebook) if args.notebook else (
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
notebook = Path(args.notebook) if args.notebook else scenario.folder / "notebooks" / "01_eda.ipynb"
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
@@ -133,10 +152,10 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
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)):
"""Scores the build with a registered version and writes the output file."""
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
return 1
return _estimate_step(args, path)
return _estimate_step(args, scenario, source)
def _promote_step(args: argparse.Namespace, version: str) -> int:
@@ -171,11 +190,12 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
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")):
if not (scenario := _scenario(args)):
return 1
if args.export:
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
args.read = "file"
cohort = scenario.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":
@@ -185,25 +205,25 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
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)):
if not (source := _cohort_source(args, scenario)):
return 1
version = args.version
if args.train or (args.promote and not version):
if not (trainer := _model_module(args, "train")):
return 1
from models.dags.training import find_trained, train
environment = args.environment.upper()
version = trainer.find_trained(path, environment)
version = find_trained(scenario, source, environment)
if args.train and version:
print(f"already trained: version {version}, from {path}")
print(f"already trained: version {version}, from {_describe(source)}")
elif args.train:
version = trainer.train(path, environment)
print(f"trained: version {version}, from {path}")
version = train(scenario, source, environment)
print(f"trained: version {version}, from {_describe(source)}")
elif not version:
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
print(f"no {environment} version trained on {_describe(source)}: 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)):
if args.estimate and (code := _estimate_step(args, scenario, source)):
return code
return _store_step(args, args.output) if args.store else 0
@@ -365,22 +385,26 @@ def build_parser() -> argparse.ArgumentParser:
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 = commands.add_parser("train", help="train a model on a cohort build 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("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
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 = commands.add_parser("estimate", help="score a cohort build 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("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
@@ -390,7 +414,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--notebook", help="the notebook; the scenario's <scenario>/notebooks/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'")
@@ -414,6 +438,8 @@ def build_parser() -> argparse.ArgumentParser:
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("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
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")
+43
View File
@@ -0,0 +1,43 @@
"""Validators a dataflow puts on its nodes. Nothing here does I/O or imports MLflow.
- `@checked_frame(schema)`: validates the node's frame with a pandera schema and fails the run if it doesn't hold. The
failure names the columns, the checks and how many rows failed, never the values: pandera's own report (and
`@check_output(schema=...)`) quotes them.
"""
from typing import Any
import pandas as pd
import pandera.pandas as pandera
from hamilton.data_quality.base import DataValidator, ValidationResult
from hamilton.function_modifiers import check_output_custom
from models.io.contracts import failed_checks
class FrameCheck(DataValidator):
"""A pandera schema as a Hamilton validator whose message carries no data values."""
def __init__(self, schema: pandera.DataFrameSchema, importance: str = "fail"):
super().__init__(importance)
self.schema = schema
def applies_to(self, datatype: type) -> bool:
return issubclass(datatype, pd.DataFrame)
def description(self) -> str:
return f"rows satisfy {self.schema.name or 'the schema'}"
@classmethod
def name(cls) -> str:
return "frame_check"
def validate(self, dataset: Any) -> ValidationResult:
failed = failed_checks(self.schema, dataset)
if failed:
return ValidationResult(False, f"{self.description()} doesn't hold: {failed}")
return ValidationResult(True, f"{self.description()}: holds")
def checked_frame(schema: pandera.DataFrameSchema):
return check_output_custom(FrameCheck(schema))
-41
View File
@@ -1,41 +0,0 @@
"""Scores a build's file with a registered version and writes the probabilities to a Parquet file."""
from pathlib import Path
import mlflow.pyfunc
import pyarrow as pa
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import read_cohort, read_metadata, write_once
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
"""Whether the output file already holds this version's scores of this build's file."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]:
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows
come from, and the outcome and horizon they estimate (`cin2_12m`, 1.0 years); `modelo_sha` is copied when the
version has it, and isn't checked."""
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
output_path = Path(output_path)
resolved = registry.resolve(domain, scenario, version)
cohort = cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
window = SETTINGS["outcome_window_months"]
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
**cohort}
if resolved.modelo_sha:
provenance["modelo_sha"] = resolved.modelo_sha
table = pa.Table.from_pandas(risks, preserve_index=False)
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
return resolved, True
+52 -160
View File
@@ -1,215 +1,107 @@
"""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
`y` is 1 when a biopsy graded in `event_grades` falls within the window (`horizons_years`, one) 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.
The split, the classifier, the fit, the metrics and the routine records (ML-01a) are `models.steps.model_fitting`'s,
listed with this module in `model.toml`; `missing_data` and `members_left_out` are this scenario's part of them. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
scikit-learn `Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through
loaders, and registering is the driver's saver (`models.dags.training`).
"""
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
import pandera.pandas as pandera
from sklearn.base import BaseEstimator, TransformerMixin
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
from models.annotations import checked_frame
from models.io.contracts import DAYS_PER_YEAR
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
PREDICTORS = ("bethesda", "vph", "vph_16_18")
MISSING = "(none)"
DAYS_PER_MONTH = 30.44
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"y": pandera.Column(int, pandera.Check.isin([0, 1]))},
name="labelled members")
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:
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(lineage["datos_as_of"])
return date.fromisoformat(cohort_lineage["datos_as_of"])
def predictors(cohort: pd.DataFrame) -> pd.DataFrame:
def index_sample_results(cohort: pd.DataFrame, predictor_columns: list[str]) -> 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"]]
results = results[results["fuente_id"] == results["sample"]].copy()
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(
wide = results[results["tipo"].isin(predictor_columns)].pivot_table(
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
wide = wide.reindex(columns=list(PREDICTORS))
wide = wide.reindex(columns=list(predictor_columns)).astype(object)
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
{name: MISSING for name in PREDICTORS})
{name: MISSING for name in predictor_columns})
def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame:
def windowed_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, horizons_years: list[float],
event_grades: list[str]) -> 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
(window_years,) = horizons_years
window = window_years * DAYS_PER_YEAR
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)
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(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
follow_up = (pd.Timestamp(cohort_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:
@checked_frame(LABELLED_MEMBERS)
def labelled_members(index_sample_results: pd.DataFrame, windowed_outcomes: pd.DataFrame) -> pd.DataFrame:
"""The members whose outcome is known, with their predictors and `y`."""
labelled = predictors.merge(outcome, on="pac_id")
labelled = index_sample_results.merge(windowed_outcomes, 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 members_left_out(windowed_outcomes: pd.DataFrame) -> int:
"""The members scored but not trained on: their outcome isn't known yet."""
return int((~windowed_outcomes["known"]).sum())
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:
def missing_data(index_sample_results: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
predictor_columns: list[str]) -> 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 {name: int((frame[name] == MISSING).sum()) for name in predictor_columns}
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)}
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
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])))}
class IndexSampleResults(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member, in `pac_id` order, with the index sample's results. Learns
nothing."""
def __init__(self, predictor_columns: list[str]):
self.predictor_columns = predictor_columns
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_sample_results(X, self.predictor_columns)[list(self.predictor_columns)]
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
def fitted_model(fitted_pipeline: Pipeline, predictor_columns: list[str]) -> Pipeline:
"""What's registered: the fitted pipeline behind `IndexSampleResults`."""
return Pipeline([("index_sample", IndexSampleResults(predictor_columns)), ("classifier", fitted_pipeline)])
+16 -6
View File
@@ -1,13 +1,23 @@
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"]
outcome = "cin2_12m"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting"]
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."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
[config]
classifier = "logistic"
train_fraction = 0.7
predictor_columns = ["bethesda", "vph", "vph_16_18"]
# Provisional, to be decided with the domain expert: the window, in years, in which a CIN2+ biopsy counts as the
# outcome; the model's one horizon. On the DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 2-year
# window leaves no member with a complete window; 1 year leaves 5,231 known members, 162 with the event.
horizons_years = [1.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
@@ -17,7 +17,7 @@
"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))",
"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/cin2_logistic/notebooks → ../../../../../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"
},
{
-27
View File
@@ -1,27 +0,0 @@
"""The model's Hamilton driver, and what makes repeating a training a no-op."""
from hamilton import driver
from models.cacu.cin2_logistic import model
from models.io.lineage import matches
from models.io.registry import registered_name, registry
def train(cohort_path: str, environment: str = "DEV") -> str:
"""Trains on a build's file and returns the registered version."""
dr = driver.Builder().with_modules(model).build()
inputs = {"cohort_path": str(cohort_path), "environment": environment}
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
def find_trained(cohort_path: str, environment: str = "DEV") -> str | None:
"""The newest version not retired from the same file, code and environment."""
name = registered_name(model.SETTINGS["domain"], model.SETTINGS["scenario"])
expected = {"cohort_sha256": model.cohort_sha256(str(cohort_path)), "code_sha256": model.code_sha256()}
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
for mv in versions:
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
continue
if matches(registry.client.get_run(mv.run_id).data.params, expected):
return str(mv.version)
return None
View File
+135
View File
@@ -0,0 +1,135 @@
"""Prevalence–incidence mixture (PIMixture) likelihood, written plainly: the Weibull family and maximum likelihood.
Each row has a code `c` and an interval `(l, r]` in years since the index visit:
- `c = 1`: prevalent at the index visit. Contributes `pi`.
- `c = 0`: not prevalent; the disease, if any, appeared in `(l, r]` (`r = inf` means censored at `l`).
Contributes `(1 - pi) * (S(l) - S(r))`.
- `c = -999`: unknown at the index visit (no colposcopy). Contributes `pi + (1 - pi) * (S(l) - S(r))`, usually
with `l = 0`.
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-(t / scale) ** shape * exp(Z @ beta))` the Weibull
survival of the incidence (proportional hazards in `Z`).
"""
import numpy as np
from scipy.optimize import minimize
from scipy.special import expit
UNKNOWN = -999
TINY = 1e-12
BOUNDARY = 15.0 # |parameter| beyond this is taken as "at the boundary" (expit(−15) = 3e-7)
def prevalence(theta, X):
return expit(X @ theta)
def weibull_survival(t, log_scale, log_shape, beta, Z):
"""S(t). S(0) = 1 and S(inf) = 0."""
t = np.asarray(t, dtype=float)
scale, shape = np.exp(log_scale), np.exp(log_shape)
hazard_ratio = np.exp(Z @ beta)
with np.errstate(over="ignore", invalid="ignore"):
cumulative = (t / scale) ** shape * hazard_ratio
survival = np.exp(-cumulative)
survival = np.where(t <= 0, 1.0, survival)
survival = np.where(np.isinf(t), 0.0, survival)
return survival
def split_params(params, n_x, n_z):
"""params = [theta (n_x), beta (n_z), log_scale, log_shape]."""
theta = params[:n_x]
beta = params[n_x:n_x + n_z]
log_scale = params[n_x + n_z]
log_shape = params[n_x + n_z + 1]
return theta, beta, log_scale, log_shape
def neg_loglik(params, c, l, r, X, Z):
theta, beta, log_scale, log_shape = split_params(params, X.shape[1], Z.shape[1])
pi = prevalence(theta, X)
interval = weibull_survival(l, log_scale, log_shape, beta, Z) - weibull_survival(r, log_scale, log_shape, beta, Z)
interval = np.maximum(interval, TINY)
total = 0.0
prevalent = c == 1
total += np.sum(np.log(pi[prevalent] + TINY))
not_prevalent = c == 0
total += np.sum(np.log(1 - pi[not_prevalent] + TINY))
total += np.sum(np.log(interval[not_prevalent]))
unknown = c == UNKNOWN
total += np.sum(np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY))
return -total
def numerical_hessian(f, x, step=1e-4):
"""Central finite differences, one pair of parameters at a time. Plain and slow (4 p² calls), fine for p < 30."""
x = np.asarray(x, dtype=float)
p = len(x)
hessian = np.zeros((p, p))
for i in range(p):
for j in range(i, p):
ei = np.zeros(p)
ej = np.zeros(p)
ei[i] = step
ej[j] = step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (4 * step * step)
hessian[i, j] = value
hessian[j, i] = value
return hessian
def fit(c, l, r, X, Z):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
n_x, n_z = X.shape[1], Z.shape[1]
start = np.zeros(n_x + n_z + 2)
finite = r[np.isfinite(r) & (r > 0)]
start[n_x + n_z] = np.log(np.median(finite)) if len(finite) else 0.0
result = minimize(neg_loglik, start, args=(c, l, r, X, Z), method="BFGS")
theta, beta, log_scale, log_shape = split_params(result.x, n_x, n_z)
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
# likelihood, a zero row in the Hessian, and makes the whole matrix singular. It gets no standard error (NaN) and
# the others are computed without it.
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), result.x)
free = np.abs(result.x) < BOUNDARY
standard_errors = np.full(len(result.x), np.nan)
try:
covariance = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
return {
"theta": theta,
"beta": beta,
"log_scale": log_scale,
"log_shape": log_shape,
"params": result.x,
"se": standard_errors,
"neg_loglik": result.fun,
# BFGS with a numerical gradient often stops with "precision loss" at the optimum; what matters is that
# the gradient is ~0 there.
"converged": bool(np.max(np.abs(result.jac)) < 1e-3),
"message": result.message,
}
def cumulative_risk(fitted, X, Z, years):
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence."""
pi = prevalence(fitted["theta"], X)
columns = []
for t in years:
survival = weibull_survival(np.full(len(X), float(t)), fitted["log_scale"], fitted["log_shape"],
fitted["beta"], Z)
columns.append(pi + (1 - pi) * (1 - survival))
return np.column_stack(columns)
+229
View File
@@ -0,0 +1,229 @@
"""CaCu CIN2+ prevalence–incidence prototype: the cumulative risk of CIN2+ at the index visit and at later horizons.
Each member becomes a code `c` and an interval `(l, r]` in years (`likelihood`'s convention), from the index sample's
results and the biopsies after it:
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`;
- otherwise, a known negative baseline (`known_negative` results, or a biopsy in the window below CIN2+): `c = 0`, with
`(0, t_event]` if a later biopsy is CIN2+ and `(follow-up, inf)` if none is;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]` or `(0, inf)`.
The interval's left end is 0 for a later event: the last negative visit before it isn't looked for.
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
π logistic in every feature and the incidence S(t) Weibull with proportional hazards in `incidence_features`.
The routine records (ML-01a) are nodes too: `sampling`, `missing_data`, `analytic_method`, `class_balance` and
`output_confidence`, gathered by `routines`. `fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort and its lineage through loaders, and registering is the
driver's saver (`models.dags.training`).
"""
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cacu.cin2_pim import likelihood
from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
FEATURES = ["abnormal_cytology", "hpv_positive"]
INTERVAL_CODED = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"c": pandera.Column(int, pandera.Check.isin([1, 0, likelihood.UNKNOWN])),
"l": pandera.Column(float, pandera.Check.ge(0)),
"r": pandera.Column(float, pandera.Check.ge(0))},
checks=pandera.Check(lambda frame: frame["r"] >= frame["l"], error="r >= l"),
name="interval-coded members")
def _days(cohort: pd.DataFrame) -> pd.Series:
return (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first Bethesda and HPV results within `index_sample_days` of the
index date, and the features taken from them."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "vph"])]
wide = near.sort_values("fecha").pivot_table(index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
members = cohort.groupby("pac_id", as_index=False)["fecha_indice"].first()
members = members.merge(wide.reindex(columns=["bethesda", "vph"]), left_on="pac_id", right_index=True, how="left")
members["abnormal_cytology"] = (members["bethesda"].notna() & (members["bethesda"] != "NORMAL")).astype(float)
members["hpv_positive"] = (members["vph"] == "POSITIVO").astype(float)
return members
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
@checked_frame(INTERVAL_CODED)
def interval_coded_members(cohort: pd.DataFrame, cohort_cutoff: date, event_grades: list[str],
prevalent_window_months: int, index_sample_days: int, known_negative: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
biopsies = cohort[(cohort["tipo"] == "biopsia") & (days >= 0)].assign(days=days)
window = prevalent_window_months * DAYS_PER_YEAR / 12
first_event = biopsies[biopsies["valor_codigo"].isin(event_grades)].groupby("pac_id")["days"].min()
negative_biopsy = biopsies[~biopsies["valor_codigo"].isin(event_grades) & (biopsies["days"] <= window)]
coded = index_results(cohort, index_sample_days)
results_negative = np.logical_and.reduce([coded[name] == value for name, value in known_negative.items()])
event_days = coded["pac_id"].map(first_event)
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(coded["fecha_indice"])).dt.days / DAYS_PER_YEAR
prevalent = event_days <= window
baseline_negative = results_negative | coded["pac_id"].isin(negative_biopsy["pac_id"])
later_event = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(baseline_negative, 0, likelihood.UNKNOWN))
coded["l"] = np.where(~prevalent & baseline_negative & ~later_event, follow_up, 0.0)
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
return coded
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(interval_coded_members, train_fraction, target_column="c")
class PrevalenceIncidenceMixture(BaseEstimator):
"""Logistic prevalence and Weibull incidence fitted by maximum likelihood (`likelihood.fit`)."""
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",)):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
def _design(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), X.to_numpy(dtype=float)])
return prevalence, X[list(self.incidence_features)].to_numpy(dtype=float)
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
prevalence, incidence = self._design(X)
found = likelihood.fit(y["c"], y["l"], y["r"], prevalence, incidence)
self.theta_, self.beta_ = found["theta"], found["beta"]
self.log_scale_, self.log_shape_ = float(found["log_scale"]), float(found["log_shape"])
self.standard_errors_, self.neg_loglik_, self.converged_ = found["se"], found["neg_loglik"], found["converged"]
return self
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
prevalence, incidence = self._design(X)
fitted = {"theta": self.theta_, "beta": self.beta_, "log_scale": self.log_scale_, "log_shape": self.log_shape_}
return likelihood.cumulative_risk(fitted, prevalence, incidence, self.horizons_years)
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float]) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years).fit(train_set[FEATURES], train_set[["c", "l", "r"]])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[FEATURES])
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
"""1 if CIN2+ is known by `horizon`, 0 if known free at it, NaN if not known."""
case = (members["c"] == 1) | ((members["c"] != 1) & (members["r"] <= horizon))
free = (members["c"] == 0) & (members["l"] >= horizon) & ~case
return np.where(case, 1.0, np.where(free, 0.0, np.nan))
def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame, test_set: pd.DataFrame,
test_cumulative_risks: np.ndarray, horizons_years: list[float]) -> dict:
"""Aggregates only: per horizon, among test members whose status at it is known, how many, the observed and
expected rates, the Brier score and, with both classes, the AUC."""
found = {"n_train": len(train_set), "n_test": len(test_set), "neg_loglik": float(fitted_mixture.neg_loglik_),
"converged": float(fitted_mixture.converged_)}
for column, horizon in enumerate(horizons_years):
status = _status_at(test_set, horizon)
known = ~np.isnan(status)
y, p = status[known], test_cumulative_risks[known, column]
tag = f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
if known.any():
found[f"observed_{tag}"] = float(y.mean())
found[f"expected_{tag}"] = float(p.mean())
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
if len(np.unique(y)) == 2:
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
return found
def sampling(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: every member is used; the split is `models.steps.model_fitting`'s."""
return model_fitting.sampling(interval_coded_members, train_set, test_set, train_fraction)
def missing_data(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many lacked each index result or a known baseline, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {"bethesda": int(frame["bethesda"].isna().sum()), "vph": int(frame["vph"].isna().sum()),
"unknown_baseline": int((frame["c"] == likelihood.UNKNOWN).sum())}
return {"method": "sin Bethesda no cuenta como citología anormal y sin VPH no cuenta como positivo; una línea "
"basal desconocida entra a la verosimilitud como mezcla de prevalente y no prevalente; nadie se "
"excluye",
"members": missing(interval_coded_members), "train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_mixture: PrevalenceIncidenceMixture) -> dict:
"""METODO_ANALITICO: the fitted mixture and its parameters."""
return {"method": "mezcla de prevalencia (logística) e incidencia (Weibull de riesgos proporcionales) por máxima "
"verosimilitud con censura por intervalo",
"estimator": type(fitted_mixture).__name__, "settings": fitted_mixture.get_params(),
"prevalence_coefficients": dict(zip(["intercept", *FEATURES], map(float, fitted_mixture.theta_))),
"incidence_coefficients": dict(zip(fitted_mixture.incidence_features, map(float, fitted_mixture.beta_))),
"log_scale": fitted_mixture.log_scale_, "log_shape": fitted_mixture.log_shape_,
"neg_loglik": float(fitted_mixture.neg_loglik_), "converged": bool(fitted_mixture.converged_)}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: how many members have each baseline code (1 prevalent, 0 known negative, -999 unknown)."""
def counts(frame: pd.DataFrame) -> dict:
return {str(code): int(n) for code, n in frame["c"].value_counts().sort_index().items()}
return {"method": "ninguno: los códigos se usan en su proporción observada", "train": counts(train_set),
"test": counts(test_set)}
def output_confidence(metrics: dict, horizons_years: list[float]) -> dict:
"""CONFIANZA_SALIDA: per horizon, among the test members whose status at it is known, the expected risk against
the observed rate."""
names = {"n_known": "n", "expected": "mean_probability", "observed": "observed_rate", "brier": "brier"}
return {"method": "calibración en la prueba por horizonte: riesgo acumulado medio contra frecuencia observada, "
"entre quienes tienen estado conocido en ese horizonte",
"horizons": [{"years": horizon, **{name: metrics[f"{key}_{horizon:g}y"] for key, name in names.items()
if f"{key}_{horizon:g}y" in metrics}} for horizon in horizons_years]}
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 model_fitting.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
def __init__(self, index_sample_days: int = 30):
self.index_sample_days = index_sample_days
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days)[FEATURES]
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days)), ("mixture", fitted_mixture)])
+24
View File
@@ -0,0 +1,24 @@
domain = "cacu"
scenario = "cin2_pim"
cohort = "cacu/cohorte_vigilancia"
outcome = "cin2"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_pim.model"]
description = """
Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \
modelo de mezcla prevalencia (logística) e incidencia (Weibull) a partir de la citología y el VPH índice. Sin \
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
prevalent_window_months = 6
# The index sample's results: the first ones within these days of the index date.
index_sample_days = 30
# The results that make a baseline known negative without a biopsy.
known_negative = { bethesda = "NORMAL", vph = "NEGATIVO" }
View File
+64
View File
@@ -0,0 +1,64 @@
"""Estimating with any scenario's registered version: score a source's build and write the estimate, once.
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order.
A build with no rows, or with nulls where a member, a date or an event goes, is refused first (`storage.model_frame`).
Its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
classifier that's the positive class at its one horizon. The output has one row per member and horizon
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
"""
import json
from pathlib import Path
import mlflow.pyfunc
import numpy as np
import pandas as pd
import pyarrow as pa
from models.dags.training import Scenario
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, model_frame, 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."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
if probabilities.ndim != 2 or len(probabilities) != len(members):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
risks = probabilities[:, -len(horizons):]
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(members["fecha_indice"].to_numpy(), len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": risks.ravel().astype(float)})
def estimate(scenario: Scenario, source: CohortSource, 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.
`modelo_sha` is copied when the version has it, and isn't checked."""
output_path = Path(output_path)
resolved = registry.resolve(scenario.domain, scenario.scenario, version)
cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = model_frame(source)
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
risks = estimate_frame(cohort_frame, probabilities, horizons)
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
"desenlace": scenario.outcome, **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
+131
View File
@@ -0,0 +1,131 @@
"""Training any scenario: one driver built from the modules its `model.toml` lists, its config, a cohort source and
the adapters.
A scenario is a folder with `model.toml` and its dataflow. `model.toml` names it (`domain`, `scenario`, `cohort`,
`outcome`, `description`), lists the `modules` whose functions are the graph's nodes, and holds `[config]`, the values
the dataflow receives through `with_config`. The dataflow goes from `cohort` and `cohort_lineage` to `fitted_model` (a
scikit-learn estimator that takes the long frame), `metrics` and, for a version that can be promoted, `routines` (what each
routine around training did, by kind, ML-01a), with no I/O.
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold
members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
"""
import hashlib
import json
import logging
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
from types import ModuleType
from hamilton import base, driver
from hamilton.io.materialization import from_, to
from models.io import adapters # noqa: F401 (registers the loaders and the saver)
from models.io.lineage import code_version, matches
from models.io.registry import registered_name, registry
from models.io.storage import CohortSource
from models.io.tracking import TrainingRun
REGISTERED_MODEL = "registered_model"
# A scenario without this node registers a version that ML-01a keeps out of production.
ROUTINES = "routines"
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
@dataclass(frozen=True)
class Scenario:
domain: str
scenario: str
cohort: str
outcome: str
description: str
modules: tuple[ModuleType, ...]
config: dict
folder: Path
requirements: tuple[str, ...] = ()
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
path = Path(path)
found = tomllib.loads(path.read_text())
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
"""`models/<domain>/<scenario>/model.toml`; `LookupError` if there's no such scenario."""
try:
package = import_module(f"models.{domain}.{scenario}")
except ModuleNotFoundError as error:
raise LookupError(f"no such model: {domain}/{scenario}") from error
return cls.from_toml(Path(package.__file__).parent / "model.toml")
def config_sha256(self) -> str:
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
"""The graph of these modules. Without materializers it takes `cohort` and `cohort_lineage` as inputs."""
builder = driver.Builder().with_modules(*modules).with_config(config)
if materializers:
builder = builder.with_materializers(*materializers)
return builder.build()
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
"""The graph's inputs that some node requires, and those every node taking them has a default for."""
variables = dr.list_available_variables()
inputs = {v.name for v in variables if v.is_external_input}
required = set().union(*(v.required_dependencies for v in variables)) & inputs
return required, inputs - required
def expected_params(scenario: Scenario, source: CohortSource) -> dict[str, str]:
return {**source.reference(), **code_version(), "config_sha256": scenario.config_sha256()}
def find_trained(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str | None:
"""The newest version not retired from the same source reference, `models` version, config and environment."""
name = registered_name(scenario.domain, scenario.scenario)
expected = expected_params(scenario, source)
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
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows."""
logging.getLogger(HAMILTON_NODE_ERRORS).setLevel(logging.CRITICAL)
run = TrainingRun(domain=scenario.domain, scenario=scenario.scenario, environment=environment,
cohorte_armado_id=source.armado_id, cohort=source.reference())
try:
plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain)
loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("cohort_lineage", from_.cohort_source_lineage))
if target in required]
produced = ["fitted_model", "metrics", *(v.name for v in plain.list_available_variables() if v.name == ROUTINES)]
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=produced,
combine=base.DictResult(), run=run, description=scenario.description,
hyperparameters={**expected_params(scenario, source), **scenario.config},
requirements=list(scenario.requirements))
dr = dataflow(*scenario.modules, config=scenario.config, materializers=(*loaders, saver))
result = dr.execute([REGISTERED_MODEL])
except BaseException:
run.client.set_terminated(run.run_id, status="FAILED")
raise
return result[REGISTERED_MODEL]["version"]
+135
View File
@@ -0,0 +1,135 @@
"""Hamilton's boundary with storage and MLflow: the loaders and the saver a model's driver attaches.
A model's dataflow has no I/O: it receives `cohort` and `cohort_lineage` and ends at `fitted_model` and `metrics`. The
driver (`models.dags.training`) attaches these adapters with `with_materializers`, so they're nodes of the graph before
anything runs and nothing in the model imports MLflow:
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage",
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
The frame is checked against `MODEL_COHORT` whatever its source: a build with no rows, or with a member, a date or
an event missing, stops the run before any node reads it.
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics"], ...)`: logs the fitted model in
the open `TrainingRun` (`tracking`), records the metrics and the config, closes the run, and registers and describes
the version (`registry`). Its value is the version's metadata.
The saver pickles the packages of the model's own classes by value, so the registered version loads with
scikit-learn and the model's libraries, without this repository. The saver and the metrics being numbers are what keep members' rows out
of MLflow. Names are registered once, here, since Hamilton's adapter registry is global and keyed by name.
"""
import dataclasses
import sys
from collections.abc import Collection
from typing import Any
import cloudpickle
import pandas as pd
from hamilton import registry as hamilton_registry
from hamilton.io.data_adapters import DataLoader, DataSaver
from models.io.registry import registered_name, registry
from models.io.storage import model_frame
from models.io.tracking import TrainingRun, pinned
@dataclasses.dataclass
class CohortSourceLoader(DataLoader):
"""A build's long frame, from whatever source reads it, if a model may read it (`storage.model_frame`)."""
source: Any
@classmethod
def applicable_types(cls) -> Collection[type]:
return [pd.DataFrame]
@classmethod
def name(cls) -> str:
return "cohort_source"
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
frame = model_frame(self.source)
return frame, {"source": type(self.source).__name__, "rows": len(frame)}
@dataclasses.dataclass
class CohortSourceLineageLoader(DataLoader):
"""A build's lineage, from whatever source reads it."""
source: Any
@classmethod
def applicable_types(cls) -> Collection[type]:
return [dict]
@classmethod
def name(cls) -> str:
return "cohort_source_lineage"
def load_data(self, type_: type) -> tuple[dict, dict[str, Any]]:
return self.source.lineage(), {"source": type(self.source).__name__}
def _own_packages(model) -> list:
"""The packages of the classes in a fitted model (the model, or each step of a `Pipeline`) whose code isn't an
installed library: `models.cacu.cin2_pim` for a class of `models.cacu.cin2_pim.model`. Those are pickled with the
model; scikit-learn and the rest are expected where it's loaded."""
found = {}
for step in [model, *(step for _, step in getattr(model, "steps", []))]:
module = sys.modules[type(step).__module__]
if module.__name__ == "__main__" or "site-packages" in (getattr(module, "__file__", None) or "site-packages"):
continue
package = module.__name__.rpartition(".")[0] or module.__name__
found[package] = sys.modules[package]
return list(found.values())
def _numbers(metrics: dict) -> dict[str, float]:
found = {}
for key, value in metrics.items():
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"metrics.{key} is a {type(value).__name__}; only numbers are logged")
found[key] = float(value)
return found
@dataclasses.dataclass
class RegisteredModelSaver(DataSaver):
"""Records each of `routines` (ML-01a) in `run`, logs `fitted_model` with `requirements` (pinned to the installed
versions), records `metrics` (numbers only) and `hyperparameters`, closes the run, registers the version and gives
it `description`."""
run: TrainingRun
description: str = ""
hyperparameters: dict = dataclasses.field(default_factory=dict)
requirements: list = dataclasses.field(default_factory=list)
@classmethod
def applicable_types(cls) -> Collection[type]:
return [dict]
@classmethod
def name(cls) -> str:
return "registered_model"
def save_data(self, data: dict) -> dict[str, Any]:
model, metrics = data["fitted_model"], _numbers(data["metrics"])
for kind, record in data.get("routines", {}).items():
self.run.log_routine(kind, record)
packages = _own_packages(model)
for package in packages:
cloudpickle.register_pickle_by_value(package)
try:
self.run.log_model(model, requirements=pinned(self.requirements) if self.requirements else None)
finally:
for package in packages:
cloudpickle.unregister_pickle_by_value(package)
self.run.finish(metrics=metrics, hyperparameters=self.hyperparameters)
version = registry.register_run(self.run)
if self.description:
registry.set_description(self.run.domain, self.run.scenario, version, self.description)
return {"registered_model": registered_name(self.run.domain, self.run.scenario), "version": version,
"mlflow_run_id": self.run.run_id, "modelo_sha": self.run.modelo_sha}
for _adapter in (CohortSourceLoader, CohortSourceLineageLoader, RegisteredModelSaver):
hamilton_registry.register_adapter(_adapter)
+33 -6
View File
@@ -3,8 +3,10 @@
- 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`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member and horizon (`horizonte_anios`, years from the
index date; 0 is the prevalence).
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`), and what a model may read
(`MODEL_COHORT`): a build's rows, and at least one.
- 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
@@ -26,7 +28,8 @@ COHORT_SCHEMA = pa.schema([
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
])
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "horizonte_anios", "probabilidad")
DAYS_PER_YEAR = 365.25 # horizons and intervals are in years from the index date
# 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.
@@ -42,11 +45,18 @@ COHORT_FRAME = pandera.DataFrameSchema(
error="a member has more than one index date"),
name="cohort build")
# A build with no rows is a valid file, and nothing a model can train on or score.
MODEL_COHORT = pandera.DataFrameSchema(
COHORT_FRAME.columns,
checks=[*COHORT_FRAME.checks, pandera.Check(lambda frame: len(frame) > 0, error="the build has no rows")],
name="cohort build a model reads")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
strict=True, ordered=True, name="estimate")
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
@@ -56,8 +66,13 @@ class CohortFileError(ValueError):
`COHORT_FRAME`."""
class UnusableCohortError(ValueError):
"""The rows a source gave a model break `MODEL_COHORT`: none at all, or a member, date or event missing."""
class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice at one horizon, a negative
horizon, a probability outside 0..1."""
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
@@ -69,6 +84,18 @@ def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: typ
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
def failed_checks(schema: pandera.DataFrameSchema, frame: pd.DataFrame) -> str | None:
"""The checks `frame` fails, each with its column and how many rows failed it, never a value; `None` when it
satisfies `schema`."""
try:
schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
return "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return None
class CohortDefinitionError(ValueError):
"""The cohort's queries or their results don't follow the structure a build chains."""
+12 -56
View File
@@ -1,21 +1,16 @@
"""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.
the keys lineage is recorded with, the code's version, a model's hash, and the rule that an output already exists when
its recorded lineage matches what's expected. The hashes of data files live with the files (`models.io.storage`).
"""
import hashlib
import os
import subprocess
from importlib.metadata import version
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"
MODELS_VERSION_TAG = "models.version"
COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source"
COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256"
@@ -25,52 +20,17 @@ def registered_name(domain: str, scenario: str) -> str:
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()}
"""The version of the installed `models` package: what a run's code is, with or without a repository."""
return {MODELS_VERSION_TAG: version("models")}
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()
"""sha256 of a saved model's pickle (`python_model.pkl` for a pyfunc, `model.pkl` for scikit-learn): the fitted
model itself. `MLmodel` is left out because it carries ids and dates, so the same model saved twice has the same
sha."""
folder = Path(model_dir)
pickle = next(path for path in (folder / "python_model.pkl", folder / "model.pkl") if path.exists())
return hashlib.sha256(pickle.read_bytes()).hexdigest()
def matches(recorded: dict, expected: dict) -> bool:
@@ -78,7 +38,3 @@ def matches(recorded: dict, expected: dict) -> bool:
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}")
+2 -2
View File
@@ -26,7 +26,7 @@ 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.reports.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"
@@ -41,7 +41,7 @@ STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos",
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,
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", 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://"
+145 -4
View File
@@ -1,5 +1,13 @@
"""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.
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates) and
their hashes, dbt's manifest, a domain's Persistance repositories, the batches of risks they store, and the cohort
sources a model trains and estimates on.
A cohort source (`KitBuild`, `CohortFile`) gives a build's long frame (`COHORT_SCHEMA`), its lineage (at least `url`
and `datos_as_of`, as text) and the reference a run, a version and an estimate keep of it (`cohort.url`,
`cohort.source`, `cohort.build`), so the dataflow doesn't know where the rows came from. `KitBuild` reads a kit build
now from the domain's database (its members, and their timeline up to its clinical cut-off and, when the build has
one, its load cut-off `conocida_hasta`; the lineage records when it was read) and writes nothing; reading it again later may give other rows if the
timeline changed. `CohortFile` reads an exported file, kit's or dbt's, and its reference adds the file's hash.
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
@@ -11,8 +19,11 @@ import importlib
import json
import os
import tempfile
from datetime import date
from dataclasses import dataclass, field
from datetime import date, datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any, Protocol
import pandas as pd
import pyarrow as pa
@@ -20,7 +31,9 @@ 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)
CohortFileError, CohortQueries, ExclusionRule, MODEL_COHORT, UnusableCohortError,
check_frame, failed_checks)
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
def cohorts_root(database_url: str) -> Path:
@@ -238,3 +251,131 @@ class ReadOnlyRepository:
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
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 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 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}")
class CohortSource(Protocol):
armado_id: int | None # the kit build it is, if any (ML-03)
def frame(self) -> pd.DataFrame: ...
def lineage(self) -> dict[str, str]: ...
def reference(self) -> dict[str, str]: ...
def model_frame(source: CohortSource) -> pd.DataFrame:
"""The source's frame, if a model may read it (`MODEL_COHORT`): a build with no rows, or with a member, a date or
an event missing, is refused whether it came from the database or a file. The refusal names the failed checks and
how many rows failed each, never a value."""
frame = source.frame()
failed = failed_checks(MODEL_COHORT, frame)
if failed:
raise UnusableCohortError(f"{type(source).__name__} isn't a {MODEL_COHORT.name}: {failed}")
return frame
@dataclass
class KitBuild:
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
`cohort_repository` and `timeline_repository`; tests pass stand-ins."""
domain: str
build_id: int
cohorts: Any = None
timeline: Any = None
_build: Any = field(default=None, init=False, repr=False)
def __post_init__(self):
if self.cohorts is None or self.timeline is None:
repositories = import_module(f"persistance.{self.domain}")
self.cohorts = self.cohorts or repositories.cohort_repository
self.timeline = self.timeline or repositories.timeline_repository
@property
def armado_id(self) -> int:
return self.build.armado_id
@property
def build(self):
if self._build is None:
self._build = self.cohorts.build(self.build_id)
if self._build is None:
raise LookupError(f"no kit build {self.build_id} in {self.domain}")
return self._build
def known_until(self) -> datetime | None:
"""The build's load cut-off, if it has one; without it everything loaded so far is read."""
return self.build.conocida_hasta
def frame(self) -> pd.DataFrame:
from models.steps.cohort_file import cohort_events
members = self.cohorts.members(self.build_id)
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
rows = self.timeline.read(patients=population["pac_id"].tolist(), until=self.build.datos_as_of,
known_until=self.known_until())
return cohort_events(rows, population, self.build.datos_as_of)
def lineage(self) -> dict[str, str]:
build = self.build
return {"url": build.url, "version": build.version, "armado_id": str(build.armado_id), "producer": "kit",
"datos_as_of": build.datos_as_of.isoformat(), "n_members": str(build.n_miembros),
"known_until": self.known_until().isoformat() if self.known_until() else "",
"read_at": datetime.now(timezone.utc).isoformat()}
def reference(self) -> dict[str, str]:
return {COHORT_URL_TAG: self.build.url, COHORT_SOURCE_TAG: "kit", COHORT_BUILD_TAG: str(self.build_id)}
@dataclass
class CohortFile:
"""An exported build's Parquet file."""
path: str | Path
@property
def armado_id(self) -> int | None:
lineage = self.lineage()
return int(lineage["armado_id"]) if lineage.get("producer") != "dbt" and "armado_id" in lineage else None
def frame(self) -> pd.DataFrame:
return read_cohort(self.path)
def lineage(self) -> dict[str, str]:
return read_metadata(self.path)
def reference(self) -> dict[str, str]:
return cohort_reference(self.lineage(), file_sha256(self.path))
+27 -11
View File
@@ -22,20 +22,25 @@ 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.
tagged with the installed `models` package's version. A PROD run only logs models
whose class lives in a module, never one defined in a notebook.
A model is a scikit-learn estimator (saved with MLflow's sklearn flavor, served
through `predict_proba`) or an `mlflow.pyfunc.PythonModel`. Classes of a package
registered with `cloudpickle.register_pickle_by_value` are stored with the model,
so it loads without this repository.
"""
import io
import json
import os
import tempfile
import zipfile
from importlib.metadata import version
from pathlib import Path
from typing import Any
import mlflow.pyfunc
import mlflow.sklearn
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
@@ -123,6 +128,11 @@ def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], f
return run.info.run_id
def pinned(requirements: list[str]) -> list[str]:
"""Each distribution at the version installed here: `scikit-learn` → `scikit-learn==1.7.2`."""
return [f"{name}=={version(name)}" for name in requirements]
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
@@ -181,18 +191,24 @@ class TrainingRun:
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."""
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
"""Saves `model` 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. `requirements` are what an environment needs to load it (`pinned`); without them
MLflow infers them from the environment, which in this repository means its whole lock."""
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__":
if self.environment is Environment.PROD and type(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")
f"{type(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)
if isinstance(model, mlflow.pyfunc.PythonModel):
mlflow.pyfunc.save_model(path=str(path), python_model=model, signature=signature,
pip_requirements=requirements)
else:
mlflow.sklearn.save_model(model, str(path), serialization_format="cloudpickle", signature=signature,
pyfunc_predict_fn="predict_proba", pip_requirements=requirements)
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)
+1 -1
View File
@@ -63,7 +63,7 @@ class Experiment:
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.storage import cohort_reference, file_sha256
from models.io.tracking import TrainingRun
cohort = cohort_reference(self.lineage(), file_sha256(self.cohort_path))
+4 -5
View File
@@ -1,7 +1,7 @@
"""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
content hash, the build's file (`models.io.storage.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
@@ -25,14 +25,13 @@ 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.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, 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.storage import cohort_reference, file_sha256, read_metadata
from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files
from models.steps.report import notebook_sha256, without_outputs
from models.reports.rendering import notebook_sha256, without_outputs
EXPERIMENT_SUFFIX = "experimentos"
KIND_TAG, KIND = "experiment", "notebook"
+3 -2
View File
@@ -20,8 +20,9 @@ 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.io.lineage import matches
from models.io.storage import (cohort_path, dbt_build_path, latest_dbt_build, read_metadata, require_match,
write_once)
from models.pipelines.cohort_build import build_cohort
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
+3 -3
View File
@@ -1,7 +1,7 @@
"""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
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome, and the cohort build it scored; each row carries its horizon. 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.
"""
@@ -15,7 +15,7 @@ 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)
REQUIRED = (*PROVENANCE, "desenlace", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
@@ -26,6 +26,6 @@ def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
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"]))
rows = risk_rows(pd.read_parquet(estimate_path))
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
metadata["desenlace"], rows)
+6
View File
@@ -0,0 +1,6 @@
"""Reports: notebooks run on a build's file, rendered with Quarto and kept in MLflow, using `models.io` to read the
build and record the run.
rendering.py a notebook to a self-contained HTML page with Quarto, and what identifies its content
eda.py the exploratory notebook of a scenario, as a report run
"""
@@ -1,7 +1,7 @@
"""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
in it, tagged with the notebook's content hash and the build's file (`models.io.storage.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.
@@ -15,11 +15,10 @@ 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.lineage import registered_name
from models.io.storage import cohort_reference, file_sha256, read_metadata
from models.io.tracking import find_run, record_report
from models.steps.report import notebook_sha256, without_outputs
from models.reports.rendering import notebook_sha256, render_notebook, without_outputs
COHORT_FILE_ENV = "COHORT_FILE"
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
@@ -2,7 +2,8 @@
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.
picks one; otherwise Quarto when it's installed, else Jupyter. A notebook's content is identified by its cells' sources, without outputs or
execution counts.
`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
@@ -12,6 +13,8 @@ cohort folder and a build's file. Quarto writes next to its input, so the notebo
first and the source folder is left untouched.
"""
import copy
import hashlib
import json
import os
import shutil
@@ -150,3 +153,19 @@ def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, s
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(page)
return output
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
+1 -1
View File
@@ -6,7 +6,7 @@ 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
from models.io.storage import table_sha256
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"]
+150
View File
@@ -0,0 +1,150 @@
"""Fitting a classifier on labelled members and measuring it: the steps every scenario shares.
A scenario's own module produces `labelled_members` (one row per member whose outcome is known, its predictors and
the outcome) and the driver passes both modules to `with_modules`, with `predictor_columns`, `train_fraction` and the
`classifier` config. Each node is named after what it produces. No node reads, writes or logs: registering the result
is a saver's job.
`routines` gathers what each routine around training did (ML-01a), by the kind it's stored under: `sampling`,
`analytic_method`, `class_balance` and `output_confidence` are here; `missing_data` is the scenario's, since only it
knows what a missing predictor is. A scenario that leaves members out before `labelled_members` says how many with a
`members_left_out` node.
The classifier is chosen by config: `@config.when(classifier=...)` picks one `prefit_classifier`, so another
classifier is one more function here and no change to any scenario.
"""
import pandas as pd
from hamilton.function_modifiers import config, extract_fields
from sklearn.base import ClassifierMixin, clone
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
SPLIT_ORDER = ("fecha_indice", "pac_id")
PROBABILITY = "probabilidad"
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float, target_column: str = "y",
split_order: tuple = SPLIT_ORDER) -> dict:
"""The oldest members by `split_order` train and the newest test: a model is judged on cases later than the ones
it learned from, never on a shuffled mix."""
if target_column not in labelled_members.columns:
raise ValueError(f"labelled_members has no {target_column!r} column")
ordered = labelled_members.sort_values(list(split_order), kind="stable")
cut = int(len(ordered) * train_fraction)
return {"train_set": ordered.iloc[:cut], "test_set": ordered.iloc[cut:]}
def encoder(predictor_columns: list[str]) -> ColumnTransformer:
"""One-hot predictors; a category not seen in training counts as none of the known ones."""
return ColumnTransformer([("predictors", OneHotEncoder(handle_unknown="ignore"), list(predictor_columns))])
@config.when(classifier="logistic")
def prefit_classifier__logistic(max_iter: int = 1000) -> ClassifierMixin:
"""An unfitted logistic regression."""
return LogisticRegression(max_iter=max_iter)
def fitted_pipeline(encoder: ColumnTransformer, prefit_classifier: ClassifierMixin, train_set: pd.DataFrame,
predictor_columns: list[str], target_column: str = "y") -> Pipeline:
"""The encoder and the classifier fitted on `train_set`. Fits copies, so the prefit nodes stay unfitted."""
pipeline = Pipeline([("encode", clone(encoder)), ("classify", clone(prefit_classifier))])
return pipeline.fit(train_set[list(predictor_columns)], train_set[target_column])
def test_probabilities(fitted_pipeline: Pipeline, test_set: pd.DataFrame, predictor_columns: list[str]) -> pd.Series:
"""The probability of the outcome for each row of `test_set`."""
return pd.Series(fitted_pipeline.predict_proba(test_set[list(predictor_columns)])[:, 1], index=test_set.index,
name=PROBABILITY)
def auc(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
"""Area under the ROC curve on `test_set`; undefined (an error) when the test set has a single class."""
return float(roc_auc_score(test_set[target_column], test_probabilities))
def brier_score(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
return float(brier_score_loss(test_set[target_column], test_probabilities))
def positive_rate_train(train_set: pd.DataFrame, target_column: str = "y") -> float:
return float(train_set[target_column].mean())
def positive_rate_test(test_set: pd.DataFrame, target_column: str = "y") -> float:
return float(test_set[target_column].mean())
def mean_probability_test(test_probabilities: pd.Series) -> float:
return float(test_probabilities.mean())
def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: pd.DataFrame,
positive_rate_train: float, positive_rate_test: float, mean_probability_test: float) -> dict:
"""What a training run records: aggregates only, no patient data. The keys are the names MLflow keeps."""
return {"auc": auc, "brier": brier_score, "n_train": len(train_set), "n_test": len(test_set),
"positive_rate_train": positive_rate_train, "positive_rate_test": positive_rate_test,
"mean_probability_test": mean_probability_test}
def _index_dates(frame: pd.DataFrame, column: str) -> dict:
if frame.empty:
return {"n": 0}
return {"n": len(frame), "first_index_date": str(frame[column].min()), "last_index_date": str(frame[column].max())}
def sampling(labelled_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame, train_fraction: float,
members_left_out: int = 0, split_order: tuple = SPLIT_ORDER) -> 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": train_fraction, "members": len(labelled_members) + members_left_out,
"left_out_unknown_outcome": members_left_out, "train": _index_dates(train_set, split_order[0]),
"test": _index_dates(test_set, split_order[0])}
def analytic_method(fitted_pipeline: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted classifier, its settings and, when it has them, its coefficients."""
classifier = fitted_pipeline.named_steps["classify"]
found = {"method": f"{type(classifier).__name__} sobre los predictores codificados one-hot",
"estimator": type(classifier).__name__, "settings": classifier.get_params()}
if hasattr(classifier, "coef_"):
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
found["intercept"] = float(classifier.intercept_[0])
found["coefficients"] = dict(zip(map(str, features), map(float, classifier.coef_[0])))
return found
def _class_counts(frame: pd.DataFrame, column: str) -> dict:
return {str(value): int(n) for value, n in frame[column].value_counts().sort_index().items()}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline,
target_column: str = "y") -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = getattr(fitted_pipeline.named_steps["classify"], "class_weight", None)
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
"train": _class_counts(train_set, target_column), "test": _class_counts(test_set, target_column)}
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, brier_score: float,
target_column: str = "y", calibration_bins: int = 10) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by quantiles."""
bins = pd.qcut(test_probabilities, q=min(calibration_bins, test_probabilities.nunique()), duplicates="drop")
table = pd.DataFrame({"p": test_probabilities, "y": test_set[target_column]}).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": brier_score,
"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}
-21
View File
@@ -1,21 +0,0 @@
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
import copy
import hashlib
import json
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
+6 -5
View File
@@ -5,9 +5,10 @@ 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."""
def risk_rows(estimate: pd.DataFrame) -> list[tuple]:
"""One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored
twice at one horizon 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"])]
return [(int(pac_id), float(horizon), float(probability), None, None)
for pac_id, horizon, probability in zip(estimate["pac_id"], estimate["horizonte_anios"],
estimate["probabilidad"])]
+7 -1
View File
@@ -18,7 +18,7 @@ dependencies = [
]
[project.optional-dependencies]
# Running uploaded notebooks without Quarto (models.io.rendering.JupyterRenderer, models.pipelines.experiment).
# Running uploaded notebooks without Quarto (models.reports.rendering.JupyterRenderer, models.pipelines.experiment).
notebooks = [
"nbclient>=0.10",
"nbconvert>=7.16",
@@ -45,3 +45,9 @@ dev = [
"nbconvert>=7.16",
"ipykernel>=6.29",
]
# The scenarios' notebooks (`<scenario>/notebooks/`): a Jupyter kernel and the drawing of the Hamilton DAGs.
# `graphviz` is only the Python side: drawing also needs Graphviz's `dot` program on the machine.
notebooks = [
"ipykernel>=6.29",
"graphviz>=0.20",
]
+127 -43
View File
@@ -19,12 +19,22 @@ 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.dags import training
from models.dags.training import Scenario, dataflow, 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
from models.io.storage import CohortFile
from models.steps.model_fitting import train_test_split
CUTOFF = date(2027, 6, 30)
SCENARIO = Scenario.load("cacu", "cin2_logistic")
CONFIG = SCENARIO.config
PREDICTORS, GRADES = CONFIG["predictor_columns"], CONFIG["event_grades"]
def _outcomes(frame):
return model.windowed_outcomes(frame, CUTOFF, [1.0], GRADES)
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
@@ -89,7 +99,7 @@ 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")
found = model.index_sample_results(cohort_frame, PREDICTORS).set_index("pac_id")
assert len(found) == 20
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
@@ -103,7 +113,7 @@ def test_the_genotype_is_read_from_its_number():
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"
assert model.index_sample_results(frame, PREDICTORS).loc[0, "vph_16_18"] == "POSITIVO"
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
@@ -114,54 +124,82 @@ def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
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
assert _outcomes(frame).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,
of `labelled_members`; 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")
outcome = _outcomes(frame).set_index("pac_id")
assert outcome["known"].tolist() == [False, True]
assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2]
assert model.labelled_members(model.index_sample_results(frame, PREDICTORS), _outcomes(frame))["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)))
labelled = model.labelled_members(model.index_sample_results(cohort_frame, PREDICTORS), _outcomes(cohort_frame))
parts = train_test_split(labelled, CONFIG["train_fraction"])
assert (len(parts["train"]), len(parts["test"])) == (14, 6)
assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min()
assert (len(parts["train_set"]), len(parts["test_set"])) == (14, 6)
assert parts["train_set"]["fecha_indice"].max() < parts["test_set"]["fecha_indice"].min()
def test_the_graph_takes_exactly_its_config_and_the_cohort():
"""Pins down the driver's external inputs: the loaders' `cohort` and `cohort_lineage` and the config's keys, and
nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
or a module added to the driver rewires a parameter."""
required, optional = training.external_inputs(dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
assert optional == {"calibration_bins", "classifier", "max_iter", "split_order", "target_column"}
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
"""Pins down: the scenario's graph, without the driver's adapters, runs from a frame to its metrics and its fitted
model with no file and no MLflow, and that model takes the long frame: one row per member, in `pac_id` order, the
same probabilities the fitted pipeline gives the test set. Fails if a node starts reading, writing or logging, a
node name stops matching `models.steps.model_fitting`'s, or `IndexSampleResults` orders members differently."""
lineage = {"datos_as_of": CUTOFF.isoformat()}
found = dataflow(*SCENARIO.modules, config=CONFIG).execute(
["metrics", "fitted_model", "test_set", "test_probabilities"],
inputs={"cohort": cohort_frame, "cohort_lineage": lineage})
assert found["metrics"]["n_train"] == 14 and found["metrics"]["n_test"] == 6
probabilities = found["fitted_model"].predict_proba(cohort_frame)
assert probabilities.shape == (20, 2)
test_rows = found["test_set"]["pac_id"].to_numpy() - 1
assert probabilities[test_rows, 1] == pytest.approx(found["test_probabilities"].to_numpy())
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)
window and the note that it's a prototype, and a model that takes the long frame. Fails if any is lost, or if the
driver stops reaching `registered_model`."""
version = train(SCENARIO, CohortFile(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 "Prototipo" in stored.description and run.params["horizons_years"] == "[1.0]"
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort_sha256"]) == 64
assert len(run.params["cohort.file_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()
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
assert probabilities.shape == (20, 2) and ((probabilities >= 0) & (probabilities <= 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)
counts that add up to the split. Fails if the saver stops logging the `routines` node, a routine node leaves the
graph, or one records something other than this training's own numbers."""
version = train(SCENARIO, CohortFile(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
@@ -175,7 +213,7 @@ def test_training_records_each_routine_as_it_ran(cohort_file, cacu_db, mlflow_tr
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 main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
assert "version 1" in capsys.readouterr().out
stored = registry.get("cacu", "cin2_logistic", "1")
@@ -185,7 +223,7 @@ def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracki
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
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--armado", "7", "--environment", "prod"]) == 0
stored = registry.get("cacu", "cin2_logistic", "1")
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
@@ -195,14 +233,14 @@ 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"])
main(["train", "cacu", "cin2_logistic", "--read", "file", "--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"),
(["cacu", "cin2_logistic", "--read", "file", "--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
@@ -215,16 +253,16 @@ def test_estimate_scores_each_member_with_the_production_version(exported, mlflo
"""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"])
main(["train", "cacu", "cin2_logistic", "--read", "file"])
main(["train", "cacu", "cin2_logistic", "--read", "file"])
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 main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--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 list(risks.columns) == ["pac_id", "fecha_indice", "horizonte_anios", "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"
@@ -233,10 +271,10 @@ def test_estimate_scores_each_member_with_the_production_version(exported, mlflo
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"])
main(["train", "cacu", "cin2_logistic", "--read", "file"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output), "--version", "1"]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
@@ -244,15 +282,15 @@ def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_pa
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"])
main(["train", "cacu", "cin2_logistic", "--read", "file"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output)]) == 1
assert "no version in production" in capsys.readouterr().err and not output.exists()
RUN = ["run", "cacu", "cin2_logistic"]
RUN = ["run", "cacu", "cin2_logistic", "--read", "file"]
def _versions():
@@ -306,22 +344,23 @@ def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
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`."""
def test_another_models_version_trains_again(exported, mlflow_tracking, monkeypatch):
"""Pins down: a version trained by another release of `models` isn't reused. Fails if the check stops comparing the
installed package's version."""
assert main([*RUN, "--train"]) == 0
assert find_trained(exported / "12.parquet") == "1"
assert find_trained(SCENARIO, CohortFile(exported / "12.parquet")) == "1"
monkeypatch.setattr(model, "code_sha256", lambda: "other")
monkeypatch.setattr(training, "code_version", lambda: {"models.version": "9.9.9"})
assert find_trained(exported / "12.parquet") is None
assert find_trained(SCENARIO, CohortFile(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."""
output = tmp_path / "output.parquet"
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
@@ -370,7 +409,7 @@ def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported,
"""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
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt"]) == 0
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert ARMADO_TAG not in tags
@@ -384,7 +423,7 @@ def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, m
dbt file."""
output = tmp_path / "output.parquet"
assert main(["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod",
assert main(["run", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "1", "--environment", "prod",
"--train", "--promote", "--estimate", "--output", str(output)]) == 0
tags = registry.get("cacu", "cin2_logistic", "1").tags
@@ -397,5 +436,50 @@ def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, m
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 main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "9"]) == 1
assert "--source dbt" in capsys.readouterr().err
def test_the_registered_artifact_runs_without_this_repository(cohort_file, cohort_frame, mlflow_tracking,
predict_without_repository):
"""Pins down: the version scores the long frame in a Python that can't import `models`, with the same probabilities
as in this one. Fails if `IndexSampleResults` starts using a function outside the scenario's package, which would
be pickled by reference."""
uri = registry.resolve("cacu", "cin2_logistic", train(SCENARIO, CohortFile(cohort_file))).model_uri
outside = predict_without_repository(uri, cohort_frame)
inside = mlflow.pyfunc.load_model(uri).predict(cohort_frame)
assert outside.to_numpy() == pytest.approx(inside)
def test_by_default_the_command_reads_the_kit_build_from_the_database(cohort_frame, kit_stand_ins, mlflow_tracking,
monkeypatch, capsys):
"""Pins down: with no `--read`, `train` reads the latest kit build's members and timeline through the domain's
repositories, cut at the build's date, writes no file, and the version points to the build with no file hash.
Fails if the default goes back to the exported file, or the source's reference keeps a hash it can't have."""
cohorts, timeline = kit_stand_ins(cohort_frame, 7, CUTOFF)
monkeypatch.setattr("persistance.cacu.cohort_repository", cohorts)
monkeypatch.setattr("persistance.cacu.timeline_repository", timeline)
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert "from kit build 7" in capsys.readouterr().out
assert [read["until"] for read in timeline.reads] == [CUTOFF]
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert (tags["cohort.source"], tags["cohort.build"], tags[ARMADO_TAG]) == ("kit", "7", "7")
assert "cohort.file_sha256" not in tags
def test_no_member_value_reaches_mlflow(cohort_frame, tmp_path, mlflow_tracking, mlflow_store_leaks):
"""Pins down the outcome the logger's and the saver's allowlists are there for: after training, no `pac_id` and no
source row id of the training data is in MLflow's database or artifacts, as text or as an integer. Fails if a
node's rows are logged, the model keeps the training frame, or an error message carries values."""
frame = cohort_frame.assign(pac_id=cohort_frame["pac_id"] + 987_650_000,
fuente_id="CANARY-" + cohort_frame["fuente_id"])
path = _write(frame, tmp_path / "input" / "7.parquet", {"armado_id": 7})
train(SCENARIO, CohortFile(path))
leaks = mlflow_store_leaks(tmp_path, texts=["CANARY-"], integers=frame["pac_id"].unique(), skip=("input",))
assert leaks == []
+154
View File
@@ -0,0 +1,154 @@
"""What this module covers: `models.cacu.cin2_pim`: how a member's index results and biopsies become a code and an
interval, the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
driver, with every member scored at every horizon, also outside this repository.
Fixtures: `cohort_frame`, a long frame of 300 simulated members (a quarter with an abnormal index sample, some with a
prevalent or a later CIN2+ biopsy); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
`predict_without_repository` (conftest).
"""
from datetime import date, datetime, timedelta, timezone
import mlflow.pyfunc
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cacu.cin2_pim import model
from models.dags import training
from models.dags.estimation import estimate
from models.io.contracts import COHORT_SCHEMA
from models.io.registry import PRODUCTION_ALIAS, registry
from models.io.storage import CohortFile
CUTOFF = date(2027, 6, 30)
SCENARIO = training.Scenario.load("cacu", "cin2_pim")
CONFIG = SCENARIO.config
def _row(pac_id, index, days, tipo, valor=None):
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo,
"codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "t",
"fuente_id": f"{pac_id}-{tipo}-{days}"}
def _member(pac_id, index, bethesda, vph, biopsies=()):
rows = [_row(pac_id, index, 0, "citologia"), _row(pac_id, index, 7, "bethesda", bethesda),
_row(pac_id, index, 7, "vph", vph)]
return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies]
def _coded(rows):
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
return model.interval_coded_members(frame, CUTOFF, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"]).set_index("pac_id")
@pytest.fixture
def cohort_frame():
"""Abnormal members (every fourth) are biopsied within 2 months, CIN2+ for a third of them; a tenth of the normal
ones has a CIN2+ biopsy between 1 and 2 years later. Index dates rise with `pac_id` over 2023-2024."""
rng = np.random.default_rng(0)
rows = []
for pac_id in range(1, 301):
index = date(2023, 1, 1) + timedelta(days=2 * pac_id)
if pac_id % 4 == 0:
grade = "LIEAG" if rng.random() < 0.35 else "NEGATIVO"
rows += _member(pac_id, index, "LIEBG", "POSITIVO", [(45, grade)])
elif rng.random() < 0.1:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")])
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
table = pa.Table.from_pandas(cohort_frame, schema=COHORT_SCHEMA, preserve_index=False)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), "armado_id": "3"}
path = tmp_path / "3.parquet"
pq.write_table(table.replace_schema_metadata(lineage), path)
return path
def test_each_member_gets_its_code_and_interval():
"""Pins down the coding: a CIN2+ biopsy in the window is prevalent; a known negative baseline with a later CIN2+
biopsy is incident in `(0, t]`; a known negative without one is censored at its follow-up; an abnormal sample with
no biopsy is unknown in `(0, inf)`; a negative biopsy in the window makes the baseline known. Fails if any case
gets another code, which changes what the likelihood counts."""
index = date(2025, 1, 1)
coded = _coded(_member(1, index, "LIEAG", "POSITIVO", [(30, "LIEAG")])
+ _member(2, index, "NORMAL", "NEGATIVO", [(730, "CIS")])
+ _member(3, index, "NORMAL", "NEGATIVO")
+ _member(4, index, "ASC-US", "POSITIVO")
+ _member(5, index, "ASC-US", "POSITIVO", [(60, "NEGATIVO")]))
assert coded["c"].tolist() == [1, 0, 0, -999, 0]
assert coded.loc[2, "r"] == pytest.approx(730 / 365.25) and coded.loc[2, "l"] == 0.0
assert coded.loc[3, "l"] == pytest.approx((CUTOFF - index).days / 365.25) and np.isinf(coded.loc[3, "r"])
assert (coded.loc[4, "l"], coded.loc[4, "r"]) == (0.0, np.inf)
def test_the_graph_takes_exactly_its_config_and_the_cohort():
"""Pins down the driver's external inputs: the loaders' `cohort` and `cohort_lineage` and the config's keys, and
nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
or a module added to the driver rewires a parameter."""
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "index_sample_days",
"known_negative", "prevalent_window_months", "train_fraction"}
assert optional == set()
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
"""Pins down: the graph runs from a frame to aggregates per horizon with no file and no MLflow, and the expected
rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the
fit stops recovering the prevalence."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["metrics"], inputs={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["metrics"]
assert found["n_train"] == 210 and found["n_test"] == 90
assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found)
assert all(isinstance(value, (int, float)) for value in found.values())
assert found["expected_0y"] == pytest.approx(found["observed_0y"], abs=0.05)
def test_the_dataflow_records_each_routine(cohort_frame):
"""ML-01a: the graph gives the five routine records, in counts that add up to the split and one calibration entry
per horizon. Fails if a routine node leaves the graph, so a trained version could never be promoted, or records
something other than this fit's own numbers."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["routines"], inputs={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["routines"]
assert set(found) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert found["MUESTREO"]["train"]["n"] == 210 and found["MUESTREO"]["test"]["n"] == 90
assert sum(found["BALANCE_CLASES"]["train"].values()) == 210
assert [h["years"] for h in found["CONFIANZA_SALIDA"]["horizons"]] == CONFIG["horizons_years"]
assert set(found["METODO_ANALITICO"]["prevalence_coefficients"]) == {"intercept", "abnormal_cytology", "hpv_positive"}
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
predict_without_repository):
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata.
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository."""
version = training.train(SCENARIO, CohortFile(cohort_file))
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
output = tmp_path / "estimate.parquet"
estimate(SCENARIO, CohortFile(cohort_file), output)
risks = pd.read_parquet(output)
assert len(risks) == 300 * len(CONFIG["horizons_years"])
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
uri = registry.resolve("cacu", "cin2_pim", version).model_uri
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, len(CONFIG["horizons_years"]))
np.testing.assert_allclose(outside.to_numpy(), inside)
+57
View File
@@ -0,0 +1,57 @@
import numpy as np
import pytest
from models.cacu.cin2_pim import likelihood as L
def simulate(n=4000, seed=0):
"""Two groups, known prevalence and Weibull incidence, screening every year for 5 years."""
rng = np.random.default_rng(seed)
group = rng.integers(0, 2, n)
X = np.column_stack([np.ones(n), group])
Z = group[:, None].astype(float)
theta, beta, scale, shape = np.array([-3.0, 1.5]), np.array([0.7]), 8.0, 1.3
prevalent = rng.random(n) < L.prevalence(theta, X)
time = scale * (-np.log(rng.random(n)) / np.exp(Z @ beta)) ** (1 / shape)
c = np.where(prevalent, 1, 0)
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 5.0))
r = np.where(prevalent, 0.0, np.where(time < 5, np.floor(time) + 1, np.inf))
return c, l, r, X, Z, theta, beta, scale, shape
def test_survival_limits():
Z = np.zeros((3, 1))
s = L.weibull_survival([0.0, 2.0, np.inf], np.log(5.0), 0.0, np.zeros(1), Z)
assert s[0] == 1.0 and s[2] == 0.0
assert s[1] == pytest.approx(np.exp(-2 / 5))
def test_fit_recovers_simulated_parameters():
c, l, r, X, Z, theta, beta, scale, shape = simulate()
fitted = L.fit(c, l, r, X, Z)
assert fitted["converged"]
np.testing.assert_allclose(fitted["theta"], theta, atol=0.3)
np.testing.assert_allclose(fitted["beta"], beta, atol=0.3)
assert np.exp(fitted["log_scale"]) == pytest.approx(scale, rel=0.3)
assert np.exp(fitted["log_shape"]) == pytest.approx(shape, rel=0.3)
def test_unknown_rows_only_add_information_about_the_mixture():
"""A row with c = -999 and l = 0, r = inf says nothing: it contributes log(1) = 0."""
c, l, r, X, Z, *_ = simulate(n=200)
params = np.zeros(X.shape[1] + Z.shape[1] + 2)
base = L.neg_loglik(params, c, l, r, X, Z)
c2 = np.r_[c, L.UNKNOWN]
l2, r2 = np.r_[l, 0.0], np.r_[r, np.inf]
X2, Z2 = np.vstack([X, X[:1]]), np.vstack([Z, Z[:1]])
assert L.neg_loglik(params, c2, l2, r2, X2, Z2) == pytest.approx(base, abs=1e-9)
def test_cumulative_risk_starts_at_prevalence():
c, l, r, X, Z, *_ = simulate(n=500)
fitted = L.fit(c, l, r, X, Z)
cr = L.cumulative_risk(fitted, X, Z, years=[0, 1, 5])
np.testing.assert_allclose(cr[:, 0], L.prevalence(fitted["theta"], X))
assert np.all(np.diff(cr, axis=1) >= 0)
+91
View File
@@ -101,3 +101,94 @@ def armado(huella: str) -> int:
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
session.commit()
return fila.armado_id
LOAD_WITHOUT_REPOSITORY = """
import sys
import pandas as pd
sys.modules["models"] = None # importing anything from this repository now fails
sys.modules["hamilton"] = None # nor Hamilton: the artifact runs where the dataflow isn't installed
import mlflow.pyfunc
model = mlflow.pyfunc.load_model(sys.argv[1])
output = pd.DataFrame(model.predict(pd.read_parquet(sys.argv[2])))
output.columns = [str(column) for column in output.columns]
output.to_parquet(sys.argv[3])
"""
@pytest.fixture
def predict_without_repository(tmp_path):
"""Runs a registered version in a separate Python where neither `models` nor `hamilton` can be imported, on a
frame, and returns its output, columns named `"0"`, `"1"`…: what an environment with MLflow and the model's
libraries would get."""
import os
import subprocess
import sys
import pandas as pd
def run(model_uri: str, frame: pd.DataFrame) -> pd.DataFrame:
source, output = tmp_path / "input.parquet", tmp_path / "output.parquet"
frame.to_parquet(source)
env = {**os.environ, "MLFLOW_DISABLE_AGENT_HINT": "1", "PYTHONPATH": ""}
subprocess.run([sys.executable, "-c", LOAD_WITHOUT_REPOSITORY, model_uri, str(source), str(output)],
check=True, env=env, cwd=tmp_path, capture_output=True)
return pd.read_parquet(output)
return run
@pytest.fixture
def kit_stand_ins():
"""Factory: stand-ins of a domain's `cohort_repository` and `timeline_repository` holding one kit build made of a
long frame's members and events, with dates as text as the database returns them. The timeline records each read's
patients and cut-offs."""
from datetime import datetime, timezone
from types import SimpleNamespace
from persistance.edges.gold import CohortBuild, CohortMember
def make(frame, build_id, cutoff, url="cacu/cohorte_vigilancia"):
index_dates = frame.groupby("pac_id")["fecha_indice"].first()
build = CohortBuild(build_id, url, "1", "huella", "marco", cutoff, None, len(index_dates),
datetime(2027, 1, 1, tzinfo=timezone.utc))
cohorts = SimpleNamespace(
latest_build=lambda asked: build_id if asked == url else None,
build=lambda asked: build if asked == build_id else None,
members=lambda asked: [CohortMember(int(p), d, "t", str(p)) for p, d in index_dates.items()])
rows = [{key: value.isoformat() if hasattr(value, "isoformat") else value
for key, value in row.items() if key != "fecha_indice"} for row in frame.to_dict("records")]
class Timeline:
reads = []
def read(self, *, patients=None, until=None, known_until=None):
self.reads.append({"patients": patients, "until": until, "known_until": known_until})
return [row for row in rows if patients is None or row["pac_id"] in set(patients)]
return cohorts, Timeline()
return make
@pytest.fixture
def mlflow_store_leaks():
"""Factory: which of these texts and integers appear, as text or as 8-byte integers, in any file under `root`
outside `skip` (the inputs themselves). Used with values only the training data holds, to show they never reached
MLflow's database or artifacts."""
from pathlib import Path
def scan(root, texts=(), integers=(), skip=()):
needles = {str(t): str(t).encode() for t in texts}
for number in integers:
needles[f"{number} (text)"] = str(number).encode()
needles[f"{number} (int64)"] = int(number).to_bytes(8, "little", signed=True)
found = set()
for path in Path(root).rglob("*"):
if not path.is_file() or any(part in skip for part in path.relative_to(root).parts):
continue
content = path.read_bytes()
found |= {name for name, needle in needles.items() if needle in content}
return sorted(found)
return scan
+230
View File
@@ -0,0 +1,230 @@
"""What this module covers: `models.io.adapters` and the generic driver of `models.dags.training`: the loaders feed the
graph from any cohort source and refuse a build with no rows or with nulls where a member, a date or an event goes,
the saver logs, registers and describes a version from `fitted_model` and `metrics`, the
registered model runs without this repository, metrics that aren't numbers fail the run and register nothing, and a
failing node's inputs never reach the log.
Fixtures: `scenario`, a throwaway scenario package (`model.py`, `model.toml`) under `tmp_path`, whose model gives every
member the same risk at two horizons; `cohort_file`, kit build 5's file with members 987654301 to 987654303;
`mlflow_tracking` and `predict_without_repository` (conftest).
"""
import importlib
import logging
import sys
import textwrap
from datetime import date, datetime, timezone
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from hamilton import ad_hoc_utils, driver
from hamilton.io.materialization import from_
from mlflow.entities import RunStatus
from models.dags import training
from models.io.contracts import COHORT_SCHEMA, UnusableCohortError
from models.io.registry import registry
from models.io.storage import CohortFile
MEMBERS = (987654301, 987654302, 987654303)
SCENARIO_TOML = """
domain = "cacu"
scenario = "fake_scenario"
cohort = "cacu/cohorte_vigilancia"
outcome = "fake"
modules = ["fake_scenario_pkg.model"]
requirements = ["scikit-learn", "numpy"]
description = "A scenario for tests."
[config]
risk = 0.25
horizons_years = [0.0, 2.0]
"""
SCENARIO_MODEL = '''
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
def member_count(cohort: pd.DataFrame) -> int:
return int(cohort["pac_id"].nunique())
def metrics(member_count: int, risk: float) -> dict:
return {"n_members": member_count, "risk": risk}
class ConstantRisk(BaseEstimator):
def __init__(self, risk=0.25, horizons_years=(0.0, 2.0)):
self.risk, self.horizons_years = risk, horizons_years
def fit(self, X, y=None):
return self
def predict_proba(self, X):
return np.full((X["pac_id"].nunique(), len(self.horizons_years)), float(self.risk))
def fitted_model(risk: float, horizons_years: list) -> ConstantRisk:
return ConstantRisk(risk, horizons_years)
'''
def _write_scenario(root, model_source=SCENARIO_MODEL):
package = root / "fake_scenario_pkg"
package.mkdir(exist_ok=True)
(package / "__init__.py").write_text("")
(package / "model.py").write_text(textwrap.dedent(model_source))
(package / "model.toml").write_text(SCENARIO_TOML)
for name in ("fake_scenario_pkg.model", "fake_scenario_pkg"):
sys.modules.pop(name, None)
importlib.invalidate_caches()
return training.Scenario.from_toml(package / "model.toml")
@pytest.fixture
def scenario(tmp_path, monkeypatch):
"""The throwaway scenario, its module importable as `fake_scenario_pkg.model`."""
monkeypatch.syspath_prepend(str(tmp_path))
return _write_scenario(tmp_path)
@pytest.fixture
def cohort_file(tmp_path):
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, day), "fecha": date(2025, 1, day),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "t",
"fuente_id": str(pac_id)} for day, pac_id in enumerate(MEMBERS, start=1)]
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA,
preserve_index=False)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": "2026-12-31", "armado_id": "5"}
path = tmp_path / "5.parquet"
pq.write_table(table.replace_schema_metadata(lineage), path)
return path
def test_the_loaders_feed_the_graph_from_a_source(cohort_file):
"""Pins down: `cohort_source` and `cohort_source_lineage` give the nodes the build's frame and its lineage, from the
source they're given. Fails if a loader's name changes or it stops asking its source."""
def members(cohort: pd.DataFrame) -> int:
return len(cohort)
def build_number(cohort_lineage: dict) -> str:
return cohort_lineage["armado_id"]
module = ad_hoc_utils.create_temporary_module(members, build_number)
dr = driver.Builder().with_modules(module).with_materializers(
from_.cohort_source(target="cohort", source=CohortFile(cohort_file)),
from_.cohort_source_lineage(target="cohort_lineage", source=CohortFile(cohort_file))).build()
assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"}
class _FrameSource:
"""A source that gives the frame it holds, as a database read would, without `read_cohort`'s checks."""
def __init__(self, frame):
self._frame = frame
def frame(self):
return self._frame
@pytest.mark.parametrize("change, check", [
(lambda frame: frame.iloc[0:0], "the build has no rows"),
(lambda frame: frame.assign(fecha_indice=None), "fecha_indice: not_nullable failed 3 time"),
(lambda frame: frame.assign(tipo=[None, "citologia", "citologia"]), "tipo: not_nullable failed 1 time"),
])
def test_a_build_with_no_rows_or_with_nulls_never_reaches_a_node(cohort_file, change, check):
"""Pins down: the `cohort_source` loader refuses an empty frame, and one with a null index date or event type, from
a source that doesn't check its own rows, naming the check and the count but no member. Fails if the loader stops
validating `MODEL_COHORT`, the schema loses its no-rows check, or the refusal starts quoting values."""
def members(cohort: pd.DataFrame) -> int:
return len(cohort)
broken = _FrameSource(change(CohortFile(cohort_file).frame()))
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(members)).with_materializers(
from_.cohort_source(target="cohort", source=broken)).build()
with pytest.raises(UnusableCohortError, match=check) as refused:
dr.execute(["members"])
assert not any(str(member) in str(refused.value) for member in MEMBERS)
def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scenario, cohort_file, mlflow_tracking):
"""Pins down: the saver logs the fitted model, records the metrics, the config and the `models` version, registers
the version with its build and describes it. Fails if the saver stops being reached from `registered_model`, or
drops any of those."""
version = training.train(scenario, CohortFile(cohort_file))
stored = registry.get("cacu", "fake_scenario", version)
run = registry.client.get_run(stored.run_id)
assert stored.description == "A scenario for tests." and stored.tags["kit.armado_id"] == "5"
assert run.data.metrics == {"n_members": 3.0, "risk": 0.25}
assert run.data.params["risk"] == "0.25" and "models.version" in run.data.params
assert run.info.status == RunStatus.to_string(RunStatus.FINISHED)
assert training.find_trained(scenario, CohortFile(cohort_file)) == version
def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking,
predict_without_repository):
"""Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the
scenario still loads the version and gives a probability per member and horizon. Fails if the model's classes go
back to being pickled by reference."""
version = training.train(scenario, CohortFile(cohort_file))
output = predict_without_repository(registry.resolve("cacu", "fake_scenario", version).model_uri,
pd.read_parquet(cohort_file))
assert output.shape == (3, 2) and (output == 0.25).all().all()
def test_metrics_that_are_not_numbers_fail_the_run_and_register_nothing(tmp_path, monkeypatch, cohort_file,
mlflow_tracking):
"""Pins down: a `metrics` value that isn't a number (a frame put there by mistake) stops the saver before MLflow
receives it, marks the run failed and registers no version. Fails if the check goes, or a failed graph leaves a
run open or a version behind."""
monkeypatch.syspath_prepend(str(tmp_path))
leaking = SCENARIO_MODEL.replace('return {"n_members": member_count, "risk": risk}',
'return {"n_members": member_count, "rows": pd.DataFrame({"pac_id": [1]})}')
scenario = _write_scenario(tmp_path, leaking)
with pytest.raises(TypeError, match="rows"):
training.train(scenario, CohortFile(cohort_file))
runs = registry.client.search_runs([e.experiment_id for e in registry.client.search_experiments()])
assert [r.info.status for r in runs] == [RunStatus.to_string(RunStatus.FAILED)]
assert not registry.client.search_model_versions("name='cacu-fake_scenario'")
def test_a_failing_node_does_not_log_its_inputs(tmp_path, monkeypatch, cohort_file, mlflow_tracking, caplog):
"""Pins down: when a node fails during training, the exception reaches the caller but Hamilton's log of the node's
inputs, which would show the first rows of the cohort, isn't written. Fails if the driver stops silencing
`hamilton.execution.graph_functions` or Hamilton moves that message to another logger."""
monkeypatch.syspath_prepend(str(tmp_path))
scenario = _write_scenario(tmp_path, SCENARIO_MODEL.replace('return int(cohort["pac_id"].nunique())',
'return int(cohort["missing"].sum())'))
with caplog.at_level(logging.DEBUG), pytest.raises(KeyError):
training.train(scenario, CohortFile(cohort_file))
assert not any(str(pac_id) in caplog.text for pac_id in MEMBERS)
def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohort_file, mlflow_tracking):
"""Pins down: the version's `requirements.txt` holds the scenario's `requirements`, each pinned to the installed
version, and no path or editable install of this repository. Fails if MLflow goes back to inferring them from the
environment, which copies the whole lock with `-e ../Persistance` and the like."""
import mlflow
from importlib.metadata import version as installed
run_id = registry.get("cacu", "fake_scenario", training.train(scenario, CohortFile(cohort_file))).run_id
lines = Path(mlflow.artifacts.download_artifacts(f"runs:/{run_id}/model/requirements.txt")).read_text().split()
assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines
assert not [line for line in lines if line.startswith("-e") or "/" in line]
+19 -7
View File
@@ -63,13 +63,25 @@ def test_reading_and_building_a_file_apply_the_checks(tmp_path):
@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]}),
pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "horizonte_anios": [1.0, 1.0],
"probabilidad": [0.1, 0.2]}),
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [1.0], "probabilidad": [1.2]}),
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [-1.0], "probabilidad": [0.1]}),
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [1.0], "probabilidad": [0.1],
"extra": [1]}),
pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "horizonte_anios": [1.0], "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."""
def test_an_estimate_is_one_probability_per_member_and_horizon_in_its_columns(estimate):
"""Pins down: a member twice at one horizon, a probability outside 0..1, a negative horizon, 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")
def test_an_estimate_may_hold_several_horizons_per_member():
"""Pins down: the same member at the prevalence and at later horizons is a valid estimate. Fails if the check goes
back to one row per member, which would refuse a prevalence–incidence model's output."""
estimate = pd.DataFrame({"pac_id": [1, 1, 1], "fecha_indice": [date(2025, 1, 1)] * 3,
"horizonte_anios": [0.0, 1.0, 5.0], "probabilidad": [0.01, 0.02, 0.05]})
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
+4 -3
View File
@@ -1,5 +1,5 @@
"""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.
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with, and
the rule that decides an output is already done; and the hashes of files and tables in `models.io.storage`.
Fixtures: none; each test builds its own small table or file.
"""
@@ -7,7 +7,8 @@ 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
from models.io.lineage import matches, registered_name
from models.io.storage import cohort_reference, file_sha256, require_match, table_sha256
def test_a_table_hashes_by_its_rows_not_its_metadata():
+7 -40
View File
@@ -4,11 +4,10 @@ code version every run records (`code_version`), and choosing the version to use
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.
logged model.
"""
import subprocess
from pathlib import Path
from importlib.metadata import version
import mlflow.pyfunc
import pandas as pd
@@ -16,8 +15,7 @@ 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.lineage import MODEL_SHA_TAG, MODELS_VERSION_TAG
from models.io.registry import registry
from models.io.tracking import TrainingRun
@@ -129,43 +127,12 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready):
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.
"""
def test_every_run_records_the_version_of_the_code(mlflow_tracking):
"""Pins down: a run is tagged with the installed `models` package's version, which a deployment without the
repository has too. Fails if the tag is dropped or renamed, or the version is read from anywhere else."""
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
assert MlflowClient().get_run(run.run_id).data.tags[MODELS_VERSION_TAG] == version("models")
def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking):
+74
View File
@@ -0,0 +1,74 @@
"""What this module covers: `models.io.storage`: a kit build read from the database and the same build read from its
exported file give the dataflow the same frame, each with its own reference, and a build that doesn't exist is named.
Fixtures: `frame`, a long frame of two members with one event after the cut-off; `kit_stand_ins` (conftest).
"""
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_SCHEMA
from models.io.storage import CohortFile, KitBuild
from models.steps.cohort_file import cohort_events
CUTOFF = date(2025, 12, 31)
def _row(pac_id, index, fecha, fuente_id):
return {"pac_id": pac_id, "fecha_indice": index, "fecha": fecha,
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "t",
"fuente_id": fuente_id}
@pytest.fixture
def frame():
"""Members 10 and 20; member 10 has an event after the cut-off, which no source may return."""
return pd.DataFrame([_row(10, date(2025, 1, 1), date(2025, 1, 1), "a"),
_row(20, date(2025, 2, 1), date(2025, 2, 1), "b"),
_row(10, date(2025, 1, 1), date(2026, 3, 1), "late")], columns=COHORT_SCHEMA.names)
def test_the_database_and_the_file_give_the_same_frame(frame, kit_stand_ins, tmp_path):
"""Pins down that the reading is interchangeable: the kit build read through the repositories and its exported
file are the same frame, so the dataflow can't tell them apart. Fails if one source cuts, orders or types the rows
differently."""
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
from_database = KitBuild("cacu", 3, cohorts=cohorts, timeline=timeline).frame()
population = frame[["pac_id", "fecha_indice"]].drop_duplicates()
exported = cohort_events(kit_stand_ins(frame, 3, CUTOFF)[1].read(), population, CUTOFF)
path = tmp_path / "3.parquet"
pq.write_table(pa.Table.from_pandas(exported, schema=COHORT_SCHEMA, preserve_index=False).replace_schema_metadata(
{"url": "cacu/cohorte_vigilancia", "armado_id": "3", "datos_as_of": CUTOFF.isoformat()}), path)
pd.testing.assert_frame_equal(from_database, CohortFile(path).frame())
assert "late" not in from_database["fuente_id"].tolist()
def test_a_kit_build_reads_its_members_up_to_its_cutoffs(frame, kit_stand_ins):
"""Pins down: the timeline is asked for the build's members, cut at its clinical date and, since this build has no
`conocida_hasta`, at no load cut-off (the lineage records when it was read); the reference names the build without
a file hash. Fails if the read takes everyone, loses the clinical cut-off, invents a load cut-off, or the reference
claims a hash it doesn't have."""
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
source = KitBuild("cacu", 3, cohorts=cohorts, timeline=timeline)
source.frame()
assert timeline.reads[-1]["patients"] == [10, 20] and timeline.reads[-1]["until"] == CUTOFF
assert timeline.reads[-1]["known_until"] is None and source.lineage()["read_at"]
assert source.lineage()["datos_as_of"] == "2025-12-31" and source.armado_id == 3
assert source.reference() == {"cohort.url": "cacu/cohorte_vigilancia", "cohort.source": "kit", "cohort.build": "3"}
def test_a_missing_kit_build_is_named(frame, kit_stand_ins):
"""Pins down: asking for a build the database doesn't have fails with its number before any read. Fails if it
reads an empty frame instead."""
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
with pytest.raises(LookupError, match="kit build 9"):
KitBuild("cacu", 9, cohorts=cohorts, timeline=timeline).frame()
+120
View File
@@ -0,0 +1,120 @@
"""What this module covers: `models.steps.model_fitting` run by a Hamilton driver built from that module alone, the
way a scenario's driver uses it: the temporal split, the classifier chosen by config, the fit and the metrics.
Fixtures: `labelled`, forty members with index dates one day apart, one categorical predictor (`resultado`: `A` is
always positive, `B` never) and `y`; `_driver` builds the driver with `classifier = "logistic"` unless told
otherwise, and `_run` executes nodes with the three required inputs.
"""
import ast
import inspect
from datetime import date, timedelta
import pandas as pd
import pytest
from hamilton import driver
from sklearn.metrics import brier_score_loss, roc_auc_score
from models.steps import model_fitting
PREDICTORS = ["resultado"]
@pytest.fixture
def labelled() -> pd.DataFrame:
"""Forty members, `pac_id` 1..40, index dates from 2025-01-01 one day apart in reverse `pac_id` order (so the
oldest is member 40). Members whose `pac_id` is divisible by 4 have `resultado` `A` and `y` 1, the rest `B`
and `y` 0."""
rows = [{"pac_id": n, "fecha_indice": date(2025, 1, 1) + timedelta(days=40 - n),
"resultado": "A" if n % 4 == 0 else "B", "y": int(n % 4 == 0)} for n in range(1, 41)]
return pd.DataFrame(rows)
def _driver(config: dict | None = None):
return driver.Builder().with_modules(model_fitting).with_config(
{"classifier": "logistic"} if config is None else config).build()
def _run(nodes: list[str], labelled: pd.DataFrame, config: dict | None = None, **inputs) -> dict:
required = {"labelled_members": labelled, "predictor_columns": PREDICTORS, "train_fraction": 0.75}
return _driver(config).execute(nodes, inputs={**required, **inputs})
def test_the_oldest_members_train_and_the_newest_test(labelled):
"""Pins down the temporal split: with 0.75, the 30 oldest index dates train and the 10 newest test, and every
member is in exactly one of them. Fails if the split shuffles, ignores the index date or loses rows."""
result = _run(["train_set", "test_set"], labelled)
train, test = result["train_set"], result["test_set"]
assert len(train) == 30 and len(test) == 10
assert train["fecha_indice"].max() < test["fecha_indice"].min()
assert sorted(train["pac_id"].tolist() + test["pac_id"].tolist()) == list(range(1, 41))
def test_the_driver_needs_only_the_members_the_predictors_and_the_fraction(labelled):
"""Pins down the dataflow's external inputs: the three required ones and `missing_data`, the routine record only
a scenario can write; `target_column`, `split_order`, `max_iter`, `calibration_bins` and `members_left_out` have
defaults. Fails if a node reads a setting from a global or the disk instead of taking it as an input, or if a new
input appears without a default."""
required = {v.name for v in _driver().list_available_variables()
if v.is_external_input and v.originating_functions and not _has_default(v)}
assert required == {"labelled_members", "missing_data", "predictor_columns", "train_fraction"}
def _has_default(variable) -> bool:
for function in variable.originating_functions:
parameter = inspect.signature(function).parameters.get(variable.name)
if parameter is not None and parameter.default is inspect.Parameter.empty:
return False
return True
def test_the_classifier_is_chosen_by_config(labelled):
"""Pins down `@config.when`: with `classifier = "logistic"` the prefit node is an unfitted logistic regression,
and without a known classifier there's no `prefit_classifier` to fit with. Fails if the classifier is built
inside `fitted_pipeline` again or the config key changes."""
prefit = _run(["prefit_classifier"], labelled)["prefit_classifier"]
assert type(prefit).__name__ == "LogisticRegression" and not hasattr(prefit, "coef_")
with pytest.raises(ValueError):
_run(["fitted_pipeline"], labelled, config={"classifier": "unknown"})
def test_fitting_leaves_the_prefit_nodes_unfitted(labelled):
"""Pins down that `fitted_pipeline` fits copies: the `encoder` and `prefit_classifier` values the driver computed
stay unfitted. Fails if the fit mutates them, which would leak one run's fit into anything else that reads them."""
result = _run(["encoder", "prefit_classifier", "fitted_pipeline"], labelled)
assert not hasattr(result["prefit_classifier"], "coef_")
assert not hasattr(result["encoder"], "transformers_")
assert hasattr(result["fitted_pipeline"].named_steps["classify"], "coef_")
def test_metrics_are_sklearn_s_on_the_test_set_under_the_names_mlflow_keeps(labelled):
"""Pins down `metrics`: AUC and Brier computed on the test set's `y` and probabilities, the sizes and rates, with
the keys training runs have always recorded. Fails if a metric is computed on the wrong set or a key is renamed
(a renamed key splits a model's history in MLflow)."""
result = _run(["metrics", "test_set", "test_probabilities"], labelled)
test, probabilities, metrics = result["test_set"], result["test_probabilities"], result["metrics"]
assert set(metrics) == {"auc", "brier", "n_train", "n_test", "positive_rate_train", "positive_rate_test",
"mean_probability_test"}
assert metrics["auc"] == pytest.approx(roc_auc_score(test["y"], probabilities))
assert metrics["brier"] == pytest.approx(brier_score_loss(test["y"], probabilities))
assert (metrics["n_train"], metrics["n_test"]) == (30, 10)
assert metrics["positive_rate_test"] == pytest.approx(test["y"].mean())
assert probabilities.name == "probabilidad" and probabilities.index.equals(test.index)
def test_an_unseen_category_scores_as_none_of_the_known_ones(labelled):
"""Pins down the encoder's `handle_unknown="ignore"`: a test member with a category training never saw still
gets a probability, between the two known categories'. Fails if the encoder raises on unknown categories."""
pipeline = _run(["fitted_pipeline"], labelled)["fitted_pipeline"]
a, b, c = pipeline.predict_proba(pd.DataFrame({"resultado": ["A", "B", "C"]}))[:, 1]
assert b < c < a
def test_no_node_reads_writes_or_logs():
"""Pins down that the module imports nothing that does I/O (MLflow, the registry, storage, tracking). Fails if a
node starts logging or registering again instead of leaving that to a saver."""
tree = ast.parse(inspect.getsource(model_fitting))
imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names}
imported |= {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)}
assert not {name for name in imported if name.split(".")[0] in {"mlflow", "persistance"}
or name.startswith("models.io")}
+32
View File
@@ -0,0 +1,32 @@
"""What this module covers: `models.annotations`: `@checked_frame` fails a node whose frame breaks its schema without
quoting the values.
Fixtures: none; each test builds a one-function graph with `ad_hoc_utils`.
"""
import pandas as pd
import pandera.pandas as pandera
import pytest
from hamilton import ad_hoc_utils, driver
from hamilton.data_quality.base import DataValidationError
from models.annotations import checked_frame
MEMBERS = pandera.DataFrameSchema({"pac_id": pandera.Column(int, pandera.Check.gt(0))}, name="members")
def test_a_failing_frame_check_names_columns_and_counts_not_values():
"""Pins down: `@checked_frame` stops the node and says which column and check failed and how often, without the
failing values, which are members' data. Fails if the message goes back to pandera's report of failure cases."""
@checked_frame(MEMBERS)
def members(cohort: pd.DataFrame) -> pd.DataFrame:
return cohort
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(members)).build()
with pytest.raises(DataValidationError) as failed:
dr.execute(["members"], inputs={"cohort": pd.DataFrame({"pac_id": [-48213, -48214, 7]})})
message = str(failed.value)
assert "pac_id" in message and "failed 2 time(s)" in message
assert "48213" not in message and "48214" not in message
+4 -5
View File
@@ -1,5 +1,5 @@
"""What this module covers: an exploratory notebook as an MLflow report (`models.steps.report`, `models.io.rendering`,
`models.io.tracking.find_run`/`record_report`, `models.pipelines.report_eda`) and `models report eda`: the content hash,
"""What this module covers: an exploratory notebook as an MLflow report (`models.reports.rendering`,
`models.io.tracking.find_run`/`record_report`, `models.reports.eda`) and `models report eda`: the content hash,
rendering with the build's file in the environment, one run per notebook and file, and its artifacts.
Fixtures: `fake_quarto`, a stand-in `quarto` (through `QUARTO_BIN`) that writes a page naming the kernel and the
@@ -19,9 +19,8 @@ import pytest
from mlflow import MlflowClient
from models.__main__ import main
from models.io.rendering import RenderError, render_notebook
from models.pipelines.report_eda import report_eda
from models.steps.report import notebook_sha256, without_outputs
from models.reports.eda import report_eda
from models.reports.rendering import RenderError, notebook_sha256, render_notebook, without_outputs
FAKE = '''#!{python}
import json, os, pathlib, sys
+26 -12
View File
@@ -1,6 +1,6 @@
"""What this module covers: storing an estimate file as a batch of risks (`models.steps.risks`,
`models.io.storage.store_risk_batch`, `models.pipelines.store_risks`) and the `models store` command: one risk per
member at the model's horizon, the batch's MLflow keys, no duplicate batch, and builds without a `cohorte_armado` row
member and horizon, the batch's MLflow keys, no duplicate batch, and builds without a `cohorte_armado` row
refused.
Fixtures: `cacu_db` (conftest), an empty CaCu schema on SQLite; `kit_build`, kit build 1 with members 1 to 3;
@@ -20,13 +20,13 @@ from models.pipelines.store_risks import store_estimate
from models.steps.risks import risk_rows
METADATA = {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "3", "mlflow_run_id": "run-a", "modelo_sha": "sha-a",
"desenlace": "cin2_12m", "horizonte_anios": "1.0", "cohort.url": "cacu/cohorte_vigilancia",
"desenlace": "cin2_12m", "cohort.url": "cacu/cohorte_vigilancia",
"cohort.source": "kit", "cohort.build": "1", "cohort.file_sha256": "f" * 64}
def _estimate(pac_ids=(1, 2, 3)):
return pd.DataFrame({"pac_id": list(pac_ids), "fecha_indice": [date(2025, 1, i) for i in pac_ids],
"probabilidad": [0.1 * i for i in pac_ids]})
def _estimate(pac_ids=(1, 2, 3), horizons=(1.0,)):
rows = [(i, date(2025, 1, i), h, round(0.1 * i + 0.01 * h, 2)) for i in pac_ids for h in horizons]
return pd.DataFrame(rows, columns=["pac_id", "fecha_indice", "horizonte_anios", "probabilidad"])
def _write(frame, path, **metadata):
@@ -65,19 +65,21 @@ def _stored():
return session.exec(select(EvaluacionRiesgoLote)).all(), session.exec(select(EvaluacionRiesgo)).all()
def test_each_member_becomes_one_risk_at_the_horizon():
"""Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member. Fails if the horizon is
dropped or the interval is filled with something the model didn't give."""
assert risk_rows(_estimate((1, 2)), 1.0) == [(1, 1.0, 0.1, None, None), (2, 1.0, 0.2, None, None)]
def test_each_row_becomes_one_risk_at_its_horizon():
"""Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member and horizon, the
horizon taken from the row. Fails if the horizon is dropped, taken from elsewhere, or the interval is filled with
something the model didn't give."""
assert risk_rows(_estimate((1, 2), horizons=(0.0, 3.0))) == [
(1, 0.0, 0.1, None, None), (1, 3.0, 0.13, None, None), (2, 0.0, 0.2, None, None), (2, 3.0, 0.23, None, None)]
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),
_estimate().rename(columns={"probabilidad": "p"})])
def test_a_malformed_estimate_stops_the_batch(frame):
"""Pins down: a member scored twice, a probability outside 0..1, or other columns stop the batch before anything is
written. Fails if any of them reaches the database."""
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, or other columns stop the batch
before anything is written. Fails if any of them reaches the database."""
with pytest.raises(ValueError):
risk_rows(frame, 1.0)
risk_rows(frame)
def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_file):
@@ -92,6 +94,18 @@ def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_fil
(1, 1.0, "preliminary", 1), (2, 1.0, "preliminary", 1), (3, 1.0, "preliminary", 1)]
def test_several_horizons_are_stored_in_one_batch(kit_build, tmp_path):
"""Pins down: an estimate with the prevalence and later horizons is one batch with a risk per member and horizon.
Fails if storing assumes one horizon per batch."""
path = _write(_estimate(horizons=(0.0, 1.0, 5.0)), tmp_path / "horizons.parquet")
store_estimate(path, "cacu")
batches, risks = _stored()
assert len(batches) == 1 and len(risks) == 9
assert sorted({r.horizonte_anios for r in risks}) == [0.0, 1.0, 5.0]
def test_storing_the_same_estimate_again_adds_nothing(kit_build, estimate_file, capsys):
"""Pins down: the command is idempotent: the second time it reports the existing batch. Fails if Persistance's
content check stops matching what this module sends."""