| 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_TASKS = len(all_tasks) |
| |
| |
| N_CHANNELS = 32 |
| N_TIMESTEPS = 1101 |
|
|
|
|
| if os.path.exists(f'./images/erpdata.pkl'): |
| X, Y = pickle.load(open(f'./images/erpdata.pkl', 'rb')) |
| else: |
| task = None |
| |
| |
| 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')) |
|
|
|
|
| |
| 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 |
| T_MIN, T_MAX = -0.2, 0.9 |
|
|
| |
| ERP_CHANNEL = 'Pz' |
| TOPO_TIMES = [0.200, 0.300, 0.400, 0.500, 0.600] |
|
|
| |
| OUTPUT_DIR = "images" |
| os.makedirs(OUTPUT_DIR, exist_ok=True) |
|
|
| def process_eeg_data(X, Y, ch_names, sfreq): |
| |
| |
| info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types='eeg') |
|
|
| |
| montage = mne.channels.make_standard_montage('standard_1020') |
| info.set_montage(montage, on_missing='ignore') |
|
|
| |
| 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} |
|
|
| |
| |
| epochs = mne.EpochsArray(X, info, events=events, tmin=T_MIN, event_id=event_id) |
|
|
| |
| |
| print("Applying baseline correction from -0.2s to 0s...") |
| epochs.apply_baseline(baseline=(T_MIN, 0)) |
|
|
| |
| 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): |
| |
| data = epochs_condition.get_data(picks=picks)[:, :] * 1e3 |
|
|
| mean_erp = np.mean(data, axis=0).flatten() |
|
|
| |
| sem = np.std(data, axis=0, ddof=1) |
| sem = sem.flatten() |
|
|
| times = epochs_condition.times |
|
|
| |
| ax.plot(times, mean_erp, color=color, linestyle=linestyle, label=label, lw=2) |
|
|
| |
| 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) |
| |
| 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]) |
| 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) |
|
|
| |
| 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}'") |
| |