Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c12ea569cf | |||
| 3908ddf74d | |||
| 2a04ee8c8e | |||
| f9d97f4d12 | |||
| 674bdc4bb2 | |||
| 678c02b79d | |||
| 1c445286eb | |||
| 706f7510c5 | |||
| 07c91adbe6 | |||
| 8545c36bc4 | |||
| 6d653e9f17 | |||
| a9ab8612f8 | |||
| b3e02f0980 | |||
| 5a10be44d0 | |||
| 547ceedea3 | |||
| d91ac7c14b | |||
| 94c7cf93dc | |||
| 73c5176482 | |||
| 9c7c718a7b | |||
| 42161eb612 | |||
| c70aef2a04 | |||
| 0b25a5687e |
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "tea"]
|
||||
path = libs/tea
|
||||
url = ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
url = ../../alberto/tea.git
|
||||
|
||||
+1
-1
Submodule libs/tea updated: 05ee02990c...ed31baf70f
+47
-1
@@ -4,8 +4,10 @@ Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit
|
||||
command that needs them, so `--help` stays immediate.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import asdict
|
||||
|
||||
|
||||
def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||
@@ -164,13 +166,49 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
|
||||
|
||||
def _tea_analyze(args: argparse.Namespace) -> int:
|
||||
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
|
||||
if args.ids is not None and (args.all or args.limit is not None):
|
||||
print("--ids cannot be combined with --all or --limit", file=sys.stderr)
|
||||
return 2
|
||||
ids = [value.strip() for value in args.ids.split(",")] if args.ids is not None else None
|
||||
if ids is not None and not all(ids):
|
||||
print("--ids requires a comma-separated list of EEG ids", file=sys.stderr)
|
||||
return 2
|
||||
from models.eeg_analysis import analyze_pending
|
||||
|
||||
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
|
||||
try:
|
||||
s = analyze_pending(everything=args.all, limit=args.limit, ids=ids, cluster=args.cluster)
|
||||
except LookupError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
|
||||
print(f"summary: {json.dumps(asdict(s))}")
|
||||
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
|
||||
@@ -518,9 +556,17 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
|
||||
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
|
||||
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
|
||||
analyze.add_argument("--ids", help="comma-separated EEG IDs to analyse again")
|
||||
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)")
|
||||
|
||||
@@ -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-<UTC time>-<fingerprint>`: 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_<biomarker>_<zone>` and `z_<biomarker>`."""
|
||||
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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import os
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
CSV_ENTRADA = "./brca_metabric_clinical_data.tsv"
|
||||
DIR_INT = "./intermedios_recurrencia"
|
||||
os.makedirs(DIR_INT, exist_ok=True)
|
||||
V_MAX = 0.80
|
||||
|
||||
d = pd.read_csv(CSV_ENTRADA, sep="\t")
|
||||
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
|
||||
|
||||
out = pd.DataFrame({"paciente": d["Patient ID"]})
|
||||
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
|
||||
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
|
||||
|
||||
def con_desconocido(s):
|
||||
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
|
||||
|
||||
def cortar(s, cortes, etiquetas):
|
||||
c = pd.cut(s, cortes, labels=etiquetas, right=False)
|
||||
return con_desconocido(c.astype("object"))
|
||||
|
||||
out["Edad"] = cortar(d["Age at Diagnosis"], [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||
out["Tamano_tumor"] = cortar(d["Tumor Size"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
||||
out["Ganglios_positivos"] = cortar(d["Lymph nodes examined positive"], [0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
||||
out["Grado_histologico"] = con_desconocido(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
|
||||
mc = d["Mutation Count"]
|
||||
q = mc.quantile([1 / 3, 2 / 3]).values
|
||||
out["Carga_mutacional"] = cortar(mc, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
|
||||
for nombre, col in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
|
||||
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
|
||||
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
|
||||
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
|
||||
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
|
||||
out[nombre] = con_desconocido(d[col])
|
||||
|
||||
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
|
||||
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento")]
|
||||
|
||||
|
||||
def cramer_v(a, b):
|
||||
t = pd.crosstab(a, b)
|
||||
from scipy.stats import chi2_contingency
|
||||
chi2 = chi2_contingency(t, correction=False)[0]
|
||||
n = t.values.sum()
|
||||
k = min(t.shape) - 1
|
||||
return np.sqrt(chi2 / (n * k)) if k > 0 else 0.0
|
||||
|
||||
|
||||
eliminadas = []
|
||||
cand = [c for c in covariables if c not in TRATAMIENTO]
|
||||
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
|
||||
for v, a, b in pares:
|
||||
if v < V_MAX:
|
||||
break
|
||||
if a in eliminadas or b in eliminadas:
|
||||
continue
|
||||
na_a, na_b = (out[a] == "Desconocido").mean(), (out[b] == "Desconocido").mean()
|
||||
quitar = a if na_a >= na_b else b
|
||||
eliminadas.append(quitar)
|
||||
covariables.remove(quitar)
|
||||
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia.csv", index=False)
|
||||
|
||||
out = out[["paciente", "tiempo_meses", "evento"] + covariables]
|
||||
out.to_csv(f"{DIR_INT}/cohorte_recurrencia.csv", index=False)
|
||||
with open(f"{DIR_INT}/covariables_recurrencia.json", "w", encoding="utf8") as f:
|
||||
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
|
||||
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
|
||||
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
import os
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import chi2_contingency
|
||||
|
||||
CSV_ENTRADA = "./scanb_clinical_metadata.txt"
|
||||
V_MAX = 0.80
|
||||
DIAS_POR_MES = 30.4375
|
||||
DIR_INT = "./intermedios_recurrencia"
|
||||
os.makedirs(DIR_INT, exist_ok=True)
|
||||
|
||||
d = pd.read_csv(CSV_ENTRADA, sep="\t", low_memory=False)
|
||||
d = d[d["Gender"] == "F"]
|
||||
d = d.dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
|
||||
|
||||
out = pd.DataFrame({"paciente": d["PatientName"]})
|
||||
out["tiempo_meses"] = d["RFI_days"].astype(float) / DIAS_POR_MES
|
||||
out["evento"] = d["RFI_event"].astype(int)
|
||||
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
|
||||
|
||||
|
||||
def con_desconocido(s):
|
||||
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
|
||||
|
||||
|
||||
def cortar(s, cortes, etiquetas):
|
||||
return con_desconocido(pd.cut(s, cortes, labels=etiquetas, right=False).astype("object"))
|
||||
|
||||
|
||||
out["Edad"] = cortar(d["Age_5year_bin"].astype(float) - 2, [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||
out["Tamano_tumor"] = cortar(d["TumorSize_mm"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
||||
out["Ganglios_positivos"] = con_desconocido(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
|
||||
out["Grado_histologico"] = con_desconocido(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
|
||||
for nombre, col in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
|
||||
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
|
||||
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
|
||||
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
|
||||
out[nombre] = con_desconocido(d[col])
|
||||
|
||||
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
|
||||
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento", "muerte_sin_recaida")]
|
||||
|
||||
|
||||
def cramer_v(a, b):
|
||||
t = pd.crosstab(a, b)
|
||||
chi2 = chi2_contingency(t, correction=False)[0]
|
||||
k = min(t.shape) - 1
|
||||
return np.sqrt(chi2 / (t.values.sum() * k)) if k > 0 else 0.0
|
||||
|
||||
|
||||
eliminadas = []
|
||||
cand = [c for c in covariables if c not in TRATAMIENTO]
|
||||
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
|
||||
for v, a, b in pares:
|
||||
if v < V_MAX:
|
||||
break
|
||||
if a in eliminadas or b in eliminadas:
|
||||
continue
|
||||
quitar = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
|
||||
eliminadas.append(quitar)
|
||||
covariables.remove(quitar)
|
||||
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia_scanb.csv", index=False)
|
||||
|
||||
out = out[["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] + covariables]
|
||||
out.to_csv(f"{DIR_INT}/cohorte_recurrencia_scanb.csv", index=False)
|
||||
with open(f"{DIR_INT}/covariables_recurrencia_scanb.json", "w", encoding="utf8") as f:
|
||||
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
|
||||
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
|
||||
@@ -0,0 +1,261 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.metrics import roc_auc_score, roc_curve
|
||||
from sklearn.calibration import calibration_curve
|
||||
from lifelines import CoxPHFitter
|
||||
from lifelines.utils import concordance_index
|
||||
from pgmpy.estimators import HillClimbSearch, BDeu
|
||||
from pgmpy.causal_discovery import ExpertKnowledge
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import networkx as nx
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
|
||||
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
|
||||
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
|
||||
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
|
||||
os.makedirs(DIR_INT, exist_ok=True)
|
||||
os.makedirs(DIR_FIG, exist_ok=True)
|
||||
|
||||
SEMILLA = 42
|
||||
N_BOOTSTRAP = int(os.environ.get("N_BOOTSTRAP", 100 if COHORTE == "metabric" else 40))
|
||||
BDEU_ESS = 10
|
||||
MAX_PADRES = 6
|
||||
ALFA_IN, ALFA_OUT, ALFA_PREFILTRO = 0.10, 0.15, 0.10
|
||||
|
||||
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
|
||||
covariables = meta["covariables"]
|
||||
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
|
||||
|
||||
TIER_DEMOGRAFIA = ["Edad", "Estado_menopausico"]
|
||||
TIER_TUMOR = ["Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
|
||||
"Receptor_progesterona", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Cluster_integrativo", "Lateralidad",
|
||||
"Ki67", "Subtipo_clinico", "Estadio_clinico"]
|
||||
TIER_TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
|
||||
|
||||
|
||||
# ---- funciones ----
|
||||
def orden_temporal(cols):
|
||||
tiers = [[c for c in t if c in cols] for t in (TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, ["outcome"])]
|
||||
sin = [c for c in cols if c not in sum(tiers, [])]
|
||||
return ([sin] if sin else []) + [t for t in tiers if t]
|
||||
|
||||
|
||||
def codificar(df):
|
||||
X = pd.get_dummies(df[covariables], drop_first=True).astype(float)
|
||||
return X.loc[:, X.nunique() > 1]
|
||||
|
||||
|
||||
def ajuste_logit(y, X):
|
||||
try:
|
||||
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def prefiltro(X, y):
|
||||
keep = []
|
||||
for c in X.columns:
|
||||
m = ajuste_logit(y, X[[c]])
|
||||
if m is not None and m.pvalues[c] < ALFA_PREFILTRO:
|
||||
keep.append(c)
|
||||
return keep
|
||||
|
||||
|
||||
def stepwise(X, y):
|
||||
incl = []
|
||||
for _ in range(200):
|
||||
cambio = False
|
||||
mejor, p_mejor = None, ALFA_IN
|
||||
for c in [c for c in X.columns if c not in incl]:
|
||||
m = ajuste_logit(y, X[incl + [c]])
|
||||
if m is not None and m.pvalues[c] < p_mejor:
|
||||
mejor, p_mejor = c, m.pvalues[c]
|
||||
if mejor is not None:
|
||||
incl.append(mejor)
|
||||
cambio = True
|
||||
if incl:
|
||||
m = ajuste_logit(y, X[incl])
|
||||
if m is not None:
|
||||
p = m.pvalues.drop("const")
|
||||
if p.max() > ALFA_OUT:
|
||||
incl.remove(p.idxmax())
|
||||
cambio = True
|
||||
if not cambio:
|
||||
break
|
||||
return incl
|
||||
|
||||
|
||||
def lr_completo(df_train, df_test):
|
||||
Xall = codificar(pd.concat([df_train, df_test]))
|
||||
Xtr, Xte = Xall.loc[df_train.index], Xall.loc[df_test.index]
|
||||
Xtr = Xtr.loc[:, Xtr.nunique() > 1]
|
||||
Xte = Xte[Xtr.columns]
|
||||
cand = prefiltro(Xtr, df_train["y"])
|
||||
sel = stepwise(Xtr[cand], df_train["y"]) if cand else []
|
||||
if not sel:
|
||||
return None, [], np.full(len(df_test), df_train["y"].mean())
|
||||
m = ajuste_logit(df_train["y"], Xtr[sel])
|
||||
return m, sel, m.predict(sm.add_constant(Xte[sel], has_constant="add")).values
|
||||
|
||||
|
||||
def variable_de(t):
|
||||
return next((c for c in sorted(covariables, key=len, reverse=True) if t.startswith(c + "_")), t)
|
||||
|
||||
|
||||
def padres_outcome(train, candidatos):
|
||||
sc = BDeu(train, equivalent_sample_size=BDEU_ESS)
|
||||
padres, actual = [], sc.local_score("outcome", [])
|
||||
while len(padres) < MAX_PADRES:
|
||||
mejor, ganancia = None, 0
|
||||
for c in candidatos:
|
||||
if c in padres:
|
||||
continue
|
||||
g = sc.local_score("outcome", padres + [c]) - actual
|
||||
if g > ganancia:
|
||||
mejor, ganancia = c, g
|
||||
if mejor is None:
|
||||
break
|
||||
padres.append(mejor)
|
||||
actual += ganancia
|
||||
return padres
|
||||
|
||||
|
||||
def prob_hbn(train, test, padres):
|
||||
if not padres:
|
||||
return np.full(len(test), (train["outcome"] == "1").mean())
|
||||
q = int(np.prod([train[p].nunique() for p in padres]))
|
||||
alpha = BDEU_ESS / (2 * q)
|
||||
g = train.groupby(padres)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
||||
p_glob = (train["outcome"] == "1").mean()
|
||||
tabla = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
|
||||
return np.array([tabla.get(k, p_glob) for k in map(tuple, test[padres].values)])
|
||||
|
||||
|
||||
def tabla_bn(df):
|
||||
t = df[covariables].astype(str).copy()
|
||||
t["outcome"] = df["y"].astype(int).astype(str)
|
||||
return t
|
||||
|
||||
|
||||
def cohorte_a_horizonte(H):
|
||||
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
|
||||
libre = coh_total["tiempo_meses"] > H
|
||||
d = coh_total[recurre | libre].reset_index(drop=True)
|
||||
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
|
||||
return d
|
||||
|
||||
|
||||
# ---- Cox de referencia (tiempo completo) ----
|
||||
cox_df = pd.get_dummies(coh_total[["tiempo_meses", "evento"] + covariables], columns=covariables, drop_first=True).astype(float)
|
||||
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
|
||||
ctr, cte = train_test_split(cox_df, test_size=0.3, random_state=SEMILLA, stratify=cox_df["evento"])
|
||||
_ok = [c for c in ctr.columns if c in ("tiempo_meses", "evento") or 10 <= ctr[c].sum() <= len(ctr) - 10]
|
||||
ctr, cte = ctr[_ok], cte[_ok]
|
||||
cox = CoxPHFitter(penalizer=0.05).fit(ctr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
|
||||
c_index = concordance_index(cte["tiempo_meses"], -cox.predict_partial_hazard(cte), cte["evento"])
|
||||
|
||||
|
||||
# ---- modelos por horizonte ----
|
||||
filas_auc, modelos_json, curvas = [], {}, {}
|
||||
for H in HORIZONTES:
|
||||
coh = cohorte_a_horizonte(H)
|
||||
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=SEMILLA, stratify=coh["y"])
|
||||
tr, te = coh.loc[tr_idx], coh.loc[te_idx]
|
||||
|
||||
modelo_lr, sel_lr, p_lr = lr_completo(tr, te)
|
||||
auc_lr = roc_auc_score(te["y"], p_lr)
|
||||
|
||||
bn_tr, bn_te = tabla_bn(tr), tabla_bn(te)
|
||||
padres = padres_outcome(bn_tr, covariables)
|
||||
p_hbn = prob_hbn(bn_tr, bn_te, padres)
|
||||
auc_hbn = roc_auc_score(te["y"], p_hbn)
|
||||
|
||||
if H == max(HORIZONTES):
|
||||
expert = ExpertKnowledge(temporal_order=orden_temporal(list(bn_tr.columns)))
|
||||
estructura = HillClimbSearch(bn_tr).estimate(scoring_method=BDeu(bn_tr, equivalent_sample_size=BDEU_ESS), max_indegree=4,
|
||||
expert_knowledge=expert, show_progress=False)
|
||||
arcos_red = [(u, v) for u, v in estructura.edges() if u != "outcome" and v != "outcome"] + [(p, "outcome") for p in padres]
|
||||
G = nx.DiGraph(arcos_red)
|
||||
plt.figure(figsize=(10, 7))
|
||||
nx.draw(G, nx.spring_layout(G, seed=SEMILLA, k=0.9), with_labels=True, node_color="lightblue", node_size=2200, font_size=7, arrowsize=14)
|
||||
plt.title(f"Estructura de la red bayesiana ({COHORTE}, {H} meses)")
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"{DIR_FIG}/hbn_estructura_{COHORTE}.png", dpi=150)
|
||||
plt.close()
|
||||
|
||||
rng = np.random.default_rng(SEMILLA)
|
||||
aucs, cuenta_lr, cuenta_hbn, n_lr, n_hbn = [], {}, {}, 0, 0
|
||||
for b in range(N_BOOTSTRAP):
|
||||
db = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
|
||||
try:
|
||||
dtr, dte = train_test_split(db, test_size=0.3, random_state=SEMILLA + b, stratify=db["y"])
|
||||
m, sel, p = lr_completo(dtr, dte)
|
||||
a_lr = roc_auc_score(dte["y"], p)
|
||||
btr, bte = tabla_bn(dtr), tabla_bn(dte)
|
||||
pa = padres_outcome(btr, covariables)
|
||||
a_h = roc_auc_score(dte["y"], prob_hbn(btr, bte, pa))
|
||||
except Exception:
|
||||
continue
|
||||
aucs.append((a_lr, a_h))
|
||||
n_lr += 1
|
||||
n_hbn += 1
|
||||
if m is not None:
|
||||
for v in {variable_de(t) for t in m.params.drop("const").index}:
|
||||
cuenta_lr[v] = cuenta_lr.get(v, 0) + 1
|
||||
for v in pa:
|
||||
cuenta_hbn[v] = cuenta_hbn.get(v, 0) + 1
|
||||
aucs = np.array(aucs)
|
||||
for j, (nombre, auc_int) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
|
||||
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": H, "modelo": nombre, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
|
||||
"AUC_validacion_interna": auc_int, "AUC_bootstrap_medio": aucs[:, j].mean(),
|
||||
"AUC_bootstrap_IC95_inf": np.percentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.percentile(aucs[:, j], 97.5),
|
||||
"replicas_bootstrap": len(aucs)})
|
||||
ci = modelo_lr.conf_int()
|
||||
modelos_json[str(H)] = {"terminos_lr": list(sel_lr), "padres_hbn": padres, "n_replicas": n_lr,
|
||||
"seleccion_lr": cuenta_lr, "seleccion_hbn": cuenta_hbn,
|
||||
"arcos_hbn": [list(a) for a in (arcos_red if H == max(HORIZONTES) else [(p, "outcome") for p in padres])]}
|
||||
curvas[H] = (te["y"].values, p_lr, p_hbn)
|
||||
|
||||
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(coh_total),
|
||||
"recurrencias": int(coh_total["evento"].sum()), "AUC_validacion_interna": c_index})
|
||||
json.dump(modelos_json, open(f"{DIR_INT}/modelos{SFX}.json", "w", encoding="utf8"), indent=1, ensure_ascii=False)
|
||||
|
||||
# ---- consolidado de AUC (un solo archivo con las dos cohortes) ----
|
||||
nuevo = pd.DataFrame(filas_auc)
|
||||
destino = "./auc_recurrencia.csv"
|
||||
if os.path.exists(destino):
|
||||
previo = pd.read_csv(destino)
|
||||
previo = previo[~((previo["cohorte"] == COHORTE) & (previo["horizonte_meses"].astype(str).isin([str(h) for h in HORIZONTES] + ["completo"])))]
|
||||
nuevo = pd.concat([previo, nuevo], ignore_index=True)
|
||||
nuevo.round(4).to_csv(destino, index=False)
|
||||
|
||||
# ---- figuras: ROC y calibracion (un panel por horizonte) ----
|
||||
for nombre_fig, tipo in [("roc", "roc"), ("calibracion", "cal")]:
|
||||
fig, axs = plt.subplots(1, len(HORIZONTES), figsize=(5.2 * len(HORIZONTES), 5), squeeze=False)
|
||||
for ax, H in zip(axs[0], HORIZONTES):
|
||||
y, pl, ph = curvas[H]
|
||||
for nom, p in [("LR", pl), ("HBN", ph)]:
|
||||
if tipo == "roc":
|
||||
f, t, _ = roc_curve(y, p)
|
||||
ax.plot(f, t, label=f"{nom} (AUC {roc_auc_score(y, p):.3f})")
|
||||
else:
|
||||
fr, mp = calibration_curve(y, p, n_bins=8, strategy="quantile")
|
||||
ax.plot(mp, fr, "o-", label=nom)
|
||||
ax.plot([0, 1], [0, 1], "k:")
|
||||
ax.set_title(f"{COHORTE}: {H} meses")
|
||||
ax.set_xlabel("1 - especificidad" if tipo == "roc" else "probabilidad predicha de recurrencia")
|
||||
ax.set_ylabel("sensibilidad" if tipo == "roc" else "frecuencia observada")
|
||||
ax.legend()
|
||||
fig.tight_layout()
|
||||
fig.savefig(f"{DIR_FIG}/{nombre_fig}_{COHORTE}.png", dpi=150)
|
||||
plt.close(fig)
|
||||
@@ -0,0 +1,158 @@
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
|
||||
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
|
||||
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
|
||||
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
|
||||
DIR_INT = "./intermedios_recurrencia"
|
||||
ALFA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
|
||||
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
|
||||
variables = meta["covariables"]
|
||||
tratamiento = meta["tratamiento"]
|
||||
intrinsecas = [v for v in variables if v not in tratamiento]
|
||||
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
|
||||
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in variables})
|
||||
|
||||
|
||||
# ---- funciones ----
|
||||
def bh(p):
|
||||
p = np.asarray(p, float)
|
||||
orden = np.argsort(p)
|
||||
aj = np.empty_like(p)
|
||||
m = len(p)
|
||||
prev = 1.0
|
||||
for rango, i in zip(range(m, 0, -1), orden[::-1]):
|
||||
prev = min(prev, p[i] * m / rango)
|
||||
aj[i] = prev
|
||||
return aj
|
||||
|
||||
|
||||
def variable_de(termino, vars_modelo):
|
||||
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
|
||||
|
||||
|
||||
def km_en(m, e, h):
|
||||
T = int(m.max()) + 2
|
||||
d = np.bincount(m[e], minlength=T)
|
||||
c = np.bincount(m[~e], minlength=T)
|
||||
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
|
||||
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
|
||||
h = min(h, T - 1)
|
||||
S = np.prod(q[:h + 1])
|
||||
return S, S * np.sqrt(np.sum(v[:h + 1]))
|
||||
|
||||
|
||||
def procesar_horizonte(H):
|
||||
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
|
||||
libre = coh_total["tiempo_meses"] > H
|
||||
datos_km = coh_total.copy()
|
||||
coh = coh_total[recurre | libre].reset_index(drop=True)
|
||||
datos = coh[variables].astype(str)
|
||||
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
|
||||
meses = np.floor(np.minimum(datos_km["tiempo_meses"].values, H + 1)).astype(int)
|
||||
evento = ((datos_km["evento"] == 1) & (datos_km["tiempo_meses"] <= H)).values
|
||||
datos_km = datos_km[variables].astype(str)
|
||||
|
||||
def referencia(v):
|
||||
return datos[v].value_counts().idxmax()
|
||||
|
||||
def ajustar_or(vars_modelo):
|
||||
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
|
||||
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
|
||||
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
modelo = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ic = modelo.conf_int()
|
||||
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(modelo.params[X.columns].values),
|
||||
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
|
||||
"p": modelo.pvalues[X.columns].values})
|
||||
|
||||
def delta_s(v, cat, ref):
|
||||
a = (datos_km[v] == cat).values
|
||||
b = (datos_km[v] == ref).values
|
||||
Sa, ea = km_en(meses[a], evento[a], H)
|
||||
Sb, eb = km_en(meses[b], evento[b], H)
|
||||
d = Sa - Sb
|
||||
es = np.sqrt(ea ** 2 + eb ** 2)
|
||||
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
|
||||
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
|
||||
|
||||
def completar(t, vars_modelo):
|
||||
t = t.copy()
|
||||
t["variable"] = [variable_de(x, vars_modelo) for x in t["termino"]]
|
||||
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
|
||||
t["referencia"] = [referencia(v) for v in t["variable"]]
|
||||
t["p_ajustado_BH"] = bh(t["p"])
|
||||
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
|
||||
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
||||
|
||||
tab = completar(ajustar_or(intrinsecas), intrinsecas)
|
||||
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
|
||||
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
|
||||
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
|
||||
|
||||
mh = modelos.get(str(H), {})
|
||||
n_rep = mh.get("n_replicas", 0)
|
||||
sel = mh.get("seleccion_lr", {})
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: sel.get(v, 0) / n_rep if n_rep else np.nan)
|
||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
||||
manta = set(mh.get("padres_hbn", []))
|
||||
tab["en_manta_markov"] = tab["variable"].isin(manta)
|
||||
tab["c3_manta_markov"] = tab["en_manta_markov"]
|
||||
|
||||
crit = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
tab["criterios_cumplidos"] = tab[crit].astype(bool).sum(axis=1)
|
||||
|
||||
def clasificar(r):
|
||||
if r["categoria"] == "Desconocido":
|
||||
return "no aplica (categoria desconocida)"
|
||||
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
|
||||
return f"{r['direccion']} robusto"
|
||||
if r["criterios_cumplidos"] >= 2:
|
||||
return f"{r['direccion']} sugerente"
|
||||
return "no concluyente"
|
||||
|
||||
tab["clasificacion"] = tab.apply(clasificar, axis=1)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
|
||||
if tratamiento:
|
||||
tr = ajustar_or(intrinsecas + tratamiento)
|
||||
tr["_v"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
|
||||
tr = tr[tr["_v"].isin(tratamiento) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
|
||||
tr = completar(tr, tratamiento)
|
||||
tr["tipo"] = "tratamiento"
|
||||
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
tab = pd.concat([tab, tr], ignore_index=True)
|
||||
|
||||
tab["cohorte"] = COHORTE
|
||||
tab["horizonte_meses"] = H
|
||||
return tab
|
||||
|
||||
|
||||
columnas = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
|
||||
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
|
||||
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
|
||||
"criterios_cumplidos", "clasificacion"]
|
||||
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
|
||||
|
||||
nuevo = pd.concat([procesar_horizonte(H) for H in HORIZONTES], ignore_index=True)
|
||||
nuevo["_t"] = (nuevo["tipo"] != "factor de riesgo").astype(int)
|
||||
nuevo["_o"] = nuevo["clasificacion"].map(orden).fillna(5)
|
||||
nuevo = nuevo.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[columnas]
|
||||
|
||||
destino = "./factores_riesgo_recurrencia.csv"
|
||||
if os.path.exists(destino):
|
||||
previo = pd.read_csv(destino)
|
||||
previo = previo[previo["cohorte"] != COHORTE]
|
||||
nuevo = pd.concat([previo, nuevo], ignore_index=True)
|
||||
nuevo.round(4).to_csv(destino, index=False)
|
||||
@@ -0,0 +1,450 @@
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import subprocess
|
||||
import warnings
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.optimize import minimize
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
try:
|
||||
import mpmath as mp
|
||||
except ImportError:
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
|
||||
import mpmath as mp
|
||||
|
||||
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
|
||||
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
|
||||
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
|
||||
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
|
||||
os.makedirs(DIR_FIG, exist_ok=True)
|
||||
SEMILLA = 42
|
||||
B_BOOT = int(os.environ.get("N_BOOT_CALC", 200))
|
||||
MIN_EVENTOS = 15
|
||||
TOPE_MESES = 72
|
||||
BDEU_ESS = 10
|
||||
COLOR_PUNTOS, MARCA_PUNTOS = "#6a3d9a", "D"
|
||||
|
||||
SUBGRUPOS = {
|
||||
"metabric": {
|
||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
|
||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||
"< 45 años": {"Edad": ["<45"]},
|
||||
"≥ 75 años": {"Edad": ["75+"]},
|
||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
||||
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
|
||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
||||
},
|
||||
"scanb": {
|
||||
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
|
||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||
"< 45 años": {"Edad": ["<45"]},
|
||||
"≥ 75 años": {"Edad": ["75+"]},
|
||||
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
||||
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
||||
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
||||
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
|
||||
"Grado 3": {"Grado_histologico": ["3"]},
|
||||
},
|
||||
}[COHORTE]
|
||||
|
||||
|
||||
# ---- ajuste parametrico (Weibull y Weibull fraccional de Kilbas-Saigo) ----
|
||||
from functools import lru_cache
|
||||
from scipy.special import gammaln
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _coefs(rho, m, l, N, dps):
|
||||
mp.mp.dps = dps
|
||||
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
|
||||
c = [mp.mpf(1)]
|
||||
for i in range(N - 1):
|
||||
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
|
||||
return tuple(c)
|
||||
|
||||
def _log_terms(az, rho, m, l, N):
|
||||
i = np.arange(N - 1)
|
||||
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
|
||||
n = np.arange(N)
|
||||
with np.errstate(divide="ignore"):
|
||||
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
|
||||
return lt
|
||||
|
||||
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
|
||||
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
|
||||
out = np.full(z.shape, np.nan)
|
||||
az = np.abs(z)
|
||||
N = 400
|
||||
lt = _log_terms(az, rho, m, l, N)
|
||||
lmax, llast = lt.max(axis=1), lt[:, -1]
|
||||
zero = az == 0
|
||||
out[zero] = 1.0
|
||||
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
|
||||
if okf.any():
|
||||
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
|
||||
terms[:, 0] = 1.0
|
||||
out[okf] = terms.sum(axis=1)
|
||||
rest = np.where(~zero & ~okf)[0]
|
||||
if rest.size:
|
||||
with np.errstate(over="ignore"):
|
||||
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
|
||||
est = np.maximum(est, lmax[rest])
|
||||
use = rest[est <= logmax_cap]
|
||||
if use.size:
|
||||
est_u = est[est <= logmax_cap]
|
||||
dps = 30 + int(est_u.max() / 2.3) + 10
|
||||
zmax = float(az[use].max())
|
||||
with np.errstate(over="ignore"):
|
||||
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
|
||||
N2 = max(N2, 60)
|
||||
while True:
|
||||
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
|
||||
mp.mp.dps = dps
|
||||
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
|
||||
if last < tol or N2 >= nmax:
|
||||
break
|
||||
N2 *= 2
|
||||
if last < tol:
|
||||
cr = list(c)[::-1]
|
||||
for j in use:
|
||||
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
|
||||
return out
|
||||
|
||||
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
|
||||
tau1 = lam if tau1 is None else tau1
|
||||
tau2 = lam if tau2 is None else tau2
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
s = k + alpha - 2
|
||||
if k + alpha <= 1 or s + beta <= 0:
|
||||
return np.full_like(t, np.nan)
|
||||
m = s/beta + 1; l = s/beta
|
||||
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
|
||||
z = np.where(t > 0, z, 0.0)
|
||||
res = np.ones_like(t)
|
||||
pos = t > 0
|
||||
if pos.any():
|
||||
res[pos] = kilbas_saigo(z[pos], beta, m, l)
|
||||
return np.clip(res, 0.0, 1.0)
|
||||
|
||||
|
||||
def S_weibull(t, k, lam):
|
||||
t = np.asarray(t, float)
|
||||
return np.exp(-(t/lam)**k)
|
||||
|
||||
|
||||
def tabla_eventos(meses, evento):
|
||||
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
|
||||
T = int(meses.max()) + 2
|
||||
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
|
||||
return d, c
|
||||
|
||||
def _nll_from_S(Sfun, d, c):
|
||||
T = len(d)
|
||||
grid = np.arange(0, T + 1, dtype=float)
|
||||
Sg = Sfun(grid)
|
||||
mid = Sfun(np.arange(T) + 0.5)
|
||||
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
|
||||
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
|
||||
return 1e12
|
||||
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
|
||||
|
||||
def ajustar_weibull(d, c):
|
||||
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
|
||||
best = None
|
||||
for k0 in (0.7, 1.0, 1.5):
|
||||
for l0 in (50., 200., 1000.):
|
||||
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
|
||||
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
|
||||
if best is None or r.fun < best.fun: best = r
|
||||
k, lam = np.exp(best.x)
|
||||
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
|
||||
S=lambda t: S_weibull(t, k, lam))
|
||||
|
||||
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
|
||||
amin = max(0.0, 1.0 - k_fijo) + 1e-6
|
||||
def unpack(p):
|
||||
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
|
||||
T_max = float(len(d))
|
||||
t_fin = time.time() + max_seg
|
||||
agotado = [False]
|
||||
def f(p):
|
||||
if time.time() > t_fin:
|
||||
agotado[0] = True
|
||||
return 1e12
|
||||
a, b, lam = unpack(p)
|
||||
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
|
||||
return 1e12
|
||||
try:
|
||||
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
|
||||
except Exception:
|
||||
return 1e12
|
||||
lams = [lam_ref] if lam_ref else []
|
||||
lams += [100., 500.]
|
||||
best = None
|
||||
inicios = []
|
||||
if lam_ref:
|
||||
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
|
||||
for l0 in lams:
|
||||
for a0 in (0.3, 1.0):
|
||||
for b0 in (0.5, 0.9):
|
||||
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
|
||||
for p0 in inicios:
|
||||
if time.time() > t_fin and best is not None: break
|
||||
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
|
||||
if best is None or r.fun < best.fun: best = r
|
||||
a, b, lam = unpack(best.x)
|
||||
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
|
||||
S=lambda t: S_ks(t, k_fijo, a, b, lam))
|
||||
|
||||
|
||||
def km_curva(meses_int, evento, T):
|
||||
d, c = tabla_eventos(meses_int, evento)
|
||||
L = max(len(d), T + 1)
|
||||
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
|
||||
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
|
||||
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
|
||||
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
|
||||
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
se = np.sqrt(V) / np.abs(np.log(S))
|
||||
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
|
||||
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
|
||||
return S, lo, hi
|
||||
|
||||
# ---- datos y modelos ya seleccionados en 03_modelado.py ----
|
||||
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
|
||||
covariables = meta["covariables"]
|
||||
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
|
||||
df = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
|
||||
N = len(df)
|
||||
meses_int = np.floor(df["tiempo_meses"].values).astype(int)
|
||||
evento = (df["evento"] == 1).values
|
||||
tiempo, ev_num = df["tiempo_meses"].values, df["evento"].values
|
||||
|
||||
X_dum = pd.get_dummies(df[covariables], drop_first=True).astype(float)
|
||||
codigos = {v: pd.factorize(df[v])[0] for v in covariables}
|
||||
niveles = {v: int(codigos[v].max()) + 1 for v in covariables}
|
||||
|
||||
|
||||
def ajuste_logit(y, X):
|
||||
try:
|
||||
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def prob_lr(idx_ent, y_ent, terminos):
|
||||
if not terminos:
|
||||
return np.full(N, y_ent.mean())
|
||||
m = ajuste_logit(y_ent, X_dum.iloc[idx_ent][terminos])
|
||||
if m is None:
|
||||
return None
|
||||
return m.predict(sm.add_constant(X_dum[terminos], has_constant="add")).values
|
||||
|
||||
|
||||
def clave(padres, filas):
|
||||
k = np.zeros(len(filas), dtype=np.int64)
|
||||
for p in padres:
|
||||
k = k * niveles[p] + codigos[p][filas]
|
||||
return k
|
||||
|
||||
|
||||
def prob_hbn(idx_ent, y_ent, padres):
|
||||
if not padres:
|
||||
return np.full(N, y_ent.mean())
|
||||
q = int(np.prod([niveles[p] for p in padres]))
|
||||
alpha = BDEU_ESS / (2 * q)
|
||||
k_ent = clave(padres, idx_ent)
|
||||
n = pd.Series(1, index=k_ent).groupby(level=0).sum()
|
||||
n1 = pd.Series(y_ent, index=k_ent).groupby(level=0).sum()
|
||||
tabla = (n1 + alpha) / (n + 2 * alpha)
|
||||
p_glob = y_ent.mean()
|
||||
return tabla.reindex(clave(padres, np.arange(N))).fillna(p_glob).values
|
||||
|
||||
|
||||
def riesgos(idx, H):
|
||||
t, e = tiempo[idx], ev_num[idx]
|
||||
rec = (e == 1) & (t <= H)
|
||||
ok = rec | (t > H)
|
||||
ent = idx[ok]
|
||||
y = rec[ok].astype(int)
|
||||
mh = modelos[str(H)]
|
||||
pl = prob_lr(ent, y, mh["terminos_lr"])
|
||||
ph = prob_hbn(ent, y, mh["padres_hbn"])
|
||||
if pl is None:
|
||||
return None
|
||||
return pl, ph
|
||||
|
||||
|
||||
def riesgo_subgrupo(idx, masks):
|
||||
out = {n: np.full(len(HORIZONTES), np.nan) for n in masks}
|
||||
for j, H in enumerate(HORIZONTES):
|
||||
r = riesgos(idx, H)
|
||||
if r is None:
|
||||
return None
|
||||
comb = (r[0] + r[1]) / 2
|
||||
for n, mk in masks.items():
|
||||
sel = mk[idx]
|
||||
if sel.any():
|
||||
out[n][j] = comb[idx][sel].mean()
|
||||
return out
|
||||
|
||||
|
||||
# ---- subgrupos y bootstrap ----
|
||||
MASCARAS = {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in SUBGRUPOS.items()}
|
||||
todos = np.arange(N)
|
||||
puntos = riesgo_subgrupo(todos, MASCARAS)
|
||||
rng = np.random.default_rng(SEMILLA)
|
||||
boots = {n: [] for n in MASCARAS}
|
||||
for b in range(B_BOOT):
|
||||
r = riesgo_subgrupo(rng.integers(0, N, N), MASCARAS)
|
||||
if r is None:
|
||||
continue
|
||||
for n in MASCARAS:
|
||||
boots[n].append(r[n])
|
||||
|
||||
|
||||
def graficar(nombre, mk):
|
||||
sub = df[mk]
|
||||
n_, ev_ = len(sub), int(sub["evento"].sum())
|
||||
if n_ == 0 or ev_ < MIN_EVENTOS:
|
||||
return None
|
||||
m_s, e_s = meses_int[mk], evento[mk]
|
||||
d_, c_ = tabla_eventos(m_s, e_s)
|
||||
w_ = ajustar_weibull(d_, c_)
|
||||
ks_ = ajustar_ks(d_, c_, k_fijo=w_["k"], lam_ref=w_["lam"], max_seg=60)
|
||||
Tm = int(m_s.max())
|
||||
Sk, lok, hik = km_curva(m_s, e_s, Tm)
|
||||
tt = np.arange(Tm + 1)
|
||||
r = 1 - puntos[nombre]
|
||||
B = np.array(boots[nombre])
|
||||
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(HORIZONTES)), np.nan)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(9, 5.2))
|
||||
ax.fill_between(tt, lok, hik, step="post", color="#9aa5b1", alpha=.3, lw=0)
|
||||
ax.step(tt, Sk, where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
|
||||
for ajuste, col, ls, lb in [(w_, "#1f77b4", "-", "Weibull"), (ks_, "#d1495b", "--", "Weibull fraccional")]:
|
||||
t_in = np.linspace(0, Tm, 300)
|
||||
t_ex = np.linspace(Tm, TOPE_MESES, 200)
|
||||
ax.plot(t_in, ajuste["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
|
||||
ax.plot(t_ex, ajuste["S"](t_ex), color=col, lw=1.4, ls=":")
|
||||
ax.errorbar(HORIZONTES, r, yerr=[np.clip(r - ic[0], 0, None), np.clip(ic[1] - r, 0, None)], fmt=MARCA_PUNTOS, color=COLOR_PUNTOS,
|
||||
ms=9, capsize=4, lw=1.8, mec="white", mew=1, label="LR + HBN combinado (IC 95 % bootstrap)", zorder=5)
|
||||
x1 = TOPE_MESES + 0.8
|
||||
xs = np.linspace(0, x1, 400)
|
||||
v = np.concatenate([w_["S"](xs), ks_["S"](xs), Sk[:int(min(x1, Tm)) + 1], lok[:int(min(x1, Tm)) + 1], r, ic.ravel()])
|
||||
v = v[np.isfinite(v)]
|
||||
mg = (v.max() - v.min()) * .06
|
||||
ax.set_xlim(0, x1)
|
||||
ax.set_ylim(max(0, v.min() - mg), min(1.005, v.max() + mg))
|
||||
ax.set_xlabel("Meses desde el diagnóstico")
|
||||
ax.set_ylabel("Libre de recaída S(t)")
|
||||
ax.grid(alpha=.25)
|
||||
ax.set_title(f"{nombre}\n{'SCAN-B' if COHORTE == 'scanb' else 'METABRIC'} · n={n_:,}, recaídas={ev_:,}", fontsize=11)
|
||||
ax.legend(frameon=False, loc="lower left", fontsize=9)
|
||||
for sp in ("top", "right"):
|
||||
ax.spines[sp].set_visible(False)
|
||||
fig.tight_layout()
|
||||
arch = re.sub(r"[^A-Za-z0-9]+", "_", nombre.replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt")
|
||||
.replace("−", "neg").replace("+", "pos").replace("ñ", "n").replace("á", "a").replace("í", "i").replace("é", "e")).strip("_")
|
||||
fig.savefig(f"{DIR_FIG}/subgrupo_{COHORTE}_{arch}.png", dpi=170)
|
||||
plt.close(fig)
|
||||
filas = []
|
||||
for j, H in enumerate(HORIZONTES):
|
||||
filas.append({"cohorte": COHORTE, "subgrupo": nombre, "n": n_, "recaidas": ev_, "horizonte_meses": H,
|
||||
"S_libre_LR_HBN": r[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - r[j],
|
||||
"S_libre_KM": Sk[min(H, Tm)] if H <= Tm else np.nan, "replicas_bootstrap": len(B)})
|
||||
return filas
|
||||
|
||||
|
||||
filas = []
|
||||
for nombre, mk in MASCARAS.items():
|
||||
f = graficar(nombre, mk)
|
||||
if f:
|
||||
filas += f
|
||||
|
||||
nuevo = pd.DataFrame(filas)
|
||||
destino = "./calculadora_recurrencia_subgrupos.csv"
|
||||
if os.path.exists(destino):
|
||||
previo = pd.read_csv(destino)
|
||||
nuevo = pd.concat([previo[previo["cohorte"] != COHORTE], nuevo], ignore_index=True)
|
||||
nuevo.round(4).to_csv(destino, index=False)
|
||||
|
||||
|
||||
# ---- escenarios clinicos: factores de riesgo que incluye cada subgrupo ----
|
||||
PCT_DEFINITORIA = 0.95
|
||||
PCT_MAYORITARIA = 0.50
|
||||
PCT_PRESENTE = 0.10
|
||||
|
||||
|
||||
def nivel_presencia(p):
|
||||
if p >= PCT_DEFINITORIA:
|
||||
return "definitoria"
|
||||
if p >= PCT_MAYORITARIA:
|
||||
return "mayoritaria"
|
||||
return "presente" if p >= PCT_PRESENTE else "minoritaria"
|
||||
|
||||
|
||||
def definicion(cond):
|
||||
return "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
|
||||
|
||||
|
||||
if os.path.exists("./factores_riesgo_recurrencia.csv"):
|
||||
fr = pd.read_csv("./factores_riesgo_recurrencia.csv", dtype={"categoria": str})
|
||||
fr = fr[(fr["cohorte"] == COHORTE) & fr["horizonte_meses"].isin(HORIZONTES)]
|
||||
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
|
||||
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
|
||||
filas_esc, filas_res = [], []
|
||||
for nombre, mk in MASCARAS.items():
|
||||
n_sub = int(mk.sum())
|
||||
if n_sub == 0:
|
||||
continue
|
||||
cond = SUBGRUPOS[nombre]
|
||||
pct = {}
|
||||
for v, c in set(zip(fr["variable"], fr["categoria"])):
|
||||
pct[(v, c)] = (float((df.loc[mk, v] == c).mean()), float((df[v] == c).mean()))
|
||||
det = fr.copy()
|
||||
det["pct_en_escenario"] = [pct[(v, c)][0] for v, c in zip(det["variable"], det["categoria"])]
|
||||
det["pct_en_cohorte"] = [pct[(v, c)][1] for v, c in zip(det["variable"], det["categoria"])]
|
||||
det["presencia"] = det["pct_en_escenario"].map(nivel_presencia)
|
||||
det["en_definicion"] = [c in cond.get(v, []) for v, c in zip(det["variable"], det["categoria"])]
|
||||
det.insert(0, "escenario", nombre)
|
||||
det.insert(1, "definicion", definicion(cond))
|
||||
det.insert(2, "n_escenario", n_sub)
|
||||
columnas = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
|
||||
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte",
|
||||
"presencia", "en_definicion"]
|
||||
filas_esc.append(det[det["pct_en_escenario"] >= PCT_PRESENTE][columnas])
|
||||
for H in HORIZONTES:
|
||||
d = det[det["horizonte_meses"] == H]
|
||||
fila = {"cohorte": COHORTE, "escenario": nombre, "definicion": definicion(cond), "n_escenario": n_sub, "horizonte_meses": H}
|
||||
for tipo in ("riesgo", "protector", "tratamiento"):
|
||||
for nivel, etiqueta in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
|
||||
s_ = d[(d["tipo_efecto"] == tipo) & (d["presencia"] == nivel)]
|
||||
fila[f"{tipo}_{etiqueta}"] = "; ".join(
|
||||
f"{v}={c} ({k.split()[-1] if tipo != 'tratamiento' else 'asociacion'}, {p:.0%})"
|
||||
for v, c, k, p in zip(s_["variable"], s_["categoria"], s_["clasificacion"], s_["pct_en_escenario"]))
|
||||
fila["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
|
||||
fila["incluye_factor_riesgo"] = fila["n_factores_riesgo_incluidos"] > 0
|
||||
filas_res.append(fila)
|
||||
for archivo, filas_x in (("./escenarios_factores_riesgo_recurrencia.csv", pd.concat(filas_esc, ignore_index=True)),
|
||||
("./escenarios_resumen_recurrencia.csv", pd.DataFrame(filas_res))):
|
||||
if os.path.exists(archivo):
|
||||
previo = pd.read_csv(archivo)
|
||||
filas_x = pd.concat([previo[previo["cohorte"] != COHORTE], filas_x], ignore_index=True)
|
||||
filas_x.round(4).to_csv(archivo, index=False)
|
||||
@@ -0,0 +1,33 @@
|
||||
import argparse
|
||||
import csv
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cohorte", choices=["metabric", "scanb"])
|
||||
ap.add_argument("--horizontes", nargs="+", default=["12", "36", "60"])
|
||||
a = ap.parse_args()
|
||||
cohortes = [a.cohorte] if a.cohorte else ["metabric", "scanb"]
|
||||
prep = {"metabric": "01_preparacion_metabric.py", "scanb": "02_preparacion_scanb.py"}
|
||||
|
||||
pasos = []
|
||||
for c in cohortes:
|
||||
pasos.append((f"preparacion_{c}", [prep[c]]))
|
||||
pasos.append((f"03_modelado_{c}", ["03_modelado.py", c] + a.horizontes))
|
||||
pasos.append((f"04_factores_riesgo_{c}", ["04_factores_riesgo.py", c] + a.horizontes))
|
||||
pasos.append((f"05_calculadora_{c}", ["05_calculadora.py", c] + a.horizontes))
|
||||
|
||||
bit = []
|
||||
for nombre, cmd in pasos:
|
||||
t0 = time.time()
|
||||
r = subprocess.run([sys.executable, "-W", "ignore"] + cmd, capture_output=True, text=True)
|
||||
bit.append([nombre, "ok" if r.returncode == 0 else "ERROR", round(time.time() - t0, 1)])
|
||||
with open("bitacora_recurrencia.csv", "w", newline="", encoding="utf8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["paso", "estado", "segundos"])
|
||||
w.writerows(bit)
|
||||
if r.returncode != 0:
|
||||
sys.stderr.write(f"\n[{nombre}] fallo:\n{r.stderr[-3000:]}\n")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Luis's recurrence analysis of one cohort over its frame (`cohort.recode`): the covariates that survive the
|
||||
collinearity pruning, the logistic regression and the Bayesian network's outcome parents of each horizon, and the figure
|
||||
of each clinical scenario (Kaplan-Meier with its Greenwood band, the Weibull and the fractional Weibull, and the
|
||||
combined estimate at each horizon with its bootstrap interval).
|
||||
|
||||
Every number a stage uses is the model's (`modeling`, `calculator` of `model.toml`).
|
||||
"""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from pgmpy.estimators import BDeu
|
||||
from scipy.stats import chi2_contingency
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.seer_survival.fractional_weibull import ajustar_ks, ajustar_weibull, km_curva, tabla_eventos
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
|
||||
def cramer_v(a: pd.Series, b: pd.Series) -> float:
|
||||
table = pd.crosstab(a, b)
|
||||
chi2 = chi2_contingency(table, correction=False)[0]
|
||||
k = min(table.shape) - 1
|
||||
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
|
||||
|
||||
|
||||
def prune_covariates(frame: pd.DataFrame, covariates: list[str], treatment: list[str], settings: dict) -> tuple[list, list]:
|
||||
"""Of each pair of non-treatment covariates with Cramér's V at or above the limit, the one with more unknowns goes."""
|
||||
unknown = settings["unknown_label"]
|
||||
kept, dropped = list(covariates), []
|
||||
candidates = [c for c in covariates if c not in treatment]
|
||||
pairs = sorted(((cramer_v(frame[a], frame[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]),
|
||||
reverse=True)
|
||||
for v, a, b in pairs:
|
||||
if v < settings["cramer_v_max"]:
|
||||
break
|
||||
if a in dropped or b in dropped:
|
||||
continue
|
||||
out = a if (frame[a] == unknown).mean() >= (frame[b] == unknown).mean() else b
|
||||
dropped.append(out)
|
||||
kept.remove(out)
|
||||
return kept, dropped
|
||||
|
||||
|
||||
def horizon_cohort(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
||||
"""The patients who recurred by the horizon or are free beyond it; the rest were censored before it and are left out."""
|
||||
recurred = (frame["evento"] == 1) & (frame["tiempo_meses"] <= horizon)
|
||||
free = frame["tiempo_meses"] > horizon
|
||||
out = frame[recurred | free].reset_index(drop=True)
|
||||
out["y"] = ((out["evento"] == 1) & (out["tiempo_meses"] <= horizon)).astype(int)
|
||||
return out
|
||||
|
||||
|
||||
def _encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
|
||||
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
||||
return X.loc[:, X.nunique() > 1]
|
||||
|
||||
|
||||
def _logit(y, X):
|
||||
try:
|
||||
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _prefilter(X: pd.DataFrame, y, alpha: float) -> list[str]:
|
||||
keep = []
|
||||
for c in X.columns:
|
||||
fit = _logit(y, X[[c]])
|
||||
if fit is not None and fit.pvalues[c] < alpha:
|
||||
keep.append(c)
|
||||
return keep
|
||||
|
||||
|
||||
def _stepwise(X: pd.DataFrame, y, alpha_in: float, alpha_out: float) -> list[str]:
|
||||
chosen: list[str] = []
|
||||
for _ in range(200):
|
||||
changed = False
|
||||
best, best_p = None, alpha_in
|
||||
for c in [c for c in X.columns if c not in chosen]:
|
||||
fit = _logit(y, X[chosen + [c]])
|
||||
if fit is not None and fit.pvalues[c] < best_p:
|
||||
best, best_p = c, fit.pvalues[c]
|
||||
if best is not None:
|
||||
chosen.append(best)
|
||||
changed = True
|
||||
if chosen:
|
||||
fit = _logit(y, X[chosen])
|
||||
if fit is not None:
|
||||
p = fit.pvalues.drop("const")
|
||||
if p.max() > alpha_out:
|
||||
chosen.remove(p.idxmax())
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
return chosen
|
||||
|
||||
|
||||
def logistic_terms(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
|
||||
both = _encode(pd.concat([train, test]), covariates)
|
||||
X = both.loc[train.index]
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
candidates = _prefilter(X, train["y"], settings["alpha_prefilter"])
|
||||
return _stepwise(X[candidates], train["y"], settings["alpha_in"], settings["alpha_out"]) if candidates else []
|
||||
|
||||
|
||||
def outcome_parents(frame: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
|
||||
"""The outcome's parents by greedy BDeu, at most `max_parents`."""
|
||||
table = frame[covariates].astype(str).copy()
|
||||
table["outcome"] = frame["y"].astype(int).astype(str)
|
||||
score = BDeu(table, equivalent_sample_size=settings["bdeu_ess"])
|
||||
parents, current = [], score.local_score("outcome", [])
|
||||
while len(parents) < settings["max_parents"]:
|
||||
best, gain = None, 0
|
||||
for c in covariates:
|
||||
if c in parents:
|
||||
continue
|
||||
g = score.local_score("outcome", parents + [c]) - current
|
||||
if g > gain:
|
||||
best, gain = c, g
|
||||
if best is None:
|
||||
break
|
||||
parents.append(best)
|
||||
current += gain
|
||||
return parents
|
||||
|
||||
|
||||
def select_models(frame: pd.DataFrame, covariates: list[str], horizons: list[int], settings: dict) -> dict:
|
||||
"""The logistic terms and the Bayesian network's outcome parents of each horizon, selected on the 70/30 split."""
|
||||
models = {}
|
||||
for horizon in horizons:
|
||||
cohort = horizon_cohort(frame, horizon)
|
||||
train_idx, test_idx = train_test_split(cohort.index, test_size=settings["test_share"], random_state=settings["seed"],
|
||||
stratify=cohort["y"])
|
||||
train, test = cohort.loc[train_idx], cohort.loc[test_idx]
|
||||
models[horizon] = {"lr_terms": logistic_terms(train, test, covariates, settings),
|
||||
"hbn_parents": outcome_parents(train, covariates, settings)}
|
||||
return models
|
||||
|
||||
|
||||
class Calculator:
|
||||
"""The combined estimate (mean of the logistic regression and the Bayesian network) of a group of patients, refitting
|
||||
both on any resample of the cohort with the terms and parents selected for each horizon."""
|
||||
|
||||
def __init__(self, frame: pd.DataFrame, covariates: list[str], models: dict, horizons: list[int], ess: int):
|
||||
self.frame, self.horizons, self.models, self.ess = frame, horizons, models, ess
|
||||
self.n = len(frame)
|
||||
self.time = frame["tiempo_meses"].to_numpy()
|
||||
self.event = frame["evento"].to_numpy()
|
||||
self.dummies = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
||||
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
|
||||
self.levels = {v: int(self.codes[v].max()) + 1 for v in covariates}
|
||||
|
||||
def _lr(self, rows, y, terms):
|
||||
if not terms:
|
||||
return np.full(self.n, y.mean())
|
||||
fit = _logit(y, self.dummies.iloc[rows][terms])
|
||||
if fit is None:
|
||||
return None
|
||||
return fit.predict(sm.add_constant(self.dummies[terms], has_constant="add")).to_numpy()
|
||||
|
||||
def _key(self, parents, rows):
|
||||
key = np.zeros(len(rows), dtype=np.int64)
|
||||
for p in parents:
|
||||
key = key * self.levels[p] + self.codes[p][rows]
|
||||
return key
|
||||
|
||||
def _hbn(self, rows, y, parents):
|
||||
if not parents:
|
||||
return np.full(self.n, y.mean())
|
||||
q = int(np.prod([self.levels[p] for p in parents]))
|
||||
alpha = self.ess / (2 * q)
|
||||
key = self._key(parents, rows)
|
||||
n = pd.Series(1, index=key).groupby(level=0).sum()
|
||||
n1 = pd.Series(y, index=key).groupby(level=0).sum()
|
||||
table = (n1 + alpha) / (n + 2 * alpha)
|
||||
return table.reindex(self._key(parents, np.arange(self.n))).fillna(y.mean()).to_numpy()
|
||||
|
||||
def risk(self, rows: np.ndarray, masks: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None:
|
||||
"""For each group, its members' mean combined risk at every horizon, fitted on `rows` (a resample or all)."""
|
||||
out = {name: np.full(len(self.horizons), np.nan) for name in masks}
|
||||
for j, horizon in enumerate(self.horizons):
|
||||
t, e = self.time[rows], self.event[rows]
|
||||
recurred = (e == 1) & (t <= horizon)
|
||||
fit_rows = rows[recurred | (t > horizon)]
|
||||
y = recurred[recurred | (t > horizon)].astype(int)
|
||||
model = self.models[horizon]
|
||||
lr = self._lr(fit_rows, y, model["lr_terms"])
|
||||
if lr is None:
|
||||
return None
|
||||
combined = (lr + self._hbn(fit_rows, y, model["hbn_parents"])) / 2
|
||||
for name, mask in masks.items():
|
||||
chosen = mask[rows]
|
||||
if chosen.any():
|
||||
out[name][j] = combined[rows][chosen].mean()
|
||||
return out
|
||||
|
||||
def bootstrap(self, masks: dict[str, np.ndarray], replicas: int, seed: int) -> dict[str, list]:
|
||||
rng = np.random.default_rng(seed)
|
||||
draws = {name: [] for name in masks}
|
||||
for _ in range(replicas):
|
||||
risk = self.risk(rng.integers(0, self.n, self.n), masks)
|
||||
if risk is None:
|
||||
continue
|
||||
for name in masks:
|
||||
draws[name].append(risk[name])
|
||||
return draws
|
||||
|
||||
|
||||
def scenario_masks(frame: pd.DataFrame, scenarios: list[dict]) -> dict[str, np.ndarray]:
|
||||
return {s["name"]: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in s["when"].items()]) for s in scenarios}
|
||||
|
||||
|
||||
def scenario_figure(frame: pd.DataFrame, name: str, mask: np.ndarray, point: np.ndarray, draws: list,
|
||||
horizons: list[int], settings: dict) -> dict | None:
|
||||
"""The figure record of a scenario, or None when it has fewer recurrences than the calculator draws."""
|
||||
members = frame[mask]
|
||||
events = int(members["evento"].sum())
|
||||
if len(members) == 0 or events < settings["min_events"]:
|
||||
return None
|
||||
months = np.floor(members["tiempo_meses"].to_numpy()).astype(int)
|
||||
event = (members["evento"] == 1).to_numpy()
|
||||
d, c = tabla_eventos(months, event)
|
||||
weibull = ajustar_weibull(d, c)
|
||||
fractional = ajustar_ks(d, c, k_fijo=weibull["k"], lam_ref=weibull["lam"], max_seg=settings["fractional_weibull_budget_s"])
|
||||
last = int(months.max())
|
||||
survival, low, high = km_curva(months, event, last)
|
||||
t = np.arange(0, settings["cap_months"] * 4 + 1) / 4
|
||||
free = 1 - point
|
||||
boot = np.array(draws)
|
||||
interval = 1 - np.nanpercentile(boot, [97.5, 2.5], axis=0) if len(boot) else np.full((2, len(horizons)), np.nan)
|
||||
clean = lambda a: [None if not np.isfinite(x) else float(x) for x in a]
|
||||
return {
|
||||
"escenario": name, "n": int(len(members)), "recaidas": events, "observado_hasta": last,
|
||||
"months_max": settings["cap_months"], "horizons_months": horizons, "bootstrap_replicas": len(boot),
|
||||
"km": {"months": list(range(last + 1)), "S": clean(survival), "low": clean(low), "high": clean(high)},
|
||||
"weibull": {"t": t.tolist(), "S": clean(weibull["S"](t))},
|
||||
"weibull_fractional": {"t": t.tolist(), "S": clean(fractional["S"](t))},
|
||||
"points": {"COMB": {"S": clean(free), "low": clean(interval[0]), "high": clean(interval[1])}},
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence
|
||||
event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `cohorts.toml`).
|
||||
|
||||
The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from
|
||||
it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to
|
||||
`window_days_after_index` after the index; a category no rule gives is the variable's `missing` one.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival.variables import Reader, category_of
|
||||
|
||||
TOML = Path(__file__).with_name("cohorts.toml")
|
||||
SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"}
|
||||
|
||||
|
||||
def load(path: Path = TOML) -> dict:
|
||||
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _spec(dictionary: dict, name: str, cohort: str) -> dict:
|
||||
spec = dictionary[name]
|
||||
own = spec.get(cohort, {})
|
||||
return {**spec, "rules": own["rules"]} if "rules" in own else spec
|
||||
|
||||
|
||||
def _cut(values: pd.Series, cuts: list, labels: list, missing: str) -> pd.Series:
|
||||
cut = pd.cut(values, cuts, labels=labels, right=False)
|
||||
return cut.astype("object").where(cut.notna(), missing).astype(str)
|
||||
|
||||
|
||||
def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool = True, follow_up: bool = True) -> pd.DataFrame:
|
||||
"""One row per patient. `of_source` keeps only the patients whose record comes from this cohort's source (a patient of
|
||||
another source is read with the same variables when it is false); `follow_up` drops those with no recurrence or
|
||||
last contact, whose time is unknown."""
|
||||
dictionary = model["variables"]
|
||||
index = dictionary["index"]
|
||||
events = events.copy()
|
||||
events["fecha"] = pd.to_datetime(events["fecha"])
|
||||
events["fecha_indice"] = pd.to_datetime(events["fecha_indice"])
|
||||
|
||||
if of_source:
|
||||
source = events[events["tipo"] == "fuente"].groupby("pac_id")["valor_codigo"].last()
|
||||
patients = pd.Index(sorted(source[source == SOURCE_CODE[cohort]].index), name="pac_id")
|
||||
else:
|
||||
patients = pd.Index(sorted(events["pac_id"].unique()), name="pac_id")
|
||||
events = events[events["pac_id"].isin(patients)]
|
||||
start = events.groupby("pac_id")["fecha_indice"].first().reindex(patients)
|
||||
recurrence = events[events["tipo"] == index["recurrence_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
|
||||
contact = events[events["tipo"] == index["last_contact_source"]].groupby("pac_id")["fecha"].max().reindex(patients)
|
||||
end = recurrence.fillna(contact)
|
||||
birth = events[events["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
|
||||
|
||||
window = pd.Timedelta(days=int(dictionary["window_days_after_index"]))
|
||||
visible = events[events["fecha"] <= events["pac_id"].map(start) + window]
|
||||
reader = Reader(visible, patients, {})
|
||||
|
||||
result = pd.DataFrame(index=patients)
|
||||
result["paciente"] = patients.to_numpy()
|
||||
result["tiempo_meses"] = ((end - start).dt.days / index["days_per_month"]).to_numpy()
|
||||
result["evento"] = recurrence.notna().astype(int).to_numpy()
|
||||
unknown = dictionary["Edad"]["missing"]
|
||||
for name in model["cohorts"][cohort]["covariates"]:
|
||||
spec = _spec(dictionary, name, cohort)
|
||||
if name == "Edad":
|
||||
age = (start - birth).dt.days / 365.25
|
||||
result[name] = _cut(age, spec["cuts"], spec["labels"], unknown).to_numpy()
|
||||
elif "rules" in spec:
|
||||
category = category_of(spec, reader)
|
||||
labels = spec.get(cohort, {}).get("labels", {})
|
||||
result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy()
|
||||
elif spec.get("terciles"):
|
||||
count = reader.value(spec["source"], True)
|
||||
if count.notna().sum() == 0:
|
||||
result[name] = spec["missing"]
|
||||
continue
|
||||
q = count.quantile([1 / 3, 2 / 3]).to_numpy()
|
||||
result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy()
|
||||
else:
|
||||
result[name] = _cut(reader.value(spec["source"], True), spec["cuts"], spec["labels"], spec["missing"]).to_numpy()
|
||||
keep = start.notna().to_numpy() & (end.notna().to_numpy() if follow_up else True)
|
||||
result = result[keep]
|
||||
return result.reset_index(drop=True)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import
|
||||
schemas take, to be uploaded through the platform's import like any other source.
|
||||
|
||||
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR [--diagnosis-from 2018-01-01 --spread-days 540
|
||||
--censor 2026-11-21]
|
||||
|
||||
What goes where is the dictionary's (`[variables.*]` of `cohorts.toml`): each source category is stored as the catalog value
|
||||
the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day
|
||||
of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the
|
||||
follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps
|
||||
the month it falls in and its side of every horizon.
|
||||
|
||||
`--diagnosis-from` places the diagnoses in a window of the platform's own (spread over `--spread-days` days, the same day for
|
||||
the same patient on every run) in place of the dictionary's fixed year, and `--censor` ends every follow-up by that day: a
|
||||
recurrence after it is not known yet, and the patient is a last contact on that day.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import math
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
TOML = Path(__file__).with_name("cohorts.toml")
|
||||
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos",
|
||||
"SeguimientoMama": "seguimientos"}
|
||||
FEMALE = "Femenino"
|
||||
UNKNOWN = {"", "NA", "nan", "NaN", "None"}
|
||||
|
||||
|
||||
def load(path: Path = TOML) -> dict:
|
||||
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def follow_up_days(months: float, horizons: list[int], days_per_month: float) -> int:
|
||||
"""The whole days nearest to `months` that keep floor(months) and, for each horizon, whether the follow-up is within it."""
|
||||
exact = months * days_per_month
|
||||
month = math.floor(months)
|
||||
low = math.ceil(month * days_per_month)
|
||||
high = math.ceil((month + 1) * days_per_month) - 1
|
||||
sides = [months <= h for h in horizons]
|
||||
first = int(round(exact))
|
||||
for step in range(0, high - low + 2):
|
||||
for day in (first - step, first + step):
|
||||
if low <= day <= high and math.floor(day / days_per_month) == month \
|
||||
and [day / days_per_month <= h for h in horizons] == sides:
|
||||
return day
|
||||
return first
|
||||
|
||||
|
||||
def _known(raw: pd.Series) -> pd.Series:
|
||||
return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN)
|
||||
|
||||
|
||||
def _spread(ids: pd.Series, days: int) -> pd.Series:
|
||||
"""A day in [0, days) per patient, fixed by her identifier."""
|
||||
return ids.map(lambda i: int.from_bytes(hashlib.sha256(str(i).encode()).digest()[:4], "big") % days)
|
||||
|
||||
|
||||
def convert(raw: pd.DataFrame, cohort: str, model: dict, *, diagnosis_from: str | None = None, spread_days: int = 1,
|
||||
censor: str | None = None) -> dict[str, pd.DataFrame]:
|
||||
dictionary = model["variables"]
|
||||
index = dictionary["index"]
|
||||
cfg = dictionary["cohorts"][cohort]
|
||||
covariates = model["cohorts"][cohort]["covariates"]
|
||||
horizons = model["config"]["horizons_months"]
|
||||
dpm = index["days_per_month"]
|
||||
|
||||
frame = raw
|
||||
if cfg["sex_filter"]:
|
||||
frame = frame[frame[cfg["sex_filter"]["column"]] == cfg["sex_filter"]["value"]]
|
||||
frame = frame[_known(frame[cfg["months"]]) & _known(frame[cfg["event"]])].copy()
|
||||
|
||||
if cohort == "scanb":
|
||||
days = pd.to_numeric(frame[cfg["months"]]).round().astype(int)
|
||||
event = pd.to_numeric(frame[cfg["event"]]).astype(int)
|
||||
else:
|
||||
months = pd.to_numeric(frame[cfg["months"]])
|
||||
days = pd.Series([follow_up_days(m, horizons, dpm) for m in months], index=frame.index)
|
||||
event = frame[cfg["event"]].astype(str).str.startswith(cfg["event_prefix"]).astype(int)
|
||||
|
||||
age = pd.to_numeric(frame[cfg["diagnosis_age"]], errors="coerce") + cfg.get("diagnosis_age_offset", 0)
|
||||
frame, days, event, age = (x[age.notna()] for x in (frame, days, event, age))
|
||||
if "diagnosis_year_column" in cfg:
|
||||
year = pd.to_numeric(frame[cfg["diagnosis_year_column"]], errors="coerce").fillna(2000).astype(int)
|
||||
else:
|
||||
year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index)
|
||||
diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"])
|
||||
if diagnosis_from:
|
||||
diagnosis = pd.Timestamp(diagnosis_from) + pd.to_timedelta(_spread(frame[cfg["id"]], spread_days), unit="D")
|
||||
birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D")
|
||||
end = diagnosis + pd.to_timedelta(days, unit="D")
|
||||
if censor:
|
||||
late = end > pd.Timestamp(censor)
|
||||
event = event.where(~late, 0)
|
||||
end = end.where(~late, pd.Timestamp(censor))
|
||||
ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str)
|
||||
date = lambda s: s.dt.strftime("%Y-%m-%d")
|
||||
|
||||
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
|
||||
tables["Paciente"]["pac_sexo"] = FEMALE
|
||||
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
|
||||
tables["Paciente"]["pac_fuente"] = "SCANB" if cohort == "scanb" else "METABRIC"
|
||||
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
|
||||
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
|
||||
|
||||
treatments = []
|
||||
for name in covariates:
|
||||
spec = dictionary[name]
|
||||
source = spec.get(cohort)
|
||||
if not source or "column" not in source:
|
||||
continue
|
||||
column = frame[source["column"]]
|
||||
known = _known(column)
|
||||
if "treatment" in spec:
|
||||
code = column.astype(str).map(source["values"])
|
||||
code = code.where(~known | code.notna(), source.get("absent")).where(known)
|
||||
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": spec["treatment"], "trat_fecha": date(diagnosis),
|
||||
"trat_detalle": code})[code.notna()]
|
||||
if spec["treatment"] == "cirugia":
|
||||
rows["trat_lateralidad"] = None
|
||||
treatments.append(rows)
|
||||
continue
|
||||
if "bronze" not in spec:
|
||||
continue
|
||||
entity, target = spec["bronze"].split(".")
|
||||
if "number_values" in source:
|
||||
value = column.astype(str).map(source["number_values"])
|
||||
elif "values" in source:
|
||||
value = column.astype(str).map(source["values"])
|
||||
else:
|
||||
value = pd.to_numeric(column.where(known), errors="coerce")
|
||||
tables[entity][target] = value.where(known)
|
||||
|
||||
tables["BiopsiaMama"]["bx_grado_histologico"] = "CARCINOMA_INVASOR"
|
||||
if "Cirugia" in covariates and "bx_lateralidad" in tables["BiopsiaMama"]:
|
||||
for rows in treatments:
|
||||
if (rows["trat_tipo"] == "cirugia").any():
|
||||
rows["trat_lateralidad"] = tables["BiopsiaMama"]["bx_lateralidad"].reindex(rows.index)
|
||||
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
|
||||
|
||||
notes = tables["NotaMedica"]
|
||||
notes["nm_id_hospital"] = ident + "-dx"
|
||||
notes["nm_fecha"] = date(diagnosis)
|
||||
notes["nm_tipo_nota"] = "CONSULTA"
|
||||
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(end),
|
||||
"nm_tipo_nota": "EGRESO"})
|
||||
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
|
||||
|
||||
recurred = event.eq(1)
|
||||
contact = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["last_contact_source"], "seg_fecha": date(end),
|
||||
"seg_detalle": "VIVA"})[~recurred]
|
||||
recurrence = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["recurrence_source"], "seg_fecha": date(end),
|
||||
"seg_detalle": "NO_ESPECIFICADO"})[recurred]
|
||||
tables["SeguimientoMama"] = pd.concat([recurrence, contact], ignore_index=True)
|
||||
return tables
|
||||
|
||||
|
||||
def main(argv=None) -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("cohort", choices=["metabric", "scanb"])
|
||||
ap.add_argument("file")
|
||||
ap.add_argument("out_dir")
|
||||
ap.add_argument("--diagnosis-from", help="first day of the diagnoses (YYYY-MM-DD); the dictionary's year without it")
|
||||
ap.add_argument("--spread-days", type=int, default=1, help="days over which the diagnoses are spread")
|
||||
ap.add_argument("--censor", help="last day of follow-up (YYYY-MM-DD)")
|
||||
args = ap.parse_args(argv)
|
||||
raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False)
|
||||
out = Path(args.out_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for entity, table in convert(raw, args.cohort, load(), diagnosis_from=args.diagnosis_from,
|
||||
spread_days=args.spread_days, censor=args.censor).items():
|
||||
table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,400 @@
|
||||
# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and
|
||||
# clinical scenarios, as in his scripts; the cohorts are not pooled.
|
||||
domain = "cama"
|
||||
scenario = "recurrence"
|
||||
cohort = "cama/cohorte_total"
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"]
|
||||
settings_tables = ["modeling", "calculator", "variables"]
|
||||
description = """
|
||||
Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \
|
||||
sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico."""
|
||||
|
||||
[config]
|
||||
horizons_months = [12, 36, 60]
|
||||
|
||||
# ---- settings of the stages (Luis's scripts 03, 04 and 05) ----
|
||||
[modeling]
|
||||
seed = 42
|
||||
unknown_label = "Desconocido"
|
||||
cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped
|
||||
alpha_prefilter = 0.10 # univariate prefilter of the logistic regression
|
||||
alpha_in = 0.10 # stepwise: p to enter
|
||||
alpha_out = 0.15 # stepwise: p to leave
|
||||
bdeu_ess = 10
|
||||
max_parents = 6
|
||||
test_share = 0.30 # the 70/30 split of the AUC
|
||||
|
||||
[calculator]
|
||||
min_events = 15 # a scenario is drawn only with at least this many recurrences
|
||||
bootstrap_replicas = 200
|
||||
cap_months = 72 # the curves are drawn dotted past the follow-up up to here
|
||||
fractional_weibull_budget_s = 60
|
||||
|
||||
# ---- the variable dictionary ----
|
||||
# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give
|
||||
# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed).
|
||||
# `<cohort>.column` is the source file's column; `<cohort>.values` maps its values to the codes the loader sends;
|
||||
# `<cohort>.labels` renames the rules' category where the source names it differently (neutral label = source label);
|
||||
# `[variables.X.<cohort>]` replaces the rules for a variable whose categories differ between the cohorts.
|
||||
[variables]
|
||||
window_days_after_index = 365
|
||||
|
||||
[variables.index]
|
||||
id_column = "paciente"
|
||||
months_column = "tiempo_meses"
|
||||
event_column = "evento"
|
||||
death_source = "defuncion"
|
||||
birth_source = "nacimiento"
|
||||
recurrence_source = "recurrencia"
|
||||
last_contact_source = "ultimo_contacto"
|
||||
days_per_month = 30.4375
|
||||
|
||||
[variables.cohorts.metabric]
|
||||
id = "Patient ID"
|
||||
months = "Relapse Free Status (Months)"
|
||||
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
|
||||
event_prefix = "1"
|
||||
diagnosis_age = "Age at Diagnosis" # years
|
||||
sex_filter = {}
|
||||
diagnosis_month_day = "07-01"
|
||||
diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it
|
||||
# Per covariate, the source columns and category cuts as the preparation script defines them.
|
||||
|
||||
[variables.cohorts.scanb]
|
||||
id = "PatientName"
|
||||
months = "RFI_days" # days, divided by days_per_month
|
||||
months_divisor = 30.4375
|
||||
event = "RFI_event"
|
||||
sex_filter = { column = "Gender", value = "F" }
|
||||
diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script
|
||||
diagnosis_age_offset = -2
|
||||
diagnosis_month_day = "07-01"
|
||||
diagnosis_year_column = "dxYear"
|
||||
|
||||
# Cuts shared by both cohorts (pd.cut with the right edge open).
|
||||
[variables.Edad]
|
||||
cuts = [0, 45, 60, 75, 200]
|
||||
labels = ["<45", "45-59", "60-74", "75+"]
|
||||
missing = "Desconocido"
|
||||
|
||||
[variables.Tamano_tumor]
|
||||
bronze = "BiopsiaMama.bx_tamano_tumor_mm"
|
||||
source = "tamano_tumor_mm"
|
||||
cuts = [0, 20.01, 50.01, 10000]
|
||||
labels = ["<=20 mm", "21-50 mm", ">50 mm"]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Tumor Size" }
|
||||
scanb = { column = "TumorSize_mm" }
|
||||
|
||||
[variables.Ganglios_positivos]
|
||||
bronze = "BiopsiaMama.bx_ganglios_positivos"
|
||||
source = "ganglios_positivos"
|
||||
cuts = [0, 1, 4, 1000]
|
||||
labels = ["0", "1-3", "4+"]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Lymph nodes examined positive" }
|
||||
scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } }
|
||||
|
||||
[variables.Grado_histologico]
|
||||
bronze = "BiopsiaMama.bx_grado_nottingham"
|
||||
rules = [
|
||||
{ source = "grado_nottingham", codes = ["G1"], then = "1" },
|
||||
{ source = "grado_nottingham", codes = ["G2"], then = "2" },
|
||||
{ source = "grado_nottingham", codes = ["G3"], then = "3" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } }
|
||||
scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } }
|
||||
|
||||
[variables.Receptor_estrogeno]
|
||||
bronze = "BiopsiaMama.bx_receptor_estrogeno"
|
||||
rules = [
|
||||
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" },
|
||||
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
|
||||
scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
|
||||
|
||||
[variables.Receptor_progesterona]
|
||||
bronze = "BiopsiaMama.bx_receptor_progesterona"
|
||||
rules = [
|
||||
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" },
|
||||
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
|
||||
scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
|
||||
|
||||
[variables.HER2]
|
||||
bronze = "BiopsiaMama.bx_her2_fish"
|
||||
rules = [
|
||||
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positive" },
|
||||
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" },
|
||||
{ source = "her2", codes = ["H3"], then = "Positive" },
|
||||
{ source = "her2", codes = ["H0", "H1"], then = "Negative" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
|
||||
scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
|
||||
|
||||
[variables.Tipo_histologico]
|
||||
bronze = "BiopsiaMama.bx_tipo_histologico"
|
||||
rules = [
|
||||
{ source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" },
|
||||
{ source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" },
|
||||
{ source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" },
|
||||
{ source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" },
|
||||
{ source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" },
|
||||
{ source = "tipo_histologico", codes = ["8000/3"], then = "Breast" },
|
||||
{ source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" },
|
||||
{ source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } }
|
||||
|
||||
[variables.Tipo_histologico.scanb]
|
||||
rules = [
|
||||
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" },
|
||||
{ source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" },
|
||||
{ source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" },
|
||||
{ source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" },
|
||||
{ source = "tipo_histologico", codes = ["8010/3"], then = "Other" },
|
||||
]
|
||||
column = "Histology"
|
||||
values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" }
|
||||
|
||||
[variables.Estado_menopausico]
|
||||
bronze = "Paciente.pac_estado_menopausico"
|
||||
rules = [
|
||||
{ source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" },
|
||||
{ source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } }
|
||||
scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } }
|
||||
|
||||
[variables.Lateralidad]
|
||||
bronze = "BiopsiaMama.bx_lateralidad"
|
||||
rules = [
|
||||
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" },
|
||||
{ source = "lateralidad", codes = ["DERECHA"], then = "Right" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } }
|
||||
scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } }
|
||||
|
||||
# Treatments. The category is the source's own, as the scenarios of each cohort name them.
|
||||
[variables.Cirugia]
|
||||
treatment = "cirugia"
|
||||
rules = [
|
||||
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" },
|
||||
{ source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } }
|
||||
scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } }
|
||||
|
||||
[variables.Quimioterapia]
|
||||
treatment = "quimioterapia"
|
||||
rules = [
|
||||
{ source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" },
|
||||
{ source = "quimioterapia", codes = ["NINGUNA"], then = "NO" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
|
||||
scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
|
||||
|
||||
[variables.Radioterapia]
|
||||
treatment = "radioterapia"
|
||||
rules = [
|
||||
{ source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" },
|
||||
{ source = "radioterapia", codes = ["NINGUNA"], then = "NO" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
|
||||
scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
|
||||
|
||||
[variables.Hormonoterapia]
|
||||
treatment = "hormonoterapia"
|
||||
rules = [
|
||||
{ source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" },
|
||||
{ source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
|
||||
scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
|
||||
|
||||
# ---- METABRIC only ----
|
||||
[variables.Carga_mutacional]
|
||||
bronze = "Paciente.pac_carga_mutacional"
|
||||
source = "carga_mutacional"
|
||||
terciles = true # the cohort's own terciles of the mutation count
|
||||
labels = ["baja", "media", "alta"]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Mutation Count" }
|
||||
|
||||
[variables.Subtipo_PAM50]
|
||||
bronze = "Paciente.pac_pam50"
|
||||
rules = [
|
||||
{ source = "pam50", codes = ["LUMA"], then = "LumA" },
|
||||
{ source = "pam50", codes = ["LUMB"], then = "LumB" },
|
||||
{ source = "pam50", codes = ["HER2"], then = "Her2" },
|
||||
{ source = "pam50", codes = ["BASAL"], then = "Basal" },
|
||||
{ source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" },
|
||||
{ source = "pam50", codes = ["NORMAL"], then = "Normal" },
|
||||
{ source = "pam50", codes = ["NC"], then = "NC" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } }
|
||||
|
||||
[variables.Celularidad]
|
||||
bronze = "Paciente.pac_celularidad"
|
||||
rules = [
|
||||
{ source = "celularidad", codes = ["ALTA"], then = "High" },
|
||||
{ source = "celularidad", codes = ["MODERADA"], then = "Moderate" },
|
||||
{ source = "celularidad", codes = ["BAJA"], then = "Low" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } }
|
||||
|
||||
[variables.Cluster_integrativo]
|
||||
bronze = "Paciente.pac_cluster_integrativo"
|
||||
rules = [
|
||||
{ source = "cluster_integrativo", codes = ["IC1"], then = "1" },
|
||||
{ source = "cluster_integrativo", codes = ["IC2"], then = "2" },
|
||||
{ source = "cluster_integrativo", codes = ["IC3"], then = "3" },
|
||||
{ source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" },
|
||||
{ source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" },
|
||||
{ source = "cluster_integrativo", codes = ["IC5"], then = "5" },
|
||||
{ source = "cluster_integrativo", codes = ["IC6"], then = "6" },
|
||||
{ source = "cluster_integrativo", codes = ["IC7"], then = "7" },
|
||||
{ source = "cluster_integrativo", codes = ["IC8"], then = "8" },
|
||||
{ source = "cluster_integrativo", codes = ["IC9"], then = "9" },
|
||||
{ source = "cluster_integrativo", codes = ["IC10"], then = "10" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } }
|
||||
|
||||
# ---- SCAN-B only ----
|
||||
[variables.Ki67]
|
||||
bronze = "Paciente.pac_ki67_categoria"
|
||||
rules = [
|
||||
{ source = "ki67_categoria", codes = ["BAJO"], then = "Low" },
|
||||
{ source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" },
|
||||
{ source = "ki67_categoria", codes = ["ALTO"], then = "High" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } }
|
||||
|
||||
[variables.Subtipo_clinico]
|
||||
bronze = "Paciente.pac_subtipo_clinico"
|
||||
rules = [
|
||||
{ source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" },
|
||||
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" },
|
||||
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" },
|
||||
{ source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" },
|
||||
{ source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" },
|
||||
{ source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" },
|
||||
{ source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } }
|
||||
|
||||
[variables.Estadio_clinico]
|
||||
bronze = "NotaMedica.nm_estadio_clinico"
|
||||
rules = [
|
||||
{ source = "estadio_clinico", codes = ["E0"], then = "0" },
|
||||
{ source = "estadio_clinico", codes = ["EI"], then = "1" },
|
||||
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" },
|
||||
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } }
|
||||
|
||||
[variables.AntiHER2]
|
||||
treatment = "anti_her2"
|
||||
rules = [
|
||||
{ source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" },
|
||||
{ source = "anti_her2", codes = ["NINGUNA"], then = "No" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" }
|
||||
|
||||
# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ----
|
||||
[cohorts.metabric]
|
||||
name = "METABRIC"
|
||||
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
|
||||
"Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico",
|
||||
"Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
|
||||
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
|
||||
|
||||
[cohorts.scanb]
|
||||
name = "SCAN-B"
|
||||
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno",
|
||||
"Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad",
|
||||
"Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
|
||||
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
|
||||
|
||||
# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ----
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)"
|
||||
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "Ganglios 4+"
|
||||
when = { Ganglios_positivos = ["4+"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "Tumor >50 mm"
|
||||
when = { Tamano_tumor = [">50 mm"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "< 45 años"
|
||||
when = { Edad = ["<45"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "≥ 75 años"
|
||||
when = { Edad = ["75+"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "Basal (PAM50)"
|
||||
when = { Subtipo_PAM50 = ["Basal"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "HER2 (PAM50)"
|
||||
when = { Subtipo_PAM50 = ["Her2"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "Luminal B (PAM50)"
|
||||
when = { Subtipo_PAM50 = ["LumB"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "RE+ · 1-3 ganglios · cirugía conservadora"
|
||||
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] }
|
||||
[[cohorts.metabric.scenarios]]
|
||||
name = "RE− · grado 3"
|
||||
when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] }
|
||||
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)"
|
||||
when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Ganglios 4+"
|
||||
when = { Ganglios_positivos = ["4+"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Tumor >50 mm"
|
||||
when = { Tamano_tumor = [">50 mm"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "< 45 años"
|
||||
when = { Edad = ["<45"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "≥ 75 años"
|
||||
when = { Edad = ["75+"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Basal-like"
|
||||
when = { Subtipo_clinico = ["Basal-like"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "HER2+ (luminal B HER2+ o no luminal)"
|
||||
when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Luminal B HER2−"
|
||||
when = { Subtipo_clinico = ["Luminal B HER2-"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Luminal · 1-3 ganglios · lumpectomía"
|
||||
when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] }
|
||||
[[cohorts.scanb.scenarios]]
|
||||
name = "Grado 3"
|
||||
when = { Grado_histologico = ["3"] }
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
"""CaMa's recurrence analysis as a scenario: the dataflow from the two external cohorts to the registered model, its results and
|
||||
its routines. Each node is one stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery
|
||||
(`models.dags.training.train`) saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the
|
||||
dashboard shows are in `population["recurrencia"]`.
|
||||
"""CaMa's recurrence analysis as a scenario: the dataflow from the cohort's patients loaded from METABRIC and SCAN-B (the
|
||||
`fuente` of each, indexed at her first invasive biopsy) to the registered model, its results and its routines. Each node is one
|
||||
stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery (`models.dags.training.train`)
|
||||
saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the dashboard shows are in
|
||||
`population["recurrencia"]`.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
@@ -11,17 +12,22 @@ import statsmodels.api as sm
|
||||
from models.cama.recurrence import calculator as calc
|
||||
from models.cama.recurrence import factors as fac
|
||||
from models.cama.recurrence import modeling
|
||||
from models.cama.recurrence.prep import FILES, PREPARE, Prepared
|
||||
from models.cama.recurrence.source import data_folder
|
||||
from models.cama.recurrence.steps import run_steps # noqa: F401 (the CLI's own steps: not a node)
|
||||
from models.cama.recurrence import cohort as timeline
|
||||
from models.cama.recurrence.prep import Prepared, finish
|
||||
|
||||
COHORTS = ("metabric", "scanb")
|
||||
|
||||
|
||||
def prepared(recurrence: dict) -> dict[str, Prepared]:
|
||||
"""Each cohort as one table of categories with its covariates (`prep`)."""
|
||||
folder = data_folder(recurrence["data_dir"])
|
||||
return {name: PREPARE[name](str(folder / FILES[name]), recurrence["v_max"]) for name in COHORTS}
|
||||
def dictionary() -> dict:
|
||||
"""The variables, cohorts and scenarios of `cohorts.toml`."""
|
||||
return timeline.load()
|
||||
|
||||
|
||||
def prepared(cohort: pd.DataFrame, dictionary: dict, recurrence: dict) -> dict[str, Prepared]:
|
||||
"""Each cohort's patients as one table of categories with its covariates (`cohort.recode`, then `prep`)."""
|
||||
fixed = ["paciente", "tiempo_meses", "evento"]
|
||||
return {name: finish(timeline.recode(cohort, dictionary, name), fixed, dictionary["cohorts"][name]["treatment"],
|
||||
recurrence["v_max"]) for name in COHORTS}
|
||||
|
||||
|
||||
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
|
||||
@@ -122,7 +128,7 @@ def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModel
|
||||
return {
|
||||
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
|
||||
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)"},
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "pacientes cargadas de METABRIC y SCAN-B (`fuente`)"},
|
||||
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
|
||||
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
|
||||
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, from two external cohorts (METABRIC and SCAN-B).
|
||||
# Trained from governance on the files in `data/`; the scenarios' figures are what the dashboard shows. Its covariates are the
|
||||
# cohorts' own; the hospital's patient is placed in the scenarios her covariates meet.
|
||||
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, trained on the patients loaded from METABRIC and
|
||||
# SCAN-B (`cohort_import`, through the platform's import) and read from the database by the dictionary of `cohorts.toml`.
|
||||
# The scenarios' figures are what the dashboard shows; the hospital's patient is placed in the scenarios her covariates meet.
|
||||
domain = "cama"
|
||||
scenario = "recurrence"
|
||||
cohort = "cama/externa"
|
||||
cohort = "cama/cohorte_total"
|
||||
outcome = "recurrencia"
|
||||
external = true # trained on files, not on a dbt cohort of the platform
|
||||
modules = ["models.cama.recurrence.model"]
|
||||
modules = ["models.cama.recurrence.model", "models.steps.indexing"]
|
||||
description = """\
|
||||
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
|
||||
regresión logística y una red bayesiana por horizonte, entrenadas en dos cohortes externas (METABRIC y SCAN-B). Pendiente \
|
||||
regresión logística y una red bayesiana por horizonte, entrenadas con las pacientes cargadas de dos cohortes externas (METABRIC y SCAN-B). Pendiente \
|
||||
de validación clínica."""
|
||||
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
|
||||
# Its figures are answered per clinical scenario (`/cama/modelo/recurrencia`); the cycle does not score each member.
|
||||
batch_estimates = false
|
||||
|
||||
[config.recurrence]
|
||||
data_dir = "" # empty: the `data/` folder of this package
|
||||
horizons = [12, 36, 60] # months
|
||||
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
|
||||
seed = 42
|
||||
@@ -31,3 +31,8 @@ n_boot_calc = 200 # replicas of each scenario's interval
|
||||
min_events = 15 # recurrences a scenario needs to be drawn
|
||||
cap_months = 72 # the figure's time axis
|
||||
ks_seconds = 60 # time budget of each fractional Weibull fit
|
||||
|
||||
[config.index]
|
||||
kind = "primera_biopsia_invasora"
|
||||
event_grades = ["CARCINOMA_INVASOR"]
|
||||
observacion_previa_minima_dias = 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""The recurrence analysis' data: the two external cohorts (METABRIC and SCAN-B) as one table each, the covariates as
|
||||
categories with the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped. Ported
|
||||
from `01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
|
||||
"""The recurrence analysis' data: each cohort's patients (`cohort.recode`) as one table, the covariates as categories with
|
||||
the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped, as in
|
||||
`01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -9,7 +9,6 @@ import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import chi2_contingency
|
||||
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
|
||||
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
|
||||
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
|
||||
@@ -23,14 +22,6 @@ class Prepared:
|
||||
eliminated: list[str]
|
||||
|
||||
|
||||
def _unknown(s: pd.Series) -> pd.Series:
|
||||
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
|
||||
|
||||
|
||||
def _cut(s: pd.Series, cuts: list, labels: list) -> pd.Series:
|
||||
return _unknown(pd.cut(s, cuts, labels=labels, right=False).astype("object"))
|
||||
|
||||
|
||||
def cramer_v(a: pd.Series, b: pd.Series) -> float:
|
||||
table = pd.crosstab(a, b)
|
||||
chi2 = chi2_contingency(table, correction=False)[0]
|
||||
@@ -54,55 +45,7 @@ def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[st
|
||||
return covariates, eliminated
|
||||
|
||||
|
||||
def _finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
|
||||
def finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
|
||||
covariates = [c for c in out.columns if c not in fixed]
|
||||
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
|
||||
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
|
||||
|
||||
|
||||
def prepare_metabric(path: str, v_max: float) -> Prepared:
|
||||
d = pd.read_csv(path, sep="\t")
|
||||
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["Patient ID"]})
|
||||
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
|
||||
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
|
||||
out["Edad"] = _cut(d["Age at Diagnosis"], AGE_CUTS, AGE_LABELS)
|
||||
out["Tamano_tumor"] = _cut(d["Tumor Size"], SIZE_CUTS, SIZE_LABELS)
|
||||
out["Ganglios_positivos"] = _cut(d["Lymph nodes examined positive"], NODE_CUTS, NODE_LABELS)
|
||||
out["Grado_histologico"] = _unknown(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
|
||||
mutations = d["Mutation Count"]
|
||||
q = mutations.quantile([1 / 3, 2 / 3]).values
|
||||
out["Carga_mutacional"] = _cut(mutations, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
|
||||
for name, column in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
|
||||
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
|
||||
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
|
||||
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
|
||||
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
|
||||
out[name] = _unknown(d[column])
|
||||
return _finish(out, ["paciente", "tiempo_meses", "evento"], ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], v_max)
|
||||
|
||||
|
||||
def prepare_scanb(path: str, v_max: float) -> Prepared:
|
||||
d = pd.read_csv(path, sep="\t", low_memory=False)
|
||||
d = d[d["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["PatientName"]})
|
||||
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH
|
||||
out["evento"] = d["RFI_event"].astype(int)
|
||||
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
|
||||
out["Edad"] = _cut(d["Age_5year_bin"].astype(float) - 2, AGE_CUTS, AGE_LABELS)
|
||||
out["Tamano_tumor"] = _cut(d["TumorSize_mm"], SIZE_CUTS, SIZE_LABELS)
|
||||
out["Ganglios_positivos"] = _unknown(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
|
||||
out["Grado_histologico"] = _unknown(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
|
||||
for name, column in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
|
||||
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
|
||||
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
|
||||
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
|
||||
out[name] = _unknown(d[column])
|
||||
return _finish(out, ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||
["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], v_max)
|
||||
|
||||
|
||||
PREPARE = {"metabric": prepare_metabric, "scanb": prepare_scanb}
|
||||
FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
"""The recurrence analysis' training data: two files on disk, not a cohort of the platform. It takes the part of a cohort source
|
||||
(`models.io.storage.CohortSource`) for the training run: the reference the version is traced to, which is the hash of the files."""
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence.prep import FILES
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
|
||||
PACKAGE_DATA = Path(__file__).parent / "data"
|
||||
URL = "cama/externa/metabric+scanb"
|
||||
|
||||
|
||||
def data_folder(configured: str) -> Path:
|
||||
return Path(configured) if configured else PACKAGE_DATA
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExternalCohorts:
|
||||
"""The METABRIC and SCAN-B files of a folder."""
|
||||
|
||||
folder: Path = PACKAGE_DATA
|
||||
armado_id: int | None = None
|
||||
|
||||
def sha256(self) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for name in sorted(FILES.values()):
|
||||
digest.update((self.folder / name).read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
def frame(self) -> pd.DataFrame:
|
||||
return pd.DataFrame()
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
return {"url": URL, "files": ",".join(sorted(FILES.values())), "sha256": self.sha256()}
|
||||
|
||||
def reference(self) -> dict[str, str]:
|
||||
return {COHORT_URL_TAG: URL, COHORT_SOURCE_TAG: REFERENCE_SOURCE, COHORT_BUILD_TAG: self.sha256()}
|
||||
@@ -1,31 +0,0 @@
|
||||
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
|
||||
from models.__main__ import _promote_step
|
||||
from models.cama.recurrence.source import ExternalCohorts, data_folder
|
||||
from models.dags.training import Scenario, find_trained, train
|
||||
|
||||
if args.export or args.estimate or args.store or args.version:
|
||||
print("cama/recurrence trains on its external cohorts: only --train and --promote apply", file=sys.stderr)
|
||||
return 2
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
source = ExternalCohorts(data_folder(scenario.config["recurrence"]["data_dir"]))
|
||||
environment = args.environment.upper()
|
||||
version = find_trained(scenario, source, environment)
|
||||
if args.train:
|
||||
if version:
|
||||
print(f"already trained: version {version}, from {source.lineage()['sha256'][:12]}")
|
||||
else:
|
||||
version = train(scenario, source, environment)
|
||||
print(f"trained: version {version}, from {source.lineage()['sha256'][:12]}")
|
||||
if args.promote:
|
||||
if not version:
|
||||
print(f"no {environment} version trained: use --train", file=sys.stderr)
|
||||
return 1
|
||||
return _promote_step(args, version)
|
||||
return 0
|
||||
@@ -9,7 +9,6 @@ likelihood on monthly counts of events and censorings (`tabla_eventos`), by Neld
|
||||
import time
|
||||
from functools import lru_cache
|
||||
|
||||
import mpmath as mp
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import gammaln
|
||||
@@ -17,6 +16,7 @@ from scipy.special import gammaln
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _coefs(rho, m, l, N, dps):
|
||||
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
|
||||
mp.mp.dps = dps
|
||||
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
|
||||
c = [mp.mpf(1)]
|
||||
@@ -37,6 +37,7 @@ def _log_terms(az, rho, m, l, N):
|
||||
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
|
||||
"""The Kilbas-Saigo function E_{rho,m,l}(z) at each `z`: the plain series when its terms stay small, else a polynomial
|
||||
in `mpmath` with as many digits as the largest term needs; NaN where even that is out of reach."""
|
||||
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
|
||||
z = np.atleast_1d(np.asarray(z, float))
|
||||
rho, m, l = float(rho), float(m), float(l)
|
||||
out = np.full(z.shape, np.nan)
|
||||
@@ -80,6 +81,7 @@ def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
|
||||
|
||||
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
|
||||
"""The fractional Weibull's survival function at `t`; NaN outside its parameter region."""
|
||||
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
|
||||
tau1 = lam if tau1 is None else tau1
|
||||
tau2 = lam if tau2 is None else tau2
|
||||
t = np.atleast_1d(np.asarray(t, float))
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
exclude = ["Outcome_cat"] # never analysed or touched
|
||||
auto_extra = ["Age_group", "Tumor_group"] # included when present
|
||||
extra_cols = []
|
||||
protected = [] # e.g. ["Estadio_cat"]: never dropped
|
||||
protected = ["Estadio_cat", "Subtipo_molecular_cat", "Tratamiento_quirurgico_cat"] # the axes of the clinical scenarios: never dropped
|
||||
prefer = ["Tumor_group", "Age_group"] # on a tie or duplicate, the one listed here wins (the project's own groupings)
|
||||
drop_raw_sources = true # also drop the raw SEER column of a dropped variable
|
||||
unknown_label = "Desconocido"
|
||||
@@ -151,7 +151,103 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty
|
||||
|
||||
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
|
||||
|
||||
# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`.
|
||||
# The clinical scenarios, in the doctors' terms: every condition must hold. A condition names a variable of the
|
||||
# dictionary (`Edad`: the age in years, the start of its band) and tests `contains` (the category has this text), `in` (it
|
||||
# is one of these) or, for the age, `ge` / `lt`.
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2+" },
|
||||
{ variable = "Edad", ge = 60 },
|
||||
{ variable = "Estadio", in = ["III", "IV"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2+" },
|
||||
{ variable = "Edad", lt = 60 },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio IV"
|
||||
conditions = [
|
||||
{ variable = "Estadio", in = ["IV"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio I"
|
||||
conditions = [
|
||||
{ variable = "Estadio", in = ["I"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 75 años"
|
||||
conditions = [
|
||||
{ variable = "Edad", ge = 75 }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "< 45 años"
|
||||
conditions = [
|
||||
{ variable = "Edad", lt = 45 }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2-" },
|
||||
{ variable = "Edad", lt = 45 },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
|
||||
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "HER2− · estadio 0–II · cirugía conservadora"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2-" },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
|
||||
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · estadio 0–II · cirugía conservadora"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2+" },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
|
||||
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · estadio 0–II"
|
||||
conditions = [
|
||||
{ variable = "Edad", lt = 45 },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2−"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2-" },
|
||||
{ variable = "Edad", lt = 45 }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HR-/HER2-" },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
|
||||
]
|
||||
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
|
||||
conditions = [
|
||||
{ variable = "Subtipo_molecular", contains = "HER2-" },
|
||||
{ variable = "Edad", ge = 65 },
|
||||
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
|
||||
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
|
||||
]
|
||||
|
||||
[risk_factors]
|
||||
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
|
||||
@@ -263,3 +359,266 @@ Microcalcificaciones_cat = "Microcalcificaciones"
|
||||
Multifocalidad_cat = "Multifocalidad"
|
||||
BRCA_cat = "BRCA"
|
||||
HER2_IHQ_cat = "HER2_IHQ"
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# The variable dictionary. One table per variable of the model: the column it makes, how its category is read from a
|
||||
# patient's timeline (`rules`, in order, the first that holds; `missing` when none does) and, for the SEER load, where the
|
||||
# SEER category is stored in CaMa's bronze (`seer`). A rule is one condition or a `when` list that must all hold; a
|
||||
# condition names a timeline `source` (the `tipo` of the patient's latest event of that kind) or an earlier `variable`,
|
||||
# and tests `codes` (the value is one of them), `present` (there is such an event), or `ge` / `lt` (the number).
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
[variables]
|
||||
window_days_after_index = 365 # the events from the index on that still describe the patient at diagnosis and treatment
|
||||
|
||||
[variables.index]
|
||||
id_column = "Patient_ID"
|
||||
year_column = "Year_of_diagnosis"
|
||||
age_column = "Age_recode_with_1_year_olds_and_90"
|
||||
age_band_years = 5
|
||||
age_open_from = 90
|
||||
age_label = "{low}-{high} years"
|
||||
age_open_label = "{low}+ years"
|
||||
age_unknown = "Otros (agrupado)"
|
||||
months_column = "Survival_months"
|
||||
vital_column = "Vital_status_recode_study_cutoff_used"
|
||||
alive = "Alive"
|
||||
dead = "Dead"
|
||||
days_per_month = 30.4375
|
||||
death_source = "defuncion"
|
||||
birth_source = "nacimiento"
|
||||
# SEER's calendar dates are not recorded: the diagnosis is the 1st of July of its year, the birth the middle of the age
|
||||
# band, the death the diagnosis plus the survival months, the last contact of the living the same.
|
||||
seer_diagnosis_month_day = "07-01"
|
||||
seer_age_open_value = 92
|
||||
|
||||
[variables.Estadio]
|
||||
rules = [
|
||||
{ source = "estadio_clinico", codes = ["E0"], then = "0 (in situ)" },
|
||||
{ source = "estadio_clinico", codes = ["EI"], then = "I" },
|
||||
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "II" },
|
||||
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "III" },
|
||||
{ source = "estadio_clinico", codes = ["EIV"], then = "IV" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { bronze = "NotaMedica.nm_estadio_clinico", values = { "0 (in situ)" = "E0", "I" = "EI", "II" = "EIIA", "III" = "EIIIA", "IV" = "EIV" } }
|
||||
|
||||
[variables.Grado_histologico]
|
||||
rules = [
|
||||
{ source = "grado_nottingham", codes = ["G1"], then = "G1" },
|
||||
{ source = "grado_nottingham", codes = ["G2"], then = "G2" },
|
||||
{ source = "grado_nottingham", codes = ["G3"], then = "G3" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { bronze = "BiopsiaMama.bx_grado_nottingham", values = { "G1" = "G1", "G2" = "G2", "G3" = "G3" } }
|
||||
|
||||
[variables.Receptor_estrogeno]
|
||||
rules = [
|
||||
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positivo" },
|
||||
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negativo" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { bronze = "BiopsiaMama.bx_receptor_estrogeno", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
|
||||
|
||||
[variables.Receptor_progesterona]
|
||||
rules = [
|
||||
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positivo" },
|
||||
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negativo" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { bronze = "BiopsiaMama.bx_receptor_progesterona", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
|
||||
|
||||
# HER2 is positive or negative by the FISH when there is one, else by the immunohistochemistry (3+ positive, 0 and 1+
|
||||
# negative, 2+ equivocal).
|
||||
[variables.HER2_estado]
|
||||
internal = true
|
||||
rules = [
|
||||
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positivo" },
|
||||
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negativo" },
|
||||
{ source = "her2", codes = ["H3"], then = "Positivo" },
|
||||
{ source = "her2", codes = ["H0", "H1"], then = "Negativo" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { from = "Subtipo_molecular", bronze = "BiopsiaMama.bx_her2_fish", values = { "HR+/HER2+" = "POSITIVO", "HR-/HER2+" = "POSITIVO", "HR+/HER2-" = "NEGATIVO", "HR-/HER2-" = "NEGATIVO" } }
|
||||
|
||||
[variables.HER2_IHQ]
|
||||
rules = [
|
||||
{ source = "her2", codes = ["H0"], then = "0" },
|
||||
{ source = "her2", codes = ["H1"], then = "1+" },
|
||||
{ source = "her2", codes = ["H2"], then = "2+" },
|
||||
{ source = "her2", codes = ["H3"], then = "3+" },
|
||||
]
|
||||
missing = "Sin dato"
|
||||
seer = { bronze = "BiopsiaMama.bx_her2", values = { "0" = "H0", "1+" = "H1", "2+" = "H2", "3+" = "H3" } }
|
||||
|
||||
[variables.HR_estado]
|
||||
internal = true
|
||||
rules = [
|
||||
{ when = [{ variable = "Receptor_estrogeno", codes = ["Positivo"] }], then = "HR+" },
|
||||
{ when = [{ variable = "Receptor_progesterona", codes = ["Positivo"] }], then = "HR+" },
|
||||
{ when = [{ variable = "Receptor_estrogeno", codes = ["Negativo"] }, { variable = "Receptor_progesterona", codes = ["Negativo"] }], then = "HR-" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
|
||||
[variables.Subtipo_molecular]
|
||||
rules = [
|
||||
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR+/HER2-" },
|
||||
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR+/HER2+" },
|
||||
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR-/HER2+" },
|
||||
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR-/HER2-" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
|
||||
[variables.Tipo_histologico]
|
||||
rules = [
|
||||
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal (NST)" },
|
||||
{ source = "tipo_histologico", codes = ["8520/3", "8521/3"], then = "Lobulillar" },
|
||||
{ source = "tipo_histologico", codes = ["8522/3", "8523/3"], then = "Ductal-lobulillar mixto" },
|
||||
{ source = "tipo_histologico", codes = ["8480/3"], then = "Mucinoso" },
|
||||
{ source = "tipo_histologico", codes = ["8211/3", "8201/3"], then = "Tubular / cribiforme" },
|
||||
{ source = "tipo_histologico", codes = ["8050/3", "8503/3", "8504/3"], then = "Papilar" },
|
||||
{ source = "tipo_histologico", codes = ["8507/3"], then = "Micropapilar" },
|
||||
{ source = "tipo_histologico", codes = ["8540/3", "8541/3", "8543/3"], then = "Paget" },
|
||||
{ source = "tipo_histologico", codes = ["8510/3"], then = "Medular" },
|
||||
{ source = "tipo_histologico", codes = ["8530/3"], then = "Inflamatorio" },
|
||||
{ source = "tipo_histologico", present = true, then = "Otros" },
|
||||
]
|
||||
missing = "SIN MAPEAR"
|
||||
seer = { bronze = "BiopsiaMama.bx_tipo_histologico", values = { "Ductal (NST)" = "8500/3", "Lobulillar" = "8520/3", "Ductal-lobulillar mixto" = "8522/3", "Mucinoso" = "8480/3", "Tubular / cribiforme" = "8211/3", "Papilar" = "8503/3", "Micropapilar" = "8507/3", "Paget" = "8541/3", "Medular" = "8510/3", "Inflamatorio" = "8530/3", "Otros" = "8575/3" } }
|
||||
|
||||
[variables.Localizacion_mama]
|
||||
rules = [
|
||||
{ source = "localizacion", codes = ["C500"], then = "Pezón" },
|
||||
{ source = "localizacion", codes = ["C501"], then = "Porción central" },
|
||||
{ source = "localizacion", codes = ["C502", "C503"], then = "Cuadrantes internos" },
|
||||
{ source = "localizacion", codes = ["C504", "C505"], then = "Cuadrantes externos" },
|
||||
{ source = "localizacion", codes = ["C506"], then = "Cola axilar" },
|
||||
{ source = "localizacion", codes = ["C508"], then = "Lesión solapada" },
|
||||
{ source = "localizacion", codes = ["C509"], then = "Mama NOS" },
|
||||
]
|
||||
missing = "Mama NOS"
|
||||
seer = { bronze = "BiopsiaMama.bx_localizacion", values = { "Pezón" = "C500", "Porción central" = "C501", "Cuadrantes internos" = "C502", "Cuadrantes externos" = "C504", "Cola axilar" = "C506", "Lesión solapada" = "C508", "Mama NOS" = "C509" } }
|
||||
|
||||
[variables.Lateralidad]
|
||||
rules = [
|
||||
{ source = "lateralidad", codes = ["DERECHA"], then = "Derecha" },
|
||||
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Izquierda" },
|
||||
]
|
||||
missing = "Otra / no especificada"
|
||||
seer = { bronze = "BiopsiaMama.bx_lateralidad", values = { "Derecha" = "DERECHA", "Izquierda" = "IZQUIERDA" } }
|
||||
|
||||
[variables.Metastasis]
|
||||
rules = [
|
||||
{ source = "metastasis", codes = ["M1"], then = "Con metástasis" },
|
||||
]
|
||||
missing = "Sin metástasis"
|
||||
seer = { bronze = "NotaMedica.nm_metastasis", values = { "Con metástasis" = "M1", "Sin metástasis" = "M0" } }
|
||||
|
||||
# The tumour size in millimetres: its category and the raw column the age and tumour groupings of stage 02 read.
|
||||
[variables.Tamano_tumor]
|
||||
source = "tamano_tumor_mm"
|
||||
rules = [
|
||||
{ source = "tamano_tumor_mm", lt = 21, then = "T1 (<=20 mm)" },
|
||||
{ source = "tamano_tumor_mm", ge = 21, lt = 51, then = "T2 (21-50 mm)" },
|
||||
{ source = "tamano_tumor_mm", ge = 51, then = "T3+ (>50 mm)" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
raw_column = "Tumor_Size_Over_Time_Recode_1988"
|
||||
raw_format = "{:03.0f}"
|
||||
raw_missing = "Unknown or size unreasonable (includes any tumor sizes 401-989)"
|
||||
seer = { bronze = "BiopsiaMama.bx_tamano_tumor_mm", number = "Tumor_Size_Over_Time_Recode_1988", unknown = ["Unknown or size unreasonable (includes any tumor sizes 401-989)", "Otros (agrupado)"], microscopic = ["990 (microscopic focus)"], microscopic_mm = 1 }
|
||||
|
||||
[variables.Ganglios_positivos]
|
||||
rules = [
|
||||
{ source = "ganglios_positivos", lt = 1, then = "0" },
|
||||
{ source = "ganglios_positivos", ge = 1, lt = 4, then = "1-3" },
|
||||
{ source = "ganglios_positivos", ge = 4, lt = 10, then = "4-9" },
|
||||
{ source = "ganglios_positivos", ge = 10, then = "10+" },
|
||||
]
|
||||
missing = "0"
|
||||
seer = { bronze = "BiopsiaMama.bx_ganglios_positivos", number_values = { "0" = 0, "1-3" = 2, "4-9" = 6, "10+" = 12 } }
|
||||
|
||||
[variables.Invasion_linfovascular]
|
||||
rules = [{ source = "invasion_linfovascular", codes = ["PRESENTE"], then = "Si" }]
|
||||
missing = "No"
|
||||
seer = { bronze = "BiopsiaMama.bx_invasion_linfovascular", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
|
||||
|
||||
[variables.Multifocalidad]
|
||||
rules = [{ source = "multifocalidad", codes = ["PRESENTE"], then = "Si" }]
|
||||
missing = "No"
|
||||
seer = { bronze = "BiopsiaMama.bx_multifocalidad", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
|
||||
|
||||
[variables.Margenes]
|
||||
rules = [
|
||||
{ source = "margenes", codes = ["LIBRES"], then = "Negativos" },
|
||||
{ source = "margenes", codes = ["CERCANOS", "AFECTADOS"], then = "Positivos" },
|
||||
{ source = "margenes", codes = ["SIN_CIRUGIA"], then = "Sin cirugia" },
|
||||
]
|
||||
missing = "Sin dato"
|
||||
seer = { bronze = "BiopsiaMama.bx_margenes", values = { "Negativos" = "LIBRES", "Positivos" = "AFECTADOS", "Sin cirugia" = "SIN_CIRUGIA" } }
|
||||
|
||||
[variables.Densidad_BIRADS]
|
||||
rules = [
|
||||
{ source = "densidad_mamaria", codes = ["A"], then = "A" },
|
||||
{ source = "densidad_mamaria", codes = ["B"], then = "B" },
|
||||
{ source = "densidad_mamaria", codes = ["C"], then = "C" },
|
||||
{ source = "densidad_mamaria", codes = ["D"], then = "D" },
|
||||
]
|
||||
missing = "B"
|
||||
seer = { bronze = "Mastografia.mast_densidad", values = { "A" = "A", "B" = "B", "C" = "C", "D" = "D" } }
|
||||
|
||||
[variables.Masa_espiculada]
|
||||
rules = [{ source = "margen_masa", codes = ["ESPICULADO"], then = "Si" }]
|
||||
missing = "No"
|
||||
seer = { bronze = "Mastografia.mast_margen_masa", values = { "Si" = "ESPICULADO" } }
|
||||
|
||||
[variables.Microcalcificaciones]
|
||||
rules = [{ source = "tipo_hallazgo", codes = ["CALCIFICACIONES"], then = "Si" }]
|
||||
missing = "No"
|
||||
seer = { bronze = "Mastografia.mast_tipo_hallazgo", values = { "Si" = "CALCIFICACIONES" } }
|
||||
|
||||
[variables.BRCA]
|
||||
rules = [
|
||||
{ source = "brca1", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA1" },
|
||||
{ source = "brca2", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA2" },
|
||||
]
|
||||
missing = "Negativo"
|
||||
seer = { bronze = "Paciente.pac_brca1", values = { "BRCA1" = "PATOGENICA", "Negativo" = "NEGATIVO" }, also = { bronze = "Paciente.pac_brca2", values = { "BRCA2" = "PATOGENICA", "Negativo" = "NEGATIVO" } } }
|
||||
|
||||
[variables.Estado_civil]
|
||||
rules = [
|
||||
{ source = "estado_civil", codes = ["SOLTERA", "CASADA", "UNION_LIBRE"], then = "Con pareja" },
|
||||
{ source = "estado_civil", codes = ["SEPARADA", "DIVORCIADA", "VIUDA"], then = "Sin pareja" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { bronze = "Paciente.pac_estado_civil", values = { "Con pareja" = "CASADA", "Sin pareja" = "DIVORCIADA" } }
|
||||
|
||||
[variables.Race]
|
||||
column = "Race_recode_White_Black_Other"
|
||||
rules = [
|
||||
{ source = "raza", codes = ["BLANCA"], then = "White" },
|
||||
{ source = "raza", codes = ["NEGRA"], then = "Black" },
|
||||
{ source = "raza", codes = ["OTRA"], then = "Other (American Indian/AK Native, Asian/Pacific Islander)" },
|
||||
]
|
||||
missing = "Unknown"
|
||||
seer = { bronze = "Paciente.pac_raza", values = { "White" = "BLANCA", "Black" = "NEGRA", "Other (American Indian/AK Native, Asian/Pacific Islander)" = "OTRA" } }
|
||||
|
||||
[variables.Tratamiento_quirurgico]
|
||||
rules = [
|
||||
{ source = "cirugia", codes = ["ESCISIONAL", "SEGMENTECTOMIA"], then = "Conservadora" },
|
||||
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"], then = "Mastectomía" },
|
||||
{ source = "cirugia", codes = ["SIN_CIRUGIA"], then = "Ninguna" },
|
||||
{ source = "cirugia", codes = ["DESTRUCCION_LOCAL"], then = "Destrucción local" },
|
||||
{ source = "cirugia", codes = ["CIRUGIA_NO_ESPECIFICADA"], then = "Cirugía NOS" },
|
||||
]
|
||||
missing = "Desconocido"
|
||||
seer = { treatment = "cirugia", values = { "Conservadora" = "SEGMENTECTOMIA", "Mastectomía" = "MASTECTOMIA_TOTAL", "Ninguna" = "SIN_CIRUGIA", "Destrucción local" = "DESTRUCCION_LOCAL", "Cirugía NOS" = "CIRUGIA_NO_ESPECIFICADA" } }
|
||||
|
||||
[variables.Radioterapia]
|
||||
rules = [{ source = "radioterapia", present = true, then = "Sí" }]
|
||||
missing = "No o desconocido"
|
||||
seer = { treatment = "radioterapia", values = { "Sí" = "ADYUVANTE" } }
|
||||
|
||||
[variables.Quimioterapia]
|
||||
rules = [{ source = "quimioterapia", present = true, then = "Sí" }]
|
||||
missing = "No o desconocido"
|
||||
seer = { treatment = "quimioterapia", values = { "Sí" = "ADYUVANTE" } }
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""SEER's recoded file as CaMa import files: one CSV per bronze entity, named by the fields the import schemas take, to be
|
||||
uploaded through the platform's import like any other source.
|
||||
|
||||
python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR
|
||||
|
||||
What goes where is the dictionary's (`[variables.*.seer]` of `model.toml`): each SEER category is stored as the catalog
|
||||
value the dictionary names, and read back as the same category. SEER records no calendar dates: the diagnosis is a fixed
|
||||
day of its year, the birth the middle of the age band, the death (or, for the living, the last contact) the diagnosis
|
||||
plus the survival months; the months stay exact.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import variables
|
||||
|
||||
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "Mastografia": "mastografias",
|
||||
"NotaMedica": "notas", "TratamientoMama": "tratamientos"}
|
||||
FEMALE = "Femenino"
|
||||
|
||||
|
||||
def _age_years(label: str, index: dict) -> float | None:
|
||||
"""The middle of an age band ("60-64 years" -> 62.5); the open band's own value; None without a number."""
|
||||
head = str(label).split(" ")[0]
|
||||
if head.endswith("+"):
|
||||
return float(index["seer_age_open_value"])
|
||||
low, _, high = head.partition("-")
|
||||
if not (low.isdigit() and high.isdigit()):
|
||||
return None
|
||||
return (int(low) + int(high) + 1) / 2
|
||||
|
||||
|
||||
def _number(text, spec: dict) -> float | None:
|
||||
text = str(text)
|
||||
if text in spec["microscopic"]:
|
||||
return float(spec["microscopic_mm"])
|
||||
return float(text) if text.replace(".", "", 1).isdigit() else None
|
||||
|
||||
|
||||
def convert(recoded: pd.DataFrame, dictionary: dict) -> dict[str, pd.DataFrame]:
|
||||
index = dictionary["index"]
|
||||
ages = recoded[index["age_column"]].map(lambda v: _age_years(v, index))
|
||||
frame = recoded[ages.notna()].copy()
|
||||
ages = ages[ages.notna()]
|
||||
months = pd.to_numeric(frame[index["months_column"]]).astype(int)
|
||||
dead = frame[index["vital_column"]].eq(index["dead"])
|
||||
day = pd.to_timedelta(months * index["days_per_month"], unit="D").dt.round("D")
|
||||
diagnosis = frame[index["year_column"]].astype(int).map(lambda y: pd.Timestamp(variables.diagnosis_date(y, dictionary)))
|
||||
birth = diagnosis - pd.to_timedelta((ages * 365.25).round(), unit="D")
|
||||
ident = frame[index["id_column"]].astype(str)
|
||||
date = lambda s: s.dt.strftime("%Y-%m-%d")
|
||||
|
||||
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
|
||||
tables["Paciente"]["pac_sexo"] = FEMALE
|
||||
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
|
||||
tables["Paciente"]["pac_fecha_defuncion"] = date(diagnosis + day).where(dead)
|
||||
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
|
||||
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
|
||||
tables["Mastografia"]["mast_fecha_toma"] = date(diagnosis)
|
||||
tables["Mastografia"]["mast_fecha_reporte"] = date(diagnosis)
|
||||
|
||||
for name in variables.variable_names(dictionary):
|
||||
spec = dictionary[name]
|
||||
seer = spec.get("seer")
|
||||
if not seer or "treatment" in seer:
|
||||
continue
|
||||
origin = seer.get("from", name)
|
||||
category = frame[variables.column_of(origin, dictionary[origin])]
|
||||
for target in (seer, seer.get("also")):
|
||||
if not target:
|
||||
continue
|
||||
entity, column = target["bronze"].split(".")
|
||||
if "number" in seer:
|
||||
tables[entity][column] = frame[seer["number"]].map(lambda v: _number(v, seer))
|
||||
elif "number_values" in seer:
|
||||
tables[entity][column] = category.map(seer["number_values"])
|
||||
else:
|
||||
tables[entity][column] = category.map(target["values"])
|
||||
|
||||
# A biopsy is invasive unless the stage says in situ.
|
||||
stage = frame[variables.column_of("Estadio", dictionary["Estadio"])]
|
||||
in_situ = [k for k, v in dictionary["Estadio"]["seer"]["values"].items() if v == "E0"]
|
||||
tables["BiopsiaMama"]["bx_grado_histologico"] = stage.isin(in_situ).map(
|
||||
{True: "CARCINOMA_IN_SITU", False: "CARCINOMA_INVASOR"})
|
||||
|
||||
# A receptor status the subtype contradicts follows the subtype (the model reads the subtype from the receptors).
|
||||
subtype = frame[variables.column_of("Subtipo_molecular", dictionary["Subtipo_molecular"])]
|
||||
positive_hr = subtype.str.startswith("HR+")
|
||||
negative_hr = subtype.str.startswith("HR-")
|
||||
bx = tables["BiopsiaMama"]
|
||||
no_positive = ~((bx["bx_receptor_estrogeno"] == "POSITIVO") | (bx["bx_receptor_progesterona"] == "POSITIVO"))
|
||||
bx.loc[positive_hr & no_positive, "bx_receptor_estrogeno"] = "POSITIVO"
|
||||
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
|
||||
bx.loc[negative_hr & bx[column].isna(), column] = "NEGATIVO"
|
||||
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
|
||||
bx.loc[negative_hr & (bx[column] == "POSITIVO"), column] = "NEGATIVO"
|
||||
|
||||
notes = tables["NotaMedica"]
|
||||
notes["nm_id_hospital"] = ident + "-dx"
|
||||
notes["nm_fecha"] = date(diagnosis)
|
||||
notes["nm_tipo_nota"] = "CONSULTA"
|
||||
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(diagnosis + day),
|
||||
"nm_tipo_nota": "CONSULTA"})[~dead.to_numpy()]
|
||||
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
|
||||
|
||||
treatments = []
|
||||
for name in variables.variable_names(dictionary):
|
||||
seer = dictionary[name].get("seer", {})
|
||||
if "treatment" not in seer:
|
||||
continue
|
||||
category = frame[variables.column_of(name, dictionary[name])]
|
||||
values = category.map(seer["values"])
|
||||
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": seer["treatment"], "trat_fecha": date(diagnosis),
|
||||
"trat_detalle": values})[values.notna()]
|
||||
if seer["treatment"] == "cirugia":
|
||||
rows["trat_lateralidad"] = bx["bx_lateralidad"].reindex(rows.index)
|
||||
treatments.append(rows)
|
||||
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
|
||||
return tables
|
||||
|
||||
|
||||
def main(argv=None) -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("recoded")
|
||||
ap.add_argument("out_dir")
|
||||
args = ap.parse_args(argv)
|
||||
recoded = pd.read_csv(args.recoded, dtype=str, low_memory=False)
|
||||
out = Path(args.out_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for entity, table in convert(recoded, variables.load()).items():
|
||||
table.to_csv(out / f"{ENTITIES[entity]}.csv", index=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -148,6 +148,7 @@ class SurvivalSettings:
|
||||
ks_sub_max_seconds: int
|
||||
xlim_sub: tuple[float, ...]
|
||||
ylim_sub: dict
|
||||
subgroups: tuple[dict, ...] = ()
|
||||
|
||||
@property
|
||||
def file_suffix(self) -> str:
|
||||
@@ -211,5 +212,6 @@ def load(path: Path = TOML) -> Settings:
|
||||
categorization=_group(CategorizationSettings, raw["categorization"]),
|
||||
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
|
||||
modeling=_group(ModelingSettings, raw["modeling"]),
|
||||
survival=_group(SurvivalSettings, raw["survival"]),
|
||||
survival=_group(SurvivalSettings, {**raw["survival"],
|
||||
"subgroups": tuple(raw["survival"].get("subgroups", ()))}),
|
||||
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
|
||||
|
||||
@@ -18,6 +18,7 @@ from sklearn.linear_model import LogisticRegression
|
||||
from models.cama.seer_survival import fractional_weibull as fw
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival import survival_models as sm
|
||||
from models.cama.seer_survival import variables
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
|
||||
STYLE = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
|
||||
@@ -82,10 +83,14 @@ def _age_midpoint(v):
|
||||
# ---------------------------------------------------------------- the cohort
|
||||
|
||||
def sv_frame(depurated_csv: str, survival: SurvivalSettings) -> SurvivalFrame:
|
||||
return survival_frame(pd.read_csv(depurated_csv, dtype=str), survival)
|
||||
|
||||
|
||||
def survival_frame(df: pd.DataFrame, survival: SurvivalSettings) -> SurvivalFrame:
|
||||
"""The cohort with follow-up truncated at `cap_months` (later deaths count as alive), its covariates and, when no
|
||||
categorical age column exists, the grouped age `Edad_cat`."""
|
||||
s = survival
|
||||
df = pd.read_csv(depurated_csv, dtype=str)
|
||||
df = df.copy()
|
||||
col_months, col_vital = _find_col(df, ["survival months"]), _find_col(df, ["vital status"])
|
||||
assert col_months and col_vital, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
|
||||
df["meses"] = pd.to_numeric(df[col_months], errors="coerce")
|
||||
@@ -323,9 +328,31 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
|
||||
|
||||
# ---------------------------------------------------------------- subgroups
|
||||
|
||||
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
|
||||
"""Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold."""
|
||||
return scenarios.masks(sv_frame.df)
|
||||
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict | None = None) -> dict[str, np.ndarray]:
|
||||
"""Each clinical scenario's mask over the cohort: the `subgroups` of the settings over the variable dictionary when
|
||||
both are given, else `scenarios.masks`. Every condition of a scenario must hold."""
|
||||
if not (survival.subgroups and dictionary):
|
||||
return scenarios.masks(sv_frame.df)
|
||||
df = sv_frame.df
|
||||
masks = {}
|
||||
for spec in survival.subgroups:
|
||||
mask = np.ones(len(df), bool)
|
||||
for condition in spec["conditions"]:
|
||||
name = condition["variable"]
|
||||
if name == "Edad":
|
||||
values = df["_edad"].astype(float)
|
||||
else:
|
||||
values = df[variables.column_of(name, dictionary[name])].astype(str)
|
||||
if "contains" in condition:
|
||||
mask &= values.str.contains(condition["contains"], regex=False).to_numpy()
|
||||
if "in" in condition:
|
||||
mask &= values.isin(condition["in"]).to_numpy()
|
||||
if "ge" in condition:
|
||||
mask &= (values >= condition["ge"]).to_numpy()
|
||||
if "lt" in condition:
|
||||
mask &= (values < condition["lt"]).to_numpy()
|
||||
masks[spec["name"]] = mask
|
||||
return masks
|
||||
|
||||
|
||||
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
|
||||
|
||||
@@ -279,3 +279,42 @@ def adjusted_curve(c: Cohort, idx, T: int, step: int) -> np.ndarray:
|
||||
S_b.append(S_i.mean())
|
||||
S_b = np.minimum.accumulate(np.array(S_b))
|
||||
return np.exp(np.interp(np.arange(T + 1), borders, np.log(np.maximum(S_b, 1e-12))))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fitted models that can be kept and applied later
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class IntervalFit:
|
||||
"""One interval's fitted LR (coefficients, intercept) and HBN (parents and the table of P(survives | parents))."""
|
||||
|
||||
coef: np.ndarray
|
||||
intercept: float
|
||||
parents: list[int]
|
||||
cpt: np.ndarray
|
||||
|
||||
|
||||
def fit_kept_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]:
|
||||
"""The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied."""
|
||||
m, e = c.months[idx], c.event[idx]
|
||||
fits = []
|
||||
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
|
||||
sel = np.where(m >= a)[0]
|
||||
y = np.where(e[sel] & (m[sel] < b), 0, 1)
|
||||
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
|
||||
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
|
||||
chosen, cpt = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
|
||||
fits.append(IntervalFit(lr.coef_[0].copy(), float(lr.intercept_[0]), list(chosen), cpt))
|
||||
return fits
|
||||
|
||||
|
||||
def apply_intervals(fits: list[IntervalFit], X_dum: np.ndarray, X_int: np.ndarray, levels) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""(LR, HBN): each patient's probability of surviving each interval."""
|
||||
P_lr = np.column_stack([1 / (1 + np.exp(-(X_dum @ f.coef + f.intercept))) for f in fits])
|
||||
P_hb = np.column_stack([predict_hbn((f.parents, f.cpt), X_int, levels) for f in fits])
|
||||
return P_lr, P_hb
|
||||
|
||||
|
||||
def mix(P_lr: np.ndarray, P_hb: np.ndarray, weights) -> np.ndarray:
|
||||
"""The combined survival at each horizon: each interval's LR and HBN probabilities mixed by `weights`, accumulated."""
|
||||
W = np.asarray(weights)[None, :]
|
||||
return np.cumprod(W * P_lr + (1 - W) * P_hb, axis=1)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""The variable dictionary (`[variables]` of `model.toml`) applied to a cohort's events: one row per patient with the
|
||||
columns the six stages read (the `_cat` columns, the age band, the tumour size, the diagnosis year, the follow-up and the
|
||||
vital status). Nothing about a variable is written here: its rules, categories and the columns it makes are the
|
||||
dictionary's.
|
||||
|
||||
A cohort is the long frame of `COHORT_SCHEMA`: one row per member and event, with the member's `fecha_indice`. A
|
||||
variable reads the latest event of each `source` (`tipo`) up to `window_days_after_index` after the index; its rules
|
||||
are tried in order and the first that holds gives the category, `missing` when none does.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
TOML = Path(__file__).with_name("model.toml")
|
||||
|
||||
|
||||
def load(path: Path = TOML) -> dict:
|
||||
return tomllib.loads(Path(path).read_text(encoding="utf-8"))["variables"]
|
||||
|
||||
|
||||
def variable_names(dictionary: dict) -> list[str]:
|
||||
return [n for n, v in dictionary.items() if isinstance(v, dict) and "rules" in v]
|
||||
|
||||
|
||||
def output_columns(dictionary: dict) -> list[str]:
|
||||
"""The columns the dictionary makes, in its order: every variable that is not internal, the tumour's raw size, the
|
||||
age band and the follow-up columns."""
|
||||
index = dictionary["index"]
|
||||
columns = [index["id_column"], index["year_column"], index["age_column"]]
|
||||
for name in variable_names(dictionary):
|
||||
spec = dictionary[name]
|
||||
if spec.get("internal"):
|
||||
continue
|
||||
columns.append(column_of(name, spec))
|
||||
if "raw_column" in spec:
|
||||
columns.append(spec["raw_column"])
|
||||
return columns + [index["months_column"], index["vital_column"]]
|
||||
|
||||
|
||||
def column_of(name: str, spec: dict) -> str:
|
||||
return spec.get("column", f"{name}_cat")
|
||||
|
||||
|
||||
def _latest(events: pd.DataFrame, source: str, numeric: bool) -> pd.Series:
|
||||
"""Each patient's latest event of this kind (by date, then source id): its value, indexed by `pac_id`."""
|
||||
rows = events[events["tipo"] == source]
|
||||
if numeric:
|
||||
rows = rows[rows["valor_numerico"].notna()]
|
||||
column = "valor_numerico"
|
||||
else:
|
||||
rows = rows[rows["valor_codigo"].notna()]
|
||||
column = "valor_codigo"
|
||||
rows = rows.sort_values(["fecha", "fuente_id"], kind="stable")
|
||||
return rows.groupby("pac_id")[column].last()
|
||||
|
||||
|
||||
def _present(events: pd.DataFrame, source: str) -> pd.Series:
|
||||
return pd.Series(True, index=events.loc[events["tipo"] == source, "pac_id"].unique())
|
||||
|
||||
|
||||
class Reader:
|
||||
"""Evaluates conditions over the patients' events, caching each source's per-patient value."""
|
||||
|
||||
def __init__(self, events: pd.DataFrame, patients: pd.Index, made: dict[str, pd.Series]):
|
||||
self.events, self.patients, self.made = events, patients, made
|
||||
self._cache: dict[tuple, pd.Series] = {}
|
||||
|
||||
def value(self, source: str, numeric: bool) -> pd.Series:
|
||||
key = (source, numeric)
|
||||
if key not in self._cache:
|
||||
self._cache[key] = _latest(self.events, source, numeric).reindex(self.patients)
|
||||
return self._cache[key]
|
||||
|
||||
def present(self, source: str) -> pd.Series:
|
||||
key = (source, "present")
|
||||
if key not in self._cache:
|
||||
self._cache[key] = _present(self.events, source).reindex(self.patients, fill_value=False).astype(bool)
|
||||
return self._cache[key]
|
||||
|
||||
def holds(self, condition: dict) -> np.ndarray:
|
||||
if "variable" in condition:
|
||||
return self.made[condition["variable"]].isin(condition["codes"]).to_numpy()
|
||||
source = condition["source"]
|
||||
if condition.get("present"):
|
||||
return self.present(source).to_numpy()
|
||||
if "codes" in condition:
|
||||
return self.value(source, False).isin(condition["codes"]).to_numpy()
|
||||
number = self.value(source, True)
|
||||
ok = number.notna()
|
||||
if "ge" in condition:
|
||||
ok &= number >= condition["ge"]
|
||||
if "lt" in condition:
|
||||
ok &= number < condition["lt"]
|
||||
return ok.to_numpy()
|
||||
|
||||
|
||||
def category_of(spec: dict, reader: Reader) -> pd.Series:
|
||||
out = pd.Series(spec["missing"], index=reader.patients, dtype=object)
|
||||
decided = np.zeros(len(reader.patients), bool)
|
||||
for rule in spec["rules"]:
|
||||
conditions = rule["when"] if "when" in rule else [rule]
|
||||
holds = np.ones(len(reader.patients), bool)
|
||||
for condition in conditions:
|
||||
holds &= reader.holds(condition)
|
||||
take = holds & ~decided
|
||||
out[take] = rule["then"]
|
||||
decided |= take
|
||||
return out
|
||||
|
||||
|
||||
def _band(age: pd.Series, index: dict) -> pd.Series:
|
||||
width, open_from = index["age_band_years"], index["age_open_from"]
|
||||
low = (np.floor(age / width) * width).clip(lower=0)
|
||||
closed = [index["age_label"].format(low=int(a), high=int(a) + width - 1) if pd.notna(a) else None for a in low]
|
||||
opened = index["age_open_label"].format(low=open_from)
|
||||
label = pd.Series(closed, index=age.index, dtype=object)
|
||||
label[age >= open_from] = opened
|
||||
return label.fillna(index["age_unknown"])
|
||||
|
||||
|
||||
def recode(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
|
||||
"""One row per patient of the cohort, in the columns of `output_columns`."""
|
||||
index = dictionary["index"]
|
||||
window = timedelta(days=int(dictionary["window_days_after_index"]))
|
||||
frame = cohort.copy()
|
||||
frame["fecha"] = pd.to_datetime(frame["fecha"])
|
||||
frame["fecha_indice"] = pd.to_datetime(frame["fecha_indice"])
|
||||
patients = pd.Index(sorted(frame["pac_id"].unique()), name="pac_id")
|
||||
start = frame.groupby("pac_id")["fecha_indice"].first().reindex(patients)
|
||||
visible = frame[frame["fecha"] <= frame["pac_id"].map(start) + window]
|
||||
|
||||
reader = Reader(visible, patients, {})
|
||||
for name in variable_names(dictionary):
|
||||
reader.made[name] = category_of(dictionary[name], reader)
|
||||
|
||||
birth = frame[frame["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
|
||||
death = frame[frame["tipo"] == index["death_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
|
||||
last = frame.groupby("pac_id")["fecha"].max().reindex(patients)
|
||||
end = death.fillna(last)
|
||||
days = (end - start).dt.days
|
||||
age = (start - birth).dt.days / 365.25
|
||||
|
||||
result = pd.DataFrame(index=patients)
|
||||
result[index["id_column"]] = patients.to_numpy()
|
||||
result[index["year_column"]] = start.dt.year.astype(str)
|
||||
result[index["age_column"]] = _band(age, index)
|
||||
for name in variable_names(dictionary):
|
||||
spec = dictionary[name]
|
||||
if spec.get("internal"):
|
||||
continue
|
||||
result[column_of(name, spec)] = reader.made[name]
|
||||
if "raw_column" in spec:
|
||||
size = reader.value(spec["source"], True)
|
||||
result[spec["raw_column"]] = [spec["raw_format"].format(v) if pd.notna(v) else spec["raw_missing"]
|
||||
for v in size]
|
||||
result[index["months_column"]] = (days / index["days_per_month"]).round().astype(int).astype(str)
|
||||
result[index["vital_column"]] = np.where(death.notna(), index["dead"], index["alive"])
|
||||
return result[output_columns(dictionary)].reset_index(drop=True)
|
||||
|
||||
|
||||
def diagnosis_date(year: int, dictionary: dict) -> date:
|
||||
month, day = dictionary["index"]["seer_diagnosis_month_day"].split("-")
|
||||
return date(int(year), int(month), int(day))
|
||||
@@ -19,7 +19,8 @@ import pandas as pd
|
||||
from models.cama.survival.estimator import molecular_subtype
|
||||
|
||||
|
||||
UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat")
|
||||
CONTEXT_COLUMNS = {"Estadio_cat": "stage", "Tratamiento_quirurgico_cat": "surgery", "Radioterapia_cat": "radiotherapy",
|
||||
"Quimioterapia_cat": "chemotherapy"}
|
||||
# What the dashboard reads: the file written by a stage, under the name it is published with.
|
||||
TABLES = {
|
||||
"or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos",
|
||||
@@ -28,10 +29,13 @@ TABLES = {
|
||||
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
|
||||
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
|
||||
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
|
||||
"curva_supervivencia_puntos_LR_HBN.csv": "cohorte_puntos",
|
||||
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
|
||||
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
|
||||
}
|
||||
MAX_ROWS = 60
|
||||
# The name the whole cohort's points go by among the subgroups' (`subgroup_points`).
|
||||
WHOLE_COHORT = "Toda la cohorte"
|
||||
MAX_FIGURE_BYTES = 400_000
|
||||
|
||||
|
||||
@@ -53,8 +57,8 @@ def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
|
||||
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
|
||||
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
|
||||
frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype
|
||||
for column in UNAVAILABLE:
|
||||
frame[column] = "Desconocido"
|
||||
for column, source in CONTEXT_COLUMNS.items():
|
||||
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy() if source in lm else "Desconocido"
|
||||
return frame
|
||||
|
||||
|
||||
@@ -111,9 +115,28 @@ def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict:
|
||||
figures[path.stem] = base64.b64encode(raw).decode("ascii")
|
||||
return {"desarrollo": {
|
||||
"version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log],
|
||||
"errores": errors, "variables_no_disponibles": list(UNAVAILABLE), "tablas": tables, "figuras": figures}}
|
||||
"errores": errors, "variables_no_disponibles": [c for c, s in CONTEXT_COLUMNS.items() if s not in labelled_members], "tablas": tables, "figuras": figures}}
|
||||
|
||||
|
||||
def population(population_curves: dict, development: dict) -> dict:
|
||||
"""Everything the version publishes about its cohort, by file name under `analisis/`: the curves and the development."""
|
||||
return {**population_curves, **development}
|
||||
|
||||
|
||||
def subgroup_points(labelled_members: pd.DataFrame, desarrollo: dict) -> list[dict]:
|
||||
"""The pipeline's stages 01 and 05 over the members as they are now: the depuration, then the LR and HBN fitted on them with
|
||||
each clinical scenario's survival at the horizons and its bootstrap interval (`subgrupos_puntos`), and the whole cohort's
|
||||
(`cohorte_puntos`, as subgroup `WHOLE_COHORT`), one row per model, horizon and scenario. What the dashboard draws as a
|
||||
scenario's points between trainings."""
|
||||
from models.cama.seer_survival import pipeline
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp)
|
||||
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
|
||||
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
|
||||
pipeline.run_pipeline(out, only=["01", "05"], everything=True, settings=_seer_settings(desarrollo))
|
||||
cohort = pd.read_csv(out / "curva_supervivencia_puntos_LR_HBN.csv").assign(subgrupo=WHOLE_COHORT)
|
||||
table = pd.concat([pd.read_csv(out / "subgrupos_puntos_LR_HBN.csv"), cohort[["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"]]],
|
||||
ignore_index=True)
|
||||
table = table.replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
return table.where(table.notna(), None).to_dict("records")
|
||||
|
||||
@@ -29,6 +29,13 @@ NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding:
|
||||
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"]
|
||||
RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er",
|
||||
"receptor_progesterona": "pr", "her2": "her2"}
|
||||
# What describes a member's disease and treatment without being a covariate: the clinical scenarios and the development
|
||||
# stages read them. The stage is the one reported with the diagnosis; a treatment counts in the first year after it.
|
||||
CONTEXT = ["stage", "surgery", "radiotherapy", "chemotherapy"]
|
||||
TREATMENT_DAYS = 365
|
||||
SURGERY_LABELS = {"SEGMENTECTOMIA": "Cirugía conservadora", "ESCISIONAL": "Cirugía conservadora",
|
||||
"MASTECTOMIA_TOTAL": "Mastectomía", "MASTECTOMIA_RADICAL_MODIFICADA": "Mastectomía",
|
||||
"SIN_CIRUGIA": "Sin cirugía"}
|
||||
WINDOW_KEYS = ("recruitment_start", "recruitment_end")
|
||||
DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
|
||||
EPOCH = pd.Timestamp("1970-01-01")
|
||||
@@ -78,7 +85,15 @@ def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_d
|
||||
size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
|
||||
members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS)
|
||||
members["size_mm"], members["ki67_pct"] = size, ki67
|
||||
return members[["fecha_indice", *FEATURES, *NUMERIC]]
|
||||
stage = near[near["tipo"] == "estadio_clinico"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
|
||||
members["stage"] = stage.map(lambda v: v[1:] if isinstance(v, str) and v.startswith("E") else v)
|
||||
treated = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, TREATMENT_DAYS)].sort_values(["fecha", "fuente_id"])
|
||||
surgery = treated[treated["tipo"] == "cirugia"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
|
||||
members["surgery"] = surgery.map(lambda v: SURGERY_LABELS.get(v, "Otra cirugía") if isinstance(v, str) else None)
|
||||
for kind, name in (("radioterapia", "radiotherapy"), ("quimioterapia", "chemotherapy")):
|
||||
given = set(treated.loc[treated["tipo"] == kind, "pac_id"])
|
||||
members[name] = ["Sí" if pac in given else "No" for pac in members.index]
|
||||
return members[["fecha_indice", *FEATURES, *NUMERIC, *CONTEXT]]
|
||||
|
||||
|
||||
def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame:
|
||||
@@ -88,7 +103,7 @@ def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame
|
||||
frame = _dated(cohort)
|
||||
index = frame.groupby("pac_id")["fecha_indice"].first()
|
||||
death = frame[frame["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(index.index)
|
||||
cutoff = pd.Timestamp(cutoff)
|
||||
cutoff = min(pd.Timestamp(cutoff), pd.Timestamp.today().normalize()) # nobody is followed past today
|
||||
died = (death.notna() & (death <= cutoff)).to_numpy()
|
||||
end = death.where(died, cutoff)
|
||||
months = np.floor((end - index).dt.days.to_numpy() / DAYS_PER_MONTH).astype(int).clip(min=0)
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
|
||||
"""The survival figure of a clinical scenario over the data ingested so far, as the SEER pipeline's survival stage draws a subgroup.
|
||||
|
||||
Training and tuning happen in governance; here the production version is only applied. The scenarios are the subgroups of
|
||||
the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
|
||||
share a figure, and a patient sees the figure of each scenario she belongs to. The record is the one the training run
|
||||
publishes for the whole cohort (`population`), for the scenario's members: the Kaplan-Meier curve of what happened to them
|
||||
with its Greenwood band, the survival the model predicts for them (their mean at each horizon by the logistic regression, the
|
||||
Bayesian network and their combination, with a 95 % interval from resampling the members), and the Weibull fits the SEER
|
||||
pipeline makes to that prediction. Nothing is fitted on the scenario and nothing is stored.
|
||||
Training and tuning happen in governance; here the production version's results are only shown. The scenarios are the subgroups
|
||||
of the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
|
||||
share a figure, and a patient sees the figure of each scenario she belongs to, or the whole cohort's when she is in none. The
|
||||
record has the Kaplan-Meier curve of what happened to the scenario's members with its Greenwood band, the classic and fractional
|
||||
Weibull fitted to their deaths, and the pipeline's LR, HBN and combined survival at each horizon with their bootstrap intervals:
|
||||
the survival stage's points for the scenario (`development.subgroup_points`), never a model of this module's.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -17,14 +16,13 @@ import pandas as pd
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival import survival_curves as luis
|
||||
from models.cama.survival import population
|
||||
from models.cama.survival.estimator import FEATURES, IntervalSurvival, molecular_subtype, survival_settings
|
||||
from models.cama.survival.development import WHOLE_COHORT
|
||||
from models.cama.survival.estimator import IntervalSurvival, molecular_subtype, survival_settings
|
||||
from models.dags.training import Scenario, dataflow
|
||||
|
||||
MIN_MEMBERS = 30
|
||||
MIN_EVENTS = 5
|
||||
REPLICAS = 200
|
||||
SEED = 42
|
||||
WHOLE = "Toda la cohorte"
|
||||
WHOLE = WHOLE_COHORT
|
||||
|
||||
|
||||
class QueryError(ValueError):
|
||||
@@ -47,9 +45,10 @@ def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFr
|
||||
|
||||
|
||||
def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported
|
||||
yet, so a scenario that needs them has no member."""
|
||||
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index)
|
||||
"""Each scenario's mask over the members, by her age, molecular subtype, stage and surgery."""
|
||||
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy(),
|
||||
"Estadio_cat": labelled["stage"].to_numpy(), "Tratamiento_quirurgico_cat": labelled["surgery"].to_numpy()},
|
||||
index=labelled.index)
|
||||
return scenarios.masks(raw)
|
||||
|
||||
|
||||
@@ -66,22 +65,27 @@ def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
|
||||
return found or [WHOLE]
|
||||
|
||||
|
||||
def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray:
|
||||
"""Each member's survival month by month from 0 to `months`: log-linear between the horizons, which is a constant hazard
|
||||
in each interval, and past the last one with the hazard of the last interval."""
|
||||
borders = np.array([0, *horizons], float)
|
||||
log = np.log(np.clip(np.column_stack([np.ones(len(survival)), survival]), 1e-12, 1.0))
|
||||
grid = np.arange(months + 1, dtype=float)
|
||||
out = np.empty((len(survival), len(grid)))
|
||||
slope = (log[:, -1] - log[:, -2]) / (borders[-1] - borders[-2])
|
||||
for i in range(len(survival)):
|
||||
out[i] = np.where(grid > borders[-1], log[i, -1] + slope[i] * (grid - borders[-1]), np.interp(grid, borders, log[i]))
|
||||
return np.minimum.accumulate(np.exp(out), axis=1)
|
||||
def published_points(rows: list[dict], name: str | None) -> dict | None:
|
||||
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`, or `cohorte_puntos` for `WHOLE`:
|
||||
its model with the stage and the treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
|
||||
found = [r for r in rows if r.get("subgrupo") == (name or WHOLE)]
|
||||
if not found:
|
||||
return None
|
||||
out = {}
|
||||
for series in population.SERIES:
|
||||
mine = sorted((r for r in found if r["modelo"] == series), key=lambda r: r["meses"])
|
||||
if not mine:
|
||||
return None
|
||||
out[series] = {"S": [float(r["S"]) for r in mine], "low": [float(r["IC_inf"]) for r in mine],
|
||||
"high": [float(r["IC_sup"]) for r in mine]}
|
||||
return out
|
||||
|
||||
|
||||
def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) -> dict:
|
||||
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone) scored with `model` (the fitted
|
||||
`IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
|
||||
def curves(scenario: Scenario, labelled: pd.DataFrame, name: str | None, points: dict | None) -> dict:
|
||||
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage
|
||||
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths, with the
|
||||
stage's `points` for it (`published_points`). `QueryError` for an unknown scenario, one with too few members to say
|
||||
anything, or one the stage has no points for yet."""
|
||||
if name in (None, WHOLE):
|
||||
mask = np.ones(len(labelled), bool)
|
||||
else:
|
||||
@@ -92,25 +96,22 @@ def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None)
|
||||
if not answerable(labelled, mask):
|
||||
raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; "
|
||||
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
|
||||
if points is None:
|
||||
raise QueryError("El modelo todavía no tiene la supervivencia de este escenario; se calcula en el siguiente recálculo de indicadores.")
|
||||
selected = labelled[mask].reset_index(drop=True)
|
||||
s = survival_settings(scenario.config["survival"])
|
||||
horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons))
|
||||
predicted = model.component_survival(selected[FEATURES])
|
||||
resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected)))
|
||||
points = {}
|
||||
for series in population.SERIES:
|
||||
low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0)
|
||||
points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()}
|
||||
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
|
||||
S, low, high = luis.fw.km_curva(np.minimum(followed, cap), died & (followed < cap), cap)
|
||||
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
|
||||
classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_max_seconds)
|
||||
months, ended = np.minimum(followed, cap), died & (followed < cap)
|
||||
S, low, high = luis.fw.km_curva(months, ended, cap)
|
||||
d, c = luis.fw.tabla_eventos(months, ended)
|
||||
classic = luis.fw.ajustar_weibull(d, c)
|
||||
fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_max_seconds)
|
||||
grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP)
|
||||
return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)),
|
||||
"events": int((died & (followed < cap)).sum()), "median_follow_up_months": float(np.median(followed)),
|
||||
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": REPLICAS,
|
||||
"events": int(ended.sum()), "median_follow_up_months": float(np.median(followed)),
|
||||
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": int(s.n_boot if name in (None, WHOLE) else s.n_boot_sub),
|
||||
"km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
|
||||
"km_adjusted": {"months": list(range(len(adjusted))), "S": adjusted.tolist()},
|
||||
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
|
||||
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
|
||||
"points": points, "etiquetas": scenario.config.get("etiquetas", {})}
|
||||
|
||||
@@ -47,9 +47,14 @@ class Scenario:
|
||||
config: dict
|
||||
folder: Path
|
||||
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)
|
||||
# Whether the cycle scores every member of the cohort with the version in production (`batch_estimates`); off for a
|
||||
# model whose answers are per clinical scenario, not a risk per member.
|
||||
batch_estimates: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, path: str | Path) -> "Scenario":
|
||||
@@ -59,7 +64,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", ())),
|
||||
estimand=dict(found.get("estimand", {})))
|
||||
tables={name: found[name] for name in found.get("settings_tables", ())} or None,
|
||||
estimand=dict(found.get("estimand", {})), batch_estimates=bool(found.get("batch_estimates", True)))
|
||||
|
||||
@classmethod
|
||||
def load(cls, domain: str, scenario: str) -> "Scenario":
|
||||
@@ -71,7 +77,8 @@ class Scenario:
|
||||
return cls.from_toml(Path(package.__file__).parent / "model.toml")
|
||||
|
||||
def config_sha256(self) -> str:
|
||||
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
|
||||
content = self.config if not self.tables else {"config": self.config, **self.tables}
|
||||
return hashlib.sha256(json.dumps(content, sort_keys=True, default=str).encode()).hexdigest()
|
||||
|
||||
|
||||
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
|
||||
|
||||
+83
-46
@@ -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.
|
||||
|
||||
@@ -13,18 +13,20 @@ its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrup
|
||||
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
||||
"""
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from itertools import batched
|
||||
|
||||
from sqlalchemy import case
|
||||
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"
|
||||
|
||||
@@ -38,10 +40,26 @@ def checked_settings() -> Settings:
|
||||
return s
|
||||
|
||||
|
||||
def selected_ids(session: Session, ids: Sequence[int | str]) -> list[str]:
|
||||
"""Resolve requested IDs and return the ones with stored EDFs."""
|
||||
requested = {str(eeg_id) for eeg_id in ids}
|
||||
has_edf = case((Eeg.eeg_estudio.is_not(None), 1), else_=0)
|
||||
found = {}
|
||||
for group in batched(requested, 500):
|
||||
query = select(Eeg.eeg_id, has_edf).where(col(Eeg.eeg_id).in_(group))
|
||||
found.update(session.exec(query).all())
|
||||
missing = sorted(requested - found.keys())
|
||||
if missing:
|
||||
raise LookupError(f"No se encontraron los EEG: {', '.join(missing)}")
|
||||
return sorted(eeg_id for eeg_id, stored in found.items() if stored)
|
||||
|
||||
|
||||
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
|
||||
everything: bool = False, limit: int | None = None) -> list[str]:
|
||||
everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None) -> list[str]:
|
||||
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
|
||||
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
|
||||
if ids is not None:
|
||||
return selected_ids(session, ids)
|
||||
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
|
||||
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
|
||||
out, expected = [], None
|
||||
@@ -83,6 +101,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 +127,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 +162,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 +175,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 +212,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
|
||||
|
||||
@@ -190,47 +221,53 @@ def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
|
||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None,
|
||||
cluster: str = "auto", batch: int = 16,
|
||||
settings: Settings | None = None, baselines: Baselines | None = None,
|
||||
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
from tea.pipeline.run_monitor import monitor_from_env
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings or checked_settings()
|
||||
b = baselines or Baselines(s.domain)
|
||||
pipe = pipeline(s)
|
||||
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
||||
with eeg_repository.open_session() as session:
|
||||
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||
everything=everything, limit=limit)
|
||||
summary = Summary(pending=len(ids))
|
||||
|
||||
def write(m: Measurement) -> None:
|
||||
ended = _now()
|
||||
with monitor_from_env() as monitor:
|
||||
s = settings or checked_settings()
|
||||
b = baselines or Baselines(s.domain)
|
||||
pipe = pipeline(s)
|
||||
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, m.key, rows(m, s, b, at=ended))
|
||||
session.commit()
|
||||
if log_runs:
|
||||
from persistance.governance import extraction_run_repository
|
||||
selected = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||
everything=everything, limit=limit, ids=ids)
|
||||
summary = Summary(pending=len(selected))
|
||||
monitor.total(summary.pending)
|
||||
monitor.phase("analizando")
|
||||
|
||||
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
|
||||
if m.error:
|
||||
summary.failed += 1
|
||||
elif m.valid:
|
||||
summary.valid += 1
|
||||
else:
|
||||
summary.not_valid += 1
|
||||
def write(m: Measurement) -> None:
|
||||
ended = _now()
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, m.key, rows(m, s, b, at=ended))
|
||||
session.commit()
|
||||
monitor.advance()
|
||||
if log_runs:
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
def lost(args, exc) -> Measurement:
|
||||
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
||||
error=f"{type(exc).__name__}: the batch lost this study")
|
||||
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
|
||||
if m.error:
|
||||
summary.failed += 1
|
||||
elif m.valid:
|
||||
summary.valid += 1
|
||||
else:
|
||||
summary.not_valid += 1
|
||||
|
||||
for start in range(0, len(ids), batch):
|
||||
argsets = []
|
||||
with eeg_repository.open_session() as session:
|
||||
for eeg_id in ids[start:start + batch]:
|
||||
edf, age = inputs(session, eeg_id, s.days_per_month)
|
||||
argsets.append((eeg_id, edf, age, s))
|
||||
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
|
||||
return summary
|
||||
def lost(args, exc) -> Measurement:
|
||||
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
||||
error=f"{type(exc).__name__}: the batch lost this study")
|
||||
|
||||
for start in range(0, len(selected), batch):
|
||||
argsets = []
|
||||
with eeg_repository.open_session() as session:
|
||||
for eeg_id in selected[start:start + batch]:
|
||||
edf, age = inputs(session, eeg_id, s.days_per_month)
|
||||
argsets.append((eeg_id, edf, age, s))
|
||||
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost, track_progress=False)
|
||||
return summary
|
||||
|
||||
@@ -28,6 +28,9 @@ earlier events ("no CIN2+ before the index", "first colposcopy", the referral ye
|
||||
with enough history makes them valid without changing code. Observation starts, for now, at the patient's first
|
||||
event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline).
|
||||
|
||||
- `primera_biopsia_invasora` (CaMa): the first biopsy reported as invasive carcinoma, if it falls in the window; no
|
||||
rules. The cohort is read whole, not patient by patient (`VECTORIZED`).
|
||||
|
||||
A scenario without `[config.index]` keeps its cohort's own index.
|
||||
"""
|
||||
|
||||
@@ -146,6 +149,24 @@ KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposc
|
||||
"primera_biopsia_invasora": _first_invasive_biopsy}
|
||||
|
||||
|
||||
def _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
|
||||
"""(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame."""
|
||||
biopsies = cohort[(cohort["tipo"] == "biopsia") & (cohort["valor_codigo"] == index.get("invasive_code", "CARCINOMA_INVASOR"))]
|
||||
first = pd.to_datetime(biopsies["fecha"]).groupby(biopsies["pac_id"]).min()
|
||||
start, end = index.get("recruitment_start"), index.get("recruitment_end")
|
||||
inside = pd.Series(True, index=first.index)
|
||||
if start is not None:
|
||||
inside &= first >= pd.Timestamp(start)
|
||||
if end is not None:
|
||||
inside &= first < pd.Timestamp(end)
|
||||
members = first[inside].rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index()
|
||||
return members, [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(members))]
|
||||
|
||||
|
||||
# Kinds read from the whole frame: (cohort, index) -> (members, attrition), for cohorts too large to take apart by patient.
|
||||
VECTORIZED = {"primera_biopsia_invasora": _first_invasive_biopsy}
|
||||
|
||||
|
||||
def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]:
|
||||
events = defaultdict(list)
|
||||
for e in cohort.to_dict("records"):
|
||||
@@ -161,6 +182,8 @@ def _prior_days(rows: list[dict], fecha: date) -> int:
|
||||
def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
|
||||
"""(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and
|
||||
after each rule, in order; each rule is charged only for those it removes from what it receives."""
|
||||
if index["kind"] in VECTORIZED:
|
||||
return VECTORIZED[index["kind"]](cohort, index)
|
||||
rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0))
|
||||
events = _events(cohort)
|
||||
found = {}
|
||||
@@ -207,6 +230,12 @@ def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index:
|
||||
if not index:
|
||||
return {}
|
||||
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
|
||||
if index["kind"] in VECTORIZED:
|
||||
first = pd.to_datetime(source_cohort["fecha"]).groupby(source_cohort["pac_id"]).min()
|
||||
days = (pd.to_datetime(members["fecha_indice"]) - first.reindex(members["pac_id"]).to_numpy()).dt.days.astype(float)
|
||||
return {"members": len(days), "under_365_days": int((days < 365).sum()),
|
||||
"median_days": None if days.empty else float(days.median()),
|
||||
"threshold_days": int(index.get("observacion_previa_minima_dias", 0))}
|
||||
events = _events(source_cohort)
|
||||
days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float)
|
||||
return {"members": len(days), "under_365_days": int((days < 365).sum()),
|
||||
|
||||
@@ -1 +1 @@
|
||||
"""TEA's models: the EEG analysis (`eeg`)."""
|
||||
"""TEA's models: the EEG analysis (`eeg`) and the ADOS-2 association (`ados2`)."""
|
||||
|
||||
@@ -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`."""
|
||||
@@ -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"
|
||||
@@ -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"]))
|
||||
+17
-11
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -6,11 +6,19 @@ then promoting each through the registry's checks. `--reference-dir` trains on a
|
||||
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
SETTINGS = settings()
|
||||
CLUSTERS = ("auto", "local", "remote", "sync")
|
||||
|
||||
|
||||
def _cluster() -> str:
|
||||
"""Where training measures the studies: `EEG_ANALYSIS_CLUSTER` when it names a runner, else `auto`."""
|
||||
chosen = os.environ.get("EEG_ANALYSIS_CLUSTER", "auto")
|
||||
return chosen if chosen in CLUSTERS else "auto"
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
@@ -32,7 +40,7 @@ def run_steps(args: argparse.Namespace) -> int:
|
||||
return 2
|
||||
versions: dict[str, str] = {}
|
||||
if args.train:
|
||||
for scenario, (version, new) in train.train_all(s, environment).items():
|
||||
for scenario, (version, new) in train.train_all(s, environment, cluster=_cluster()).items():
|
||||
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
||||
versions[scenario] = version
|
||||
if not args.promote:
|
||||
|
||||
@@ -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 `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode.
|
||||
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode, and `zones` the
|
||||
# one whose `<zone_prefix><zone>` 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"
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
+24
-14
@@ -19,6 +19,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
from tea.pipeline.run_monitor import active_monitor, monitor_from_env
|
||||
|
||||
from models.io.lineage import (
|
||||
COHORT_BUILD_TAG,
|
||||
@@ -78,7 +79,7 @@ def list_reference(s: Settings) -> list[tuple[str, float]]:
|
||||
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster, track_progress=False)
|
||||
return Listing.of(s.reference.name, found)
|
||||
|
||||
|
||||
@@ -146,9 +147,14 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
data = table(studies, biomarker, phase)
|
||||
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
||||
monitor = active_monitor()
|
||||
if monitor is not None:
|
||||
monitor.phase("ajustando")
|
||||
module.train(data)
|
||||
sha, state = _module_state(module)
|
||||
name = registered_name(DOMAIN, scenario)
|
||||
if monitor is not None:
|
||||
monitor.phase("registrando")
|
||||
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
||||
experiment_id(MlflowClient(), name)
|
||||
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
||||
@@ -210,19 +216,23 @@ def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Li
|
||||
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
||||
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
||||
scenario needs it."""
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
studies = studies if studies is not None else measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
with monitor_from_env() as monitor:
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
if studies is None:
|
||||
monitor.total(len(found.studies))
|
||||
monitor.phase("midiendo")
|
||||
studies = measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
|
||||
|
||||
def latest(scenario: str, environment: str):
|
||||
|
||||
+121
-127
@@ -1,93 +1,119 @@
|
||||
"""CaMa's recurrence analysis (`models.cama.recurrence`): the two external cohorts as Luis's preparation reads them, the whole
|
||||
dataflow over small synthetic cohorts with the same columns (the figures of the scenarios, the tables, the routines the registry
|
||||
asks for and the saved model), and the model's prediction. Fixtures: `files`, METABRIC- and SCAN-B-shaped files of 700 patients
|
||||
each whose recurrence depends on grade, size and estrogen receptor, in a temporary folder.
|
||||
"""What this module covers: CaMa's recurrence analysis (`models.cama.recurrence`) over the total cohort's timeline: each
|
||||
cohort's patients read by the dictionary (`cohort.recode`), the whole dataflow (the figures of the scenarios, the tables, the
|
||||
routines the registry asks for and the saved model), training a version from a build, and the import files that put the
|
||||
cohorts in the platform (`cohort_import`).
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 600 patients loaded from METABRIC and 600 from SCAN-B (their `fuente`), each with
|
||||
her birth, an invasive biopsy in 2018-2019 with grade, estrogen receptor, size and nodes, a surgery, and her recurrence or
|
||||
last contact (recurrence faster with grade 3, a large tumor and no estrogen receptor), plus 20 hospital patients with no
|
||||
`fuente` that neither cohort takes; `cohort_file`, that frame as a build's Parquet file with its lineage; `mlflow_tracking`
|
||||
(conftest), a SQLite-backed MLflow.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import dataclasses
|
||||
import json
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.cama.recurrence import prep
|
||||
from models.cama.recurrence import cohort, cohort_import
|
||||
from models.cama.recurrence.model import RecurrenceModel
|
||||
from models.cama.recurrence.source import PACKAGE_DATA, ExternalCohorts
|
||||
from models.dags.training import Scenario, dataflow
|
||||
from models.dags.training import Scenario, dataflow, train
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||
from models.io.storage import CohortFile
|
||||
from models.steps import indexing
|
||||
|
||||
N = 700
|
||||
N = 600
|
||||
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": "2026-12-31"}
|
||||
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": "2026-11-21", "parametros": json.dumps(WINDOW)}
|
||||
SMALL = {"horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5,
|
||||
"ks_seconds": 2, "max_parents": 3}
|
||||
|
||||
|
||||
def _risk(rng, grade, size, er_positive):
|
||||
return 0.012 * np.exp(0.8 * (grade - 2) + 0.5 * (size > 30) - 0.5 * er_positive)
|
||||
def _row(pac_id, when, first, tipo, valor=None, numero=None, source_id=None):
|
||||
return {"pac_id": pac_id, "fecha_indice": first, "fecha": when, "conocida_en": datetime(2026, 11, 21, tzinfo=timezone.utc),
|
||||
"clase": "medicion", "tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": numero,
|
||||
"fuente_tabla": "silver", "fuente_id": source_id or f"{pac_id}-{tipo}"}
|
||||
|
||||
|
||||
def _patient(rng, pac_id, source):
|
||||
index = date(2018, 1, 1) + timedelta(days=int(rng.integers(0, 540)))
|
||||
grade, er = str(rng.choice(["G1", "G2", "G3"])), bool(rng.random() < 0.7)
|
||||
size, nodes = float(rng.gamma(4, 7)), int(rng.integers(0, 9))
|
||||
rate = 0.012 * np.exp(0.8 * (int(grade[1]) - 2) + 0.5 * (size > 30) - 0.5 * er)
|
||||
months, followed = rng.exponential(1 / rate), rng.uniform(30, 90)
|
||||
end = index + timedelta(days=int(min(months, followed) * 30.4375))
|
||||
born = index - timedelta(days=int(rng.normal(60, 12) * 365.25))
|
||||
rows = [_row(pac_id, born, born, "nacimiento")]
|
||||
if source:
|
||||
rows.append(_row(pac_id, born, born, "fuente", source))
|
||||
rows += [_row(pac_id, index, born, "biopsia", "CARCINOMA_INVASOR"), _row(pac_id, index, born, "grado_nottingham", grade),
|
||||
_row(pac_id, index, born, "receptor_estrogeno", "POSITIVO" if er else "NEGATIVO"),
|
||||
_row(pac_id, index, born, "tamano_tumor_mm", numero=size), _row(pac_id, index, born, "ganglios_positivos", numero=float(nodes)),
|
||||
_row(pac_id, index, born, "cirugia", str(rng.choice(["MASTECTOMIA_TOTAL", "SEGMENTECTOMIA"])))]
|
||||
rows.append(_row(pac_id, end, born, "recurrencia" if months <= followed else "ultimo_contacto"))
|
||||
return rows
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def files(tmp_path_factory) -> Path:
|
||||
"""Two files shaped like METABRIC's TSV and SCAN-B's metadata, recurrence exponential in months and faster with a high grade,
|
||||
a large tumor and no estrogen receptor; 10 % of the SCAN-B rows are men, which the preparation leaves out."""
|
||||
def cohort_frame():
|
||||
"""METABRIC's patients are 1-600, SCAN-B's 1001-1600, and 2001-2020 are the hospital's own."""
|
||||
rng = np.random.default_rng(5)
|
||||
folder = tmp_path_factory.mktemp("externas")
|
||||
grade = rng.choice([1, 2, 3], N, p=[0.2, 0.45, 0.35])
|
||||
size = rng.gamma(4, 7, N)
|
||||
er = rng.random(N) < 0.7
|
||||
months = rng.exponential(1 / _risk(rng, grade, size, er))
|
||||
followed = np.minimum(months, rng.uniform(30, 150, N))
|
||||
event = months <= followed
|
||||
common = lambda: rng.choice(["Positive", "Negative"], N, p=[0.5, 0.5])
|
||||
pd.DataFrame({
|
||||
"Patient ID": [f"M{i}" for i in range(N)], "Relapse Free Status": np.where(event, "1:Recurred", "0:Not Recurred"),
|
||||
"Relapse Free Status (Months)": followed, "Age at Diagnosis": rng.normal(60, 12, N).clip(25, 90), "Tumor Size": size,
|
||||
"Lymph nodes examined positive": rng.integers(0, 9, N), "Neoplasm Histologic Grade": grade.astype(float),
|
||||
"Mutation Count": rng.integers(1, 12, N), "ER Status": np.where(er, "Positive", "Negative"), "PR Status": common(),
|
||||
"HER2 Status": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
|
||||
"Pam50 + Claudin-low subtype": rng.choice(["LumA", "LumB", "Basal", "Her2"], N), "Cancer Type Detailed": rng.choice(["Ductal", "Lobular"], N),
|
||||
"Cellularity": rng.choice(["High", "Moderate", "Low"], N), "Inferred Menopausal State": rng.choice(["Post", "Pre"], N),
|
||||
"Integrative Cluster": rng.choice(list("12345"), N), "Primary Tumor Laterality": rng.choice(["Left", "Right"], N),
|
||||
"Type of Breast Surgery": rng.choice(["MASTECTOMY", "BREAST CONSERVING"], N), "Chemotherapy": rng.choice(["YES", "NO"], N),
|
||||
"Radio Therapy": rng.choice(["YES", "NO"], N), "Hormone Therapy": rng.choice(["YES", "NO"], N),
|
||||
}).to_csv(folder / prep.FILES["metabric"], sep="\t", index=False)
|
||||
days = followed * prep.DAYS_PER_MONTH
|
||||
pd.DataFrame({
|
||||
"PatientName": [f"S{i}" for i in range(N)], "Gender": np.where(rng.random(N) < 0.1, "M", "F"), "RFI_event": event.astype(int),
|
||||
"RFI_days": days, "OS_event": rng.integers(0, 2, N), "Age_5year_bin": rng.choice([42, 47, 52, 57, 62, 67, 72, 77], N),
|
||||
"TumorSize_mm": size, "NodeMetSpec": rng.choice(["NodeNegative", "1to3", "4toX"], N), "NHG": np.array(["Grade1", "Grade2", "Grade3"])[grade - 1],
|
||||
"ER": np.where(er, "Positive", "Negative"), "PR": common(), "HER2": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
|
||||
"Ki67": rng.choice(["High", "Low"], N), "ClinicalSubtype": rng.choice(["Luminal A", "Basal-like", "Luminal B HER2-"], N),
|
||||
"Histology": rng.choice(["Ductal", "Lobular"], N), "MenopauseStatus_bin": rng.choice(["Post", "Pre"], N), "Laterality": rng.choice(["Left", "Right"], N),
|
||||
"tnm_ClinicalStage": rng.choice(["I", "II", "III"], N), "SurgeryType": rng.choice(["Mastectomy", "Lumpectomy"], N),
|
||||
"Chemotherapy": rng.choice(["Yes", "No"], N), "Radiation": rng.choice(["Yes", "No"], N), "Endocrine": rng.choice(["Yes", "No"], N),
|
||||
"AntiHER2": rng.choice(["Yes", "No"], N),
|
||||
}).to_csv(folder / prep.FILES["scanb"], sep="\t", index=False)
|
||||
return folder
|
||||
rows = []
|
||||
for offset, source in ((0, "METABRIC"), (1000, "SCANB")):
|
||||
for i in range(1, N + 1):
|
||||
rows += _patient(rng, offset + i, source)
|
||||
for i in range(2001, 2021):
|
||||
rows += _patient(rng, i, None)
|
||||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
|
||||
def test_the_real_cohorts_are_read_as_the_preparation_scripts_read_them():
|
||||
"""Pins down: METABRIC gives 2,380 patients with time and status of recurrence (964 recurrences) and SCAN-B 8,847 women, with
|
||||
the covariates as categories (the unknowns one more) and a redundant covariate dropped from each. Fails if a column is read
|
||||
differently, a patient with no follow-up is kept, or the collinearity rule drops other covariates."""
|
||||
metabric = prep.prepare_metabric(str(PACKAGE_DATA / prep.FILES["metabric"]), 0.80)
|
||||
scanb = prep.prepare_scanb(str(PACKAGE_DATA / prep.FILES["scanb"]), 0.80)
|
||||
|
||||
assert (len(metabric.cohort), int(metabric.cohort["evento"].sum())) == (2380, 964)
|
||||
assert len(scanb.cohort) == 8847 and "Gender" not in scanb.cohort
|
||||
assert metabric.eliminated == ["HER2"] and "HER2" not in metabric.covariates
|
||||
assert set(scanb.eliminated) == {"Receptor_estrogeno", "HER2", "Receptor_progesterona"}
|
||||
assert set(metabric.cohort["Edad"]) <= {"<45", "45-59", "60-74", "75+", "Desconocido"}
|
||||
assert metabric.treatment == ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
"""The frame as build 4's file, with the lineage a dbt build gives."""
|
||||
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "4.parquet"
|
||||
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "4"}), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(files):
|
||||
"""Pins down: the dataflow over small cohorts gives a figure for each scenario with enough recurrences (the Kaplan-Meier with
|
||||
its band, both Weibull and the combined recurrence-free probability at each horizon with its interval), the tables behind
|
||||
them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a stage stops
|
||||
feeding the next, the figures lose a curve or a routine is missing."""
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
config = {"recurrence": {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2,
|
||||
"n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}}
|
||||
dr = dataflow(*scenario.modules, config=config)
|
||||
def _small(scenario: Scenario) -> Scenario:
|
||||
return dataclasses.replace(scenario, config={**scenario.config, "recurrence": {**scenario.config["recurrence"], **SMALL}})
|
||||
|
||||
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"])
|
||||
|
||||
def test_each_cohort_takes_only_the_patients_loaded_from_it(cohort_frame):
|
||||
"""Pins down: METABRIC's frame has its 600 patients and SCAN-B's its own, with the follow-up in months from the biopsy,
|
||||
the recurrence as the event and the dictionary's categories (the unknown one more), once the scenario's index (the first
|
||||
invasive biopsy) is set; the hospital's patients are in neither. Fails if `recode` stops filtering by `fuente`, reads another index, or a rule maps a code to another category."""
|
||||
model = cohort.load()
|
||||
indexed = indexing.cohort(cohort_frame, LINEAGE, Scenario.load("cama", "recurrence").config["index"])
|
||||
|
||||
metabric = cohort.recode(indexed, model, "metabric")
|
||||
scanb = cohort.recode(indexed, model, "scanb")
|
||||
|
||||
assert len(metabric) == N and set(metabric["paciente"]) == set(range(1, N + 1))
|
||||
assert len(scanb) == N and set(scanb["paciente"]) == set(range(1001, 1001 + N))
|
||||
assert (metabric["tiempo_meses"] > 0).all() and 0 < metabric["evento"].sum() < N
|
||||
assert set(metabric["Grado_histologico"]) == {"1", "2", "3"}
|
||||
assert set(metabric["Receptor_estrogeno"]) == {"Positive", "Negative"}
|
||||
assert set(metabric["Cirugia"]) == {"MASTECTOMY", "BREAST CONSERVING"} and set(scanb["Cirugia"]) == {"Mastectomy", "Lumpectomy"}
|
||||
assert set(metabric["Subtipo_PAM50"]) == {"Desconocido"}
|
||||
|
||||
|
||||
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(cohort_frame):
|
||||
"""Pins down: the dataflow over the total cohort's timeline gives a figure for each scenario with enough recurrences (the
|
||||
Kaplan-Meier with its band, both Weibull and the combined recurrence-free probability at each horizon with its interval),
|
||||
the tables behind them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a
|
||||
stage stops feeding the next, the figures lose a curve or a routine is missing."""
|
||||
scenario = _small(Scenario.load("cama", "recurrence"))
|
||||
dr = dataflow(*scenario.modules, config=scenario.config)
|
||||
|
||||
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"],
|
||||
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
|
||||
|
||||
figures = r["population"]["recurrencia"]["escenarios"]
|
||||
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
|
||||
@@ -95,78 +121,46 @@ def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(fi
|
||||
assert set(one) >= {"escenario", "condiciones", "n", "recaidas", "km", "weibull", "weibull_fractional", "points"}
|
||||
comb = one["points"]["COMB"]
|
||||
assert len(comb["S"]) == 2 and all(lo <= s <= hi + 1e-9 for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
|
||||
assert len(one["km"]["S"]) == len(one["km"]["low"]) == one["observado_hasta"] + 1
|
||||
assert {"auc", "factores_riesgo", "calculadora", "escenarios_resumen"} <= set(r["population"]["recurrencia_desarrollo"]["tablas"])
|
||||
assert set(r["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
|
||||
assert r["metrics"] and all(isinstance(v, float) for v in r["metrics"].values())
|
||||
assert len(r["prepared"]["scanb"].cohort) < N # the men are left out
|
||||
assert len(r["prepared"]["metabric"].cohort) == len(r["prepared"]["scanb"].cohort) == N
|
||||
model: RecurrenceModel = r["fitted_model"]
|
||||
p = model.predict_proba(r["prepared"]["metabric"].cohort.head(50))
|
||||
assert p.shape == (50, 2) and ((p >= 0) & (p <= 1)).all()
|
||||
|
||||
|
||||
def test_the_external_cohorts_are_the_versions_reference_and_the_files_are_hashed(files):
|
||||
"""Pins down: the reference the version is traced to is the hash of the two files, as a reference source and not a platform
|
||||
build, and a different file is a different reference. Fails if a change in the data does not change the reference (a retrain
|
||||
would then be skipped) or the version cannot be promoted for want of a cohort link."""
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
|
||||
source = ExternalCohorts(files)
|
||||
before = source.reference()[COHORT_BUILD_TAG]
|
||||
(files / prep.FILES["metabric"]).write_text((files / prep.FILES["metabric"]).read_text() + "\n")
|
||||
|
||||
assert source.reference()[COHORT_SOURCE_TAG] == REFERENCE_SOURCE and len(before) == 64
|
||||
assert ExternalCohorts(files).reference()[COHORT_BUILD_TAG] != before
|
||||
|
||||
|
||||
def test_a_version_trains_registers_and_publishes_its_figures(files, mlflow_tracking):
|
||||
"""Pins down: training the scenario on its files registers a PROD version that carries the figures the dashboard draws
|
||||
(`analisis/recurrencia.json`), the tables, the routines, the metrics and the saved model, linked to the files' hash, so that
|
||||
only the human reports stand between it and promotion. Fails if the version cannot be saved, loses its figures, or fails a
|
||||
promotion check that is not the reports."""
|
||||
import dataclasses
|
||||
import json
|
||||
|
||||
from models.dags.training import train
|
||||
def test_a_version_trains_from_a_build_registers_and_publishes_its_figures(cohort_file, mlflow_tracking):
|
||||
"""Pins down: training the scenario on a build of the total cohort registers a PROD version that carries the figures the
|
||||
dashboard draws (`analisis/recurrencia.json`) and the tables. Fails if the version cannot be saved or loses its figures."""
|
||||
from models.io.registry import registry
|
||||
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
|
||||
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
|
||||
scenario = dataclasses.replace(scenario, config={"recurrence": tiny})
|
||||
|
||||
version = train(scenario, ExternalCohorts(files), "PROD")
|
||||
version = train(_small(Scenario.load("cama", "recurrence")), CohortFile(cohort_file), "PROD")
|
||||
|
||||
_, figures = registry.artifact("cama", "recurrence", version, "analisis/recurrencia.json")
|
||||
_, tables = registry.artifact("cama", "recurrence", version, "analisis/recurrencia_desarrollo.json")
|
||||
assert json.loads(figures)["escenarios"] and "auc" in json.loads(tables)["tablas"]
|
||||
checks = {c.code: c.passed for c in registry.checks("cama", "recurrence", version)}
|
||||
assert all(checks[code] for code in ("ML-02", "ML-03", "ML-01a", "ML-01b"))
|
||||
assert not checks["MLD-01b"] and not checks["MLD-03"] # the reports are the human gate
|
||||
|
||||
|
||||
def test_the_cli_trains_and_leaves_the_version_waiting_for_its_reports(files, mlflow_tracking, monkeypatch, capsys):
|
||||
"""Pins down: `models run cama recurrence --train --promote` (what a governance job runs) trains the version, says "trained", then
|
||||
refuses to promote it for want of its reports with the message the job reads ("not promoted, missing") and exit code 1; run
|
||||
again it finds the version already trained. Fails if the entry point cannot run (a missing import), trains twice, or
|
||||
promotes without the human reports."""
|
||||
import argparse
|
||||
import dataclasses
|
||||
def test_the_import_files_place_the_diagnoses_in_a_window_and_end_the_follow_up_at_the_censor():
|
||||
"""Pins down: with `diagnosis_from` every diagnosis falls in the given span (the same day for the same patient), and with
|
||||
`censor` no date is after it: a recurrence after it becomes a last contact on that day. Fails if the dictionary's fixed year
|
||||
is kept, the spread depends on the row order, or a follow-up runs past the censor."""
|
||||
raw = pd.DataFrame({"Patient ID": ["A", "B", "C"], "Relapse Free Status": ["1:Recurred", "0:Not Recurred", "1:Recurred"],
|
||||
"Relapse Free Status (Months)": ["10", "200", "120"], "Age at Diagnosis": ["50", "61", "70"]})
|
||||
model = cohort_import.load()
|
||||
named = [s["metabric"]["column"] for s in model["variables"].values() if isinstance(s, dict) and "column" in s.get("metabric", {})]
|
||||
raw = raw.reindex(columns=[*raw.columns, *named], fill_value="")
|
||||
|
||||
from models.cama.recurrence.steps import run_steps
|
||||
tables = cohort_import.convert(raw, "metabric", model, diagnosis_from="2018-01-01", spread_days=540,
|
||||
censor="2026-11-21")
|
||||
again = cohort_import.convert(raw.iloc[::-1], "metabric", model, diagnosis_from="2018-01-01",
|
||||
spread_days=540, censor="2026-11-21")
|
||||
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
|
||||
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
|
||||
monkeypatch.setattr(Scenario, "load", classmethod(lambda cls, domain, name: dataclasses.replace(scenario, config={"recurrence": tiny})))
|
||||
args = argparse.Namespace(export=False, estimate=False, store=False, version=None, train=True, promote=True, environment="prod",
|
||||
domain="cama", scenario="recurrence")
|
||||
|
||||
first = run_steps(args)
|
||||
out = capsys.readouterr()
|
||||
second = run_steps(args)
|
||||
again = capsys.readouterr()
|
||||
|
||||
assert first == 1 and "trained: version 1" in out.out and "not promoted, missing" in out.err
|
||||
assert second == 1 and "already trained: version 1" in again.out
|
||||
diagnosis = pd.to_datetime(tables["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"])
|
||||
assert diagnosis.between("2018-01-01", "2019-06-24").all()
|
||||
assert diagnosis.equals(pd.to_datetime(again["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"]).reindex(diagnosis.index))
|
||||
follow = tables["SeguimientoMama"].set_index("pac_id_hospital")
|
||||
assert (pd.to_datetime(follow["seg_fecha"]) <= "2026-11-21").all()
|
||||
assert follow.loc["METABRIC-A", "seg_tipo"] == "recurrencia"
|
||||
assert follow.loc["METABRIC-C", "seg_tipo"] == "ultimo_contacto" and follow.loc["METABRIC-C", "seg_fecha"] == "2026-11-21"
|
||||
|
||||
@@ -300,10 +300,11 @@ def development_record(cohort_frame):
|
||||
def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record):
|
||||
"""Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation
|
||||
publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's
|
||||
exception escapes the node, which would stop a version from training."""
|
||||
exception escapes the node, which would stop a version from training. The stage and the treatments come from the
|
||||
members' timeline, so none of them is listed as unavailable; fails if the record stops reading them."""
|
||||
assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"]
|
||||
assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"}
|
||||
assert "Estadio_cat" in development_record["variables_no_disponibles"]
|
||||
assert development_record["variables_no_disponibles"] == []
|
||||
|
||||
|
||||
def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort():
|
||||
@@ -442,6 +443,25 @@ def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(me
|
||||
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
|
||||
|
||||
|
||||
def test_the_live_figure_fits_its_curves_to_the_members_deaths_and_takes_the_published_points(members_frame, production_model):
|
||||
"""Pins down: the Weibull curves of a scenario's figure follow its members' own deaths (close to their Kaplan-Meier, as the
|
||||
pipeline's survival stage fits a subgroup), and the points are the ones the version published for the subgroup when it did.
|
||||
Fails if the curves are fitted to the model's prediction instead of the data, or the published points are ignored."""
|
||||
from models.cama.survival import live
|
||||
|
||||
rows = [{"modelo": m, "meses": h, "S": 0.8, "IC_inf": 0.7, "IC_sup": 0.9, "subgrupo": "Toda la cohorte"}
|
||||
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
|
||||
published = live.published_points(rows, "Toda la cohorte")
|
||||
|
||||
record = live.curves(SCENARIO, production_model, members_frame, None, published)
|
||||
|
||||
km, weibull = np.asarray(record["km"]["S"]), np.asarray(record["weibull"]["S"])
|
||||
at_months = np.interp(np.arange(len(km)), record["weibull"]["t"], weibull)
|
||||
assert np.abs(at_months - km).max() < 0.05
|
||||
assert record["points"]["COMB"] == {"S": [0.8] * 3, "low": [0.7] * 3, "high": [0.9] * 3}
|
||||
assert live.published_points(rows, "Otro") is None
|
||||
|
||||
|
||||
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
|
||||
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
|
||||
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
|
||||
@@ -513,3 +533,29 @@ def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(m
|
||||
|
||||
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
|
||||
assert again[name] == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_the_members_carry_their_stage_and_treatments_and_the_scenarios_read_them():
|
||||
"""Pins down: a member's stage is the one reported with her diagnosis and her surgery, radiotherapy and chemotherapy are
|
||||
those of the year after it, and the clinical scenarios that need a stage or a conservative surgery find her. Fails if
|
||||
`member_table` stops reading them or `live.scenario_masks` goes back to age and subtype only."""
|
||||
from models.cama.survival import estimator, live
|
||||
|
||||
rows = []
|
||||
for pac, (stage, surgery, her2) in enumerate([("EI", "SEGMENTECTOMIA", "H0"), ("EIV", "MASTECTOMIA_TOTAL", "H3")], start=1):
|
||||
rows += [
|
||||
{"pac_id": pac, "tipo": "nacimiento", "fecha": "1950-01-01", "valor_codigo": None, "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "biopsia", "fecha": "2025-01-10", "valor_codigo": "CARCINOMA_INVASOR", "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "estadio_clinico", "fecha": "2025-01-10", "valor_codigo": stage, "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "her2", "fecha": "2025-01-10", "valor_codigo": her2, "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "receptor_estrogeno", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "receptor_progesterona", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
|
||||
{"pac_id": pac, "tipo": "cirugia", "fecha": "2025-03-01", "valor_codigo": surgery, "valor_numerico": None},
|
||||
]
|
||||
rows.append({"pac_id": 1, "tipo": "radioterapia", "fecha": "2025-05-01", "valor_codigo": "ADYUVANTE", "valor_numerico": None})
|
||||
cohort = pd.DataFrame(rows).assign(fecha_indice="2025-01-10", fuente_id="x")
|
||||
members = estimator.member_table(cohort, [45, 60, 75], [14, 20], 30)
|
||||
assert members.loc[1, ["stage", "surgery", "radiotherapy", "chemotherapy"]].tolist() == ["I", "Cirugía conservadora", "Sí", "No"]
|
||||
assert members.loc[2, ["stage", "surgery", "radiotherapy"]].tolist() == ["IV", "Mastectomía", "No"]
|
||||
masks = live.scenario_masks(members.reset_index())
|
||||
assert masks["Estadio I"].tolist() == [True, False] and masks["Estadio IV"].tolist() == [False, True]
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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-<time>-<fingerprint>` version, unvalidated, over the 60 children with a
|
||||
valid EEG and an ADOS-2, with the metric codes, `CSS` outcomes and an `>=8` event, and finds the planted
|
||||
spindle effect in central. Fails if the cohort takes the child without ADOS-2 or the invalid EEG, the
|
||||
biomarker codes stop following `model.toml`, or the written estimates stop being the library's."""
|
||||
summary = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
models, patients = _read()
|
||||
assert summary.children == 60 and summary.level == "domain"
|
||||
assert summary.version.startswith("tea-20261121T120000-") and len(summary.version) <= 32
|
||||
assert {m.rel_version for m in models} == {summary.version} and len(models) == summary.associations
|
||||
assert {m.rel_validado for m in models} == {0} and {m.rel_n_cohorte for m in models} == {60}
|
||||
assert {m.rel_resultado for m in models} == {"CSS"} and {m.rel_evento for m in models} == {">=8"}
|
||||
assert {m.rel_biomarcador for m in models} <= set(CODES.values())
|
||||
central = next(m for m in models if m.rel_biomarcador == "HUSOS_SUENO_N2" and m.rel_zona == "central")
|
||||
assert central.rel_or < 1 and central.rel_q < .05
|
||||
assert len(patients) == summary.scored
|
||||
|
||||
|
||||
def test_every_valid_eeg_of_the_cohort_is_scored_and_no_other(stored):
|
||||
"""Pins down: child 1's later valid EEG gets probabilities too (the gold view shows the study's EEG, whichever
|
||||
it is), while the invalid EEG and the EEG of the child without ADOS-2 get none. Fails if scoring stops at the
|
||||
fit's EEGs or starts scoring outside the cohort."""
|
||||
rel.relate()
|
||||
_, patients = _read()
|
||||
eegs = {p.rap_eeg_id for p in patients}
|
||||
assert {"e-000", "e-000-b"} <= eegs
|
||||
assert not {"e-001-x", "e-099"} & eegs
|
||||
assert all(0 <= p.rap_probabilidad <= 1 and 0 <= p.rap_probabilidad_referencia <= 1 for p in patients)
|
||||
|
||||
|
||||
def test_the_same_cohort_writes_nothing_and_a_new_one_is_a_later_version(stored):
|
||||
"""Pins down: fitting the same cohort again writes nothing and names the latest version; a changed z is a new
|
||||
version that sorts after the first, so the gold view's greatest version is the newest fit. Fails if reruns
|
||||
duplicate versions, or the version stops sorting by time."""
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
again = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert again.unchanged and again.version == first.version
|
||||
assert len({m.rel_version for m in _read()[0]}) == 1
|
||||
with Session(_engine()) as s:
|
||||
zone = s.get(EegMetricaZona, "e-000/HUSOS_SUENO_N2/central")
|
||||
zone.mez_z = 3.0
|
||||
s.add(zone)
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 23, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
assert {m.rel_version for m in _read()[0]} == {first.version, later.version}
|
||||
|
||||
|
||||
def test_an_open_interval_is_stored_as_null():
|
||||
"""Pins down: an infinite interval limit (the profile never crossed the threshold) is stored as NULL, which every
|
||||
engine accepts. Fails if `inf` reaches the database (MySQL and SQL Server reject it)."""
|
||||
assert rel._finite(float("inf")) is None and rel._finite(None) is None and rel._finite(2.5) == 2.5
|
||||
|
||||
|
||||
def test_the_fit_uses_the_first_eeg_with_predictors_and_a_new_eeg_is_a_new_version(stored):
|
||||
"""Pins down: a child whose earliest valid EEG has no metric rows is fitted on its next EEG, and a valid EEG
|
||||
added for a child already in the fit (so the fit table is the same) is still a new version that scores it.
|
||||
Fails if the fit takes an EEG without predictors (the child would drop out of every model), or the fingerprint
|
||||
covers only the fit table (the new EEG would stay unscored)."""
|
||||
with Session(_engine()) as s:
|
||||
s.add(Eeg(eeg_id="e-000-a", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 1, 1), eeg_valido=1,
|
||||
eeg_edad_meses=20.0))
|
||||
s.commit()
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
assert first.children == 60
|
||||
assert "e-000-a" not in {p.rap_eeg_id for p in _read()[1]}
|
||||
with Session(_engine()) as s:
|
||||
_eeg(s, "e-000-c", 1, stored.iloc[0], studied=date(2025, 12, 1))
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
models, patients = _read()
|
||||
latest = {m.rel_id for m in models if m.rel_version == later.version}
|
||||
assert "e-000-c" in {p.rap_eeg_id for p in patients if p.rap_rel_id in latest}
|
||||
@@ -0,0 +1,104 @@
|
||||
"""What this module covers: the ADOS-2 totals, CSS and classification of `tea.scoring`, and the job that writes
|
||||
them to the TEA database (`models.ados2_scoring`).
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, a child born 2022-01-01 with three Module 3 evaluations
|
||||
(items summing to 12, no CSS), one Module 1 evaluation (some words, items summing to 6) and one evaluation that
|
||||
already carries a CSS of 9 and a classification from its source.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from core.tea.models import Ados2, Pacientes
|
||||
from models import ados2_scoring
|
||||
from tea.scoring import score
|
||||
|
||||
ITEMS_12 = {"sa_b1": 2, "sa_b2": 2, "sa_b3": 2, "sa_b4": 2, "rrb_d1": 2, "rrb_d2": 2}
|
||||
|
||||
|
||||
def test_a_score_of_three_counts_as_two():
|
||||
"""Pins down: item scores above 2 are capped at 2, as the algorithms do. Fails if the cap is dropped (the
|
||||
total would be 8, not 4)."""
|
||||
s = score("MODULO_3", {"sa_b1": 3, "sa_b2": 3, "rrb_d1": 3, "rrb_d2": 3})
|
||||
assert (s.social_affect, s.restricted_repetitive, s.total) == (4, 4, 8)
|
||||
|
||||
|
||||
def test_the_css_rises_with_the_total_and_the_classification_follows_it():
|
||||
"""Pins down: for one module a higher total never gives a lower CSS, and the classification is no-spectrum
|
||||
under CSS 3, spectrum from 3 and autism from 5. Fails if a cut-point row stops being ordered or the
|
||||
classification thresholds move."""
|
||||
codes = [f"sa_b{i}" for i in range(1, 13)] + ["rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5"]
|
||||
scores = [score("MODULO_3", {c: 2 if i < n else 0 for i, c in enumerate(codes)}) for n in range(0, 17)]
|
||||
css = [s.css for s in scores]
|
||||
assert css == sorted(css) and css[0] == 1 and css[-1] == 10
|
||||
assert [scores[0].classification, scores[3].classification, scores[8].classification] == [
|
||||
"NO_ESPECTRO", "ESPECTRO_AUTISTA", "AUTISMO"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module, age, algorithm, expected", [
|
||||
("MODULO_1", None, "Algunas palabras", None),
|
||||
("MODULO_1", 40.0, None, None),
|
||||
("MODULO_2", None, None, None),
|
||||
("MODULO_3", None, None, 7),
|
||||
])
|
||||
def test_a_table_that_needs_age_or_language_level_gives_no_css_without_them(module, age, algorithm, expected):
|
||||
"""Pins down: Modules 1 and 2 give no CSS without the child's age (and Module 1 without its algorithm), Module 3
|
||||
needs neither. Fails if a missing age silently picks a table."""
|
||||
assert score(module, ITEMS_12, age_months=age, algorithm=algorithm).css == expected
|
||||
|
||||
|
||||
def test_the_toddler_module_gives_a_range_of_concern_and_no_css():
|
||||
"""Pins down: Toddler totals become a classification by age band and never a CSS: a total of 12 is mild to
|
||||
moderate at 25 months and at 19, 9 is none at 19 but mild to moderate at 25. Fails if Toddler starts
|
||||
returning a CSS or the two age bands share cut points."""
|
||||
t12 = {**{f"sa_b{i}": 2 for i in (1, 4, 5, 6)}, "rrb_d1": 2, "rrb_d2": 2}
|
||||
t9 = {**{f"sa_b{i}": 2 for i in (1, 4, 5)}, "rrb_d1": 2, "rrb_d2": 1}
|
||||
assert [score("TODDLER", t12, age_months=m).classification for m in (19, 25)] == ["PREOCUPACION_LEVE_MODERADA"] * 2
|
||||
assert [score("TODDLER", t9, age_months=m).classification for m in (19, 25)] == [
|
||||
"NO_ESPECTRO", "PREOCUPACION_LEVE_MODERADA"]
|
||||
assert score("TODDLER", t12, age_months=25).css is None
|
||||
|
||||
|
||||
def test_an_unknown_module_or_missing_domain_is_not_scored():
|
||||
"""Pins down: no score without a known module or without items in both domains. Fails if a half-read PDF is
|
||||
scored from one domain."""
|
||||
assert score(None, ITEMS_12) is None
|
||||
assert score("MODULO_9", ITEMS_12) is None
|
||||
assert score("MODULO_3", {"sa_b1": 2}) is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stored(tea_db):
|
||||
"""Child 1 (born 2022-01-01) with the evaluations the module docstring lists."""
|
||||
from persistance.db import get_tea_engine
|
||||
|
||||
with Session(get_tea_engine()) as s:
|
||||
s.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2022, 1, 1)))
|
||||
for i in (1, 2, 3):
|
||||
s.add(Ados2(ado_id=f"a-{i}", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3",
|
||||
**{f"ado_{k}": v for k, v in ITEMS_12.items()}))
|
||||
s.add(Ados2(ado_id="m1", ado_pac_id=1, ado_fecha=date(2025, 1, 1), ado_modulo="MODULO_1",
|
||||
ado_algoritmo="Algunas palabras", ado_sa_a2=2, ado_sa_b1=2, ado_sa_b3=1, ado_rrb_d1=1))
|
||||
s.add(Ados2(ado_id="given", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3", ado_css=9,
|
||||
ado_clasificacion="AUTISMO", **{f"ado_{k}": v for k, v in ITEMS_12.items()}))
|
||||
s.commit()
|
||||
yield s
|
||||
|
||||
|
||||
def test_the_job_fills_what_is_empty_and_keeps_what_a_source_gave(stored):
|
||||
"""Pins down: `score_all` writes CSS and classification on evaluations that lack them, uses the age at the
|
||||
evaluation (3 years for the Module 1 one, so the under-five table) and leaves a stored CSS alone. Fails if it
|
||||
overwrites a source's value by default or reads the wrong age."""
|
||||
summary = ados2_scoring.score_all(stored)
|
||||
assert (summary.evaluations, summary.scored) == (5, 4)
|
||||
rows = {r.ado_id: r for r in stored.exec(select(Ados2)).all()}
|
||||
assert rows["a-1"].ado_css == 7 and rows["a-1"].ado_clasificacion == "AUTISMO"
|
||||
assert rows["m1"].ado_css == 3 and rows["m1"].ado_clasificacion == "ESPECTRO_AUTISTA"
|
||||
assert rows["given"].ado_css == 9
|
||||
|
||||
|
||||
def test_overwrite_recomputes_what_a_source_gave(stored):
|
||||
"""Pins down: with `overwrite` the stored CSS is recomputed from the items. Fails if `overwrite` is ignored."""
|
||||
ados2_scoring.score_all(stored, overwrite=True)
|
||||
assert stored.get(Ados2, "given").ado_css == 7
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Outside markers for centile and age-block references in modern and legacy tea.
|
||||
|
||||
Fixtures: parameterized baseline modules and in-memory synthetic control values.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles import _baseline as modern
|
||||
from tea.legacy.biomarkers.spindles import _baseline as legacy
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_centile_outside_requires_a_reference(baseline):
|
||||
"""Pin float -1/0/+1 and missing values. Fails if missing data, uncovered ages or sparse controls give zero."""
|
||||
curve = baseline.CentileCurves().fit(np.tile([1, 2, 3], 50), np.repeat([12, 24, 36], 50))
|
||||
outside, _ = curve.deviation([0, 2, 4, np.nan, 2, 2], [24, 24, 24, 24, 60, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan, np.nan])
|
||||
sparse = baseline.CentileCurves().fit([1, 2], [12, 36])
|
||||
assert np.isnan(sparse.deviation([2], [24])[0][0])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_age_block_outside_requires_a_z_score(baseline):
|
||||
"""Pin float markers with a valid score. Fails if a missing score or degenerate MAD is classified in range."""
|
||||
fitted = baseline.AgeBlockZ().fit(np.arange(30), np.full(30, 24))
|
||||
outside, _ = fitted.deviation([-2, 15, 40, np.nan, 15], [24, 24, 24, 24, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan])
|
||||
flat = baseline.AgeBlockZ().fit(np.ones(30), np.full(30, 24))
|
||||
assert np.isnan(flat.deviation([1], [24])[0][0])
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Cover cluster probes using clean_environment, loopback_port and monkeypatch.
|
||||
|
||||
Fails if mode resolution, connection handling or independent probe results regress.
|
||||
"""
|
||||
|
||||
import socket
|
||||
from contextlib import nullcontext
|
||||
from time import perf_counter
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import distributed
|
||||
import pytest
|
||||
|
||||
from tea.pipeline import cluster_status
|
||||
from tea.pipeline.cluster_status import ClusterStatus
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_environment(monkeypatch):
|
||||
"""Clear cluster configuration so machine settings cannot change probe targets or results."""
|
||||
for variable in (
|
||||
"DASK_SCHEDULER_ADDRESS",
|
||||
"TEA_DASK_EXPECTED_WORKERS",
|
||||
"TEA_DASK_DASHBOARD_URL",
|
||||
"TEA_DASK_DASHBOARD_PORT",
|
||||
):
|
||||
monkeypatch.delenv(variable, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def loopback_port():
|
||||
"""Reserve a loopback port so live probes cannot connect to another service."""
|
||||
try:
|
||||
port = socket.socket()
|
||||
except PermissionError as exc:
|
||||
pytest.skip(f"TCP sockets are unavailable: {exc}")
|
||||
with port:
|
||||
try:
|
||||
port.bind(("127.0.0.1", 0))
|
||||
except PermissionError as exc:
|
||||
pytest.skip(f"Loopback binding is unavailable: {exc}")
|
||||
yield port.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["auto", "local", "sync"])
|
||||
def test_non_remote_mode_does_not_connect(monkeypatch, mode):
|
||||
"""Pin the full non-remote response. Fail if a client starts or a probe reports a value."""
|
||||
client = Mock()
|
||||
monkeypatch.setattr(distributed, "Client", client)
|
||||
if mode != "auto":
|
||||
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
|
||||
|
||||
assert ClusterStatus().check(mode) == {
|
||||
"mode": "local" if mode == "auto" else mode,
|
||||
"scheduler": None,
|
||||
"reachable": True,
|
||||
"workers": None,
|
||||
"expected_workers": None,
|
||||
"versions_ok": None,
|
||||
"version_error": None,
|
||||
"dashboard_ok": None,
|
||||
"dashboard_url": None,
|
||||
"reference": None,
|
||||
"latency_ms": None,
|
||||
"error": None,
|
||||
}
|
||||
client.assert_not_called()
|
||||
|
||||
|
||||
def test_unreachable_scheduler_is_bounded(monkeypatch, loopback_port):
|
||||
"""Pin failure on a closed TCP port. Fail if it raises or ignores the connection timeout."""
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_PORT", str(loopback_port))
|
||||
start = perf_counter()
|
||||
status = ClusterStatus().check(scheduler=f"tcp://127.0.0.1:{loopback_port}")
|
||||
|
||||
assert perf_counter() - start < 9
|
||||
assert status["mode"] == "remote"
|
||||
assert status["reachable"] is False
|
||||
assert status["error"]
|
||||
assert status["workers"] is None
|
||||
assert status["versions_ok"] is None
|
||||
assert status["dashboard_ok"] is False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("loopback_port")
|
||||
def test_reachable_scheduler_reports_one_worker(monkeypatch):
|
||||
"""Pin health on a real Dask worker. Fail if the client miscounts it or skips version checks."""
|
||||
with distributed.LocalCluster(
|
||||
n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0"
|
||||
) as cluster:
|
||||
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", cluster.scheduler_address)
|
||||
monkeypatch.setenv("TEA_DASK_EXPECTED_WORKERS", "2")
|
||||
port = cluster.scheduler.services["dashboard"].port
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", f"http://127.0.0.1:{port}/status")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
|
||||
status = ClusterStatus().check()
|
||||
|
||||
assert status["scheduler"] == cluster.scheduler_address
|
||||
assert status["reachable"] is True
|
||||
assert status["workers"] == 1
|
||||
assert status["expected_workers"] == 2
|
||||
assert status["versions_ok"] is True
|
||||
assert status["dashboard_ok"] is True
|
||||
assert status["latency_ms"] >= 0
|
||||
assert status["error"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dashboard_healthy", [True, False])
|
||||
def test_version_mismatch_and_dashboard_are_independent(monkeypatch, dashboard_healthy):
|
||||
"""Pin zero-worker and mismatch responses. Fail if either prevents an independent dashboard probe."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {}}
|
||||
client.get_versions.side_effect = ValueError("version mismatch")
|
||||
connect = Mock(return_value=client)
|
||||
monkeypatch.setattr(distributed, "Client", connect)
|
||||
if dashboard_healthy:
|
||||
dashboard_url = "https://dashboard.example/status?view=all"
|
||||
health_url = "https://dashboard.example/health"
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", dashboard_url)
|
||||
open_health = Mock(return_value=nullcontext(SimpleNamespace(status=200)))
|
||||
else:
|
||||
dashboard_url = "http://scheduler:8787/status"
|
||||
health_url = "http://scheduler:8787/health"
|
||||
open_health = Mock(side_effect=TimeoutError)
|
||||
monkeypatch.setattr(cluster_status, "urlopen", open_health)
|
||||
|
||||
status = ClusterStatus().check("remote", "tcp://scheduler:8786", "cohort")
|
||||
|
||||
assert status["reachable"] is True
|
||||
assert status["error"] is None
|
||||
assert status["workers"] == 0
|
||||
assert status["versions_ok"] is False
|
||||
assert status["version_error"] == "version mismatch"
|
||||
assert status["dashboard_ok"] is dashboard_healthy
|
||||
assert status["dashboard_url"] == dashboard_url
|
||||
assert status["reference"] is None
|
||||
connect.assert_called_once_with("tcp://scheduler:8786", timeout=5)
|
||||
client.get_versions.assert_called_once_with(check=True)
|
||||
client.submit.assert_not_called()
|
||||
client.close.assert_called_once_with()
|
||||
open_health.assert_called_once_with(health_url, timeout=3)
|
||||
|
||||
|
||||
def test_warning_only_version_mismatch_is_reported(monkeypatch):
|
||||
"""Pin mismatches returned by Dask without an exception. Fail if they count as compatible."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||
matching = {"packages": {"distributed": "2026.8.0"}}
|
||||
client.get_versions.return_value = {
|
||||
"scheduler": matching,
|
||||
"client": matching,
|
||||
"workers": {"worker": {"packages": {"distributed": "2026.9.0"}}},
|
||||
}
|
||||
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||
|
||||
status = ClusterStatus().check(scheduler="tcp://scheduler:8786")
|
||||
|
||||
assert status["versions_ok"] is False
|
||||
assert "Mismatched versions found" in status["version_error"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["cohort-1", "../escape", ".."])
|
||||
def test_reference_submission_requires_safe_name(monkeypatch, name):
|
||||
"""Pin worker-side reference lookup. Fail if an unsafe name is submitted or a valid count is lost."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||
client.submit.return_value.result.return_value = 3
|
||||
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||
|
||||
status = ClusterStatus().check(scheduler="tcp://scheduler:8786", reference_name=name)
|
||||
|
||||
if name == "cohort-1":
|
||||
client.submit.assert_called_once_with(cluster_status._count_edfs, name, pure=False)
|
||||
assert status["reference"] == {"name": name, "edfs": 3}
|
||||
else:
|
||||
client.submit.assert_not_called()
|
||||
assert status["reference"] is None
|
||||
|
||||
|
||||
def test_local_workers_can_be_capped_by_the_environment(monkeypatch):
|
||||
"""Pins down: `TEA_LOCAL_WORKERS` fixes the size of a local cluster, an explicit count still wins, and a value
|
||||
below one means one worker.
|
||||
|
||||
Fails if a local run on a shared machine can no longer be limited from the environment.
|
||||
"""
|
||||
from tea.pipeline.dask_runner import local_workers
|
||||
|
||||
monkeypatch.setenv("TEA_LOCAL_WORKERS", "1")
|
||||
assert local_workers() == 1
|
||||
monkeypatch.setenv("TEA_LOCAL_WORKERS", "0")
|
||||
assert local_workers() == 1
|
||||
assert local_workers(n_workers=3) == 3
|
||||
@@ -1,9 +1,10 @@
|
||||
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
|
||||
library.
|
||||
library, plus EEG selection and the CLI summary. Fails if explicit selection skips current studies or the CLI
|
||||
stops reporting its final counts.
|
||||
|
||||
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
|
||||
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
|
||||
posterior channels flat; and bytes that are not an EDF.
|
||||
posterior channels flat; and bytes that are not an EDF. `selection_session` holds three EEG rows in SQLite.
|
||||
"""
|
||||
import pytest
|
||||
from synth_edf import edf_bytes
|
||||
@@ -18,7 +19,7 @@ FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured():
|
||||
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
|
||||
"""Measure clean, flat, and broken studies to expose changes in triage and metrics."""
|
||||
s = settings()
|
||||
return {
|
||||
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
|
||||
@@ -115,3 +116,77 @@ def test_channel_codes_lose_their_numbers():
|
||||
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
|
||||
"intermittent-bursts"
|
||||
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def selection_session():
|
||||
"""Store current, pending, and EDF-less EEGs to expose scope regressions."""
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from core.tea.models import Eeg
|
||||
|
||||
engine = create_engine("sqlite://")
|
||||
Eeg.__table__.create(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
Eeg(eeg_id="1", eeg_estudio=b"edf", eeg_plan_hash="current", eeg_versiones="current", eeg_valido=0),
|
||||
Eeg(eeg_id="2"),
|
||||
Eeg(eeg_id="3", eeg_estudio=b"edf"),
|
||||
])
|
||||
session.commit()
|
||||
yield session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_explicit_ids_select_current_edfs(selection_session):
|
||||
"""Pin explicit reanalysis. Fail if current EEGs are skipped or EDF-less and unrequested rows are selected."""
|
||||
from models.eeg_analysis import pending_ids
|
||||
|
||||
options = {"plan_hash": "current", "versions": "current", "models": dict}
|
||||
assert pending_ids(selection_session, **options) == ["3"]
|
||||
assert pending_ids(selection_session, ids=[2, 1, 1], **options) == ["1"]
|
||||
with pytest.raises(LookupError, match=r"8, 9"):
|
||||
pending_ids(selection_session, ids=[1, 9, 8], **options)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failed", [0, 1])
|
||||
def test_analyze_cli_emits_summary_and_passes_ids(monkeypatch, capsys, failed):
|
||||
"""Pin the final JSON line and failure status. Fail if explicit IDs or the failed count are ignored."""
|
||||
import json
|
||||
|
||||
from models import eeg_analysis
|
||||
from models.__main__ import main
|
||||
|
||||
def analyze(**options):
|
||||
assert options == {"everything": False, "limit": None, "ids": ["1", "2"], "cluster": "sync"}
|
||||
return eeg_analysis.Summary(pending=2, valid=1, not_valid=1 - failed, failed=failed)
|
||||
|
||||
monkeypatch.setattr(eeg_analysis, "analyze_pending", analyze)
|
||||
assert main(["tea", "analyze", "--ids", "1,2", "--cluster", "sync"]) == failed
|
||||
line = capsys.readouterr().out.splitlines()[-1]
|
||||
assert line.startswith("summary: ")
|
||||
assert json.loads(line.removeprefix("summary: ")) == {
|
||||
"pending": 2, "valid": 1, "not_valid": 1 - failed, "failed": failed,
|
||||
}
|
||||
|
||||
|
||||
def test_explicit_ids_may_be_uuids(selection_session):
|
||||
"""Pin that ids are matched as strings, so the UUID ids real EEGs carry select their rows. Fail if ids go back
|
||||
to being parsed as integers."""
|
||||
from core.tea.models import Eeg
|
||||
from models.eeg_analysis import selected_ids
|
||||
|
||||
uuid = "ed257fbd-61d5-4c9c-bb72-00c4ec550961"
|
||||
selection_session.add(Eeg(eeg_id=uuid, eeg_estudio=b"EDF"))
|
||||
selection_session.commit()
|
||||
assert selected_ids(selection_session, [uuid]) == [uuid]
|
||||
with pytest.raises(LookupError, match="no-such-id"):
|
||||
selected_ids(selection_session, [uuid, "no-such-id"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("other", [["--all"], ["--limit", "2"]])
|
||||
def test_analyze_cli_rejects_conflicting_scope(other):
|
||||
"""Pin exit 2 for ambiguous scopes. Fail if an explicit ID request can start with another scope."""
|
||||
from models.__main__ import main
|
||||
|
||||
assert main(["tea", "analyze", "--ids", "1", *other]) == 2
|
||||
|
||||
@@ -144,7 +144,34 @@ def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves)
|
||||
(1, "tea-eeg-posterior-rhythm/3")
|
||||
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
|
||||
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"))
|
||||
mapped = [m.code for m in settings().metrics if m.electrodes]
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in mapped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ("uncovered_age", "missing_cutoffs"))
|
||||
def test_missing_reference_stores_null_outside(bronze, curves, case):
|
||||
"""Pin SQL NULL when a reference interval is absent. Fails if a missing marker is cast to int or stored as zero."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
age = 60.0
|
||||
if case == "missing_cutoffs":
|
||||
from tea.biomarkers.posterior_rhythm._baseline import AgeBlockZ
|
||||
|
||||
age = 26.0
|
||||
reference = AgeBlockZ().fit([5.0, 6.0, 7.0], [age] * 3)
|
||||
reference.state["cortes"] = [float("nan")] * 2
|
||||
curves.module("eeg-posterior-rhythm").baseline = reference
|
||||
|
||||
measurement = fake_measure("e-1", b"edf", age, settings())
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(measurement, settings(), curves))
|
||||
session.commit()
|
||||
metric = next(row for row in _all(EegMetrica) if row.met_codigo == "RITMO_POSTERIOR")
|
||||
assert metric.met_valor == 9.0
|
||||
assert metric.met_modelo == "tea-eeg-posterior-rhythm/3"
|
||||
assert metric.met_fuera is None
|
||||
if case == "missing_cutoffs":
|
||||
assert metric.met_z == pytest.approx(3.0 / 1.4826)
|
||||
|
||||
|
||||
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
|
||||
|
||||
@@ -184,3 +184,20 @@ def test_a_reference_study_is_measured_from_its_path(tmp_path):
|
||||
assert (st.valid, st.error) == (1, None)
|
||||
assert set(st.features) == set(settings().scenarios.values())
|
||||
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
|
||||
|
||||
|
||||
def test_training_reads_the_cluster_choice_from_the_environment(monkeypatch):
|
||||
"""Pins down: training measures its studies on the runner `EEG_ANALYSIS_CLUSTER` names, and falls back to `auto`
|
||||
for an unset or unknown value (including `off`, which only the analysis understands).
|
||||
|
||||
Fails if `run_steps` stops passing the choice to `train_all`, or lets an unknown value reach the runner.
|
||||
"""
|
||||
from models.tea.eeg import model
|
||||
|
||||
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
|
||||
assert model._cluster() == "auto"
|
||||
for chosen in ("auto", "local", "remote", "sync"):
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", chosen)
|
||||
assert model._cluster() == chosen
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "off")
|
||||
assert model._cluster() == "auto"
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""What this module covers: the zone values of the EEG analysis (`models.tea.eeg.settings` zones,
|
||||
`analyze._metrics`, `models.eeg_analysis.rows` and `save`): which metrics read zones, how a biomarker's
|
||||
`<zone_prefix><zone>` features become a metric's zones, and the `eeg_metrica_zona` rows with the z of the zone's
|
||||
baseline, replaced on the next analysis.
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `spike_zones`, `Baselines` whose only production version is
|
||||
`tea-eeg-spikes/2`, a spikes module with one centile curve, 0.5/1/2 spikes per minute at p5/median/p95 at every age,
|
||||
for `spike_zone_rate_nrem_temporal_izq` alone.
|
||||
"""
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from core.tea.models import Eeg, EegMetrica, EegMetricaZona, Pacientes
|
||||
from models.eeg_analysis import rows, save
|
||||
from models.tea.eeg.analyze import Measurement, MetricValue, _metrics
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import settings
|
||||
from tea.contracts import ZONES
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def spike_zones():
|
||||
"""Spikes in production with a curve for the temporal_izq zone feature only."""
|
||||
from tea.biomarkers.spikes._baseline import CentileCurves
|
||||
|
||||
curve = pd.DataFrame({"edad_meses": [12.0, 36.0], "n_efectivo": [50.0] * 2, "p5": [0.5] * 2, "p25": [0.8] * 2,
|
||||
"mediana": [1.0] * 2, "p75": [1.4] * 2, "p95": [2.0] * 2})
|
||||
module = SimpleNamespace(baselines={"spike_zone_rate_nrem_temporal_izq": CentileCurves(curva=curve)})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="2", model_uri="models:/tea-eeg-spikes/2")
|
||||
|
||||
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
|
||||
|
||||
|
||||
def test_spikes_and_spindles_read_zones_and_their_scenarios_are_trained():
|
||||
"""Pins down: the spike metric reads `spike_zone_rate_nrem_<zone>` and the per-electrode `spike_density_nrem_<E>`
|
||||
from spikes with `spike_minutes_nrem` as exposure, both spindle metrics read `spindle_zone_<zone>` from spindles
|
||||
at their stage, and no scenario is added for them (the zone features train with the metric's own biomarker).
|
||||
Fails if `model.toml` loses the zones the ADOS-2 association reads, or zones start a scenario of their own."""
|
||||
s = settings()
|
||||
by_code = {m.code: m for m in s.metrics}
|
||||
spikes = by_code["PICOS_PAROXISTICOS"]
|
||||
assert (spikes.zones, spikes.zone_prefix, spikes.electrodes, spikes.electrode_prefix) == (
|
||||
"spikes", "spike_zone_rate_nrem_", "spikes", "spike_density_nrem_")
|
||||
assert spikes.exposure == "spike_minutes_nrem"
|
||||
assert spikes.zone_scenario == spikes.scenario == "eeg-spikes"
|
||||
for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"):
|
||||
assert (by_code[code].zones, by_code[code].zone_prefix) == ("spindles", "spindle_zone_")
|
||||
assert set(s.scenarios) == {"eeg-posterior-rhythm", "eeg-spindles-n2", "eeg-spindles-n3",
|
||||
"eeg-spindle-topography-n2", "eeg-spindle-topography-n3", "eeg-spikes",
|
||||
"eeg-gradient"}
|
||||
|
||||
|
||||
def test_a_biomarkers_zone_features_become_the_metrics_zones():
|
||||
"""Pins down: the features named `<zone_prefix><zone>` are the metric's zones by zone code, the electrode map
|
||||
keeps its own prefix, and a feature whose name only starts like the prefix's biomarker is left out. Fails if
|
||||
the prefix is not stripped or zone and electrode features mix."""
|
||||
s = settings()
|
||||
spikes = {"spike_rate_nrem": 0.7, "spike_density_nrem_T3": 1.2,
|
||||
**{f"spike_zone_rate_nrem_{z}": float(i) for i, z in enumerate(ZONES)},
|
||||
"spike_zone_rate_awake_central": 9.0, "spike_minutes_nrem": 12.5}
|
||||
measured = {("posterior_rhythm", None): {}, ("spindles", "N2"): {}, ("spindles", "N3"): {},
|
||||
("spindle_topography", "N2"): {}, ("spindle_topography", "N3"): {}, ("spikes", None): spikes,
|
||||
("gradient", None): {}}
|
||||
value = {v.code: v for v in _metrics(measured, s)}["PICOS_PAROXISTICOS"]
|
||||
assert value.value == 0.7
|
||||
assert value.electrodes == {"T3": 1.2}
|
||||
assert value.zones == {z: float(i) for i, z in enumerate(ZONES)}
|
||||
assert value.exposure == 12.5
|
||||
|
||||
|
||||
def test_zone_rows_carry_the_zone_baselines_z_and_are_replaced(tea_db, spike_zones):
|
||||
"""Pins down: each zone of a metric is an `eeg_metrica_zona` row of that metric, with the z of the zone's own
|
||||
curve where one is in production and null elsewhere, and a new analysis replaces them. Fails if zone rows are
|
||||
not written, read another feature's baseline, or pile up across analyses."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings()
|
||||
with eeg_repository.open_session() as session:
|
||||
session.add_all([Pacientes(pac_id=1), Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1))])
|
||||
session.commit()
|
||||
zones = {"temporal_izq": 2.0, "central": 1.0}
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, zones if x.code == "PICOS_PAROXISTICOS" else {})
|
||||
for x in s.metrics))
|
||||
for _ in range(2):
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(m, s, spike_zones))
|
||||
session.commit()
|
||||
with eeg_repository.open_session() as session:
|
||||
found = {z.mez_zona: z for z in session.exec(select(EegMetricaZona)).all()}
|
||||
met_id = session.exec(select(EegMetrica.met_id).where(EegMetrica.met_codigo == "PICOS_PAROXISTICOS")).one()
|
||||
assert set(found) == {"temporal_izq", "central"}
|
||||
assert {z.mez_met_id for z in found.values()} == {met_id}
|
||||
assert found["temporal_izq"].mez_z == pytest.approx(1.645) and found["temporal_izq"].mez_valor == 2.0
|
||||
assert found["central"].mez_z is None
|
||||
|
||||
|
||||
def test_a_count_baseline_gets_the_metrics_minutes(tea_db):
|
||||
"""Pins down: a baseline whose `deviation` takes `exposure` gets the metric's minutes for the value, every
|
||||
electrode and every zone, and one without that parameter is called as before. Fails if the minutes stop reaching
|
||||
count baselines (spike z would be computed against no exposure) or curves start receiving them."""
|
||||
import numpy as np
|
||||
|
||||
seen = []
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
seen.append(float(exposure[0]))
|
||||
return np.array([0.0]), np.array([1.0])
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count(), "spike_density_nrem_T3": Count(),
|
||||
"spike_zone_rate_nrem_central": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {"T3": 0.5}, {"central": 0.2}, 12.5)
|
||||
if x.code == "PICOS_PAROXISTICOS" else MetricValue(x.code, 1.0)
|
||||
for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
assert seen == [12.5, 12.5, 12.5]
|
||||
assert [z.mez_z for z in out.zones] == [1.0] and [e.mel_z for e in out.electrodes] == [1.0]
|
||||
|
||||
|
||||
def test_a_count_baselines_range_is_its_own_for_the_minutes(tea_db):
|
||||
"""Pins down: a baseline with `percentiles` gives the metric's p5, median and p95 from the metric's minutes, and
|
||||
the metric row stores them, so a spike metric with a z has a reference range. Fails if count baselines lose their
|
||||
range (the patient summary then refuses the EEG: a metric with a z and no reference)."""
|
||||
import numpy as np
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
return np.array([0.0]), np.array([0.5])
|
||||
|
||||
def percentiles(self, ages_months, exposure):
|
||||
return np.array([[0.0, 0.1, 0.4]]) * 10 / exposure[0]
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, {}, 20.0) if x.code == "PICOS_PAROXISTICOS"
|
||||
else MetricValue(x.code, 1.0) for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
spikes = next(r for r in out.metrics if r.met_codigo == "PICOS_PAROXISTICOS")
|
||||
assert (spikes.met_p5, spikes.met_mediana, spikes.met_p95) == (0.0, 0.05, 0.2)
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Cover optional, atomic progress reporting and ETA with temporary files and a fake clock.
|
||||
|
||||
Fails if monitoring changes unconfigured runs, publishes incomplete samples, or miscalculates throughput.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
from tea.pipeline import run_monitor
|
||||
|
||||
|
||||
def test_monitor_without_directory(monkeypatch):
|
||||
"""Pin the no-op monitor. Fail if an unconfigured run activates sampling."""
|
||||
monkeypatch.delenv("RUN_PROGRESS_DIR", raising=False)
|
||||
with run_monitor.monitor_from_env() as monitor:
|
||||
monitor.start()
|
||||
monitor.phase("analizando")
|
||||
monitor.total(12)
|
||||
monitor.advance()
|
||||
assert run_monitor.active_monitor() is None
|
||||
monitor.stop()
|
||||
|
||||
|
||||
def test_local_cluster_progress(tmp_path, monkeypatch):
|
||||
"""Pin live Dask telemetry and atomic snapshots. Fail if progress stalls, grows unbounded, or tears."""
|
||||
path = tmp_path / "progress.json"
|
||||
replace = run_monitor.os.replace
|
||||
replacements = []
|
||||
|
||||
def verify_replace(source, target):
|
||||
if target == path:
|
||||
assert json.loads(source.read_text())["history"]
|
||||
if path.exists():
|
||||
assert json.loads(path.read_text())["history"]
|
||||
replacements.append(source)
|
||||
replace(source, target)
|
||||
|
||||
def read_until(predicate):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
if path.exists():
|
||||
progress = json.loads(path.read_text())
|
||||
if predicate(progress):
|
||||
return progress
|
||||
time.sleep(0.01)
|
||||
pytest.fail("Timed out waiting for progress")
|
||||
|
||||
monkeypatch.setattr(run_monitor.os, "replace", verify_replace)
|
||||
with LocalCluster(n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0") as cluster:
|
||||
with Client(cluster) as client, run_monitor.RunMonitor(tmp_path, interval=0.1, history=4) as monitor:
|
||||
monitor.start(client, ("local", None))
|
||||
monitor.total(10)
|
||||
monitor.phase("midiendo")
|
||||
initial = read_until(lambda p: p["phase"] == "midiendo" and p["tasks"] and p["cluster"]["workers"])
|
||||
assert initial["done"] == 0 and initial["eta_s"] is None
|
||||
assert set(initial["tasks"]) == {"processing", "waiting", "memory", "erred"}
|
||||
assert initial["cluster"]["workers"][0]["threads"] == 1
|
||||
monitor.advance(3)
|
||||
measured = read_until(lambda p: p["done"] == 3 and len(p["history"]) == 4)
|
||||
assert measured["eta_s"] > 0
|
||||
monitor.advance(2)
|
||||
monitor.phase("ajustando")
|
||||
monitor.stop()
|
||||
|
||||
final = json.loads(path.read_text())
|
||||
assert final["done"] == 5 and final["eta_s"] is None
|
||||
assert final["phase"] == "ajustando"
|
||||
assert len(final["history"]) == 4
|
||||
assert final["history"][-1]["done"] == 5
|
||||
assert len(replacements) >= 5
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_eta_smoothed_rate(tmp_path, monkeypatch):
|
||||
"""Pin ETA arithmetic and its threshold. Fail if cumulative or instantaneous rate replaces smoothing."""
|
||||
now = 100.0
|
||||
monkeypatch.setattr(run_monitor, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(run_monitor.Thread, "start", lambda self: None)
|
||||
monkeypatch.setenv("RUN_PROGRESS_DIR", str(tmp_path))
|
||||
path = tmp_path / "progress.json"
|
||||
with run_monitor.monitor_from_env() as monitor:
|
||||
assert run_monitor.active_monitor() is monitor
|
||||
monitor.phase("analizando")
|
||||
monitor.total(20)
|
||||
monitor.advance(2)
|
||||
now += 2
|
||||
monitor._write_sample()
|
||||
first = json.loads(path.read_text())
|
||||
assert first["eta_s"] is None
|
||||
assert first["tasks"] is None and first["cluster"] is None
|
||||
monitor.advance(4)
|
||||
now += 2
|
||||
monitor._write_sample()
|
||||
assert json.loads(path.read_text())["eta_s"] == pytest.approx(14 / (0.3 * 2 + 0.7))
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
"""A stand-in for a Dask client with one busy worker, whose status the test can flip."""
|
||||
|
||||
status = "running"
|
||||
|
||||
def scheduler_info(self):
|
||||
return {"workers": {"tcp://w:1": {"name": "w", "nthreads": 1, "memory_limit": 1000,
|
||||
"metrics": {"cpu": 90.0, "memory": 500, "executing": 1}}}}
|
||||
|
||||
|
||||
def _wait_for(path, condition, seconds=5.0):
|
||||
"""The last snapshot at `path` once `condition(snapshot)` holds, or fail after `seconds`."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if path.exists():
|
||||
snapshot = json.loads(path.read_text())
|
||||
if condition(snapshot):
|
||||
return snapshot
|
||||
time.sleep(0.02)
|
||||
raise AssertionError(f"no snapshot matched: {path.read_text() if path.exists() else 'no file'}")
|
||||
|
||||
|
||||
def test_the_cluster_figures_clear_when_the_client_is_released(tmp_path):
|
||||
"""Pin that `release` drops the cluster and task figures from every later snapshot, including the final one.
|
||||
Fail if a finished run keeps reporting its last CPU, RAM and task counts as if the cluster were still busy."""
|
||||
path = tmp_path / "progress.json"
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
monitor.start(_FakeClient(), ("local", None))
|
||||
busy = _wait_for(path, lambda s: s["cluster"] and s["cluster"]["cpu_pct"] == 90.0)
|
||||
assert busy["cluster"]["workers"][0]["name"] == "w"
|
||||
monitor.release()
|
||||
cleared = _wait_for(path, lambda s: s["cluster"] is None)
|
||||
assert cleared["tasks"] is None
|
||||
monitor.stop()
|
||||
final = json.loads(path.read_text())
|
||||
assert final["cluster"] is None and final["tasks"] is None
|
||||
|
||||
|
||||
def test_the_cluster_figures_clear_when_the_sampler_sees_a_closed_client(tmp_path):
|
||||
"""Pin that a client closed without a `release` call still stops being reported on the next sample.
|
||||
Fail if the sampler goes on writing the last figures of a client whose status is closed."""
|
||||
path = tmp_path / "progress.json"
|
||||
client = _FakeClient()
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
monitor.start(client, ("remote", "tcp://s:1"))
|
||||
_wait_for(path, lambda s: s["cluster"] and s["cluster"]["scheduler"] == "tcp://s:1")
|
||||
client.status = "closed"
|
||||
_wait_for(path, lambda s: s["cluster"] is None and s["tasks"] is None)
|
||||
monitor.stop()
|
||||
|
||||
|
||||
def test_a_client_attached_later_is_reported_again(tmp_path):
|
||||
"""Pin that releasing one client does not stop the next one (a run opens a cluster per phase) from reporting.
|
||||
Fail if `release` leaves the monitor unable to take a new client."""
|
||||
path = tmp_path / "progress.json"
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
first = _FakeClient()
|
||||
monitor.start(first, ("local", None))
|
||||
_wait_for(path, lambda s: s["cluster"] is not None)
|
||||
monitor.release(first)
|
||||
_wait_for(path, lambda s: s["cluster"] is None)
|
||||
monitor.start(_FakeClient(), ("local", None))
|
||||
_wait_for(path, lambda s: s["cluster"] is not None and s["cluster"]["cpu_pct"] == 90.0)
|
||||
monitor.stop()
|
||||
@@ -0,0 +1,99 @@
|
||||
"""What this module covers: the spikes biomarker's baselines around the per-electrode and
|
||||
per-zone features: training from a feature table that predates them, and loading a baseline
|
||||
saved before they existed. Both implementations, modern and legacy.
|
||||
|
||||
Fixtures: `old_table`, a DataFrame with only the original seven study-wide spikes features and
|
||||
an age column, as a reference cohort measured before the density features existed; `full_table`,
|
||||
the same rows plus every current feature.
|
||||
"""
|
||||
import importlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
ORIGINAL = ("spike_rate_awake", "spike_rate_nrem", "spike_nrem_activation", "spike_focus_frac",
|
||||
"spike_laterality", "spike_frac_generalized", "spike_index_nrem")
|
||||
MODULES = (("tea.biomarkers.spikes.api", "Spikes"),
|
||||
("tea.legacy.biomarkers.spikes.api", "LegacySpikes"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def old_table():
|
||||
"""Twelve synthetic children with only the study-wide spikes features and their ages."""
|
||||
rng = np.random.default_rng(0)
|
||||
t = pd.DataFrame({f: rng.uniform(0.0, 2.0, size=12) for f in ORIGINAL})
|
||||
t["age_months"] = np.linspace(16.0, 36.0, 12)
|
||||
return t
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_table(old_table):
|
||||
"""`old_table` plus every per-electrode, per-zone and inherited feature the module has now."""
|
||||
rng = np.random.default_rng(1)
|
||||
t = old_table.copy()
|
||||
cls = getattr(importlib.import_module(MODULES[0][0]), MODULES[0][1])
|
||||
for f in cls.features:
|
||||
if f not in t.columns:
|
||||
t[f] = rng.uniform(0.0, 2.0, size=len(t))
|
||||
return t
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_training_skips_features_the_table_lacks(path, name, old_table, tmp_path):
|
||||
"""Pins down: training from a table without the new columns works, fits only the columns
|
||||
it has, and saving then loading that baseline keeps predicting those features only.
|
||||
|
||||
Fails if `train` starts requiring the new columns, or if save/load stops round-tripping
|
||||
a baseline that knows nothing about them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(old_table)
|
||||
out = module.predict(old_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
module.save(tmp_path)
|
||||
loaded = cls.load(tmp_path)
|
||||
assert set(loaded.predict(old_table).feature) == set(ORIGINAL)
|
||||
assert len(cls.features) > len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_baseline_saved_before_the_new_features_loads_and_predicts(path, name, old_table,
|
||||
full_table, tmp_path):
|
||||
"""Pins down: a baseline bundle written before the new features existed (no new
|
||||
parameters in params.json, none of the new features in baseline.json) loads into the
|
||||
current module and predicts; the new features simply have no baseline and are not
|
||||
evaluated.
|
||||
|
||||
Fails if load starts requiring the new parameters, if a saved baseline stops being
|
||||
readable after the feature list grows, or if predict evaluates a feature that has no
|
||||
fitted baseline.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
cls().train(old_table).save(tmp_path)
|
||||
params = json.loads((tmp_path / "params.json").read_text())
|
||||
for k in ("vent_s", "rechazar_transitorio", "herencia_s"):
|
||||
params.pop(k, None)
|
||||
(tmp_path / "params.json").write_text(json.dumps(params))
|
||||
loaded = cls.load(tmp_path)
|
||||
out = loaded.predict(full_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
assert len(out) == len(full_table) * len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_full_baseline_round_trips(path, name, full_table, tmp_path):
|
||||
"""Pins down: with every column present, train fits all features and save/load predicts
|
||||
the same deviations.
|
||||
|
||||
Fails if the per-electrode and per-zone features stop getting their own baselines when
|
||||
the training table has them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(full_table)
|
||||
before = module.predict(full_table)
|
||||
assert set(before.feature) == set(cls.features)
|
||||
module.save(tmp_path)
|
||||
after = cls.load(tmp_path).predict(full_table)
|
||||
pd.testing.assert_frame_equal(before, after)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""What this module covers: the count reference of spike candidates (`_baseline.CountRate` of both spikes modules)
|
||||
and how `Spikes` / `LegacySpikes` use it: the aggregate rate and its dispersion, a child's z from the tail of its
|
||||
own count in its own minutes, NaN without exposure, the per-electrode zone scale, and which features it serves.
|
||||
|
||||
Fixtures: `count_rate`, parametrized over the modern and legacy `CountRate` classes; `reference`, 200 invented
|
||||
children of 16 to 36 months with 5 to 15 clean NREM minutes and Poisson candidates at 0.02 per minute (most have
|
||||
none), as rates.
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from scipy import stats
|
||||
|
||||
from tea.biomarkers.spikes import _baseline as modern_baseline
|
||||
from tea.biomarkers.spikes import api as modern
|
||||
from tea.legacy.biomarkers.spikes import _baseline as legacy_baseline
|
||||
from tea.legacy.biomarkers.spikes import api as legacy
|
||||
|
||||
|
||||
@pytest.fixture(params=["modern", "legacy"])
|
||||
def count_rate(request):
|
||||
"""The implementation's `CountRate` class."""
|
||||
return {"modern": modern_baseline, "legacy": legacy_baseline}[request.param].CountRate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reference():
|
||||
"""(rates, ages, minutes) of 200 children with Poisson candidates at 0.02 per minute."""
|
||||
rng = np.random.default_rng(3)
|
||||
minutes = rng.uniform(5, 15, 200).round(2)
|
||||
counts = rng.poisson(0.02 * minutes)
|
||||
return counts / minutes, rng.uniform(16, 36, 200), minutes
|
||||
|
||||
|
||||
def test_the_reference_is_the_aggregate_rate_with_its_dispersion(count_rate):
|
||||
"""Pins down: the rate is all candidates over all minutes of the children within the ages (one child of 50
|
||||
months left out) and the dispersion is the research code's moments estimate, Poisson (inf) without excess.
|
||||
Fails if the rate becomes a mean of per-child rates, the age range stops filtering, or the moments change."""
|
||||
rates = np.array([0, 0.1, 0.2, 0])
|
||||
b = count_rate().fit(rates, np.array([20, 20, 30, 50.0]), exposure=np.array([10, 10, 20, 30.0]))
|
||||
assert b.state["rate"] == pytest.approx(5 / 40) and b.state["reference"] == 3 and b.state["events"] == 5
|
||||
n, mu = np.array([0, 1, 4]), 5 / 40 * np.array([10, 10, 20])
|
||||
excess = ((n - mu) ** 2 - n).sum()
|
||||
assert b.state["k"] == (pytest.approx((mu ** 2).sum() / excess) if excess > 0 else np.inf)
|
||||
flat = count_rate().fit(np.array([0.1, 0.1]), np.array([20, 20.0]), exposure=np.array([10, 10.0]))
|
||||
assert flat.state["k"] == np.inf
|
||||
|
||||
|
||||
def test_a_count_is_judged_in_its_own_minutes(count_rate, reference):
|
||||
"""Pins down: no candidates is a mildly negative z (never -inf), the same one candidate is rarer in fewer
|
||||
minutes, many candidates in few minutes are outside +1 with a large z, and z is the normal quantile of the mid-p
|
||||
tail. Fails if z stops using the child's minutes, the mid-p correction, or the 0.05 cut for `outside`."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.0, 1 / 5, 1 / 40, 8 / 5]), np.full(4, 24.0),
|
||||
exposure=np.array([10.0, 5.0, 40.0, 5.0]))
|
||||
assert -1 < z[0] < 0
|
||||
assert z[1] > z[2]
|
||||
assert outside.tolist() == [0.0, 0.0, 0.0, 1.0] and z[3] > 3
|
||||
mu = b.state["rate"] * 5.0
|
||||
tail = stats.poisson.sf(0, mu) if np.isinf(b.state["k"]) else stats.nbinom.sf(0, b.state["k"],
|
||||
b.state["k"] / (b.state["k"] + mu))
|
||||
at = (stats.poisson.pmf(1, mu) if np.isinf(b.state["k"])
|
||||
else stats.nbinom.pmf(1, b.state["k"], b.state["k"] / (b.state["k"] + mu)))
|
||||
assert z[1] == pytest.approx(stats.norm.ppf(1 - (tail - at / 2)))
|
||||
|
||||
|
||||
def test_no_exposure_value_age_or_reference_is_nan(count_rate, reference):
|
||||
"""Pins down: without minutes, with zero minutes, without a value, at an age outside the range, or against a
|
||||
reference with no minutes, z and outside are NaN, and a reference with no candidates at all clips z instead of
|
||||
reaching infinity. Fails if any of them reads as within the reference, or `inf` leaves the baseline."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.1, 0.1, np.nan, 0.1]), np.array([24, 24, 24, 60.0]),
|
||||
exposure=np.array([np.nan, 0.0, 10.0, 10.0]))
|
||||
assert np.isnan(z).all() and np.isnan(outside).all()
|
||||
assert np.isnan(b.deviation(np.array([0.1]), np.array([24.0]))[1]).all()
|
||||
empty = count_rate().fit(np.array([0.1]), np.array([24.0]), exposure=np.array([np.nan]))
|
||||
assert np.isnan(empty.deviation(np.array([0.1]), np.array([24.0]), exposure=np.array([10.0]))[1]).all()
|
||||
none = count_rate().fit(np.zeros(5), np.full(5, 24.0), exposure=np.full(5, 10.0))
|
||||
assert none.deviation(np.array([0.5]), np.array([24.0]), exposure=np.array([10.0]))[1][0] == count_rate.Z_MAX
|
||||
|
||||
|
||||
def test_the_reference_range_is_the_rates_expected_in_the_childs_minutes(count_rate, reference):
|
||||
"""Pins down: the p5, median and p95 of a count reference are the reference count's quantiles in the child's own
|
||||
minutes (times the zone scale) as rates, ordered, narrower in rate with more minutes, and NaN where z is NaN.
|
||||
Fails if the range stops using the child's minutes or the scale, or a child without minutes gets one (the
|
||||
patient summary shows it as the metric's reference)."""
|
||||
b = count_rate(scale=2.0).fit(*reference[:2], exposure=reference[2])
|
||||
out = b.percentiles(np.array([24.0, 24.0, 24.0, 60.0]), np.array([5.0, 400.0, np.nan, 10.0]))
|
||||
mu, k = b.state["rate"] * 400.0 * 2.0, b.state["k"]
|
||||
p95 = stats.poisson.ppf(0.95, mu) if np.isinf(k) else stats.nbinom.ppf(0.95, k, k / (k + mu))
|
||||
assert out[1, 2] == pytest.approx(p95 / 800.0)
|
||||
assert (np.diff(out[:2], axis=1) >= 0).all()
|
||||
assert out[1, 2] - out[1, 0] < out[0, 2] - out[0, 0] or out[0, 2] == 0
|
||||
assert np.isnan(out[2:]).all()
|
||||
|
||||
|
||||
def test_round_trip_and_scale(count_rate, reference):
|
||||
"""Pins down: `to_dict` / `from_dict` keep the state and the scale, and a per-electrode zone value is counted
|
||||
back through its electrodes (0.1 per minute per electrode over 3 electrodes in 10 minutes is 3 candidates).
|
||||
Fails if the scale is lost on save or not applied."""
|
||||
b = count_rate(scale=3.0).fit(*reference[:2], exposure=reference[2])
|
||||
again = count_rate.from_dict(b.to_dict())
|
||||
args = (np.array([0.1]), np.array([24.0]))
|
||||
assert again.deviation(*args, exposure=np.array([10.0]))[1] == pytest.approx(
|
||||
b.deviation(*args, exposure=np.array([10.0]))[1])
|
||||
assert again.scale == 3.0
|
||||
counts, exposure = b._counts(np.array([0.1]), np.array([10.0]))
|
||||
assert counts.tolist() == [3.0] and exposure.tolist() == [30.0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", [modern, legacy], ids=["modern", "legacy"])
|
||||
def test_the_rates_are_counted_against_their_minutes(module, reference):
|
||||
"""Pins down: every rate and density feature (overall, per electrode, per zone, unnormalised zone, inherited)
|
||||
has a count baseline whose exposure is the minutes of its own state and variant, the minutes themselves have no
|
||||
baseline, and the other spike features keep the configured one; a table without the minutes gives NaN for the
|
||||
counted features. Fails if a rate falls back to centile curves (collapsed at 0 in the reference) or reads
|
||||
another state's minutes."""
|
||||
spikes = (module.Spikes if module is modern else module.LegacySpikes)()
|
||||
assert set(module.EXPOSURE) == {f for f in module.FEATURES if f.startswith(
|
||||
("spike_rate_", "spike_density_", "spike_zone_", "spike_inherited_rate_", "spike_inherited_zone_"))}
|
||||
assert all(module.EXPOSURE[f].endswith(("_nrem" if "nrem" in f else "_awake")) for f in module.EXPOSURE)
|
||||
assert not set(module.MINUTES) & set(module.FEATURES)
|
||||
assert {spikes.baselines[f].name for f in module.EXPOSURE} == {"count_rate"}
|
||||
assert spikes.baselines["spike_laterality"].name == "curves"
|
||||
rates, ages, minutes = reference
|
||||
table = pd.DataFrame({"spike_rate_nrem": rates, "spike_minutes_nrem": minutes, "age_months": ages})
|
||||
spikes.train(table)
|
||||
out = spikes.predict(table.iloc[:3]).set_index("feature")
|
||||
assert out.loc["spike_rate_nrem", "z"].notna().all()
|
||||
blind = spikes.predict(table.iloc[:3].drop(columns="spike_minutes_nrem")).set_index("feature")
|
||||
assert blind.loc["spike_rate_nrem", "z"].isna().all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_count_alike(reference):
|
||||
"""Pins down: both implementations' count baselines give the same reference and the same z. Fails if one copy
|
||||
of `CountRate` drifts from the other."""
|
||||
rates, ages, minutes = reference
|
||||
a = modern_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
b = legacy_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
assert a.state == b.state
|
||||
np.testing.assert_array_equal(a.deviation(rates, ages, exposure=minutes)[1],
|
||||
b.deviation(rates, ages, exposure=minutes)[1])
|
||||
@@ -0,0 +1,424 @@
|
||||
"""What this module covers: the spikes biomarker's density features: only useful candidates
|
||||
count (a field and no vertex/POSTS/ocular mark), the per-electrode and per-zone density per
|
||||
state, the 0-vs-NaN convention, and the inherited-state variant where a stretch without a
|
||||
clean-window state takes the nearest labeled window's state (30 s, conservative on
|
||||
transitions, never before the stable start). Both implementations, modern and legacy, are
|
||||
exercised and must agree.
|
||||
|
||||
Fixtures: synthetic in-memory studies built around 1/f noise with spike waveforms injected
|
||||
(`density_study`: 40 field spikes at C3 in sleep and 20 isolated artifacts on O2 in wake;
|
||||
`rejected_study`: all sleep, a 20 s stretch the QC left without a state, and 20 s annotated
|
||||
as crying; `edge_study`: a single clean sleep window at 10-14 s with one field spike at 13 s;
|
||||
`montage_study`: sleep windows at 2-6 s and 30-34 s with field spikes at 10 s, 24 s and 31 s)
|
||||
and a quiet all-wake study. Nothing comes from a patient.
|
||||
"""
|
||||
import contextlib
|
||||
import importlib
|
||||
import io
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
FS = 250.0
|
||||
DUR = 600.0
|
||||
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
C3_NEIGHBORS = ("F3", "T3", "Cz", "P3")
|
||||
DENSITY_MODULES = ("tea.biomarkers.spikes._density", "tea.legacy.biomarkers.spikes._density")
|
||||
|
||||
|
||||
def _fondo(n, n_ch, rng):
|
||||
"""1/f noise at ~20 µV per channel, as the director's spike-detector validation uses."""
|
||||
f = np.fft.rfftfreq(n, 1 / FS)
|
||||
f[0] = f[1]
|
||||
out = np.empty((n, n_ch))
|
||||
for j in range(n_ch):
|
||||
esp = (1.0 / f) * np.exp(1j * rng.uniform(0, 2 * np.pi, len(f)))
|
||||
y = np.fft.irfft(esp, n)
|
||||
out[:, j] = y / np.std(y) * 20.0
|
||||
return out
|
||||
|
||||
|
||||
def _punta(dur_ms=50.0, amp=120.0, post=60.0):
|
||||
"""A spike with its slow posterior wave, as the director's criterion 3 describes."""
|
||||
n = int(dur_ms * FS / 1000)
|
||||
t = np.linspace(-1, 1, max(n, 3))
|
||||
p = amp * (1 - t ** 2) ** 2
|
||||
m = int(0.30 * FS)
|
||||
s = -post * np.sin(np.pi * np.linspace(0, 1, m))
|
||||
return np.concatenate([p, s])
|
||||
|
||||
|
||||
def _add_spikes(x, rng, canal, spans, field):
|
||||
"""`spikes` per (start_s, end_s) span on `canal`, with the field on its 10-20 neighbors
|
||||
when `field`, as one simultaneous discharge."""
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
pun = _punta()
|
||||
for a, b, k in spans:
|
||||
for t in np.sort(rng.uniform(a, b, k)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(pun), idx[canal]] += pun
|
||||
if field:
|
||||
for v in C3_NEIGHBORS:
|
||||
x[i:i + len(pun), idx[v]] += 0.6 * pun
|
||||
return x
|
||||
|
||||
|
||||
def _study(x, labels, annotations=()):
|
||||
"""The contracts' Study around an in-memory (samples, channels) µV array: one variant,
|
||||
4 s windows at a 2 s step labeled by sleep_state, and the annotated states as
|
||||
annotation_mask events (the same annotations ride the variant for the legacy adapter,
|
||||
whose director code translates them itself)."""
|
||||
import mne
|
||||
|
||||
from tea.contracts import Labels, Preprocessed, Study
|
||||
from tea.processes.annotation_mask.api import state_of
|
||||
|
||||
n = x.shape[0]
|
||||
raw = mne.io.RawArray(x.T * 1e-6, mne.create_info(SCALP[: x.shape[1]], FS, ch_types="eeg"),
|
||||
verbose="error")
|
||||
anns = [(float(t0), float(d), e) for t0, d, e in annotations]
|
||||
if anns:
|
||||
onsets, durs, descs = zip(*anns)
|
||||
raw.set_annotations(mne.Annotations(list(onsets), list(durs), list(descs)))
|
||||
starts = np.arange(0.0, n / FS - 4.0 + 1e-9, 2.0)
|
||||
windows = pd.DataFrame({"start_s": starts, "end_s": starts + 4.0, "clean": True, "gap": False})
|
||||
prep = Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
|
||||
plan={"name": "synthetic"}, plan_hash="synthetic")
|
||||
sleep_state = Labels("sleep_state",
|
||||
per_window=pd.Series(labels, index=windows.index, name="vigilancia"))
|
||||
events = pd.DataFrame([{"onset_s": t0, "duration_s": d, "estado": state_of(e)}
|
||||
for t0, d, e in anns if state_of(e)],
|
||||
columns=["onset_s", "duration_s", "estado"])
|
||||
annotation_mask = Labels("annotation_mask", events=events)
|
||||
return Study(prep, {"sleep_state": sleep_state, "annotation_mask": annotation_mask})
|
||||
|
||||
|
||||
def _labels_for(edits):
|
||||
"""A 600 s window at 2 s step labeled 'sueno' everywhere, with `edits` {start_s: label}."""
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sueno", dtype=object)
|
||||
for t0, e in edits.items():
|
||||
labels[starts == float(t0)] = e
|
||||
return list(labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def density_study():
|
||||
"""Half sleep, half wake: 40 spikes with field at C3 in the sleep half, 20 isolated
|
||||
artifacts on O2 in the wake half (no field: they must not count as useful)."""
|
||||
rng = np.random.default_rng(5)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(200.0, 290.0, 40)], field=True)
|
||||
solo = _punta(dur_ms=50.0, amp=150.0, post=0.0)
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
for t in np.sort(rng.uniform(310.0, 590.0, 20)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(solo), idx["O2"]] += 1.4 * solo
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.where(starts < 300.0, "sueno", "vigilia")
|
||||
return _study(x, labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rejected_study():
|
||||
"""All sleep: 6 spikes in a 20 s stretch the QC left without a state (150-170 s), 6 in
|
||||
clean sleep, 6 in a stretch annotated as crying (400-420 s)."""
|
||||
rng = np.random.default_rng(8)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(152.0, 168.0, 6), (200.0, 216.0, 6), (402.0, 418.0, 6)],
|
||||
field=True)
|
||||
labels = _labels_for({t0: "sin_estado" for t0 in range(148, 170, 2)})
|
||||
return _study(x, labels, annotations=((400.0, 20.0, "Llanto"),))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wake_study():
|
||||
"""Two quiet minutes of wake: no spike, no sleep."""
|
||||
rng = np.random.default_rng(2)
|
||||
labels = ["vigilia"] * len(np.arange(0.0, 120.0 - 4.0 + 1e-9, 2.0))
|
||||
return _study(_fondo(int(120 * FS), len(SCALP), rng), labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edge_study():
|
||||
"""One minute with a single clean sleep window at 10-14 s and one field spike at 13 s:
|
||||
inside the 4 s window the state was classified on, beyond the 2 s grid step."""
|
||||
rng = np.random.default_rng(11)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(12.9, 13.1, 1)], field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 10.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def montage_study():
|
||||
"""One minute with clean sleep windows at 2-6 s and 30-34 s and field spikes at 10 s
|
||||
(unlabeled gap before the stable start), 24 s (unlabeled gap after it) and 31 s
|
||||
(inside the second window)."""
|
||||
rng = np.random.default_rng(13)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(9.9, 10.1, 1), (23.9, 24.1, 1), (30.9, 31.1, 1)],
|
||||
field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 2.0] = "sueno"
|
||||
labels[starts == 30.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
def _measure(impl, study, **kwargs):
|
||||
path = "tea.legacy.biomarkers.spikes.api" if impl == "legacy" else "tea.biomarkers.spikes.api"
|
||||
cls = getattr(importlib.import_module(path), "LegacySpikes" if impl == "legacy" else "Spikes")
|
||||
return cls(**kwargs).measure(study)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_density(density_study):
|
||||
"""The density study measured by both implementations, {'modern': {...}, 'legacy': {...}}."""
|
||||
return {impl: _measure(impl, density_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_rejected(rejected_study):
|
||||
"""The rejected-stretch study measured by both implementations."""
|
||||
return {impl: _measure(impl, rejected_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
def test_useful_candidates_map_to_c3_and_the_central_zone(measured_density):
|
||||
"""Pins down: with field spikes at C3 in sleep, the NREM density lands on C3 and the
|
||||
central zone (per electrode, so it divides by the zone's 3 electrodes), every other
|
||||
electrode is exactly 0, and the isolated wake artifacts on O2 count nowhere.
|
||||
|
||||
Fails if candidates without a field start counting, if canal_max stops being the
|
||||
electrode a discharge is attributed to, or if the zone density stops being normalised
|
||||
per electrode.
|
||||
"""
|
||||
m = measured_density["modern"]
|
||||
assert m["spike_rate_nrem"] > 0
|
||||
# the density divides by the unrounded minutes (the por_canal convention) and the
|
||||
# rate by the two-decimal minutes (the indicadores convention), so they can differ
|
||||
# by that rounding
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(m["spike_rate_nrem"], rel=0.01)
|
||||
assert m["spike_density_nrem_C3"] > 10 * max(m["spike_rate_awake"], 0.01)
|
||||
for e in SCALP:
|
||||
esperado = m["spike_rate_nrem"] if e == "C3" else 0.0
|
||||
assert m[f"spike_density_nrem_{e}"] == pytest.approx(esperado, rel=0.01), e
|
||||
assert m["spike_zone_nrem_central"] == pytest.approx(m["spike_rate_nrem"] / 3, rel=0.01)
|
||||
assert m["spike_zone_nrem_frontal_izq"] == 0.0
|
||||
assert m["spike_zone_nrem_occipital"] == 0.0
|
||||
assert m["spike_density_awake_O2"] == 0.0
|
||||
|
||||
|
||||
def test_a_quiet_present_electrode_is_zero_and_a_state_without_minutes_is_nan(wake_study):
|
||||
"""Pins down: an electrode present with no candidates reads 0, never NaN, while a state
|
||||
with no clean minutes (no sleep in an all-wake study) makes every feature of that state
|
||||
NaN, inherited ones included.
|
||||
|
||||
Fails if the densities stop distinguishing 'no candidates' (0) from 'no denominator'
|
||||
(NaN), or if the inherited variant stops honouring the same convention.
|
||||
"""
|
||||
m = _measure("modern", wake_study)
|
||||
for e in SCALP:
|
||||
assert m[f"spike_density_nrem_{e}"] != m[f"spike_density_nrem_{e}"] # NaN
|
||||
assert m[f"spike_density_awake_{e}"] == 0.0
|
||||
for z in ("central", "occipital", "temporal_der"):
|
||||
assert m[f"spike_zone_nrem_{z}"] != m[f"spike_zone_nrem_{z}"]
|
||||
assert m[f"spike_zone_awake_{z}"] == 0.0
|
||||
assert m[f"spike_inherited_zone_nrem_{z}"] != m[f"spike_inherited_zone_nrem_{z}"]
|
||||
assert m["spike_inherited_rate_nrem"] != m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_awake"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_absent_electrode_and_zone_are_nan(module):
|
||||
"""Pins down: an electrode missing from the montage has a NaN density (it cannot be
|
||||
measured), and a zone with no present electrode is NaN too.
|
||||
|
||||
Fails if absent electrodes start reading as a measured 0.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"canal_max": ["C3", "C3"], "fase": ["sueno", "sueno"],
|
||||
"vertice": [False, False], "posts": [False, False],
|
||||
"ocular": [False, False], "vecinos": [2, 2]})
|
||||
out = mod.electrode_densities(ev, {"sueno": 2.0}, electrodes=("C3", "T6"), present=("C3",))
|
||||
assert out["spike_density_nrem_C3"] == pytest.approx(1.0)
|
||||
assert out["spike_density_nrem_T6"] != out["spike_density_nrem_T6"]
|
||||
zonas = mod.zone_densities(ev, {"sueno": 2.0}, present=("C3",))
|
||||
assert zonas["spike_zone_nrem_central"] == pytest.approx(1.0)
|
||||
assert zonas["spike_zone_nrem_temporal_der"] != zonas["spike_zone_nrem_temporal_der"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_states_inherit_from_the_nearest_labeled_window(module):
|
||||
"""Pins down (port of the research repo's inheritance test): a stretch the QC left
|
||||
unlabeled takes the nearest clean window's state up to 30 s away; farther, or before
|
||||
the first labeled window (or `t_min`), it stays without a state; intervals never
|
||||
overlap.
|
||||
|
||||
Fails if the 30 s reach, the nearest-window rule or the `t_min` floor stop being
|
||||
applied.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(20, 40, 2.0), np.arange(60, 98, 2.0), np.arange(200, 240, 2.0)]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": "sueno"})
|
||||
v = mod.inherit_states(labeled, 300.0, inherit_s=30.0, t_min=15.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return (v.etiqueta[m].iloc[0], bool(v.heredado[m].iloc[0])) if m.any() else (None, None)
|
||||
|
||||
assert etq(30) == ("sueno", False) # clean window
|
||||
assert etq(50) == ("sueno", True) # 20 s gap between clean windows
|
||||
assert etq(120) == ("sueno", True) # 20 s after the last clean window
|
||||
assert etq(150) == (None, None) # more than 30 s away from both
|
||||
assert etq(18) == (None, None) # before the first clean window (t_min 15)
|
||||
assert not (v.t_ini_s.to_numpy()[1:] < v.t_fin_s.to_numpy()[:-1]).any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_inheritance_is_conservative_across_state_transitions(module):
|
||||
"""Pins down (port of the research repo's conservative-transition test): an unlabeled
|
||||
stretch between two different states stays 'transicion' and counts in neither; between
|
||||
two windows of the same state it inherits that state.
|
||||
|
||||
Fails if the transition rule starts assigning one of the two states.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(0, 40, 2.0), np.arange(60, 100, 2.0), np.arange(110, 150, 2.0)]
|
||||
e = np.r_[["somnolencia"] * 20, ["sueno"] * 20, ["sueno"] * 20]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": e})
|
||||
v = mod.inherit_states(labeled, 160.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return v.etiqueta[m].iloc[0] if m.any() else None
|
||||
|
||||
assert etq(45) == "transicion" and etq(58) == "transicion"
|
||||
assert etq(105) == "sueno"
|
||||
assert etq(30) == "somnolencia" and etq(70) == "sueno"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_candidate_category_marks_isolated_and_marked(module):
|
||||
"""Pins down: a candidate is 'util' only with a field and no mark; the director's mark
|
||||
order (posts, vertice, ocular) wins over 'aislado'.
|
||||
|
||||
Fails if the category rule starts counting marked or fieldless candidates as useful.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"vecinos": [2, 0, 3, 1, 0],
|
||||
"posts": [False, False, True, False, False],
|
||||
"vertice": [False, False, False, True, False],
|
||||
"ocular": [False, False, False, False, True]})
|
||||
assert list(mod.candidate_category(ev)) == ["util", "aislado", "posts", "vertice", "ocular"]
|
||||
|
||||
|
||||
def test_rejected_stretch_counts_only_when_inherited(measured_rejected):
|
||||
"""Pins down (port of the research repo's rejected-window test): spikes in a stretch
|
||||
the QC left without a state count in NREM only through inheritance — the direct rate
|
||||
sees only the clean-stretch spikes — and spikes in a stretch annotated as crying count
|
||||
nowhere, because the detector's own gate rejects those windows.
|
||||
|
||||
Fails if the inherited variant starts using the direct states, or if annotated states
|
||||
stop gating the detector.
|
||||
"""
|
||||
for m in measured_rejected.values():
|
||||
assert 0 < m["spike_rate_nrem"] < m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2 * m["spike_rate_nrem"], rel=0.2)
|
||||
assert m["spike_inherited_zone_nrem_central"] > m["spike_zone_nrem_central"]
|
||||
assert m["spike_inherited_rate_awake"] != m["spike_inherited_rate_awake"] # no wake
|
||||
|
||||
|
||||
def test_without_inheritance_the_inherited_variant_matches_the_direct(rejected_study):
|
||||
"""Pins down: with the inheritance reach at 0 the inherited variant reduces to the
|
||||
direct one (same candidates, same minutes).
|
||||
|
||||
Fails if the inherited run stops deriving its states from the inheritance intervals.
|
||||
"""
|
||||
m = _measure("modern", rejected_study, herencia_s=0.0)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(m["spike_rate_nrem"], rel=1e-9)
|
||||
assert m["spike_inherited_zone_nrem_central"] == pytest.approx(m["spike_zone_nrem_central"],
|
||||
rel=1e-9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_candidate_inside_the_classified_window_counts_as_direct(impl, edge_study):
|
||||
"""Pins down (the reviewer's 13 s scenario): a candidate at 13 s with a single clean
|
||||
4 s sleep window starting at 10 s lies inside the window's own state, so the direct
|
||||
NREM rate counts it (1 spike over the 4 clean gate minutes of [10, 14)); the inherited
|
||||
run labels 13 s as direct too and only stretches [14, 44) inherit.
|
||||
|
||||
Fails if `_vig` shortens the state windows to the 2 s grid step again: the spike would
|
||||
fall outside every window, the direct rate would read 0 and only the inherited run
|
||||
would count it.
|
||||
"""
|
||||
m = _measure(impl, edge_study)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(14.286, abs=0.001) # 1 / 0.07 rounded minutes
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(15.0, abs=0.01) # 1 over 4/60 unrounded
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(1.754, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_no_inherited_state_before_the_stable_start(impl, montage_study):
|
||||
"""Pins down (the reviewer's stable-start scenario): with the stable start at 20 s,
|
||||
the spike at 10 s — in the gap after an early labeled window but before the stable
|
||||
start — gets no state anywhere, while the spike at 24 s inherits and the spike at
|
||||
31 s is direct. The direct run sees only 31 s (0.13 clean sleep minutes, rate 7.692);
|
||||
the inherited run counts 24 s and 31 s but not 10 s (0.73 minutes, rate 2.74). With
|
||||
the default stable start of 0 the 10 s spike inherits as well (0.97 minutes, 3.093).
|
||||
|
||||
Fails if `measure` stops passing the stable start to the inheritance (the 10 s spike
|
||||
would count in the inherited rate) or if the early window's reach is clamped wrongly.
|
||||
"""
|
||||
m = _measure(impl, montage_study, stable_start_s=20.0)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(7.692, abs=0.001)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2.74, abs=0.001)
|
||||
sin_montaje = _measure(impl, montage_study)
|
||||
assert sin_montaje["spike_inherited_rate_nrem"] == pytest.approx(3.093, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_crying_annotation_rejects_gate_windows(impl, rejected_study):
|
||||
"""Pins down (port of the research repo's annotated-window test): the detector's 2 s
|
||||
gate rejects the windows of the crying stretch and nothing else.
|
||||
|
||||
Fails if annotated states stop reaching the quality gate (the crying spikes would then
|
||||
count as sleep).
|
||||
"""
|
||||
if impl == "modern":
|
||||
from tea.biomarkers.spikes import _density
|
||||
from tea.biomarkers.spikes.api import Spikes
|
||||
|
||||
module = Spikes()
|
||||
est, canales = module._prepare(rejected_study)
|
||||
gate = _density.gate_windows(est, canales, module.vent_s, module.rechazar_transitorio)
|
||||
else:
|
||||
from tea.legacy.biomarkers.spikes import _adapter, _density
|
||||
from tea.legacy.biomarkers.spikes._director import eeg_io
|
||||
|
||||
module = _density
|
||||
with _adapter.estudio(rejected_study.prep, "hp05_prom", eeg_io) as est, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
gate = _density.gate_windows(est, eeg_io, 2.0, False)
|
||||
lloro = gate.motivo.str.contains("estado llanto", regex=False)
|
||||
assert lloro.sum() >= 8 and not gate[lloro].apta.any()
|
||||
assert gate[~lloro].apta.all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_agree_on_every_feature(measured_density, measured_rejected):
|
||||
"""Pins down: both implementations expose the same 79 features with the same values on
|
||||
the same study, old and new alike.
|
||||
|
||||
Fails if one implementation's port of the detector, the densities or the inheritance
|
||||
drifts from the other's.
|
||||
"""
|
||||
for nombre, medido in (("density", measured_density), ("rejected", measured_rejected)):
|
||||
moderno, legado = medido["modern"], medido["legacy"]
|
||||
assert set(moderno) == set(legado)
|
||||
for f, v in moderno.items():
|
||||
otro = legado[f]
|
||||
iguales = v == otro or (np.isnan(v) and np.isnan(otro))
|
||||
assert iguales or v == pytest.approx(otro, rel=1e-6, abs=1e-12), (nombre, f, v, otro)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Spindle detection and summaries, plus loading partial spindle baselines.
|
||||
|
||||
Fixtures: `sleep_recording` supplies synthetic EEG with short, long or sustained
|
||||
sigma bursts. `tmp_path` holds a saved spindle baseline.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles.api import Spindles
|
||||
from tea.legacy.biomarkers.spindles.api import LegacySpindles
|
||||
from tea.legacy.processes.spindle_detection.api import LegacySpindleDetection
|
||||
from tea.processes.spindle_detection.api import SpindleDetection
|
||||
|
||||
CHANNELS = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
FS = 250
|
||||
DENSITY = "spindle_density_per_min_channel"
|
||||
NO_LONG = "spindle_density_per_min_channel_no_long"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sleep_recording():
|
||||
"""Make 600 s of sleep on the 10-20 montage with selectable sigma bursts."""
|
||||
|
||||
def make(mode):
|
||||
rng = np.random.default_rng(1)
|
||||
duration = 600
|
||||
freq = np.fft.rfftfreq(duration * FS, 1 / FS)
|
||||
freq[0] = freq[1]
|
||||
voltages = np.empty((duration * FS, len(CHANNELS)))
|
||||
for i in range(len(CHANNELS)):
|
||||
spectrum = np.exp(1j * rng.uniform(0, 2 * np.pi, len(freq))) / freq
|
||||
background = np.fft.irfft(spectrum)
|
||||
voltages[:, i] = background * (20 / background.std())
|
||||
|
||||
def inject(start, length, hz, amplitude, gains):
|
||||
t = np.arange(int(length * FS)) / FS
|
||||
envelope = np.hanning(len(t)) if length < 2 else np.clip(np.minimum(t, length - t) / 0.5, 0, 1)
|
||||
wave = amplitude * envelope * np.sin(2 * np.pi * hz * t)
|
||||
for channel, gain in gains.items():
|
||||
a = int(start * FS)
|
||||
voltages[a:a + len(t), CHANNELS.index(channel)] += gain * wave
|
||||
|
||||
short = dict.fromkeys(("F3", "F4", "C3", "C4", "Cz"), 1.0) | {"Fz": 0.8, "P3": 0.7, "P4": 0.7}
|
||||
starts = np.arange(5, duration - 10, 9.0)
|
||||
if mode != "empty":
|
||||
for start in starts + rng.uniform(-1, 1, len(starts)):
|
||||
if mode == "long" and (200 < start < 240 or 400 < start < 410):
|
||||
continue
|
||||
inject(start, 1, 12.5, 50, short)
|
||||
if mode == "long":
|
||||
inject(205, 25, 13, 60, {"C3": 1, "C4": 1, "Cz": 1, "F3": 0.8, "F4": 0.8})
|
||||
inject(402, 5, 12, 60, {"Fz": 1, "F3": 0.6, "F4": 0.6})
|
||||
if mode == "continuous":
|
||||
inject(0, duration * 0.6, 13, 60, short)
|
||||
if mode == "empty":
|
||||
voltages.fill(0)
|
||||
|
||||
class Raw:
|
||||
n_times = len(voltages)
|
||||
ch_names = CHANNELS
|
||||
info = {"sfreq": FS}
|
||||
annotations = ()
|
||||
|
||||
def get_channel_types(self):
|
||||
return ["eeg"] * len(self.ch_names)
|
||||
|
||||
def get_data(self, picks):
|
||||
return voltages[:, [self.ch_names.index(name) for name in picks]].T / 1e6
|
||||
|
||||
windows = pd.DataFrame({"start_s": np.arange(0, duration, 4.0)})
|
||||
return SimpleNamespace(variant=lambda _: Raw(), windows=windows)
|
||||
|
||||
return make
|
||||
|
||||
|
||||
IMPLEMENTATIONS = ((SpindleDetection, Spindles), (LegacySpindleDetection, LegacySpindles))
|
||||
|
||||
|
||||
def measure(prep, implementation, phase="N2"):
|
||||
detector, biomarker = implementation
|
||||
labels = {"sleep_state": SimpleNamespace(per_window=["sueno"] * len(prep.windows)),
|
||||
"slow_wave_staging": SimpleNamespace(per_window=["N2"] * len(prep.windows))}
|
||||
study = SimpleNamespace(prep=prep, label=labels.__getitem__)
|
||||
labels["spindle_detection"] = detector(phase=phase).predict(study)
|
||||
return biomarker().measure(study), labels["spindle_detection"].events
|
||||
|
||||
|
||||
def test_long_runs_split_events_and_density(sleep_recording):
|
||||
"""Pin long/extreme counts and the existing density. Fails if split events disappear from the old density."""
|
||||
prep = sleep_recording("long")
|
||||
outputs = []
|
||||
for implementation in IMPLEMENTATIONS:
|
||||
result, events = measure(prep, implementation)
|
||||
assert ((events.channel == "C3") & events.onset_s.between(204, 231)).sum() >= 6
|
||||
assert result["spindle_n_long_runs"] == 6
|
||||
assert result["spindle_n_extreme"] == 5
|
||||
assert 24 <= result["spindle_max_run_s"] <= 27
|
||||
assert result[DENSITY] == round(len(events) / 10 / 13, 3)
|
||||
assert result[NO_LONG] < result[DENSITY]
|
||||
outputs.append(result)
|
||||
for feature in ("spindle_n_long_runs", "spindle_n_extreme", "spindle_max_run_s",
|
||||
"spindle_sigma_occupancy_median", "spindle_sigma_occupancy_max", NO_LONG):
|
||||
assert outputs[0][feature] == pytest.approx(outputs[1][feature], abs=0.01)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_short_bursts_and_sustained_sigma(sleep_recording, implementation):
|
||||
"""Pin zero long runs with short spindles and occupancy with sustained sigma. Fails if occupancy uses event thresholds."""
|
||||
short, _ = measure(sleep_recording("short"), implementation)
|
||||
sustained, _ = measure(sleep_recording("continuous"), implementation)
|
||||
assert short["spindle_n_long_runs"] == short["spindle_n_extreme"] == 0
|
||||
assert short[NO_LONG] == short[DENSITY]
|
||||
assert short["spindle_sigma_occupancy_max"] < 0.45
|
||||
assert sustained["spindle_sigma_occupancy_max"] >= 0.55
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_spindle_density_by_electrode_and_zone(sleep_recording, implementation):
|
||||
"""Pin event counts per sleep minute and per searched electrode, NaN on a channel the detector never searches
|
||||
(O1, and so the occipital zone). Fails if empty searched channels are omitted, an unsearched channel reports a
|
||||
density, or a phase leaks."""
|
||||
prep = sleep_recording("short")
|
||||
result, events = measure(prep, implementation)
|
||||
counts = events.channel.value_counts()
|
||||
assert counts["C3"] > 0 and counts["Fz"] > 0
|
||||
assert result["spindle_electrode_C3"] == counts["C3"] / 10
|
||||
assert np.isnan(result["spindle_electrode_O1"])
|
||||
assert np.isnan(result["spindle_zone_occipital"])
|
||||
assert result["spindle_zone_central"] == counts[["C3", "Cz", "C4"]].sum() / 30
|
||||
other_phase, _ = measure(prep, implementation, phase="N3")
|
||||
assert all(np.isnan(value) for value in other_phase.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_sleep_without_spindles_is_nan(sleep_recording, implementation):
|
||||
"""Pin missing outputs on event-free sleep. Fails if any feature reports a value without a detected spindle."""
|
||||
result, events = measure(sleep_recording("empty"), implementation)
|
||||
assert events.empty and events.attrs["searched"]
|
||||
assert all(np.isnan(value) for value in result.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("biomarker", (Spindles, LegacySpindles))
|
||||
def test_spindle_baselines_load_without_new_features(tmp_path, biomarker):
|
||||
"""Pin save/load of a single-feature baseline. Fails if train or predict requires all current feature columns."""
|
||||
table = pd.DataFrame({"age_months": [12, 24, 36], DENSITY: [0.1, 0.2, 0.3]})
|
||||
module = biomarker(baseline_params={"n_min": 1}).train(table)
|
||||
module.save(tmp_path)
|
||||
loaded = biomarker.load(tmp_path)
|
||||
assert list(loaded.baselines) == [DENSITY]
|
||||
assert loaded.predict(table).feature.tolist() == [DENSITY] * len(table)
|
||||
Reference in New Issue
Block a user