diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 6538a51..6efc4e4 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -77,3 +77,60 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none 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"] + + +@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.""" + from models.cama.survival import live + from webapi import model_analysis + + holder = SimpleNamespace(calls=0, error=None) + + def context(domain, scenario): + return "spec", "model", "labelled", "3" + + def curves(spec, model, labelled, query): + holder.calls += 1 + if holder.error: + raise live.QueryError(holder.error) + return {"n": 100, "seleccion": query} + + monkeypatch.setattr(model_analysis, "_live_context", context) + monkeypatch.setattr(live, "curves", curves) + monkeypatch.setattr(live, "options", lambda labelled, pac_id=None: {"n": 100, "paciente": {"grade": "G2"} if pac_id == 7 else None}) + 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) + + 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 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"]}}) + + assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] + + +def test_the_options_carry_the_patients_own_values_when_one_is_named(live_client): + """Pins down: `GET /cama/modelo/curvas/opciones?paciente=7` carries patient 7's values, and without it none. Fails if the + patient parameter is ignored, which would leave the dashboard unable to offer her subgroup.""" + named = live_client.get("/cama/modelo/curvas/opciones?paciente=7").get_json() + plain = live_client.get("/cama/modelo/curvas/opciones").get_json() + + assert named["opciones"]["paciente"] == {"grade": "G2"} and plain["opciones"]["paciente"] is None diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 697eb6c..adb7e1e 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas` and `GET //modelo/desarrollo`. +"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `GET //modelo/curvas/opciones` and `POST //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 @@ -7,12 +7,47 @@ data are simulated. 404 while the scenario has no version in production, or its """ import json +from collections import OrderedDict +from threading import Lock -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, request from webapi.fhir.common import simulated_data +_LIVE: dict = {} +_ANSWERS: OrderedDict = OrderedDict() +_LOCK = Lock() +MAX_ANSWERS = 64 + + +def _live_context(domain: str, scenario: str): + """`(scenario, fitted model, labelled members, version)`: the production version and the cohort build the cycle made last, + kept until either changes. `LookupError` while there is no version or no build.""" + import importlib + + import mlflow.sklearn + + from models.cama.survival import live + from models.dags.training import Scenario + from models.io.registry import registry + from models.io.storage import KitBuild + + resolved = registry.resolve(domain, scenario) + spec = Scenario.load(domain, scenario) + build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(spec.cohort) + if build_id is None: + raise LookupError(f"({domain}, {scenario}) has no cohort build yet") + key = (resolved.version, build_id) + with _LOCK: + if _LIVE.get("key") != key: + build = KitBuild(domain, build_id) + model = mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1] + _LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version)) + _ANSWERS.clear() + return _LIVE["value"] + + 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__) @@ -47,4 +82,43 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "mlflow_run_id": resolved.run_id}, "desarrollo": json.loads(content)}) + @blueprint.get("/modelo/curvas/opciones") + def live_options(): + """What can be selected for the live figure: each covariate's values, the period, the limits and, given + `?paciente=`, that patient's own values.""" + 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 + paciente = request.args.get("paciente") + found = live.options(labelled, int(paciente) if paciente and paciente.isdigit() else None) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "opciones": found}) + + @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.""" + from models.cama.survival import live + + query = request.get_json(silent=True) or {} + 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) + with _LOCK: + record = _ANSWERS.get(key) + if record is None: + try: + record = live.curves(spec, model, labelled, query) + except live.QueryError as error: + return jsonify({"error": str(error)}), 422 + with _LOCK: + _ANSWERS[key] = record + while len(_ANSWERS) > MAX_ANSWERS: + _ANSWERS.popitem(last=False) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record}) + return blueprint