coupling, legacy and modern
- legacy: acoplamiento.fases_de_estudio + resumen (vendored unchanged); spindle and slow-wave events read through the contract columns, so either detector can feed it; in_slow_wave = --solo-en-onda. - modern: slow-oscillation phase (MNE 0.5-2 Hz, scipy Hilbert, per run) at the sigma-envelope peak of each spindle; R from 200 subsamples of 30, excess over the chance floor, preferred angle, raw R. Modern within 0.03 of legacy; phase-locked synthetic spindles give R > 0.8 at the trough in both; contract suite passes.
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from tea_modulo.biomarkers.coupling.api import MODULE, Coupling
|
||||
|
||||
__all__ = ["MODULE", "Coupling"]
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
Baselines, ported as they are (private copy; every biomarker owns one).
|
||||
|
||||
Functions copied verbatim:
|
||||
- biomarcadores-tea/biomarcadores/curvas.py @ 7dfc641: CUANTILES, rejilla,
|
||||
cuantil_ponderado, ajustar, en_edad, z_y_posicion
|
||||
- codigo/perfil_alteraciones.py @ c7a4736: MIN_CONTROLES_BLOQUE, bordes_edad,
|
||||
z_por_bloques, marcar_fuera (the cut-offs = p5/p95 of the controls' own z,
|
||||
as in construir_perfil.mete), with BLOQUES from codigo/curva_desarrollo.py
|
||||
|
||||
Two classes wrap them with fit / deviation / to_dict / from_dict:
|
||||
CentileCurves outside: below p5 or above p95 of the age curve; z = z_robusto
|
||||
AgeBlockZ outside: z beyond the controls' z p5 / p95; z = (x - median) / MAD
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
# ------------------------------------------------------------------ curvas.py (verbatim)
|
||||
CUANTILES = {"p5": 0.05, "p25": 0.25, "mediana": 0.5, "p75": 0.75, "p95": 0.95}
|
||||
|
||||
|
||||
def rejilla(edad_min=1.0, edad_max=216.0, puntos=120) -> np.ndarray:
|
||||
"""Edades (meses) espaciadas en escala log."""
|
||||
return np.exp(np.linspace(np.log(edad_min), np.log(edad_max), puntos))
|
||||
|
||||
|
||||
def cuantil_ponderado(x: np.ndarray, w: np.ndarray, q: float) -> float:
|
||||
"""Cuantil con pesos (interpolando entre los puntos medios de cada peso acumulado)."""
|
||||
o = np.argsort(x)
|
||||
x, w = x[o], w[o]
|
||||
c = (np.cumsum(w) - 0.5 * w) / w.sum()
|
||||
return float(np.interp(q, c, x))
|
||||
|
||||
|
||||
def ajustar(valores, edades_meses, ancho_log=0.2, n_min=30, edades=None) -> pd.DataFrame:
|
||||
"""Curva de percentiles: una fila por edad de la rejilla (edad_meses, n_efectivo, p5…p95)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
ok = np.isfinite(v) & np.isfinite(e) & (e > 0)
|
||||
v, le = v[ok], np.log(e[ok])
|
||||
edades = rejilla() if edades is None else np.asarray(edades, dtype=float)
|
||||
filas = []
|
||||
for a in edades:
|
||||
w = np.exp(-0.5 * ((le - np.log(a)) / ancho_log) ** 2)
|
||||
n_ef = w.sum() ** 2 / (w ** 2).sum() if w.sum() > 0 else 0.0
|
||||
fila = {"edad_meses": round(float(a), 3), "n_efectivo": round(float(n_ef), 1)}
|
||||
dentro = len(le) and le.min() <= np.log(a) <= le.max()
|
||||
for nom, q in CUANTILES.items():
|
||||
fila[nom] = (round(cuantil_ponderado(v, w, q), 4) if n_ef >= n_min and dentro
|
||||
else np.nan)
|
||||
filas.append(fila)
|
||||
return pd.DataFrame(filas)
|
||||
|
||||
|
||||
def en_edad(edad_meses: float, curva: pd.DataFrame) -> dict | None:
|
||||
"""p5…p95 a una edad exacta (interpolados en log(edad)); None si la curva no la cubre."""
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c) or not np.isfinite(edad_meses) or edad_meses <= 0:
|
||||
return None
|
||||
la, lx = np.log(edad_meses), np.log(c.edad_meses.to_numpy())
|
||||
if la < lx.min() or la > lx.max():
|
||||
return None
|
||||
return {nom: float(np.interp(la, lx, c[nom].to_numpy())) for nom in CUANTILES}
|
||||
|
||||
|
||||
def z_y_posicion(valores, edades_meses, curva: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""`z_robusto` y `posicion` de muchos valores a la vez (mismo resultado, sin bucle por fila)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
z = np.full(v.shape, np.nan)
|
||||
pos = np.full(v.shape, "sin referencia", dtype=object)
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c):
|
||||
return z, pos
|
||||
lx = np.log(c.edad_meses.to_numpy())
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
la = np.where(e > 0, np.log(np.where(e > 0, e, 1.0)), np.nan)
|
||||
ok = np.isfinite(v) & np.isfinite(la) & (la >= lx.min()) & (la <= lx.max())
|
||||
q = {k: np.interp(la, lx, c[k].to_numpy()) for k in CUANTILES}
|
||||
lado = np.where(v < q["mediana"], q["mediana"] - q["p5"], q["p95"] - q["mediana"])
|
||||
zz = (v - q["mediana"]) / (lado / 1.645)
|
||||
z[ok] = np.where(lado[ok] > 0, zz[ok], np.nan)
|
||||
pos[ok] = np.where(v[ok] < q["p5"][ok], "bajo p5",
|
||||
np.where(v[ok] > q["p95"][ok], "sobre p95", "dentro"))
|
||||
return z, pos
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ perfil_alteraciones.py (verbatim)
|
||||
BLOQUES = (2, 4, 6, 9, 12, 18, 24, 36, 48, 60, 84, 120, 192) # curva_desarrollo.BLOQUES
|
||||
MIN_CONTROLES_BLOQUE = 12
|
||||
|
||||
|
||||
def bordes_edad(edad_min, edad_max):
|
||||
"""Bloques de la curva de desarrollo recortados al rango pedido."""
|
||||
b = [x for x in BLOQUES if edad_min < x < edad_max]
|
||||
return [edad_min] + b + [edad_max]
|
||||
|
||||
|
||||
def z_por_bloques(xT, edadT, xC, edadC, bordes):
|
||||
"""
|
||||
z de cada caso contra la mediana y el MAD de los controles de su bloque
|
||||
de edad, y el z de los propios controles para sacar los cortes.
|
||||
|
||||
Un bloque con menos de MIN_CONTROLES_BLOQUE controles usa la normativa
|
||||
del rango completo, y se avisa: una banda de 8 controles es una línea
|
||||
firme dibujada sobre nada.
|
||||
"""
|
||||
xT = np.asarray(xT, dtype=float)
|
||||
xC = np.asarray(xC, dtype=float)
|
||||
bT = np.digitize(np.asarray(edadT, dtype=float), bordes[1:-1])
|
||||
bC = np.digitize(np.asarray(edadC, dtype=float), bordes[1:-1])
|
||||
okC = np.isfinite(xC)
|
||||
med_g = float(np.nanmedian(xC))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(xC - med_g))) or np.nan
|
||||
|
||||
zT = np.full(len(xT), np.nan)
|
||||
zC = np.full(len(xC), np.nan)
|
||||
for b in range(len(bordes) - 1):
|
||||
enC = okC & (bC == b)
|
||||
if enC.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(xC[enC]))
|
||||
mad = float(1.4826 * np.median(np.abs(xC[enC] - med)))
|
||||
else:
|
||||
med, mad = med_g, mad_g
|
||||
if not np.isfinite(mad) or mad == 0:
|
||||
continue
|
||||
zT[bT == b] = (xT[bT == b] - med) / mad
|
||||
zC[enC] = (xC[enC] - med) / mad
|
||||
return zT, zC
|
||||
|
||||
|
||||
def marcar_fuera(P, cortes):
|
||||
F = pd.DataFrame(0, index=P.index,
|
||||
columns=[f"fuera_{c}" for c in P.columns])
|
||||
for c in P.columns:
|
||||
lo, hi = cortes[c]
|
||||
F.loc[P[c] < lo, f"fuera_{c}"] = -1
|
||||
F.loc[P[c] > hi, f"fuera_{c}"] = 1
|
||||
return F
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ wrappers
|
||||
class CentileCurves:
|
||||
name = "curves"
|
||||
|
||||
def __init__(self, ancho_log=0.2, n_min=30, curva=None):
|
||||
self.ancho_log = ancho_log
|
||||
self.n_min = n_min
|
||||
self.curva = curva
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
self.curva = ajustar(values, ages_months, ancho_log=self.ancho_log, n_min=self.n_min)
|
||||
return self
|
||||
|
||||
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
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min,
|
||||
"curva": self.curva.replace({np.nan: None}).to_dict("list")}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
curva = pd.DataFrame(d["curva"]).astype(float)
|
||||
return cls(d["ancho_log"], d["n_min"], curva)
|
||||
|
||||
|
||||
class AgeBlockZ:
|
||||
name = "age_blocks"
|
||||
|
||||
def __init__(self, edad_min=12.0, edad_max=60.0, state=None):
|
||||
self.edad_min = edad_min
|
||||
self.edad_max = edad_max
|
||||
self.state = state
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
keep = (e >= self.edad_min) & (e <= self.edad_max) # perfil_alteraciones.filtra
|
||||
v, e = v[keep], e[keep]
|
||||
bordes = bordes_edad(self.edad_min, self.edad_max)
|
||||
_, zC = z_por_bloques(v, e, v, e, bordes)
|
||||
zC = zC[np.isfinite(zC)]
|
||||
blocks = []
|
||||
bC = np.digitize(e, bordes[1:-1])
|
||||
ok = np.isfinite(v)
|
||||
med_g = float(np.nanmedian(v))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(v - med_g))) or np.nan
|
||||
for b in range(len(bordes) - 1):
|
||||
en = ok & (bC == b)
|
||||
if en.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(v[en]))
|
||||
blocks.append({"median": med, "mad": float(1.4826 * np.median(np.abs(v[en] - med))),
|
||||
"n": int(en.sum())})
|
||||
else:
|
||||
blocks.append({"median": med_g, "mad": mad_g, "n": int(en.sum()), "fallback": True})
|
||||
self.state = {"bordes": bordes, "blocks": blocks,
|
||||
"cortes": [float(np.percentile(zC, 5)), float(np.percentile(zC, 95))]
|
||||
if len(zC) else [np.nan, np.nan], "n": int(len(v))}
|
||||
return self
|
||||
|
||||
def deviation(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
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)):
|
||||
blk = self.state["blocks"][k]
|
||||
if 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
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max,
|
||||
"state": self.state}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
return cls(d["edad_min"], d["edad_max"], d["state"])
|
||||
|
||||
|
||||
BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ}
|
||||
|
||||
|
||||
def make(name, **params):
|
||||
try:
|
||||
return BASELINES[name](**params)
|
||||
except KeyError:
|
||||
raise ValueError(f"unknown baseline {name!r}; one of {', '.join(BASELINES)}") from None
|
||||
|
||||
|
||||
def from_dict(d):
|
||||
return BASELINES[d["name"]].from_dict(d)
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Signal primitives for spindle detection (private copy), on MNE and SciPy.
|
||||
|
||||
Arrays are (samples, channels) in µV with NaN in gaps. Filters run on each
|
||||
gap-free run separately (runs shorter than the filter's minimum become NaN,
|
||||
as the director's por_tramos does).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
|
||||
"""[(start, stop)] of the True runs of a boolean vector."""
|
||||
v = np.concatenate([[False], np.asarray(valid, bool), [False]])
|
||||
d = np.diff(v.astype(int))
|
||||
return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)))
|
||||
|
||||
|
||||
def by_runs(x, fn, minimum: int):
|
||||
x = np.asarray(x, float)
|
||||
out = np.full_like(x, np.nan)
|
||||
for a, b in runs(np.isfinite(x).all(axis=1)):
|
||||
if b - a >= minimum:
|
||||
out[a:b] = fn(x[a:b])
|
||||
return out
|
||||
|
||||
|
||||
def bandpass(x, fs, lo=None, hi=None, order=4):
|
||||
"""Butterworth, zero phase (mne.filter.filter_data, IIR), run by run."""
|
||||
import mne
|
||||
iir = {"order": order, "ftype": "butter"}
|
||||
|
||||
def f(seg):
|
||||
return mne.filter.filter_data(seg.T, fs, lo, hi, method="iir", iir_params=iir,
|
||||
phase="zero", verbose="error").T
|
||||
return by_runs(x, f, minimum=max(3 * (2 * order + 1), int(fs)))
|
||||
|
||||
|
||||
def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True):
|
||||
"""Spectrum interpolation around f0 and harmonics (port of eeg_io.notch_interpolado).
|
||||
No library implements this method; MNE's notch filters change the signal differently."""
|
||||
freqs = [f0]
|
||||
if harmonics:
|
||||
k = 2
|
||||
while k * f0 < fs / 2 * 0.98:
|
||||
freqs.append(k * f0)
|
||||
k += 1
|
||||
|
||||
def f(seg):
|
||||
n = seg.shape[0]
|
||||
fr = np.fft.rfftfreq(n, 1.0 / fs)
|
||||
F = np.fft.rfft(seg, axis=0)
|
||||
for c in freqs:
|
||||
inside = (fr >= c - width) & (fr <= c + width)
|
||||
left = (fr >= c - 3 * width) & (fr < c - width)
|
||||
right = (fr > c + width) & (fr <= c + 3 * width)
|
||||
if not (inside.any() and left.any() and right.any()):
|
||||
continue
|
||||
ml, mr = np.abs(F[left]).mean(axis=0), np.abs(F[right]).mean(axis=0)
|
||||
k_ = np.linspace(0, 1, int(inside.sum()))[:, None]
|
||||
target = ml[None, :] * (1 - k_) + mr[None, :] * k_
|
||||
cur = F[inside]
|
||||
mag = np.abs(cur)
|
||||
F[inside] = target * np.where(mag > 0, cur / np.maximum(mag, 1e-30), 1.0)
|
||||
return np.fft.irfft(F, n=n, axis=0)
|
||||
return by_runs(x, f, minimum=max(int(2 * fs), 256))
|
||||
|
||||
|
||||
def welch(x, fs, seg_s=4.0, overlap=0.5):
|
||||
"""Welch PSD (Hann) per channel over the gap-free runs (mne psd_array_welch), µV²/Hz."""
|
||||
from mne.time_frequency import psd_array_welch
|
||||
x = np.asarray(x, float)
|
||||
x = x[:, None] if x.ndim == 1 else x
|
||||
n = int(round(seg_s * fs))
|
||||
acc, w = None, 0
|
||||
for a, b in runs(np.isfinite(x).all(axis=1)):
|
||||
if b - a < n:
|
||||
continue
|
||||
P, f = psd_array_welch(x[a:b].T, fs, n_fft=n, n_per_seg=n, n_overlap=int(n * overlap),
|
||||
window="hann", average="mean", verbose="error")
|
||||
k = (b - a - n) // int(n * (1 - overlap)) + 1
|
||||
acc = P * k if acc is None else acc + P * k
|
||||
w += k
|
||||
if acc is None:
|
||||
return None, None
|
||||
return f, (acc / w).T # (freqs, channels)
|
||||
|
||||
|
||||
def line_db(x, fs, f0=60.0, width=0.6, neighbourhood=(2, 6)):
|
||||
"""dB of the mains peak over its neighbourhood on the samples valid in all channels
|
||||
(eeg_io.nivel_de_red)."""
|
||||
x = np.atleast_2d(np.asarray(x, float).T).T
|
||||
fin = np.isfinite(x).all(axis=1)
|
||||
if not fin.any():
|
||||
return np.full(x.shape[1], np.nan)
|
||||
seg = x[fin] - x[fin].mean(axis=0)
|
||||
fr = np.fft.rfftfreq(len(seg), 1.0 / fs)
|
||||
P = np.abs(np.fft.rfft(seg * np.hanning(len(seg))[:, None], axis=0)) ** 2
|
||||
lo, hi = neighbourhood
|
||||
peak = P[(fr >= f0 - width) & (fr <= f0 + width)].mean(axis=0)
|
||||
nb = P[((fr >= f0 - hi) & (fr <= f0 - lo)) | ((fr >= f0 + lo) & (fr <= f0 + hi))].mean(axis=0)
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
return 10 * np.log10(np.where(nb > 0, peak / nb, np.nan))
|
||||
|
||||
|
||||
def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5):
|
||||
"""Peak over the 1/f fit (eeg_io.pico_dominante): (Hz, prominence dB, found)."""
|
||||
f, P = np.asarray(f, float), np.asarray(P, float)
|
||||
val = (f >= fit[0]) & (f <= fit[1]) & (P > 0)
|
||||
bg = val & ~((f >= exclude[0]) & (f <= exclude[1]))
|
||||
if bg.sum() < 5:
|
||||
return np.nan, 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])))
|
||||
fv = f[val]
|
||||
sel = (fv >= band[0]) & (fv <= band[1])
|
||||
if not sel.any():
|
||||
return np.nan, np.nan, False
|
||||
i = int(np.argmax(resid[sel]))
|
||||
peak, prom = float(fv[sel][i]), float(resid[sel][i])
|
||||
edge = i == 0 or i == int(sel.sum()) - 1
|
||||
found = bool(prom >= min_db and not edge)
|
||||
return (peak if found else np.nan), prom, found
|
||||
|
||||
|
||||
def fixed_lines(x, fs, f_min=1.0, f_max=None, min_db=6.0, max_width=0.5, bg_hz=2.0, seg_s=8.0):
|
||||
"""Fixed-frequency lines of the recording (lineas.lineas_fijas): [(Hz, dB, width)]."""
|
||||
from scipy.ndimage import median_filter
|
||||
x = np.asarray(x, float)
|
||||
x = x[:, None] if x.ndim == 1 else x
|
||||
n = int(round(seg_s * fs))
|
||||
f = np.fft.rfftfreq(n, 1.0 / fs)
|
||||
win = np.hanning(n)[:, None]
|
||||
acc, k = None, 0
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
seg = x[a:a + n]
|
||||
if not np.isfinite(seg).all():
|
||||
continue
|
||||
S = np.abs(np.fft.rfft((seg - seg.mean(axis=0)) * win, axis=0)) ** 2
|
||||
acc = S if acc is None else acc + S
|
||||
k += 1
|
||||
if not k:
|
||||
return []
|
||||
P = np.median(acc / k, axis=1)
|
||||
df = float(f[1] - f[0])
|
||||
lp = 10 * np.log10(np.maximum(P, 1e-30))
|
||||
kk = max(1, int(round(bg_hz / df)))
|
||||
prom = lp - median_filter(lp, size=2 * kk + 1, mode="nearest")
|
||||
f_max = min(f_max or fs / 2, fs / 2 - bg_hz)
|
||||
cand = []
|
||||
for i in range(1, len(f) - 1):
|
||||
if not (f_min <= f[i] <= f_max) or prom[i] < min_db:
|
||||
continue
|
||||
if prom[i] < prom[i - 1] or prom[i] < prom[i + 1]:
|
||||
continue
|
||||
u = prom[i] - 3.0
|
||||
a = i
|
||||
while a > 0 and prom[a - 1] >= u:
|
||||
a -= 1
|
||||
b = i
|
||||
while b < len(f) - 1 and prom[b + 1] >= u:
|
||||
b += 1
|
||||
if (b - a + 1) * df <= max_width:
|
||||
cand.append((round(float(f[i]), 3), round(float(prom[i]), 1), round((b - a + 1) * df, 3)))
|
||||
cand.sort(key=lambda c: -c[1])
|
||||
out = []
|
||||
for c in cand:
|
||||
if all(abs(c[0] - o[0]) > 0.5 for o in out):
|
||||
out.append(c)
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def band_power(f, P, lo, hi, lines=(), margin=1.0):
|
||||
"""Power of [lo, hi) without ±margin around fixed lines, rescaled (lineas.potencia_banda)."""
|
||||
f, P = np.asarray(f, float), np.asarray(P, float)
|
||||
band = (f >= lo) & (f < hi)
|
||||
clean = band.copy()
|
||||
for li in lines or ():
|
||||
clean &= np.abs(f - float(li[0])) > margin
|
||||
if not clean.any():
|
||||
return np.full(P.shape[1:], np.nan) if P.ndim > 1 else np.nan
|
||||
return P[clean].sum(axis=0) * (band.sum() / clean.sum())
|
||||
|
||||
|
||||
def hurst(x):
|
||||
"""Hurst exponent by detrended fluctuation analysis (antropy)."""
|
||||
import antropy
|
||||
v = np.asarray(x, float)
|
||||
v = v[np.isfinite(v)]
|
||||
return float(antropy.detrended_fluctuation(v)) if len(v) > 4096 else np.nan
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
Modern coupling (acoplamiento's definitions on MNE/SciPy): slow-oscillation phase
|
||||
(0.5-2 Hz MNE band-pass, scipy Hilbert, per gap-free run) at the maximum of the
|
||||
sigma envelope (11-16 Hz band-pass, |Hilbert|) within each spindle, on the
|
||||
spindle's own channel. R = median resultant length over 200 subsamples of 30
|
||||
spindles (seed 7); R over the chance floor sqrt(pi)/(2 sqrt(30)); preferred angle
|
||||
(circular mean of the subsample angles); raw R. NaN with fewer than 30 spindles.
|
||||
"""
|
||||
|
||||
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, DEVIATION_COLUMNS
|
||||
|
||||
from . import _baseline, _signal
|
||||
|
||||
SO = (0.5, 2.0)
|
||||
SIGMA = (11.0, 16.0)
|
||||
N_SUB, REPS, SEED = 30, 200, 7
|
||||
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz", "T3", "T4", "T5",
|
||||
"T6", "O1", "O2")
|
||||
FEATURES = ("coupling_r", "coupling_r_over_floor", "coupling_angle_deg", "coupling_r_raw")
|
||||
|
||||
|
||||
def resultant(ph):
|
||||
if ph is None or not len(ph):
|
||||
return np.nan, np.nan
|
||||
m = np.exp(1j * np.asarray(ph, float)).mean()
|
||||
return float(np.abs(m)), float(np.angle(m))
|
||||
|
||||
|
||||
def phases(raw, sp, slow=None):
|
||||
from scipy.signal import hilbert
|
||||
fs = float(raw.info["sfreq"])
|
||||
names = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in CHANNELS]
|
||||
x = raw.get_data(picks=names).T * 1e6
|
||||
lo = _signal.bandpass(x, fs, *SO)
|
||||
ph = _signal.by_runs(lo, lambda s: np.angle(hilbert(s, axis=0)), minimum=int(fs))
|
||||
env = _signal.by_runs(_signal.bandpass(x, fs, *SIGMA), lambda s: np.abs(hilbert(s, axis=0)), minimum=int(fs))
|
||||
idx = {c: i for i, c in enumerate(names)}
|
||||
out = []
|
||||
for r in sp.itertuples():
|
||||
if r.channel not in idx:
|
||||
continue
|
||||
a = max(int(round(float(r.onset_s) * fs)), 0)
|
||||
b = min(a + int(round(float(r.duration_s) * fs)), len(x))
|
||||
if b - a < 2:
|
||||
continue
|
||||
j = idx[r.channel]
|
||||
k = a + int(np.nanargmax(env[a:b, j])) if np.isfinite(env[a:b, j]).any() else a
|
||||
v = float(ph[k, j])
|
||||
if not np.isfinite(v):
|
||||
continue
|
||||
inside = True
|
||||
if slow is not None and len(slow):
|
||||
s = slow[slow.channel == r.channel] if (slow.channel == r.channel).any() else slow
|
||||
t = k / fs
|
||||
inside = bool(np.any((t >= s.onset_s.to_numpy(float)) &
|
||||
(t <= s.onset_s.to_numpy(float) + s.duration_s.to_numpy(float))))
|
||||
out.append((v, inside))
|
||||
return out
|
||||
|
||||
|
||||
class Coupling:
|
||||
name = "coupling"
|
||||
version = "0.1.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("spindle_detection",)
|
||||
features = FEATURES
|
||||
impl = "modern"
|
||||
|
||||
def __init__(self, variant="hp05_prom", in_slow_wave=False, baseline="curves", baseline_params=None,
|
||||
fitted=None):
|
||||
self.variant = variant
|
||||
self.in_slow_wave = bool(in_slow_wave)
|
||||
self.requires = ("spindle_detection", "slow_wave_staging") if self.in_slow_wave else ("spindle_detection",)
|
||||
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})
|
||||
self._fitted = fitted is not None
|
||||
|
||||
def measure(self, study) -> dict:
|
||||
nan = {f: float("nan") for f in FEATURES}
|
||||
sp = study.label("spindle_detection").events
|
||||
if not len(sp):
|
||||
return nan
|
||||
slow = study.label("slow_wave_staging").events if self.in_slow_wave else None
|
||||
res = phases(study.prep.variant(self.variant), sp, slow)
|
||||
ph = np.array([v for v, ok in res if ok or not self.in_slow_wave])
|
||||
if not len(ph):
|
||||
return nan
|
||||
raw_r, _ = resultant(ph)
|
||||
if len(ph) < N_SUB:
|
||||
return {**nan, "coupling_r_raw": raw_r}
|
||||
rng = np.random.default_rng(SEED)
|
||||
rs, angs = [], []
|
||||
for _ in range(REPS):
|
||||
r, a = resultant(rng.choice(ph, size=N_SUB, replace=False))
|
||||
rs.append(r)
|
||||
angs.append(a)
|
||||
R = float(np.median(rs))
|
||||
floor = float(np.sqrt(np.pi) / (2 * np.sqrt(N_SUB)))
|
||||
return {"coupling_r": R, "coupling_r_over_floor": (R - floor) / (1 - floor),
|
||||
"coupling_angle_deg": float(np.degrees(resultant(np.array(angs))[1])), "coupling_r_raw": raw_r}
|
||||
|
||||
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._fitted = True
|
||||
return self
|
||||
|
||||
def predict(self, data, age_months=None) -> pd.DataFrame:
|
||||
if not self._fitted:
|
||||
raise ValueError(f"{self.name}: train() before predict()")
|
||||
if isinstance(data, pd.DataFrame):
|
||||
t = data
|
||||
else:
|
||||
t = pd.DataFrame([self.measure(data)])
|
||||
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():
|
||||
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)
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "in_slow_wave": self.in_slow_wave, "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))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
p = json.loads(Path(path, "params.json").read_text())
|
||||
return cls(**p, fitted=json.loads(Path(path, "baseline.json").read_text()))
|
||||
|
||||
|
||||
MODULE = Coupling()
|
||||
Reference in New Issue
Block a user