def calc_psd_epochs(epochs, plot=False): """Calculate PSD for epoch. Parameters ---------- epochs : list of epochs plot : bool To show plot of the psds. It will be average for each condition that is shown. Returns ------- psds_vol : numpy array The psds for the voluntary condition. psds_invol : numpy array The psds for the involuntary condition. """ tmin, tmax = -0.5, 0.5 fmin, fmax = 2, 90 # n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 psds_vol, freqs = psd_multitaper(epochs["voluntary"], tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax) psds_inv, freqs = psd_multitaper(epochs["involuntary"], tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax) psds_vol = 20 * np.log10(psds_vol) # scale to dB psds_inv = 20 * np.log10(psds_inv) # scale to dB if plot: def my_callback(ax, ch_idx): """Executed once you click on one of the channels in the plot.""" ax.plot(freqs, psds_vol_plot[ch_idx], color='red', label="voluntary") ax.plot(freqs, psds_inv_plot[ch_idx], color='blue', label="involuntary") ax.set_xlabel = 'Frequency (Hz)' ax.set_ylabel = 'Power (dB)' ax.legend() psds_vol_plot = psds_vol.copy().mean(axis=0) psds_inv_plot = psds_inv.copy().mean(axis=0) for ax, idx in iter_topography(epochs.info, fig_facecolor='k', axis_facecolor='k', axis_spinecolor='k', on_pick=my_callback): ax.plot(psds_vol_plot[idx], color='red', label="voluntary") ax.plot(psds_inv_plot[idx], color='blue', label="involuntary") plt.legend() plt.gcf().suptitle('Power spectral densities') plt.show() return psds_vol, psds_inv, freqs
def main(args): data_dir = args.data_dir figure_dir = args.figure_dir sub = args.sub subj_id = "sub" + str(sub) + "/ball0" raw_fnames = [ "".join([data_dir, subj_id, str(i), "_sss_trans.fif"]) for i in range(1, 4) ] raws = [] for fname in raw_fnames: if os.path.isfile(fname): raw = mne.io.Raw(fname, preload=True).crop(tmax=180) print(raw.info) events = mne.find_events(raw, stim_channel="STI101", min_duration=0.003) raw.pick_types(meg="grad", misc=False) raw.notch_filter(50, notch_widths=2) raw.filter(l_freq=1.0, h_freq=70) raws.append(raw) del raw else: print(fname, "***NOT FOUND") raw = mne.concatenate_raws(raws) raw.plot(start=0., duration=20., n_channels=20, events=events) plt.show() psds, freqs = mne.time_frequency.psd_welch(raw, n_per_seg=250, n_overlap=250 / 2, average='mean', fmin=1.0, fmax=70) psds = 20 * np.log10(psds) # scale to DB fig = plt.figure(figsize=(12, 8)) for ax, idx in iter_topography(raw.info, fig_facecolor='white', axis_facecolor='white', axis_spinecolor='white', on_pick=None, fig=fig): ax.plot(psds[idx], color='red') plt.gcf().suptitle('Power spectral densities') plt.show()
n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 psds, freqs = psd_welch(raw, picks=picks, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax) psds = 20 * np.log10(psds) # scale to dB def my_callback(ax, ch_idx): """ This block of code is executed once you click on one of the channel axes in the plot. To work with the viz internals, this function should only take two parameters, the axis and the channel or data index. """ ax.plot(freqs, psds[ch_idx], color='red') ax.set_xlabel('Frequency (Hz)') ax.set_ylabel('Power (dB)') for ax, idx in iter_topography(raw.info, fig_facecolor='white', axis_facecolor='white', axis_spinecolor='white', on_pick=my_callback): ax.plot(psds[idx], color='red') plt.gcf().suptitle('Power spectral densities') plt.show()
import mne from mne.viz import iter_topography from mne import io from mne.time_frequency import psd_welch from mne.datasets import sample from mne import create_info from mne.channels import read_montage info = create_info(CHANNELS, 250, 'eeg', read_montage('standard_1005')) metric_type = 'magnitude' curves_array = np.zeros((4, 32, 30)) for ax, idx in iter_topography(info, fig_facecolor='white', axis_facecolor='white', axis_spinecolor='white'): curves = {} for f, fb_type in enumerate(['FB0', 'FB250', 'FB500', 'FBMock']): curves[fb_type] = y_df.query( 'metric_type=="{}" & fb_type=="{}" & channel=="{}"'.format( metric_type, fb_type, CHANNELS[idx])).groupby('k').median()['env'].values curves_array[f, idx, :] = curves[fb_type] ax.plot(curves['FB0'] - curves['FBMock'] * 0) ax.plot(curves['FB250'] - curves['FBMock'] * 0) ax.plot(curves['FB500'] - curves['FBMock'] * 0) ax.plot(curves['FBMock']) ax.set_xlabel(CHANNELS[idx]) ax.axhline(0, color='k', alpha=0.3) if idx > 0:
print "Plotting" def my_callback(ax, ch_idx): """ """ ax.plot(freqs, mind_spectrum[ch_idx], color='red') ax.plot(freqs, plan_spectrum[ch_idx], color='green') ax.plot(freqs, anxious_spectrum[ch_idx], color='blue') ax.plot(freqs, rest_spectrum[ch_idx], color='yellow') ax.set_xlabel = 'Frequency (Hz)' ax.set_ylabel = 'Power (dB)' plt.show() for ax, idx in iter_topography(raw.info, fig_facecolor='white', axis_facecolor='white', axis_spinecolor='white', on_pick=my_callback): ax.plot(mind_spectrum[idx], color='red') ax.plot(plan_spectrum[idx], color='green') ax.plot(anxious_spectrum[idx], color='blue') ax.plot(rest_spectrum[idx], color='yellow') plt.show() selections = { 'Oz': ['211', '192', '234', '204', '203'], 'Pz': ['183', '224', '201', '202'], 'Cz': ['071', '072', '074', '073'], 'Fz': ['061', '101', '102', '064', '062', '103'], 'C4': ['113', '134', '222', '241'],
def createGroupAverage(self, path, colors, channelColors, form, dpi, log, layout): """ Computes mean average from values stored in array 'groups'. Parameters: path - The path for the file to save. form - A format for the images ('png', 'pdf', 'svg'). dpi - Resolution for the images. log - Boolean to indicate if logarithmic scale is in use. """ try: print len(self.groups['conds'][0][0]) f = open(path + '/group_average.txt', 'w') f.write('freq;') for i in self.groups['freqs']: f.write(repr(i) + '; ') f.write('\n') for cond in self.groups['conds'].keys(): #plt.clf() #if k == 'freqs': continue for k in self.groups['conds'][cond].keys(): f.write( repr(self.keyMap[k]) + 'cond_' + str(cond + 1) + '; ') mean = np.mean(self.groups['conds'][cond][k], 0) for j in mean: f.write(repr(j) + '; ') f.write('\n') #overwrites the groups for plotting self.groups['conds'][cond][k] = mean """ plt.plot(self.groups['freqs'], mean) plt.xlabel('Frequency (Hz)') if log: plt.ylabel('Power (dB)') else: plt.ylabel('(uV)') plt.savefig(path + '/average_channel_' + k, format=form, dpi=dpi) plt.close() """ except Exception as e: print 'Error while writing group averages!' print str(e) finally: f.close() print len(self.groups['conds'][0][0]) lout = mne.layouts.read_layout(layout, scale=True) def my_callback(ax, ch_idx): #i = self.keyMap[ch_idx] for cond in self.groups['conds'].keys(): ax.plot(np.array(self.groups['freqs']), self.groups['conds'][cond][ch_idx], color=colors[cond]) ax.set_xlabel = 'Frequency (Hz)' ax.set_ylabel = 'Power (dB)' plt.show() plt.clf() for ax, idx in iter_topography(self.raw.info, fig_facecolor='white', axis_spinecolor='white', axis_facecolor='white', layout=lout, on_pick=my_callback): i = self.keyMap[idx] print idx print i for cond in self.groups['conds'].keys(): if (self.keyMap[idx] in channelColors[cond][1]): color = channelColors[cond][0] else: color = colors[cond] ax.plot(self.groups['conds'][cond][idx], color=color, linewidth=0.2) plt.show() self.keyMap.clear() self.groups.clear()
def plotSpectrum(self, parent, params, colors, channelColors, path=""): """ Method for plotting the power spectral densities. Parameters: parent - Parent dialog. params - A set of parameters for calculating psds as dictionary. colors - Color for each condition as a list. channelColors - A list of tuples indicating color for selected channels. path - A path for saving the images. If left empty, the psds will be plotted to the screen. """ try: lout = mne.layouts.read_layout(params['lout'], scale=True) except Exception: raise Exception("Could not read layout file.") #self.computeSpectrum(params) if path == "": self.e.clear() self.e2.set() self.thread = Thread(target=self.computeSpectrum, args=(params, )) self.thread.start() while not (self.e.is_set()): sleep(0.5) if self.e2.is_set(): parent.updateUi() if self.e.is_set(): break self.e.clear() else: self.computeSpectrum(params) if self.psds == []: return print "Plotting power spectrum..." parent.updateUi() def my_callback(ax, ch_idx): """ Callback for the interactive plot. Opens a channel specific plot. """ for i in xrange(len(self.psds)): color = colors[i] ax.plot(self.psds[i][1], self.psds[i][0][ch_idx], color=color) plt.xlabel('Frequency (Hz)') if params['log']: plt.ylabel('Power (dB)') else: plt.ylabel('(uV)') plt.show() # draw topography indices = [] for ax, idx in iter_topography(self.raw.info, fig_facecolor='white', axis_spinecolor='white', axis_facecolor='white', layout=lout, on_pick=my_callback): for i in xrange(len(self.psds)): channel = self.raw.info['ch_names'][idx] if (channel in channelColors[i][1]): ax.plot(self.psds[i][0][idx], color=channelColors[i][0], linewidth=0.2) indices.append(idx) else: ax.plot(self.psds[i][0][idx], color=colors[i], linewidth=0.2) indices = list(set(indices)) # Remove duplicates if path == "": print "Saving ASCII file.\n" fName = self.raw.info['filename'] fName = fName.rsplit('.', 1)[0] #path = fName.rsplit('/', 1)[0] #fName = fName.rsplit('/', 1)[1] for cond in xrange(len(self.psds)): print "Writing file " + fName + '_cond' + str(cond + 1) + '.txt' f = open(fName + '_cond' + str(cond + 1) + '.txt', 'w') f.write('Hz;') for i in self.psds[cond][1]: f.write(repr(i) + ';') f.write('\n') for i in indices: f.write(repr(self.raw.info['ch_names'][i]) + '; ') for j in self.psds[cond][0][i]: f.write(repr(j) + '; ') f.write('\n') f.close() plt.show() else: print "Saving image...\n" fName = self.raw.info['filename'] fName = fName.rsplit('.', 1)[0] fName = fName.rsplit('/', 1)[1] plt.gcf().suptitle(fName) try: form = params['format'] plt.savefig(path + '/' + fName + "_topo." + form, dpi=params['dpi'], format=form) except Exception as e: plt.close() raise (e) return print "Saving ASCII file.\n" if not self.groups.has_key('conds'): self.groups['conds'] = dict() for cond in xrange(len(self.psds)): if not self.groups['conds'].has_key(cond): self.groups['conds'][cond] = dict() f = open (path + '/' + fName + '_cond' + str(cond+1) \ + '.txt', 'w') f.write('Hz;') for i in self.psds[cond][1]: f.write(repr(i) + ';') f.write('\n') for i in xrange(len(self.psds[cond][0])): if params['groupAverage']: #Group averages: if self.groups.has_key('freqs'): pass #print self.psds[cond][1][i] #self.groups['freqs'].append(self.\ # psds[cond][1][i]) else: #self.groups['freqs'] = [] self.groups['freqs'] = copy.deepcopy(self.\ psds[cond][1]) #groupName = 'ch' + self.raw.info['ch_names'][i]# + '_cond' + str(cond+1) if self.groups['conds'][cond].has_key( i): #ChannelGroup exists self.groups['conds'][cond][i].append(self.\ psds[cond][0][i]) else: #Create new entry to dictionary #self.keyMap[i] = 'ch' + self.raw.info['ch_names'][i] #self.keyMap[i] = groupName self.keyMap[i] = self.raw.info['ch_names'][i] self.groups['conds'][cond][i] = [] #self.groups['conds'][cond][i].append(self.\ # psds[cond][0][i]) arr = [] for j in self.psds[cond][0][i]: arr.append(j) self.groups['conds'][cond][i] = [np.array(arr)] #self.groups['conds'][cond][i] = copy.deepcopy(self.psds[cond][0][i]) if i in indices: if params['plotChannels']: print "Plotting individual channels..." pos = lout.pos.copy() ax = plt.axes(pos[i]) chFName = path + '/' + fName + '_cond' + \ str(cond+1) + '_channel' + \ self.raw.info['ch_names'][i] + \ '.' + params['format'] self.plotChannelPsds(i, chFName, channelColors, params['format'], params['dpi'], params['log']) f.write(repr(self.raw.info['ch_names'][i]) + '; ') for j in self.psds[cond][0][i]: f.write(repr(j) + '; ') f.write('\n') parent.updateUi() f.close() plt.close() print "Finished"
data_path = sample.data_path() raw_fname = data_path + "/MEG/sample/sample_audvis_filt-0-40_raw.fif" raw = fiff.Raw(raw_fname, preload=True) raw.filter(1, 20) picks = fiff.pick_types(raw.info, meg=True, exclude=[]) tmin, tmax = 0, 120 # use the first 120s of data fmin, fmax = 2, 20 # look at frequencies between 2 and 20Hz n_fft = 2048 # the FFT size (NFFT). Ideally a power of 2 psds, freqs = compute_raw_psd(raw, picks=picks, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax) psds = 10 * np.log10(psds) # scale to dB def my_callback(ax, ch_idx): """ This block of code is executed once you click on one of the channel axes in the plot. To work with the viz internals this function should only take two parameters, the axis and the channel or data index. """ ax.plot(freqs, psds[ch_idx], color="yellow") ax.set_xlabel = "Frequency (Hz)" ax.set_ylabel = "Power (dB)" for ax, idx in iter_topography(raw.info, on_pick=my_callback): ax.plot(psds[idx], color="yellow") plt.show()
raw.filter(1, 20) picks = fiff.pick_types(raw.info, meg=True, exclude=[]) tmin, tmax = 0, 120 # use the first 120s of data fmin, fmax = 2, 20 # look at frequencies between 2 and 20Hz n_fft = 2048 # the FFT size (NFFT). Ideally a power of 2 psds, freqs = compute_raw_psd(raw, picks=picks, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax) psds = 10 * np.log10(psds) # scale to dB def my_callback(ax, ch_idx): """ This block of code is executed once you click on one of the channel axes in the plot. To work with the viz internals this function should only take two parameters, the axis and the channel or data index. """ ax.plot(freqs, psds[ch_idx], color='yellow') ax.set_xlabel = 'Frequency (Hz)' ax.set_ylabel = 'Power (dB)' for ax, idx in iter_topography(raw.info, on_pick=my_callback): ax.plot(psds[idx], color='yellow') plt.show()
def SensorStatsPlot(condcomb, ListSubj, colors): #ListSubj = ('sd130343','cb130477' , 'rb130313', 'jm100109', # 'sb120316', 'tk130502','lm130479' , 'ms130534', 'ma100253', 'sl130503', # 'mb140004','mp140019' , 'dm130250', 'hr130504', 'wl130316', 'rl130571') ListSubj = ('sd130343', 'cb130477', 'rb130313', 'jm100109', 'tk130502', 'lm130479', 'ms130534', 'ma100253', 'sl130503', 'mb140004', 'mp140019', 'dm130250', 'hr130504', 'rl130571') condcomb = ('EtPast', 'EtPre', 'EtFut') colors = ((1, 0, 0), (1, 0.37, 0.15), (1, 0.75, 0.3)) #ipython --pylab import mne import numpy as np import matplotlib.pyplot as plt import itertools from mne.stats import spatio_temporal_cluster_test from mne.channels import read_ch_connectivity from scipy import stats as stats from mne.viz import plot_evoked_topo, iter_topography import os os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON') os.environ['MNE_ROOT'] = '/neurospin/local/mne' wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/" # load FieldTrip neighbor definition to setup sensor connectivity neighbor_file_mag = '/neurospin/local/fieldtrip/template/neighbours/neuromag306mag_neighb.mat' # mag neighbor_file_grad = '/neurospin/local/fieldtrip/template/neighbours/neuromag306planar_neighb.mat' # grad neighbor_file_eeg = '/neurospin/local/fieldtrip/template/neighbours/easycap64ch-avg_neighb.mat' # eeg connectivity, ch_names = mne.channels.read_ch_connectivity( neighbor_file_eeg, picks=range(60)) connectivity_mag, ch_names_mag = read_ch_connectivity(neighbor_file_mag) connectivity_grad, ch_names_grad = read_ch_connectivity(neighbor_file_grad) connectivity_eeg, ch_names_eeg = read_ch_connectivity(neighbor_file_eeg) # evoked 0 to get the size of the matrix fname0 = (wdir + ListSubj[0] + "/mne_python/MEEG_" + condcomb[0] + "_" + ListSubj[0] + "-ave.fif") evoked0 = mne.read_evokeds(fname0, condition=0, baseline=(-0.2, 0)) sensordatamat_meg_mag = np.empty( [len(condcomb), len(ListSubj), 102, evoked0.data.shape[1]]) sensordatamat_meg_grad = np.empty( [len(condcomb), len(ListSubj), 204, evoked0.data.shape[1]]) sensordatamat_meg_eeg = np.empty( [len(condcomb), len(ListSubj), 60, evoked0.data.shape[1]]) # define statistical threshold p_threshold = 0.05 t_threshold = -stats.distributions.t.ppf(p_threshold / 2., len(ListSubj) - 1) # compute grand averages GDAVGmag, GDAVGgrad, GDAVGeeg = [], [], [] sensordatamat_meg_mag = np.empty( (len(condcomb), len(ListSubj), 102, len(evoked0.times))) sensordatamat_meg_grad = np.empty( (len(condcomb), len(ListSubj), 204, len(evoked0.times))) #sensordatamat_eeg = np.empty((len(condcomb),len(ListSubj),60 ,len(evoked0.times))) for c in range(len(condcomb)): evoked2plotmag, evoked2plotgrad, evoked2ploteeg = [], [], [] for i in range(len(ListSubj)): fname_ave_meg = (wdir + ListSubj[i] + "/mne_python/MEEG_" + condcomb[c] + "_" + ListSubj[i] + "-ave.fif") tmp_evoked_meg = mne.read_evokeds(fname_ave_meg, condition=0, baseline=(-0.2, 0)) evoked2plotmag.append(tmp_evoked_meg.pick_types('mag')) sensordatamat_meg_mag[c, i, ::, ::] = tmp_evoked_meg.data tmp_evoked_meg = mne.read_evokeds(fname_ave_meg, condition=0, baseline=(-0.2, 0)) evoked2plotgrad.append(tmp_evoked_meg.pick_types('grad')) sensordatamat_meg_grad[c, i, ::, ::] = tmp_evoked_meg.data #tmp_evoked_meg = mne.read_evokeds(fname_ave_meg, condition=0, baseline=(-0.2, 0)) #evoked2ploteeg.append(tmp_evoked_meg.pick_types('eeg')) #sensordatamat_eeg[c,i,::,::] = tmp_evoked_meg.data GDAVGmag.append(mne.grand_average(evoked2plotmag)) GDAVGgrad.append(mne.grand_average(evoked2plotgrad)) #GDAVGeeg.append(mne.grand_average(evoked2ploteeg)) # plot topomaps of grand_averages for ax, idx in iter_topography(GDAVGmag[0].info, fig_facecolor='black', axis_facecolor='black', axis_spinecolor='k'): for c, cond in enumerate(condcomb): ax.plot(GDAVGmag[c].data[idx], color=colors[c]) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + "_".join([str(cond) for cond in condcomb]) + "_GDAVG_mags.eps", format='eps', dpi=1500) plt.close() mne.viz.plot_topo(GDAVGmag, color=['r', 'orange', 'y']) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + "_".join([str(cond) for cond in condcomb]) + "_bis_GDAVG_mags.eps", format='eps', dpi=1500) plt.close() for ax, idx in iter_topography(GDAVGgrad[0].info, fig_facecolor='black', axis_facecolor='black', axis_spinecolor='k'): for c, cond in enumerate(condcomb): ax.plot(GDAVGgrad[c].data[idx], color=colors[c]) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + "_".join([str(cond) for cond in condcomb]) + "_GDAVG_grads.eps", format='eps', dpi=1500) plt.close() mne.viz.plot_topo(GDAVGmag, color=['r', 'orange', 'y']) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + "_".join([str(cond) for cond in condcomb]) + "_bis_GDAVG_grads.eps", format='eps', dpi=1500) plt.close() times = np.arange(-0.1, 0.9, 0.05) for c in range(len(condcomb)): GDAVGmag[c].plot_topomap(times, ch_type='mag', vmin=-40, vmax=40, average=0.05) plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + str(condcomb[c]) + "_GDAVG_mags.eps", format='eps', dpi=1500) plt.close() GDAVGgrad[c].plot_topomap(times, ch_type='grad', vmin=-10, vmax=10, average=0.05) plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + str(condcomb[c]) + "_GDAVG_grads.eps", format='eps', dpi=1500) plt.close() for combination in itertools.combinations(range(3), 2): tmp = [] tmp = GDAVGmag[combination[0]] - GDAVGmag[combination[1]] tmp.plot_topomap(times, ch_type='mag', vmin=-15, vmax=15, average=0.05) plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + str(condcomb[combination[0]]) + '_minus_' + str(condcomb[combination[1]]) + "_GDAVG_mags.eps", format='eps', dpi=1000) plt.close() tmp = [] tmp = GDAVGgrad[combination[0]] - GDAVGgrad[combination[1]] tmp.plot_topomap(times, ch_type='grad', vmin=0, vmax=2, average=0.05) plt.savefig( "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/decoding_context_yousra/TOPOPLOT_ERF/" + str(condcomb[combination[0]]) + '_minus_' + str(condcomb[combination[1]]) + "_GDAVG_grads.eps", format='eps', dpi=1000) plt.close() allcond_meg_mag = [ np.transpose(x, (0, 2, 1)) for x in sensordatamat_meg_mag ] allcond_meg_grad = [ np.transpose(x, (0, 2, 1)) for x in sensordatamat_meg_grad ] ############################################################################### t_threshold = -stats.distributions.t.ppf(0 / 2, len(ListSubj) - 1) T_obs, clusters, cluster_p_values, HO = spatio_temporal_cluster_test( allcond_meg_mag, n_permutations=1024, threshold=t_threshold, tail=0, n_jobs=4, connectivity=connectivity_mag) t_threshold = -stats.distributions.t.ppf(0 / 2, len(ListSubj) - 1) T_obs, clusters, cluster_p_values, HO = spatio_temporal_cluster_test( allcond_meg_grad, n_permutations=1024, threshold=t_threshold, tail=0, n_jobs=4, connectivity=connectivity_grad)