"""The production CaMa survival model over the live cohort build. A scenario's figure is computed on request from the production version of `cama/seer_survival` and the latest build of its cohort, and kept per (model version, cohort build, scenario): a new version or a new build computes it again. The saved model is rehydrated with the current class before it scores (`SeerSurvivalModel.rehydrate`). """ import os import pickle import threading from dataclasses import dataclass from importlib import import_module from pathlib import Path import mlflow.sklearn import pandas as pd from models.cama.seer_survival import seer_model from models.dags.training import Scenario from models.io.registry import registry from models.io.storage import KitBuild DOMAIN, SCENARIO = "cama", "seer_survival" class NotAvailable(LookupError): """There is no production version, or no cohort build to draw on.""" class SavedFile: """The model saved as a file (`CAMA_SURVIVAL_MODEL`), versioned by its modification time.""" def __init__(self, path: str): self.path = Path(path) self.version = f"archivo-{int(self.path.stat().st_mtime)}" def load(self): with self.path.open("rb") as handle: return pickle.load(handle) @dataclass class Live: """The model of the production version and the live build's members, recoded once for both.""" version: str build_id: int model: seer_model.SeerSurvivalModel cohort: pd.DataFrame frame: object figures: dict _lock = threading.RLock() _live: Live | None = None def _resolve() -> tuple[str, int, object]: scenario = Scenario.load(DOMAIN, SCENARIO) repositories = import_module(f"persistance.{DOMAIN}") file = os.environ.get("CAMA_SURVIVAL_MODEL") if file: if not Path(file).is_file(): raise NotAvailable("no hay un modelo de supervivencia guardado") resolved = SavedFile(file) else: try: resolved = registry.resolve(DOMAIN, SCENARIO) except LookupError as error: raise NotAvailable("no hay una versión del modelo de supervivencia en producción") from error build_id = repositories.cohort_repository.latest_build(scenario.cohort) if build_id is None: raise NotAvailable("no hay una cohorte armada para el modelo de supervivencia") return resolved.version, int(build_id), resolved def live() -> Live: """The production version over the latest build; loaded again only when either changed.""" global _live version, build_id, resolved = _resolve() with _lock: if _live is None or (_live.version, _live.build_id) != (version, build_id): saved = resolved.load() if isinstance(resolved, SavedFile) else mlflow.sklearn.load_model(resolved.model_uri) model = seer_model.SeerSurvivalModel.rehydrate(saved) cohort = KitBuild(DOMAIN, build_id).frame() recoded = model.recode(cohort) _live = Live(version, build_id, model, cohort, model.frame(recoded), {}) return _live def scenarios() -> dict: current = live() return {"model_version": current.version, "build": current.build_id, "scenarios": current.model.scenario_names()} def figure(scenario: str) -> dict: """The record of one scenario's figure; `KeyError` for a scenario the model doesn't define.""" current = live() if scenario not in current.model.scenario_names(): raise KeyError(scenario) with _lock: if scenario not in current.figures: settings = seer_model.figure_settings() current.figures[scenario] = { "model_version": current.version, "build": current.build_id, **current.model.figure_record( current.frame, scenario, ks_max_seconds=settings["ks_max_seconds"], n_boot=settings["n_boot"], min_members=settings["min_members"], min_deaths=settings["min_deaths"])} return current.figures[scenario] def patient_scenarios(pac_id: int) -> dict: """The scenarios a patient belongs to, from her variables over the timeline (age, stage, subtype, surgery).""" current = live() events = current.cohort[current.cohort["pac_id"] == pac_id] if events.empty: raise KeyError(pac_id) model = current.model recoded = model.recode(events) names = [] if len(recoded): masks = model.scenario_masks(model.frame(recoded)) names = [name for name, mask in masks.items() if bool(mask[0])] return {"model_version": current.version, "build": current.build_id, "pac_id": pac_id, "scenarios": names}