Live survival: the scenarios of a patient and the figure of one scenario
This commit is contained in:
@@ -82,7 +82,7 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none
|
||||
@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 `holder.answer` or raises what the test sets."""
|
||||
without MLflow or a cohort build; `live.curves` answers from the stand-in or raises what the test sets."""
|
||||
from models.cama.survival import live
|
||||
from webapi import model_analysis
|
||||
|
||||
@@ -91,36 +91,51 @@ def live_client(client, monkeypatch):
|
||||
def context(domain, scenario):
|
||||
return "spec", "model", "labelled", "3"
|
||||
|
||||
def curves(spec, model, labelled, query):
|
||||
def curves(spec, model, labelled, name):
|
||||
holder.calls += 1
|
||||
if holder.error:
|
||||
raise live.QueryError(holder.error)
|
||||
return {"n": 100, "seleccion": query}
|
||||
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(live, "curves", curves)
|
||||
monkeypatch.setattr(live, "patient_scenarios", patient_scenarios)
|
||||
model_analysis._ANSWERS.clear()
|
||||
client.holder = holder
|
||||
return client
|
||||
|
||||
|
||||
def test_the_live_figure_is_asked_with_a_selection_and_the_answer_is_kept(live_client):
|
||||
"""Pins down: `POST /cama/modelo/curvas/consulta` returns the record for the selection with the version that scored it,
|
||||
and the same selection a second time is answered without computing again. Fails if the answer lacks the version, or every
|
||||
request recomputes (the figure would take seconds each time a reader goes back to a selection)."""
|
||||
body = {"filtros": {"grade": ["G3"]}}
|
||||
first = live_client.post("/cama/modelo/curvas/consulta", json=body)
|
||||
second = live_client.post("/cama/modelo/curvas/consulta", json=body)
|
||||
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"})
|
||||
|
||||
assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3"
|
||||
assert first.get_json()["curvas"]["seleccion"] == body and second.get_json() == first.get_json()
|
||||
assert first.get_json()["curvas"]["escenario"] == "< 45 años" and second.get_json() == first.get_json()
|
||||
assert live_client.holder.calls == 1
|
||||
|
||||
|
||||
def test_a_selection_that_cannot_be_answered_is_a_422_with_the_reason(live_client):
|
||||
"""Pins down: a selection too small or invalid 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 selection says nothing."""
|
||||
live_client.holder.error = "La selección tiene 3 pacientes"
|
||||
answer = live_client.post("/cama/modelo/curvas/consulta", json={"filtros": {"er": ["NEGATIVO"]}})
|
||||
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"]
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`, `GET /<domain>/modelo/desarrollo` and, over the data ingested so far, `POST /<domain>/modelo/curvas/consulta`.
|
||||
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`, `GET /<domain>/modelo/desarrollo` and, over the data ingested so far, `GET /<domain>/modelo/escenarios` and `POST /<domain>/modelo/curvas/consulta`.
|
||||
|
||||
The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's
|
||||
survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the
|
||||
@@ -82,23 +82,42 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
|
||||
"mlflow_run_id": resolved.run_id},
|
||||
"desarrollo": json.loads(content)})
|
||||
|
||||
@blueprint.post("/modelo/curvas/consulta")
|
||||
def live_curves():
|
||||
"""The figure's record for the selection in the body (`{filtros, periodo}`), scored with the production version over
|
||||
the data ingested so far. 422 with the reason when the selection is too small or invalid."""
|
||||
@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."""
|
||||
from models.cama.survival import live
|
||||
|
||||
query = request.get_json(silent=True) or {}
|
||||
try:
|
||||
_, _, labelled, version = _live_context(domain, scenario)
|
||||
except LookupError as error:
|
||||
return jsonify({"error": f"sin curvas: {error}"}), 404
|
||||
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})
|
||||
|
||||
@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."""
|
||||
from models.cama.survival import live
|
||||
|
||||
name = (request.get_json(silent=True) or {}).get("escenario")
|
||||
try:
|
||||
spec, model, labelled, version = _live_context(domain, scenario)
|
||||
except LookupError as error:
|
||||
return jsonify({"error": f"sin curvas: {error}"}), 404
|
||||
key = json.dumps({"v": version, "q": query}, sort_keys=True, default=str)
|
||||
key = json.dumps({"v": version, "e": name}, default=str)
|
||||
with _LOCK:
|
||||
record = _ANSWERS.get(key)
|
||||
if record is None:
|
||||
try:
|
||||
record = live.curves(spec, model, labelled, query)
|
||||
record = live.curves(spec, model, labelled, name)
|
||||
except live.QueryError as error:
|
||||
return jsonify({"error": str(error)}), 422
|
||||
with _LOCK:
|
||||
|
||||
Reference in New Issue
Block a user