dbt is the only definition of a cohort: the stored build runs dbt's queries
The WebApi cycle's build (models.cohorts.build.build_of) runs the cohort's queries from dbt's manifest with the same chain as the export, instead of a Python frame per cohort; the TOML definitions, their frames and definition.py are removed. A cohort may have no exclusions (cacu/cohorte_total, for models whose rules don't fit SQL) and an optional `variables` query; the population meta carries the cohort's version. cohort_urls lists a domain's cohorts in the manifest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
|
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
|
||||||
versiones en MLflow con requisitos de promoción, registro de predicciones y
|
versiones en MLflow con requisitos de promoción, registro de predicciones y
|
||||||
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
|
los trabajos de OCR de reportes. Las cohortes se definen solo en dbt
|
||||||
armados del kit de indicadores (`cohorte_armado`, en la base de cada
|
(`Transformation/models/<dominio>/cohorts/`); el ciclo de la WebApi guarda un
|
||||||
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
|
armado de ellas (`cohorte_armado`, en la base de cada dominio, por
|
||||||
|
`models/cohorts/build.py`), y con ese armado se entrena y se estima. Las reglas
|
||||||
|
que no caben en SQL son del modelo, sobre `cacu/cohorte_total`. Lee y escribe por los mismos repositorios de `Persistance` que usa
|
||||||
WebApi.
|
WebApi.
|
||||||
|
|
||||||
| Módulo | Qué hace |
|
| Módulo | Qué hace |
|
||||||
|
|||||||
+5
-5
@@ -388,7 +388,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
|
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
|
||||||
show.add_argument("domain", choices=["cacu", "cama", "tea"])
|
show.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||||
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
|
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||||
show.add_argument("--build", type=int, required=True, help="the build's number")
|
show.add_argument("--build", type=int, required=True, help="the build's number")
|
||||||
show.set_defaults(run=_cohort_show)
|
show.set_defaults(run=_cohort_show)
|
||||||
|
|
||||||
@@ -397,7 +397,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||||
train.add_argument("--build", "--armado", dest="armado", type=int,
|
train.add_argument("--build", "--armado", dest="armado", type=int,
|
||||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||||
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||||
train.add_argument("--read", choices=["db", "file"], default="db",
|
train.add_argument("--read", choices=["db", "file"], default="db",
|
||||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||||
@@ -409,7 +409,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
||||||
estimate.add_argument("--build", "--armado", dest="armado", type=int,
|
estimate.add_argument("--build", "--armado", dest="armado", type=int,
|
||||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||||
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||||
estimate.add_argument("--read", choices=["db", "file"], default="db",
|
estimate.add_argument("--read", choices=["db", "file"], default="db",
|
||||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||||
estimate.add_argument("--version", help="the model version; the one in production by default")
|
estimate.add_argument("--version", help="the model version; the one in production by default")
|
||||||
@@ -424,7 +424,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
|
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
|
||||||
eda.add_argument("--build", "--armado", dest="armado", type=int,
|
eda.add_argument("--build", "--armado", dest="armado", type=int,
|
||||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||||
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
|
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||||
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
|
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
|
||||||
eda.set_defaults(run=_report_eda)
|
eda.set_defaults(run=_report_eda)
|
||||||
|
|
||||||
@@ -444,7 +444,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
|
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
|
||||||
run.add_argument("--build", "--armado", dest="armado", type=int,
|
run.add_argument("--build", "--armado", dest="armado", type=int,
|
||||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||||
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
|
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||||
run.add_argument("--read", choices=["db", "file"], default="db",
|
run.add_argument("--read", choices=["db", "file"], default="db",
|
||||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||||
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
|
"""Cohorts for the risk models. dbt is their only definition (`Transformation/models/<project>/cohorts/`: population,
|
||||||
builds its frame from the patients' timeline (dbt's view, through Persistance).
|
index date and exclusions as queries in the manifest); this package stores a build of them for the WebApi cycle.
|
||||||
|
|
||||||
definition.py a cohort's definition, read from its TOML
|
build.py from dbt's queries to `cohorte_armado` and its rows; the stored frame, wide
|
||||||
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
|
cama/ CaMa's screening cohort, a PROPOSAL in the old Python-frame format, not built
|
||||||
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
|
|
||||||
"""
|
"""
|
||||||
|
|||||||
+57
-88
@@ -1,111 +1,79 @@
|
|||||||
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
|
"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición.
|
||||||
|
|
||||||
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
|
dbt es la única definición de una cohorte (`Transformation/models/<proyecto>/cohorts/`): su población, su fecha
|
||||||
(`TimelineRepository.query`), recortada al corte y,
|
índice y sus exclusiones son consultas del manifest (`models.io.storage.read_queries`), y el armado las corre en la
|
||||||
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
|
sesión que le dan, con la misma cadena que la exportación (`models.pipelines.cohort_build.build_cohort`). Las
|
||||||
versiones de fila es aproximado, ADR-MD-009). La regla de
|
reglas que no caben en SQL son del modelo, sobre `cacu/cohorte_total` y la línea de tiempo, no de una cohorte.
|
||||||
la cohorte es la función que nombra su definición (`expression`).
|
|
||||||
|
|
||||||
Rearmar con la misma definición, los mismos parámetros y los mismos datos no
|
Rearmar con las mismas consultas, los mismos parámetros y los mismos datos no guarda otro armado: la huella del
|
||||||
guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están.
|
pedido y la del marco (`marco_sha`) ya están. Si los datos cambiaron, el `marco_sha` cambia y se guarda uno nuevo.
|
||||||
Si los datos cambiaron, el `marco_sha` cambia y se guarda un armado nuevo.
|
|
||||||
|
|
||||||
`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o
|
|
||||||
valida con este armado: llaves y huellas, nunca filas ni `pac_id`.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import inspect
|
import hashlib
|
||||||
import json
|
import json
|
||||||
from datetime import date, datetime, timezone
|
from contextlib import nullcontext
|
||||||
from importlib import import_module
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
from persistance.edges.dbt import DbtQueryRepository
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
from models.cohorts.definition import Definition, json_sha
|
from models.io.contracts import CohortQueries
|
||||||
|
from models.pipelines.cohort_build import build_cohort
|
||||||
DECIMALS = 9 # redondeo de los tiempos en la huella del marco
|
|
||||||
|
|
||||||
|
|
||||||
def timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]:
|
def json_sha(objeto) -> str:
|
||||||
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
|
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
|
||||||
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
|
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||||
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
|
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def frame_of(
|
def queries_sha(queries: CohortQueries) -> str:
|
||||||
sesion: Session,
|
"""Huella de las reglas: el SQL compilado de cada paso, en su orden. Hace el papel de la definición."""
|
||||||
definicion: Definition,
|
return json_sha({"all_patients": queries.all_patients, "index_date": queries.index_date,
|
||||||
inicio: date,
|
"rules": [[rule.order, rule.name, rule.sql] for rule in queries.rules],
|
||||||
fin: date,
|
"variables": queries.variables})
|
||||||
corte: date,
|
|
||||||
*,
|
|
||||||
linea,
|
|
||||||
pacientes: list[int] | None = None,
|
|
||||||
conocida_hasta: datetime | None = None,
|
|
||||||
):
|
|
||||||
"""El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente)."""
|
|
||||||
filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta)
|
|
||||||
return definicion.function()(filas, definicion.reglas, inicio, fin, corte)
|
|
||||||
|
|
||||||
|
|
||||||
def frame_sha(miembros, definicion: Definition) -> str:
|
def frame_sha(miembros, variables=()) -> str:
|
||||||
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
|
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
|
||||||
nombres = [v.nombre for v in definicion.variables]
|
return json_sha({"miembros": sorted([int(m["pac_id"]), m["fecha_indice"].isoformat()] for m in miembros),
|
||||||
|
"variables": sorted([v.pac_id, v.variable, v.valor_codigo, v.valor_numerico] for v in variables)})
|
||||||
def redondo(valor):
|
|
||||||
return round(valor, DECIMALS) if isinstance(valor, float) else valor
|
|
||||||
|
|
||||||
return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)]
|
|
||||||
for m in sorted(miembros, key=lambda m: m.pac_id)])
|
|
||||||
|
|
||||||
|
|
||||||
def code_sha(definicion: Definition) -> str:
|
def build_of(sesion: Session, queries: CohortQueries, *, cohortes: TablasCohorte, ahora: datetime | None = None):
|
||||||
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
|
"""El armado sin guardarlo: la fila de `cohorte_armado`, sus exclusiones, sus miembros y sus variables (sin
|
||||||
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
|
`armado_id`). Las variables son las de la consulta `variables` de la cohorte, si tiene, solo de sus miembros; las
|
||||||
return json_sha(inspect.getsource(modulo))
|
que no caben en SQL las calcula el modelo de la línea de tiempo.
|
||||||
|
|
||||||
|
|
||||||
def build_of(
|
|
||||||
sesion: Session,
|
|
||||||
definicion: Definition,
|
|
||||||
inicio: date,
|
|
||||||
fin: date,
|
|
||||||
corte: date,
|
|
||||||
*,
|
|
||||||
cohortes: TablasCohorte,
|
|
||||||
linea,
|
|
||||||
conocida_hasta: datetime | None = None,
|
|
||||||
ahora: datetime | None = None,
|
|
||||||
):
|
|
||||||
"""El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`).
|
|
||||||
|
|
||||||
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
|
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
|
||||||
"""
|
"""
|
||||||
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
|
consultas = DbtQueryRepository(lambda: nullcontext(sesion))
|
||||||
conocida_hasta=conocida_hasta)
|
built = build_cohort(queries, consultas)
|
||||||
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
|
miembros = built.study_population.to_dict("records")
|
||||||
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
|
parametros = {**queries.parameters, "corte": queries.cutoff.isoformat()}
|
||||||
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
|
reglas_sha = json_sha(queries.parameters)
|
||||||
"codigo": code_sha(definicion), "parametros": parametros})
|
definicion_sha = queries_sha(queries)
|
||||||
armado = cohortes.CohorteArmado(
|
armado = cohortes.CohorteArmado(
|
||||||
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
|
url=queries.url, version=queries.version or "0", definicion_sha=definicion_sha, reglas_sha=reglas_sha,
|
||||||
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
|
parametros=json.dumps(parametros, sort_keys=True), datos_as_of=queries.cutoff,
|
||||||
huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros),
|
huella=json_sha({"definicion": definicion_sha, "reglas": reglas_sha, "parametros": parametros}),
|
||||||
armado_en=ahora or datetime.now(timezone.utc),
|
marco_sha="", n_miembros=len(miembros), armado_en=ahora or datetime.now(timezone.utc),
|
||||||
)
|
)
|
||||||
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
|
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=fila["step"], n=int(fila["n"]))
|
||||||
for orden, (paso, n) in enumerate(atricion, start=1)]
|
for orden, fila in enumerate(built.attrition.to_dict("records"), start=1)]
|
||||||
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
|
filas_miembro = [cohortes.CohorteMiembro(pac_id=int(m["pac_id"]), fecha_indice=m["fecha_indice"],
|
||||||
indice_fuente_tabla=m.indice_fuente_tabla,
|
indice_fuente_tabla=m.get("indice_fuente_tabla"),
|
||||||
indice_fuente_id=m.indice_fuente_id) for m in miembros]
|
indice_fuente_id=None if m.get("indice_fuente_id") is None
|
||||||
tipos = {v.nombre: v.tipo for v in definicion.variables}
|
else str(m["indice_fuente_id"])) for m in miembros]
|
||||||
variables = [
|
socias = {int(m["pac_id"]) for m in miembros}
|
||||||
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
|
variables = [cohortes.CohorteVariable(pac_id=int(v["pac_id"]), variable=v["variable"],
|
||||||
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
|
valor_codigo=None if v.get("valor_codigo") is None else str(v["valor_codigo"]),
|
||||||
else {"valor_numerico": float(valor)}))
|
valor_numerico=None if v.get("valor_numerico") is None
|
||||||
for m in miembros for nombre, valor in m.variables.items() if valor is not None
|
else float(v["valor_numerico"]))
|
||||||
]
|
for v in (consultas.read(queries.variables) if queries.variables else [])
|
||||||
|
if int(v["pac_id"]) in socias and (v.get("valor_codigo") is not None or v.get("valor_numerico") is not None)]
|
||||||
|
armado.marco_sha = frame_sha(miembros, variables)
|
||||||
return armado, exclusiones, filas_miembro, variables
|
return armado, exclusiones, filas_miembro, variables
|
||||||
|
|
||||||
|
|
||||||
@@ -117,15 +85,16 @@ def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int |
|
|||||||
).first()
|
).first()
|
||||||
|
|
||||||
|
|
||||||
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
|
def read_frame(sesion: Session, armado_id: int, *, cohortes: TablasCohorte):
|
||||||
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
|
"""El marco guardado, ancho: (columnas, filas), una por miembro, con las variables que el armado tenga (los de
|
||||||
nombres = [v.nombre for v in definicion.variables]
|
dbt no tienen: solo `pac_id` y `fecha_indice`)."""
|
||||||
valores: dict[int, dict] = {}
|
valores: dict[int, dict] = {}
|
||||||
variable = cohortes.CohorteVariable
|
variable = cohortes.CohorteVariable
|
||||||
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
|
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
|
||||||
valores.setdefault(fila.pac_id, {})[fila.variable] = (
|
valores.setdefault(fila.pac_id, {})[fila.variable] = (
|
||||||
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
|
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
|
||||||
)
|
)
|
||||||
|
nombres = sorted({nombre for porpac in valores.values() for nombre in porpac})
|
||||||
miembro = cohortes.CohorteMiembro
|
miembro = cohortes.CohorteMiembro
|
||||||
filas = [
|
filas = [
|
||||||
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
|
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ ESTIMATE_FRAME = pandera.DataFrameSchema(
|
|||||||
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
||||||
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
|
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
|
||||||
|
|
||||||
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
|
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
|
||||||
|
|
||||||
|
|
||||||
class CohortFileError(ValueError):
|
class CohortFileError(ValueError):
|
||||||
@@ -93,6 +93,9 @@ class CohortQueries:
|
|||||||
rules: tuple[ExclusionRule, ...]
|
rules: tuple[ExclusionRule, ...]
|
||||||
cutoff: date
|
cutoff: date
|
||||||
parameters: dict
|
parameters: dict
|
||||||
|
version: str = "" # the population meta's `version`: bumped when a rule changes
|
||||||
|
# optional: the members' stored variables, long (`pac_id`, `variable`, `valor_codigo`, `valor_numerico`)
|
||||||
|
variables: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|||||||
+17
-5
@@ -30,7 +30,7 @@ import pyarrow as pa
|
|||||||
import pyarrow.parquet as pq
|
import pyarrow.parquet as pq
|
||||||
from sqlalchemy.engine import make_url
|
from sqlalchemy.engine import make_url
|
||||||
|
|
||||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
|
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, VARIABLES, CohortDefinitionError,
|
||||||
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
||||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
|
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
|
||||||
|
|
||||||
@@ -188,14 +188,16 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
|||||||
if not nodes:
|
if not nodes:
|
||||||
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
||||||
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
||||||
|
# a cohort may have no exclusions (`cacu/cohorte_total`): its study population is everyone with an index
|
||||||
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
|
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
|
||||||
if not exclusions:
|
|
||||||
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
|
|
||||||
orders = [node["config"]["meta"]["order"] for node in exclusions]
|
orders = [node["config"]["meta"]["order"] for node in exclusions]
|
||||||
if len(set(orders)) != len(orders):
|
if len(set(orders)) != len(orders):
|
||||||
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
||||||
|
variables = [node for node in nodes if node["config"]["meta"]["kind"] == VARIABLES]
|
||||||
|
if len(variables) > 1:
|
||||||
|
raise CohortDefinitionError(f"{url} has more than one `{VARIABLES}` query")
|
||||||
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
||||||
for node in exclusions:
|
for node in [*exclusions, *variables]:
|
||||||
if read := steps & set(node["depends_on"]["nodes"]):
|
if read := steps & set(node["depends_on"]["nodes"]):
|
||||||
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
|
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
|
||||||
meta = population["config"]["meta"]
|
meta = population["config"]["meta"]
|
||||||
@@ -204,7 +206,17 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
|||||||
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
||||||
for node in exclusions)
|
for node in exclusions)
|
||||||
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
||||||
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
|
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")),
|
||||||
|
str(meta.get("version", "")), _compiled(variables[0]) if variables else None)
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_urls(manifest: str | Path, domain: str) -> list[str]:
|
||||||
|
"""The urls of the domain's cohorts in dbt's manifest (`meta.cohort` of their population queries), sorted: the
|
||||||
|
cohorts the WebApi cycle builds."""
|
||||||
|
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
||||||
|
return sorted({node["config"]["meta"]["cohort"] for node in nodes
|
||||||
|
if node.get("config", {}).get("meta", {}).get("kind") == POPULATION
|
||||||
|
and str(node["config"]["meta"].get("cohort", "")).startswith(f"{domain}/")})
|
||||||
|
|
||||||
|
|
||||||
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
|
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ def _fresh(function):
|
|||||||
def build_driver(queries: CohortQueries) -> driver.Driver:
|
def build_driver(queries: CohortQueries) -> driver.Driver:
|
||||||
"""The chain for the cohort's rules, in their order."""
|
"""The chain for the cohort's rules, in their order."""
|
||||||
rules = list(queries.rules)
|
rules = list(queries.rules)
|
||||||
|
if not rules: # a cohort without rules (`cacu/cohorte_total`): everyone with an index
|
||||||
|
nodes = [all_patients, indexed, inject(last=source("indexed"))(_fresh(study_population)),
|
||||||
|
inject(populations=value([]), rules=value([]))(_fresh(attrition))]
|
||||||
|
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
||||||
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
||||||
nodes = [
|
nodes = [
|
||||||
all_patients,
|
all_patients,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from sqlmodel import Session
|
|||||||
|
|
||||||
from models.__main__ import main
|
from models.__main__ import main
|
||||||
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||||
from models.io.storage import read_queries
|
from models.io.storage import cohort_urls, read_queries
|
||||||
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
||||||
from models.steps import cohort
|
from models.steps import cohort
|
||||||
|
|
||||||
@@ -125,10 +125,11 @@ def test_a_population_without_cutoff_is_refused(manifest):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("change, message", [
|
@pytest.mark.parametrize("change, message", [
|
||||||
(lambda n: n[:1] + n[2:], "exactly one `index`"),
|
(lambda n: n[:1] + n[2:], "exactly one `index`"),
|
||||||
(lambda n: n[:2], "no `exclusion` queries"),
|
|
||||||
(lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"),
|
(lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"),
|
||||||
(lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"),
|
(lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"),
|
||||||
(lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"),
|
(lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"),
|
||||||
|
(lambda n: [*n, _node("v1", "variables", _rows(1)), _node("v2", "variables", _rows(1))], "more than one `variables`"),
|
||||||
|
(lambda n: [*n, _node("v", "variables", _rows(1)) | {"depends_on": {"nodes": ["model.p.first"]}}], "may only read"),
|
||||||
])
|
])
|
||||||
def test_a_badly_defined_cohort_is_refused(manifest, change, message):
|
def test_a_badly_defined_cohort_is_refused(manifest, change, message):
|
||||||
"""Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an
|
"""Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an
|
||||||
@@ -219,3 +220,68 @@ def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys):
|
|||||||
|
|
||||||
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1
|
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1
|
||||||
assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err
|
assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_cohort_without_rules_is_everyone_with_an_index(manifest):
|
||||||
|
"""Pins down: a cohort with no exclusions (`cacu/cohorte_total`) reads, and its study population is every patient
|
||||||
|
with an index, with only the population and index steps in its attrition. Fails if exclusions become required
|
||||||
|
again or the chain needs a last rule."""
|
||||||
|
queries = read_queries(manifest(_standard()[:2]), URL)
|
||||||
|
built = build_cohort(queries, _sqlite_reader())
|
||||||
|
|
||||||
|
assert queries.rules == ()
|
||||||
|
assert sorted(built.study_population["pac_id"]) == [1, 2, 3, 4, 5]
|
||||||
|
assert built.attrition[["step", "n"]].values.tolist() == [["all_patients", 6], ["indexed", 5]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_cycle_builds_the_domains_cohorts_of_the_manifest(manifest):
|
||||||
|
"""Pins down: the cohorts of a domain are the `meta.cohort` of the manifest's population queries with that
|
||||||
|
prefix, sorted, once each; another domain's are not. Fails if an index or exclusion query names a cohort the
|
||||||
|
cycle then builds, or the prefix leaks."""
|
||||||
|
path = manifest([*_standard(), _node("x", "population", _rows(1)) | {"config": {"meta": {"cohort": "cama/c", "kind": "population"}}}])
|
||||||
|
|
||||||
|
assert cohort_urls(path, "cacu") == ["cacu/other", URL]
|
||||||
|
assert cohort_urls(path, "cama") == ["cama/c"]
|
||||||
|
assert cohort_urls(path, "tea") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_and_variables_come_from_the_manifest(manifest):
|
||||||
|
"""Pins down: the population meta's `version` and the optional `variables` query reach `CohortQueries`. Fails if
|
||||||
|
either is dropped, so builds would lose their version or the WebApp its variables."""
|
||||||
|
nodes = _standard()
|
||||||
|
nodes[0]["config"]["meta"]["version"] = "1.2.0"
|
||||||
|
sql = "select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico"
|
||||||
|
queries = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL)
|
||||||
|
|
||||||
|
assert (queries.version, queries.variables) == ("1.2.0", sql)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_stored_build_comes_from_dbts_queries(manifest):
|
||||||
|
"""Pins down: `models.cohorts.build.build_of` turns dbt's queries into the cycle's rows: the build with the
|
||||||
|
population meta's version and the count of the study population, one exclusion row per attrition step, the
|
||||||
|
members, and the `variables` query's values of members only. Fails if the build stops running dbt's rules, keeps
|
||||||
|
a non-member's variable, or its frame hash ignores the variables."""
|
||||||
|
from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable,
|
||||||
|
EvaluacionRiesgo, EvaluacionRiesgoLote)
|
||||||
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
|
||||||
|
from models.cohorts.build import build_of
|
||||||
|
|
||||||
|
tables = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||||
|
EvaluacionRiesgo)
|
||||||
|
nodes = _standard()
|
||||||
|
nodes[0]["config"]["meta"]["version"] = "0.3.0"
|
||||||
|
sql = ("select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico "
|
||||||
|
"union all select 2, 'pap_0', 'ASC-US', null")
|
||||||
|
with_variables = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL)
|
||||||
|
without = read_queries(manifest(nodes), URL)
|
||||||
|
|
||||||
|
with Session(create_engine("sqlite://")) as session:
|
||||||
|
build, exclusions, members, variables = build_of(session, with_variables, cohortes=tables)
|
||||||
|
plain, *_ = build_of(session, without, cohortes=tables)
|
||||||
|
|
||||||
|
assert (build.url, build.version, build.n_miembros) == (URL, "0.3.0", 2)
|
||||||
|
assert [(e.paso, e.n) for e in exclusions] == [("all_patients", 6), ("indexed", 5), ("first", 3), ("second", 2)]
|
||||||
|
assert sorted(m.pac_id for m in members) == [1, 5]
|
||||||
|
assert [(v.pac_id, v.variable, v.valor_codigo) for v in variables] == [(1, "pap_0", "NORMAL")]
|
||||||
|
assert build.marco_sha != plain.marco_sha and build.huella != plain.huella
|
||||||
|
|||||||
Reference in New Issue
Block a user