Files
WebApi/webapi/model_analysis.py
T
2026-11-22 18:04:57 -06:00

191 lines
9.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 _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]:
"""The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per
cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed)."""
from models.io.registry import registry
try:
_, content = registry.artifact(domain, scenario, version, artifact)
except LookupError:
return []
record = json.loads(content)
rows = (record.get("tablas") or record.get("desarrollo", {}).get("tablas") or {}).get(table) or {}
return rows.get("filas", []) if isinstance(rows, dict) else rows
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 scenarios_menu():
"""The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also names the one she
belongs to first as the default. 404 while there is no version in production."""
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
in_summary = {row["escenario"] for row in _summary(domain, scenario, version)}
masks = live.scenario_masks(labelled)
menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)]
default = menu[0]["nombre"] if menu else None
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
mine = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
default = next((m["nombre"] for m in menu if m["nombre"] in mine), default)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default})
@blueprint.post("/modelo/curvas/consulta")
def live_curves():
"""The figure's record of the clinical scenario in the body (`{escenario}`), scored with the production version over the data
ingested so far, and the scenario's risk factors (its summary row, `null` when it has none). 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)
row = next((r for r in _summary(domain, scenario, version) if r["escenario"] == name), None)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record, "factores": row})
return blueprint
def recurrence_blueprint() -> Blueprint:
"""CaMa's recurrence analysis, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia` answers the figures of every clinical
scenario of both external cohorts (METABRIC and SCAN-B) that has a row in the summary the production version published, those rows
(one per cohort, scenario and horizon) for the risk-factor label, and, given `?paciente=<pac_id>`, the scenario her own age, tumor
size, grade and receptors place her in first as the default, and every scenario they place her in (`de_la_paciente`, the larger
first within each cohort). The figures describe the cohorts' patients, not her."""
blueprint = Blueprint("model_analysis_cama_recurrence", __name__)
@blueprint.get("/modelo/recurrencia")
def recurrence():
from models.cama.recurrence import patient
from models.io.registry import registry
try:
resolved = registry.resolve("cama", "recurrence")
_, content = registry.artifact("cama", "recurrence", resolved.version, "analisis/recurrencia.json")
except LookupError as error:
return jsonify({"error": f"sin recurrencia: {error}"}), 404
record = json.loads(content)
summary = _summary("cama", "recurrence", resolved.version, "analisis/recurrencia_desarrollo.json")
present = {(r["cohorte"], r["escenario"]) for r in summary}
figures = [f for f in record["escenarios"] if (f["cohorte"], f["escenario"]) in present]
default, hers = None, []
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
_, _, labelled, _ = _live_context("cama", "survival")
except LookupError:
labelled = None
rows = labelled[labelled["pac_id"] == int(paciente)] if labelled is not None else None
if rows is not None and not rows.empty:
mine = patient.matching(figures, patient.covariates_of(rows.iloc[0]))
hers = [{"cohorte": f["cohorte"], "escenario": f["escenario"]} for f in mine]
default = hers[0] if hers else None
return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"],
"escenarios": figures, "resumen": summary, "predeterminado": default, "de_la_paciente": hers})
return blueprint