示例#1
0
 def apply_foward_model(self, x):
     out = []
     for z in x:
         info = mne.io.read_info(self.raw_fname)
         stc = mne.SourceEstimate(z.cpu().detach().numpy(),
                                  self.vertices,
                                  tmin=0.,
                                  tstep=self.time_step)
         # print("STC", stc)
         # print("Info", info)
         leadfield = mne.apply_forward(self.fwd_fixed, stc,
                                       info).data[0:self.num_nodes]
         # leadfield = torch.from_numpy(leadfield)
         # leadfield = leadfield.transpose(0,1)
         # print("YOUYOUYOUYOUY")
         # array = leadfield.to_data_frame().values
         # print("array", leadfield.shape)
         out += [leadfield]
     out = np.asarray(out)
     out = torch.from_numpy(out).transpose(1, 2)
     if x.is_cuda:
         out = out.type(torch.cuda.FloatTensor)
     else:
         out = out.type(torch.FloatTensor)
     # print("OUTOUTOUT", out.shape)
     # (n sensors, n samples)
     return out
示例#2
0
def simu_data(evoked, forward, noise_cov, n_dipoles, times, nave=1):
    """Simulate an evoked dataset with 2 sources.

    One source is put in each hemisphere.
    """
    # Generate the two dipoles data
    mu, sigma = 0.1, 0.005
    s1 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(times - mu) ** 2 /
                                                   (2 * sigma ** 2))

    mu, sigma = 0.075, 0.008
    s2 = -1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(times - mu) ** 2 /
                                                    (2 * sigma ** 2))
    data = np.array([s1, s2]) * 1e-9

    src = forward['src']
    rng = np.random.RandomState(42)

    rndi = rng.randint(len(src[0]['vertno']))
    lh_vertno = src[0]['vertno'][[rndi]]

    rndi = rng.randint(len(src[1]['vertno']))
    rh_vertno = src[1]['vertno'][[rndi]]

    vertices = [lh_vertno, rh_vertno]
    tmin, tstep = times.min(), 1 / evoked.info['sfreq']
    stc = mne.SourceEstimate(data, vertices=vertices, tmin=tmin, tstep=tstep)

    sim_evoked = mne.simulation.simulate_evoked(forward, stc, evoked.info,
                                                noise_cov, nave=nave,
                                                random_state=rng)

    return sim_evoked, stc
示例#3
0
def run(mmvt):
    mu = mmvt.utils
    stc_fname = mmvt.coloring.get_stc_full_fname()
    if not op.isfile(stc_fname):
        print('Can\'t find the selected stc!')
        return
    stc = mne.read_source_estimate(stc_fname)
    data = {}
    if mmvt.play.get_play_to() > len(stc.times) - 1:
        mmvt.play.set_play_to(len(stc.times) - 1)
    time = np.arange(mmvt.play.get_play_from(), mmvt.play.get_play_to(),
                     mmvt.play.get_play_dt())
    data['rh'] = np.zeros((stc.rh_data.shape[0], 1))
    data['lh'] = np.zeros((stc.lh_data.shape[0], 1))
    threshold = mmvt.coloring.get_lower_threshold()
    for t_ind, t in tqdm(enumerate(time)):
        for hemi in mu.HEMIS:
            hemi_data = stc.rh_data[:,
                                    t_ind] if hemi == 'rh' else stc.lh_data[:,
                                                                            t_ind]
            verts = np.where(hemi_data >= threshold)[0]
            data[hemi][verts, 0] = time[t_ind]

    data = np.concatenate([data['lh'], data['rh']])
    vertices = [stc.lh_vertno, stc.rh_vertno]
    stc = mne.SourceEstimate(data, vertices, 0, 0, subject=mu.get_user())
    mmvt.colorbar.lock_colorbar_values(False)
    mmvt.coloring.clear_colors()
    mmvt.coloring.plot_stc(stc, bpy.context.scene.frame_current, 0, time[-1],
                           time[0])
    mmvt.coloring.set_lower_threshold(
        threshold)  # Set threshold to its previous value
示例#4
0
文件: utils.py 项目: massich/groupmne
def make_stc(data, vertices, tstep=0.1, tmin=0., subject=None):
    """Create stc from data."""
    if not isinstance(vertices, list):
        vertices = [vertices, []]
    n_sources_l, n_sources_r = [len(v) for v in vertices]
    assert data.shape[0] == n_sources_l + n_sources_r
    data_l = data[:n_sources_l]
    data_r = data[n_sources_l:]
    data_lr = [data_l, data_r]
    ns = [n_sources_l, n_sources_r]
    data = []
    for i, (v, n) in enumerate(zip(vertices, ns)):
        if n:
            order = np.argsort(v)
            data.append(data_lr[i][order])
            vertices[i] = np.asarray(vertices[i][order])
    if n_sources_l * n_sources_r:
        data = np.concatenate(data)
    else:
        data = np.array(data[0])
    stc = mne.SourceEstimate(data,
                             vertices,
                             tstep=tstep,
                             tmin=tmin,
                             subject=subject)
    return stc
示例#5
0
def _bias_params(evoked, noise_cov, fwd):
    evoked.pick_types(meg=True, eeg=True, exclude=())
    # restrict to limited set of verts (small src here) and one hemi for speed
    vertices = [fwd['src'][0]['vertno'].copy(), []]
    stc = mne.SourceEstimate(np.zeros((sum(len(v) for v in vertices), 1)),
                             vertices, 0, 1)
    fwd = mne.forward.restrict_forward_to_stc(fwd, stc)
    assert fwd['sol']['row_names'] == noise_cov['names']
    assert noise_cov['names'] == evoked.ch_names
    evoked = mne.EvokedArray(fwd['sol']['data'].copy(), evoked.info)
    data_cov = noise_cov.copy()
    data = fwd['sol']['data'] @ fwd['sol']['data'].T
    data *= 1e-14  # 100 nAm at each source, effectively (1e-18 would be 1 nAm)
    # This is rank-deficient, so let's make it actually positive semidefinite
    # by regularizing a tiny bit
    data.flat[::data.shape[0] + 1] += mne.make_ad_hoc_cov(evoked.info)['data']
    # Do our projection
    proj, _, _ = mne.io.proj.make_projector(data_cov['projs'],
                                            data_cov['names'])
    data = proj @ data @ proj.T
    data_cov['data'][:] = data
    assert data_cov['data'].shape[0] == len(noise_cov['names'])
    want = np.arange(fwd['sol']['data'].shape[1])
    if not mne.forward.is_fixed_orient(fwd):
        want //= 3
    return evoked, fwd, noise_cov, data_cov, want
示例#6
0
文件: utils.py 项目: mmagnuski/borsar
def _check_stc(clst):
    '''Make sure Clusters has a list of mne.SourceEstimate in stc attribute.'''
    import mne
    if clst.stc is None:
        vertices = clst.dimcoords[0]
        if vertices is None:
            vert = [clst.src[0]['vertno'], clst.src[1]['vertno']]
        else:
            # this should use _to_data_vert when it is moved from DiamSar
            lh, rh = [vertices[hemi] for hemi in ['lh', 'rh']]
            vert = [clst.src[0]['vertno'][lh], clst.src[1]['vertno'][rh]]

        assert clst.dimnames.index('vert') == 0

        tmin, tstep = 1., 1.
        if len(clst.dimnames) > 1:
            data_single = clst.stat[:, [0]]
        else:
            data_single = clst.stat[:, np.newaxis].copy()

        clst.stc = mne.SourceEstimate(data_single,
                                      vertices=vert,
                                      tmin=tmin,
                                      tstep=tstep,
                                      subject=clst.subject)
示例#7
0
def gen_stupid_gamma_signal(ch_names, hemi='rh'):
    ivs = InvasiveSignal()
    ivs.ch_names = ch_names

    if hemi == 'rh':
        vertnos = [np.array(()), np.arange(len(ch_names))]
    else:
        vertnos = [np.arange(len(ch_names)), np.array(())]

    from scipy.stats import gamma

    tsignal = np.zeros((len(ch_names), 100))
    for i, ch_name in enumerate(ch_names):
        scale_param = np.random.randint(5, 15)
        multi_param = np.random.randint(1, 4)
        min_param = np.random.randint(10)
        max_param = np.random.randint(10, 15)

        #import pdb
        #pdb.set_trace()

        tsignal[i, :] = np.array([
            gamma.pdf(j, scale_param) * multi_param
            for j in np.linspace(min_param, max_param, 100)
        ])

    stc = mne.SourceEstimate(tsignal,
                             tmin=1,
                             tstep=1,
                             vertices=vertnos,
                             subject='woethiezluok')

    ivs.mne_source_estimate = stc

    return ivs
示例#8
0
def mne_python():
    subjects_dir = data_path + '/subjects'

    # Read data
    evoked = mne.read_evokeds(fname_evoked,
                              condition='Left Auditory',
                              baseline=(None, 0))
    fwd = mne.read_forward_solution(fname_fwd)
    cov = mne.read_cov(fname_cov)

    inv = make_inverse_operator(evoked.info,
                                fwd,
                                cov,
                                loose=0.,
                                depth=0.8,
                                verbose=True)

    snr = 3.0
    lambda2 = 1.0 / snr**2
    kwargs = dict(initial_time=0.08,
                  hemi='both',
                  subjects_dir=subjects_dir,
                  size=(600, 600))

    stc = abs(apply_inverse(evoked, inv, lambda2, 'MNE', verbose=True))
    stc = mne.SourceEstimate(stc.data * 1e10,
                             stc.vertices,
                             stc.tmin,
                             stc.tstep,
                             subject='sample')
    stc.save(data_path + '/MEG/sample/sample_audvis_MNE')
示例#9
0
def gen_stupid_sinusoidal_signal(ch_names, hemi='rh'):
    ivs = InvasiveSignal()
    ivs.ch_names = ch_names

    if hemi == 'rh':
        vertnos = [np.array(()), np.arange(len(ch_names))]
    else:
        vertnos = [np.arange(len(ch_names)), np.array()]

    tsignal = np.zeros((len(ch_names), 100))
    for i, ch_name in enumerate(ch_names):

        amp = np.random.random() * .5
        freqp = np.random.random() * (5 - .2) + .2
        phasep = np.random.random() * 2 * np.pi
        funcp = [np.sin, np.cos][int(np.random.randint(2))]

        tsignal[i, :] = np.array([
            amp * funcp(2 * np.pi * freqp * j + phasep) + .5
            for j in np.arange(100)
        ])

    stc = mne.SourceEstimate(tsignal,
                             tmin=1,
                             tstep=1,
                             vertices=vertnos,
                             subject='woethiezluok')

    ivs.mne_source_estimate = stc

    return ivs
def normalise_stc(stc):
    """ Normalise data in STC object to absolute maximum.

    Parameters
    ----------
    stc: SourceEstimate
        The data to normalise.

    Returns
    -------
        stc_norm: Source estimate.
        STC with data normalised to absolute maximum.
    """

    data = stc.data

    data = data / np.absolute(data).max()

    # convert normalised data to source estimate
    stc_norm = mne.SourceEstimate(data,
                                  stc.vertices,
                                  tmin=stc.tmin,
                                  tstep=stc.tstep)

    return stc_norm
示例#11
0
def add_stcs(stc1, stc2):
    """Adds two SourceEstimates together, allowing for different vertices."""
    vertices = [
        np.union1d(stc1.vertices[0], stc2.vertices[0]),
        np.union1d(stc1.vertices[1], stc2.vertices[1])
    ]
    assert stc1.data.shape[1] == stc2.data.shape[1]
    assert stc1.tmin == stc2.tmin
    assert stc1.tstep == stc2.tstep

    data = np.zeros((len(vertices[0]) + len(vertices[1]), stc1.data.shape[1]))
    i = 0

    # Left hemisphere
    for vert in vertices[0]:
        if vert in stc1.vertices[0]:
            data[[i]] += stc1.lh_data[stc1.vertices[0] == vert]
        if vert in stc2.vertices[0]:
            data[[i]] += stc2.lh_data[stc2.vertices[0] == vert]
        i += 1

    # Right hemisphere
    for vert in vertices[1]:
        if vert in stc1.vertices[1]:
            data[[i]] += stc1.rh_data[stc1.vertices[1] == vert]
        if vert in stc2.vertices[1]:
            data[[i]] += stc2.rh_data[stc2.vertices[1] == vert]
        i += 1

    return mne.SourceEstimate(data, vertices, tmin=stc1.tmin, tstep=stc1.tstep)
示例#12
0
def _stc_from_array(data, tr, filename, hemi=None, tmin=0):
    #TODO allow bihemi stc
    nvert, ntimes = data.shape

    if hemi == None:
        #try to read hemi from filename
        lh = (filename.find('lh') != -1)
        rh = (filename.find('rh') != -1)

        if lh and not rh:
            hemi = 'lh'
        if rh and not lh:
            hemi = 'rh'

    if hemi not in ('lh', 'rh'):
        error_dialog('Correct hemisphere not provided and could not figure it'
                     ' out')

    if hemi == 'lh':
        vertices = [np.arange(nvert), np.array(())]
    else:
        vertices = [np.array(()), np.arange(nvert)]

    stc = mne.SourceEstimate(data, vertices=vertices, tmin=tmin, tstep=tr)

    return stc
示例#13
0
def stc_from_fiff(fiff_file, names=None):
    '''
    Creates a source estimate from the sensor space channels in a fiff file
    '''
    ra = mne.io.Raw(fiff_file)

    tmin = ra.index_as_time(0)
    tstep = 1 / ra.info['sfreq']

    if names is not None:
        vertnos = np.squeeze([
            np.where(np.array(ra.ch_names) == name)
            for name in np.intersect1d(ra.ch_names, names)
        ])

    else:
        #use all names
        vertnos = np.arange(len(ra.ch_names))

    ordering_names = np.array(ra.ch_names)
    ordering_names[np.setdiff1d(np.arange(len(ra.ch_names)), vertnos)] = 'del'

    #convert to 'delete' without messing with datatypes
    ordering_names = np.array(
        map(lambda x: 'delete' if x == 'del' else x, ordering_names.tolist()))

    #by arbitrary choice we use the RH no matter where are the electrodes
    stc = mne.SourceEstimate(ra[:][0][np.sort(vertnos)],
                             vertices=[np.array(()),
                                       np.sort(vertnos)],
                             tmin=tmin,
                             tstep=tstep)

    return stc, ordering_names
示例#14
0
def _simulate_data(fwd, idx):  # Somewhere on the frontal lobe by default
    """Simulate an oscillator on the cortex."""
    source_vertno = fwd['src'][0]['vertno'][idx]

    sfreq = 50.  # Hz.
    times = np.arange(10 * sfreq) / sfreq  # 10 seconds of data
    signal = np.sin(20 * 2 * np.pi * times)  # 20 Hz oscillator
    signal[:len(times) // 2] *= 2  # Make signal louder at the beginning
    signal *= 1e-9  # Scale to be in the ballpark of MEG data

    # Construct a SourceEstimate object that describes the signal at the
    # cortical level.
    stc = mne.SourceEstimate(
        signal[np.newaxis, :],
        vertices=[[source_vertno], []],
        tmin=0,
        tstep=1 / sfreq,
        subject='sample',
    )

    # Create an info object that holds information about the sensors
    info = mne.create_info(fwd['info']['ch_names'], sfreq, ch_types='grad')
    info.update(fwd['info'])  # Merge in sensor position information
    # heavily decimate sensors to make it much faster
    info = mne.pick_info(info, np.arange(info['nchan'])[::5])
    fwd = mne.pick_channels_forward(fwd, info['ch_names'])

    # Run the simulated signal through the forward model, obtaining
    # simulated sensor data.
    raw = mne.apply_forward_raw(fwd, stc, info)

    # Add a little noise
    random = np.random.RandomState(42)
    noise = random.randn(*raw._data.shape) * 1e-14
    raw._data += noise

    # Define a single epoch (weird baseline but shouldn't matter)
    epochs = mne.Epochs(raw, [[0, 0, 1]],
                        event_id=1,
                        tmin=0,
                        tmax=raw.times[-1],
                        baseline=(0., 0.),
                        preload=True)
    evoked = epochs.average()

    # Compute the cross-spectral density matrix
    csd = csd_morlet(epochs, frequencies=[10, 20], n_cycles=[5, 10], decim=5)

    labels = mne.read_labels_from_annot('sample',
                                        hemi='lh',
                                        subjects_dir=subjects_dir)
    label = [
        label for label in labels if np.in1d(source_vertno, label.vertices)[0]
    ]
    assert len(label) == 1
    label = label[0]
    vertices = np.intersect1d(label.vertices, fwd['src'][0]['vertno'])
    source_ind = vertices.tolist().index(source_vertno)
    assert vertices[source_ind] == source_vertno
    return epochs, evoked, csd, source_vertno, label, vertices, source_ind
示例#15
0
 def generate_eeg(self, source_index):
     stc = mne.SourceEstimate(self.preloaded_examples_source[source_index],
                              self.vertices,
                              tmin=0.,
                              tstep=1 / 250)
     leadfield = mne.apply_forward(self.fwd_fixed, stc,
                                   self.info).data / 1e-9
     return list(leadfield[:self.num_channels])
示例#16
0
def get(files):
    stcs = reduce(lambda x, y: x + y,
                  [mne.read_source_estimate(s) for s in files])
    if stcs.times[0] <= -1.5:
        times = stcs.times + 0.75
        stcs = mne.SourceEstimate(stcs.data, stcs.vertices, times[0],
                                  np.diff(times)[0])
    return stcs
示例#17
0
    def subject_Ttest(X, Y, forward, stc, CondComb):

        # Compute statistic
        np.random.seed(42)

        # compute subject-by-subject difference
        X = X[0:(len(X) / 2), :, :] - X[len(X) / 2:len(X), :, :]

        # smooth the data (optional)
        #fsave_vertices = [np.arange(10242), np.arange(10242)]
        #morph_mat = compute_morph_matrix('sample', 'fsaverage', sample_vertices,
        #                                 fsave_vertices, 20, subjects_dir)
        #n_vertices_fsave = morph_mat.shape[0]

        # optional: restrict computation to temporal window of interest
        #lower_bound = np.where(stc0.times >= 0.4)[0][0]
        #upper_bound = np.where(stc0.times >= 0.9)[0][0]
        #X = X[:,lower_bound:upper_bound,:]

        con = mne.spatial_src_connectivity(forward['src'])
        #con = spatial_tris_connectivity(grade_to_tris(5))
        X = np.transpose(X, [0, 2, 1])

        p_threshold = 0.05
        t_threshold = -stats.distributions.t.ppf(p_threshold / 2.,
                                                 X.shape[0] - 1)
        n_permutations = 1024

        T_obs, clusters, cluster_p_values, H0 = mne.stats.spatio_temporal_cluster_1samp_test(
            X,
            connectivity=con,
            n_jobs=1,
            threshold=t_threshold,
            n_permutations=n_permutations,
            verbose=True)

        # Replace the values & # save the stc
        tmp = np.transpose(np.mean(X, axis=0), [1, 0])
        fsave_vertices = [
            np.arange(len(stc.vertices[0])),
            np.arange(len(stc.vertices[1]))
        ]
        stc_Diff = mne.SourceEstimate(tmp, fsave_vertices, stc.tmin, stc.tstep)
        PlotDir = []
        PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/' + subject +
                   '/mne_python/STCS_diff/fromsingle_' + CondComb[0] + '-' +
                   CondComb[1])

        if not os.path.exists(PlotDir):
            os.makedirs(PlotDir)

        stc_Diff.save(PlotDir + '/' + modality + '_' + Method + '_' + subject +
                      '_' + CondComb[0] + '-' + CondComb[1] + '_' +
                      '_ico-5-fwd-fsaverage-' + '.stc')

        return T_obs, clusters, cluster_p_values, H0
示例#18
0
def _simulate_data(fwd_fixed, source_vertno1, source_vertno2):
    """Simulate two oscillators on the cortex."""

    sfreq = 50.  # Hz.
    base_freq = 10
    t_rand = 0.001
    std = 0.1
    times = np.arange(10. * sfreq) / sfreq  # 10 seconds of data
    n_times = len(times)
    # Generate an oscillator with varying frequency and phase lag.
    iflaw = base_freq / sfreq + t_rand * np.random.randn(n_times)
    signal1 = np.exp(1j * 2.0 * np.pi * np.cumsum(iflaw))
    signal1 *= np.conj(signal1[0])
    signal1 = signal1.real

    # Add some random fluctuations to the signal.
    signal1 += std * np.random.randn(n_times)
    signal1 *= 1e-7

    # Make identical signal
    signal2 = signal1.copy()

    # Add random fluctuations
    signal1 += 1e-8 * np.random.randn(len(times))
    signal2 += 1e-8 * np.random.randn(len(times))

    # Construct a SourceEstimate object
    stc = mne.SourceEstimate(
        np.vstack((signal1[np.newaxis, :], signal2[np.newaxis, :])),
        vertices=[np.array([source_vertno1]), np.array([source_vertno2])],
        tmin=0,
        tstep=1 / sfreq,
        subject='sample',
    )

    # Create an info object that holds information about the sensors
    info = mne.create_info(fwd_fixed['info']['ch_names'], sfreq,
                           ch_types='grad')
    info.update(fwd_fixed['info'])  # Merge in sensor position information

    # Simulated sensor data.
    raw = mne.apply_forward_raw(fwd_fixed, stc, info)

    # Add noise
    noise = random.randn(*raw._data.shape) * 1e-14
    raw._data += noise

    # Define a single epoch
    epochs = mne.Epochs(raw, np.array([[0, 0, 1]]), event_id=1, tmin=0,
                        tmax=raw.times[-1], preload=True, baseline=(0, 0))

    # Compute the cross-spectral density matrix
    csd = csd_morlet(epochs, frequencies=[10, 20])

    return csd
示例#19
0
def load_data(stcs1_fname, stcs2_fname, dec):
    stcs1 = [mne.SourceEstimate(fname) for fname in stcs1_fname]
    stcs2 = [mne.SourceEstimate(fname) for fname in stcs2_fname]

    mask = label_mask(stcs1[0], label_list)
    print mask.shape
    #mask_neg = ~mask

	#This is just resampling in time, not space
    def resample_stc(stc, dec):
        """Resample stc inplace"""
        stc.data = stc.data[:,::dec].astype(np.float)
        stc.tstep *= dec
        stc.times = stc.times[::dec]
	
    if dec is not None:
        for stc in stcs1 + stcs2:
            resample_stc(stc, dec=dec)
            stc.crop(0.1, None)  #cropping the time-window for faster runtime

    def average_stcs(stcs):
        mean_stc = copy.deepcopy(stcs[0])
        times = mean_stc.times
        n_sources, n_times = mean_stc.data.shape
        X = np.empty((len(stcs), n_sources, n_times))
        for i, stc in enumerate(stcs):
            if len(times) == len(stc.times):
                X[i] = stc.data
        mean_stc.data = np.mean(X, axis=0)
        return mean_stc, X

	#X1, X2 are the full time,vertices,subject matrices; mean_stc1 and mean_stc2 are the grand-avgs
    mean_stc1, X1 = average_stcs(stcs1)
    mean_stc2, X2 = average_stcs(stcs2)
    
    # apply mask by setting values outside label mask to 0.
    mean_stc1.data[mask == False] = 0.
    mean_stc2.data[mask == False] = 0.
    X1[:, mask == False, :] = 0.
    X2[:, mask == False, :] = 0.
    return mean_stc1, X1, mean_stc2, X2
示例#20
0
文件: epilepsy.py 项目: keshava/mmvt
def plot_stc_over_time():
    from collections import defaultdict
    mmvt, mu = _mmvt(), _mmvt().utils
    stc = coloring_panel.stc
    if stc is None:
        print('No stc was selected!')
        return
    data, valid_verts = {}, defaultdict(list)
    if mmvt.play.get_play_to() > len(stc.times) - 1:
        mmvt.play.set_play_to(len(stc.times) - 1)
    time = np.arange(mmvt.play.get_play_from(), mmvt.play.get_play_to() + 1)
    stc = mne.SourceEstimate(stc.data[:, time[0]:time[-1] + 1], stc.vertices, 0, stc.tstep, subject=mu.get_user())
    # stc = coloring_panel.smooth_map.apply(stc)
    stc = mmvt.coloring.apply_smooth_map(stc)
    t0 = time[0]
    time = time - time[0]
    data['rh'] = np.ones((stc.rh_data.shape[0], 1)) * -1
    data['lh'] = np.ones((stc.lh_data.shape[0], 1)) * -1
    threshold = mmvt.coloring.get_lower_threshold()
    for t in tqdm(time[::-1]):
        for hemi in mu.HEMIS:
            hemi_data = stc.rh_data[:, t] if hemi == 'rh' else stc.lh_data[:, t]
            verts = np.where(hemi_data >= threshold)[0]
            data[hemi][verts, 0] = t + t0

    data = np.concatenate([data['lh'], data['rh']])
    stc = mne.SourceEstimate(data, stc.vertices, 0, 0, subject=mu.get_user())
    mmvt.colorbar.lock_colorbar_values(False)
    data_max, data_min = time[-1] + t0, time[0] + t0
    mmvt.colorbar.set_colorbar_max_min(data_max, data_min, force_update=True)
    mmvt.colorbar.set_colorbar_title('MEG')
    mmvt.colorbar.set_colormap('YlOrRd')

    mmvt.coloring.clear_colors()
    mmvt.coloring.plot_stc(
        stc, 0, 0, data_max, data_min, use_abs=False, bigger_or_equal=True)
    # mmvt.coloring.set_lower_threshold(threshold) # Set threshold to its previous value
    if bpy.context.scene.epilepsy_save_stc_over_time:
        stc_output_fname = '{}_{}_{}'.format(get_stc_fname()[:-len('-rh.stc')], data_min, data_max)
        print('Saving stc over time to: {}'.format(stc_output_fname))
        stc.save(stc_output_fname)
示例#21
0
def _stc_from_bihemi_array(lh_data, rh_data, tr, filename, tmin=0):
    lh_nvert, lh_ntimes = lh_data.shape
    rh_nvert, rh_ntimes = rh_data.shape

    if lh_ntimes != rh_ntimes:
        error_dialog("Inconsistent timing across hemispheres")

    data = np.vstack((lh_data, rh_data))
    vertices = [np.arange(lh_nvert), np.arange(rh_nvert)]

    stc = mne.SourceEstimate(data, vertices=vertices, tmin=tmin, tstep=tr)

    return stc
示例#22
0
def localize_epochs(epochs, fwd, reg=0):
    ''' Returns a list of Sourceestimates, one per Epoch '''

    cov = mne.compute_covariance(epochs)
    weights = calculate_weights(fwd, cov, reg=reg)
    stcs = []
    print 'Multiplying data by beamformer weights...'
    for epoch in epochs:
        sol = np.dot(weights, epoch)
        src = mne.SourceEstimate(sol, [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']], epochs.tmin, epochs.times[1] - epochs.times[0])
        stcs.append(src)

    return stcs
示例#23
0
def _calc_source_ttest(subject):
    fol = op.join(MMVT_DIR, subject, 'meg')
    output_fname = op.join(fol, 'dSPM_mean_flip_vertices_power_spectrum_stat')
    if utils.both_hemi_files_exist('{}-{}.stc'.format(
            output_fname, '{hemi}')) and not args.overwrite:
        print('{} already exist'.format(output_fname))
        return True
    file_name = '{cond}_dSPM_mean_flip_vertices_power_spectrum.pkl'
    if not all([
            op.isfile(op.join(fol, file_name.format(cond=cond.lower())))
            for cond in MSIT_CONDS
    ]):
        print('No stc files for both conditions!')
        return False
    vertices_data = {}
    try:
        for cond in MSIT_CONDS:
            vertices_data[cond], freqs = utils.load(
                op.join(fol, file_name.format(cond=cond.lower())))
    except:
        print('Can\'t read {}'.format(file_name.format(cond=cond.lower())))
        return False
    pvals, vertno = {}, {}
    for hemi in utils.HEMIS:
        vertices_inds = {}
        pvals[hemi] = np.zeros(
            (len(vertices_data[MSIT_CONDS[0]][hemi].keys()), len(freqs)))
        for cond in MSIT_CONDS:
            vertices_inds[cond] = np.array(
                sorted(list(vertices_data[cond][hemi].keys())))
        if not np.all(
                vertices_inds[MSIT_CONDS[0]] == vertices_inds[MSIT_CONDS[1]]):
            raise Exception('Not the same vertices!')
        vertno[hemi] = vertices_inds[MSIT_CONDS[0]]
        params = [(vert_ind, vertices_data[MSIT_CONDS[0]][hemi][vert], vertices_data[MSIT_CONDS[1]][hemi][vert], len(freqs)) \
            for vert_ind, vert in enumerate(vertices_data[MSIT_CONDS[0]][hemi].keys())]
        results = utils.run_parallel(calc_vert_pvals, params, args.n_jobs)
        for vert_pvals, vert_ind in results:
            pvals[hemi][vert_ind, :] = vert_pvals

    data = np.concatenate([pvals['lh'], pvals['rh']])
    vertices = [vertno['lh'], vertno['rh']]
    stc_pvals = mne.SourceEstimate(data,
                                   vertices,
                                   freqs[0],
                                   freqs[1] - freqs[0],
                                   subject=subject)
    print('Writing to {}'.format(output_fname))
    stc_pvals.save(output_fname)
示例#24
0
def get_stc(labels, data, tmin=0, tstep=1):
    stc_vertices = [np.uint32(np.arange(10242)), np.uint32(np.arange(10242))]

    if data.ndim == 1:
        stc_data = np.ones((20484, 1), dtype=np.float32)
    else:
        stc_data = np.ones((20484, data.shape[1]), dtype=np.float32)

    stc = mne.SourceEstimate(stc_data,
                             vertices=stc_vertices,
                             tmin=tmin,
                             tstep=tstep,
                             subject='fsaverage')
    stc_new = labels2stc(labels, data, stc)
    return stc_new
示例#25
0
def save_stcs(src_df, measure='tval'):
    for r_name in src_df.columns.levels[1]:
        data = src_df.loc(axis=1)[measure, r_name].reset_index(level='time')
        data = data.pivot(columns='time')
        stc = mne.SourceEstimate(
            data.values,
            vertices=[
                data.loc['lh'].index.values, data.loc['rh'].index.values
            ],
            tmin=data.columns.levels[2][0] / 1000.,
            tstep=np.diff(data.columns.levels[2][:2])[0] / 1000,
            subject='fsaverage')

        stc_file = '{}_{}_{}'.format(file[:-3], measure, r_name)
        stc.save(stc_file)
def test_morph_data():
    """Test morphing of data
    """
    import mne
    subject_from = 'sample'
    subject_to = 'morph'
    fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg')
    stc_from = mne.SourceEstimate(fname)
    stc_to = mne.morph_data(subject_from, subject_to, stc_from, 3)

    stc_to.save('%s_audvis-meg' % subject_to)

    mean_from = stc_from.data.mean(axis=0)
    mean_to = stc_to.data.mean(axis=0)
    assert np.corrcoef(mean_to, mean_from).min() > 0.99
示例#27
0
def _simulate_data(fwd):
    """Simulate an oscillator on the cortex."""
    source_vertno = 146374  # Somewhere on the frontal lobe

    sfreq = 50.  # Hz.
    times = np.arange(10 * sfreq) / sfreq  # 10 seconds of data
    signal = np.sin(20 * 2 * np.pi * times)  # 20 Hz oscillator
    signal[:len(times) // 2] *= 2  # Make signal louder at the beginning
    signal *= 1e-9  # Scale to be in the ballpark of MEG data

    # Construct a SourceEstimate object that describes the signal at the
    # cortical level.
    stc = mne.SourceEstimate(
        signal[np.newaxis, :],
        vertices=[[source_vertno], []],
        tmin=0,
        tstep=1 / sfreq,
        subject='sample',
    )

    # Create an info object that holds information about the sensors
    info = mne.create_info(fwd['info']['ch_names'], sfreq, ch_types='grad')
    info.update(fwd['info'])  # Merge in sensor position information
    # heavily decimate sensors to make it much faster
    info = mne.pick_info(info, np.arange(info['nchan'])[::5])
    fwd = mne.pick_channels_forward(fwd, info['ch_names'])

    # Run the simulated signal through the forward model, obtaining
    # simulated sensor data.
    raw = mne.apply_forward_raw(fwd, stc, info)

    # Add a little noise
    random = np.random.RandomState(42)
    noise = random.randn(*raw._data.shape) * 1e-14
    raw._data += noise

    # Define a single epoch
    epochs = mne.Epochs(raw, [[0, 0, 1]],
                        event_id=1,
                        tmin=0,
                        tmax=raw.times[-1],
                        preload=True)
    evoked = epochs.average()

    # Compute the cross-spectral density matrix
    csd = csd_morlet(epochs, frequencies=[10, 20], n_cycles=[5, 10], decim=10)

    return epochs, evoked, csd, source_vertno
示例#28
0
def norm_stc(subject, stc_name):
    norm_stc_template = op.join(MMVT_DIR, subject, 'meg',
                                '{}-norm-{}.stc'.format(stc_name, '{hemi}'))
    if utils.both_hemi_files_exist(norm_stc_template):
        return norm_stc_template.format(hemi='lh')
    stc_fname = op.join(MMVT_DIR, subject, 'meg', '{}-lh.stc'.format(stc_name))
    stc = mne.read_source_estimate(stc_fname)
    stc_max = utils.max_stc(stc)
    norm_data = stc.data / stc_max
    stc_norm = mne.SourceEstimate(norm_data,
                                  stc.vertices,
                                  0,
                                  0,
                                  subject=subject)
    stc_norm.save(op.join(MMVT_DIR, subject, 'meg',
                          '{}-norm'.format(stc_name)))
示例#29
0
def _bias_params(evoked, noise_cov, fwd):
    evoked.pick_types(meg=True, eeg=True, exclude=())
    # restrict to limited set of verts (small src here) and one hemi for speed
    vertices = [fwd['src'][0]['vertno'].copy(), []]
    stc = mne.SourceEstimate(np.zeros((sum(len(v) for v in vertices), 1)),
                             vertices, 0., 1.)
    fwd = mne.forward.restrict_forward_to_stc(fwd, stc)
    assert fwd['sol']['row_names'] == noise_cov['names']
    assert noise_cov['names'] == evoked.ch_names
    evoked = mne.EvokedArray(fwd['sol']['data'].copy(), evoked.info)
    data_cov = noise_cov.copy()
    data_cov['data'] = np.dot(fwd['sol']['data'], fwd['sol']['data'].T)
    assert data_cov['data'].shape[0] == len(noise_cov['names'])
    want = np.arange(fwd['sol']['data'].shape[1])
    if not mne.forward.is_fixed_orient(fwd):
        want //= 3
    return evoked, fwd, noise_cov, data_cov, want
示例#30
0
def hotelling_t2(epochs,
                 inv_op,
                 src,
                 baseline=(None, 0),
                 update_interval=10,
                 epochs_other=None):
    """Compute p values from a VectorSourceEstimate."""
    assert inv_op.ndim == 3 and inv_op.shape[1] == 3
    data = epochs.get_data()
    tmin, tstep = epochs.times[0], 1. / epochs.info['sfreq']
    n_ave = len(data)
    if epochs_other is not None:
        assert np.allclose(epochs.times, epochs_other.times)
        data_other = epochs_other.get_data()
        n_ave_other = len(data_other)
    else:
        data_other = n_ave_other = None
    del epochs
    F_p = np.zeros((inv_op.shape[0], data.shape[-1]))
    inv_op_t = np.array(inv_op.transpose(0, 2, 1))
    for ti in range(data.shape[-1]):  # iterate over times
        if update_interval is not None and ti % update_interval == 0:
            print(' %s' % ti, end='')
        # Compute the means and covariances
        this_data = data[:, :, ti].T
        sens_cov = np.cov(this_data, ddof=1)[np.newaxis]
        mu = np.dot(inv_op, this_data.mean(-1))
        sigma = np.matmul(np.matmul(inv_op, sens_cov), inv_op_t)
        if data_other is not None:
            this_data = data_other[:, :, ti].T
            sens_cov = np.cov(this_data, ddof=1)[np.newaxis]
            mu_other = np.dot(inv_op, this_data.mean(-1))
            sigma_other = np.matmul(np.matmul(inv_op, sens_cov), inv_op_t)
        else:
            mu_other = sigma_other = None
        del this_data, sens_cov
        F_p[:, ti] = _ht2_p(mu,
                            sigma,
                            n_ave,
                            mu_other,
                            sigma_other,
                            n_ave_other,
                            use_pinv=False)
    stc = mne.SourceEstimate(F_p, [s['vertno'] for s in src], tmin, tstep,
                             src[0]['subject_his_id'])
    return stc