diff --git a/libs/tea b/libs/tea index 05ee029..fcf8e6e 160000 --- a/libs/tea +++ b/libs/tea @@ -1 +1 @@ -Subproject commit 05ee02990c6043148d74a192d4ded074847d2fe5 +Subproject commit fcf8e6ef03b54d0c1bbd7447f0e9a9009ffe31fe diff --git a/models/__main__.py b/models/__main__.py index 1bd308e..5a0cf9c 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -171,6 +171,30 @@ def _tea_analyze(args: argparse.Namespace) -> int: return 1 if s.failed else 0 +def _tea_score_ados2(args: argparse.Namespace) -> int: + """The ADOS-2 CSS and classification from the stored item scores (`models.ados2_scoring`).""" + from models.ados2_scoring import score_pending + + s = score_pending(overwrite=args.all) + print(f"{s.evaluations} evaluations: {s.scored} scored, {s.unscored} without enough to score") + return 0 + + +def _tea_relate_ados2(args: argparse.Namespace) -> int: + """The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`).""" + from models.ados2_relation import relate + + s = relate() + if s.unchanged: + print(f"{s.children} children: the cohort is that of {s.version}, nothing written") + elif s.version is None: + print(f"{s.children} children: no association could be estimated, nothing written") + else: + print(f"{s.version}: {s.children} children, level {s.level}, {s.associations} associations, " + f"{s.scored} patient probabilities") + return 0 + + def _tea_export_baselines(args: argparse.Namespace) -> int: """The trained age baselines as one bundle (`models.tea.eeg.bundle`).""" from models.tea.eeg.bundle import BundleError, export @@ -521,6 +545,13 @@ def build_parser() -> argparse.ArgumentParser: analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto", help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process") analyze.set_defaults(run=_tea_analyze) + score_ados2 = tea_actions.add_parser( + "score-ados2", help="compute the ADOS-2 CSS and classification from the item scores, module and age") + score_ados2.add_argument("--all", action="store_true", help="also recompute values already stored") + score_ados2.set_defaults(run=_tea_score_ados2) + relate_ados2 = tea_actions.add_parser( + "relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version") + relate_ados2.set_defaults(run=_tea_relate_ados2) export_baselines = tea_actions.add_parser( "export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child") export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)") diff --git a/models/ados2_relation.py b/models/ados2_relation.py new file mode 100644 index 0000000..ad3dcfc --- /dev/null +++ b/models/ados2_relation.py @@ -0,0 +1,189 @@ +"""The ADOS-2 association against the TEA database: the cohort from bronze, the `tea` library's fit, and its rows in +`relacion_ados2` and `relacion_ados2_paciente`. + +The cohort is one row per child with a valid analysed EEG and an ADOS-2: the child's first valid EEG with some +predictor (its zone z and metric z, its age) and first ADOS-2 (module, item scores, CSS). Every valid EEG of those +children is then scored, so the study's EEG has its probabilities whichever EEG it is. + +A fit is a version `tea--`: the time keeps versions in order (the gold view shows the +greatest), the fingerprint is that of the scored EEGs, which of them the fit used, and the module and level. Inputs +equal to the latest version's write nothing. Versions are +written unvalidated (`rel_validado` 0) until the domain expert validates them. +""" +from __future__ import annotations + +import hashlib +import math +from dataclasses import dataclass +from datetime import datetime, timezone + +import pandas as pd +from sqlmodel import Session, col, select + +from core.tea.enums import NivelRelacionAdos2 +from core.tea.models import ( + ADOS2_ITEMS, + Ados2, + Eeg, + EegMetrica, + EegMetricaZona, + RelacionAdos2, + RelacionAdos2Paciente, +) +from models.tea.ados2.settings import Settings, settings + +VERSION_PREFIX = "tea-" +LEVELS = {"item": NivelRelacionAdos2.ITEM.value, "domain": NivelRelacionAdos2.DOMINIO.value} +ZONED = ("spikes", "spindles") + + +@dataclass +class Summary: + version: str | None = None + level: str | None = None + children: int = 0 + associations: int = 0 + scored: int = 0 + unchanged: bool = False + + +def _predictors(session: Session, eeg_ids: list[str], s: Settings) -> pd.DataFrame: + """One row per EEG with a column per predictor: `z__` and `z_`.""" + codes = {code: b for b, code in s.biomarkers.items()} + metrics = session.exec(select(EegMetrica.met_id, EegMetrica.met_eeg_id, EegMetrica.met_codigo, EegMetrica.met_z) + .where(col(EegMetrica.met_eeg_id).in_(eeg_ids)) + .where(col(EegMetrica.met_codigo).in_(list(codes)))).all() + values: dict[str, dict[str, float]] = {e: {} for e in eeg_ids} + zoned = {} + for met_id, eeg_id, code, z in metrics: + biomarker = codes[code] + if biomarker in ZONED: + zoned[met_id] = (eeg_id, biomarker) + elif z is not None: + values[eeg_id][f"z_{biomarker}"] = z + if zoned: + for met_id, zone, z in session.exec(select(EegMetricaZona.mez_met_id, EegMetricaZona.mez_zona, + EegMetricaZona.mez_z) + .where(col(EegMetricaZona.mez_met_id).in_(list(zoned)))).all(): + if z is not None: + eeg_id, biomarker = zoned[met_id] + values[eeg_id][f"z_{biomarker}_{zone}"] = z + return pd.DataFrame.from_dict(values, orient="index") + + +def cohort(session: Session, s: Settings) -> tuple[pd.DataFrame, pd.DataFrame]: + """The fit's cohort (the first valid EEG of each child with an ADOS-2) and the table to score (every valid EEG + of those children), both keyed by EEG id, in the library's columns.""" + eegs = session.exec(select(Eeg.eeg_id, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, Eeg.eeg_edad_meses) + .where(Eeg.eeg_valido == 1).where(col(Eeg.eeg_edad_meses).is_not(None))).all() + ados = session.exec(select(Ados2).where(col(Ados2.ado_pac_id).is_not(None))).all() + first: dict[int, Ados2] = {} + for a in sorted(ados, key=lambda a: (a.ado_fecha is None, a.ado_fecha, a.ado_id)): + first.setdefault(a.ado_pac_id, a) + rows = [] + for eeg_id, pac_id, fecha, edad in eegs: + a = first.get(pac_id) + if a is None: + continue + rows.append({"key": eeg_id, "pac_id": pac_id, "fecha": fecha, "age_months": float(edad), + "ados_module": a.ado_modulo, "css": a.ado_css, + **{code: getattr(a, f"ado_{code}") for code in ADOS2_ITEMS}}) + columns = ["key", "pac_id", "fecha", "age_months", "ados_module", "css", *ADOS2_ITEMS] + scored = pd.DataFrame(rows, columns=columns) + if len(scored): + z = _predictors(session, scored["key"].tolist(), s) + scored = scored.join(z, on="key") + scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(drop=True) + predictors = [c for c in scored.columns if c.startswith("z_")] + with_predictors = scored[predictors].notna().any(axis=1) if predictors else pd.Series(False, index=scored.index) + fit = scored[with_predictors].drop_duplicates("pac_id").reset_index(drop=True) + return fit.drop(columns=["pac_id", "fecha"]), scored.drop(columns=["pac_id", "fecha"]) + + +def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str: + """Eight hex digits of the scored EEGs, which of them the fit used, and `module` (name, version, level); + independent of row and column order.""" + t = scored.assign(_fit=scored["key"].isin(fit["key"])) + t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True) + text = module + "\n" + t.to_csv(index=False, float_format="%.6g") + return hashlib.sha256(text.encode()).hexdigest()[:8] + + +def _latest(session: Session) -> str | None: + versions = session.exec(select(RelacionAdos2.rel_version) + .where(col(RelacionAdos2.rel_version).startswith(VERSION_PREFIX))).all() + return max(versions, default=None) + + +def _finite(value) -> float | None: + """The value as a float, or none when missing or infinite (an open interval): not every engine stores inf.""" + if value is None or pd.isna(value): + return None + value = float(value) + return value if math.isfinite(value) else None + + +def _row_id(*parts) -> str: + from models.eeg_analysis import row_id + + return row_id("relacion-ados2", *parts) + + +def rows(module, version: str, associations: pd.DataFrame, scores: pd.DataFrame, + s: Settings) -> tuple[list[RelacionAdos2], list[RelacionAdos2Paciente]]: + """The estimated associations as `relacion_ados2` rows and their scores as `relacion_ados2_paciente` rows.""" + level = LEVELS[module.fitted["level"]] + # An odds ratio rounded to 0 or never estimated is no association to show (`rel_or` is above 0). + estimated = associations[associations["odds_ratio"].astype(float) > 0] + models, ids = [], {} + for a in estimated.itertuples(): + rel_id = _row_id(version, a.biomarker, a.zone, a.outcome_code) + ids[a.biomarker, a.zone, a.outcome_code] = rel_id + models.append(RelacionAdos2( + rel_id=rel_id, rel_version=version, rel_nivel=level, rel_validado=0, + rel_n_cohorte=int(module.fitted["n"]), rel_biomarcador=s.biomarkers[a.biomarker], rel_zona=a.zone, + rel_tipo=LEVELS[a.kind], rel_resultado=a.outcome_code, rel_evento=a.event, rel_or=_finite(a.odds_ratio), + rel_ic_inf=_finite(a.ci_low), rel_ic_sup=_finite(a.ci_high), rel_q=_finite(a.q))) + patients = [] + for r in scores.itertuples(): + rel_id = ids.get((r.biomarker, r.zone, r.outcome_code)) + if rel_id is None: + continue + patients.append(RelacionAdos2Paciente( + rap_id=_row_id(rel_id, r.key), rap_rel_id=rel_id, rap_eeg_id=r.key, rap_valor_z=float(r.z), + rap_probabilidad=float(r.probability), rap_probabilidad_referencia=float(r.reference_probability))) + return models, patients + + +def _now() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def relate(*, settings_: Settings | None = None, at: datetime | None = None) -> Summary: + """Fits the association on the current cohort and writes it as a new version, unless the cohort is the latest + version's. Nothing is written when no association could be estimated.""" + from tea.pipeline import registry + + from persistance.tea import relacion_ados2_repository + + s = settings_ or settings() + with relacion_ados2_repository.open_session() as session: + fit, scored = cohort(session, s) + summary = Summary(children=len(fit)) + if not len(fit): + return summary + module = type(registry.association(s.association, s.impl))(level=s.level) + mark = fingerprint(fit, scored, f"{module.name}/{module.version}/{module.impl}/{s.level}") + latest = _latest(session) + if latest is not None and latest.endswith(f"-{mark}"): + return Summary(version=latest, children=len(fit), unchanged=True) + module.fit(fit) + version = f"{VERSION_PREFIX}{(at or _now()):%Y%m%dT%H%M%S}-{mark}" + models, patients = rows(module, version, module.associations(), module.score(scored), s) + summary.level = module.fitted["level"] + if not models: + return summary + session.add_all([*models, *patients]) + session.commit() + summary.version, summary.associations, summary.scored = version, len(models), len(patients) + return summary diff --git a/models/ados2_scoring.py b/models/ados2_scoring.py new file mode 100644 index 0000000..93c5dc8 --- /dev/null +++ b/models/ados2_scoring.py @@ -0,0 +1,61 @@ +"""The ADOS-2 CSS and classification against the TEA database: each evaluation's item scores, module, algorithm and +the child's age at the evaluation go through `tea.scoring`, and the result is written to `ado_css` and +`ado_clasificacion`. + +A value a source already gave is kept unless `overwrite` is set. An evaluation without items or module is left as +it is. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from sqlmodel import Session, select + +from core.tea.models import ADOS2_ITEMS, Ados2, Pacientes +from tea.scoring import score + +DAYS_PER_MONTH = 30.4375 + + +@dataclass +class Summary: + evaluations: int = 0 + scored: int = 0 + unscored: int = 0 + + +def age_months(born, on) -> float | None: + if born is None or on is None: + return None + return (on - born).days / DAYS_PER_MONTH + + +def score_all(session: Session, *, overwrite: bool = False) -> Summary: + """Scores every evaluation in the session's database and commits.""" + births = dict(session.exec(select(Pacientes.pac_id, Pacientes.pac_fecha_nacimiento)).all()) + summary = Summary() + for row in session.exec(select(Ados2)).all(): + summary.evaluations += 1 + if not overwrite and row.ado_css is not None and row.ado_clasificacion is not None: + continue + items = {code: getattr(row, f"ado_{code}") for code in ADOS2_ITEMS} + result = score(row.ado_modulo, items, age_months=age_months(births.get(row.ado_pac_id), row.ado_fecha), + algorithm=row.ado_algoritmo) + if result is None or (result.css is None and result.classification is None): + summary.unscored += 1 + continue + if overwrite or row.ado_css is None: + row.ado_css = result.css if result.css is not None else row.ado_css + if overwrite or row.ado_clasificacion is None: + row.ado_clasificacion = result.classification or row.ado_clasificacion + session.add(row) + summary.scored += 1 + session.commit() + return summary + + +def score_pending(*, overwrite: bool = False) -> Summary: + from persistance.tea import relacion_ados2_repository + + with relacion_ados2_repository.open_session() as session: + return score_all(session, overwrite=overwrite) diff --git a/models/cacu/cancer_pim/__init__.py b/models/cacu/cancer_pim/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/cacu/cancer_pim/model.toml b/models/cacu/cancer_pim/model.toml new file mode 100644 index 0000000..5591444 --- /dev/null +++ b/models/cacu/cancer_pim/model.toml @@ -0,0 +1,72 @@ +domain = "cacu" +scenario = "cancer_pim" +cohort = "cacu/cohorte_vigilancia" +outcome = "cancer" +# 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.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"] +description = """ +Prototipo: riesgo acumulado de cáncer cervicouterino (biopsia de carcinoma) en la visita índice y a 1, 3 y 5 años, con un \ +modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \ +citología índice en las categorías de KPNC como covariable, como la columna de cáncer de las tablas de KPNC (Cheung et al. 2020), \ +con la misma cohorte y la misma fecha índice que el modelo de CIN2+ de vigilancia. Sin \ +corrección del sesgo de verificación ni validación clínica.""" + +# The dataflow's config (`with_config`); each key is an input of the nodes that name it. +# What the model's number is, as the patient's screen and the governance pages show it. +[estimand] +quantity = "Probabilidad" +description = "Probabilidad de que la paciente tenga cáncer cervicouterino en la fecha índice o lo desarrolle antes de cada horizonte." +outcome = "Cáncer: biopsia de carcinoma" +index_date = "la última citología con resultado de citología y de VPH" +horizons_unit = "años" +covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC" + +[config] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +# The level of each risk's interval (delta method), given with the estimate; none gives no interval. +risk_interval_level = 0.95 +# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results) +# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's +# index (the first cytology in the window). None predicts from the cohort's index too. +prediction_index = "ultima_citologia" +event_grades = ["CARCINOMA"] +train_fraction = 0.7 +# Provisional: a carcinoma biopsy within this window of the index date counts as prevalent. +prevalent_window_months = 6 +# The index sample's results: the first ones within these days of the index date. +index_sample_days = 30 +# The results that make a visit free of the outcome without a biopsy: every key with one of its values (KPNC: HPV-negative +# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528). +known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] } +# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric +# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The +# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC +# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6). +incidence = { family = "ispline", knots = 3, order = 4 } +# One mixture per value of these features; the other features enter the prevalence, and those listed here the +# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020). +strata = ["hpv_positive"] +incidence_features = ["cytology"] +# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance. +history = {} +# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and +# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma +# has no KPNC row: it goes with the high-grade and malignant results. +# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance +# cohort, applied in the pipeline. The recruitment window is the source cohort's. +[config.index] +kind = "primera_citologia" +event_grades = ["CARCINOMA"] +# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded; +# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20). +observacion_previa_minima_dias = 0 + +[config.cytology] +NILM = ["NORMAL"] +ASC-US = ["ASC-US"] +LSIL = ["LIEBG"] +ASC-H = ["ASC-H"] +AGC = ["AGC"] +"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"] diff --git a/models/cacu/cin2_pim/model.py b/models/cacu/cin2_pim/model.py index e4b8199..04e763d 100644 --- a/models/cacu/cin2_pim/model.py +++ b/models/cacu/cin2_pim/model.py @@ -22,10 +22,13 @@ frame. Settings arrive as config (`model.toml`), the cohort through a loader, an driver's saver (`models.dags.training`). """ +import copy + import numpy as np import pandas as pd import pandera.pandas as pandera from hamilton.function_modifiers import extract_fields +from scipy.stats import norm from sklearn.base import BaseEstimator, TransformerMixin from sklearn.metrics import roc_auc_score from sklearn.pipeline import Pipeline @@ -36,6 +39,10 @@ from models.io.contracts import DAYS_PER_YEAR from models.steps import model_fitting FEATURES = ["cytology", "hpv_positive"] +# The member's prediction index (days since 1970-01-01), when `IndexResults` picks it: the first column of the output. +INDEX_COLUMN = "fecha_indice_modelo" +EPOCH = pd.Timestamp("1970-01-01") +PREDICTION_INDEXES = ("ultima_citologia",) def _features(history: dict) -> list[str]: @@ -168,12 +175,13 @@ class PrevalenceIncidenceMixture(BaseEstimator): """ def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(), - incidence=None, levels=None): + incidence=None, levels=None, interval_level=None): self.horizons_years = horizons_years self.incidence_features = incidence_features self.strata = strata self.incidence = incidence self.levels = levels + self.interval_level = interval_level def _baseline(self, y: pd.DataFrame): settings = dict(self.incidence or {"family": "weibull"}) @@ -232,17 +240,59 @@ class PrevalenceIncidenceMixture(BaseEstimator): self.converged_ = all(f["converged"] for f in self.fits_.values()) return self + def risk_with_variance(self, key: tuple, prevalence: np.ndarray, incidence: np.ndarray, years) -> tuple: + """CR(t) of each design row of stratum `key` at `years`, and its delta-method variance (central differences + of CR in every parameter, with the fit's inverse Hessian).""" + fit = self.fits_[key] + n_x, n_z = len(fit["theta"]), len(fit["beta"]) + + def risk(params): + found = {"theta": params[:n_x], "beta": params[n_x:n_x + n_z], "baseline": fit["baseline"], + "baseline_params": params[n_x + n_z:]} + return likelihood.cumulative_risk(found, prevalence, incidence, years) + + params = np.asarray(fit["params"], dtype=float) + gradient = np.empty((len(params), len(prevalence), len(years))) + for k in range(len(params)): + step = 1e-5 * max(1.0, abs(params[k])) + up, down = params.copy(), params.copy() + up[k] += step + down[k] -= step + gradient[k] = (risk(up) - risk(down)) / (2 * step) + covariance = np.nan_to_num(np.asarray(fit["covariance"], dtype=float), nan=0.0) + return risk(params), np.maximum(np.einsum("kij,kl,lij->ij", gradient, covariance, gradient), 0.0) + def predict_proba(self, X: pd.DataFrame) -> np.ndarray: - """One column per horizon: CR(t). The column of t = 0 is the prevalence.""" - risks = np.full((len(X), len(self.horizons_years)), np.nan) + """One column per horizon: CR(t). The column of t = 0 is the prevalence. With `INDEX_COLUMN` in `X`, its days + since 1970-01-01 come first and a member without that date gets no risk. With `interval_level`, two more + blocks of as many columns: the interval's lower and upper ends, CR · exp(∓z · SE / CR) (delta method on the + log scale, clipped to [0, 1]).""" + if INDEX_COLUMN in X.columns: + dates = pd.to_datetime(X[INDEX_COLUMN]) + risks = self.predict_proba(X.drop(columns=INDEX_COLUMN)) + risks[dates.isna().to_numpy()] = np.nan + return np.column_stack([(dates - EPOCH).dt.days.to_numpy(dtype=float), risks]) + h = len(self.horizons_years) + risks = np.full((len(X), 3 * h if self.interval_level else h), np.nan) + z = norm.ppf(0.5 + self.interval_level / 2) if self.interval_level else None for key, index in self._groups(X): if key not in self.fits_: continue members = X.iloc[index] placed = self._placed(members, self.seen_[key]) prevalence, incidence = self._design(members[placed], self.seen_[key]) - risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, - self.horizons_years) + rows = index[placed] + if not self.interval_level: + risks[rows] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, self.horizons_years) + continue + design = np.column_stack([prevalence, incidence]) + unique, inverse = np.unique(design, axis=0, return_inverse=True) + point, variance = self.risk_with_variance(key, unique[:, :prevalence.shape[1]], + unique[:, prevalence.shape[1]:], self.horizons_years) + relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) + band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1), + np.clip(point * np.exp(z * relative), 0, 1)]) + risks[rows] = band[inverse.ravel()] return risks @@ -287,23 +337,76 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame, return found -class IndexResults(TransformerMixin, BaseEstimator): - """A build's long frame to the features of each member, in `pac_id` order. Learns nothing.""" +RESULT_TYPES = ("bethesda", "glandular", "vph") +REFERRED = ("colposcopia", "biopsia") # a patient with either is past the surveillance model - def __init__(self, index_sample_days: int = 30, cytology=None, history=None): + +def latest_precolposcopy_cytology(cohort: pd.DataFrame) -> pd.DataFrame: + """Per patient with no colposcopy and no biopsy in the frame, the date of her latest cytology sample with a + cytology result (Bethesda or glandular) and an HPV result, linked to it by its source row: `pac_id`, `fecha`. A + sample still missing either result gives way to the one before it; a patient with none, or referred, is absent. + Self-contained: it runs inside the registered model, without this repository.""" + referred = set(cohort.loc[cohort["tipo"].isin(REFERRED), "pac_id"]) + key = ["pac_id", "fuente_tabla", "fuente_id"] + samples = cohort.loc[(cohort["tipo"] == "citologia") & ~cohort["pac_id"].isin(referred), [*key, "fecha"]] + results = cohort[cohort["tipo"].isin(RESULT_TYPES) & cohort["valor_codigo"].notna()] + has = results.pivot_table(index=key, columns="tipo", values="valor_codigo", aggfunc="first") + has = has.reindex(columns=list(RESULT_TYPES)) + complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["vph"].notna()].index + samples = samples.set_index(key) + samples = samples[samples.index.isin(complete)].reset_index() + latest = samples.sort_values(["pac_id", "fecha", "fuente_id"]).groupby("pac_id", as_index=False).last() + return latest[["pac_id", "fecha"]].reset_index(drop=True) + + +def latest_index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict, + history: dict | None = None) -> pd.DataFrame: + """`index_results` at each member's latest complete cytology before any colposcopy + (`latest_precolposcopy_cytology`), with that date in `INDEX_COLUMN`; one row per member in `pac_id` + order, with no features and no date for a member without such a sample.""" + chosen = latest_precolposcopy_cytology(cohort).set_index("pac_id")["fecha"] + members = pd.DataFrame({"pac_id": sorted(cohort["pac_id"].unique())}) + eligible = cohort[cohort["pac_id"].isin(chosen.index)] + if len(eligible): + found = index_results(eligible.assign(fecha_indice=eligible["pac_id"].map(chosen)), index_sample_days, + cytology, history) + members = members.merge(found[["pac_id", *_features(history)]], on="pac_id", how="left") + else: + members = members.assign(**{f: np.nan for f in _features(history)}) + members[INDEX_COLUMN] = pd.to_datetime(members["pac_id"].map(chosen)) + return members + + +class IndexResults(TransformerMixin, BaseEstimator): + """A build's long frame to the features of each member, in `pac_id` order. Learns nothing. By default at the + cohort's index date, as in training; with `prediction_index = "ultima_citologia"` at each member's latest + complete cytology before any colposcopy (`latest_index_results`), with that date as `INDEX_COLUMN`.""" + + def __init__(self, index_sample_days: int = 30, cytology=None, history=None, prediction_index=None): self.index_sample_days = index_sample_days self.cytology = cytology self.history = history + self.prediction_index = prediction_index def fit(self, X, y=None): return self def transform(self, X: pd.DataFrame) -> pd.DataFrame: - return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)] + if self.prediction_index is None: + return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)] + if self.prediction_index not in PREDICTION_INDEXES: + raise ValueError(f"unknown prediction_index {self.prediction_index!r}; known: {PREDICTION_INDEXES}") + found = latest_index_results(X, self.index_sample_days, self.cytology, self.history) + return found[[*_features(self.history), INDEX_COLUMN]].reset_index(drop=True) def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict, - history: dict) -> Pipeline: - """What's registered: the fitted mixture behind `IndexResults`.""" - return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)), - ("mixture", fitted_mixture)]) + history: dict, risk_interval_level: float | None = None, + prediction_index: str | None = None) -> Pipeline: + """What's registered: the fitted mixture behind `IndexResults`, giving each risk's interval at + `risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run), from the + index `prediction_index` names (the cohort's when none).""" + registered = copy.copy(fitted_mixture) + registered.interval_level = risk_interval_level + return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history, prediction_index)), + ("mixture", registered)]) diff --git a/models/cacu/cin2_pim/model.toml b/models/cacu/cin2_pim/model.toml index 7dd38df..1febbc9 100644 --- a/models/cacu/cin2_pim/model.toml +++ b/models/cacu/cin2_pim/model.toml @@ -13,8 +13,23 @@ citología índice en las categorías de KPNC como covariable (Cheung et al. 202 corrección del sesgo de verificación ni validación clínica.""" # The dataflow's config (`with_config`); each key is an input of the nodes that name it. +# What the model's number is, as the patient's screen and the governance pages show it. +[estimand] +quantity = "Probabilidad" +description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." +outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" +index_date = "la última citología con resultado de citología y de VPH" +horizons_unit = "años" +covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC" + [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +# The level of each risk's interval (delta method), given with the estimate; none gives no interval. +risk_interval_level = 0.95 +# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results) +# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's +# index (the first cytology in the window). None predicts from the cohort's index too. +prediction_index = "ultima_citologia" event_grades = ["LIEAG", "CIS", "CARCINOMA"] train_fraction = 0.7 # Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent. diff --git a/models/cacu/cin2_pim/report.py b/models/cacu/cin2_pim/report.py index 2f28b64..d2e1e3e 100644 --- a/models/cacu/cin2_pim/report.py +++ b/models/cacu/cin2_pim/report.py @@ -32,9 +32,13 @@ GRID_STEP = 0.1 # years between the points of the model's curve UNKNOWN = "NA" NOTICE = "Prototipo sin validación clínica." METHODS = { - "empirica": "Turnbull (estimador no paramétrico de máxima verosimilitud con censura por intervalos, autoconsistencia): " - "prevalente = masa en 0, libre de CIN2+ = censura en (l, r], basal desconocida = [0, r]; banda e " - "varianza por bootstrap de las pacientes de la combinación", + "empirica": "curva empírica de Turnbull: el estimador no paramétrico del riesgo acumulado cuando solo se sabe entre " + "qué dos visitas apareció el CIN2+ (censura por intervalos), calculado con el algoritmo EM de Turnbull " + "(1976). Cada paciente aporta el intervalo donde pudo estar su evento: un caso prevalente, el instante " + "0 (así la curva arranca en la prevalencia observada, comparable con la del modelo); una paciente " + "vista libre de CIN2+, el intervalo entre su último negativo y su biopsia CIN2+ (o sin fin); una sin " + "negativo previo, desde 0 hasta su biopsia. Banda y varianza por bootstrap de las pacientes de la " + "combinación", "modelo": "mezcla prevalencia-incidencia reajustada en todas las pacientes codificadas; banda por método delta sobre " "la verosimilitud (inversa del Hessiano numérico, gradiente numérico del riesgo acumulado), en escala log; " "un parámetro en la frontera cuenta como fijo", @@ -179,45 +183,52 @@ def _label(combination: dict) -> str: return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items()) +def _percent(values) -> list[float]: + return [100 * v for v in values] + + def _figure(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24): """The figure: one panel per combination (the `report_panels` largest), Turnbull's step curve with its band and the - model's curve with its band (a Plotly `Figure`; the page and the notebook draw it).""" + model's curve with its band (a Plotly `Figure`; the page and the notebook draw it), in percent like the table and + the patient's risk. Each panel has its own y scale, so a combination of low risk isn't flattened by one of high + risk.""" import plotly.graph_objects as go from plotly.subplots import make_subplots shown = combination_risks[:report_panels] columns = 3 rows = max(1, -(-len(shown) // columns)) - figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True, + figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=False, subplot_titles=[f"{_label(r['combination'])}
n = {r['n']}, prevalentes = {r['prevalent']}, " f"incidentes = {r['incident']}" for r in shown]) for k, record in enumerate(shown): row, col, first = k // columns + 1, k % columns + 1, k == 0 emp, model = record["empirical"], record["model"] if emp["low"] is not None: - figure.add_trace(go.Scatter(x=emp["years"], y=emp["high"], mode="lines", line={"width": 0, "shape": "hv"}, + figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["high"]), mode="lines", line={"width": 0, "shape": "hv"}, hoverinfo="skip", showlegend=False), row=row, col=col) - figure.add_trace(go.Scatter(x=emp["years"], y=emp["low"], mode="lines", line={"width": 0, "shape": "hv"}, + figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["low"]), mode="lines", line={"width": 0, "shape": "hv"}, fill="tonexty", fillcolor="rgba(120,130,140,0.30)", hoverinfo="skip", name="IC 95 % Turnbull (bootstrap)", legendgroup="emp_band", showlegend=first), row=row, col=col) - figure.add_trace(go.Scatter(x=emp["years"], y=emp["CR"], mode="lines", line={"color": "#242628", "width": 2, + figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["CR"]), mode="lines", line={"color": "#242628", "width": 2, "shape": "hv"}, name="Turnbull", legendgroup="emp", showlegend=first, - hovertemplate="%{x:.1f} años: %{y:.3f}Turnbull"), row=row, col=col) + hovertemplate="%{x:.1f} años: %{y:.2f} %Turnbull"), row=row, col=col) if model is not None: - figure.add_trace(go.Scatter(x=model["years"], y=model["high"], mode="lines", line={"width": 0}, + figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["high"]), mode="lines", line={"width": 0}, hoverinfo="skip", showlegend=False), row=row, col=col) - figure.add_trace(go.Scatter(x=model["years"], y=model["low"], mode="lines", line={"width": 0}, + figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["low"]), mode="lines", line={"width": 0}, fill="tonexty", fillcolor="rgba(111,53,165,0.18)", hoverinfo="skip", name="IC 95 % modelo (método delta)", legendgroup="model_band", showlegend=first), row=row, col=col) - figure.add_trace(go.Scatter(x=model["years"], y=model["CR"], mode="lines", line={"color": "#6f35a5", + figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["CR"]), mode="lines", line={"color": "#6f35a5", "width": 2}, name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first, - hovertemplate="%{x:.1f} años: %{y:.3f}modelo"), row=row, col=col) + hovertemplate="%{x:.1f} años: %{y:.2f} %modelo"), row=row, col=col) figure.update_xaxes(range=[0, max(horizons_years) + 0.05]) - figure.update_yaxes(rangemode="tozero") + figure.update_yaxes(rangemode="tozero", ticksuffix=" %") + figure.update_yaxes(title_text="Riesgo acumulado (%)", col=1) figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110}, title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables
" f"Años desde la fecha índice; {NOTICE}"}, diff --git a/models/cacu/cin2_pim_post_colposcopy/model.toml b/models/cacu/cin2_pim_post_colposcopy/model.toml index d65bb39..f0acde0 100644 --- a/models/cacu/cin2_pim_post_colposcopy/model.toml +++ b/models/cacu/cin2_pim_post_colposcopy/model.toml @@ -12,8 +12,19 @@ de la referencia (bajo o alto), con el VPH y la citología (tres categorías de como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \ sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+.""" +# What the model's number is, as the patient's screen and the governance pages show it. +[estimand] +quantity = "Probabilidad" +description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." +outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" +index_date = "la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+" +horizons_unit = "años" +covariates = "grado de la citología que la refirió a colposcopía (un ajuste por grado), VPH y citología de la visita índice en tres categorías de KPNC" + [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +# The level of each risk's interval (delta method), given with the estimate; none gives no interval. +risk_interval_level = 0.95 event_grades = ["LIEAG", "CIS", "CARCINOMA"] train_fraction = 0.7 prevalent_window_months = 6 diff --git a/models/cacu/cin2_pim_post_treatment/model.toml b/models/cacu/cin2_pim_post_treatment/model.toml index 6070d92..6264b97 100644 --- a/models/cacu/cin2_pim_post_treatment/model.toml +++ b/models/cacu/cin2_pim_post_treatment/model.toml @@ -12,8 +12,19 @@ base, con el VPH y la citología (tres categorías de KPNC) de esa citología co la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \ la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación.""" +# What the model's number is, as the patient's screen and the governance pages show it. +[estimand] +quantity = "Probabilidad" +description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." +outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" +index_date = "la primera citología después del tratamiento" +horizons_unit = "años" +covariates = "VPH y citología de la citología índice en tres categorías de KPNC" + [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +# The level of each risk's interval (delta method), given with the estimate; none gives no interval. +risk_interval_level = 0.95 event_grades = ["LIEAG", "CIS", "CARCINOMA"] train_fraction = 0.7 prevalent_window_months = 6 diff --git a/models/cacu/survival/estimator.py b/models/cacu/survival/estimator.py index 4468266..d028a39 100644 --- a/models/cacu/survival/estimator.py +++ b/models/cacu/survival/estimator.py @@ -105,16 +105,35 @@ class MemberFeatures(TransformerMixin, BaseEstimator): return table[[*FEATURES, INDEX_COLUMN]] +def _combinations(X: pd.DataFrame) -> pd.DataFrame: + """Each member's combination of the covariates, as `encode` reads them (a missing value is `UNKNOWN`).""" + return X[FEATURES].astype(object).where(X[FEATURES].notna(), UNKNOWN).astype(str).reset_index(drop=True) + + +def _frame(combinations: pd.DataFrame) -> pd.DataFrame: + return combinations.replace(UNKNOWN, None) + + class IntervalSurvival(BaseEstimator): """CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked; the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with `months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With `INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member - without one) and her mortality is empty too.""" + without one) and her mortality is empty too. - def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)): + With `interval_level`, two more blocks follow the mortality: its interval's lower and upper ends. The covariates + are categorical, so every member of a combination gets the same mortality, and so the same interval: `fit` keeps + one per combination of the training members (`interval_table_`), the percentiles of the mortality of + `interval_replicas` refits of this same model on bootstrap resamples of them (seeded by `seed`). A combination the + training never saw has no interval.""" + + def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0), interval_level=None, interval_replicas=100, + seed=0): self.survival = survival self.horizons_years = horizons_years + self.interval_level = interval_level + self.interval_replicas = interval_replicas + self.seed = seed def fit(self, X: pd.DataFrame, y: pd.DataFrame): s = survival_settings(self.survival) @@ -130,8 +149,30 @@ class IntervalSurvival(BaseEstimator): self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), [] self.fitted_ = sm.fit_intervals(cohort, s, everyone, None) self.levels_ = cohort.levels + self.interval_table_ = self._interval_table(X, y) if self.interval_level else {} return self + def _interval_table(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[tuple, tuple[list, list]]: + combinations = _combinations(X).drop_duplicates() + rng = np.random.default_rng(self.seed) + replicas = [] + for _ in range(int(self.interval_replicas)): + rows = rng.integers(0, len(X), len(X)) + refit = IntervalSurvival(self.survival, self.horizons_years) + refit.fit(X.iloc[rows].reset_index(drop=True), y.iloc[rows].reset_index(drop=True)) + replicas.append(1.0 - refit.survival_proba(_frame(combinations))) + tail = 50 * (1 - self.interval_level) + low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0) + rows = combinations.itertuples(index=False) + return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)} + + def mortality_interval(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """Each member's interval ends at each horizon: her combination's, empty for one the training never saw.""" + empty = ([np.nan] * len(self.horizons_years),) * 2 + ends = [self.interval_table_.get(tuple(c), empty) for c in _combinations(X).itertuples(index=False)] + return (np.array([e[0] for e in ends], dtype=float).reshape(len(X), -1), + np.array([e[1] for e in ends], dtype=float).reshape(len(X), -1)) + def interval_proba(self, X: pd.DataFrame) -> np.ndarray: """Each member's probability of surviving each interval, given she is alive at its start.""" X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_) @@ -144,6 +185,8 @@ class IntervalSurvival(BaseEstimator): def predict_proba(self, X: pd.DataFrame) -> np.ndarray: mortality = 1.0 - self.survival_proba(X) + if self.interval_level: + mortality = np.column_stack([mortality, *self.mortality_interval(X)]) if INDEX_COLUMN not in X.columns: return mortality dates = pd.to_datetime(X[INDEX_COLUMN]) diff --git a/models/cacu/survival/model.py b/models/cacu/survival/model.py index 1ec213e..03c1acb 100644 --- a/models/cacu/survival/model.py +++ b/models/cacu/survival/model.py @@ -75,9 +75,12 @@ def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> d return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event") -def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival: - """The interval survival fitted on the training members.""" - return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]]) +def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float], + risk_interval_level: float | None = None, risk_interval_replicas: int = 100) -> IntervalSurvival: + """The interval survival fitted on the training members, with each combination's bootstrap interval at + `risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run).""" + return IntervalSurvival(survival, tuple(horizons_years), risk_interval_level, risk_interval_replicas).fit( + train_set[FEATURES], train_set[["months", "event"]]) def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray: @@ -87,7 +90,7 @@ def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataF def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray: """The training members' mortality at each horizon (apparent performance).""" - return fitted_survival.predict_proba(train_set[FEATURES]) + return 1.0 - fitted_survival.survival_proba(train_set[FEATURES]) def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray, diff --git a/models/cacu/survival/model.toml b/models/cacu/survival/model.toml index f75b63d..7dd689d 100644 --- a/models/cacu/survival/model.toml +++ b/models/cacu/survival/model.toml @@ -9,25 +9,40 @@ modules = ["models.cacu.survival.model", "models.cacu.survival.population", "mod "models.steps.indexing"] description = """ Prototipo: mortalidad por cualquier causa a 1, 3 y 5 años del diagnóstico de cáncer (provisional: la primera biopsia \ -con carcinoma invasor), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \ +con carcinoma invasor o in situ), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \ recientes hasta él. Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana combinadas), \ como la de CaMa. Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la \ registra.""" +# What the model's number is, as the patient's screen shows it. The model gives the probability of dying; the screen +# shows its complement, the probability of surviving, with the interval's ends swapped. +[estimand] +quantity = "Probabilidad de supervivencia" +description = "Probabilidad de que la paciente siga viva a cada horizonte desde el diagnóstico de cáncer." +outcome = "Muerte por cualquier causa" +index_date = "la primera biopsia con carcinoma invasor o in situ" +horizons_unit = "años" +covariates = "grupo de edad al diagnóstico, citología (categorías de KPNC) y VPH más recientes hasta él" +complement = "supervivencia" + [config] train_fraction = 0.7 # The model's horizons, in years; `survival.horizons` are the same in months. horizons_years = [1.0, 3.0, 5.0] +# The level of each risk's interval: per combination of the covariates, the percentiles of `risk_interval_replicas` +# refits on bootstrap resamples of the training members. None gives no interval. +risk_interval_level = 0.95 +risk_interval_replicas = 100 # The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance. age_cuts = [35, 45, 55] # The scenario's index and rules, over its source cohort (models/steps/indexing.py). PROVISIONAL: the diagnosis is the -# first biopsy reported as invasive carcinoma (`CARCINOMA`; in situ is not), which is both the inclusion criterion and +# first biopsy reported as carcinoma, invasive or in situ (`CARCINOMA`, `CIS`), which is both the inclusion criterion and # the index date; out: no birth date (no age), a death on or before the biopsy. The recruitment window is the source # cohort's. [config.index] kind = "primera_biopsia_invasora" -event_grades = ["CARCINOMA"] +event_grades = ["CIS", "CARCINOMA"] # PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone. observacion_previa_minima_dias = 0 @@ -68,7 +83,7 @@ ylim_sub = {} # What the dashboard's survival chart says (provisional: to be defined with the clinicians). [config.etiquetas] -titulo = "Supervivencia después de la biopsia con carcinoma invasor" +titulo = "Supervivencia después de la biopsia con carcinoma invasor o in situ" eje_x = "Meses desde el diagnóstico" eje_y = "Supervivencia S(t)" km_crudo = "Kaplan-Meier (IC 95 % Greenwood)" diff --git a/models/dags/estimation.py b/models/dags/estimation.py index 29dbaec..94b1f14 100644 --- a/models/dags/estimation.py +++ b/models/dags/estimation.py @@ -21,28 +21,52 @@ from models.io.lineage import matches from models.io.registry import ResolvedVersion, registered_name, registry from models.io.storage import CohortSource, read_metadata, write_once +# The config key, logged with the run, of a model whose risks come with their interval (`estimate_frame`). +INTERVAL_PARAM = "risk_interval_level" + def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool: """Whether the output file already holds this version's scores of this build.""" return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort}) -def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame: +def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float], + intervals: bool = False) -> pd.DataFrame: """One row per member (in `pac_id` order, as the model gives them) and horizon. A model that decides its own index date (`models.steps.indexing`) gives it as one more first column, in days since 1970-01-01, with the members it - leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index.""" + leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index. A member without + a risk (NaN: one the model can't place) has no rows. With `intervals` + the model gives three blocks of one column per horizon, the risk and its interval's lower and upper ends + (`ic_bajo`, `ic_alto`).""" members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable") - if probabilities.ndim != 2 or len(probabilities) != len(members): - raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members") - risks, dates = probabilities[:, -len(horizons):], members["fecha_indice"].to_numpy() - if probabilities.shape[1] == len(horizons) + 1: + width = len(horizons) * (3 if intervals else 1) + if probabilities.ndim != 2 or len(probabilities) != len(members) or probabilities.shape[1] not in (width, width + 1): + raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members and {len(horizons)} horizons" + + (" with intervals" if intervals else "")) + risks, dates = probabilities[:, -width:], members["fecha_indice"].to_numpy() + if probabilities.shape[1] == width + 1: decided = ~np.isnan(probabilities[:, 0]) members, risks = members[decided], risks[decided] dates = pd.to_datetime(probabilities[decided, 0], unit="D").date - return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int), - "fecha_indice": np.repeat(dates, len(horizons)), - "horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)), - "probabilidad": risks.ravel().astype(float)}) + scored = ~np.isnan(risks[:, :len(horizons)]).any(axis=1) # a member the model can't place (a combination unseen in training) + members, risks, dates = members[scored], risks[scored], dates[scored] + blocks = np.split(risks, 3 if intervals else 1, axis=1) + frame = pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int), + "fecha_indice": np.repeat(dates, len(horizons)), + "horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)), + "probabilidad": blocks[0].ravel().astype(float)}) + if intervals: + frame["ic_bajo"], frame["ic_alto"] = blocks[1].ravel().astype(float), blocks[2].ravel().astype(float) + return frame + + +def scored_frame(resolved: ResolvedVersion, cohort_frame: pd.DataFrame) -> pd.DataFrame: + """The version's estimate of a build's long frame: its model's output at the run's horizons, with the interval + when the run has `INTERVAL_PARAM`.""" + params = registry.client.get_run(resolved.run_id).data.params + intervals = params.get(INTERVAL_PARAM) not in (None, "", "None", "null") + probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)) + return estimate_frame(cohort_frame, probabilities, json.loads(params["horizons_years"]), intervals) def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path, @@ -55,9 +79,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path, if already_estimated(output_path, resolved.version, cohort): return resolved, False cohort_frame = source.frame() - horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"]) - probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)) - risks = estimate_frame(cohort_frame, probabilities, horizons) + risks = scored_frame(resolved, cohort_frame) check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output") provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario), "modelo_version": resolved.version, "mlflow_run_id": resolved.run_id, diff --git a/models/dags/training.py b/models/dags/training.py index dd8bf9e..a4052c5 100644 --- a/models/dags/training.py +++ b/models/dags/training.py @@ -8,7 +8,7 @@ scikit-learn estimator that takes the long frame) and `metrics`, with no I/O. Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same. `train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks -it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed +it failed if the graph fails. Before running, it stores the graph's drawing as `diagramas/pipeline.svg` (and its `.dot`). `find_trained` answers before anything is built whether this source, the installed `models` version, the config and the environment already have a version. A failing node's inputs, which may hold members' rows, are kept out of Hamilton's error log; the exception still says which node failed. """ @@ -17,7 +17,7 @@ import hashlib import json import logging import tomllib -from dataclasses import dataclass +from dataclasses import dataclass, field from importlib import import_module from pathlib import Path from types import ModuleType @@ -49,6 +49,9 @@ class Scenario: requirements: tuple[str, ...] = () # Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`). tables: dict | None = None + # What the model's number is (`[estimand]`): `quantity`, `description`, `outcome`, `index_date`, `horizons_unit`; + # what a screen shows next to each risk. How its interval is computed is the version's report's, not the screen's. + estimand: dict = field(default_factory=dict) @classmethod def from_toml(cls, path: str | Path) -> "Scenario": @@ -58,7 +61,8 @@ class Scenario: outcome=found["outcome"], description=found.get("description", ""), modules=tuple(import_module(name) for name in found["modules"]), config=found["config"], folder=path.parent, requirements=tuple(found.get("requirements", ())), - tables={name: found[name] for name in found.get("settings_tables", ())} or None) + tables={name: found[name] for name in found.get("settings_tables", ())} or None, + estimand=dict(found.get("estimand", {}))) @classmethod def load(cls, domain: str, scenario: str) -> "Scenario": @@ -112,6 +116,23 @@ def find_trained(scenario: Scenario, source: CohortSource, environment: str = "D return None +def pipeline_drawing(dr: driver.Driver) -> tuple[str, str | None] | None: + """The scenario's Hamilton graph as Graphviz source and SVG: every node of its modules and the external inputs, + left to right. The SVG is None when Graphviz's `dot` program is missing; the whole drawing is None when the + `graphviz` package is (the `notebooks` extra).""" + try: + graph = dr.display_all_functions(None, orient="LR", show_schema=False) + except ImportError: + return None + if graph is None: # Hamilton logs the missing `graphviz` and gives nothing + return None + try: + svg = graph.pipe(format="svg", encoding="utf-8") + except Exception: # graphviz.ExecutableNotFound or a failed render: the source still goes + svg = None + return graph.source, svg + + def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str: """Trains on the source's build and returns the registered version. The run keeps the source's reference, never its rows.""" @@ -121,6 +142,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> try: plain = dataflow(*scenario.modules, config=scenario.config) required, _ = external_inputs(plain) + if drawing := pipeline_drawing(plain): + run.log_diagram("pipeline", *drawing) loaders = [loader(target=target, source=source) for target, loader in (("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source), ("cohort_lineage", from_.cohort_source_lineage)) diff --git a/models/eeg_analysis.py b/models/eeg_analysis.py index 191bc7f..a3b8e11 100644 --- a/models/eeg_analysis.py +++ b/models/eeg_analysis.py @@ -4,8 +4,8 @@ An EEG is pending when it has an EDF and was never analysed, or was analysed wit versions, or, being valid, against baselines other than those now in production. One that failed with the current plan and versions waits for a new one instead of failing again on every run. -Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`, -`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id +Each result replaces the EEG's previous checks, metrics, electrode and zone values in `eeg`, `eeg_criterio`, +`eeg_metrica`, `eeg_metrica_electrodo` and `eeg_metrica_zona`. Row ids derive from the EEG and what each row is, so a row keeps its id from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished. @@ -20,11 +20,11 @@ from datetime import datetime, timedelta, timezone from sqlmodel import Session, col, delete, select from core.tea.enums import MetricaEeg -from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes +from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, EegMetricaZona, Pacientes from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions from models.tea.eeg.baselines import Baselines -from models.tea.eeg.settings import Settings, settings as model_settings +from models.tea.eeg.settings import Settings, scenario_of, settings as model_settings COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo" @@ -83,6 +83,7 @@ class Rows: criteria: list[EegCriterio] metrics: list[EegMetrica] electrodes: list[EegMetricaElectrodo] + zones: list[EegMetricaZona] def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows: @@ -108,23 +109,34 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None )) by_code = {metric.code: metric for metric in s.metrics} - metrics, electrodes = [], [] + metrics, electrodes, zones = [], [], [] for value in m.metrics: metric = by_code[value.code] met_id = row_id(m.key, "metrica", value.code) - deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months) + deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months, value.exposure) used = [metric.scenario] if deviation is not None else [] for electrode, raw in sorted(value.electrodes.items()): at_electrode = None if metric.electrode_scenario: at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode, - raw, m.age_months) + raw, m.age_months, value.exposure) if at_electrode is not None and metric.electrode_scenario not in used: used.append(metric.electrode_scenario) electrodes.append(EegMetricaElectrodo( mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode, mel_valor=raw, mel_z=at_electrode.z if at_electrode else None, )) + for zone, raw in sorted(value.zones.items()): + at_zone = None + if metric.zone_scenario: + at_zone = baselines.deviation(metric.zone_scenario, metric.zone_prefix + zone, raw, m.age_months, + value.exposure) + if at_zone is not None and metric.zone_scenario not in used: + used.append(metric.zone_scenario) + zones.append(EegMetricaZona( + mez_id=row_id(m.key, "metrica", value.code, "zona", zone), mez_met_id=met_id, mez_zona=zone, + mez_valor=raw, mez_z=at_zone.z if at_zone else None, + )) metrics.append(EegMetrica( met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value, met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None, @@ -132,7 +144,7 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None met_p95=deviation.p95 if deviation else None, met_modelo=";".join(baselines.label(scenario) for scenario in used) or None, )) - return Rows(eeg, criteria, metrics, electrodes) + return Rows(eeg, criteria, metrics, electrodes, zones) def save(session: Session, eeg_id: str, new: Rows) -> None: @@ -145,10 +157,11 @@ def save(session: Session, eeg_id: str, new: Rows) -> None: session.add(eeg) metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id) session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids))) + session.exec(delete(EegMetricaZona).where(col(EegMetricaZona.mez_met_id).in_(metric_ids))) session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id)) session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id)) session.flush() - session.add_all([*new.criteria, *new.metrics, *new.electrodes]) + session.add_all([*new.criteria, *new.metrics, *new.electrodes, *new.zones]) def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings): @@ -181,7 +194,7 @@ class Summary: def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]: out = {} for m in s.metrics: - scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario] + scenarios = [scenario_of(n, m.phase) for n in m.readers] out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None return out diff --git a/models/io/contracts.py b/models/io/contracts.py index c376f23..62769f1 100644 --- a/models/io/contracts.py +++ b/models/io/contracts.py @@ -48,7 +48,12 @@ ESTIMATE_FRAME = pandera.DataFrameSchema( {"pac_id": pandera.Column(int, pandera.Check.gt(0)), "fecha_indice": pandera.Column(nullable=False), "horizonte_anios": pandera.Column(float, pandera.Check.ge(0)), - "probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))}, + "probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1)), + # the risk's interval, from a model that gives one (NaN where it can't) + "ic_bajo": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False), + "ic_alto": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False)}, + checks=pandera.Check(lambda f: ~(f["ic_bajo"] > f["probabilidad"]) & ~(f["ic_alto"] < f["probabilidad"]) + if "ic_bajo" in f else pd.Series(True, index=f.index), error="ic_bajo <= probabilidad <= ic_alto"), strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate") POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables" diff --git a/models/io/registry.py b/models/io/registry.py index 72bd4b9..4a29b21 100644 --- a/models/io/registry.py +++ b/models/io/registry.py @@ -125,6 +125,14 @@ class ModelRegistry: def status(self, domain: str, scenario: str, version: str) -> str: return self._status(self.get(domain, scenario, version)) + def in_production(self, domain: str) -> list[str]: + """The scenarios of `domain` with a version holding the `produccion` alias, by name.""" + if domain not in DOMAINS: + raise ValueError(f"dominio desconocido: {domain!r}") + prefix = registered_name(domain, "") + models = self.client.search_registered_models(filter_string=f"name LIKE '{prefix}%'") + return sorted(m.name.removeprefix(prefix) for m in models if PRODUCTION_ALIAS in (m.aliases or {})) + def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion: """With no `version`, the one holding the `produccion` alias; with a version, that one, whatever its status (to test or compare a candidate). The status travels with it: confirming risks only diff --git a/models/io/tracking.py b/models/io/tracking.py index 4046448..cd88879 100644 --- a/models/io/tracking.py +++ b/models/io/tracking.py @@ -52,6 +52,7 @@ MODEL_PATH = "model" ROUTINES_PATH = "rutinas" ANALYSIS_PATH = "analisis" REPORTS_PATH = "reportes" +DIAGRAMS_PATH = "diagramas" # The routines §5 of the requirements names; a version is promoted only when its run recorded each one. ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO, ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA) @@ -203,6 +204,13 @@ class TrainingRun: version keeps for whoever reviews it. Like `log_analysis`, aggregates only.""" self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html") + def log_diagram(self, name: str, dot: str, svg: str | None = None) -> None: + """A drawing of the run's dataflow, `diagramas/.dot` (Graphviz source) and, when Graphviz's `dot` could + draw it, `diagramas/.svg`: each one more file of the version, listed and downloaded on its own.""" + self.client.log_text(self.run_id, dot, f"{DIAGRAMS_PATH}/{name}.dot") + if svg is not None: + self.client.log_text(self.run_id, svg, f"{DIAGRAMS_PATH}/{name}.svg") + def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str: """Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input example, so no patient data diff --git a/models/steps/risks.py b/models/steps/risks.py index a0ef30c..837b5b8 100644 --- a/models/steps/risks.py +++ b/models/steps/risks.py @@ -1,15 +1,23 @@ """From an estimate's rows to the risks a batch stores: `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto)`; `fecha_indice` is the model's index date for the member, which its horizons count from.""" +import numpy as np import pandas as pd from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame def risk_rows(estimate: pd.DataFrame) -> list[tuple]: - """One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored - twice at one horizon or a probability outside 0..1 stops the batch.""" + """One risk per member and horizon, with its interval when the estimate has one, once the rows satisfy + `ESTIMATE_FRAME`: a member scored twice at one horizon or a probability outside 0..1 stops the batch.""" check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate") - return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None) - for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"], - estimate["horizonte_anios"], estimate["probabilidad"])] + missing = pd.Series(np.nan, index=estimate.index) + low, high = estimate.get("ic_bajo", missing), estimate.get("ic_alto", missing) + + def value(v): + return None if pd.isna(v) else float(v) + + return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), value(lo), value(hi)) + for pac_id, fecha, horizon, probability, lo, hi in zip(estimate["pac_id"], estimate["fecha_indice"], + estimate["horizonte_anios"], + estimate["probabilidad"], low, high)] diff --git a/models/tea/__init__.py b/models/tea/__init__.py index 179d5eb..313366c 100644 --- a/models/tea/__init__.py +++ b/models/tea/__init__.py @@ -1 +1 @@ -"""TEA's models: the EEG analysis (`eeg`).""" +"""TEA's models: the EEG analysis (`eeg`) and the ADOS-2 association (`ados2`).""" diff --git a/models/tea/ados2/__init__.py b/models/tea/ados2/__init__.py new file mode 100644 index 0000000..bdcd739 --- /dev/null +++ b/models/tea/ados2/__init__.py @@ -0,0 +1,2 @@ +"""TEA's ADOS-2 association: the `tea` library module and the metrics it reads (`model.toml`); fitted on the +database by `models.ados2_relation`.""" diff --git a/models/tea/ados2/model.toml b/models/tea/ados2/model.toml new file mode 100644 index 0000000..dc5c806 --- /dev/null +++ b/models/tea/ados2/model.toml @@ -0,0 +1,13 @@ +# The ADOS-2 association: the `tea` library's cohort-level module, and the stored EEG metric each of its biomarkers +# reads. Spike and spindle predictors are the metric's zone z (`eeg_metrica_zona`); the posterior rhythm and the +# gradient are the metric's own z (`eeg_metrica.met_z`). +association = "ados2_association" +impl = "modern" +# "auto": by item when the cohort has ADOS-2 item scores, by the CSS otherwise; or "item", "domain". +level = "auto" + +[biomarkers] +spikes = "PICOS_PAROXISTICOS" +spindles = "HUSOS_SUENO_N2" +posterior_rhythm = "RITMO_POSTERIOR" +gradient = "GRADIENTE_ANTEROPOSTERIOR" diff --git a/models/tea/ados2/settings.py b/models/tea/ados2/settings.py new file mode 100644 index 0000000..850c50c --- /dev/null +++ b/models/tea/ados2/settings.py @@ -0,0 +1,20 @@ +"""The ADOS-2 association's settings (`model.toml`): the library module, its implementation and level, and the +stored EEG metric each of its biomarkers reads.""" +import tomllib +from dataclasses import dataclass +from functools import cache +from pathlib import Path + + +@dataclass(frozen=True) +class Settings: + association: str + impl: str + level: str + biomarkers: dict[str, str] # library biomarker -> `MetricaEeg` code + + +@cache +def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings: + raw = tomllib.loads(path.read_text()) + return Settings(raw["association"], raw["impl"], raw["level"], dict(raw["biomarkers"])) diff --git a/models/tea/eeg/analyze.py b/models/tea/eeg/analyze.py index 307e06d..023f2eb 100644 --- a/models/tea/eeg/analyze.py +++ b/models/tea/eeg/analyze.py @@ -46,6 +46,8 @@ class MetricValue: code: str value: float | None electrodes: dict[str, float | None] = field(default_factory=dict) + zones: dict[str, float | None] = field(default_factory=dict) + exposure: float | None = None # what a count baseline divides the value, electrodes and zones by @dataclass(frozen=True) @@ -90,7 +92,7 @@ def processes(pipe, settings: Settings) -> list[str]: the phased biomarkers contribute only what their stage's detector requires.""" from tea.pipeline.run_study import order_for - needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n] + needs = [n for m in settings.metrics if not m.phase for n in m.readers] requires = {r for n in needs for r in pipe.module(n).requires} for phase in settings.phases: requires.update(phase_detector(pipe, phase).requires) @@ -158,22 +160,26 @@ def features(pipe, study, settings: Settings) -> Features: by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study)) out: Features = {} for m in settings.metrics: - for biomarker in (m.biomarker, m.electrodes): - if biomarker and (biomarker, m.phase) not in out: + for biomarker in m.readers: + if (biomarker, m.phase) not in out: out[biomarker, m.phase] = {k: _number(v) for k, v in pipe.module(biomarker).measure(by_phase[m.phase]).items()} return out +def _prefixed(measured: Features, biomarker: str | None, phase: str | None, prefix: str) -> dict[str, float | None]: + """The features of `biomarker` whose name starts with `prefix`, by the rest of the name.""" + if not biomarker: + return {} + return {name.removeprefix(prefix): v for name, v in measured[biomarker, phase].items() if name.startswith(prefix)} + + def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]: - out = [] - for m in settings.metrics: - electrodes = {} - if m.electrodes: - electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items() - if name.startswith(m.electrode_prefix)} - out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes)) - return tuple(out) + return tuple(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), + _prefixed(measured, m.electrodes, m.phase, m.electrode_prefix), + _prefixed(measured, m.zones, m.phase, m.zone_prefix), + measured[m.biomarker, m.phase].get(m.exposure) if m.exposure else None) + for m in settings.metrics) def _error(exc: Exception) -> str: diff --git a/models/tea/eeg/baselines.py b/models/tea/eeg/baselines.py index d9a351d..d123bf1 100644 --- a/models/tea/eeg/baselines.py +++ b/models/tea/eeg/baselines.py @@ -47,9 +47,15 @@ def _load(model_uri: str): sys.path[:] = path +def _takes_exposure(baseline) -> bool: + import inspect + + return "exposure" in inspect.signature(baseline.deviation).parameters + + def _feature_baseline(module, feature: str): baselines = getattr(module, "baselines", None) - return baselines[feature] if baselines is not None else module.baseline + return baselines.get(feature) if baselines is not None else module.baseline def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]: @@ -103,16 +109,30 @@ class Baselines: self._loaded[scenario] = _load(resolved.model_uri) return self._loaded[scenario] - def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None: + def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None, + exposure: float | None = None) -> Deviation | None: """None without a baseline in production; with one, a deviation whose fields are null where the value or - the age is missing or the curve doesn't cover the age.""" + the age is missing or the curve doesn't cover the age. `exposure` reaches a baseline that takes one (a count + against its minutes), whose p5, median and p95 are then the rates expected in those minutes; the others + ignore it.""" module = self.module(scenario) if module is None: return None baseline = _feature_baseline(module, feature) + if baseline is None: + return None if value is None or age_months is None: return Deviation(None, None, None, None, None) - outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float)) + args = (np.array([value], float), np.array([age_months], float)) + minutes = np.array([np.nan if exposure is None else exposure], float) + if _takes_exposure(baseline): + outside, z = baseline.deviation(*args, exposure=minutes) + else: + outside, z = baseline.deviation(*args) z_value = _number(z[0]) - p5, median, p95 = centiles(baseline, age_months) - return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95) + if hasattr(baseline, "percentiles"): + p5, median, p95 = (_number(v) for v in baseline.percentiles(args[1], minutes)[0]) + else: + p5, median, p95 = centiles(baseline, age_months) + outside_value = _number(outside[0]) + return Deviation(z_value, int(outside_value) if outside_value is not None else None, p5, median, p95) diff --git a/models/tea/eeg/model.toml b/models/tea/eeg/model.toml index 86ebb84..241febf 100644 --- a/models/tea/eeg/model.toml +++ b/models/tea/eeg/model.toml @@ -18,7 +18,10 @@ line_hz = 50.0 ages = [16.0, 36.0] # One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the -# biomarker whose `` features are the metric's value per 10-20 electrode. +# biomarker whose `` features are the metric's value per 10-20 electrode, and `zones` the +# one whose `` features are its value per scalp zone (`tea.contracts.ZONES`), which the ADOS-2 +# association reads. `exposure` names the feature a count baseline divides by: spikes are counted against the +# minutes they were looked for in, since most children of the reference have none. # The feature each metric maps to is provisional until the domain expert confirms it. [[metrics]] code = "RITMO_POSTERIOR" @@ -32,6 +35,8 @@ phase = "N2" feature = "spindle_density_per_min_channel" electrodes = "spindle_topography" electrode_prefix = "topo_enh_" +zones = "spindles" +zone_prefix = "spindle_zone_" [[metrics]] code = "HUSOS_SUENO_N3" @@ -40,11 +45,18 @@ phase = "N3" feature = "spindle_density_per_min_channel" electrodes = "spindle_topography" electrode_prefix = "topo_enh_" +zones = "spindles" +zone_prefix = "spindle_zone_" [[metrics]] code = "PICOS_PAROXISTICOS" biomarker = "spikes" feature = "spike_rate_nrem" +electrodes = "spikes" +electrode_prefix = "spike_density_nrem_" +zones = "spikes" +zone_prefix = "spike_zone_rate_nrem_" +exposure = "spike_minutes_nrem" [[metrics]] code = "GRADIENTE_ANTEROPOSTERIOR" diff --git a/models/tea/eeg/settings.py b/models/tea/eeg/settings.py index 600bb86..5d08340 100644 --- a/models/tea/eeg/settings.py +++ b/models/tea/eeg/settings.py @@ -17,6 +17,9 @@ class Metric: phase: str | None = None electrodes: str | None = None electrode_prefix: str = "" + zones: str | None = None + zone_prefix: str = "" + exposure: str | None = None # the biomarker's feature a count baseline divides by (its minutes) @property def scenario(self) -> str: @@ -26,6 +29,15 @@ class Metric: def electrode_scenario(self) -> str | None: return scenario_of(self.electrodes, self.phase) if self.electrodes else None + @property + def zone_scenario(self) -> str | None: + return scenario_of(self.zones, self.phase) if self.zones else None + + @property + def readers(self) -> tuple[str, ...]: + """The biomarkers the metric reads: its own, its electrodes' and its zones'.""" + return tuple(dict.fromkeys(n for n in (self.biomarker, self.electrodes, self.zones) if n)) + @dataclass(frozen=True) class Reference: @@ -55,13 +67,13 @@ class Settings: @property def scenarios(self) -> dict[str, tuple[str, str | None]]: """Each baseline to train, by scenario: (biomarker, sleep stage).""" - pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n] + pairs = [(n, m.phase) for m in self.metrics for n in m.readers] return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)} @property def biomarkers(self) -> tuple[str, ...]: - """Every biomarker a metric reads, its own or its electrodes'.""" - names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n] + """Every biomarker a metric reads, its own, its electrodes' or its zones'.""" + names = [n for m in self.metrics for n in m.readers] return tuple(dict.fromkeys(names)) diff --git a/tests/cacu/data/kpnc_reference.csv b/tests/cacu/data/kpnc_reference.csv new file mode 100644 index 0000000..095f933 --- /dev/null +++ b/tests/cacu/data/kpnc_reference.csv @@ -0,0 +1,141 @@ +table,outcome,group,curve,knots,gamma,eta,cr0,cr1,cr2,cr3,cr4,cr5,max_abs +1,CIN2+,HPV negativo,AGC,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.0,0.0241115195644835,0.0256092196204436,0.0268181400278813,0.028171784403177,0.0297901538513425,0.031523974593383,4.440892098500626e-16 +1,CIN2+,HPV negativo,ASC-H,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.675059058469885,0.0953469396720264,0.0980718969717476,0.100268497329922,0.102724939896397,0.10565744916419,0.108793929166055,4.440892098500626e-16 +1,CIN2+,HPV negativo,ASC-US,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.3716720902899113,0.0006886909862562,0.00291195228696667,0.00470541300218982,0.00671238510720408,0.00911019894943088,0.0116770710796392,4.440892098500626e-16 +1,CIN2+,HPV negativo,HSIL+,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",2.0164005981856348,0.468287640749052,0.474386433098624,0.47926496337816,0.484680892189583,0.491091841584196,0.497883312012614,4.440892098500626e-16 +1,CIN2+,HPV negativo,LSIL,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",1.0694381631654704,0.0321089460773336,0.036430742300162,0.0399099701641632,0.0437959045534305,0.0484282146868277,0.05337460404111,4.440892098500626e-16 +1,CIN2+,HPV negativo,NILM,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",-0.6656887215701865,3.90353647266218e-05,0.000828013277650686,0.00146529413171444,0.00217932287701656,0.00303362524453662,0.00394964078320864,4.440892098500626e-16 +1,CIN2+,HPV positivo,AGC,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.0,0.400884761372207,0.423177327520334,0.453148774204697,0.47722331054264,0.491809730088738,0.500142601911983,7.771561172376096e-16 +1,CIN2+,HPV positivo,ASC-H,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.2126697727739812,0.501106699178966,0.523966961254572,0.554371985820979,0.578511314319372,0.593010085492955,0.601248908320567,7.771561172376096e-16 +1,CIN2+,HPV positivo,ASC-US,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.7533953307304859,0.134977733606003,0.150282229405366,0.171360576935273,0.188738761408003,0.19947466518464,0.205681128069832,7.771561172376096e-16 +1,CIN2+,HPV positivo,HSIL+,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.007560314353099129,0.768895742132862,0.777558954414099,0.789202267331941,0.798551251948637,0.80421408879622,0.807448580381107,7.771561172376096e-16 +1,CIN2+,HPV positivo,LSIL,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.7121375835534804,0.150720429636477,0.166373432071245,0.187912288999706,0.205652819554319,0.216604598846303,0.222933043955648,7.771561172376096e-16 +1,CIN2+,HPV positivo,NILM,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.9861148498309161,0.0498612570542781,0.0632060742965726,0.0816675057209598,0.0969615559339089,0.106443878949773,0.111937675985206,7.771561172376096e-16 +1,CIN3+,HPV negativo,AGC,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",0.0,0.0106844641637163,0.0115079789994108,0.0121411816481693,0.0128347160639286,0.0136669643759362,0.0145666781897423,3.3306690738754696e-16 +1,CIN3+,HPV negativo,ASC-H,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-0.04872187576775001,0.0342206380443041,0.034986346556643,0.0355751224053339,0.0362200176140623,0.0369939268279508,0.0378306072669854,3.3306690738754696e-16 +1,CIN3+,HPV negativo,ASC-US,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-0.09879946244479822,0.000397811063724171,0.00115163989720337,0.0017313009790938,0.00236623247962954,0.00312821209932418,0.00395202899225357,3.3306690738754696e-16 +1,CIN3+,HPV negativo,HSIL+,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",2.004887966546689,0.252144671903415,0.256754712682076,0.260282641941786,0.264130077325419,0.268724170611435,0.273662742092822,3.3306690738754696e-16 +1,CIN3+,HPV negativo,LSIL,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",0.8576201610700221,0.0105183209491033,0.0124590219555563,0.013949740055348,0.0155810064976098,0.017536490040242,0.0196479749836111,3.3306690738754696e-16 +1,CIN3+,HPV negativo,NILM,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-1.174571179173883,2.28864043889962e-05,0.000280128375297359,0.000478023113087691,0.000694873939389557,0.000955236140567136,0.00123687521303424,3.3306690738754696e-16 +1,CIN3+,HPV positivo,AGC,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",0.0,0.262739413900099,0.276609416274342,0.302317768969549,0.324522607011181,0.338063429715532,0.345343732440977,3.885780586188048e-16 +1,CIN3+,HPV positivo,ASC-H,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-0.09530733394718151,0.25730149160114,0.270014560302542,0.293637521742104,0.314104857280649,0.326616057076886,0.333352370721709,3.885780586188048e-16 +1,CIN3+,HPV positivo,ASC-US,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.3767188384949076,0.0444540193603678,0.0490236673279738,0.0576697985578552,0.0653314891820387,0.0700965762622234,0.0726887422509778,3.885780586188048e-16 +1,CIN3+,HPV positivo,HSIL+,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-0.30370002843403754,0.488648915271303,0.495766893454262,0.509055662871487,0.520636978488655,0.527748325122181,0.531587512570922,3.885780586188048e-16 +1,CIN3+,HPV positivo,LSIL,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.4329033456135163,0.042676750204802,0.0470053353775885,0.0551984713012144,0.0624621762259645,0.0669813807353154,0.0694403197238233,3.885780586188048e-16 +1,CIN3+,HPV positivo,NILM,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.4575108528337812,0.0213187485278357,0.0256365794003271,0.0338106666152414,0.0410589243006993,0.0455692063201592,0.0480235134204469,3.885780586188048e-16 +17,CIN2+,label_0+label_2: High Grade | HPV-negative, pd.Series: + """Each member's first biopsy reported as carcinoma, in situ or invasive: the survival scenario's diagnosis.""" + biopsias = frame[(frame["tipo"] == "biopsia") & frame["valor_codigo"].isin(["CIS", "CARCINOMA"])] + return biopsias.groupby("pac_id")["fecha"].min() def test_the_index_is_the_first_carcinoma_biopsy_and_its_rules_leave_out_who_they_should(cohort_frame): - """Pins down the provisional index: members 1 to 240 are indexed at their biopsy reported as invasive carcinoma, not - at an earlier CIS biopsy nor at their first observation; a CIS biopsy only (241), no birth date (242), a death - before the diagnosis (243) and a diagnosis before the window (244) leave the cohort. Fails if the scenario stops - taking `[config.index]`, counts in situ as the diagnosis, or takes the window from elsewhere than the lineage.""" + """Pins down the provisional index: each member is indexed at her first biopsy reported as carcinoma, in situ or + invasive, not at her first observation: an earlier CIS biopsy is the diagnosis (member 5), and a CIS biopsy only + (241) is a case too; no birth date (242), a death before the diagnosis (243) and a diagnosis before the window + (244) leave the cohort. Fails if the scenario stops taking `[config.index]`, drops in situ from the diagnosis, or + takes the window from elsewhere than the lineage.""" attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"])) indexed = _indexed(cohort_frame) - assert set(indexed["pac_id"].unique()) == set(range(1, N + 1)) - assert attrition["sin_nacimiento"] == N + 1 and attrition["defuncion_hasta_el_indice"] == N + # a CIS 20 days before a diagnosis at the window's start puts that member's diagnosis before the window + inicio = date.fromisoformat(WINDOW["recruitment_start"]) + antes = set(_primer_carcinoma(cohort_frame)[lambda d: d < inicio].index) & set(range(1, N + 1)) + assert set(indexed["pac_id"].unique()) == (set(range(1, N + 1)) | {241}) - antes + assert attrition["sin_nacimiento"] == N + 2 - len(antes) + assert attrition["defuncion_hasta_el_indice"] == N + 1 - len(antes) five = cohort_frame[cohort_frame["pac_id"] == 5] - diagnosis = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CARCINOMA")]["fecha"].iloc[0] - assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == diagnosis + in_situ = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CIS")]["fecha"].iloc[0] + assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == in_situ def test_the_covariates_are_the_most_recent_observations_up_to_the_diagnosis(cohort_frame): @@ -207,8 +219,9 @@ def test_the_dataflow_reaches_its_metrics_routines_and_population_record_without def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking, tmp_path): """Pins down: training on a build's file registers a version with its population record; estimating with it writes - one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with the members the - scenario leaves out absent. Fails if the version cannot score a build or the estimate keeps the cohort's index.""" + one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with its combination's + bootstrap interval holding it, and with the members the scenario leaves out absent. Fails if the version cannot + score a build, the estimate keeps the cohort's index, or the risks lose their interval.""" version = train(dataclasses.replace(SCENARIO, config=QUICK), CohortFile(cohort_file)) output = tmp_path / "estimate.parquet" @@ -216,9 +229,15 @@ def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_mode assert wrote and resolved.version == version files = [f["path"] for f in registry.artifacts("cacu", "survival", version)] - assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html"} <= set(files) + assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html", "diagramas/pipeline.dot", + "diagramas/pipeline.svg"} <= set(files) risks = pq.read_table(output).to_pandas() - assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1)) + inicio = date.fromisoformat(WINDOW["recruitment_start"]) + antes = set(_primer_carcinoma(read_cohort(cohort_file))[lambda d: d < inicio].index) + assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} + assert risks[["ic_bajo", "ic_alto"]].notna().all().all() + assert ((risks["ic_bajo"] <= risks["probabilidad"]) & (risks["probabilidad"] <= risks["ic_alto"])).mean() > 0.9 + assert set(risks["pac_id"]) == (set(range(1, N + 1)) | {241}) - antes frame = read_cohort(cohort_file) diagnosis = frame[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "CARCINOMA") & (frame["pac_id"] == 1)] assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == diagnosis["fecha"].iloc[0] @@ -280,3 +299,19 @@ def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch): found = _run_notebook(path, cohort_file, "cacu", "survival", monkeypatch) assert sum(r["n"] for r in found["survival"]) == N + + +def test_the_survival_scenario_shows_the_probability_of_surviving(): + """Pins down: the scenario's estimand names the probability of surviving and marks it as the complement of the + model's number (the probability of dying), so the patient's record shows survival, with its covariates. Fails if + `complement` is dropped: the record would show a death probability labelled as survival.""" + estimand = Scenario.load("cacu", "survival").estimand + assert estimand["quantity"] == "Probabilidad de supervivencia" and estimand["complement"] == "supervivencia" + assert estimand["index_date"] == "la primera biopsia con carcinoma invasor o in situ" + assert "VPH" in estimand["covariates"] + + +def test_a_survival_case_is_a_carcinoma_invasive_or_in_situ(): + """Pins down: the survival scenario's index is the first biopsy of CIS or invasive carcinoma, so in situ cases are + followed too. Fails if CIS drops out of the index, which would leave its patients without a survival estimate.""" + assert Scenario.load("cacu", "survival").config["index"]["event_grades"] == ["CIS", "CARCINOMA"] diff --git a/tests/cacu/test_cancer_pim.py b/tests/cacu/test_cancer_pim.py new file mode 100644 index 0000000..841afcc --- /dev/null +++ b/tests/cacu/test_cancer_pim.py @@ -0,0 +1,54 @@ +"""What this module covers: the `cancer_pim` scenario, the surveillance PIM with carcinoma as the outcome, through its +dataflow and its registered model. + +Fixtures: `cohort_frame`, members of `test_cin2_pim`'s design whose CIN2+ biopsies are carcinomas for a part of them. +""" + +import numpy as np +import pandas as pd +import pytest + +from models.cacu.cin2_pim import model +from models.dags import training +from tests.cacu.test_cin2_pim import cohort_frame as cin2_cohort_frame # noqa: F401 + +SCENARIO = training.Scenario.load("cacu", "cancer_pim") +SURVEILLANCE = training.Scenario.load("cacu", "cin2_pim") + + +@pytest.fixture +def cohort_frame(cin2_cohort_frame): # noqa: F811 + """`test_cin2_pim`'s members with every third LIEAG biopsy reported as carcinoma.""" + frame = cin2_cohort_frame.copy() + lieag = frame.index[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "LIEAG")] + frame.loc[lieag[::3], "valor_codigo"] = "CARCINOMA" + return frame + + +def test_the_scenario_is_the_surveillance_model_with_carcinoma_as_the_outcome(): + """Pins down: same dataflow, cohort, index and prediction index as the CIN2+ surveillance model, with carcinoma as + the only event, so the patient's two risks speak of the same visit. Fails if the scenarios drift apart.""" + assert SCENARIO.config["event_grades"] == ["CARCINOMA"] == SCENARIO.config["index"]["event_grades"] + assert SCENARIO.outcome == "cancer" and SCENARIO.cohort == SURVEILLANCE.cohort + assert [m.__name__ for m in SCENARIO.modules] == [m.__name__ for m in SURVEILLANCE.modules] + same = {k: v for k, v in SCENARIO.config.items() if k not in ("event_grades", "index")} + assert same == {k: v for k, v in SURVEILLANCE.config.items() if k not in ("event_grades", "index")} + assert SCENARIO.estimand["outcome"].startswith("Cáncer") + + +def test_the_dataflow_counts_only_carcinomas_as_events(cohort_frame): + """Pins down: a LIEAG biopsy is not a case for this scenario, and the registered model gives a cancer risk no + higher than the CIN2+ model's at the same visit. Fails if `event_grades` stops reaching the coding.""" + run = training.dataflow(*SCENARIO.modules, config=SCENARIO.config).execute( + ["interval_coded_members", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}}) + coded = run["interval_coded_members"] + carcinomas = set(cohort_frame.loc[cohort_frame["valor_codigo"] == "CARCINOMA", "pac_id"]) + cases = set(coded.loc[(coded["c"] == 1) | np.isfinite(coded["r"]), "pac_id"]) + assert cases == carcinomas + + cin2 = training.dataflow(*SURVEILLANCE.modules, config=SURVEILLANCE.config).execute( + ["fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["fitted_model"] + h = len(SCENARIO.config["horizons_years"]) + cancer, cin2plus = (m.predict_proba(cohort_frame)[:, 1:1 + h] for m in (run["fitted_model"], cin2)) + scored = ~np.isnan(cancer) & ~np.isnan(cin2plus) + assert scored.any() and (cancer[scored] <= cin2plus[scored] + 1e-6).all() diff --git a/tests/cacu/test_cin2_pim.py b/tests/cacu/test_cin2_pim.py index d227669..901c0d3 100644 --- a/tests/cacu/test_cin2_pim.py +++ b/tests/cacu/test_cin2_pim.py @@ -163,7 +163,7 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort(): "incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata", "train_fraction"} # `index` from the config (a scenario without one keeps its cohort's index); the report's settings have defaults. - assert optional == {"index", "report_panels", "turnbull_bootstrap"} + assert optional == {"index", "prediction_index", "report_panels", "risk_interval_level", "turnbull_bootstrap"} def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame): @@ -181,9 +181,10 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame): def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path, predict_without_repository): - """Pins down: through the generic driver the scenario registers a version whose estimate has one row per member - and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata. - Fails if the model or the estimate go back to one horizon, or the registered model needs this repository.""" + """Pins down: through the generic driver the scenario registers a version whose estimate has one row per + precolposcopy member (no biopsy) and horizon, dated at her latest complete cytology, a risk that doesn't fall + with the horizon, the same outside this repository, and storable metadata. Fails if the model or the estimate go + back to one horizon, a biopsied member is scored, or the registered model needs this repository.""" version = training.train(SCENARIO, CohortFile(cohort_file)) registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version) output = tmp_path / "estimate.parquet" @@ -191,7 +192,12 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file estimate(SCENARIO, CohortFile(cohort_file), output) risks = pd.read_parquet(output) - assert len(risks) == 300 * len(CONFIG["horizons_years"]) + frame = pd.read_parquet(cohort_file) + biopsied = set(frame.loc[frame["tipo"] == "biopsia", "pac_id"]) + assert set(risks["pac_id"]) == set(frame["pac_id"]) - biopsied + assert len(risks) == (300 - len(biopsied)) * len(CONFIG["horizons_years"]) + scored = risks.dropna(subset=["ic_bajo"]) + assert len(scored) and ((scored["ic_bajo"] <= scored["probabilidad"]) & (scored["probabilidad"] <= scored["ic_alto"])).all() by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad") assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all() assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2" @@ -199,10 +205,76 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file uri = registry.resolve("cacu", "cin2_pim", version).model_uri outside = predict_without_repository(uri, pd.read_parquet(cohort_file)) inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file)) - assert outside.shape == (300, len(CONFIG["horizons_years"])) + assert outside.shape == (300, 1 + 3 * len(CONFIG["horizons_years"])) np.testing.assert_allclose(outside.to_numpy(), inside) +def test_the_prediction_index_is_the_latest_complete_cytology_before_any_colposcopy(): + """Pins down the surveillance model's prediction index: the latest cytology with both results; one missing its + HPV gives way to the one before; a patient with a colposcopy or a biopsy gets none (the post-colposcopy scenario + scores her). Fails if the index goes back to the cohort's first cytology or a referred patient is scored.""" + def sample(pac_id, day, bethesda, vph): + key = f"S{pac_id}-{day}" + rows = [_row(pac_id, INDEX, day, "citologia", sample=key), _row(pac_id, INDEX, day + 7, "bethesda", bethesda, key)] + return rows + ([_row(pac_id, INDEX, day + 7, "vph", vph, key)] if vph else []) + + rows = [*sample(1, 0, "ASC-US", "NEGATIVO"), *sample(1, 700, "LIEBG", "POSITIVO"), + *sample(2, 0, "NORMAL", "NEGATIVO"), *sample(2, 900, "LIEBG", None), + *sample(3, 0, "LIEBG", "POSITIVO"), _row(3, INDEX, 40, "colposcopia"), *sample(3, 400, "NORMAL", "NEGATIVO")] + frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names) + + found = model.latest_index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"]) + + assert found["pac_id"].tolist() == [1, 2, 3] + assert found[model.INDEX_COLUMN].dt.date.tolist()[:2] == [INDEX + timedelta(days=700), INDEX] + assert found["cytology"].tolist()[:2] == ["LSIL", "NILM"] and found["hpv_positive"].tolist()[:2] == [1.0, 0.0] + assert pd.isna(found[model.INDEX_COLUMN].iloc[2]) and pd.isna(found["cytology"].iloc[2]) + + +def test_the_registered_model_dates_each_risk_at_its_prediction_index(cohort_frame): + """Pins down: with `prediction_index` the registered model gives the index date first (days since 1970) and the + risk of that visit's results, and no risk to a member without one. Fails if the date column is dropped, the + risk is computed from the cohort's index, or a member without an index gets a risk.""" + found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute( + ["fitted_model", "fitted_mixture"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}}) + output = found["fitted_model"].predict_proba(cohort_frame) + features = model.latest_index_results(cohort_frame, CONFIG["index_sample_days"], CONFIG["cytology"]) + h = len(CONFIG["horizons_years"]) + + dated = ~np.isnan(output[:, 0]) + assert dated.sum() == features[model.INDEX_COLUMN].notna().sum() and np.isnan(output[~dated, 1:]).all() + np.testing.assert_allclose(output[dated, 0], (features.loc[dated, model.INDEX_COLUMN] - model.EPOCH).dt.days) + expected = found["fitted_mixture"].predict_proba(features.loc[dated, model._features(CONFIG["history"])]) + np.testing.assert_allclose(output[dated, 1:1 + h], expected) + + +def test_the_interval_brackets_the_same_risk(cohort_frame): + """Pins down: with `interval_level` the mixture gives the risk unchanged and, after it, the interval's lower and + upper ends around it, NaN only where the risk is. Fails if the delta method moves the point, the blocks' order + changes, or an end crosses the risk.""" + found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute( + ["fitted_mixture", "test_set", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}}) + X = found["test_set"][model._features(CONFIG["history"])] + h = len(CONFIG["horizons_years"]) + + point = found["fitted_mixture"].predict_proba(X) + banded = found["fitted_model"].named_steps["mixture"].predict_proba(X) + + assert found["fitted_mixture"].interval_level is None and banded.shape == (len(X), 3 * h) + np.testing.assert_allclose(banded[:, :h], point) + low, high, known = banded[:, h:2 * h], banded[:, 2 * h:], ~np.isnan(point) + assert (np.isnan(low) == ~known).all() and (low[known] <= point[known]).all() and (point[known] <= high[known]).all() + assert (high[known] - low[known]).max() > 0 + + +def test_the_scenario_says_what_its_number_is(): + """Pins down: `[estimand]` reaches the scenario with what the screens show next to each risk. Fails if the key is + renamed or `Scenario.from_toml` stops reading it.""" + assert SCENARIO.estimand["quantity"] == "Probabilidad" and SCENARIO.estimand["horizons_unit"] == "años" + assert "KPNC" in SCENARIO.estimand["covariates"] + assert {"description", "outcome", "index_date"} <= set(SCENARIO.estimand) and "interval" not in SCENARIO.estimand + + def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame): """Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN (not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up.""" @@ -349,6 +421,36 @@ def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters return namespace +def test_the_subgroup_figure_draws_risks_in_percent(): + """Pins down: the report's curves are in percent, like the patient's risk and the table, with the axis saying so. + Fails if the figure goes back to proportions, which read as a risk a hundred times smaller.""" + from models.cacu.cin2_pim import report + + curve = {"years": [0.0, 5.0], "CR": [0.1, 0.2], "low": [0.05, 0.15], "high": [0.15, 0.25]} + record = {"combination": {"cytology": "LSIL", "hpv_positive": "positivo"}, "n": 10, "prevalent": 1, + "incident": 1, "empirical": curve, "model": curve, "e_o": []} + + figure = report._figure([record], [0.0, 5.0]) + + assert [list(t.y) for t in figure.data if t.name in ("Turnbull", "Mezcla prevalencia-incidencia")] == [[10.0, 20.0]] * 2 + assert figure.layout.yaxis.ticksuffix == " %" and "%" in figure.layout.yaxis.title.text + + +def test_each_subgroup_panel_has_its_own_scale(): + """Pins down: panels don't share the y axis, so each combination's curves fill their panel. Fails if the + subplots go back to one shared scale, where a 0.5 % curve is a flat line next to a 50 % one.""" + from models.cacu.cin2_pim import report + + def record(level, risk): + curve = {"years": [0.0, 5.0], "CR": [risk, risk], "low": [risk, risk], "high": [risk, risk]} + return {"combination": {"cytology": level, "hpv_positive": "positivo"}, "n": 10, "prevalent": 1, + "incident": 1, "empirical": curve, "model": curve, "e_o": []} + + figure = report._figure([record("NILM", 0.005), record("HSIL+", 0.5)], [0.0, 5.0]) + + assert figure.layout.yaxis2.matches is None and figure.layout.yaxis2.anchor == "x2" + + def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch): """Pins down the PIM report's notebook (`models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb`): its cells run on a build's file with the platform's environment, compute the same combinations the dataflow does and draw them. Fails diff --git a/tests/cacu/test_cin2_pim_kpnc_reference.py b/tests/cacu/test_cin2_pim_kpnc_reference.py new file mode 100644 index 0000000..2ae1e14 --- /dev/null +++ b/tests/cacu/test_cin2_pim_kpnc_reference.py @@ -0,0 +1,49 @@ +"""What this module covers: `models.cacu.cin2_pim.likelihood` against KPNC's published risks (Cheung et al. 2020, +doi:10.1097/LGT.0000000000000528; tables of Egemen et al. 2020, doi:10.1097/LGT.0000000000000529). + +`data/kpnc_reference.csv` holds the published cumulative risks at 0–5 years of the KPNC curves that one shared +I-spline baseline (order 4, 3 knots) with a proportional factor per curve reproduces to the rounding of the tables +(bayes-pim chapters 6 and 25): table 1 (screening, one baseline per current HPV), 17 (post-colposcopy), 18 +(post-colposcopy, 2nd visit, the exact groups only), 24 and 25 (post-treatment). Each row is one curve with its group's +knots and γ and its own η; its CR(0) is the published one. Tables 4, 19 and 26, which no grouping reproduces, are left +out. Aggregates of public tables only. +""" + +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from scipy.special import logit + +from models.cacu.cin2_pim import likelihood as L + +REFERENCE = pd.read_csv(Path(__file__).parent / "data" / "kpnc_reference.csv", dtype={"table": str}) +YEARS = range(6) + + +@pytest.mark.parametrize("key, group", list(REFERENCE.groupby(["table", "outcome", "group"])), + ids=lambda v: " ".join(v) if isinstance(v, tuple) else "") +def test_the_mixture_gives_kpncs_published_risks(key, group): + """Pins down: with KPNC's knots, γ and η, `cumulative_risk` (logistic prevalence, PIMixture's I-splines, + proportional hazards) gives every published risk at 0–5 years to 1e-12. Fails if the I-spline basis, its + parameterization (exp γ), the proportional factor or the mixture CR = π + (1 − π)(1 − S) drift from PIMixture's.""" + knots, gamma = json.loads(group["knots"].iloc[0]), np.array(json.loads(group["gamma"].iloc[0])) + n = len(group) + with np.errstate(divide="ignore"): + theta = logit(group["cr0"].to_numpy()) + fitted = {"theta": theta, "beta": group["eta"].to_numpy(), "baseline": L.ISpline(tuple(knots), order=4), + "baseline_params": gamma} + + found = L.cumulative_risk(fitted, np.eye(n), np.eye(n), YEARS) + + published = group[[f"cr{t}" for t in YEARS]].to_numpy() + np.testing.assert_allclose(found, published, rtol=0, atol=1e-12) + + +def test_the_reference_covers_the_scenarios_tables(): + """Pins down: the fixture keeps the screening table and the post-colposcopy and post-treatment ones, both outcomes + each. Fails if a rebuild of the fixture drops a table the scenarios are checked against.""" + assert {(t, o) for t, o in REFERENCE[["table", "outcome"]].itertuples(index=False)} == { + (t, o) for t in ("1", "17", "18", "24", "25") for o in ("CIN2+", "CIN3+")} diff --git a/tests/io/test_adapters.py b/tests/io/test_adapters.py index 0c6693e..0d63abb 100644 --- a/tests/io/test_adapters.py +++ b/tests/io/test_adapters.py @@ -139,6 +139,21 @@ def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scen assert training.find_trained(scenario, CohortFile(cohort_file)) == version +def test_training_stores_the_drawing_of_its_dataflow_as_files_of_the_version(scenario, cohort_file, mlflow_tracking): + """Pins down: the version lists `diagramas/pipeline.dot` and, with Graphviz's `dot`, `diagramas/pipeline.svg`, one + file each (no archive), and the drawing names the scenario's nodes. Fails if training stops drawing its graph or + stores it as anything but separate files.""" + pytest.importorskip("graphviz") + version = training.train(scenario, CohortFile(cohort_file)) + + files = {f["path"] for f in registry.artifacts("cacu", "fake_scenario", version)} + name, dot = registry.artifact("cacu", "fake_scenario", version, "diagramas/pipeline.dot") + assert name == "pipeline.dot" and b"fitted_model" in dot and b"metrics" in dot + assert "diagramas/pipeline.svg" in files or not training.pipeline_drawing( + training.dataflow(*scenario.modules, config=scenario.config))[1] + assert not any(path.endswith(".zip") for path in files) + + def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking, predict_without_repository): """Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the @@ -196,3 +211,13 @@ def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohor assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines assert not [line for line in lines if line.startswith("-e") or "/" in line] + + +def test_without_graphviz_training_has_no_drawing_and_still_registers(): + """Pins down: when Hamilton can't draw (no `graphviz` package, it gives None instead of raising), the drawing + is skipped rather than stopping the training. Fails if `pipeline_drawing` reads a missing graph.""" + from types import SimpleNamespace + + from models.dags.training import pipeline_drawing + + assert pipeline_drawing(SimpleNamespace(display_all_functions=lambda *a, **k: None)) is None diff --git a/tests/io/test_registry.py b/tests/io/test_registry.py index 535490c..d870f37 100644 --- a/tests/io/test_registry.py +++ b/tests/io/test_registry.py @@ -1,4 +1,4 @@ -"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and +"""What this module covers: the registry's promotion checks, promotion and retirement, the scenarios in production, the lineage of a version, and what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`). Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model; @@ -108,6 +108,19 @@ def test_retire_and_lineage(production_ready): registry.retire(domain, scenario, second) +def test_in_production_lists_the_scenarios_holding_the_alias(production_ready): + """Only scenarios of the domain with a version in production are listed; a candidate or a retired one is not. + Fails if `in_production` stops reading the `produccion` alias or leaks another domain's models.""" + domain, scenario, version = production_ready("v1") + production_ready("v1-dx", scenario="diagnostico") + assert registry.in_production(domain) == [] + registry.promote(domain, scenario, version) + assert registry.in_production(domain) == [scenario] + assert registry.in_production("cama") == [] + registry.retire(domain, scenario, version) + assert registry.in_production(domain) == [] + + @pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")]) def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario): with pytest.raises(ValueError): diff --git a/tests/reports/test_templates.py b/tests/reports/test_templates.py index bb6912a..2011d05 100644 --- a/tests/reports/test_templates.py +++ b/tests/reports/test_templates.py @@ -13,7 +13,7 @@ def test_the_cacu_templates_are_listed_with_the_scenarios_they_serve(): found = {t["id"]: t for t in notebook_templates("cacu")} pim, survival = found["cacu/cin2_pim/reporte_subgrupos"], found["cacu/survival/reporte_subgrupos"] - assert pim["scenarios"] == ["cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"] + assert pim["scenarios"] == ["cancer_pim", "cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"] assert survival["scenarios"] == ["survival"] and survival["domain"] == "cacu" and survival["title"] diff --git a/tests/tea/ados2_cohort.py b/tests/tea/ados2_cohort.py new file mode 100644 index 0000000..078b855 --- /dev/null +++ b/tests/tea/ados2_cohort.py @@ -0,0 +1,35 @@ +"""An invented ADOS-2 association cohort: one row per child in the `tea` library's cohort columns, with two planted +effects (spikes in temporal_izq raise item 18, spindles in central lower the CSS) and everything else null.""" +import numpy as np +import pandas as pd + +from tea.associations.ados2 import _items as items +from tea.contracts import ZONES + +ITEM_CODES = sorted({c for _, _, codes in items.ITEMS.values() for c in codes.values()}) + + +def cohort(n: int = 60, seed: int = 4, with_items: bool = True) -> pd.DataFrame: + rng = np.random.default_rng(seed) + age = rng.uniform(16, 37, n).round(1) + module = np.where(age < 31, "TODDLER", np.where(rng.random(n) < .7, "MODULO_1", "MODULO_2")) + t = pd.DataFrame({"key": [f"e-{i:03d}" for i in range(n)], "age_months": age, "ados_module": module}) + shared = rng.normal(0, 1, n) + for zone in ZONES: + t[f"z_spikes_{zone}"] = (.5 * shared + .85 * rng.normal(0, 1, n)).round(3) + t[f"z_spindles_{zone}"] = rng.normal(0, 1, n).round(3) + t["z_posterior_rhythm"] = rng.normal(0, 1, n).round(3) + t["z_gradient"] = rng.normal(0, 1, n).round(3) + for number, (_, _, codes) in items.ITEMS.items(): + latent = rng.logistic(0, 1, n) + (1.6 * t["z_spikes_temporal_izq"].to_numpy() if number == 18 else 0) + level = np.digitize(latent, [-.3, 1.4, 3.2]) + for m, code in codes.items(): + if code not in t: + t[code] = np.nan + t.loc[t.ados_module == m, code] = level[t.ados_module.to_numpy() == m] + severity = rng.normal(0, 1, n) - .9 * t["z_spindles_central"].to_numpy() + t["css"] = np.clip(np.round(6 + 1.8 * severity), 1, 10).astype(int) + for code in ITEM_CODES: + if code not in t: + t[code] = np.nan + return t if with_items else t.drop(columns=ITEM_CODES) diff --git a/tests/tea/test_ados2_association.py b/tests/tea/test_ados2_association.py new file mode 100644 index 0000000..45415fd --- /dev/null +++ b/tests/tea/test_ados2_association.py @@ -0,0 +1,141 @@ +"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and +`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome +codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state. + +Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2 +above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in +central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both +implementations fitted once on each cohort. +""" +import numpy as np +import pandas as pd +import pytest +from ados2_cohort import ITEM_CODES, cohort + +from tea.associations.ados2 import Ados2Association +from tea.associations.ados2 import _items as items +from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES +from tea.legacy.associations.ados2 import LegacyAdos2Association + +@pytest.fixture(scope="module") +def cohort_items(): + """60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS.""" + return cohort() + + +@pytest.fixture(scope="module") +def cohort_css(cohort_items): + """The same children with the CSS only, as when the psychologist reports no items.""" + return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items]) + + +@pytest.fixture(scope="module") +def fits(cohort_items, cohort_css): + """Modern and legacy, each fitted once on both cohorts, by (impl, level).""" + return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association), + ("legacy", LegacyAdos2Association)) + for level, c in (("item", cohort_items), ("domain", cohort_css))} + + +def test_level_follows_the_cohort_and_codes_are_module_independent(fits): + """Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry + `ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior` + or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one + code is another item in another module), or a zone code leaves the shared list.""" + for impl in ("modern", "legacy"): + assert fits[impl, "item"].fitted["level"] == "item" + assert fits[impl, "domain"].fitted["level"] == "domain" + a = fits[impl, "item"].associations() + assert list(a.columns) == list(ASSOCIATION_COLUMNS) + assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"} + assert set(a.loc[a.kind == "item", "event"]) == {">=1"} + assert set(a.loc[a.kind == "domain", "event"]) == {">=8"} + assert set(a.zone) <= set(ZONES) | {"posterior", "global"} + assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"} + + +def test_the_planted_effects_are_found(fits): + """Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS + fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit, + the item read per module, or the q values break.""" + a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"]) + item = a.loc[("spikes", "temporal_izq", "ados2_item_18")] + assert item.odds_ratio > 1 and item.q < .05 + d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"]) + css = d.loc[("spindles", "central", "CSS")] + assert css.odds_ratio < 1 and css.q < .05 + + +@pytest.mark.parametrize("level", ["item", "domain"]) +def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level): + """Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child + probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC + intercept or pair list drifts from the other.""" + cohort = cohort_items if level == "item" else cohort_css + m, legacy = fits["modern", level], fits["legacy", level] + keys = ["biomarker", "zone", "outcome_code"] + joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1") + assert len(joined) == len(m.associations()) == len(legacy.associations()) + for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"): + np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9) + scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1") + assert len(scores) == len(legacy.score(cohort)) > 0 + np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9) + np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9) + + +def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items): + """Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2, + and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by + one column code for every module.""" + t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"], + "sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]}) + assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0] + assert np.isnan(items.item_scores(t, 11).iloc[3]) + + +def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path): + """Pins down: a child is scored on an item only when its module has that item, every score row has a z and a + probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the + saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`.""" + m = fits["modern", "item"] + scores = m.score(cohort_items) + assert list(scores.columns) == list(SCORE_COLUMNS) + modules = cohort_items.set_index("key").ados_module + item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only + assert set(modules[item_16.key]) <= {"MODULO_2"} + assert scores.probability.between(0, 1).all() and scores.z.notna().all() + m.save(tmp_path) + again = Ados2Association.load(tmp_path).score(cohort_items) + pd.testing.assert_frame_equal(scores, again) + + +def test_registered_under_the_association_groups(): + """Pins down: both implementations resolve through the entry points and pass the association protocol, and + the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the + pipeline's module groups.""" + from tea.pipeline import registry + + assert registry.association("ados2_association").impl == "modern" + assert registry.association("ados2_association", "legacy").impl == "legacy" + assert "ados2_association" not in registry.available("modern") + + +def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items): + """Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability + instead of the reference module's. Fails if unseen levels fall back to all-zero indicators.""" + m = fits["modern", "domain"] + other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"]) + assert m.score(other).empty + + +def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css): + """Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason + and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a + singular information matrix aborts the whole fit, or `inf` reaches the design.""" + t = cohort_css.copy() + t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float) + t.loc[0, "z_posterior_rhythm"] = np.inf + a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"]) + assert a["odds_ratio"].notna().sum() >= len(a) - 2 + assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1 diff --git a/tests/tea/test_ados2_relate.py b/tests/tea/test_ados2_relate.py new file mode 100644 index 0000000..2d4638f --- /dev/null +++ b/tests/tea/test_ados2_relate.py @@ -0,0 +1,140 @@ +"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort +it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and +`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing). + +Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item +scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid +analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an +invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2. +""" +from datetime import date, datetime + +import pytest +from ados2_cohort import ITEM_CODES, cohort +from sqlmodel import Session, select + +from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente +from models import ados2_relation as rel +from tea.contracts import ZONES + +CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR", + "gradient": "GRADIENTE_ANTEROPOSTERIOR"} + + +def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1): + session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid, + eeg_edad_meses=float(row.age_months))) + for biomarker, code in CODES.items(): + met_id = f"{eeg_id}/{code}" + zoned = biomarker in rel.ZONED + session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code, + met_z=None if zoned else float(row[f"z_{biomarker}"]))) + if zoned: + session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z, + mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES]) + + +def _engine(): + from persistance.db import get_tea_engine + + return get_tea_engine() + + +@pytest.fixture +def stored(tea_db): + """The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists.""" + t = cohort().drop(columns=ITEM_CODES) + with Session(_engine()) as s: + for i, row in t.iterrows(): + pac_id = i + 1 + s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}")) + s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1), + ado_modulo=row.ados_module, ado_css=int(row.css))) + _eeg(s, row.key, pac_id, row) + _eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1)) + _eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0) + s.add(Pacientes(pac_id=99, pac_id_hospital="H-99")) + _eeg(s, "e-099", 99, t.iloc[2]) + s.commit() + return t + + +def _read(): + with Session(_engine()) as s: + return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all() + + +def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored): + """Pins down: one fit writes a `tea-