Agregar codificadores binarios de las variables CaCu a la fecha índice
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her
|
||||
index date. NaN is missing: an absent value is never 0. No model reads these; they are
|
||||
there for when one does.
|
||||
|
||||
Only what was available at the index is read (see `visible`): the index sample's results,
|
||||
reported after it, are missing when the index is the sample day.
|
||||
|
||||
Inputs are the gold timeline with its `evidence_date` and `source_available_at`
|
||||
(persistance.gold.evidence_timelines) and, for the form fields gold does not carry, the
|
||||
wide silver cytology (persistance.gold.cervical_forms)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu, catalog
|
||||
from models.cacu.features import _referral_grade, _worst, prepared
|
||||
from models.cacu.specs import _REFERRAL
|
||||
from models.survival import age_group, band
|
||||
|
||||
# What was done to her before the index: the index day's own is left out, as it may be
|
||||
# (or follow from) the outcome.
|
||||
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
|
||||
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
|
||||
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
|
||||
EVIDENCE_TABLE = "cacu_eligibility_evidence"
|
||||
|
||||
|
||||
def _codes(field: str) -> list[str]:
|
||||
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
|
||||
|
||||
|
||||
FINDINGS = tuple(
|
||||
name for name, f in catalog.studies()["cervical_cytology"].fields.items()
|
||||
if name.startswith("finding_") and f.type == "boolean"
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _day(values: pd.Series) -> pd.Series:
|
||||
"""The calendar day of dates or ISO timestamps (as written); empty stays NaT."""
|
||||
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
|
||||
|
||||
|
||||
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's events available at her index, with her index date:
|
||||
|
||||
- dated (a result: reported) and, if it has one, clinically dated by the index;
|
||||
- `source_available_at`, when the source gave it, by the index day. When it gave none,
|
||||
the event's date stands, except for standalone eligibility evidence, dated by its
|
||||
clinical onset: that is left out, as the cohort rules do;
|
||||
- procedures and diagnoses strictly before the index day.
|
||||
|
||||
`known_at` (when the platform loaded it) is not read."""
|
||||
found = events.drop(columns="index_date", errors="ignore").merge(
|
||||
members[["person_id", "index_date"]], on="person_id"
|
||||
)
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
date, clinical = _day(found["date"]), _day(found["evidence_date"])
|
||||
available = _day(found["source_available_at"])
|
||||
keep = (date <= index) & (clinical.isna() | (clinical <= index))
|
||||
undated = available.isna() & (found["source_table"] != EVIDENCE_TABLE)
|
||||
keep &= undated | (available <= index)
|
||||
earlier = (date < index) & (clinical.isna() | (clinical < index))
|
||||
hysterectomy = (found["type"] == "gynecologic_condition") & (
|
||||
found["value_code"] == "hysterectomy"
|
||||
)
|
||||
keep &= earlier | ~(found["type"].isin(PROCEDURES) | hysterectomy)
|
||||
return prepared(found[keep])
|
||||
|
||||
|
||||
def _flag(known: pd.Series, true: pd.Series) -> pd.Series:
|
||||
"""1.0 / 0.0 where `known`, NaN elsewhere."""
|
||||
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
|
||||
|
||||
|
||||
def _one_hot(values: pd.Series, prefix: str, codes: list[str]) -> dict[str, pd.Series]:
|
||||
"""One column per code; a value that is none of them is missing, not 0 in all."""
|
||||
known = values.isin(codes)
|
||||
return {f"{prefix}__{code}": _flag(known, values == code) for code in codes}
|
||||
|
||||
|
||||
def _present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""1 when recorded; NaN otherwise (no record does not show it never happened)."""
|
||||
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
|
||||
|
||||
|
||||
def _latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
|
||||
"""Each member's latest recorded value of one kind of event."""
|
||||
found = events[(events["type"] == kind) & events["value_code"].notna()]
|
||||
found = found.sort_values(["date", "source_id"], kind="stable")
|
||||
return found.groupby("person_id")["value_code"].last().reindex(people)
|
||||
|
||||
|
||||
def _latest_bethesda(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""The result of her latest report; the most severe when that day has several."""
|
||||
codes = _codes("result")
|
||||
found = events[(events["type"] == "bethesda") & events["value_code"].isin(codes)]
|
||||
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
|
||||
# severity is the order of the KPNC categories, not the catalog's
|
||||
severity = {name: [name] for names in cacu.KPNC.values() for name in names if name in codes}
|
||||
return _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
|
||||
|
||||
|
||||
def _age(events: pd.DataFrame, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
|
||||
keyed = members.set_index("person_id", drop=False)
|
||||
keyed = keyed.assign(index_date=pd.to_datetime(keyed["index_date"]))
|
||||
found = age_group(events, keyed, cuts)
|
||||
labels = list(band(pd.Series([cuts[0] - 1, *cuts]), cuts))
|
||||
return _one_hot(found, "age", labels)
|
||||
|
||||
|
||||
def _cytology(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
result = _latest_bethesda(events, people)
|
||||
columns = _one_hot(result, "bethesda", _codes("result"))
|
||||
for name, codes in cacu.PROCEDURE_CYTOLOGY.items():
|
||||
columns[f"cytology_{name}"] = _flag(result.notna(), result.isin(codes))
|
||||
return columns
|
||||
|
||||
|
||||
def _hpv(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
columns = {}
|
||||
for kind in ("hpv", *GENOTYPES):
|
||||
value = _latest(events, kind, people)
|
||||
columns[f"{kind}_positive"] = _flag(
|
||||
value.isin(["positive", "negative"]), value == "positive"
|
||||
)
|
||||
# From the two genotypes of one sample, not gold's `hpv_16_18`: that is 0 when one is
|
||||
# negative and the other was not reported.
|
||||
found = events[events["type"].isin(GENOTYPES) & events["value_code"].notna()]
|
||||
wide = found.pivot_table(
|
||||
index=["person_id", "date", "source_id"], columns="type", values="value_code",
|
||||
aggfunc="first",
|
||||
).reindex(columns=list(GENOTYPES)) # fmt: skip
|
||||
latest = wide.sort_index().reset_index().drop_duplicates("person_id", keep="last")
|
||||
latest = latest.set_index("person_id").reindex(people)[list(GENOTYPES)]
|
||||
positive = (latest == "positive").any(axis=1)
|
||||
both_negative = (latest == "negative").all(axis=1)
|
||||
columns["hpv_16_or_18_positive"] = _flag(positive | both_negative, positive)
|
||||
return columns
|
||||
|
||||
|
||||
def _history(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
of = {kind: events[events["type"] == kind] for kind in (*PROCEDURES, "cytology")}
|
||||
columns = {
|
||||
"prior_cytology_sample": _present(
|
||||
of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]], people
|
||||
),
|
||||
"prior_biopsy_order": _present(of["biopsy_order"], people),
|
||||
"prior_biopsy_report": _present(of["biopsy"], people),
|
||||
"prior_colposcopy": _present(of["colposcopy"], people),
|
||||
"prior_treatment": _present(of["treatment"], people),
|
||||
"prior_diagnosis_note": _present(of["diagnosis"], people),
|
||||
"history_cancer_icd10": _present(of["history"], people),
|
||||
"history_hysterectomy": _present(
|
||||
events[(events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")], people
|
||||
),
|
||||
} # fmt: skip
|
||||
|
||||
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
|
||||
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
|
||||
worst = worst.reindex(people)
|
||||
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "HSIL"), ("carcinoma", "carcinoma")):
|
||||
columns[f"prior_biopsy_{name}"] = _flag(worst.notna(), worst >= rank[grade])
|
||||
|
||||
persons = pd.Series(people, index=people)
|
||||
if events["type"].eq("colposcopy").any():
|
||||
grade = _referral_grade(events, persons, _REFERRAL | {"cytology": cacu.KPNC_3})
|
||||
else:
|
||||
grade = pd.Series(None, index=people, dtype=object)
|
||||
columns["referral_high_grade"] = _flag(grade.notna(), grade == "high")
|
||||
return columns
|
||||
|
||||
|
||||
def _forms(forms: pd.DataFrame | None, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
"""The cytology form's fields gold does not carry. Silver keeps no
|
||||
`source_available_at` for them: what the sample form says counts from the sample day,
|
||||
what the report says from the report day."""
|
||||
people = pd.Index(members["person_id"])
|
||||
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
|
||||
*FINDINGS] # fmt: skip
|
||||
if forms is None:
|
||||
forms = pd.DataFrame(columns=columns)
|
||||
found = forms[columns].merge(members[["person_id", "index_date"]], on="person_id")
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
|
||||
sampled = found[(_day(found["sample_date"]) <= index) & found["screening_history"].notna()]
|
||||
sampled = sampled.sort_values("sample_date", key=_day, kind="stable")
|
||||
history = sampled.groupby("person_id")["screening_history"].last().reindex(people)
|
||||
|
||||
reported = found[(_day(found["report_date"]) <= index) & (_day(found["sample_date"]) <= index)]
|
||||
reported = reported.assign(r=_day(reported["report_date"]), s=_day(reported["sample_date"]))
|
||||
# Her latest report, whole: a finding it does not state is unknown, whatever older
|
||||
# reports said.
|
||||
report = reported.sort_values(["r", "s"], kind="stable").drop_duplicates(
|
||||
"person_id", keep="last"
|
||||
)
|
||||
report = report.set_index("person_id").reindex(people)
|
||||
|
||||
out = _one_hot(history, "screening_history", _codes("screening_history"))
|
||||
adequacy = report["adequacy"]
|
||||
out["sample_unsatisfactory"] = _flag(
|
||||
adequacy.isin(_codes("adequacy")), adequacy == "unsatisfactory"
|
||||
)
|
||||
for name in FINDINGS:
|
||||
value = report[name]
|
||||
out[name] = _flag(value.notna(), value.eq(True))
|
||||
return out
|
||||
|
||||
|
||||
def encode(events: pd.DataFrame, forms: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
"""One row per member of `events` (`person_id`, `index_date`): every encoder's column,
|
||||
0.0, 1.0 or NaN. `events` needs `evidence_date` and `source_available_at`; without
|
||||
`forms` their columns are all missing."""
|
||||
missing = {"evidence_date", "source_available_at"} - set(events.columns)
|
||||
if missing:
|
||||
raise ValueError(f"timeline without availability columns: {', '.join(sorted(missing))}")
|
||||
members = events[["person_id", "index_date"]].drop_duplicates().reset_index(drop=True)
|
||||
if members["person_id"].duplicated().any():
|
||||
raise ValueError("one index date per person")
|
||||
people = pd.Index(members["person_id"], name="person_id")
|
||||
seen = visible(events, members)
|
||||
|
||||
columns = _age(seen, members)
|
||||
columns |= _cytology(seen, people)
|
||||
columns |= _hpv(seen, people)
|
||||
exam = seen[seen["source_table"] == "cervical_cytology"]
|
||||
for field in EXAM_FIELDS:
|
||||
columns |= _one_hot(_latest(exam, field, people), field, _codes(field))
|
||||
columns |= _history(seen, people)
|
||||
columns |= _forms(forms, members)
|
||||
|
||||
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
|
||||
return pd.concat([members, pd.DataFrame(values)], axis=1)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The binary encoders read only what was available at the index, and never turn an
|
||||
absent value into 0."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.encoders import FINDINGS, encode
|
||||
|
||||
INDEX = "2025-06-10"
|
||||
|
||||
|
||||
def event(day, kind, code=None, person="p1", table="cervical_cytology", sample=None,
|
||||
clinical=None, available=None): # fmt: skip
|
||||
return {
|
||||
"person_id": person, "index_date": INDEX, "date": day, "type": kind,
|
||||
"value_code": code, "value_num": np.nan, "source_table": table,
|
||||
"source_id": sample or day, "evidence_date": clinical, "source_available_at": available,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def form(sample, report, person="p1", **fields):
|
||||
empty = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
|
||||
return {"person_id": person, "sample_date": sample, "report_date": report} | empty | fields
|
||||
|
||||
|
||||
def row(events, forms=None, person="p1"):
|
||||
found = encode(pd.DataFrame(events), None if forms is None else pd.DataFrame(forms))
|
||||
return found.set_index("person_id").loc[person].drop("index_date").astype(float)
|
||||
|
||||
|
||||
def test_nothing_known_is_all_missing():
|
||||
found = row([event(INDEX, "cytology", "satisfactory")])
|
||||
assert found.isna().all()
|
||||
|
||||
|
||||
def test_values_and_missing():
|
||||
found = row([
|
||||
event("1980-06-11", "birth", table="person"),
|
||||
event("2025-01-15", "bethesda", "LSIL", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv", "positive", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv_16", "negative", sample="2025-01-10"),
|
||||
event(INDEX, "cervix_appearance", "lesion"),
|
||||
event(INDEX, "presenting_symptom", "not-a-code"),
|
||||
]) # fmt: skip
|
||||
assert found["age__35-44"] == 1 and found["age__45-54"] == 0
|
||||
assert found["bethesda__LSIL"] == 1 and found["bethesda__HSIL"] == 0
|
||||
assert found["cytology_ascus_plus"] == 1 and found["cytology_hsil_plus"] == 0
|
||||
assert found["hpv_positive"] == 1 and found["hpv_16_positive"] == 0
|
||||
assert np.isnan(found["hpv_18_positive"])
|
||||
# one genotype negative and the other unreported is unknown, not negative
|
||||
assert np.isnan(found["hpv_16_or_18_positive"])
|
||||
assert found["cervix_appearance__lesion"] == 1 and found["cervix_appearance__healthy"] == 0
|
||||
assert found.filter(like="presenting_symptom").isna().all() # ambiguous value
|
||||
assert found.filter(like="prior_").isna().all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("positive, other, expected", [
|
||||
("positive", None, 1.0), ("negative", "negative", 0.0), ("negative", "positive", 1.0),
|
||||
]) # fmt: skip
|
||||
def test_genotypes_combined(positive, other, expected):
|
||||
events = [event("2025-01-15", "hpv_16", positive)]
|
||||
if other:
|
||||
events.append(event("2025-01-15", "hpv_18", other))
|
||||
assert row(events)["hpv_16_or_18_positive"] == expected
|
||||
|
||||
|
||||
def test_nothing_later_than_the_index_is_read():
|
||||
base = [event(INDEX, "cytology", "satisfactory")]
|
||||
later = [
|
||||
event("2025-06-20", "bethesda", "HSIL", sample=INDEX), # the index sample's report
|
||||
event("2025-06-20", "hpv", "positive", sample=INDEX),
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
|
||||
event("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
|
||||
# procedures of the index day may be the outcome
|
||||
event(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
|
||||
event(INDEX, "colposcopy", table="clinical_note"),
|
||||
event(INDEX, "treatment", table="clinical_note"),
|
||||
event("2025-08-01", "history", table="clinical_note"),
|
||||
# standalone evidence without an availability date: its onset says nothing of it
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence"),
|
||||
] # fmt: skip
|
||||
forms = [form(INDEX, "2025-06-20", adequacy="unsatisfactory", finding_atrophy=True)]
|
||||
pd.testing.assert_series_equal(row(base + later, forms), row(base))
|
||||
|
||||
|
||||
def test_available_by_the_index_day_is_read():
|
||||
found = row([
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence", available="2024-01-01"),
|
||||
]) # fmt: skip
|
||||
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
|
||||
|
||||
|
||||
def test_prior_procedures_and_referral():
|
||||
found = row([
|
||||
event("2025-01-15", "bethesda", "HSIL", sample="2025-01-10"),
|
||||
event("2025-03-01", "colposcopy", table="clinical_note"),
|
||||
event("2025-03-01", "biopsy_order", table="cervical_biopsy"),
|
||||
event("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
|
||||
]) # fmt: skip
|
||||
assert found["prior_colposcopy"] == 1 and found["prior_biopsy_order"] == 1
|
||||
assert found["prior_biopsy_lsil_plus"] == 1 and found["prior_biopsy_hsil_plus"] == 0
|
||||
assert found["referral_high_grade"] == 1
|
||||
assert np.isnan(found["prior_treatment"])
|
||||
|
||||
|
||||
def test_form_fields_come_from_the_latest_report():
|
||||
forms = [
|
||||
form("2024-01-10", "2024-01-20", screening_history="never", finding_atrophy=True),
|
||||
form("2025-01-10", "2025-01-20", adequacy="satisfactory", finding_candida=1),
|
||||
]
|
||||
found = row([event(INDEX, "cytology")], forms)
|
||||
assert found["screening_history__never"] == 1
|
||||
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
|
||||
assert np.isnan(found["finding_atrophy"])
|
||||
|
||||
|
||||
def test_members_are_kept_apart():
|
||||
events = [event("2025-01-15", "hpv", "positive"), event(INDEX, "cytology", person="p2")]
|
||||
assert np.isnan(row(events, person="p2")["hpv_positive"])
|
||||
|
||||
|
||||
def test_a_timeline_without_availability_is_refused():
|
||||
events = pd.DataFrame([event(INDEX, "cytology")]).drop(columns="source_available_at")
|
||||
with pytest.raises(ValueError, match="source_available_at"):
|
||||
encode(events)
|
||||
Reference in New Issue
Block a user