Compare commits

..

2 Commits

21 changed files with 31 additions and 585 deletions
+4 -4
View File
@@ -226,7 +226,7 @@ def _cohort_export(args: argparse.Namespace) -> int:
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
from importlib import import_module
from persistance.edges.dbt import DbtRelationError
from persistance.aristas.dbt import DbtRelationError
from persistance.settings import settings
from sqlalchemy.exc import DBAPIError
@@ -244,7 +244,7 @@ def _cohort_export(args: argparse.Namespace) -> int:
queries = read_queries(args.manifest, url)
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
else:
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
path, outcome = export_kit_build(repositories.cohorte_repository, timeline, root, args.domain, url, args.build)
except PermissionError as error:
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
return 1
@@ -273,7 +273,7 @@ def _cohort_list(args: argparse.Namespace) -> int:
except ValueError as error:
print(error, file=sys.stderr)
return 1
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohort_repository
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohorte_repository
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
if not rows:
print(f"{url}: no builds", file=sys.stderr)
@@ -297,7 +297,7 @@ def _cohort_show(args: argparse.Namespace) -> int:
url = f"{args.domain}/{args.cohort}"
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
cohorts = import_module(f"persistance.{args.domain}").cohort_repository if args.source == "kit" else None
cohorts = import_module(f"persistance.{args.domain}").cohorte_repository if args.source == "kit" else None
described = describe_build(root, url, args.source, args.build, cohorts)
except (ValueError, LookupError) as error:
print(error, file=sys.stderr)
@@ -31,7 +31,7 @@
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "from persistance.edges.silver import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohort_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)",
"source": "from persistance.aristas.plata import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohorte_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)",
"id": "cacu-cin2-01-04"
},
{
@@ -45,7 +45,7 @@
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohort_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"",
"source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohorte_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"",
"id": "cacu-cin2-01-06"
},
{
@@ -53,7 +53,7 @@
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "builds = pd.DataFrame([vars(b) for b in cohort_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]",
"source": "builds = pd.DataFrame([vars(b) for b in cohorte_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]",
"id": "cacu-cin2-01-07"
},
{
@@ -61,7 +61,7 @@
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "build = cohort_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)",
"source": "build = cohorte_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)",
"id": "cacu-cin2-01-08"
},
{
-7
View File
@@ -1,7 +0,0 @@
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
builds its frame from the patients' timeline (dbt's view, through Persistance).
definition.py a cohort's definition, read from its TOML
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
"""
-134
View File
@@ -1,134 +0,0 @@
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
(`TimelineRepository.query`), recortada al corte y,
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
versiones de fila es aproximado, ADR-MD-009). La regla de
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
guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están.
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 json
from datetime import date, datetime, timezone
from importlib import import_module
from core.indicadores.cohortes import TablasCohorte
from sqlmodel import Session, select
from models.cohorts.definition import Definition, json_sha
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]:
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
def frame_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
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:
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
nombres = [v.nombre for v in definicion.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:
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
return json_sha(inspect.getsource(modulo))
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.
"""
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
conocida_hasta=conocida_hasta)
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
"codigo": code_sha(definicion), "parametros": parametros})
armado = cohortes.CohorteArmado(
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros),
armado_en=ahora or datetime.now(timezone.utc),
)
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
for orden, (paso, n) in enumerate(atricion, start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
indice_fuente_tabla=m.indice_fuente_tabla,
indice_fuente_id=m.indice_fuente_id) for m in miembros]
tipos = {v.nombre: v.tipo for v in definicion.variables}
variables = [
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
else {"valor_numerico": float(valor)}))
for m in miembros for nombre, valor in m.variables.items() if valor is not None
]
return armado, exclusiones, filas_miembro, variables
def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int | None:
"""El `armado_id` más reciente de la cohorte `url` (el último que se guardó); nulo si no hay. Solo lee."""
armado = cohortes.CohorteArmado
return sesion.exec(
select(armado.armado_id).where(armado.url == url).order_by(armado.armado_id.desc()).limit(1)
).first()
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
nombres = [v.nombre for v in definicion.variables]
valores: dict[int, dict] = {}
variable = cohortes.CohorteVariable
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
valores.setdefault(fila.pac_id, {})[fila.variable] = (
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
)
miembro = cohortes.CohorteMiembro
filas = [
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
for m in sesion.exec(select(miembro).where(miembro.armado_id == armado_id).order_by(miembro.pac_id))
]
return ["pac_id", "fecha_indice", *nombres], filas
-1
View File
@@ -1 +0,0 @@
"""CaCu's cohorts: the surveillance cohort."""
-106
View File
@@ -1,106 +0,0 @@
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
Quién entra:
- la índice es la primera citología de toda la historia, si cae en la ventana;
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
- y luego a quien no tiene resultado citológico ni de VPH en la índice.
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
SIN_ESTADO = -999
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # nombre -> valor; un valor nulo no se guarda
def _by_patient(filas):
pacientes = defaultdict(list)
for fila in filas:
pacientes[fila["pac_id"]].append(fila)
return pacientes
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(miembros, atrición). `filas`: la línea de tiempo de CaCu, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_evento"])
ventana = int(reglas["ventana_basal_dias"])
pap_negativo = set(reglas["no_prevalente"]["pap"])
vph_negativo = set(reglas["no_prevalente"]["vph"])
candidatas = evento_previo = sin_resultado = 0
miembros = []
for pac_id, eventos in sorted(_by_patient(filas).items()):
eventos = [e for e in eventos if e["fecha"] <= corte]
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
continue
indice = tomas[0]
llave = (indice["fuente_tabla"], indice["fuente_id"])
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
candidatas += 1
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
evento_previo += 1
continue
if pap_0 is None and hpv_0 is None:
sin_resultado += 1
continue
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
for fecha, positiva in biopsias if fecha >= fecha_indice]
if reglas["negativo_da_l"]:
for toma in tomas[1:]:
clave = (toma["fuente_tabla"], toma["fuente_id"])
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
positivas = [d for d, positiva, _ in verificaciones if positiva]
primera_positiva = min(positivas) if positivas else None
negativas = [d for d, positiva, _ in verificaciones
if not positiva and (primera_positiva is None or d < primera_positiva)]
ultima_negativa = max(negativas) if negativas else None
if primera_positiva is not None and primera_positiva <= ventana:
c = 1
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
c = 0
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
c = 0
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
c = 0
else:
c = SIN_ESTADO
if c == 1:
l = r = SIN_ESTADO
else:
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
miembros.append(Member(pac_id, fecha_indice, *llave,
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
("sin sin_resultado", len(miembros))]
return miembros, atricion
-78
View File
@@ -1,78 +0,0 @@
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
#
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cacu/cohorte_vigilancia"
version = "0.2.0"
status = "draft"
membership = "definitional"
title = "Mujeres en vigilancia por citología"
expression = "cacu.surveillance:frame"
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "evento_previo"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
[[group.characteristic]]
code = "sin_resultado"
exclude = true
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
[group.reglas]
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
ventana_basal_dias = 90
negativo_da_l = true
negativo_confirma_no_prevalente = true
colposcopia_negativa = []
[group.reglas.no_prevalente]
pap = ["NORMAL"]
vph = ["NEGATIVO"]
description = "Tamizaje completamente negativo: confirma que no es prevalente"
[group.reglas_estado]
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
[[evidenceVariable]]
name = "c"
role = "outcome"
tipo = "numero"
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
[[evidenceVariable]]
name = "l"
role = "outcome"
tipo = "numero"
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
[[evidenceVariable]]
name = "r"
role = "outcome"
tipo = "numero"
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Categoría citológica de la citología índice"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "Resultado de VPH de la misma muestra"
-1
View File
@@ -1 +0,0 @@
"""CaMa's cohorts: the screening cohort, a proposal the cycle doesn't build yet."""
@@ -1,63 +0,0 @@
# Cohorte de tamizaje mastográfico de CaMa: quién entra al modelo de riesgo de cáncer de mama y con qué marco.
#
# PROPUESTA (T-21g, 2026-10-21): MD-Q14 está abierta. El índice, la exclusión, el desenlace, el
# horizonte y los predictores son una propuesta del orquestador para que CaMa tenga una cohorte que
# armar y estimar, como CaCu y TEA. Todas las reglas están en `sin_definir`. Se lee de la línea de
# tiempo de CaMa (`cama/linea_de_tiempo.py`).
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cama/cohorte_tamizaje"
version = "0.1.0"
status = "draft"
membership = "definitional"
title = "Pacientes con un primer BI-RADS"
expression = "cama.screening:frame"
indice = "Primer BI-RADS de la historia de la paciente (fecha de su resultado), si cae en la ventana de reclutamiento"
desenlace = "cancer_de_mama"
[[group.characteristic]]
code = "cancer_previo"
exclude = true
description = "Cáncer de mama antes de la fecha índice: una nota con un CIE-10 de `cie_antecedente` o una biopsia con grado en `grados_cancer`"
[group.reglas]
grados_cancer = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
cie_antecedente = ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
horizonte_dias = 365
[group.reglas_estado]
grados_cancer = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.biopsia_cancer` (provisional para CAMA_BIOPSIAS)" }
cie_antecedente = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.diagnostico.cie_antecedente` (D05 y C50, como en CaCu)" }
horizonte_dias = { estado = "sin_definir", fuente = "Propuesta T-21g: un año desde el BI-RADS índice; decide clínica con modelos (MD-Q14)" }
[[evidenceVariable]]
name = "d"
role = "outcome"
tipo = "numero"
title = "Cáncer de mama por biopsia dentro del horizonte: 1 sí, 0 no (horizonte vencido al corte), -999 en observación"
[[evidenceVariable]]
name = "t"
role = "outcome"
tipo = "numero"
title = "Años del índice a la biopsia con cáncer (sin fila = sin cáncer al corte)"
[[evidenceVariable]]
name = "birads_0"
role = "covariate"
tipo = "codigo"
title = "BI-RADS índice"
[[evidenceVariable]]
name = "calidad_0"
role = "covariate"
tipo = "codigo"
title = "Calidad de imagen de la mastografía más reciente al índice"
[[evidenceVariable]]
name = "n_ordenes_previas"
role = "covariate"
tipo = "numero"
title = "Órdenes de estudio antes del índice"
-82
View File
@@ -1,82 +0,0 @@
"""El marco de la cohorte de tamizaje mastográfico de CaMa, desde la línea de tiempo (`cohorte_tamizaje.toml`). PROPUESTA (MD-Q14).
Una fila del marco por miembro:
d 1 = cáncer de mama por biopsia dentro del horizonte; 0 = sin cáncer y el horizonte venció
al corte; -999 = sin cáncer y el horizonte todavía no vence (en observación)
t años del índice a la biopsia con cáncer (nulo sin cáncer al corte)
Quién entra:
- el índice es el primer BI-RADS con categoría de toda la historia (la fecha de su resultado), si
cae en la ventana de reclutamiento;
- se excluye a quien tiene cáncer antes del índice: una nota con un CIE-10 de `cie_antecedente` o
una biopsia con grado en `grados_cancer`.
Predictores, todos conocidos a más tardar en el índice: el BI-RADS índice, la calidad de imagen de
la mastografía más reciente y cuántas órdenes de estudio hubo antes. Es el patrón de
`tea/cohortes/tamizaje.py`.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
EN_OBSERVACION = -999
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # nombre -> valor; un valor nulo no se guarda
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(miembros, atrición). `filas`: la línea de tiempo de CaMa, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_cancer"])
cie = set(reglas["cie_antecedente"])
horizonte = int(reglas["horizonte_dias"])
por_paciente = defaultdict(list)
for fila in filas:
if fila["fecha"] is not None and fila["fecha"] <= corte:
por_paciente[fila["pac_id"]].append(fila)
candidatos = cancer_previo = 0
miembros = []
for pac_id, eventos in sorted(por_paciente.items()):
birads = sorted((e for e in eventos if e["tipo"] == "birads" and e["valor_codigo"]),
key=lambda e: (e["fecha"], e["fuente_id"]))
if not birads or not (inicio <= birads[0]["fecha"] < fin):
continue
indice = birads[0]
fecha_indice = indice["fecha"]
candidatos += 1
biopsias = sorted(e["fecha"] for e in eventos if e["tipo"] == "biopsia" and e["valor_codigo"] in grados)
notas = [e["fecha"] for e in eventos if e["tipo"] == "nota_medica" and e["valor_codigo"] in cie]
if any(fecha < fecha_indice for fecha in [*biopsias, *notas]):
cancer_previo += 1
continue
posteriores = [(fecha - fecha_indice).days for fecha in biopsias]
primero = min(posteriores) if posteriores else None
if primero is not None and primero <= horizonte:
d = 1
elif (corte - fecha_indice).days >= horizonte:
d = 0
else:
d = EN_OBSERVACION
antes = [e for e in eventos if e["fecha"] <= fecha_indice]
mastografias = sorted((e for e in antes if e["tipo"] == "mastografia"), key=lambda e: (e["fecha"], e["fuente_id"]))
miembros.append(Member(pac_id, fecha_indice, indice["fuente_tabla"], indice["fuente_id"], {
"d": d, "t": None if primero is None else primero / DIAS_POR_ANIO, "birads_0": indice["valor_codigo"],
"calidad_0": mastografias[-1]["valor_codigo"] if mastografias else None,
"n_ordenes_previas": sum(1 for e in antes if e["tipo"] == "orden" and e["fecha"] < fecha_indice),
}))
atricion = [("candidatos", candidatos), ("sin cancer_previo", candidatos - cancer_previo)]
return miembros, atricion
-82
View File
@@ -1,82 +0,0 @@
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
"""
import hashlib
import json
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
@dataclass(frozen=True)
class Variable:
nombre: str
rol: str # outcome o covariate
tipo: str # numero o codigo
titulo: str
@dataclass(frozen=True)
class Definition:
url: str
version: str
titulo: str
expression: str
desenlace: str
reglas: dict
variables: tuple[Variable, ...]
definicion_sha: str # sha256 del TOML
@property
def reglas_sha(self) -> str:
return json_sha(self.reglas)
def function(self):
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
return function_of(self.expression)
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
def read_definition(ruta: Path) -> Definition:
texto = ruta.read_text(encoding="utf-8")
doc = tomllib.loads(texto)
g = doc["group"]
reglas = dict(g["reglas"])
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
nombres = [v.nombre for v in variables]
if len(set(nombres)) != len(nombres):
raise ValueError(f"{g['url']}: variables repetidas.")
return Definition(
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
desenlace=g["desenlace"], reglas=reglas, variables=variables,
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
)
def function_of(expresion: str):
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
modulo, nombre = expresion.split(":")
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
if not callable(function):
raise ValueError(f"{modulo} debe definir la función {nombre}.")
return function
+1 -1
View File
@@ -8,7 +8,7 @@
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
Persistance's `PROVENANCE` expects.
Persistance's `PROCEDENCIA` expects.
"""
from dataclasses import asdict, dataclass
+2 -2
View File
@@ -292,12 +292,12 @@ def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]
"""The kit cohort build a version was trained on, and its attrition steps."""
if not armado_id:
return None, []
cohortes = import_module(f"persistance.{domain}").cohort_repository
cohortes = import_module(f"persistance.{domain}").cohorte_repository
armado = cohortes.get(int(armado_id))
if armado is None:
return None, []
exclusion = cohortes.cohortes.CohorteExclusion
pasos = cohortes.read(lambda sesion: sesion.exec(
pasos = cohortes.leer(lambda sesion: sesion.exec(
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
+5 -5
View File
@@ -67,7 +67,7 @@ def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path
def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
"""One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and,
with `cohorts` (the domain's `cohort_repository`), the kit's builds and whether each has its file. Without
with `cohorts` (the domain's `cohorte_repository`), the kit's builds and whether each has its file. Without
`cohorts` only files are read, never the database."""
rows = []
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
@@ -85,7 +85,7 @@ def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
without a file is described from `cohorts` (the domain's `cohort_repository`). `LookupError` if there's no such
without a file is described from `cohorts` (the domain's `cohorte_repository`). `LookupError` if there's no such
build."""
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
if path.exists():
@@ -173,10 +173,10 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
"""Writes a batch of risks for a kit build through the domain's `cohort_repository`: its `lote_id` and whether it's
"""Writes a batch of risks for a kit build through the domain's `cohorte_repository`: its `lote_id` and whether it's
new. The only write the pipelines make to the database; risks of anyone outside the build are refused."""
cohorts = importlib.import_module(f"persistance.{domain}").cohort_repository
return cohorts.save_batch(armado_id, provenance, outcome, rows)
cohorts = importlib.import_module(f"persistance.{domain}").cohorte_repository
return cohorts.guardar_lote(armado_id, provenance, outcome, rows)
def resolve_repository(domain: str, entity: str):
+1 -1
View File
@@ -8,7 +8,7 @@ import types
from hamilton import ad_hoc_utils, driver
from hamilton.function_modifiers import group, inject, parameterize, source, value
from persistance.edges.dbt import DbtQueryRepository
from persistance.aristas.dbt import DbtQueryRepository
from models.io.contracts import BuiltCohort, CohortQueries
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
+1 -1
View File
@@ -37,7 +37,7 @@ def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, ba
def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]:
"""The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's
`cohort_repository` and `timeline_repository`."""
`cohorte_repository` and `timeline_repository`."""
build_id = build_id if build_id is not None else cohorts.latest_build(url)
build = None if build_id is None else cohorts.build(build_id)
if build is None or build.url != url:
+5 -5
View File
@@ -2,7 +2,7 @@
Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows
which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories
are inputs too: whoever builds the driver passes a domain's `cohort_repository` and a
are inputs too: whoever builds the driver passes a domain's `cohorte_repository` and a
`timeline_repository` already bound to its query.
The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off
@@ -14,8 +14,8 @@ from dataclasses import fields
from datetime import datetime, timezone
import pandas as pd
from persistance.edges.gold import CohortBuild, CohortMember, CohortRepository
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from persistance.assets import Asset
MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember))
@@ -25,7 +25,7 @@ class UnknownBuild(LookupError):
"""The requested cohort build doesn't exist."""
def cohort_build(cohorte_armado: Asset, cohort_repository: CohortRepository, build_id: int) -> CohortBuild:
def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, build_id: int) -> CohortBuild:
"""The build's lineage: cohort, version, fingerprints and cut-offs."""
build = cohort_repository.build(build_id)
if build is None:
@@ -33,7 +33,7 @@ def cohort_build(cohorte_armado: Asset, cohort_repository: CohortRepository, bui
return build
def members(cohorte_miembro: Asset, cohort_repository: CohortRepository, cohort_build: CohortBuild) -> pd.DataFrame:
def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort_build: CohortBuild) -> pd.DataFrame:
"""One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`."""
return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS))
+1 -1
View File
@@ -6,7 +6,7 @@ the domain's `dbt_query_repository`.
import pandas as pd
from persistance.edges.dbt import DbtQueryRepository
from persistance.aristas.dbt import DbtQueryRepository
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
+4 -4
View File
@@ -2,7 +2,7 @@
run by a Hamilton driver built from that module alone, and their place in the asset graph.
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
`timeline_events` table; it returns the `CohortRepository` and a `TimelineRepository` bound to
`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
executes the requested nodes.
"""
@@ -22,8 +22,8 @@ from core.cacu.indicadores.models import (
)
from core.indicadores.cohortes import TablasCohorte
from hamilton import driver
from persistance.edges.gold import CohortRepository
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
from persistance.aristas.oro import CohorteRepository
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from persistance.assets import Asset, InvalidGraph, validate
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
from sqlalchemy.pool import StaticPool
@@ -102,7 +102,7 @@ def repositories():
session.connection().execute(insert(events), EVENTS)
session.commit()
factory = lambda: Session(engine) # noqa: E731
return CohortRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
def _run(repositories, build_id, nodes=("members", "timeline")):
+1 -1
View File
@@ -10,7 +10,7 @@ import json
from datetime import date
import pytest
from persistance.edges.dbt import DbtQueryRepository
from persistance.aristas.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session
+2 -2
View File
@@ -14,8 +14,8 @@ from types import SimpleNamespace
import pandas as pd
import pyarrow.parquet as pq
import pytest
from persistance.edges.gold import CohortBuild, CohortMember
from persistance.edges.dbt import DbtQueryRepository
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session