233 lines
8.8 KiB
Python
233 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
eeg_plot.py — Vistas por canal para el EEG ya preprocesado.
|
||
|
||
from eeg_io import Estudio
|
||
from eeg_plot import paneles, apilado, crudo_vs_limpio, mosaico_psd
|
||
|
||
est = Estudio("salida/estudio_signals.npz", "salida/estudio_metadata.json")
|
||
lim, nombres = est.preprocesado(notch_hz=60, pasa_altas=0.5, pasa_bajas=45)
|
||
|
||
paneles(est, lim, nombres, t0=120, dur=10) # un panel por canal
|
||
paneles(est, lim, nombres, t0=120, dur=10, cols=3) # en rejilla
|
||
|
||
Los huecos son NaN, asi que matplotlib corta la linea sola: un tramo sin datos
|
||
se ve como un vacio, no como una linea plana que podrias confundir con senal.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import numpy as np
|
||
import matplotlib.pyplot as plt
|
||
|
||
COLOR_EVENTO = "#c0392b"
|
||
COLOR_HUECO = "#bdc3c7"
|
||
|
||
|
||
def _ventana(est, x, t0, dur):
|
||
a = int(round(t0 * est.fs))
|
||
b = int(round((t0 + dur) * est.fs))
|
||
a, b = max(0, a), min(len(x), b)
|
||
if b <= a:
|
||
raise ValueError(f"Ventana vacia: t0={t0}, dur={dur}, "
|
||
f"duracion del registro {len(x) / est.fs:.1f} s")
|
||
return a, b, np.arange(a, b) / est.fs
|
||
|
||
|
||
def _eventos_en(est, t_ini, t_fin):
|
||
out = []
|
||
for e in est.md.get("eventos", []):
|
||
ts = e.get("t_seg")
|
||
if ts is not None and t_ini <= ts <= t_fin:
|
||
out.append((ts, str(e.get("texto") or "")[:26]))
|
||
return out
|
||
|
||
|
||
def _marcar_huecos(ax, t, col):
|
||
"""Sombrea los tramos sin datos para que el vacio sea explicito."""
|
||
nan = ~np.isfinite(col)
|
||
if not nan.any():
|
||
return
|
||
d = np.diff(nan.astype(np.int8), prepend=0, append=0)
|
||
for a, b in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)):
|
||
ax.axvspan(t[a], t[min(b, len(t) - 1)], color=COLOR_HUECO, alpha=.5,
|
||
lw=0)
|
||
|
||
|
||
def paneles(est, x, nombres, t0=0.0, dur=10.0, cols=1, escala=None,
|
||
eventos=True, huecos=True, alto=1.5, compartir_y=False,
|
||
titulo=None):
|
||
"""
|
||
Un panel por canal, cada uno con su propio eje en microvoltios.
|
||
|
||
escala : None -> cada canal se autoescala (ves bien los pequenos)
|
||
numero -> mismo limite +/-escala uV en todos (comparas amplitudes)
|
||
compartir_y : ata los ejes entre si; util para comparar de un vistazo
|
||
"""
|
||
x = np.asarray(x, dtype=np.float64)
|
||
a, b, t = _ventana(est, x, t0, dur)
|
||
seg = x[a:b]
|
||
n = len(nombres)
|
||
filas = int(np.ceil(n / cols))
|
||
fig, axs = plt.subplots(filas, cols, figsize=(15, alto * filas),
|
||
sharex=True, sharey=compartir_y, squeeze=False)
|
||
evs = _eventos_en(est, t[0], t[-1]) if eventos else []
|
||
|
||
for k, nm in enumerate(nombres):
|
||
ax = axs[k % filas][k // filas] if cols > 1 else axs[k][0]
|
||
col = seg[:, k]
|
||
ax.plot(t, col, lw=.6, color="#1a1a1a")
|
||
if huecos:
|
||
_marcar_huecos(ax, t, col)
|
||
finito = col[np.isfinite(col)]
|
||
if escala is not None:
|
||
ax.set_ylim(-escala, escala)
|
||
elif len(finito):
|
||
m = np.percentile(np.abs(finito), 99.5) * 1.25
|
||
ax.set_ylim(-m, m) if m > 0 else None
|
||
ax.set_ylabel(nm, rotation=0, ha="right", va="center", fontsize=9)
|
||
ax.tick_params(labelsize=7)
|
||
ax.grid(alpha=.2)
|
||
for ts, txt in evs:
|
||
ax.axvline(ts, color=COLOR_EVENTO, lw=.8, alpha=.6)
|
||
if len(finito):
|
||
ax.text(.995, .93, f"{finito.std():.0f} µV rms",
|
||
transform=ax.transAxes, ha="right", va="top",
|
||
fontsize=6.5, color="#555")
|
||
|
||
for c in range(cols):
|
||
for r in range(filas):
|
||
idx = c * filas + r if cols > 1 else r
|
||
if idx >= n:
|
||
axs[r][c].set_visible(False)
|
||
axs[min(filas, n) - 1 if cols == 1 else filas - 1][c].set_xlabel("s")
|
||
|
||
if evs and cols == 1:
|
||
for ts, txt in evs:
|
||
axs[0][0].annotate(txt, (ts, 1.02), xycoords=("data", "axes fraction"),
|
||
rotation=45, fontsize=7, color=COLOR_EVENTO,
|
||
ha="left", va="bottom")
|
||
fig.suptitle(titulo or f"t = {t[0]:.1f}–{t[-1]:.1f} s"
|
||
+ (" (autoescala por canal)" if escala is None
|
||
else f" (±{escala} µV en todos)"),
|
||
y=1.0, fontsize=10)
|
||
fig.tight_layout()
|
||
return fig, axs
|
||
|
||
|
||
def apilado(est, x, nombres, t0=0.0, dur=10.0, escala_uv=100,
|
||
negativo_arriba=True, eventos=True):
|
||
"""
|
||
Vista clasica de tira: todos los canales en un eje, separados por offsets.
|
||
Sirve para leer el registro; `paneles` sirve para inspeccionar un canal.
|
||
"""
|
||
x = np.asarray(x, dtype=np.float64)
|
||
a, b, t = _ventana(est, x, t0, dur)
|
||
seg = x[a:b]
|
||
signo = -1 if negativo_arriba else 1
|
||
fig, ax = plt.subplots(figsize=(15, .42 * len(nombres) + 2))
|
||
for k, nm in enumerate(nombres):
|
||
ax.plot(t, signo * seg[:, k] / escala_uv + k, lw=.5, color="k")
|
||
ax.set_yticks(range(len(nombres)))
|
||
ax.set_yticklabels(nombres, fontsize=8)
|
||
ax.invert_yaxis()
|
||
ax.set_xlim(t[0], t[-1])
|
||
ax.set_xlabel("s")
|
||
ax.grid(axis="x", alpha=.2)
|
||
if eventos:
|
||
for ts, txt in _eventos_en(est, t[0], t[-1]):
|
||
ax.axvline(ts, color=COLOR_EVENTO, lw=.9, alpha=.7)
|
||
ax.text(ts, -.6, txt, rotation=90, fontsize=7,
|
||
color=COLOR_EVENTO, va="bottom")
|
||
ax.set_title(f"{escala_uv} µV por division"
|
||
+ (" · negativo hacia arriba" if negativo_arriba else ""))
|
||
fig.tight_layout()
|
||
return fig, ax
|
||
|
||
|
||
def crudo_vs_limpio(est, crudo, limpio, nombres, canal, t0=0.0, dur=10.0):
|
||
"""
|
||
El mismo canal antes y despues del preprocesado, superpuesto y en espectro.
|
||
Es la comprobacion que evita filtrar de mas sin darte cuenta.
|
||
"""
|
||
k = nombres.index(canal) if canal in nombres else int(canal)
|
||
a, b, t = _ventana(est, limpio, t0, dur)
|
||
fig, axs = plt.subplots(1, 2, figsize=(15, 3.6),
|
||
gridspec_kw={"width_ratios": [2, 1]})
|
||
axs[0].plot(t, np.asarray(crudo)[a:b, k], lw=.5, color="#95a5a6",
|
||
label="crudo")
|
||
axs[0].plot(t, np.asarray(limpio)[a:b, k], lw=.6, color="#2c3e50",
|
||
label="preprocesado")
|
||
axs[0].set_xlabel("s")
|
||
axs[0].set_ylabel("µV")
|
||
axs[0].legend(fontsize=8)
|
||
axs[0].grid(alpha=.2)
|
||
axs[0].set_title(f"{nombres[k]} — t = {t[0]:.0f}–{t[-1]:.0f} s")
|
||
|
||
for datos, etq, color in ((crudo, "crudo", "#95a5a6"),
|
||
(limpio, "preprocesado", "#2c3e50")):
|
||
f, P = est.psd(np.asarray(datos)[:, k])
|
||
axs[1].semilogy(f, P, lw=1, color=color, label=etq)
|
||
axs[1].axvline(60, color=COLOR_EVENTO, ls="--", alpha=.6)
|
||
axs[1].axvspan(8, 13, color="gold", alpha=.15)
|
||
axs[1].set_xlim(0, min(80, est.fs / 2))
|
||
axs[1].set_xlabel("Hz")
|
||
axs[1].set_ylabel("µV²/Hz")
|
||
axs[1].legend(fontsize=8)
|
||
axs[1].grid(alpha=.3)
|
||
fig.tight_layout()
|
||
return fig, axs
|
||
|
||
|
||
def mosaico_psd(est, x, nombres, cols=4, fmax=45, banda_sombra=(8, 13)):
|
||
"""Un espectro por canal, en rejilla. Delata electrodos anomalos rapido."""
|
||
x = np.asarray(x, dtype=np.float64)
|
||
n = len(nombres)
|
||
filas = int(np.ceil(n / cols))
|
||
fig, axs = plt.subplots(filas, cols, figsize=(3.4 * cols, 2.1 * filas),
|
||
sharex=True, sharey=True, squeeze=False)
|
||
for k, nm in enumerate(nombres):
|
||
ax = axs[k // cols][k % cols]
|
||
try:
|
||
f, P = est.psd(x[:, k])
|
||
ax.semilogy(f, P, lw=.8, color="#2c3e50")
|
||
except ValueError as e:
|
||
ax.text(.5, .5, str(e)[:40], transform=ax.transAxes, fontsize=7,
|
||
ha="center")
|
||
if banda_sombra:
|
||
ax.axvspan(*banda_sombra, color="gold", alpha=.15)
|
||
ax.set_xlim(0, fmax)
|
||
ax.set_title(nm, fontsize=9)
|
||
ax.tick_params(labelsize=7)
|
||
ax.grid(alpha=.25)
|
||
for k in range(n, filas * cols):
|
||
axs[k // cols][k % cols].set_visible(False)
|
||
for c in range(cols):
|
||
axs[filas - 1][c].set_xlabel("Hz", fontsize=8)
|
||
for r in range(filas):
|
||
axs[r][0].set_ylabel("µV²/Hz", fontsize=8)
|
||
fig.tight_layout()
|
||
return fig, axs
|
||
|
||
|
||
def navegador(est, x, nombres, dur=10.0, **kw):
|
||
"""
|
||
Deslizador para recorrer el registro. Necesita ipywidgets; si no esta,
|
||
devuelve una funcion normal a la que le pasas el tiempo a mano.
|
||
"""
|
||
def dibujar(t0):
|
||
paneles(est, x, nombres, t0=t0, dur=dur, **kw)
|
||
plt.show()
|
||
try:
|
||
from ipywidgets import interact, FloatSlider
|
||
except ImportError:
|
||
print("ipywidgets no esta instalado (pip install ipywidgets).")
|
||
print(f"Usa la funcion devuelta: nav(120) dibuja desde el segundo 120.")
|
||
return dibujar
|
||
tope = max(0.0, len(x) / est.fs - dur)
|
||
return interact(dibujar,
|
||
t0=FloatSlider(min=0, max=tope, step=dur / 2, value=0,
|
||
continuous_update=False,
|
||
description="t0 (s)"))
|