347 lines
16 KiB
Python
347 lines
16 KiB
Python
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates) and
|
|
their hashes, dbt's manifest, a domain's Persistance repositories, the batches of risks they store, and the cohort
|
|
sources a model trains and estimates on.
|
|
|
|
A cohort source (`KitBuild`, `CohortFile`) gives a build's long frame (`COHORT_SCHEMA`), its lineage (at least `url`
|
|
and `datos_as_of`, as text) and the reference a run, a version and an estimate keep of it (`cohort.url`,
|
|
`cohort.source`, `cohort.build`), so the dataflow doesn't know where the rows came from. `KitBuild` reads a kit build
|
|
now from the domain's database (its members, and their timeline up to its clinical cut-off and, when the build has
|
|
one, its load cut-off `conocida_hasta`; the lineage records when it was read) and writes nothing; reading it again later may give other rows if the
|
|
timeline changed. `CohortFile` reads an exported file, kit's or dbt's, and its reference adds the file's hash.
|
|
|
|
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 dataclasses import dataclass, field
|
|
from datetime import date, datetime, timezone
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
from typing import Any, Protocol
|
|
|
|
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)
|
|
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
|
|
|
|
|
|
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 `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)):
|
|
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 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 `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():
|
|
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 `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}").cohorte_repository
|
|
return cohorts.guardar_lote(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)
|
|
|
|
|
|
def file_sha256(*paths: str | Path) -> str:
|
|
"""The hash of these files' bytes, in this order."""
|
|
digest = hashlib.sha256()
|
|
for path in paths:
|
|
digest.update(Path(path).read_bytes())
|
|
return digest.hexdigest()
|
|
|
|
|
|
def table_sha256(table: pa.Table) -> str:
|
|
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
|
|
sink = pa.BufferOutputStream()
|
|
table = table.replace_schema_metadata(None)
|
|
with pa.ipc.new_stream(sink, table.schema) as stream:
|
|
stream.write_table(table)
|
|
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
|
|
|
|
|
|
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
|
|
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
|
|
`dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
|
|
build, numbered by its `armado_id`."""
|
|
source = "dbt" if metadata.get("producer") == "dbt" else "kit"
|
|
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
|
|
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
|
|
COHORT_FILE_TAG: file_sha256}
|
|
|
|
|
|
def require_match(recorded: dict, expected: dict, what: str) -> None:
|
|
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
|
|
if not matches(recorded, expected):
|
|
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
|
|
|
|
|
|
class CohortSource(Protocol):
|
|
armado_id: int | None # the kit build it is, if any (ML-03)
|
|
|
|
def frame(self) -> pd.DataFrame: ...
|
|
|
|
def lineage(self) -> dict[str, str]: ...
|
|
|
|
def reference(self) -> dict[str, str]: ...
|
|
|
|
|
|
@dataclass
|
|
class KitBuild:
|
|
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
|
|
`cohorte_repository` and `timeline_repository`; tests pass stand-ins."""
|
|
|
|
domain: str
|
|
build_id: int
|
|
cohorts: Any = None
|
|
timeline: Any = None
|
|
_build: Any = field(default=None, init=False, repr=False)
|
|
|
|
def __post_init__(self):
|
|
if self.cohorts is None or self.timeline is None:
|
|
repositories = import_module(f"persistance.{self.domain}")
|
|
self.cohorts = self.cohorts or repositories.cohorte_repository
|
|
self.timeline = self.timeline or repositories.timeline_repository
|
|
|
|
@property
|
|
def armado_id(self) -> int:
|
|
return self.build.armado_id
|
|
|
|
@property
|
|
def build(self):
|
|
if self._build is None:
|
|
self._build = self.cohorts.build(self.build_id)
|
|
if self._build is None:
|
|
raise LookupError(f"no kit build {self.build_id} in {self.domain}")
|
|
return self._build
|
|
|
|
def known_until(self) -> datetime | None:
|
|
"""The build's load cut-off, if it has one; without it everything loaded so far is read."""
|
|
return self.build.conocida_hasta
|
|
|
|
def frame(self) -> pd.DataFrame:
|
|
from models.steps.cohort_file import cohort_events
|
|
|
|
members = self.cohorts.members(self.build_id)
|
|
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
|
|
rows = self.timeline.read(patients=population["pac_id"].tolist(), until=self.build.datos_as_of,
|
|
known_until=self.known_until())
|
|
return cohort_events(rows, population, self.build.datos_as_of)
|
|
|
|
def lineage(self) -> dict[str, str]:
|
|
build = self.build
|
|
return {"url": build.url, "version": build.version, "armado_id": str(build.armado_id), "producer": "kit",
|
|
"datos_as_of": build.datos_as_of.isoformat(), "n_members": str(build.n_miembros),
|
|
"known_until": self.known_until().isoformat() if self.known_until() else "",
|
|
"read_at": datetime.now(timezone.utc).isoformat()}
|
|
|
|
def reference(self) -> dict[str, str]:
|
|
return {COHORT_URL_TAG: self.build.url, COHORT_SOURCE_TAG: "kit", COHORT_BUILD_TAG: str(self.build_id)}
|
|
|
|
|
|
@dataclass
|
|
class CohortFile:
|
|
"""An exported build's Parquet file."""
|
|
|
|
path: str | Path
|
|
|
|
@property
|
|
def armado_id(self) -> int | None:
|
|
lineage = self.lineage()
|
|
return int(lineage["armado_id"]) if lineage.get("producer") != "dbt" and "armado_id" in lineage else None
|
|
|
|
def frame(self) -> pd.DataFrame:
|
|
return read_cohort(self.path)
|
|
|
|
def lineage(self) -> dict[str, str]:
|
|
return read_metadata(self.path)
|
|
|
|
def reference(self) -> dict[str, str]:
|
|
return cohort_reference(self.lineage(), file_sha256(self.path))
|