OSCR

Subthalamic stimulation modulates working memory-related cortical dynamics in Parkinson's disease.

Code ↔ Paper

7 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 7 matches
  1. [1] § Materials and methods › EEG data analysis ↔ main.py, lines 217–260 · score 0.71 · log transformed, 1–4 Hz, 4–8 Hz, delta, windows, theta
  2. [2] § Materials and methods › EEG data analysis ↔ project_package/project_functions/physio_features.py, lines 122–183 · score 0.61 · log transformed, spectrogram, signal, Median, windows, channels
  3. [3] § Materials and methods › Statistical analysis ↔ main.py, lines 527–553 · score 0.60 · task accuracy, task RT, frequency band, power, behavioural, EEG
  4. [4] § Materials and methods › Behavioural data analysis ↔ project_package/project_functions/behavioral_features.py, lines 266–368 · score 0.59 · positions correct, button presses, SDR task, Behavioural
  5. [5] § Materials and methods › Statistical analysis ↔ statistics.R, lines 121–171 · score 0.58 · dDBS, oDBS, spectral responses, models, stimulation
  6. [6] § Materials and methods › Patients ↔ project_package/project_functions/behavioral_features.py, lines 372–433 · score 0.51 · button press, oddball tasks, SDR tasks, scores, stimuli, patients
  7. [7] § Materials and methods › EEG data analysis ↔ project_package/project_functions/preprocessing.py, lines 551–698 · score 0.50 · notch filter, noise, preprocessing, EEG, stimulation

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 704 lines · 27 KB · MIT · 2 matches

  1. # -*- coding: utf-8 -*-
  2. """End-to-end workflow for the working-memory EEG analysis."""
  3. #%%
  4. import ast
  5. import seaborn as sns
  6. from pathlib import Path
  7. import pickle as pkl
  8. import pandas as pd
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. import mne
  12. from scipy import stats
  13. from project_package.project_functions.preprocessing import (preprocess,
  14. get_stim_info)
  15. from project_package.project_functions.behavioral_features import (evaluate_beh_patients,
  16. summarize_all_results)
  17. from project_package.project_functions.files_management import (get_available_measurements,
  18. divide_by_measurement_type)
  19. from project_package.project_functions.physio_features import (get_P300, clustInfo,
  20. epochs_permutation_test,
  21. tfa_epocher, meanpower,
  22. tf_data)
  23. from project_package.project_functions.statistics import (add_norm_values,
  24. add_baseline_values,
  25. corr_df, subsetter,
  26. significance_df, renamer,
  27. plot_for_stats)
  28. plt.rcParams["font.family"] = "Arial"
  29. #%% Define steps to be ran
  30. redo_preprocessing = False
  31. redo_timefrequency = False
  32. redo_permutation_test = False
  33. redo_P300 = False
  34. redo_behavioral = False
  35. plots_report = False
  36. plotP3waves = False
  37. #%% PATHS
  38. PROJECT_ROOT = Path(__file__).resolve().parent
  39. DATA_DIR = PROJECT_ROOT / 'data'
  40. METADATA_DIR = DATA_DIR / 'metadata'
  41. RAW_DATA_DIR = DATA_DIR / 'raw'
  42. PREPROCESSED_DATA_DIR = DATA_DIR / 'preprocessed'
  43. PROCESSED_DATA_DIR = DATA_DIR / 'processed'
  44. R_INPUT_DIR = DATA_DIR / 'r_inputs'
  45. RESULTS_DIR = PROJECT_ROOT / 'results'
  46. STATISTICS_RESULTS_DIR = RESULTS_DIR / 'statistics'
  47. FIGURES_DIR = RESULTS_DIR / 'figures'
  48. for folder in (PREPROCESSED_DATA_DIR, PROCESSED_DATA_DIR, R_INPUT_DIR,
  49. STATISTICS_RESULTS_DIR, FIGURES_DIR):
  50. folder.mkdir(parents=True, exist_ok=True)
  51. # Measurement and task metadata.
  52. subsetInfoPath = METADATA_DIR / 'Analizable_info.csv'
  53. stimInfoPath = METADATA_DIR / 'Stimulation_Info.csv'
  54. filenamesPath = METADATA_DIR / 'Data_file_names.csv'
  55. rightAnswersPath = METADATA_DIR / 'rightAnswers.txt'
  56. if not rightAnswersPath.exists():
  57. rightAnswersPath = None
  58. # Cached outputs used when the corresponding redo_* flag is False.
  59. P3infoPath = PROCESSED_DATA_DIR / 'p300potentialsinfo.pkl'
  60. behScoresPath = PROCESSED_DATA_DIR / 'behScores.pkl'
  61. prepInfoPath = PROCESSED_DATA_DIR / 'preprocessed_files_info_1.csv'
  62. # Data locations. Place private EEG files under these folders before running.
  63. rawDataPath = RAW_DATA_DIR
  64. prepPath = PREPROCESSED_DATA_DIR
  65. dataPath = prepPath
  66. # Available preprocessed files
  67. files = {}
  68. fileList, measStatus = get_available_measurements(filenamesPath, dataPath)
  69. files['SDR'], files['VDR'] = divide_by_measurement_type(fileList)
  70. # Oddball correspondences
  71. oddDict = {'VDR': 'acoustic',
  72. 'SDR': 'visual'}
  73. #%% PREPROCESS
  74. # ! This sections runs for a several hours if True
  75. manual_rejection = False
  76. preselected_bad_ch = True #To use bad channels selected before by hand as bad
  77. #Using it ensures the reproducibility of the results
  78. if redo_preprocessing:
  79. # Initiliaze preprocess info storage
  80. preprocess_info = pd.DataFrame(columns=['measurement', 'task', 'n_bad_ch', 'bad_ch',
  81. 'n_task_epochs', 'n_bad_task_epochs',
  82. 'n_oddball_epochs', 'n_bad_oddball_epochs',
  83. 'path'])
  84. filenames = [file.name for file in rawDataPath.glob('*raw.fif')]
  85. for file in filenames:
  86. if preselected_bad_ch:
  87. info = pd.read_csv(prepInfoPath)
  88. idx = info.loc[info['measurement'] == file.replace('raw.fif', '')].index[0]
  89. bad_ch = ast.literal_eval(info.at[idx, 'bad_ch'])
  90. else:
  91. bad_ch = None
  92. prep_info = preprocess(rawDataPath, file, prepPath, stimInfoPath,
  93. bad_ch = bad_ch, manual = manual_rejection)
  94. preprocess_info = pd.concat(
  95. [preprocess_info, pd.DataFrame([prep_info])],
  96. ignore_index=True
  97. )
  98. preprocess_info.to_csv(PROCESSED_DATA_DIR / 'preprocessingInfo.csv', index=False)
  99. dataPath = prepPath
  100. #%% BEHAVIORAL ANALYSIS
  101. # Raw evaluation
  102. # ! This sections runs for a couple of minutes if True
  103. #Results stored for each trial (not measurement!)
  104. if redo_behavioral:
  105. swapper = np.array([2, 3, 4, 5, 6, 7, 8, 1]) # For button label correction
  106. sdrScoreAll = evaluate_beh_patients(files['SDR'], 'SDR', rightAnswersPath, swapper)
  107. #outcome dictionaries contain dictionaries for each patient with the time points and trial-wise accuracy and RT
  108. vdrScoreAll = evaluate_beh_patients(files['VDR'], 'VDR', rightAnswersPath)
  109. vobScoreAll = evaluate_beh_patients(files['SDR'], 'oddball')
  110. aobScoreAll = evaluate_beh_patients(files['VDR'], 'oddball')
  111. #These results are already saved for whole measurement
  112. sensitivityVobAll = evaluate_beh_patients(files['SDR'], 'sensitivity')
  113. sensitivityAobAll = evaluate_beh_patients(files['VDR'], 'sensitivity')
  114. # Compute measurement total results
  115. sumResultsVdr = summarize_all_results(vdrScoreAll)
  116. sumResultsSdr = summarize_all_results(sdrScoreAll, sdr=True)
  117. sumResultsVob = summarize_all_results(vobScoreAll)
  118. sumResultsAob = summarize_all_results(aobScoreAll)
  119. behScores = {'VDR': sumResultsVdr,
  120. 'SDR': sumResultsSdr,
  121. 'vob': sumResultsVob,
  122. 'aob': sumResultsAob,
  123. 'vob_s': sensitivityVobAll,
  124. 'aob_s': sensitivityAobAll}
  125. #Save data
  126. behPath = PROCESSED_DATA_DIR / 'behScores.pkl'
  127. with behPath.open('wb') as file:
  128. pkl.dump(behScores, file)
  129. else:
  130. behPath = behScoresPath
  131. with behPath.open("rb") as file:
  132. behScores = pkl.load(file)
  133. sumResultsVdr, sumResultsSdr, sumResultsVob, sumResultsAob,\
  134. sensitivityVobAll, sensitivityAobAll = behScores.values()
  135. #%% EXTRACTION P300 FEATURES
  136. # ! This sections runs for a couple of minutes if True
  137. # to run the test and visualize channels chosen
  138. # It takes time because all V0 epochs are read and concatenated
  139. if redo_permutation_test:
  140. #Here only for visualization purposes, not to actually change cluster chosen
  141. #TODO: Does not work yet
  142. for task in ['VDR', 'SDR']:
  143. obs, clust, cluster_pv, H0 = epochs_permutation_test(files[task], oddDict[task], clustInfo=clustInfo)
  144. ##note that adj matrix has not been specified for the cluster perm, so interpretation is difficult
  145. clustInfo = {'acoustic': {'cluster': 46, 'chans': ['Cz','CPz','Pz','POz']},
  146. 'visual': {'cluster': 69, 'chans': ['Cz','CPz','Pz','POz']}}
  147. # dictionary clustInfo (imported from physio_features) has channels of the clusters
  148. # previously selected
  149. if redo_P300:
  150. P3info = {}
  151. features = ['peak', 'latency', 'amplitude']
  152. for file in fileList:
  153. eFile = file.replace('_p_raw', '_oe_epo')
  154. task = 'VDR' if 'VDR' in eFile else 'SDR'
  155. epochs = mne.read_epochs(eFile, preload=True).apply_baseline()
  156. epochs.pick_channels(clustInfo[oddDict[task]]['chans'])
  157. #TODO: this picks channels that belong to any cluster, maybe make it a bit more specific?
  158. P3info[eFile] = {}
  159. for k in epochs.event_id.keys():
  160. #print(k)
  161. if len(epochs[k])>0:
  162. P3info[eFile][k] = {f:v for f,v in zip(features, get_P300(epochs[k]))}
  163. P3Path = PROCESSED_DATA_DIR / 'p300potentialsinfo.pkl'
  164. with P3Path.open('wb') as file:
  165. pkl.dump(P3info, file)
  166. else:
  167. P3Path = P3infoPath
  168. with P3infoPath.open("rb") as file:
  169. P3info = pkl.load(file)
  170. #%% EXTRACTION TIME-FREQUENCY FEATURES
  171. t_window = 4 #seconds before and after cue for the epochs
  172. freqBands = {'delta (1-3)': (1, 4),
  173. 'theta (4-8)': (4, 9),
  174. 'alpha (9-14)': (9, 15),
  175. 'beta (15-30)': (15, 31),
  176. 'total (1-30)': (1,31)}
  177. baseline = {'VDR': (1.5, 3.5),
  178. 'SDR': (1.5,3.5)}
  179. TFPath = PROCESSED_DATA_DIR / 'timefrequencydata.pkl'
  180. tfaInfo = {}
  181. if redo_timefrequency:
  182. for file in fileList:
  183. filename = Path(file).name
  184. print(f'running TFA for {filename}')
  185. task = 'VDR' if 'VDR' in file else 'SDR'
  186. data = mne.io.read_raw_fif(file, preload=True)
  187. epochs = tfa_epocher(data, t_window=t_window)
  188. f, t, Sxx, BL, tfband = tf_data(epochs, freqBands=freqBands, log_transform=True,
  189. baseline=baseline[task])
  190. tfaInfo[filename] = tfband
  191. print(f'current keys in tfaInfo: {tfaInfo.keys()}')
  192. tfaData = {'Sxx':{}, 'BL': {}}
  193. tfaData['Sxx'][filename] = Sxx
  194. tfaData['BL'][filename] = BL
  195. # sxxpath = f'{file}_spectrum.pkl' #tfaspectra will contain the raw spectra for all channels
  196. # file = open(sxxpath, 'wb')
  197. # pkl.dump(Sxx, file)
  198. # file.close()
  199. TFpath = PROCESSED_DATA_DIR / f'{filename}_timefrequencydata_raw.pkl'
  200. with TFpath.open('wb') as file:
  201. pkl.dump(tfaData, file)
  202. with TFPath.open('wb') as file:
  203. pkl.dump(tfaInfo, file)
  204. print(f'dumped tfaInfo with keys: {tfaInfo.keys()}')
  205. else:
  206. with TFPath.open('rb') as file:
  207. tfaInfo=pkl.load(file)
  208. # else:
  209. # with open(TFPath, "rb") as pf:
  210. # tfaInfo = pkl.load(pf)
  211. ##read in one file to get time and frequency indices
  212. ##to save memory, they can also be generated as simple arrays
  213. epochs = tfa_epocher(mne.io.read_raw_fif(fileList[0], preload=True), t_window=t_window)
  214. f, t, _, _, _ = tf_data(epochs, freqBands=freqBands, log_transform=True,
  215. baseline=(0,0) )
  216. f = np.arange(1,31)
  217. t = np.linspace(-3.5,3.5,num=141)
  218. #extract raw spectra and relative spectra, plot along with topos
  219. over_time_abs = np.nan*np.zeros((len(fileList),len(f),len(t)))
  220. over_time_rel = over_time_abs.copy()
  221. over_chans_abs = np.nan*np.zeros((len(fileList),len(f), 64))
  222. over_chans_rel = over_chans_abs.copy()
  223. taskvec = np.nan*np.zeros(len(fileList))
  224. #read in single-subject spectra from pickle files
  225. for i,file in enumerate(fileList):
  226. print(i)
  227. filename = Path(file).name
  228. if 'VDR' in filename:
  229. taskvec[i] = 1
  230. elif 'SDR' in filename:
  231. taskvec[i] = 2
  232. TFpath = PROCESSED_DATA_DIR / f'{filename}_timefrequencydata_raw.pkl'
  233. with TFpath.open("rb") as pf:
  234. tfaData = pkl.load(pf)
  235. Sxx = np.array(list(tfaData['Sxx'].values()))
  236. rel = Sxx - np.array(list(tfaData['BL'].values()))
  237. Sxx = np.squeeze(Sxx)
  238. rel = np.squeeze(rel)
  239. if len(Sxx.shape) != 4:
  240. continue
  241. over_time_abs[i,:,:] = np.median(Sxx, (0,1))
  242. over_time_rel[i,:,:] = np.median(rel, (0,1))
  243. over_chans_abs[i,:,:] = np.median(Sxx, (0,3)).T
  244. over_chans_rel[i,:,:] = np.median(rel, (0,3)).T
  245. # tfaInfo[filename] = {band: np.nanmedian(rel[:,:,lo:hi,:]) for band, (lo,hi) in freqBands.items()}
  246. #TODO: include correlation topos!
  247. #%% relative spectra in both tasks
  248. fig,ax = plt.subplots(2,2) #for relative spectra in both tasks
  249. im2=ax[0,0].pcolor(np.nanmedian(over_time_rel[taskvec==2],0))
  250. ax[0,0].set_title('Spectral response (SDR)')
  251. cbar=plt.colorbar(im2, ax=ax[1,0])
  252. cbar.set_label('dB', rotation=270)
  253. im=ax[1,0].pcolor(np.nanmedian(over_time_rel[taskvec==1],0))
  254. ax[1,0].set_title('Spectral response (VDR)')
  255. cbar=plt.colorbar(im, ax=ax[0,0])
  256. cbar.set_label('dB', rotation=270)
  257. i=.1
  258. for band, (lo,hi) in freqBands.items():
  259. ax[1,1].plot(np.nanmedian(over_time_rel[taskvec==1,lo:hi,:],(1,0)),label=band, color=(i,i,.6))
  260. ax[1,1].legend()
  261. ax[0,1].plot(np.nanmedian(over_time_rel[taskvec==2,lo:hi,:],(1,0)),label=band, color=(i,i,.6))
  262. ax[0,1].legend()
  263. i+=.2
  264. ax[0,1].set_title('Frequency bands (SDR)')
  265. ax[1,1].set_title('Frequency bands (VDR)')
  266. lab='frequency [Hz]'
  267. ax[0,0].set_ylabel(lab)
  268. ax[1,0].set_ylabel(lab)
  269. lab='power [dB]'
  270. ax[0,1].set_ylabel(lab)
  271. ax[1,1].set_ylabel(lab)
  272. lab='time [s]'
  273. for i in range(2):
  274. for k in range(2):
  275. ax[i,k].set_xticks(range(len(t))[::10])
  276. ax[i,k].set_xticklabels(t[::10])
  277. ax[i,k].set_xlabel(lab)
  278. fig.set_size_inches(12,6)
  279. plt.tight_layout()
  280. plt.savefig(FIGURES_DIR / 'spectral_response.svg')
  281. #%% absolute spectrum
  282. plt.figure()
  283. plt.plot(np.nanmedian(over_time_abs, (0,2)))
  284. #%% relative spectrum topo
  285. from multichannel_tools.viz import my_topomap
  286. fig=plt.figure()
  287. i=0
  288. clim = {
  289. 'delta (1-3)':[0,1.5],
  290. 'theta (4-8)':[-.5,.5],
  291. 'alpha (9-14)':[-.4,.4],
  292. 'beta (15-30)':[-.3,.3]}
  293. for task,taski in {'SDR':2, 'VDR':1}.items():
  294. for band, (lo,hi) in freqBands.items():
  295. if band == 'total (1-30)':
  296. continue
  297. i+=1
  298. clo,chi = clim[band]
  299. plt.subplot(2,4,i)
  300. plt.title(f'{task}, {band}')
  301. my_topomap(np.nanmedian(over_chans_rel[taskvec==taski,lo:hi,:], (0,1) ), chans = epochs.info.ch_names, clim=(clo,chi))
  302. plt.gcf().set_size_inches(14,5)
  303. plt.savefig(FIGURES_DIR / 'spectral_response_topos.svg')
  304. #%% ALL FEATURES TOGETHER FOR STATISTICS
  305. # Build-up the master DataFrame with all variables by measurement
  306. #Grouping by stimulus type
  307. oddCategory = {'circle':'nontarget',
  308. 'lowPitch': 'nontarget',
  309. 'large': 'target',
  310. 'largeCircle': 'target',
  311. 'highPitch': 'target',
  312. 'distractor': 'distractor'}
  313. varsDict = {'info': ['ID', 'stimulation', 'task', 'time'],
  314. 'physio': ['P3distractoramplitude', 'P3distractorlatency',
  315. 'P3nontargetamplitude', 'P3nontargetlatency', 'P3targetamplitude',
  316. 'P3targetlatency'],#, 'TFalpha', 'TFbeta', 'TFdelta', 'TFtheta', 'TFtotal'],
  317. 'timefreq': ['TFalpha', 'TFbeta', 'TFdelta', 'TFtheta', 'TFtotal'],
  318. 'P3potentials' : ['P3distractoramplitude', 'P3distractorlatency',
  319. 'P3nontargetamplitude', 'P3nontargetlatency',
  320. 'P3targetamplitude', 'P3targetlatency'],
  321. 'behavior': ['oddballAcc', 'oddballRT', 'sensitivity', 'taskAcc', 'taskRT']}
  322. varsDict['physio'].extend(['TF'+k for k in freqBands.keys()])
  323. # Grand dict with all data
  324. pats = list(measStatus['ID'])
  325. measurements = list(measStatus.columns.delete(0))
  326. info = {}
  327. for p in pats:
  328. for m in measurements:
  329. if measStatus.loc[measStatus['ID'] == p][m].item():
  330. measurement = str(p) + '_' + m
  331. info[measurement] = {}
  332. #info: stim, task, time, ID
  333. info[measurement]['ID'] = p
  334. info[measurement]['stimulation'] = get_stim_info(stimInfoPath,
  335. measurement[:-4])
  336. info[measurement]['stimNum'] = 0 if info[measurement]['stimulation'] == 'OFF' else 1
  337. info[measurement]['task'] = m[-3:]
  338. info[measurement]['time'] = m[:-4]
  339. #results: acc ratio, response time, oddball acc, oddball rt, sensitivity idx
  340. if 'VDR' in m:
  341. task, oddball, sensitivity = sumResultsVdr, sumResultsAob, sensitivityAobAll
  342. else:
  343. task, oddball, sensitivity = sumResultsSdr, sumResultsVob, sensitivityVobAll
  344. if m in task[str(p)].keys():
  345. info[measurement]['taskAcc'] = task[str(p)][m][0]
  346. info[measurement]['taskRT'] = task[str(p)][m][1]
  347. info[measurement]['oddballAcc'] = oddball[str(p)][m][0]
  348. info[measurement]['oddballRT'] = oddball[str(p)][m][1]
  349. info[measurement]['sensitivity'] = sensitivity[str(p)][m][0]
  350. #physio features 1: p3 latency, p3 amplitude * stimuli
  351. p3data = P3info[[key for key in P3info.keys() if measurement in key][0]]
  352. for s in p3data: #stimulus type
  353. for f in p3data[s]: #feature
  354. cat = oddCategory[s]
  355. info[measurement]['P3'+cat+f] = p3data[s][f]
  356. #physio features 2: delta, theta, alpha, beta & total after cue
  357. tfdata = tfaInfo[[key for key in tfaInfo.keys() if measurement in key][0]]
  358. for b in tfdata:
  359. info[measurement]['TF'+b] = tfdata[b]
  360. # Convert to pandas data frame
  361. infoDf = pd.DataFrame(info.values())
  362. columnsNorm = varsDict['physio'] + varsDict['behavior']
  363. infoDf = add_norm_values(infoDf, columns=columnsNorm)
  364. # Save
  365. infoDf.to_csv(PROCESSED_DATA_DIR / 'infoDf.csv', index =False)
  366. #Do subsets according to analizable patients and save for analysis in R
  367. subsetInfo = pd.read_csv(subsetInfoPath, index_col=False)
  368. for ta in ['SDR', 'VDR']:
  369. for ti in ['short', 'long', 'all']:
  370. df = subsetter(infoDf, task = ta, time = ti, analizableDf = subsetInfo)
  371. df.to_csv(R_INPUT_DIR / f'{ta}_{ti}.csv', index=False)
  372. #
  373. #
  374. # # -> R : Run statistics.R saved in the same directory as this script
  375. #
  376. # #%% STATISTICS: FROM R
  377. # # Read what was run in R and convert to be used in the report
  378. # ttests = pd.read_csv(STATISTICS_RESULTS_DIR / 'tTestsResults.csv')
  379. # ttests = ttests.drop(0, axis=0).drop('Unnamed: 0', axis=1)
  380. # modelsResults = pd.read_csv(STATISTICS_RESULTS_DIR / 'GLMMresults.csv')
  381. # modelsResults = modelsResults.drop(0, axis=0).drop('Unnamed: 0', axis=1)
  382. #
  383. # #convert to DF with significance info
  384. # sigttests = significance_df(ttests)
  385. # sigmodels = significance_df(modelsResults)
  386. #
  387. # # Save for projects' documentation
  388. # sigttests.to_csv(STATISTICS_RESULTS_DIR / 'tTestsResultsSign.csv', index = False)
  389. # sigmodels.to_csv(STATISTICS_RESULTS_DIR / 'GLMMresultsSign.csv', index = False)
  390. #%% STATISTICS: CORRELATION BETWEEN PHYSIO AND BEHAVIORAL
  391. # Note : The data frames generated here compute correlation between all behavioral
  392. # and all physiological values of a measurement. In the documentation and data
  393. # interpretation only connected variables (time-frequency to VDR and SDR,
  394. # P3 to oddball) were considered
  395. #Generate correlation values between physio and behavioral data
  396. drop_columns = ['ID', 'stimulation', 'time', 'task']
  397. for t in ['short', 'long']:
  398. for task in ['SDR', 'VDR']:
  399. data = subsetter(infoDf, task=task, time=t, analizableDf = subsetInfo)
  400. corrDf = corr_df(data, varsDict['behavior'], varsDict['physio'], drop_columns=drop_columns)
  401. corrDf = significance_df(corrDf)
  402. corrDf.to_csv(STATISTICS_RESULTS_DIR / f'Corr{task}{t}.csv' )
  403. # Generate correlation values between long-term cognitive change and physio values
  404. for task in ['SDR', 'VDR']:
  405. data = subsetter(infoDf, task=task, time='long', analizableDf = subsetInfo)
  406. data = data[data['time'] != 'V0']
  407. colnames = [n + 'Norm' for n in varsDict['behavior']]
  408. corrDf = corr_df(data, colnames, varsDict['physio'], drop_columns=drop_columns)
  409. corrDf = significance_df(corrDf)
  410. corrDf.to_csv(STATISTICS_RESULTS_DIR / f'DiffsCorr{task}long.csv' )
  411. #TODO: add correlation topo here!!
  412. # Generate and store correlation values between baseline values and difference values from V4/V5
  413. infoDf = add_baseline_values(infoDf, columnsNorm)
  414. drop_columns = ['ID', 'stimulation', 'time', 'task']
  415. EEGcors_topo = {}
  416. for task in ['SDR', 'VDR']:
  417. EEGcors_topo[task]={}
  418. for stim in ['OMNI', 'DIR']:
  419. data = subsetter(infoDf, task=task, time='long', analizableDf = subsetInfo)
  420. data = data[data['time'] != 'V0']
  421. data = data[data['stimulation'] == stim]
  422. rownames = [n + 'BL' for n in varsDict['physio']]
  423. colnames = [n + 'Norm' for n in varsDict['behavior']]
  424. corrDf = corr_df(data, colnames, rownames, drop_columns=drop_columns)
  425. corrDf = significance_df(corrDf)
  426. corrDf.to_csv(STATISTICS_RESULTS_DIR / f'BLNormCorr{task}{stim}.csv' )
  427. #select elements in eeg data corresponding to current task and IDs
  428. sel = np.isin(infoDf.ID,data.ID)&np.isin(infoDf.time, ['V4','V5'])&(infoDf.task==task)
  429. if (stim=="DIR"):
  430. sel&=infoDf.ID!=0 #exclude patient 0 because of excess power
  431. for band, (lo,hi) in freqBands.items():
  432. accdat = infoDf.taskAccNorm.to_numpy()[sel]
  433. rtdat = infoDf.taskRTNorm.to_numpy()[sel]
  434. banddat = np.median(over_chans_rel[sel,lo:hi,:],1)
  435. EEGcors_topo[task][f'Acc_{band}'] = [stats.pearsonr(accdat, banddat[:,chan])[0] for chan in range(banddat.shape[1])]
  436. EEGcors_topo[task][f'RT_{band}'] = [stats.pearsonr(rtdat, banddat[:,chan])[0] for chan in range(banddat.shape[1])]
  437. #%% VISUALIZATIONS TO REPORT
  438. # Descriptive table for baseline behavioral results.
  439. #Table with average behavioral results at baseline
  440. behInfoDf = infoDf[['ID', 'time','task','taskAcc', 'taskRT', 'oddballAcc', 'oddballRT', 'sensitivity']]
  441. behInfoV0 = pd.DataFrame(index = ['SDR', 'VDR', 'auditory oddball', 'visual oddball'],
  442. columns = ['Accuracy mean', 'Accuracy SD', 'Response time mean',
  443. 'Response time SD', 'Sensitivity mean',
  444. 'Sensitivity SD'])
  445. dc = {'SDR': 'visual oddball',
  446. 'VDR':'auditory oddball'}
  447. df = behInfoDf[behInfoDf['time'] == 'V0']
  448. for task in ['SDR', 'VDR']:
  449. df = behInfoDf[behInfoDf['time'] == 'V0']
  450. df = df[df['task'] == task]
  451. behInfoV0.loc[(task, 'Accuracy mean')] = df['taskAcc'].mean()
  452. behInfoV0.loc[(task, 'Accuracy SD')] = df['taskAcc'].std()
  453. behInfoV0.loc[(task, 'Response time mean')] = df['taskRT'].mean()
  454. behInfoV0.loc[(task, 'Response time SD')] = df['taskRT'].std()
  455. behInfoV0.loc[(dc[task], 'Accuracy mean')] = df['oddballAcc'].mean()
  456. behInfoV0.loc[(dc[task], 'Accuracy SD')] = df['oddballAcc'].std()
  457. behInfoV0.loc[(dc[task], 'Response time mean')] = df['oddballRT'].mean()
  458. behInfoV0.loc[(dc[task], 'Response time SD')] = df['oddballRT'].std()
  459. behInfoV0.loc[(dc[task], 'Sensitivity mean')] = df['sensitivity'].mean()
  460. behInfoV0.loc[(dc[task], 'Sensitivity SD')] = df['sensitivity'].std()
  461. behInfoV0.to_csv(STATISTICS_RESULTS_DIR / 'baselinebehavioralresults.csv', index=False)
  462. #
  463. # #BOXPLOTS
  464. #
  465. # data = infoDf
  466. # depvar = ['taskAccNorm', 'taskAccNorm', 'TFalpha', 'TFbeta', 'TFbeta', 'TFdelta',
  467. # 'TFbeta', 'P3distractoramplitude', 'P3distractoramplitude']
  468. # indvar = ['stimulation', 'stimulation', 'time', 'time', 'stimulation', 'stimulation',
  469. # 'time', 'stimulation', 'stimulation']
  470. # hue = [None, None, 'stimulation', 'stimulation', None, None, 'stimulation',
  471. # None, None]
  472. # task = ['VDR', 'SDR', 'VDR', 'VDR', 'VDR', 'VDR', 'SDR', 'VDR', 'SDR']
  473. # time = ['long', 'long', 'short', 'short', 'long', 'long', 'long', 'short', 'short']
  474. # for i in range(len(depvar)):
  475. # plot_for_stats(data, depvar[i], indvar[i], hue=hue[i], task=task[i],
  476. # time=time[i], analizableDf=subsetInfo)
  477. #
  478. # #
  479. # if plotP3waves:
  480. # tasks = ['VDR', 'SDR']
  481. # for task in tasks:
  482. # filesV3 = [f for f in files[task] if 'V3' in f]
  483. # epochsdistV3 = {}
  484. # for f in filesV3:
  485. # measurement = f.split('/')[-1][:-14]
  486. # pat = int(measurement.split('_')[0])
  487. # if subsetInfo[subsetInfo['ID'] == pat][task+'_short'].item():
  488. # eFile = f.replace('_p_raw', '_oe_epo')
  489. # epochs = mne.read_epochs(eFile, preload=True).apply_baseline()
  490. # epochs.pick_channels(clustInfo[oddDict[task]]['chans'])
  491. # epochs = epochs['distractor'].apply_baseline()\
  492. # .get_data().mean(axis=0).std(axis=0)
  493. # stim = get_stim_info(stimInfoPath, measurement)
  494. # if stim not in epochsdistV3:
  495. # epochsdistV3[stim] = epochs
  496. # else:
  497. # epochsdistV3[stim] = np.dstack((epochsdistV3[stim], epochs))
  498. #
  499. # plt.figure()
  500. # colors=['mediumblue','limegreen' , 'deepskyblue','aquamarine', 'mediumblue', 'aquamarine', 'yellowgreen']
  501. # for i, stim in enumerate(['OFF', 'DIR', 'OMNI']):
  502. # array = epochsdistV3[stim].squeeze().mean(axis=1)
  503. # bl = array[0:1000].mean()
  504. # array = array - bl
  505. # error = epochsdistV3[stim].squeeze().std(axis=1)/np.sqrt(epochsdistV3[stim].shape[2])
  506. # time = np.linspace(-0.2, 1.0, 6001)
  507. # plt.plot(time,array, label = stim, color = colors[i])
  508. # plt.fill_between(time, array-error, array + error, alpha = 0.3, color=colors[i])
  509. #
  510. # plt.ylabel(renamer('P3distractoramplitude', task))
  511. # plt.xlabel('time [s]')
  512. # plt.legend()
  513. # sns.despine()
  514. #
  515. # # SCATTER PLOTS
  516. # # In different colors :)
  517. #
  518. # #Part 1[]
  519. # task = ['VDR', 'VDR']
  520. # time = ['short', 'long']
  521. # x=['TFalpha', 'TFtheta']
  522. # y=['taskAcc', 'taskAcc']
  523. # #stim = 'OMNI'
  524. #
  525. # color = ['deepskyblue','limegreen' ,'aquamarine', 'yellowgreen', 'mediumblue']
  526. # for i in range(len(task)):
  527. # data = subsetter(infoDf, task=task[i], time=time[i], analizableDf=subsetInfo)
  528. # plt.figure()
  529. # plt.scatter(data[x[i]],data[y[i]], color=color[0])
  530. # plt.xlabel(renamer(x[i], task[i]))
  531. # plt.ylabel(renamer(y[i], task[i]))
  532. # sns.despine()
  533. #
  534. # #Part 2 (changes)
  535. # task = 'VDR'
  536. # time = 'long'
  537. # x = 'TFbeta'
  538. # y = 'taskAccNorm'
  539. # data = subsetter(infoDf, task=task, time=time, analizableDf=subsetInfo)
  540. #
  541. # data = data[data['time'] != 'V0']
  542. # plt.figure()
  543. # plt.scatter(data[x],data[y], color=color[1])
  544. # plt.xlabel(renamer(x, task))
  545. # plt.ylabel(renamer(y, task))
  546. # sns.despine()
  547. #
  548. # #Part 3 (baseline -> change)
  549. #
  550. # task = [ 'VDR', 'SDR']
  551. # time = [ 'long', 'long']
  552. # x=['TFbetaBL', 'TFalphaBL']
  553. # y=[ 'taskAccNorm', 'taskAccNorm']
  554. # stim = ['OMNI', 'DIR']
  555. #
  556. # for i in range(len(task)):
  557. # data = subsetter(infoDf, task=task[i], time=time[i], analizableDf=subsetInfo)
  558. # data = data[data['stimulation'] == stim[i]]
  559. # data = data[data['time'] != 'V0']
  560. # plt.figure()
  561. # plt.scatter(data[x[i]],data[y[i]], color=color[2])
  562. # plt.xlabel(renamer(x[i], task[i]))
  563. # plt.ylabel(renamer(y[i], task[i]))
  564. # sns.despine()
  565. plt.figure()
  566. plt.subplot(2,2,1)
  567. plt.title('SDR / Accuracy')
  568. my_topomap(np.array(EEGcors_topo['SDR']['Acc_alpha (9-14)']), chans = epochs.ch_names)
  569. plt.subplot(2,2,2)
  570. plt.title('SDR / RT')
  571. my_topomap(np.array(EEGcors_topo['SDR']['RT_alpha (9-14)']), chans = epochs.ch_names)
  572. plt.subplot(2,2,3)
  573. plt.title('VDR / Accuracy')
  574. my_topomap(np.array(EEGcors_topo['VDR']['Acc_alpha (9-14)']), chans = epochs.ch_names)
  575. plt.subplot(2,2,4)
  576. plt.title('VDR / RT')
  577. my_topomap(np.array(EEGcors_topo['VDR']['RT_alpha (9-14)']), chans = epochs.ch_names)
  578. plt.savefig(FIGURES_DIR / 'EEG_cor_topos.png')

main.py at commit 0145cac, under MIT · at the source

Overview

Authors: Marius Keute1, Tianlu Wang1, Silvana Miranda Montenegro1, Maximilian Scherer1, Patrick Bookjans1, Bastian Brunnett1, Idil Cebi1,2, Luka Milosevic1,3,4, Daniel Weiss2, Alireza Gharabaghi1,4,5,6,7,8
  1. Institute for Neuromodulation and Neurotechnology, University Hospital and University of Tübingen, Tübingen 72076, Germany
  2. Center for Neurology, Department for Neurodegenerative Diseases, and Hertie Institute for Clinical Brain Research, University of Tübingen, Tübingen 72076, Germany
  3. Clinical and Computational Neuroscience, Krembil Research Institute, University Health Network, Toronto M5T 2S8, Canada
  4. Max Planck-University of Toronto Centre for Neural Science & Technology (MPUTC), Toronto M5T 2S8 (Canada)/Tübingen 72076, Germany
  5. Center for Digital Health (CDH), Tübingen 72076, Germany
  6. Cognitive Science Center (CSC), Tübingen 72076, Germany
  7. Center for Bionic Intelligence Tübingen Stuttgart (BITS), Tübingen 72076, Germany
  8. German Center for Mental Health (DZPG), Tübingen 72076, Germany
Journal: Brain communications, volume 8, issue 5, article fcag328
Dates: received 11 June 2025; accepted 27 July 2026; published online 31 August 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1093/braincomms/fcag328 · PMID 42712895 · PMCID PMC13550774 · OpenAlex W7204800039
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), human (organism), Parkinson's (population), cognitive (subfield)
Methods: Spectral & time-frequency, Preprocessing, Connectivity, Statistics, Smoothing, state filtering, decompositions, Physiology & signal measures
Keywords: deep brain stimulation, working memory, electroencephalography, Parkinson’s disease, subthalamic nucleus
Topic: Neurological disorders and treatments (Neurology, Medicine), according to OpenAlex
Funding: EU Joint Programme - Neurodegenerative Disease Research (EU-JPND 2022-130, 01ED2309); Abbott Northwestern Hospital Foundation; European Commission; St. Jude Medical
Citations: not cited yet (Europe PMC); 49 references in the paper

Abstract

The dynamic modulation of large-scale network activity, which is inherent to cognitive processes, is disrupted in Parkinson’s disease. Subthalamic deep brain stimulation can either improve or deteriorate cognition, particularly executive function, with these effects often going unnoticed during acute parameter optimization. This highlights the need for longer stimulation periods and more focused research on the underlying cortical mechanisms, which remain underexplored. This study was a prospective clinical trial involving nineteen people with Parkinson’s disease, who were evaluated off their medication at preoperative baseline and 6 months after deep brain stimulation implantation. Brain activity related to verbal and visuospatial working memory tasks was recorded using electroencephalography at both baseline and during follow-up evaluations conducted under stimulation. The follow-up assessments were carried out following 3-week periods of either omnidirectional or directional stimulation, applied in a randomized, double-blind, crossover design. Average postoperative working memory performance remained stable at the group level regardless of the stimulation condition for both verbal and visuospatial working memory tasks. However, at the individual level, higher alpha and beta power at baseline was associated with slower visuospatial working memory reaction time at follow-up. Additionally, reductions in theta and beta power during stimulation at follow-up correlated with better verbal working memory accuracy during the task and compared with baseline, respectively. These findings suggest that task-related electroencephalography may provide candidate physiological markers of individual working memory trajectories after subthalamic deep brain stimulation. Oscillatory brain activity may help to characterize stimulation-related cognitive variability beyond motor outcomes, but these exploratory findings require validation in larger cohorts before they can inform stimulation programming or closed-loop treatment strategies. Registration: ClinicalTrials.gov: NCT03548506

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 7 matches between paragraphs and lines of code.

neuromti/stn-dbs-working-memory-eeg

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 0145cacc0429658f04a480353f182c61034c8746, 19 May 2026
Languages: Python (8), R (1)
Size: 16 files, 9 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (requirements.txt, project_package/setup.py)
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (6 files), MNE-Python (5 files), pandas (5 files), SciPy (5 files), Matplotlib (4 files), seaborn (2 files), ggplot2 (1 file), lme4 (1 file), lmerTest (1 file), patchwork (1 file), reshape2 (1 file), tidyverse (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
11 files

Code availability

The GitHub repository https://github.com/neuromti/stn-dbs-working-memory-eeg includes the analysis scripts for this study.

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

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;
  • 9 scripts, each with its path and the digest of its content;
  • 7 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

Data are available upon request from the first author after institutional approval.

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 2, 28 September 2026

  • Funding: added EU Joint Programme – Neurodegenerative Disease Research: EU-JPND 2022-130, 01ED2309; Abbott Northwestern Hospital Foundation; European Commission; St. Jude Medical

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 10 authors, 5 keywords, 48 references.

Cite

This paper

Keute, M., Wang, T., Miranda Montenegro, S., Scherer, M., Bookjans, P., Brunnett, B., Cebi, I., Milosevic, L., Weiss, D., & Gharabaghi, A. (2026). Subthalamic stimulation modulates working memory-related cortical dynamics in Parkinson's disease. Brain communications, 8(5), fcag328. https://doi.org/10.1093/braincomms/fcag328

BibTeX

@article{keute2026subthalamic,
author = {Keute, Marius and Wang, Tianlu and Miranda Montenegro, Silvana and Scherer, Maximilian and Bookjans, Patrick and Brunnett, Bastian and Cebi, Idil and Milosevic, Luka and Weiss, Daniel and Gharabaghi, Alireza},
title = {{Subthalamic stimulation modulates working memory-related cortical dynamics in Parkinson's disease}},
journal = {Brain communications},
year = {2026},
month = aug,
volume = {8},
number = {5},
pages = {fcag328},
publisher = {Oxford University Press},
issn = {2632-1297},
doi = {10.1093/braincomms/fcag328},
url = {https://doi.org/10.1093/braincomms/fcag328},
pmid = {42712895},
pmcid = {PMC13550774}
}

RIS

TY - JOUR
AU - Keute, Marius
AU - Wang, Tianlu
AU - Miranda Montenegro, Silvana
AU - Scherer, Maximilian
AU - Bookjans, Patrick
AU - Brunnett, Bastian
AU - Cebi, Idil
AU - Milosevic, Luka
AU - Weiss, Daniel
AU - Gharabaghi, Alireza
TI - Subthalamic stimulation modulates working memory-related cortical dynamics in Parkinson's disease
T2 - Brain communications
J2 - Brain Commun
PY - 2026
DA - 2026/08/31
VL - 8
IS - 5
SP - fcag328
SN - 2632-1297
PB - Oxford University Press
DO - 10.1093/braincomms/fcag328
UR - https://doi.org/10.1093/braincomms/fcag328
LA - en
ER -

CSL-JSON

{
"id": "10.1093/braincomms/fcag328",
"type": "article-journal",
"title": "Subthalamic stimulation modulates working memory-related cortical dynamics in Parkinson's disease",
"container-title": "Brain communications",
"author": [
{
"family": "Keute",
"given": "Marius"
},
{
"family": "Wang",
"given": "Tianlu"
},
{
"family": "Miranda Montenegro",
"given": "Silvana"
},
{
"family": "Scherer",
"given": "Maximilian"
},
{
"family": "Bookjans",
"given": "Patrick"
},
{
"family": "Brunnett",
"given": "Bastian"
},
{
"family": "Cebi",
"given": "Idil"
},
{
"family": "Milosevic",
"given": "Luka"
},
{
"family": "Weiss",
"given": "Daniel"
},
{
"family": "Gharabaghi",
"given": "Alireza"
}
],
"container-title-short": "Brain Commun",
"volume": "8",
"issue": "5",
"page": "fcag328",
"DOI": "10.1093/braincomms/fcag328",
"PMID": "42712895",
"PMCID": "PMC13550774",
"ISSN": "2632-1297",
"publisher": "Oxford University Press",
"URL": "https://doi.org/10.1093/braincomms/fcag328",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
31
]
]
}
}

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/imag.a.1245 [code]
Towards precision EEG connectomics: Evaluating the benefits of dense sampling.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: MNE-Python, lmerTest, lme4, 9 other tools, EEG
[2] doi:10.1162/imag.a.105 [code]
Right posterior theta reflects human parahippocampal phase resetting by salient cues during goal-directed navigation
Journal: —
In common: MNE-Python, lmerTest, lme4, 8 other tools, EEG, cognitive
[3] doi:10.1093/cercor/bhag077 [code]
The longitudinal development of intrinsic timescales in infancy and their relation to alpha brain rhythm.
Journal: Cerebral cortex (New York, N.Y. : 1991)
In common: MNE-Python, lmerTest, lme4, 8 other tools, EEG
[4] doi:10.1016/j.xcrm.2026.102766 [code]
A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.
Journal: Cell reports. Medicine
In common: lmerTest, lme4, reshape2, 8 other tools
[5] doi:10.1093/nc/niag029 [code]
A data-driven approach to identifying and evaluating connectivity-based neural correlates of conscious visual perception.
Journal: Neuroscience of consciousness
In common: MNE-Python, lmerTest, patchwork, 7 other tools, cognitive, 1 reference
[6] doi:10.1038/s41598-026-58505-y [code]
Remoteness sensitive theta network dynamics during early autobiographical memory access.
Journal: Scientific reports
In common: MNE-Python, lme4, reshape2, 7 other tools, EEG, cognitive
[7] doi:10.1162/imag.a.1321 [code]
Phase similarity between similar objects indicates representational merging across retrieval training but not sleep.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: MNE-Python, lmerTest, lme4, 6 other tools, EEG, cognitive, 1 reference
[8] doi:10.1093/cercor/bhag113 [code]
Long-term reliability and stability of parameterized resting state EEG: evidence from a five-year follow-up.
Journal: Cerebral cortex (New York, N.Y. : 1991)
In common: MNE-Python, lmerTest, lme4, 7 other tools, EEG
[9] doi:10.7554/elife.107088 [code]
Development of auditory and spontaneous movement responses to music over the first postnatal year.
Journal: eLife
In common: MNE-Python, lme4, reshape2, 7 other tools, EEG
[10] doi:10.1162/imag.a.1347 [code]
Neural and behavioural correlates of theory of mind reasoning in five-year-old children born preterm.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: lmerTest, lme4, reshape2, 7 other tools

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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

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