Files
models/models/cacu/features.py
T

165 lines
8.8 KiB
Python

"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
value_code, value_num, source_table, source_id."""
import numpy as np
import pandas as pd
from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
MISSING = "(none)"
def prepared(events: pd.DataFrame) -> pd.DataFrame:
return events.assign(
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
)
def days(events: pd.DataFrame) -> pd.Series:
return (events["date"] - events["index_date"]).dt.days
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
names = list(cytology)
worst = codes.map(rank).groupby(level=0).max()
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
"""Why she was referred: the worst result in the year before her first colposcopy."""
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
before = (events["person_id"].map(first) - events["date"]).dt.days
near = events[before.between(0, history["lookback_days"])]
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
positive = persons.isin(hpv["person_id"])
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
& positive.to_numpy()), "low", None)) # fmt: skip
return pd.Series(grade, index=persons.index, dtype=object)
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
"""Per patient: the cytology category and HPV result of her index sample (the first
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
when `history` asks for it."""
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
members = events.groupby("person_id", as_index=False)["index_date"].first()
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
codes = wide[["bethesda", "glandular"]].stack()
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history:
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
return members
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
negative co-test (the later day of its two results)."""
timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None
for kind, values in cacu.KNOWN_NEGATIVE.items():
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
found = found[["person_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
left_on="days", right_on=kind, by="person_id", direction="nearest",
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
).dropna(subset=[kind]) # fmt: skip
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
the prevalent window), free at the index (a negative before any outcome), or unknown;
and the years between her last negative and her outcome biopsy."""
d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
negatives = _negatives(events, d, grades)
before = ~(negatives["days"] >= negatives["person_id"].map(first))
last_negative = negatives[before].groupby("person_id")["days"].max()
coded = index_results(events, cytology, history)
window = cacu.PREVALENT_WINDOW_DAYS
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
prevalent = event_days <= window
free = free_until.notna() & ~prevalent
later = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0,
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
return coded
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
[*key, "date"]] # fmt: skip
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete.index)].reset_index()
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
return latest["date"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test."""
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
"""Per patient: each predictor's result on her index sample, MISSING when none."""
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members = members[["person_id", "index_date"]]
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
genotype = results["type"] == "hpv_16_18"
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
{1.0: "positive", 0.0: "negative"}
)
wide = results[results["type"].isin(predictors)].pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
wide = wide.reindex(columns=list(predictors)).astype(object)
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
return found.fillna(dict.fromkeys(predictors, MISSING))
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window)
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
followed = (follow_up_end - members["index_date"]).dt.days
members["known"] = (members["y"] == 1) | (followed >= window)
return members[["person_id", "y", "known"]]