CaMa: the patient import takes the recurrence variables again, recurrence trains on the cohort export, the second survival route is retired
This commit is contained in:
@@ -50,7 +50,7 @@ def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings
|
||||
assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries
|
||||
assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte"
|
||||
assert ("cama", "seer_survival") not in entries
|
||||
assert entries[("cama", "recurrence")]["kind"] == "referencia" # trained on its external files, not on a dbt cohort
|
||||
assert entries[("cama", "recurrence")]["kind"] == "cohorte" # the patients loaded from METABRIC and SCAN-B
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code,estado", [
|
||||
@@ -118,15 +118,12 @@ def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypat
|
||||
assert "--manifest" not in tea and "--reference-dir" not in cama
|
||||
|
||||
|
||||
def test_a_scenario_with_external_data_trains_without_a_dbt_export_or_manifest(monkeypatch):
|
||||
"""Pins down: CaMa's recurrence scenario, whose training data are files, is started with no `--export`, `--manifest` or dbt
|
||||
manifest, while CaMa's survival scenario still is. Fails if an external scenario is refused for want of a manifest or run
|
||||
through the cohort export, which would train it on the wrong data."""
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
def test_cama_recurrence_trains_on_the_cohort_export_like_survival(monkeypatch):
|
||||
"""Pins down: CaMa's recurrence scenario, trained on the patients loaded from METABRIC and SCAN-B, is started with the
|
||||
cohort export and the dbt manifest, as survival is. Fails if it is run without a database build, which would leave it
|
||||
with no patients."""
|
||||
monkeypatch.setenv("DBT_MANIFEST", "m.json")
|
||||
|
||||
recurrence = training_jobs._command("cama", "recurrence")
|
||||
monkeypatch.setenv("DBT_MANIFEST", "m.json")
|
||||
survival = training_jobs._command("cama", "survival")
|
||||
|
||||
assert "--export" not in recurrence and "--manifest" not in recurrence
|
||||
assert "--export" in survival and survival[survival.index("--manifest") + 1] == "m.json"
|
||||
assert "--export" in recurrence and recurrence[recurrence.index("--manifest") + 1] == "m.json"
|
||||
@@ -13,7 +13,6 @@ from webapi.blueprints.reports import reports_bp
|
||||
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
|
||||
from webapi.cama_recurrence.routes import cama_recurrence_bp
|
||||
from webapi.cama_survival.routes import cama_survival_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
@@ -106,7 +105,6 @@ def create_app() -> Flask:
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
||||
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
||||
app.register_blueprint(cama_survival_bp, url_prefix="/cama/supervivencia")
|
||||
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
|
||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
"""CaMa's survival figures over the model in production.
|
||||
|
||||
service.py the production model and the live cohort, a scenario's figure and a patient's scenarios, cached
|
||||
routes.py the routes: `/cama/supervivencia/...`
|
||||
"""
|
||||
@@ -1,37 +0,0 @@
|
||||
"""`/cama/supervivencia`: the survival figure of a clinical scenario and the scenarios of a patient."""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from werkzeug.exceptions import BadRequest, NotFound
|
||||
|
||||
from webapi.cama_survival import service
|
||||
|
||||
cama_survival_bp = Blueprint("cama_survival", __name__)
|
||||
|
||||
|
||||
@cama_survival_bp.errorhandler(service.NotAvailable)
|
||||
def _not_available(error):
|
||||
return jsonify({"error": str(error)}), 404
|
||||
|
||||
|
||||
@cama_survival_bp.get("/escenarios")
|
||||
def scenarios():
|
||||
return jsonify(service.scenarios())
|
||||
|
||||
|
||||
@cama_survival_bp.get("/figura")
|
||||
def figure():
|
||||
scenario = request.args.get("escenario", "").strip()
|
||||
if not scenario:
|
||||
raise BadRequest("falta el parámetro «escenario»")
|
||||
try:
|
||||
return jsonify(service.figure(scenario))
|
||||
except KeyError:
|
||||
raise NotFound(f"el modelo no define el escenario «{scenario}»")
|
||||
|
||||
|
||||
@cama_survival_bp.get("/pacientes/<int:pac_id>")
|
||||
def patient(pac_id: int):
|
||||
try:
|
||||
return jsonify(service.patient_scenarios(pac_id))
|
||||
except KeyError:
|
||||
raise NotFound("la paciente no está en la cohorte")
|
||||
@@ -1,124 +0,0 @@
|
||||
"""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}
|
||||
@@ -31,3 +31,15 @@ class PacienteImportSchema(ImportSchema):
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_estado_civil: Optional[str] = None
|
||||
pac_raza: Optional[str] = None
|
||||
pac_brca1: Optional[str] = None
|
||||
pac_brca2: Optional[str] = None
|
||||
pac_estado_menopausico: Optional[str] = None
|
||||
pac_pam50: Optional[str] = None
|
||||
pac_subtipo_clinico: Optional[str] = None
|
||||
pac_cluster_integrativo: Optional[str] = None
|
||||
pac_celularidad: Optional[str] = None
|
||||
pac_carga_mutacional: Optional[float] = None
|
||||
pac_ki67_categoria: Optional[str] = None
|
||||
pac_fuente: Optional[str] = None
|
||||
|
||||
@@ -17,8 +17,7 @@ from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
TAIL_CHARS = 4000
|
||||
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its
|
||||
# `model.toml` does too, whatever its domain.
|
||||
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build.
|
||||
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."}
|
||||
|
||||
|
||||
@@ -36,7 +35,7 @@ def catalog() -> list[dict]:
|
||||
domain = spec.get("domain")
|
||||
if domain is None:
|
||||
continue
|
||||
own = domain in OWN_STEPS or bool(spec.get("external"))
|
||||
own = domain in OWN_STEPS
|
||||
if not own and "scenario" not in spec:
|
||||
continue
|
||||
found.append({
|
||||
|
||||
Reference in New Issue
Block a user