validation: modern validation on MNE/SciPy, agreeing with the director's

The director's rules (validacion.validar, preproceso.canales_malos,
lote.qc_estudio window QC, triaje.triar, cluster gates) rebuilt on MNE
(EDF reading, IIR filtering run by run, Welch PSD), SciPy and antropy (DFA).
All thresholds in rules.ValidationConfig with their sources; edfio header
checks (no silent resampling); R4B FHIR Bundle (private copy of the builder).

Agrees with legacy.validation on dropped channels, triage level and verdict
in every synthetic case; accepted differences (gaps as NaN, one notch, MNE
filter edges, no set-up detection) are documented and tested.
This commit is contained in:
AlbertoPMDM
2026-11-18 20:47:07 -06:00
parent e03b2f2326
commit fcd0f76d76
13 changed files with 979 additions and 0 deletions
+1
View File
@@ -36,6 +36,7 @@ sleep_state = "tea_modulo.legacy.processes.sleep_state:MODULE"
posterior_rhythm = "tea_modulo.legacy.biomarkers.posterior_rhythm:MODULE"
[project.entry-points."tea_modulo.modules"]
validation = "tea_modulo.validation:MODULE"
[project.entry-points."tea_modulo.executors"]
legacy = "tea_modulo.legacy.executor:run_serial"
+14
View File
@@ -0,0 +1,14 @@
"""
Validation of an EDF: the director's rules on MNE/SciPy.
from tea_modulo.validation import validate, summarize, ValidationConfig
bundle, valid = validate("study.edf") # R4B FHIR Bundle, 1 = valid / 0 = not valid
"""
from tea_modulo.validation.api import MODULE, Validation
from tea_modulo.validation.rules import ValidationConfig
validate = MODULE.validate
summarize = MODULE.summarize
__all__ = ["MODULE", "Validation", "ValidationConfig", "validate", "summarize"]
+76
View File
@@ -0,0 +1,76 @@
"""
Channel labels and classes (private copy; other modules own their own).
Label sets, classes and 10-20 neighbours are the director's
(preproceso/eeg_io.py EEG_1020 / OREJAS / EOG / CARDIACO / AUXILIAR,
validacion.VECINOS_1020, edf_convert.normalizar_canal) @ 7dfc641.
"""
from __future__ import annotations
import re
EEG_1020 = {"FP1", "FP2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2", "F7", "F8", "T3", "T4",
"T5", "T6", "FZ", "CZ", "PZ", "T7", "T8", "P7", "P8", "FPZ", "OZ"}
EARS = {"A1", "A2", "M1", "M2"}
EOG = {"ROC", "LOC", "EOG", "EOG1", "EOG2", "VEOG", "HEOG", "E1", "E2"}
CARDIAC = {"EKG", "ECG", "EKG1", "EKG2"}
AUX = {"DC", "OSAT", "PR", "SPO2", "RESP", "EMG", "CHIN", "PHOTIC", "TRIG", "PULSE"}
STANDARD = ("Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz").split()
_MAP = {n.upper(): n for n in STANDARD}
_MODERN = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
NEIGHBOURS_1020 = {
"Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"),
"F7": ("Fp1", "F3", "T3"), "F8": ("Fp2", "F4", "T4"),
"F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
"Fz": ("F3", "F4", "Cz"),
"T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"),
"Cz": ("Fz", "C3", "C4", "Pz"),
"T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"),
"P3": ("C3", "T5", "Pz", "O1"), "P4": ("C4", "T6", "Pz", "O2"),
"Pz": ("Cz", "P3", "P4"),
"O1": ("T5", "P3", "O2"), "O2": ("T6", "P4", "O1"),
}
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
def normalize(label: str) -> str | None:
"""'EEG Fp1-REF' -> 'Fp1'; None if not a recognised channel (edf_convert.normalizar_canal)."""
s = str(label).strip()
if not s or "ANNOT" in s.upper():
return None
s2 = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", s, flags=re.I)
s2 = re.split(r"[-]", s2)[0].strip()
key = re.sub(r"[^A-Z0-9]", "", s2.upper())
if key in _MAP:
return _MODERN.get(_MAP[key], _MAP[key])
up = s.upper()
for aux, dev in (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC")):
if aux in up:
return dev
return None
def classify(names) -> dict[str, str]:
"""{name: eeg | orejas | eog | cardiaco | auxiliar | sin_uso | desconocido}."""
out = {}
for n in names:
u = str(n).strip().upper()
if u in EEG_1020:
out[n] = "eeg"
elif u in EARS:
out[n] = "orejas"
elif u in EOG:
out[n] = "eog"
elif u in CARDIAC:
out[n] = "cardiaco"
elif u in AUX:
out[n] = "auxiliar"
elif u.isdigit() or (u.startswith("CH") and u[2:].isdigit()):
out[n] = "sin_uso"
else:
out[n] = "desconocido"
return out
+192
View File
@@ -0,0 +1,192 @@
"""
Signal primitives for validation (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
+156
View File
@@ -0,0 +1,156 @@
"""
Modern validation: the director's rules (validacion.validar, preproceso.canales_malos,
lote.qc_estudio, triaje.triar, the cluster gates) on MNE/SciPy primitives.
bundle, valid = validate("study.edf")
summary = summarize("study.edf")
Accepted differences from the legacy module (each covered by a test):
- gaps (BAD_* annotations) are NaN, so a channel's or window's gap is seen as a gap;
the director's EDF reader reads zero-filled gaps as signal (coverage 1.0);
- one notch (spectrum interpolation) everywhere; the director's window QC used an
IIR notch;
- filters are MNE's IIR Butterworth (zero phase), whose edge padding differs
from scipy's sosfiltfilt in the first and last seconds of each run;
- Hurst exponent by antropy's DFA (descriptive only);
- no set-up ('montaje') detection: EDF files start at the stable signal.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
from tea_modulo.contracts import CONTRACT_VERSION, ValidationSummary, sha256_of
from . import _channels, _signal
from . import fhir as _fhir
from .checks.channel import channel_table
from .checks.file import FileNotValid, check_file
from .checks.study import gates, triage
from .checks.windows import window_qc
from .rules import ValidationConfig
INCLUDE = ("eeg", "orejas", "eog", "cardiaco")
class Validation:
name = "validation"
version = "0.1.0"
contract_version = CONTRACT_VERSION
impl = "modern"
def __init__(self, config: ValidationConfig | None = None):
self.config = config or ValidationConfig()
def load(self, edf_path):
"""(x µV (samples, channels) with NaN gaps, fs, names, classes, file info)."""
import mne
info = check_file(edf_path)
raw = mne.io.read_raw_edf(edf_path, include=[o for o, _ in info["keep"]], preload=True,
verbose="error")
raw.rename_channels({o: n for o, n in info["keep"] if o in raw.ch_names and o != n})
classes = _channels.classify(raw.ch_names)
names = [n for n in raw.ch_names if classes[n] in INCLUDE]
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
return x, float(raw.info["sfreq"]), names, {n: classes[n] for n in names}, info
def run(self, edf_path, *, line_hz: float = 60.0) -> dict:
cfg = self.config
try:
x, fs, names, classes, finfo = self.load(edf_path)
except FileNotValid as e:
return {"valid": 0, "reasons": [str(e)], "level": "no_analizable", "channels": [],
"windows": [], "bad": {}, "file_error": True, "line_db": float("nan"),
"clean_pct": 0.0, "scalp": [], "scalp_ok": [], "ears_ok": [], "triage": None}
rows = channel_table(x, fs, names, classes, line_hz, cfg)
bad = {r["channel"]: "; ".join(r["reasons"]) for r in rows if r["reasons"]}
scalp = [n for n in names if classes[n] == "eeg"]
scalp_ok = [n for n in scalp if n not in bad]
ears_ok = [n for n in names if classes[n] == "orejas" and n not in bad]
# window QC on the kept scalp electrodes (excluidos_para_qc), notch + 0.5-45 Hz
qc_names = scalp_ok if len(scalp_ok) >= 2 else scalp
idx = [names.index(n) for n in qc_names]
y = _signal.bandpass(_signal.notch_interpolated(x[:, idx], fs, line_hz), fs, 0.5, 45.0)
wins = window_qc(y, fs, cfg)
n_w = len(wins)
clean_pct = 100.0 * sum(w["verdict"] == "limpia" for w in wins) / max(n_w, 1)
# triage inputs from the QC signal of all scalp + ear electrodes (lote: rms, plana)
qc_all = [i for i, n in enumerate(names) if classes[n] in ("eeg", "orejas")]
yq = _signal.bandpass(_signal.notch_interpolated(x[:, qc_all], fs, line_hz), fs, 0.5, 45.0)
by_name = {r["channel"]: r for r in rows}
for k, i in enumerate(qc_all):
col = yq[:, k]
fin = np.isfinite(col)
by_name[names[i]]["rms_qc_uv"] = float(np.nanstd(col)) if fin.any() else np.nan
by_name[names[i]]["frac_flat_qc"] = (float(np.mean(np.abs(np.diff(col[fin])) < 1e-9))
if fin.sum() > 1 else 1.0)
coverage = float(np.isfinite(x).all(axis=1).mean())
db = _signal.line_db(x[:, [names.index(n) for n in scalp]] if scalp else x, fs, line_hz)
tri = triage([by_name[n] for n in scalp], {n for n in bad if classes[n] == "orejas"},
coverage, clean_pct, len(x) / fs, cfg)
reasons = gates(tri, clean_pct, len(scalp_ok), len(scalp), cfg)
return {"valid": 0 if reasons else 1, "reasons": reasons, "level": tri["level"],
"channels": rows, "windows": wins, "bad": bad, "scalp": scalp, "scalp_ok": scalp_ok,
"ears_ok": ears_ok, "triage": tri, "clean_pct": clean_pct, "coverage": coverage,
"line_db": float(np.nanmedian(db)) if np.isfinite(db).any() else float("nan"),
"fs": fs, "dropped": finfo["dropped"], "duration_s": len(x) / fs}
# ------------------------------------------------------------------ contract
def summarize(self, edf_path, *, line_hz: float = 60.0) -> ValidationSummary:
return self.summary_of(self.run(edf_path, line_hz=line_hz))
@staticmethod
def summary_of(r: dict) -> ValidationSummary:
return ValidationSummary(valid=r["valid"], level=r["level"], bad_channels=dict(r["bad"]),
ears_usable=len(r["ears_ok"]) == 2, line_db=r["line_db"],
clean_fraction=r["clean_pct"] / 100.0,
extra={"reasons": list(r["reasons"]), "impl": "modern",
"windows": r["windows"]})
def validate(self, edf_path, *, line_hz: float = 60.0, subject: str | None = None):
r = self.run(edf_path, line_hz=line_hz)
checks = self.checks_of(r)
if r.get("file_error"):
conclusion = "not valid: " + "; ".join(r["reasons"])
else:
conclusion = (f"{r['level']} · {len(r['scalp']) - len(r['scalp_ok'])} scalp electrodes "
f"dropped · {r['clean_pct']:.1f}% clean windows")
if r["reasons"]:
conclusion = "not valid: " + "; ".join(r["reasons"]) + " · " + conclusion
bundle = _fhir.build_bundle(checks, valid=r["valid"], conclusion=conclusion,
edf_sha256=sha256_of(edf_path), edf_size=Path(edf_path).stat().st_size,
subject=subject, method="modern")
return bundle, r["valid"]
def checks_of(self, r: dict) -> list:
C, cfg = _fhir.Check, self.config
out = []
if r.get("file_error"):
return [C("file", "EDF file checks", r["reasons"][0], abnormal=True, decisive=True)]
for n, why in r["bad"].items():
for part in why.split("; "):
code = part.split(" (")[0].split(" with ")[0].split(" ")[0:3]
out.append(C("-".join(code).lower(), part, part, abnormal=True, electrode=n))
out.append(C("clean-windows", "clean 4 s windows", r["clean_pct"], "%", low=cfg.min_clean_pct,
abnormal=r["clean_pct"] < cfg.min_clean_pct, decisive=True))
out.append(C("internal-coverage", "internal coverage", r["coverage"], "fraction",
low=cfg.min_coverage, abnormal=r["coverage"] < cfg.min_coverage, decisive=True))
nb = len(r["triage"]["bad_scalp"])
out.append(C("bad-scalp-triage", "unusable scalp electrodes (triage rule)", nb, "electrodes",
high=cfg.max_bad_scalp, abnormal=nb > cfg.max_bad_scalp, decisive=True))
out.append(C("usable-scalp", "usable scalp electrodes", len(r["scalp_ok"]), "electrodes",
low=cfg.min_scalp, abnormal=len(r["scalp_ok"]) < cfg.min_scalp, decisive=True))
out.append(C("triage-level", "triage level", r["level"], abnormal=r["level"] == "no_analizable",
decisive=True))
if r["line_db"] == r["line_db"]:
out.append(C("line-noise", "mains line level (median)", r["line_db"], "dB", high=45.0,
abnormal=r["line_db"] > 45.0))
return out
MODULE = Validation()
+156
View File
@@ -0,0 +1,156 @@
"""
Channel rules (validacion.validar + preproceso.canales_malos), on MNE/SciPy.
Input: x (samples, channels) µV with NaN in gaps, the channel names, their
classes. Output: one dict per channel with the metrics and `reasons` (the
rules that discard it). Every threshold comes from ValidationConfig.
"""
from __future__ import annotations
import warnings
import numpy as np
from .. import _channels, _signal
from ..rules import ValidationConfig
def channel_table(x, fs, names, classes, line_hz, cfg: ValidationConfig) -> list[dict]:
rows = [_temporal(x[:, i], cfg) | {"channel": n, "class": classes[n]} for i, n in enumerate(names)]
# 0.5-45 Hz after the interpolated notch: amplitude and contact (amplitud_relativa,
# contacto_intermitente); 1-40 Hz: correlations (relacionales, corr_con_vecinos)
y45 = _signal.bandpass(_signal.notch_interpolated(x, fs, line_hz), fs, 0.5, min(45.0, fs / 2 * 0.9))
y40 = _signal.bandpass(_signal.notch_interpolated(x, fs, line_hz), fs, 1.0, 40.0)
scalp = [i for i, n in enumerate(names) if classes[n] == "eeg"]
rms = np.nanstd(y45, axis=0)
med = float(np.nanmedian(rms[scalp])) if scalp else np.nan
ratio = rms / med if np.isfinite(med) and med > 0 else np.full(len(names), np.nan)
low, burst = _contact(y45, fs, cfg)
bridges = _bridges(y40, names, classes, cfg)
ears = _ear_neighbours(y40, fs, names)
frac_missing = np.array([r["frac_missing"] for r in rows])
base_missing = float(np.nanmin(frac_missing)) if len(rows) else 0.0
for i, (r, n) in enumerate(zip(rows, names)):
cls = classes[n]
r["rms_filtered_uv"] = float(rms[i]) if np.isfinite(rms[i]) else None
r["ratio_vs_scalp"] = float(ratio[i]) if np.isfinite(ratio[i]) else None
r["frac_blocks_low"] = None if np.isnan(low[i]) else float(low[i])
r["frac_blocks_burst"] = None if np.isnan(burst[i]) else float(burst[i])
reasons = r["reasons"]
if r["frac_missing"] > base_missing + cfg.gap_excess:
reasons.append(f"own gaps ({100 * (r['frac_missing'] - base_missing):.1f}% more than the rest)")
if r.get("dead"):
continue
if cls == "eeg" and n in bridges:
reasons.append(f"bridge with {bridges[n]}")
if cls in ("eeg", "orejas") and r["ratio_vs_scalp"] and r["ratio_vs_scalp"] > cfg.amplitude_ratio:
reasons.append(f"amplitude {r['ratio_vs_scalp']:.1f} x the scalp median")
if n in ears:
c_, e_ = ears[n]
r["corr_neighbours"], r["corr_between_neighbours"] = c_, e_
if e_ > cfg.ear_neighbours_r and c_ < cfg.ear_ratio * e_:
reasons.append(f"does not correlate with its neighbours ({c_:.2f} vs {e_:.2f})")
if r["frac_blocks_low"] is not None and r["frac_blocks_low"] > cfg.contact_frac:
reasons.append(f"intermittent contact ({100 * r['frac_blocks_low']:.0f}% of blocks silent)")
if cls in ("eeg", "orejas") and r["frac_blocks_burst"] is not None \
and r["frac_blocks_burst"] > cfg.burst_frac:
reasons.append(f"intermittent contact by bursts ({100 * r['frac_blocks_burst']:.0f}% of "
f"blocks above {cfg.burst_factor:g} x the montage)")
if cls in ("cardiaco", "eog"):
raw_rms = r.get("rms_uv") or 0
if raw_rms > cfg.aux_rms_uv:
reasons.append(f"amplitude {raw_rms:.0f} uV, out of range even for {cls}")
return rows
def _temporal(x, cfg):
fin = np.isfinite(x)
v = x[fin]
r = {"n_valid": int(fin.sum()), "frac_missing": float(1 - fin.mean()) if len(x) else 1.0,
"n_inf": int(np.isinf(x).sum()), "reasons": []}
if len(v) < cfg.dead_min_valid or np.std(v) < cfg.dead_sd_uv:
r["dead"] = True
r["reasons"].append("dead channel")
return r
dif = np.diff(v)
r.update({"sd_uv": float(v.std()), "rms_uv": float(np.sqrt(np.mean(v ** 2))),
"frac_flat": float(np.mean(np.abs(dif) < 1e-9)),
"frac_saturated": float(np.mean(np.abs(v) > cfg.saturated_level * np.max(np.abs(v)))),
"hurst": _signal.hurst(v)})
if r["frac_flat"] > cfg.frozen_frac:
r["reasons"].append("frozen")
if r["frac_saturated"] > cfg.saturated_frac:
r["reasons"].append("saturated")
if r["n_inf"]:
r["reasons"].append("Inf values")
return r
def _contact(y, fs, cfg):
"""Per channel: fraction of 10 s blocks silent vs the montage, and bursting above it."""
npb = int(cfg.contact_block_s * fs)
nb = len(y) // npb
n = y.shape[1]
if nb < 6:
return np.full(n, np.nan), np.full(n, np.nan)
sds = np.full((nb, n), np.nan)
for b in range(nb):
seg = y[b * npb:(b + 1) * npb]
if np.isfinite(seg).all():
sds[b] = seg.std(axis=0)
with np.errstate(all="ignore"), warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # all-NaN blocks (gaps)
rel = sds / np.maximum(np.nanmedian(sds, axis=1, keepdims=True), 1e-12)
low, high = np.full(n, np.nan), np.full(n, np.nan)
for i in range(n):
v = rel[:, i]
v = v[np.isfinite(v) & (v > 0)]
if len(v) < 6:
continue
level = float(np.percentile(v, 75))
low[i] = float(np.mean((v < cfg.contact_drop * max(level, 1e-12)) & (v < cfg.contact_floor)))
high[i] = float(np.mean(v > cfg.burst_factor))
return low, high
def _bridges(y, names, classes, cfg) -> dict:
"""Scalp pairs above bridge_r with a contiguous neighbour, unless also above it with a
non-contiguous electrode (no spatial structure: a study note, not a bridge)."""
fin = np.isfinite(y).all(axis=1)
scalp = [i for i, n in enumerate(names) if classes[n] == "eeg"]
if fin.sum() < 200 or len(scalp) < 2:
return {}
r = np.abs(np.corrcoef(y[fin][:, scalp].T))
idx = {names[i]: k for k, i in enumerate(scalp)}
out = {}
for n, k in idx.items():
adj = [idx[a] for a in _channels.NEIGHBOURS_1020.get(n, ()) if a in idx]
far = [j for m, j in idx.items() if j != k and j not in adj]
best = max(adj, key=lambda j: r[k, j], default=None)
if best is None:
continue
no_structure = bool(far) and max(r[k, j] for j in far) > cfg.bridge_r
if r[k, best] > cfg.bridge_r and not no_structure:
out[n] = [m for m, j in idx.items() if j == best][0]
return out
def _ear_neighbours(y, fs, names) -> dict:
out = {}
for ear, nb in _channels.EAR_NEIGHBOURS.items():
cs = [c for c in nb if c in names]
if ear not in names or len(cs) < 2:
continue
i, idx = names.index(ear), [names.index(c) for c in cs]
m = np.isfinite(y[:, [i, *idx]]).all(axis=1)
if m.sum() < fs * 30:
continue
r = np.abs(np.corrcoef(y[m][:, [i, *idx]].T))
con = r[0, 1:]
between = [r[a, b] for a in range(1, len(idx) + 1) for b in range(a + 1, len(idx) + 1)]
out[ear] = (float(np.nanmax(con)), float(np.nanmedian(between)))
return out
+52
View File
@@ -0,0 +1,52 @@
"""
File checks before anything is read into memory (edf_convert.leer_edf rules):
header of at least 256 bytes, more than 0 signals, at least one recognised
channel, the majority sampling rate (channels at another rate are dropped,
never resampled: MNE would resample them silently).
"""
from __future__ import annotations
from pathlib import Path
from .. import _channels
class FileNotValid(ValueError):
pass
def check_file(path) -> dict:
import edfio
path = Path(path)
if path.stat().st_size < 256:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
try:
edf = edfio.read_edf(path, lazy_load_data=True)
except Exception as e: # noqa: BLE001
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(e).__name__})") from None
signals = [s for s in edf.signals]
if not signals:
raise FileNotValid("the EDF declares zero signals")
labels, rates, dropped = [], [], []
for s in signals:
name = _channels.normalize(s.label)
if name is None:
dropped.append((s.label, "not a recognised channel"))
continue
labels.append((s.label, name))
rates.append(float(s.sampling_frequency))
if not labels:
raise FileNotValid("no recognised channel")
fs = max(set(rates), key=rates.count)
keep, seen = [], set()
for (orig, name), r in zip(labels, rates):
if abs(r - fs) > 1e-6:
dropped.append((name, f"sampled at {r:g} Hz, the rest at {fs:g}; not resampled"))
elif name in seen:
dropped.append((name, "duplicate; the first is kept"))
else:
seen.add(name)
keep.append((orig, name))
return {"fs": fs, "keep": keep, "dropped": dropped}
+41
View File
@@ -0,0 +1,41 @@
"""
Study verdict: triage (triaje.triar) and the cluster gates (60% clean
windows, at least 12 usable scalp electrodes, not no_analizable).
"""
from __future__ import annotations
import numpy as np
from ..rules import ValidationConfig
def triage(scalp_rows: list[dict], ears_bad: set, coverage: float, clean_pct: float,
duration_s: float, cfg: ValidationConfig) -> dict:
"""triaje.triar for one study. Bad scalp electrodes (canales_malos_cuero): RMS above
max(5 x median, 300 uV) or below 0.5 uV, or more than 50% flat."""
rms = np.array([r.get("rms_qc_uv", np.nan) for r in scalp_rows], float)
med = float(np.nanmedian(rms)) if len(rms) else np.nan
bad = [r["channel"] for r in scalp_rows
if (r.get("rms_qc_uv", np.nan) > max(5 * med, 300.0)) or (r.get("rms_qc_uv", np.nan) < 0.5)
or (r.get("frac_flat_qc", 0) > 0.5)]
minutes = duration_s * clean_pct / 100.0 / 60.0
base = coverage >= cfg.min_coverage and len(bad) <= cfg.max_bad_scalp
bipolar = base and clean_pct >= cfg.min_clean_pct_bipolar and minutes >= cfg.min_clean_minutes
spectral = base and clean_pct >= cfg.min_clean_pct_spectral and minutes >= cfg.min_clean_minutes
ears_ok = not ({"A1", "A2"} & ears_bad)
level = ("no_analizable" if not bipolar else "parcial" if not spectral
else "sin_referencia_auricular" if not ears_ok else "completo")
return {"level": level, "bad_scalp": bad, "minutes_clean": round(minutes, 1),
"coverage": coverage, "bipolar": bipolar, "spectral": spectral}
def gates(tri: dict, clean_pct: float, n_scalp_ok: int, n_scalp: int, cfg: ValidationConfig) -> list[str]:
reasons = []
if tri["level"] == "no_analizable":
reasons.append("triage level no_analizable")
if clean_pct < cfg.min_clean_pct:
reasons.append(f"only {clean_pct:.0f}% clean windows (minimum {cfg.min_clean_pct:.0f}%)")
if n_scalp_ok < cfg.min_scalp:
reasons.append(f"only {n_scalp_ok} of {n_scalp} scalp electrodes usable (minimum {cfg.min_scalp})")
return reasons
@@ -0,0 +1,53 @@
"""
Window QC (lote.qc_estudio): back-to-back windows on the scalp electrodes that
are kept, after notch + 0.5-45 Hz. A window with a gap is HUECO; otherwise it
is not clean if p2p > p2p_max, EMG (30-45 / 4-13 Hz, fixed lines removed) >
emg_max or common mode > common_mode_max.
"""
from __future__ import annotations
import numpy as np
from .. import _signal
from ..rules import ValidationConfig
def window_qc(y, fs, cfg: ValidationConfig) -> list[dict]:
"""y: filtered scalp signal (samples, channels) µV."""
from mne.time_frequency import psd_array_welch
n = int(cfg.window_s * fs)
lines = _signal.fixed_lines(y, fs, f_max=44.0)
out = []
starts = list(range(0, y.shape[0] - n + 1, n))
segs = [y[a:a + n] for a in starts]
ok = [bool(np.isfinite(s).all()) for s in segs]
psd = {}
if any(ok):
arr = np.stack([s.T for s, g in zip(segs, ok) if g]) # (win, ch, times)
P, f = psd_array_welch(arr, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
hi = _signal.band_power(f, np.moveaxis(P, -1, 0), 30.0, 45.0, lines) # (win, ch)
lo = _signal.band_power(f, np.moveaxis(P, -1, 0), 4.0, 13.0, lines)
emg = np.median(hi / np.maximum(lo, 1e-12), axis=1)
psd = dict(zip([a for a, g in zip(starts, ok) if g], emg))
for a, s, good in zip(starts, segs, ok):
row = {"start_s": a / fs, "end_s": (a + n) / fs}
if not good:
out.append({**row, "verdict": "HUECO", "reasons": "missing samples"})
continue
p2p = float(np.max(s.max(axis=0) - s.min(axis=0)))
mean = s.mean(axis=1)
v_med = float(np.mean(s.var(axis=0)))
mc = float(mean.var() / v_med) if v_med > 0 else np.nan
emg = float(psd[a])
reasons = []
if p2p > cfg.p2p_max_uv:
reasons.append(f"p2p {p2p:.0f} uV")
if np.isfinite(emg) and emg > cfg.emg_max:
reasons.append(f"EMG {emg:.2f}")
if np.isfinite(mc) and mc > cfg.common_mode_max:
reasons.append(f"common mode {mc:.2f}")
out.append({**row, "p2p_uv": p2p, "emg": emg, "common_mode": mc,
"verdict": "sospechosa" if reasons else "limpia", "reasons": "; ".join(reasons)})
return out
+107
View File
@@ -0,0 +1,107 @@
"""
FHIR output of a validation: a Bundle (type collection) with one
DiagnosticReport, one Observation per check, and a DocumentReference for the
EDF (hash and size only). Built and validated with fhir.resources R4B (the
package ships no R4; these four resources have the same structure in R4).
No `subject` unless the caller passes one, so the output carries no patient
identifier.
This file is a private copy: the legacy validation module has its own.
"""
from __future__ import annotations
import base64
import uuid
from dataclasses import dataclass
SYSTEM = "urn:tea-modulo:validation"
INTERP = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
@dataclass(frozen=True)
class Check:
"""One rule evaluated on the file."""
code: str # rule key, e.g. "bursts", "clean-windows"
display: str # human text
value: float | str | None = None
unit: str = ""
low: float | None = None # threshold: abnormal below
high: float | None = None # threshold: abnormal above
abnormal: bool = False
electrode: str | None = None
decisive: bool = False # True if this check alone can make the study not valid
def _uuid() -> str:
return f"urn:uuid:{uuid.uuid4()}"
def _quantity(v, unit):
q = {"value": float(v)}
if unit:
q["unit"] = unit
return q
def build_bundle(checks, *, valid: int, conclusion: str, edf_sha256: str, edf_size: int,
subject: str | None = None, method: str = "") -> dict:
"""The Bundle as a JSON-ready dict, validated by fhir.resources.R4B."""
from fhir.resources.R4B.bundle import Bundle
doc_url = _uuid()
doc = {"resourceType": "DocumentReference", "status": "current",
"content": [{"attachment": {
"contentType": "application/edf",
"hash": base64.b64encode(bytes.fromhex(edf_sha256)).decode() if edf_sha256 else None,
"size": int(edf_size)}}]}
if subject:
doc["subject"] = {"reference": subject}
entries, refs = [], []
for c in checks:
url = _uuid()
obs = {"resourceType": "Observation", "status": "final",
"code": {"coding": [{"system": SYSTEM, "code": c.code, "display": c.display}],
"text": c.display},
"interpretation": [{"coding": [{"system": INTERP, "code": "A" if c.abnormal else "N"}]}],
"derivedFrom": [{"reference": doc_url}]}
if isinstance(c.value, (int, float)) and c.value == c.value:
obs["valueQuantity"] = _quantity(c.value, c.unit)
elif c.value is not None:
obs["valueString"] = str(c.value)
rr = {}
if c.low is not None:
rr["low"] = _quantity(c.low, c.unit)
if c.high is not None:
rr["high"] = _quantity(c.high, c.unit)
if rr:
obs["referenceRange"] = [rr]
comps = []
if c.electrode:
comps.append({"code": {"text": "electrode"}, "valueString": c.electrode})
comps.append({"code": {"text": "decisive"}, "valueBoolean": bool(c.decisive)})
obs["component"] = comps
if subject:
obs["subject"] = {"reference": subject}
entries.append({"fullUrl": url, "resource": obs})
refs.append({"reference": url})
report = {"resourceType": "DiagnosticReport", "status": "final",
"code": {"coding": [{"system": SYSTEM, "code": "eeg-quality",
"display": "EEG file quality"}], "text": "EEG file quality"},
"conclusion": conclusion,
"conclusionCode": [{"coding": [{"system": SYSTEM,
"code": "valid" if valid else "not-valid"}]}],
"result": refs}
if method:
report["code"]["text"] = f"EEG file quality ({method})"
if subject:
report["subject"] = {"reference": subject}
bundle = {"resourceType": "Bundle", "type": "collection",
"entry": [{"fullUrl": _uuid(), "resource": report}, *entries,
{"fullUrl": doc_url, "resource": doc}]}
return Bundle.model_validate(bundle).model_dump(mode="json", exclude_none=True)
+68
View File
@@ -0,0 +1,68 @@
"""
Every threshold of the validation, in one place.
Values are the director's (biomarcadores-tea/preproceso @ 7dfc641); `SOURCES`
names the file and function each one comes from. Change a value with
`ValidationConfig(...)`; the config used is recorded in the FHIR Bundle.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
@dataclass(frozen=True)
class ValidationConfig:
# channel rules
dead_min_valid: int = 10 # fewer valid samples -> dead
dead_sd_uv: float = 0.5 # SD below -> dead
frozen_frac: float = 0.5 # identical consecutive samples
saturated_frac: float = 0.001 # samples above 98% of the channel's max |x|
saturated_level: float = 0.98
gap_excess: float = 0.02 # own gaps above the least-missing channel
bridge_r: float = 0.99 # |r| with a contiguous scalp neighbour, 1-40 Hz
amplitude_ratio: float = 4.0 # RMS 0.5-45 Hz vs median scalp RMS
ear_neighbours_r: float = 0.2 # neighbours must correlate above this...
ear_ratio: float = 0.5 # ...and the ear below this fraction of it
contact_block_s: float = 10.0
contact_drop: float = 0.25 # below 0.25 x own p75...
contact_floor: float = 0.35 # ...and below 0.35 of the montage
contact_frac: float = 0.10 # in more than 10% of blocks
burst_factor: float = 4.0 # above 4 x the montage in the same block
burst_frac: float = 0.05 # in more than 5% of blocks
aux_rms_uv: float = 20000.0 # ECG / EOG range
# window QC
window_s: float = 4.0
p2p_max_uv: float = 800.0
emg_max: float = 0.6 # 30-45 / 4-13 Hz power, fixed lines removed
common_mode_max: float = 0.8
# study
min_clean_pct: float = 60.0
min_coverage: float = 0.90
max_bad_scalp: int = 2 # triage rule
min_clean_minutes: float = 3.0
min_clean_pct_spectral: float = 50.0
min_clean_pct_bipolar: float = 30.0
min_scalp: int = 12 # preproceso.MIN_CUERO
def to_dict(self) -> dict:
return asdict(self)
SOURCES = {
"dead": "preproceso.canales_malos; validacion.temporales (constante)",
"frozen": "validacion.temporales (frac_plana > 0.5)",
"saturated": "validacion.temporales (frac_saturada > 0.001 of 0.98 max|x|)",
"inf": "validacion.temporales",
"own-gaps": "validacion.validar (huecos exclusivos, +2 points)",
"bridge": "validacion.relacionales (puente_probable)",
"amplitude": "validacion.amplitud_relativa / preproceso.canales_malos",
"ear-neighbours": "validacion.corr_con_vecinos / preproceso.canales_malos",
"contact": "validacion.contacto_intermitente (frac_bloques_hundidos)",
"bursts": "validacion.contacto_intermitente (frac_bloques_disparados), director 17 Nov 2026",
"aux-range": "preproceso.canales_malos (EKG / EOG > 20000 uV)",
"window-qc": "lote.qc_estudio (metricas)",
"triage": "triaje.triar",
"min-clean": "un_estudio.procesar (min_ventanas_limpias 60%)",
"min-scalp": "preproceso.MIN_CUERO",
}
+63
View File
@@ -0,0 +1,63 @@
"""Modern validation: agrees with the legacy (director) validation on synthetic studies."""
from __future__ import annotations
import pytest
from synth_edf import SCALP, make_edf
from tea_modulo.contracts.testing import check_validation
from tea_modulo.legacy.validation import MODULE as LEGACY
from tea_modulo.validation import MODULE, Validation, ValidationConfig
CASES = {
"faults": dict(bad={"flat": ["P3"], "bursts": ["P4"], "bridge": [("F3", "C3")]}),
"too_few_scalp": dict(bad={"flat": SCALP[:8]}),
"loud_and_frozen": dict(bad={"loud": ["O1"], "frozen": ["T4"]}),
"clean": dict(),
}
@pytest.fixture(scope="module", params=list(CASES))
def case(request, tmp_path_factory):
p = make_edf(tmp_path_factory.mktemp(request.param) / "s.edf", minutes=5, **CASES[request.param])
return request.param, p
def test_agrees_with_legacy(case):
name, p = case
m, l = MODULE.run(p), LEGACY.run(p)
assert sorted(m["bad"]) == sorted(l["malos"]), name
assert m["valid"] == l["valid"], name
assert m["level"] == l["triaje"]["nivel"], name
assert abs(m["clean_pct"] - l["qc"]["pct_ventanas_limpias"]) <= 5.0, name
def test_contract_and_fhir(case):
_, p = case
bundle, valid = MODULE.validate(p)
check_validation(bundle, valid, MODULE.summarize(p))
from fhir.resources.R4B.bundle import Bundle
Bundle.model_validate(bundle)
def test_gaps_are_gaps_not_signal(tmp_path):
"""Accepted difference: a BAD_ACQ_SKIP span makes its windows HUECO (legacy reads zeros)."""
p = make_edf(tmp_path / "g.edf", minutes=5, gaps=[(60.0, 8.0)])
r = MODULE.run(p)
assert any(w["verdict"] == "HUECO" for w in r["windows"])
assert r["coverage"] < 1.0 and r["valid"] == 1
def test_broken_file_is_not_valid_not_an_exception(tmp_path):
p = tmp_path / "x.edf"
p.write_bytes(b"0" * 300)
bundle, valid = MODULE.validate(p)
assert valid == 0
check_validation(bundle, valid)
def test_config_changes_the_verdict(tmp_path):
p = make_edf(tmp_path / "s.edf", minutes=4, bad={"flat": SCALP[:2]}) # 17 usable, 2 bad
assert MODULE.run(p)["valid"] == 1
assert Validation(ValidationConfig(min_scalp=18)).run(p)["valid"] == 0
assert Validation(ValidationConfig(max_bad_scalp=1)).run(p)["level"] == "no_analizable"