diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index cdb7630..0f443b9 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -139,3 +139,56 @@ def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_cl assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"] assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422 assert live_client.get("/cama/modelo/escenarios").status_code == 422 + + +@pytest.fixture +def recurrence_client(monkeypatch): + """The recurrence route on a bare app, with the registry's production version, its recurrence record and the labelled members + replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" + import pandas as pd + from flask import Flask + + from models.io import registry as registry_module + from webapi import model_analysis + + record = {"horizons_months": [12, 36, 60], "escenarios": [ + {"cohorte": "metabric", "escenario": "< 45 años", "condiciones": {"Edad": ["<45"]}, "n": 100}, + {"cohorte": "metabric", "escenario": "RE− · grado 3", "condiciones": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, "n": 300}, + {"cohorte": "metabric", "escenario": "Ganglios 4+", "condiciones": {"Ganglios_positivos": ["4+"]}, "n": 80}, + {"cohorte": "scanb", "escenario": "Grado 3", "condiciones": {"Grado_histologico": ["3"]}, "n": 900}]} + labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]}) + holder = SimpleNamespace(production="2") + + def resolve(domain, scenario, version=None): + if holder.production is None: + raise LookupError("no hay una versión en producción") + return SimpleNamespace(version=holder.production, run_id="run-2") + + monkeypatch.setattr(registry_module.registry, "resolve", resolve) + monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: ("recurrencia.json", json.dumps(record).encode())) + monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) + app = Flask(__name__) + app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama") + with app.test_client() as client: + client.holder = holder + yield client + + +def test_a_patient_gets_the_recurrence_scenarios_her_covariates_meet(recurrence_client): + """Pins down: `GET /cama/modelo/recurrencia?paciente=7` returns the scenarios whose every condition her age, grade and + receptors meet (one that needs the nodes, which the hospital does not report, is left out), the larger first within a + cohort, with the version that published them. Fails if a scenario she does not meet is returned, a missing covariate counts + as met, or the version is not named.""" + body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json() + + assert [(s["cohorte"], s["escenario"]) for s in body["escenarios"]] == [("metabric", "RE− · grado 3"), ("metabric", "< 45 años"), ("scanb", "Grado 3")] + assert body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + + +def test_without_a_recurrence_version_or_for_a_stranger_it_says_so(recurrence_client): + """Pins down: no recurrence version in production is a 404, a patient outside the cohort or no patient is a 422 with a reason. + Fails if either becomes a 200 with nothing or a 500.""" + assert recurrence_client.get("/cama/modelo/recurrencia?paciente=99").status_code == 422 + assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 422 + recurrence_client.holder.production = None + assert recurrence_client.get("/cama/modelo/recurrencia?paciente=7").status_code == 404 diff --git a/tests/test_training_jobs.py b/tests/test_training_jobs.py index 1a7f22d..5c9f827 100644 --- a/tests/test_training_jobs.py +++ b/tests/test_training_jobs.py @@ -50,6 +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 @pytest.mark.parametrize("code,estado", [ @@ -115,3 +116,17 @@ def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypat assert tea[tea.index("--reference-dir") + 1] == "/referencia" and tea[tea.index("--reference-ages") + 1] == "/referencia/edades.csv" 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) + + 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" diff --git a/uv.lock b/uv.lock index 729b021..ce6d0b9 100644 --- a/uv.lock +++ b/uv.lock @@ -299,6 +299,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "autograd" +version = "1.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/ac/4a8b58364ba865ab545251edbe475e5a35326814a5d274a2211d33ed8a5d/autograd-1.9.1.tar.gz", hash = "sha256:7818c5c69ddf9efb7da74097bd741a4c7920133f41966f68537223a15ef798bc", size = 2566975, upload-time = "2026-07-02T07:43:58.255Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/ce/8c98e6604bb1ec9d03c8493c328185b69bb7533fe08f3640f0f3641bd9d1/autograd-1.9.1-py3-none-any.whl", hash = "sha256:b788bae3fa010cbffb4cfb7b8ba2a3f0daa6072a8506da6164c779fe9cf3e05a", size = 54387, upload-time = "2026-07-02T07:43:56.502Z" }, +] + +[[package]] +name = "autograd-gamma" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "autograd" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/ae/7f2031ea76140444b2453fa139041e5afd4a09fc5300cfefeb1103291f80/autograd-gamma-0.5.0.tar.gz", hash = "sha256:f27abb7b8bb9cffc8badcbf59f3fe44a9db39e124ecacf1992b6d952934ac9c4", size = 3952, upload-time = "2020-10-15T16:51:06.785Z" } + [[package]] name = "beautifulsoup4" version = "4.15.0" @@ -1783,6 +1805,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" }, ] +[[package]] +name = "lifelines" +version = "0.30.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "autograd" }, + { name = "autograd-gamma" }, + { name = "formulaic" }, + { name = "matplotlib" }, + { name = "numpy" }, + { name = "pandas" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ea/4f/f0b363278d40baf7d7a03217bee839cb880946c62109f243391c8754bb09/lifelines-0.30.0.tar.gz", hash = "sha256:f7f6f6275fcb167fe0f5b1ef98f868993f9c074cb74b1dd6e92736efa854be18", size = 383221, upload-time = "2024-10-29T12:00:43.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/f7/379e185a75ac8166ac70756d0ba68d9a2b02b555c7fde4983246752396bd/lifelines-0.30.0-py3-none-any.whl", hash = "sha256:ac7c602c8aceced9770d3977817c9d99c250ed8cd86f2567fa0d23e4e8014bf9", size = 349319, upload-time = "2024-10-29T12:00:41.749Z" }, +] + [[package]] name = "lightgbm" version = "4.7.0" @@ -2161,6 +2201,7 @@ notebooks = [ { name = "nbconvert" }, ] seer-survival = [ + { name = "lifelines" }, { name = "matplotlib" }, { name = "mpmath" }, { name = "networkx" }, @@ -2179,6 +2220,7 @@ requires-dist = [ { name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" }, { name = "extraction", editable = "../Extraction" }, { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, + { name = "lifelines", marker = "extra == 'seer-survival'", specifier = ">=0.28" }, { name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" }, { name = "mlflow", specifier = ">=2.9" }, { name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" }, diff --git a/webapi/__init__.py b/webapi/__init__.py index 3a8323f..82e564e 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -98,7 +98,7 @@ def create_app() -> Flask: from persistance import cama as cama_repositories from persistance.db import get_cacu_session, get_cama_session - from webapi.model_analysis import model_analysis_blueprint + from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint from webapi.risk_batches import risk_batches_blueprint app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") @@ -107,5 +107,6 @@ def create_app() -> Flask: 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") app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") + app.register_blueprint(recurrence_blueprint(), url_prefix="/cama") return app diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 4941954..6e6a1ab 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -127,3 +127,37 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: 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=` + 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 diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py index 4ce244a..6b5feea 100644 --- a/webapi/training_jobs.py +++ b/webapi/training_jobs.py @@ -17,7 +17,8 @@ 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 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. OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."} @@ -35,13 +36,13 @@ def catalog() -> list[dict]: domain = spec.get("domain") if domain is None: continue - own = domain in OWN_STEPS + own = domain in OWN_STEPS or bool(spec.get("external")) if not own and "scenario" not in spec: continue found.append({ "domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"), "outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()), - "kind": "referencia" if own else "cohorte", + "kind": "referencia" if own else "cohorte", "external": own, }) return found @@ -52,7 +53,8 @@ def _base() -> Path: def _command(domain: str, scenario: str) -> list[str]: argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] - if domain not in OWN_STEPS: + external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) + if not external: argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"): # A reference cohort on this machine's disk, instead of the configured one in the cluster's storage. @@ -100,7 +102,7 @@ def start(domain: str, scenario: str) -> dict: """Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest.""" if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}: raise LookupError(f"no such model: {domain}/{scenario}") - if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"): + if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"): raise RuntimeError("No hay un manifest de dbt configurado.") job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}" folder = _base() / job_id