Files
WebApi/tests/test_model_analysis.py
T

295 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""What this module covers: `GET /cama/modelo/curvas` and `GET /cama/modelo/desarrollo` (`webapi.model_analysis`): they serve the production version's
population record with the version it comes from, and answers 404 while there is no version in production or the
version has no such record.
Fixtures: `client`, the app with the registry's `resolve` and `artifact` replaced by what the test says a production
version holds, so no MLflow is needed; the CaMa survival record is a small stand-in for what a run publishes.
"""
import json
from types import SimpleNamespace
import pytest
RECORD = {"horizons_months": [6, 12, 18], "points": {"COMB": {"S": [0.9, 0.8, 0.7], "low": [0.8, 0.7, 0.6], "high": [0.95, 0.9, 0.8]}}}
@pytest.fixture
def client(monkeypatch):
from flask import Flask
from models.io import registry as registry_module
from webapi.model_analysis import model_analysis_blueprint
app = Flask(__name__)
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
monkeypatch.setenv("DEV_REVISION", "pruebas")
holder = SimpleNamespace(files={"analisis/curvas.json": json.dumps(RECORD).encode()}, production="3")
def resolve(domain, scenario, version=None):
if holder.production is None:
raise LookupError("no hay una versión en producción")
return SimpleNamespace(version=holder.production, run_id="run-1")
def artifact(domain, scenario, version, path):
if path not in holder.files:
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
return path.rsplit("/", 1)[-1], holder.files[path]
monkeypatch.setattr(registry_module.registry, "resolve", resolve)
monkeypatch.setattr(registry_module.registry, "artifact", artifact)
with app.test_client() as test_client:
test_client.holder = holder
yield test_client
def test_it_serves_the_production_versions_record_and_names_the_version(client):
"""Pins down: the answer carries the record unchanged, the model and version it comes from and the simulated-data
flag. Fails if the record is altered on the way or the answer stops saying which version it is."""
body = client.get("/cama/modelo/curvas").get_json()
assert body["curvas"] == RECORD and body["simulado"] is True
assert body["modelo"] == {"nombre": "cama-survival", "version": "3", "mlflow_run_id": "run-1"}
def test_without_a_version_in_production_or_a_record_it_is_a_404(client):
"""Pins down: no production version, and a version whose run published no `analisis/curvas.json`, are both a 404
with the reason, never an empty record. Fails if either becomes a 200 or a 500."""
client.holder.files.clear()
missing_record = client.get("/cama/modelo/curvas")
client.holder.production = None
no_version = client.get("/cama/modelo/curvas")
assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"]
assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"]
def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none(client):
"""Pins down: `GET /cama/modelo/desarrollo` returns `analisis/desarrollo.json` with the version it comes from, and a
version trained before that record existed is a 404, not an empty page. Fails if the route reads another file or
answers 200 without a record."""
record = {"tablas": {"or_lr_balanceada": [{"variable": "Grado"}]}, "figuras": {}}
client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode()
found = client.get("/cama/modelo/desarrollo")
del client.holder.files["analisis/desarrollo.json"]
missing = client.get("/cama/modelo/desarrollo")
assert found.status_code == 200 and found.get_json()["desarrollo"] == record
assert found.get_json()["modelo"]["version"] == "3"
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, 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 = 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 curves(spec, model, labelled_members, name, points=None):
holder.calls += 1
holder.points = points
if holder.error:
raise live.QueryError(holder.error)
return {"n": 100, "escenario": name or "Toda la cohorte"}
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3"))
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: None)
monkeypatch.setattr(live, "scenario_masks", lambda frame: masks)
monkeypatch.setattr(live, "curves", curves)
model_analysis._ANSWERS.clear()
return client
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 menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años"
assert menu["de_la_paciente"] == [{"nombre": "< 45 años", "n": 100}]
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):
"""Pins down: an unknown scenario or one too small is a 422 with the message, not a 500 or an empty record. Fails if the
reader sees a server error instead of why the scenario says nothing."""
live_client.holder.error = "El escenario tiene 3 pacientes"
answer = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"})
assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"]
@pytest.fixture
def recurrence_client(monkeypatch):
"""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": [
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")
def resolve(domain, scenario, version=None):
if holder.production is None:
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: (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")
with app.test_client() as client:
client.holder = holder
yield client
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), and every scenario she meets. Fails if a
scenario with no row is offered, the rows are not returned, or the default or her scenarios include one she does not meet."""
body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json()
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 body["de_la_paciente"][0] == body["predeterminado"]
assert all(s in [{"cohorte": f["cohorte"], "escenario": f["escenario"]} for f in body["escenarios"]] for s in body["de_la_paciente"])
assert {"cohorte": "metabric", "escenario": "Ganglios 4+"} not in body["de_la_paciente"]
anonymous = recurrence_client.get("/cama/modelo/recurrencia").get_json()
assert anonymous["predeterminado"] is None and anonymous["de_la_paciente"] == []
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").status_code == 404
def test_the_members_are_computed_once_per_build_and_version_and_read_from_their_file_after(tmp_path, monkeypatch):
"""Pins down: the first reader of a build's labelled members computes them from the build and leaves them in
`INDICADORES_DIR/modelos`; the next reader (another worker, or the API after the cycle) reads that file without touching the
build, and a new build replaces the old file. Fails if every worker reads the build again, or old builds pile up."""
import pandas as pd
from models.cama.survival import live
from models.io import storage
from webapi import model_analysis
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
reads = []
class Build:
def __init__(self, domain, build_id):
reads.append(build_id)
def frame(self):
return pd.DataFrame()
def lineage(self):
return {}
monkeypatch.setattr(storage, "KitBuild", Build)
monkeypatch.setattr(live, "members", lambda spec, frame, lineage: pd.DataFrame({"pac_id": [1, 2], "stage": ["I", None]}))
first = model_analysis._members("spec", "cama", "survival", "3", 8)
again = model_analysis._members("spec", "cama", "survival", "3", 8)
model_analysis._members("spec", "cama", "survival", "3", 9)
assert reads == [8, 9] and again.equals(first)
assert [p.name for p in (tmp_path / "modelos").iterdir()] == ["cama-survival-v3-armado9.parquet"]
def test_the_figure_takes_the_points_the_version_published_for_the_scenario(live_client):
"""Pins down: the live figure of a scenario carries the points the pipeline's survival stage published for it
(`subgrupos_puntos`: LR, HBN and their combination with bootstrap intervals), and none for a scenario without them. Fails if
the figure draws the members' own scores where the version has the pipeline's."""
rows = [{"modelo": m, "meses": h, "S": 0.9, "IC_inf": 0.85, "IC_sup": 0.95, "subgrupo": "< 45 años"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
record = json.loads(live_client.holder.files["analisis/desarrollo.json"])
record["tablas"]["subgrupos_puntos"] = {"columnas": ["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"], "filas": rows}
live_client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode()
live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"})
published = live_client.holder.points
live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"})
assert published["COMB"] == {"S": [0.9] * 3, "low": [0.85] * 3, "high": [0.95] * 3}
assert live_client.holder.points is None
def test_the_cycle_computes_the_scenario_points_once_per_build_and_the_figure_takes_them(live_client, tmp_path, monkeypatch):
"""Pins down: `refresh_subgroups` runs the pipeline's survival stage over the latest build's members once and saves its
scenario points beside them; the figure then draws those points instead of the ones the version published when it trained,
and a new build replaces the file. Fails if the figure keeps the training's points after the data changed, or every cycle
reruns the stage for the same build."""
from models.cama.survival import development
from webapi import model_analysis
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
build = {"id": 8}
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: ("3", build["id"]))
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: (SimpleNamespace(config={"desarrollo": {}}), "model", None, "3"))
runs = []
def stage(labelled, desarrollo):
runs.append(build["id"])
return [{"modelo": m, "meses": h, "S": 0.7, "IC_inf": 0.6, "IC_sup": 0.8, "subgrupo": "< 45 años"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
monkeypatch.setattr(development, "subgroup_points", stage)
first = model_analysis.refresh_subgroups("cama")
again = model_analysis.refresh_subgroups("cama")
rows = model_analysis._subgroup_rows("cama", "survival", "3")
build["id"] = 9
model_analysis.refresh_subgroups("cama")
assert first == ["survival"] and again == [] and runs == [8, 9]
assert [r["S"] for r in rows if r["modelo"] == "COMB"] == [0.7] * 3
assert [p.name for p in (tmp_path / "modelos").glob("*-subgrupos.json")] == ["cama-survival-v3-armado9-subgrupos.json"]