diff --git a/models/cama/seer_survival/risk_factors.py b/models/cama/seer_survival/risk_factors.py index 05dbb08..031aefa 100644 --- a/models/cama/seer_survival/risk_factors.py +++ b/models/cama/seer_survival/risk_factors.py @@ -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"]) diff --git a/models/cama/survival/development.py b/models/cama/survival/development.py new file mode 100644 index 0000000..d904fb2 --- /dev/null +++ b/models/cama/survival/development.py @@ -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} diff --git a/models/cama/survival/estimator.py b/models/cama/survival/estimator.py index 51c8c18..6c97ddc 100644 --- a/models/cama/survival/estimator.py +++ b/models/cama/survival/estimator.py @@ -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]] diff --git a/models/cama/survival/model.py b/models/cama/survival/model.py index eb0b25d..478bb24 100644 --- a/models/cama/survival/model.py +++ b/models/cama/survival/model.py @@ -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)]) diff --git a/models/cama/survival/model.toml b/models/cama/survival/model.toml index 6cbb8ff..94e9b9d 100644 --- a/models/cama/survival/model.toml +++ b/models/cama/survival/model.toml @@ -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 diff --git a/models/cama/survival/population.py b/models/cama/survival/population.py index 296f8ac..0fefbca 100644 --- a/models/cama/survival/population.py +++ b/models/cama/survival/population.py @@ -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 diff --git a/tests/cama/test_seer_survival_stages.py b/tests/cama/test_seer_survival_stages.py index 32c46c6..a3b8196 100644 --- a/tests/cama/test_seer_survival_stages.py +++ b/tests/cama/test_seer_survival_stages.py @@ -250,3 +250,17 @@ def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monke log = pipeline.run_pipeline(tmp_path, settings=object()) assert [row[:2] for row in log] == [("99", "saltada"), ("98", "ok")] # 99's output is current; 98 has none to check assert (tmp_path / pipeline.LOG).read_text().splitlines()[0] == "etapa,estado,segundos" + + +def test_treatment_associations_are_none_when_no_treatment_variable_varies(): + """Pins down: a cohort where every treatment column is a single category (as when the hospital reports none) gives + no associations, as the docstring says, and not a missing-columns error. Fails if the empty case is formatted.""" + from models.cama.seer_survival import risk_factors + from models.cama.seer_survival.settings import load + + rng = np.random.default_rng(8) + n = 300 + data = pd.DataFrame({"Grado": rng.choice(["G1", "G3"], n), "Radioterapia": "Desconocido"}) + follow = risk_factors.FollowUp(death=pd.Series(rng.integers(0, 2, n)), months=pd.Series(rng.uniform(1, 20, n)), + event=pd.Series(rng.integers(0, 2, n))) + assert risk_factors.risk_treatment_associations(data, follow, ["Grado"], ["Radioterapia"], load().risk_factors) is None diff --git a/tests/cama/test_survival.py b/tests/cama/test_survival.py index 6fea8eb..c78e685 100644 --- a/tests/cama/test_survival.py +++ b/tests/cama/test_survival.py @@ -41,7 +41,7 @@ def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", sour "fuente_id": source_id or f"{pac_id}-{tipo}"} -def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None): +def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None, size=30.0): """The invasive biopsy report of `pac_id` on `index`, with its results.""" key = f"B{pac_id}" rows = [_row(pac_id, index, "biopsia", "CARCINOMA_INVASOR", source_id=key, first=first), @@ -50,7 +50,8 @@ def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, firs _row(pac_id, index, "receptor_estrogeno", er, source_id=key, first=first), _row(pac_id, index, "receptor_progesterona", er, source_id=key, first=first), _row(pac_id, index, "her2", her2, source_id=key, first=first), - _row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first)] + _row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first), + _row(pac_id, index, "tamano_tumor_mm", numero=size, source_id=key, first=first)] return rows @@ -122,12 +123,12 @@ def test_covariates_are_the_index_reports_results(cohort_frame): later = pd.DataFrame([_row(1, date(2025, 12, 1), "grado_nottingham", "G1" if one[one["tipo"] == "grado_nottingham"][ "valor_codigo"].iloc[0] != "G1" else "G3", first=one["fecha_indice"].iloc[0])], columns=SCHEMA.names) table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["ki67_cuts"], - CONFIG["result_days"]) + CONFIG["result_days"], CONFIG["size_cuts"]) row = table.loc[1] reported = one[one["tipo"] == "grado_nottingham"]["valor_codigo"].iloc[0] - assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"]) == ( - "DUCTAL_INFILTRANTE", reported, "H1", "14-19") + assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"], row["size_group"]) == ( + "DUCTAL_INFILTRANTE", reported, "H1", "14-19", "20-49") assert row["er"] == one[one["tipo"] == "receptor_estrogeno"]["valor_codigo"].iloc[0] == row["pr"] born, index = date(1960, 1, 1) + timedelta(days=30), table.loc[1, "fecha_indice"].date() age = (index - born).days / 365.25 @@ -155,7 +156,7 @@ def labelled(cohort_frame): """The 240 indexed members with their covariates and outcome, as the dataflow labels them.""" indexed = _indexed(cohort_frame) indexed = indexed[indexed["pac_id"] <= N] - features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"]) + features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"], CONFIG["size_cuts"]) return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index() @@ -198,7 +199,7 @@ def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leave fitted = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES], labelled[["months", "event"]]) pipeline = Pipeline([("members", MemberFeatures(dict(CONFIG["index"]), WINDOW, tuple(CONFIG["age_cuts"]), - tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"])), + tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"], tuple(CONFIG["size_cuts"]))), ("survival", fitted)]) scored = pipeline.predict_proba(cohort_frame) @@ -249,7 +250,7 @@ def population_record(cohort_frame): """The `curvas` record the dataflow publishes for the 240 indexed members, with a small bootstrap to stay quick.""" config = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}} dr = dataflow(*SCENARIO.modules, config=config) - return dr.execute(["population"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population"]["curvas"] + return dr.execute(["population_curves"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population_curves"]["curvas"] def test_the_population_record_has_the_figures_curves_points_and_labels(population_record): @@ -285,3 +286,50 @@ def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking) record = json.loads(content) assert "analisis/curvas.json" in files and name == "curvas.json" assert record["horizons_months"] == [6, 12, 18] and set(record["points"]) == {"LR", "HBN", "COMB"} + + +@pytest.fixture(scope="module") +def development_record(cohort_frame): + """The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget.""" + config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30, + "proposals_max_seconds": 20, "restarts": 1}} + dr = dataflow(*SCENARIO.modules, config=config) + return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"] + + +def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record): + """Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation + publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's + exception escapes the node, which would stop a version from training.""" + assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"] + assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"} + assert "Estadio_cat" in development_record["variables_no_disponibles"] + + +def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort(): + """Pins down: on 600 members with varied covariates all six SEER stages run and publish their tables and figures. + Fails if a stage errors on a cohort of this shape or stops writing what the dashboard reads.""" + from models.cama.survival import development as dev + + rng = np.random.default_rng(11) + n = 600 + grade = rng.choice(["G1", "G2", "G3"], n, p=[0.2, 0.5, 0.3]) + er = rng.choice(["POSITIVO", "NEGATIVO"], n, p=[0.7, 0.3]) + risk = 0.03 * np.exp(1.0 * (grade == "G3") - 0.6 * (er == "POSITIVO")) + months = np.minimum(rng.exponential(1 / risk), 30).round() + members = pd.DataFrame({ + "fecha_indice": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 540, n), unit="D"), + "months": months.astype(int), "event": rng.random(n) < 1 - np.exp(-risk * 24), + "age_years": rng.normal(58, 12, n).clip(25, 90), "size_mm": rng.integers(5, 70, n).astype(float), + "histologic_type": rng.choice(["8500/3", "8520/3"], n, p=[0.85, 0.15]), "grade": grade, "er": er, + "pr": rng.choice(["POSITIVO", "NEGATIVO"], n), "her2": rng.choice(["H0", "H1", "H2", "H3"], n), + "ki67_group": rng.choice(["<14", "14-19", "≥20"], n)}) + members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24) + settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30, + "proposals_max_seconds": 20, "restarts": 1} + + r = dev.development(members, settings)["desarrollo"] + + assert r["errores"] == {}, r["errores"] + assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"]) + assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())