Files
tea/src/tea_modulo/legacy/processes/sleep_state/api.py
T
AlbertoPMDM 441113c7b7 legacy: annotation_mask, sleep_state and posterior_rhythm on the director's code
- contracts: Preprocessed.quality_spans (QC-unclean stretches at the QC's
  own resolution), so the director's state mask can be rebuilt exactly.
- legacy.preprocessing: annotations straight from the EDF (exact onsets, as
  edf_convert), quality_spans from his 4 s QC.
- legacy processes annotation_mask (intervalos_estado, estado_de_ventana) and
  sleep_state (vigilancia.rasgos with senal._mascara_excluir's mask,
  clasificar with the HK1K cut-offs or cohort cut-offs after train()).
- legacy biomarker posterior_rhythm (medidas_director.ritmo on
  ritmo.psd_de_ventanas + pico_dominante) with a private _baseline.py holding
  curvas.py and perfil_alteraciones' age-block z, copied verbatim.
- Each legacy module owns its adapter, which writes the study in the
  director's preprocessed format and opens it with his eeg_io.Estudio.

Identical to the submodule's cluster route on a synthetic study (window
labels and rhythm); contract suites pass.
2026-11-18 20:12:47 -06:00

121 lines
5.1 KiB
Python

"""
Legacy sleep_state: the director's vigilancia, as the cluster route runs it.
mask = QC-unclean spans + annotated EXCLUIDOS/PROVOCACION intervals
(biomarcadores senal._mascara_excluir)
rasgos = vigilancia.rasgos(est, linea_hz, excluir=mask) 4 s windows, 2 s step
corte = HK1K cut-offs (normas/estado_hk1k.json, estado_director.corte_hk1k)
or, after train(), the cohort's (vigilancia.referencia_cohorte +
cortes_cohorte, estado_director.cortes)
labels = vigilancia.clasificar(rasgos, ref, cortes, edad_meses)
per_window: the label of the vigilancia window that starts at the same time
as each window of `Preprocessed.windows` (`sin_estado` where the director
gives none, e.g. masked windows).
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
from tea_modulo.contracts import CONTRACT_VERSION, Labels
from . import _adapter
DIRECTOR_COMMIT = "7dfc641"
HK1K = Path(__file__).with_name("data") / "estado_hk1k.json"
def corte_hk1k(path=HK1K) -> dict:
"""Copied from biomarcadores/estado_director.corte_hk1k @ 7dfc641 (path argument only)."""
d = json.loads(Path(path).read_text(encoding="utf-8"))
bajo, b = float(d["cortes_A"][0]), float(d["corte_B"])
if not bajo < b:
raise ValueError(f"cortes de HK1K inconsistentes: vigilia {bajo} ≥ sueño {b}")
return {"ref": d["ref"], "cortes": [bajo, b], "n_estudios": d.get("n_estudios_ref"),
"origen": "hk1k_calibrado"}
class LegacySleepState:
name = "sleep_state"
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
contract_version = CONTRACT_VERSION
requires = ("annotation_mask",)
impl = "legacy"
def __init__(self, variant: str = "hp05_prom", cutoffs: str = "hk1k",
age_range=(16, 36), n_groups: int = 3, corte: dict | None = None):
self.variant = variant
self.cutoffs = cutoffs
self.age_range = tuple(age_range)
self.n_groups = n_groups
self.corte = corte if corte is not None else (corte_hk1k() if cutoffs == "hk1k" else None)
# ------------------------------------------------------------------ director steps
def features(self, study) -> pd.DataFrame:
from ._director import eeg_io, vigilancia
prep = study.prep
ev = 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.itertuples()]
line_hz = float(prep.plan.get("line_hz", 60.0))
with _adapter.estudio(prep, self.variant, eeg_io) as est:
mask = (_adapter.mask_from(prep, ivs, ev.attrs.get("excluded_states", ()), est.n, est.fs)
if prep.plan.get("state", {}).get("mask", True) else None)
return vigilancia.rasgos(est, linea_hz=line_hz, excluir=mask)
def train(self, studies):
"""Cohort cut-offs (estado_director.cortes): needed when cutoffs='cohort'."""
if self.cutoffs != "cohort":
return self
from ._director import vigilancia
tablas = []
edades = {}
for i, s in enumerate(studies):
t = self.features(s)
if len(t) >= 30:
tablas.append(t.assign(estudio=str(i)))
if s.prep.age_months:
edades[str(i)] = float(s.prep.age_months)
lo, hi = self.age_range
en_rango = [t for t in tablas if lo <= edades.get(str(t.estudio.iloc[0]), -1) <= hi]
ref_t = en_rango if len(en_rango) >= 10 else tablas
ref = vigilancia.referencia_cohorte(ref_t, edades or None)
c = vigilancia.cortes_cohorte(ref_t, ref, n_grupos=self.n_groups, edades=edades or None)
self.corte = {"ref": ref, "cortes": [float(v) for v in c], "n_estudios": len(ref_t),
"origen": "cohorte"}
return self
def predict(self, study) -> Labels:
from ._director import vigilancia
if self.corte is None:
raise ValueError("sleep_state with cutoffs='cohort' must be trained first")
rasgos = self.features(study)
w = study.prep.windows
if rasgos is None or not len(rasgos):
return Labels(self.name, per_window=pd.Series("sin_estado", index=w.index, name="vigilancia"))
t, _ = vigilancia.clasificar(rasgos, self.corte["ref"], self.corte["cortes"],
edad_meses=study.prep.age_months)
por_inicio = dict(zip(np.round(t.t_ini_s.astype(float), 2), t.vigilancia))
per = [por_inicio.get(round(float(s), 2), "sin_estado") for s in w.start_s]
return Labels(self.name, per_window=pd.Series(per, index=w.index, name="vigilancia"))
# ------------------------------------------------------------------ persistence
def save(self, path):
Path(path, "params.json").write_text(json.dumps(
{"variant": self.variant, "cutoffs": self.cutoffs, "age_range": list(self.age_range),
"n_groups": self.n_groups, "corte": self.corte}, default=float))
@classmethod
def load(cls, path):
return cls(**json.loads(Path(path, "params.json").read_text()))
MODULE = LegacySleepState()