acc8c371bc
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the cohort's events, fits the interval survival, writes the five routines and publishes the population curves (analisis/curvas.json) with the version. An estimate may carry the model's own index date.
215 lines
12 KiB
Python
215 lines
12 KiB
Python
"""Each scenario's index and its rules, over a cohort's long frame (`COHORT_SCHEMA`), usually `cacu/cohorte_total`.
|
|
|
|
A cohort gives every patient's events; a scenario says from when it predicts (the index) and who is out given that
|
|
index. `[config.index]` of its `model.toml` names the kind and its rules. A scenario that lists this module gets its
|
|
source cohort as `source_cohort`; the node `cohort` gives that frame re-indexed (`fecha_indice` is the scenario's)
|
|
with only the members left, and `index_attrition` how many each step leaves. The recruitment window is the source
|
|
cohort's (its build's parameters), unless the config sets one. The rules are dbt's (`Transformation/models/cacu/cohorts/`, `macros/cacu_post_colposcopy.sql`), in the same
|
|
order and with the same names, so the two can be compared before either is retired.
|
|
|
|
Kinds:
|
|
|
|
- `primera_citologia` (surveillance): the first cytology sample, if it falls in the window; out: a biopsy with the
|
|
outcome before the index (`prior_event`), an index sample with no cytology or HPV result (`no_index_result`).
|
|
- `post_colposcopia` (visit `visita`): the first colposcopy's episode, its result known at the last report of the
|
|
biopsies ordered that day (PROVISIONAL: without a biopsy order it is below CIN2, which assumes the colposcopic
|
|
impression misses no CIN2+); index at that result (`visita = 0`) or at the k-th cytology sample after it, before any
|
|
later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`,
|
|
`histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1).
|
|
|
|
- `primera_biopsia_invasora` (CaMa survival): the first biopsy report graded in `event_grades` (`CARCINOMA_INVASOR`),
|
|
if it falls in the window; out, in order: `sin_nacimiento` (no birth date, so no age), `defuncion_hasta_el_indice`
|
|
(a death on or before the index, which leaves no time to the event).
|
|
|
|
Every kind ends with `observacion_previa_insuficiente`: out if the days observed before the index are fewer than
|
|
`observacion_previa_minima_dias` (default 0, so nobody; owner, 2026-11-20). The data are left-truncated: a rule on
|
|
earlier events ("no CIN2+ before the index", "first colposcopy", the referral year) reads only what was recorded, so
|
|
"none before" means "none observed". The rules are kept as written; raising the threshold when the population starts
|
|
with enough history makes them valid without changing code. Observation starts, for now, at the patient's first
|
|
event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline).
|
|
|
|
A scenario without `[config.index]` keeps its cohort's own index.
|
|
"""
|
|
|
|
import json
|
|
from collections import defaultdict
|
|
from datetime import date
|
|
|
|
import pandas as pd
|
|
|
|
RESULT_TYPES = ("bethesda", "glandular", "vph")
|
|
POST_COLPOSCOPY_RULES = ("biopsia_sin_resultado", "cin2_hasta_el_indice", "antecedente_cacu", "histerectomia",
|
|
"tratamiento_previo", "sin_referencia", "sin_cotest")
|
|
|
|
|
|
def _key(e: dict) -> tuple:
|
|
return e["fuente_tabla"], e["fuente_id"]
|
|
|
|
|
|
def _in_window(fecha: date, index: dict) -> bool:
|
|
start, end = index.get("recruitment_start"), index.get("recruitment_end")
|
|
return (start is None or fecha >= date.fromisoformat(start)) and (end is None or fecha < date.fromisoformat(end))
|
|
|
|
|
|
def _results(events: list[dict], sample: dict) -> dict:
|
|
"""The sample's Bethesda, glandular and HPV codes (first non-null of each)."""
|
|
return {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and _key(e) == _key(sample)
|
|
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
|
|
|
|
|
|
def _first_cytology(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
|
|
"""The surveillance index and, per rule, whether it flags the patient."""
|
|
samples = sorted((e for e in events if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
|
|
if not samples or not _in_window(samples[0]["fecha"], index):
|
|
return None, []
|
|
sample, grades = samples[0], set(index["event_grades"])
|
|
found = _results(events, sample)
|
|
return sample["fecha"], [
|
|
("prior_event", any(e["tipo"] == "biopsia" and e["fecha"] < sample["fecha"] and e["valor_codigo"] in grades
|
|
for e in events)),
|
|
("no_index_result", all(v is None for v in found.values())),
|
|
]
|
|
|
|
|
|
def _colposcopy_episode(events: list[dict]) -> dict | None:
|
|
"""The first colposcopy, when its result is known and how many of that day's biopsy orders have no report."""
|
|
colposcopies = sorted((e for e in events if e["tipo"] == "colposcopia"),
|
|
key=lambda e: (e["fecha"], e["fuente_tabla"], e["fuente_id"]))
|
|
if not colposcopies:
|
|
return None
|
|
first = colposcopies[0]
|
|
orders = {_key(e) for e in events if e["tipo"] == "orden_biopsia" and e["fecha"] == first["fecha"]}
|
|
reports = [e for e in events if e["tipo"] == "biopsia" and _key(e) in orders]
|
|
return {"colposcopy": first, "result_date": max((e["fecha"] for e in reports), default=first["fecha"]),
|
|
"unreported_orders": len(orders - {_key(e) for e in reports})}
|
|
|
|
|
|
def _surveillance_visits(events: list[dict], episode: dict) -> list[dict]:
|
|
"""The cytology samples after the colposcopy's result is known, before any later colposcopy, in order."""
|
|
result = episode["result_date"]
|
|
closing = min((e["fecha"] for e in events if e["tipo"] == "colposcopia" and e["fecha"] > result), default=None)
|
|
return sorted((e for e in events if e["tipo"] == "citologia" and e["fecha"] > result
|
|
and (closing is None or e["fecha"] < closing)), key=lambda e: (e["fecha"], e["fuente_id"]))
|
|
|
|
|
|
def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
|
|
"""The index of visit `index["visita"]` and, per rule, whether it flags the patient."""
|
|
k = int(index["visita"])
|
|
episode = _colposcopy_episode(events)
|
|
if episode is None:
|
|
return None, []
|
|
if k == 0:
|
|
sample, fecha = None, episode["result_date"]
|
|
else:
|
|
visits = _surveillance_visits(events, episode)
|
|
if len(visits) < k:
|
|
return None, []
|
|
sample, fecha = visits[k - 1], visits[k - 1]["fecha"]
|
|
if not _in_window(fecha, index):
|
|
return None, []
|
|
grades, hysterectomy = set(index["event_grades"]), set(index["hysterectomy_cie"])
|
|
colposcopy, lookback = episode["colposcopy"]["fecha"], int(index["referral_lookback_days"])
|
|
|
|
def up_to(test):
|
|
return any(e["fecha"] <= fecha and test(e) for e in events)
|
|
|
|
flags = [
|
|
("biopsia_sin_resultado", episode["unreported_orders"] > 0),
|
|
("cin2_hasta_el_indice", up_to(lambda e: e["tipo"] == "biopsia" and e["valor_codigo"] in grades)),
|
|
("antecedente_cacu", up_to(lambda e: e["tipo"] == "antecedente")),
|
|
("histerectomia", up_to(lambda e: e["tipo"] == "nota_medica" and e["valor_codigo"] in hysterectomy)),
|
|
("tratamiento_previo", up_to(lambda e: e["tipo"] == "tratamiento")),
|
|
("sin_referencia", not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
|
|
and 0 <= (colposcopy - e["fecha"]).days <= lookback for e in events)),
|
|
]
|
|
if k >= 1:
|
|
found = _results(events, sample)
|
|
flags.append(("sin_cotest", found["vph"] is None or (found["bethesda"] is None and found["glandular"] is None)))
|
|
return fecha, flags
|
|
|
|
|
|
def _first_invasive_biopsy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
|
|
"""The CaMa survival index and, per rule, whether it flags the patient."""
|
|
grades = set(index["event_grades"])
|
|
reports = sorted((e for e in events if e["tipo"] == "biopsia" and e["valor_codigo"] in grades),
|
|
key=lambda e: (e["fecha"], e["fuente_id"]))
|
|
if not reports or not _in_window(reports[0]["fecha"], index):
|
|
return None, []
|
|
fecha = reports[0]["fecha"]
|
|
return fecha, [
|
|
("sin_nacimiento", not any(e["tipo"] == "nacimiento" for e in events)),
|
|
("defuncion_hasta_el_indice", any(e["tipo"] == "defuncion" and e["fecha"] <= fecha for e in events)),
|
|
]
|
|
|
|
|
|
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy,
|
|
"primera_biopsia_invasora": _first_invasive_biopsy}
|
|
|
|
|
|
def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]:
|
|
events = defaultdict(list)
|
|
for e in cohort.to_dict("records"):
|
|
events[int(e["pac_id"])].append(e)
|
|
return events
|
|
|
|
|
|
def _prior_days(rows: list[dict], fecha: date) -> int:
|
|
"""Days observed before the index: from the patient's first event in the frame."""
|
|
return (fecha - min(e["fecha"] for e in rows)).days
|
|
|
|
|
|
def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
|
|
"""(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and
|
|
after each rule, in order; each rule is charged only for those it removes from what it receives."""
|
|
rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0))
|
|
events = _events(cohort)
|
|
found = {}
|
|
for pac_id, rows in sorted(events.items()):
|
|
fecha, flags = rule(rows, index)
|
|
if fecha is not None:
|
|
flags = [*flags, ("observacion_previa_insuficiente", _prior_days(rows, fecha) < minimum)]
|
|
found[pac_id] = (fecha, flags)
|
|
left = {pac_id: flags for pac_id, (fecha, flags) in found.items() if fecha is not None}
|
|
attrition = [("pacientes", len(found)), ("indexed", len(left))]
|
|
names = [name for name, _ in next(iter(left.values()), [])]
|
|
for position, name in enumerate(names):
|
|
left = {pac_id: flags for pac_id, flags in left.items() if not flags[position][1]}
|
|
attrition.append((name, len(left)))
|
|
members = pd.DataFrame([(pac_id, found[pac_id][0]) for pac_id in left], columns=["pac_id", "fecha_indice"])
|
|
return members, attrition
|
|
|
|
|
|
def _with_window(cohort_lineage: dict, index: dict) -> dict:
|
|
"""The index config with the source cohort's recruitment window (its build's `parametros`), unless the config
|
|
sets its own: the window lives once, in the cohort's dbt vars."""
|
|
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
|
|
return {**{k: parameters[k] for k in ("recruitment_start", "recruitment_end") if k in parameters}, **index}
|
|
|
|
|
|
def cohort(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> pd.DataFrame:
|
|
"""The source cohort's long frame re-indexed by the scenario (`[config.index]`): only its members, each with the
|
|
scenario's `fecha_indice`. Without an index config, the source cohort as it is."""
|
|
if not index:
|
|
return source_cohort
|
|
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
|
|
return (source_cohort.drop(columns="fecha_indice").merge(members, on="pac_id")[list(source_cohort.columns)]
|
|
.reset_index(drop=True))
|
|
|
|
|
|
def index_attrition(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> list:
|
|
"""How many are left after the scenario's index and each of its rules; empty without an index config."""
|
|
return _indexed_members(source_cohort, _with_window(cohort_lineage, index))[1] if index else []
|
|
|
|
|
|
def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> dict:
|
|
"""How much history the scenario's members had before their index (aggregates only): how many, how many with
|
|
under a year, and the median days. Shows the weight of left truncation while the threshold is 0."""
|
|
if not index:
|
|
return {}
|
|
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
|
|
events = _events(source_cohort)
|
|
days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float)
|
|
return {"members": len(days), "under_365_days": int((days < 365).sum()),
|
|
"median_days": None if days.empty else float(days.median()),
|
|
"threshold_days": int(index.get("observacion_previa_minima_dias", 0))}
|