Follow Persistance's English names
This commit is contained in:
+4
-4
@@ -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."""
|
"""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 importlib import import_module
|
||||||
|
|
||||||
from persistance.aristas.dbt import DbtRelationError
|
from persistance.edges.dbt import DbtRelationError
|
||||||
from persistance.settings import settings
|
from persistance.settings import settings
|
||||||
from sqlalchemy.exc import DBAPIError
|
from sqlalchemy.exc import DBAPIError
|
||||||
|
|
||||||
@@ -244,7 +244,7 @@ def _cohort_export(args: argparse.Namespace) -> int:
|
|||||||
queries = read_queries(args.manifest, url)
|
queries = read_queries(args.manifest, url)
|
||||||
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
|
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
|
||||||
else:
|
else:
|
||||||
path, outcome = export_kit_build(repositories.cohorte_repository, timeline, root, args.domain, url, args.build)
|
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
|
||||||
except PermissionError as error:
|
except PermissionError as error:
|
||||||
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
@@ -273,7 +273,7 @@ def _cohort_list(args: argparse.Namespace) -> int:
|
|||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
print(error, file=sys.stderr)
|
print(error, file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohorte_repository
|
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohort_repository
|
||||||
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
|
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
|
||||||
if not rows:
|
if not rows:
|
||||||
print(f"{url}: no builds", file=sys.stderr)
|
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}"
|
url = f"{args.domain}/{args.cohort}"
|
||||||
try:
|
try:
|
||||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||||
cohorts = import_module(f"persistance.{args.domain}").cohorte_repository if args.source == "kit" else None
|
cohorts = import_module(f"persistance.{args.domain}").cohort_repository if args.source == "kit" else None
|
||||||
described = describe_build(root, url, args.source, args.build, cohorts)
|
described = describe_build(root, url, args.source, args.build, cohorts)
|
||||||
except (ValueError, LookupError) as error:
|
except (ValueError, LookupError) as error:
|
||||||
print(error, file=sys.stderr)
|
print(error, file=sys.stderr)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"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)",
|
"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)",
|
||||||
"id": "cacu-cin2-01-04"
|
"id": "cacu-cin2-01-04"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"outputs": [],
|
"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 = 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\"",
|
"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\"",
|
||||||
"id": "cacu-cin2-01-06"
|
"id": "cacu-cin2-01-06"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"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\"]]",
|
"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\"]]",
|
||||||
"id": "cacu-cin2-01-07"
|
"id": "cacu-cin2-01-07"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -61,7 +61,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"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)",
|
"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)",
|
||||||
"id": "cacu-cin2-01-08"
|
"id": "cacu-cin2-01-08"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
- 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
|
`(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
|
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
||||||
Persistance's `PROCEDENCIA` expects.
|
Persistance's `PROVENANCE` expects.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import asdict, dataclass
|
from dataclasses import asdict, dataclass
|
||||||
|
|||||||
@@ -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."""
|
"""The kit cohort build a version was trained on, and its attrition steps."""
|
||||||
if not armado_id:
|
if not armado_id:
|
||||||
return None, []
|
return None, []
|
||||||
cohortes = import_module(f"persistance.{domain}").cohorte_repository
|
cohortes = import_module(f"persistance.{domain}").cohort_repository
|
||||||
armado = cohortes.get(int(armado_id))
|
armado = cohortes.get(int(armado_id))
|
||||||
if armado is None:
|
if armado is None:
|
||||||
return None, []
|
return None, []
|
||||||
exclusion = cohortes.cohortes.CohorteExclusion
|
exclusion = cohortes.cohortes.CohorteExclusion
|
||||||
pasos = cohortes.leer(lambda sesion: sesion.exec(
|
pasos = cohortes.read(lambda sesion: sesion.exec(
|
||||||
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
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,
|
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(),
|
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
||||||
|
|||||||
@@ -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]:
|
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,
|
"""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
|
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."""
|
`cohorts` only files are read, never the database."""
|
||||||
rows = []
|
rows = []
|
||||||
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
|
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:
|
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
|
"""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
|
without a file is described from `cohorts` (the domain's `cohort_repository`). `LookupError` if there's no such
|
||||||
build."""
|
build."""
|
||||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||||
if path.exists():
|
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]:
|
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
|
"""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."""
|
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
|
cohorts = importlib.import_module(f"persistance.{domain}").cohort_repository
|
||||||
return cohorts.guardar_lote(armado_id, provenance, outcome, rows)
|
return cohorts.save_batch(armado_id, provenance, outcome, rows)
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(domain: str, entity: str):
|
def resolve_repository(domain: str, entity: str):
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import types
|
|||||||
from hamilton import ad_hoc_utils, driver
|
from hamilton import ad_hoc_utils, driver
|
||||||
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
||||||
|
|
||||||
from persistance.aristas.dbt import DbtQueryRepository
|
from persistance.edges.dbt import DbtQueryRepository
|
||||||
|
|
||||||
from models.io.contracts import BuiltCohort, CohortQueries
|
from models.io.contracts import BuiltCohort, CohortQueries
|
||||||
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
||||||
|
|||||||
@@ -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]:
|
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
|
"""The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's
|
||||||
`cohorte_repository` and `timeline_repository`."""
|
`cohort_repository` and `timeline_repository`."""
|
||||||
build_id = build_id if build_id is not None else cohorts.latest_build(url)
|
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)
|
build = None if build_id is None else cohorts.build(build_id)
|
||||||
if build is None or build.url != url:
|
if build is None or build.url != url:
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows
|
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
|
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 `cohorte_repository` and a
|
are inputs too: whoever builds the driver passes a domain's `cohort_repository` and a
|
||||||
`timeline_repository` already bound to its query.
|
`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
|
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
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository
|
from persistance.edges.gold import CohortBuild, CohortMember, CohortRepository
|
||||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
|
||||||
from persistance.assets import Asset
|
from persistance.assets import Asset
|
||||||
|
|
||||||
MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember))
|
MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember))
|
||||||
@@ -25,7 +25,7 @@ class UnknownBuild(LookupError):
|
|||||||
"""The requested cohort build doesn't exist."""
|
"""The requested cohort build doesn't exist."""
|
||||||
|
|
||||||
|
|
||||||
def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, build_id: int) -> CohortBuild:
|
def cohort_build(cohorte_armado: Asset, cohort_repository: CohortRepository, build_id: int) -> CohortBuild:
|
||||||
"""The build's lineage: cohort, version, fingerprints and cut-offs."""
|
"""The build's lineage: cohort, version, fingerprints and cut-offs."""
|
||||||
build = cohort_repository.build(build_id)
|
build = cohort_repository.build(build_id)
|
||||||
if build is None:
|
if build is None:
|
||||||
@@ -33,7 +33,7 @@ def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, bu
|
|||||||
return build
|
return build
|
||||||
|
|
||||||
|
|
||||||
def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort_build: CohortBuild) -> pd.DataFrame:
|
def members(cohorte_miembro: Asset, cohort_repository: CohortRepository, cohort_build: CohortBuild) -> pd.DataFrame:
|
||||||
"""One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`."""
|
"""One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`."""
|
||||||
return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS))
|
return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS))
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ the domain's `dbt_query_repository`.
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from persistance.aristas.dbt import DbtQueryRepository
|
from persistance.edges.dbt import DbtQueryRepository
|
||||||
|
|
||||||
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
run by a Hamilton driver built from that module alone, and their place in the asset graph.
|
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
|
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
|
||||||
`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to
|
`timeline_events` table; it returns the `CohortRepository` and a `TimelineRepository` bound to
|
||||||
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
|
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
|
||||||
executes the requested nodes.
|
executes the requested nodes.
|
||||||
"""
|
"""
|
||||||
@@ -22,8 +22,8 @@ from core.cacu.indicadores.models import (
|
|||||||
)
|
)
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
from hamilton import driver
|
from hamilton import driver
|
||||||
from persistance.aristas.oro import CohorteRepository
|
from persistance.edges.gold import CohortRepository
|
||||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
|
||||||
from persistance.assets import Asset, InvalidGraph, validate
|
from persistance.assets import Asset, InvalidGraph, validate
|
||||||
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
|
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
|
||||||
from sqlalchemy.pool import StaticPool
|
from sqlalchemy.pool import StaticPool
|
||||||
@@ -102,7 +102,7 @@ def repositories():
|
|||||||
session.connection().execute(insert(events), EVENTS)
|
session.connection().execute(insert(events), EVENTS)
|
||||||
session.commit()
|
session.commit()
|
||||||
factory = lambda: Session(engine) # noqa: E731
|
factory = lambda: Session(engine) # noqa: E731
|
||||||
return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
|
return CohortRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
|
||||||
|
|
||||||
|
|
||||||
def _run(repositories, build_id, nodes=("members", "timeline")):
|
def _run(repositories, build_id, nodes=("members", "timeline")):
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import json
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from persistance.aristas.dbt import DbtQueryRepository
|
from persistance.edges.dbt import DbtQueryRepository
|
||||||
from sqlalchemy import create_engine, text
|
from sqlalchemy import create_engine, text
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ from types import SimpleNamespace
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pyarrow.parquet as pq
|
import pyarrow.parquet as pq
|
||||||
import pytest
|
import pytest
|
||||||
from persistance.aristas.oro import CohortBuild, CohortMember
|
from persistance.edges.gold import CohortBuild, CohortMember
|
||||||
from persistance.aristas.dbt import DbtQueryRepository
|
from persistance.edges.dbt import DbtQueryRepository
|
||||||
from sqlalchemy import create_engine, text
|
from sqlalchemy import create_engine, text
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user