174 lines
8.6 KiB
Python
174 lines
8.6 KiB
Python
"""Export a kit cohort build to its Parquet file, once.
|
|
|
|
uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]
|
|
|
|
One file per build, `<data>/cohorts/<domain>/<cohort>/<armado_id>.parquet`, where `<data>` is the folder of the
|
|
domain's database and `COHORTS_DIR` replaces `<data>/cohorts`. Long format: one row per member and event, with
|
|
the member's index date on every row and the build's lineage in the file's metadata.
|
|
|
|
The timeline comes from the dbt model `<domain>_linea_de_tiempo`. dbt only compiles it to SQL, which runs here as
|
|
a subquery, so nothing is stored in the database and it can be opened read-only (on SQLite, dbt doesn't open it at
|
|
all). In a read-only folder, with nothing writing to the file, use
|
|
`CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database.
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from collections.abc import Callable, Iterable
|
|
from datetime import datetime, timezone
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
import pyarrow.parquet as pq
|
|
from persistance.aristas.oro import CohortBuild, CohortMember
|
|
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
|
from persistance.settings import settings
|
|
from sqlalchemy import column, select, text
|
|
from sqlalchemy.engine import make_url
|
|
|
|
from models.io.cohorts import SCHEMA
|
|
|
|
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
|
DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
|
|
DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation"
|
|
|
|
|
|
def cohorts_root(database_url: str) -> Path:
|
|
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
|
if configured := os.environ.get("COHORTS_DIR"):
|
|
return Path(configured)
|
|
url = make_url(database_url)
|
|
if url.get_backend_name() != "sqlite" or not url.database:
|
|
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
|
return Path(url.database.removeprefix("file:")).parent / "cohorts"
|
|
|
|
|
|
def cohort_file(build: CohortBuild, root: Path) -> Path:
|
|
domain, cohort = build.url.split("/", 1)
|
|
return root / domain / cohort / f"{build.armado_id}.parquet"
|
|
|
|
|
|
def lineage_of(path: Path) -> dict[str, str]:
|
|
"""The lineage in the file's metadata, without reading any rows."""
|
|
metadata = pq.read_metadata(path).metadata
|
|
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
|
|
|
|
|
def compile_timeline(domain: str, database_url: str, transformation: Path) -> str:
|
|
"""The SQL of the domain's timeline model for this engine. On SQLite, dbt connects to an empty throwaway file."""
|
|
backend = make_url(database_url).get_backend_name()
|
|
model = f"{domain}_linea_de_tiempo"
|
|
with tempfile.TemporaryDirectory(prefix="dbt-compile-") as workdir:
|
|
work = Path(workdir)
|
|
(work / "schemas").mkdir()
|
|
env = {**os.environ, "DBT_SCHEMA_DIR": str(work / "schemas")}
|
|
if backend == "sqlite":
|
|
env[f"{domain.upper()}_DB_PATH"] = str(work / "empty.db")
|
|
subprocess.run(
|
|
["uv", "run", "--no-sync", "dbt", "--quiet", "compile", "--profiles-dir", ".", "--profile", domain,
|
|
"--target", DBT_TARGETS[backend], "--select", model, "--target-path", str(work / "target"),
|
|
"--log-path", str(work / "logs")],
|
|
cwd=transformation, env=env, check=True, capture_output=True, text=True)
|
|
compiled = next((work / "target" / "compiled").rglob(f"{model}.sql"))
|
|
return compiled.read_text().strip().rstrip(";")
|
|
|
|
|
|
def read_timeline(repository: TimelineRepository, sql: str) -> list[dict]:
|
|
"""Every event of the domain, with `sql` as a subquery. The cut-offs are applied in `build_table`."""
|
|
linea = text(sql.replace(":", r"\:")).columns(*(column(name) for name in TIMELINE_COLUMNS)).subquery("linea")
|
|
query = select(*(linea.c[name] for name in TIMELINE_COLUMNS))
|
|
return repository.with_query(lambda **_: query).read()
|
|
|
|
|
|
def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str,
|
|
parametros: str | None) -> pa.Table:
|
|
"""The members' events up to `datos_as_of` and loaded by `conocida_hasta`, in the file's order, with the lineage."""
|
|
members = list(members)
|
|
index_dates = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
|
|
frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(index_dates, on="pac_id")
|
|
frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date
|
|
frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True)
|
|
frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"])
|
|
frame = frame[frame["fecha"] <= build.datos_as_of]
|
|
if build.conocida_hasta is not None:
|
|
known_until = pd.Timestamp(build.conocida_hasta)
|
|
frame = frame[frame["conocida_en"] <= (known_until.tz_localize("UTC") if known_until.tzinfo is None else known_until)]
|
|
missing = len(members) - frame["pac_id"].nunique()
|
|
if missing:
|
|
raise ValueError(f"{missing} members of build {build.armado_id} have no events in the timeline")
|
|
frame = frame.sort_values(ROW_ORDER, kind="stable")
|
|
lineage = {
|
|
"url": build.url, "version": build.version, "armado_id": build.armado_id, "domain": domain,
|
|
"parametros": parametros or "{}", "datos_as_of": build.datos_as_of.isoformat(),
|
|
"conocida_hasta": build.conocida_hasta.isoformat() if build.conocida_hasta else "",
|
|
"n_members": len(members), "producer": "kit", "built_at": datetime.now(timezone.utc).isoformat(),
|
|
}
|
|
table = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)
|
|
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
|
|
|
|
|
def write_once(table: pa.Table, path: Path) -> None:
|
|
"""The file appears complete or not at all."""
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
|
|
partial = Path(handle.name)
|
|
try:
|
|
pq.write_table(table, partial)
|
|
partial.replace(path)
|
|
finally:
|
|
partial.unlink(missing_ok=True)
|
|
|
|
|
|
def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]:
|
|
"""The build's file: reused if it's already there and belongs to the build, written once if not."""
|
|
path = cohort_file(build, root)
|
|
if path.exists():
|
|
lineage = lineage_of(path)
|
|
if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros):
|
|
raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}")
|
|
return path, "reused"
|
|
write_once(make_table(), path)
|
|
return path, "exported"
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="Export a kit cohort build to its Parquet file, once.")
|
|
parser.add_argument("--domain", required=True, choices=["cacu", "cama", "tea"])
|
|
parser.add_argument("--cohort", required=True, help="the cohort without its domain, e.g. cohorte_vigilancia")
|
|
parser.add_argument("--build", type=int, help="the build's armado_id; the cohort's latest by default")
|
|
args = parser.parse_args(argv)
|
|
|
|
repositories = import_module(f"persistance.{args.domain}")
|
|
cohorts, timeline = repositories.cohorte_repository, repositories.timeline_repository
|
|
url = f"{args.domain}/{args.cohort}"
|
|
build_id = args.build if args.build 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:
|
|
print(f"no such build of {url}: {build_id}", file=sys.stderr)
|
|
return 1
|
|
|
|
database_url = getattr(settings, f"{args.domain}_database_url")
|
|
transformation = Path(os.environ.get("TRANSFORMATION_DIR", DEFAULT_TRANSFORMATION))
|
|
|
|
def make_table() -> pa.Table:
|
|
rows = read_timeline(timeline, compile_timeline(args.domain, database_url, transformation))
|
|
return build_table(rows, cohorts.members(build.armado_id), build, domain=args.domain,
|
|
parametros=cohorts.get(build.armado_id).parametros)
|
|
|
|
try:
|
|
path, outcome = ensure(build, cohorts_root(database_url), make_table)
|
|
except PermissionError as error:
|
|
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
|
return 1
|
|
print(f"{outcome}: {path}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|