From 05ee02990c6043148d74a192d4ded074847d2fe5 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Thu, 19 Nov 2026 19:20:29 -0600 Subject: [PATCH 1/4] Age at the recording from the EDF header (start minus birth date) when no age is passed; preprocessing 0.2.0 --- pyproject.toml | 2 +- src/tea/__init__.py | 2 +- src/tea/contracts/__init__.py | 5 +++ src/tea/contracts/data.py | 57 +++++++++++++++++++++++++---- src/tea/legacy/preprocessing/api.py | 7 +++- src/tea/preprocessing/api.py | 23 +++++++----- 6 files changed, 74 insertions(+), 22 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index fdab5fc..a1b9e47 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "tea" -version = "0.1.0" +version = "0.2.0" description = "Modular EEG biomarker library for TEA: validation, preprocessing, processes and biomarkers, each a replaceable module" readme = "README.md" authors = [ diff --git a/src/tea/__init__.py b/src/tea/__init__.py index ebf774f..54d0487 100644 --- a/src/tea/__init__.py +++ b/src/tea/__init__.py @@ -6,4 +6,4 @@ Every biomarker and every process is its own module. Modules talk only through `tea.contracts`; see the architecture plan. """ -__version__ = "0.1.0" +__version__ = "0.2.0" diff --git a/src/tea/contracts/__init__.py b/src/tea/contracts/__init__.py index dc4a4df..74b3114 100644 --- a/src/tea/contracts/__init__.py +++ b/src/tea/contracts/__init__.py @@ -3,10 +3,12 @@ The shared API of `tea`: the only code every module may import. from tea.contracts import Recording, Preprocessed, Study, Labels from tea.contracts import check_module, CONTRACT_VERSION + from tea.contracts import header_age_months """ from tea.contracts.data import ( CONTRACT_VERSION, + DAYS_PER_MONTH, DEVIATION_COLUMNS, SPAN_COLUMNS, WINDOW_COLUMNS, @@ -16,6 +18,8 @@ from tea.contracts.data import ( Study, ValidationSummary, empty_spans, + header_age_months, + read_edf, sha256_of, ) from tea.contracts.protocols import ( @@ -32,6 +36,7 @@ from tea.contracts.protocols import ( __all__ = [ "CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "empty_spans", "Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of", + "DAYS_PER_MONTH", "header_age_months", "read_edf", "Module", "Validator", "Preprocessor", "Process", "Biomarker", "KINDS", "ContractError", "check_module", ] diff --git a/src/tea/contracts/data.py b/src/tea/contracts/data.py index d8d6d36..8fd6c51 100644 --- a/src/tea/contracts/data.py +++ b/src/tea/contracts/data.py @@ -15,6 +15,7 @@ from __future__ import annotations import hashlib from collections.abc import Mapping from dataclasses import dataclass, field +from datetime import date, datetime from pathlib import Path from typing import Any @@ -22,6 +23,12 @@ import pandas as pd CONTRACT_VERSION = "1.0" +# Months of the age at a recording: days divided by this. +DAYS_PER_MONTH = 30.4375 +MAX_HEADER_AGE_MONTHS = 216 +# What EDF writers put in the header's start date when they don't know it. +UNKNOWN_START = date(1985, 1, 1) + # Columns of the table that Biomarker.predict returns. DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline") @@ -65,20 +72,54 @@ class Recording: @classmethod def from_edf(cls, path: str | Path, *, age_months: float | None = None) -> Recording: - """Read an EDF with MNE. The only EDF reader shared through contracts.""" - import mne + """Read an EDF with MNE. The only EDF reader shared through contracts. + Without `age_months`, the age is the header's (`header_age_months`). + """ path = Path(path) - try: - raw = mne.io.read_raw_edf(path, preload=True, verbose="error") - except Exception as e: # annotation texts in a Windows code page - if "latin1" not in str(e): - raise - raw = mne.io.read_raw_edf(path, preload=True, verbose="error", encoding="latin1") + raw = read_edf(path, preload=True) + if age_months is None: + age_months = header_age_months(raw) return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path), source_name=path.stem) +def read_edf(path: str | Path, *, preload: bool) -> Any: + """`mne.io.read_raw_edf`, retrying in latin1 when annotation texts are in a Windows code page.""" + import mne + + try: + return mne.io.read_raw_edf(path, preload=preload, verbose="error") + except Exception as e: + if "latin1" not in str(e): + raise + return mne.io.read_raw_edf(path, preload=preload, verbose="error", encoding="latin1") + + +def header_age_months(source: Any, *, days_per_month: float = DAYS_PER_MONTH) -> float | None: + """ + Age at the recording from the EDF header: start date minus birth date, in + months of `days_per_month` days, to one decimal. + + `source` is an EDF path (only the header is read) or an `mne.io.BaseRaw`. + None when the header lacks either date (anonymised EDF+ writes `X`), the + start is the 01.01.85 placeholder, the birth date is after the start or the + age exceeds `MAX_HEADER_AGE_MONTHS`. + """ + raw = source if hasattr(source, "info") else read_edf(source, preload=False) + start = raw.info.get("meas_date") + born = (raw.info.get("subject_info") or {}).get("birthday") + if start is None or born is None: + return None + studied = start.date() if isinstance(start, datetime) else start + if isinstance(born, tuple): # MNE before 1.8 + born = date(*born) + if studied == UNKNOWN_START or born > studied: + return None + months = round((studied - born).days / days_per_month, 1) + return months if months <= MAX_HEADER_AGE_MONTHS else None + + @dataclass(frozen=True) class ValidationSummary: """ diff --git a/src/tea/legacy/preprocessing/api.py b/src/tea/legacy/preprocessing/api.py index fe7f3e9..42beb90 100644 --- a/src/tea/legacy/preprocessing/api.py +++ b/src/tea/legacy/preprocessing/api.py @@ -30,7 +30,7 @@ from typing import Any import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of +from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, header_age_months, sha256_of DIRECTOR_COMMIT = "7dfc641" _SUFFIX = {"average": "prom", "linked_ears": "orejas"} @@ -42,7 +42,7 @@ class PlanNotSupported(ValueError): class LegacyPreprocessing: name = "preprocessing" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION impl = "legacy" @@ -88,12 +88,15 @@ class LegacyPreprocessing: # ---------------------------------------------------------------- run def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed: + """Without `age_months`, the age is the EDF header's (`header_age_months`).""" import mne from ._director import edf_convert, lote, preproceso args = self.director_args(plan) edf_path = Path(edf_path) + if age_months is None: + age_months = header_age_months(edf_path) nombre = edf_path.stem with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \ contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings(): diff --git a/src/tea/preprocessing/api.py b/src/tea/preprocessing/api.py index 2261371..3f9eba9 100644 --- a/src/tea/preprocessing/api.py +++ b/src/tea/preprocessing/api.py @@ -25,7 +25,14 @@ from typing import Any import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of +from tea.contracts import ( + CONTRACT_VERSION, + Preprocessed, + ValidationSummary, + header_age_months, + read_edf, + sha256_of, +) from . import _channels, _qc, _signal from .plan import PreprocessPlan @@ -36,7 +43,7 @@ _TYPE = {"eeg": "eeg", "orejas": "eeg", "eog": "eog", "cardiaco": "ecg"} class Preprocessing: name = "preprocessing" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION impl = "modern" @@ -52,15 +59,11 @@ class Preprocessing: # ------------------------------------------------------------------ run def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed: - import mne - + """Without `age_months`, the age is the EDF header's (`header_age_months`).""" p = PreprocessPlan.from_dict(plan) - try: - raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error") - except Exception as e: # annotation texts in a Windows code page - if "latin1" not in str(e): - raise - raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error", encoding="latin1") + raw = read_edf(edf_path, preload=True) + if age_months is None: + age_months = header_age_months(raw) ren, seen, drop = {}, set(), [] for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept n = _channels.normalize(c) -- 2.53.0 From 24e7824fe763fea19df4651d5d6d39f1740523e4 Mon Sep 17 00:00:00 2001 From: ulises Date: Sat, 21 Nov 2026 23:18:39 -0600 Subject: [PATCH 2/4] ADOS-2 association (modern and legacy), per-electrode and per-zone spike and spindle densities, count reference for spike rates with its expected range; 0.3.0 --- README.md | 17 +- pyproject.toml | 8 +- src/tea/__init__.py | 2 +- src/tea/associations/__init__.py | 1 + src/tea/associations/ados2/__init__.py | 3 + src/tea/associations/ados2/_items.py | 118 ++++++++ src/tea/associations/ados2/_models.py | 279 ++++++++++++++++++ src/tea/associations/ados2/api.py | 162 ++++++++++ src/tea/biomarkers/aperiodic/_baseline.py | 12 +- src/tea/biomarkers/aperiodic/api.py | 2 +- src/tea/biomarkers/coupling/_baseline.py | 12 +- src/tea/biomarkers/coupling/api.py | 2 +- src/tea/biomarkers/gradient/_baseline.py | 12 +- src/tea/biomarkers/gradient/api.py | 2 +- src/tea/biomarkers/mse/_baseline.py | 12 +- src/tea/biomarkers/mse/api.py | 2 +- .../biomarkers/posterior_rhythm/_baseline.py | 12 +- src/tea/biomarkers/posterior_rhythm/api.py | 2 +- src/tea/biomarkers/slow_waves/_baseline.py | 12 +- src/tea/biomarkers/slow_waves/api.py | 2 +- src/tea/biomarkers/spikes/_baseline.py | 102 ++++++- src/tea/biomarkers/spikes/_density.py | 214 ++++++++++++++ src/tea/biomarkers/spikes/api.py | 153 ++++++++-- .../spindle_topography/_baseline.py | 12 +- src/tea/biomarkers/spindle_topography/api.py | 2 +- src/tea/biomarkers/spindles/_baseline.py | 12 +- src/tea/biomarkers/spindles/api.py | 65 +++- src/tea/contracts/__init__.py | 9 +- src/tea/contracts/data.py | 23 +- src/tea/contracts/protocols.py | 17 ++ src/tea/contracts/testing.py | 3 +- src/tea/legacy/associations/__init__.py | 1 + src/tea/legacy/associations/ados2/__init__.py | 3 + .../associations/ados2/_research/__init__.py | 1 + .../ados2/_research/ados2_items.py | 150 ++++++++++ .../associations/ados2/_research/modelo_or.py | 251 ++++++++++++++++ src/tea/legacy/associations/ados2/api.py | 157 ++++++++++ .../legacy/biomarkers/aperiodic/_baseline.py | 12 +- src/tea/legacy/biomarkers/aperiodic/api.py | 2 +- .../legacy/biomarkers/coupling/_baseline.py | 12 +- .../biomarkers/coupling/_director/eeg_io.py | 11 +- src/tea/legacy/biomarkers/coupling/api.py | 4 +- .../legacy/biomarkers/gradient/_baseline.py | 12 +- .../biomarkers/gradient/_director/eeg_io.py | 11 +- src/tea/legacy/biomarkers/gradient/api.py | 4 +- src/tea/legacy/biomarkers/mse/_baseline.py | 12 +- src/tea/legacy/biomarkers/mse/api.py | 2 +- .../biomarkers/posterior_rhythm/_baseline.py | 12 +- .../posterior_rhythm/_director/eeg_io.py | 11 +- .../legacy/biomarkers/posterior_rhythm/api.py | 4 +- .../legacy/biomarkers/slow_waves/_baseline.py | 12 +- .../biomarkers/slow_waves/_director/eeg_io.py | 11 +- src/tea/legacy/biomarkers/slow_waves/api.py | 4 +- src/tea/legacy/biomarkers/spikes/_baseline.py | 102 ++++++- src/tea/legacy/biomarkers/spikes/_density.py | 216 ++++++++++++++ .../biomarkers/spikes/_director/eeg_io.py | 11 +- src/tea/legacy/biomarkers/spikes/api.py | 154 +++++++--- .../spindle_topography/_baseline.py | 12 +- .../spindle_topography/_director/eeg_io.py | 11 +- .../spindle_topography/_director/husos.py | 181 +++++++++++- .../biomarkers/spindle_topography/api.py | 4 +- .../legacy/biomarkers/spindles/_baseline.py | 12 +- .../biomarkers/spindles/_director/eeg_io.py | 11 +- .../biomarkers/spindles/_director/husos.py | 181 +++++++++++- src/tea/legacy/biomarkers/spindles/api.py | 82 +++-- .../legacy/preprocessing/_director/eeg_io.py | 11 +- src/tea/legacy/preprocessing/api.py | 4 +- .../annotation_mask/_director/eeg_io.py | 11 +- .../legacy/processes/annotation_mask/api.py | 4 +- .../processes/sleep_state/_director/eeg_io.py | 11 +- src/tea/legacy/processes/sleep_state/api.py | 4 +- .../slow_wave_staging/_director/eeg_io.py | 11 +- .../legacy/processes/slow_wave_staging/api.py | 4 +- .../spindle_detection/_director/eeg_io.py | 11 +- .../spindle_detection/_director/husos.py | 181 +++++++++++- .../legacy/processes/spindle_detection/api.py | 27 +- .../window_selection/_director/eeg_io.py | 11 +- .../legacy/processes/window_selection/api.py | 4 +- src/tea/legacy/validation/_director/eeg_io.py | 11 +- src/tea/legacy/validation/api.py | 4 +- src/tea/pipeline/registry.py | 13 + src/tea/processes/spindle_detection/api.py | 134 ++++++++- 82 files changed, 3133 insertions(+), 285 deletions(-) create mode 100644 src/tea/associations/__init__.py create mode 100644 src/tea/associations/ados2/__init__.py create mode 100644 src/tea/associations/ados2/_items.py create mode 100644 src/tea/associations/ados2/_models.py create mode 100644 src/tea/associations/ados2/api.py create mode 100644 src/tea/biomarkers/spikes/_density.py create mode 100644 src/tea/legacy/associations/__init__.py create mode 100644 src/tea/legacy/associations/ados2/__init__.py create mode 100644 src/tea/legacy/associations/ados2/_research/__init__.py create mode 100644 src/tea/legacy/associations/ados2/_research/ados2_items.py create mode 100644 src/tea/legacy/associations/ados2/_research/modelo_or.py create mode 100644 src/tea/legacy/associations/ados2/api.py create mode 100644 src/tea/legacy/biomarkers/spikes/_density.py diff --git a/README.md b/README.md index aa579c6..b8018a5 100644 --- a/README.md +++ b/README.md @@ -49,15 +49,30 @@ pipe.biomarker("posterior_rhythm").measure(study) table = pipe.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=("posterior_rhythm", "spindles")) # Dask: LocalCluster, or scheduler= rhythm = pipe.biomarker("posterior_rhythm").train(table) # baseline: curves or age_blocks -rhythm.predict(table.iloc[[0]]) # outside -1/0/+1, z +rhythm.predict(table.iloc[[0]]) # outside -1/0/+1 (NaN: no reference), z from tea.serving import log_plan, log_biomarker # MLflow models, privacy guard ``` +```python +from tea.pipeline import registry +assoc = registry.association("ados2_association").fit(cohort) # or impl="legacy" +assoc.associations() # odds ratio per unit of z, interval, p, q; per pair +assoc.score(cohort) # each child's probability of the outcome event +``` + Replace a module: `pipe.replace("spindle_detection", MyDetector())`, or register it under the same name in the `tea.modules` entry-point group. Check it with `tea.contracts.testing`. +## Associations + +Cohort-level models of EEG findings against a clinical outcome run outside the per-study pipeline and register in +`tea.associations` / `tea.legacy_associations`. `ados2_association` relates each zone's z (spike and spindle +densities per scalp zone, `tea.contracts.ZONES`), the posterior rhythm's and the gradient's z with ADOS-2 items +(Firth logistic) or the CSS (ordinal), adjusted for age and module; legacy is the research code vendored unchanged. +The cohort's columns and the outputs are in `tea.associations.ados2.api` and `tea.contracts`. + ## Install Python ≥ 3.12. As a git submodule of another project: diff --git a/pyproject.toml b/pyproject.toml index a1b9e47..aa87134 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "tea" -version = "0.2.0" +version = "0.3.0" description = "Modular EEG biomarker library for TEA: validation, preprocessing, processes and biomarkers, each a replaceable module" readme = "README.md" authors = [ @@ -64,6 +64,12 @@ spindle_topography = "tea.biomarkers.spindle_topography:MODULE" spikes = "tea.biomarkers.spikes:MODULE" window_selection = "tea.processes.window_selection:MODULE" +[project.entry-points."tea.associations"] +ados2_association = "tea.associations.ados2:MODULE" + +[project.entry-points."tea.legacy_associations"] +ados2_association = "tea.legacy.associations.ados2:MODULE" + [project.entry-points."tea.executors"] legacy = "tea.legacy.executor:run_serial" diff --git a/src/tea/__init__.py b/src/tea/__init__.py index 54d0487..12d6770 100644 --- a/src/tea/__init__.py +++ b/src/tea/__init__.py @@ -6,4 +6,4 @@ Every biomarker and every process is its own module. Modules talk only through `tea.contracts`; see the architecture plan. """ -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/src/tea/associations/__init__.py b/src/tea/associations/__init__.py new file mode 100644 index 0000000..ff0c2ee --- /dev/null +++ b/src/tea/associations/__init__.py @@ -0,0 +1 @@ +"""Cohort-level associations of EEG findings with clinical outcomes, outside the per-study pipeline.""" diff --git a/src/tea/associations/ados2/__init__.py b/src/tea/associations/ados2/__init__.py new file mode 100644 index 0000000..43537bf --- /dev/null +++ b/src/tea/associations/ados2/__init__.py @@ -0,0 +1,3 @@ +from tea.associations.ados2.api import MODULE, Ados2Association + +__all__ = ["MODULE", "Ados2Association"] diff --git a/src/tea/associations/ados2/_items.py b/src/tea/associations/ados2/_items.py new file mode 100644 index 0000000..22ca1e0 --- /dev/null +++ b/src/tea/associations/ados2/_items.py @@ -0,0 +1,118 @@ +""" +The ADOS-2 algorithm items grouped by what they measure, and the pairs of EEG predictor and ADOS-2 outcome the +association tests. One code is not one item across modules (`sa_b5` is gaze integration in the Toddler module, +shared enjoyment in Module 1 and showing in Module 2), so each item has a code per module and a module-independent +code (`ados2_item_06`) that the outcomes carry. + +Source: the ADOS-2 manual (Toddler, Modules 1 and 2), Part I and Part II; zone and item pairs from the EEG +alteration table of the TEA research protocol. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from tea.contracts import ZONES + +MODULES = ("TODDLER", "MODULO_1", "MODULO_2") + +# Item number: (label, algorithm domain, code per module; a module without the item leaves it out). +ITEMS = { + 1: ("Vocalización espontánea dirigida a otros", "SA", {"TODDLER": "sa_a2", "MODULO_1": "sa_a2"}), + 2: ("Señalar", "SA", {"TODDLER": "sa_a7", "MODULO_1": "sa_a7", "MODULO_2": "sa_a6"}), + 3: ("Gestos", "SA", {"TODDLER": "sa_a8", "MODULO_1": "sa_a8", "MODULO_2": "sa_a7"}), + 4: ("Contacto visual inusual", "SA", {"TODDLER": "sa_b1", "MODULO_1": "sa_b1", "MODULO_2": "sa_b1"}), + 5: ("Expresiones faciales dirigidas a otros", "SA", {"TODDLER": "sa_b4", "MODULO_1": "sa_b3", + "MODULO_2": "sa_b2"}), + 6: ("Integración de la mirada con otras conductas", "SA", {"TODDLER": "sa_b5", "MODULO_1": "sa_b4"}), + 7: ("Disfrute compartido en la interacción", "SA", {"TODDLER": "sa_b6", "MODULO_1": "sa_b5", + "MODULO_2": "sa_b3"}), + 8: ("Respuesta al nombre", "SA", {"TODDLER": "sa_b7"}), + 9: ("Búsqueda de atención cuando se le ignora", "SA", {"TODDLER": "sa_b8"}), + 10: ("Pedir", "SA", {"TODDLER": "sa_b9"}), + 11: ("Mostrar", "SA", {"TODDLER": "sa_b12", "MODULO_1": "sa_b9", "MODULO_2": "sa_b5"}), + 12: ("Iniciación espontánea de la atención conjunta", "SA", {"TODDLER": "sa_b13", "MODULO_1": "sa_b10", + "MODULO_2": "sa_b6"}), + 13: ("Respuesta a la atención conjunta", "SA", {"TODDLER": "sa_b14", "MODULO_1": "sa_b11"}), + 14: ("Calidad de los acercamientos sociales", "SA", {"TODDLER": "sa_b15", "MODULO_1": "sa_b12", + "MODULO_2": "sa_b8"}), + 15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"TODDLER": "sa_b16b"}), + 16: ("Cantidad de comunicación social recíproca", "SA", {"MODULO_2": "sa_b11"}), + 17: ("Calidad general de la relación", "SA", {"TODDLER": "sa_b18", "MODULO_2": "sa_b12"}), + 18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"TODDLER": "rrb_a3", "MODULO_1": "rrb_a3"}), + 19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"MODULO_1": "rrb_a5", "MODULO_2": "rrb_a4"}), + 20: ("Interés sensorial inusual", "RRB", {"TODDLER": "rrb_d1", "MODULO_1": "rrb_d1", "MODULO_2": "rrb_d1"}), + 21: ("Manierismos de manos y dedos", "RRB", {"TODDLER": "rrb_d2", "MODULO_1": "rrb_d2", "MODULO_2": "rrb_d2"}), + 22: ("Intereses repetitivos o conductas estereotipadas", "RRB", {"TODDLER": "rrb_d5", "MODULO_1": "rrb_d4", + "MODULO_2": "rrb_d4"}), +} + +# Items each zone's spike density is paired with. +ZONE_ITEMS = { + "frontal_izq": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16), + "frontal_der": (4, 5, 7, 14, 22), + "frontal_media": (6, 11, 12, 13, 14), + "central": (21,), + "parietal": (6, 13, 20), + "temporal_izq": (1, 16, 18, 19), + "temporal_der": (4, 5, 8), + "occipital": (4, 20), +} +SPINDLE_ZONES = ("frontal_izq", "frontal_der", "frontal_media", "central", "parietal") +RHYTHM_ITEMS = (20, 22) + +# The domain outcome: the total calibrated severity score (1 to 10), high from 8 (Gotham 2009; Hus 2014). +CSS = "CSS" +CSS_HIGH = 8 +ALTERED = 1 # an item is altered from algorithm score 1 + + +def item_code(n: int) -> str: + """The module-independent outcome code of item `n`.""" + return f"ados2_item_{n:02d}" + + +def pairs(level: str) -> list[dict]: + """The pairs tested. `level` "item": spike zones and the posterior rhythm against items, spindles and gradient + against the CSS; "domain": everything against the CSS. Each pair: biomarker, zone, predictor column, outcome + kind ("item" or "domain") and outcome (item number or `CSS`).""" + out = [] + for zone in ZONES: + outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)] + out += [{"biomarker": "spikes", "zone": zone, "predictor": f"z_spikes_{zone}", "kind": k, "outcome": o} + for k, o in outcomes] + out += [{"biomarker": "spindles", "zone": zone, "predictor": f"z_spindles_{zone}", "kind": "domain", + "outcome": CSS} for zone in SPINDLE_ZONES] + rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)] + out += [{"biomarker": "posterior_rhythm", "zone": "posterior", "predictor": "z_posterior_rhythm", "kind": k, + "outcome": o} for k, o in rhythm] + out.append({"biomarker": "gradient", "zone": "global", "predictor": "z_gradient", "kind": "domain", + "outcome": CSS}) + return out + + +def algorithm_score(v) -> pd.Series: + """Protocol code to algorithm score: 3 is 2; 7, 8 and 9 are 0; 0, 1 and 2 stay.""" + v = pd.to_numeric(pd.Series(v), errors="coerce") + return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2) + + +def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series: + """Item `n`'s algorithm score (0 to 2) for each child, read from the column of the child's module. NaN when the + item is not in that module's algorithm or has no value.""" + out = pd.Series(np.nan, index=cohort.index) + if "ados_module" not in cohort: + return out + module = cohort["ados_module"].astype(str).str.upper() + for m, code in ITEMS[n][2].items(): + if code in cohort: + chosen = module == m + out[chosen] = algorithm_score(cohort.loc[chosen, code]).to_numpy() + return out + + +def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool: + """Whether at least `minimum` children have some item score.""" + scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1) + return int(scores.notna().any(axis=1).sum()) >= minimum diff --git a/src/tea/associations/ados2/_models.py b/src/tea/associations/ados2/_models.py new file mode 100644 index 0000000..c9bcccb --- /dev/null +++ b/src/tea/associations/ados2/_models.py @@ -0,0 +1,279 @@ +""" +Odds ratios of a continuous EEG z with an ADOS-2 outcome for small cohorts, with the fitted state needed to score +other children. + +- `firth`: logistic regression with Firth's penalty (Jeffreys prior) for a yes/no outcome. It corrects the + small-sample bias and stays finite under separation (Heinze and Schemper 2002, Stat Med 21:2409). Interval and p + by profiled penalised likelihood; probabilities with the FLIC intercept correction (Puhr et al. 2017, Stat Med + 36:2302), which keeps the odds ratio and makes the mean probability the observed proportion. +- `ordinal`: proportional-odds ordinal logistic regression by maximum likelihood, interval and p by profiled + likelihood. The odds ratio is that of a higher level. + +Both give the odds ratio per unit of z, adjusted for the covariates. `logistf` (R) is the authors' reference. +""" + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field + +import numpy as np +import pandas as pd +from scipy import optimize, stats +from scipy.special import expit + +CHI2_95 = float(stats.chi2.ppf(0.95, 1)) +MIN_ROWS = 8 + + +@dataclass +class Design: + """How a table becomes the design matrix: intercept, predictor (uncentred, z = 0 is the reference median), + numeric adjustments centred on their mean, categorical ones as indicators against the most frequent level. + Adjustments that do not vary are left out.""" + + predictor: str + numeric: dict[str, float] = field(default_factory=dict) + categorical: dict[str, list[str]] = field(default_factory=dict) # the indicator levels, by adjustment + reference: dict[str, str] = field(default_factory=dict) # the reference level, by adjustment + + @classmethod + def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design: + d = cls(predictor) + for a in adjust: + if a not in t: + continue + v = t[a] + if pd.api.types.is_numeric_dtype(v): + v = v.astype(float) + if v.std() > 0: + d.numeric[a] = float(v.mean()) + else: + ref = v.value_counts().index[0] + levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)] + if levels: + d.categorical[a] = [str(lv) for lv in levels] + d.reference[a] = str(ref) + return d + + @property + def names(self) -> list[str]: + return (["intercept", self.predictor, *self.numeric] + + [f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels]) + + def matrix(self, t: pd.DataFrame) -> np.ndarray: + """X for `t`. A row missing a covariate, or with a level the fit never saw, is NaN.""" + cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)] + for a, mean in self.numeric.items(): + cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan)) + for a, levels in self.categorical.items(): + v = t[a].astype(str) if a in t else pd.Series([None] * len(t)) + for lv in levels: + cols.append((v == lv).to_numpy(float)) + X = np.column_stack(cols) + known = np.ones(len(t), bool) + for a, levels in self.categorical.items(): + seen = {self.reference[a], *levels} + known &= t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy() if a in t else False + X[~known] = np.nan + return X + + def to_dict(self) -> dict: + return {"predictor": self.predictor, "numeric": self.numeric, "categorical": self.categorical, + "reference": self.reference} + + @classmethod + def from_dict(cls, d: dict) -> Design: + return cls(d["predictor"], dict(d["numeric"]), {k: list(v) for k, v in d["categorical"].items()}, + dict(d["reference"])) + + +# Firth +def _pl(b, X, y): + """Firth's penalised log-likelihood: l(b) + log|X'WX| / 2.""" + eta = X @ b + p = expit(eta) + w = p * (1 - p) + sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None])) + if sign <= 0: + return -np.inf + return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet) + + +def _score(b, X, y): + """Firth's modified score X'(y - p + h(1/2 - p)), h the hat matrix diagonal, and the information.""" + p = expit(X @ b) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w + return X.T @ (y - p + h * (0.5 - p)), info + + +def _fit_firth(X, y, max_iter=200, tol=1e-10): + b = np.zeros(X.shape[1]) + pl = _pl(b, X, y) + for _ in range(max_iter): + U, info = _score(b, X, y) + step = np.linalg.solve(info, U) + t = 1.0 + while t > 1e-8: + nb = b + t * step + npl = _pl(nb, X, y) + if npl >= pl - 1e-12: + break + t /= 2 + b, pl = nb, npl + if np.max(np.abs(t * step)) < tol: + break + return b, pl + + +def _profile_firth(value, j, X, y, b0): + free = [k for k in range(X.shape[1]) if k != j] + + def f(bf): + b = np.empty(X.shape[1]) + b[free], b[j] = bf, value + v = _pl(b, X, y) + if not np.isfinite(v): + return 1e10, np.zeros(len(free)) + U, _ = _score(b, X, y) + return -v, -U[free] + + return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun) + + +def _interval(profile, centre, maximum, scale): + """Profile likelihood interval: where 2 (max - profile) reaches the 95 % chi-square with one degree.""" + g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731 + limits = [] + for sign in (-1, 1): + previous, limit = centre, sign * np.inf + for k in range(1, 80): + v = centre + sign * scale * k + if g(v) > 0: + limit = optimize.brentq(g, min(previous, v), max(previous, v)) + break + previous = v + limits.append(limit) + return limits[0], limits[1] + + +def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict: + return {"model": model, "n": n, "coef": round(float(coef), 4), "odds_ratio": round(float(np.exp(coef)), 4), + "ci_low": round(float(np.exp(lo)), 4), "ci_high": round(float(np.exp(hi)), 4), "p": round(p, 5), + "adjusted_for": ", ".join(design.names[2:]), "reason": "", **extra, + "state": {"design": design.to_dict(), **state}} + + +def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict: + """Firth logistic regression of `outcome` (0/1) on `predictor`, adjusted: n, events, odds ratio per unit of z, + profiled 95 % interval, penalised likelihood-ratio p, and the state `firth_probability` scores with.""" + d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna() + y = d[outcome].to_numpy(float) + out = {"model": "firth", "n": len(d), "events": int(y.sum())} + if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0: + return {**out, "reason": "too few data or no variation"} + design = Design.of(d, predictor, adjust) + X = design.matrix(d) + b, pl = _fit_firth(X, y) + _, info = _score(b, X, y) + se = float(np.sqrt(np.linalg.inv(info)[1, 1])) + profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731 + lo, hi = _interval(profile, b[1], pl, max(se, 0.05)) + p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1)) + eta = X[:, 1:] @ b[1:] + flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) + return _summary("firth", len(d), b[1], lo, hi, p, design, + {"beta": [float(v) for v in b[1:]], "intercept": float(flic)}, events=int(y.sum())) + + +def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray: + X = Design.from_dict(state["design"]).matrix(t) + return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"])) + + +def firth_reference(state: dict) -> float: + """The probability at z = 0 with the covariates at their reference: mean age, most frequent level.""" + return float(expit(state["intercept"])) + + +# Ordinal (proportional odds) +def _nll_ordinal(par, X, yk, K): + theta = np.cumsum(np.r_[par[0], np.exp(par[1:K - 1])]) + eta = X @ par[K - 1:] + n = len(yk) + cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)] + pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk] + return -float(np.sum(np.log(np.clip(pr, 1e-300, None)))) + + +def _fit_ordinal(X, yk, K, fixed=None): + """Minimum of the negative log-likelihood; `fixed` = (j, value) holds coefficient j of X (the profile).""" + start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])] + if fixed is None: + r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS") + return r.x, float(r.fun) + j, value = fixed + idx = [k for k in range(len(start)) if k != K - 1 + j] + + def f(q): + par = np.empty(len(start)) + par[idx], par[K - 1 + j] = q, value + return _nll_ordinal(par, X, yk, K) + + return None, float(optimize.minimize(f, start[idx], method="BFGS").fun) + + +def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict: + """Ordinal logistic regression of `outcome` (ordered levels): odds ratio of a higher level per unit of z, + profiled interval, likelihood-ratio p, and the state `ordinal_probability` scores P(outcome >= high) with.""" + d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna() + levels = np.sort(d[outcome].unique()) + out = {"model": "ordinal", "n": len(d), "levels": len(levels)} + if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0: + return {**out, "reason": "too few data or no variation"} + design = Design.of(d, predictor, adjust) + X = design.matrix(d)[:, 1:] # the thresholds are the intercept + K = len(levels) + yk = np.searchsorted(levels, d[outcome].to_numpy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + par, nll = _fit_ordinal(X, yk, K) + beta = par[K - 1:] + if abs(beta[0]) > 20: + return {**out, "reason": "does not converge (separation)"} + profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731 + lo, hi = _interval(profile, beta[0], -nll, 0.1) + p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1)) + theta = np.cumsum(np.r_[par[0], np.exp(par[1:K - 1])]) + k = int(np.searchsorted(levels, high)) # first level at or above `high` + return _summary("ordinal", len(d), beta[0], lo, hi, p, design, + {"beta": [float(v) for v in beta], "threshold": float(theta[k - 1]) if 0 < k < K else None, + "always": None if 0 < k < K else float(k == 0)}, levels=K) + + +def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray: + X = Design.from_dict(state["design"]).matrix(t)[:, 1:] + if state["threshold"] is None: + return np.where(np.isnan(X).any(axis=1), np.nan, state["always"]) + return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"])) + + +def ordinal_reference(state: dict) -> float: + """P(outcome >= high) at z = 0 with the covariates at their reference.""" + return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"])) + + +def bh(p) -> np.ndarray: + """Benjamini-Hochberg q values; NaN stays NaN.""" + p = np.asarray(p, dtype=float) + q = np.full(len(p), np.nan) + ok = np.isfinite(p) + if ok.any(): + v = p[ok] + o = np.argsort(v) + r = v[o] * len(v) / np.arange(1, len(v) + 1) + r = np.minimum.accumulate(r[::-1])[::-1] + q[np.flatnonzero(ok)[o]] = np.minimum(r, 1) + return q diff --git a/src/tea/associations/ados2/api.py b/src/tea/associations/ados2/api.py new file mode 100644 index 0000000..235b3a9 --- /dev/null +++ b/src/tea/associations/ados2/api.py @@ -0,0 +1,162 @@ +""" +The ADOS-2 association: how strongly an EEG alteration in a scalp zone (its continuous z against the age baseline) +goes with an ADOS-2 item or with the severity score, in a cohort of children who all have the diagnosis. It does +not predict autism. + +Two levels, chosen from the cohort (`level="auto"`): +- item, when the cohort has item scores: Firth logistic of "item altered" (algorithm score >= 1) for spike zones + and the posterior rhythm, ordinal of the item's 0/1/2 as sensitivity; +- domain: ordinal of the CSS, Firth of "CSS >= 8" as sensitivity. +Spindles and the gradient always go against the CSS. Every model is adjusted for age and ADOS-2 module; q values +are Benjamini-Hochberg within each biomarker. + +The cohort is one row per child: `key`, `age_months`, `ados_module` (TODDLER, MODULO_1, MODULO_2), the item scores +by their per-module codes (`sa_a2`... `rrb_d5`), `css` (1 to 10), and the predictors `z_spikes_`, +`z_spindles_`, `z_posterior_rhythm`, `z_gradient` (zones of `tea.contracts.ZONES`). Nothing per child leaves +`associations()`; `score()` gives each child's probability. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd + +from tea.contracts import ASSOCIATION_COLUMNS, CONTRACT_VERSION, SCORE_COLUMNS + +from . import _items as it +from . import _models as mo + +ADJUST = ("age_months", "ados_module") + + +def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]: + """The pair's principal outcome and the ordinal one: item altered and item score, or CSS high and CSS.""" + if pair["kind"] == "item": + score = it.item_scores(cohort, pair["outcome"]) + return (score >= it.ALTERED).astype(float).where(score.notna()), score + css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce") + return (css >= it.CSS_HIGH).astype(float).where(css.notna()), css + + +def _guarded(fit, model: str, *args, **kwargs) -> dict: + """One fit, or a row with its reason when the design is singular: one pair never stops the others.""" + try: + return fit(*args, **kwargs) + except (np.linalg.LinAlgError, ValueError) as error: + return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} + + +def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]: + """Principal and sensitivity fits: Firth then ordinal for an item, ordinal then Firth for the CSS.""" + p = pair["predictor"] + firth = lambda: _guarded(mo.firth, "firth", d, "_yes", p, ADJUST) # noqa: E731 + if pair["kind"] == "item": + return firth(), _guarded(mo.ordinal, "ordinal", d, "_level", p, ADJUST, high=it.ALTERED) + return _guarded(mo.ordinal, "ordinal", d, "_level", p, ADJUST, high=it.CSS_HIGH), firth() + + +def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: + """Each row's probability of the event, and the reference probability (z = 0, covariates at reference).""" + if fit["model"] == "firth": + return mo.firth_probability(fit["state"], t), mo.firth_reference(fit["state"]) + return mo.ordinal_probability(fit["state"], t), mo.ordinal_reference(fit["state"]) + + +class Ados2Association: + name = "ados2_association" + version = "0.1.0" + contract_version = CONTRACT_VERSION + impl = "modern" + + def __init__(self, level: str = "auto", fitted: dict | None = None): + if level not in ("auto", "item", "domain"): + raise ValueError(f"level must be auto, item or domain, not {level!r}") + self.level = level + self.fitted = fitted + + def fit(self, cohort: pd.DataFrame) -> Ados2Association: + level = self.level if self.level != "auto" else ("item" if it.has_items(cohort) else "domain") + rows = [] + for pair in it.pairs(level): + if pair["predictor"] not in cohort: + continue + d = cohort.copy() + d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan) + d["_yes"], d["_level"] = _outcome(cohort, pair) + principal, sensitivity = _models(d, pair) + rows.append({**pair, "principal": principal, "sensitivity": sensitivity}) + q = np.full(len(rows), np.nan) + biomarkers = np.array([r["biomarker"] for r in rows]) + p = np.array([r["principal"].get("p", np.nan) for r in rows], float) + for b in dict.fromkeys(biomarkers): + q[biomarkers == b] = mo.bh(p[biomarkers == b]).round(5) + for r, v in zip(rows, q): + r["q"] = None if np.isnan(v) else float(v) + self.fitted = {"level": level, "n": len(cohort), "rows": rows} + return self + + def _rows(self) -> list[dict]: + if self.fitted is None: + raise ValueError(f"{self.name}: fit() before associations() or score()") + return self.fitted["rows"] + + def associations(self) -> pd.DataFrame: + """One row per pair tested: the cohort's odds ratio per unit of z, interval, p and q, and the sensitivity + model's odds ratio and whether it points the same way.""" + out = [] + for r in self._rows(): + f, s = r["principal"], r["sensitivity"] + kind = r["kind"] + ors, sens = f.get("odds_ratio"), s.get("odds_ratio") + out.append({ + "biomarker": r["biomarker"], "zone": r["zone"], "kind": kind, "outcome": r["outcome"], + "outcome_code": it.item_code(r["outcome"]) if kind == "item" else it.CSS, + "event": f">={it.ALTERED if kind == 'item' else it.CSS_HIGH}", "model": f["model"], + "n": f["n"], "odds_ratio": ors, "ci_low": f.get("ci_low"), "ci_high": f.get("ci_high"), + "p": f.get("p"), "q": r["q"], "sens_model": s["model"], "sens_odds_ratio": sens, + "same_direction": (None if ors is None or sens is None + else bool(np.sign(ors - 1) == np.sign(sens - 1))), + "reason": f.get("reason", ""), + }) + return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS)) + + def score(self, cohort: pd.DataFrame) -> pd.DataFrame: + """Each child's z and probability of the event, with the pair's reference probability (z = 0, mean age, most + frequent module), for every estimated pair whose outcome exists in the child's module.""" + parts = [] + for r in self._rows(): + f = r["principal"] + if f.get("odds_ratio") is None or r["predictor"] not in cohort: + continue + t = cohort + if r["kind"] == "item": + modules = set(it.ITEMS[r["outcome"]][2]) + t = cohort[cohort["ados_module"].astype(str).str.upper().isin(modules)] + t = t[t[r["predictor"]].notna()] + if not len(t): + continue + prob, ref = _probability(f, t) + kept = np.isfinite(prob) + parts.append(pd.DataFrame({ + "key": t["key"].to_numpy()[kept], "biomarker": r["biomarker"], "zone": r["zone"], + "outcome_code": it.item_code(r["outcome"]) if r["kind"] == "item" else it.CSS, + "z": t[r["predictor"]].to_numpy(float)[kept], "probability": prob[kept].round(4), + "reference_probability": round(ref, 4)})) + if not parts: + return pd.DataFrame(columns=list(SCORE_COLUMNS)) + return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)] + + def save(self, path) -> None: + Path(path, "association.json").write_text(json.dumps( + {"level": self.level, "fitted": self.fitted}, default=float)) + + @classmethod + def load(cls, path) -> Ados2Association: + d = json.loads(Path(path, "association.json").read_text()) + return cls(d["level"], d["fitted"]) + + +MODULE = Ados2Association() diff --git a/src/tea/biomarkers/aperiodic/_baseline.py b/src/tea/biomarkers/aperiodic/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/biomarkers/aperiodic/_baseline.py +++ b/src/tea/biomarkers/aperiodic/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/aperiodic/api.py b/src/tea/biomarkers/aperiodic/api.py index 0d8e3f5..7fa6d95 100644 --- a/src/tea/biomarkers/aperiodic/api.py +++ b/src/tea/biomarkers/aperiodic/api.py @@ -100,7 +100,7 @@ def exponent(f, spectrum) -> float: class Aperiodic: name = "aperiodic" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("sleep_state", "annotation_mask") features = FEATURES diff --git a/src/tea/biomarkers/coupling/_baseline.py b/src/tea/biomarkers/coupling/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/coupling/_baseline.py +++ b/src/tea/biomarkers/coupling/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/coupling/api.py b/src/tea/biomarkers/coupling/api.py index 053dd8c..7eed900 100644 --- a/src/tea/biomarkers/coupling/api.py +++ b/src/tea/biomarkers/coupling/api.py @@ -68,7 +68,7 @@ def phases(raw, sp, slow=None): class Coupling: name = "coupling" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("spindle_detection",) features = FEATURES diff --git a/src/tea/biomarkers/gradient/_baseline.py b/src/tea/biomarkers/gradient/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/gradient/_baseline.py +++ b/src/tea/biomarkers/gradient/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/gradient/api.py b/src/tea/biomarkers/gradient/api.py index 31ab212..bdcfdb3 100644 --- a/src/tea/biomarkers/gradient/api.py +++ b/src/tea/biomarkers/gradient/api.py @@ -72,7 +72,7 @@ def slopes(raw, starts, window_s=4.0) -> dict: class Gradient: name = "gradient" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("sleep_state",) features = FEATURES diff --git a/src/tea/biomarkers/mse/_baseline.py b/src/tea/biomarkers/mse/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/biomarkers/mse/_baseline.py +++ b/src/tea/biomarkers/mse/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/mse/api.py b/src/tea/biomarkers/mse/api.py index 4df5684..ea3d3d9 100644 --- a/src/tea/biomarkers/mse/api.py +++ b/src/tea/biomarkers/mse/api.py @@ -66,7 +66,7 @@ def mse_curve(x) -> np.ndarray: class MSE: name = "mse" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("sleep_state", "annotation_mask") features = FEATURES diff --git a/src/tea/biomarkers/posterior_rhythm/_baseline.py b/src/tea/biomarkers/posterior_rhythm/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/posterior_rhythm/_baseline.py +++ b/src/tea/biomarkers/posterior_rhythm/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/posterior_rhythm/api.py b/src/tea/biomarkers/posterior_rhythm/api.py index 5da88fd..61b698f 100644 --- a/src/tea/biomarkers/posterior_rhythm/api.py +++ b/src/tea/biomarkers/posterior_rhythm/api.py @@ -79,7 +79,7 @@ def rhythm(raw, starts, min_windows=MIN_WINDOWS) -> dict: class PosteriorRhythm: name = "posterior_rhythm" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("sleep_state",) features = ("posterior_rhythm_hz",) diff --git a/src/tea/biomarkers/slow_waves/_baseline.py b/src/tea/biomarkers/slow_waves/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/slow_waves/_baseline.py +++ b/src/tea/biomarkers/slow_waves/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/slow_waves/api.py b/src/tea/biomarkers/slow_waves/api.py index 098c1a7..da739a4 100644 --- a/src/tea/biomarkers/slow_waves/api.py +++ b/src/tea/biomarkers/slow_waves/api.py @@ -21,7 +21,7 @@ FEATURES = ("slow_wave_frac_n3", "slow_wave_density", "slow_wave_frequency_hz", class SlowWaves: name = "slow_waves" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("slow_wave_staging",) features = FEATURES diff --git a/src/tea/biomarkers/spikes/_baseline.py b/src/tea/biomarkers/spikes/_baseline.py index f70c368..9a42c31 100644 --- a/src/tea/biomarkers/spikes/_baseline.py +++ b/src/tea/biomarkers/spikes/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, @@ -227,7 +229,95 @@ class AgeBlockZ: return cls(d["edad_min"], d["edad_max"], d["state"]) -BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ} +# ------------------------------------------------------------------ counts against their minutes +class CountRate: + """Spike candidates against the minutes they were looked for in, as the research reference of candidates + (biomarcadores-tea/biomarcadores/picos_ref.py @ 366f7e1: referencia, percentil). Most children of the reference + have none, so a centile curve collapses at 0; here the reference is the aggregate rate per minute of the children + within `edad_min`..`edad_max` and its dispersion between children (negative binomial by moments, Poisson when + there is none). + + A value is a rate: its count is value x exposure x `scale` (`scale` the electrodes a per-electrode zone value + was divided by). z = Phi^-1(1 - mid-p), the mid-p tail of seeing that many or more in the child's own minutes, + clipped to +-Z_MAX; outside = +1 when P(N >= n) < 0.05, else 0. No exposure, value or reference: NaN. + """ + + name = "count_rate" + Z_MAX = 8.0 + + def __init__(self, edad_min=16.0, edad_max=37.0, scale=1.0, state=None): + self.edad_min = float(edad_min) + self.edad_max = float(edad_max) + self.scale = float(scale) + self.state = state + + def _counts(self, values, exposure): + x = np.asarray(exposure, float) * self.scale + return np.round(np.asarray(values, float) * x), x + + def fit(self, values, ages_months, exposure=None): + e = np.asarray(ages_months, float) + if exposure is None: + exposure = np.full(len(e), np.nan) + n, x = self._counts(values, exposure) + keep = np.isfinite(n) & np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + n, x = n[keep], x[keep] + rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") + mu = rate * x + excess = float(((n - mu) ** 2 - n).sum()) + k = float((mu ** 2).sum() / excess) if excess > 0 else float("inf") + self.state = {"rate": rate, "k": k, "reference": int(keep.sum()), "events": int(n.sum())} + return self + + def deviation(self, values, ages_months, exposure=None): + from scipy import stats + + e = np.asarray(ages_months, float) + z = np.full(len(e), np.nan) + outside = np.full(len(e), np.nan) + rate = (self.state or {}).get("rate", float("nan")) + if exposure is None or not np.isfinite(rate): + return outside, z + n, x = self._counts(values, exposure) + ok = np.isfinite(n) & np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + mu, k = rate * x[ok], self.state["k"] + if np.isfinite(k): + p = k / (k + mu) + tail, at = stats.nbinom.sf(n[ok] - 1, k, p), stats.nbinom.pmf(n[ok], k, p) + else: + tail, at = stats.poisson.sf(n[ok] - 1, mu), stats.poisson.pmf(n[ok], mu) + z[ok] = np.clip(stats.norm.ppf(1 - (tail - at / 2)), -self.Z_MAX, self.Z_MAX) + outside[ok] = np.where(tail < 0.05, 1.0, 0.0) + return outside, z + + def percentiles(self, ages_months, exposure, q=(0.05, 0.5, 0.95)): + """The rates at the quantiles `q` of the reference's count in each child's own minutes, one row per child + and one column per quantile; NaN where z would be.""" + from scipy import stats + + e = np.asarray(ages_months, float) + out = np.full((len(e), len(q)), np.nan) + rate = (self.state or {}).get("rate", float("nan")) + if exposure is None or not np.isfinite(rate): + return out + x = np.asarray(exposure, float) * self.scale + ok = np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + mu, k = rate * x[ok], self.state["k"] + for j, p in enumerate(q): + counts = (stats.nbinom.ppf(p, k, k / (k + mu)) if np.isfinite(k) else stats.poisson.ppf(p, mu)) + out[ok, j] = counts / x[ok] + return out + + def to_dict(self): + return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, "scale": self.scale, + "state": self.state} + + @classmethod + def from_dict(cls, d): + return cls(d["edad_min"], d["edad_max"], d.get("scale", 1.0), d["state"]) + + +BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ, "count_rate": CountRate} def make(name, **params): diff --git a/src/tea/biomarkers/spikes/_density.py b/src/tea/biomarkers/spikes/_density.py new file mode 100644 index 0000000..6c6cf9b --- /dev/null +++ b/src/tea/biomarkers/spikes/_density.py @@ -0,0 +1,214 @@ +""" +Spike density by electrode and zone, and state inheritance, on the modern +detector: which candidates count as useful (a field and no normal-graphoelement +mark), the per-electrode and per-zone density per state, and the inherited +variant where a stretch without a clean-window state takes the nearest labeled +window's state (30 s reach, conservative on state transitions). + +Ported from the research repo's medidas_director.py (estados_con_herencia, +categoria_candidato, _puerta, minutos_por_origen and the por_canal table of +picos) onto tea's own study objects. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from tea.contracts import ZONES + +from ._signal import VECINOS_1020 + +GRID_S = 0.5 +STATES = {"nrem": ("sueno",), "awake": ("vigilia", "somnolencia")} + + +def inherit_states(labeled, duration_s, inherit_s=30.0, t_min=0.0) -> pd.DataFrame: + """State intervals on a 0.5 s grid: a point keeps its clean-window state; + an unlabeled point from `t_min` (and from the first labeled window) takes + the nearest labeled window's state when it is within `inherit_s`. When the + nearest windows before and after carry different states, the stretch stays + 'transicion' (it counts in neither state). Columns: t_ini_s, t_fin_s, + etiqueta, heredado; no overlaps.""" + cols = ["t_ini_s", "t_fin_s", "etiqueta", "heredado"] + if not len(labeled): + return pd.DataFrame(columns=cols) + paso = GRID_S + t = np.arange(0.0, float(duration_s), paso) + etq = np.full(len(t), "", dtype=object) + filas = sorted(zip(labeled.t_ini_s.astype(float), labeled.t_fin_s.astype(float), + labeled.etiqueta.astype(str))) + for t0, t1, e in filas: + m = (t >= t0) & (t < t1) & (etq == "") + etq[m] = e + directo = etq != "" + heredado = np.zeros(len(t), dtype=bool) + if directo.any() and inherit_s > 0: + td = t[directo] + inicio = max(float(t_min or 0.0), float(td[0])) + faltan = np.flatnonzero(~directo & (t >= inicio)) + if len(faltan): + ed = etq[directo] + tf = t[faltan] + j = np.searchsorted(td, tf) + hay_a, hay_d = j > 0, j < len(td) + ia, idp = np.clip(j - 1, 0, len(td) - 1), np.clip(j, 0, len(td) - 1) + da = np.where(hay_a, tf - td[ia], np.inf) + dd = np.where(hay_d, td[idp] - tf, np.inf) + transicion = hay_a & hay_d & (ed[ia] != ed[idp]) + lab = np.where(da <= dd, ed[ia], ed[idp]) + ok = ~transicion & (np.minimum(da, dd) <= inherit_s) + etq[faltan[ok]] = lab[ok] + heredado[faltan[ok]] = True + etq[faltan[transicion]] = "transicion" + heredado[faltan[transicion]] = True + filas, k = [], 0 + while k < len(t): + if etq[k] == "": + k += 1 + continue + j = k + while j + 1 < len(t) and etq[j + 1] == etq[k] and heredado[j + 1] == heredado[k]: + j += 1 + filas.append({"t_ini_s": float(t[k]), "t_fin_s": float(t[j] + paso), + "etiqueta": etq[k], "heredado": bool(heredado[k])}) + k = j + 1 + return pd.DataFrame(filas, columns=cols) + + +def candidate_category(ev) -> np.ndarray: + """One category per candidate: 'util' (a field and no mark), else the + first matching mark in the director's order (posts, vertice, ocular) or + 'aislado' when there is no field at all.""" + cat = np.full(len(ev), "util", dtype=object) + if not len(ev): + return cat + cat[(ev.vecinos == 0).to_numpy()] = "aislado" + for marca in ("posts", "vertice", "ocular"): + cat[ev[marca].to_numpy(bool)] = marca + return cat + + +def useful(ev) -> pd.DataFrame: + """The candidates that count for densities: with field, no mark.""" + if not len(ev): + return ev + return ev[~ev.vertice & ~ev.posts & ~ev.ocular & (ev.vecinos > 0)] + + +def gate_windows(est, channels, vent_s, reject_transient) -> pd.DataFrame: + """The detector's 2 s quality-gate windows over the whole recording, with + the same rejection rule as de_estudio (muscle, frozen, gap, annotated + state; a transient only when `reject_transient`). Columns include apta.""" + from . import _selection + + sel = _selection.seleccionar(est, vent_s=vent_s, paso_s=vent_s, canales=channels) + mot = sel.motivo.fillna("").astype(str) + bad = mot.str.contains("musculo|congelada|hueco|estado |caballo", regex=True) + if reject_transient: + bad = bad | mot.str.contains("transitorio") + return sel.assign(motivo=mot, apta=~bad)[["t_ini_s", "t_fin_s", "motivo", "apta"]] + + +def minutes_by_origin(gate, states, vent_s=2.0) -> dict: + """Clean gate minutes per state interval, keyed directo_ for + clean-window intervals and heredado_ for inherited ones (including + heredado_transicion): each clean window counts where its midpoint falls.""" + out = {} + if not len(states): + return out + apt = gate[gate.apta] + mid = ((apt.t_ini_s + apt.t_fin_s) / 2).to_numpy(float) + for r in states.itertuples(): + n = int(((mid >= r.t_ini_s) & (mid < r.t_fin_s)).sum()) + k = ("heredado_" if r.heredado else "directo_") + str(r.etiqueta) + out[k] = out.get(k, 0.0) + n * vent_s / 60.0 + return out + + +def _counts(ev, electrodes, fases): + u = useful(ev) if ev is not None else ev + if u is None or not len(u): + return {c: 0 for c in electrodes} + sub = u[u.fase.isin(fases)] + if not len(sub): + return {c: 0 for c in electrodes} + cuenta = sub.canal_max.value_counts() + return {c: int(cuenta.get(c, 0)) for c in electrodes} + + +def _state_minutes(minutes, fases): + return float(sum(minutes.get(f, 0.0) for f in fases)) if minutes is not None else 0.0 + + +def state_rates(ev, minutes, states=STATES) -> dict: + """The overall rate per state (as the director's tasa_NREM / tasa_despierto): + useful candidates in the state's phases per clean minute of the state, NaN + without minutes. indicadores rounds each phase's minutes to two decimals + before dividing; these rates keep that convention.""" + redondeados = {} + for fases in states.values(): + for f in fases: + redondeados[f] = round(float(minutes.get(f, 0.0)), 2) if minutes is not None else 0.0 + u = useful(ev) if ev is not None else ev + out = {} + for estado, fases in states.items(): + m = sum(redondeados.get(f, 0.0) for f in fases) + n = int(u.fase.isin(fases).sum()) if u is not None and len(u) else 0 + out[estado] = round(n / m, 3) if m > 0 else float("nan") + return out + + +def electrode_densities(ev, minutes, electrodes, present, states=STATES) -> dict: + """{spike_density__: useful candidates whose canal_max is E per + clean minute of the state}. `electrodes` is the fixed 10-20 feature order + and `present` the study's electrodes among them: a present electrode with + no candidates is 0; an absent electrode, or a state with no minutes, is + NaN.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, electrodes, fases) + for c in electrodes: + v = round(n_por_canal[c] / m, 4) if (m > 0 and c in set(present)) else float("nan") + out[f"spike_density_{estado}_{c}"] = v + return out + + +def zone_densities(ev, minutes, present, prefix="spike_zone", states=STATES, + zones=ZONES) -> dict: + """{__: the zone's useful candidates per clean minute + and per present electrode, so zones of different sizes compare}. NaN when + the state has no minutes or the zone has no present electrode.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, present, fases) + for zona, electrodos in zones.items(): + cs = [c for c in electrodos if c in set(present)] + if not cs: + out[f"{prefix}_{estado}_{zona}"] = float("nan") + continue + n = sum(n_por_canal[c] for c in cs) + out[f"{prefix}_{estado}_{zona}"] = round(n / (m * len(cs)), 4) if m > 0 else float("nan") + return out + + +def minutes_features(minutes, prefix="spike_minutes", states=STATES) -> dict: + """{_: the clean minutes of the state}, what the rates and densities divide by.""" + return {f"{prefix}_{s}": round(_state_minutes(minutes, fases), 4) for s, fases in states.items()} + + +def zone_rates(ev, minutes, present, states=STATES, zones=ZONES) -> dict: + """{spike_zone_rate__: the zone's useful candidates per clean minute of the state}, not divided by + its electrodes (the research's candidates per zone). NaN when the state has no minutes or the zone has no + present electrode.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, present, fases) + for zona, electrodos in zones.items(): + cs = [c for c in electrodos if c in set(present)] + out[f"spike_zone_rate_{estado}_{zona}"] = (round(sum(n_por_canal[c] for c in cs) / m, 4) + if cs and m > 0 else float("nan")) + return out diff --git a/src/tea/biomarkers/spikes/api.py b/src/tea/biomarkers/spikes/api.py index f0557e5..4d815a6 100644 --- a/src/tea/biomarkers/spikes/api.py +++ b/src/tea/biomarkers/spikes/api.py @@ -1,8 +1,9 @@ """ Modern spikes: the director's spike-candidate detector (candidatos_punta) ported function by function in _detector.py, on MNE band-pass filters and a private port -of the seleccion quality gate; features from indicadores. Descriptive (spike -candidates are not validated against a reader). +of the seleccion quality gate; features from indicadores plus the per-electrode +and per-zone densities per state and the inherited-state variant (_density.py). +Descriptive (spike candidates are not validated against a reader). """ from __future__ import annotations @@ -13,13 +14,37 @@ from pathlib import Path import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS +from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS, ZONES -from . import _baseline, _detector -FEATURES = {"spike_rate_awake": "tasa_despierto", "spike_rate_nrem": "tasa_NREM", - "spike_nrem_activation": "activacion_NREM", "spike_focus_frac": "foco_frac", - "spike_laterality": "lateralidad", "spike_frac_generalized": "frac_generalizado", - "spike_index_nrem": "indice_punta_onda_NREM"} +from . import _baseline, _density, _detector +from ._signal import VECINOS_1020 + +INDICATORS = {"spike_rate_awake": "tasa_despierto", "spike_rate_nrem": "tasa_NREM", + "spike_nrem_activation": "activacion_NREM", "spike_focus_frac": "foco_frac", + "spike_laterality": "lateralidad", "spike_frac_generalized": "frac_generalizado", + "spike_index_nrem": "indice_punta_onda_NREM"} +ELECTRODES = tuple(VECINOS_1020) +STATES = ("nrem", "awake") +FEATURES = tuple(INDICATORS) + \ + tuple(f"spike_density_{s}_{e}" for s in STATES for e in ELECTRODES) + \ + tuple(f"spike_zone_{s}_{z}" for s in STATES for z in ZONES) + \ + tuple(f"spike_zone_rate_{s}_{z}" for s in STATES for z in ZONES) + \ + tuple(f"spike_inherited_rate_{s}" for s in STATES) + \ + tuple(f"spike_inherited_zone_{s}_{z}" for s in STATES for z in ZONES) +# The clean minutes each rate divides by: exposure for the count baselines, with no baseline of their own. +MINUTES = tuple(f"spike_minutes_{s}" for s in STATES) + tuple(f"spike_inherited_minutes_{s}" for s in STATES) +# Each rate or density feature, by the minutes feature of its state and variant: these are counted against their +# minutes (`_baseline.CountRate`); a per-electrode zone value is also multiplied back by the zone's electrodes. +EXPOSURE = { + **{f"spike_rate_{s}": f"spike_minutes_{s}" for s in STATES}, + **{f"spike_density_{s}_{e}": f"spike_minutes_{s}" for s in STATES for e in ELECTRODES}, + **{f"spike_zone_{s}_{z}": f"spike_minutes_{s}" for s in STATES for z in ZONES}, + **{f"spike_zone_rate_{s}_{z}": f"spike_minutes_{s}" for s in STATES for z in ZONES}, + **{f"spike_inherited_rate_{s}": f"spike_inherited_minutes_{s}" for s in STATES}, + **{f"spike_inherited_zone_{s}_{z}": f"spike_inherited_minutes_{s}" for s in STATES for z in ZONES}, +} +SCALE = {f"{prefix}_{s}_{z}": float(len(electrodes)) for prefix in ("spike_zone", "spike_inherited_zone") + for s in STATES for z, electrodes in ZONES.items()} class _Est: @@ -46,54 +71,109 @@ class _Est: return np.array(self._x[int(a):int(b)][:, cols], dtype=np.float64) +def _exposure(t: pd.DataFrame, feature: str) -> np.ndarray: + """The minutes `feature` was counted in, from the table; NaN when the table doesn't carry them.""" + column = EXPOSURE[feature] + return t[column].to_numpy(float) if column in t else np.full(len(t), np.nan) + + class Spikes: name = "spikes" - version = "0.1.0" + version = "0.4.0" contract_version = CONTRACT_VERSION requires = ("sleep_state", "annotation_mask") - features = tuple(FEATURES) + features = FEATURES impl = "modern" - def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None): + def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None, + vent_s=2.0, rechazar_transitorio=False, herencia_s=30.0, stable_start_s=0.0): self.variant = variant self.baseline_name = baseline self.baseline_params = dict(baseline_params or {}) self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted - else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) + else {f: self._new_baseline(f, baseline) for f in FEATURES}) self._fitted = fitted is not None + self._evaluable = tuple(self.baselines) if fitted else () + self.vent_s = float(vent_s) + self.rechazar_transitorio = bool(rechazar_transitorio) + self.herencia_s = float(herencia_s) + # No state is inherited before this (the montage's stable start). Tea + # validation assumes EDFs begin at the stable signal, so 0 by default. + self.stable_start_s = float(stable_start_s) + + def _new_baseline(self, feature, baseline): + """A count reference for the rates and densities, the configured baseline for the other features.""" + if feature in EXPOSURE: + return _baseline.CountRate(scale=SCALE.get(feature, 1.0)) + return _baseline.make(baseline, **self.baseline_params) @staticmethod def _vig(study): - """The sleep_state labels as the director's vigilancia table (t_ini_s, t_fin_s, etiqueta).""" + """The sleep_state labels as the director's vigilancia table (t_ini_s, t_fin_s, + etiqueta): each labeled window keeps its full classified length, as the research + states table labels VENT_VIGILANCIA_S per window.""" w, lab = study.prep.windows, study.label("sleep_state").per_window - step = float(w.start_s.iloc[1] - w.start_s.iloc[0]) if len(w) > 1 else 2.0 - v = pd.DataFrame({"t_ini_s": w.start_s.astype(float), "t_fin_s": w.start_s.astype(float) + step, + v = pd.DataFrame({"t_ini_s": w.start_s.astype(float), "t_fin_s": w.end_s.astype(float), "etiqueta": lab.values}) return v[v.etiqueta.isin(("vigilia", "somnolencia", "sueno"))].reset_index(drop=True) - def measure(self, study) -> dict: - ind = self.indicators(study) - if ind is None: - return {f: float("nan") for f in FEATURES} - return {f: float(ind[k]) if ind.get(k) is not None else float("nan") for f, k in FEATURES.items()} - - def indicators(self, study): + def _prepare(self, study): + """What the detector reads from the study, built once per measure.""" ev_a = study.label("annotation_mask").events - ivs = [{"t_ini": r.onset_s, "t_fin": r.onset_s + r.duration_s, "estado": r.estado} for r in ev_a.itertuples()] + ivs = [{"t_ini": r.onset_s, "t_fin": r.onset_s + r.duration_s, "estado": r.estado} + for r in ev_a.itertuples()] est = _Est(study.prep.variant(self.variant), ivs) - ev, minutos, _ = _detector.de_estudio(est, "", self._vig(study), None) + return est, [c for c in est.canales if c in VECINOS_1020] + + def _events(self, est, vig): + """One detector run over `vig`: the candidate table and the clean minutes per state. + (None, None) when the montage has too few 10-20 electrodes.""" + ev, minutos, _ = _detector.de_estudio(est, "", vig, None, calidad=True, + vent_s=self.vent_s, + rechazar_transitorio=self.rechazar_transitorio) + return (None, None) if ev is None else (ev, minutos) + + def _run(self, est, vig): + """The director's indicadores for a run over `vig` (None without one).""" + ev, minutos = self._events(est, vig) if ev is None: return None return _detector.indicadores("", ev, minutos) + def indicators(self, study): + est, _ = self._prepare(study) + return self._run(est, self._vig(study)) + + def measure(self, study) -> dict: + est, canales = self._prepare(study) + vig = self._vig(study) + ev, minutos = self._events(est, vig) + ind = None if ev is None else _detector.indicadores("", ev, minutos) + out = {f: (float(ind[k]) if ind is not None and ind.get(k) is not None else float("nan")) + for f, k in INDICATORS.items()} + out.update(_density.electrode_densities(ev, minutos, ELECTRODES, canales)) + out.update(_density.zone_densities(ev, minutos, canales)) + out.update(_density.zone_rates(ev, minutos, canales)) + out.update(_density.minutes_features(minutos)) + heredados = _density.inherit_states(vig, est.n / est.fs, self.herencia_s, + t_min=self.stable_start_s) + ev_h, minutos_h = self._events(est, heredados) + for s, v in _density.state_rates(ev_h, minutos_h).items(): + out[f"spike_inherited_rate_{s}"] = v + out.update(_density.minutes_features(minutos_h, prefix="spike_inherited_minutes")) + out.update(_density.zone_densities(ev_h, minutos_h, canales, prefix="spike_inherited_zone")) + return out + def train(self, data, ages_months=None): if isinstance(data, pd.DataFrame): t = data else: t = pd.DataFrame([self.measure(s) for s in data]) t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] - for f, b in self.baselines.items(): - b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self._evaluable = tuple(f for f in self.baselines if f in t.columns) + for f in self._evaluable: + b, args = self.baselines[f], (t[f].to_numpy(float), t["age_months"].to_numpy(float)) + b.fit(*args, exposure=_exposure(t, f)) if isinstance(b, _baseline.CountRate) else b.fit(*args) self._fitted = True return self @@ -107,18 +187,27 @@ class Spikes: t["age_months"] = [age_months if age_months is not None else data.prep.age_months] a = t["age_months"].to_numpy(float) parts = [] - for f, b in self.baselines.items(): + for f in self._evaluable: + if f not in t.columns: + continue + b = self.baselines[f] v = t[f].to_numpy(float) - outside, z = b.deviation(v, a) + if isinstance(b, _baseline.CountRate): + outside, z = b.deviation(v, a, exposure=_exposure(t, f)) + else: + outside, z = b.deviation(v, a) parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) return pd.concat(parts, ignore_index=True) def save(self, path): - Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "baseline": self.baseline_name, - "baseline_params": self.baseline_params})) - Path(path, "baseline.json").write_text(json.dumps( - {f: b.to_dict() for f, b in self.baselines.items()} if self._fitted else None, default=float)) + Path(path, "params.json").write_text(json.dumps( + {"variant": self.variant, "baseline": self.baseline_name, + "baseline_params": self.baseline_params, "vent_s": self.vent_s, + "rechazar_transitorio": self.rechazar_transitorio, "herencia_s": self.herencia_s, + "stable_start_s": self.stable_start_s})) + fitted = ({f: self.baselines[f].to_dict() for f in self._evaluable} if self._fitted else None) + Path(path, "baseline.json").write_text(json.dumps(fitted, default=float)) @classmethod def load(cls, path): diff --git a/src/tea/biomarkers/spindle_topography/_baseline.py b/src/tea/biomarkers/spindle_topography/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/spindle_topography/_baseline.py +++ b/src/tea/biomarkers/spindle_topography/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/spindle_topography/api.py b/src/tea/biomarkers/spindle_topography/api.py index 035b8fc..162f076 100644 --- a/src/tea/biomarkers/spindle_topography/api.py +++ b/src/tea/biomarkers/spindle_topography/api.py @@ -50,7 +50,7 @@ def episodes(sp: pd.DataFrame): class SpindleTopography: name = "spindle_topography" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("spindle_detection", "sleep_state") features = FEATURES diff --git a/src/tea/biomarkers/spindles/_baseline.py b/src/tea/biomarkers/spindles/_baseline.py index f70c368..3983e9c 100644 --- a/src/tea/biomarkers/spindles/_baseline.py +++ b/src/tea/biomarkers/spindles/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/biomarkers/spindles/api.py b/src/tea/biomarkers/spindles/api.py index 8acfd35..0aa9f56 100644 --- a/src/tea/biomarkers/spindles/api.py +++ b/src/tea/biomarkers/spindles/api.py @@ -1,9 +1,4 @@ -""" -Modern spindles: summary of the spindle_detection events (husos.resumen's -definitions): density per minute of sleep per channel, median frequency, -% fast (>= 13 Hz), median duration, slow and fast densities. NaN with less -than 1 minute of sleep or no spindle. -""" +"""Summarize sleep spindle events, long runs, sigma occupancy and scalp densities.""" from __future__ import annotations @@ -13,12 +8,47 @@ from pathlib import Path import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS +from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS, ZONES from . import _baseline +ADDITIONAL_FEATURES = ( + "spindle_density_per_min_channel_no_long", + "spindle_n_long_runs", + "spindle_n_extreme", + "spindle_max_run_s", + "spindle_sigma_occupancy_median", + "spindle_sigma_occupancy_max", + *(f"spindle_electrode_{channel}" for channels in ZONES.values() for channel in channels), + *(f"spindle_zone_{zone}" for zone in ZONES), +) + + +def _additional_summary(events, minutes): + extra = dict.fromkeys(ADDITIONAL_FEATURES, np.nan) + if events.empty or minutes <= 0 or not events.attrs.get("searched", True): + return extra + + extra.update(events.attrs.get("long_run_features", {})) + # Only the channels the detector searched: one it never looks at has no density, not zero. + searched = set(events.attrs.get("channels", ())) + present = set(events.attrs.get("eeg_channels", searched)) & searched + counts = events.channel.value_counts() + for zone, channels in ZONES.items(): + electrodes = [channel for channel in channels if channel in present] + if not electrodes: + continue + total = 0 + for channel in electrodes: + count = counts.get(channel, 0) + extra[f"spindle_electrode_{channel}"] = count / minutes + total += count + extra[f"spindle_zone_{zone}"] = total / (minutes * len(electrodes)) + return extra + + FEATURES = ("spindle_density_per_min_channel", "spindle_frequency_hz", "spindle_pct_fast", - "spindle_duration_s", "spindle_density_slow", "spindle_density_fast") + "spindle_duration_s", "spindle_density_slow", "spindle_density_fast", *ADDITIONAL_FEATURES) def summary(ev: pd.DataFrame) -> dict: @@ -33,12 +63,13 @@ def summary(ev: pd.DataFrame) -> dict: "spindle_pct_fast": round(100 * float((ev.kind == "fast").mean()), 1), "spindle_duration_s": round(float(ev.duration_s.median()), 2), "spindle_density_slow": round(float((ev.kind == "slow").sum()) / minutes / n_ch, 3), - "spindle_density_fast": round(float((ev.kind == "fast").sum()) / minutes / n_ch, 3)} + "spindle_density_fast": round(float((ev.kind == "fast").sum()) / minutes / n_ch, 3), + **_additional_summary(ev, minutes)} class Spindles: name = "spindles" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("spindle_detection",) features = FEATURES @@ -47,7 +78,7 @@ class Spindles: def __init__(self, baseline="curves", baseline_params=None, fitted=None): self.baseline_name = baseline self.baseline_params = dict(baseline_params or {}) - self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted + self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted is not None else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) self._fitted = fitted is not None @@ -60,8 +91,12 @@ class Spindles: else: t = pd.DataFrame([self.measure(s) for s in data]) t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] - for f, b in self.baselines.items(): - b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + fitted = {} + for f in FEATURES: + if f in t: + baseline = _baseline.make(self.baseline_name, **self.baseline_params) + fitted[f] = baseline.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self.baselines = fitted self._fitted = True return self @@ -76,11 +111,13 @@ class Spindles: a = t["age_months"].to_numpy(float) parts = [] for f, b in self.baselines.items(): + if f not in t: + continue v = t[f].to_numpy(float) outside, z = b.deviation(v, a) parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) - return pd.concat(parts, ignore_index=True) + return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=DEVIATION_COLUMNS) def save(self, path): Path(path, "params.json").write_text(json.dumps({"baseline": self.baseline_name, diff --git a/src/tea/contracts/__init__.py b/src/tea/contracts/__init__.py index 74b3114..21b8f99 100644 --- a/src/tea/contracts/__init__.py +++ b/src/tea/contracts/__init__.py @@ -7,11 +7,14 @@ The shared API of `tea`: the only code every module may import. """ from tea.contracts.data import ( + ASSOCIATION_COLUMNS, CONTRACT_VERSION, DAYS_PER_MONTH, DEVIATION_COLUMNS, SPAN_COLUMNS, + SCORE_COLUMNS, WINDOW_COLUMNS, + ZONES, Labels, Preprocessed, Recording, @@ -24,6 +27,7 @@ from tea.contracts.data import ( ) from tea.contracts.protocols import ( KINDS, + Association, Biomarker, ContractError, Module, @@ -34,9 +38,10 @@ from tea.contracts.protocols import ( ) __all__ = [ - "CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "empty_spans", + "CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "ZONES", "empty_spans", + "ASSOCIATION_COLUMNS", "SCORE_COLUMNS", "Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of", "DAYS_PER_MONTH", "header_age_months", "read_edf", - "Module", "Validator", "Preprocessor", "Process", "Biomarker", + "Module", "Validator", "Preprocessor", "Process", "Biomarker", "Association", "KINDS", "ContractError", "check_module", ] diff --git a/src/tea/contracts/data.py b/src/tea/contracts/data.py index 8fd6c51..b53c1e6 100644 --- a/src/tea/contracts/data.py +++ b/src/tea/contracts/data.py @@ -29,9 +29,30 @@ MAX_HEADER_AGE_MONTHS = 216 # What EDF writers put in the header's start date when they don't know it. UNKNOWN_START = date(1985, 1, 1) -# Columns of the table that Biomarker.predict returns. +# Columns of the table that Biomarker.predict returns. Outside is a float: -1 below, 0 inside, +# +1 above the reference interval, or NaN without a reference. DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline") +# The scalp zones a per-zone feature groups its 10-20 electrodes into: an anatomical grouping of the montage, +# the one the ADOS-2 association pairs each zone with its items by. Feature names carry the zone code. +ZONES = { + "frontal_izq": ("Fp1", "F3", "F7"), + "frontal_der": ("Fp2", "F4", "F8"), + "frontal_media": ("Fz",), + "central": ("C3", "Cz", "C4"), + "parietal": ("P3", "Pz", "P4"), + "temporal_izq": ("T3", "T5"), + "temporal_der": ("T4", "T6"), + "occipital": ("O1", "O2"), +} + +# Columns of the table that Association.associations returns: one row per pair of EEG predictor and outcome. +ASSOCIATION_COLUMNS = ("biomarker", "zone", "kind", "outcome", "outcome_code", "event", "model", "n", "odds_ratio", + "ci_low", "ci_high", "p", "q", "sens_model", "sens_odds_ratio", "same_direction", "reason") + +# Columns of the table that Association.score returns: one row per child and estimated pair. +SCORE_COLUMNS = ("key", "biomarker", "zone", "outcome_code", "z", "probability", "reference_probability") + # Columns that Preprocessed.windows must have. WINDOW_COLUMNS = ("start_s", "end_s", "clean", "gap") diff --git a/src/tea/contracts/protocols.py b/src/tea/contracts/protocols.py index 65f4163..27e0f70 100644 --- a/src/tea/contracts/protocols.py +++ b/src/tea/contracts/protocols.py @@ -77,11 +77,28 @@ class Biomarker(Module, Protocol): def load(cls, path) -> Biomarker: ... +@runtime_checkable +class Association(Module, Protocol): + """A cohort-level model of EEG findings against a clinical outcome; it runs outside the per-study pipeline.""" + + def fit(self, cohort: pd.DataFrame) -> Association: ... + + def associations(self) -> pd.DataFrame: ... + + def score(self, cohort: pd.DataFrame) -> pd.DataFrame: ... + + def save(self, path) -> None: ... + + @classmethod + def load(cls, path) -> Association: ... + + KINDS: dict[str, type] = { "validator": Validator, "preprocessor": Preprocessor, "process": Process, "biomarker": Biomarker, + "association": Association, } diff --git a/src/tea/contracts/testing.py b/src/tea/contracts/testing.py index cce311e..558fbb8 100644 --- a/src/tea/contracts/testing.py +++ b/src/tea/contracts/testing.py @@ -107,7 +107,8 @@ def _check_deviation(df: pd.DataFrame, module): assert tuple(df.columns[: len(DEVIATION_COLUMNS)]) == DEVIATION_COLUMNS, \ f"{module.name}.predict columns {list(df.columns)} must start with {DEVIATION_COLUMNS}" assert set(df["feature"]) <= set(module.features), f"{module.name}: unknown feature in predict" - assert df["outside"].isin([-1, 0, 1]).all(), f"{module.name}: outside must be -1, 0 or 1" + known = df["outside"].dropna() + assert known.isin([-1, 0, 1]).all(), f"{module.name}: outside must be -1, 0, 1 or NaN (no reference)" def _same_labels(a: Labels, b: Labels, name: str): diff --git a/src/tea/legacy/associations/__init__.py b/src/tea/legacy/associations/__init__.py new file mode 100644 index 0000000..793057a --- /dev/null +++ b/src/tea/legacy/associations/__init__.py @@ -0,0 +1 @@ +"""Legacy cohort-level associations: the research code vendored unchanged, on the contract.""" diff --git a/src/tea/legacy/associations/ados2/__init__.py b/src/tea/legacy/associations/ados2/__init__.py new file mode 100644 index 0000000..66e1bc1 --- /dev/null +++ b/src/tea/legacy/associations/ados2/__init__.py @@ -0,0 +1,3 @@ +from tea.legacy.associations.ados2.api import MODULE, LegacyAdos2Association + +__all__ = ["MODULE", "LegacyAdos2Association"] diff --git a/src/tea/legacy/associations/ados2/_research/__init__.py b/src/tea/legacy/associations/ados2/_research/__init__.py new file mode 100644 index 0000000..5892257 --- /dev/null +++ b/src/tea/legacy/associations/ados2/_research/__init__.py @@ -0,0 +1 @@ +"""Research code of the ADOS-2 association, vendored unchanged.""" diff --git a/src/tea/legacy/associations/ados2/_research/ados2_items.py b/src/tea/legacy/associations/ados2/_research/ados2_items.py new file mode 100644 index 0000000..d2f7055 --- /dev/null +++ b/src/tea/legacy/associations/ados2/_research/ados2_items.py @@ -0,0 +1,150 @@ +# Vendored from biomarcadores-tea biomarcadores/ados2_items.py @ 478c74d +# source sha256 d197757caccd158c6e22ac38140cb89f8fb9d835bac760d774a77ca107791024. Do not edit: copied unchanged. +""" +ados2_items.py — Los ítems del algoritmo del ADOS-2 juntados por lo que miden, y los pares biomarcador–zona ↔ +ítem (o dominio) que prueba el modelo de OR (`docs/plan_modelo_or.md`). + +Fuente: `docs/tabla_alteraciones_ados2.md` (Tablas 1 y 4), hecha con el manual oficial del ADOS-2 (Toddler, +módulos 1 y 2). Los códigos coinciden con el Anexo B de la especificación de la plataforma. **Un mismo código no +es el mismo ítem en todos los módulos** (B5 es integración de la mirada en el Toddler, disfrute compartido en el +Módulo 1 y mostrar en el Módulo 2); por eso cada ítem dice su código en cada módulo. + +Columnas de ítem que acepta la tabla por niño: `sa_a2`, `rrb_d1`… con o sin prefijo (`ado_sa_a2`, +`psi_ados2_sa_a2`). El módulo va en `ados_modulo`: TODDLER, MODULO_1 o MODULO_2 (`NO_REGISTRADO` deja los +ítems vacíos). Con los nombres de la plataforma (`psi_ados2_modulo`, `psi_ados2_css`…) usar `desde_plataforma`. +""" + +from __future__ import annotations + + + +import numpy as np +import pandas as pd + +MODULOS = ("TODDLER", "MODULO_1", "MODULO_2") + +# número de la Tabla 1: (nombre, dominio del algoritmo, código por módulo; None = no entra al algoritmo) +ITEMS = { + 1: ("Vocalización espontánea dirigida a otros", "SA", {"TODDLER": "sa_a2", "MODULO_1": "sa_a2"}), + 2: ("Señalar", "SA", {"TODDLER": "sa_a7", "MODULO_1": "sa_a7", "MODULO_2": "sa_a6"}), + 3: ("Gestos", "SA", {"TODDLER": "sa_a8", "MODULO_1": "sa_a8", "MODULO_2": "sa_a7"}), + 4: ("Contacto visual inusual", "SA", {"TODDLER": "sa_b1", "MODULO_1": "sa_b1", "MODULO_2": "sa_b1"}), + 5: ("Expresiones faciales dirigidas a otros", "SA", {"TODDLER": "sa_b4", "MODULO_1": "sa_b3", + "MODULO_2": "sa_b2"}), + 6: ("Integración de la mirada con otras conductas", "SA", {"TODDLER": "sa_b5", "MODULO_1": "sa_b4"}), + 7: ("Disfrute compartido en la interacción", "SA", {"TODDLER": "sa_b6", "MODULO_1": "sa_b5", + "MODULO_2": "sa_b3"}), + 8: ("Respuesta al nombre", "SA", {"TODDLER": "sa_b7"}), + 9: ("Búsqueda de atención cuando se le ignora", "SA", {"TODDLER": "sa_b8"}), + 10: ("Pedir", "SA", {"TODDLER": "sa_b9"}), + 11: ("Mostrar", "SA", {"TODDLER": "sa_b12", "MODULO_1": "sa_b9", "MODULO_2": "sa_b5"}), + 12: ("Iniciación espontánea de la atención conjunta", "SA", {"TODDLER": "sa_b13", "MODULO_1": "sa_b10", + "MODULO_2": "sa_b6"}), + 13: ("Respuesta a la atención conjunta", "SA", {"TODDLER": "sa_b14", "MODULO_1": "sa_b11"}), + 14: ("Calidad de los acercamientos sociales", "SA", {"TODDLER": "sa_b15", "MODULO_1": "sa_b12", + "MODULO_2": "sa_b8"}), + 15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"TODDLER": "sa_b16b"}), + 16: ("Cantidad de comunicación social recíproca", "SA", {"MODULO_2": "sa_b11"}), + 17: ("Calidad general de la relación", "SA", {"TODDLER": "sa_b18", "MODULO_2": "sa_b12"}), + 18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"TODDLER": "rrb_a3", "MODULO_1": "rrb_a3"}), + 19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"MODULO_1": "rrb_a5", "MODULO_2": "rrb_a4"}), + 20: ("Interés sensorial inusual", "RRB", {"TODDLER": "rrb_d1", "MODULO_1": "rrb_d1", "MODULO_2": "rrb_d1"}), + 21: ("Manierismos de manos y dedos", "RRB", {"TODDLER": "rrb_d2", "MODULO_1": "rrb_d2", "MODULO_2": "rrb_d2"}), + 22: ("Intereses repetitivos o conductas estereotipadas", "RRB", {"TODDLER": "rrb_d5", "MODULO_1": "rrb_d4", + "MODULO_2": "rrb_d4"}), +} + +ZONAS = ("frontal_izquierda", "frontal_derecha", "frontal_media", "central", "parietal", + "temporal_izquierda", "temporal_derecha", "occipital") +# Tabla 4: ítems de cada zona (picos) +ITEMS_POR_ZONA = { + "frontal_izquierda": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16), + "frontal_derecha": (4, 5, 7, 14, 22), + "frontal_media": (6, 11, 12, 13, 14), + "central": (21,), + "parietal": (6, 13, 20), + "temporal_izquierda": (1, 16, 18, 19), + "temporal_derecha": (4, 5, 8), + "occipital": (4, 20), +} +# dominio de cada zona (Tabla 2 de la tabla del ADOS-2), para el modo por dominio +DOMINIOS_POR_ZONA = {"frontal_izquierda": ("css_sa",), "frontal_derecha": ("css_sa",), + "frontal_media": ("css_sa",), "temporal_izquierda": ("css_sa",), + "temporal_derecha": ("css_sa",), "central": ("css_rrb",), "occipital": ("css_rrb",), + "parietal": ("css_sa", "css_rrb")} +ZONAS_HUSOS = ("frontal_izquierda", "frontal_derecha", "frontal_media", "central", "parietal") +NOMBRE_DOMINIO = {"css_total": "CSS total", "css_sa": "CSS afecto social", "css_rrb": "CSS conductas repetitivas"} + + +def pares(nivel: str = "item") -> list[dict]: + """Los pares que se prueban. `nivel`: «item» (ítems; husos y gradiente siempre por dominio) o «dominio» + (todo con CSS). Cada par: biomarcador, zona, predictor (columna de z) y resultado (ítem n o columna CSS).""" + out = [] + for z in ZONAS: + resultados = ([("item", i) for i in ITEMS_POR_ZONA[z]] if nivel == "item" + else [("dominio", d) for d in DOMINIOS_POR_ZONA[z]]) + out += [{"biomarcador": "picos", "zona": z, "predictor": f"z_picos_{z}", "tipo": t, "resultado": r} + for t, r in resultados] + for z in ZONAS_HUSOS: # husos: no hay base para un ítem (tabla del ADOS-2) + out += [{"biomarcador": "husos", "zona": z, "predictor": f"z_husos_{z}", "tipo": "dominio", + "resultado": d} for d in ("css_total", "css_sa")] + ritmo = ([("item", 20), ("item", 22)] if nivel == "item" else [("dominio", "css_rrb")]) + out += [{"biomarcador": "ritmo_posterior", "zona": "posterior", "predictor": "z_ritmo_posterior", + "tipo": t, "resultado": r} for t, r in ritmo] + out += [{"biomarcador": "gradiente", "zona": "global", "predictor": "z_gradiente", "tipo": "dominio", + "resultado": "css_total"}] + return out + + +def _columna(t: pd.DataFrame, codigo: str) -> str | None: + """La columna de la tabla para un código (`sa_b5`), con o sin prefijo.""" + for c in t.columns: + nombre = str(c).lower() + if nombre == codigo or nombre.endswith("_" + codigo): + return c + return None + + +# Nombres de la tabla `evaluacion_psicologica` de la plataforma (Core/spec/tablas_TEA.md) → los del modelo. +NOMBRES_PLATAFORMA = {"psi_ados2_modulo": "ados_modulo", "psi_ados2_css": "css_total", + "psi_ados2_css_sa": "css_sa", "psi_ados2_css_rrb": "css_rrb"} + + +def desde_plataforma(t: pd.DataFrame) -> pd.DataFrame: + """La tabla con los nombres del modelo para el módulo y los CSS, si viene con los de la plataforma. + Las columnas de ítem (`psi_ados2_sa_a2`…) no se renombran: `_columna` ya las encuentra con el prefijo.""" + cambios = {p: m for p, m in NOMBRES_PLATAFORMA.items() if p in t and m not in t} + return t.rename(columns=cambios) if cambios else t + + +def puntaje_algoritmo(v): + """Del código del protocolo al puntaje del algoritmo: 3 → 2; 7, 8 y 9 → 0; 0, 1 y 2 igual.""" + v = pd.to_numeric(v, errors="coerce") + return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2) + + +def item_por_nino(t: pd.DataFrame, n: int) -> pd.Series: + """El puntaje de algoritmo (0–2) del ítem `n` para cada niño, tomado de la columna de su módulo. + NaN si el ítem no entra al algoritmo de su módulo o no hay dato.""" + _, _, codigos = ITEMS[n] + out = pd.Series(np.nan, index=t.index) + mod = t["ados_modulo"].astype(str).str.upper() + for m, cod in codigos.items(): + col = _columna(t, cod) + if col is None: + continue + sel = mod == m + out[sel] = puntaje_algoritmo(t.loc[sel, col]) + return out + + +def hay_items(t: pd.DataFrame, minimo: int = 10) -> bool: + """¿La tabla trae ítems del ADOS-2? (al menos `minimo` niños con algún ítem).""" + if "ados_modulo" not in t: + return False + vals = pd.concat([item_por_nino(t, n) for n in ITEMS], axis=1) + return int(vals.notna().any(axis=1).sum()) >= minimo + + +def nombre_resultado(tipo: str, resultado) -> str: + return f"{resultado}. {ITEMS[resultado][0]}" if tipo == "item" else NOMBRE_DOMINIO.get(resultado, str(resultado)) diff --git a/src/tea/legacy/associations/ados2/_research/modelo_or.py b/src/tea/legacy/associations/ados2/_research/modelo_or.py new file mode 100644 index 0000000..9cc77ab --- /dev/null +++ b/src/tea/legacy/associations/ados2/_research/modelo_or.py @@ -0,0 +1,251 @@ +# Vendored from biomarcadores-tea biomarcadores/modelo_or.py @ 478c74d +# source sha256 ac6168dd7774f1da624aa8088915799e2e3ed78436a4417387a0750afac386b0. Do not edit: copied unchanged. +""" +modelo_or.py — Razón de momios (OR) de una alteración del EEG (z continuo) con un aspecto del ADOS-2, para +muestras pequeñas (`docs/plan_modelo_or.md`). + +Dos modelos: + * `firth`: regresión logística con la penalización de Firth (prior de Jeffreys), para un resultado sí/no (ítem + alterado, o severidad alta). Corrige el sesgo de las muestras chicas y da estimaciones finitas aun con + separación (Heinze y Schemper 2002, Stat Med 21:2409). Intervalo y p por verosimilitud penalizada + perfilada. Probabilidades con la corrección del intercepto FLIC (Puhr et al. 2017, Stat Med 36:2302): no + cambia el OR y hace que la probabilidad media sea la proporción observada. + * `ordinal`: logística ordinal de momios proporcionales (ítem 0/1/2 o CSS 1–10), por máxima verosimilitud; + intervalo y p por verosimilitud perfilada. El OR es el de pasar a un nivel más alto. + +Implementación propia (no hay paquete instalado para Firth en Python); `logistf` (R) es la referencia de los +autores. Ambos devuelven el OR por **una unidad de z** del predictor, ajustado por las covariables. +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import pandas as pd +from scipy import optimize, stats +from scipy.special import expit + +CHI2_95 = float(stats.chi2.ppf(0.95, 1)) + + +# ------------------------------------------------------------------ matriz de diseño +def diseno(t: pd.DataFrame, predictor: str, ajustes=("edad_meses", "ados_modulo")): + """X con: intercepto, predictor (sin centrar: z = 0 es la mediana de la referencia) y ajustes. Los + numéricos se centran en su media; los categóricos van como indicadoras, con la categoría más frecuente de + referencia. Se omiten los ajustes que no varían. Devuelve (X, nombres, fila_ref).""" + cols = {"intercepto": np.ones(len(t)), predictor: t[predictor].to_numpy(float)} + for a in ajustes: + if a not in t: + continue + v = t[a] + if pd.api.types.is_numeric_dtype(v): + v = v.astype(float) + if v.std() > 0: + cols[a] = (v - v.mean()).to_numpy() + else: + ref = v.value_counts().index[0] + for nivel in sorted(set(v) - {ref}): + d = (v == nivel).to_numpy(float) + if 0 < d.sum() < len(d): + cols[f"{a}={nivel}"] = d + nombres = list(cols) + X = np.column_stack([cols[n] for n in nombres]) + fila_ref = np.zeros(len(nombres)) + fila_ref[0] = 1.0 + return X, nombres, fila_ref + + +# ------------------------------------------------------------------ Firth +def _pl(b, X, y): + """Log-verosimilitud penalizada de Firth: l(b) + ½ log|X'WX|.""" + eta = X @ b + p = expit(eta) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + signo, logdet = np.linalg.slogdet(info) + if signo <= 0: + return -np.inf + return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet) + + +def _score(b, X, y): + """Puntaje modificado de Firth: X'(y − p + h(½ − p)), con h la diagonal de la matriz sombrero.""" + eta = X @ b + p = expit(eta) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + inv = np.linalg.inv(info) + h = np.einsum("ij,jk,ik->i", X, inv, X) * w + return X.T @ (y - p + h * (0.5 - p)), info + + +def _ajustar_firth(X, y, max_iter=200, tol=1e-10): + b = np.zeros(X.shape[1]) + pl = _pl(b, X, y) + for _ in range(max_iter): + U, info = _score(b, X, y) + paso = np.linalg.solve(info, U) + t = 1.0 + while t > 1e-8: + nb = b + t * paso + npl = _pl(nb, X, y) + if npl >= pl - 1e-12: + break + t /= 2 + b, pl = nb, npl + if np.max(np.abs(t * paso)) < tol: + break + return b, pl + + +def _perfil_firth(valor, j, X, y, b0): + libres = [k for k in range(X.shape[1]) if k != j] + + def f(bl): + b = np.empty(X.shape[1]) + b[libres], b[j] = bl, valor + v = _pl(b, X, y) + if not np.isfinite(v): + return 1e10, np.zeros(len(libres)) + U, _ = _score(b, X, y) + return -v, -U[libres] + + r = optimize.minimize(f, b0[libres], jac=True, method="BFGS") + return -float(r.fun) + + +def _intervalo(f_perfil, centro, maximo, escala): + """Intervalo de verosimilitud perfilada: los valores donde 2·(máx − perfil) = χ²₁(0.95).""" + g = lambda v: 2 * (maximo - f_perfil(v)) - CHI2_95 # noqa: E731 + lims = [] + for signo in (-1, 1): + anterior, lim = centro, signo * np.inf + for k in range(1, 80): + v = centro + signo * escala * k + if g(v) > 0: + lim = optimize.brentq(g, min(anterior, v), max(anterior, v)) + break + anterior = v + lims.append(lim) + return lims[0], lims[1] + + +def firth(t: pd.DataFrame, resultado: str, predictor: str, ajustes=("edad_meses", "ados_modulo"), + z_curva=(0.0, 2.0), por_fila: bool = False) -> dict: + """Logística de Firth de `resultado` (0/1) en `predictor`, ajustada. Devuelve n, eventos, OR por unidad de + z, intervalo del 95 % perfilado, p (razón de verosimilitudes penalizada) y la probabilidad FLIC a los z de + `z_curva` con los ajustes en su referencia.""" + d = t[[resultado, predictor, *[a for a in ajustes if a in t]]].dropna() + y = d[resultado].to_numpy(float) + out = {"modelo": "firth", "n": len(d), "eventos": int(y.sum())} + if len(d) < 8 or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0: + return {**out, "motivo": "muy pocos datos o sin variación"} + X, nombres, ref = diseno(d, predictor, ajustes) + b, pl = _ajustar_firth(X, y) + _, info = _score(b, X, y) + se = float(np.sqrt(np.linalg.inv(info)[1, 1])) + perfil = lambda v: _perfil_firth(v, 1, X, y, b) # noqa: E731 + lo, hi = _intervalo(perfil, b[1], pl, max(se, 0.05)) + p = float(stats.chi2.sf(max(2 * (pl - perfil(0.0)), 0.0), 1)) + # FLIC: intercepto que iguala la probabilidad media a la proporción observada + eta0 = X[:, 1:] @ b[1:] + b0 = optimize.brentq(lambda a: expit(a + eta0).sum() - y.sum(), -50, 50) + curva = {} + for z in z_curva: + fila = ref.copy() + fila[1] = z + curva[f"prob_z{z:g}"] = round(float(expit(b0 + fila[1:] @ b[1:])), 4) + if por_fila: # cada niño con su z, su edad y su módulo + curva["prob_por_fila"] = dict(zip(d.index, np.round(expit(b0 + eta0), 4))) + return {**out, "coef": round(float(b[1]), 4), "or": round(float(np.exp(b[1])), 4), + "ic_inf": round(float(np.exp(lo)), 4), "ic_sup": round(float(np.exp(hi)), 4), + "p": round(p, 5), "ajustes": ", ".join(nombres[2:]), **curva, "motivo": ""} + + +# ------------------------------------------------------------------ ordinal (momios proporcionales) +def _nll_ordinal(par, X, yk, K): + theta = np.cumsum(np.r_[par[0], np.exp(par[1:K - 1])]) + eta = X @ par[K - 1:] + cdf = expit(theta[None, :] - eta[:, None]) + n = len(yk) + cdf = np.c_[np.zeros(n), cdf, np.ones(n)] + pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk] + return -float(np.sum(np.log(np.clip(pr, 1e-300, None)))) + + +def _ajustar_ordinal(X, yk, K, fijo=None): + """Mínimo de la −log-verosimilitud; `fijo` = (j, valor) fija el coeficiente j de X (perfil).""" + p = X.shape[1] + inicio = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(p)] + if fijo is None: + f = lambda q: _nll_ordinal(q, X, yk, K) # noqa: E731 + r = optimize.minimize(f, inicio, method="BFGS") + return r.x, float(r.fun) + j, valor = fijo + idx = [k for k in range(len(inicio)) if k != K - 1 + j] + + def f(q): + par = np.empty(len(inicio)) + par[idx], par[K - 1 + j] = q, valor + return _nll_ordinal(par, X, yk, K) + + r = optimize.minimize(f, inicio[idx], method="BFGS") + return None, float(r.fun) + + +def ordinal(t: pd.DataFrame, resultado: str, predictor: str, ajustes=("edad_meses", "ados_modulo"), + corte_alto: float | None = None, z_curva=(0.0, 2.0), por_fila: bool = False) -> dict: + """Logística ordinal de `resultado` (niveles ordenados: 0/1/2 o CSS). OR de estar en un nivel más alto por + unidad de z, intervalo perfilado, p (razón de verosimilitudes) y, si se da `corte_alto`, la probabilidad + de `resultado ≥ corte_alto` a los z de `z_curva`.""" + d = t[[resultado, predictor, *[a for a in ajustes if a in t]]].dropna() + niveles = np.sort(d[resultado].unique()) + out = {"modelo": "ordinal", "n": len(d), "niveles": len(niveles)} + if len(d) < 8 or len(niveles) < 2 or d[predictor].std() == 0: + return {**out, "motivo": "muy pocos datos o sin variación"} + X, nombres, ref = diseno(d, predictor, ajustes) + X = X[:, 1:] # los umbrales hacen de intercepto + ref = ref[1:] + K = len(niveles) + yk = np.searchsorted(niveles, d[resultado].to_numpy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + par, nll = _ajustar_ordinal(X, yk, K) + beta = par[K - 1:] + if abs(beta[0]) > 20: + return {**out, "motivo": "no converge (separación)"} + perfil = lambda v: -_ajustar_ordinal(X, yk, K, fijo=(0, v))[1] # noqa: E731 + lo, hi = _intervalo(perfil, beta[0], -nll, 0.1) + p = float(stats.chi2.sf(max(2 * (-nll - perfil(0.0)), 0.0), 1)) + curva = {} + if corte_alto is not None: + theta = np.cumsum(np.r_[par[0], np.exp(par[1:K - 1])]) + k = int(np.searchsorted(niveles, corte_alto)) # primer nivel ≥ corte + for z in z_curva: + fila = ref.copy() + fila[0] = z + eta = float(fila @ beta) + curva[f"prob_z{z:g}"] = (round(float(1 - expit(theta[k - 1] - eta)), 4) if 0 < k < K + else (1.0 if k == 0 else 0.0)) + if por_fila: # cada niño con su z, su edad y su módulo + eta = X @ beta + pf = (1 - expit(theta[k - 1] - eta)) if 0 < k < K else np.full(len(eta), 1.0 if k == 0 else 0.0) + curva["prob_por_fila"] = dict(zip(d.index, np.round(pf, 4))) + return {**out, "coef": round(float(beta[0]), 4), "or": round(float(np.exp(beta[0])), 4), + "ic_inf": round(float(np.exp(lo)), 4), "ic_sup": round(float(np.exp(hi)), 4), + "p": round(p, 5), "ajustes": ", ".join(nombres[2:]), **curva, "motivo": ""} + + +def bh(p) -> np.ndarray: + """q de Benjamini–Hochberg (los NaN quedan NaN).""" + p = np.asarray(p, dtype=float) + q = np.full(len(p), np.nan) + ok = np.isfinite(p) + if ok.any(): + v = p[ok] + o = np.argsort(v) + r = v[o] * len(v) / np.arange(1, len(v) + 1) + r = np.minimum.accumulate(r[::-1])[::-1] + q[np.flatnonzero(ok)[o]] = np.minimum(r, 1) + return q diff --git a/src/tea/legacy/associations/ados2/api.py b/src/tea/legacy/associations/ados2/api.py new file mode 100644 index 0000000..85d71bd --- /dev/null +++ b/src/tea/legacy/associations/ados2/api.py @@ -0,0 +1,157 @@ +""" +Legacy ADOS-2 association: the research code's Firth and ordinal fits (`_research.modelo_or`) and its item table +(`_research.ados2_items`), vendored unchanged, on the contract. The pairs are the research code's, with the domain +outcomes on the total CSS (the per-domain CSS is not recorded) and the zone codes of `tea.contracts.ZONES`. +The cohort and the output are those of `tea.associations.ados2`; `score` covers the children the fit used. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd + +from tea.contracts import ASSOCIATION_COLUMNS, CONTRACT_VERSION, SCORE_COLUMNS + +from ._research import ados2_items as ai +from ._research import modelo_or as mo + +RESEARCH_COMMIT = "478c74d" +ADJUST = ("edad_meses", "ados_modulo") +CSS_HIGH = 8 +ZONE = {"frontal_izquierda": "frontal_izq", "frontal_derecha": "frontal_der", "frontal_media": "frontal_media", + "central": "central", "parietal": "parietal", "temporal_izquierda": "temporal_izq", + "temporal_derecha": "temporal_der", "occipital": "occipital", "posterior": "posterior", "global": "global"} +BIOMARKER = {"picos": "spikes", "husos": "spindles", "ritmo_posterior": "posterior_rhythm", "gradiente": "gradient"} + + +def _table(cohort: pd.DataFrame) -> pd.DataFrame: + """The cohort with the research code's column names.""" + t = cohort.rename(columns={"age_months": "edad_meses", "ados_module": "ados_modulo", "css": "css_total", + "z_posterior_rhythm": "z_ritmo_posterior", "z_gradient": "z_gradiente"}) + for zona, zone in ZONE.items(): + for ours, theirs in (("spikes", "picos"), ("spindles", "husos")): + if f"z_{ours}_{zone}" in t: + t[f"z_{theirs}_{zona}"] = t[f"z_{ours}_{zone}"] + return t + + +def _guarded(fit, model: str, *args, **kwargs) -> dict: + """One fit, or a row with its reason when the design is singular: one pair never stops the others.""" + try: + return fit(*args, **kwargs) + except (np.linalg.LinAlgError, ValueError) as error: + return {"modelo": model, "n": 0, "motivo": f"singular design ({type(error).__name__})"} + + +def _pairs(level: str) -> list[dict]: + """The research pairs with every domain outcome on the total CSS, each pair once.""" + seen, out = set(), [] + for p in ai.pares("item" if level == "item" else "dominio"): + p = {**p, "resultado": "css_total" if p["tipo"] == "dominio" else p["resultado"]} + key = (p["biomarcador"], p["zona"], p["tipo"], p["resultado"]) + if key not in seen: + seen.add(key) + out.append(p) + return out + + +class LegacyAdos2Association: + name = "ados2_association" + version = f"0.1.0+research.{RESEARCH_COMMIT}" + contract_version = CONTRACT_VERSION + impl = "legacy" + + def __init__(self, level: str = "auto", fitted: dict | None = None): + if level not in ("auto", "item", "domain"): + raise ValueError(f"level must be auto, item or domain, not {level!r}") + self.level = level + self.fitted = fitted + + def fit(self, cohort: pd.DataFrame) -> LegacyAdos2Association: + t = _table(cohort.reset_index(drop=True)) + level = self.level if self.level != "auto" else ("item" if ai.hay_items(t) else "domain") + rows = [] + for par in _pairs(level): + if par["predictor"] not in t: + continue + d = t.copy() + d[par["predictor"]] = d[par["predictor"]].replace([np.inf, -np.inf], np.nan) + item = par["tipo"] == "item" + if item: + d["_y"] = ai.item_por_nino(t, par["resultado"]) + d["_alterado"] = (d["_y"] >= 1).astype(float).where(d["_y"].notna()) + principal = _guarded(mo.firth, "firth", d, "_alterado", par["predictor"], ADJUST, por_fila=True) + sensitivity = _guarded(mo.ordinal, "ordinal", d, "_y", par["predictor"], ADJUST) + else: + principal = _guarded(mo.ordinal, "ordinal", d, "css_total", par["predictor"], ADJUST, + corte_alto=CSS_HIGH, por_fila=True) + d["_alto"] = (d["css_total"] >= CSS_HIGH).astype(float).where(d["css_total"].notna()) + sensitivity = _guarded(mo.firth, "firth", d, "_alto", par["predictor"], ADJUST) + by_row = principal.pop("prob_por_fila", {}) + rows.append({ + "biomarker": BIOMARKER[par["biomarcador"]], "zone": ZONE[par["zona"]], + "kind": "item" if item else "domain", "outcome": par["resultado"] if item else "CSS", + "predictor": par["predictor"], "principal": principal, "sensitivity": sensitivity, + "scores": {str(t.loc[i, "key"]): [float(t.loc[i, par["predictor"]]), float(v)] + for i, v in by_row.items()}, + }) + biomarkers = np.array([r["biomarker"] for r in rows]) + p = np.array([r["principal"].get("p", np.nan) for r in rows], float) + q = np.full(len(rows), np.nan) + for b in dict.fromkeys(biomarkers): + q[biomarkers == b] = mo.bh(p[biomarkers == b]).round(5) + for r, v in zip(rows, q): + r["q"] = None if np.isnan(v) else float(v) + self.fitted = {"level": level, "n": len(cohort), "rows": rows} + return self + + def _rows(self) -> list[dict]: + if self.fitted is None: + raise ValueError(f"{self.name}: fit() before associations() or score()") + return self.fitted["rows"] + + @staticmethod + def _code(r) -> str: + return f"ados2_item_{r['outcome']:02d}" if r["kind"] == "item" else "CSS" + + def associations(self) -> pd.DataFrame: + out = [] + for r in self._rows(): + f, s = r["principal"], r["sensitivity"] + ors, sens = f.get("or"), s.get("or") + out.append({ + "biomarker": r["biomarker"], "zone": r["zone"], "kind": r["kind"], "outcome": r["outcome"], + "outcome_code": self._code(r), "event": ">=1" if r["kind"] == "item" else f">={CSS_HIGH}", + "model": f["modelo"], "n": f["n"], "odds_ratio": ors, "ci_low": f.get("ic_inf"), + "ci_high": f.get("ic_sup"), "p": f.get("p"), "q": r["q"], "sens_model": s["modelo"], + "sens_odds_ratio": sens, + "same_direction": (None if ors is None or sens is None + else bool(np.sign(ors - 1) == np.sign(sens - 1))), + "reason": f.get("motivo", ""), + }) + return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS)) + + def score(self, cohort: pd.DataFrame) -> pd.DataFrame: + """The probabilities the fit gave each of its children in `cohort`, with the pair's reference probability + (z = 0, mean age, most frequent module).""" + keys = set(cohort["key"].astype(str)) + rows = [{"key": k, "biomarker": r["biomarker"], "zone": r["zone"], "outcome_code": self._code(r), "z": z, + "probability": prob, "reference_probability": r["principal"].get("prob_z0")} + for r in self._rows() if r["principal"].get("or") is not None + for k, (z, prob) in r["scores"].items() if k in keys] + return pd.DataFrame(rows, columns=list(SCORE_COLUMNS)) + + def save(self, path) -> None: + Path(path, "association.json").write_text(json.dumps( + {"level": self.level, "fitted": self.fitted}, default=float)) + + @classmethod + def load(cls, path) -> LegacyAdos2Association: + d = json.loads(Path(path, "association.json").read_text()) + return cls(d["level"], d["fitted"]) + + +MODULE = LegacyAdos2Association() diff --git a/src/tea/legacy/biomarkers/aperiodic/_baseline.py b/src/tea/legacy/biomarkers/aperiodic/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/aperiodic/_baseline.py +++ b/src/tea/legacy/biomarkers/aperiodic/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/aperiodic/api.py b/src/tea/legacy/biomarkers/aperiodic/api.py index cc00670..7f26e7c 100644 --- a/src/tea/legacy/biomarkers/aperiodic/api.py +++ b/src/tea/legacy/biomarkers/aperiodic/api.py @@ -38,7 +38,7 @@ DIRECTOR_COMMIT = "7dfc641" class LegacyAperiodic: name = "aperiodic" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state", "annotation_mask") features = FEATURES diff --git a/src/tea/legacy/biomarkers/coupling/_baseline.py b/src/tea/legacy/biomarkers/coupling/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/coupling/_baseline.py +++ b/src/tea/legacy/biomarkers/coupling/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/coupling/_director/eeg_io.py b/src/tea/legacy/biomarkers/coupling/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/coupling/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/coupling/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/coupling/api.py b/src/tea/legacy/biomarkers/coupling/api.py index 8283b87..6723ddb 100644 --- a/src/tea/legacy/biomarkers/coupling/api.py +++ b/src/tea/legacy/biomarkers/coupling/api.py @@ -21,13 +21,13 @@ from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS from . import _adapter, _baseline -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" FEATURES = ("coupling_r", "coupling_r_over_floor", "coupling_angle_deg", "coupling_r_raw") class LegacyCoupling: name = "coupling" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("spindle_detection",) features = FEATURES diff --git a/src/tea/legacy/biomarkers/gradient/_baseline.py b/src/tea/legacy/biomarkers/gradient/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/gradient/_baseline.py +++ b/src/tea/legacy/biomarkers/gradient/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/gradient/_director/eeg_io.py b/src/tea/legacy/biomarkers/gradient/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/gradient/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/gradient/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/gradient/api.py b/src/tea/legacy/biomarkers/gradient/api.py index 88e181b..2a835e7 100644 --- a/src/tea/legacy/biomarkers/gradient/api.py +++ b/src/tea/legacy/biomarkers/gradient/api.py @@ -20,7 +20,7 @@ from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS from . import _adapter, _baseline -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" BANDS = ("delta", "theta", "alfa", "beta") # pipeline.BANDAS_GRADIENTE STATES = ("sueno", "somnolencia") MIN_WINDOWS = 15 @@ -39,7 +39,7 @@ def gradiente(est, inicios, g, min_ventanas=MIN_WINDOWS) -> dict: class LegacyGradient: name = "gradient" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state",) features = FEATURES diff --git a/src/tea/legacy/biomarkers/mse/_baseline.py b/src/tea/legacy/biomarkers/mse/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/mse/_baseline.py +++ b/src/tea/legacy/biomarkers/mse/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/mse/api.py b/src/tea/legacy/biomarkers/mse/api.py index ab8e054..373ef24 100644 --- a/src/tea/legacy/biomarkers/mse/api.py +++ b/src/tea/legacy/biomarkers/mse/api.py @@ -37,7 +37,7 @@ DIRECTOR_COMMIT = "7dfc641" class LegacyMSE: name = "mse" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state", "annotation_mask") features = FEATURES diff --git a/src/tea/legacy/biomarkers/posterior_rhythm/_baseline.py b/src/tea/legacy/biomarkers/posterior_rhythm/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/posterior_rhythm/_baseline.py +++ b/src/tea/legacy/biomarkers/posterior_rhythm/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/posterior_rhythm/_director/eeg_io.py b/src/tea/legacy/biomarkers/posterior_rhythm/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/posterior_rhythm/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/posterior_rhythm/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/posterior_rhythm/api.py b/src/tea/legacy/biomarkers/posterior_rhythm/api.py index 5316037..d3ababc 100644 --- a/src/tea/legacy/biomarkers/posterior_rhythm/api.py +++ b/src/tea/legacy/biomarkers/posterior_rhythm/api.py @@ -23,7 +23,7 @@ from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS from . import _adapter, _baseline -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" POSTERIORES = ("O1", "O2", "P3", "P4") # medidas_director.POSTERIORES MIN_CANALES_RITMO = 2 # medidas_director.MIN_CANALES_RITMO @@ -68,7 +68,7 @@ def ritmo(est, inicios_vigilia, r, eeg_io, min_ventanas=None) -> dict: class LegacyPosteriorRhythm: name = "posterior_rhythm" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state",) features = ("posterior_rhythm_hz",) diff --git a/src/tea/legacy/biomarkers/slow_waves/_baseline.py b/src/tea/legacy/biomarkers/slow_waves/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/slow_waves/_baseline.py +++ b/src/tea/legacy/biomarkers/slow_waves/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/slow_waves/_director/eeg_io.py b/src/tea/legacy/biomarkers/slow_waves/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/slow_waves/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/slow_waves/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/slow_waves/api.py b/src/tea/legacy/biomarkers/slow_waves/api.py index d3e4b63..2d21d95 100644 --- a/src/tea/legacy/biomarkers/slow_waves/api.py +++ b/src/tea/legacy/biomarkers/slow_waves/api.py @@ -19,7 +19,7 @@ from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS from . import _baseline -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" FEATURES = {"slow_wave_frac_n3": "frac_N3", "slow_wave_density": "densidad_por_min_canal", "slow_wave_frequency_hz": "frecuencia_mediana_Hz", "slow_wave_p2p_uv": "p2p_mediana_uV"} DIRECTOR_COLS = ["t_ini_s", "duracion_s", "dur_neg_s", "frecuencia_Hz", "p2p_uV", "pico_neg_uV", @@ -28,7 +28,7 @@ DIRECTOR_COLS = ["t_ini_s", "duracion_s", "dur_neg_s", "frecuencia_Hz", "p2p_uV" class LegacySlowWaves: name = "slow_waves" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("slow_wave_staging",) features = tuple(FEATURES) diff --git a/src/tea/legacy/biomarkers/spikes/_baseline.py b/src/tea/legacy/biomarkers/spikes/_baseline.py index 167759e..958413f 100644 --- a/src/tea/legacy/biomarkers/spikes/_baseline.py +++ b/src/tea/legacy/biomarkers/spikes/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, @@ -227,7 +229,95 @@ class AgeBlockZ: return cls(d["edad_min"], d["edad_max"], d["state"]) -BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ} +# ------------------------------------------------------------------ counts against their minutes +class CountRate: + """Spike candidates against the minutes they were looked for in, as the research reference of candidates + (biomarcadores-tea/biomarcadores/picos_ref.py @ 366f7e1: referencia, percentil). Most children of the reference + have none, so a centile curve collapses at 0; here the reference is the aggregate rate per minute of the children + within `edad_min`..`edad_max` and its dispersion between children (negative binomial by moments, Poisson when + there is none). + + A value is a rate: its count is value x exposure x `scale` (`scale` the electrodes a per-electrode zone value + was divided by). z = Phi^-1(1 - mid-p), the mid-p tail of seeing that many or more in the child's own minutes, + clipped to +-Z_MAX; outside = +1 when P(N >= n) < 0.05, else 0. No exposure, value or reference: NaN. + """ + + name = "count_rate" + Z_MAX = 8.0 + + def __init__(self, edad_min=16.0, edad_max=37.0, scale=1.0, state=None): + self.edad_min = float(edad_min) + self.edad_max = float(edad_max) + self.scale = float(scale) + self.state = state + + def _counts(self, values, exposure): + x = np.asarray(exposure, float) * self.scale + return np.round(np.asarray(values, float) * x), x + + def fit(self, values, ages_months, exposure=None): + e = np.asarray(ages_months, float) + if exposure is None: + exposure = np.full(len(e), np.nan) + n, x = self._counts(values, exposure) + keep = np.isfinite(n) & np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + n, x = n[keep], x[keep] + rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") + mu = rate * x + excess = float(((n - mu) ** 2 - n).sum()) + k = float((mu ** 2).sum() / excess) if excess > 0 else float("inf") + self.state = {"rate": rate, "k": k, "reference": int(keep.sum()), "events": int(n.sum())} + return self + + def deviation(self, values, ages_months, exposure=None): + from scipy import stats + + e = np.asarray(ages_months, float) + z = np.full(len(e), np.nan) + outside = np.full(len(e), np.nan) + rate = (self.state or {}).get("rate", float("nan")) + if exposure is None or not np.isfinite(rate): + return outside, z + n, x = self._counts(values, exposure) + ok = np.isfinite(n) & np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + mu, k = rate * x[ok], self.state["k"] + if np.isfinite(k): + p = k / (k + mu) + tail, at = stats.nbinom.sf(n[ok] - 1, k, p), stats.nbinom.pmf(n[ok], k, p) + else: + tail, at = stats.poisson.sf(n[ok] - 1, mu), stats.poisson.pmf(n[ok], mu) + z[ok] = np.clip(stats.norm.ppf(1 - (tail - at / 2)), -self.Z_MAX, self.Z_MAX) + outside[ok] = np.where(tail < 0.05, 1.0, 0.0) + return outside, z + + def percentiles(self, ages_months, exposure, q=(0.05, 0.5, 0.95)): + """The rates at the quantiles `q` of the reference's count in each child's own minutes, one row per child + and one column per quantile; NaN where z would be.""" + from scipy import stats + + e = np.asarray(ages_months, float) + out = np.full((len(e), len(q)), np.nan) + rate = (self.state or {}).get("rate", float("nan")) + if exposure is None or not np.isfinite(rate): + return out + x = np.asarray(exposure, float) * self.scale + ok = np.isfinite(x) & (x > 0) & (e >= self.edad_min) & (e < self.edad_max) + mu, k = rate * x[ok], self.state["k"] + for j, p in enumerate(q): + counts = (stats.nbinom.ppf(p, k, k / (k + mu)) if np.isfinite(k) else stats.poisson.ppf(p, mu)) + out[ok, j] = counts / x[ok] + return out + + def to_dict(self): + return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, "scale": self.scale, + "state": self.state} + + @classmethod + def from_dict(cls, d): + return cls(d["edad_min"], d["edad_max"], d.get("scale", 1.0), d["state"]) + + +BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ, "count_rate": CountRate} def make(name, **params): diff --git a/src/tea/legacy/biomarkers/spikes/_density.py b/src/tea/legacy/biomarkers/spikes/_density.py new file mode 100644 index 0000000..12d1ab8 --- /dev/null +++ b/src/tea/legacy/biomarkers/spikes/_density.py @@ -0,0 +1,216 @@ +""" +Spike density by electrode and zone, and state inheritance, on the vendored +director code: which candidates count as useful (a field and no +normal-graphoelement mark), the per-electrode and per-zone density per state, +and the inherited variant where a stretch without a clean-window state takes +the nearest labeled window's state (30 s reach, conservative on state +transitions). + +Ported from the research repo's medidas_director.py (estados_con_herencia, +categoria_candidato, _puerta, minutos_por_origen and the por_canal table of +picos), calling the vendored candidatos_punta and seleccion. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from tea.contracts import ZONES + +from ._director.candidatos_punta import VECINOS_1020 + +GRID_S = 0.5 +STATES = {"nrem": ("sueno",), "awake": ("vigilia", "somnolencia")} + + +def inherit_states(labeled, duration_s, inherit_s=30.0, t_min=0.0) -> pd.DataFrame: + """State intervals on a 0.5 s grid: a point keeps its clean-window state; + an unlabeled point from `t_min` (and from the first labeled window) takes + the nearest labeled window's state when it is within `inherit_s`. When the + nearest windows before and after carry different states, the stretch stays + 'transicion' (it counts in neither state). Columns: t_ini_s, t_fin_s, + etiqueta, heredado; no overlaps.""" + cols = ["t_ini_s", "t_fin_s", "etiqueta", "heredado"] + if not len(labeled): + return pd.DataFrame(columns=cols) + paso = GRID_S + t = np.arange(0.0, float(duration_s), paso) + etq = np.full(len(t), "", dtype=object) + filas = sorted(zip(labeled.t_ini_s.astype(float), labeled.t_fin_s.astype(float), + labeled.etiqueta.astype(str))) + for t0, t1, e in filas: + m = (t >= t0) & (t < t1) & (etq == "") + etq[m] = e + directo = etq != "" + heredado = np.zeros(len(t), dtype=bool) + if directo.any() and inherit_s > 0: + td = t[directo] + inicio = max(float(t_min or 0.0), float(td[0])) + faltan = np.flatnonzero(~directo & (t >= inicio)) + if len(faltan): + ed = etq[directo] + tf = t[faltan] + j = np.searchsorted(td, tf) + hay_a, hay_d = j > 0, j < len(td) + ia, idp = np.clip(j - 1, 0, len(td) - 1), np.clip(j, 0, len(td) - 1) + da = np.where(hay_a, tf - td[ia], np.inf) + dd = np.where(hay_d, td[idp] - tf, np.inf) + transicion = hay_a & hay_d & (ed[ia] != ed[idp]) + lab = np.where(da <= dd, ed[ia], ed[idp]) + ok = ~transicion & (np.minimum(da, dd) <= inherit_s) + etq[faltan[ok]] = lab[ok] + heredado[faltan[ok]] = True + etq[faltan[transicion]] = "transicion" + heredado[faltan[transicion]] = True + filas, k = [], 0 + while k < len(t): + if etq[k] == "": + k += 1 + continue + j = k + while j + 1 < len(t) and etq[j + 1] == etq[k] and heredado[j + 1] == heredado[k]: + j += 1 + filas.append({"t_ini_s": float(t[k]), "t_fin_s": float(t[j] + paso), + "etiqueta": etq[k], "heredado": bool(heredado[k])}) + k = j + 1 + return pd.DataFrame(filas, columns=cols) + + +def candidate_category(ev) -> np.ndarray: + """One category per candidate: 'util' (a field and no mark), else the + first matching mark in the director's order (posts, vertice, ocular) or + 'aislado' when there is no field at all.""" + cat = np.full(len(ev), "util", dtype=object) + if not len(ev): + return cat + cat[(ev.vecinos == 0).to_numpy()] = "aislado" + for marca in ("posts", "vertice", "ocular"): + cat[ev[marca].to_numpy(bool)] = marca + return cat + + +def useful(ev) -> pd.DataFrame: + """The candidates that count for densities: with field, no mark.""" + if not len(ev): + return ev + return ev[~ev.vertice & ~ev.posts & ~ev.ocular & (ev.vecinos > 0)] + + +def gate_windows(est, eeg_io, vent_s, reject_transient) -> pd.DataFrame: + """The detector's 2 s quality-gate windows over the whole recording, with + the same rejection rule as de_estudio (muscle, frozen, gap, annotated + state; a transient only when `reject_transient`). Columns include apta.""" + from ._director import seleccion + + canales = [c for c in eeg_io.canales_de(est.canales, "eeg") if c in VECINOS_1020] + sel = seleccion.seleccionar(est, vent_s=vent_s, paso_s=vent_s, canales=canales) + mot = sel.motivo.fillna("").astype(str) + bad = mot.str.contains("musculo|congelada|hueco|estado |caballo", regex=True) + if reject_transient: + bad = bad | mot.str.contains("transitorio") + return sel.assign(motivo=mot, apta=~bad)[["t_ini_s", "t_fin_s", "motivo", "apta"]] + + +def minutes_by_origin(gate, states, vent_s=2.0) -> dict: + """Clean gate minutes per state interval, keyed directo_ for + clean-window intervals and heredado_ for inherited ones (including + heredado_transicion): each clean window counts where its midpoint falls.""" + out = {} + if not len(states): + return out + apt = gate[gate.apta] + mid = ((apt.t_ini_s + apt.t_fin_s) / 2).to_numpy(float) + for r in states.itertuples(): + n = int(((mid >= r.t_ini_s) & (mid < r.t_fin_s)).sum()) + k = ("heredado_" if r.heredado else "directo_") + str(r.etiqueta) + out[k] = out.get(k, 0.0) + n * vent_s / 60.0 + return out + + +def _counts(ev, electrodes, fases): + u = useful(ev) if ev is not None else ev + if u is None or not len(u): + return {c: 0 for c in electrodes} + sub = u[u.fase.isin(fases)] + if not len(sub): + return {c: 0 for c in electrodes} + cuenta = sub.canal_max.value_counts() + return {c: int(cuenta.get(c, 0)) for c in electrodes} + + +def _state_minutes(minutes, fases): + return float(sum(minutes.get(f, 0.0) for f in fases)) if minutes is not None else 0.0 + + +def state_rates(ev, minutes, states=STATES) -> dict: + """The overall rate per state (as the director's tasa_NREM / tasa_despierto): + useful candidates in the state's phases per clean minute of the state, NaN + without minutes. indicadores rounds each phase's minutes to two decimals + before dividing; these rates keep that convention.""" + redondeados = {} + for fases in states.values(): + for f in fases: + redondeados[f] = round(float(minutes.get(f, 0.0)), 2) if minutes is not None else 0.0 + u = useful(ev) if ev is not None else ev + out = {} + for estado, fases in states.items(): + m = sum(redondeados.get(f, 0.0) for f in fases) + n = int(u.fase.isin(fases).sum()) if u is not None and len(u) else 0 + out[estado] = round(n / m, 3) if m > 0 else float("nan") + return out + + +def electrode_densities(ev, minutes, electrodes, present, states=STATES) -> dict: + """{spike_density__: useful candidates whose canal_max is E per + clean minute of the state}. `electrodes` is the fixed 10-20 feature order + and `present` the study's electrodes among them: a present electrode with + no candidates is 0; an absent electrode, or a state with no minutes, is + NaN.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, electrodes, fases) + for c in electrodes: + v = round(n_por_canal[c] / m, 4) if (m > 0 and c in set(present)) else float("nan") + out[f"spike_density_{estado}_{c}"] = v + return out + + +def zone_densities(ev, minutes, present, prefix="spike_zone", states=STATES, + zones=ZONES) -> dict: + """{__: the zone's useful candidates per clean minute + and per present electrode, so zones of different sizes compare}. NaN when + the state has no minutes or the zone has no present electrode.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, present, fases) + for zona, electrodos in zones.items(): + cs = [c for c in electrodos if c in set(present)] + if not cs: + out[f"{prefix}_{estado}_{zona}"] = float("nan") + continue + n = sum(n_por_canal[c] for c in cs) + out[f"{prefix}_{estado}_{zona}"] = round(n / (m * len(cs)), 4) if m > 0 else float("nan") + return out + + +def minutes_features(minutes, prefix="spike_minutes", states=STATES) -> dict: + """{_: the clean minutes of the state}, what the rates and densities divide by.""" + return {f"{prefix}_{s}": round(_state_minutes(minutes, fases), 4) for s, fases in states.items()} + + +def zone_rates(ev, minutes, present, states=STATES, zones=ZONES) -> dict: + """{spike_zone_rate__: the zone's useful candidates per clean minute of the state}, not divided by + its electrodes (the research's candidates per zone). NaN when the state has no minutes or the zone has no + present electrode.""" + out = {} + for estado, fases in states.items(): + m = _state_minutes(minutes, fases) + n_por_canal = _counts(ev, present, fases) + for zona, electrodos in zones.items(): + cs = [c for c in electrodos if c in set(present)] + out[f"spike_zone_rate_{estado}_{zona}"] = (round(sum(n_por_canal[c] for c in cs) / m, 4) + if cs and m > 0 else float("nan")) + return out diff --git a/src/tea/legacy/biomarkers/spikes/_director/eeg_io.py b/src/tea/legacy/biomarkers/spikes/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/spikes/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/spikes/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/spikes/api.py b/src/tea/legacy/biomarkers/spikes/api.py index 81e2baa..eca1c62 100644 --- a/src/tea/legacy/biomarkers/spikes/api.py +++ b/src/tea/legacy/biomarkers/spikes/api.py @@ -1,7 +1,9 @@ """ Legacy spikes: candidatos_punta.de_estudio + indicadores (vendored unchanged) on -the contract adapter, with the sleep_state labels as the vigilancia table. The -quality gate inside is seleccion.seleccionar, as in the director's script. +the contract adapter, with the sleep_state labels as the vigilancia table; plus +the per-electrode and per-zone densities per state and the inherited-state +variant (_density.py), as the research repo's medidas_director computes them. +The quality gate inside is seleccion.seleccionar, as in the director's script. Descriptive features (spike candidates are not validated against a reader). """ @@ -15,64 +17,141 @@ from pathlib import Path import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS +from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS, ZONES -from . import _adapter, _baseline +from . import _adapter, _baseline, _density +from ._director.candidatos_punta import VECINOS_1020 -DIRECTOR_COMMIT = "7dfc641" -FEATURES = {"spike_rate_awake": "tasa_despierto", "spike_rate_nrem": "tasa_NREM", - "spike_nrem_activation": "activacion_NREM", "spike_focus_frac": "foco_frac", - "spike_laterality": "lateralidad", "spike_frac_generalized": "frac_generalizado", - "spike_index_nrem": "indice_punta_onda_NREM"} +DIRECTOR_COMMIT = "366f7e1" +INDICATORS = {"spike_rate_awake": "tasa_despierto", "spike_rate_nrem": "tasa_NREM", + "spike_nrem_activation": "activacion_NREM", "spike_focus_frac": "foco_frac", + "spike_laterality": "lateralidad", "spike_frac_generalized": "frac_generalizado", + "spike_index_nrem": "indice_punta_onda_NREM"} +ELECTRODES = tuple(VECINOS_1020) +STATES = ("nrem", "awake") +FEATURES = tuple(INDICATORS) + \ + tuple(f"spike_density_{s}_{e}" for s in STATES for e in ELECTRODES) + \ + tuple(f"spike_zone_{s}_{z}" for s in STATES for z in ZONES) + \ + tuple(f"spike_zone_rate_{s}_{z}" for s in STATES for z in ZONES) + \ + tuple(f"spike_inherited_rate_{s}" for s in STATES) + \ + tuple(f"spike_inherited_zone_{s}_{z}" for s in STATES for z in ZONES) +# The clean minutes each rate divides by: exposure for the count baselines, with no baseline of their own. +MINUTES = tuple(f"spike_minutes_{s}" for s in STATES) + tuple(f"spike_inherited_minutes_{s}" for s in STATES) +# Each rate or density feature, by the minutes feature of its state and variant: these are counted against their +# minutes (`_baseline.CountRate`); a per-electrode zone value is also multiplied back by the zone's electrodes. +EXPOSURE = { + **{f"spike_rate_{s}": f"spike_minutes_{s}" for s in STATES}, + **{f"spike_density_{s}_{e}": f"spike_minutes_{s}" for s in STATES for e in ELECTRODES}, + **{f"spike_zone_{s}_{z}": f"spike_minutes_{s}" for s in STATES for z in ZONES}, + **{f"spike_zone_rate_{s}_{z}": f"spike_minutes_{s}" for s in STATES for z in ZONES}, + **{f"spike_inherited_rate_{s}": f"spike_inherited_minutes_{s}" for s in STATES}, + **{f"spike_inherited_zone_{s}_{z}": f"spike_inherited_minutes_{s}" for s in STATES for z in ZONES}, +} +SCALE = {f"{prefix}_{s}_{z}": float(len(electrodes)) for prefix in ("spike_zone", "spike_inherited_zone") + for s in STATES for z, electrodes in ZONES.items()} + + +def _exposure(t: pd.DataFrame, feature: str) -> np.ndarray: + """The minutes `feature` was counted in, from the table; NaN when the table doesn't carry them.""" + column = EXPOSURE[feature] + return t[column].to_numpy(float) if column in t else np.full(len(t), np.nan) class LegacySpikes: name = "spikes" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.4.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state",) - features = tuple(FEATURES) + features = FEATURES impl = "legacy" - def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None): + def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None, + vent_s=2.0, rechazar_transitorio=False, herencia_s=30.0, stable_start_s=0.0): self.variant = variant self.baseline_name = baseline self.baseline_params = dict(baseline_params or {}) self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted - else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) + else {f: self._new_baseline(f, baseline) for f in FEATURES}) self._fitted = fitted is not None + self._evaluable = tuple(self.baselines) if fitted else () + self.vent_s = float(vent_s) + self.rechazar_transitorio = bool(rechazar_transitorio) + self.herencia_s = float(herencia_s) + # No state is inherited before this (the montage's stable start). Tea + # validation assumes EDFs begin at the stable signal, so 0 by default. + self.stable_start_s = float(stable_start_s) + + def _new_baseline(self, feature, baseline): + """A count reference for the rates and densities, the configured baseline for the other features.""" + if feature in EXPOSURE: + return _baseline.CountRate(scale=SCALE.get(feature, 1.0)) + return _baseline.make(baseline, **self.baseline_params) @staticmethod def _vig(study): - """The sleep_state labels as the director's vigilancia table (t_ini_s, t_fin_s, etiqueta).""" + """The sleep_state labels as the director's vigilancia table (t_ini_s, t_fin_s, + etiqueta): each labeled window keeps its full classified length, as the research + states table labels VENT_VIGILANCIA_S per window.""" w, lab = study.prep.windows, study.label("sleep_state").per_window - step = float(w.start_s.iloc[1] - w.start_s.iloc[0]) if len(w) > 1 else 2.0 - v = pd.DataFrame({"t_ini_s": w.start_s.astype(float), "t_fin_s": w.start_s.astype(float) + step, + v = pd.DataFrame({"t_ini_s": w.start_s.astype(float), "t_fin_s": w.end_s.astype(float), "etiqueta": lab.values}) return v[v.etiqueta.isin(("vigilia", "somnolencia", "sueno"))].reset_index(drop=True) - def measure(self, study) -> dict: - ind = self.indicators(study) - if ind is None: - return {f: float("nan") for f in FEATURES} - return {f: float(ind[k]) if ind.get(k) is not None else float("nan") for f, k in FEATURES.items()} + def _events(self, cp, est, vig): + """One detector run over `vig`: the candidate table and the clean minutes per state. + (None, None) when the montage has too few 10-20 electrodes.""" + ev, minutos, _ = cp.de_estudio(est, "", vig, None, calidad=True, + vent_s=self.vent_s, + rechazar_transitorio=self.rechazar_transitorio) + return (None, None) if ev is None else (ev, minutos) - def indicators(self, study): - from ._director import candidatos_punta as cp, eeg_io - with _adapter.estudio(study.prep, self.variant, eeg_io) as est, contextlib.redirect_stdout(io.StringIO()): - ev, minutos, _ = cp.de_estudio(est, "", self._vig(study), None) + def _run(self, cp, est, vig): + """The director's indicadores for a run over `vig` (None without one).""" + ev, minutos = self._events(cp, est, vig) if ev is None: return None return cp.indicadores("", ev, minutos) + def indicators(self, study): + from ._director import candidatos_punta as cp, eeg_io + + with _adapter.estudio(study.prep, self.variant, eeg_io) as est, contextlib.redirect_stdout(io.StringIO()): + return self._run(cp, est, self._vig(study)) + + def measure(self, study) -> dict: + from ._director import candidatos_punta as cp, eeg_io + + with _adapter.estudio(study.prep, self.variant, eeg_io) as est, contextlib.redirect_stdout(io.StringIO()): + canales = [c for c in eeg_io.canales_de(est.canales, "eeg") if c in VECINOS_1020] + vig = self._vig(study) + ev, minutos = self._events(cp, est, vig) + ind = None if ev is None else cp.indicadores("", ev, minutos) + out = {f: (float(ind[k]) if ind is not None and ind.get(k) is not None else float("nan")) + for f, k in INDICATORS.items()} + out.update(_density.electrode_densities(ev, minutos, ELECTRODES, canales)) + out.update(_density.zone_densities(ev, minutos, canales)) + out.update(_density.zone_rates(ev, minutos, canales)) + out.update(_density.minutes_features(minutos)) + heredados = _density.inherit_states(vig, est.duracion, self.herencia_s, + t_min=self.stable_start_s) + ev_h, minutos_h = self._events(cp, est, heredados) + for s, v in _density.state_rates(ev_h, minutos_h).items(): + out[f"spike_inherited_rate_{s}"] = v + out.update(_density.minutes_features(minutos_h, prefix="spike_inherited_minutes")) + out.update(_density.zone_densities(ev_h, minutos_h, canales, + prefix="spike_inherited_zone")) + return out + def train(self, data, ages_months=None): if isinstance(data, pd.DataFrame): t = data else: t = pd.DataFrame([self.measure(s) for s in data]) t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] - for f, b in self.baselines.items(): - b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self._evaluable = tuple(f for f in self.baselines if f in t.columns) + for f in self._evaluable: + b, args = self.baselines[f], (t[f].to_numpy(float), t["age_months"].to_numpy(float)) + b.fit(*args, exposure=_exposure(t, f)) if isinstance(b, _baseline.CountRate) else b.fit(*args) self._fitted = True return self @@ -86,18 +165,27 @@ class LegacySpikes: t["age_months"] = [age_months if age_months is not None else data.prep.age_months] a = t["age_months"].to_numpy(float) parts = [] - for f, b in self.baselines.items(): + for f in self._evaluable: + if f not in t.columns: + continue + b = self.baselines[f] v = t[f].to_numpy(float) - outside, z = b.deviation(v, a) + if isinstance(b, _baseline.CountRate): + outside, z = b.deviation(v, a, exposure=_exposure(t, f)) + else: + outside, z = b.deviation(v, a) parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) return pd.concat(parts, ignore_index=True) def save(self, path): - Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "baseline": self.baseline_name, - "baseline_params": self.baseline_params})) - Path(path, "baseline.json").write_text(json.dumps( - {f: b.to_dict() for f, b in self.baselines.items()} if self._fitted else None, default=float)) + Path(path, "params.json").write_text(json.dumps( + {"variant": self.variant, "baseline": self.baseline_name, + "baseline_params": self.baseline_params, "vent_s": self.vent_s, + "rechazar_transitorio": self.rechazar_transitorio, "herencia_s": self.herencia_s, + "stable_start_s": self.stable_start_s})) + fitted = ({f: self.baselines[f].to_dict() for f in self._evaluable} if self._fitted else None) + Path(path, "baseline.json").write_text(json.dumps(fitted, default=float)) @classmethod def load(cls, path): diff --git a/src/tea/legacy/biomarkers/spindle_topography/_baseline.py b/src/tea/legacy/biomarkers/spindle_topography/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/spindle_topography/_baseline.py +++ b/src/tea/legacy/biomarkers/spindle_topography/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/spindle_topography/_director/eeg_io.py b/src/tea/legacy/biomarkers/spindle_topography/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/spindle_topography/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/spindle_topography/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/spindle_topography/_director/husos.py b/src/tea/legacy/biomarkers/spindle_topography/_director/husos.py index 7400b63..eebabf0 100644 --- a/src/tea/legacy/biomarkers/spindle_topography/_director/husos.py +++ b/src/tea/legacy/biomarkers/spindle_topography/_director/husos.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 7dfc641 -# source sha256 cbb444cfc560f879feeb45c0473f07ac0557f374784bbccdfcd797aef7cf8e2d. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 366f7e1 +# source sha256 a4b0fdb39593859aa0755c8d6a8da717dd08d26df2acdcbced7b23e9bccf956e. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -325,6 +325,183 @@ def resumen(ev, minutos, nombres, estudio): return filas +# --------------------------------------------------------------- husos largos y extremos +# +# Agregado el 18 nov 2026 (biomarcadores-tea, pedido del director). `detectar` +# parte todo tramo de mas de DUR_MAX en pedazos de DUR_MAX y cuenta cada pedazo +# como un huso: un huso extremo de 20 s se cuenta como unos siete husos normales +# y SUBE la densidad. Estas funciones no cambian `detectar` (su REFERENCIA sigue +# valiendo); miden aparte lo que el detector parte. +# +# Huso extremo (Gibbs y Gibbs 1962): de mayor voltaje y "mas continuo" que lo +# normal. No hay criterio de duracion publicado; los 20 s son los del director +# (y aparecen en Medscape, "Normal Sleep EEG"). Un huso normal dura ~0.8 s entre +# los 10 meses y los 3 anos (Gruber y Wise 2016). +LARGO_S = DUR_MAX # mas que esto, detectar ya lo parte +EXTREMO_S = 20.0 # definicion del director +UNION_S = 0.5 # huecos mas cortos dentro de un tramo se unen (diseno propio) + + +def _corridas(mascara): + """(inicio, fin) de cada corrida de True.""" + d = np.diff(mascara.astype(np.int8), prepend=0, append=0) + return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1))) + + +def tramos_largos(est, ventanas_sueno, canales=None, percentil=95.0, vent_s=4.0, + min_estrechez=1.5, realce_min=3.0, largo_s=LARGO_S, + union_s=UNION_S, solo_huso=True): + """ + Tramos de actividad sigma continua de mas de `largo_s`, por canal, en el sueno. + + Mismos umbrales que `detectar` (alto: max(p95, 3 x mediana); bajo: + max(p70, 1.6 x mediana) de la envolvente del propio canal en el sueno), pero + sin tope de duracion: un tramo es la corrida sobre el umbral bajo, uniendo + huecos de menos de `union_s`, cuyo NUCLEO continuo (sobre el umbral alto) + dura mas de `largo_s`. `duracion_s` es la extension; `duracion_nucleo_s`, + la que decide. Se exige lo mismo que + a un huso en el tramo entero: estrechez espectral >= `min_estrechez` y + frecuencia instantanea estable dentro de la banda sigma. + + Limite: los umbrales son relativos al propio sueno del nino. Si la actividad + sigma ocupa mas de ~30 % del sueno, el umbral bajo (p70) cae dentro de ella y + los tramos se cortan o no aparecen. Para ese caso esta `ocupacion_sigma`. + """ + from scipy.signal import welch, hilbert + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + x = est.datos(canales=nombres) + fs = est.fs + npv = int(vent_s * fs) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + minutos = float(dormido.sum() / fs / 60) + cols = ["canal", "t_ini_s", "duracion_s", "duracion_nucleo_s", "frecuencia_Hz", + "amplitud_uV", "estrechez", "realce"] + if minutos < 1: + return pd.DataFrame(columns=cols), minutos, nombres + bruto, env = envolvente_sigma(x, fs) + hueco = int(union_s * fs) + filas = [] + for i, nm in enumerate(nombres): + e = env[:, i].copy() + e[~dormido] = np.nan + val = e[np.isfinite(e)] + if len(val) < fs * 30: + continue + mediana = float(np.median(val)) or 1e-9 + u_alto = max(float(np.percentile(val, percentil)), realce_min * mediana) + u_bajo = max(float(np.percentile(val, max(50.0, percentil - 25))), + 1.6 * mediana) + nucleo = np.isfinite(e) & (e > u_alto) + ext = np.isfinite(e) & (e > u_bajo) + # unir huecos cortos (un huso continuo puede bajar un instante del umbral) + for m in (nucleo, ext): + for a, b in _corridas(~m): + if 0 < a and b < len(m) and (b - a) < hueco and dormido[a:b].all(): + m[a:b] = True + for a, b in _corridas(ext): + dur = (b - a) / fs + # La duracion que decide es la del NUCLEO (sobre el umbral alto), no la + # de la extension: con senal sintetica, la cola del umbral bajo alargaba + # husos normales de 1 s hasta 3-4 s y los contaba como largos. + dur_nuc = max(((d - c) / fs for c, d in _corridas(nucleo[a:b])), default=0.0) + if dur_nuc <= largo_s: + continue + seg = x[a:b, i] + if not np.isfinite(seg).all(): + continue + nper = int(min(len(seg), 2 * fs)) + f, P = welch(seg - seg.mean(), fs=fs, nperseg=nper, + nfft=max(1024, nper * 2)) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + estrechez = float(P[en].mean() / max(P[fuera].mean(), 1e-30)) + if estrechez < min_estrechez: + continue + fase = np.unwrap(np.angle(hilbert(bruto[a:b, i]))) + dif = np.diff(fase) * fs / (2 * np.pi) + dentro = dif[(dif >= SIGMA[0] - 1) & (dif <= SIGMA[1] + 1)] + if len(dentro) < 0.5 * max(len(dif), 1): + continue + filas.append({"canal": nm, "t_ini_s": round(a / fs, 3), + "duracion_s": round(dur, 2), + "duracion_nucleo_s": round(dur_nuc, 2), + "frecuencia_Hz": round(float(np.median(dentro)), 2), + # p5-p95 de la senal sigma: el pico a pico absoluto lo dispara un solo artefacto + "amplitud_uV": round(float(np.subtract(*np.percentile( + bruto[a:b, i], [95, 5]))), 1), + "estrechez": round(estrechez, 2), + "realce": round(float(np.nanmax(e[a:b]) / mediana), 2)}) + return pd.DataFrame(filas, columns=cols), minutos, nombres + + +def ocupacion_sigma(est, ventanas_sueno, canales=None, vent_s=4.0, ventana_s=2.0, + min_estrechez=1.5, solo_huso=True): + """ + Fraccion del sueno, por canal, en ventanas de `ventana_s` donde la banda + sigma sobresale (estrechez >= `min_estrechez`, el criterio de `detectar`). + + No depende de umbrales relativos a la amplitud del propio nino: sirve justo + cuando la actividad sigma es tan continua que los percentiles la absorben. + """ + from scipy.signal import welch + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + fs = est.fs + n = int(ventana_s * fs) + npv = int(vent_s * fs) + x = est.datos(canales=nombres) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + inicios = [a for a in range(0, len(x) - n + 1, n) if dormido[a:a + n].all()] + out = {} + if not inicios: + return out + seg = np.stack([x[a:a + n] for a in inicios]) # ventanas x muestras x canales + ok = np.isfinite(seg).all(axis=(1, 2)) + seg = seg[ok] + if not len(seg): + return out + f, P = welch(seg - seg.mean(axis=1, keepdims=True), fs=fs, nperseg=n, axis=1) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + est_ = P[:, en, :].mean(axis=1) / np.maximum(P[:, fuera, :].mean(axis=1), 1e-30) + for j, nm in enumerate(nombres): + out[nm] = round(float((est_[:, j] >= min_estrechez).mean()), 3) + return out + + +def resumen_largos(tl, minutos, extremo_s=EXTREMO_S): + """Por estudio: cuantos tramos largos y extremos, el mas largo y donde.""" + f = {"n_tramos_largos": int(len(tl)), + "n_husos_extremos": int((tl.duracion_nucleo_s >= extremo_s).sum()) if len(tl) else 0, + "dur_max_tramo_s": float(tl.duracion_nucleo_s.max()) if len(tl) else 0.0, + "canal_tramo_max": (tl.canal.iloc[int(np.argmax(tl.duracion_nucleo_s.values))] + if len(tl) else None), + "min_en_tramos_largos": round(float(tl.duracion_s.sum()) / 60, 2) if len(tl) else 0.0} + f["canales_con_extremos"] = (", ".join(sorted(tl.loc[tl.duracion_nucleo_s >= extremo_s, "canal"].unique())) + if f["n_husos_extremos"] else "") + return f + + +def sin_pedazos_de_largos(ev, tl): + """Los husos de `detectar` que NO son pedazos de un tramo largo del mismo canal.""" + if ev is None or not len(ev) or not len(tl): + return ev + quitar = np.zeros(len(ev), dtype=bool) + t0 = ev.t_ini_s.to_numpy(float) + t1 = t0 + ev.duracion_s.to_numpy(float) + for r in tl.itertuples(): + quitar |= ((ev.canal.to_numpy() == r.canal) & (t1 > r.t_ini_s) + & (t0 < r.t_ini_s + r.duracion_s)) + return ev[~quitar] + + def picos_sigma(est, eventos, region="central", ancho_s=2.0, min_eventos=15): """ ¿Uno o dos picos en la banda sigma, medidos SOBRE LOS HUSOS? diff --git a/src/tea/legacy/biomarkers/spindle_topography/api.py b/src/tea/legacy/biomarkers/spindle_topography/api.py index fc09d82..85b8d84 100644 --- a/src/tea/legacy/biomarkers/spindle_topography/api.py +++ b/src/tea/legacy/biomarkers/spindle_topography/api.py @@ -20,7 +20,7 @@ from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS from . import _adapter, _baseline -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz") # husos.CANALES_HUSO REFERENCE = "Fp1" FEATURES = tuple([f"topo_enh_{c}" for c in CHANNELS] + [f"topo_amp_rel_{c}" for c in CHANNELS if c != REFERENCE]) @@ -29,7 +29,7 @@ MARGIN_S = 0.25 class LegacySpindleTopography: name = "spindle_topography" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("spindle_detection", "sleep_state") features = FEATURES diff --git a/src/tea/legacy/biomarkers/spindles/_baseline.py b/src/tea/legacy/biomarkers/spindles/_baseline.py index 167759e..be211f3 100644 --- a/src/tea/legacy/biomarkers/spindles/_baseline.py +++ b/src/tea/legacy/biomarkers/spindles/_baseline.py @@ -158,7 +158,7 @@ class CentileCurves: def deviation(self, values, ages_months): z, pos = z_y_posicion(values, ages_months, self.curva) outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) - return outside.astype(int), z + return np.where(pos == "sin referencia", np.nan, outside), z def to_dict(self): return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, @@ -210,13 +210,15 @@ class AgeBlockZ: bordes = self.state["bordes"] b = np.digitize(e, bordes[1:-1]) z = np.full(len(v), np.nan) - for i, (x, k) in enumerate(zip(v, b)): + for i, (x, age, k) in enumerate(zip(v, e, b)): blk = self.state["blocks"][k] - if np.isfinite(blk["mad"]) and blk["mad"] != 0: + if np.isfinite(x) and np.isfinite(age) and np.isfinite(blk["mad"]) and blk["mad"] != 0: z[i] = (x - blk["median"]) / blk["mad"] P = pd.DataFrame({"m": z}) - F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) - return F["fuera_m"].to_numpy().astype(int), z + cuts = tuple(self.state["cortes"]) + F = marcar_fuera(P, {"m": cuts}) + outside = np.where(np.isfinite(z) & np.isfinite(cuts).all(), F["fuera_m"], np.nan) + return outside, z def to_dict(self): return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, diff --git a/src/tea/legacy/biomarkers/spindles/_director/eeg_io.py b/src/tea/legacy/biomarkers/spindles/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/biomarkers/spindles/_director/eeg_io.py +++ b/src/tea/legacy/biomarkers/spindles/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/biomarkers/spindles/_director/husos.py b/src/tea/legacy/biomarkers/spindles/_director/husos.py index 7400b63..eebabf0 100644 --- a/src/tea/legacy/biomarkers/spindles/_director/husos.py +++ b/src/tea/legacy/biomarkers/spindles/_director/husos.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 7dfc641 -# source sha256 cbb444cfc560f879feeb45c0473f07ac0557f374784bbccdfcd797aef7cf8e2d. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 366f7e1 +# source sha256 a4b0fdb39593859aa0755c8d6a8da717dd08d26df2acdcbced7b23e9bccf956e. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -325,6 +325,183 @@ def resumen(ev, minutos, nombres, estudio): return filas +# --------------------------------------------------------------- husos largos y extremos +# +# Agregado el 18 nov 2026 (biomarcadores-tea, pedido del director). `detectar` +# parte todo tramo de mas de DUR_MAX en pedazos de DUR_MAX y cuenta cada pedazo +# como un huso: un huso extremo de 20 s se cuenta como unos siete husos normales +# y SUBE la densidad. Estas funciones no cambian `detectar` (su REFERENCIA sigue +# valiendo); miden aparte lo que el detector parte. +# +# Huso extremo (Gibbs y Gibbs 1962): de mayor voltaje y "mas continuo" que lo +# normal. No hay criterio de duracion publicado; los 20 s son los del director +# (y aparecen en Medscape, "Normal Sleep EEG"). Un huso normal dura ~0.8 s entre +# los 10 meses y los 3 anos (Gruber y Wise 2016). +LARGO_S = DUR_MAX # mas que esto, detectar ya lo parte +EXTREMO_S = 20.0 # definicion del director +UNION_S = 0.5 # huecos mas cortos dentro de un tramo se unen (diseno propio) + + +def _corridas(mascara): + """(inicio, fin) de cada corrida de True.""" + d = np.diff(mascara.astype(np.int8), prepend=0, append=0) + return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1))) + + +def tramos_largos(est, ventanas_sueno, canales=None, percentil=95.0, vent_s=4.0, + min_estrechez=1.5, realce_min=3.0, largo_s=LARGO_S, + union_s=UNION_S, solo_huso=True): + """ + Tramos de actividad sigma continua de mas de `largo_s`, por canal, en el sueno. + + Mismos umbrales que `detectar` (alto: max(p95, 3 x mediana); bajo: + max(p70, 1.6 x mediana) de la envolvente del propio canal en el sueno), pero + sin tope de duracion: un tramo es la corrida sobre el umbral bajo, uniendo + huecos de menos de `union_s`, cuyo NUCLEO continuo (sobre el umbral alto) + dura mas de `largo_s`. `duracion_s` es la extension; `duracion_nucleo_s`, + la que decide. Se exige lo mismo que + a un huso en el tramo entero: estrechez espectral >= `min_estrechez` y + frecuencia instantanea estable dentro de la banda sigma. + + Limite: los umbrales son relativos al propio sueno del nino. Si la actividad + sigma ocupa mas de ~30 % del sueno, el umbral bajo (p70) cae dentro de ella y + los tramos se cortan o no aparecen. Para ese caso esta `ocupacion_sigma`. + """ + from scipy.signal import welch, hilbert + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + x = est.datos(canales=nombres) + fs = est.fs + npv = int(vent_s * fs) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + minutos = float(dormido.sum() / fs / 60) + cols = ["canal", "t_ini_s", "duracion_s", "duracion_nucleo_s", "frecuencia_Hz", + "amplitud_uV", "estrechez", "realce"] + if minutos < 1: + return pd.DataFrame(columns=cols), minutos, nombres + bruto, env = envolvente_sigma(x, fs) + hueco = int(union_s * fs) + filas = [] + for i, nm in enumerate(nombres): + e = env[:, i].copy() + e[~dormido] = np.nan + val = e[np.isfinite(e)] + if len(val) < fs * 30: + continue + mediana = float(np.median(val)) or 1e-9 + u_alto = max(float(np.percentile(val, percentil)), realce_min * mediana) + u_bajo = max(float(np.percentile(val, max(50.0, percentil - 25))), + 1.6 * mediana) + nucleo = np.isfinite(e) & (e > u_alto) + ext = np.isfinite(e) & (e > u_bajo) + # unir huecos cortos (un huso continuo puede bajar un instante del umbral) + for m in (nucleo, ext): + for a, b in _corridas(~m): + if 0 < a and b < len(m) and (b - a) < hueco and dormido[a:b].all(): + m[a:b] = True + for a, b in _corridas(ext): + dur = (b - a) / fs + # La duracion que decide es la del NUCLEO (sobre el umbral alto), no la + # de la extension: con senal sintetica, la cola del umbral bajo alargaba + # husos normales de 1 s hasta 3-4 s y los contaba como largos. + dur_nuc = max(((d - c) / fs for c, d in _corridas(nucleo[a:b])), default=0.0) + if dur_nuc <= largo_s: + continue + seg = x[a:b, i] + if not np.isfinite(seg).all(): + continue + nper = int(min(len(seg), 2 * fs)) + f, P = welch(seg - seg.mean(), fs=fs, nperseg=nper, + nfft=max(1024, nper * 2)) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + estrechez = float(P[en].mean() / max(P[fuera].mean(), 1e-30)) + if estrechez < min_estrechez: + continue + fase = np.unwrap(np.angle(hilbert(bruto[a:b, i]))) + dif = np.diff(fase) * fs / (2 * np.pi) + dentro = dif[(dif >= SIGMA[0] - 1) & (dif <= SIGMA[1] + 1)] + if len(dentro) < 0.5 * max(len(dif), 1): + continue + filas.append({"canal": nm, "t_ini_s": round(a / fs, 3), + "duracion_s": round(dur, 2), + "duracion_nucleo_s": round(dur_nuc, 2), + "frecuencia_Hz": round(float(np.median(dentro)), 2), + # p5-p95 de la senal sigma: el pico a pico absoluto lo dispara un solo artefacto + "amplitud_uV": round(float(np.subtract(*np.percentile( + bruto[a:b, i], [95, 5]))), 1), + "estrechez": round(estrechez, 2), + "realce": round(float(np.nanmax(e[a:b]) / mediana), 2)}) + return pd.DataFrame(filas, columns=cols), minutos, nombres + + +def ocupacion_sigma(est, ventanas_sueno, canales=None, vent_s=4.0, ventana_s=2.0, + min_estrechez=1.5, solo_huso=True): + """ + Fraccion del sueno, por canal, en ventanas de `ventana_s` donde la banda + sigma sobresale (estrechez >= `min_estrechez`, el criterio de `detectar`). + + No depende de umbrales relativos a la amplitud del propio nino: sirve justo + cuando la actividad sigma es tan continua que los percentiles la absorben. + """ + from scipy.signal import welch + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + fs = est.fs + n = int(ventana_s * fs) + npv = int(vent_s * fs) + x = est.datos(canales=nombres) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + inicios = [a for a in range(0, len(x) - n + 1, n) if dormido[a:a + n].all()] + out = {} + if not inicios: + return out + seg = np.stack([x[a:a + n] for a in inicios]) # ventanas x muestras x canales + ok = np.isfinite(seg).all(axis=(1, 2)) + seg = seg[ok] + if not len(seg): + return out + f, P = welch(seg - seg.mean(axis=1, keepdims=True), fs=fs, nperseg=n, axis=1) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + est_ = P[:, en, :].mean(axis=1) / np.maximum(P[:, fuera, :].mean(axis=1), 1e-30) + for j, nm in enumerate(nombres): + out[nm] = round(float((est_[:, j] >= min_estrechez).mean()), 3) + return out + + +def resumen_largos(tl, minutos, extremo_s=EXTREMO_S): + """Por estudio: cuantos tramos largos y extremos, el mas largo y donde.""" + f = {"n_tramos_largos": int(len(tl)), + "n_husos_extremos": int((tl.duracion_nucleo_s >= extremo_s).sum()) if len(tl) else 0, + "dur_max_tramo_s": float(tl.duracion_nucleo_s.max()) if len(tl) else 0.0, + "canal_tramo_max": (tl.canal.iloc[int(np.argmax(tl.duracion_nucleo_s.values))] + if len(tl) else None), + "min_en_tramos_largos": round(float(tl.duracion_s.sum()) / 60, 2) if len(tl) else 0.0} + f["canales_con_extremos"] = (", ".join(sorted(tl.loc[tl.duracion_nucleo_s >= extremo_s, "canal"].unique())) + if f["n_husos_extremos"] else "") + return f + + +def sin_pedazos_de_largos(ev, tl): + """Los husos de `detectar` que NO son pedazos de un tramo largo del mismo canal.""" + if ev is None or not len(ev) or not len(tl): + return ev + quitar = np.zeros(len(ev), dtype=bool) + t0 = ev.t_ini_s.to_numpy(float) + t1 = t0 + ev.duracion_s.to_numpy(float) + for r in tl.itertuples(): + quitar |= ((ev.canal.to_numpy() == r.canal) & (t1 > r.t_ini_s) + & (t0 < r.t_ini_s + r.duracion_s)) + return ev[~quitar] + + def picos_sigma(est, eventos, region="central", ancho_s=2.0, min_eventos=15): """ ¿Uno o dos picos en la banda sigma, medidos SOBRE LOS HUSOS? diff --git a/src/tea/legacy/biomarkers/spindles/api.py b/src/tea/legacy/biomarkers/spindles/api.py index ad4ea1b..af32284 100644 --- a/src/tea/legacy/biomarkers/spindles/api.py +++ b/src/tea/legacy/biomarkers/spindles/api.py @@ -1,12 +1,4 @@ -""" -Legacy spindles: husos.resumen on the spindle_detection events, as the cluster -route summarises them (medidas_director.husos @ 7dfc641). - -Features (the HK1K reference's spindle measures): density per minute per -channel, median frequency, % fast, median duration, slow and fast densities. -NaN when less than 1 minute of sleep was searched or no spindle was found -(the director's summary then has no density). -""" +"""Summarize sleep spindle events, long runs, sigma occupancy and scalp densities.""" from __future__ import annotations @@ -16,22 +8,61 @@ from pathlib import Path import numpy as np import pandas as pd -from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS +from tea.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS, ZONES from . import _baseline -DIRECTOR_COMMIT = "7dfc641" -FEATURES = {"spindle_density_per_min_channel": "densidad_por_min_canal", - "spindle_frequency_hz": "frecuencia_mediana_Hz", - "spindle_pct_fast": "pct_rapidos", - "spindle_duration_s": "duracion_mediana_s", - "spindle_density_slow": "densidad_lento", - "spindle_density_fast": "densidad_rapido"} +DIRECTOR_COMMIT = "366f7e1" +DIRECTOR_FEATURES = { + "spindle_density_per_min_channel": "densidad_por_min_canal", + "spindle_frequency_hz": "frecuencia_mediana_Hz", + "spindle_pct_fast": "pct_rapidos", + "spindle_duration_s": "duracion_mediana_s", + "spindle_density_slow": "densidad_lento", + "spindle_density_fast": "densidad_rapido", +} + +ADDITIONAL_FEATURES = ( + "spindle_density_per_min_channel_no_long", + "spindle_n_long_runs", + "spindle_n_extreme", + "spindle_max_run_s", + "spindle_sigma_occupancy_median", + "spindle_sigma_occupancy_max", + *(f"spindle_electrode_{channel}" for channels in ZONES.values() for channel in channels), + *(f"spindle_zone_{zone}" for zone in ZONES), +) + + +def _additional_summary(events, minutes): + extra = dict.fromkeys(ADDITIONAL_FEATURES, np.nan) + if events.empty or minutes <= 0 or not events.attrs.get("searched", True): + return extra + + extra.update(events.attrs.get("long_run_features", {})) + # Only the channels the detector searched: one it never looks at has no density, not zero. + searched = set(events.attrs.get("channels", ())) + present = set(events.attrs.get("eeg_channels", searched)) & searched + counts = events.channel.value_counts() + for zone, channels in ZONES.items(): + electrodes = [channel for channel in channels if channel in present] + if not electrodes: + continue + total = 0 + for channel in electrodes: + count = counts.get(channel, 0) + extra[f"spindle_electrode_{channel}"] = count / minutes + total += count + extra[f"spindle_zone_{zone}"] = total / (minutes * len(electrodes)) + return extra + + +FEATURES = {**DIRECTOR_FEATURES, **{f: f for f in ADDITIONAL_FEATURES}} class LegacySpindles: name = "spindles" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("spindle_detection",) features = tuple(FEATURES) @@ -40,7 +71,7 @@ class LegacySpindles: def __init__(self, baseline="curves", baseline_params=None, fitted=None): self.baseline_name = baseline self.baseline_params = dict(baseline_params or {}) - self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted + self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted is not None else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) self._fitted = fitted is not None @@ -55,6 +86,7 @@ class LegacySpindles: res = husos.resumen(director, minutos, nombres, estudio="") res.pop("estudio", None) res["ritmo_cerca_de_sigma"] = bool(ev.attrs.get("rhythm_near_sigma", False)) + res.update(_additional_summary(ev, minutos)) return res def measure(self, study) -> dict: @@ -67,8 +99,12 @@ class LegacySpindles: else: t = pd.DataFrame([self.measure(s) for s in data]) t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] - for f, b in self.baselines.items(): - b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + fitted = {} + for f in FEATURES: + if f in t: + baseline = _baseline.make(self.baseline_name, **self.baseline_params) + fitted[f] = baseline.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self.baselines = fitted self._fitted = True return self @@ -83,11 +119,13 @@ class LegacySpindles: a = t["age_months"].to_numpy(float) parts = [] for f, b in self.baselines.items(): + if f not in t: + continue v = t[f].to_numpy(float) outside, z = b.deviation(v, a) parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) - return pd.concat(parts, ignore_index=True) + return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=DEVIATION_COLUMNS) def save(self, path): Path(path, "params.json").write_text(json.dumps({"baseline": self.baseline_name, diff --git a/src/tea/legacy/preprocessing/_director/eeg_io.py b/src/tea/legacy/preprocessing/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/preprocessing/_director/eeg_io.py +++ b/src/tea/legacy/preprocessing/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/preprocessing/api.py b/src/tea/legacy/preprocessing/api.py index 42beb90..145e1e1 100644 --- a/src/tea/legacy/preprocessing/api.py +++ b/src/tea/legacy/preprocessing/api.py @@ -32,7 +32,7 @@ import pandas as pd from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, header_age_months, sha256_of -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" _SUFFIX = {"average": "prom", "linked_ears": "orejas"} @@ -42,7 +42,7 @@ class PlanNotSupported(ValueError): class LegacyPreprocessing: name = "preprocessing" - version = f"0.2.0+director.{DIRECTOR_COMMIT}" + version = f"0.3.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION impl = "legacy" diff --git a/src/tea/legacy/processes/annotation_mask/_director/eeg_io.py b/src/tea/legacy/processes/annotation_mask/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/processes/annotation_mask/_director/eeg_io.py +++ b/src/tea/legacy/processes/annotation_mask/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/processes/annotation_mask/api.py b/src/tea/legacy/processes/annotation_mask/api.py index 44bd704..df53997 100644 --- a/src/tea/legacy/processes/annotation_mask/api.py +++ b/src/tea/legacy/processes/annotation_mask/api.py @@ -21,12 +21,12 @@ from tea.contracts import CONTRACT_VERSION, Labels from . import _adapter -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" class LegacyAnnotationMask: name = "annotation_mask" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires: tuple[str, ...] = () impl = "legacy" diff --git a/src/tea/legacy/processes/sleep_state/_director/eeg_io.py b/src/tea/legacy/processes/sleep_state/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/processes/sleep_state/_director/eeg_io.py +++ b/src/tea/legacy/processes/sleep_state/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/processes/sleep_state/api.py b/src/tea/legacy/processes/sleep_state/api.py index d2150f0..4e564f3 100644 --- a/src/tea/legacy/processes/sleep_state/api.py +++ b/src/tea/legacy/processes/sleep_state/api.py @@ -26,7 +26,7 @@ from tea.contracts import CONTRACT_VERSION, Labels from . import _adapter -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" HK1K = Path(__file__).with_name("data") / "estado_hk1k.json" @@ -42,7 +42,7 @@ def corte_hk1k(path=HK1K) -> dict: class LegacySleepState: name = "sleep_state" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("annotation_mask",) impl = "legacy" diff --git a/src/tea/legacy/processes/slow_wave_staging/_director/eeg_io.py b/src/tea/legacy/processes/slow_wave_staging/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/processes/slow_wave_staging/_director/eeg_io.py +++ b/src/tea/legacy/processes/slow_wave_staging/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/processes/slow_wave_staging/api.py b/src/tea/legacy/processes/slow_wave_staging/api.py index f2f355b..18c3003 100644 --- a/src/tea/legacy/processes/slow_wave_staging/api.py +++ b/src/tea/legacy/processes/slow_wave_staging/api.py @@ -22,14 +22,14 @@ from tea.contracts import CONTRACT_VERSION, Labels from . import _adapter -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" COLUMNS = ["onset_s", "duration_s", "channel", "t_ini_s", "duracion_s", "dur_neg_s", "frecuencia_Hz", "p2p_uV", "pico_neg_uV", "pendiente_bajada_uV_s", "canal"] class LegacySlowWaveStaging: name = "slow_wave_staging" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state",) impl = "legacy" diff --git a/src/tea/legacy/processes/spindle_detection/_director/eeg_io.py b/src/tea/legacy/processes/spindle_detection/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/processes/spindle_detection/_director/eeg_io.py +++ b/src/tea/legacy/processes/spindle_detection/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/processes/spindle_detection/_director/husos.py b/src/tea/legacy/processes/spindle_detection/_director/husos.py index 7400b63..eebabf0 100644 --- a/src/tea/legacy/processes/spindle_detection/_director/husos.py +++ b/src/tea/legacy/processes/spindle_detection/_director/husos.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 7dfc641 -# source sha256 cbb444cfc560f879feeb45c0473f07ac0557f374784bbccdfcd797aef7cf8e2d. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/husos.py @ 366f7e1 +# source sha256 a4b0fdb39593859aa0755c8d6a8da717dd08d26df2acdcbced7b23e9bccf956e. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -325,6 +325,183 @@ def resumen(ev, minutos, nombres, estudio): return filas +# --------------------------------------------------------------- husos largos y extremos +# +# Agregado el 18 nov 2026 (biomarcadores-tea, pedido del director). `detectar` +# parte todo tramo de mas de DUR_MAX en pedazos de DUR_MAX y cuenta cada pedazo +# como un huso: un huso extremo de 20 s se cuenta como unos siete husos normales +# y SUBE la densidad. Estas funciones no cambian `detectar` (su REFERENCIA sigue +# valiendo); miden aparte lo que el detector parte. +# +# Huso extremo (Gibbs y Gibbs 1962): de mayor voltaje y "mas continuo" que lo +# normal. No hay criterio de duracion publicado; los 20 s son los del director +# (y aparecen en Medscape, "Normal Sleep EEG"). Un huso normal dura ~0.8 s entre +# los 10 meses y los 3 anos (Gruber y Wise 2016). +LARGO_S = DUR_MAX # mas que esto, detectar ya lo parte +EXTREMO_S = 20.0 # definicion del director +UNION_S = 0.5 # huecos mas cortos dentro de un tramo se unen (diseno propio) + + +def _corridas(mascara): + """(inicio, fin) de cada corrida de True.""" + d = np.diff(mascara.astype(np.int8), prepend=0, append=0) + return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1))) + + +def tramos_largos(est, ventanas_sueno, canales=None, percentil=95.0, vent_s=4.0, + min_estrechez=1.5, realce_min=3.0, largo_s=LARGO_S, + union_s=UNION_S, solo_huso=True): + """ + Tramos de actividad sigma continua de mas de `largo_s`, por canal, en el sueno. + + Mismos umbrales que `detectar` (alto: max(p95, 3 x mediana); bajo: + max(p70, 1.6 x mediana) de la envolvente del propio canal en el sueno), pero + sin tope de duracion: un tramo es la corrida sobre el umbral bajo, uniendo + huecos de menos de `union_s`, cuyo NUCLEO continuo (sobre el umbral alto) + dura mas de `largo_s`. `duracion_s` es la extension; `duracion_nucleo_s`, + la que decide. Se exige lo mismo que + a un huso en el tramo entero: estrechez espectral >= `min_estrechez` y + frecuencia instantanea estable dentro de la banda sigma. + + Limite: los umbrales son relativos al propio sueno del nino. Si la actividad + sigma ocupa mas de ~30 % del sueno, el umbral bajo (p70) cae dentro de ella y + los tramos se cortan o no aparecen. Para ese caso esta `ocupacion_sigma`. + """ + from scipy.signal import welch, hilbert + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + x = est.datos(canales=nombres) + fs = est.fs + npv = int(vent_s * fs) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + minutos = float(dormido.sum() / fs / 60) + cols = ["canal", "t_ini_s", "duracion_s", "duracion_nucleo_s", "frecuencia_Hz", + "amplitud_uV", "estrechez", "realce"] + if minutos < 1: + return pd.DataFrame(columns=cols), minutos, nombres + bruto, env = envolvente_sigma(x, fs) + hueco = int(union_s * fs) + filas = [] + for i, nm in enumerate(nombres): + e = env[:, i].copy() + e[~dormido] = np.nan + val = e[np.isfinite(e)] + if len(val) < fs * 30: + continue + mediana = float(np.median(val)) or 1e-9 + u_alto = max(float(np.percentile(val, percentil)), realce_min * mediana) + u_bajo = max(float(np.percentile(val, max(50.0, percentil - 25))), + 1.6 * mediana) + nucleo = np.isfinite(e) & (e > u_alto) + ext = np.isfinite(e) & (e > u_bajo) + # unir huecos cortos (un huso continuo puede bajar un instante del umbral) + for m in (nucleo, ext): + for a, b in _corridas(~m): + if 0 < a and b < len(m) and (b - a) < hueco and dormido[a:b].all(): + m[a:b] = True + for a, b in _corridas(ext): + dur = (b - a) / fs + # La duracion que decide es la del NUCLEO (sobre el umbral alto), no la + # de la extension: con senal sintetica, la cola del umbral bajo alargaba + # husos normales de 1 s hasta 3-4 s y los contaba como largos. + dur_nuc = max(((d - c) / fs for c, d in _corridas(nucleo[a:b])), default=0.0) + if dur_nuc <= largo_s: + continue + seg = x[a:b, i] + if not np.isfinite(seg).all(): + continue + nper = int(min(len(seg), 2 * fs)) + f, P = welch(seg - seg.mean(), fs=fs, nperseg=nper, + nfft=max(1024, nper * 2)) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + estrechez = float(P[en].mean() / max(P[fuera].mean(), 1e-30)) + if estrechez < min_estrechez: + continue + fase = np.unwrap(np.angle(hilbert(bruto[a:b, i]))) + dif = np.diff(fase) * fs / (2 * np.pi) + dentro = dif[(dif >= SIGMA[0] - 1) & (dif <= SIGMA[1] + 1)] + if len(dentro) < 0.5 * max(len(dif), 1): + continue + filas.append({"canal": nm, "t_ini_s": round(a / fs, 3), + "duracion_s": round(dur, 2), + "duracion_nucleo_s": round(dur_nuc, 2), + "frecuencia_Hz": round(float(np.median(dentro)), 2), + # p5-p95 de la senal sigma: el pico a pico absoluto lo dispara un solo artefacto + "amplitud_uV": round(float(np.subtract(*np.percentile( + bruto[a:b, i], [95, 5]))), 1), + "estrechez": round(estrechez, 2), + "realce": round(float(np.nanmax(e[a:b]) / mediana), 2)}) + return pd.DataFrame(filas, columns=cols), minutos, nombres + + +def ocupacion_sigma(est, ventanas_sueno, canales=None, vent_s=4.0, ventana_s=2.0, + min_estrechez=1.5, solo_huso=True): + """ + Fraccion del sueno, por canal, en ventanas de `ventana_s` donde la banda + sigma sobresale (estrechez >= `min_estrechez`, el criterio de `detectar`). + + No depende de umbrales relativos a la amplitud del propio nino: sirve justo + cuando la actividad sigma es tan continua que los percentiles la absorben. + """ + from scipy.signal import welch + nombres = canales or [c for c in eeg_io.canales_de(est.canales, "eeg") + if not solo_huso or c in CANALES_HUSO] + fs = est.fs + n = int(ventana_s * fs) + npv = int(vent_s * fs) + x = est.datos(canales=nombres) + dormido = np.zeros(len(x), dtype=bool) + for t0 in np.atleast_1d(ventanas_sueno): + a = int(round(float(t0) * fs)) + dormido[a:a + npv] = True + inicios = [a for a in range(0, len(x) - n + 1, n) if dormido[a:a + n].all()] + out = {} + if not inicios: + return out + seg = np.stack([x[a:a + n] for a in inicios]) # ventanas x muestras x canales + ok = np.isfinite(seg).all(axis=(1, 2)) + seg = seg[ok] + if not len(seg): + return out + f, P = welch(seg - seg.mean(axis=1, keepdims=True), fs=fs, nperseg=n, axis=1) + en = (f >= SIGMA[0]) & (f <= SIGMA[1]) + fuera = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + est_ = P[:, en, :].mean(axis=1) / np.maximum(P[:, fuera, :].mean(axis=1), 1e-30) + for j, nm in enumerate(nombres): + out[nm] = round(float((est_[:, j] >= min_estrechez).mean()), 3) + return out + + +def resumen_largos(tl, minutos, extremo_s=EXTREMO_S): + """Por estudio: cuantos tramos largos y extremos, el mas largo y donde.""" + f = {"n_tramos_largos": int(len(tl)), + "n_husos_extremos": int((tl.duracion_nucleo_s >= extremo_s).sum()) if len(tl) else 0, + "dur_max_tramo_s": float(tl.duracion_nucleo_s.max()) if len(tl) else 0.0, + "canal_tramo_max": (tl.canal.iloc[int(np.argmax(tl.duracion_nucleo_s.values))] + if len(tl) else None), + "min_en_tramos_largos": round(float(tl.duracion_s.sum()) / 60, 2) if len(tl) else 0.0} + f["canales_con_extremos"] = (", ".join(sorted(tl.loc[tl.duracion_nucleo_s >= extremo_s, "canal"].unique())) + if f["n_husos_extremos"] else "") + return f + + +def sin_pedazos_de_largos(ev, tl): + """Los husos de `detectar` que NO son pedazos de un tramo largo del mismo canal.""" + if ev is None or not len(ev) or not len(tl): + return ev + quitar = np.zeros(len(ev), dtype=bool) + t0 = ev.t_ini_s.to_numpy(float) + t1 = t0 + ev.duracion_s.to_numpy(float) + for r in tl.itertuples(): + quitar |= ((ev.canal.to_numpy() == r.canal) & (t1 > r.t_ini_s) + & (t0 < r.t_ini_s + r.duracion_s)) + return ev[~quitar] + + def picos_sigma(est, eventos, region="central", ancho_s=2.0, min_eventos=15): """ ¿Uno o dos picos en la banda sigma, medidos SOBRE LOS HUSOS? diff --git a/src/tea/legacy/processes/spindle_detection/api.py b/src/tea/legacy/processes/spindle_detection/api.py index 25d3ab7..8104325 100644 --- a/src/tea/legacy/processes/spindle_detection/api.py +++ b/src/tea/legacy/processes/spindle_detection/api.py @@ -1,6 +1,5 @@ """ -Legacy spindle_detection: husos.detectar on the windows labelled 'sueno', as the -cluster route runs it (medidas_director.husos / husos_eventos @ 7dfc641). +Detect spindle events and sigma runs on the selected sleep windows. The wake rhythm the director passes in only sets the 'rhythm near sigma' flag; this module computes it itself (medidas_director.ritmo on ritmo.psd_de_ventanas @@ -9,7 +8,7 @@ this module computes it itself (medidas_director.ritmo on ritmo.psd_de_ventanas events: one row per spindle with the director's columns (canal, t_ini_s, realce, duracion_s, frecuencia_Hz, amplitud_uV, estrechez, simetria, tipo) plus onset_s, duration_s, channel, frequency_hz. attrs: minutes of sleep searched, channels, -rhythm_near_sigma. +rhythm_near_sigma, EEG montage and long-run measurements. """ from __future__ import annotations @@ -24,7 +23,7 @@ from tea.contracts import CONTRACT_VERSION, Labels from . import _adapter -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" POSTERIORES = ("O1", "O2", "P3", "P4") MIN_CANALES_RITMO = 2 COLUMNS = ["onset_s", "duration_s", "channel", "frequency_hz", "canal", "t_ini_s", "realce", @@ -49,7 +48,7 @@ def wake_rhythm(est, inicios, r, eeg_io) -> float: class LegacySpindleDetection: name = "spindle_detection" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires = ("sleep_state",) impl = "legacy" @@ -79,16 +78,32 @@ class LegacySpindleDetection: lab, w = study.label("sleep_state").per_window, study.prep.windows sueno = [float(s) for s, ok in zip(w.start_s, self._sleep(study, lab)) if ok] vigilia = [float(s) for s, e in zip(w.start_s, lab) if e == "vigilia"] + features = {} with _adapter.estudio(study.prep, self.variant, eeg_io) as est: rh = wake_rhythm(est, vigilia, r, eeg_io) ev, minutos, nombres, contaminado = husos.detectar(est, sueno, ritmo_posterior=rh) + eeg_names = eeg_io.canales_de(est.canales, "eeg") + if ev is not None and len(ev): + runs, _, _ = husos.tramos_largos(est, sueno, canales=nombres) + summary = husos.resumen_largos(runs, minutos) + short = husos.sin_pedazos_de_largos(ev, runs) + occupancy = husos.ocupacion_sigma(est, sueno, canales=nombres) + features = { + "spindle_density_per_min_channel_no_long": round(len(short) / minutos / len(nombres), 3), + "spindle_n_long_runs": summary["n_tramos_largos"], + "spindle_n_extreme": summary["n_husos_extremos"], + "spindle_max_run_s": summary["dur_max_tramo_s"], + "spindle_sigma_occupancy_median": float(np.median(list(occupancy.values()))) if occupancy else np.nan, + "spindle_sigma_occupancy_max": max(occupancy.values(), default=np.nan), + } if ev is None or not len(ev): out = pd.DataFrame(columns=COLUMNS) else: out = ev.assign(onset_s=ev.t_ini_s.astype(float), duration_s=ev.duracion_s.astype(float), channel=ev.canal, frequency_hz=ev.frecuencia_Hz.astype(float))[COLUMNS] out.attrs.update({"minutes": float(minutos), "channels": list(nombres), - "rhythm_near_sigma": bool(contaminado), "searched": ev is not None}) + "rhythm_near_sigma": bool(contaminado), "searched": ev is not None, + "eeg_channels": eeg_names, "long_run_features": features}) return Labels(self.name, events=out.reset_index(drop=True)) def save(self, path): diff --git a/src/tea/legacy/processes/window_selection/_director/eeg_io.py b/src/tea/legacy/processes/window_selection/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/processes/window_selection/_director/eeg_io.py +++ b/src/tea/legacy/processes/window_selection/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/processes/window_selection/api.py b/src/tea/legacy/processes/window_selection/api.py index b4e5143..be0aaef 100644 --- a/src/tea/legacy/processes/window_selection/api.py +++ b/src/tea/legacy/processes/window_selection/api.py @@ -19,12 +19,12 @@ from tea.contracts import CONTRACT_VERSION, Labels from . import _adapter -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" class LegacyWindowSelection: name = "window_selection" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION requires: tuple[str, ...] = () impl = "legacy" diff --git a/src/tea/legacy/validation/_director/eeg_io.py b/src/tea/legacy/validation/_director/eeg_io.py index 3179e3c..5e70673 100644 --- a/src/tea/legacy/validation/_director/eeg_io.py +++ b/src/tea/legacy/validation/_director/eeg_io.py @@ -1,5 +1,5 @@ -# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 7dfc641 -# source sha256 6eaf2dd9c4907804460b39840f665eed6b2430c41082776e03326fb6043d3353. Do not edit: changed only in imports. +# Vendored by tools/vendor_legacy.py from preproceso/eeg_io.py @ 366f7e1 +# source sha256 3b67da5f68b89100de228034da01efbcf19a81dc339624495402bed97c5f8589. Do not edit: changed only in imports. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -1173,7 +1173,14 @@ def intervalos_estado(est, duracion_nota=60.0, minimo_s=1.0): Devuelve una lista de dicts ordenada, sin solapes, cubriendo todo el registro; los huecos entre eventos quedan como "no_marcado". + + Si el estudio trae `intervalos_precalculados` (biomarcadores-tea, 18 nov + 2026: la senal en memoria del cluster, donde las notas ya se tradujeron + y no viajan), se devuelven esos tal cual. """ + pre = getattr(est, "intervalos_precalculados", None) + if pre is not None: + return [dict(d) for d in pre] iv = [] for tr in est.trenes_foticos(): f = tr.get("frecuencia_hz") diff --git a/src/tea/legacy/validation/api.py b/src/tea/legacy/validation/api.py index edb1e0a..349e1e0 100644 --- a/src/tea/legacy/validation/api.py +++ b/src/tea/legacy/validation/api.py @@ -24,12 +24,12 @@ from tea.contracts import CONTRACT_VERSION, ValidationSummary, sha256_of from . import fhir as _fhir -DIRECTOR_COMMIT = "7dfc641" +DIRECTOR_COMMIT = "366f7e1" class LegacyValidation: name = "validation" - version = f"0.1.0+director.{DIRECTOR_COMMIT}" + version = f"0.2.0+director.{DIRECTOR_COMMIT}" contract_version = CONTRACT_VERSION impl = "legacy" diff --git a/src/tea/pipeline/registry.py b/src/tea/pipeline/registry.py index 9c4028c..81b6ac4 100644 --- a/src/tea/pipeline/registry.py +++ b/src/tea/pipeline/registry.py @@ -6,6 +6,8 @@ package or another) is picked up with no code change. Groups (pyproject.toml): tea.modules modern modules name = "pkg.mod:MODULE" tea.legacy_modules legacy modules + tea.associations cohort-level associations (modern), outside the pipeline + tea.legacy_associations tea.executors plain executors (legacy = single-threaded loop) """ @@ -15,6 +17,7 @@ import importlib from importlib.metadata import entry_points GROUPS = {"modern": "tea.modules", "legacy": "tea.legacy_modules"} +ASSOCIATION_GROUPS = {"modern": "tea.associations", "legacy": "tea.legacy_associations"} KIND_OF = {"validation": "validator", "preprocessing": "preprocessor"} @@ -45,6 +48,16 @@ def resolve(name: str, impl: str = "modern"): return load(targets[name]) +def association(name: str, impl: str = "modern"): + """The registered cohort-level association `name`, checked against its protocol.""" + from tea.contracts import check_module + + targets = {ep.name: ep.value for ep in entry_points(group=ASSOCIATION_GROUPS[impl])} + if name not in targets: + raise KeyError(f"no {impl} association named {name!r}; registered: {', '.join(sorted(targets)) or 'none'}") + return check_module(load(targets[name]), "association") + + def executor(name: str): eps = {ep.name: ep.value for ep in entry_points(group="tea.executors")} if name not in eps: diff --git a/src/tea/processes/spindle_detection/api.py b/src/tea/processes/spindle_detection/api.py index 4b33358..6b75373 100644 --- a/src/tea/processes/spindle_detection/api.py +++ b/src/tea/processes/spindle_detection/api.py @@ -31,6 +31,8 @@ SIGMA = (11.0, 16.0) FAST = 13.0 SPINDLE_CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz") DUR_MIN, DUR_MAX = 0.5, 3.0 +LONG_RUN_JOIN_S = 0.5 +EXTREME_RUN_S = 20.0 COLUMNS = ["onset_s", "duration_s", "channel", "frequency_hz", "enhancement", "amplitude_uv", "narrowness", "symmetry", "kind"] @@ -53,24 +55,47 @@ def segments(core, extent, fs, dmin=DUR_MIN, dmax=DUR_MAX): return out -def detect(x, fs, names, asleep, pct=95.0, min_narrow=1.5, min_enh=3.0): - from scipy.signal import hilbert, welch +def _sigma_envelope(x, fs): + from scipy.signal import hilbert y = _signal.bandpass(x, fs, *SIGMA) env = np.abs(hilbert(np.nan_to_num(y), axis=0)) k = max(1, int(0.2 * fs)) env = np.apply_along_axis(lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, env) env[~np.isfinite(y)] = np.nan + return y, env + + +def _sigma_thresholds(env, asleep, fs, pct, min_enh): + sleep_env = np.where(asleep, env, np.nan) + valid = sleep_env[np.isfinite(sleep_env)] + if len(valid) < fs * 30: + return None + median = float(np.median(valid)) or 1e-9 + high = max(float(np.percentile(valid, pct)), min_enh * median) + low = max(float(np.percentile(valid, max(50.0, pct - 25))), 1.6 * median) + return sleep_env, median, high, low + + +def _sigma_narrowness(frequencies, power): + sigma = (frequencies >= SIGMA[0]) & (frequencies <= SIGMA[1]) + flanks = ((frequencies >= 5) & (frequencies < SIGMA[0])) | ( + (frequencies > SIGMA[1]) & (frequencies <= 30)) + return power[sigma].mean(axis=0) / np.maximum(power[flanks].mean(axis=0), 1e-30) + + +def detect(x, fs, names, asleep, pct=95.0, min_narrow=1.5, min_enh=3.0, *, sigma=None): + from scipy.signal import hilbert, welch + + if not names: + return pd.DataFrame(columns=COLUMNS) + y, env = _sigma_envelope(x, fs) if sigma is None else sigma rows = [] for i, nm in enumerate(names): - e = env[:, i].copy() - e[~asleep] = np.nan - val = e[np.isfinite(e)] - if len(val) < fs * 30: + thresholds = _sigma_thresholds(env[:, i], asleep, fs, pct, min_enh) + if thresholds is None: continue - med = float(np.median(val)) or 1e-9 - hi = max(float(np.percentile(val, pct)), min_enh * med) - lo = max(float(np.percentile(val, max(50.0, pct - 25))), 1.6 * med) + e, med, hi, lo = thresholds for a, b in segments(np.isfinite(e) & (e > hi), np.isfinite(e) & (e > lo), fs): seg = x[a:b, i] if not np.isfinite(seg).all(): @@ -105,9 +130,80 @@ def detect(x, fs, names, asleep, pct=95.0, min_narrow=1.5, min_enh=3.0): return pd.DataFrame(rows, columns=COLUMNS) +def long_runs(x, fs, names, asleep, sigma, join_s=LONG_RUN_JOIN_S): + """Find sigma runs whose high-threshold core exceeds the usual event limit.""" + from scipy.signal import hilbert, welch + + filtered, envelope = sigma + rows = [] + for i, name in enumerate(names): + thresholds = _sigma_thresholds(envelope[:, i], asleep, fs, 95.0, 3.0) + if thresholds is None: + continue + sleep_env, _, high, low = thresholds + core, extent = sleep_env > high, sleep_env > low + for mask in (core, extent): + for start, stop in _signal.runs(~mask): + if 0 < start and stop < len(mask) and stop - start < int(join_s * fs) and asleep[start:stop].all(): + mask[start:stop] = True + for start, stop in _signal.runs(extent): + core_s = max(((b - a) / fs for a, b in _signal.runs(core[start:stop])), default=0.0) + segment = x[start:stop, i] + if core_s <= DUR_MAX or not np.isfinite(segment).all(): + continue + nper = int(min(len(segment), 2 * fs)) + f, power = welch(segment - segment.mean(), fs=fs, nperseg=nper, nfft=max(1024, nper * 2)) + if _sigma_narrowness(f, power) < 1.5: + continue + phase = np.unwrap(np.angle(hilbert(filtered[start:stop, i]))) + inst = np.diff(phase) * fs / (2 * np.pi) + in_band = (inst >= SIGMA[0] - 1) & (inst <= SIGMA[1] + 1) + if in_band.sum() < 0.5 * max(len(inst), 1): + continue + rows.append((name, round(start / fs, 3), round((stop - start) / fs, 2), round(core_s, 2))) + return pd.DataFrame(rows, columns=["channel", "onset_s", "duration_s", "core_s"]) + + +def sigma_occupancy(x, fs, names, asleep): + """Fraction of two-second sleep windows with dominant sigma per channel.""" + from scipy.signal import welch + + n = int(2 * fs) + segments = [x[a:a + n] for a in range(0, len(x) - n + 1, n) + if asleep[a:a + n].all() and np.isfinite(x[a:a + n]).all()] + if not segments: + return {} + data = np.stack(segments) + f, power = welch(data - data.mean(axis=1, keepdims=True), fs=fs, nperseg=n, axis=1) + narrowness = _sigma_narrowness(f, power.transpose(1, 0, 2)) + return {name: round(float(value), 3) for name, value in zip(names, (narrowness >= 1.5).mean(axis=0))} + + +def without_long_runs(events, runs): + """Exclude events overlapping a long run on the same channel.""" + overlap = np.zeros(len(events), dtype=bool) + start = events.onset_s.to_numpy(float) + stop = start + events.duration_s.to_numpy(float) + channels = events.channel.to_numpy() + for run in runs.itertuples(index=False): + overlap |= ((channels == run.channel) & (stop > run.onset_s) + & (start < run.onset_s + run.duration_s)) + return events[~overlap] + + +def summarize_long_runs(events, runs, occupancy, minutes, names): + return { + "spindle_density_per_min_channel_no_long": round(len(without_long_runs(events, runs)) / minutes / len(names), 3), + "spindle_n_long_runs": len(runs), + "spindle_n_extreme": int((runs.core_s >= EXTREME_RUN_S).sum()), + "spindle_max_run_s": float(runs.core_s.max()) if len(runs) else 0.0, + "spindle_sigma_occupancy_median": float(np.median(list(occupancy.values()))) if occupancy else np.nan, + "spindle_sigma_occupancy_max": max(occupancy.values(), default=np.nan), + } + + def wake_rhythm(raw, starts) -> float: """Median 3-14 Hz peak of O1 O2 P3 P4 over the wake windows (>= 15, >= 2 channels).""" - from mne.time_frequency import psd_array_welch chans = [c for c in ("O1", "O2", "P3", "P4") if c in raw.ch_names] if len(starts) < 15 or len(chans) < 2: # median of >= 2 channels with a peak return np.nan @@ -118,6 +214,8 @@ def wake_rhythm(raw, starts) -> float: if int(round(t * fs)) + n <= len(x) and np.isfinite(x[int(round(t * fs)):int(round(t * fs)) + n]).all()] if not segs or not chans: return np.nan + from mne.time_frequency import psd_array_welch + P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") peaks = [] for k in range(len(chans)): @@ -135,7 +233,7 @@ def wake_rhythm(raw, starts) -> float: class SpindleDetection: name = "spindle_detection" - version = "0.1.0" + version = "0.2.0" contract_version = CONTRACT_VERSION requires = ("sleep_state",) impl = "modern" @@ -162,7 +260,8 @@ class SpindleDetection: raw = study.prep.variant(self.variant) fs = float(raw.info["sfreq"]) lab, w = study.label("sleep_state").per_window, study.prep.windows - names = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in SPINDLE_CHANNELS] + eeg_names = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + names = [c for c in eeg_names if c in SPINDLE_CHANNELS] x = raw.get_data(picks=names).T * 1e6 if names else np.empty((raw.n_times, 0)) asleep = np.zeros(len(x), bool) n = int(4 * fs) @@ -171,9 +270,16 @@ class SpindleDetection: a = int(round(float(s) * fs)) asleep[a:a + n] = True minutes = float(asleep.sum() / fs / 60) - ev = detect(x, fs, names, asleep) if minutes >= 1 else pd.DataFrame(columns=COLUMNS) + ev = pd.DataFrame(columns=COLUMNS) + if minutes >= 1 and names: + sigma = _sigma_envelope(x, fs) + ev = detect(x, fs, names, asleep, sigma=sigma) + if len(ev): + runs = long_runs(x, fs, names, asleep, sigma) + occupancy = sigma_occupancy(x, fs, names, asleep) + ev.attrs["long_run_features"] = summarize_long_runs(ev, runs, occupancy, minutes, names) rh = wake_rhythm(raw, [float(s) for s, e in zip(w.start_s, lab) if e == "vigilia"]) - ev.attrs.update({"minutes": minutes, "channels": names, "searched": minutes >= 1, + ev.attrs.update({"minutes": minutes, "channels": names, "eeg_channels": eeg_names, "searched": minutes >= 1, "rhythm_near_sigma": bool(rh == rh and rh > SIGMA[0] - 1.5)}) return Labels(self.name, events=ev) -- 2.53.0 From fcf8e6ef03b54d0c1bbd7447f0e9a9009ffe31fe Mon Sep 17 00:00:00 2001 From: ulises Date: Sun, 22 Nov 2026 22:01:50 -0600 Subject: [PATCH 3/4] ADOS-2 scoring: calibrated severity score and classification per module, as registered scorers with approximate cut-point tables --- src/tea/scoring/__init__.py | 4 + src/tea/scoring/ados2.py | 152 ++++++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 src/tea/scoring/__init__.py create mode 100644 src/tea/scoring/ados2.py diff --git a/src/tea/scoring/__init__.py b/src/tea/scoring/__init__.py new file mode 100644 index 0000000..558f1b3 --- /dev/null +++ b/src/tea/scoring/__init__.py @@ -0,0 +1,4 @@ +"""Clinical scores computed from a study's recorded items, outside the per-study EEG pipeline.""" +from tea.scoring.ados2 import Ados2Score, ModuleScorer, register, score + +__all__ = ["Ados2Score", "ModuleScorer", "register", "score"] diff --git a/src/tea/scoring/ados2.py b/src/tea/scoring/ados2.py new file mode 100644 index 0000000..8662fec --- /dev/null +++ b/src/tea/scoring/ados2.py @@ -0,0 +1,152 @@ +"""ADOS-2 totals, calibrated severity score (CSS) and classification from the algorithm item scores. + +A module's scorer is a `ModuleScorer` subclass registered with `@register`; adding a module touches nothing else. +Items are named by their code without the table prefix (`sa_a2`, `rrb_d1`); a score of 3 counts as 2, as the +algorithms do. The total is the sum of the items given, so a missing item lowers it. + +The CSS cut points below are approximate values from the published calibrated severity tables (Gotham, Pickles and +Lord 2009; Hus and Lord 2014), kept as data so the licensed tables can replace them without changing the code. Each +row lists the lowest total that reaches CSS 2, 3, ... 10; a total under the first is CSS 1. +""" +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Mapping +from dataclasses import dataclass +from typing import ClassVar + +MAX_ALGORITHM_SCORE = 2 +SOCIAL_AFFECT = "sa_" +RESTRICTED_REPETITIVE = "rrb_" + +# Classification from the CSS: from 3 on the child is on the spectrum, from 5 on autism. +CSS_SPECTRUM = 3 +CSS_AUTISM = 5 +NO_SPECTRUM = "NO_ESPECTRO" +SPECTRUM = "ESPECTRO_AUTISTA" +AUTISM = "AUTISMO" +CONCERN_MILD_MODERATE = "PREOCUPACION_LEVE_MODERADA" +CONCERN_SEVERE = "PREOCUPACION_SEVERA" + +MONTHS_PER_YEAR = 12 +FIVE_YEARS = 5 * MONTHS_PER_YEAR +DAYS_PER_MONTH = 30.4375 + + +@dataclass(frozen=True) +class Ados2Score: + """What an evaluation's items give. `css` is empty where the module has none (Toddler) or the table needs an + age or a language level that wasn't given.""" + + social_affect: int + restricted_repetitive: int + total: int + css: int | None + classification: str | None + + +def classify_css(css: int) -> str: + if css < CSS_SPECTRUM: + return NO_SPECTRUM + return SPECTRUM if css < CSS_AUTISM else AUTISM + + +def totals(items: Mapping[str, int | None]) -> tuple[int, int] | None: + """Social affect and restricted-repetitive totals, or none if either domain has no item.""" + sa = [min(v, MAX_ALGORITHM_SCORE) for k, v in items.items() if k.startswith(SOCIAL_AFFECT) and v is not None] + rrb = [min(v, MAX_ALGORITHM_SCORE) for k, v in items.items() + if k.startswith(RESTRICTED_REPETITIVE) and v is not None] + if not sa or not rrb: + return None + return sum(sa), sum(rrb) + + +class ModuleScorer(ABC): + module: ClassVar[str] + + @abstractmethod + def severity(self, total: int, *, age_months: float | None, algorithm: str | None) -> tuple[int | None, str | None]: + """The CSS and the classification of a total, each empty if it can't be given.""" + + +SCORERS: dict[str, ModuleScorer] = {} + + +def register(cls: type[ModuleScorer]) -> type[ModuleScorer]: + SCORERS[cls.module] = cls() + return cls + + +def _css(total: int, cut_points: tuple[int, ...]) -> int: + return 1 + sum(total >= c for c in cut_points) + + +class TableScorer(ModuleScorer): + """A module whose CSS reads a cut-point row chosen by the language level and the age group.""" + + # (algorithm, under five years) -> cut points; `None` matches any. + tables: ClassVar[dict[tuple[str | None, bool | None], tuple[int, ...]]] + + def severity(self, total, *, age_months, algorithm): + under_five = None if age_months is None else age_months < FIVE_YEARS + for key in ((algorithm, under_five), (algorithm, None), (None, under_five), (None, None)): + if key in self.tables: + css = _css(total, self.tables[key]) + return css, classify_css(css) + return None, None + + +@register +class ModuleOne(TableScorer): + module = "MODULO_1" + tables = { + ("Pocas o ninguna palabra", True): (4, 7, 11, 14, 16, 18, 20, 22, 24), + ("Pocas o ninguna palabra", False): (6, 9, 12, 15, 17, 19, 21, 23, 25), + ("Algunas palabras", True): (3, 5, 8, 10, 12, 14, 16, 18, 20), + ("Algunas palabras", False): (4, 6, 9, 11, 13, 15, 17, 19, 21), + } + + +@register +class ModuleTwo(TableScorer): + module = "MODULO_2" + tables = { + (None, True): (3, 5, 7, 9, 10, 12, 14, 16, 18), + (None, False): (3, 6, 8, 10, 11, 13, 15, 17, 19), + } + + +@register +class ModuleThree(TableScorer): + module = "MODULO_3" + tables = {(None, None): (2, 4, 7, 8, 9, 11, 13, 15, 17)} + + +@register +class Toddler(ModuleScorer): + """Ranges of concern by age band instead of a CSS: the lowest total of the mild-to-moderate and of the severe + range, for 12 to 20 months and for 21 to 30.""" + + module = "TODDLER" + bands = ((20, (10, 16)), (30, (8, 14))) + + def severity(self, total, *, age_months, algorithm): + if age_months is None: + return None, None + mild, severe = next((cuts for limit, cuts in self.bands if age_months <= limit), self.bands[-1][1]) + if total >= severe: + return None, CONCERN_SEVERE + return None, CONCERN_MILD_MODERATE if total >= mild else NO_SPECTRUM + + +def score(module: str | None, items: Mapping[str, int | None], *, age_months: float | None = None, + algorithm: str | None = None) -> Ados2Score | None: + """The score of an evaluation, or none when its module isn't one the library knows or it has no items in a + domain. `age_months` is the child's age at the evaluation.""" + scorer = SCORERS.get(module or "") + given = totals(items) + if scorer is None or given is None: + return None + sa, rrb = given + css, classification = scorer.severity(sa + rrb, age_months=age_months, algorithm=algorithm) + return Ados2Score(sa, rrb, sa + rrb, css, classification) -- 2.53.0 From ed31baf70f7f2ded1f51a9ed056d466e53d1fdde Mon Sep 17 00:00:00 2001 From: ulises Date: Mon, 23 Nov 2026 09:29:20 -0600 Subject: [PATCH 4/4] Dask runner: progress monitor with CPU, RAM and ETA that clears when the client closes, cluster health probe, TEA_LOCAL_WORKERS cap --- src/tea/pipeline/cluster_status.py | 117 +++++++++++++++ src/tea/pipeline/dask_runner.py | 32 +++- src/tea/pipeline/run_monitor.py | 225 +++++++++++++++++++++++++++++ 3 files changed, 373 insertions(+), 1 deletion(-) create mode 100644 src/tea/pipeline/cluster_status.py create mode 100644 src/tea/pipeline/run_monitor.py diff --git a/src/tea/pipeline/cluster_status.py b/src/tea/pipeline/cluster_status.py new file mode 100644 index 0000000..f4c9863 --- /dev/null +++ b/src/tea/pipeline/cluster_status.py @@ -0,0 +1,117 @@ +"""Probe a TEA scheduler and its associated services.""" + +import os +import re +from contextlib import suppress +from pathlib import Path +from time import perf_counter +from urllib.parse import urlsplit +from urllib.request import urlopen + +from .dask_runner import scheduler_address + + +def _count_edfs(name: str) -> int: + root = Path("/referencia").resolve() + folder = (root / name).resolve() + if folder.parent != root: + raise ValueError("La carpeta de referencia está fuera de /referencia.") + return sum(path.is_file() for path in folder.rglob("*.edf")) + + +class ClusterStatus: + """Report independent Dask health checks.""" + + def check(self, mode="auto", scheduler=None, reference_name=None) -> dict: + """Resolve the mode and report cluster health.""" + if mode not in ("auto", "local", "remote", "sync"): + raise ValueError("El modo debe ser auto, local, remote o sync.") + + address = scheduler_address(scheduler) if mode in ("auto", "remote") else None + if mode == "auto": + mode = "remote" if address else "local" + if mode == "remote" and not address: + raise ValueError("El modo remote requiere un planificador Dask.") + + status = { + "mode": mode, + "scheduler": address, + "reachable": mode != "remote", + "workers": None, + "expected_workers": None, + "versions_ok": None, + "version_error": None, + "dashboard_ok": None, + "dashboard_url": None, + "reference": None, + "latency_ms": None, + "error": None, + } + if mode != "remote": + return status + + with suppress(ValueError): + status["expected_workers"] = int(os.environ.get("TEA_DASK_EXPECTED_WORKERS", "")) + self._check_scheduler(status, reference_name) + self._check_dashboard(status) + return status + + def _check_scheduler(self, status: dict, reference_name: str | None) -> None: + try: + from distributed import Client + from distributed.versions import error_message + + start = perf_counter() + client = Client(status["scheduler"], timeout=5) + except Exception as exc: + status["error"] = str(exc) or type(exc).__name__ + return + + try: + status["latency_ms"] = (perf_counter() - start) * 1000 + status["reachable"] = True + with suppress(Exception): + status["workers"] = len(client.scheduler_info()["workers"]) + + try: + versions = client.get_versions(check=True) + # Dask can report mismatches as warnings. + mismatch = error_message(versions["scheduler"], versions["workers"], versions["client"]) + except Exception as exc: + status["versions_ok"] = False + status["version_error"] = str(exc) + else: + status["version_error"] = mismatch["error"] or mismatch["warning"] or None + status["versions_ok"] = status["version_error"] is None + + if ( + status["workers"] != 0 + and reference_name + and reference_name not in (".", "..") + and re.fullmatch(r"[A-Za-z0-9._-]{1,64}", reference_name) + ): + with suppress(Exception): + future = client.submit(_count_edfs, reference_name, pure=False) + status["reference"] = {"name": reference_name, "edfs": future.result(timeout=5)} + finally: + with suppress(Exception): + client.close() + + def _check_dashboard(self, status: dict) -> None: + status["dashboard_ok"] = False + with suppress(Exception): + url = os.environ.get("TEA_DASK_DASHBOARD_URL") + if not url: + address = status["scheduler"] + host = urlsplit(address if "://" in address else f"//{address}").hostname + if not host: + return + if ":" in host: + host = f"[{host}]" + port = os.environ.get("TEA_DASK_DASHBOARD_PORT", "8787") + url = f"http://{host}:{port}/status" + status["dashboard_url"] = url + parts = urlsplit(url) + health_url = parts._replace(path="/health", query="", fragment="").geturl() + with urlopen(health_url, timeout=3) as response: + status["dashboard_ok"] = 200 <= response.status < 300 diff --git a/src/tea/pipeline/dask_runner.py b/src/tea/pipeline/dask_runner.py index b978a62..aa32e52 100644 --- a/src/tea/pipeline/dask_runner.py +++ b/src/tea/pipeline/dask_runner.py @@ -23,6 +23,8 @@ import contextlib import os from collections.abc import Callable, Sequence +from tea.pipeline.run_monitor import active_monitor + BLAS_ENV = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1"} @@ -38,11 +40,20 @@ def _bytes(s) -> int: def local_workers(memory_per_worker="4.25GiB", n_workers: int | None = None) -> int: if n_workers: return int(n_workers) + if os.environ.get("TEA_LOCAL_WORKERS"): + return max(1, int(os.environ["TEA_LOCAL_WORKERS"])) import psutil by_mem = int(psutil.virtual_memory().available // _bytes(memory_per_worker)) return max(1, min(os.cpu_count() or 1, by_mem)) +def _release(client) -> None: + """Tell the job's monitor the client is going away, so it stops reporting the cluster's last figures.""" + monitor = active_monitor() + if monitor is not None: + monitor.release(client) + + @contextlib.contextmanager def client_for(cluster: str = "auto", scheduler: str | None = None, memory_per_worker="4.25GiB", n_workers: int | None = None, check_versions=True): @@ -62,8 +73,12 @@ def client_for(cluster: str = "auto", scheduler: str | None = None, try: if check_versions: client.get_versions(check=True) + monitor = active_monitor() + if monitor is not None: + monitor.start(client, ("remote", addr)) yield client finally: + _release(client) client.close() # never restart() or shutdown(): it may be shared return lc = LocalCluster(n_workers=local_workers(memory_per_worker, n_workers), threads_per_worker=1, @@ -71,8 +86,12 @@ def client_for(cluster: str = "auto", scheduler: str | None = None, env=BLAS_ENV) client = Client(lc) try: + monitor = active_monitor() + if monitor is not None: + monitor.start(client, ("local", None)) yield client finally: + _release(client) client.close() lc.close() # this runner started it, so it closes it @@ -80,7 +99,7 @@ def client_for(cluster: str = "auto", scheduler: str | None = None, def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=None, priority: int = 0, retries: int = 1, memory_per_worker="4.25GiB", n_workers: int | None = None, on_result: Callable | None = None, - on_error: Callable | None = None) -> list: + on_error: Callable | None = None, track_progress: bool = True) -> list: """Run fn(*args) for every args in argsets; results in the input order. `on_error(args, exc)`, when given, turns a task that failed at the Dask level (a worker @@ -88,10 +107,19 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non the batch; without it the exception propagates.""" import dask + monitor = active_monitor() if track_progress else None + if monitor is not None: + monitor.total(len(argsets)) with dask.annotate(priority=priority, retries=retries): tasks = [dask.delayed(fn, pure=False)(*a) for a in argsets] with client_for(cluster, scheduler, memory_per_worker, n_workers) as client: if client is None: + def completed(result): + monitor.advance() + return result + + if monitor is not None: + tasks = [dask.delayed(completed, pure=False)(task) for task in tasks] out = list(dask.compute(*tasks, scheduler="synchronous")) if on_result: for r in out: @@ -109,6 +137,8 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non raise r = on_error(argsets[index[f.key]], e) out[index[f.key]] = r + if monitor is not None: + monitor.advance() if on_result: on_result(r) return out diff --git a/src/tea/pipeline/run_monitor.py b/src/tea/pipeline/run_monitor.py new file mode 100644 index 0000000..f6979aa --- /dev/null +++ b/src/tea/pipeline/run_monitor.py @@ -0,0 +1,225 @@ +"""Publish best-effort job progress snapshots.""" + +import json +import os +from collections import Counter, deque +from contextvars import ContextVar +from datetime import datetime, timezone +from pathlib import Path +from tempfile import NamedTemporaryFile +from threading import Event, Lock, Thread +from time import monotonic + +_MEASURING = {"midiendo", "analizando"} +_TASK_STATES = ("processing", "waiting", "memory", "erred") +_active = ContextVar("run_monitor", default=None) + + +def active_monitor(): + """Return the monitor for the current job, if any.""" + return _active.get() + + +def _task_counts(dask_scheduler): + counts = Counter(task.state for task in dask_scheduler.tasks.values()) + return {state: counts[state] for state in _TASK_STATES} + + +def _cluster_sample(info, mode, scheduler): + workers = [] + for address, worker in info["workers"].items(): + metrics = worker.get("metrics", {}) + workers.append({ + "name": str(worker.get("name", address)), + "cpu_pct": metrics.get("cpu", 0), + "memory_bytes": metrics.get("memory", 0), + "memory_limit": worker.get("memory_limit") or None, + "executing": metrics.get("executing", metrics.get("task_counts", {}).get("executing", 0)), + "threads": worker["nthreads"], + }) + limit = sum(worker["memory_limit"] or 0 for worker in workers) + return { + "mode": mode, "scheduler": scheduler, "workers": workers, + "cpu_pct": min(100, sum(w["cpu_pct"] / w["threads"] for w in workers) / len(workers)) if workers else 0, + "memory_pct": 100 * sum(w["memory_bytes"] for w in workers) / limit if limit else 0, + } + + +class RunMonitor: + """Track a job and publish atomic progress snapshots.""" + + def __init__(self, directory, interval=2.0, history=120): + self._directory = Path(directory) + self._interval = interval + self._history = deque(maxlen=history) + self._lock = Lock() + self._stopped = Event() + self._thread = None + self._started = None + self._client = None + self._cluster = None + self._tasks = None + self._phase = "preparando" + self._done = self._total = 0 + self._rate = None + self._previous = None + + def __enter__(self): + self.start() + self._token = _active.set(self) + return self + + def __exit__(self, *exc): + try: + self.stop() + finally: + _active.reset(self._token) + + def start(self, client=None, cluster=("local", None)): + """Start sampling or attach a newly opened Dask client.""" + with self._lock: + if client is not None: + mode, scheduler = cluster + self._client = client + if self._cluster is None or (self._cluster["mode"], self._cluster["scheduler"]) != cluster: + self._cluster = _cluster_sample({"workers": {}}, mode, scheduler) + self._tasks = None + if self._thread is None and not self._stopped.is_set(): + self._started = monotonic() + self._thread = Thread(target=self._sample_loop, daemon=True) + try: + self._thread.start() + except RuntimeError: + pass + + def release(self, client=None): + """Forget the cluster once its client closes: later snapshots carry no CPU, RAM or task figures.""" + with self._lock: + if client is None or client is self._client: + self._client = self._cluster = self._tasks = None + + def phase(self, name): + with self._lock: + if name != self._phase and name in _MEASURING: + self._rate = None + elapsed = monotonic() - self._started if self._started is not None else 0 + self._previous = (elapsed, self._done) + self._phase = name + + def total(self, n): + with self._lock: + self._total = n + + def advance(self, n=1): + with self._lock: + self._done += n + + def stop(self): + """Write a final snapshot with the most recent telemetry.""" + with self._lock: + if self._thread is not None and not self._stopped.is_set(): + self._stopped.set() + self._write_sample() + + def _sample_loop(self): + while not self._stopped.is_set(): + with self._lock: + client, cluster, tasks = self._client, self._cluster, self._tasks + gone = client is not None and getattr(client, "status", None) in {"closing", "closed"} + if client is not None and not gone: + try: + info = client.scheduler_info() + cluster = _cluster_sample(info, cluster["mode"], cluster["scheduler"]) + if not hasattr(client, "run_on_scheduler"): + counts = info.get("tasks") + if isinstance(counts, dict): + tasks = {state: counts.get(state, 0) for state in _TASK_STATES} + except Exception: + pass + try: + if hasattr(client, "run_on_scheduler"): + tasks = client.run_on_scheduler(_task_counts, callback_timeout=self._interval) + except Exception: + pass + with self._lock: + if self._stopped.is_set(): + return + if client is self._client: + if gone: + self._client = self._cluster = self._tasks = None + else: + self._cluster, self._tasks = cluster, tasks + self._write_sample() + self._stopped.wait(self._interval) + + def _eta(self, elapsed): + if self._phase not in _MEASURING: + return None + when, done = self._previous + if elapsed > when: + rate = (self._done - done) / (elapsed - when) + self._rate = rate if self._rate is None else 0.3 * rate + 0.7 * self._rate + self._previous = (elapsed, self._done) + if self._done >= 3 and self._rate and self._rate > 0: + return max(0, self._total - self._done) / self._rate + return None + + def _write_sample(self): + temporary = None + try: + elapsed = monotonic() - self._started + eta = self._eta(elapsed) + self._history.append({ + "t": elapsed, "done": self._done, + "cpu_pct": self._cluster["cpu_pct"] if self._cluster else 0, + "memory_pct": self._cluster["memory_pct"] if self._cluster else 0, + }) + snapshot = { + "updated_at": datetime.now(timezone.utc).isoformat(), + "phase": self._phase, "done": self._done, "total": self._total, + "elapsed_s": elapsed, "eta_s": eta, "tasks": self._tasks, + "cluster": self._cluster, "history": list(self._history), + } + self._directory.mkdir(parents=True, exist_ok=True) + with NamedTemporaryFile(mode="w", encoding="utf-8", dir=self._directory, delete=False) as stream: + temporary = Path(stream.name) + json.dump(snapshot, stream, allow_nan=False) + os.replace(temporary, self._directory / "progress.json") + except Exception: + if temporary is not None: + try: + temporary.unlink(missing_ok=True) + except OSError: + pass + + +class _NullMonitor: + def __enter__(self): + return self + + def __exit__(self, *exc): + pass + + def start(self, client=None, cluster=("local", None)): + pass + + def release(self, client=None): + pass + + def phase(self, name): + pass + + def total(self, n): + pass + + def advance(self, n=1): + pass + + def stop(self): + pass + + +def monitor_from_env(): + """Enable progress reporting when a job directory is configured.""" + directory = os.environ.get("RUN_PROGRESS_DIR") + return RunMonitor(directory) if directory else _NullMonitor() -- 2.53.0