diff --git a/pyproject.toml b/pyproject.toml index 6e8bec8..c336e85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.12" dependencies = [ "flask>=3.0", "persistance", - "models[notebooks]", + "models[notebooks,survival-curves]", "extraction", "apache-hamilton>=1.90", "pandas>=2.0", diff --git a/tests/test_fhir_cama_risk.py b/tests/test_fhir_cama_risk.py new file mode 100644 index 0000000..6d0b149 --- /dev/null +++ b/tests/test_fhir_cama_risk.py @@ -0,0 +1,109 @@ +"""What this module covers: `GET /cama/fhir/RiskAssessment?subject=Patient/` (`webapi.fhir.cama`, built by +`webapi.fhir.risk` as CaCu's is): a patient's current mortality risk as a FHIR R4 `RiskAssessment` in a `searchset` +Bundle: its shape (status, subject, method, one prediction per horizon from the model's own index date, the interval +extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the +`CapabilityStatement` entry. The reads behind it are Persistance's, tested there. + +Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaMa demonstration +database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a total-cohort build with two of its patients, one +with a confirmed batch whose risks, at 0.5 and 1.5 years, have the model's index date. +""" + +import os +from datetime import date, datetime, timezone + +import pytest +from conftest import cliente_de + +MODEL_INDEX = date(2026, 6, 1) + + +@pytest.fixture(scope="module") +def client(tmp_path_factory): + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + with pytest.MonkeyPatch.context() as mp: + mp.setenv("DEV_REVISION", "pruebas") + yield from cliente_de("cama", tmp_path_factory) + + +@pytest.fixture(scope="module") +def seeded(client): + """Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0.5 and 1.5 years, the + 1.5-year one with an interval. Returns (scored patient, member without risks).""" + from core.cama.indicadores.models import CohorteArmado, CohorteMiembro + from persistance import cama + from persistance.db import get_cama_session + + scored, unscored = [p.pac_id for p in cama.persona_repository.list(limit=2)] + with get_cama_session() as session: + build = CohorteArmado(url="cama/cohorte_total", version="0.1.0", definicion_sha="d", reglas_sha="r", + parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk-cama", marco_sha="m", + n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)) + session.add(build) + session.flush() + session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1), + indice_fuente_tabla="biopsiamama", indice_fuente_id=str(p)) + for p in (scored, unscored)]) + session.commit() + build_id = build.armado_id + batch, _ = cama.cohort_repository.save_batch( + build_id, {"modelo_nombre": "cama-survival", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"}, + "muerte", [(scored, MODEL_INDEX, 1.5, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.5, 0.08, None, None)], + ahora=datetime(2026, 10, 1, tzinfo=timezone.utc)) + cama.cohort_repository.change_state(batch, "final", "revisado") + return scored, unscored, batch + + +def test_a_scored_patient_gets_her_risk_assessment(client, seeded): + """Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/`, evaluated + when the batch was, by the registered model and version, with one prediction per horizon whose period starts at + the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension; + tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere.""" + scored, _, batch = seeded + + response = client.get(f"/cama/fhir/RiskAssessment?subject=Patient/{scored}") + + assert response.status_code == 200 and response.mimetype == "application/fhir+json" + bundle = response.get_json() + assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1) + risk = bundle["entry"][0]["resource"] + assert bundle["entry"][0]["fullUrl"].endswith(f"/cama/fhir/RiskAssessment/{batch}-{scored}") + assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"}) + assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z" + assert risk["method"]["coding"][0]["code"] == "cama-survival" and risk["method"]["coding"][0]["version"] == "3" + assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["muerte", "muerte"] + assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [ + (0.08, {"start": "2026-06-01", "end": "2026-12-01"}), (0.21, {"start": "2026-06-01", "end": "2027-12-01"})] + assert "extension" not in risk["prediction"][0] + assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}} + assert any(t["code"] == "simulado" for t in risk["meta"]["tag"]) + + +def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded): + """Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error. + Fails if a missing risk becomes a 404 or a resource with no predictions.""" + _, unscored, _ = seeded + + for subject in (f"Patient/{unscored}", "Patient/987654321"): + bundle = client.get(f"/cama/fhir/RiskAssessment?subject={subject}").get_json() + assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry` + + +@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"]) +def test_the_risk_is_searched_by_patient(client, query): + """Pins down: without `subject=Patient/` the answer is a 400 `OperationOutcome`. Fails if the route lists + every patient's risk.""" + response = client.get(f"/cama/fhir/RiskAssessment{query}") + + assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome" + + +def test_the_capability_statement_declares_the_search(client): + """Pins down: CaMa's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient + resources stay TEA's. Fails if the route exists without being declared, or the other way round.""" + resources = client.get("/cama/fhir/metadata").get_json()["rest"][0]["resource"] + risk = [r for r in resources if r["type"] == "RiskAssessment"] + + assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}] + assert not [r for r in resources if r["type"] == "EpisodeOfCare"] diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py new file mode 100644 index 0000000..2001b6e --- /dev/null +++ b/tests/test_model_analysis.py @@ -0,0 +1,64 @@ +"""What this module covers: `GET /cama/modelo/curvas` (`webapi.model_analysis`): it serves the production version's +population record with the version it comes from, and answers 404 while there is no version in production or the +version has no such record. + +Fixtures: `client`, the app with the registry's `resolve` and `artifact` replaced by what the test says a production +version holds, so no MLflow is needed; the CaMa survival record is a small stand-in for what a run publishes. +""" + +import json +from types import SimpleNamespace + +import pytest + +RECORD = {"horizons_months": [6, 12, 18], "points": {"COMB": {"S": [0.9, 0.8, 0.7], "low": [0.8, 0.7, 0.6], "high": [0.95, 0.9, 0.8]}}} + + +@pytest.fixture +def client(monkeypatch): + from flask import Flask + + from models.io import registry as registry_module + from webapi.model_analysis import model_analysis_blueprint + + app = Flask(__name__) + app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") + monkeypatch.setenv("DEV_REVISION", "pruebas") + holder = SimpleNamespace(files={"analisis/curvas.json": json.dumps(RECORD).encode()}, production="3") + + 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-1") + + def artifact(domain, scenario, version, path): + if path not in holder.files: + raise LookupError(f"la corrida no tiene el artefacto {path!r}") + return path.rsplit("/", 1)[-1], holder.files[path] + + monkeypatch.setattr(registry_module.registry, "resolve", resolve) + monkeypatch.setattr(registry_module.registry, "artifact", artifact) + with app.test_client() as test_client: + test_client.holder = holder + yield test_client + + +def test_it_serves_the_production_versions_record_and_names_the_version(client): + """Pins down: the answer carries the record unchanged, the model and version it comes from and the simulated-data + flag. Fails if the record is altered on the way or the answer stops saying which version it is.""" + body = client.get("/cama/modelo/curvas").get_json() + + assert body["curvas"] == RECORD and body["simulado"] is True + assert body["modelo"] == {"nombre": "cama-survival", "version": "3", "mlflow_run_id": "run-1"} + + +def test_without_a_version_in_production_or_a_record_it_is_a_404(client): + """Pins down: no production version, and a version whose run published no `analisis/curvas.json`, are both a 404 + with the reason, never an empty record. Fails if either becomes a 200 or a 500.""" + client.holder.files.clear() + missing_record = client.get("/cama/modelo/curvas") + client.holder.production = None + no_version = client.get("/cama/modelo/curvas") + + assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"] + assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"] diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index f89e3dc..e0bf2dc 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -68,14 +68,16 @@ def test_volver_a_correr_no_agrega_reportes(bases): def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases): """Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores - as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from - anywhere else than dbt, or a build's count and members disagree.""" + as many members as it counts. TEA has no dbt cohorts, so no cohort step; CaCu's include the surveillance cohort + and CaMa's the total cohort. Fails if a cohort comes from anywhere else than dbt, or a build's count and members + disagree.""" proyecto, ctx, motor, _, pasos = bases - if proyecto != "cacu": + if proyecto == "tea": assert "cohorts" not in [p.name for p in pasos] return armados = [p.summary for p in pasos if p.name == "cohorts"][0] - assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados + principal = {"cacu": "cacu/cohorte_vigilancia", "cama": "cama/cohorte_total"}[proyecto] + assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and principal in armados with motor.connect() as con: assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados) for armado_id, _ in armados.values(): diff --git a/tests/test_pathology_report_wording.py b/tests/test_pathology_report_wording.py new file mode 100644 index 0000000..0828fa6 --- /dev/null +++ b/tests/test_pathology_report_wording.py @@ -0,0 +1,52 @@ +"""What this module covers: how silver reads the wording of a breast pathology report's text layer, as the hospital's +reports (and dev-data's synthetic ones) print it: the grade after a histological type that says "no especial", the +HER2 caption with its method in parentheses, and Ki-67 under its long caption. Each case is one report fragment. + +Fixtures: none; the extractor is `silver.cama.DEL_REPORTE_DE_PATOLOGIA`, fed text through `lineas_de_texto`. +""" + +import pytest + +from webapi.orchestration.silver.cama import DEL_REPORTE_DE_PATOLOGIA +from webapi.orchestration.silver.extracted import lineas_de_texto + +DIAGNOSTICO = ( + "BIOPSIA: CARCINOMA DUCTAL INFILTRANTE (CARCINOMA INVASOR DE TIPO NO ESPECIAL) (8500/3), GRADO HISTOLÓGICO {g} " + "DE NOTTINGHAM (PUNTAJE 6/9). INVASIÓN LINFOVASCULAR: NO IDENTIFICADA." +) + + +def _leer(texto: str) -> dict: + extractor = DEL_REPORTE_DE_PATOLOGIA._extraer # the cached reader of text, as `leer` calls it + return extractor(texto) + + +@pytest.mark.parametrize("grado, codigo", [(1, "G1"), (2, "G2"), (3, "G3")]) +def test_the_grade_after_a_type_that_says_no_especial_is_read(grado, codigo): + """Pins down: "TIPO NO ESPECIAL" names a histological type, it does not deny what follows, so the Nottingham grade + later in the same line is still read. Fails if "no especial" stops being a pseudo-trigger of the negation context.""" + assert _leer(DIAGNOSTICO.format(g=grado))["biopsia.grado_nottingham"][0] == codigo + + +@pytest.mark.parametrize("texto, codigo", [ + ("HER2/neu (IHQ): NEGATIVO (0)", "H0"), ("HER2/neu (IHQ): NEGATIVO (1+)", "H1"), + ("HER2/neu (IHQ): EQUÍVOCO (2+)", "H2"), ("HER2/neu (IHQ): POSITIVO (3+)", "H3"), +]) +def test_her2_is_read_with_its_method_in_the_caption(texto, codigo): + """Pins down: a caption "HER2/neu (IHQ):" gives the score that follows it, not the "(IHQ):" of its own method. + Fails if the longer captions leave the catalog's `etiquetas_fuente` for HER2.""" + assert _leer(texto)["biopsia.her2"][0] == codigo + + +def test_ki67_is_read_under_its_long_caption_and_not_from_the_name(): + """Pins down: "Índice de proliferación Ki-67: 25 %" gives 25, not the 67 of the marker's name. Fails if the long + caption leaves the catalog's `etiquetas_fuente` for Ki-67.""" + assert float(_leer("Índice de proliferación Ki-67: 25 %")["biopsia.ki67_pct"][0]) == 25.0 + + +@pytest.mark.parametrize("tipo", ["CARCINOMA MUCINOSO", "CARCINOMA TUBULAR", + "CARCINOMA DUCTAL Y LOBULILLAR INFILTRANTE (MIXTO)"]) +def test_the_rarer_invasive_types_are_read_as_other(tipo): + """Pins down: a mucinous, tubular or mixed carcinoma is read as `OTRO` rather than left unresolved or taken as + ductal or lobular. Fails if their aliases leave the catalog.""" + assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == "OTRO" diff --git a/uv.lock b/uv.lock index 36bfe76..451ff3f 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -2068,32 +2068,64 @@ notebooks = [ { name = "nbclient" }, { name = "nbconvert" }, ] +survival-curves = [ + { name = "mpmath" }, + { name = "scipy" }, +] [package.metadata] requires-dist = [ { name = "apache-hamilton", specifier = ">=1.90" }, + { name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" }, { name = "extraction", editable = "../Extraction" }, { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, + { name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" }, { name = "mlflow", specifier = ">=2.9" }, + { name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" }, + { name = "mpmath", marker = "extra == 'survival-curves'", specifier = ">=1.3" }, { name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" }, { name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" }, + { name = "networkx", marker = "extra == 'seer-survival'", specifier = ">=3.0" }, { name = "pandas", specifier = ">=2.0" }, { name = "pandera", specifier = ">=0.20" }, { name = "persistance", editable = "../Persistance" }, + { name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" }, { name = "pyarrow", specifier = ">=15" }, { name = "scikit-learn", specifier = ">=1.4" }, + { name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" }, + { name = "scipy", marker = "extra == 'survival-curves'", specifier = ">=1.11" }, + { name = "statsmodels", marker = "extra == 'seer-survival'", specifier = ">=0.14" }, { name = "tea", editable = "../models/libs/tea" }, { name = "tea", extras = ["s3"], marker = "extra == 'eeg-reference'", editable = "../models/libs/tea" }, ] -provides-extras = ["eeg-reference", "notebooks"] +provides-extras = ["eeg-reference", "notebooks", "seer-survival", "survival-curves", "seer-survival-dca"] [package.metadata.requires-dev] dev = [ { name = "ipykernel", specifier = ">=6.29" }, + { name = "matplotlib", specifier = ">=3.8" }, + { name = "mpmath", specifier = ">=1.3" }, { name = "nbclient", specifier = ">=0.10" }, { name = "nbconvert", specifier = ">=7.16" }, + { name = "networkx", specifier = ">=3.0" }, + { name = "pgmpy", specifier = ">=1.0" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, + { name = "scipy", specifier = ">=1.11" }, + { name = "statsmodels", specifier = ">=0.14" }, +] +notebooks = [ + { name = "graphviz", specifier = ">=0.20" }, + { name = "ipykernel", specifier = ">=6.29" }, +] + +[[package]] +name = "mpmath" +version = "1.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" }, ] [[package]] @@ -4503,7 +4535,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "models", extra = ["notebooks"] }, + { name = "models", extra = ["notebooks", "survival-curves"] }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -4539,7 +4571,7 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "models", extras = ["notebooks"], editable = "../models" }, + { name = "models", extras = ["notebooks", "survival-curves"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, { name = "pdfplumber", specifier = ">=0.11" }, diff --git a/webapi/__init__.py b/webapi/__init__.py index fd5a899..3a8323f 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -95,13 +95,17 @@ def create_app() -> Flask: # Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's # `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined. from persistance import cacu as cacu_repositories + 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.risk_batches import risk_batches_blueprint 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(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") return app diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index 330c5d4..0cab556 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -9,7 +9,7 @@ individual risk. GET CodeSystem, CodeSystem/, ValueSet/ the project's code systems GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only) GET Patient//$resumen-tea TEA's patient summary (DEV only) - GET RiskAssessment?subject=Patient/ CaCu's individual risk, the current batch (DEV only) + GET RiskAssessment?subject=Patient/ CaCu's and CaMa's individual risk, the current batch (DEV only) Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are `OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`. @@ -28,6 +28,7 @@ from webapi.fhir.terminology import code_systems, metric_value_set from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of from webapi.metrics import Question, UndecidedRule +RISK_DOMAINS = ("cacu", "cama") # the domains whose patients' individual risk is served as a RiskAssessment TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion") @@ -38,7 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: blueprint = Blueprint(f"{project}_fhir", __name__) titles = labels(manifest) patients = with_patients and project == "tea" - risks = with_patients and project == "cacu" + risks = with_patients and project in RISK_DOMAINS def definitions() -> dict: """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" @@ -176,13 +177,15 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: if patients: _patient_routes(blueprint, repositories, now) if risks: - _risk_routes(blueprint, repositories) + _risk_routes(blueprint, repositories, project) return blueprint -def _risk_routes(blueprint: Blueprint, repositories) -> None: - """CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data).""" - from webapi.fhir import cacu +def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None: + """A patient's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data).""" + from importlib import import_module + + domain = import_module(f"webapi.fhir.{project}") @blueprint.get("/RiskAssessment") def risk_assessments(): @@ -196,7 +199,7 @@ def _risk_routes(blueprint: Blueprint, repositories) -> None: return outcome(400, "invalid", str(error)) pac_id = int(reference) risk = repositories.cohort_repository.current_risk(pac_id) - found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())] + found = [] if risk is None else [domain.risk_assessment(pac_id, risk, simulated_data())] return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset)) diff --git a/webapi/fhir/cacu.py b/webapi/fhir/cacu.py index 46e3765..7d96a75 100644 --- a/webapi/fhir/cacu.py +++ b/webapi/fhir/cacu.py @@ -1,62 +1,12 @@ -"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data). +"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by +`webapi.fhir.risk` with CaCu's outcomes.""" -The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed -evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient: +from webapi.fhir import risk +from webapi.fhir.risk import DAYS_PER_YEAR, INTERVAL, MODEL, OUTCOME # noqa: F401 (kept for readers of this module) - id `-` - status the batch's state (`final`) - subject `Patient/`: CaCu's follow-up list uses the platform's `pac_id` (TEA keeps a - pseudonym until its patients get their own identity) - occurrenceDateTime when the batch was evaluated - method the registered model and its version (MLflow) - prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod` - from the risk's index date (the model's decision point) to that date plus the horizon; - the immediate risk (horizon 0) is a period of one day. A confidence interval, when the - model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a - decimal or a range, not both). - -Not yet: `basis` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical -action thresholds are for CIN3+; the outcome here is CIN2+). -""" - -from datetime import date, datetime, timedelta, timezone - -from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged - -OUTCOME = f"{CODE_SYSTEM}/desenlace" -MODEL = f"{CODE_SYSTEM}/modelo" -INTERVAL = f"{STRUCTURE}/intervalo-confianza" OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"} -DAYS_PER_YEAR = 365.25 -def _utc(moment: datetime) -> str: - moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc) - return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _until(start: date, years: float) -> date: - return start + timedelta(days=round(years * DAYS_PER_YEAR)) - - -def _prediction(horizon, outcome: dict, start: date | None) -> dict: - item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad} - if start is not None: - item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()} - if horizon.ic_bajo is not None and horizon.ic_alto is not None: - item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo}, - "high": {"value": horizon.ic_alto}}}] - return item - - -def risk_assessment(pac_id: int, risk, simulated: bool) -> dict: +def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict: """The patient's current risk (`PatientRisk`) as a `RiskAssessment`.""" - desenlace = risk.desenlace or "cin2_mas" - outcome = concept(OUTCOME, desenlace, OUTCOMES.get(desenlace)) - resource = { - "resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote, - "subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en), - "method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]}, - "prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes], - } - return tagged(resource, simulated) + return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "cin2_mas") diff --git a/webapi/fhir/cama.py b/webapi/fhir/cama.py new file mode 100644 index 0000000..54e51cd --- /dev/null +++ b/webapi/fhir/cama.py @@ -0,0 +1,11 @@ +"""CaMa's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by +`webapi.fhir.risk` with CaMa's outcomes: the mortality at each horizon from the model's index date.""" + +from webapi.fhir import risk + +OUTCOMES = {"muerte": "Muerte por cualquier causa"} + + +def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict: + """The patient's current risk (`PatientRisk`) as a `RiskAssessment`.""" + return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "muerte") diff --git a/webapi/fhir/risk.py b/webapi/fhir/risk.py new file mode 100644 index 0000000..84bf7b6 --- /dev/null +++ b/webapi/fhir/risk.py @@ -0,0 +1,60 @@ +"""A patient's individual risk in FHIR R4: one `RiskAssessment` per batch and patient, built from `PatientRisk` +(`CohortRepository.current_risk`: the newest batch with a confirmed evaluation). + + id `-` + status the batch's state (`final`) + subject `Patient/`: the platform's key (TEA keeps a pseudonym until its patients get + their own identity) + occurrenceDateTime when the batch was evaluated + method the registered model and its version (MLflow) + prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod` + from the risk's index date (the model's decision point) to that date plus the horizon; + the immediate risk (horizon 0) is a period of one day. A confidence interval, when the + model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a + decimal or a range, not both). + +Not yet: `basis` (the observations the model used) and `mitigation`. Each domain gives its outcomes' codes and labels +(`webapi.fhir.cacu`, `webapi.fhir.cama`). +""" + +from datetime import date, datetime, timedelta, timezone + +from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged + +OUTCOME = f"{CODE_SYSTEM}/desenlace" +MODEL = f"{CODE_SYSTEM}/modelo" +INTERVAL = f"{STRUCTURE}/intervalo-confianza" +DAYS_PER_YEAR = 365.25 + + +def _utc(moment: datetime) -> str: + moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc) + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _until(start: date, years: float) -> date: + return start + timedelta(days=round(years * DAYS_PER_YEAR)) + + +def _prediction(horizon, outcome: dict, start: date | None) -> dict: + item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad} + if start is not None: + item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()} + if horizon.ic_bajo is not None and horizon.ic_alto is not None: + item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo}, + "high": {"value": horizon.ic_alto}}}] + return item + + +def risk_assessment(pac_id: int, risk, simulated: bool, outcomes: dict[str, str], default_outcome: str) -> dict: + """The patient's current risk (`PatientRisk`) as a `RiskAssessment`; `outcomes` maps the domain's outcome codes to + their labels, and `default_outcome` stands for a batch that doesn't name one.""" + desenlace = risk.desenlace or default_outcome + outcome = concept(OUTCOME, desenlace, outcomes.get(desenlace)) + resource = { + "resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote, + "subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en), + "method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]}, + "prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes], + } + return tagged(resource, simulated) diff --git a/webapi/imports/schemas/cama/paciente.py b/webapi/imports/schemas/cama/paciente.py index 563d434..5bdf32c 100644 --- a/webapi/imports/schemas/cama/paciente.py +++ b/webapi/imports/schemas/cama/paciente.py @@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import ( Catalog, CatalogValue, + FlexDate, PostalCode, RequiredDate, RequiredHospitalId, @@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema): pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None # IND-01: required, since age at each event of interest is derived from it. pac_fecha_nacimiento: RequiredDate + # Survival's outcome; empty while she is alive or the date is unknown. + pac_fecha_defuncion: FlexDate = None pac_codigo_postal: PostalCode = None pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py new file mode 100644 index 0000000..95f9359 --- /dev/null +++ b/webapi/model_analysis.py @@ -0,0 +1,35 @@ +"""What a model's production version found about its cohort: `GET //modelo/curvas`. + +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 flask import Blueprint, jsonify + +from webapi.fhir.common import simulated_data + + +def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: + """The blueprint of one scenario, to register with `url_prefix="/"`.""" + 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)}) + + return blueprint diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py index 31a762c..709d219 100644 --- a/webapi/orchestration/estimators.py +++ b/webapi/orchestration/estimators.py @@ -25,15 +25,16 @@ class Provenance: return {key: value for key, value in self.__dict__.items() if value} -class Cin2LogisticEstimator: - """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to - test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has - something to report when `estimate` calls it.""" +class ScenarioEstimator: + """Scores a domain's cohort with the version of one scenario that is in production (or `version`, to test a + candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has something to + report when `estimate` calls it.""" - def __init__(self, domain: str = "cacu", version: str | None = None): + def __init__(self, domain: str, scenario: str, version: str | None = None): self.domain = domain + self.scenario = scenario self.version = version - self.desenlace = "cin2_mas" + self.desenlace = "" self._provenance: Provenance | None = None def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: @@ -49,7 +50,7 @@ class Cin2LogisticEstimator: from models.steps.risks import risk_rows repos = import_module(f"persistance.{self.domain}") - scenario = Scenario.load(self.domain, "cin2_logistic") + scenario = Scenario.load(self.domain, self.scenario) build_id = repos.cohort_repository.latest_build(scenario.cohort) resolved = registry.resolve(self.domain, scenario.scenario, self.version) frame = KitBuild(self.domain, build_id).frame() @@ -67,11 +68,39 @@ class Cin2LogisticEstimator: return self._provenance +class Cin2LogisticEstimator(ScenarioEstimator): + """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`).""" + + def __init__(self, domain: str = "cacu", version: str | None = None): + super().__init__(domain, "cin2_logistic", version) + self.desenlace = "cin2_mas" + + +# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production +# scores the cohort it names. +LIVE_SCENARIOS = {"cama": ("survival",)} + + +def _scenario_estimators(domain: str) -> dict[str, Any]: + from models.dags.training import Scenario + from models.io.registry import registry + + found = {} + for name in LIVE_SCENARIOS.get(domain, ()): + scenario = Scenario.load(domain, name) + try: + registry.resolve(domain, name) + except LookupError: + continue + found[scenario.cohort] = ScenarioEstimator(domain, name) + return found + + def live_estimators(domain: str) -> dict[str, Any]: """The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" if domain != "cacu": - return {} + return _scenario_estimators(domain) from models.dags.training import Scenario from models.io.registry import registry diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py index 613c760..ae7f31e 100644 --- a/webapi/orchestration/silver/persons.py +++ b/webapi/orchestration/silver/persons.py @@ -25,6 +25,12 @@ def de_derechohabiente(paciente) -> dict: } +def con_defuncion(paciente) -> dict: + """Lo de `de_derechohabiente` y la fecha de defunción, el desenlace de la supervivencia: nula mientras vive o si se + desconoce.""" + return {**de_derechohabiente(paciente), "fecha_defuncion": paciente.pac_fecha_defuncion} + + def con_sexo(paciente) -> dict: """Lo que la persona de TEA agrega: el sexo, como código.""" return {"sexo": codigo(paciente.pac_sexo)} diff --git a/webapi/orchestration/tables/cama.py b/webapi/orchestration/tables/cama.py index c1a7b5f..da4c23b 100644 --- a/webapi/orchestration/tables/cama.py +++ b/webapi/orchestration/tables/cama.py @@ -34,7 +34,7 @@ from core.cama.indicadores.models import ( Persona, ) -from webapi.orchestration.silver.persons import de_derechohabiente +from webapi.orchestration.silver.persons import con_defuncion from core.indicadores.cohortes import TablasCohorte from webapi.orchestration.tables import TablasKit @@ -63,7 +63,7 @@ TABLAS = TablasKit( CatMeasureEstrato=CatMeasureEstrato, MeasureReportUnidad=MeasureReportUnidad, MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, - persona_propias=de_derechohabiente, + persona_propias=con_defuncion, ) # Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12). diff --git a/webapi/risk_batches.py b/webapi/risk_batches.py index 3319d6c..8e739fe 100644 --- a/webapi/risk_batches.py +++ b/webapi/risk_batches.py @@ -9,9 +9,10 @@ from flask import Blueprint, jsonify, request from persistance.edges.gold import ERROR, FINAL -def risk_batches_blueprint(repositories) -> Blueprint: - """The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`.""" - blueprint = Blueprint("risk_batches", __name__) +def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprint: + """The blueprint, to register with `url_prefix="/"`. `repositories` is `persistance.`; `name` is + unique per domain registered.""" + blueprint = Blueprint(name, __name__) @blueprint.get("/riesgos/lotes") def list_pending_batches():