Recurrence figures for a patient; governance trains scenarios with external data; lifelines in the lock

This commit is contained in:
rockdrigo
2026-11-21 13:34:56 -06:00
parent a53179aa2e
commit 2c4bfa5691
6 changed files with 153 additions and 6 deletions
+2 -1
View File
@@ -98,7 +98,7 @@ def create_app() -> Flask:
from persistance import cama as cama_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.model_analysis import model_analysis_blueprint
from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
@@ -107,5 +107,6 @@ def create_app() -> Flask:
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
app.register_blueprint(recurrence_blueprint(), url_prefix="/cama")
return app
+34
View File
@@ -127,3 +127,37 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record})
return blueprint
def recurrence_blueprint() -> Blueprint:
"""CaMa's recurrence figures for a patient, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia?paciente=<pac_id>`
answers the figures (METABRIC's and SCAN-B's) of the clinical scenarios her covariates meet, from the recurrence version in
production. The scenarios are the external cohorts' analyses; she is placed in them by her own age, tumor size, grade and
receptors, from the data ingested so far."""
blueprint = Blueprint("model_analysis_cama_recurrence", __name__)
@blueprint.get("/modelo/recurrencia")
def recurrence():
import pandas as pd
from models.cama.recurrence import patient
from models.io.registry import registry
paciente = request.args.get("paciente", "")
if not paciente.isdigit():
return jsonify({"error": "Falta la paciente."}), 422
try:
resolved = registry.resolve("cama", "recurrence")
_, content = registry.artifact("cama", "recurrence", resolved.version, "analisis/recurrencia.json")
_, _, labelled, _ = _live_context("cama", "survival")
except LookupError as error:
return jsonify({"error": f"sin recurrencia: {error}"}), 404
rows = labelled[labelled["pac_id"] == int(paciente)]
if rows.empty:
return jsonify({"error": "La paciente no está en la cohorte del modelo."}), 422
record = json.loads(content)
found = patient.matching(record["escenarios"], patient.covariates_of(rows.iloc[0]))
return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"],
"escenarios": found})
return blueprint
+7 -5
View File
@@ -17,7 +17,8 @@ from datetime import datetime, timezone
from pathlib import Path
TAIL_CHARS = 4000
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build.
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its
# `model.toml` does too, whatever its domain.
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."}
@@ -35,13 +36,13 @@ def catalog() -> list[dict]:
domain = spec.get("domain")
if domain is None:
continue
own = domain in OWN_STEPS
own = domain in OWN_STEPS or bool(spec.get("external"))
if not own and "scenario" not in spec:
continue
found.append({
"domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"),
"outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()),
"kind": "referencia" if own else "cohorte",
"kind": "referencia" if own else "cohorte", "external": own,
})
return found
@@ -52,7 +53,8 @@ def _base() -> Path:
def _command(domain: str, scenario: str) -> list[str]:
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"]
if domain not in OWN_STEPS:
external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario))
if not external:
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"):
# A reference cohort on this machine's disk, instead of the configured one in the cluster's storage.
@@ -100,7 +102,7 @@ def start(domain: str, scenario: str) -> dict:
"""Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest."""
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
raise LookupError(f"no such model: {domain}/{scenario}")
if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"):
if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"):
raise RuntimeError("No hay un manifest de dbt configurado.")
job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}"
folder = _base() / job_id