172 lines
7.4 KiB
Python
172 lines
7.4 KiB
Python
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
|
|
manifest, and a domain's Persistance repositories.
|
|
|
|
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 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_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
|
|
CohortQueries, ExclusionRule)
|
|
|
|
|
|
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 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 pd.read_parquet(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 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)
|