/
uh_paper_analysis-worked-one-backup.py
261 lines (206 loc) · 9.09 KB
/
uh_paper_analysis-worked-one-backup.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import os
import mne
import matplotlib.pyplot as plt
from mne.minimum_norm import (apply_inverse,apply_inverse_epochs,make_inverse_operator)
from mne.connectivity import seed_target_indices, spectral_connectivity
import glob
"""
The goal of the analysis is to make a statistical appraisal of the neural
activation evoked from the BMI triggered exoskeleton at Movement onset detected by Robot event.
1) The question is whether evidence can be found against the hull hypothesis that
neural activations (plasticity) in (the somatosensory and motor) cortex does doen depend on
whether or not the when BMI is inactive (subject is idle)
2) Can we find any evidence against hull hypothesis that neural activations patterns
on the cortex does remain the same across sessions ?
* In other words, there is no evidence of cortical reorganization.
"""
#%%##############################################################################
# Read the EEG data
from uhClass import MRCP
mainDir = '/home/hero/uhdata/freesurfer'
subject = 'S9023'
os.chdir(os.path.join(mainDir, subject))
eegfiles = glob.glob('*-epo.fif')
#%%
eeg = []
for eegfilename in eegfiles:
if not ('_ses1_' in eegfilename or '_ses2_' in eegfilename):
# eegfilename = 'S9017_ses3_closeloop_block0000-epo.fif'
ep = MRCP.readEEGepoch(eegfilename, mainDir)
ep = ep.interpolate_bads(reset_bads='True', mode = 'accurate')
ep.info['bads'] = []
ep.resample(100)
eeg.append(ep)
#%% Plot EEG
#from uhClass import MRCP
#filename = eegfilename.split('_s')[0]
ev =[]
for ep in eeg:
print(ep)
evoked = ep.average().detrend(order=1)
ev.append(evoked)
#%% STEP 1: COMPUTER THE SOURCE SPACE (SOURCE GRID ON MRI)
"""
The source space defines the position of the candidate source locations.
The following code compute such a cortical source space with an
OCT-5 resolution.
"""
# this is a freesurfer folder name
#src = mne.setup_source_space(subject, spacing='oct5', subjects_dir = mainDir)
#%%
#src.plot(head=True, brain=True, skull = True, subjects_dir = mainDir)
#%% READ FORWARD SOLUTION
fname_fwd = os.path.join(mainDir, subject) + '/' + subject + '-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd)
#%%
noise_cov = mne.compute_covariance(eeg[1], keep_sample_mean=True, tmin=-0.8, tmax=-0.0)
stcs = []
for ii, epoch in enumerate(ev):
# tmin, tmax = epoch.time_as_index([-1, -0.5])
# calculate noise covariance matrix
# make inverse operator
info = epoch.info
inverse_operator = make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=None)
epoch.set_eeg_reference(ref_channels = "average", projection=True)
# apply inverse solution
method = 'MNE'
snr = 3.
lambda2 = 1. / snr ** 2
stc = apply_inverse(epoch, inverse_operator, lambda2,method= method, pick_ori="normal",)
stcs.append(stc)
#%%
#e1 = copy.deepcopy(evoked)
#e2 = copy.deepcopy(evoked)
#e1.crop(-0.5, 0)
#e2.crop(0, 0.5)
#%%
import copy
# condition 1 -- > baseline
cond1, cond2 = [], []
# condition 2 ---> Movement detected by Robot
for source in stcs:
cond1.append(copy.deepcopy(source).crop(-0.5, 0))
cond2.append(copy.deepcopy(source).crop(0, 0.5))
#%%
n_vertices_sample, n_times = cond2[2].data.shape
n_subjects = len(cond2)
#%%
try:
del X
except Exception:
pass
X = np.zeros([n_vertices_sample, n_times, n_subjects, 2])
for ii, c1 in enumerate(cond1):
X[:,:,ii,0] = c1.data
for ii, c2 in enumerate(cond2):
X[:,:,ii,1] = c2.data
""""
X = np.zeros([n_vertices_sample, n_times, n_subjects])
for ii, c in enumerate(cond2):
X[:,:, ii] = c.data
"""
#%%############################################################################
# Finally, we want to compare the overall activity levels in each condition,
# the diff is taken along the last axis (condition). The negative sign makes
# it so condition1 > condition2 shows up as "red blobs" (instead of blue).
X = np.abs(X) # only magnitude
X = X[:, :, :, 0] - X[:, :, :, 1] # make paired contrast
#%%############################################################################
src_fname = os.path.join(mainDir, subject) + '/'+ subject + '-src.fif'
# Read the source space we are morphing to
src = mne.read_source_spaces(src_fname)
fsave_vertices = [s['vertno'] for s in src]
#%%############################################################################
# Compute statistic
# -----------------
# To use an algorithm optimized for spatio-temporal clustering, we
# just pass the spatial connectivity matrix (instead of spatio-temporal)
print('Computing connectivity.')
connectivity = mne.spatial_src_connectivity(src)
#X1 = X[:,:,:,1]
# Note that X needs to be a multi-dimensional array of shape
# samples (subjects) x time x space, so we permute dimensions
X = np.transpose(X, [2, 1, 0])
# Now let's actually do the clustering. This can take a long time...
#%% Here we set the threshold quite high to reduce computation.
p_threshold = 0.05
#t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)
t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)
#%%
tstep = cond2[0].tstep
from mne.stats import (spatio_temporal_cluster_1samp_test, summarize_clusters_stc)
print('Clustering.')
T_obs, clusters, cluster_p_values, H0 = clu = \
spatio_temporal_cluster_1samp_test(X, connectivity=connectivity, n_jobs=1,
threshold=t_threshold, buffer_size = None)
# Now select the clusters that are sig. at p < 0.05 (note that this value
# is multiple-comparisons corrected).
#%%
from mne.stats import spatio_temporal_cluster_test
good_cluster_inds = np.where(cluster_p_values < 0.1)[0]
a = spatio_temporal_cluster_test(
X, threshold=None, n_permutations=1024, tail=0, stat_fun=None,
connectivity=None, verbose=None, n_jobs=1, seed=None, max_step=1,
spatial_exclude=None, step_down_p=0, t_power=1, out_type='indices',
check_disjoint=False, buffer_size=1000)
#%%############################################################################
# Visualize the clusters
# ----------------------
print('Visualizing clusters.')
# Now let's build a convenient representation of each cluster, where each
# cluster becomes a "time point" in the SourceEstimate
stc_all_cluster_vis = summarize_clusters_stc(clu, p_thresh=0.1, tstep=tstep,
vertices=fsave_vertices, subject=subject)
#%% Let's actually plot the first "time point" in the SourceEstimate, which
# shows all the clusters, weighted by duration
subjects_dir = os.path.join(mainDir)
# blue blobs are for condition A < condition B, red for A > B
brain = stc_all_cluster_vis.plot(surface='inflated',
hemi='both', views='lateral', subjects_dir=subjects_dir,
time_label='Duration significant (ms)', size=(800, 800),
smoothing_steps=10)
# brain.save_image('clusters.png')
#%% Statistics
"""
1) Parametric Hypothesis Testing assumes Normal distribution or iid
2) Non-parametric Hypothesis Testing does not rely on any assumption and is usually done by
methods such as Bootstrap analysis & Permutation Test
a) Paired data has dependent samples since the data is acquired from the same subject (multiple data)
Paired data: there are two measurements from each patient, one before treatment and one after treatment.
These two measurements relate to one another, we are
interested in the difference between the two measurements (the
log ratio) to determine whether a gene has been up-regulated or
down-regulated in breast cancer following that treatment.
b) Unpaired data has independent samples as the data is acqured from two different/distinct subjects
c) Complex data has more than two Groups (ANOVA)
###########################
The significance level (alpha) is related to the degree of certainty you require in
order to reject the null hypothesis in favor of the alternative e.g. alpha = 0.05
The p-value is the probability of observing the given sample result under the
assumption that the null hypothesis is true.
If the p-value is less than alpha, then you reject the null hypothesis.
For example, if alpha = 0.05 and the p-value is 0.03, then you reject the null hypothesis
##########################
Confidence intervals: a range of values that have a chosen probability of
containing the true hypothesized quantity.
###########################
Steps of Hypthesis testing:
1. Determine the null and alternative hypothesis, using
mathematical expressions if applicable.
2. Select a significance level (alpha).
3. Take a random sample from the population of interest.
4. Calculate a test statistic from the sample that provides
information about the null hypothesis.
5. Decision
>>> If the value of the statistic is consistent with the null hypothesis
then do not reject H0.
>>> If the value of the statistic is not consistent with the null
hypothesis, then reject H0 and accept the alternative hypothesis.
##########################
"""
#%%
#fname = 'S9017_ses1_cond1_block0001-rh.stc'
#stc = mne.read_source_estimate(fname)