modern annotation_mask, sleep_state and posterior_rhythm

- processes.annotation_mask: the director's state words and interval rules
  on the EDF+ annotations (MNE), window dominant state and 'mixta'.
- processes.sleep_state: vigilancia's features from batched Hann
  periodograms (mne psd_array_welch), depth index, HK1K cut-offs or cohort
  reference + KMeans (scikit-learn) after train().
- biomarkers.posterior_rhythm: Welch of the wake windows (MNE), 1/f-fitted
  dominant peak, median of O1 O2 P3 P4; private copy of the baselines.
- Registered as the modern modules; Pipeline.default("modern") now runs
  the full slice.

On a synthetic study: annotation states and sleep-state labels identical to
legacy, rhythm equal (6.5 Hz); contract suites and cohort cut-offs tested.
This commit is contained in:
AlbertoPMDM
2026-11-18 20:53:52 -06:00
parent acfd3a70d4
commit 1f8793aacb
12 changed files with 885 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""processes: one independent module each."""
@@ -0,0 +1,3 @@
from tea_modulo.processes.annotation_mask.api import MODULE, AnnotationMask
__all__ = ["MODULE", "AnnotationMask"]
@@ -0,0 +1,136 @@
"""
Modern annotation_mask: annotated states from the EDF+ annotations (MNE).
Rules ported from the director (eeg_io._PALABRAS_ESTADO, _estado_de_texto,
intervalos_estado; seleccion.estado_de_ventana, EXCLUIDOS, PROVOCACION):
- a note's state is the first state whose words appear in its text
(lower case, accents removed, ñ kept), as substrings, like the director;
- a note lasts until its end if it has a duration, otherwise 60 s or until
the next note with a state, whichever comes first; pieces under 1 s are dropped;
- gaps between notes are 'no_marcado';
- each window takes its dominant state; it is 'mixta' when the dominant one
covers less than 80% of the window.
"""
from __future__ import annotations
import json
import unicodedata
from pathlib import Path
import pandas as pd
from tea_modulo.contracts import CONTRACT_VERSION, Labels
WORDS = [
("fotica", ("fotic", "photic", "flash", "estimulacion luminosa")),
("HV", ("hv", "hipervent", "hypervent")),
("ojos_abiertos", ("ojos abiertos", "eyes open", "oa")),
("ojos_cerrados", ("ojos cerrados", "eyes closed", "oc")),
("sueno", ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", "n1", "n2", "n3")),
("despertar", ("despierta", "despierto", "arousal", "vigilia")),
("llanto", ("llanto", "llora", "cry")),
("movimiento", ("movimiento", "movement", "artefacto de movimiento")),
("alimentacion", ("come", "alimenta", "biberon", "lactancia")),
]
EXCLUDED = ("llanto", "movimiento", "desconexion")
PROVOCATION = ("fotica", "HV")
NOTE_S = 60.0
MIN_S = 1.0
def normalize(s: str) -> str:
s = str(s or "").replace("ñ", "\x00").replace("Ñ", "\x01")
s = "".join(c for c in unicodedata.normalize("NFD", s) if unicodedata.category(c) != "Mn")
return s.replace("\x00", "ñ").replace("\x01", "Ñ").lower().strip()
def state_of(text: str) -> str | None:
t = normalize(text)
for state, words in WORDS:
if any(w in t for w in words):
return state
return None
def intervals(annotations, duration_s: float) -> list[dict]:
notes = sorted([(float(a["onset"]), float(a["duration"]), a["description"]) for a in annotations],
key=lambda n: n[0])
iv = []
for i, (t0, dur, text) in enumerate(notes):
st = state_of(text)
if st is None:
continue
if dur > 0:
t1 = t0 + dur
else:
nxt = next((n[0] for n in notes[i + 1:] if state_of(n[2])), None)
t1 = min(t0 + NOTE_S, nxt if nxt else t0 + NOTE_S)
if t1 - t0 >= MIN_S:
iv.append({"t_ini": t0, "t_fin": t1, "estado": st, "fuente": "edf"})
iv.sort(key=lambda d: d["t_ini"])
kept = [d for d in iv if d["t_fin"] - d["t_ini"] >= MIN_S]
full, cursor = [], 0.0
for d in kept:
if d["t_ini"] - cursor >= MIN_S:
full.append({"t_ini": cursor, "t_fin": d["t_ini"], "estado": "no_marcado", "fuente": "-"})
full.append(d)
cursor = max(cursor, d["t_fin"])
if duration_s - cursor >= MIN_S:
full.append({"t_ini": cursor, "t_fin": duration_s, "estado": "no_marcado", "fuente": "-"})
for d in full:
d["t_ini"], d["t_fin"] = round(d["t_ini"], 2), round(d["t_fin"], 2)
return full
def window_state(a: float, b: float, ivs) -> tuple[str, bool]:
overlap = {}
for d in ivs:
lo, hi = max(a, d["t_ini"]), min(b, d["t_fin"])
if hi > lo:
overlap[d["estado"]] = overlap.get(d["estado"], 0) + (hi - lo)
if not overlap:
return "sin_etiqueta", False
dom = max(overlap, key=overlap.get)
return dom, overlap[dom] < 0.8 * (b - a)
class AnnotationMask:
name = "annotation_mask"
version = "0.1.0"
contract_version = CONTRACT_VERSION
requires: tuple[str, ...] = ()
impl = "modern"
def __init__(self, variant: str = "hp05_prom"):
self.variant = variant
def train(self, studies):
return self
def predict(self, study) -> Labels:
prep = study.prep
raw = prep.variant(self.variant) if self.variant in prep.variants else next(iter(prep.variants.values()))
ivs = intervals(raw.annotations, raw.n_times / raw.info["sfreq"])
states, mixed = [], []
for r in prep.windows.itertuples():
s, m = window_state(r.start_s, r.end_s, ivs)
states.append(s)
mixed.append(m)
ev = pd.DataFrame([{"onset_s": float(d["t_ini"]), "duration_s": float(d["t_fin"] - d["t_ini"]),
"estado": d["estado"], "fuente": d["fuente"]} for d in ivs],
columns=["onset_s", "duration_s", "estado", "fuente"])
ev.attrs["mixed_windows"] = [int(i) for i, m in zip(prep.windows.index, mixed) if m]
ev.attrs["excluded_states"] = list(EXCLUDED) + list(PROVOCATION)
return Labels(self.name, per_window=pd.Series(states, index=prep.windows.index, name="estado"),
events=ev)
def save(self, path):
Path(path, "params.json").write_text(json.dumps({"variant": self.variant}))
@classmethod
def load(cls, path):
return cls(**json.loads(Path(path, "params.json").read_text()))
MODULE = AnnotationMask()
@@ -0,0 +1,3 @@
from tea_modulo.processes.sleep_state.api import MODULE, SleepState, hk1k_cut
__all__ = ["MODULE", "SleepState", "hk1k_cut"]
+242
View File
@@ -0,0 +1,242 @@
"""
Modern sleep_state: the director's vigilancia on MNE/scikit-learn.
Per 4 s window (2 s step) of the variant, skipping windows that touch the mask
(QC-unclean spans + annotated EXCLUIDOS/PROVOCACION) or a gap:
features delta/beta, relative delta and alpha, central sigma, EMG
(20-40 / theta+alpha), posterior rhythm prominence (1/f-fitted peak)
from one Hann periodogram per window (mne psd_array_welch, batched)
depth weighted sum of the features standardised by the reference
(cohort or age-adjusted line), clipped to ±6 (vigilancia.indice_profundidad)
label vigilia / somnolencia / sueno by the cut-offs: HK1K (estado_hk1k.json,
E13) by default, or the cohort's KMeans after train(cutoffs="cohort")
"""
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
HK1K = Path(__file__).with_name("data") / "estado_hk1k.json"
POSTERIOR = ("O1", "O2", "P3", "P4")
CENTRAL = ("C3", "C4", "Cz")
BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alfa": (8, 13), "sigma": (11, 16), "beta": (16, 30),
"alto": (20, 40)}
SIGN = {"delta_beta": +1, "ritmo_post": -1, "sigma_rel": +1, "emg": -1, "rel_alfa": -1}
WEIGHT = {"delta_beta": 1.0, "ritmo_post": 1.0, "sigma_rel": 0.7, "emg": 0.7, "rel_alfa": 0.6}
FEATURES = tuple(SIGN)
def hk1k_cut(path=HK1K) -> dict:
d = json.loads(Path(path).read_text(encoding="utf-8"))
low, b = float(d["cortes_A"][0]), float(d["corte_B"])
if not low < b:
raise ValueError(f"inconsistent HK1K cut-offs: wake {low} >= sleep {b}")
return {"ref": d["ref"], "cuts": [low, b], "n_studies": d.get("n_estudios_ref"), "origin": "hk1k"}
def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5):
val = (f >= fit[0]) & (f <= fit[1]) & (P > 0)
bg = val & ~((f >= exclude[0]) & (f <= exclude[1]))
if bg.sum() < 5:
return np.nan, False
coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1)
resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val])))
sel = (f[val] >= band[0]) & (f[val] <= band[1])
if not sel.any():
return np.nan, False
i = int(np.argmax(resid[sel]))
prom = float(resid[sel][i])
return prom, bool(prom >= min_db and 0 < i < int(sel.sum()) - 1)
def features(raw, mask, window_s=4.0, step_s=2.0) -> pd.DataFrame:
from mne.time_frequency import psd_array_welch
fs = float(raw.info["sfreq"])
eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"]
x = raw.get_data(picks=eeg).T * 1e6
n, k = int(window_s * fs), int(step_s * fs)
starts = [a for a in range(0, len(x) - n + 1, k)
if np.isfinite(x[a:a + n]).all() and (mask is None or not mask[a:a + n].any())]
cols = ["t_ini_s", *FEATURES, "rel_delta"]
if not starts:
return pd.DataFrame(columns=cols)
seg = np.stack([x[a:a + n].T for a in starts]) # (win, ch, n)
P, f = psd_array_welch(seg, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
pot = {b: P[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
tot = np.maximum(pot["delta"] + pot["theta"] + pot["alfa"] + pot["beta"], 1e-12)
i_post = [eeg.index(c) for c in POSTERIOR if c in eeg]
i_cent = [eeg.index(c) for c in CENTRAL if c in eeg] or list(range(min(3, len(eeg))))
out = pd.DataFrame({"t_ini_s": np.round(np.array(starts) / fs, 2)})
out["delta_beta"] = np.median(pot["delta"] / np.maximum(pot["beta"], 1e-12), axis=1)
out["rel_delta"] = np.median(pot["delta"] / tot, axis=1)
out["rel_alfa"] = np.median(pot["alfa"] / tot, axis=1)
out["sigma_rel"] = np.median((pot["sigma"] / tot)[:, i_cent], axis=1)
out["emg"] = np.median(pot["alto"] / np.maximum(pot["theta"] + pot["alfa"], 1e-12), axis=1)
if i_post:
prom = [dominant_peak(f, P[w, i_post].mean(axis=0)) for w in range(len(starts))]
out["ritmo_post"] = [p if ok else 0.0 for p, ok in prom]
else:
out["ritmo_post"] = np.nan
return out
def depth(t: pd.DataFrame, ref=None, age_months=None) -> np.ndarray:
z = pd.DataFrame(index=t.index)
for c, sg in SIGN.items():
if c not in t or not t[c].notna().any():
continue
v = t[c].astype(float)
if c == "delta_beta":
v = np.log10(v.clip(lower=1e-6))
r = (ref or {}).get(c)
if r is None:
med = float(v.median())
disp = float(1.4826 * np.median(np.abs(v - med))) or 1.0
elif "pend" in r and age_months and age_months > 0:
med, disp = r["pend"] * np.log10(float(age_months)) + r["orden"], r["disp"]
else:
med, disp = r["med"], r["disp"]
z[c] = sg * (v - med) / max(disp, 1e-9)
if not len(z.columns):
return np.zeros(len(t))
w = np.array([WEIGHT[c] for c in z.columns], float)
return np.clip((z.values * w).sum(axis=1) / w.sum(), -6, 6)
def label(depths, cuts) -> np.ndarray:
names = (["vigilia", "sueno"] if len(cuts) == 1
else ["vigilia"] + ["somnolencia"] * (len(cuts) - 1) + ["sueno"])
return np.array(names, dtype=object)[np.digitize(depths, cuts)]
def cohort_reference(tables, ages=None, r_min=0.30) -> dict:
"""vigilancia.referencia_cohorte: median / MAD per feature, age line where |r| >= r_min."""
allw = pd.concat(tables, ignore_index=True)
ref = {}
for c in FEATURES:
if c not in allw or not allw[c].notna().any():
continue
v = allw[c].astype(float)
v = np.log10(v.clip(lower=1e-6)) if c == "delta_beta" else v
med = float(v.median())
ref[c] = {"med": med, "disp": float(1.4826 * np.median(np.abs(v.dropna() - med))) or 1.0}
rows = []
for i, t in enumerate(tables):
a = (ages or {}).get(i)
if not a or a <= 0:
continue
r = {"log_age": np.log10(a)}
for c in FEATURES:
if c in t and t[c].notna().any():
v = t[c].astype(float)
r[c] = float(np.log10(v.clip(lower=1e-6)).median() if c == "delta_beta" else v.median())
rows.append(r)
if len(rows) < 10:
return ref
d = pd.DataFrame(rows)
for c in FEATURES:
if c not in d or d[c].notna().sum() < 10:
continue
m = d[c].notna()
rr = float(np.corrcoef(d.log_age[m], d[c][m])[0, 1])
if not np.isfinite(rr) or abs(rr) < r_min:
continue
pend, orden = np.polyfit(d.log_age[m], d[c][m], 1)
res = d[c][m] - (pend * d.log_age[m] + orden)
ref[c] = {"pend": float(pend), "orden": float(orden), "med": float(d[c][m].median()),
"disp": float(1.4826 * np.median(np.abs(res - res.median()))) or 1.0}
return ref
def cohort_cuts(tables, ref, n_groups=3, seed=0, ages=None) -> list[float]:
from sklearn.cluster import KMeans
idx = np.concatenate([depth(t, ref, (ages or {}).get(i)) for i, t in enumerate(tables)])
idx = idx[np.isfinite(idx)]
if len(idx) > 200000:
idx = np.random.default_rng(seed).choice(idx, 200000, replace=False)
km = KMeans(n_clusters=max(2, n_groups), n_init=10, random_state=seed).fit(idx.reshape(-1, 1))
c = np.sort(km.cluster_centers_.ravel())
return [float((c[i] + c[i + 1]) / 2) for i in range(len(c) - 1)]
class SleepState:
name = "sleep_state"
version = "0.1.0"
contract_version = CONTRACT_VERSION
requires = ("annotation_mask",)
impl = "modern"
def __init__(self, variant="hp05_prom", cutoffs="hk1k", age_range=(16, 36), n_groups=3, cut=None):
self.variant = variant
self.cutoffs = cutoffs
self.age_range = tuple(age_range)
self.n_groups = n_groups
self.cut = cut if cut is not None else (hk1k_cut() if cutoffs == "hk1k" else None)
def mask(self, study, n, fs):
prep = study.prep
if not prep.plan.get("state", {}).get("mask", True):
return None
m = np.zeros(n, bool)
for r in prep.quality_spans.itertuples():
m[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True
ev = study.label("annotation_mask").events
excl = set(ev.attrs.get("excluded_states", ()))
for r in ev.itertuples():
if r.estado in excl:
m[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True
return m
def features(self, study) -> pd.DataFrame:
raw = study.prep.variant(self.variant)
return features(raw, self.mask(study, raw.n_times, float(raw.info["sfreq"])))
def train(self, studies):
if self.cutoffs != "cohort":
return self
tables, ages = [], {}
for s in studies:
t = self.features(s)
if len(t) >= 30:
if s.prep.age_months:
ages[len(tables)] = float(s.prep.age_months)
tables.append(t)
lo, hi = self.age_range
in_range = [i for i in range(len(tables)) if lo <= ages.get(i, -1) <= hi]
use = in_range if len(in_range) >= 10 else list(range(len(tables)))
sub, sub_ages = [tables[i] for i in use], {k: ages[i] for k, i in enumerate(use) if i in ages}
ref = cohort_reference(sub, sub_ages or None)
self.cut = {"ref": ref, "cuts": cohort_cuts(sub, ref, self.n_groups, ages=sub_ages or None),
"n_studies": len(sub), "origin": "cohort"}
return self
def predict(self, study) -> Labels:
if self.cut is None:
raise ValueError("sleep_state with cutoffs='cohort' must be trained first")
w = study.prep.windows
t = self.features(study)
per = pd.Series("sin_estado", index=w.index, name="vigilancia", dtype=object)
if len(t):
lab = label(depth(t, self.cut["ref"], study.prep.age_months), self.cut["cuts"])
by_start = dict(zip(t.t_ini_s.round(2), lab))
per[:] = [by_start.get(round(float(s), 2), "sin_estado") for s in w.start_s]
return Labels(self.name, per_window=per)
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, "cut": self.cut}, default=float))
@classmethod
def load(cls, path):
return cls(**json.loads(Path(path, "params.json").read_text()))
MODULE = SleepState()
@@ -0,0 +1,47 @@
{
"ref": {
"delta_beta": {
"med": 1.6117037688126001,
"disp": 0.3097998485854789
},
"ritmo_post": {
"pend": 4.934510806157707,
"orden": 0.999676072265559,
"disp": 1.021788597296859,
"med": 7.765061458878031
},
"sigma_rel": {
"med": 0.019957376774209706,
"disp": 0.012167857665235331
},
"emg": {
"med": 0.0742822337558628,
"disp": 0.056777351044491706
},
"rel_alfa": {
"med": 0.03498707283228359,
"disp": 0.016352123389996105
}
},
"cortes_A": [
-1.2326590642152986,
0.243030749000992
],
"corte_B": -0.3031551001049524,
"youden_B": 0.5286948181809392,
"validacion_cruzada": {
"cv1_corte": -0.307,
"cv1_sueno_n2_pct_mediana": 85.3,
"cv1_sueno_pre_pct_mediana": 26.8,
"cv2_corte": -0.299,
"cv2_sueno_n2_pct_mediana": 85.9,
"cv2_sueno_pre_pct_mediana": 23.0
},
"edad_meses": [
16,
36
],
"n_estudios_ref": 223,
"version": "0.2.0",
"fuente": "E13, HK1K (Zenodo 17138539); vigilancia.py del director, rasgos solo en ventanas limpias; corte B por Youden (0–300 s frente a 360–900 s)"
}