Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 14e11e20b6 | |||
| 0c102d89f7 | |||
| c2b18d9969 |
@@ -2,7 +2,7 @@
|
||||
set -e
|
||||
|
||||
# The notebook runner shares the image but runs with no network, a read-only
|
||||
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
|
||||
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
|
||||
if [ "$1" = "notebooks" ]; then
|
||||
exec /app/WebApi/.venv/bin/python -m models notebooks serve
|
||||
fi
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
2026-11-22T10:18:21+00:00
|
||||
+1
-1
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models[notebooks,seer-survival]",
|
||||
"models[notebooks]",
|
||||
"extraction",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
|
||||
File diff suppressed because one or more lines are too long
+8
-18
@@ -16,9 +16,9 @@ armado = [
|
||||
]
|
||||
lote_final = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, fecha_indice = 2025-08-01, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
|
||||
[[caso]]
|
||||
@@ -34,16 +34,6 @@ incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el periodo es el de la fecha índice del riesgo, no la del miembro"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-09-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
espera."2025-S2" = { "cat:BAJO" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "los cortes son parámetros"
|
||||
incluye = ["armado", "lote_final"]
|
||||
@@ -56,7 +46,7 @@ nombre = "un lote preliminar más nuevo no desplaza al vigente"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
|
||||
@@ -64,7 +54,7 @@ espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
nombre = "una evaluación anulada en su versión 2 queda sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
|
||||
|
||||
@@ -73,7 +63,7 @@ nombre = "una evaluación a otro horizonte no cuenta"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
@@ -82,7 +72,7 @@ nombre = "sin lote confirmado no hay población"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
@@ -92,6 +82,6 @@ filas = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""What this module covers: the publication metadata of CaCu's FHIR `Measure`s (figures, category captions and the
|
||||
optional category groups) read from dbt's manifest alone, and the checks that keep a composition's groups consistent.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
|
||||
reference parameters, whose CaCu catalogs and lists hold the captions, colours and memberships the dbt definitions
|
||||
repeat; Transformation's `dbt_project.yml` next to the manifest, whose variables repeat the same lists.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tomllib
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
|
||||
from webapi.compositions import CompositionAnswer, InvalidCategoryGroups, category_groups
|
||||
from webapi.fhir.measures import CATEGORY_GROUP, CATEGORY_LABEL, FIGURES, labels, measure_report, measure_resource
|
||||
from webapi.kpis import definitions_of
|
||||
|
||||
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
|
||||
GROUPED = {"CACU-EU7": "citologia_anomala", "CACU-CONFIRMACION-CITOLOGIA": "deteccion_grados"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
def _measures(domain: str, manifest: Path) -> dict[str, dict]:
|
||||
titles = labels(manifest)
|
||||
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
|
||||
for d in definitions_of(domain, manifest).values()}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measures(manifest):
|
||||
"""Each CaCu measure as the API serves it, by its FHIR id."""
|
||||
return _measures("cacu", manifest)
|
||||
|
||||
|
||||
def reference(*keys: str):
|
||||
with REFERENCE.open("rb") as f:
|
||||
node = tomllib.load(f)
|
||||
for key in keys:
|
||||
node = node[key]
|
||||
return node["valor"]
|
||||
|
||||
|
||||
def figures(measure: dict) -> list[str]:
|
||||
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
|
||||
|
||||
|
||||
def categories(measure: dict) -> dict[str, dict[str, str]]:
|
||||
"""The measure's declared categories, in order: code -> its parts (etiqueta, color and, if any, grupo)."""
|
||||
return {part["codigo"]: part for part in (
|
||||
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
|
||||
for e in measure["extension"] if e["url"] == CATEGORY_LABEL)}
|
||||
|
||||
|
||||
def groups(measure: dict) -> dict[str, str]:
|
||||
"""The measure's category groups, in order: code -> caption."""
|
||||
return {part["codigo"]: part["etiqueta"] for part in (
|
||||
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
|
||||
for e in measure["extension"] if e["url"] == CATEGORY_GROUP)}
|
||||
|
||||
|
||||
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
|
||||
"""Pins down: the two distributions offer the donut and the bars and the four durations their box plot; the C1
|
||||
proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared
|
||||
that the page has no builder for, or one is dropped."""
|
||||
assert {i: figures(m) for i, m in measures.items()} == {
|
||||
"CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"],
|
||||
"CACU-DIAS-TOMA-TRATAMIENTO": ["fig_c3r_caja"], "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO": ["fig_c3r_caja"],
|
||||
"CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []}
|
||||
|
||||
|
||||
def test_the_category_captions_are_the_reference_catalogs(measures):
|
||||
"""Pins down: the captions, colours and order of the cytology distribution equal `cacu.catalogos.citologia` plus
|
||||
`cacu.catalogos.sin_dato`, and the confirmation's grades `cacu.catalogos.biopsia`. Fails if either side is edited
|
||||
without the other."""
|
||||
sin_dato = reference("cacu", "catalogos", "sin_dato")
|
||||
citologia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "citologia")}
|
||||
eu7 = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-EU7"]).items()}
|
||||
assert eu7 == {**citologia, "SIN_DATO": (sin_dato["etiqueta"], sin_dato["color"])}
|
||||
biopsia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "biopsia")}
|
||||
confirmacion = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-CONFIRMACION-CITOLOGIA"]).items()}
|
||||
assert list(confirmacion)[:len(biopsia)] == list(biopsia)
|
||||
assert {c: confirmacion[c] for c in biopsia} == biopsia
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
|
||||
def test_the_anomalous_group_is_the_reference_list(measures, manifest, fhir_id):
|
||||
"""Pins down: a grouped composition's ANORMAL members are exactly the parameter list the grouping is defined by
|
||||
(`cacu.citologia_anomala` for EU7, `cacu.deteccion_grados` for the confirmation) and the dbt variable of the same
|
||||
name; the other declared categories are NO_ANORMAL, «Sin dato» its own group and «Sin biopsia aún» none. Fails if
|
||||
a membership drifts from the lists the measures count with."""
|
||||
yaml = pytest.importorskip("yaml")
|
||||
lista = GROUPED[fhir_id]
|
||||
project = manifest.parent.parent / "dbt_project.yml"
|
||||
dbt_vars = yaml.safe_load(project.read_text(encoding="utf-8"))["vars"] if project.exists() else None
|
||||
parts = categories(measures[fhir_id])
|
||||
anomalous = sorted(c for c, p in parts.items() if p.get("grupo") == "ANORMAL")
|
||||
assert anomalous == sorted(reference("cacu", lista))
|
||||
if dbt_vars is not None:
|
||||
assert anomalous == sorted(dbt_vars[lista])
|
||||
assert all(p.get("grupo") == "NO_ANORMAL" for c, p in parts.items()
|
||||
if c not in anomalous and c not in ("SIN_DATO", "SIN_BIOPSIA"))
|
||||
assert parts["SIN_DATO"]["grupo"] == "SIN_DATO"
|
||||
assert "grupo" not in parts.get("SIN_BIOPSIA", {})
|
||||
|
||||
|
||||
def test_the_group_captions_are_the_reference_ones(measures):
|
||||
"""Pins down: EU7's groups are `cacu.catalogos.resultado_anormal` plus «Sin dato», and the confirmation's
|
||||
«Menor que LIEAG» / «LIEAG o más» plus its no-data category's caption, in that order. Fails if a caption drifts."""
|
||||
resultado = {e["clave"]: e["etiqueta"] for e in reference("cacu", "catalogos", "resultado_anormal")}
|
||||
assert groups(measures["CACU-EU7"]) == {**resultado, "SIN_DATO": "Sin dato"}
|
||||
assert groups(measures["CACU-CONFIRMACION-CITOLOGIA"]) == {
|
||||
"NO_ANORMAL": "Menor que LIEAG", "ANORMAL": "LIEAG o más", "SIN_DATO": "Biopsia sin grado"}
|
||||
|
||||
|
||||
def test_measures_without_groups_publish_none(manifest, measures):
|
||||
"""Pins down: groups are opt-in. CaCu's other measures and every CaMa and TEA measure publish neither a
|
||||
`categoria-grupo` nor a `grupo` inside a category. Fails if the new extensions leak onto measures that don't
|
||||
declare them (their clients see exactly what they see without groups)."""
|
||||
others = {**{i: m for i, m in measures.items() if i not in GROUPED},
|
||||
**_measures("cama", manifest), **_measures("tea", manifest)}
|
||||
for fhir_id, measure in others.items():
|
||||
assert not groups(measure), fhir_id
|
||||
assert all("grupo" not in part for part in categories(measure).values()), fhir_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
|
||||
def test_a_grouped_measure_is_valid_fhir_r4b(measures, fhir_id):
|
||||
"""Pins down: the nested `grupo` and the `categoria-grupo` extensions keep the Measure valid FHIR R4B. Fails if
|
||||
the extensions are shaped in a way FHIR's models reject."""
|
||||
get_fhir_model_class("Measure").model_validate(measures[fhir_id])
|
||||
|
||||
|
||||
def test_a_composite_stratum_carries_its_caption(manifest):
|
||||
"""Pins down: in a composition's report, a stratum value of a crossed stratifier (status by result) carries the
|
||||
caption of `meta.etiquetas_estrato` as its display, and a value without one (an age group) keeps the code alone.
|
||||
Fails if the captions stop reaching the report or start replacing codes."""
|
||||
definition = next(d for d in definitions_of("cacu", manifest).values() if d.measure_id == "CACU_EU7")
|
||||
result = CompositionAnswer(report_id=1, categories={"NORMAL": 2, "ASC-US": 1}, stored_before=True, strata={
|
||||
"estatus_seguimiento": {"PRE_COLPOSCOPIA": {"NORMAL": 2}, "POST_COLPOSCOPIA": {"ASC-US": 1}},
|
||||
"grupo_edad": {"25-34": {"NORMAL": 2, "ASC-US": 1}}})
|
||||
question = SimpleNamespace(event_cutoff=None, knowledge_cutoff=None)
|
||||
period = SimpleNamespace(inicio=date(2025, 7, 1), fin=date(2026, 1, 1))
|
||||
report = measure_report(definition, question, result, period, datetime(2026, 1, 2, tzinfo=timezone.utc))
|
||||
shown = {}
|
||||
for stratifier in report["group"][0]["stratifier"][1:]:
|
||||
for stratum in stratifier["stratum"]:
|
||||
value = stratum["component"][0]["value"]["coding"][0]
|
||||
shown[value["code"]] = value.get("display")
|
||||
assert shown == {"PRE_COLPOSCOPIA": "Pre colposcopia", "POST_COLPOSCOPIA": "Post colposcopia", "25-34": None}
|
||||
get_fhir_model_class("MeasureReport").model_validate(report)
|
||||
|
||||
|
||||
RULE = {"sin_dato": "SIN_DATO", "etiquetas": {
|
||||
"A": {"etiqueta": "A", "color": "#000000", "grupo": "G1"}, "B": {"etiqueta": "B", "color": "#000000", "grupo": "G2"},
|
||||
"APARTE": {"etiqueta": "Aparte", "color": "#000000"},
|
||||
"SIN_DATO": {"etiqueta": "Sin dato", "color": "#000000", "grupo": "SIN_DATO"}},
|
||||
"grupos": {"G1": "Uno", "G2": "Dos", "SIN_DATO": "Sin dato"}}
|
||||
|
||||
|
||||
def _with(**changes) -> dict:
|
||||
rule = {**RULE, "etiquetas": {k: dict(v) for k, v in RULE["etiquetas"].items()}, "grupos": dict(RULE["grupos"])}
|
||||
for path, value in changes.items():
|
||||
*parents, last = path.split("__")
|
||||
node = rule
|
||||
for p in parents:
|
||||
node = node[p]
|
||||
if value is None:
|
||||
node.pop(last, None)
|
||||
else:
|
||||
node[last] = value
|
||||
return rule
|
||||
|
||||
|
||||
def test_valid_groups_are_returned_in_order_and_a_category_may_stay_apart():
|
||||
"""Pins down: declared and used groups come back in their declared order, and a category without `grupo` (one kept
|
||||
apart) is allowed. Fails if a valid declaration is rejected or reordered."""
|
||||
assert list(category_groups("x", RULE).items()) == [("G1", "Uno"), ("G2", "Dos"), ("SIN_DATO", "Sin dato")]
|
||||
|
||||
|
||||
def test_a_composition_without_groups_has_none():
|
||||
"""Pins down: groups are optional; neither `grupos` nor any `grupo` means none. Fails if declaring groups becomes
|
||||
mandatory (CaMa's and TEA's compositions declare none)."""
|
||||
rule = {k: v for k, v in RULE.items() if k != "grupos"}
|
||||
rule["etiquetas"] = {c: {k: v for k, v in s.items() if k != "grupo"} for c, s in RULE["etiquetas"].items()}
|
||||
assert category_groups("x", rule) == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rule, message", [
|
||||
(_with(grupos=None), "`grupos` is missing"),
|
||||
(_with(etiquetas__A__grupo="G9"), "undeclared groups"),
|
||||
(_with(grupos__G3="Tres"), "groups without categories"),
|
||||
(_with(grupos__G1=" "), "non-empty caption"),
|
||||
(_with(etiquetas__SIN_DATO__grupo="G1", grupos__SIN_DATO=None), "goes alone"),
|
||||
(_with(etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "goes alone"),
|
||||
(_with(etiquetas__SIN_DATO__grupo=None, etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "no-data category's own"),
|
||||
])
|
||||
def test_invalid_groups_fail_the_load(rule, message):
|
||||
"""Pins down: each way a declaration can't be read as a partition fails with its reason (a group named but
|
||||
missing, one declared but unused, an empty caption, the no-data category mixed with others or without its own
|
||||
group). Fails if one of them is accepted, because the page would draw a wrong or incomplete grouping."""
|
||||
with pytest.raises(InvalidCategoryGroups, match=message):
|
||||
category_groups("x", rule)
|
||||
@@ -1,109 +0,0 @@
|
||||
"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
|
||||
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
|
||||
resource's shape (status, subject, method, one prediction per horizon from the risk's 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 CaCu demonstration
|
||||
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
|
||||
with a confirmed batch whose risks 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("cacu", 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 and 3 years, the
|
||||
3-year one with an interval. Returns (scored patient, member without risks)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", 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="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.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/<pac_id>`, 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"/cacu/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"/cacu/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"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
|
||||
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
|
||||
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
|
||||
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-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"/cacu/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/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
|
||||
every patient's risk."""
|
||||
response = client.get(f"/cacu/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: CaCu'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("/cacu/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"]
|
||||
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
|
||||
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
|
||||
domain, client = domain_client
|
||||
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
|
||||
assert measures["total"] == {"cacu": 7, "cama": 11}[domain]
|
||||
assert measures["total"] == {"cacu": 9, "cama": 11}[domain]
|
||||
for item in measures["entry"]:
|
||||
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
|
||||
assert response.status_code in (200, 409), response.get_json()
|
||||
|
||||
@@ -80,8 +80,8 @@ def test_the_list_names_what_is_answered_on_request(client):
|
||||
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
|
||||
|
||||
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"CACU_RIESGO_BANDA"}
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
|
||||
"CACU_CONFIRMACION_CITOLOGIA", "CACU_RIESGO_BANDA"}
|
||||
|
||||
|
||||
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
|
||||
@@ -19,9 +19,9 @@ from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, Paciente
|
||||
from webapi.compositions import answer_composition, composition_definitions, composition_report
|
||||
from webapi.metrics import Question, answer, measure_definitions, measure_report
|
||||
from webapi.metrics import INTERVAL_HIGH, INTERVAL_LOW, Counts, Question, answer, measure_definitions, measure_report
|
||||
from webapi.orchestration import run
|
||||
|
||||
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
||||
@@ -47,6 +47,28 @@ def base(tmp_path, sin_supresion, manifest):
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def _con_tratamiento(sesion: Session) -> None:
|
||||
"""The fixture data and, for H-004, her colposcopy (August 20) and her treatment (August 28), after the
|
||||
valuation visit of August 10: the timeline then holds a treatment to end an interval at."""
|
||||
from staging.cacu import COLPOSCOPIA, FAMILIAR, insertar
|
||||
|
||||
insertar(sesion)
|
||||
paciente = sesion.exec(select(Paciente).where(Paciente.pac_id_hospital == "H-004")).one()
|
||||
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-004", nm_id_hospital=f"NM-9{n}", nm_fecha=fecha,
|
||||
nm_cie_codigo=cie, nm_especialidad=especialidad)
|
||||
for n, (fecha, cie, especialidad) in enumerate(
|
||||
[(date(2025, 8, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 28), "D06.9", FAMILIAR)], start=1))
|
||||
sesion.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base_con_tratamiento(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cacu", tmp_path, datos=_con_tratamiento)
|
||||
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit():
|
||||
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
|
||||
@@ -254,8 +276,9 @@ def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base,
|
||||
|
||||
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
||||
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
|
||||
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
|
||||
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
|
||||
inclusive period end, each population's count, the score with its interval, strata as a `stratifier`, and a
|
||||
composition's categories as one more. Fails if a population, the score, a stratum or a category stops matching
|
||||
the answer."""
|
||||
period = base.dominio.dim_periodo_repository.get("2025-S1")
|
||||
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
|
||||
|
||||
@@ -265,7 +288,7 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
||||
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "denominator": 4, "numerator": 1}
|
||||
assert group["measureScore"] == {"value": 0.25}
|
||||
assert group["measureScore"]["value"] == 0.25
|
||||
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
|
||||
|
||||
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
|
||||
@@ -281,6 +304,18 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def test_a_proportion_is_scored_with_its_wilson_interval():
|
||||
"""Pins down: `Counts.score` carries the proportion and its 95 % Wilson interval as proportions, in the
|
||||
`ic-bajo` and `ic-alto` extensions (1 of 4 is 0.25 within 0.0456 and 0.6994), and publishes no score when the
|
||||
denominator is zero. Fails if an interval is dropped, comes out as a percentage, or a zero denominator is scored."""
|
||||
score = Counts(1, 4).score
|
||||
bounds = {e["url"]: e["valueDecimal"] for e in score["extension"]}
|
||||
assert score["value"] == 0.25
|
||||
assert bounds[INTERVAL_LOW] == pytest.approx(0.0456, abs=1e-4)
|
||||
assert bounds[INTERVAL_HIGH] == pytest.approx(0.6994, abs=1e-4)
|
||||
assert Counts(0, 0).score is None
|
||||
|
||||
|
||||
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
|
||||
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
|
||||
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
@@ -454,6 +489,26 @@ def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_y
|
||||
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
|
||||
|
||||
|
||||
DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
|
||||
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (4, 1, 58.0, 3)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
|
||||
def test_the_times_to_treatment_are_counted_from_their_start_to_the_first_treatment(base_con_tratamiento, manifest, url, expected):
|
||||
"""Pins down the two times to treatment on the fixture with H-004's colposcopy and treatment, 2025-S2 cut at the
|
||||
end of the year, with a 60-day horizon. From the sample: H-004's July sample reaches her treatment of August 28 in
|
||||
58 days; the other three samples of the semester have no treatment and their horizon has passed, so they are in
|
||||
the initial population and not measured. From the diagnosis: only that sample has one in the period, and its
|
||||
diagnosis of August 10 reaches the treatment in 18 days. Fails if the end event, the start (sample or diagnosis),
|
||||
the horizon rule or the split between not measured yet and without event changes."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
definition = duration_definitions(manifest)[url]
|
||||
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)),
|
||||
**repositories(base_con_tratamiento))
|
||||
assert (result.initial, result.n, result.median, result.excluded) == expected
|
||||
|
||||
|
||||
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ from sqlalchemy import create_engine, text
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.project import cohort_urls
|
||||
from webapi.orchestration.connection import point_to
|
||||
|
||||
ANIO = 2025
|
||||
@@ -66,22 +65,16 @@ def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
|
||||
|
||||
|
||||
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."""
|
||||
def test_en_cacu_arma_su_cohorte_una_vez(bases):
|
||||
proyecto, ctx, motor, _, pasos = bases
|
||||
if proyecto != "cacu":
|
||||
assert "cohorts" not in [p.name for p in pasos]
|
||||
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
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
|
||||
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
|
||||
for armado_id, _ in armados.values():
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
|
||||
{"a": armado_id}).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
|
||||
# CaCu: three strata and its nine measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
|
||||
# TEA: the age group and its ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto]
|
||||
assert resumen["definitions"] == {"cacu": 12, "cama": 17, "tea": 11}[base.proyecto]
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 9, "cama": 11, "tea": 10}[base.proyecto]
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
@@ -35,16 +33,8 @@ def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
assert {"load", "catalogs"} <= antes(deps, "check_silver")
|
||||
|
||||
|
||||
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
|
||||
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
|
||||
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
|
||||
definitions from anywhere else than dbt."""
|
||||
manifest = tmp_path / "manifest.json"
|
||||
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
|
||||
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
|
||||
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
|
||||
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
|
||||
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
|
||||
|
||||
@@ -38,7 +38,7 @@ class EstimadorFijo:
|
||||
|
||||
def estimar(self, columnas, filas):
|
||||
self.columnas = columnas
|
||||
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
|
||||
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
|
||||
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def seeded(client):
|
||||
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
|
||||
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", 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="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.flush()
|
||||
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
|
||||
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
||||
the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200 and body["simulado"] is True
|
||||
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
|
||||
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
|
||||
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
|
||||
horizons = body["riesgo"]["horizontes"]
|
||||
assert all(set(h) == HORIZON_KEYS for h in horizons)
|
||||
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
|
||||
|
||||
|
||||
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
|
||||
null. Fails if either case errors or invents a risk."""
|
||||
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
|
||||
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
|
||||
|
||||
assert member["cohorte"] is not None and member["riesgo"] is None
|
||||
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
|
||||
|
||||
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
@@ -108,7 +108,8 @@ def test_indicators_recompute_from_imported_rows(client):
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
|
||||
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
|
||||
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
|
||||
"CACU_RIESGO_BANDA"}
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
@@ -41,7 +41,7 @@ def batches(client):
|
||||
|
||||
def batch(version, risk, ahora):
|
||||
lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version},
|
||||
"cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora)
|
||||
"cin2_12m", [(pac_id, 1.0, risk, None, None)], ahora=ahora)
|
||||
return lote_id
|
||||
|
||||
older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
|
||||
@@ -992,15 +992,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filelock"
|
||||
version = "4.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6c/bf/a895b0b8e83d0a64d134f658e393e83998abfc22bbb8b58181ce55268706/filelock-4.3.0.tar.gz", hash = "sha256:143407310acf479e82d88068e3b9a6486f45fb410c0ed8729fe7359eaabeb6f1", size = 742199, upload-time = "2026-11-22T02:15:03.187Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/68/66/870b527908a06c7ec0e91239bd2c4d0bb22921efd4f915428b4e47d461a6/filelock-4.3.0-py3-none-any.whl", hash = "sha256:f933f39f7e01249a4a49b9abab30edc6d4b874624c3de5dd0b0d137aa8adb979", size = 244553, upload-time = "2026-11-22T02:15:01.667Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flask"
|
||||
version = "3.1.3"
|
||||
@@ -1363,69 +1354,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hf-xet"
|
||||
version = "1.8.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpcore2"
|
||||
version = "2.16.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "h11" },
|
||||
{ name = "truststore" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpx2"
|
||||
version = "2.16.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio", marker = "sys_platform != 'emscripten'" },
|
||||
{ name = "httpcore2", marker = "sys_platform != 'emscripten'" },
|
||||
{ name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" },
|
||||
{ name = "idna" },
|
||||
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpx2-jsfetch"
|
||||
version = "1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "huey"
|
||||
version = "3.4.0"
|
||||
@@ -1435,26 +1363,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "huggingface-hub"
|
||||
version = "2.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "click" },
|
||||
{ name = "filelock" },
|
||||
{ name = "fsspec" },
|
||||
{ name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
|
||||
{ name = "httpx2" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.20"
|
||||
@@ -2160,66 +2068,32 @@ notebooks = [
|
||||
{ name = "nbclient" },
|
||||
{ name = "nbconvert" },
|
||||
]
|
||||
seer-survival = [
|
||||
{ name = "matplotlib" },
|
||||
{ name = "mpmath" },
|
||||
{ name = "networkx" },
|
||||
{ name = "pgmpy" },
|
||||
{ name = "scipy" },
|
||||
{ name = "statsmodels" },
|
||||
]
|
||||
|
||||
[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 = "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 = "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", "seer-survival", "seer-survival-dca"]
|
||||
provides-extras = ["eeg-reference", "notebooks"]
|
||||
|
||||
[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]]
|
||||
@@ -2519,15 +2393,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/09/ed/559d2915dce85794bc0c36064043da170da50cd98746dcbddd85d5932017/nest_asyncio2-1.7.4-py3-none-any.whl", hash = "sha256:86e77b52c3d1496b294af3c944b44213b9b82a12a5ee590c0acc4ca4692ef6c7", size = 8543, upload-time = "2026-10-07T22:31:49.245Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "networkx"
|
||||
version = "3.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "numba"
|
||||
version = "0.68.1"
|
||||
@@ -2699,15 +2564,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opt-einsum"
|
||||
version = "3.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "packaging"
|
||||
version = "26.3"
|
||||
@@ -2907,29 +2763,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pgmpy"
|
||||
version = "1.1.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "joblib" },
|
||||
{ name = "networkx" },
|
||||
{ name = "numpy" },
|
||||
{ name = "opt-einsum" },
|
||||
{ name = "pandas" },
|
||||
{ name = "pyparsing" },
|
||||
{ name = "scikit-base" },
|
||||
{ name = "scikit-learn" },
|
||||
{ name = "scipy" },
|
||||
{ name = "statsmodels" },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/72/9a/b94ccd1d6cbf2982937c26e54e887b47ee10f848ad53c4427965578a358d/pgmpy-1.1.2.tar.gz", hash = "sha256:a62a89352f139a5d459839e54e6bfa202a7d8749e6dc6d7ceec088a71529af45", size = 2183113, upload-time = "2026-04-30T11:34:49.538Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c6/5d/d03634ed296986abad834a69b0df21510cc9b6c40fb8afaed5df1c4b6074/pgmpy-1.1.2-py3-none-any.whl", hash = "sha256:e55c78763a4a45dd644a13b250cea86af0c7e08590cf35de489624f34a4d9a0b", size = 2446383, upload-time = "2026-04-30T11:34:47.189Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "12.3.0"
|
||||
@@ -3993,15 +3826,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scikit-base"
|
||||
version = "1.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d9/e9/287707e71be93558076d873f92444fa788c1a11c259982a1967ad2071b0e/scikit_base-1.2.1.tar.gz", hash = "sha256:6cccfab1cf51e36141b731fe3248bd3c1a55361e965ddc7457be75ad8a9803eb", size = 136836, upload-time = "2026-11-08T20:24:26.859Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/b4/21adac81fbb522bdbb74c4809c7ea06fbde847a24c54b68dfed1519ff3dc/scikit_base-1.2.1-py3-none-any.whl", hash = "sha256:8695538dcf61c5439752b56baeca9d4ce52de012ddc4cee50ee67c910a9b5fb9", size = 163886, upload-time = "2026-11-08T20:24:25.324Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scikit-learn"
|
||||
version = "1.9.1"
|
||||
@@ -4500,15 +4324,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "truststore"
|
||||
version = "0.10.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typeguard"
|
||||
version = "4.6.0"
|
||||
@@ -4688,7 +4503,7 @@ dependencies = [
|
||||
{ name = "flask" },
|
||||
{ name = "flask-cors" },
|
||||
{ name = "gunicorn" },
|
||||
{ name = "models", extra = ["notebooks", "seer-survival"] },
|
||||
{ name = "models", extra = ["notebooks"] },
|
||||
{ name = "openpyxl" },
|
||||
{ name = "pandas" },
|
||||
{ name = "pdfplumber" },
|
||||
@@ -4724,7 +4539,7 @@ requires-dist = [
|
||||
{ name = "flask", specifier = ">=3.0" },
|
||||
{ name = "flask-cors", specifier = ">=4.0" },
|
||||
{ name = "gunicorn", specifier = ">=23.0" },
|
||||
{ name = "models", extras = ["notebooks", "seer-survival"], editable = "../models" },
|
||||
{ name = "models", extras = ["notebooks"], editable = "../models" },
|
||||
{ name = "openpyxl", specifier = ">=3.1" },
|
||||
{ name = "pandas", specifier = ">=2.0" },
|
||||
{ name = "pdfplumber", specifier = ">=0.11" },
|
||||
|
||||
+4
-6
@@ -12,8 +12,6 @@ from webapi.blueprints.imports import imports_bp
|
||||
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
|
||||
|
||||
|
||||
@@ -94,18 +92,18 @@ def create_app() -> Flask:
|
||||
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
||||
url_prefix=f"/{domain}/fhir")
|
||||
# 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.
|
||||
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
||||
# an access rule still to be defined, not an environment variable.
|
||||
from persistance import cacu as cacu_repositories
|
||||
from persistance.db import get_cacu_session, get_cama_session
|
||||
|
||||
from webapi.patient_risk import patient_risk_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(cama_survival_bp, url_prefix="/cama/supervivencia")
|
||||
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -8,7 +8,7 @@ either run elsewhere and register its result through `POST /model-versions`
|
||||
`cohorte_armado_id`), or be triggered in place through `POST
|
||||
/model-versions/<domain>/<scenario>/train`, for a deployment with no
|
||||
command-line access to run the `entrenar` compose profile by hand.
|
||||
Notebooks (`models.reports.experiment`) run in the background on the build's
|
||||
Notebooks (`models.pipelines.experiment`) run in the background on the build's
|
||||
file alone and are kept as MLflow runs.
|
||||
"""
|
||||
import contextlib
|
||||
@@ -28,7 +28,7 @@ from models.io.lineage import DOMAINS
|
||||
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from models.io.storage import build_file, cohorts_root, exported_builds
|
||||
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
|
||||
from models.reports import experiment
|
||||
from models.pipelines import experiment
|
||||
from persistance.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
from persistance.settings import settings
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
"""`/cama/recurrencia`: the scenarios of each cohort, the figure of one and the scenarios a patient meets."""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from werkzeug.exceptions import BadRequest, NotFound
|
||||
|
||||
from webapi.cama_recurrence import service
|
||||
|
||||
cama_recurrence_bp = Blueprint("cama_recurrence", __name__)
|
||||
|
||||
|
||||
@cama_recurrence_bp.errorhandler(service.NotAvailable)
|
||||
def _not_available(error):
|
||||
return jsonify({"error": str(error)}), 404
|
||||
|
||||
|
||||
@cama_recurrence_bp.get("/escenarios")
|
||||
def scenarios():
|
||||
return jsonify(service.scenarios())
|
||||
|
||||
|
||||
@cama_recurrence_bp.get("/figura")
|
||||
def figure():
|
||||
cohort = request.args.get("cohorte", "").strip()
|
||||
scenario = request.args.get("escenario", "").strip()
|
||||
if not cohort or not scenario:
|
||||
raise BadRequest("faltan los parámetros «cohorte» y «escenario»")
|
||||
try:
|
||||
return jsonify(service.figure(cohort, scenario))
|
||||
except service.Calculating:
|
||||
return jsonify({"estado": "calculando"}), 202
|
||||
except KeyError:
|
||||
raise NotFound(f"el modelo no define el escenario «{scenario}» en la cohorte «{cohort}»")
|
||||
except LookupError:
|
||||
raise NotFound(f"el escenario «{scenario}» no tiene recaídas suficientes para dibujarse")
|
||||
|
||||
|
||||
@cama_recurrence_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,183 +0,0 @@
|
||||
"""CaMa's recurrence analysis over the live cohort build.
|
||||
|
||||
Each cohort (METABRIC, SCAN-B) is recoded from the latest build of `cama/cohorte_total` by the dictionary of
|
||||
`models.cama.recurrence`. Its covariates, the terms of each horizon and the bootstrap of the combined estimate are
|
||||
computed once per build, in the background, and kept on disk; a scenario's figure is computed when it is asked for and kept
|
||||
in memory. A new build computes them again.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import pickle
|
||||
import tempfile
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence import analysis, cohort as recurrence_cohort
|
||||
from models.io.storage import KitBuild
|
||||
|
||||
DOMAIN, COHORT = "cama", "cama/cohorte_total"
|
||||
CACHE_DIR = Path(tempfile.gettempdir()) / "cama_recurrence"
|
||||
|
||||
|
||||
class NotAvailable(LookupError):
|
||||
"""There is no cohort build to draw on."""
|
||||
|
||||
|
||||
class Calculating(RuntimeError):
|
||||
"""The cohort's models and bootstrap are still being computed."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class CohortState:
|
||||
name: str
|
||||
frame: pd.DataFrame
|
||||
scenarios: list[dict]
|
||||
masks: dict
|
||||
status: str = "calculando"
|
||||
error: str | None = None
|
||||
covariates: list[str] = field(default_factory=list)
|
||||
dropped: list[str] = field(default_factory=list)
|
||||
models: dict = field(default_factory=dict)
|
||||
point: dict = field(default_factory=dict)
|
||||
draws: dict = field(default_factory=dict)
|
||||
figures: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Live:
|
||||
build_id: int
|
||||
model: dict
|
||||
events: pd.DataFrame
|
||||
cohorts: dict[str, CohortState]
|
||||
|
||||
|
||||
_lock = threading.RLock()
|
||||
_live: Live | None = None
|
||||
|
||||
|
||||
def _cache_file(build_id: int, name: str, model_text: str, members: int) -> Path:
|
||||
key = hashlib.sha256(f"{build_id}|{name}|{members}|{model_text}".encode()).hexdigest()[:20]
|
||||
return CACHE_DIR / f"{name}-{key}.pkl"
|
||||
|
||||
|
||||
def _compute(state: CohortState, model: dict, cache: Path) -> None:
|
||||
try:
|
||||
if cache.is_file():
|
||||
with cache.open("rb") as handle:
|
||||
saved = pickle.load(handle)
|
||||
else:
|
||||
settings, calculator = model["modeling"], model["calculator"]
|
||||
horizons = model["config"]["horizons_months"]
|
||||
cfg = model["cohorts"][state.name]
|
||||
covariates, dropped = analysis.prune_covariates(state.frame, cfg["covariates"], cfg["treatment"], settings)
|
||||
models = analysis.select_models(state.frame, covariates, horizons, settings)
|
||||
calc = analysis.Calculator(state.frame, covariates, models, horizons, settings["bdeu_ess"])
|
||||
point = calc.risk(np.arange(calc.n), state.masks)
|
||||
draws = calc.bootstrap(state.masks, calculator["bootstrap_replicas"], settings["seed"])
|
||||
saved = {"covariates": covariates, "dropped": dropped, "models": models, "point": point, "draws": draws}
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with cache.open("wb") as handle:
|
||||
pickle.dump(saved, handle)
|
||||
with _lock:
|
||||
state.covariates, state.dropped, state.models = saved["covariates"], saved["dropped"], saved["models"]
|
||||
state.point, state.draws, state.status = saved["point"], saved["draws"], "listo"
|
||||
except Exception as error: # the cohort reports its failure; the others keep working
|
||||
with _lock:
|
||||
state.status, state.error = "error", f"{type(error).__name__}: {error}"
|
||||
|
||||
|
||||
def live() -> Live:
|
||||
"""The latest build's cohorts; recoded again only when the build changed."""
|
||||
global _live
|
||||
repositories = import_module(f"persistance.{DOMAIN}")
|
||||
build_id = repositories.cohort_repository.latest_build(COHORT)
|
||||
if build_id is None:
|
||||
raise NotAvailable("no hay una cohorte armada para el análisis de recurrencia")
|
||||
with _lock:
|
||||
if _live is not None and _live.build_id == int(build_id):
|
||||
return _live
|
||||
model = recurrence_cohort.load()
|
||||
model_text = recurrence_cohort.TOML.read_text(encoding="utf-8")
|
||||
events = KitBuild(DOMAIN, int(build_id)).frame()
|
||||
cohorts = {}
|
||||
for name, cfg in model["cohorts"].items():
|
||||
frame = recurrence_cohort.recode(events, model, name)
|
||||
if frame.empty:
|
||||
continue
|
||||
scenarios = cfg["scenarios"]
|
||||
state = CohortState(name, frame, scenarios, analysis.scenario_masks(frame, scenarios))
|
||||
cohorts[name] = state
|
||||
cache = _cache_file(int(build_id), name, model_text, len(frame))
|
||||
threading.Thread(target=_compute, args=(state, model, cache), daemon=True).start()
|
||||
_live = Live(int(build_id), model, events, cohorts)
|
||||
return _live
|
||||
|
||||
|
||||
def _cohort(current: Live, name: str) -> CohortState:
|
||||
if name not in current.cohorts:
|
||||
raise KeyError(name)
|
||||
return current.cohorts[name]
|
||||
|
||||
|
||||
def scenarios() -> dict:
|
||||
current = live()
|
||||
minimum = current.model["calculator"]["min_events"]
|
||||
cohorts = []
|
||||
for name, state in current.cohorts.items():
|
||||
rows = []
|
||||
for scenario in state.scenarios:
|
||||
mask = state.masks[scenario["name"]]
|
||||
events = int(state.frame.loc[mask, "evento"].sum())
|
||||
rows.append({"nombre": scenario["name"], "condiciones": scenario["when"], "n": int(mask.sum()),
|
||||
"recaidas": events, "dibujable": events >= minimum})
|
||||
cohorts.append({"id": name, "nombre": current.model["cohorts"][name]["name"], "estado": state.status,
|
||||
"error": state.error, "escenarios": rows})
|
||||
return {"build": current.build_id, "horizontes": current.model["config"]["horizons_months"], "cohortes": cohorts}
|
||||
|
||||
|
||||
def figure(cohort: str, scenario: str) -> dict:
|
||||
"""The record of one scenario's figure; `KeyError` for an unknown cohort or scenario, `Calculating` while the cohort
|
||||
is being computed, `LookupError` when the scenario has too few recurrences to be drawn."""
|
||||
current = live()
|
||||
state = _cohort(current, cohort)
|
||||
if scenario not in state.masks:
|
||||
raise KeyError(scenario)
|
||||
with _lock:
|
||||
if state.status == "calculando":
|
||||
raise Calculating(cohort)
|
||||
if state.status == "error":
|
||||
raise RuntimeError(state.error)
|
||||
if scenario not in state.figures:
|
||||
figure_record = analysis.scenario_figure(
|
||||
state.frame, scenario, state.masks[scenario], state.point[scenario], state.draws[scenario],
|
||||
current.model["config"]["horizons_months"], current.model["calculator"])
|
||||
if figure_record is None:
|
||||
raise LookupError(scenario)
|
||||
state.figures[scenario] = {"cohorte": cohort, "cohorte_nombre": current.model["cohorts"][cohort]["name"],
|
||||
"condiciones": next(s["when"] for s in state.scenarios if s["name"] == scenario),
|
||||
"build": current.build_id, **figure_record}
|
||||
return state.figures[scenario]
|
||||
|
||||
|
||||
def patient_scenarios(pac_id: int) -> dict:
|
||||
"""The scenarios a patient's covariates meet in each cohort; one that needs a covariate she lacks does not include her."""
|
||||
current = live()
|
||||
events = current.events[current.events["pac_id"] == pac_id]
|
||||
if events.empty:
|
||||
raise KeyError(pac_id)
|
||||
found = []
|
||||
# The analysis is for patients after treatment: those whose timeline holds the post-treatment scenario.
|
||||
if not (events["tipo"] == "escenario_postratamiento").any():
|
||||
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": False, "escenarios": found}
|
||||
for name, state in current.cohorts.items():
|
||||
recoded = recurrence_cohort.recode(events, current.model, name, of_source=False, follow_up=False)
|
||||
if recoded.empty:
|
||||
continue
|
||||
masks = analysis.scenario_masks(recoded, state.scenarios)
|
||||
found += [{"cohorte": name, "escenario": n} for n, mask in masks.items() if bool(mask[0])]
|
||||
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": True, "escenarios": found}
|
||||
@@ -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}
|
||||
@@ -99,6 +99,40 @@ class CompositionDefinition:
|
||||
improvement_notation = None
|
||||
|
||||
|
||||
class InvalidCategoryGroups(ValueError):
|
||||
"""A composition's category groups (`categoria.grupos` and each label's `grupo`) don't hold together."""
|
||||
|
||||
|
||||
def category_groups(url: str, rule: dict) -> dict[str, str]:
|
||||
"""The groups of a composition's categories (`categoria.grupos`: code -> caption), checked against the labels that
|
||||
name them (`categoria.etiquetas.<code>.grupo`). Optional: without either, there are none.
|
||||
|
||||
A label may name no group (a category kept apart, like «Sin biopsia aún»); every group named is declared, every
|
||||
declared group has a category, and the no-data category, if grouped, is alone in the group of its own code, as the
|
||||
indicator page reads it.
|
||||
"""
|
||||
grupos = rule.get("grupos")
|
||||
labels = rule.get("etiquetas", {})
|
||||
named = {code: spec["grupo"] for code, spec in labels.items() if isinstance(spec, dict) and "grupo" in spec}
|
||||
if grupos is None:
|
||||
if named:
|
||||
raise InvalidCategoryGroups(f"{url}: categories name groups ({', '.join(sorted(named))}) but `grupos` is missing")
|
||||
return {}
|
||||
if not isinstance(grupos, dict) or not grupos or not all(
|
||||
isinstance(code, str) and code and isinstance(caption, str) and caption.strip() for code, caption in grupos.items()):
|
||||
raise InvalidCategoryGroups(f"{url}: `grupos` maps each group's code to a non-empty caption")
|
||||
if unknown := sorted({g for g in named.values() if g not in grupos}):
|
||||
raise InvalidCategoryGroups(f"{url}: undeclared groups {unknown}")
|
||||
if unused := sorted(set(grupos) - set(named.values())):
|
||||
raise InvalidCategoryGroups(f"{url}: groups without categories {unused}")
|
||||
no_data = rule.get("sin_dato")
|
||||
if no_data in named and (named[no_data] != no_data or [c for c, g in named.items() if g == no_data and c != no_data]):
|
||||
raise InvalidCategoryGroups(f"{url}: the no-data category {no_data!r} goes alone in the group {no_data!r}")
|
||||
if no_data in grupos and named.get(no_data) != no_data:
|
||||
raise InvalidCategoryGroups(f"{url}: the group {no_data!r} is the no-data category's own")
|
||||
return dict(grupos)
|
||||
|
||||
|
||||
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
||||
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
@@ -112,6 +146,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
||||
model = _semantic_model_of(metric, semantic)
|
||||
node = models[model["depends_on"]["nodes"][0]]
|
||||
rule = meta["categoria"]
|
||||
category_groups(meta["measure_url"], rule) # fails the manifest's load if the groups don't hold together
|
||||
definitions[meta["measure_url"]] = CompositionDefinition(
|
||||
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
|
||||
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
|
||||
|
||||
+1
-29
@@ -1,5 +1,4 @@
|
||||
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA and CaCu, its patients' screening and
|
||||
individual risk.
|
||||
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
|
||||
|
||||
GET metadata CapabilityStatement
|
||||
GET Measure, Measure/<id> the measures (dbt's definitions)
|
||||
@@ -9,7 +8,6 @@ individual risk.
|
||||
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
|
||||
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
|
||||
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
|
||||
GET RiskAssessment?subject=Patient/<pac_id> CaCu'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`.
|
||||
@@ -38,7 +36,6 @@ 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"
|
||||
|
||||
def definitions() -> dict:
|
||||
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
|
||||
@@ -83,9 +80,6 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
|
||||
"definition": canonical("OperationDefinition/resumen-tea")}]},
|
||||
{"type": "ValueSet", "interaction": [{"code": "read"}]},
|
||||
]
|
||||
if risks:
|
||||
resources += [{"type": "RiskAssessment", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": "subject", "type": "reference"}]}]
|
||||
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
|
||||
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
|
||||
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
|
||||
@@ -175,31 +169,9 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
|
||||
|
||||
if patients:
|
||||
_patient_routes(blueprint, repositories, now)
|
||||
if risks:
|
||||
_risk_routes(blueprint, repositories)
|
||||
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
|
||||
|
||||
@blueprint.get("/RiskAssessment")
|
||||
def risk_assessments():
|
||||
subject = request.args.get("subject", "")
|
||||
reference = subject.removeprefix("Patient/")
|
||||
if not reference.isdigit():
|
||||
return outcome(400, "invalid", "falta `subject=Patient/<pac_id>`: el riesgo se busca por paciente")
|
||||
try:
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
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())]
|
||||
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
|
||||
|
||||
|
||||
def _period_asked(repositories):
|
||||
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
|
||||
if periodo := request.args.get("periodo"):
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
|
||||
|
||||
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:
|
||||
|
||||
id `<lote_id>-<pac_id>`
|
||||
status the batch's state (`final`)
|
||||
subject `Patient/<pac_id>`: 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:
|
||||
"""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)
|
||||
+20
-5
@@ -11,7 +11,7 @@ import json
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.compositions import CompositionAnswer, CompositionDefinition
|
||||
from webapi.compositions import CompositionAnswer, CompositionDefinition, category_groups
|
||||
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
|
||||
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
|
||||
@@ -24,6 +24,7 @@ EXCLUDED = "measure-population-exclusion"
|
||||
FIGURES = f"{STRUCTURE}/figuras"
|
||||
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
|
||||
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
|
||||
CATEGORY_GROUP = f"{STRUCTURE}/categoria-grupo"
|
||||
CONTRACT = f"{STRUCTURE}/contrato"
|
||||
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
|
||||
POPULATION_LABELS = {
|
||||
@@ -87,9 +88,16 @@ def measure_resource(definition, title: str, description: str) -> dict:
|
||||
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
|
||||
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
|
||||
category = meta.get("categoria", {})
|
||||
# Optional and additive: a category's group (`grupo`) and each group's caption (`categoria-grupo`), only when the
|
||||
# composition declares them; a client that doesn't know them reads the labels alone.
|
||||
extensions += [{"url": CATEGORY_LABEL, "extension": [
|
||||
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
|
||||
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
|
||||
{"url": "color", "valueString": spec["color"]},
|
||||
*([{"url": "grupo", "valueCode": spec["grupo"]}] if spec.get("grupo") else [])]}
|
||||
for code, spec in category.get("etiquetas", {}).items()]
|
||||
extensions += [{"url": CATEGORY_GROUP, "extension": [
|
||||
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": caption}]}
|
||||
for code, caption in category_groups(definition.url, category).items()]
|
||||
if meta.get("requiere_validacion"):
|
||||
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
|
||||
resource = {
|
||||
@@ -114,8 +122,8 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -
|
||||
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
|
||||
if excluded is not None and getattr(definition, "exclusion", None):
|
||||
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
|
||||
if counts.proportion is not None:
|
||||
cells["measureScore"] = {"value": counts.proportion}
|
||||
if counts.score:
|
||||
cells["measureScore"] = counts.score
|
||||
return cells
|
||||
|
||||
|
||||
@@ -141,13 +149,20 @@ def _groups(definition, result) -> list[dict]:
|
||||
result.total)]}
|
||||
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
|
||||
category = definition.category.value
|
||||
# A stratum value's caption, as a proportion's strata have it (`_label`), or from `meta.etiquetas_estrato`,
|
||||
# which stays out of the strata's spec so the report's key doesn't change.
|
||||
spec_of = {s.name: s.spec for s in definition.strata}
|
||||
captions = definition.meta.get("etiquetas_estrato", {})
|
||||
|
||||
def caption(name: str, value: str) -> str | None:
|
||||
return _label(spec_of.get(name, {}), value) or captions.get(name, {}).get(value)
|
||||
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
|
||||
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
|
||||
for c, n in sorted(result.categories.items())]}]
|
||||
for name, by_value in result.strata.items():
|
||||
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
|
||||
"stratum": [{"component": [
|
||||
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
|
||||
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v, caption(name, v))},
|
||||
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
|
||||
], "population": [_count("initial-population", n)]}
|
||||
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
|
||||
|
||||
@@ -9,7 +9,7 @@ de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
||||
|
||||
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
|
||||
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
|
||||
misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`; `id_seudonimo` repite ese valor
|
||||
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
|
||||
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
|
||||
|
||||
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
||||
|
||||
@@ -19,21 +19,3 @@ class BiopsiaMamaImportSchema(ImportSchema):
|
||||
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
bx_tipo_histologico: Optional[str] = None
|
||||
bx_grado_nottingham: Optional[str] = None
|
||||
bx_receptor_estrogeno: Optional[str] = None
|
||||
bx_receptor_estrogeno_pct: Optional[float] = None
|
||||
bx_receptor_progesterona: Optional[str] = None
|
||||
bx_receptor_progesterona_pct: Optional[float] = None
|
||||
bx_her2: Optional[str] = None
|
||||
bx_her2_fish: Optional[str] = None
|
||||
bx_ki67_pct: Optional[float] = None
|
||||
bx_tamano_tumor_mm: Optional[float] = None
|
||||
bx_ganglios_positivos: Optional[float] = None
|
||||
bx_invasion_linfovascular: Optional[str] = None
|
||||
bx_multifocalidad: Optional[str] = None
|
||||
bx_margenes: Optional[str] = None
|
||||
bx_pt: Optional[str] = None
|
||||
bx_pn: Optional[str] = None
|
||||
bx_lateralidad: Optional[str] = None
|
||||
bx_localizacion: Optional[str] = None
|
||||
|
||||
@@ -22,6 +22,3 @@ class MastografiaImportSchema(ImportSchema):
|
||||
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
|
||||
mast_dicom_blob: Optional[bytes] = None
|
||||
mast_interpretacion: Optional[str] = None
|
||||
mast_densidad: Optional[str] = None
|
||||
mast_margen_masa: Optional[str] = None
|
||||
mast_tipo_hallazgo: Optional[str] = None
|
||||
|
||||
@@ -36,5 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_estadio_clinico: Optional[str] = None
|
||||
nm_metastasis: Optional[str] = None
|
||||
|
||||
@@ -6,7 +6,6 @@ from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
FlexDate,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
@@ -26,19 +25,6 @@ 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
|
||||
pac_fecha_defuncion: FlexDate = None
|
||||
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
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
"""Import schema for `core.cama.models.SeguimientoMama`."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
|
||||
class SeguimientoMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
seg_tipo: RequiredStr
|
||||
seg_fecha: FlexDate = None
|
||||
seg_detalle: Optional[str] = None
|
||||
@@ -1,14 +0,0 @@
|
||||
"""Import schema for `core.cama.models.TratamientoMama`."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
|
||||
class TratamientoMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
trat_tipo: RequiredStr
|
||||
trat_fecha: FlexDate = None
|
||||
trat_detalle: Optional[str] = None
|
||||
trat_lateralidad: Optional[str] = None
|
||||
@@ -18,8 +18,6 @@ from persistance.cacu import paciente_repository as cacu_paciente_repository
|
||||
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
|
||||
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
|
||||
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
|
||||
from persistance.cama import tratamiento_mama_repository as cama_tratamiento_mama_repository
|
||||
from persistance.cama import seguimiento_mama_repository as cama_seguimiento_mama_repository
|
||||
from persistance.cama import mastografia_repository as cama_mastografia_repository
|
||||
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
@@ -53,8 +51,6 @@ from webapi.imports.schemas.cama.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
|
||||
from webapi.imports.schemas.cama.tratamiento_mama import TratamientoMamaImportSchema
|
||||
from webapi.imports.schemas.cama.seguimiento_mama import SeguimientoMamaImportSchema
|
||||
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
|
||||
@@ -154,16 +150,6 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.TratamientoMama": EntitySpec(
|
||||
schema=TratamientoMamaImportSchema,
|
||||
repository=cama_tratamiento_mama_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.SeguimientoMama": EntitySpec(
|
||||
schema=SeguimientoMamaImportSchema,
|
||||
repository=cama_seguimiento_mama_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
|
||||
+15
-2
@@ -41,6 +41,8 @@ from sqlalchemy import (
|
||||
true,
|
||||
)
|
||||
|
||||
from webapi.cama_analysis.stats import wilson
|
||||
|
||||
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
|
||||
TOTAL = "total"
|
||||
NO_DATA = "sin_dato"
|
||||
@@ -545,6 +547,15 @@ class Counts:
|
||||
def proportion(self) -> float | None:
|
||||
return self.numerator / self.denominator if self.denominator else None
|
||||
|
||||
@property
|
||||
def score(self) -> dict | None:
|
||||
"""The FHIR `measureScore`: the proportion and its 95 % Wilson interval, all as proportions in [0, 1]."""
|
||||
if not self.denominator:
|
||||
return None
|
||||
low, high = wilson(self.numerator, self.denominator)
|
||||
return {"value": self.proportion, "extension": [
|
||||
{"url": INTERVAL_LOW, "valueDecimal": low}, {"url": INTERVAL_HIGH, "valueDecimal": high}]}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Answer:
|
||||
@@ -657,6 +668,8 @@ POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population"
|
||||
EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento"
|
||||
KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento"
|
||||
HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id"
|
||||
INTERVAL_LOW = "https://isssteleon.org/fhir/StructureDefinition/ic-bajo"
|
||||
INTERVAL_HIGH = "https://isssteleon.org/fhir/StructureDefinition/ic-alto"
|
||||
|
||||
|
||||
def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
|
||||
@@ -667,8 +680,8 @@ def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
|
||||
|
||||
|
||||
def _scored(entry: dict, counts: Counts) -> dict:
|
||||
if counts.proportion is not None:
|
||||
entry["measureScore"] = {"value": counts.proportion}
|
||||
if counts.score:
|
||||
entry["measureScore"] = counts.score
|
||||
return entry
|
||||
|
||||
|
||||
|
||||
@@ -37,13 +37,13 @@ from webapi.orchestration.reference.rules import (
|
||||
from webapi.orchestration.reference.periods import periodos_de_tipos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from persistance.edges.silver import save_load_in
|
||||
from sqlmodel import SQLModel, select
|
||||
from sqlmodel import SQLModel, func, select
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.semantic_layer import catalog_layers, event_views
|
||||
from models.cohorts.build import build_of, latest_build, read_frame
|
||||
from models.io.storage import read_queries
|
||||
from webapi.orchestration.project import cohort_urls, period_types
|
||||
from models.cohorts.definition import read_definition
|
||||
from webapi.orchestration.project import cohort_definitions, period_types
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -188,17 +188,23 @@ def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con las reglas de dbt, su única definición: la población, la fecha índice, las
|
||||
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
|
||||
corte (las variables de dbt), y corren en la base después de `event_models`.
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
|
||||
|
||||
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
|
||||
"""
|
||||
tablas = tablas_de(ctx.project)
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
manifest = _manifest(ctx)
|
||||
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
|
||||
|
||||
def armado(definicion, sesion):
|
||||
corte = ctx.cutoff or _last_load_date(sesion, tablas)
|
||||
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
|
||||
linea=ctx.repos.silver.timeline.query)
|
||||
|
||||
armados = {}
|
||||
for url in cohort_urls(ctx.project, manifest):
|
||||
consultas = read_queries(manifest, url)
|
||||
armados[url] = ctx.repos.gold.cohorts.assemble(
|
||||
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = read_definition(ruta)
|
||||
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
|
||||
return armados
|
||||
|
||||
|
||||
@@ -214,20 +220,30 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
|
||||
"""
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
lotes = {}
|
||||
for url in cohort_urls(ctx.project, _manifest(ctx)):
|
||||
estimador = ctx.estimators.get(url)
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = read_definition(ruta)
|
||||
estimador = ctx.estimators.get(definicion.url)
|
||||
if estimador is None:
|
||||
continue
|
||||
|
||||
def frame(sesion, url=url):
|
||||
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
|
||||
def frame(sesion, definicion=definicion):
|
||||
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
|
||||
cohortes=tablas_cohorte)
|
||||
|
||||
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[url] = ctx.repos.gold.cohorts.save_batch(
|
||||
lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
|
||||
|
||||
def _last_load_date(sesion, tablas) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
|
||||
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
|
||||
if ultima is None or isinstance(ultima, date):
|
||||
return ultima.date() if isinstance(ultima, datetime) else ultima
|
||||
return date.fromisoformat(str(ultima)[:10])
|
||||
|
||||
@@ -3,9 +3,9 @@ its domain has in production.
|
||||
|
||||
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
|
||||
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
|
||||
set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`):
|
||||
the cycle's latest build for membership, the domain's timeline for the events, then the production version in
|
||||
MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go
|
||||
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
|
||||
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
|
||||
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
|
||||
unused by design.
|
||||
"""
|
||||
|
||||
@@ -37,29 +37,28 @@ class Cin2LogisticEstimator:
|
||||
self._provenance: Provenance | None = None
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
|
||||
import json
|
||||
|
||||
import mlflow.pyfunc
|
||||
import numpy as np
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.dags.estimation import estimate_frame
|
||||
from models.dags.training import Scenario
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.storage import KitBuild
|
||||
from models.io.storage import cohorts_root, read_cohort
|
||||
from models.pipelines.export_cohort import export_kit_build
|
||||
from models.steps.risks import risk_rows
|
||||
|
||||
repos = import_module(f"persistance.{self.domain}")
|
||||
scenario = Scenario.load(self.domain, "cin2_logistic")
|
||||
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()
|
||||
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
|
||||
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
|
||||
self.desenlace = scenario.outcome
|
||||
url = SETTINGS["cohort"]
|
||||
build_id = repos.cohort_repository.latest_build(url)
|
||||
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
|
||||
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
|
||||
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
|
||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
|
||||
window = SETTINGS["outcome_window_months"]
|
||||
self.desenlace = f"cin2_{window}m"
|
||||
self._provenance = Provenance(
|
||||
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
|
||||
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
|
||||
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
|
||||
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
|
||||
return [tuple(row) for row in risk_rows(risks, window / 12)]
|
||||
|
||||
def procedencia(self) -> Provenance:
|
||||
if self._provenance is None:
|
||||
@@ -72,12 +71,11 @@ def live_estimators(domain: str) -> dict[str, Any]:
|
||||
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
|
||||
if domain != "cacu":
|
||||
return {}
|
||||
from models.dags.training import Scenario
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.registry import registry
|
||||
|
||||
scenario = Scenario.load(domain, "cin2_logistic")
|
||||
try:
|
||||
registry.resolve(domain, scenario.scenario)
|
||||
registry.resolve(domain, SETTINGS["scenario"])
|
||||
except LookupError:
|
||||
return {}
|
||||
return {scenario.cohort: Cin2LogisticEstimator(domain)}
|
||||
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""What the cycle needs to know of a project's definitions, all from dbt's manifest: its period types and its cohorts."""
|
||||
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from models.io.storage import cohort_urls as _cohort_urls
|
||||
from models.cohorts.definition import ROOT
|
||||
|
||||
|
||||
def period_types(proyecto: str, manifest: Path) -> list[str]:
|
||||
@@ -13,7 +13,7 @@ def period_types(proyecto: str, manifest: Path) -> list[str]:
|
||||
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
|
||||
|
||||
|
||||
def cohort_urls(proyecto: str, manifest: Path | None) -> list[str]:
|
||||
"""The cohorts the cycle builds: those of the project in dbt's manifest (`Transformation/models/<project>/cohorts/`,
|
||||
`meta.cohort` of their population query). dbt is their only definition. None without a manifest."""
|
||||
return _cohort_urls(manifest, proyecto) if manifest else []
|
||||
def cohort_definitions(proyecto: str) -> list[Path]:
|
||||
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
|
||||
Those in `<project>/proposals/` aren't built."""
|
||||
return sorted((ROOT / proyecto).glob("*.toml"))
|
||||
|
||||
@@ -18,8 +18,7 @@ from hamilton.lifecycle import NodeExecutionHook
|
||||
|
||||
from webapi.orchestration import cycle
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.context import dbt_manifest_path
|
||||
from webapi.orchestration.project import cohort_urls
|
||||
from webapi.orchestration.project import cohort_definitions
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -50,10 +49,10 @@ class _Logbook(NodeExecutionHook):
|
||||
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
|
||||
|
||||
|
||||
def _driver(proyecto: str, manifest, *adaptadores) -> driver.Driver:
|
||||
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
|
||||
return (driver.Builder()
|
||||
.with_modules(cycle)
|
||||
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
|
||||
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
|
||||
.with_adapters(*adaptadores)
|
||||
.build())
|
||||
|
||||
@@ -62,9 +61,9 @@ def _in_order(dr: driver.Driver) -> list[str]:
|
||||
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
|
||||
|
||||
|
||||
def steps_of(proyecto: str, manifest=None) -> list[str]:
|
||||
def steps_of(proyecto: str) -> list[str]:
|
||||
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
|
||||
return _in_order(_driver(proyecto, manifest or dbt_manifest_path()))
|
||||
return _in_order(_driver(proyecto))
|
||||
|
||||
|
||||
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
|
||||
@@ -76,7 +75,7 @@ def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
|
||||
if ctx.repos is None:
|
||||
ctx = replace(ctx, repos=repositories_of(ctx.project))
|
||||
bitacora = _Logbook()
|
||||
dr = _driver(ctx.project, ctx.dbt_manifest, bitacora)
|
||||
dr = _driver(ctx.project, bitacora)
|
||||
todos = _in_order(dr)
|
||||
pedidos = [p for p in todos if only is None or p in only]
|
||||
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
|
||||
"""
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente, SeguimientoMama, TratamientoMama
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
|
||||
|
||||
from webapi.orchestration.silver.extracted import ConEstructurado, DesdeTexto
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
|
||||
|
||||
@@ -36,39 +36,11 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
|
||||
"biopsia.her2", "biopsia.ki67_pct"),
|
||||
texto=lambda f: f.bx_pdf_blob,
|
||||
)
|
||||
DE_LA_MASTOGRAFIA = ConEstructurado(DE_LA_INTERPRETACION, {"mastografia.densidad": "mast_densidad"})
|
||||
# A mammogram's findings, each a part of its report.
|
||||
LOS_HALLAZGOS = (
|
||||
Hija("mastografia", "parte", solo_si=("mast_margen_masa",), fecha="mast_fecha_reporte",
|
||||
resultados={"mast_margen_masa": "mastografia.margen_masa"}),
|
||||
Hija("mastografia", "parte", solo_si=("mast_tipo_hallazgo",), fecha="mast_fecha_reporte",
|
||||
resultados={"mast_tipo_hallazgo": "mastografia.tipo_hallazgo"}),
|
||||
)
|
||||
DE_LA_NOTA = DesdeTexto(
|
||||
"cama", ("nota_medica.estadio_clinico",),
|
||||
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
|
||||
)
|
||||
|
||||
# What a biopsy report and a note carry structured wins over the text's reading; the rest is read from the text.
|
||||
DE_LA_PATOLOGIA = ConEstructurado(DEL_REPORTE_DE_PATOLOGIA, {
|
||||
"biopsia.tipo_histologico": "bx_tipo_histologico", "biopsia.grado_nottingham": "bx_grado_nottingham",
|
||||
"biopsia.receptor_estrogeno": "bx_receptor_estrogeno", "biopsia.receptor_estrogeno_pct": "bx_receptor_estrogeno_pct",
|
||||
"biopsia.receptor_progesterona": "bx_receptor_progesterona",
|
||||
"biopsia.receptor_progesterona_pct": "bx_receptor_progesterona_pct", "biopsia.her2": "bx_her2",
|
||||
"biopsia.ki67_pct": "bx_ki67_pct", "biopsia.her2_fish": "bx_her2_fish",
|
||||
"biopsia.tamano_tumor_mm": "bx_tamano_tumor_mm", "biopsia.ganglios_positivos": "bx_ganglios_positivos",
|
||||
"biopsia.invasion_linfovascular": "bx_invasion_linfovascular", "biopsia.multifocalidad": "bx_multifocalidad",
|
||||
"biopsia.margenes": "bx_margenes", "biopsia.pt": "bx_pt", "biopsia.pn": "bx_pn",
|
||||
})
|
||||
DE_LA_NOTA_ESTRUCTURADA = ConEstructurado(DE_LA_NOTA, {
|
||||
"nota_medica.estadio_clinico": "nm_estadio_clinico", "nota_medica.m": "nm_metastasis",
|
||||
})
|
||||
# The biopsy's sample: the breast and the site it was taken from, dated by its request or, without one, its report.
|
||||
LA_TOMA_DE_LA_BIOPSIA = Hija(
|
||||
"biopsia", "toma", solo_si=("bx_lateralidad", "bx_localizacion"), fecha="bx_fecha_toma",
|
||||
resultados={"bx_lateralidad": "biopsia.lateralidad", "bx_localizacion": "biopsia.localizacion"},
|
||||
)
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
|
||||
@@ -79,62 +51,17 @@ DESDE_STAGING = (
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
|
||||
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
|
||||
derivadas=DE_LA_MASTOGRAFIA.derivadas,
|
||||
resultados={"mast_birads": "mastografia.birads", **DE_LA_MASTOGRAFIA.resultados},
|
||||
fuentes=DE_LA_MASTOGRAFIA.fuentes, hijas=LOS_HALLAZGOS,
|
||||
derivadas=DE_LA_INTERPRETACION.derivadas,
|
||||
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
|
||||
fuentes=DE_LA_INTERPRETACION.fuentes,
|
||||
),
|
||||
DeStaging(
|
||||
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
|
||||
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
derivadas={**DE_LA_PATOLOGIA.derivadas,
|
||||
"bx_fecha_toma": lambda f: f.bx_fecha_solicitud or f.bx_fecha_reporte},
|
||||
fuentes=DE_LA_PATOLOGIA.fuentes,
|
||||
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
|
||||
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
|
||||
resultados={"bx_grado_histologico": "biopsia.grado", **DE_LA_PATOLOGIA.resultados}),
|
||||
LA_TOMA_DE_LA_BIOPSIA),
|
||||
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
|
||||
),
|
||||
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA_ESTRUCTURADA),
|
||||
# Facts of the patient with no date of their own: dated at her birth, known as of the load.
|
||||
DeStaging(
|
||||
Paciente, "pac_id", "parte", estudio_id="sociodemografico", fecha="pac_fecha_nacimiento",
|
||||
resultados={"pac_estado_civil": "sociodemografico.estado_civil", "pac_raza": "sociodemografico.raza",
|
||||
"pac_estado_menopausico": "sociodemografico.estado_menopausico",
|
||||
"pac_fuente": "sociodemografico.fuente"},
|
||||
),
|
||||
DeStaging(
|
||||
Paciente, "pac_id", "reporte", estudio_id="prueba_genetica", fecha="pac_fecha_nacimiento",
|
||||
solo_si=lambda f: f.pac_brca1 is not None or f.pac_brca2 is not None,
|
||||
resultados={"pac_brca1": "prueba_genetica.brca1", "pac_brca2": "prueba_genetica.brca2"},
|
||||
),
|
||||
*(
|
||||
DeStaging(
|
||||
TratamientoMama, "trat_id", "encuentro", estudio_id=estudio, fecha="trat_fecha",
|
||||
solo_si=lambda f, e=estudio: f.trat_tipo == e,
|
||||
resultados={"trat_detalle": resultado, **({"trat_lateralidad": "cirugia.lateralidad"} if estudio == "cirugia" else {})},
|
||||
)
|
||||
for estudio, resultado in (
|
||||
("cirugia", "cirugia.tipo_cirugia"), ("radioterapia", "radioterapia.intencion"),
|
||||
("quimioterapia", "quimioterapia.intencion"), ("hormonoterapia", "hormonoterapia.intencion"),
|
||||
("anti_her2", "anti_her2.intencion"),
|
||||
)
|
||||
),
|
||||
*(
|
||||
DeStaging(
|
||||
SeguimientoMama, "seg_id", "encuentro", estudio_id=estudio, fecha="seg_fecha",
|
||||
solo_si=lambda f, e=estudio: f.seg_tipo == e, resultados={"seg_detalle": resultado},
|
||||
)
|
||||
for estudio, resultado in (("recurrencia", "recurrencia.sitio"), ("ultimo_contacto", "ultimo_contacto.estado"))
|
||||
),
|
||||
DeStaging(
|
||||
Paciente, "pac_id", "parte", estudio_id="perfil_molecular", fecha="pac_fecha_nacimiento",
|
||||
solo_si=lambda f: any(getattr(f, c) is not None for c in (
|
||||
"pac_pam50", "pac_subtipo_clinico", "pac_cluster_integrativo", "pac_celularidad", "pac_carga_mutacional",
|
||||
"pac_ki67_categoria")),
|
||||
resultados={"pac_pam50": "perfil_molecular.pam50", "pac_subtipo_clinico": "perfil_molecular.subtipo_clinico",
|
||||
"pac_cluster_integrativo": "perfil_molecular.cluster_integrativo",
|
||||
"pac_celularidad": "perfil_molecular.celularidad",
|
||||
"pac_carga_mutacional": "perfil_molecular.carga_mutacional",
|
||||
"pac_ki67_categoria": "perfil_molecular.ki67_categoria"},
|
||||
),
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
|
||||
)
|
||||
|
||||
@@ -117,42 +117,3 @@ def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
|
||||
if texto is not None and str(texto.value).strip():
|
||||
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
|
||||
return None, None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConEstructurado:
|
||||
"""`DesdeTexto` whose results the row may carry already structured: a structured column wins over what the text
|
||||
gives, and a column with no text twin is a result of its own. `estructurados`: result -> staging column;
|
||||
each result keeps the text reading as its fallback when `lector` has it."""
|
||||
|
||||
lector: DesdeTexto | None
|
||||
estructurados: dict[str, str]
|
||||
|
||||
@property
|
||||
def derivadas(self) -> dict[str, Callable]:
|
||||
columnas = dict(self.lector.derivadas) if self.lector else {}
|
||||
leidos = set(self.lector.resultado_ids) if self.lector else set()
|
||||
for resultado_id, columna in self.estructurados.items():
|
||||
clave = _columna(resultado_id)
|
||||
texto = self.lector.derivadas[clave] if resultado_id in leidos else (lambda f: None)
|
||||
fuente = self.lector.derivadas[clave + "_fuente"] if resultado_id in leidos else (lambda f: None)
|
||||
columnas[clave] = lambda f, c=columna, t=texto: _con_valor(getattr(f, c, None), t(f))
|
||||
columnas[clave + "_fuente"] = lambda f, c=columna, t=fuente: (
|
||||
None if _vacio(getattr(f, c, None)) else t(f))
|
||||
return columnas
|
||||
|
||||
@property
|
||||
def resultados(self) -> dict[str, str]:
|
||||
return {_columna(r): r for r in {*(self.lector.resultado_ids if self.lector else ()), *self.estructurados}}
|
||||
|
||||
@property
|
||||
def fuentes(self) -> dict[str, str]:
|
||||
return {columna: columna + "_fuente" for columna in self.resultados}
|
||||
|
||||
|
||||
def _vacio(valor) -> bool:
|
||||
return valor is None or (isinstance(valor, str) and not valor.strip())
|
||||
|
||||
|
||||
def _con_valor(estructurado, leido):
|
||||
return leido if _vacio(estructurado) else estructurado
|
||||
|
||||
@@ -22,7 +22,6 @@ def de_derechohabiente(paciente) -> dict:
|
||||
"dependencia": texto_limpio(paciente.pac_dependencia),
|
||||
"parentesco": texto_limpio(paciente.pac_parentesco),
|
||||
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
|
||||
"fecha_defuncion": paciente.pac_fecha_defuncion,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
|
||||
|
||||
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
|
||||
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
|
||||
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
|
||||
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
||||
removed or renamed, only added.
|
||||
"""
|
||||
|
||||
from datetime import timezone
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
COHORT_URL = "cacu/cohorte_vigilancia"
|
||||
COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
|
||||
|
||||
|
||||
def patient_risk_blueprint(repositories) -> Blueprint:
|
||||
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
|
||||
blueprint = Blueprint("cacu_patient_risk", __name__)
|
||||
|
||||
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
|
||||
def get_patient_risk(pac_id: int):
|
||||
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
|
||||
if repositories.persona_repository.get(pac_id) is None:
|
||||
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
|
||||
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
|
||||
risk = repositories.cohort_repository.current_risk(pac_id)
|
||||
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
|
||||
|
||||
return blueprint
|
||||
|
||||
|
||||
def _cohort(membership) -> dict | None:
|
||||
if membership is None:
|
||||
return None
|
||||
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
|
||||
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
|
||||
|
||||
|
||||
def _risk(risk) -> dict | None:
|
||||
if risk is None:
|
||||
return None
|
||||
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
|
||||
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
|
||||
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"estado_lote": risk.estado_lote,
|
||||
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
|
||||
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
|
||||
@@ -1,8 +1,7 @@
|
||||
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
|
||||
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
|
||||
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
|
||||
confirm one (`preliminary` -> `final`, visible on `/cacu/pacientes/<id>/riesgo`) or void it (`entered-in-error`).
|
||||
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
|
||||
to be defined.
|
||||
to be defined, as `patient_risk.py` notes for reads.
|
||||
"""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
Reference in New Issue
Block a user