f870ee9f14
- legacy: husos.detectar / husos.resumen vendored unchanged, run on the 'sueno' windows as medidas_director does; the wake rhythm that sets the 'rhythm near sigma' flag is computed inside the process (no biomarker dependency). - modern: the same detector on MNE (sigma band-pass) and SciPy (Hilbert, Welch narrowness, phase stability); summary with the director's definitions; one baseline per feature. - privacy.group_size understands per-feature baseline dicts. Legacy equals the submodule's cluster route exactly (spindle count and the six summary measures); modern equals legacy on the synthetic study.
105 lines
4.3 KiB
Python
105 lines
4.3 KiB
Python
"""
|
|
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).
|
|
"""
|
|
|
|
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
|
|
|
|
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"}
|
|
|
|
|
|
class LegacySpindles:
|
|
name = "spindles"
|
|
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
|
|
contract_version = CONTRACT_VERSION
|
|
requires = ("spindle_detection",)
|
|
features = tuple(FEATURES)
|
|
impl = "legacy"
|
|
|
|
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
|
|
else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES})
|
|
self._fitted = fitted is not None
|
|
|
|
def summary(self, study) -> dict:
|
|
from ._director import husos
|
|
ev = study.label("spindle_detection").events
|
|
minutos = float(ev.attrs.get("minutes", 0.0))
|
|
nombres = list(ev.attrs.get("channels", []))
|
|
director = None if not ev.attrs.get("searched", True) else ev[
|
|
["canal", "t_ini_s", "realce", "duracion_s", "frecuencia_Hz", "amplitud_uV", "estrechez",
|
|
"simetria", "tipo"]]
|
|
res = husos.resumen(director, minutos, nombres, estudio="")
|
|
res.pop("estudio", None)
|
|
res["ritmo_cerca_de_sigma"] = bool(ev.attrs.get("rhythm_near_sigma", False))
|
|
return res
|
|
|
|
def measure(self, study) -> dict:
|
|
res = self.summary(study)
|
|
return {f: float(res[k]) if res.get(k) is not None else float("nan") for f, k in FEATURES.items()}
|
|
|
|
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({"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 = LegacySpindles()
|