EEGFaceSem / scripts /gen_ERPplot.py
yefllower's picture
EEGFaceSem: processed data, code, models
196bee3
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib import colors, cm
import mne
import pickle
all_tasks = ['facecat/female', 'facecat/male', 'facecat/blond', 'facecat/darkhaired', 'facecat/smiles', 'facecat/nosmile', 'facecat/old', 'facecat/young']
indir = './data/processed/'
# N_SUBJECTS = 30
N_TASKS = len(all_tasks)
# TRIALS_PER_TASK_SUBJECT = 280
# TOTAL_TRIALS = N_SUBJECTS * N_TASKS * TRIALS_PER_TASK_SUBJECT # 67200
N_CHANNELS = 32 # 32 channels
N_TIMESTEPS = 1101 # 1101 time points [-0.2, 0.9]s with 1000Hz sampling rate
if os.path.exists(f'./images/erpdata.pkl'):
X, Y = pickle.load(open(f'./images/erpdata.pkl', 'rb'))
else:
task = None
# task_id = 0
# task = all_tasks[task_id]
data_path='./data/processed/'
from utils import Dataset
dataset = Dataset(data_path, cache=True, chs=N_CHANNELS, samples=N_TIMESTEPS, task=task)
X, Y, ids = dataset.X, dataset.Y, dataset.ids
print(f"Loaded data with shapes: X:{X.shape}, Y:{Y.shape}, ids:{ids.shape}")
X = X.reshape(X.shape[0], N_CHANNELS, N_TIMESTEPS)
Xs, Ys = [], []
for subject in range(30):
for y in range(2):
mask = (ids[:, 0] == subject) & (Y == y)
Xs.append(X[mask].mean(axis=0))
Ys.append(Y[mask][0])
X = np.array(Xs)
Y = np.array(Ys)
pickle.dump((X, Y), open(f'./images/erpdata.pkl', 'wb'))
# Define channel names and properties
CHANNEL_NAMES = [
'Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'FC5', 'FC1', 'FC2', 'FC6', 'T7',
'C3', 'Cz', 'C4', 'T8', 'TP9', 'CP5', 'CP1', 'CP2', 'CP6', 'TP10', 'P7', 'P3',
'Pz', 'P4', 'P8', 'PO9', 'O1', 'Iz', 'O2', 'PO10'
]
N_CHANNELS = len(CHANNEL_NAMES)
SAMPLING_FREQ = 1000 # in Hz
T_MIN, T_MAX = -0.2, 0.9 # Time window in seconds
# ERP and Topoplot plotting settings
ERP_CHANNEL = 'Pz' # Channel to display in the ERP plot
TOPO_TIMES = [0.200, 0.300, 0.400, 0.500, 0.600] # Time points for topoplots in seconds
# Output directory
OUTPUT_DIR = "images"
os.makedirs(OUTPUT_DIR, exist_ok=True)
def process_eeg_data(X, Y, ch_names, sfreq):
# Create an MNE Info object, which is required for all MNE functions.
# It holds metadata like channel names, sampling rate, etc.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types='eeg')
# Set standard montage for plotting topographies
montage = mne.channels.make_standard_montage('standard_1020')
info.set_montage(montage, on_missing='ignore') # ignore channels not in montage
# The event array needs to be in the format: [sample_index, 0, event_id]
n_trials = X.shape[0]
events = np.array([
[i * (T_MAX - T_MIN) * sfreq, 0, label] for i, label in enumerate(Y)
]).astype(int)
event_id = {'non_target': 0, 'target': 1}
# Create MNE Epochs object from the raw numpy array
# The data must be in (trials, channels, time) and scaled to Volts
epochs = mne.EpochsArray(X, info, events=events, tmin=T_MIN, event_id=event_id)
# Perform baseline correction using the interval [-0.2s, 0s]
# This subtracts the mean of the baseline period from each channel in each epoch.
print("Applying baseline correction from -0.2s to 0s...")
epochs.apply_baseline(baseline=(T_MIN, 0))
# Average the epochs for each condition to create Evoked objects
evoked_target = epochs['target'].average()
evoked_nontarget = epochs['non_target'].average()
evokeds = {'Target': evoked_target, 'Non-Target': evoked_nontarget}
return evokeds, epochs, info
def plot_erp_with_shade(epochs_condition, picks, ax, color, linestyle, label):
# MNE returns data in Volts, convert to microVolts for plotting
data = epochs_condition.get_data(picks=picks)[:, :] * 1e3
mean_erp = np.mean(data, axis=0).flatten()
# Calculate Standard Error of the Mean (SEM)
sem = np.std(data, axis=0, ddof=1) #/ np.sqrt(data.shape[0])
sem = sem.flatten()
times = epochs_condition.times
# Plot the mean ERP line
ax.plot(times, mean_erp, color=color, linestyle=linestyle, label=label, lw=2)
# Plot the shaded SEM area
ax.fill_between(times, mean_erp - sem, mean_erp + sem, color=color, alpha=0.2, linewidth=0)
evokeds, epochs, info = process_eeg_data(X, Y, CHANNEL_NAMES, SAMPLING_FREQ)
diff_wave = mne.combine_evoked([evokeds['Target'], evokeds['Non-Target']], weights=[1, -1])
print("Generating the figure...")
fig = plt.figure(figsize=(12, 8))
n_times = len(TOPO_TIMES)
# Make the colorbar column narrow compared to topoplot columns
width_ratios = [20] * n_times + [1]
gs = GridSpec(3, n_times + 1, height_ratios=[1, 2, 1], hspace=0.5, wspace=0.7, width_ratios=width_ratios)
max_val_target = np.abs(evokeds['Target'].data).max() * 1e6
max_val_nontarget = np.abs(evokeds['Non-Target'].data).max() * 1e6
global_max_val = max(max_val_target, max_val_nontarget) * 0.5
vlim = (-global_max_val, global_max_val)
print(f"Topoplot color limits set to: [{vlim[0]:.2f}, {vlim[1]:.2f}] µV")
for i, t in enumerate(TOPO_TIMES):
ax = fig.add_subplot(gs[0, i])
evokeds['Target'].plot_topomap(times=t, axes=ax, show=False, cmap='RdBu_r', vlim=vlim, colorbar=False)
ax.set_title(f'{t:.3f} s')
if i == 0:
ax.set_ylabel('Target', fontsize=14, rotation=90, labelpad=20)
erp_ax = fig.add_subplot(gs[1, :-1])
plot_erp_with_shade(epochs['target'], picks=ERP_CHANNEL, ax=erp_ax, color='blue', linestyle='-', label='Target')
plot_erp_with_shade(epochs['non_target'], picks=ERP_CHANNEL, ax=erp_ax, color='red', linestyle='-', label='Non-Target')
erp_ax.axhline(0, linestyle='-', color='black', linewidth=0.8)
erp_ax.axvline(0, linestyle='-', color='black', linewidth=0.8)
erp_ax.set_xlabel("Time (s)", fontsize=14)
erp_ax.set_ylabel("Amplitude (µV)", fontsize=14)
erp_ax.legend(loc='upper left', fontsize=12)
erp_ax.set_xlim(epochs.times.min(), epochs.times.max())
for t in TOPO_TIMES:
erp_ax.axvline(t, linestyle=':', color='gray', linewidth=0.5)
cax = fig.add_subplot(gs[1, -1]) # Use the last column of the middle row
norm = colors.Normalize(vmin=vlim[0], vmax=vlim[1])
sm = cm.ScalarMappable(cmap='RdBu_r', norm=norm)
cbar = fig.colorbar(sm, cax=cax)
cbar.set_label("Amplitude (µV)", fontsize=14)
# --- Bottom Row: Non-Target Topoplots ---
for i, t in enumerate(TOPO_TIMES):
ax = fig.add_subplot(gs[2, i])
evokeds['Non-Target'].plot_topomap(times=t, axes=ax, show=False, cmap='RdBu_r', vlim=vlim, colorbar=False)
ax.set_title(f'{t:.3f} s', y=-0.3)
if i == 0:
ax.set_ylabel('Non-Target', fontsize=14, rotation=90, labelpad=20)
fig.tight_layout(rect=[0, 0, 1, 0.96])
pdf_path = os.path.join(OUTPUT_DIR, "erp_figure3.pdf")
eps_path = os.path.join(OUTPUT_DIR, "erp_figure3.eps")
png_path = os.path.join(OUTPUT_DIR, "erp_figure3.png")
fig.savefig(pdf_path)
fig.savefig(eps_path)
fig.savefig(png_path)
print(f"\nFigure saved to '{pdf_path}' and '{eps_path}'")
# plt.show()