298 lines
12 KiB
Python
298 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
comparar.py — Antes y después del preprocesado, en una figura.
|
|
|
|
python comparar.py convertidos preprocesado --estudio eeg_077 --png fig.png
|
|
python comparar.py convertidos preprocesado --sin-orejas --n 4 --png comp.png
|
|
python comparar.py convertidos preprocesado --metodos --estudio eeg_011
|
|
|
|
Tres modos:
|
|
|
|
normal crudo frente a preprocesado: trazas, espectro y amplitud por canal
|
|
--sin-orejas escoge automáticamente estudios sin referencia auricular
|
|
utilizable, que son los que conviene mirar con más cuidado
|
|
--metodos compara el notch IIR con la interpolación espectral sobre el
|
|
mismo tramo, para ver cuál deforma menos
|
|
|
|
Las trazas de antes y después se dibujan SIEMPRE con la misma escala vertical
|
|
cuando se comparan estados del mismo canal. Escalas distintas harían parecer
|
|
que el preprocesado mejora la señal cuando solo la ha encogido.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import eeg_io # noqa: E402
|
|
import texto as _txt # noqa: E402
|
|
|
|
_txt.consola_utf8()
|
|
|
|
CRUDO = "#95a5a6"
|
|
LIMPIO = "#2c3e50"
|
|
ROJO = "#c0392b"
|
|
|
|
|
|
def cargar(dir_conv: Path, dir_pre: Path, estudio: str):
|
|
conv = dir_conv / estudio
|
|
npz = next(iter(sorted(conv.glob("*_signals.npz"))), None)
|
|
meta = next(iter(sorted(conv.glob("*_metadata.json"))), None)
|
|
if npz is None:
|
|
raise FileNotFoundError(f"sin *_signals.npz en {conv}")
|
|
est = eeg_io.Estudio(npz, meta)
|
|
pre_f = dir_pre / estudio / f"{estudio}_preproc.npz"
|
|
if not pre_f.exists():
|
|
raise FileNotFoundError(f"sin preprocesado: {pre_f}")
|
|
z = np.load(pre_f, allow_pickle=False)
|
|
proc = json.loads(str(z["procedencia"]))
|
|
return est, z, proc
|
|
|
|
|
|
def _tramo_bueno(est, dur, evitar_montaje=True):
|
|
"""
|
|
Instante de inicio dentro del tramo continuo mas largo.
|
|
|
|
Se salta el montaje si cabe, pero nunca se sale del tramo: preferir un
|
|
inicio "bonito" a uno valido dejaba la figura en blanco.
|
|
"""
|
|
tramos = est.tramos_limpios(minimo_s=0.0)
|
|
if not tramos:
|
|
return 0.0
|
|
a, b = max(tramos, key=lambda ab: ab[1] - ab[0])
|
|
if evitar_montaje:
|
|
md = est.md.get("verificaciones", {})
|
|
a = max(a, float(md.get("desfase_inicial_s", 0) or 0))
|
|
margen = min(60.0, max(0.0, (b - a - dur) / 2))
|
|
return float(min(max(a + margen, a), max(b - dur, a)))
|
|
|
|
|
|
def figura(est, z, proc, canal=None, t0=None, dur=10.0, hp="05", png=None,
|
|
ref=None):
|
|
import matplotlib
|
|
if png:
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
|
|
canales = [str(c) for c in z["canales"]]
|
|
# el nombre del array lleva la referencia: prom (todos) u orejas
|
|
cand = ([f"signals_hp{hp}_{ref}_uV"] if ref else
|
|
[f"signals_hp{hp}_{r}_uV" for r in ("orejas", "prom")])
|
|
clave = next((c for c in cand if c in z.files), f"signals_hp{hp}_uV")
|
|
if clave not in z.files:
|
|
raise KeyError(f"no encuentro {cand} en el archivo; claves: "
|
|
f"{[k for k in z.files if k.startswith('signals')]}")
|
|
lim = z[clave]
|
|
if canal is None:
|
|
canal = next((c for c in ("O1", "O2", "C3", "Cz") if c in canales),
|
|
canales[0])
|
|
j = canales.index(canal)
|
|
crudo = est.datos(canales=[canal])[:, 0]
|
|
|
|
if t0 is None:
|
|
t0 = _tramo_bueno(est, dur)
|
|
a, b = int(t0 * est.fs), int((t0 + dur) * est.fs)
|
|
b = min(b, len(lim), len(crudo))
|
|
t = np.arange(a, b) / est.fs
|
|
|
|
fig = plt.figure(figsize=(16, 7.5))
|
|
gs = fig.add_gridspec(2, 3, width_ratios=[2.2, 1.2, 1.2], hspace=0.35,
|
|
wspace=0.28)
|
|
|
|
# --- trazas, misma escala en las dos ---------------------------------
|
|
c_seg, l_seg = crudo[a:b], lim[a:b, j]
|
|
fin = np.isfinite(c_seg) & np.isfinite(l_seg)
|
|
lim_y = (np.nanpercentile(np.abs(c_seg[fin]), 99.5) * 1.2
|
|
if fin.any() else 100)
|
|
ax = fig.add_subplot(gs[0, 0])
|
|
ax.plot(t, c_seg, lw=.6, color=CRUDO)
|
|
ax.set_ylim(-lim_y, lim_y)
|
|
ax.set_ylabel("µV")
|
|
ax.set_title(f"{canal} · crudo", loc="left")
|
|
ax.grid(alpha=.2)
|
|
ax2 = fig.add_subplot(gs[1, 0], sharex=ax)
|
|
ax2.plot(t, l_seg, lw=.6, color=LIMPIO)
|
|
ax2.set_ylim(-lim_y, lim_y)
|
|
ax2.set_ylabel("µV")
|
|
ax2.set_xlabel("s")
|
|
ax2.set_title(f"{canal} · preprocesado — MISMA escala vertical", loc="left")
|
|
ax2.grid(alpha=.2)
|
|
|
|
# --- espectro ---------------------------------------------------------
|
|
axp = fig.add_subplot(gs[:, 1])
|
|
for datos, etq, col in ((crudo, "crudo", CRUDO), (lim[:, j],
|
|
"preprocesado", LIMPIO)):
|
|
f, P = est.psd(np.asarray(datos, dtype=np.float64)[:, None])
|
|
axp.loglog(f[1:], np.atleast_1d(P)[1:], lw=1, color=col, label=etq)
|
|
axp.axvline(proc.get("notch_hz") or 60, color=ROJO, ls="--", alpha=.5)
|
|
axp.axvspan(4, 13, color="gold", alpha=.15)
|
|
axp.set_xlim(0.3, min(100, est.fs / 2))
|
|
axp.set_xlabel("Hz")
|
|
axp.set_ylabel("µV²/Hz")
|
|
axp.set_title("Espectro (banda sombreada: ritmo)", loc="left")
|
|
axp.legend(fontsize=8)
|
|
axp.grid(alpha=.3, which="both")
|
|
|
|
# --- amplitud por canal ----------------------------------------------
|
|
axb = fig.add_subplot(gs[:, 2])
|
|
rms_c = [float(np.nanstd(est.datos(canales=[c])[:, 0])) for c in canales]
|
|
rms_l = list(np.nanstd(lim, axis=0))
|
|
y = np.arange(len(canales))
|
|
axb.barh(y - 0.2, rms_c, height=0.4, color=CRUDO, label="crudo")
|
|
axb.barh(y + 0.2, rms_l, height=0.4, color=LIMPIO, label="preprocesado")
|
|
axb.set_yticks(y)
|
|
axb.set_yticklabels(canales, fontsize=8)
|
|
axb.invert_yaxis()
|
|
axb.set_xscale("log")
|
|
axb.set_xlabel("rms (µV, escala log)")
|
|
axb.set_title("Amplitud por canal", loc="left")
|
|
axb.legend(fontsize=8)
|
|
axb.grid(alpha=.3, axis="x", which="both")
|
|
|
|
ref = proc.get("referencia", "?")
|
|
excl = proc.get("canales_excluidos") or []
|
|
metodo = proc.get("metodo_red") or "sin quitar red"
|
|
fig.suptitle(
|
|
f"{proc.get('estudio', '')} · referencia: {ref}"
|
|
+ (f" ({', '.join(proc.get('canales_referencia', []))})"
|
|
if proc.get("canales_referencia") else "")
|
|
+ f" · red: {metodo}"
|
|
+ f" · {proc.get('red_dB_antes', '?')} → "
|
|
f"{proc.get('red_dB_despues', '?')} dB"
|
|
+ (f" · excluidos: {', '.join(excl)}" if excl else ""),
|
|
y=0.985, fontsize=11)
|
|
if png:
|
|
fig.savefig(png, dpi=110, bbox_inches="tight")
|
|
print(f" figura: {png}")
|
|
return fig
|
|
|
|
|
|
def figura_metodos(est, canal=None, t0=None, dur=10.0, linea_hz=60.0,
|
|
ancho=1.5, png=None):
|
|
"""El mismo tramo con notch IIR y con interpolación espectral."""
|
|
import matplotlib
|
|
if png:
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
|
|
nombres = eeg_io.canales_de(est.canales, "eeg")
|
|
if canal is None:
|
|
canal = next((c for c in ("O1", "C3", "Cz") if c in nombres),
|
|
nombres[0])
|
|
x = est.datos(canales=[canal])
|
|
if t0 is None:
|
|
t0 = _tramo_bueno(est, dur)
|
|
|
|
iir = eeg_io.pasa_banda(eeg_io.notch(x, est.fs, linea_hz), est.fs,
|
|
lo=0.5, hi=45)
|
|
itp = eeg_io.pasa_banda(
|
|
eeg_io.notch_interpolado(x, est.fs, linea_hz, ancho=ancho), est.fs,
|
|
lo=0.5, hi=45)
|
|
|
|
a, b = int(t0 * est.fs), int((t0 + dur) * est.fs)
|
|
b = min(b, len(x))
|
|
t = np.arange(a, b) / est.fs
|
|
fig, axs = plt.subplots(1, 2, figsize=(15, 4.2),
|
|
gridspec_kw={"width_ratios": [2, 1.3]})
|
|
axs[0].plot(t, iir[a:b, 0], lw=.7, color="#8e44ad", label="notch IIR")
|
|
axs[0].plot(t, itp[a:b, 0], lw=.7, color="#16a085",
|
|
label="interpolación espectral")
|
|
axs[0].set_xlabel("s")
|
|
axs[0].set_ylabel("µV")
|
|
axs[0].legend(fontsize=9)
|
|
axs[0].grid(alpha=.2)
|
|
axs[0].set_title(f"{canal} — las dos curvas deberían superponerse salvo "
|
|
f"cerca de {linea_hz:.0f} Hz", loc="left")
|
|
|
|
for datos, etq, col in ((x, "crudo", CRUDO), (iir, "notch IIR", "#8e44ad"),
|
|
(itp, "interpolación", "#16a085")):
|
|
f, P = est.psd(np.asarray(datos, dtype=np.float64))
|
|
axs[1].semilogy(f, np.atleast_1d(P), lw=1, color=col, label=etq)
|
|
axs[1].axvline(linea_hz, color=ROJO, ls="--", alpha=.5)
|
|
axs[1].set_xlim(40, min(90, est.fs / 2))
|
|
axs[1].set_xlabel("Hz")
|
|
axs[1].set_ylabel("µV²/Hz")
|
|
axs[1].legend(fontsize=8)
|
|
axs[1].grid(alpha=.3)
|
|
axs[1].set_title("Alrededor de la red: cuánto se toca a los vecinos",
|
|
loc="left")
|
|
fig.suptitle(f"{est.ruta.name} — métodos para quitar la red", y=1.02)
|
|
fig.tight_layout()
|
|
if png:
|
|
fig.savefig(png, dpi=110, bbox_inches="tight")
|
|
print(f" figura: {png}")
|
|
return fig
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(description="Antes y después del preprocesado")
|
|
ap.add_argument("convertidos")
|
|
ap.add_argument("preprocesado")
|
|
ap.add_argument("--estudio", nargs="+", default=None)
|
|
ap.add_argument("--sin-orejas", action="store_true",
|
|
help="escoge estudios sin referencia auricular")
|
|
ap.add_argument("--con-orejas", action="store_true")
|
|
ap.add_argument("--n", type=int, default=2)
|
|
ap.add_argument("--canal", default=None)
|
|
ap.add_argument("--t0", type=float, default=None)
|
|
ap.add_argument("--dur", type=float, default=10.0)
|
|
ap.add_argument("--hp", default="05", choices=("03", "05"))
|
|
ap.add_argument("--ref", default=None, choices=("orejas", "prom"),
|
|
help="cual de las referencias guardadas dibujar")
|
|
ap.add_argument("--metodos", action="store_true")
|
|
ap.add_argument("--png", default=None)
|
|
args = ap.parse_args(argv)
|
|
|
|
conv, pre = Path(args.convertidos).resolve(), Path(args.preprocesado).resolve()
|
|
estudios = args.estudio
|
|
if not estudios:
|
|
man = pre / "preproceso_manifiesto.csv"
|
|
if not man.exists():
|
|
raise SystemExit(f"no encuentro {man}; pasa --estudio")
|
|
import pandas as pd
|
|
m = pd.read_csv(man, encoding="utf-8-sig")
|
|
if args.sin_orejas:
|
|
m = m[m.referencia == "promedio_comun"]
|
|
elif args.con_orejas:
|
|
m = m[m.referencia == "orejas_enlazadas"]
|
|
estudios = list(m.estudio.head(args.n))
|
|
print(f"Seleccionados: {', '.join(estudios)}")
|
|
|
|
for e in estudios:
|
|
print(f"\n{e}")
|
|
try:
|
|
est, z, proc = cargar(conv, pre, e)
|
|
print(f" referencia {proc['referencia']}"
|
|
+ (f" ({', '.join(proc['canales_referencia'])})"
|
|
if proc.get("canales_referencia") else "")
|
|
+ f" · red {proc.get('metodo_red')} "
|
|
f"{proc.get('red_dB_antes')}→{proc.get('red_dB_despues')} dB")
|
|
base = Path(args.png) if args.png else None
|
|
if args.metodos:
|
|
figura_metodos(est, args.canal, args.t0, args.dur,
|
|
png=(base.with_name(f"{base.stem}_{e}_metodos"
|
|
f"{base.suffix or '.png'}")
|
|
if base else None))
|
|
else:
|
|
figura(est, z, proc, args.canal, args.t0, args.dur, args.hp,
|
|
ref=args.ref,
|
|
png=(base.with_name(f"{base.stem}_{e}"
|
|
f"{base.suffix or '.png'}")
|
|
if base else None))
|
|
except Exception as ex:
|
|
print(f" FALLO — {type(ex).__name__}: {ex}")
|
|
if not args.png:
|
|
import matplotlib.pyplot as plt
|
|
plt.show()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|