CaMa: scenario menus and risk-factor rows for the survival and recurrence analyses
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user