From 4cc2ce83ac7af2518d77aaa96f0f72ca18fcb726 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 14:43:46 -0600 Subject: [PATCH] CaMa: scenario menus and risk-factor rows for the survival and recurrence analyses --- tests/test_model_analysis.py | 118 +++++++++++++++++++---------------- webapi/model_analysis.py | 81 +++++++++++++++--------- 2 files changed, 117 insertions(+), 82 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 0f443b9..6267750 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -79,47 +79,63 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"] +SUMMARY = {"columnas": ["escenario", "riesgo_definitorios", "incluye_factor_riesgo"], + "filas": [{"escenario": "< 45 años", "riesgo_definitorios": "Grado=G3 (robusto, 97%)", "incluye_factor_riesgo": True}, + {"escenario": "Estadio IV", "riesgo_definitorios": "", "incluye_factor_riesgo": False}]} + + @pytest.fixture def live_client(client, monkeypatch): - """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, so the routes run - without MLflow or a cohort build; `live.curves` answers from the stand-in or raises what the test sets.""" + """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, and the version's summary + of two scenarios (one with a risk factor, one without) in its development record, so the routes run without MLflow or a + cohort build; `live.curves` answers from the stand-in or raises what the test sets; the masks put patients 1-100 in + `< 45 años`, 1-3 in a tiny scenario with no summary row, and nobody in `Estadio IV`.""" + import numpy as np + import pandas as pd from models.cama.survival import live from webapi import model_analysis - holder = SimpleNamespace(calls=0, error=None) + holder = client.holder + holder.calls, holder.error = 0, None + labelled = pd.DataFrame({"pac_id": range(1, 201), "event": [True] * 40 + [False] * 160}) + masks = {"< 45 años": np.arange(200) < 100, "Diminuto": np.arange(200) < 3, "Estadio IV": np.zeros(200, bool)} + holder.files["analisis/desarrollo.json"] = json.dumps({"tablas": {"escenarios_resumen": SUMMARY}}).encode() - def context(domain, scenario): - return "spec", "model", "labelled", "3" - - def curves(spec, model, labelled, name): + def curves(spec, model, labelled_members, name): holder.calls += 1 if holder.error: raise live.QueryError(holder.error) return {"n": 100, "escenario": name or "Toda la cohorte"} - def patient_scenarios(labelled, pac_id): - if pac_id == 404: - raise live.QueryError("La paciente no está en la cohorte del modelo.") - return ["< 45 años"] if pac_id == 7 else ["Toda la cohorte"] - - monkeypatch.setattr(model_analysis, "_live_context", context) + monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) + monkeypatch.setattr(live, "scenario_masks", lambda frame: masks) monkeypatch.setattr(live, "curves", curves) - monkeypatch.setattr(live, "patient_scenarios", patient_scenarios) model_analysis._ANSWERS.clear() - client.holder = holder return client -def test_a_scenarios_figure_is_asked_by_name_and_the_answer_is_kept(live_client): - """Pins down: `POST /cama/modelo/curvas/consulta` returns the record of the named scenario with the version that scored it, - and the same scenario a second time is answered without computing again. Fails if the answer lacks the version, or every - request recomputes (the figure takes seconds each time a patient's record opens).""" - first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) - second = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) +def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(live_client): + """Pins down: `GET /cama/modelo/escenarios` offers only the scenarios that have a row in the version's summary and enough patients + to draw (not the one with no row, not the one with nobody), with their patients, in the pipeline's order, and names the one a + patient belongs to as the default. Fails if a scenario with nothing to say reaches the menu, or the default ignores the patient.""" + menu = live_client.get("/cama/modelo/escenarios?paciente=7").get_json() - assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3" - assert first.get_json()["curvas"]["escenario"] == "< 45 años" and second.get_json() == first.get_json() - assert live_client.holder.calls == 1 + assert menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años" + assert menu["modelo"]["version"] == "3" + assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422 + + +def test_a_scenarios_figure_comes_with_its_risk_factors_and_the_answer_is_kept(live_client): + """Pins down: `POST /cama/modelo/curvas/consulta` returns the figure of the named scenario with its summary row (the risk-factor + label) and the version that scored it, and the same scenario a second time is answered without computing again; a scenario with + no row has no factors. Fails if curve and label can come from different scenarios, or every request recomputes.""" + first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json() + again = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json() + other = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Diminuto"}).get_json() + + assert first["curvas"]["escenario"] == "< 45 años" and first["factores"]["riesgo_definitorios"] == "Grado=G3 (robusto, 97%)" + assert again == first and live_client.holder.calls == 2 and other["factores"] is None + assert first["modelo"]["version"] == "3" def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client): @@ -131,31 +147,24 @@ def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] -def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_client): - """Pins down: `GET /cama/modelo/escenarios?paciente=7` lists her scenarios, one in none gets the whole cohort, and a patient - outside the cohort or no patient is a 422. Fails if the patient parameter is ignored, which would draw the same figure for - every patient.""" - assert live_client.get("/cama/modelo/escenarios?paciente=7").get_json()["escenarios"] == ["< 45 años"] - assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"] - assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422 - assert live_client.get("/cama/modelo/escenarios").status_code == 422 - - @pytest.fixture def recurrence_client(monkeypatch): - """The recurrence route on a bare app, with the registry's production version, its recurrence record and the labelled members - replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" + """The recurrence route on a bare app, with the registry's production version, its recurrence record, its summary and the + labelled members replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" import pandas as pd from flask import Flask from models.io import registry as registry_module from webapi import model_analysis + figure = lambda cohorte, name, cond, n: {"cohorte": cohorte, "escenario": name, "condiciones": cond, "n": n} record = {"horizons_months": [12, 36, 60], "escenarios": [ - {"cohorte": "metabric", "escenario": "< 45 años", "condiciones": {"Edad": ["<45"]}, "n": 100}, - {"cohorte": "metabric", "escenario": "RE− · grado 3", "condiciones": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, "n": 300}, - {"cohorte": "metabric", "escenario": "Ganglios 4+", "condiciones": {"Ganglios_positivos": ["4+"]}, "n": 80}, - {"cohorte": "scanb", "escenario": "Grado 3", "condiciones": {"Grado_histologico": ["3"]}, "n": 900}]} + figure("metabric", "< 45 años", {"Edad": ["<45"]}, 100), figure("metabric", "RE− · grado 3", {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, 300), + figure("metabric", "Ganglios 4+", {"Ganglios_positivos": ["4+"]}, 80), figure("scanb", "Grado 3", {"Grado_histologico": ["3"]}, 900), + figure("scanb", "Sin fila", {"Edad": ["<45"]}, 50)]} + summary = {"tablas": {"escenarios_resumen": {"filas": [ + {"cohorte": "metabric", "escenario": "< 45 años", "horizonte_meses": 60}, {"cohorte": "metabric", "escenario": "RE− · grado 3", "horizonte_meses": 60}, + {"cohorte": "metabric", "escenario": "Ganglios 4+", "horizonte_meses": 60}, {"cohorte": "scanb", "escenario": "Grado 3", "horizonte_meses": 60}]}}} labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]}) holder = SimpleNamespace(production="2") @@ -164,8 +173,9 @@ def recurrence_client(monkeypatch): raise LookupError("no hay una versión en producción") return SimpleNamespace(version=holder.production, run_id="run-2") + files = {"analisis/recurrencia.json": json.dumps(record).encode(), "analisis/recurrencia_desarrollo.json": json.dumps(summary).encode()} monkeypatch.setattr(registry_module.registry, "resolve", resolve) - monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: ("recurrencia.json", json.dumps(record).encode())) + monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: (p, files[p])) monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) app = Flask(__name__) app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama") @@ -174,21 +184,21 @@ def recurrence_client(monkeypatch): yield client -def test_a_patient_gets_the_recurrence_scenarios_her_covariates_meet(recurrence_client): - """Pins down: `GET /cama/modelo/recurrencia?paciente=7` returns the scenarios whose every condition her age, grade and - receptors meet (one that needs the nodes, which the hospital does not report, is left out), the larger first within a - cohort, with the version that published them. Fails if a scenario she does not meet is returned, a missing covariate counts - as met, or the version is not named.""" +def test_the_recurrence_menu_has_the_scenarios_with_a_summary_row_and_the_patients_default(recurrence_client): + """Pins down: `GET /cama/modelo/recurrencia` returns the figures of the scenarios that have a row in the version's summary (not + the one without), the summary rows, the version, and, for patient 7, the larger scenario her age, grade and receptors meet as the + default (one that needs the nodes, which the hospital does not report, is never it). Fails if a scenario with no row is offered, + the rows are not returned, or the default is not one she meets.""" body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json() - assert [(s["cohorte"], s["escenario"]) for s in body["escenarios"]] == [("metabric", "RE− · grado 3"), ("metabric", "< 45 años"), ("scanb", "Grado 3")] - assert body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + assert [(f["cohorte"], f["escenario"]) for f in body["escenarios"]] == [("metabric", "< 45 años"), ("metabric", "RE− · grado 3"), ("metabric", "Ganglios 4+"), ("scanb", "Grado 3")] + assert len(body["resumen"]) == 4 and body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + assert body["predeterminado"] == {"cohorte": "metabric", "escenario": "RE− · grado 3"} + assert recurrence_client.get("/cama/modelo/recurrencia").get_json()["predeterminado"] is None -def test_without_a_recurrence_version_or_for_a_stranger_it_says_so(recurrence_client): - """Pins down: no recurrence version in production is a 404, a patient outside the cohort or no patient is a 422 with a reason. - Fails if either becomes a 200 with nothing or a 500.""" - assert recurrence_client.get("/cama/modelo/recurrencia?paciente=99").status_code == 422 - assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 422 +def test_without_a_recurrence_version_it_is_a_404(recurrence_client): + """Pins down: no recurrence version in production is a 404 with the reason. Fails if it becomes a 200 with nothing or a 500.""" recurrence_client.holder.production = None - assert recurrence_client.get("/cama/modelo/recurrencia?paciente=7").status_code == 404 + + assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 404 diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 6e6a1ab..814717d 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -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="/"`.""" 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=` 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=` 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=` - 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=`, 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