OSCR

Structural Eigenmodes of the Brain to Improve the Source Localization of EEG: Application to Epileptiform Activity.

Code ↔ Paper

14 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 14 matches
  1. [1] § Results › Structural Eigenmodes Enable Source Localization of Seizure Spread › Testing, Validation, and Comparison to Other Approaches › Comparison Between Structural Eigenmode Approaches ↔ STC_Analysis.ipynb, lines 501 to 531 · score 0.70 · region localization error, squared error, variance explained, cosine score, correlated, SNR · Report a mismatch
  2. [2] § Methods › Simulated Evaluation Data › Mapping to Sensor Space with MNE Python ↔ gem_fns.py, lines 561 to 619 · score 0.66 · sensor space, inverse problem, efficiency, oriented, source space, cortex · Report a mismatch
  3. [3] § Results › Structural Eigenmodes Enable Source Localization of Seizure Spread › Performance Against Number of Modes — The Over‐ Versus Under‐Parameterized Regimes ↔ STC_Analysis.ipynb, lines 143 to 245 · score 0.63 · region localization error, EEG noise, EEG power, cosine score, SNR, metrics · Report a mismatch
  4. [4] § Methods › Source Localization ↔ gem_fns.py, lines 473 to 559 · score 0.62 · Small singular, EEG modes, component, SVD, rcond, truncate · Report a mismatch
  5. [5] § Methods › Evaluation › Simulation Test Conditions ↔ sample_sesl_pipeline.ipynb, lines 134 to 150 · score 0.62 · dSPM, eLORETA, sLORETA, MNE · Report a mismatch
  6. [6] § Results › Structural Eigenmodes Enable Source Localization of Seizure Spread › Testing, Validation, and Comparison to Other Approaches › Performance of Established Methods ↔ sample_sesl_pipeline.ipynb, lines 134 to 150 · score 0.60 · dSPM, eLORETA, sLORETA, loose, MNE, noise · Report a mismatch
  7. [7] § Results › Structural Eigenmodes Enable Source Localization of Seizure Spread › Testing, Validation, and Comparison to Other Approaches › Performance of Established Methods ↔ STC_Analysis.ipynb, lines 501 to 531 · score 0.58 · sLORETA, variance explained, cosine score, loose, MNE, metrics · Report a mismatch
  8. [8] § Methods › Structural Brain Data ↔ dynsim_fns.py, lines 101 to 196 · score 0.56 · streamline length, connectivity matrix, Spherical, parcellation, threshold · Report a mismatch
  9. [9] § Methods › Simulated Evaluation Data › Epileptor Equations ↔ dynsim_fns.py, lines 436 to 507 · score 0.55 · state variables, Epileptor model, spike, TVB, seizures · Report a mismatch
  10. [10] § Methods › Evaluation › Simulation Test Conditions ↔ STC_Analysis.ipynb, lines 28 to 88 · score 0.55 · inverse solutions, forward model, HCP, fsaverage, signal, EEG · Report a mismatch
  11. [11] § Methods › Evaluation › Simulation Metrics › Region Localization Error ↔ STC_Analysis.ipynb, lines 143 to 245 · score 0.54 · Region localization error, EEG power, Otsu, MNE, Threshold · Report a mismatch
  12. [12] § Methods › Eigenmode Creation › Connectome Eigenmodes ↔ STC_Analysis.ipynb, lines 306 to 384 · score 0.54 · subcortical regions, Connectome eigenmodes, geometric eigenmodes, discrete, eigenvalue · Report a mismatch
  13. [13] § Methods › Structural Brain Data ↔ dynsim_fns.py, lines 267 to 325 · score 0.53 · subcortical structures, cortical region, atlas, parcellation, vertex · Report a mismatch
  14. [14] § Methods › Source Localization ↔ gem_fns.py, lines 473 to 559 · score 0.51 · EEG modes, singular, vector, SVD, operator, squares · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 720 lines · 33 KB · BSD-3-Clause · 6 matches

  1. # %% [markdown]
  2. # # Paper STC Analysis Notebook
  3. #
  4. # This notebook provides an example of how the functions in `sesl` (structural eigenmode source localisation) can be used to perform source localisation on a simulated dataset.
  5. # It runs on one example simulation, uses fsaverage, and demonstrates how the figures in the original paper can be generated (if run on all simulations and with all the different input files).
  6. # Remember to put the 1000 region parcellation labels into the appropriate folder in your Freesurfer fsaverage directory.
  7. # The aim for this notebook is for reproducibility of the analysis in the paper, so if you are interested in running `sesl` on your own data, please refer to the other notebook.
  8. # %%
  9. import numpy as np
  10. import matplotlib.pyplot as plt
  11. from pathlib import Path
  12. from IPython.display import clear_output
  13. import mne
  14. from mne.minimum_norm import make_inverse_operator, apply_inverse
  15. from skimage.filters import threshold_otsu
  16. from useful_fns import *
  17. from gem_fns import *
  18. from dynsim_fns import *
  19. from plot_fns import plot_mean_and_range, plot_tria_mesh
  20. %load_ext autoreload
  21. %autoreload 2
  22. # %%
  23. ANALYSIS_TYPE = 'GEM_discrete' # 'GEM_discrete' or 'GEM_surface' or 'CEM_discrete' or 'SEM_discrete'
  24. SNR = None # Signal to noise ratio for the simulation and MN inverse solutions - None for no noise
  25. if SNR is not None:
  26. RCOND = 1/(10**(SNR/10))
  27. else:
  28. RCOND = None
  29. ELECTRODE_CONFIG = '1010'
  30. if ELECTRODE_CONFIG == '1020':
  31. ONLY_20ELECTRODES = True # Whether to only use the 20 electrodes in the 10-20 system
  32. MONTAGE = 'standard_1020' # EEG montage - 'standard_1020' or 'standard_1005'
  33. elif ELECTRODE_CONFIG == '1010':
  34. ONLY_20ELECTRODES = False
  35. MONTAGE = 'standard_1020' # EEG montage - 'standard_1020' or 'standard_1005'
  36. elif ELECTRODE_CONFIG == '1005':
  37. ONLY_20ELECTRODES = False
  38. MONTAGE = 'standard_1005' # EEG montage - 'standard_1020' or 'standard_1005'
  39. LOOSE = 0 # Fixed Orientation = 0, Loose = 1.
  40. DEPTH = 0 # Depth weighting - Best not to use for EMs
  41. DOWNSAMPLE = True # Whether to use the downsampled SRC or dense MRI mesh for calculating the GEM
  42. PICK_EEG = True # Whether to use EEG
  43. PICK_MEG = False # Whether to use MEG
  44. BINARISE_CEM = False # Whether to binarise the CEM before calculating the eigenmodes
  45. USE_FSAVERAGE_FWD = False # Whether to use the fsaverage forward model when solving the inverse problem
  46. USE_FSAVERAGE_GEM = False # Whether to use the fsaverage MRI when calculating the GEMs
  47. USE_GROUP_CON = False # Whether to use the group connectome when calculating the CEMs
  48. NUM_MODES = 1000
  49. STEP = 50
  50. num_modes = np.arange(start=STEP, stop=NUM_MODES+STEP, step=STEP)
  51. COMPARE_MNE = None # Whether to compare with MNE - Type the method or None/False
  52. SURROGATE_TEST = None # 'rotate' # 'roll' or 'rotate'
  53. SHUFFLE_ARRAY = np.arange(7, 700, 70) # Best to use an increment such that it's not a divisor of the number of sources in each hemisphere and don't start from 0 if using roll
  54. # Hyperparameters Unlikely To Change:
  55. ICO = 5 # Ideally this would be 5 for a higher resolution mesh, but 3 for this working example due to online memory limits.
  56. CON = 'con1019' # 'con1019' or 'con379'
  57. SFREQ = 78.125 # Hz - Default Sampling Frequency is 78.125Hz from 78.125Hz = 20kHz /256 = from 1/dt*1000 / scaling of 256 - Or it is /128 by the temporal averaging = 0.61 Hz
  58. # Path
  59. FS_PATH = Path("/Applications/freesurfer/7.3.2/")
  60. SUBJECTS_DIR = FS_PATH / "subjects"
  61. SUBJECT = "fsaverage"
  62. SIM_DIRECTORY = Path('Ignore/Simulations/')
  63. PARCELLATION = 'native.1000Parcels_Yeo2011_7Networks' # 'HCPMMP1'
  64. CON_PATH = f'External_Resources/HCP_data/HCP100206_{CON}'
  65. DISCRETE_FWD_PATH = Path(f'Ignore/{SUBJECT}_Con1000_twohemisrc_fwd.fif')
  66. # If None, will generate the GEMs - Path('Ignore/{SUBJECT}_ico5_gems.npz')
  67. # Better to recalculate to avoid mistakes, but using the ultra high res mesh is better and not realistic to recalculate.
  68. GEM_PATH = None
  69. SIM_TYPE = 'NMM'
  70. # '7networks_RH_Default_TempPole_1' # 'NMM' for TVB simualtion / a given time series or NAME_OF_REGION / INDEX_OF_REGION for a patch simulation
  71. EXTENT = 20 # Extent of the patch in mm
  72. SIM_FILE = Path(f'{SIM_DIRECTORY}/HCP100206_con1019_CIFTI_STRUCTURE_THALAMUS_LEFT_g_2.0.npz')
  73. print(f"Simulation File: {SIM_FILE}")
  74. # %%
  75. if SIM_TYPE == 'NMM':
  76. # Load the TVB Simulation
  77. raw_x = np.load(SIM_FILE)['raw_x'].astype(np.float32)
  78. raw_t = np.arange(raw_x.shape[0])/SFREQ
  79. # Reduce data to 60s
  80. raw_x = raw_x[:int(60*SFREQ),:,:,:]
  81. raw_t = raw_t[:int(60*SFREQ)]
  82. # Take only necessary state_variables
  83. raw_x = raw_x[:,0,:,0]
  84. # Transformations to the data:
  85. # Use the negative, so that the seizure-state has higher voltage
  86. raw_x = -raw_x
  87. # Add 1 to the data so neutral is 0V
  88. # raw_x = raw_x + 1
  89. # Lower the units
  90. raw_x = raw_x*10e-9
  91. # Subtracting by simple offset works best, such that resting is around 0
  92. offset = np.percentile(raw_x, 20)
  93. raw_x = raw_x - offset
  94. # %%
  95. if SIM_TYPE == 'NMM':
  96. plt.plot(raw_t, raw_x[:, 0])
  97. plt.xlabel('Time (s)', fontsize=14)
  98. plt.ylabel('Amplitude (Am)', fontsize=14)
  99. plt.xticks(fontsize=14)
  100. plt.yticks(fontsize=14)
  101. plt.tight_layout()
  102. plt.show()
  103. # %%
  104. if SIM_TYPE == 'NMM':
  105. # Plot a carpet plot (square)
  106. # Need to Change the Shape of the Simulation Output (2D and Transposed)
  107. plt.figure(figsize=(20, 10))
  108. cs=plt.imshow(raw_x.T, cmap="gray", aspect='equal',interpolation='none',origin='lower')
  109. plt.title('Raw Source Time Series', fontsize=20)
  110. axcb=plt.colorbar(cs)
  111. axcb.set_label('Amplitude (Am)', fontsize=20)
  112. axcb.ax.tick_params(labelsize=16)
  113. plt.ylabel('Region', fontsize=20)
  114. plt.xlabel('Time (s)', fontsize=20)
  115. xticks = np.arange(start=0,stop=raw_t.shape[0],step=int(np.ceil(raw_t.shape[0]/5)))
  116. plt.xticks(ticks=xticks,labels=np.round(raw_t[xticks],0).astype(int))
  117. plt.axis("tight")
  118. plt.xticks(fontsize=16)
  119. plt.yticks(fontsize=16)
  120. plt.show()
  121. # %% [markdown]
  122. # ## GEM Surface
  123. # %%
  124. if ANALYSIS_TYPE == 'GEM_surface':
  125. # Initialise the lists
  126. RLEs = []
  127. RLE_points = []
  128. coss = []
  129. ses = []
  130. cos_acrosstime = []
  131. expvars = []
  132. # Read fwd solution
  133. fwd = mne.read_forward_solution(f'Ignore/{SUBJECT}_ico{ICO}-fwd.fif') # mne.read_forward_solution(f'Ignore/{SUBJECT}_openmeeg_ico{ICO}-fwd.fif')
  134. # Construct the cortical mask
  135. mask = cortical_mask(SUBJECT, SUBJECTS_DIR, fwd['src'], downsample=True)
  136. info = generate_mne_info(sampling_freq=SFREQ, montage_name=MONTAGE, add_meg=PICK_MEG)
  137. if ONLY_20ELECTRODES:
  138. names_1020 = ['Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'A1', 'T3', 'C3', 'Cz', 'C4', 'T4', 'T5', 'P3', 'Pz', 'P4', 'T6', 'O1', 'O2', 'A2']
  139. ch_inds = mne.pick_channels(ch_names=info['ch_names'], include=names_1020, )
  140. info = mne.pick_info(info, ch_inds)
  141. fwd = mne.pick_channels_forward(fwd, include=info['ch_names'], )
  142. fwd = mne.pick_types_forward(fwd, meg=PICK_MEG, eeg=PICK_EEG, exclude=info['bads'], )
  143. com_labels = None # If end up shifting the ordering of function calls around, com_labels is input to tvb_loadtomne
  144. # Load the TVB simulation
  145. stc, sim = tvb_loadtomne(raw_x, SUBJECT, fwd, info, PARCELLATION, selected_label=com_labels, fs_path= FS_PATH, )
  146. if SNR is not None:
  147. eeg_power = np.sum(sim.data**2)/sim.data.size
  148. eeg_noise = np.random.normal(0, np.sqrt(eeg_power)/np.sqrt(10**(SNR/10)), sim.data.shape)
  149. sim.data = sim.data + eeg_noise
  150. # Set EEG Reference if required - Doesn't matter if before or after adding noise
  151. if PICK_EEG:
  152. sim.set_eeg_reference('average',projection=True)
  153. # Compute covariance
  154. cov = mne.Covariance(data=np.identity(len(sim.ch_names)), names=sim.ch_names, bads=sim.info['bads'], projs=sim.info['projs'], nfree=1 )
  155. # Apply a highpass filter
  156. # sim = sim.filter(l_freq=1., h_freq=None )
  157. # Index of 50% of max EEG power
  158. hmp_i = np.where(np.sum(sim.data * sim.data, axis=0) > 0.5*np.sum(sim.data * sim.data, axis=0).max())[0][0]
  159. # GEM Solver
  160. # Graph for varying number of modes
  161. if USE_FSAVERAGE_FWD:
  162. fwd = mne.read_forward_solution(Path(f'Ignore/fsaverage_ico{ICO}-fwd.fif'))
  163. fwd = mne.pick_channels_forward(fwd, include=info['ch_names'], )
  164. fwd = mne.pick_types_forward(fwd, meg=PICK_MEG, eeg=PICK_EEG, exclude=info['bads'], )
  165. stc, _ = tvb_loadtomne(raw_x, 'fsaverage', fwd, info, PARCELLATION, selected_label=com_labels, fs_path= FS_PATH, )
  166. SUBJECT = 'fsaverage'
  167. if GEM_PATH:
  168. # Load the GEMs
  169. eval, emodes = np.load(GEM_PATH)['evals'], np.load(GEM_PATH)['emodes']
  170. else:
  171. # Calculate the eigenmodes
  172. if USE_FSAVERAGE_GEM:
  173. fwd_fsaverage = mne.read_forward_solution(Path(f'Ignore/fsaverage_ico{ICO}-fwd.fif'))
  174. mask = cortical_mask('fsaverage', SUBJECTS_DIR, fwd_fsaverage['src'], downsample=True)
  175. evals, emodes = both_hemi_calc_eig(fwd_fsaverage['src'], mask=mask, num_modes=NUM_MODES)
  176. del fwd_fsaverage
  177. else:
  178. evals, emodes = both_hemi_calc_eig(fwd['src'], mask=mask, num_modes=NUM_MODES)
  179. weight = 1 / (2*np.pi + np.sqrt(np.abs(evals)))
  180. emodes = emodes * weight[np.newaxis, :]
  181. for num_mode in num_modes:
  182. # 1. Obtain the eigenmodes
  183. emodes_subset = np.concatenate((emodes[:, :num_mode//2], emodes[:, NUM_MODES//2:NUM_MODES//2+num_mode//2]), axis=1)
  184. # 2. Apply the solver
  185. loose, depth = LOOSE, DEPTH
  186. solver_kwargs = dict(emodes=emodes_subset, rcond=RCOND)
  187. stc_est_region, var_exp, w = apply_solver(gem_solver, sim, fwd, cov, loose, depth, **solver_kwargs)
  188. # 3. Calculate threshold
  189. threshold = threshold_otsu(np.abs(stc_est_region.data,))/ np.max(np.abs(stc_est_region.data)) * 100
  190. # threshold = 40
  191. # print(f"Otsu's Threshold = {threshold}")
  192. # 4. Calculate metrics
  193. RLE = mne.simulation.metrics.region_localization_error(stc, stc_est_region, fwd['src'], threshold=f'{threshold}%', per_sample=False)
  194. RLE_point = mne.simulation.metrics.region_localization_error(stc.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), stc_est_region.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), fwd['src'], threshold=f'{threshold}%', per_sample=False)
  195. cos = mne.simulation.metrics.cosine_score(stc, stc_est_region, per_sample=False)
  196. aligned_stc_est = stc_aligner(stc, stc_est_region)
  197. nse = (aligned_stc_est.data/np.abs(aligned_stc_est.data).max() - stc.data/np.abs(stc.data).max())**2
  198. varexp_stc = log_exp_var(stc.data/np.abs(stc.data).max(), np.sqrt(nse))
  199. se = np.mean(nse)
  200. cos_t = mne.simulation.metrics.cosine_score(stc, stc_est_region, per_sample=True)
  201. varexp_stc = log_exp_var(stc.data/np.abs(stc.data).max(), np.sqrt(nse))
  202. expvars.append(varexp_stc)
  203. RLEs.append(RLE)
  204. RLE_points.append(RLE_point)
  205. coss.append(cos)
  206. ses.append(se)
  207. cos_acrosstime.append(cos_t)
  208. # %% [markdown]
  209. # ## CON1019 Discrete Source Space (1000 cortical regions)
  210. # %%
  211. if ANALYSIS_TYPE != 'GEM_surface':
  212. # Load Connectivity
  213. if SIM_TYPE == 'NMM':
  214. load_centres=False
  215. else:
  216. load_centres=True
  217. if USE_GROUP_CON or SUBJECT == 'fsaverage':
  218. con = con_loader(Path('External_Resources/HCP_data/SC_con1019/group_streamline_count_atlas.csv'), load_tracts=True, threshold=None, weights_only=True, load_centres=load_centres, subject=SUBJECT, subjects_dir=SUBJECTS_DIR)
  219. con.region_labels = np.loadtxt(CON_PATH / Path('region_names.txt'), dtype=str)
  220. else:
  221. con = con_loader(CON_PATH, load_tracts=True, threshold=None, weights_only=False, load_centres=load_centres, subject=SUBJECT, subjects_dir=SUBJECTS_DIR)
  222. selected_label = mne.read_labels_from_annot(SUBJECT, PARCELLATION, subjects_dir=SUBJECTS_DIR)
  223. # Remove the ??? regions
  224. selected_label = [label for label in selected_label if '???' not in label.name]
  225. # Load fwd, needs to be the discrete one
  226. fwd = mne.read_forward_solution(DISCRETE_FWD_PATH)
  227. info = generate_mne_info(sampling_freq=SFREQ, montage_name=MONTAGE, add_meg=PICK_MEG)
  228. if ONLY_20ELECTRODES:
  229. names_1020 = ['Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'A1', 'T3', 'C3', 'Cz', 'C4', 'T4', 'T5', 'P3', 'Pz', 'P4', 'T6', 'O1', 'O2', 'A2']
  230. ch_inds = mne.pick_channels(ch_names=info['ch_names'], include=names_1020, )
  231. info = mne.pick_info(info, ch_inds)
  232. fwd = mne.pick_channels_forward(fwd, include=info['ch_names'], )
  233. fwd = mne.pick_types_forward(fwd, meg=PICK_MEG, eeg=PICK_EEG, exclude=info['bads'], )
  234. # 1. Generate the information from the dense source space Freesurfer labels
  235. region_centres = centre_loader(con.region_labels, coords='MRI_RAS', parcellation=PARCELLATION, subject=SUBJECT, subjects_dir=SUBJECTS_DIR, ) / 1000 # Convert to m
  236. label_hemi = np.array([label.hemi for label in selected_label])
  237. label_names = np.array([label.name[:-3] for label in selected_label])
  238. com_labels = generate_com_labels(region_centres, label_names, label_hemi, SUBJECT)
  239. if SIM_TYPE == 'NMM':
  240. # Load the TVB simulation and convert to EEG
  241. stc, sim = tvb_loadtomne(raw_x, SUBJECT, fwd, info, PARCELLATION, selected_label=com_labels, fs_path= FS_PATH, )
  242. else:
  243. # Create a single timepoint patch simulation with the centre region being the string in SIM_TYPE
  244. stc, sim = patch_simulator(con, SIM_TYPE, fwd, info, selected_label=com_labels, radius=EXTENT, restrict_hemi=True, full_src=True)
  245. raw_t = np.array([0])
  246. if SNR is not None:
  247. eeg_power = np.sum(sim.data**2)/sim.data.size
  248. eeg_noise = np.random.normal(0, np.sqrt(eeg_power)/np.sqrt(10**(SNR/10)), sim.data.shape)
  249. sim.data = sim.data + eeg_noise
  250. # Set EEG Reference if required - Doesn't matter if before or after adding noise
  251. if PICK_EEG:
  252. sim.set_eeg_reference('average',projection=True)
  253. # sim.apply_proj()
  254. # Compute covariance
  255. cov = mne.Covariance(data=np.identity(len(sim.ch_names)), names=sim.ch_names, bads=sim.info['bads'], projs=sim.info['projs'], nfree=1 )
  256. # Index of 50% of max EEG power
  257. hmp_i = np.where(np.sum(sim.data * sim.data, axis=0) > 0.5*np.sum(sim.data * sim.data, axis=0).max())[0][0]
  258. # %%
  259. # Load or generate the EMs
  260. if ANALYSIS_TYPE != 'GEM_surface':
  261. # In case we want to use a different fwd to the one used for the simulation (i.e. using group average fwd)
  262. if USE_FSAVERAGE_FWD:
  263. SUBJECT = 'fsaverage'
  264. fwd = mne.read_forward_solution(Path(f'Ignore/{SUBJECT}_Con1000_twohemisrc_fwd.fif'))
  265. # Read fwd solution
  266. fwd_surf = mne.read_forward_solution(Path(f'Ignore/{SUBJECT}_ico{ICO}-fwd.fif'))
  267. # Geometric eigenmodes
  268. if ANALYSIS_TYPE == 'GEM_discrete':
  269. # Load the pre-computed GEMs
  270. if GEM_PATH:
  271. evals, emodes = np.load(GEM_PATH)['evals'], np.load(GEM_PATH)['emodes']
  272. # Calculate the eigenmodes
  273. elif USE_FSAVERAGE_GEM:
  274. fwd_surf = mne.read_forward_solution(Path(f'Ignore/fsaverage_ico5-fwd.fif'))
  275. mask = cortical_mask('fsaverage', SUBJECTS_DIR, fwd_surf['src'], downsample=DOWNSAMPLE)
  276. evals, emodes = both_hemi_calc_eig(fwd_surf['src'], downsample=DOWNSAMPLE, mask=mask, num_modes=NUM_MODES, normalise=False )
  277. emodes = subset_eigenmodes(emodes, fwd_surf['src'], method='average', downsample=DOWNSAMPLE, parcellation=PARCELLATION, subjects_dir=SUBJECTS_DIR, region_labels=con.region_labels, subject='fsaverage', normalise=True)
  278. else:
  279. mask = cortical_mask(SUBJECT, SUBJECTS_DIR, fwd_surf['src'], downsample=DOWNSAMPLE)
  280. evals, emodes = both_hemi_calc_eig(fwd_surf['src'], downsample=DOWNSAMPLE, mask=mask, num_modes=NUM_MODES, normalise=False )
  281. # np.savez_compressed(Path(f'Ignore/{SUBJECT}_ico5_gems.npz'), evals=evals, emodes=emodes)
  282. emodes = subset_eigenmodes(emodes, fwd_surf['src'], method='average', downsample=DOWNSAMPLE, parcellation=PARCELLATION, subjects_dir=SUBJECTS_DIR, region_labels=con.region_labels, subject=SUBJECT, normalise=True)
  283. # np.savez_compressed(Path(f'Ignore/{SUBJECT}_con1000_gems.npz'), evals=evals, emodes=emodes)
  284. # Now weight the emodes by the inverse of the eigenvalues
  285. weight = 1 / (2*np.pi + np.sqrt(np.abs(evals)))
  286. emodes = emodes * weight[np.newaxis, :]
  287. # Connectivity eigenmodes
  288. elif ANALYSIS_TYPE == 'CEM_discrete':
  289. evals, emodes = calc_con_eigenmodes(con.weights, NUM_MODES, threshold=0, normed=True, binarise=BINARISE_CEM)
  290. # Now weight the emodes by the inverse of the eigenvalues
  291. weight = 1 / (0.1*np.abs(evals).mean() + np.abs(evals))
  292. emodes = emodes * weight[np.newaxis, :]
  293. # Truncate the eigenmodes to remove subcortical regions
  294. if CON == 'con1019':
  295. emodes = emodes[:-19,:]
  296. elif CON == 'con379':
  297. emodes = emodes[19:,:]
  298. # Both types of eigenmodes
  299. elif ANALYSIS_TYPE == 'SEM_discrete':
  300. mask = cortical_mask(SUBJECT, SUBJECTS_DIR, fwd_surf['src'], downsample=DOWNSAMPLE)
  301. g_evals, emodes = both_hemi_calc_eig(fwd_surf['src'], downsample=DOWNSAMPLE, mask=mask, num_modes=NUM_MODES, )
  302. g_emodes = subset_eigenmodes(emodes, fwd_surf['src'], method='average', downsample=DOWNSAMPLE, parcellation=PARCELLATION, subjects_dir=SUBJECTS_DIR, region_labels=con.region_labels, subject=SUBJECT)
  303. # Order g_emodes by eigenvalue
  304. # Create interleaved index array for ordering eigenmodes
  305. idx = np.array([[i, i+NUM_MODES//2] for i in range(1, NUM_MODES//2+1)]).flatten()
  306. idx = idx - 1 # Convert to 0-based indexing
  307. g_emodes = g_emodes[:, idx]
  308. g_evals = g_evals[idx]
  309. c_evals, c_emodes = calc_con_eigenmodes(con.weights, NUM_MODES, threshold=0, normed=True, binarise=BINARISE_CEM)
  310. c_emodes = c_emodes/ np.linalg.norm(c_emodes, axis=0)
  311. # Truncate the eigenmodes to remove subcortical regions
  312. if CON == 'con1019':
  313. c_emodes = c_emodes[:-19,:]
  314. elif CON == 'con379':
  315. c_emodes = c_emodes[19:,:]
  316. # # Normalise the evals
  317. g_evals = np.abs(g_evals)/np.abs(g_evals).mean()
  318. c_evals = np.abs(c_evals)/np.abs(c_evals).mean()
  319. g_weight = np.pi / (0.1 + np.sqrt(np.abs(g_evals)))
  320. c_weight = np.pi / (0.1 + c_evals)
  321. g_emodes = g_emodes * g_weight[np.newaxis, :]
  322. c_emodes = c_emodes * c_weight[np.newaxis, :]
  323. # Combine the emodes and evals
  324. evals = np.concatenate((g_evals, c_evals))
  325. idx = np.argsort(evals) # Get indices that would sort eigenvalues from low to high
  326. evals = evals[idx] # Sort eigenvalues
  327. emodes = np.concatenate((g_emodes, c_emodes), axis=1)[:, idx] # Combine and sort eigenmodes
  328. # %%
  329. if ANALYSIS_TYPE != 'GEM_surface':
  330. # Initialise the lists
  331. RLEs = []
  332. RLE_points = []
  333. coss = []
  334. ses = []
  335. cos_acrosstime = []
  336. expvars = []
  337. rle_acrosstime = []
  338. for num_mode in num_modes:
  339. # 1. Obtain the eigenmodes
  340. if ANALYSIS_TYPE == 'GEM_discrete':
  341. emodes_subset = np.concatenate((emodes[:, :num_mode//2], emodes[:, NUM_MODES//2:NUM_MODES//2+num_mode//2]), axis=1)
  342. evals_subset = np.concatenate((evals[:num_mode//2], evals[NUM_MODES//2:NUM_MODES//2+num_mode//2]), )
  343. # elif ANALYSIS_TYPE == 'SEM_discrete':
  344. # # This will make it so that there are an equal number of g and c modes
  345. # g_emodes_subset = g_emodes[:, :num_mode//2]
  346. # c_emodes_subset = c_emodes[:, :num_mode//2]
  347. # emodes_subset = np.zeros((g_emodes_subset.shape[0], num_mode))
  348. # emodes_subset[:, ::2] = g_emodes_subset # Even indices for g_emodes
  349. # emodes_subset[:, 1::2] = c_emodes_subset # Odd indices for c_emodes
  350. else:
  351. emodes_subset = emodes[:, :num_mode]
  352. evals_subset = evals[:num_mode]
  353. # 2. Apply the solver
  354. loose, depth = LOOSE, DEPTH
  355. solver_kwargs = dict(emodes=emodes_subset, rcond=RCOND,)
  356. stc_est_region, var_exp, w = apply_solver(gem_solver, sim, fwd, cov, loose, depth, pick_ori='normal', **solver_kwargs)
  357. # 3. Calculate threshold
  358. threshold = threshold_otsu(np.abs(stc_est_region.data,))/ np.max(np.abs(stc_est_region.data)) * 100
  359. # threshold = 40
  360. print(f"Otsu's Threshold = {threshold}")
  361. # 4. Calculate metrics
  362. RLE = mne.simulation.metrics.region_localization_error(stc, stc_est_region, fwd['src'], threshold=f'{threshold}%', per_sample=False)
  363. rle_t = mne.simulation.metrics.region_localization_error(stc, stc_est_region, fwd['src'], threshold=f'{threshold}%', per_sample=True)
  364. RLE_point = mne.simulation.metrics.region_localization_error(stc.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), stc_est_region.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), fwd['src'], threshold=f'{threshold}%', per_sample=False)
  365. cos = mne.simulation.metrics.cosine_score(stc, stc_est_region, per_sample=False)
  366. aligned_stc_est = stc_aligner(stc, stc_est_region) # Technically not needed for the discrete source case
  367. nse = (aligned_stc_est.data/np.abs(aligned_stc_est.data).max() - stc.data/np.abs(stc.data).max())**2
  368. varexp_stc = log_exp_var(stc.data/np.abs(stc.data).max(), np.sqrt(nse))
  369. se = np.mean(nse)
  370. cos_t = mne.simulation.metrics.cosine_score(stc, stc_est_region, per_sample=True)
  371. expvars.append(varexp_stc)
  372. RLEs.append(RLE)
  373. RLE_points.append(RLE_point)
  374. coss.append(cos)
  375. ses.append(se)
  376. cos_acrosstime.append(cos_t)
  377. rle_acrosstime.append(rle_t)
  378. # %% [markdown]
  379. # # Graphs
  380. # %%
  381. # Plot the results
  382. # Turn into arrays
  383. RLEs = np.array(RLEs)
  384. RLE_points = np.array(RLE_points)
  385. fig, axs = plt.subplots(3, 2, figsize=(20, 10))
  386. axs[0, 0].plot(num_modes[:len(RLEs)], RLEs*1e3, marker='o')
  387. axs[0, 0].axvline(fwd['nchan'], ymin=0, ymax=1, color='r', linestyle='--')
  388. axs[0, 0].set_title(f'RLE - Otsu\'s Threshold')
  389. axs[0, 0].set_xlabel('Number of Modes')
  390. axs[0, 0].set_ylabel(f'RLE (mm)')
  391. axs[0, 0].grid()
  392. axs[0, 1].plot(num_modes, RLE_points*1e3, marker='o')
  393. axs[0, 1].axvline(fwd['nchan'], ymin=0, ymax=1, color='r', linestyle='--')
  394. axs[0, 1].set_title(f'RLE 50% EEG at Otsu\'s Threshold - t = {raw_t[hmp_i]:.1f}s')
  395. axs[0, 1].set_xlabel('Number of Modes')
  396. axs[0, 1].set_ylabel('RLE 50% EEG (mm)')
  397. axs[0, 1].grid()
  398. # Plot the Explained Variance
  399. axs[1,0].plot(num_modes, expvars, marker='o')
  400. axs[1,0].axvline(fwd['nchan'], ymin=0, ymax=1, color='r', linestyle='--')
  401. axs[1,0].set_title('Explained Variance')
  402. axs[1,0].set_xlabel('Number of Modes')
  403. axs[1,0].set_ylabel('Explained Variance (%)')
  404. axs[1,0].grid()
  405. # Normalised Mean Squared Error
  406. axs[1, 1].plot(num_modes, ses, marker='o')
  407. axs[1, 1].axvline(fwd['nchan'], ymin=0, ymax=1, color='r', linestyle='--')
  408. # axs[1, 1].axvline(306, ymin=0, ymax=1, color='r', linestyle='--')
  409. # axs[1, 1].axvline(343, ymin=0, ymax=1, color='r', linestyle='--')
  410. axs[1, 1].set_title('Normalised Mean Squared Error')
  411. axs[1, 1].set_xlabel('Number of Modes')
  412. axs[1, 1].set_ylabel('Mean Squared Error')
  413. # axs[1, 1].set_yscale('log')
  414. axs[1, 1].grid()
  415. axs[2, 0].plot(num_modes, coss, marker='o')
  416. axs[2, 0].axvline(fwd['nchan'], ymin=0, ymax=1, color='r', linestyle='--')
  417. axs[2, 0].set_title('Cosine Score')
  418. axs[2, 0].set_xlabel('Number of Modes')
  419. axs[2, 0].set_ylabel('Cosine Score')
  420. axs[2, 0].grid()
  421. cos_acrosstime = np.array(cos_acrosstime)
  422. plot_mean_and_range(cos_acrosstime, raw_t, stat_type='max', show_minmax=True, ax=axs[2,1])
  423. axs[2,1].set_title(f'Cosine Score Across Time - {ANALYSIS_TYPE}')
  424. axs[2,1].set_xlabel('Time (s)')
  425. axs[2,1].set_ylabel('Cosine Score')
  426. plt.tight_layout()
  427. # %% [markdown]
  428. # ## MNE inverse operator for comparison
  429. # %%
  430. COMPARE_MNE = 'sLORETA'
  431. # MNE inverse operator for comparison
  432. if COMPARE_MNE:
  433. # Compute inverse operator
  434. inv = make_inverse_operator(sim.info, fwd, cov, loose=LOOSE, depth=DEPTH, )
  435. if SNR is not None:
  436. # Noting that MNE-Python takes in a linear SNR - (10**(SNR/10)) - 1 / lambda2**2
  437. stc_est_region_mne = apply_inverse(sim, inv, method=COMPARE_MNE, lambda2=1/(10**(SNR/10)), pick_ori=None)
  438. else:
  439. stc_est_region_mne = apply_inverse(sim, inv, method=COMPARE_MNE, lambda2=np.finfo(np.float64).eps, pick_ori=None)
  440. # 3. Calculate tresholds
  441. threshold = threshold_otsu(np.abs(stc_est_region_mne.data,))/ np.max(np.abs(stc_est_region_mne.data)) * 100
  442. # threshold = 40
  443. print(f"Otsu's Threshold = {threshold}")
  444. print('RLE timeseries = ', mne.simulation.metrics.region_localization_error(stc, stc_est_region_mne, fwd['src'], threshold=f'{threshold}%', per_sample=False))
  445. print('RLE 50% EEG = ', mne.simulation.metrics.region_localization_error(stc.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), stc_est_region_mne.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), fwd['src'],
  446. threshold=f'{threshold}%', per_sample=False))
  447. print('Cosine Score = ', mne.simulation.metrics.cosine_score(stc, stc_est_region_mne, per_sample=False))
  448. cos_t = mne.simulation.metrics.cosine_score(stc, stc_est_region_mne, per_sample=True)
  449. cos_t = cos_t.reshape(1,-1)
  450. aligned_stc_est = stc_aligner(stc, stc_est_region_mne)
  451. print('Squared Error = ', np.sum((aligned_stc_est.data - stc.data)**2))
  452. print('Standardised Square Error = ', np.sum((aligned_stc_est.data/np.abs(aligned_stc_est.data).max() - stc.data/np.abs(stc.data).max())**2))
  453. print('Variance Explained = ', log_exp_var(stc.data/np.abs(stc.data).max(), np.sqrt(np.sum((aligned_stc_est.data/np.abs(aligned_stc_est.data).max() - stc.data/np.abs(stc.data).max())**2))))
  454. # print('Correlation = ', np.corrcoef(aligned_stc_est.data, stc.data)[0, 1]) # Correlation takes too long to compute for ico5
  455. # %%
  456. if COMPARE_MNE:
  457. fig, axs = plt.subplots(3, 2, figsize=(20, 10))
  458. plot_mean_and_range(cos_t, raw_t, show_minmax=True, ax=axs[0,0])
  459. axs[0,0].set_title(f'Cosine Score Across Time - {COMPARE_MNE}', fontsize=12)
  460. axs[0,0].set_xlabel('Time (s)', fontsize=12)
  461. axs[0,0].set_ylabel('Cosine Score', fontsize=12)
  462. axs[0,0].set_title(f'Cosine Score Across Time - {COMPARE_MNE}', fontsize=12)
  463. axs[0,0].set_xlabel('Time (s)', fontsize=12)
  464. axs[0,0].set_ylabel('Cosine Score', fontsize=12)
  465. axs[0,0].get_legend().remove()
  466. plt.tight_layout()
  467. # %% [markdown]
  468. # ## Surrogate Test
  469. # %%
  470. if 'SHUFFLE_ARRAY' not in locals() and SURROGATE_TEST:
  471. # Create a shuffle array - Increments of 7 such that it's not a divisor of the number of sources in each hemisphere
  472. print('Shuffle Array not defined, using default with 99 surrogates')
  473. SHUFFLE_ARRAY = np.arange(7, 700, 7)
  474. # Perform the surrogate test for N interations
  475. if SURROGATE_TEST:
  476. RLEs = RLEs.tolist()
  477. RLE_points = RLE_points.tolist()
  478. for shuffle in SHUFFLE_ARRAY:
  479. # Generate Surrogate Modes using the Roll Method
  480. if SURROGATE_TEST == 'roll':
  481. if ANALYSIS_TYPE == 'GEM_discrete':
  482. emodes_subset = np.concatenate((emodes[:, :num_mode//2], emodes[:, NUM_MODES//2:NUM_MODES//2+num_mode//2]), axis=1)
  483. elif ANALYSIS_TYPE == 'CEM_discrete':
  484. emodes_subset = emodes[:, :num_mode]
  485. # Roll the eigenmodes
  486. emodes_subset[:emodes_subset.shape[0]//2,:emodes_subset.shape[1]//2] = np.roll(emodes_subset[:emodes_subset.shape[0]//2,:emodes_subset.shape[1]//2], shift=shuffle, axis=0)
  487. emodes_subset[emodes_subset.shape[0]//2:,emodes_subset.shape[1]//2:] = np.roll(emodes_subset[emodes_subset.shape[0]//2:,emodes_subset.shape[1]//2:], shift=shuffle, axis=0)
  488. # Generate Surrogate Modes using the Rotational Eigenstrapping Method
  489. if SURROGATE_TEST == 'rotate':
  490. # Normalise to be safe
  491. emodes = emodes / np.linalg.norm(emodes, axis=0)[np.newaxis, :]
  492. surrogate_emodes = both_hemi_surrogate_eig(emodes, evals, normalize=True, thresh=0, )
  493. surrogate_emodes = surrogate_emodes*weight[np.newaxis, :]
  494. emodes_subset = np.concatenate((surrogate_emodes[:, :num_mode//2], surrogate_emodes[:, NUM_MODES//2:NUM_MODES//2+num_mode//2]), axis=1)
  495. # 2. Apply the solver
  496. loose, depth = LOOSE, DEPTH
  497. solver_kwargs = dict(emodes=emodes_subset, rcond=RCOND)
  498. stc_est_region, var_exp, w = apply_solver(gem_solver, sim, fwd, cov, loose, depth, **solver_kwargs)
  499. # 3. Calculate threshold
  500. threshold = threshold_otsu(np.abs(stc_est_region.data), )/ np.max(stc_est_region.data) * 100
  501. # 4. Calculate metrics
  502. RLE = mne.simulation.metrics.region_localization_error(stc, stc_est_region, fwd['src'], threshold=f'{threshold}%', per_sample=False)
  503. RLE_point = mne.simulation.metrics.region_localization_error(stc.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), stc_est_region.copy().crop(tmin=raw_t[hmp_i], tmax=raw_t[hmp_i]), fwd['src'], threshold=f'{threshold}%', per_sample=False)
  504. cos = mne.simulation.metrics.cosine_score(stc, stc_est_region, per_sample=False)
  505. aligned_stc_est = stc_aligner(stc, stc_est_region) # Technically not needed for the discrete source case
  506. nse = (aligned_stc_est.data/np.abs(aligned_stc_est.data).max() - stc.data/np.abs(stc.data).max())**2
  507. varexp_stc = log_exp_var(stc.data/np.abs(stc.data).max(), np.sqrt(nse))
  508. se = np.mean(nse)
  509. expvars.append(varexp_stc)
  510. RLEs.append(RLE)
  511. RLE_points.append(RLE_point)
  512. coss.append(cos)
  513. ses.append(se)
  514. # Clear Cell Output
  515. clear_output(wait=True)
  516. RLEs = np.array(RLEs)
  517. RLE_points = np.array(RLE_points)
  518. # %%
  519. # Stop it here for now if run all
  520. 1/0
  521. # %% [markdown]
  522. # ## Videos of Sources
  523. #
  524. # ### Source Estimate
  525. # %%
  526. if ANALYSIS_TYPE != 'GEM_surface':
  527. # To convert the discrete source estimate to a surface estimate just run these two functions - then allows us to use MNE's plotting functions
  528. fwd_surface = mne.read_forward_solution(f'Ignore/{SUBJECT}_ico3-fwd.fif')
  529. fwd_surface = mne.pick_channels_forward(fwd_surface, include=info['ch_names'], )
  530. fwd_surface = mne.pick_types_forward(fwd_surface, meg=PICK_MEG, eeg=PICK_EEG, exclude=info['bads'], )
  531. stc_surface, _ = tvb_loadtomne(stc_est_region.data.T, SUBJECT, fwd_surface, info, PARCELLATION, fs_path= FS_PATH, )
  532. # time_max here is the frame shown in the video. Which can be interpretted as a picture.
  533. surfer_kwargs = dict(
  534. hemi='both', subjects_dir=SUBJECTS_DIR,
  535. # colormap='mne',
  536. # clim=dict(kind='value', lims=[stc_est_region.data.min(), (stc_est_region.data.max()+stc_est_region.data.min())/2, stc_est_region.data.max()]),
  537. clim = dict(kind='value', lims=[0, stc_est_region.data.max()/2, stc_est_region.data.max()]),
  538. # clim=dict(kind='value', lims=[0, stc.data.max()/2, stc.data.max()]),
  539. views='rostral', initial_time=raw_t[hmp_i],
  540. time_unit='s', size=(800, 800), smoothing_steps=10,
  541. backend='pyvistaqt',
  542. )
  543. if ANALYSIS_TYPE == 'GEM_surface':
  544. brain = stc_est_region.plot(**surfer_kwargs)
  545. else:
  546. brain = stc_surface.plot(**surfer_kwargs)
  547. brain.set_playback_speed(speed=1)
  548. # %% [markdown]
  549. # ### True Sources
  550. # %%
  551. if ANALYSIS_TYPE != 'GEM_surface':
  552. # Looking at true stc
  553. stc_surface, _ = tvb_loadtomne(stc.data.T, SUBJECT, fwd_surface, info, PARCELLATION, fs_path= FS_PATH, )
  554. # time_max here is the frame shown in the video. Which can be interpretted as a picture.
  555. surfer_kwargs = dict(
  556. hemi='both', subjects_dir=SUBJECTS_DIR,
  557. # colormap='mne',
  558. # clim=dict(kind='value', lims=[stc.data.min(), (stc.data.max()+stc.data.min())/2, stc.data.max()]),
  559. clim = dict(kind='value', lims=[0, stc.data.max()/2, stc.data.max()]),
  560. # clim=dict(kind='value', lims=[0, stc.data[:,hmp_i].max()/2, stc.data[:,hmp_i].max()]),
  561. views='rostral',
  562. initial_time=raw_t[hmp_i], #
  563. # background='white',
  564. time_unit='s', size=(800, 800), smoothing_steps=10)
  565. if ANALYSIS_TYPE == 'GEM_surface':
  566. brain = stc.plot(**surfer_kwargs)
  567. else:
  568. brain = stc_surface.plot(**surfer_kwargs)
  569. brain.set_playback_speed(speed=1)
  570. # %% [markdown]
  571. # ## Visualising the Eigenmodes
  572. # %%
  573. # Plot the eigenmodes
  574. l_points, l_trias = get_tria_from_src(fwd_surf['src'], hemi=0, downsample=DOWNSAMPLE)
  575. l_tria = lapy.TriaMesh(l_points, l_trias)
  576. mask = cortical_mask(SUBJECT, SUBJECTS_DIR, fwd_surf['src'], downsample=DOWNSAMPLE)
  577. evals, s_emodes = both_hemi_calc_eig(fwd_surf['src'], downsample=DOWNSAMPLE, mask=mask, num_modes=NUM_MODES, normalise=False )
  578. mode_number = 20
  579. plot_tria_mesh(l_tria, vfunc=s_emodes[:s_emodes.shape[0]//2, mode_number],showcaxis=True)
  580. # %%
  581. from mpl_toolkits.mplot3d import Axes3D
  582. %matplotlib widget
  583. # Check discrete source space - for the eigenmodes
  584. # 3D plot of Discrete Source space where colour is dependent on subset_emodes
  585. mode_number = 20
  586. # Extract positions and colors
  587. positions = np.concatenate((fwd['src'][0]['rr'], fwd['src'][1]['rr']), axis=0)
  588. # colors = disc_emodes[:, mode_number]
  589. colors = emodes[:, mode_number]
  590. # Create a 3D scatter plot
  591. fig = plt.figure(figsize=(10, 10))
  592. ax = fig.add_subplot(111, projection='3d')
  593. sc = ax.scatter(positions[:, 0], positions[:, 1], positions[:, 2], c=colors, cmap='coolwarm', s=50)
  594. # Ensure axes follow the same scale
  595. ax.set_box_aspect([np.ptp(positions[:, 0]), np.ptp(positions[:, 1]), np.ptp(positions[:, 2])])
  596. # Add color bar
  597. cb = plt.colorbar(sc, ax=ax, shrink=0.5)
  598. cb.set_label(f'Subset Eigenmodes (Mode {mode_number})', fontsize=12)
  599. # Set labels
  600. ax.set_xlabel('X', fontsize=12)
  601. ax.set_ylabel('Y', fontsize=12)
  602. ax.set_zlabel('Z', fontsize=12)
  603. ax.set_title('3D Plot of Discrete Source Space', fontsize=14)
  604. plt.show()
  605. # %%

STC_Analysis.ipynb at commit 81268ed, under BSD-3-Clause · at the source

Overview

  1. Department of Biomedical Engineering The University of Melbourne Melbourne Australia
  2. Graeme Clark Institute The University of Melbourne Melbourne Australia
  3. National University of Singapore Singapore Singapore
  4. Grenoble Institut des Neurosciences INSERM Grenoble (La Tronche) France
  5. Department of Data Science & AI Monash University Melbourne Australia
  6. Department of Medicine, St Vincent's Hospital, Melbourne The University of Melbourne Melbourne Australia
Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany), volume 13, issue 31, article e16802
Dates: received 1 September 2025; accepted 12 March 2026; published online 23 March 2026; in print June 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1002/advs.202516802 · PMID 41869755 · PMCID PMC13588046 · OpenAlex W7140078093
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: EEG (modality), human (organism), epilepsy (population)
Methods: Connectivity, Statistics, Physiology & signal measures, Machine learning, fMRI & imaging
Keywords: connectome, EEG, epilepsy, geometric eigenmodes, source localization
MeSH: Brain*, Brain Mapping*, Connectome*, Electroencephalography*, Epilepsy*, Humans, Magnetic Resonance Imaging (* major topic)
Topic: Functional Brain Connectivity Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: cited by 1 paper (Europe PMC); 82 references in the paper

Abstract

A fundamental view of neuroscience is that, in addition to neuronal activity, the structure of the brain constrains and explains brain function. An alluring formalism in computational neuroscience has been the generation of structural eigenmodes of neural activity from a matrix representing the anatomy of the brain. Traditionally, brain connectomics has been the gold standard for the coupling between structure and function. However, it has recently been suggested that simpler brain geometry can provide more explanatory power in fMRI. An adjacent modality is the source localization problem of EEG, which aims to identify the underlying generators of EEG recordings. The underdetermined nature of the problem requires sufficient constraints to produce realistic and unique solutions of source activity. In this work, a simple framework for incorporating different forms of structural brain eigenmodes to constrain the source localization problem in epilepsy is presented. Geometric eigenmodes were found to be able to reconstruct the spread of a seizure through the brain slightly better than connectome eigenmodes, and both types of structural modes significantly outperformed commonly used approaches.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 14 matches between paragraphs and lines of code.

Spokhim/sesl

License: BSD-3-Clause
State: the link answers, verified on 31 October 2026
Evidence: files inventoried
Commit: 81268edac5a70ea091d06cdce6ec2539075fdec0, 23 March 2026
Languages: Python (4), Jupyter (2)
Size: 11 files, 6 scripts
Software Heritage: not archived
Found in: “Data Availability Statement”
Holds: README, license file, environment (requirements.txt, requirements_sesl.txt), 2 notebooks
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (6 files), MNE-Python (5 files), Matplotlib (3 files), SciPy (3 files), BrainSpace (1 file), Plotly (1 file), scikit-image (1 file), scikit-learn (1 file), The Virtual Brain (1 file)
Availability: 2 checks, the latest on 31 October 2026: the link answers
  • 31 October 2026: the link answers
  • 30 September 2026: the link answers
8 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 6 scripts, each with its path and the digest of its content;
  • 14 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability Statement

All code for the source localization pipeline can be found at: https://github.com/Spokhim/sesl. All code should be easily compatible with current MNE‐Python pipelines whether it is EEG or MEG. If there is enough interest, the author may look into a proper implementation into MNE‐Python.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 7 authors, 5 keywords, 7 MeSH terms, 1 funder, 73 references.

Cite

This paper

Siu, P. H., Karoly, P. J., Mansour L., S., Soto‐Breceda, A., Kuhlmann, L., Cook, M. J., & Grayden, D. B. (2026). Structural Eigenmodes of the Brain to Improve the Source Localization of EEG: Application to Epileptiform Activity. Advanced science (Weinheim, Baden-Wurttemberg, Germany), 13(31), e16802. https://doi.org/10.1002/advs.202516802

BibTeX

@article{siu2026structural,
author = {Siu, Pok Him and Karoly, Philippa J. and Mansour L., Sina and Soto‐Breceda, Artemio and Kuhlmann, Levin and Cook, Mark J. and Grayden, David B.},
title = {{Structural Eigenmodes of the Brain to Improve the Source Localization of EEG: Application to Epileptiform Activity}},
journal = {Advanced science (Weinheim, Baden-Wurttemberg, Germany)},
year = {2026},
month = mar,
volume = {13},
number = {31},
pages = {e16802},
publisher = {Wiley},
issn = {2198-3844},
doi = {10.1002/advs.202516802},
url = {https://doi.org/10.1002/advs.202516802},
pmid = {41869755},
pmcid = {PMC13588046}
}

RIS

TY - JOUR
AU - Siu, Pok Him
AU - Karoly, Philippa J.
AU - Mansour L., Sina
AU - Soto‐Breceda, Artemio
AU - Kuhlmann, Levin
AU - Cook, Mark J.
AU - Grayden, David B.
TI - Structural Eigenmodes of the Brain to Improve the Source Localization of EEG: Application to Epileptiform Activity
T2 - Advanced science (Weinheim, Baden-Wurttemberg, Germany)
J2 - Adv Sci (Weinh)
PY - 2026
DA - 2026/03/23
VL - 13
IS - 31
SP - e16802
SN - 2198-3844
PB - Wiley
DO - 10.1002/advs.202516802
UR - https://doi.org/10.1002/advs.202516802
LA - en
ER -

CSL-JSON

{
"id": "10.1002/advs.202516802",
"type": "article-journal",
"title": "Structural Eigenmodes of the Brain to Improve the Source Localization of EEG: Application to Epileptiform Activity",
"container-title": "Advanced science (Weinheim, Baden-Wurttemberg, Germany)",
"author": [
{
"family": "Siu",
"given": "Pok Him"
},
{
"family": "Karoly",
"given": "Philippa J."
},
{
"family": "Mansour L.",
"given": "Sina"
},
{
"family": "Soto‐Breceda",
"given": "Artemio"
},
{
"family": "Kuhlmann",
"given": "Levin"
},
{
"family": "Cook",
"given": "Mark J."
},
{
"family": "Grayden",
"given": "David B."
}
],
"container-title-short": "Adv Sci (Weinh)",
"volume": "13",
"issue": "31",
"page": "e16802",
"DOI": "10.1002/advs.202516802",
"PMID": "41869755",
"PMCID": "PMC13588046",
"ISSN": "2198-3844",
"publisher": "Wiley",
"URL": "https://doi.org/10.1002/advs.202516802",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
23
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1162/netn.a.543 [code]
High-resolution Bayesian Virtual Epileptic Patient using neural field models.
Journal: Network neuroscience (Cambridge, Mass.)
In common: The Virtual Brain, MNE-Python, SciPy, 2 other tools, epilepsy, 10 references
[2] doi:10.1002/advs.202405246 [code]
Seizure Sources Can Be Imaged from Scalp EEG by Means of Biophysically Constrained Deep Neural Networks.
Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany)
In common: The Virtual Brain, MNE-Python, scikit-image, 3 other tools, epilepsy, EEG, 9 references
[3] doi:10.1073/pnas.2201128119 [code]
Deep neural networks constrained by neural mass models improve electrophysiological source imaging of spatiotemporal brain dynamics.
Journal: Proceedings of the National Academy of Sciences of the United States of America
In common: The Virtual Brain, MNE-Python, scikit-image, 3 other tools, epilepsy, EEG, 8 references
[4] doi:10.1371/journal.pcbi.1011642 [code]
Parameter estimation in a whole-brain network model of epilepsy: Comparison of parallel global optimization solvers.
Journal: PLoS computational biology
In common: scikit-learn, SciPy, Matplotlib, 1 other tool, epilepsy, EEG, 10 references
[5] doi:10.1038/s43588-025-00841-6 [code]
Virtual brain twins for stimulation in epilepsy.
Journal: Nature computational science
In common: The Virtual Brain, MNE-Python, scikit-learn, 3 other tools, epilepsy, EEG, 7 references
[6] doi:10.1371/journal.pcbi.1012911 [code]
Virtual epilepsy patient cohort: Generation and evaluation.
Journal: PLoS computational biology
In common: The Virtual Brain, MNE-Python, scikit-learn, 3 other tools, epilepsy, EEG, 6 references
[7] doi:10.1093/braincomms/fcag217 [code]
Investigation of stress hormones across multiday seizure cycles.
Journal: Brain communications
In common: epilepsy, 3 authors
[8] doi:10.7554/elife.106194 [code]
Virtual Brain Inference (VBI), a flexible and integrative toolkit for efficient probabilistic inference on whole-brain models.
Journal: eLife
In common: MNE-Python, scikit-learn, SciPy, 2 other tools, 8 references
[9] doi:10.1038/s41586-023-06098-1 [code]
Geometric constraints on human brain function.
Journal: Nature
In common: BrainSpace, SciPy, NumPy, 10 references
[10] doi:10.1093/braincomms/fcac173 [code]
Multiple mechanisms shape the relationship between pathway and duration of focal seizures.
Journal: Brain communications
In common: epilepsy, 3 references, 2 authors

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1002/advs.202516802.svg)](https://openscicode.org/badge/doi/10.1002/advs.202516802)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1002/advs.202516802.svg
   :target: https://openscicode.org/badge/doi/10.1002/advs.202516802
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1002/advs.202516802"><img src="https://openscicode.org/badge/doi/10.1002/advs.202516802.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.