241 lines
12 KiB
Python
241 lines
12 KiB
Python
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
|
|
manifest, a domain's Persistance repositories, and the batches of risks they store.
|
|
|
|
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
|
|
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
|
|
repository is used, so a model folder reading its cohort file never loads the database layer.
|
|
"""
|
|
|
|
import hashlib
|
|
import importlib
|
|
import json
|
|
import os
|
|
import tempfile
|
|
from datetime import date
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
import pyarrow.parquet as pq
|
|
from sqlalchemy.engine import make_url
|
|
|
|
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
|
|
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
|
|
|
|
|
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).parent / "cohorts"
|
|
|
|
|
|
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
|
domain, cohort = url.split("/", 1)
|
|
return root / domain / cohort / f"{armado_id}.parquet"
|
|
|
|
|
|
def dbt_build_path(root: Path, url: str, number: int) -> Path:
|
|
return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet"
|
|
|
|
|
|
def _numbers(folder: Path) -> list[int]:
|
|
return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit())
|
|
|
|
|
|
def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None:
|
|
"""The highest-numbered build of dbt's rules, or `None` if there's none."""
|
|
numbers = _numbers(dbt_build_path(root, url, 0).parent)
|
|
return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None
|
|
|
|
|
|
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
|
"""The file of that build, or of the cohort's latest build that has a file."""
|
|
if armado_id is None:
|
|
builds = _numbers(cohort_path(root, url, 0).parent)
|
|
if not builds:
|
|
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
|
armado_id = max(builds)
|
|
path = cohort_path(root, url, armado_id)
|
|
if not path.exists():
|
|
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
|
return 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
|
|
`cohorts` only files are read, never the database."""
|
|
rows = []
|
|
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
|
|
path = dbt_build_path(root, url, number)
|
|
lineage = read_metadata(path)
|
|
rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
|
"n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)})
|
|
for build in (cohorts.builds(url) if cohorts is not None else []):
|
|
path = cohort_path(root, url, build.armado_id)
|
|
rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(),
|
|
"n_members": str(build.n_miembros), "created": build.armado_en.isoformat(),
|
|
"file": str(path) if path.exists() else None})
|
|
return rows
|
|
|
|
|
|
def exported_builds(root: Path, domain: str) -> list[dict]:
|
|
"""Every build of the domain's cohorts that has its file, newest first within each cohort and source, read from
|
|
the files alone: `url`, `source`, `build`, `datos_as_of`, `n_members`."""
|
|
rows = []
|
|
folder = root / domain
|
|
for cohort in sorted(p for p in folder.iterdir() if p.is_dir()) if folder.is_dir() else []:
|
|
url = f"{domain}/{cohort.name}"
|
|
for source, place in (("kit", cohort), ("dbt", cohort / "dbt")):
|
|
for number in reversed(_numbers(place)):
|
|
lineage = read_metadata(place / f"{number}.parquet")
|
|
rows.append({"url": url, "source": source, "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
|
"n_members": lineage.get("n_members") or lineage.get("n_miembros")})
|
|
return rows
|
|
|
|
|
|
def build_file(root: Path, url: str, source: str, build: int) -> Path:
|
|
"""The file of one exported build; `LookupError` when it isn't there."""
|
|
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
|
if source not in ("kit", "dbt") or not path.exists():
|
|
raise LookupError(f"no hay archivo de la construcción {source} {build} de {url}")
|
|
return path
|
|
|
|
|
|
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
|
|
build."""
|
|
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
|
if path.exists():
|
|
lineage = read_metadata(path)
|
|
for key in ("parametros", "rules", "attrition"):
|
|
if lineage.get(key):
|
|
lineage[key] = json.loads(lineage[key])
|
|
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage}
|
|
stored = cohorts.build(build) if source == "kit" and cohorts is not None else None
|
|
if stored is None or stored.url != url:
|
|
raise LookupError(f"no {source} build {build} of {url}")
|
|
return {"source": "kit", "build": build, "file": None, "file_sha256": None,
|
|
"lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(),
|
|
"n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}}
|
|
|
|
|
|
def read_cohort(path: str | Path) -> pd.DataFrame:
|
|
"""The build's rows, after checking the file's schema without reading them."""
|
|
schema = pq.read_schema(path)
|
|
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
|
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
|
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
|
|
|
|
|
|
def write_once(table: pa.Table, path: Path) -> None:
|
|
"""The file appears complete or not at all: written beside it, then renamed."""
|
|
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 read_metadata(path: str | Path) -> dict[str, str]:
|
|
"""A Parquet file's own metadata, without reading any rows."""
|
|
metadata = pq.read_metadata(path).metadata or {}
|
|
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
|
|
|
|
|
def _one(nodes: list[dict], kind: str, url: str) -> dict:
|
|
found = [node for node in nodes if node["config"]["meta"]["kind"] == kind]
|
|
if len(found) != 1:
|
|
raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}")
|
|
return found[0]
|
|
|
|
|
|
def _compiled(node: dict) -> str:
|
|
if not node.get("compiled_code"):
|
|
raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`")
|
|
return node["compiled_code"]
|
|
|
|
|
|
def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
|
"""The cohort's compiled queries, with its exclusions in their `order`.
|
|
|
|
An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every
|
|
rule's excluded members, and the study population, independent of the order.
|
|
"""
|
|
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
|
nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url]
|
|
if not nodes:
|
|
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
|
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
|
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]
|
|
if len(set(orders)) != len(orders):
|
|
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
|
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
|
for node in exclusions:
|
|
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)}")
|
|
meta = population["config"]["meta"]
|
|
if "cutoff" not in meta:
|
|
raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta")
|
|
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
|
for node in exclusions)
|
|
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
|
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
|
|
|
|
|
|
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
|
|
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)
|
|
|
|
|
|
def resolve_repository(domain: str, entity: str):
|
|
"""`entity` is the repository's name in `persistance.<domain>` without
|
|
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
|
module = importlib.import_module(f"persistance.{domain}")
|
|
try:
|
|
return getattr(module, f"{entity}_repository")
|
|
except AttributeError as exc:
|
|
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
|
|
|
|
|
class ReadOnlyRepository:
|
|
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
|
Write methods raise `PermissionError` so a training routine cannot
|
|
modify clinical data."""
|
|
|
|
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
|
|
|
def __init__(self, repository):
|
|
self._repository = repository
|
|
self.model = repository.model
|
|
|
|
def get(self, id_):
|
|
return self._repository.get(id_)
|
|
|
|
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
|
return self._repository.list(limit=limit, offset=offset, **filters)
|
|
|
|
def count(self, **filters) -> int:
|
|
return self._repository.count(**filters)
|
|
|
|
def __getattr__(self, name: str):
|
|
if name in self._WRITE_METHODS:
|
|
raise PermissionError(
|
|
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
|
)
|
|
raise AttributeError(name)
|