CaMa survival: lesion-size feature and the SEER development stages published with each version
This commit is contained in:
@@ -205,13 +205,16 @@ def risk_variable_summary(risk_classification: Classification) -> pd.DataFrame:
|
||||
def risk_treatment_associations(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
|
||||
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
|
||||
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by
|
||||
indication); None when there are none."""
|
||||
indication); None when there are none
|
||||
or none of them varies."""
|
||||
if not risk_treatment:
|
||||
return None
|
||||
variables = risk_intrinsic + risk_treatment
|
||||
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
|
||||
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
|
||||
tr = tr[tr["variable"].isin(risk_treatment)].copy()
|
||||
if tr.empty:
|
||||
return None
|
||||
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
|
||||
tr["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
|
||||
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"])
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The SEER development stages over the cohort a run trains on: what the dashboard shows as the model's development.
|
||||
|
||||
The members are written as the pipeline's recoded file (`models.cama.seer_survival`, stages 01 to 06): the depuration of
|
||||
redundant variables, the balanced cohort and its age and tumor categorization, the stepwise logistic regression and the
|
||||
Bayesian network with their comparison, the bootstrap, the survival curves of the subgroups and the risk factors. Their
|
||||
tables and figures are the version's `analisis/desarrollo.json`. Stage and treatment are not in the hospital's data yet, so
|
||||
they enter as `Desconocido` and the record names them; a stage that cannot run publishes its error and the others go on.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import dataclasses
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import pipeline
|
||||
from models.cama.seer_survival.settings import load
|
||||
|
||||
UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat")
|
||||
# What the dashboard reads: the file written by a stage, under the name it is published with.
|
||||
TABLES = {
|
||||
"or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos",
|
||||
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
|
||||
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
|
||||
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
|
||||
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
|
||||
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
|
||||
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
|
||||
}
|
||||
MAX_ROWS = 60
|
||||
MAX_FIGURE_BYTES = 400_000
|
||||
|
||||
|
||||
def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The members as the pipeline's recoded file: its raw SEER columns (year, age level, months, vital status, tumor
|
||||
size) and the categorical ones, each unknown value `Desconocido`."""
|
||||
lm = labelled_members
|
||||
age = lm["age_years"].fillna(lm["age_years"].median()).to_numpy()
|
||||
lower = (np.floor(age / 5) * 5).astype(int)
|
||||
frame = pd.DataFrame({
|
||||
"Year of diagnosis": pd.to_datetime(lm["fecha_indice"]).dt.year.astype(str),
|
||||
"Age recode with <1 year olds": [f"{v}-{v + 4} years" if v < 85 else "85+ years" for v in lower],
|
||||
"Survival months": lm["months"].astype(float).astype(str),
|
||||
"Vital status recode (study cutoff used)": np.where(lm["event"], "Dead", "Alive"),
|
||||
"Tumor size summary (mm)": lm["size_mm"].map(lambda v: "" if pd.isna(v) else str(int(v))),
|
||||
})
|
||||
for column, source in (("Tipo_histologico_cat", "histologic_type"), ("Grado_histologico_cat", "grade"),
|
||||
("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"),
|
||||
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
|
||||
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
|
||||
for column in UNAVAILABLE:
|
||||
frame[column] = "Desconocido"
|
||||
return frame
|
||||
|
||||
|
||||
def _seer_settings(development: dict):
|
||||
"""The pipeline's own settings with this model's budget (`[config.desarrollo]`) and its Ki-67 column, which the
|
||||
SEER dictionary does not have."""
|
||||
s = load()
|
||||
m = s.modeling
|
||||
modeling = dataclasses.replace(
|
||||
m, canonical_map={**m.canonical_map, "Ki67_cat": "Ki67"}, categorical_order=(*m.categorical_order, "Ki67"),
|
||||
tier_tumor=(*m.tier_tumor, "Ki67"), n_bootstrap_run=development["n_bootstrap"],
|
||||
bootstrap_max_seconds=development["bootstrap_max_seconds"], bootstrap_restarts=development["bootstrap_restarts"],
|
||||
n_splits_prop=development["n_splits_proposals"], proposals_max_seconds=development["proposals_max_seconds"],
|
||||
n_restarts=development["restarts"])
|
||||
return dataclasses.replace(
|
||||
s, modeling=modeling, depuration=dataclasses.replace(s.depuration, null_perm=development["null_perm"]),
|
||||
balancing=dataclasses.replace(s.balancing, exclude_censored_years=False))
|
||||
|
||||
|
||||
def _records(path: Path) -> list[dict]:
|
||||
table = pd.read_csv(path)
|
||||
if table.columns[0].startswith("Unnamed"):
|
||||
table = table.rename(columns={table.columns[0]: "indice"})
|
||||
table = table.head(MAX_ROWS).replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
return table.where(table.notna(), None).to_dict("records")
|
||||
|
||||
|
||||
def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict:
|
||||
"""`{"desarrollo": record}`, or `{}` when `[config.desarrollo]` has `enabled = false`."""
|
||||
if not desarrollo.get("enabled", True):
|
||||
return {}
|
||||
errors, log = {}, []
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp)
|
||||
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
|
||||
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
|
||||
settings = _seer_settings(desarrollo)
|
||||
for stage in pipeline.STAGES:
|
||||
try:
|
||||
log += pipeline.run_pipeline(out, only=[stage.id], everything=True, settings=settings)
|
||||
except Exception as error:
|
||||
errors[stage.id] = f"{type(error).__name__}: {error}"
|
||||
log.append((stage.id, "error", 0))
|
||||
traceback.print_exc()
|
||||
tables = {name: _records(out / file) for file, name in TABLES.items() if (out / file).exists()}
|
||||
figures = {}
|
||||
for path in sorted(out.rglob("*.png")):
|
||||
raw = path.read_bytes()
|
||||
if len(raw) <= MAX_FIGURE_BYTES:
|
||||
figures[path.stem] = base64.b64encode(raw).decode("ascii")
|
||||
return {"desarrollo": {
|
||||
"version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log],
|
||||
"errores": errors, "variables_no_disponibles": list(UNAVAILABLE), "tablas": tables, "figuras": figures}}
|
||||
|
||||
|
||||
def population(population_curves: dict, development: dict) -> dict:
|
||||
"""Everything the version publishes about its cohort, by file name under `analisis/`: the curves and the development."""
|
||||
return {**population_curves, **development}
|
||||
@@ -25,10 +25,12 @@ from models.steps import indexing
|
||||
UNKNOWN = "NA"
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
INDEX_COLUMN = "fecha_indice_modelo"
|
||||
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group"]
|
||||
NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding: the SEER development stages band them themselves
|
||||
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"]
|
||||
RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er",
|
||||
"receptor_progesterona": "pr", "her2": "her2"}
|
||||
WINDOW_KEYS = ("recruitment_start", "recruitment_end")
|
||||
DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
|
||||
EPOCH = pd.Timestamp("1970-01-01")
|
||||
|
||||
|
||||
@@ -48,20 +50,25 @@ def _dated(cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
return cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
|
||||
|
||||
|
||||
def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_days: int) -> pd.DataFrame:
|
||||
def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_days: int,
|
||||
size_cuts: list | None = None) -> pd.DataFrame:
|
||||
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice` and the covariates in `FEATURES`,
|
||||
empty where the build has no such result near the index."""
|
||||
frame = _dated(cohort)
|
||||
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
|
||||
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
|
||||
members["age_group"] = _band((members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR, age_cuts)
|
||||
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
|
||||
members["age_group"] = _band(members["age_years"], age_cuts)
|
||||
near = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, result_days)]
|
||||
near = near.sort_values(["fecha", "fuente_id"])
|
||||
for tipo, name in RESULTS.items():
|
||||
members[name] = near[near["tipo"] == tipo].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
|
||||
ki67 = near[near["tipo"] == "ki67_pct"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
|
||||
members["ki67_group"] = _band(ki67, ki67_cuts)
|
||||
return members[["fecha_indice", *FEATURES]]
|
||||
size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
|
||||
members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS)
|
||||
members["size_mm"], members["ki67_pct"] = size, ki67
|
||||
return members[["fecha_indice", *FEATURES, *NUMERIC]]
|
||||
|
||||
|
||||
def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame:
|
||||
@@ -111,12 +118,14 @@ class MemberFeatures(TransformerMixin, BaseEstimator):
|
||||
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
|
||||
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
|
||||
|
||||
def __init__(self, index=None, window=None, age_cuts=(45, 60, 75), ki67_cuts=(14, 20), result_days=30):
|
||||
def __init__(self, index=None, window=None, age_cuts=(45, 60, 75), ki67_cuts=(14, 20), result_days=30,
|
||||
size_cuts=DEFAULT_SIZE_CUTS):
|
||||
self.index = index
|
||||
self.window = window
|
||||
self.age_cuts = age_cuts
|
||||
self.ki67_cuts = ki67_cuts
|
||||
self.result_days = result_days
|
||||
self.size_cuts = size_cuts
|
||||
|
||||
def fit(self, X, y=None):
|
||||
return self
|
||||
@@ -124,8 +133,8 @@ class MemberFeatures(TransformerMixin, BaseEstimator):
|
||||
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
|
||||
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
|
||||
table = member_table(indexed, list(self.age_cuts), list(self.ki67_cuts), self.result_days) \
|
||||
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES])
|
||||
table = member_table(indexed, list(self.age_cuts), list(self.ki67_cuts), self.result_days, list(self.size_cuts)) \
|
||||
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
|
||||
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
|
||||
return table[[*FEATURES, INDEX_COLUMN]]
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ invasive biopsy report.
|
||||
|
||||
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
|
||||
`[config.index]`): the index is the first biopsy report graded invasive. Each member's covariates are the results of
|
||||
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67) and her age at the index; her outcome is the
|
||||
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67, lesion size) and her age at the index; her outcome is the
|
||||
months from the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts
|
||||
the follow-up). The fit is the SEER pipeline's interval survival (`models.cama.seer_survival.survival_models`): per
|
||||
interval a logistic regression and a Bayesian network, stacked. A member without a result has it as a category of its
|
||||
@@ -53,9 +53,10 @@ def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSe
|
||||
return settings
|
||||
|
||||
|
||||
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int) -> pd.DataFrame:
|
||||
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int,
|
||||
size_cuts: list[int]) -> pd.DataFrame:
|
||||
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates."""
|
||||
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days)
|
||||
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days, size_cuts)
|
||||
|
||||
|
||||
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
|
||||
@@ -212,9 +213,9 @@ def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_ba
|
||||
|
||||
|
||||
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
|
||||
ki67_cuts: list[int], result_days: int) -> Pipeline:
|
||||
ki67_cuts: list[int], result_days: int, size_cuts: list[int]) -> Pipeline:
|
||||
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
|
||||
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
|
||||
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
|
||||
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days)),
|
||||
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days, tuple(size_cuts))),
|
||||
("survival", fitted_survival)])
|
||||
|
||||
@@ -5,20 +5,21 @@ outcome = "muerte"
|
||||
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
# The modules whose functions are the graph's nodes, in `with_modules`.
|
||||
modules = ["models.cama.survival.model", "models.cama.survival.population", "models.steps.indexing"]
|
||||
modules = ["models.cama.survival.model", "models.cama.survival.population", "models.cama.survival.development", "models.steps.indexing"]
|
||||
description = """
|
||||
Prototipo: mortalidad por cualquier causa a los 6, 12 y 18 meses del primer reporte de biopsia con carcinoma invasor, \
|
||||
a partir de la edad y de los resultados de ese reporte (tipo histológico, grado de Nottingham, receptores de estrógeno \
|
||||
y de progesterona, HER2 y Ki-67). Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana \
|
||||
y de progesterona, HER2, Ki-67 y tamaño de la lesión). Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana \
|
||||
combinadas). Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la registra."""
|
||||
|
||||
[config]
|
||||
train_fraction = 0.7
|
||||
# The model's horizons, in years; `survival.horizons` are the same in months.
|
||||
horizons_years = [0.5, 1.0, 1.5]
|
||||
# Covariate bands: the age at the index, in years, and the Ki-67 percentage.
|
||||
# Covariate bands: the age at the index, in years, the Ki-67 percentage and the lesion size in millimetres (T1, T2, T3).
|
||||
age_cuts = [45, 60, 75]
|
||||
ki67_cuts = [14, 20]
|
||||
size_cuts = [20, 50]
|
||||
# A report's results count for the index when they are dated up to this many days after it (and a week before).
|
||||
result_days = 30
|
||||
|
||||
@@ -31,6 +32,17 @@ event_grades = ["CARCINOMA_INVASOR"]
|
||||
observacion_previa_minima_dias = 0
|
||||
|
||||
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
|
||||
[config.desarrollo]
|
||||
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort.
|
||||
enabled = true
|
||||
null_perm = 20
|
||||
n_bootstrap = 20
|
||||
bootstrap_max_seconds = 240
|
||||
bootstrap_restarts = 2
|
||||
n_splits_proposals = 2
|
||||
proposals_max_seconds = 120
|
||||
restarts = 4
|
||||
|
||||
[config.survival]
|
||||
age_mode = "categorizada"
|
||||
include_age = true
|
||||
|
||||
@@ -88,7 +88,7 @@ def weibull_fits(adjusted_km: np.ndarray, curve_cohort: sm.Cohort, survival_sett
|
||||
"parameters": {"classic": parameters(classic), "fractional": parameters(fractional)}}
|
||||
|
||||
|
||||
def population(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
|
||||
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
|
||||
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
|
||||
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
|
||||
"""What a version publishes about its cohort, by file name under `analisis/`: `curvas`, the record the dashboard
|
||||
|
||||
Reference in New Issue
Block a user