Files
WebApi/webapi/model_analysis.py
T

164 lines
7.8 KiB
Python

"""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
cohort, not any patient. The answer names the version they come from, and carries `simulado: true` in DEV, where the
data are simulated. 404 while the scenario has no version in production, or its version has no such record.
"""
import json
from collections import OrderedDict
from threading import Lock
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 = live.rehydrate(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="/<domain>"`."""
blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__)
@blueprint.get("/modelo/curvas")
def curves():
"""The curves and points of the scenario's production version."""
from models.io.registry import registry
try:
resolved = registry.resolve(domain, scenario)
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/curvas.json")
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"mlflow_run_id": resolved.run_id},
"curvas": json.loads(content)})
@blueprint.get("/modelo/desarrollo")
def development():
"""The development stages' tables and figures of the scenario's production version."""
from models.io.registry import registry
try:
resolved = registry.resolve(domain, scenario)
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/desarrollo.json")
except LookupError as error:
return jsonify({"error": f"sin desarrollo: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"mlflow_run_id": resolved.run_id},
"desarrollo": json.loads(content)})
@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
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, "e": name}, default=str)
with _LOCK:
record = _ANSWERS.get(key)
if record is None:
try:
record = live.curves(spec, model, labelled, name)
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
def recurrence_blueprint() -> Blueprint:
"""CaMa's recurrence figures for a patient, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia?paciente=<pac_id>`
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."""
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]))
return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"],
"escenarios": found})
return blueprint