CaMa: scenario menus and risk-factor rows for the survival and recurrence analyses

This commit is contained in:
rockdrigo
2026-11-21 14:43:46 -06:00
parent d185aba364
commit 4cc2ce83ac
2 changed files with 117 additions and 82 deletions
+53 -28
View File
@@ -48,6 +48,20 @@ def _live_context(domain: str, scenario: str):
return _LIVE["value"]
def _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]:
"""The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per
cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed)."""
from models.io.registry import registry
try:
_, content = registry.artifact(domain, scenario, version, artifact)
except LookupError:
return []
record = json.loads(content)
rows = (record.get("tablas") or record.get("desarrollo", {}).get("tablas") or {}).get(table) or {}
return rows.get("filas", []) if isinstance(rows, dict) else rows
def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
"""The blueprint of one scenario, to register with `url_prefix="/<domain>"`."""
blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__)
@@ -83,28 +97,34 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
"desarrollo": json.loads(content)})
@blueprint.get("/modelo/escenarios")
def patient_scenarios():
"""The clinical scenarios `?paciente=<pac_id>` belongs to (the whole cohort when she is in none), over the data
ingested so far. 404 while there is no version in production; 422 with the reason for a patient outside the cohort."""
def scenarios_menu():
"""The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also names the one she
belongs to first as the default. 404 while there is no version in production."""
from models.cama.survival import live
try:
_, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
in_summary = {row["escenario"] for row in _summary(domain, scenario, version)}
masks = live.scenario_masks(labelled)
menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)]
default = menu[0]["nombre"] if menu else None
paciente = request.args.get("paciente", "")
if not paciente.isdigit():
return jsonify({"error": "Falta la paciente."}), 422
try:
found = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": found})
if paciente.isdigit():
try:
mine = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
default = next((m["nombre"] for m in menu if m["nombre"] in mine), default)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default})
@blueprint.post("/modelo/curvas/consulta")
def live_curves():
"""The figure's record for the clinical scenario in the body (`{escenario}`, none for the whole cohort), scored with the
production version over the data ingested so far. 422 with the reason for an unknown scenario or one too small."""
"""The figure's record of the clinical scenario in the body (`{escenario}`), scored with the production version over the data
ingested so far, and the scenario's risk factors (its summary row, `null` when it has none). 422 with the reason for an
unknown scenario or one too small."""
from models.cama.survival import live
name = (request.get_json(silent=True) or {}).get("escenario")
@@ -124,40 +144,45 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
_ANSWERS[key] = record
while len(_ANSWERS) > MAX_ANSWERS:
_ANSWERS.popitem(last=False)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record})
row = next((r for r in _summary(domain, scenario, version) if r["escenario"] == name), None)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record, "factores": row})
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."""
"""CaMa's recurrence analysis, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia` answers the figures of every clinical
scenario of both external cohorts (METABRIC and SCAN-B) that has a row in the summary the production version published, those rows
(one per cohort, scenario and horizon) for the risk-factor label, and, given `?paciente=<pac_id>`, the scenario her own age, tumor
size, grade and receptors place her in first as the default. The figures describe the cohorts' patients, not her."""
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]))
summary = _summary("cama", "recurrence", resolved.version, "analisis/recurrencia_desarrollo.json")
present = {(r["cohorte"], r["escenario"]) for r in summary}
figures = [f for f in record["escenarios"] if (f["cohorte"], f["escenario"]) in present]
default = None
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
_, _, labelled, _ = _live_context("cama", "survival")
except LookupError:
labelled = None
rows = labelled[labelled["pac_id"] == int(paciente)] if labelled is not None else None
if rows is not None and not rows.empty:
mine = patient.matching(figures, patient.covariates_of(rows.iloc[0]))
default = {"cohorte": mine[0]["cohorte"], "escenario": mine[0]["escenario"]} if mine else None
return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"],
"escenarios": found})
"escenarios": figures, "resumen": summary, "predeterminado": default})
return blueprint