Estimates stored as batches of risks in the domain's database: models store and run --store; a kit file is read as dbt's only when its producer is dbt

This commit is contained in:
2026-11-06 00:21:53 -06:00
parent 22d1fda0f3
commit 761b5b03bc
9 changed files with 236 additions and 15 deletions
+33 -7
View File
@@ -77,6 +77,23 @@ 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 _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 +121,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 +145,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 +165,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:
@@ -267,6 +286,12 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
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 +299,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
+5 -3
View File
@@ -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)
@@ -31,8 +31,10 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No
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)}")
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)
+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}
+8 -1
View File
@@ -1,5 +1,5 @@
"""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
@@ -133,6 +133,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"`."""
+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)
+17
View File
@@ -0,0 +1,17 @@
"""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_COLUMNS
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
"""One risk per member at the model's horizon, without an interval; a member scored twice stops the batch."""
if tuple(estimate.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}")
if estimate["pac_id"].duplicated().any():
raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}")
if not estimate["probabilidad"].between(0, 1).all():
raise ValueError("a probability outside 0..1")
return [(int(pac_id), float(horizon_years), float(probability), None, None)
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]