def _append_data(analysis):
    """append source scores across subjects"""
    try:
        stcs, connectivity = load('score_source', subject='fsaverage',
                                  analysis=analysis['name'])
    except Exception:
        stcs = list()
        for meg_subject, subject in zip(range(1, 21), subjects_id):
            if subject in bad_mri:
                continue
            # load
            stc, _, _ = load('evoked_source', subject=meg_subject,
                             analysis=analysis['name'])
            morph = load('morph', subject=meg_subject)
            vertices_to = [np.arange(10242)] * 2
            # fix angle error scale
            if 'circAngle' in analysis['name']:
                stc._data /= 2.

            # apply morph
            stc_morph = morph_data_precomputed(subject, 'fsaverage', stc,
                                               vertices_to, morph)
            stcs.append(stc_morph.data)
        stcs = np.array(stcs)
        save([stcs, connectivity], 'score_source', subject='fsaverage',
             analysis=analysis['name'], overwrite=True, upload=True)
    return stcs, connectivity
Ejemplo n.º 2
0
def test_morphing():
    mne.set_log_level('warning')
    data_dir = mne.datasets.sample.data_path()
    subjects_dir = os.path.join(data_dir, 'subjects')

    sss = datasets._mne_source_space('fsaverage', 'ico-4', subjects_dir)
    vertices_to = [sss[0]['vertno'], sss[1]['vertno']]
    ds = datasets.get_mne_sample(-0.1,
                                 0.1,
                                 src='ico',
                                 sub='index==0',
                                 stc=True)
    stc = ds['stc', 0]
    morph_mat = mne.compute_morph_matrix('sample', 'fsaverage', stc.vertices,
                                         vertices_to, None, subjects_dir)
    ndvar = ds['src']

    morphed_ndvar = morph_source_space(ndvar, 'fsaverage')
    morphed_stc = mne.morph_data_precomputed('sample', 'fsaverage', stc,
                                             vertices_to, morph_mat)
    assert_array_equal(morphed_ndvar.x[0], morphed_stc.data)
    morphed_stc_ndvar = load.fiff.stc_ndvar([morphed_stc],
                                            'fsaverage',
                                            'ico-4',
                                            subjects_dir,
                                            'dSPM',
                                            False,
                                            'src',
                                            parc=None)
    assert_dataobj_equal(morphed_ndvar, morphed_stc_ndvar)
Ejemplo n.º 3
0
def _append_data(analysis):
    """append source scores across subjects"""
    try:
        stcs, connectivity = load('score_source',
                                  subject='fsaverage',
                                  analysis=analysis['name'])
    except Exception:
        stcs = list()
        for meg_subject, subject in zip(range(1, 21), subjects_id):
            if subject in bad_mri:
                continue
            # load
            stc, _, _ = load('evoked_source',
                             subject=meg_subject,
                             analysis=analysis['name'])
            morph = load('morph', subject=meg_subject)
            vertices_to = [np.arange(10242)] * 2
            # fix angle error scale
            if 'circAngle' in analysis['name']:
                stc._data /= 2.

            # apply morph
            stc_morph = morph_data_precomputed(subject, 'fsaverage', stc,
                                               vertices_to, morph)
            stcs.append(stc_morph.data)
        stcs = np.array(stcs)
        save([stcs, connectivity],
             'score_source',
             subject='fsaverage',
             analysis=analysis['name'],
             overwrite=True,
             upload=True)
    return stcs, connectivity
Ejemplo n.º 4
0
def test_morphing():
    mne.set_log_level('warning')
    sss = datasets._mne_source_space('fsaverage', 'ico-4', subjects_dir)
    vertices_to = [sss[0]['vertno'], sss[1]['vertno']]
    ds = datasets.get_mne_sample(-0.1, 0.1, src='ico', sub='index==0', stc=True)
    stc = ds['stc', 0]
    morph_mat = mne.compute_morph_matrix('sample', 'fsaverage', stc.vertno,
                                         vertices_to, None, subjects_dir)
    ndvar = ds['src']

    morphed_ndvar = morph_source_space(ndvar, 'fsaverage')
    morphed_stc = mne.morph_data_precomputed('sample', 'fsaverage', stc,
                                             vertices_to, morph_mat)
    assert_array_equal(morphed_ndvar.x[0], morphed_stc.data)
    morphed_stc_ndvar = load.fiff.stc_ndvar([morphed_stc], 'fsaverage', 'ico-4',
                                            subjects_dir, 'src', parc=None)
    assert_dataobj_equal(morphed_ndvar, morphed_stc_ndvar)
Ejemplo n.º 5
0
    def make_stcs(self, snr = 3.0, method='dSPM', save_to_disk = False, morph=True):
        """docstring for make_stcs"""

        morph_status = 'no_morph'

        lambda2 = 1.0 / snr ** 2.0
        pick_ori = None

        stcs = []

        for evoked_object, cond in self.evoked_list:

            print "Making source estimates for %s." %cond
            stc = mne.minimum_norm.apply_inverse(evoked_object, self.inverse_solution, method = method, lambda2 = lambda2, pick_ori = pick_ori)

            if morph == True:

                morph_status = 'morphed'
                # create morph map
                # get vertices to morph to (we'll take the fsaverage vertices)
                subject_to = 'fsaverage'
                fs = mne.read_source_spaces(self.subjects_dir + '%s/bem/%s-ico-4-src.fif' % (subject_to, subject_to))
                vertices_to = [fs[0]['vertno'], fs[1]['vertno']]

                # info of the stc we're going to morph is just the present stc
                subject_from = self.subject
                stc_from = stc

                # use the morph function
                morph_mat = mne.compute_morph_matrix(subject_from, subject_to, vertices_from=stc_from.vertices, vertices_to=vertices_to, subjects_dir=self.subjects_dir)
                stc = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat)


                # stc_to.save('%s_audvis-meg' % subject_from)
                # mne.compute_morph_matrix('2-COMB','3-COMB',stcs[0].vertices, stcs[5].vertices, subjects_dir=self.subjects_dir)

            if save_to_disk:
                fact_morph_cond_path = op.join(self.stc_fact, morph_status, cond)
                if not os.path.isdir(fact_morph_cond_path):
                    os.makedirs(fact_morph_cond_path)

                stc.save(op.join(fact_morph_cond_path, '%s_%s_%s' %(self.subject, cond, morph_status)))

                self.add_preprocessing_notes("Saved source estimates (%s) for %s." %(morph_status, cond))
    def make_stcs(self, snr = 3.0, method='dSPM', save_to_disk = False, morph=True):
        """docstring for make_stcs"""

        morph_status = 'no_morph'

        lambda2 = 1.0 / snr ** 2.0
        pick_ori = None

        stcs = []

        for evoked_object, cond in self.evoked_list:

            print "Making source estimates for %s." %cond
            stc = mne.minimum_norm.apply_inverse(evoked_object, self.inverse_solution, method = method, lambda2 = lambda2, pick_ori = pick_ori)

            if morph == True:

                morph_status = 'morphed'
                # create morph map
                # get vertices to morph to (we'll take the fsaverage vertices)
                subject_to = 'fsaverage'
                fs = mne.read_source_spaces(self.subjects_dir + '%s/bem/%s-ico-4-src.fif' % (subject_to, subject_to))
                vertices_to = [fs[0]['vertno'], fs[1]['vertno']]

                # info of the stc we're going to morph is just the present stc
                subject_from = self.subject
                stc_from = stc

                # use the morph function
                morph_mat = mne.compute_morph_matrix(subject_from, subject_to, vertices_from=stc_from.vertices, vertices_to=vertices_to, subjects_dir=self.subjects_dir)
                stc = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat)


                # stc_to.save('%s_audvis-meg' % subject_from)
                # mne.compute_morph_matrix('2-COMB','3-COMB',stcs[0].vertices, stcs[5].vertices, subjects_dir=self.subjects_dir)

            if save_to_disk:
                fact_morph_cond_path = op.join(self.stc_fact, morph_status, cond)
                if not os.path.isdir(fact_morph_cond_path):
                    os.makedirs(fact_morph_cond_path)

                stc.save(op.join(fact_morph_cond_path, '%s_%s_%s' %(self.subject, cond, morph_status)))

                self.add_preprocessing_notes("Saved source estimates (%s) for %s." %(morph_status, cond))
Ejemplo n.º 7
0
    def make_epoch_stcs(self, epochs, snr = 2.0, method='dSPM', morph=True, save_to_disk = False):
        """Apply inverse operator to epochs to get source estimates of each item"""


        lambda2 = 1.0 / snr ** 2.0

        inverse = mne.minimum_norm.read_inverse_operator( self.processed_files + self.subject + '_inv.fif' )

        eps = mne.minimum_norm.apply_inverse_epochs(epochs=epochs,inverse_operator=inverse,lambda2=lambda2,method = method)

        if morph == True:
            eps_morphed = []
            counter = 1
            morph_status = 'morphed'
            # create morph map
            # get vertices to morph to (we'll take the fsaverage vertices)
            subject_to = 'fsaverage'
            fs = mne.read_source_spaces(self.subjects_dir + '%s/bem/%s-ico-4-src.fif' % (subject_to, subject_to))
            vertices_to = [fs[0]['vertno'], fs[1]['vertno']]
            subject_from = self.subject

            for stc_from in eps:
                print "Morphing source estimate for epoch %d" %counter
            # use the morph function
                morph_mat = mne.compute_morph_matrix(subject_from, subject_to, vertices_from=stc_from.vertices, vertices_to=vertices_to, subjects_dir=self.subjects_dir)
                stc = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat)
                # stc = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1,
                #                     grade=vertices_to, subjects_dir=self.subjects_dir)

                eps_morphed.append(stc)
                counter += 1

            eps = eps_morphed

        if save_to_disk:
            with open(op.join(self.stc_cont, '%s_stc_epochs.pickled' %self.subject), 'w') as fileout:
                pickle.dump(eps, fileout)
            #save.pickle(obj=eps,dest=self.stc_cont + self.subject + '_stc_epochs')

        return eps
    def make_epoch_stcs(self, epochs, snr = 2.0, method='dSPM', morph=True, save_to_disk = False):
        """Apply inverse operator to epochs to get source estimates of each item"""


        lambda2 = 1.0 / snr ** 2.0

        inverse = mne.minimum_norm.read_inverse_operator( self.processed_files + self.subject + '_inv.fif' )

        eps = mne.minimum_norm.apply_inverse_epochs(epochs=epochs,inverse_operator=inverse,lambda2=lambda2,method = method)

        if morph == True:
            eps_morphed = []
            counter = 1
            morph_status = 'morphed'
            # create morph map
            # get vertices to morph to (we'll take the fsaverage vertices)
            subject_to = 'fsaverage'
            fs = mne.read_source_spaces(self.subjects_dir + '%s/bem/%s-ico-4-src.fif' % (subject_to, subject_to))
            vertices_to = [fs[0]['vertno'], fs[1]['vertno']]
            subject_from = self.subject

            for stc_from in eps:
                print "Morphing source estimate for epoch %d" %counter
            # use the morph function
                morph_mat = mne.compute_morph_matrix(subject_from, subject_to, vertices_from=stc_from.vertices, vertices_to=vertices_to, subjects_dir=self.subjects_dir)
                stc = mne.morph_data_precomputed(subject_from, subject_to, stc_from, vertices_to, morph_mat)
                # stc = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1,
                #                     grade=vertices_to, subjects_dir=self.subjects_dir)

                eps_morphed.append(stc)
                counter += 1

            eps = eps_morphed

        if save_to_disk:
            with open(op.join(self.stc_cont, '%s_stc_epochs.pickled' %self.subject), 'w') as fileout:
                pickle.dump(eps, fileout)
            #save.pickle(obj=eps,dest=self.stc_cont + self.subject + '_stc_epochs')

        return eps
Ejemplo n.º 9
0
def test_source_estimate():
    "Test SourceSpace dimension"
    ds = datasets.get_mne_sample(src='ico')
    dsa = ds.aggregate('side')

    # test auto-conversion
    asndvar('epochs', ds=ds)
    asndvar('epochs', ds=dsa)
    asndvar(dsa['epochs'][0])

    # source space clustering
    res = testnd.ttest_ind('src', 'side', ds=ds, samples=0, pmin=0.05,
                           tstart=0.05, mintime=0.02, minsource=10)
    assert_equal(res.clusters.n_cases, 52)

    # test morphing
    dsa = ds.aggregate('side')
    ndvar = dsa['src']
    stc = mne.SourceEstimate(ndvar.x[0], ndvar.source.vertno,
                             ndvar.time.tmin, ndvar.time.tstep,
                             ndvar.source.subject)
    subjects_dir = ndvar.source.subjects_dir
    path = ndvar.source._src_pattern.format(subject='fsaverage',
                                            src=ndvar.source.src,
                                            subjects_dir=subjects_dir)
    if os.path.exists(path):
        src_to = mne.read_source_spaces(path)
    else:
        src_to = mne.setup_source_space('fsaverage', path, 'ico4',
                                        subjects_dir=subjects_dir)
    vertices_to = [src_to[0]['vertno'], src_to[1]['vertno']]
    mm = mne.compute_morph_matrix('sample', 'fsaverage', ndvar.source.vertno,
                                  vertices_to, None, subjects_dir)
    stc_to = mne.morph_data_precomputed('sample', 'fsaverage', stc,
                                        vertices_to, mm)

    ndvar_m = morph_source_space(ndvar, 'fsaverage')
    assert_array_equal(ndvar_m.x[0], stc_to.data)
Ejemplo n.º 10
0
import os
import os.path as op
import numpy as np
from mne import morph_data_precomputed
from matplotlib.colors import LinearSegmentedColormap
from conditions import analyses
from jr.plot import alpha_cmap
from config import load, subjects_id, report, tois
report._setup_provenance()

# Load a first source space to setup plotting
stc, _, _ = load('evoked_source', subject=1, analysis='target_present')
morph = load('morph', subject=1)
vertices_to = [np.arange(10242)] * 2
stc_morph = morph_data_precomputed(subjects_id[0], 'fsaverage', stc,
                                   vertices_to, morph)
# Loop across analyses (target presence, angle etc)
for analysis in analyses:
    stcs, connectivity = load('score_source', analysis=analysis['name'])
    p_val = load('score_pval', analysis=analysis['name'])

    # Morph pval in log space
    stc_morph._data[:, :] = np.log(p_val.T)
    stc_pval = stc_morph.morph('fsaverage', grade=None)
    sig = np.exp(stc_pval._data) < .05
    del stc_pval, p_val

    # Get absolute score value for plotting
    chance = analysis['chance']
    stc2 = np.mean(np.abs(stcs - chance) + chance, axis=0)
    stc = np.mean(stcs, axis=0)
Ejemplo n.º 11
0
cov_blank = mne.compute_covariance(epochs_ds['STB'], tmin=0, tmax=None, method='auto')
inv_blank = make_inverse_operator(epochs_ds.info, forward, cov_blank,
                                  loose=0.2, depth=0.8)
blank_idx = np.nonzero(epochs_ds.events[:, 2] == 15)[0]
epochs_ds.drop_epochs(blank_idx)
cov_base = mne.compute_covariance(epochs_ds, tmin=None, tmax=0, method='auto')
inv_base = make_inverse_operator(epochs_ds.info, forward, cov_base,
                                 loose=0.2, depth=0.8)

vertices_to = [np.arange(10242), np.arange(10242)]
vertices_from = [forward['src'][0]['vertno'], forward['src'][1]['vertno']]
morph_mat = mne.compute_morph_matrix(subj, 'fsaverage', vertices_from, vertices_to)
for c in range(len(conds)):
    # start with the simplest method, MNE + dSPM
    stc = apply_inverse(evoked_ds[c], inv_base, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    fname = out_dir + '%s_%s_dSPM_base_clean' % (subj, conds[c])
    stc.save(fname)
    stc = apply_inverse(evoked_ds[c], inv_blank, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    fname = out_dir + '%s_%s_dSPM_blank_clean' % (subj, conds[c])
    stc.save(fname)

    # the next estimate is LCMV beamformer in time
    data_cov = mne.compute_covariance(epochs_ds[conds[c]], tmin=0, tmax=None,
                                      method='shrunk')
    stc = lcmv(evoked_ds[c], forward, cov_blank, data_cov, reg=0.01,
               pick_ori='max-power')
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
        # Save each unprocessed stc file and compute/save morphed stc
        ######################################################################
        for ti, temp_stc in enumerate(stc_list):
            # Save each unprocessed stc file
            save_fname = op.join(save_folder_unproc, subj_d[i]['Subj#'] + '_' +
                                 p + '_' + inv_method + '_t' + str(ti))
            temp_stc.save(save_fname, verbose=False)

            if bin_width is not None:
                temp_stc = temp_stc.bin(bin_width)

            if takeMagOfVals:
                temp_stc._data = np.abs(temp_stc._data)

            # Also morph to fsaverage if not using spherical head inverse
            # (if spherical, head model source space IS fsaverage)
            if inv_model != 'sphere':
                morphed_stc = mne.morph_data_precomputed(
                    subject_from=subj_d[i]['Struct'], subject_to='fsaverage',
                    stc_from=temp_stc, vertices_to=fsaverage['vertices'],
                    morph_mat=subj_d[i]['fs_morph'])

                # Save each morphed stc file
                save_fname = op.join(save_folder_morph, subj_d[i]['Subj#'] +
                                     '_' + p + '_' + inv_method +
                                     '_FsMorphed_bin' + str(bin_width) + '_Abs'
                                     + str(takeMagOfVals) + '_t' + str(ti))
                morphed_stc.save(save_fname, ftype=ftype, verbose=False)

    print ' ...  Done'
        fname_morph = C.fname_STC(
            C, 'SensitivityMaps', subject,
            'SensMap_' + modality + '_' + metric + '_mph')

        # read existing source estimate
        print('Reading: %s.' % fname_stc)
        stc = mne.read_source_estimate(fname_stc, subject)

        # compute morph_mat only once per subject
        if morph_mat == []:

            vertices_to = mne.grade_to_vertices(subject=C.stc_morph,
                                                grade=5,
                                                subjects_dir=C.subjects_dir)

            morph_mat = mne.compute_morph_matrix(subject_from=subject,
                                                 subject_to=C.stc_morph,
                                                 vertices_from=stc.vertices,
                                                 vertices_to=vertices_to,
                                                 subjects_dir=C.subjects_dir)

        # Morphing to standard brain
        morphed = mne.morph_data_precomputed(subject_from=subject,
                                             subject_to=C.stc_morph,
                                             stc_from=stc,
                                             vertices_to=vertices_to,
                                             morph_mat=morph_mat)

        print('Writing morphed to: %s.' % fname_morph)
        morphed.save(fname_morph)
# Done
Ejemplo n.º 14
0
epochs_ds.drop_epochs(blank_idx)
cov_base = mne.compute_covariance(epochs_ds, tmin=None, tmax=0, method='auto')
inv_base = make_inverse_operator(epochs_ds.info,
                                 forward,
                                 cov_base,
                                 loose=0.2,
                                 depth=0.8)

vertices_to = [np.arange(10242), np.arange(10242)]
vertices_from = [forward['src'][0]['vertno'], forward['src'][1]['vertno']]
morph_mat = mne.compute_morph_matrix(subj, 'fsaverage', vertices_from,
                                     vertices_to)
for c in range(len(conds)):
    # start with the simplest method, MNE + dSPM
    stc = apply_inverse(evoked_ds[c], inv_base, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to,
                                     morph_mat)
    fname = out_dir + '%s_%s_dSPM_base_clean' % (subj, conds[c])
    stc.save(fname)
    stc = apply_inverse(evoked_ds[c], inv_blank, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to,
                                     morph_mat)
    fname = out_dir + '%s_%s_dSPM_blank_clean' % (subj, conds[c])
    stc.save(fname)

    # the next estimate is LCMV beamformer in time
    data_cov = mne.compute_covariance(epochs_ds[conds[c]],
                                      tmin=0,
                                      tmax=None,
                                      method='shrunk')
    stc = lcmv(evoked_ds[c],
               forward,
Ejemplo n.º 15
0
def stft_source_localization(data, fn_inv, method="dSPM",
                             morph2fsaverage=False,
                             nave=1, snr=3.,
                             pick_ori="normal", verbose=True):

    """
    Apply inverse operator to data. In general, the
    L2-norm inverse solution is computed.

        Parameters
        ----------
        data: array of MEG data
            (only the data, no MNE-data object!)
        kernel: kernel of the inverse operator.
            (could be estimated using
            mne.minimum_norm._assemble_kernel())
        noise_norm: noise normalization array.
            (could be estimated using
            mne.minimum_norm._assemble_kernel())

        Returns
        -------
        src_loc: SourceEstimate | VolSourceEstimate
            The source estimates
        estimation_time: time needed to perform source
            localization (for one time slice)
    """

    # -------------------------------------------
    # import necessary modules
    # -------------------------------------------
    import numpy as np
    import types

    # check if data should be morphed
    if morph2fsaverage:
        from mne import compute_morph_matrix, grade_to_vertices, morph_data_precomputed
        from mne.source_estimate import SourceEstimate
        from os.path import basename, dirname


    # -------------------------------------------
    # estimate inverse kernel
    # -------------------------------------------
    kernel, noise_norm, vertno = calc_inv_kernel(fn_inv, method=method,
                                                 nave=nave, snr=snr,
                                                 pick_ori=pick_ori)


    # -------------------------------------------
    # get some information from the
    # input data
    # -------------------------------------------
    nfreq, nepochs, nchan = data.shape
    nvoxel = noise_norm.shape[0]

    if isinstance(data[0, 0, 0], types.ComplexType):
        src_loc_data = np.zeros((nfreq, nepochs, nvoxel), dtype=np.complex)
    else:
        src_loc_data = np.zeros((nfreq, nepochs, nvoxel))


    # -------------------------------------------
    # read in morphing matrix
    # -------------------------------------------
    if morph2fsaverage:
        subject_id = basename(fn_inv)[:6]
        subjects_dir = dirname(dirname(fn_inv))
        vertices_to = grade_to_vertices('fsaverage', grade=4,
                                        subjects_dir=subjects_dir)

        morph_mat = compute_morph_matrix(subject_id, 'fsaverage',
                                         vertno, vertices_to,
                                         subjects_dir=subjects_dir)
        nvoxel_morph = 2 * len(vertices_to[0])

        if isinstance(data[0, 0, 0], types.ComplexType):
            morphed_src_loc_data = np.zeros((nfreq, nepochs, nvoxel_morph), dtype=np.complex)
        else:
            morphed_src_loc_data = np.zeros((nfreq, nepochs, nvoxel_morph), dtype=np.complex)


    # -------------------------------------------
    # apply inverse operator for each time slice
    # -------------------------------------------
    for iepoch in range(nepochs):

        if verbose:
            from sys import stdout
            info = "\r" if iepoch > 0 else ""
            info += "... --> Epoch %d of %d done" % (iepoch+1, nepochs)
            stdout.write(info)
            stdout.flush()

        for ifreq in range(0, nfreq):
            # multiply measured data with inverse kernel
            loc_tmp = np.dot(kernel, data[ifreq, iepoch, :])

            if pick_ori != "normal":

                # estimate L2-norm and apply noise normalization
                src_loc_data[ifreq, iepoch, :] = loc_tmp[0::3].real ** 2 + 1j * loc_tmp[0::3].imag ** 2
                src_loc_data[ifreq, iepoch, :] += loc_tmp[1::3].real ** 2 + 1j * loc_tmp[1::3].imag ** 2
                src_loc_data[ifreq, iepoch, :] += loc_tmp[2::3].real ** 2 + 1j * loc_tmp[2::3].imag ** 2
                src_loc_data[ifreq, iepoch, :] = (np.sqrt(src_loc_data[ifreq, iepoch, :].real) +
                                                  1j * np.sqrt(src_loc_data[ifreq, iepoch, :].imag))
            else:
                src_loc_data[ifreq, iepoch, :] = loc_tmp

            src_loc_data[ifreq, iepoch, :] *= noise_norm[:, 0]


        if morph2fsaverage:
            SrcEst = SourceEstimate(src_loc_data[:, iepoch, :].T,
                                    vertno, 0, 1, verbose=verbose)
            SrcEst_morphed = morph_data_precomputed(subject_id, 'fsaverage',
                                                    SrcEst, vertices_to, morph_mat)

            morphed_src_loc_data[:, iepoch, :] = SrcEst_morphed.data.T

    if verbose:
         print ""

    if morph2fsaverage:
        src_loc_data = morphed_src_loc_data
        vertno = vertices_to

    return src_loc_data, vertno
Ejemplo n.º 16
0
stc_from = mne.read_source_estimate(fname)
# Morph using one method (supplying the vertices in fsaverage's source
# space makes it faster). Note that for any generic subject, you could do:
#     vertices_to = mne.grade_to_vertices(subject_to, grade=5)
# But fsaverage's source space was set up so we can just do this:
vertices_to = [np.arange(10242), np.arange(10242)]
stc_to = mne.morph_data(subject_from,
                        subject_to,
                        stc_from,
                        n_jobs=1,
                        grade=vertices_to)
stc_to.save('%s_audvis-meg' % subject_to)

# Morph using another method -- useful if you're going to do a lot of the
# same inter-subject morphing operations; you could save and load morph_mat
morph_mat = mne.compute_morph_matrix(subject_from, subject_to, stc_from.vertno,
                                     vertices_to)
stc_to_2 = mne.morph_data_precomputed(subject_from, subject_to, stc_from,
                                      vertices_to, morph_mat)
stc_to_2.save('%s_audvis-meg_2' % subject_to)

# View source activations
import matplotlib.pyplot as plt
plt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from')
plt.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to')
plt.plot(stc_to_2.times, stc_to.data.mean(axis=0), 'g', label='to_2')
plt.xlabel('time (ms)')
plt.ylabel('Mean Source amplitude')
plt.legend()
plt.show()
Ejemplo n.º 17
0
            cov = mne.compute_covariance(epochs_rej,tmin=None,tmax=0, method=['shrunk', 'diagonal_fixed', 'empirical'])
            cov.save(cov_fname)
            print 'Done. File saved.'


        #---------------------Inverse operator-------------------------#
        print 'Getting inverse operator'
        if fixed == True:
            fwd = mne.convert_forward_solution(fwd, surf_ori=True)

        inv = mne.minimum_norm.make_inverse_operator(info, fwd, cov, depth=None, loose=None, fixed=fixed) #fixed=False: Ignoring dipole direction.
        lambda2 = 1.0 / SNR ** 2.0

        #--------------------------STCs--------------------------------#

        print '%s: Creating STCs...'%subj
        os.makedirs('STC/%s' %subj)
        for ev in evoked:
            stc = mne.minimum_norm.apply_inverse(ev, inv, lambda2=lambda2, method='dSPM')
            # mophing stcs to the fsaverage using precomputed matrix method:
            vertices_to = mne.grade_to_vertices('fsaverage', grade=4, subjects_dir=subjects_dir) #fsaverage's source space
            morph_mat = mne.compute_morph_matrix(subject_from=subj, subject_to='fsaverage', vertices_from=stc.vertices, vertices_to=vertices_to, subjects_dir=subjects_dir)
            stc_morph = mne.morph_data_precomputed(subject_from=subj, subject_to='fsaverage', stc_from=stc, vertices_to=vertices_to, morph_mat=morph_mat)
            stc_morph.save('STC/%s/%s_%s_dSPM' %(subj,subj,ev.comment))
            del stc, stc_morph
        print '>> DONE CREATING STCS FOR SUBJ=%s'%subj
        print '-----------------------------------------\n'

        #deleting variables
        del epochs_rej, evoked, info, trans, src, fwd, cov, inv
Ejemplo n.º 18
0
src_fname = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'

# Read input stc file
stc_from = mne.read_source_estimate(fname)
# Morph using one method (supplying the vertices in fsaverage's source
# space makes it faster). Note that for any generic subject, you could do:
#     vertices_to = mne.grade_to_vertices(subject_to, grade=5)
# But fsaverage's source space was set up so we can just do this:
vertices_to = [np.arange(10242), np.arange(10242)]
stc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1,
                        grade=vertices_to, subjects_dir=subjects_dir)
stc_to.save('%s_audvis-meg' % subject_to)

# Morph using another method -- useful if you're going to do a lot of the
# same inter-subject morphing operations; you could save and load morph_mat
morph_mat = mne.compute_morph_matrix(subject_from, subject_to,
                                     stc_from.vertices, vertices_to,
                                     subjects_dir=subjects_dir)
stc_to_2 = mne.morph_data_precomputed(subject_from, subject_to,
                                      stc_from, vertices_to, morph_mat)
stc_to_2.save('%s_audvis-meg_2' % subject_to)

# View source activations
plt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from')
plt.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to')
plt.plot(stc_to_2.times, stc_to.data.mean(axis=0), 'g', label='to_2')
plt.xlabel('time (ms)')
plt.ylabel('Mean Source amplitude')
plt.legend()
plt.show()
                               stc_data=act_scale * stc_activation, tmin=0,
                               tstep=0.001)

        # Generate simulated raw data
        raw_temp = gen_x_raw(n_trials, raw_template, stc_sim, s_dict)

        # Calculate source estimates
        stc_est_sph.append(apply_inverse_raw(raw_temp, s_dict['inv_sph'],
                                             lambda2, 'MNE',
                                             label=fsaverage['lab']))
        stc_est_temp = apply_inverse_raw(raw_temp, s_dict['inv'], lambda2, 'MNE')
                                         #label=s_dict['lab'])

        # Need to morph to fsaverage to match spherical and morphed data
        stc_est.append(mne.morph_data_precomputed(
            subject_from=s_dict['Struct'], subject_to='fsaverage',
            stc_from=stc_est_temp, vertices_to=fsaverage['vertices'],
            morph_mat=s_dict['fs_morph']).in_label(fsaverage['lab']))

        # Resample and store
        # Use copy in raw_sim because of strange error with in-place resample
        raw_sim.append(raw_temp.resample(1. / bin_width, copy=True,
                                         n_jobs=n_jobs, verbose=False))
        stc_est[-1].resample(1. / bin_width, n_jobs=n_jobs, verbose=False)
        stc_est_sph[-1].resample(1. / bin_width, n_jobs=n_jobs, verbose=False)

    print '\t%s: Data simulated, source estimates computed' % s_dict['Subj#']

    ###########################################################################
    # Classify
    ###########################################################################