6fbf573999
dev's 1b45bc6 (governance requirements, sandboxed notebooks) was written on the per-scenario driver that this branch
replaced with models.dags; it is carried over in that shape:
- cin2_logistic: the five ML-01a routines (sampling, missing_data, analytic_method, class_balance, output_confidence)
and `routines` are nodes of the scenario's dataflow, on its node names (windowed_outcomes, train_set, test_set,
fitted_pipeline, test_probabilities); `calibration_bins` is a config input with a default.
- io/adapters, dags/training: the saver writes each routine with TrainingRun.log_routine before logging the model;
the driver hands it `routines` when the dataflow has that node. Without it a scenario still trains, but the registry
won't promote it (ROUTINE_KINDS).
- io/tracking: dev's log_routine, run_files and run_file next to this branch's log_model (scikit-learn or pyfunc,
pinned requirements).
- reports/rendering: dev's Quarto and Jupyter renderers (io/rendering.py, followed as a rename) with this branch's
notebook hash; notebook_jobs and experiment import it from there, and cohort_reference and file_sha256 from
io/storage.
- cin2_logistic/train.py: a delegate to models.dags.training for callers of the old driver.
- Persistance's English names from dev: persistance.edges.gold, cohort_repository.
Tests: 219 passed against the monorepo's dev Persistance, Extraction and Core (OCR with tesseract deselected).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
75 lines
4.2 KiB
Python
75 lines
4.2 KiB
Python
"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage.
|
|
|
|
The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them:
|
|
|
|
- `export_kit_build`: a build the kit stored, written once to `<armado_id>.parquet`;
|
|
- `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is
|
|
reused; otherwise the next number is written.
|
|
|
|
The timeline comes from the domain's `timeline_repository` (dbt's view `<domain>_linea_de_tiempo`), cut at the
|
|
build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the
|
|
database.
|
|
"""
|
|
|
|
import json
|
|
from datetime import date
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
from hamilton import ad_hoc_utils, driver
|
|
|
|
from models.io.contracts import CohortQueries
|
|
from models.io.lineage import matches
|
|
from models.io.storage import (cohort_path, dbt_build_path, latest_dbt_build, read_metadata, require_match,
|
|
write_once)
|
|
from models.pipelines.cohort_build import build_cohort
|
|
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
|
|
|
|
NODES = [cohort_events, content_sha256, lineage, cohort_table]
|
|
|
|
|
|
def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]:
|
|
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build()
|
|
inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage}
|
|
results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs)
|
|
return results["cohort_table"], results["content_sha256"]
|
|
|
|
|
|
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
|
|
`cohort_repository` and `timeline_repository`."""
|
|
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)
|
|
if build is None or build.url != url:
|
|
raise LookupError(f"no such build of {url}: {build_id}")
|
|
path = cohort_path(root, url, build.armado_id)
|
|
if path.exists():
|
|
require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path))
|
|
return path, "reused"
|
|
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)],
|
|
columns=["pac_id", "fecha_indice"])
|
|
base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit",
|
|
"parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()}
|
|
table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base)
|
|
write_once(table, path)
|
|
return path, "exported"
|
|
|
|
|
|
def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]:
|
|
"""Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and
|
|
`timeline` are the domain's `dbt_query_repository` and `timeline_repository`."""
|
|
built = build_cohort(queries, dbt_queries)
|
|
latest = latest_dbt_build(root, queries.url)
|
|
number = latest[0] + 1 if latest else 1
|
|
base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt",
|
|
"parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(),
|
|
"rules": json.dumps([rule.name for rule in queries.rules]),
|
|
"attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")}
|
|
table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base)
|
|
if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}):
|
|
return latest[1], "reused"
|
|
path = dbt_build_path(root, queries.url, number)
|
|
write_once(table, path)
|
|
return path, "exported"
|