73c5176482
Luis's recurrence scripts are kept as experiments. `models/cama/recurrence` holds the variable dictionary, the scenarios and the settings as data (`model.toml`), the writer of each cohort file as CaMa import files, the recode of the timeline into the per-patient frame and the analysis (Cramér's-V pruning, logistic terms and Bayesian-network parents per horizon, the scenario figures). The variable reader of the survival model is public so both share it. Includes the survival pipeline work this builds on. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
139 lines
6.5 KiB
Python
139 lines
6.5 KiB
Python
"""SEER's recoded file as CaMa import files: one CSV per bronze entity, named by the fields the import schemas take, to be
|
|
uploaded through the platform's import like any other source.
|
|
|
|
python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR
|
|
|
|
What goes where is the dictionary's (`[variables.*.seer]` of `model.toml`): each SEER category is stored as the catalog
|
|
value the dictionary names, and read back as the same category. SEER records no calendar dates: the diagnosis is a fixed
|
|
day of its year, the birth the middle of the age band, the death (or, for the living, the last contact) the diagnosis
|
|
plus the survival months; the months stay exact.
|
|
"""
|
|
|
|
import argparse
|
|
from datetime import timedelta
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
from models.cama.seer_survival import variables
|
|
|
|
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "Mastografia": "mastografias",
|
|
"NotaMedica": "notas", "TratamientoMama": "tratamientos"}
|
|
FEMALE = "Femenino"
|
|
|
|
|
|
def _age_years(label: str, index: dict) -> float | None:
|
|
"""The middle of an age band ("60-64 years" -> 62.5); the open band's own value; None without a number."""
|
|
head = str(label).split(" ")[0]
|
|
if head.endswith("+"):
|
|
return float(index["seer_age_open_value"])
|
|
low, _, high = head.partition("-")
|
|
if not (low.isdigit() and high.isdigit()):
|
|
return None
|
|
return (int(low) + int(high) + 1) / 2
|
|
|
|
|
|
def _number(text, spec: dict) -> float | None:
|
|
text = str(text)
|
|
if text in spec["microscopic"]:
|
|
return float(spec["microscopic_mm"])
|
|
return float(text) if text.replace(".", "", 1).isdigit() else None
|
|
|
|
|
|
def convert(recoded: pd.DataFrame, dictionary: dict) -> dict[str, pd.DataFrame]:
|
|
index = dictionary["index"]
|
|
ages = recoded[index["age_column"]].map(lambda v: _age_years(v, index))
|
|
frame = recoded[ages.notna()].copy()
|
|
ages = ages[ages.notna()]
|
|
months = pd.to_numeric(frame[index["months_column"]]).astype(int)
|
|
dead = frame[index["vital_column"]].eq(index["dead"])
|
|
day = pd.to_timedelta(months * index["days_per_month"], unit="D").dt.round("D")
|
|
diagnosis = frame[index["year_column"]].astype(int).map(lambda y: pd.Timestamp(variables.diagnosis_date(y, dictionary)))
|
|
birth = diagnosis - pd.to_timedelta((ages * 365.25).round(), unit="D")
|
|
ident = frame[index["id_column"]].astype(str)
|
|
date = lambda s: s.dt.strftime("%Y-%m-%d")
|
|
|
|
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
|
|
tables["Paciente"]["pac_sexo"] = FEMALE
|
|
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
|
|
tables["Paciente"]["pac_fecha_defuncion"] = date(diagnosis + day).where(dead)
|
|
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
|
|
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
|
|
tables["Mastografia"]["mast_fecha_toma"] = date(diagnosis)
|
|
tables["Mastografia"]["mast_fecha_reporte"] = date(diagnosis)
|
|
|
|
for name in variables.variable_names(dictionary):
|
|
spec = dictionary[name]
|
|
seer = spec.get("seer")
|
|
if not seer or "treatment" in seer:
|
|
continue
|
|
origin = seer.get("from", name)
|
|
category = frame[variables.column_of(origin, dictionary[origin])]
|
|
for target in (seer, seer.get("also")):
|
|
if not target:
|
|
continue
|
|
entity, column = target["bronze"].split(".")
|
|
if "number" in seer:
|
|
tables[entity][column] = frame[seer["number"]].map(lambda v: _number(v, seer))
|
|
elif "number_values" in seer:
|
|
tables[entity][column] = category.map(seer["number_values"])
|
|
else:
|
|
tables[entity][column] = category.map(target["values"])
|
|
|
|
# A biopsy is invasive unless the stage says in situ.
|
|
stage = frame[variables.column_of("Estadio", dictionary["Estadio"])]
|
|
in_situ = [k for k, v in dictionary["Estadio"]["seer"]["values"].items() if v == "E0"]
|
|
tables["BiopsiaMama"]["bx_grado_histologico"] = stage.isin(in_situ).map(
|
|
{True: "CARCINOMA_IN_SITU", False: "CARCINOMA_INVASOR"})
|
|
|
|
# A receptor status the subtype contradicts follows the subtype (the model reads the subtype from the receptors).
|
|
subtype = frame[variables.column_of("Subtipo_molecular", dictionary["Subtipo_molecular"])]
|
|
positive_hr = subtype.str.startswith("HR+")
|
|
negative_hr = subtype.str.startswith("HR-")
|
|
bx = tables["BiopsiaMama"]
|
|
no_positive = ~((bx["bx_receptor_estrogeno"] == "POSITIVO") | (bx["bx_receptor_progesterona"] == "POSITIVO"))
|
|
bx.loc[positive_hr & no_positive, "bx_receptor_estrogeno"] = "POSITIVO"
|
|
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
|
|
bx.loc[negative_hr & bx[column].isna(), column] = "NEGATIVO"
|
|
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
|
|
bx.loc[negative_hr & (bx[column] == "POSITIVO"), column] = "NEGATIVO"
|
|
|
|
notes = tables["NotaMedica"]
|
|
notes["nm_id_hospital"] = ident + "-dx"
|
|
notes["nm_fecha"] = date(diagnosis)
|
|
notes["nm_tipo_nota"] = "CONSULTA"
|
|
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(diagnosis + day),
|
|
"nm_tipo_nota": "CONSULTA"})[~dead.to_numpy()]
|
|
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
|
|
|
|
treatments = []
|
|
for name in variables.variable_names(dictionary):
|
|
seer = dictionary[name].get("seer", {})
|
|
if "treatment" not in seer:
|
|
continue
|
|
category = frame[variables.column_of(name, dictionary[name])]
|
|
values = category.map(seer["values"])
|
|
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": seer["treatment"], "trat_fecha": date(diagnosis),
|
|
"trat_detalle": values})[values.notna()]
|
|
if seer["treatment"] == "cirugia":
|
|
rows["trat_lateralidad"] = bx["bx_lateralidad"].reindex(rows.index)
|
|
treatments.append(rows)
|
|
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
|
|
return tables
|
|
|
|
|
|
def main(argv=None) -> None:
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("recoded")
|
|
ap.add_argument("out_dir")
|
|
args = ap.parse_args(argv)
|
|
recoded = pd.read_csv(args.recoded, dtype=str, low_memory=False)
|
|
out = Path(args.out_dir)
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
for entity, table in convert(recoded, variables.load()).items():
|
|
table.to_csv(out / f"{ENTITIES[entity]}.csv", index=False)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|