-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBF_localize_preStim.py
235 lines (192 loc) · 9.63 KB
/
BF_localize_preStim.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python
#Need mne version 0.21.0 to run this script because noise cross spectral density is only a feature in the most recent update
# Import libraries
import os
import mne
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd
from mne.time_frequency import tfr_morlet
import multiprocessing as mp
import time
mne.set_log_level('WARNING')
def make_BF_map(subjectID):
"""Top-level run script for making spectral events BF map from MEG data."""
print(subjectID)
#################################
# Variables
channelName = 'MEG1311'
# BF Analysis Paramaters
startTime = -1.25
endTime = -0.25
eventDuration = 0.4 # See distplot below for justification
# TFR analysis parameters
TFRfmin = 5
TFRfmax = 60
TFRfstep = 5
# DICS Settings
tmins = [0.0, -0.575] # Start of each window (active, baseline)
tstep = 0.4
fmin = 15
fmax = 30
numFreqBins = 10 # linear spacing
DICS_regularizaion = 0.5
data_decimation = 1
plotOK = False
###############
# Setup paths and names for file
dataDir = '/home/timb/camcan/'
MEGDir = os.path.join(dataDir, 'proc_data/TaskSensorAnalysis_transdef')
outDir = os.path.join('/media/NAS/lpower/BetaSourceLocalization/preStimData',channelName, subjectID)
subjectsDir = os.path.join(dataDir, 'subjects/')
epochFifFilename = 'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo.fif'
epochFif = os.path.join(MEGDir, subjectID, epochFifFilename)
emptyroomFif = '/media/NAS/lpower/BetaSourceLocalization/emptyroomData/' + subjectID + '/emptyroom_trans-epo.fif' #Added this file **NEW**
spectralEventsCSV = subjectID +'_MEG1311_spectral_events.csv'
csvFile = os.path.join('/media/NAS/bbrady/random old results/spectralEvents/', subjectID, spectralEventsCSV)
transFif = subjectsDir + 'coreg/sub-' + subjectID + '-trans.fif'
srcFif = subjectsDir + 'sub-' + subjectID + '/bem/sub-' + subjectID + '-5-src.fif'
bemFif = subjectsDir + 'sub-' + subjectID + '/bem/sub-' + subjectID + '-5120-bem-sol.fif'
# Files to make
stcFile = os.path.join(outDir,
'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo_preBetaEvents_DICS')
#stcFileNew = os.path.join(outDir,
# 'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo_moveBetaEvents_DICS')
stcMorphFile = os.path.join(outDir,
'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo_preBetaEvents_DICS_fsaverage')
#stcMorphFileNew = os.path.join(outDir,
# 'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo_moveBetaEvents_DICS_fsaverage')
testCompleteFile = os.path.join(outDir,
'transdef_transrest_mf2pt2_task_raw_buttonPress_duration=3.4s_cleaned-epo_preBetaEvents_DICS-lh.stc')
if os.path.exists(testCompleteFile):
return
else:
if not os.path.exists(outDir):
os.makedirs(outDir)
#####################################
# Pull events from CSV
# Read all transient events for subject
df = pd.read_csv(csvFile)
# Events that meet Shin criteria only
df1 = df[df['Outlier Event']]
# Freq range of interest
df2 = df1.drop(df1[df1['Peak Frequency'] < fmin].index)
df3 = df2.drop(df2[df2['Peak Frequency'] > fmax].index)
df4 = df3.drop(df3[df3['Peak Time'] > endTime].index)
newDf = df4.drop(df4[df4['Peak Time'] < startTime].index)
#Creates a dataframe with only the top 55 highest power bursts
#If a subject has less than 55 bursts, they will be excluded
newDf = newDf.sort_values(by='Normalized Peak Power')
if newDf.size >= 55:
newDf = newDf.tail(n=55)
else:
print("Not enough bursts to create map.")
return
if plotOK:
# Raster plot of event onset and offset times
ax = sns.scatterplot(x='Event Onset Time', y='Trial', data=newDf)
sns.scatterplot(x='Event Offset Time', y='Trial', data=newDf, ax=ax)
plt.show()
# Distribution of event durations
sns.distplot(newDf['Event Duration'])
plt.show()
# Based on the distribution, an interval of 0-400 ms will include the full event duration in most cases
##############################################
# Now do the DICS beamformer map calcaulation
# Read epochs
originalEpochs = mne.read_epochs(epochFif)
# Re-calculate epochs to have one per spectral event
numEvents = len(newDf)
print("Length of new DF:")
print(numEvents)
epochList = []
for e in np.arange(numEvents):
thisDf = newDf.iloc[e]
onsetTime = thisDf['Event Onset Time']
epoch = originalEpochs[thisDf['Trial']]
epochCrop = epoch.crop(onsetTime+tmins[1], onsetTime-tmins[1])
epochCrop = epochCrop.apply_baseline(baseline=(None,None))
# Fix epochCrops times array to be the same every time = (-.4, .4)
epochCrop.shift_time(tmins[1], relative=False)
if (epochCrop.tmin == -0.575 and epochCrop.tmax == 0.575):
epochList.append(epochCrop)
epochs = mne.concatenate_epochs(epochList)
epochs.pick_types(meg=True)
'''
# Let's look at the TFR across sensors
magPicks = mne.pick_types(epochs.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads')
freqs = np.arange(TFRfmin, TFRfmax, TFRfstep)
n_cycles = freqs / 2.0
power, _ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, picks=magPicks,
use_fft=False, return_itc=True, decim=1, n_jobs=1)
#power.save(tfrFile, overwrite=True)
if plotOK:
power.plot_joint(baseline=(-0.4, 0), mode='mean',
timefreqs = [(.2, 20)])
'''
# Read source space
src = mne.read_source_spaces(srcFif)
# Make forward solution
forward = mne.make_forward_solution(epochs.info,
trans=transFif, src=src, bem=bemFif,
meg=True, eeg=False)
# DICS Source Power example
# https://martinos.org/mne/stable/auto_examples/inverse/plot_dics_source_power.html#sphx-glr-auto-examples-inverse-plot-dics-source-power-py
#Compute noise csd from empty room data **NEW**
epochs_emptyroom = mne.read_epochs(emptyroomFif)
epochs_emptyroomMAG = epochs_emptyroom.pick_types(meg='mag')
csd_emptyroom = csd_morlet(epochs_emptyroomMAG, decim=data_decimation, frequencies = np.linspace(fmin, fmax, numFreqBins))
# Compute DICS spatial filter and estimate source power.
stcs = []
epochsMAG = epochs.copy()
epochsMAG.pick_types(meg='mag')
for tmin in tmins:
csd = csd_morlet(epochsMAG, tmin=tmin, tmax=tmin + tstep, decim=data_decimation,
frequencies=np.linspace(fmin, fmax, numFreqBins))
filters = make_dics(epochsMAG.info, forward, csd, noise_csd=csd_emptyroom, reg=DICS_regularizaion)# Added noise_csd arg **NEW**
stc, freqs = apply_dics_csd(csd, filters)
stcs.append(stc)
# Take difference between active and baseline, and mean across frequencies
ERS = np.log2(stcs[0].data / stcs[1].data)
a = stcs[0]
ERSstc = mne.SourceEstimate(ERS, vertices=a.vertices, tmin=a.tmin, tstep=a.tstep, subject=a.subject)
ERSband = ERSstc.mean()
ERSband.save(stcFile)
#ERSmorph = ERSband.morph(subject_to='fsaverage', subject_from='sub-' + subjectID, subjects_dir=subjectsDir)
morph = mne.compute_source_morph(ERSband, subject_from='sub-' + subjectID,
subject_to='fsaverage',
subjects_dir=subjectsDir)
ERSmorph = morph.apply(ERSband)
ERSmorph.save(stcMorphFile)
return
if __name__ == "__main__":
# Find subjects to be analysed
homeDir = '/media/NAS/lpower/camcan/'
dataDir = homeDir + 'spectralEvents/task/MEG0221'
camcanCSV = dataDir + '/spectralEventAnalysis.csv'
subjectData = pd.read_csv(camcanCSV)
# Take only subjects with more than 55 epochs
subjectData = subjectData[subjectData['numEpochs'] > 55]
# Drop subjects with MR files missing
subjectData = subjectData.drop(subjectData[subjectData['bemExists'] == False].index)
subjectData = subjectData.drop(subjectData[subjectData['srcExists'] == False].index)
subjectData = subjectData.drop(subjectData[subjectData['transExists'] == False].index)
#subjectData = subjectData.drop(subjectData[subjectData['Event Stc Exists'] == True].index)
subjectIDs = subjectData['SubjectID'].tolist()
print(len(subjectIDs))
#subjectIDs =subjectIDs[0]
ex_subs = ['CC520395','CC222326','CC310414','CC320568', 'CC320636', 'CC321595', 'CC510534','CC520136','CC520745', 'CC520775', 'CC621080', 'CC720304']
for x in ex_subs:
subjectIDs.remove(x)
# Set up the parallel task pool to use all available processors
count = int(np.round(mp.cpu_count()*1/4))
pool = mp.Pool(processes=count)
# Run the jobs
pool.map(make_BF_map, subjectIDs)
#make_BF_map('CC110033')
# Or run one subject for testing purposes
#for x in subjectIDs:
# make_BF_map(x)