"""The steps from a study population and the timeline to a build's table, with its lineage.""" from datetime import date, datetime, timezone import pandas as pd import pyarrow as pa from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame from models.io.storage import table_sha256 ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"] def cohort_events(timeline_rows: list[dict], study_population: pd.DataFrame, cutoff: date) -> pd.DataFrame: """The members' events up to `cutoff`, in the file's order. A member without events stops the build.""" members = study_population[["pac_id", "fecha_indice"]] frame = pd.DataFrame(timeline_rows, columns=TIMELINE).merge(members, on="pac_id") frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True) frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"]) frame = frame[frame["fecha"] <= cutoff] if missing := len(members) - frame["pac_id"].nunique(): raise ValueError(f"{missing} members have no events in the timeline") return frame.sort_values(ROW_ORDER, kind="stable")[SCHEMA.names].reset_index(drop=True) def content_sha256(cohort_events: pd.DataFrame) -> str: """The hash of the rows alone, so the same content gives the same hash whenever it's built.""" return table_sha256(pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)) def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str) -> dict: return {**base_lineage, "n_members": cohort_events["pac_id"].nunique(), "content_sha256": content_sha256, "built_at": datetime.now(timezone.utc).isoformat()} def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table: """The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written.""" check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}") table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False) return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})