Merge pull request 'CaCu CIN2+ prototype, risk batches stored, report eda, cohorts list and show, pandera checks' (#5) from feature/model-proto into dev

Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/5
This commit was merged in pull request #5.
This commit is contained in:
2026-11-06 15:05:39 +00:00
22 changed files with 1050 additions and 97 deletions
+4 -1
View File
@@ -20,7 +20,10 @@ WebApi.
| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. Estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--armado N] [--version N]` (`estimate.py`); by default it uses 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. |
| `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`, `io/rendering.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 with Quarto 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. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). |
| `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. 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). |
| `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. |
+129 -7
View File
@@ -77,6 +77,46 @@ def _estimate_step(args: argparse.Namespace, path) -> int:
return 0
def _store_step(args: argparse.Namespace, estimate_path) -> int:
from models.pipelines.store_risks import store_estimate
try:
batch, written = store_estimate(estimate_path, args.domain)
except (LookupError, ValueError, FileNotFoundError) as error:
print(error, file=sys.stderr)
return 1
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
return 0
def _store(args: argparse.Namespace) -> int:
"""Stores an estimate file as a batch of risks in the domain's database."""
return _store_step(args, args.input)
def _report_eda(args: argparse.Namespace) -> int:
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
from pathlib import Path
from models.io.rendering import RenderError
from models.pipelines.report_eda import report_eda
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
return 1
notebook = Path(args.notebook) if args.notebook else (
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
try:
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
except RenderError as error:
print(error, file=sys.stderr)
return 1
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
return 0
def _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)):
@@ -104,10 +144,10 @@ def _promote_step(args: argparse.Namespace, version: str) -> int:
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate):
parser.error("name at least one step: --export, --train, --promote, --estimate")
if args.estimate and not args.output:
parser.error("--estimate needs --output")
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
parser.error("a prod run names its cohort build: --build (ML-03)")
if args.export and args.source == "dbt" and not args.manifest:
@@ -128,7 +168,7 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if code := _cohort_export(export):
return code
if not (args.train or args.promote or args.estimate):
return 0
return _store_step(args, args.output) if args.store else 0
if not (path := _cohort_file(args, model)):
return 1
@@ -148,7 +188,9 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
return 1
if args.promote and (code := _promote_step(args, version)):
return code
return _estimate_step(args, path) if args.estimate else 0
if args.estimate and (code := _estimate_step(args, path)):
return code
return _store_step(args, args.output) if args.store else 0
def _cohort_build(args: argparse.Namespace) -> int:
@@ -217,6 +259,53 @@ def _cohort_export(args: argparse.Namespace) -> int:
return 0
def _cohort_list(args: argparse.Namespace) -> int:
"""Prints the cohort's builds: dbt's from their files, the kit's from the database."""
from importlib import import_module
from persistance.settings import settings
from models.io.storage import cohorts_root, list_builds
url = f"{args.domain}/{args.cohort}"
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
except ValueError as error:
print(error, file=sys.stderr)
return 1
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohorte_repository
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
if not rows:
print(f"{url}: no builds", file=sys.stderr)
return 1
print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file")
for row in rows:
print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} "
f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}")
return 0
def _cohort_show(args: argparse.Namespace) -> int:
"""Prints one build's file, hash and lineage as JSON."""
import json
from importlib import import_module
from persistance.settings import settings
from models.io.storage import cohorts_root, describe_build
url = f"{args.domain}/{args.cohort}"
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
cohorts = import_module(f"persistance.{args.domain}").cohorte_repository if args.source == "kit" else None
described = describe_build(root, url, args.source, args.build, cohorts)
except (ValueError, LookupError) as error:
print(error, file=sys.stderr)
return 1
print(json.dumps(described, indent=2, ensure_ascii=False))
return 0
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if args.source == "dbt" and not args.manifest:
parser.error("--source dbt needs --manifest")
@@ -248,6 +337,19 @@ def build_parser() -> argparse.ArgumentParser:
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file")
listing.add_argument("domain", choices=["cacu", "cama", "tea"])
listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database")
listing.set_defaults(run=_cohort_list)
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
show.add_argument("domain", choices=["cacu", "cama", "tea"])
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
show.add_argument("--build", type=int, required=True, help="the build's number")
show.set_defaults(run=_cohort_show)
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
train.add_argument("domain", choices=["cacu", "cama", "tea"])
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
@@ -267,6 +369,25 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
report.set_defaults(run=lambda args: _show_help(report))
reports = report.add_subparsers(dest="action", metavar="<report>")
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
eda.add_argument("--notebook", help="the notebook; the scenario's notebooks/<scenario>/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
store.add_argument("domain", choices=["cacu", "cama", "tea"])
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
store.set_defaults(run=_store)
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
run.add_argument("domain", choices=["cacu", "cama", "tea"])
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
@@ -274,12 +395,13 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.set_defaults(run=lambda args: _run(run, args))
return parser
+7 -6
View File
@@ -6,7 +6,7 @@ import mlflow.pyfunc
import pyarrow as pa
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.contracts import ESTIMATE_COLUMNS
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
@@ -20,8 +20,8 @@ def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -
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; `modelo_sha` is copied when the version has
it, and isn't checked."""
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)
@@ -29,10 +29,11 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
if tuple(risks.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
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, **cohort}
"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)
+68 -25
View File
@@ -1,19 +1,25 @@
"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version.
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
No clinical meaning. `y` is 1 if any Bethesda result isn't `NORMAL`, and `days` runs from the index date to the first
abnormal result, or to the last result when `y` is 0. `days` is only known after the outcome, so the metrics say
nothing about performance.
`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with
no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet:
it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
nothing after them is used.
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
"""
import tomllib
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256
from models.io.registry import registry
@@ -21,7 +27,9 @@ from models.io.storage import read_cohort, read_metadata
from models.io.tracking import TrainingRun
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
NORMAL = "NORMAL"
PREDICTORS = ("bethesda", "vph", "vph_16_18")
MISSING = "(none)"
DAYS_PER_MONTH = 30.44
def cohort(cohort_path: str) -> pd.DataFrame:
@@ -42,16 +50,44 @@ def code_sha256() -> str:
return file_sha256(folder / "model.py", folder / "model.toml")
def prepare(cohort: pd.DataFrame) -> pd.DataFrame:
"""One row per member with a Bethesda result: `pac_id`, `fecha_indice`, `y`, `days`."""
results = cohort[cohort["tipo"] == "bethesda"].copy()
results["days"] = (pd.to_datetime(results["fecha"]) - pd.to_datetime(results["fecha_indice"])).dt.days
results["abnormal"] = results["valor_codigo"] != NORMAL
members = results.groupby(["pac_id", "fecha_indice"], as_index=False).agg(y=("abnormal", "any"), last=("days", "max"))
first_abnormal = results[results["abnormal"]].groupby("pac_id")["days"].min()
members["days"] = members["pac_id"].map(first_abnormal).fillna(members["last"]).astype(int)
members["y"] = members["y"].astype(int)
return members[["pac_id", "fecha_indice", "y", "days"]]
def cutoff(lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(lineage["datos_as_of"])
def predictors(cohort: pd.DataFrame) -> pd.DataFrame:
"""One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none."""
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])]
sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample")
results = cohort.merge(sample, left_on="pac_id", right_index=True)
results = results[results["fuente_id"] == results["sample"]]
genotype = results["tipo"] == "vph_genotipo_16_18"
results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"})
results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"})
wide = results[results["tipo"].isin(PREDICTORS)].pivot_table(
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
wide = wide.reindex(columns=list(PREDICTORS))
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
{name: MISSING for name in PREDICTORS})
def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame:
"""One row per member: `y`, and `known`, whether the window is complete or the event already happened."""
window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH
days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window)
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int)
follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
members["known"] = (members["y"] == 1) | (follow_up >= window)
return members[["pac_id", "y", "known"]]
def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame:
"""The members whose outcome is known, with their predictors and `y`."""
labelled = predictors.merge(outcome, on="pac_id")
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
def split(prepare: pd.DataFrame) -> dict:
@@ -69,33 +105,38 @@ def test(split: dict) -> pd.DataFrame:
return split["test"]
def fit(train: pd.DataFrame) -> LogisticRegression:
return LogisticRegression().fit(train[["days"]], train["y"])
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: LogisticRegression, test: pd.DataFrame) -> pd.Series:
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[["days"]])[:, 1], index=test.index, name="probabilidad")
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_test": float(test["y"].mean())}
"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())}
class Cin2Logistic(mlflow.pyfunc.PythonModel):
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`."""
"""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: LogisticRegression):
def __init__(self, fitted: Pipeline):
self.fitted = fitted
def predict(self, context, model_input, params=None):
members = prepare(model_input)
members = predictors(model_input)
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str,
def registered_model(fit: Pipeline, evaluate: 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."""
@@ -105,7 +146,9 @@ def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, coh
cohorte_armado_id=armado_id, cohort=cohort)
run.log_model(Cin2Logistic(fit))
run.finish(metrics=evaluate, hyperparameters={
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256})
"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
+8 -2
View File
@@ -2,6 +2,12 @@ domain = "cacu"
scenario = "cin2_logistic"
cohort = "cacu/cohorte_vigilancia"
train_fraction = 0.7
# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the
# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a
# complete window; 12 months leaves 5,231 known members, 162 with the event.
outcome_window_months = 12
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
description = """
Modelo de prueba de la cadena de entrenamiento, sin significado clínico. Los días se conocen solo después del \
desenlace, así que sus métricas no dicen nada sobre su desempeño."""
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."""
+37 -1
View File
@@ -4,6 +4,7 @@
every row.
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
@@ -15,6 +16,7 @@ from datetime import date
from typing import NamedTuple, Protocol, runtime_checkable
import pandas as pd
import pandera.pandas as pandera
import pyarrow as pa
COHORT_SCHEMA = pa.schema([
@@ -26,11 +28,45 @@ COHORT_SCHEMA = pa.schema([
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
# schema says which columns and types; these say what a valid row and a valid file are.
COHORT_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"fecha": pandera.Column(nullable=False),
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"fuente_tabla": pandera.Column(str, nullable=False),
"fuente_id": pandera.Column(str, nullable=False)},
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
error="a member has more than one index date"),
name="cohort build")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
strict=True, ordered=True, name="estimate")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s."""
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
`COHORT_FRAME`."""
class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
try:
return schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
class CohortDefinitionError(ValueError):
+4 -3
View File
@@ -48,9 +48,10 @@ def model_sha(model_dir: str | Path) -> str:
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. A kit build's number is its `armado_id`."""
source = metadata.get("producer", "kit")
build = metadata["armado_id"] if source == "kit" else metadata["build"]
`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}
+49
View File
@@ -0,0 +1,49 @@
"""Renders a notebook to a self-contained HTML page with Quarto, running it first.
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
first and the source folder is left untouched.
"""
import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
QUARTO_ENV = "QUARTO_BIN"
class RenderError(RuntimeError):
"""Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed."""
def quarto() -> str:
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
if not found:
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
return found
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
kernel: str | None = None) -> Path:
"""Runs and renders `notebook` (its JSON) as `name`, and writes the page to `output`."""
command = quarto()
if kernel:
notebook = {**notebook, "metadata": {**notebook.get("metadata", {}),
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
with tempfile.TemporaryDirectory(prefix="render-") as folder:
source = Path(folder) / f"{name}.ipynb"
source.write_text(json.dumps(notebook, ensure_ascii=False))
done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
cwd=folder, env={**os.environ, **(env or {})}, capture_output=True, text=True)
page = source.with_suffix(".html")
if done.returncode or not page.exists():
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
output.parent.mkdir(parents=True, exist_ok=True)
shutil.move(page, output)
return output
+50 -4
View File
@@ -1,11 +1,12 @@
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
manifest, and a domain's Persistance repositories.
manifest, a domain's Persistance repositories, and the batches of risks they store.
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
repository is used, so a model folder reading its cohort file never loads the database layer.
"""
import hashlib
import importlib
import json
import os
@@ -18,8 +19,8 @@ import pyarrow as pa
import pyarrow.parquet as pq
from sqlalchemy.engine import make_url
from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
CohortQueries, ExclusionRule)
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
CohortFileError, CohortQueries, ExclusionRule, check_frame)
def cohorts_root(database_url: str) -> Path:
@@ -64,12 +65,50 @@ def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path
return path
def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
"""One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and,
with `cohorts` (the domain's `cohorte_repository`), the kit's builds and whether each has its file. Without
`cohorts` only files are read, never the database."""
rows = []
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
path = dbt_build_path(root, url, number)
lineage = read_metadata(path)
rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"),
"n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)})
for build in (cohorts.builds(url) if cohorts is not None else []):
path = cohort_path(root, url, build.armado_id)
rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(),
"n_members": str(build.n_miembros), "created": build.armado_en.isoformat(),
"file": str(path) if path.exists() else None})
return rows
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
without a file is described from `cohorts` (the domain's `cohorte_repository`). `LookupError` if there's no such
build."""
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
if path.exists():
lineage = read_metadata(path)
for key in ("parametros", "rules", "attrition"):
if lineage.get(key):
lineage[key] = json.loads(lineage[key])
digest = hashlib.sha256(path.read_bytes()).hexdigest()
return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage}
stored = cohorts.build(build) if source == "kit" and cohorts is not None else None
if stored is None or stored.url != url:
raise LookupError(f"no {source} build {build} of {url}")
return {"source": "kit", "build": build, "file": None, "file_sha256": None,
"lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(),
"n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}}
def read_cohort(path: str | Path) -> pd.DataFrame:
"""The build's rows, after checking the file's schema without reading them."""
schema = pq.read_schema(path)
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
return pd.read_parquet(path)
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
def write_once(table: pa.Table, path: Path) -> None:
@@ -133,6 +172,13 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
"""Writes a batch of risks for a kit build through the domain's `cohorte_repository`: its `lote_id` and whether it's
new. The only write the pipelines make to the database; risks of anyone outside the build are refused."""
cohorts = importlib.import_module(f"persistance.{domain}").cohorte_repository
return cohorts.guardar_lote(armado_id, provenance, outcome, rows)
def resolve_repository(domain: str, entity: str):
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
+38 -7
View File
@@ -11,6 +11,9 @@ process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
their own, and `find_run` finds one already made from the same inputs.
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
@@ -29,7 +32,7 @@ import mlflow.pyfunc
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
@@ -70,6 +73,39 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str |
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
def experiment_id(client: MlflowClient, name: str) -> str:
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
experiment = client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
found = client.get_experiment_by_name(experiment)
if found is None:
return None
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
return run.info.run_id
return None
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
try:
for kind, path in files.items():
log_artifact_file(client, run.info.run_id, kind, path)
except Exception:
client.set_terminated(run.info.run_id, "FAILED")
raise
client.set_terminated(run.info.run_id, "FINISHED")
return run.info.run_id
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs name the cohort build they were trained on, so their metrics trace
@@ -112,12 +148,7 @@ class TrainingRun:
self.client.set_tag(self.run_id, tag, value)
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
return experiment_id(self.client, registered_name(self.domain, self.scenario))
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
+48
View File
@@ -0,0 +1,48 @@
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
were already reported together are not rendered again.
The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the
environment it inherits.
"""
import json
import tempfile
from pathlib import Path
from mlflow import MlflowClient
from models.io.lineage import cohort_reference, file_sha256, registered_name
from models.io.rendering import render_notebook
from models.io.storage import read_metadata
from models.io.tracking import find_run, record_report
from models.steps.report import notebook_sha256, without_outputs
COHORT_FILE_ENV = "COHORT_FILE"
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
def report_experiment(domain: str, scenario: str, notebook: Path) -> str:
return f"{registered_name(domain, scenario)}/{notebook.stem}"
def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str,
kernel: str | None = None) -> tuple[str, bool]:
"""Returns the report's run id and whether it was rendered now."""
notebook_path, cohort_path = Path(notebook_path), Path(cohort_path)
notebook = json.loads(notebook_path.read_text())
experiment = report_experiment(domain, scenario, notebook_path)
tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook),
**cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))}
client = MlflowClient()
if existing := find_run(client, experiment, tags):
return existing, False
with tempfile.TemporaryDirectory(prefix="report-") as folder:
page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html",
env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel)
source = Path(folder) / notebook_path.name
source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1))
return record_report(client, experiment, tags, {"report": page, "notebook": source}), True
+31
View File
@@ -0,0 +1,31 @@
"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`).
The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`,
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome and its horizon, and the cohort build it scored. A batch
points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same
estimate again adds nothing: Persistance finds the batch by its content.
"""
from pathlib import Path
import pandas as pd
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
from models.io.storage import read_metadata, store_risk_batch
from models.steps.risks import risk_rows
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
REQUIRED = (*PROVENANCE, "desenlace", "horizonte_anios", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
"""Returns the batch's `lote_id` and whether it was written now."""
metadata = read_metadata(estimate_path)
if missing := [key for key in REQUIRED if not metadata.get(key)]:
raise ValueError(f"{estimate_path} lacks {missing}: write it with `python -m models estimate`")
if metadata[COHORT_SOURCE_TAG] != "kit":
raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, "
"which has no row in cohorte_armado for its batch to point to")
rows = risk_rows(pd.read_parquet(estimate_path), float(metadata["horizonte_anios"]))
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
metadata["desenlace"], rows)
+3 -1
View File
@@ -5,7 +5,7 @@ from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
from models.io.lineage import table_sha256
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
@@ -36,5 +36,7 @@ def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
"""The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written."""
check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}")
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
+21
View File
@@ -0,0 +1,21 @@
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
import copy
import hashlib
import json
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
+13
View File
@@ -0,0 +1,13 @@
"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`."""
import pandas as pd
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
"""One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a
member scored twice or a probability outside 0..1 stops the batch."""
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
return [(int(pac_id), float(horizon_years), float(probability), None, None)
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
+3 -1
View File
@@ -13,11 +13,13 @@ dependencies = [
"pandas>=2.0",
"pyarrow>=15",
"scikit-learn>=1.4",
# The values of the cohort and estimate files (`models.io.contracts`).
"pandera>=0.20",
]
[project.optional-dependencies]
# Only needed to read back a checkpoint's own metadata (opset, producer) in
# models.io.export.inspect_onnx_metadata — writing/logging a checkpoint never
# models.io.tracking.inspect_onnx_metadata — writing/logging a checkpoint never
# requires it, see that module's docstring.
export = [
"onnx>=1.15",
+82 -38
View File
@@ -1,10 +1,11 @@
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
split, that training on a build's file registers a version with its lineage, and the `models train` and
`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none.
"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members
whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on
a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run`
commands over it, repeating no step.
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
SQLite-backed MLflow.
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
from datetime import date, datetime, timedelta, timezone
@@ -22,88 +23,132 @@ from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
from models.io.registry import PRODUCTION_ALIAS, registry
CUTOFF = date(2027, 6, 30)
def _row(pac_id, index, days, valor, tipo="bethesda"):
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion")
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": f"{pac_id}-{tipo}-{days}"}
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical",
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60):
"""The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given."""
sample = f"S{pac_id}"
rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample),
_row(pac_id, index, 7, "vph", vph, sample)]
if biopsy:
rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy))
return rows
@pytest.fixture
def cohort_frame():
"""Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row
each, which the outcome must ignore."""
"""Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members:
NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore."""
rows = []
for pac_id in range(1, 21):
index = date(2025, 1, 1) + timedelta(days=pac_id)
rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")]
rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL"))
if pac_id % 2:
rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG")
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"),
_row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")]
return pd.DataFrame(rows, columns=SCHEMA.names)
def _write(frame, path, armado_id):
def _write(frame, path, metadata):
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
path.parent.mkdir(parents=True, exist_ok=True)
pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata}
pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path)
return path
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 7's file."""
return _write(cohort_frame, tmp_path / "7.parquet", 7)
return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7})
@pytest.fixture
def exported(cohort_frame, tmp_path, monkeypatch):
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
_write(cohort_frame, folder / "7.parquet", 7)
_write(cohort_frame, folder / "12.parquet", 12)
_write(cohort_frame, folder / "7.parquet", {"armado_id": 7})
_write(cohort_frame, folder / "12.parquet", {"armado_id": 12})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder
def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame):
"""Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when
`y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes."""
prepared = model.prepare(cohort_frame).set_index("pac_id")
def test_predictors_are_the_index_sample_results(cohort_frame):
"""Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a
result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is
taken, or a missing result becomes NaN, which the encoder would reject."""
found = model.predictors(cohort_frame).set_index("pac_id")
assert len(prepared) == 20
assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30]
assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300]
assert len(found) == 20
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"]
def test_first_abnormal_result_sets_days_when_there_are_several():
"""Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails
if `days` takes the last abnormal result or the first row."""
def test_the_genotype_is_read_from_its_number():
"""Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails
if the genotype is read from `valor_codigo`, which is empty for it."""
index = date(2025, 1, 1)
frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")])
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.prepare(frame).loc[0, "days"] == 40
assert model.predictors(frame).loc[0, "vph_16_18"] == "POSITIVO"
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
("LIEAG", 400, 0)])
def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
"""Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if
a lower grade counts, or a biopsy after the window does."""
frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day),
columns=SCHEMA.names)
assert model.outcome(frame, CUTOFF).loc[0, "y"] == expected
def test_a_member_without_a_complete_window_is_scored_but_not_trained_on():
"""Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out
of `prepare`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives,
which biases the risk down."""
late = date(2027, 3, 1)
frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS",
biopsy_day=30), columns=SCHEMA.names)
outcome = model.outcome(frame, CUTOFF).set_index("pac_id")
assert outcome["known"].tolist() == [False, True]
assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2]
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
is random or follows another column."""
parts = model.split(model.prepare(cohort_frame))
parts = model.split(model.prepare(model.predictors(cohort_frame), model.outcome(cohort_frame, CUTOFF)))
assert (len(parts["train"]), len(parts["test"])) == (14, 6)
assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min()
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that
it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or
if the driver stops reaching `registered_model`."""
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's
window and the note that it's a prototype, and an artifact that holds `predictors`, so it takes the long frame. Fails
if any is lost, or if the driver stops reaching `registered_model`."""
version = train(cohort_file)
resolved = registry.resolve("cacu", "cin2_logistic", version)
stored = registry.get("cacu", "cin2_logistic", version)
run = registry.client.get_run(stored.run_id).data
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
assert "sin significado clínico" in stored.description
assert "Prototipo" in stored.description and run.params["outcome_window_months"] == "12"
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort_sha256"]) == 64
@@ -239,7 +284,7 @@ def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
assert main([*RUN, "--train", "--armado", "7"]) == 0
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
frame = pd.read_parquet(exported / "12.parquet")
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12)
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12})
assert main([*RUN, "--train", "--armado", "12"]) == 0
assert len(_versions()) == 3
@@ -300,8 +345,7 @@ def dbt_exported(cohort_frame, tmp_path, monkeypatch):
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
path = folder / f"{number}.parquet"
path.parent.mkdir(parents=True, exist_ok=True)
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path)
_write(frame, path, {"build": number, "producer": "dbt"})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder
+95
View File
@@ -0,0 +1,95 @@
"""What this module covers: listing and describing a cohort's builds (`models.io.storage.list_builds`,
`describe_build`) and the `models cohorts list` and `cohorts show` commands.
Fixtures: `root`, a cohorts folder with dbt builds 1 and 2 and kit build 7's file; `kit`, a stand-in of the cohort
repository with kit builds 7 (exported) and 8 (not exported).
"""
import json
from datetime import date, datetime, timezone
from types import SimpleNamespace
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.__main__ import main
from models.io.storage import cohort_path, dbt_build_path, describe_build, list_builds
URL = "cacu/cohorte_vigilancia"
ATTRITION = [{"step": "all_patients", "n": 3, "excluded": None}, {"step": "indexed", "n": 2, "excluded": 1}]
def _file(path, **metadata):
path.parent.mkdir(parents=True, exist_ok=True)
pq.write_table(pa.table({"pac_id": [1]}).replace_schema_metadata({k: str(v) for k, v in metadata.items()}), path)
@pytest.fixture
def root(tmp_path):
for number in (1, 2):
_file(dbt_build_path(tmp_path, URL, number), producer="dbt", build=number, datos_as_of="2026-12-31",
n_members=2, built_at=f"2026-11-0{number}T00:00:00+00:00", rules=json.dumps(["prior_event"]),
parametros=json.dumps({"cutoff": "2026-12-31"}), attrition=json.dumps(ATTRITION))
_file(cohort_path(tmp_path, URL, 7), producer="kit", armado_id=7, datos_as_of="2026-12-31", n_members=2)
return tmp_path
def _kit_build(armado_id):
return SimpleNamespace(armado_id=armado_id, url=URL, version="0.2.0", datos_as_of=date(2026, 12, 31), n_miembros=2,
huella="h", armado_en=datetime(2026, 10, armado_id, tzinfo=timezone.utc))
@pytest.fixture
def kit():
builds = {8: _kit_build(8), 7: _kit_build(7)}
return SimpleNamespace(builds=lambda url: list(builds.values()) if url == URL else [], build=builds.get)
def test_both_sources_are_listed_newest_first_with_their_files(root, kit):
"""Pins down: dbt's builds come from their files, newest first, and the kit's from the repository, each saying
whether its file exists. Fails if a source is dropped, the order is by name, or an unexported build shows a file."""
rows = list_builds(root, URL, kit)
assert [(r["source"], r["build"]) for r in rows] == [("dbt", 2), ("dbt", 1), ("kit", 8), ("kit", 7)]
assert rows[2]["file"] is None and rows[3]["file"].endswith("7.parquet")
assert rows[0]["created"] == "2026-11-02T00:00:00+00:00"
def test_without_the_repository_only_files_are_read(root):
"""Pins down: listing dbt's builds needs no database. Fails if `list_builds` reaches for the kit's builds anyway."""
assert [r["source"] for r in list_builds(root, URL)] == ["dbt", "dbt"]
def test_a_dbt_build_is_described_with_its_lineage_decoded(root):
"""Pins down: `describe_build` gives the file, its hash, and the parameters, rules and attrition as JSON values,
not strings. Fails if the hash is missing or the lineage stays encoded."""
described = describe_build(root, URL, "dbt", 2)
assert len(described["file_sha256"]) == 64
assert described["lineage"]["attrition"] == ATTRITION and described["lineage"]["rules"] == ["prior_event"]
assert described["lineage"]["parametros"] == {"cutoff": "2026-12-31"}
def test_an_unexported_kit_build_is_described_from_the_database(root, kit):
"""Pins down: a kit build without a file still has its lineage, from the repository; an unknown build is a
`LookupError`. Fails if an unexported build is reported as missing, or a missing one as empty."""
described = describe_build(root, URL, "kit", 8, kit)
assert described["file"] is None and described["lineage"]["n_members"] == "2"
with pytest.raises(LookupError):
describe_build(root, URL, "kit", 9, kit)
with pytest.raises(LookupError):
describe_build(root, URL, "dbt", 9)
def test_the_commands_print_the_dbt_builds(root, monkeypatch, capsys):
"""Pins down: `cohorts list --source dbt` and `cohorts show` work from the files alone. Fails if either opens the
database for dbt's builds, or `show` prints something other than JSON."""
monkeypatch.setenv("COHORTS_DIR", str(root))
assert main(["cohorts", "list", "cacu", "cohorte_vigilancia", "--source", "dbt"]) == 0
listed = capsys.readouterr().out
assert "dbt/2.parquet" in listed and "dbt/1.parquet" in listed
assert main(["cohorts", "show", "cacu", "cohorte_vigilancia", "--build", "1"]) == 0
assert json.loads(capsys.readouterr().out)["build"] == 1
+75
View File
@@ -0,0 +1,75 @@
"""What this module covers: the value checks of the cohort and estimate files (`COHORT_FRAME`, `ESTIMATE_FRAME`,
`check_frame` in `models.io.contracts`), and that reading a cohort file and building one apply them.
Fixtures: none; `_events` makes a valid two-member frame and each test breaks one rule.
"""
from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, ESTIMATE_FRAME, CohortFileError, EstimateError,
check_frame)
from models.io.storage import read_cohort
from models.steps.cohort_file import cohort_table
def _events(**changes):
frame = pd.DataFrame({"pac_id": [1, 1, 2], "fecha_indice": [date(2025, 1, 1)] * 2 + [date(2025, 2, 1)],
"fecha": [date(2025, 1, 1), date(2025, 3, 1), date(2025, 2, 1)],
"conocida_en": [datetime(2025, 4, 1, tzinfo=timezone.utc)] * 3,
"clase": ["procedimiento", "medicion", "procedimiento"],
"tipo": ["citologia", "bethesda", "citologia"], "codigo": ["c", "b", "c"],
"valor_codigo": [None, "NORMAL", None], "valor_numerico": [None, None, None],
"fuente_tabla": ["citologiacervical"] * 3, "fuente_id": ["a", "a", "b"]})
for column, (row, value) in changes.items():
frame.loc[row, column] = value
return frame
def test_a_valid_build_passes():
"""Pins down: a well-formed frame comes back unchanged. Fails if a check rejects valid data, which would stop every
export and training."""
assert check_frame(COHORT_FRAME, _events(), CohortFileError, "test").equals(_events())
@pytest.mark.parametrize("changes, check", [
({"fecha_indice": (1, date(2025, 1, 5))}, "more than one index date"),
({"pac_id": (2, 0)}, "greater_than"),
({"fecha": (0, None)}, "not_nullable"),
({"tipo": (1, "")}, "str_length"),
])
def test_a_broken_build_names_what_failed(changes, check):
"""Pins down: two index dates for a member, a non-positive id, a missing date or an empty type are refused, and
the error names the check. Fails if a broken file reaches a model, where it would train on wrong rows."""
with pytest.raises(CohortFileError, match=check):
check_frame(COHORT_FRAME, _events(**changes), CohortFileError, "test")
def test_reading_and_building_a_file_apply_the_checks(tmp_path):
"""Pins down: `read_cohort` refuses a file whose rows break `COHORT_FRAME`, and `cohort_table` refuses to build
one. Fails if either path skips the check."""
broken = _events(fecha_indice=(1, date(2025, 1, 5)))
path = tmp_path / "1.parquet"
pq.write_table(pa.Table.from_pandas(broken, schema=COHORT_SCHEMA, preserve_index=False), path)
with pytest.raises(CohortFileError):
read_cohort(path)
with pytest.raises(CohortFileError):
cohort_table(broken, {"build": 1})
@pytest.mark.parametrize("estimate", [
pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "probabilidad": [0.1, 0.2]}),
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [1.2]}),
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [0.1], "extra": [1]}),
pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "probabilidad": [0.1]}),
])
def test_an_estimate_is_one_probability_per_member_in_its_columns(estimate):
"""Pins down: a member twice, a probability outside 0..1, an extra column or another column order are refused.
Fails if a malformed output can be written or stored as risks."""
with pytest.raises(EstimateError):
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
+16 -1
View File
@@ -7,7 +7,7 @@ Fixtures: none; each test builds its own small table or file.
import pyarrow as pa
import pytest
from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256
from models.io.lineage import cohort_reference, file_sha256, matches, registered_name, require_match, table_sha256
def test_a_table_hashes_by_its_rows_not_its_metadata():
@@ -47,3 +47,18 @@ def test_a_mismatch_is_refused_with_both_sides():
def test_models_are_registered_as_domain_and_scenario():
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
@pytest.mark.parametrize("metadata, expected", [
({"url": "u", "producer": "dbt", "build": "4"}, ("dbt", "4")),
({"url": "u", "producer": "kit", "armado_id": "2"}, ("kit", "2")),
({"url": "u", "producer": "kit build, timeline from dbt view", "armado_id": "1"}, ("kit", "1")),
({"url": "u", "armado_id": "3"}, ("kit", "3")),
])
def test_a_file_is_dbts_only_when_its_producer_says_dbt(metadata, expected):
"""Pins down: a cohort file's source is dbt only for `producer: dbt`; any other producer, or none, is a kit build
numbered by `armado_id`. Fails if an older kit file with a descriptive producer is read as dbt's and loses its
`armado_id`."""
reference = cohort_reference(metadata, "f" * 64)
assert (reference["cohort.source"], reference["cohort.build"]) == expected
+148
View File
@@ -0,0 +1,148 @@
"""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,
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
`COHORT_FILE` it was given, or fails when the notebook says so; `notebook`, a two-cell notebook with outputs;
`cohort`, a dbt build's file with its metadata; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
import json
import os
import stat
import sys
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
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
FAKE = '''#!{python}
import json, os, pathlib, sys
source = pathlib.Path(sys.argv[2])
notebook = json.loads(source.read_text())
if "fail" in json.dumps(notebook["cells"]):
sys.exit("a cell raised")
kernel = notebook["metadata"]["kernelspec"]["name"]
source.with_suffix(".html").write_text(f"<html>kernel={{kernel}} cohort={{os.environ.get('COHORT_FILE')}}</html>")
'''
@pytest.fixture
def fake_quarto(tmp_path, monkeypatch):
path = tmp_path / "quarto"
path.write_text(FAKE.format(python=sys.executable))
path.chmod(path.stat().st_mode | stat.S_IEXEC)
monkeypatch.setenv("QUARTO_BIN", str(path))
return path
def _notebook(source="print(1)"):
return {"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# EDA"]},
{"cell_type": "code", "metadata": {}, "execution_count": 3, "source": [source],
"outputs": [{"output_type": "stream", "name": "stdout", "text": ["1\n"]}]}],
"metadata": {"kernelspec": {"name": "isssteleon-webapi", "display_name": "k", "language": "python"}},
"nbformat": 4, "nbformat_minor": 5}
@pytest.fixture
def notebook(tmp_path):
path = tmp_path / "notebooks" / "01_eda.ipynb"
path.parent.mkdir()
path.write_text(json.dumps(_notebook()))
return path
def _cohort(path, build):
path.parent.mkdir(parents=True, exist_ok=True)
table = pa.table({"pac_id": [1, 2]})
pq.write_table(table.replace_schema_metadata({"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": str(build)}), path)
return path
@pytest.fixture
def cohort(tmp_path):
return _cohort(tmp_path / "cohorts" / "dbt" / "1.parquet", 1)
def test_the_hash_follows_the_sources_not_the_outputs():
"""Pins down: running a notebook again (new outputs, counts) keeps its hash; editing a cell changes it. Fails if
outputs enter the hash, which would make every rendering a new report."""
ran_again = _notebook()
ran_again["cells"][1].update(outputs=[], execution_count=9)
assert notebook_sha256(ran_again) == notebook_sha256(_notebook())
assert notebook_sha256(_notebook("print(2)")) != notebook_sha256(_notebook())
assert without_outputs(_notebook())["cells"][1]["outputs"] == []
def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path):
"""Pins down: the page is rendered with the extra environment (the build's file) and with `kernel` when given.
Fails if either is lost on the way to Quarto."""
page = render_notebook(_notebook(), "01_eda", tmp_path / "out" / "01_eda.html", env={"COHORT_FILE": "/x.parquet"},
kernel="models")
assert page.read_text() == "<html>kernel=models cohort=/x.parquet</html>"
def test_a_failing_notebook_or_missing_quarto_is_a_render_error(fake_quarto, tmp_path, monkeypatch):
"""Pins down: a cell that raises, and Quarto not being installed, end as `RenderError` with the reason. Fails if a
broken report is logged or the error is a bare `FileNotFoundError`."""
with pytest.raises(RenderError, match="a cell raised"):
render_notebook(_notebook("fail"), "01_eda", tmp_path / "page.html")
monkeypatch.setenv("QUARTO_BIN", "")
monkeypatch.setenv("PATH", str(tmp_path / "empty"))
with pytest.raises(RenderError, match="isn't installed"):
render_notebook(_notebook(), "01_eda", tmp_path / "page.html")
def test_a_report_is_a_run_of_the_notebooks_experiment_with_its_page(fake_quarto, notebook, cohort, mlflow_tracking):
"""Pins down: the run is in `<domain>-<scenario>/<notebook>`, tagged with the notebook's hash and the build's file,
and holds the page (rendered on that file) and the notebook without outputs. Fails if the page or the source is
missing, or the run can't be traced to its inputs."""
run_id, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
client = MlflowClient()
run = client.get_run(run_id)
assert written and client.get_experiment(run.info.experiment_id).name == "cacu-cin2_logistic/01_eda"
assert run.data.tags["notebook.sha256"] == notebook_sha256(_notebook())
assert (run.data.tags["cohort.source"], run.data.tags["cohort.build"]) == ("dbt", "1")
assert sorted(a.path for a in client.list_artifacts(run_id)) == ["notebook", "report"]
page = Path(client.download_artifacts(run_id, "report/01_eda.html")).read_text()
assert str(cohort.resolve()) in page
source = json.loads(Path(client.download_artifacts(run_id, "notebook/01_eda.ipynb")).read_text())
assert source["cells"][1]["outputs"] == []
def test_the_same_notebook_and_file_are_reported_once(fake_quarto, notebook, cohort, mlflow_tracking, tmp_path):
"""Pins down: reporting again reuses the run; an edited notebook or another build's file makes a new one. Fails if
the check ignores either input, or renders every time."""
first, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
again, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
other_build, _ = report_eda(notebook, _cohort(tmp_path / "cohorts" / "dbt" / "2.parquet", 2), "cacu", "cin2_logistic")
notebook.write_text(json.dumps(_notebook("print(2)")))
edited, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
assert again == first and not written
assert len({first, other_build, edited}) == 3
def test_the_command_reports_on_the_latest_dbt_build(fake_quarto, notebook, tmp_path, monkeypatch, mlflow_tracking, capsys):
"""Pins down: `models report eda` takes dbt's latest exported build by default and the notebook given. Fails if it
reads the kit's builds by default, or ignores `--notebook`."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
_cohort(folder / "1.parquet", 1)
_cohort(folder / "2.parquet", 2)
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
assert main(["report", "eda", "cacu", "cin2_logistic", "--notebook", str(notebook)]) == 0
assert "reported" in capsys.readouterr().out
run = MlflowClient().search_runs([MlflowClient().get_experiment_by_name("cacu-cin2_logistic/01_eda").experiment_id])[0]
assert run.data.tags["cohort.build"] == "2"
+121
View File
@@ -0,0 +1,121 @@
"""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
refused.
Fixtures: `cacu_db` (conftest), an empty CaCu schema on SQLite; `kit_build`, kit build 1 with members 1 to 3;
`estimate_file`, an estimate of those members with the metadata `models estimate` writes.
"""
from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from sqlmodel import select
from models.__main__ import main
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",
"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 _write(frame, path, **metadata):
table = pa.Table.from_pandas(frame, preserve_index=False)
pq.write_table(table.replace_schema_metadata({**table.schema.metadata, **METADATA, **metadata}), path)
return path
@pytest.fixture
def kit_build(cacu_db):
"""Kit build 1 of the surveillance cohort, with members 1, 2 and 3 (and their `persona` rows)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, Persona
from persistance.db import get_cacu_session
with get_cacu_session() as session:
session.add_all(Persona(pac_id=i, pac_id_hospital=f"H{i}") for i in (1, 2, 3))
session.add(CohorteArmado(armado_id=1, url="cacu/cohorte_vigilancia", version="1", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="h", marco_sha="m", n_miembros=3,
armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)))
session.add_all(CohorteMiembro(armado_id=1, pac_id=i, fecha_indice=date(2025, 1, i), indice_fuente_tabla="t",
indice_fuente_id=str(i)) for i in (1, 2, 3))
session.commit()
return 1
@pytest.fixture
def estimate_file(tmp_path):
return _write(_estimate(), tmp_path / "estimate.parquet")
def _stored():
from core.cacu.indicadores.models import EvaluacionRiesgo, EvaluacionRiesgoLote
from persistance.db import get_cacu_session
with get_cacu_session() as session:
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)]
@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."""
with pytest.raises(ValueError):
risk_rows(frame, 1.0)
def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_file):
"""Pins down: the batch points to the kit build and to the MLflow version and run, holds the outcome, and its risks
are preliminary version 1 at the horizon. Fails if a key is lost or a risk is stored at another horizon."""
batch, written = store_estimate(estimate_file, "cacu")
batches, risks = _stored()
assert written and [b.lote_id for b in batches] == [batch]
assert (batches[0].armado_id, batches[0].modelo_version, batches[0].mlflow_run_id, batches[0].desenlace) == (1, "3", "run-a", "cin2_12m")
assert sorted((r.pac_id, r.horizonte_anios, r.estado, r.version) for r in risks) == [
(1, 1.0, "preliminary", 1), (2, 1.0, "preliminary", 1), (3, 1.0, "preliminary", 1)]
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."""
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert "already stored: batch 1" in capsys.readouterr().out
assert len(_stored()[0]) == 1
def test_a_dbt_build_has_no_batch_to_point_to(kit_build, tmp_path, capsys):
"""Pins down: an estimate of a dbt build is refused with the reason, since a batch needs a `cohorte_armado` row.
Fails if a dbt build's number is taken for a kit `armado_id`, which would point the batch to another build."""
path = _write(_estimate(), tmp_path / "dbt.parquet", **{"cohort.source": "dbt"})
assert main(["store", "cacu", "cin2_logistic", "--input", str(path)]) == 1
assert "cohorte_armado" in capsys.readouterr().err and not _stored()[0]
def test_an_estimate_without_its_keys_is_refused(kit_build, tmp_path):
"""Pins down: a file without the version's keys (a hand-made one, or one from an older `estimate`) isn't stored.
Fails if a batch could be written without knowing which model produced it."""
path = tmp_path / "bare.parquet"
pq.write_table(pa.Table.from_pandas(_estimate(), preserve_index=False), path)
with pytest.raises(ValueError, match="lacks"):
store_estimate(path, "cacu")