Files
WebApi/webapi/model_analysis.py

309 lines
15 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
import logging
import os
from collections import OrderedDict
from pathlib import Path
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
# The scenarios whose members are scored over the data ingested so far, by domain.
LIVE_SCENARIOS = {"cama": ("survival",)}
log = logging.getLogger(__name__)
def _members_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
folder = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "modelos"
return folder / f"{domain}-{scenario}-v{version}-armado{build_id}.parquet"
def _members(spec, domain: str, scenario: str, version: str, build_id: int):
"""The build's members labelled for the version: read from the file the first reader left (the cycle or another API worker), or
computed from the build and saved for the next. Reading the build takes minutes; the file, a fraction of a second."""
import pandas as pd
from models.cama.survival import live
from models.io.storage import KitBuild
path = _members_path(domain, scenario, version, build_id)
if path.exists():
try:
return pd.read_parquet(path)
except (OSError, ValueError):
log.warning("no se pudo leer %s; se recalcula", path)
build = KitBuild(domain, build_id)
labelled = live.members(spec, build.frame(), build.lineage())
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
labelled.to_parquet(tmp)
tmp.replace(path)
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*.parquet"):
if old != path:
old.unlink(missing_ok=True)
return labelled
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
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:
model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1])
_LIVE.update(key=key, value=(spec, model, _members(spec, domain, scenario, resolved.version, build_id), resolved.version))
_ANSWERS.clear()
return _LIVE["value"]
def _subgroups_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
return _members_path(domain, scenario, version, build_id).with_name(f"{domain}-{scenario}-v{version}-armado{build_id}-subgrupos.json")
def _current_build(domain: str, scenario: str) -> tuple[str, int] | None:
import importlib
from models.dags.training import Scenario
from models.io.registry import registry
try:
version = registry.resolve(domain, scenario).version
except LookupError:
return None
build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(Scenario.load(domain, scenario).cohort)
return (str(version), build_id) if build_id is not None else None
def refresh_subgroups(domain: str) -> list[str]:
"""Runs the pipeline's survival stage over the members of the latest build (`development.subgroup_points`) for each live
scenario whose build has none yet, and saves its scenario points beside the members; the scenarios it computed. Minutes:
the indicators cycle calls it, not a request."""
from models.cama.survival import development
done = []
for scenario in LIVE_SCENARIOS.get(domain, ()):
try:
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError:
continue
current = _current_build(domain, scenario)
if current is None:
continue
path = _subgroups_path(domain, scenario, *current)
if path.exists():
continue
rows = development.subgroup_points(labelled, spec.config.get("desarrollo", {}))
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
tmp.write_text(json.dumps(rows, default=str), encoding="utf-8")
tmp.replace(path)
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*-subgrupos.json"):
if old != path:
old.unlink(missing_ok=True)
done.append(scenario)
return done
def _subgroup_rows(domain: str, scenario: str, version: str) -> list[dict]:
"""The scenario points of the latest build computed by the cycle (`refresh_subgroups`), or the ones the version published
when it trained while the cycle hasn't computed them, the whole cohort's among them as `WHOLE_COHORT`."""
from models.cama.survival.development import WHOLE_COHORT
current = _current_build(domain, scenario)
if current is not None and current[0] == str(version):
path = _subgroups_path(domain, scenario, *current)
if path.exists():
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
log.warning("no se pudo leer %s", path)
return _summary(domain, scenario, version, table="subgrupos_puntos") + [
{**row, "subgrupo": WHOLE_COHORT} for row in _summary(domain, scenario, version, table="cohorte_puntos")]
def warm(domain: str) -> list[str]:
"""Loads the live context of each of the domain's live scenarios (`LIVE_SCENARIOS`), leaving their members' file for every
reader; the scenarios it loaded. One without a version in production or a build is skipped."""
loaded = []
for scenario in LIVE_SCENARIOS.get(domain, ()):
try:
_live_context(domain, scenario)
except LookupError:
continue
loaded.append(scenario)
return loaded
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 gives the ones she belongs to
(`de_la_paciente`, the whole cohort when she is in none) and the first of them 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, hers = (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
hers = [m for m in menu if m["nombre"] in mine] or (
[{"nombre": live.WHOLE, "n": len(labelled)}] if mine == [live.WHOLE] else [])
default = hers[0]["nombre"] if hers else default
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu,
"de_la_paciente": hers, "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, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
published = live.published_points(_subgroup_rows(domain, scenario, version), name)
key = json.dumps({"v": version, "e": name, "p": published}, default=str)
with _LOCK:
record = _ANSWERS.get(key)
if record is None:
try:
record = live.curves(spec, labelled, name, published)
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