def calc_sub_cortical_activity(events_id, evoked_fn, inv_fn, sub_corticals_codes_file, baseline_min_t=None,
        baseline_max_t = 0, snr = 3.0, inverse_method='dSPM'):

    sub_corticals = read_sub_corticals_code_file(sub_corticals_codes_file)
    if len(sub_corticals) == 0:
        return

    lambda2 = 1.0 / snr ** 2
    lut = read_freesurfer_lookup_table(FREE_SURFER_HOME)
    for cond in events_id.keys():
        evo = evoked_fn.format(cond=cond)
        evoked = {event:mne.read_evokeds(evo, baseline=(baseline_min_t, baseline_max_t))[0] for event in [event]}
        inverse_operator = read_inverse_operator(inv_fn.format(cond=cond))
        stc = apply_inverse(evoked[cond], inverse_operator, lambda2, inverse_method)
        read_vertices_from = len(stc.vertices[0])+len(stc.vertices[1])
        sub_corticals_activity = {}
        for sub_cortical_ind, sub_cortical_code in enumerate(sub_corticals):
            # +2 becasue the first two are the hemispheres
            sub_corticals_activity[sub_cortical_code] = stc.data[
                read_vertices_from: read_vertices_from + len(stc.vertices[sub_cortical_ind + 2])]
            read_vertices_from += len(stc.vertices[sub_cortical_ind + 2])

        if not os.path.isdir:
            os.mkdir(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals'))
        for sub_cortical_code, activity in sub_corticals_activity.iteritems():
            sub_cortical, _ = get_numeric_index_to_label(sub_cortical_code, lut)
            np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}'.format(cond, sub_cortical, inverse_method)), activity.mean(0))
            np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}-all-vertices'.format(cond, sub_cortical, inverse_method)), activity)
def test_spatio_temporal_src_connectivity():
    """Test spatio-temporal connectivity from source spaces."""
    tris = np.array([[0, 1, 2], [3, 4, 5]])
    src = [dict(), dict()]
    connectivity = spatio_temporal_tris_connectivity(tris, 2)
    src[0]['use_tris'] = np.array([[0, 1, 2]])
    src[1]['use_tris'] = np.array([[0, 1, 2]])
    src[0]['vertno'] = np.array([0, 1, 2])
    src[1]['vertno'] = np.array([0, 1, 2])
    src[0]['type'] = 'surf'
    src[1]['type'] = 'surf'
    connectivity2 = spatio_temporal_src_connectivity(src, 2)
    assert_array_equal(connectivity.todense(), connectivity2.todense())
    # add test for dist connectivity
    src[0]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[1]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[0]['vertno'] = [0, 1, 2]
    src[1]['vertno'] = [0, 1, 2]
    src[0]['type'] = 'surf'
    src[1]['type'] = 'surf'
    connectivity3 = spatio_temporal_src_connectivity(src, 2, dist=2)
    assert_array_equal(connectivity.todense(), connectivity3.todense())
    # add test for source space connectivity with omitted vertices
    inverse_operator = read_inverse_operator(fname_inv)
    src_ = inverse_operator['src']
    with pytest.warns(RuntimeWarning, match='will have holes'):
        connectivity = spatio_temporal_src_connectivity(src_, n_times=2)
    a = connectivity.shape[0] / 2
    b = sum([s['nuse'] for s in inverse_operator['src']])
    assert (a == b)

    assert_equal(grade_to_tris(5).shape, [40960, 3])
def test_epochs_vector_inverse():
    """Test vector inverse consistency between evoked and epochs."""
    raw = read_raw_fif(fname_raw)
    events = find_events(raw, stim_channel='STI 014')[:2]
    reject = dict(grad=2000e-13, mag=4e-12, eog=150e-6)

    epochs = Epochs(raw, events, None, 0, 0.01, baseline=None,
                    reject=reject, preload=True)

    assert_equal(len(epochs), 2)

    evoked = epochs.average(picks=range(len(epochs.ch_names)))

    inv = read_inverse_operator(fname_inv)

    method = "MNE"
    snr = 3.
    lambda2 = 1. / snr ** 2

    stcs_epo = apply_inverse_epochs(epochs, inv, lambda2, method=method,
                                    pick_ori='vector', return_generator=False)
    stc_epo = np.mean(stcs_epo)

    stc_evo = apply_inverse(evoked, inv, lambda2, method=method,
                            pick_ori='vector')

    assert_allclose(stc_epo.data, stc_evo.data, rtol=1e-9, atol=0)
def test_spatio_temporal_src_connectivity():
    """Test spatio-temporal connectivity from source spaces"""
    tris = np.array([[0, 1, 2], [3, 4, 5]])
    src = [dict(), dict()]
    connectivity = spatio_temporal_tris_connectivity(tris, 2)
    src[0]['use_tris'] = np.array([[0, 1, 2]])
    src[1]['use_tris'] = np.array([[0, 1, 2]])
    src[0]['vertno'] = np.array([0, 1, 2])
    src[1]['vertno'] = np.array([0, 1, 2])
    connectivity2 = spatio_temporal_src_connectivity(src, 2)
    assert_array_equal(connectivity.todense(), connectivity2.todense())
    # add test for dist connectivity
    src[0]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[1]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[0]['vertno'] = [0, 1, 2]
    src[1]['vertno'] = [0, 1, 2]
    connectivity3 = spatio_temporal_src_connectivity(src, 2, dist=2)
    assert_array_equal(connectivity.todense(), connectivity3.todense())
    # add test for source space connectivity with omitted vertices
    inverse_operator = read_inverse_operator(fname_inv)
    with warnings.catch_warnings(record=True) as w:
        connectivity = spatio_temporal_src_connectivity(
                                            inverse_operator['src'], n_times=2)
        assert len(w) == 1
    a = connectivity.shape[0] / 2
    b = sum([s['nuse'] for s in inverse_operator['src']])
    assert_true(a == b)
def test_spatio_temporal_src_connectivity():
    """Test spatio-temporal connectivity from source spaces."""
    tris = np.array([[0, 1, 2], [3, 4, 5]])
    src = [dict(), dict()]
    connectivity = spatio_temporal_tris_connectivity(tris, 2)
    src[0]['use_tris'] = np.array([[0, 1, 2]])
    src[1]['use_tris'] = np.array([[0, 1, 2]])
    src[0]['vertno'] = np.array([0, 1, 2])
    src[1]['vertno'] = np.array([0, 1, 2])
    src[0]['type'] = 'surf'
    src[1]['type'] = 'surf'
    connectivity2 = spatio_temporal_src_connectivity(src, 2)
    assert_array_equal(connectivity.todense(), connectivity2.todense())
    # add test for dist connectivity
    src[0]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[1]['dist'] = np.ones((3, 3)) - np.eye(3)
    src[0]['vertno'] = [0, 1, 2]
    src[1]['vertno'] = [0, 1, 2]
    src[0]['type'] = 'surf'
    src[1]['type'] = 'surf'
    connectivity3 = spatio_temporal_src_connectivity(src, 2, dist=2)
    assert_array_equal(connectivity.todense(), connectivity3.todense())
    # add test for source space connectivity with omitted vertices
    inverse_operator = read_inverse_operator(fname_inv)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        src_ = inverse_operator['src']
        connectivity = spatio_temporal_src_connectivity(src_, n_times=2)
    assert_equal(len(w), 1)
    a = connectivity.shape[0] / 2
    b = sum([s['nuse'] for s in inverse_operator['src']])
    assert_true(a == b)

    assert_equal(grade_to_tris(5).shape, [40960, 3])
def _create_stcs(params):
    subject, events_id, epochs, evoked, inv, inverse_method, baseline, apply_for_epochs, apply_SSP_projection_vectors, add_eeg_ref = params
    snr = 3.0
    lambda2 = 1.0 / snr ** 2

    local_inv_file_name = op.join(LOCAL_ROOT_DIR, 'inv', '{}_ecr_nTSSS_conflict-inv.fif'.format(subject))
    if inv is None and os.path.isfile(local_inv_file_name):
        inv = read_inverse_operator(local_inv_file_name)
    if inv is None:
        return
    print([s['vertno'] for s in inv['src']])
    for cond_name in events_id.keys():
        if not apply_for_epochs:
            local_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc', '{}_{}_{}'.format(subject, cond_name, inverse_method))
            if os.path.isfile('{}-lh.stc'.format(local_stc_file_name)):
                print('stc was already calculated for {}'.format(subject))
            else:
                if evoked is None:
                    evoked_cond = mne.read_evokeds(op.join(LOCAL_ROOT_DIR, 'evo', '{}_ecr_{}-ave.fif'.format(subject, cond_name)))
                else:
                    evoked_cond = evoked[cond_name]
                stcs = apply_inverse(evoked_cond, inv, lambda2, inverse_method, pick_ori=None)
                stcs.save(local_stc_file_name, ftype='h5')
        else:
            local_stc_template = op.join(LOCAL_ROOT_DIR, 'stc_epochs', '{}_{}_{}_{}'.format(subject, cond_name, '{epoch_ind}', inverse_method))
            if len(glob.glob(local_stc_template.format(epoch_ind='*') == 36)):
                print('stc was already calculated for {}'.format(subject))
            else:
                stcs = apply_inverse_epochs(epochs[cond_name], inv, lambda2, inverse_method, pick_ori=None, return_generator=True)
                for epoch_ind, stc in enumerate(stcs):
                    if not os.path.isfile(local_stc_template.format(epoch_ind=epoch_ind)):
                        stc.save(local_stc_template.format(epoch_ind=epoch_ind), ftype='h5')
Exemple #7
0
def apply_STC_ave(fnevo, method='dSPM', snr=3.0):
    ''' Inverse evoked data into the source space.
        Parameter
        ---------
        fnevo: string or list
            The evoked file with ECG, EOG and environmental noise free.
        method:string
            Inverse method, 'MNE' or 'dSPM'
        snr: float
            Signal to noise ratio for inverse solution.
    '''
    #Get the default subjects_dir
    from mne.minimum_norm import apply_inverse, read_inverse_operator
    fnlist = get_files_from_list(fnevo)
    # loop across all filenames
    for fname in fnlist:
        name = os.path.basename(fname)
        fn_path = os.path.split(fname)[0]
        fn_stc = fname[:fname.rfind('-ave.fif')]
        # fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif'
        subject = name.split('_')[0]
        fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' % subject
        snr = snr
        lambda2 = 1.0 / snr ** 2
        # noise_cov = mne.read_cov(fn_cov)
        [evoked] = mne.read_evokeds(fname)
        evoked.pick_types(meg=True, ref_meg=False)
        inv = read_inverse_operator(fn_inv)
        stc = apply_inverse(evoked, inv, lambda2, method,
                            pick_ori='normal')
        stc.save(fn_stc)
def apply_STC_epo(fnepo, event, method='MNE', snr=1.0, min_subject='fsaverage',
                  subjects_dir=None):

    from mne import morph_data
    from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs

    fnlist = get_files_from_list(fnepo)
    # loop across all filenames
    for fname in fnlist:
        fn_path = os.path.split(fname)[0]
        name = os.path.basename(fname)
        subject = name.split('_')[0]
        min_dir = subjects_dir + '/%s' %min_subject
        snr = snr
        lambda2 = 1.0 / snr ** 2
        stcs_path = min_dir + '/stcs/%s/%s/' % (subject,event)
        reset_directory(stcs_path)
        # fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif'
        fn_inv = fn_path + '/%s_epo-inv.fif' %subject

        # noise_cov = mne.read_cov(fn_cov)
        epo = mne.read_epochs(fname)
        epo.pick_types(meg=True, ref_meg=False)
        inv = read_inverse_operator(fn_inv)
        stcs = apply_inverse_epochs(epo, inv, lambda2, method,
                            pick_ori='normal')
        s = 0
        while s < len(stcs):
            stc_morph = morph_data(subject, min_subject, stcs[s])
            stc_morph.save(stcs_path + '/trial%s_fsaverage'
                           % (str(s)), ftype='stc')
            s = s + 1
Exemple #9
0
def test_plot_snr():
    """Test plotting SNR estimate."""
    import matplotlib.pyplot as plt
    inv = read_inverse_operator(inv_fname)
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    plot_snr_estimate(evoked, inv)
    plt.close('all')
def plot_inverse_operator(subject, fnout_img=None, verbose=None):
    """"Reads in and plots the inverse solution."""

    # get name of inverse solution-file
    subjects_dir = os.environ.get('SUBJECTS_DIR')
    fname_dir_inv = os.path.join(subjects_dir,
                                 subject)

    for files in os.listdir(fname_dir_inv):
        if files.endswith(",cleaned_epochs_avg-7-src-meg-inv.fif"):
            fname_inv = os.path.join(fname_dir_inv,
                                     files)
            break

    try:
        fname_inv
    except NameError:
        print "ERROR: No forward solution found!"
        sys.exit()


    # read inverse solution
    inv = min_norm.read_inverse_operator(fname_inv)

    # print some information if desired
    if verbose is not None:
        print "Method: %s" % inv['methods']
        print "fMRI prior: %s" % inv['fmri_prior']
        print "Number of sources: %s" % inv['nsource']
        print "Number of channels: %s" % inv['nchan']


    # show 3D source space
    lh_points = inv['src'][0]['rr']
    lh_faces = inv['src'][0]['tris']
    rh_points = inv['src'][1]['rr']
    rh_faces = inv['src'][1]['tris']

    # create figure and plot results
    fig_inverse = mlab.figure(size=(1200, 1200),
                              bgcolor=(0, 0, 0))

    mlab.triangular_mesh(lh_points[:, 0],
                         lh_points[:, 1],
                         lh_points[:, 2],
                         lh_faces)

    mlab.triangular_mesh(rh_points[:, 0],
                         rh_points[:, 1],
                         rh_points[:, 2],
                         rh_faces)

    # save result
    if fnout_img is not None:
        mlab.savefig(fnout_img,
                     figure=fig_inverse,
                     size=(1200, 1200))

    mlab.close(all=True)
Exemple #11
0
def test_psf_ctf():
    """Test computation of PSFs and CTFs for linear estimators
    """

    inverse_operator = read_inverse_operator(fname_inv)
    forward = read_forward_solution(fname_fwd, force_fixed=False,
                                    surf_ori=True)
    forward = pick_types_forward(forward, meg=True, eeg=False)
    labels = [mne.read_label(ss) for ss in fname_label]

    method = 'MNE'
    n_svd_comp = 2

    # Test PSFs (then CTFs)
    for mode in ('sum', 'svd'):
        stc_psf, psf_ev = point_spread_function(inverse_operator,
                                                forward,
                                                method=method,
                                                labels=labels,
                                                lambda2=lambda2,
                                                pick_ori='normal',
                                                mode=mode,
                                                n_svd_comp=n_svd_comp)

        n_vert, n_samples = stc_psf.shape
        should_n_vert = (inverse_operator['src'][1]['vertno'].shape[0] +
                         inverse_operator['src'][0]['vertno'].shape[0])
        if mode == 'svd':
            should_n_samples = len(labels) * n_svd_comp + 1
        else:
            should_n_samples = len(labels) + 1

        assert_true(n_vert == should_n_vert)
        assert_true(n_samples == should_n_samples)

        n_chan, n_samples = psf_ev.data.shape
        assert_true(n_chan == forward['nchan'])

    forward = read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True)
    forward = pick_types_forward(forward, meg=True, eeg=False)

    # Test CTFs
    for mode in ('sum', 'svd'):
        stc_ctf = cross_talk_function(inverse_operator, forward,
                                      labels, method=method,
                                      lambda2=lambda2,
                                      signed=False, mode=mode,
                                      n_svd_comp=n_svd_comp)

        n_vert, n_samples = stc_ctf.shape
        should_n_vert = (inverse_operator['src'][1]['vertno'].shape[0] +
                         inverse_operator['src'][0]['vertno'].shape[0])
        if mode == 'svd':
            should_n_samples = len(labels) * n_svd_comp + 1
        else:
            should_n_samples = len(labels) + 1

        assert_true(n_vert == should_n_vert)
        assert_true(n_samples == should_n_samples)
Exemple #12
0
def calc_inv_kernel(fn_inv, method="dSPM", nave=1, snr=6.,
                    pick_ori="normal", verbose=None):

    """
    Interface for preparing the kernel of the inverse
    estimation.

        Parameters
        ----------
        fn_inv : String containing the filename
            of the inverse operator (must be a fif-file)
        method : string
            which source localization method should be used?
            MNE-based: "MNE" | "dSPM" | "sLORETA"
            default: method="dSPM"
        nave : number of averages used to regularize the solution
            default: nave=1
        snr : signal-to-noise ratio
            default: snr = 3.
        verbose : bool, str, int, or None
            If not None, override default verbose level
            (see mne.verbose).
            default: verbose=None
    """

    # -------------------------------------------
    # import necessary modules
    # -------------------------------------------
    import mne.minimum_norm as min_norm
    from mne.minimum_norm.inverse import _assemble_kernel
    import numpy as np

    # -------------------------------------------
    # estimate inverse kernel
    # -------------------------------------------
    # load inverse solution
    inv_operator = min_norm.read_inverse_operator(fn_inv, verbose=verbose)

    # set up the inverse according to the parameters
    lambda2      = 1. / snr ** 2.   # the regularization parameter.
    inv_operator = min_norm.prepare_inverse_operator(inv_operator, nave, lambda2, method)

    # estimate inverse kernel and noise normalization coefficient
    kernel, noise_norm, vertno = _assemble_kernel(inv_operator, None, method, pick_ori)

    if method == "MNE":
        noise_norm = np.ones((kernel.shape[0]/3))
        noise_norm = noise_norm[:, np.newaxis]


    # -------------------------------------------
    # return results
    # -------------------------------------------
    return kernel, noise_norm, vertno
Exemple #13
0
def test_surface_vector_source_morph():
    """Test surface and vector source estimate morph."""
    tempdir = _TempDir()

    inverse_operator_surf = read_inverse_operator(fname_inv_surf)

    stc_surf = read_source_estimate(fname_smorph, subject='sample')
    stc_surf.crop(0.09, 0.1)  # for faster computation

    stc_vec = _real_vec_stc()

    source_morph_surf = compute_source_morph(
        inverse_operator_surf['src'], subjects_dir=subjects_dir,
        smooth=1, warn=False)  # smooth 1 for speed
    assert source_morph_surf.subject_from == 'sample'
    assert source_morph_surf.subject_to == 'fsaverage'
    assert source_morph_surf.kind == 'surface'
    assert isinstance(source_morph_surf.src_data, dict)
    assert isinstance(source_morph_surf.src_data['vertices_from'], list)
    assert isinstance(source_morph_surf, SourceMorph)
    stc_surf_morphed = source_morph_surf.apply(stc_surf)
    assert isinstance(stc_surf_morphed, SourceEstimate)
    stc_vec_morphed = source_morph_surf.apply(stc_vec)
    with pytest.raises(ValueError, match='Only volume source estimates'):
        source_morph_surf.apply(stc_surf, output='nifti1')

    # check if correct class after morphing
    assert isinstance(stc_surf_morphed, SourceEstimate)
    assert isinstance(stc_vec_morphed, VectorSourceEstimate)

    # check __repr__
    assert 'surface' in repr(source_morph_surf)

    # check loading and saving for surf
    source_morph_surf.save(op.join(tempdir, '42.h5'))

    source_morph_surf_r = read_source_morph(op.join(tempdir, '42.h5'))

    assert (all([read == saved for read, saved in
                 zip(sorted(source_morph_surf_r.__dict__),
                     sorted(source_morph_surf.__dict__))]))

    # check wrong subject correction
    stc_surf.subject = None
    assert isinstance(source_morph_surf.apply(stc_surf), SourceEstimate)

    # degenerate
    stc_vol = read_source_estimate(fname_vol, 'sample')
    with pytest.raises(ValueError, match='stc_from was type'):
        source_morph_surf.apply(stc_vol)
Exemple #14
0
def test_snr():
    """Test SNR calculation"""
    tempdir = _TempDir()
    inv = read_inverse_operator(fname_inv)
    evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0]
    snr = estimate_snr(evoked, inv)[0]
    orig_dir = os.getcwd()
    os.chdir(tempdir)
    try:
        cmd = ['mne_compute_mne', '--inv', fname_inv, '--meas', fname_evoked,
               '--snronly', '--bmin', '-200', '--bmax', '0']
        run_subprocess(cmd)
    except Exception:
        pass  # this returns 1 for some reason
    finally:
        os.chdir(orig_dir)
    snr_c = np.loadtxt(op.join(tempdir, 'SNR'))[:, 1]
    assert_allclose(snr, snr_c, atol=1e-2, rtol=1e-2)
Exemple #15
0
def apply_STC_ave(fnevo, method='dSPM', snr=3.0, min_subject='fsaverage'):
    ''' Inverse evoked data into the source space. 
        Parameter
        ---------
        fnevo: string or list
            The evoked file with ECG, EOG and environmental noise free.
        method:string
            Inverse method, 'MNE' or 'dSPM'
        snr: float
            Signal to noise ratio for inverse solution.
        event: string
            The event name related with evoked data.
        baseline: bool
            If true, prestimulus segment from 'btmin' to 'btmax' will be saved, 
            If false, no baseline segment is saved.
        btmin: float
            The start time point (second) of baseline.
        btmax: float
            The end time point(second) of baseline.
        min_subject: string
            The subject name as the common brain.
    '''
    #Get the default subjects_dir
    from mne.minimum_norm import apply_inverse, read_inverse_operator
    fnlist = get_files_from_list(fnevo)
    # loop across all filenames
    for fname in fnlist:
        name = os.path.basename(fname)
        fn_path = os.path.split(fname)[0]
        fn_stc = fname[:fname.rfind('-ave.fif')] 
        #fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' 
        subject = name.split('_')[0]
        fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' %subject
        snr = snr
        lambda2 = 1.0 / snr ** 2 
        #noise_cov = mne.read_cov(fn_cov)
        [evoked] = mne.read_evokeds(fname)
        evoked.pick_types(meg=True, ref_meg=False)
        inv = read_inverse_operator(fn_inv)
        stc = apply_inverse(evoked, inv, lambda2, method,
                            pick_ori='normal')
        stc.save(fn_stc)
def get_mne_stc(ndvar=False, vol=False, subject='sample'):
    """MNE-Python SourceEstimate

    Parameters
    ----------
    ndvar : bool
        Convert to NDVar (default False; src="ico-4" is false, but it works as
        long as the source space is not accessed).
    vol : bool
        Volume source estimate.
    """
    data_path = Path(mne.datasets.testing.data_path())
    meg_sdir = data_path / 'MEG/sample'
    subjects_dir = data_path / 'subjects'
    # scaled subject
    if subject == 'fsaverage_scaled':
        subject_dir = os.path.join(subjects_dir, subject)
        if not os.path.exists(subject_dir):
            mne.scale_mri('fsaverage', subject, .9, subjects_dir=subjects_dir, skip_fiducials=True, labels=False, annot=True)
        data_subject = 'fsaverage'
    else:
        data_subject = subject

    if vol:
        inv = mn.read_inverse_operator(str(meg_sdir / 'sample_audvis_trunc-meg-vol-7-meg-inv.fif'))
        evoked = mne.read_evokeds(str(meg_sdir / 'sample_audvis_trunc-ave.fif'), 'Left Auditory')
        stc = mn.apply_inverse(evoked, inv, method='MNE', pick_ori='vector')
        if data_subject == 'fsaverage':
            m = mne.compute_source_morph(stc, 'sample', data_subject, subjects_dir)
            stc = m.apply(stc)
            stc.subject = subject
        elif subject != 'sample':
            raise ValueError(f"subject={subject!r}")
        if ndvar:
            return load.fiff.stc_ndvar(stc, subject, 'vol-7', subjects_dir, 'MNE', sss_filename='{subject}-volume-7mm-src.fif')
        else:
            return stc
    stc_path = meg_sdir / f'{data_subject}_audvis_trunc-meg'
    if ndvar:
        return load.fiff.stc_ndvar(stc_path, subject, 'ico-5', subjects_dir)
    else:
        return mne.read_source_estimate(str(stc_path), subject)
def load(typ, subject='fsaverage', analysis='analysis', block=999,
         download=True, preload=False):
    """Auxiliary saving function."""
    # get file name
    fname = paths(typ, subject=subject, analysis=analysis, block=block)

    # check if file exists
    if not op.exists(fname) and download:
        client.download(fname)

    # different data format depending file type
    if typ == 'behavior':
        from base import read_events
        out = read_events(fname)
    elif typ == 'sss':
        out = Raw(fname, preload=preload)
    elif typ in ['epo_block', 'epochs', 'epochs_decim', 'epochs_vhp']:
        out = read_epochs(fname, preload=preload)
    elif typ in ['cov']:
        from mne.cov import read_cov
        out = read_cov(fname)
    elif typ in ['fwd']:
        from mne import read_forward_solution
        out = read_forward_solution(fname, surf_ori=True)
    elif typ in ['inv']:
        from mne.minimum_norm import read_inverse_operator
        out = read_inverse_operator(fname)
    elif typ in ['evoked', 'decod', 'decod_tfr', 'score', 'score_tfr',
                 'evoked_source']:
        with open(fname, 'rb') as f:
            out = pickle.load(f)
    elif typ == 'morph':
        from scipy.sparse import csr_matrix
        loader = np.load(fname)
        out = csr_matrix((loader['data'], loader['indices'], loader['indptr']),
                         shape=loader['shape'])
    elif typ in ['score_source', 'score_pval']:
        out = np.load(fname)
    else:
        raise NotImplementedError()
    return out
Exemple #18
0
def _calc_inverse(params):
    subject, epochs, overwrite = params
    epo = op.join(REMOTE_ROOT_DIR, 'ave', '{}_ecr_nTSSS_conflict-epo.fif'.format(subject))
    fwd = op.join(REMOTE_ROOT_DIR, 'fwd', '{}_ecr-fwd.fif'.format(subject))
    local_inv_file_name = op.join(LOCAL_ROOT_DIR, 'inv', '{}_ecr_nTSSS_conflict-inv.fif'.format(subject))

    if os.path.isfile(local_inv_file_name) and not overwrite:
        inverse_operator = read_inverse_operator(local_inv_file_name)
        print('inv already calculated for {}'.format(subject))
    else:
        if epochs is None:
            epochs = mne.read_epochs(epo)
        noise_cov = mne.compute_covariance(epochs.crop(None, 0, copy=True))
        inverse_operator = None
        if not os.path.isfile(fwd):
            print('no fwd for {}'.format(subject))
        else:
            forward = mne.read_forward_solution(fwd)
            inverse_operator = make_inverse_operator(epochs.info, forward, noise_cov,
                loose=None, depth=None)
            write_inverse_operator(local_inv_file_name, inverse_operator)
    return inverse_operator
def test_stc_as_volume():
    """Test previous volume source estimate morph."""
    import nibabel as nib
    inverse_operator_vol = read_inverse_operator(fname_inv_vol)

    # Apply inverse operator
    stc_vol = read_source_estimate(fname_vol, 'sample')

    img = stc_vol.as_volume(inverse_operator_vol['src'], mri_resolution=True,
                            dest='42')
    t1_img = nib.load(fname_t1)
    # always assure nifti and dimensionality
    assert isinstance(img, nib.Nifti1Image)
    assert img.header.get_zooms()[:3] == t1_img.header.get_zooms()[:3]

    img = stc_vol.as_volume(inverse_operator_vol['src'], mri_resolution=False)

    assert isinstance(img, nib.Nifti1Image)
    assert img.shape[:3] == inverse_operator_vol['src'][0]['shape'][:3]

    with pytest.raises(ValueError, match='invalid output'):
        stc_vol.as_volume(inverse_operator_vol['src'], format='42')
Exemple #20
0
def test_extract_label_time_course():
    """Test extraction of label time courses from stc."""
    n_stcs = 3
    n_times = 50

    src = read_inverse_operator(fname_inv)['src']
    vertices = [src[0]['vertno'], src[1]['vertno']]
    n_verts = len(vertices[0]) + len(vertices[1])

    # get some labels
    labels_lh = read_labels_from_annot('sample',
                                       hemi='lh',
                                       subjects_dir=subjects_dir)
    labels_rh = read_labels_from_annot('sample',
                                       hemi='rh',
                                       subjects_dir=subjects_dir)
    labels = list()
    labels.extend(labels_lh[:5])
    labels.extend(labels_rh[:4])

    n_labels = len(labels)

    label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))
    label_maxs = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))

    # compute the mean with sign flip
    label_means_flipped = np.zeros_like(label_means)
    for i, label in enumerate(labels):
        label_means_flipped[i] = i * np.mean(label_sign_flip(label, src))

    # generate some stc's with known data
    stcs = list()
    for i in range(n_stcs):
        data = np.zeros((n_verts, n_times))
        # set the value of the stc within each label
        for j, label in enumerate(labels):
            if label.hemi == 'lh':
                idx = np.intersect1d(vertices[0], label.vertices)
                idx = np.searchsorted(vertices[0], idx)
            elif label.hemi == 'rh':
                idx = np.intersect1d(vertices[1], label.vertices)
                idx = len(vertices[0]) + np.searchsorted(vertices[1], idx)
            data[idx] = label_means[j]

        this_stc = SourceEstimate(data, vertices, 0, 1)
        stcs.append(this_stc)

    # test some invalid inputs
    pytest.raises(ValueError,
                  extract_label_time_course,
                  stcs,
                  labels,
                  src,
                  mode='notamode')

    # have an empty label
    empty_label = labels[0].copy()
    empty_label.vertices += 1000000
    pytest.raises(ValueError,
                  extract_label_time_course,
                  stcs,
                  empty_label,
                  src,
                  mode='mean')

    # but this works:
    with pytest.warns(RuntimeWarning, match='does not contain any vertices'):
        tc = extract_label_time_course(stcs,
                                       empty_label,
                                       src,
                                       mode='mean',
                                       allow_empty=True)
    for arr in tc:
        assert (arr.shape == (1, n_times))
        assert_array_equal(arr, np.zeros((1, n_times)))

    # test the different modes
    modes = ['mean', 'mean_flip', 'pca_flip', 'max']

    for mode in modes:
        label_tc = extract_label_time_course(stcs, labels, src, mode=mode)
        label_tc_method = [
            stc.extract_label_time_course(labels, src, mode=mode)
            for stc in stcs
        ]
        assert (len(label_tc) == n_stcs)
        assert (len(label_tc_method) == n_stcs)
        for tc1, tc2 in zip(label_tc, label_tc_method):
            assert (tc1.shape == (n_labels, n_times))
            assert (tc2.shape == (n_labels, n_times))
            assert (np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16))
            if mode == 'mean':
                assert_array_almost_equal(tc1, label_means)
            if mode == 'mean_flip':
                assert_array_almost_equal(tc1, label_means_flipped)
            if mode == 'max':
                assert_array_almost_equal(tc1, label_maxs)

    # test label with very few vertices (check SVD conditionals)
    label = Label(vertices=src[0]['vertno'][:2], hemi='lh')
    x = label_sign_flip(label, src)
    assert (len(x) == 2)
    label = Label(vertices=[], hemi='lh')
    x = label_sign_flip(label, src)
    assert (x.size == 0)
        # Reading epochs
        epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'     
        epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'
            
        epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
        epochs_ld = mne.read_epochs(epo_name_LD, preload=True)
        
        epochs_SD = epochs_sd['words'] 
        epochs_LD = epochs_ld['words'] 
    
       
        # Reading inverse operator
        inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
        inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'
    
        inv_op_SD = read_inverse_operator(inv_fname_SD) 
        inv_op_LD = read_inverse_operator(inv_fname_LD) 

        
        # Evoked responses 
        evoked_sd = epochs_SD.average().set_eeg_reference(ref_channels = \
                            'average',projection=True)
        evoked_ld = epochs_LD.average().set_eeg_reference(ref_channels = \
                            'average',projection=True)
        evoked_SD = evoked_sd.copy().resample(500)
        evoked_LD = evoked_ld.copy().resample(500)
        # evoked_SD = evoked_sd.copy()
        # evoked_LD = evoked_ld.copy()

        # Applying inverse solution to get sourse signals    
        stc_sd = apply_inverse(evoked_SD, inv_op_SD,lambda2,method ='MNE', 
Exemple #22
0
def test_source_psd_epochs(method):
    """Test multi-taper source PSD computation in label from epochs."""
    raw = read_raw_fif(fname_data)
    inverse_operator = read_inverse_operator(fname_inv)
    label = read_label(fname_label)

    event_id, tmin, tmax = 1, -0.2, 0.5
    lambda2 = 1. / 9.
    bandwidth = 8.
    fmin, fmax = 0, 100

    picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
                       ecg=True, eog=True, include=['STI 014'],
                       exclude='bads')
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

    events = find_events(raw, stim_channel='STI 014')
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject)

    # only look at one epoch
    epochs.drop_bad()
    one_epochs = epochs[:1]

    inv = prepare_inverse_operator(inverse_operator, nave=1,
                                   lambda2=1. / 9., method="dSPM")
    # return list
    stc_psd = compute_source_psd_epochs(one_epochs, inv,
                                        lambda2=lambda2, method=method,
                                        pick_ori="normal", label=label,
                                        bandwidth=bandwidth,
                                        fmin=fmin, fmax=fmax,
                                        prepared=True)[0]

    # return generator
    stcs = compute_source_psd_epochs(one_epochs, inv,
                                     lambda2=lambda2, method=method,
                                     pick_ori="normal", label=label,
                                     bandwidth=bandwidth,
                                     fmin=fmin, fmax=fmax,
                                     return_generator=True,
                                     prepared=True)

    for stc in stcs:
        stc_psd_gen = stc

    assert_allclose(stc_psd.data, stc_psd_gen.data, atol=1e-7)

    # compare with direct computation
    stc = apply_inverse_epochs(one_epochs, inv,
                               lambda2=lambda2, method=method,
                               pick_ori="normal", label=label,
                               prepared=True)[0]

    sfreq = epochs.info['sfreq']
    psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq,
                                      bandwidth=bandwidth, fmin=fmin,
                                      fmax=fmax)

    assert_allclose(psd, stc_psd.data, atol=1e-7)
    assert_allclose(freqs, stc_psd.times)

    # Check corner cases caused by tiny bandwidth
    with pytest.raises(ValueError, match='use a value of at least'):
        compute_source_psd_epochs(
            one_epochs, inv, lambda2=lambda2, method=method,
            pick_ori="normal", label=label, bandwidth=0.01, low_bias=True,
            fmin=fmin, fmax=fmax, return_generator=False, prepared=True)
from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs

from my_settings import (mne_folder, epochs_folder, source_folder)

subject = sys.argv[1]

method = "dSPM"
snr = 1.
lambda2 = 1. / snr**2

labels = mne.read_labels_from_annot(
    subject=subject, parc="PALS_B12_Brodmann", regexp="Brodmann")

condition = "interupt"

inv = read_inverse_operator(mne_folder + "%s_%s-inv.fif" % (subject, condition
                                                            ))
epochs = mne.read_epochs(epochs_folder + "%s_%s-epo.fif" % (subject, condition
                                                            ))
# epochs.resample(500)

stcs = apply_inverse_epochs(
    epochs["press"], inv, lambda2, method=method, pick_ori=None)
ts = [
    mne.extract_label_time_course(
        stc, labels, inv["src"], mode="mean_flip") for stc in stcs
]

# for h, tc in enumerate(ts):
#     for j, t in enumerate(tc):
#         t *= np.sign(t[np.argmax(np.abs(t))])
#         tc[j, :] = t
Exemple #24
0
def SN_functional_connectivity_betweenROIs(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    con_SD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bands_SD_sub' + str(
        i) + '.json'
    con_LD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bands_LD_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_SD = epochs_sd['words'].copy().resample(500)
    epochs_LD = epochs_ld['words'].copy().resample(500)

    # Equalize trial counts to eliminate bias
    equalize_epoch_counts([epochs_SD, epochs_LD])

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_sd = apply_inverse_epochs(epochs_SD,
                                  inv_op_SD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    times = epochs_SD.times
    stc_SD_t = []
    stc_LD_t = []

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    for n in np.arange(0, len(stc_sd)):
        stc_SD_t.append(stc_baseline_correction(stc_sd[n], times))
        stc_LD_t.append(stc_baseline_correction(stc_ld[n], times))

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_SD = []
        stc_LD = []
        for n in np.arange(0, len(stc_sd)):
            stc_SD.append(stc_SD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
            stc_LD.append(stc_LD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            # print('[i,win,k]: ',i,win,k)
            morphed_labels[k].name = C.rois_labels[k]

        labels_ts_sd = mne.extract_label_time_course(stc_SD, morphed_labels, \
                   src_SD, mode='mean_flip',return_generator=False)
        labels_ts_ld = mne.extract_label_time_course(stc_LD, morphed_labels, \
                   src_LD, mode='mean_flip',return_generator=False)

        for f in np.arange(0, len(C.con_freq_band) - 1):
            print('[i,win,k,f]: ', i, win, k, f)
            f_min = C.con_freq_band[f]
            f_max = C.con_freq_band[f + 1]
            print(f_min, f_max)

            con_SD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                labels_ts_sd,
                method=method,
                mode='fourier',
                sfreq=500,
                fmin=f_min,
                fmax=f_max,
                faverage=True,
                n_jobs=10)

            con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                labels_ts_ld,
                method=method,
                mode='fourier',
                sfreq=500,
                fmin=f_min,
                fmax=f_max,
                faverage=True,
                n_jobs=10)

            con_labels_SD[win][f] = con_SD.reshape(6, 6)
            con_labels_LD[win][f] = con_LD.reshape(6, 6)

    with open(con_SD_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_SD, fp)

    with open(con_LD_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_LD, fp)
    e = time.time()
    print(e - s)
def test_extract_label_time_course():
    """Test extraction of label time courses from stc
    """
    n_stcs = 3
    n_times = 50

    src = read_inverse_operator(fname_inv)['src']
    vertices = [src[0]['vertno'], src[1]['vertno']]
    n_verts = len(vertices[0]) + len(vertices[1])

    # get some labels
    labels_lh, _ = labels_from_parc('sample', hemi='lh',
                                    subjects_dir=subjects_dir)
    labels_rh, _ = labels_from_parc('sample', hemi='rh',
                                    subjects_dir=subjects_dir)
    labels = list()
    labels.extend(labels_lh[:5])
    labels.extend(labels_rh[:4])

    n_labels = len(labels)

    label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))

    # compute the mean with sign flip
    label_means_flipped = np.zeros_like(label_means)
    for i, label in enumerate(labels):
        label_means_flipped[i] = i * np.mean(label_sign_flip(label, src))

    # generate some stc's with known data
    stcs = list()
    for i in range(n_stcs):
        data = np.zeros((n_verts, n_times))
        # set the value of the stc within each label
        for j, label in enumerate(labels):
            if label.hemi == 'lh':
                idx = np.intersect1d(vertices[0], label.vertices)
                idx = np.searchsorted(vertices[0], idx)
            elif label.hemi == 'rh':
                idx = np.intersect1d(vertices[1], label.vertices)
                idx = len(vertices[0]) + np.searchsorted(vertices[1], idx)
            data[idx] = label_means[j]

        this_stc = SourceEstimate(data, vertices, 0, 1)
        stcs.append(this_stc)

    # test some invalid inputs
    assert_raises(ValueError, extract_label_time_course, stcs, labels,
                  src, mode='notamode')

    # have an empty label
    empty_label = labels[0].copy()
    empty_label.vertices += 1000000
    assert_raises(ValueError, extract_label_time_course, stcs, empty_label,
                  src, mode='mean')

    # but this works:
    tc = extract_label_time_course(stcs, empty_label, src, mode='mean',
                                   allow_empty=True)
    for arr in tc:
        assert_true(arr.shape == (1, n_times))
        assert_array_equal(arr, np.zeros((1, n_times)))

    # test the different modes
    modes = ['mean', 'mean_flip', 'pca_flip']

    for mode in modes:
        label_tc = extract_label_time_course(stcs, labels, src, mode=mode)
        label_tc_method = [stc.extract_label_time_course(labels, src,
                           mode=mode) for stc in stcs]
        assert_true(len(label_tc) == n_stcs)
        assert_true(len(label_tc_method) == n_stcs)
        for tc1, tc2 in zip(label_tc, label_tc_method):
            assert_true(tc1.shape == (n_labels, n_times))
            assert_true(tc2.shape == (n_labels, n_times))
            assert_true(np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16))
            if mode == 'mean':
                assert_array_almost_equal(tc1, label_means)
            if mode == 'mean_flip':
                assert_array_almost_equal(tc1, label_means_flipped)
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'

# Read evoked data
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))

# Read inverse solution
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
inv = read_inverse_operator(fname_inv)

# Apply inverse solution, set pick_ori='vector' to obtain a
# :class:`mne.VectorSourceEstimate` object
snr = 3.0
lambda2 = 1.0 / snr**2
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')

# Use peak getter to move visualization to the time point of the peak magnitude
_, peak_time = stc.magnitude().get_peak(hemi='lh')

###############################################################################
# Plot the source estimate:
brain = stc.plot(initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir)

###############################################################################
Exemple #27
0
def SN_functional_connectivity_bands(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    stc_SD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_equalized_bands_SD_sub' + str(
        i) + '.json'
    stc_LD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_equalized_bands_LD_sub' + str(
        i) + '.json'
    # stc_SD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/stc_'+method+'bl_bands_SD_sub'+str(i)+'.json'
    # stc_LD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/stc_'+method+'bl_bands_LD_sub'+str(i)+'.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_SD = epochs_sd['words'].copy().resample(500)
    epochs_LD = epochs_ld['words'].copy().resample(500)

    equalize_epoch_counts([epochs_SD, epochs_LD])
    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_sd = apply_inverse_epochs(epochs_SD,
                                  inv_op_SD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']
    # Construct indices to estimate connectivity between the label time course
    # and all source space time courses
    vertices_SD = [src_SD[j]['vertno'] for j in range(2)]
    n_signals_tot = 1 + len(vertices_SD[0]) + len(vertices_SD[1])
    indices = seed_target_indices([0], np.arange(1, n_signals_tot))

    morph_SD = mne.compute_source_morph(src=inv_op_SD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    morph_LD = mne.compute_source_morph(src= inv_op_LD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_SD = []
        stc_LD = []

        for n in np.arange(0, len(stc_sd)):
            stc_SD.append(stc_sd[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for n in np.arange(0, len(stc_ld)):
            stc_LD.append(stc_ld[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            print('[i,win,k]: ', i, win, k)
            morphed_labels[k].name = C.rois_labels[k]

            seed_ts_sd = mne.extract_label_time_course(stc_SD, morphed_labels[k], \
                        src_SD, mode='mean_flip',return_generator=False)
            seed_ts_ld = mne.extract_label_time_course(stc_LD, morphed_labels[k], \
                        src_LD, mode='mean_flip',return_generator=False)

            for f in np.arange(0, len(C.con_freq_band) - 1):
                print('[i,win,k,f]: ', i, win, k, f)
                f_min = C.con_freq_band[f]
                f_max = C.con_freq_band[f + 1]
                print(f_min, f_max)

                comb_ts_sd = zip(seed_ts_sd, stc_SD)
                comb_ts_ld = zip(seed_ts_ld, stc_LD)

                con_SD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_sd,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_ld,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_stc_SD = mne.SourceEstimate(con_SD, vertices=vertices_SD,\
                              tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                con_stc_LD = mne.SourceEstimate(con_LD, vertices=vertices_SD,\
                              tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                stc_total_SD[win][k][f] = morph_SD.apply(con_stc_SD)
                stc_total_LD[win][k][f] = morph_LD.apply(con_stc_LD)

    with open(stc_SD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_SD, fp)

    with open(stc_LD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_LD, fp)
    e = time.time()
    print(e - s)
from metacog.utils import setup_logging

logger = setup_logging(__file__)

parser = ArgumentParser(description=__doc__)
parser.add_argument("subject", help="subject id")
args = parser.parse_args()
subj = args.subject

fwd_path = bp.fwd.fpath(subject=subj)
fwd = read_forward_solution(fwd_path)
inv_path = bp.inv.fpath(subject=subj)

epochs_path = bp.epochs.fpath(subject=subj)
epochs = read_epochs(epochs_path)["answer"]
inverse_operator = read_inverse_operator(inv_path)

# stcs_low = source_band_induced_power(
#     epochs["low"],
#     inverse_operator,
#     bands,
#     n_cycles=2,
#     use_fft=False,
#     n_jobs=4,
#     decim=2,
#     baseline=(-1, 0),
# )

epochs_active = epochs.copy().crop(tmin=cfg.config_sources["active_win"][0],
                                   tmax=cfg.config_sources["active_win"][1])
epochs_base = epochs.copy().crop(
Exemple #29
0
def test_plot_snr():
    """Test plotting SNR estimate."""
    inv = read_inverse_operator(inv_fname)
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    plot_snr_estimate(evoked, inv)
# params
for subject in subjects:
    print (subject)
    subj_dir = '%s%s/'%(meg_dir,subject)

    # paths
    epochs_fname = subj_dir + subject+ '_shepard-epo.fif'
    inv_fname = subj_dir+subject+'_shepard-inv.fif'


    print ("Loading variables...")
    epochs = read_epochs(epochs_fname)
    epochs.metadata['freq'].replace(524,523,inplace=True)

    inverse_operator = read_inverse_operator(inv_fname)
    src = inverse_operator['src']

    # make stcs for each frequency for each tonetype
    for tonetype in tonetypes:
        print("Beginning %s tones..."%(tonetype))
        # frequencies = np.sort(epochs.metadata[np.logical_and(epochs.metadata['key']==key,
        #                                                 epochs.metadata['condition']==tonetype)].freq.unique())
        for freq in frequencies:
            print(freq)

            freq_epochs = epochs[(epochs.metadata['condition']==tonetype) &
                            (epochs.metadata['freq']==freq) &
                            (epochs.metadata['key']==key)]
            evoked = freq_epochs.average()
        # if there is no baseline, e.g., in resting state data
        # there is no stimulus, use empty room noise cov
        fn_cov = fn_epo.split('-epo.fif')[0] + '-cov.fif'
        fn_inv = fn_epo.rsplit('-epo.fif')[0] + '-inv.fif'

        # to read forward solution and noise_cov

        noise_cov = mne.read_cov(fn_cov)

        if not op.isfile(fn_inv):
            # compute the inverse operator (mne_do_inverse_operator)
            inv = make_inverse_operator(epochs.info, fwd, noise_cov, loose=0.2,
                                        depth=0.8, limit_depth_chs=False)
            write_inverse_operator(fn_inv, inv)
        else:
            inv = read_inverse_operator(fn_inv)

        evoked = epochs.average()

        # Compute inverse solution for evoked data
        fn_stc = fn_epo.rsplit('-epo.fif')[0] + ',ave'

        if not op.isfile(fn_stc + '-lh.stc'):
            stc = apply_inverse(evoked, inv, lambda2, method, pick_ori=None)
            stc.save(fn_stc)
            print('Saved...', fn_stc + '-lh.stc')

        if plot_stc:

            stc = mne.read_source_estimate(fn_stc + '-lh.stc')
            pos, t_peak = stc.get_peak(hemi=None, tmin=0., tmax=0.5,
Exemple #32
0
from mne.minimum_norm import read_inverse_operator, apply_inverse

from my_settings import (mne_folder, epochs_folder, conditions, source_folder)

subject = sys.argv[1]

method = "dSPM"
snr = 3.
lambda2 = 1. / snr**2

labels = mne.read_labels_from_annot(subject=subject,
                                    parc="PALS_B12_Brodmann",
                                    regexp="Brodmann")

for condition in conditions:
    inv = read_inverse_operator(mne_folder + "%s_%s-inv.fif" %
                                (subject, condition))
    evoked = mne.read_evokeds(epochs_folder + "%s_%s-ave.fif" %
                              (subject, condition))[0]

    stc = apply_inverse(evoked, inv, lambda2, method=method, pick_ori=None)
    ts = mne.extract_label_time_course(stc,
                                       labels,
                                       inv["src"],
                                       mode="mean_flip")
    # for j, t in enumerate(ts):
    #     t *= np.sign(t[np.argmax(np.abs(t))])
    #     ts[j, :] = t

    stc.save(source_folder + "%s_%s_ave" % (subject, condition))
    np.save(source_folder + "ave_ts/%s_%s_ts.npy" % (subject, condition), ts)
Exemple #33
0
def SN_functional_connectivity_bands_runs(i, method, SN_ROI):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    stc_F_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_F_bands_SD_sub' + str(
        i) + '.json'
    stc_O_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_O_bands_LD_sub' + str(
        i) + '.json'
    stc_M_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_M_bands_SD_sub' + str(
        i) + '.json'
    stc_SD_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_mean_bands_SD_sub' + str(
        i) + '.json'
    stc_LD_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_mean_bands_LD_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,
                                      subject_to=sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)

    # Reading epochs

    # Reading epochs
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_LD = epochs_ld['words'].copy().resample(500)

    epoch_fname_fruit = data_path + meg + 'block_fruit_epochs-epo.fif'
    epoch_fname_odour = data_path + meg + 'block_odour_epochs-epo.fif'
    epoch_fname_milk = data_path + meg + 'block_milk_epochs-epo.fif'

    epochs_fruit = mne.read_epochs(epoch_fname_fruit, preload=True)
    epochs_odour = mne.read_epochs(epoch_fname_odour, preload=True)
    epochs_milk = mne.read_epochs(epoch_fname_milk, preload=True)

    epochs_f = mne.epochs.combine_event_ids(
        epochs_fruit, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_o = mne.epochs.combine_event_ids(
        epochs_odour, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_m = mne.epochs.combine_event_ids(
        epochs_milk, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})

    epochs_f = epochs_f['words'].copy().resample(500)
    epochs_o = epochs_o['words'].copy().resample(500)
    epochs_m = epochs_m['words'].copy().resample(500)

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_f = apply_inverse_epochs(epochs_f,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_o = apply_inverse_epochs(epochs_o,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_m = apply_inverse_epochs(epochs_m,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    # Construct indices to estimate connectivity between the label time course
    # and all source space time courses
    vertices_SD = [src_SD[j]['vertno'] for j in range(2)]
    n_signals_tot = 1 + len(vertices_SD[0]) + len(vertices_SD[1])
    indices = seed_target_indices([0], np.arange(1, n_signals_tot))

    morph_SD = mne.compute_source_morph(src=inv_op_SD['src'],
                                        subject_from=sub_to,
                                        subject_to=C.subject_to,
                                        spacing=C.spacing_morph,
                                        subjects_dir=C.data_path)
    morph_LD = mne.compute_source_morph(src=inv_op_LD['src'],
                                        subject_from=sub_to,
                                        subject_to=C.subject_to,
                                        spacing=C.spacing_morph,
                                        subjects_dir=C.data_path)

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_F = []
        stc_O = []
        stc_M = []
        stc_LD = []

        for n in np.arange(0, len(stc_f)):
            stc_F.append(stc_f[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_o)):
            stc_O.append(stc_o[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_m)):
            stc_M.append(stc_m[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_ld)):
            stc_LD.append(stc_ld[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            print('[i,win,k]: ', i, win, k)
            morphed_labels[k].name = C.rois_labels[k]

            seed_ts_f = mne.extract_label_time_course(stc_F,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_o = mne.extract_label_time_course(stc_O,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_m = mne.extract_label_time_course(stc_M,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_ld = mne.extract_label_time_course(stc_LD,
                                                       morphed_labels[k],
                                                       src_LD,
                                                       mode='mean_flip',
                                                       return_generator=False)

            for f in np.arange(0, len(C.con_freq_band) - 1):
                print('[i,win,k,f]: ', i, win, k, f)
                f_min = C.con_freq_band[f]
                f_max = C.con_freq_band[f + 1]
                print(f_min, f_max)

                comb_ts_f = zip(seed_ts_f, stc_F)
                comb_ts_o = zip(seed_ts_o, stc_O)
                comb_ts_m = zip(seed_ts_m, stc_M)
                comb_ts_ld = zip(seed_ts_ld, stc_LD)

                con_F, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_f,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_O, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_o,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_M, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_m,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)
                con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_ld,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_SD = (con_F + con_O + con_M) / 3

                con_stc_F = mne.SourceEstimate(con_F,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_O = mne.SourceEstimate(con_O,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_M = mne.SourceEstimate(con_M,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_SD = mne.SourceEstimate(con_SD,
                                                vertices=vertices_SD,
                                                tmin=t_min * 1e-3,
                                                tstep=2e-3,
                                                subject=sub_to)

                con_stc_LD = mne.SourceEstimate(con_LD,
                                                vertices=vertices_SD,
                                                tmin=t_min * 1e-3,
                                                tstep=2e-3,
                                                subject=sub_to)

                stc_total_F[win][k][f] = morph_SD.apply(con_stc_F)
                stc_total_O[win][k][f] = morph_SD.apply(con_stc_O)
                stc_total_M[win][k][f] = morph_SD.apply(con_stc_M)
                stc_total_SD[win][k][f] = morph_SD.apply(con_stc_SD)
                stc_total_LD[win][k][f] = morph_LD.apply(con_stc_LD)

    # with open(stc_F_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_F, fp)
    # with open(stc_O_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_O, fp)
    # with open(stc_M_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_M, fp)
    # with open(stc_SD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_SD, fp)
    with open(stc_LD_file_name, "wb") as fp:  # Pickling
        pickle.dump(stc_total_LD, fp)
    e = time.time()
    print(e - s)
Exemple #34
0
def test_apply_inverse_operator(evoked, inv, min_, max_):
    """Test MNE inverse application."""
    # use fname_inv as it will be faster than fname_full (fewer verts and chs)
    inverse_operator = read_inverse_operator(inv)

    # Inverse has 306 channels - 4 proj = 302
    assert (compute_rank_inverse(inverse_operator) == 302)

    # Inverse has 306 channels - 4 proj = 302
    assert (compute_rank_inverse(inverse_operator) == 302)

    stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE")
    assert stc.subject == 'sample'
    assert stc.data.min() > min_
    assert stc.data.max() < max_
    assert abs(stc).data.mean() > 1e-11

    # test if using prepared and not prepared inverse operator give the same
    # result
    inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave,
                                      lambda2=lambda2, method="MNE")
    stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE")
    assert_array_almost_equal(stc.data, stc2.data)
    assert_array_almost_equal(stc.times, stc2.times)

    # This is little more than a smoke test...
    stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA")
    assert stc.subject == 'sample'
    assert abs(stc).data.min() > 0
    assert 2 < stc.data.max() < 7
    assert abs(stc).data.mean() > 0.1

    stc = apply_inverse(evoked, inverse_operator, lambda2, "eLORETA")
    assert stc.subject == 'sample'
    assert abs(stc).data.min() > min_
    assert stc.data.max() < max_ * 2
    assert abs(stc).data.mean() > 1e-11

    stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM")
    assert stc.subject == 'sample'
    assert abs(stc).data.min() > 0
    assert 7.5 < stc.data.max() < 15
    assert abs(stc).data.mean() > 0.1

    # test without using a label (so delayed computation is used)
    label = read_label(fname_label % 'Aud-lh')
    for method in INVERSE_METHODS:
        stc = apply_inverse(evoked, inv_op, lambda2, method)
        stc_label = apply_inverse(evoked, inv_op, lambda2, method,
                                  label=label)
        assert_equal(stc_label.subject, 'sample')
        label_stc = stc.in_label(label)
        assert label_stc.subject == 'sample'
        assert_allclose(stc_label.data, label_stc.data)

    # Test that no errors are raised with loose inverse ops and picking normals
    noise_cov = read_cov(fname_cov)
    fwd = read_forward_solution_meg(fname_fwd)
    inv_op_meg = make_inverse_operator(
        evoked.info, fwd, noise_cov, loose=1,
        fixed='auto', depth=None)
    apply_inverse(evoked, inv_op_meg, 1 / 9., method='MNE', pick_ori='normal')

    # Test we get errors when using custom ref or no average proj is present
    evoked.info['custom_ref_applied'] = True
    pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
    evoked.info['custom_ref_applied'] = False
    evoked.info['projs'] = []  # remove EEG proj
    pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")

    # But test that we do not get EEG-related errors on MEG-only inv (gh-4650)
    apply_inverse(evoked, inv_op_meg, 1. / 9.)
effects=['A','A:B']
for i in np.arange(0, len(subjects)-17):
    n_subjects = len(subjects)
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    print('Participant : ' , i)

    for n in np.array([0]):
        # Reading epochs
        epo_name= data_path + meg + epochs_names[n]
        epochs = mne.read_epochs(epo_name, preload=True)
        epochs = epochs['words'].crop(-0.300,0.550).resample(500)
    
        # Reading inverse operator
        inv_fname = data_path + meg + inv_op_name[n]
        inv_op = read_inverse_operator(inv_fname) 
       
        print('Participant: ' , i,'/ condition: ',n)
        power, itc = source_induced_power(epochs,inverse_operator=\
                 inv_op, freqs=freq, label=None, lambda2=\
                 C.lambda2, method='MNE', baseline=(-.300,0), baseline_mode=\
                 'percent', n_jobs=6, n_cycles=n_cycles)
        X[i,:,:]  = power.copy().mean(1)
        Y[i,:,:]  = itc.copy().mean(1)

        inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    
        inv_op_SD = read_inverse_operator(inv_fname_SD) 

        morph_SD = mne.compute_source_morph( src= inv_op_SD['src'],subject_from\
                    = sub_to , subject_to = 'fsaverage' , spacing = \
Exemple #36
0
def test_volume_source_morph():
    """Test volume source estimate morph, special cases and exceptions."""
    import nibabel as nib
    tempdir = _TempDir()
    inverse_operator_vol = read_inverse_operator(fname_inv_vol)
    stc_vol = read_source_estimate(fname_vol, 'sample')

    # check for invalid input type
    with pytest.raises(TypeError, match='src must be an instance of'):
        compute_source_morph(src=42)

    # check for raising an error if neither
    # inverse_operator_vol['src'][0]['subject_his_id'] nor subject_from is set,
    # but attempting to perform a volume morph
    src = inverse_operator_vol['src']
    src[0]['subject_his_id'] = None

    with pytest.raises(ValueError, match='subject_from could not be inferred'):
        compute_source_morph(src=src, subjects_dir=subjects_dir)

    # check infer subject_from from src[0]['subject_his_id']
    src[0]['subject_his_id'] = 'sample'

    with pytest.raises(ValueError, match='Inter-hemispheric morphing'):
        compute_source_morph(src=src, subjects_dir=subjects_dir, xhemi=True)

    with pytest.raises(ValueError, match='Only surface.*sparse morph'):
        compute_source_morph(src=src, sparse=True, subjects_dir=subjects_dir)

    # terrible quality buts fast
    zooms = 20
    kwargs = dict(zooms=zooms, niter_sdr=(1,), niter_affine=(1,))
    source_morph_vol = compute_source_morph(
        subjects_dir=subjects_dir, src=inverse_operator_vol['src'], **kwargs)
    shape = (13,) * 3  # for the given zooms

    assert source_morph_vol.subject_from == 'sample'

    # the brain used in sample data has shape (255, 255, 255)
    assert tuple(source_morph_vol.sdr_morph.domain_shape) == shape

    assert tuple(source_morph_vol.pre_affine.domain_shape) == shape

    # proofs the above
    assert_array_equal(source_morph_vol.zooms, (zooms,) * 3)

    # assure proper src shape
    mri_size = (src[0]['mri_height'], src[0]['mri_depth'], src[0]['mri_width'])
    assert source_morph_vol.src_data['src_shape_full'] == mri_size

    fwd = read_forward_solution(fname_fwd_vol)
    source_morph_vol = compute_source_morph(
        fwd['src'], 'sample', 'sample', subjects_dir=subjects_dir,
        **kwargs)

    # check wrong subject_to
    with pytest.raises(IOError, match='cannot read file'):
        compute_source_morph(fwd['src'], 'sample', '42',
                             subjects_dir=subjects_dir)

    # two different ways of saving
    source_morph_vol.save(op.join(tempdir, 'vol'))

    # check loading
    source_morph_vol_r = read_source_morph(
        op.join(tempdir, 'vol-morph.h5'))

    # check for invalid file name handling ()
    with pytest.raises(IOError, match='not found'):
        read_source_morph(op.join(tempdir, '42'))

    # check morph
    stc_vol_morphed = source_morph_vol.apply(stc_vol)

    # check output as NIfTI
    assert isinstance(source_morph_vol.apply(stc_vol, output='nifti2'),
                      nib.Nifti2Image)

    # check for subject_from mismatch
    source_morph_vol_r.subject_from = '42'
    with pytest.raises(ValueError, match='subject_from must match'):
        source_morph_vol_r.apply(stc_vol_morphed)

    # check if nifti is in grid morph space with voxel_size == spacing
    img_morph_res = source_morph_vol.apply(stc_vol, output='nifti1')

    # assure morph spacing
    assert isinstance(img_morph_res, nib.Nifti1Image)
    assert img_morph_res.header.get_zooms()[:3] == (zooms,) * 3

    # assure src shape
    img_mri_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=True)
    assert isinstance(img_mri_res, nib.Nifti1Image)
    assert (img_mri_res.shape == (src[0]['mri_height'], src[0]['mri_depth'],
                                  src[0]['mri_width']) +
            (img_mri_res.shape[3],))

    # check if nifti is defined resolution with voxel_size == (5., 5., 5.)
    img_any_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=(5., 5., 5.))
    assert isinstance(img_any_res, nib.Nifti1Image)
    assert img_any_res.header.get_zooms()[:3] == (5., 5., 5.)

    # check if morph outputs correct data
    assert isinstance(stc_vol_morphed, VolSourceEstimate)

    # check if loaded and saved objects contain the same
    assert (all([read == saved for read, saved in
                 zip(sorted(source_morph_vol_r.__dict__),
                     sorted(source_morph_vol.__dict__))]))

    # check __repr__
    assert 'volume' in repr(source_morph_vol)

    # check Nifti2Image
    assert isinstance(
        source_morph_vol.apply(stc_vol, mri_resolution=True,
                               mri_space=True, output='nifti2'),
        nib.Nifti2Image)

    # Degenerate conditions
    with pytest.raises(TypeError, match='output must be'):
        source_morph_vol.apply(stc_vol, output=1)
    with pytest.raises(ValueError, match='subject_from does not match'):
        compute_source_morph(src=src, subject_from='42')
    with pytest.raises(ValueError, match='output must be one of'):
        source_morph_vol.apply(stc_vol, output='42')
    with pytest.raises(TypeError, match='subject_to must'):
        compute_source_morph(src, 'sample', None,
                             subjects_dir=subjects_dir)
    # Check if not morphed, but voxel size not boolean, raise ValueError.
    # Note that this check requires dipy to not raise the dipy ImportError
    # before checking if the actual voxel size error will raise.
    with pytest.raises(ValueError, match='Cannot infer original voxel size'):
        stc_vol.as_volume(inverse_operator_vol['src'], mri_resolution=4)
Exemple #37
0
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_inv_eegmeg = (data_path +
                    '/MEG/sample/sample_audvis-meg-eeg-oct-6-meg-eeg-inv.fif')
fname_inv_meg = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_label = [
    data_path + '/MEG/sample/labels/Aud-rh.label',
    data_path + '/MEG/sample/labels/Aud-lh.label',
    data_path + '/MEG/sample/labels/Vis-rh.label',
    data_path + '/MEG/sample/labels/Vis-lh.label'
]

# read forward solution
forward = mne.read_forward_solution(fname_fwd)

# read inverse operators
inverse_operator_eegmeg = read_inverse_operator(fname_inv_eegmeg)
inverse_operator_meg = read_inverse_operator(fname_inv_meg)

# read label(s)
labels = [mne.read_label(ss) for ss in fname_label]

# regularisation parameter
snr = 3.0
lambda2 = 1.0 / snr**2
method = 'MNE'  # can be 'MNE' or 'sLORETA'
mode = 'svd'
n_svd_comp = 1

stc_psf_eegmeg, _ = point_spread_function(inverse_operator_eegmeg,
                                          forward,
                                          method=method,
Exemple #38
0
The inverse operator's source space is shown in 3D.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator

print(__doc__)

data_path = sample.data_path()
fname = data_path
fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(fname)

print("Method: %s" % inv['methods'])
print("fMRI prior: %s" % inv['fmri_prior'])
print("Number of sources: %s" % inv['nsource'])
print("Number of channels: %s" % inv['nchan'])

###############################################################################
# Show result on 3D source space
lh_points = inv['src'][0]['rr']
lh_faces = inv['src'][0]['use_tris']
rh_points = inv['src'][1]['rr']
rh_faces = inv['src'][1]['use_tris']
try:
    from enthought.mayavi import mlab
except:
Exemple #39
0
conditions = ['EngGram', 'EngUngram', 'JabGram', 'JabUngram']
method = "dSPM"
snr = 3.
lambda2 = 1. / snr**2

source = mne.read_source_spaces(
    op.join(anat_path, 'BBC_249', 'bem', 'BBC_249-oct-6-src.fif'))
source_verts = [source[0]['vertno'], source[1]['vertno']]

for si, s in enumerate(subj):
    fwd = mne.read_forward_solution(
        op.join(data_path, '%s' % s, 'forward', '%s-sss-fwd.fif' % s))
    cov = mne.read_cov(
        op.join(data_path, '%s' % s, 'covariance', '%s-80-sss-cov.fif' % s))
    inv = read_inverse_operator(
        op.join(data_path, '%s' % s, 'inverse',
                '%s-80-sss-meg-free-inv.fif' % s))
    evokeds = [
        mne.read_evokeds(op.join(data_path, '%s' % s, 'inverse',
                                 'Conditions_80-sss_eq_%s-ave.fif' % s),
                         condition=c) for c in conditions
    ]
    stcs = [
        apply_inverse(e, inv, lambda2, method=method, pick_ori=None)
        for e in evokeds
    ]
    if not op.isdir(op.join(data_path, '%s' % s, 'stc')):
        os.mkdir(op.join(data_path, '%s' % s, 'stc'))
    for j, stc in enumerate(stcs):
        stc.save(
            op.join(data_path, '%s' % s, 'stc',
Exemple #40
0
        continue
    #initialize names   
    subject = "h%02d" % run
    fssub = "H%02d" % run #freesurfer subject 
    subjects_dir=op.join('/path/path/path/path/', '%s/RAW/fs_test/' % (fssub)) #create subject directory for freesurfer data
    print("processing subject: %s" % subject)
    src_fname=op.join('/path/path/path/path/%s/RAW/fs_test/%s/bem/%s-oct-6-src.fif' %(fssub, fssub, fssub))
    inv40_fname=op.join(data_path,'inv/', '%s_40hz-meg-oct-6-inv.fif' % (subject))
    cov40_fname=op.join(data_path, 'noise_cov/', '%s_noise_40-cov.fif' % (subject))
    fname40=op.join(data_path, 'epochs/', '%s_40epo.fif' % (subject))
    fwd_fname40=op.join(data_path, 'fwd/', '%s_40.fwd.fif' % (subject))
    epochs40=mne.read_epochs(fname40, proj=True, preload=True, verbose=None)
    evoked40 = epochs40.average()
    fwd40 =  mne.read_forward_solution(fwd_fname40, surf_ori=True)
    noise_cov40=mne.read_cov(cov40_fname)
    inverse_operator40 = read_inverse_operator(inv40_fname)
    # label information
    # read label information
    label_rh = mne.read_labels_from_annot(fssub, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=labeln_rh1)[0]

    label_lh = mne.read_labels_from_annot(fssub, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=labeln_lh1)[0]
    
    label_rh2 = mne.read_labels_from_annot(fssub, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=labeln_rh2)[0]
    
    label_lh2 = mne.read_labels_from_annot(fssub, parc='aparc',
Exemple #41
0
def _real_vec_stc():
    inv = read_inverse_operator(fname_inv_surf)
    evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01)
    return apply_inverse(evoked, inv, pick_ori='vector')
Exemple #42
0
 def make_inverse_operator():
     from mne.datasets import sample
     from mne.minimum_norm import read_inverse_operator
     data_path = sample.data_path()
     filename_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
     return read_inverse_operator(filename_inv, verbose='ERROR')
Exemple #43
0
def test_volume_source_morph(tmpdir):
    """Test volume source estimate morph, special cases and exceptions."""
    import nibabel as nib
    inverse_operator_vol = read_inverse_operator(fname_inv_vol)
    stc_vol = read_source_estimate(fname_vol_w, 'sample')

    # check for invalid input type
    with pytest.raises(TypeError, match='src must be'):
        compute_source_morph(src=42)

    # check for raising an error if neither
    # inverse_operator_vol['src'][0]['subject_his_id'] nor subject_from is set,
    # but attempting to perform a volume morph
    src = inverse_operator_vol['src']
    assert src._subject is None  # already None on disk (old!)

    with pytest.raises(ValueError, match='subject_from could not be inferred'):
        with pytest.warns(RuntimeWarning, match='recommend regenerating'):
            compute_source_morph(src=src, subjects_dir=subjects_dir)

    # check infer subject_from from src[0]['subject_his_id']
    src[0]['subject_his_id'] = 'sample'

    with pytest.raises(ValueError, match='Inter-hemispheric morphing'):
        compute_source_morph(src=src, subjects_dir=subjects_dir, xhemi=True)

    with pytest.raises(ValueError, match='Only surface.*sparse morph'):
        compute_source_morph(src=src, sparse=True, subjects_dir=subjects_dir)

    # terrible quality but fast
    zooms = 20
    kwargs = dict(zooms=zooms, niter_sdr=(1,), niter_affine=(1,))
    source_morph_vol = compute_source_morph(
        subjects_dir=subjects_dir, src=fname_inv_vol,
        subject_from='sample', **kwargs)
    shape = (13,) * 3  # for the given zooms

    assert source_morph_vol.subject_from == 'sample'

    # the brain used in sample data has shape (255, 255, 255)
    assert tuple(source_morph_vol.sdr_morph.domain_shape) == shape

    assert tuple(source_morph_vol.pre_affine.domain_shape) == shape

    # proofs the above
    assert_array_equal(source_morph_vol.zooms, (zooms,) * 3)

    # assure proper src shape
    mri_size = (src[0]['mri_height'], src[0]['mri_depth'], src[0]['mri_width'])
    assert source_morph_vol.src_data['src_shape_full'] == mri_size

    fwd = read_forward_solution(fname_fwd_vol)
    fwd['src'][0]['subject_his_id'] = 'sample'  # avoid further warnings
    source_morph_vol = compute_source_morph(
        fwd['src'], 'sample', 'sample', subjects_dir=subjects_dir,
        **kwargs)

    # check wrong subject_to
    with pytest.raises(IOError, match='cannot read file'):
        compute_source_morph(fwd['src'], 'sample', '42',
                             subjects_dir=subjects_dir)

    # two different ways of saving
    source_morph_vol.save(tmpdir.join('vol'))

    # check loading
    source_morph_vol_r = read_source_morph(tmpdir.join('vol-morph.h5'))

    # check for invalid file name handling ()
    with pytest.raises(IOError, match='not found'):
        read_source_morph(tmpdir.join('42'))

    # check morph
    stc_vol_morphed = source_morph_vol.apply(stc_vol)
    # old way, verts do not match
    assert not np.array_equal(stc_vol_morphed.vertices[0], stc_vol.vertices[0])

    # vector
    stc_vol_vec = VolVectorSourceEstimate(
        np.tile(stc_vol.data[:, np.newaxis], (1, 3, 1)),
        stc_vol.vertices, 0, 1)
    stc_vol_vec_morphed = source_morph_vol.apply(stc_vol_vec)
    assert isinstance(stc_vol_vec_morphed, VolVectorSourceEstimate)
    for ii in range(3):
        assert_allclose(stc_vol_vec_morphed.data[:, ii], stc_vol_morphed.data)

    # check output as NIfTI
    assert isinstance(source_morph_vol.apply(stc_vol_vec, output='nifti2'),
                      nib.Nifti2Image)

    # check for subject_from mismatch
    source_morph_vol_r.subject_from = '42'
    with pytest.raises(ValueError, match='subject_from must match'):
        source_morph_vol_r.apply(stc_vol_morphed)

    # check if nifti is in grid morph space with voxel_size == spacing
    img_morph_res = source_morph_vol.apply(stc_vol, output='nifti1')

    # assure morph spacing
    assert isinstance(img_morph_res, nib.Nifti1Image)
    assert img_morph_res.header.get_zooms()[:3] == (zooms,) * 3

    # assure src shape
    img_mri_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=True)
    assert isinstance(img_mri_res, nib.Nifti1Image)
    assert (img_mri_res.shape == (src[0]['mri_height'], src[0]['mri_depth'],
                                  src[0]['mri_width']) +
            (img_mri_res.shape[3],))

    # check if nifti is defined resolution with voxel_size == (5., 5., 5.)
    img_any_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=(5., 5., 5.))
    assert isinstance(img_any_res, nib.Nifti1Image)
    assert img_any_res.header.get_zooms()[:3] == (5., 5., 5.)

    # check if morph outputs correct data
    assert isinstance(stc_vol_morphed, VolSourceEstimate)

    # check if loaded and saved objects contain the same
    assert (all([read == saved for read, saved in
                 zip(sorted(source_morph_vol_r.__dict__),
                     sorted(source_morph_vol.__dict__))]))

    # check __repr__
    assert 'volume' in repr(source_morph_vol)

    # check Nifti2Image
    assert isinstance(
        source_morph_vol.apply(stc_vol, mri_resolution=True,
                               mri_space=True, output='nifti2'),
        nib.Nifti2Image)

    # Degenerate conditions
    with pytest.raises(TypeError, match='output must be'):
        source_morph_vol.apply(stc_vol, output=1)
    with pytest.raises(ValueError, match='subject_from does not match'):
        compute_source_morph(src=src, subject_from='42')
    with pytest.raises(ValueError, match='output'):
        source_morph_vol.apply(stc_vol, output='42')
    with pytest.raises(ValueError, match='subject_to cannot be None'):
        compute_source_morph(src, 'sample', None,
                             subjects_dir=subjects_dir)
    # Check if not morphed, but voxel size not boolean, raise ValueError.
    # Note that this check requires dipy to not raise the dipy ImportError
    # before checking if the actual voxel size error will raise.
    with pytest.raises(ValueError, match='Cannot infer original voxel size'):
        stc_vol.as_volume(inverse_operator_vol['src'], mri_resolution=4)

    stc_surf = read_source_estimate(fname_stc, 'sample')
    with pytest.raises(TypeError, match='stc_from must be an instance'):
        source_morph_vol.apply(stc_surf)

    # src_to
    source_morph_vol = compute_source_morph(
        fwd['src'], subject_from='sample', src_to=fwd['src'],
        subject_to='sample', subjects_dir=subjects_dir, **kwargs)
    stc_vol_2 = source_morph_vol.apply(stc_vol)
    # new way, verts match
    assert_array_equal(stc_vol.vertices[0], stc_vol_2.vertices[0])
    stc_vol_bad = VolSourceEstimate(
        stc_vol.data[:-1], [stc_vol.vertices[0][:-1]],
        stc_vol.tmin, stc_vol.tstep)
    match = (
        'vertices do not match between morph \\(4157\\) and stc \\(4156\\).*'
        '\n.*\n.*\n.*Vertices were likely excluded during forward computatio.*'
    )
    with pytest.raises(ValueError, match=match):
        source_morph_vol.apply(stc_vol_bad)
def calc_power(subject, epochs, condition=None, label=None, save=True):
    """Calculate induced power and ITC.

    Does TF...

    Parameters
    ----------
    subject : string
        the subject number.
    epochs : ???  # TODO give proper name for epochs file
        the epochs to calculate power from.
    label : string
        restrict to a label.
    condition : string
        the condition to use if there several in the epochs file.
    save : bool
        whether for save the results. Defaults to True.
    """
    frequencies = np.arange(8, 13, 1)  # define frequencies of interest
    n_cycles = frequencies / 3.
    inverse_operator = read_inverse_operator(mne_folder +
                                             "%s-inv.fif" % subject)
    snr = 1.0
    lambda2 = 1.0 / snr ** 2
    method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

    if condition:
        epochs_test = epochs[condition]
    else:
        epochs_test = epochs

    power, phase_lock = source_induced_power(epochs_test,
                                             inverse_operator,
                                             frequencies,
                                             label=label,
                                             method=method,
                                             lambda2=lambda2,
                                             n_cycles=n_cycles,
                                             use_fft=True,
                                             pick_ori=None,
                                             baseline=(None, -0.3),
                                             baseline_mode='zscore',
                                             pca=True,
                                             n_jobs=2)

    if save:
        np.save(tf_folder + "pow_%s_%s-%s_%s_%s_%s.npy" % (subject,
                                                           frequencies[0],
                                                           frequencies[-1],
                                                           label.name,
                                                           condition,
                                                           method),
                power)
        np.save(tf_folder + "itc_%s_%s-%s_%s_%s_%s.npy" % (subject,
                                                           frequencies[0],
                                                           frequencies[-1],
                                                           label.name,
                                                           condition,
                                                           method),
                phase_lock)

    return power, phase_lock
epo_name = data_path + meg + 'block_' + cond + '_words_epochs-epo.fif'

epochs_cond = mne.read_epochs(epo_name, preload=True)

# crop epochs
epochs = epochs_cond['words'].copy().crop(-.200,
                                          .900).resample(f_down_sampling)

# equalize trial counts to eliminate bias
# equalize_epoch_counts([epochs_SD, epochs_LD])

inv_fname_epoch = data_path + meg + 'InvOp_' + cond + '_EMEG-inv.fif'

output = [0] * 2
# read inverse operator,apply inverse operator
inv_op = read_inverse_operator(inv_fname_epoch)
stc = apply_inverse_epochs(epochs,
                           inv_op,
                           lambda2,
                           method='MNE',
                           pick_ori="normal",
                           return_generator=False)

for j, idx in enumerate([ROI_x, ROI_y]):
    labels[idx].subject = sub_to
    # define dimentions of matrix (vertices X timepoints), & initializing
    v, t = stc[0].in_label(labels[idx]).data.shape
    X = np.zeros([len(stc), v, t])
    # create output array of size (vertices X stimuli X timepoints)
    for s in np.arange(0, len(stc)):
        S = stc[s].in_label(labels[idx]).data
Exemple #46
0
snr = 1.0  # Standard assumption for average data but using it for single trial
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
freqs = np.arange(8, 13, 1)
n_cycle = freqs / 3.

conditions = ["ent/left", "ctl/left", "ent/right", "ctl/right"]

for subject in subjects_select:
    # Load data
    labels = mne.read_labels_from_annot(subject, parc='PALS_B12_Brodmann',
                                        regexp="Bro",
                                        subjects_dir=subjects_dir)
    labels_sel = [labels[6], labels[7]]

    inverse_operator = read_inverse_operator(mne_folder +
                                             "%s-inv.fif" % subject)
    src = inverse_operator["src"]
    epochs = mne.read_epochs(epochs_folder +
                             "%s_trial_start-epo.fif" % subject)
    # epochs.drop_bad_epochs(reject_params)
    # epochs.resample(250, n_jobs=4)

    for condition in conditions:
        stcs = apply_inverse_epochs(epochs[condition],
                                    inverse_operator,
                                    lambda2,
                                    method,
                                    pick_ori=None)

        for label in labels_sel:
            label_ts = []
import numpy as np
import scipy.io

datapath = '/net/server/data/Archive/aut_gamma/orekhova/KI/'
savepath = '/net/server/data/Archive/aut_gamma/orekhova/KI/Scripts_bkp/Shishkina/KI/Results_Alpha_and_Gamma/'
subjects_dir = datapath + 'freesurfersubjects'

subject = '0102'

fname_raw = datapath + 'SUBJECTS/' + subject + '/ICA_nonotch_crop/' + subject + '_rings_ICA_raw.fif'
fname_inv = savepath + subject + '/' + subject + '_inv'

# Load Data
raw = io.Raw(fname_raw, preload=True)
raw.filter(2, 40)
inverse_operator = read_inverse_operator(fname_inv, verbose=None)
events = mne.find_events(raw,
                         stim_channel='STI101',
                         verbose=True,
                         shortest_event=1)

# Make epochs from raw

delay = 8
events[:, 0] = events[:, 0] + delay / 1000. * raw.info['sfreq']
ev = np.sort(
    np.concatenate((np.where(events[:, 2] == 2), np.where(events[:, 2] == 4),
                    np.where(events[:, 2] == 8)),
                   axis=1))
relevantevents = events[ev, :][0]
Exemple #48
0
def test_channel_name_limit(tmpdir, monkeypatch, fname):
    """Test that our remapping works properly."""
    #
    # raw
    #
    if fname.endswith('fif'):
        raw = read_raw_fif(fname)
        raw.pick_channels(raw.ch_names[:3])
        ref_names = []
        data_names = raw.ch_names
    else:
        assert fname.endswith('.ds')
        raw = read_raw_ctf(fname)
        ref_names = [
            raw.ch_names[pick]
            for pick in pick_types(raw.info, meg=False, ref_meg=True)
        ]
        data_names = raw.ch_names[32:35]
    proj = dict(data=np.ones((1, len(data_names))),
                col_names=data_names[:2].copy(),
                row_names=None,
                nrow=1)
    proj = Projection(data=proj,
                      active=False,
                      desc='test',
                      kind=0,
                      explained_var=0.)
    raw.add_proj(proj, remove_existing=True)
    raw.info.normalize_proj()
    raw.pick_channels(data_names + ref_names).crop(0, 2)
    long_names = ['123456789abcdefg' + name for name in raw.ch_names]
    fname = tmpdir.join('test-raw.fif')
    with catch_logging() as log:
        raw.save(fname)
    log = log.getvalue()
    assert 'truncated' not in log
    rename = dict(zip(raw.ch_names, long_names))
    long_data_names = [rename[name] for name in data_names]
    long_proj_names = long_data_names[:2]
    raw.rename_channels(rename)
    for comp in raw.info['comps']:
        for key in ('row_names', 'col_names'):
            for name in comp['data'][key]:
                assert name in raw.ch_names
    if raw.info['comps']:
        assert raw.compensation_grade == 0
        raw.apply_gradient_compensation(3)
        assert raw.compensation_grade == 3
    assert len(raw.info['projs']) == 1
    assert raw.info['projs'][0]['data']['col_names'] == long_proj_names
    raw.info['bads'] = bads = long_data_names[2:3]
    good_long_data_names = [
        name for name in long_data_names if name not in bads
    ]
    with catch_logging() as log:
        raw.save(fname, overwrite=True, verbose=True)
    log = log.getvalue()
    assert 'truncated to 15' in log
    for name in raw.ch_names:
        assert len(name) > 15
    # first read the full way
    with catch_logging() as log:
        raw_read = read_raw_fif(fname, verbose=True)
    log = log.getvalue()
    assert 'Reading extended channel information' in log
    for ra in (raw, raw_read):
        assert ra.ch_names == long_names
    assert raw_read.info['projs'][0]['data']['col_names'] == long_proj_names
    del raw_read
    # next read as if no longer names could be read
    monkeypatch.setattr(meas_info, '_read_extended_ch_info',
                        lambda x, y, z: None)
    with catch_logging() as log:
        raw_read = read_raw_fif(fname, verbose=True)
    log = log.getvalue()
    assert 'extended' not in log
    if raw.info['comps']:
        assert raw_read.compensation_grade == 3
        raw_read.apply_gradient_compensation(0)
        assert raw_read.compensation_grade == 0
    monkeypatch.setattr(  # restore
        meas_info, '_read_extended_ch_info', _read_extended_ch_info)
    short_proj_names = [
        f'{name[:13 - bool(len(ref_names))]}-{len(ref_names) + ni}'
        for ni, name in enumerate(long_data_names[:2])
    ]
    assert raw_read.info['projs'][0]['data']['col_names'] == short_proj_names
    #
    # epochs
    #
    epochs = Epochs(raw, make_fixed_length_events(raw))
    fname = tmpdir.join('test-epo.fif')
    epochs.save(fname)
    epochs_read = read_epochs(fname)
    for ep in (epochs, epochs_read):
        assert ep.info['ch_names'] == long_names
        assert ep.ch_names == long_names
    del raw, epochs_read
    # cov
    epochs.info['bads'] = []
    cov = compute_covariance(epochs, verbose='error')
    fname = tmpdir.join('test-cov.fif')
    write_cov(fname, cov)
    cov_read = read_cov(fname)
    for co in (cov, cov_read):
        assert co['names'] == long_data_names
        assert co['bads'] == []
    del cov_read

    #
    # evoked
    #
    evoked = epochs.average()
    evoked.info['bads'] = bads
    assert evoked.nave == 1
    fname = tmpdir.join('test-ave.fif')
    evoked.save(fname)
    evoked_read = read_evokeds(fname)[0]
    for ev in (evoked, evoked_read):
        assert ev.ch_names == long_names
        assert ev.info['bads'] == bads
    del evoked_read, epochs

    #
    # forward
    #
    with pytest.warns(None):  # not enough points for CTF
        sphere = make_sphere_model('auto', 'auto', evoked.info)
    src = setup_volume_source_space(
        pos=dict(rr=[[0, 0, 0.04]], nn=[[0, 1., 0.]]))
    fwd = make_forward_solution(evoked.info, None, src, sphere)
    fname = tmpdir.join('temp-fwd.fif')
    write_forward_solution(fname, fwd)
    fwd_read = read_forward_solution(fname)
    for fw in (fwd, fwd_read):
        assert fw['sol']['row_names'] == long_data_names
        assert fw['info']['ch_names'] == long_data_names
        assert fw['info']['bads'] == bads
    del fwd_read

    #
    # inv
    #
    inv = make_inverse_operator(evoked.info, fwd, cov)
    fname = tmpdir.join('test-inv.fif')
    write_inverse_operator(fname, inv)
    inv_read = read_inverse_operator(fname)
    for iv in (inv, inv_read):
        assert iv['info']['ch_names'] == good_long_data_names
    apply_inverse(evoked, inv)  # smoke test
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_inv_eegmeg = (data_path +
                    '/MEG/sample/sample_audvis-meg-eeg-oct-6-meg-eeg-inv.fif')
fname_inv_meg = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_label = [data_path + '/MEG/sample/labels/Aud-rh.label',
               data_path + '/MEG/sample/labels/Aud-lh.label',
               data_path + '/MEG/sample/labels/Vis-rh.label',
               data_path + '/MEG/sample/labels/Vis-lh.label']


# read forward solution (sources in surface-based coordinates)
forward = mne.read_forward_solution(fname_fwd, force_fixed=False,
                                    surf_ori=True)

# read inverse operators
inverse_operator_eegmeg = read_inverse_operator(fname_inv_eegmeg)
inverse_operator_meg = read_inverse_operator(fname_inv_meg)

# read label(s)
labels = [mne.read_label(ss) for ss in fname_label]

# regularisation parameter
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = 'MNE'  # can be 'MNE' or 'sLORETA'
mode = 'svd'
n_svd_comp = 1

stc_psf_eegmeg, _ = point_spread_function(inverse_operator_eegmeg,
                                          forward, method=method,
                                          labels=labels,
Exemple #50
0
times = np.arange(-0.1, 1.5, 0.1) # Timing of the source time course (shouldn't be too big)

for nip in nips:    
    for bloc in bloc_names:
        for stimulus in stimulus_names:

            ###################################################################
            ########################### Importation ###########################
            ###################################################################

            # Evoked responses            
            fname = data_evoked_directory + bloc + '/' + nip + '/' + stimulus
            evoked = mne.Evoked(fname + '-ave.fif')

            # Corresponding inverse operator
            inverse_operator = read_inverse_operator(fname + '-inv.fif')
            
            ###################################################################
            ######################### Source estimation #######################
            ###################################################################
            
            stc = apply_inverse(evoked, inverse_operator, lambda2, 
                                method=method, pick_ori=None)

            ###################################################################
            ########################### Visualization #########################
            ###################################################################
            
            # We need to separate right and left hemisphere
            stc_data = dict()
            stc_data['lh'] = stc.data[:len(stc.lh_vertno)]
Exemple #51
0
def _real_vec_stc():
    inv = read_inverse_operator(fname_inv)
    evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01)
    return apply_inverse(evoked, inv, pick_ori='vector')
Exemple #52
0
def test_volume_source_morph():
    """Test volume source estimate morph, special cases and exceptions."""
    import nibabel as nib
    tempdir = _TempDir()
    inverse_operator_vol = read_inverse_operator(fname_inv_vol)
    stc_vol = read_source_estimate(fname_vol, 'sample')

    # check for invalid input type
    with pytest.raises(TypeError, match='src must be an instance of'):
        compute_source_morph(src=42)

    # check for raising an error if neither
    # inverse_operator_vol['src'][0]['subject_his_id'] nor subject_from is set,
    # but attempting to perform a volume morph
    src = inverse_operator_vol['src']
    src[0]['subject_his_id'] = None

    with pytest.raises(ValueError, match='subject_from could not be inferred'):
        compute_source_morph(src=src, subjects_dir=subjects_dir)

    # check infer subject_from from src[0]['subject_his_id']
    src[0]['subject_his_id'] = 'sample'

    with pytest.raises(ValueError, match='Inter-hemispheric morphing'):
        compute_source_morph(src=src, subjects_dir=subjects_dir, xhemi=True)

    with pytest.raises(ValueError, match='Only surface.*sparse morph'):
        compute_source_morph(src=src, sparse=True, subjects_dir=subjects_dir)

    # terrible quality buts fast
    zooms = 20
    kwargs = dict(zooms=zooms, niter_sdr=(1,), niter_affine=(1,))
    source_morph_vol = compute_source_morph(
        subjects_dir=subjects_dir, src=inverse_operator_vol['src'], **kwargs)
    shape = (13,) * 3  # for the given zooms

    assert source_morph_vol.subject_from == 'sample'

    # the brain used in sample data has shape (255, 255, 255)
    assert tuple(source_morph_vol.sdr_morph.domain_shape) == shape

    assert tuple(source_morph_vol.pre_affine.domain_shape) == shape

    # proofs the above
    assert_array_equal(source_morph_vol.zooms, (zooms,) * 3)

    # assure proper src shape
    mri_size = (src[0]['mri_height'], src[0]['mri_depth'], src[0]['mri_width'])
    assert source_morph_vol.src_data['src_shape_full'] == mri_size

    fwd = read_forward_solution(fname_fwd_vol)
    source_morph_vol = compute_source_morph(
        fwd['src'], 'sample', 'sample', subjects_dir=subjects_dir,
        **kwargs)

    # check wrong subject_to
    with pytest.raises(IOError, match='cannot read file'):
        compute_source_morph(fwd['src'], 'sample', '42',
                             subjects_dir=subjects_dir)

    # two different ways of saving
    source_morph_vol.save(op.join(tempdir, 'vol'))

    # check loading
    source_morph_vol_r = read_source_morph(
        op.join(tempdir, 'vol-morph.h5'))

    # check for invalid file name handling ()
    with pytest.raises(IOError, match='not found'):
        read_source_morph(op.join(tempdir, '42'))

    # check morph
    stc_vol_morphed = source_morph_vol.apply(stc_vol)

    # check output as NIfTI
    assert isinstance(source_morph_vol.apply(stc_vol, output='nifti2'),
                      nib.Nifti2Image)

    # check for subject_from mismatch
    source_morph_vol_r.subject_from = '42'
    with pytest.raises(ValueError, match='subject_from must match'):
        source_morph_vol_r.apply(stc_vol_morphed)

    # check if nifti is in grid morph space with voxel_size == spacing
    img_morph_res = source_morph_vol.apply(stc_vol, output='nifti1')

    # assure morph spacing
    assert isinstance(img_morph_res, nib.Nifti1Image)
    assert img_morph_res.header.get_zooms()[:3] == (zooms,) * 3

    # assure src shape
    img_mri_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=True)
    assert isinstance(img_mri_res, nib.Nifti1Image)
    assert (img_mri_res.shape == (src[0]['mri_height'], src[0]['mri_depth'],
                                  src[0]['mri_width']) +
            (img_mri_res.shape[3],))

    # check if nifti is defined resolution with voxel_size == (5., 5., 5.)
    img_any_res = source_morph_vol.apply(stc_vol, output='nifti1',
                                         mri_resolution=(5., 5., 5.))
    assert isinstance(img_any_res, nib.Nifti1Image)
    assert img_any_res.header.get_zooms()[:3] == (5., 5., 5.)

    # check if morph outputs correct data
    assert isinstance(stc_vol_morphed, VolSourceEstimate)

    # check if loaded and saved objects contain the same
    assert (all([read == saved for read, saved in
                 zip(sorted(source_morph_vol_r.__dict__),
                     sorted(source_morph_vol.__dict__))]))

    # check __repr__
    assert 'volume' in repr(source_morph_vol)

    # check Nifti2Image
    assert isinstance(
        source_morph_vol.apply(stc_vol, mri_resolution=True,
                               mri_space=True, output='nifti2'),
        nib.Nifti2Image)

    # Degenerate conditions
    with pytest.raises(TypeError, match='output must be'):
        source_morph_vol.apply(stc_vol, output=1)
    with pytest.raises(ValueError, match='subject_from does not match'):
        compute_source_morph(src=src, subject_from='42')
    with pytest.raises(ValueError, match='output must be one of'):
        source_morph_vol.apply(stc_vol, output='42')
    with pytest.raises(TypeError, match='subject_to must'):
        compute_source_morph(src, 'sample', None,
                             subjects_dir=subjects_dir)
    # Check if not morphed, but voxel size not boolean, raise ValueError.
    # Note that this check requires dipy to not raise the dipy ImportError
    # before checking if the actual voxel size error will raise.
    with pytest.raises(ValueError, match='Cannot infer original voxel size'):
        stc_vol.as_volume(inverse_operator_vol['src'], mri_resolution=4)
Exemple #53
0
                    baseline=(None, 0),
                    reject=reject,
                    preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
epochs.equalize_event_counts(event_id)

###############################################################################
# Transform to source space
# -------------------------
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr**2
method = "dSPM"  # use dSPM method (could also be MNE, sLORETA, or eLORETA)
inverse_operator = read_inverse_operator(fname_inv)

# we'll only use one hemisphere to speed up this example
# instead of a second vertex array we'll pass an empty array
sample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)]

#    Let's average and compute inverse, then resample to speed things up
conditions = []
for cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']:  # order is important
    evoked = epochs[cond].average()
    evoked.resample(50, npad='auto')
    condition = apply_inverse(evoked, inverse_operator, lambda2, method)
    #    Let's only deal with t > 0, cropping to reduce multiple comparisons
    condition.crop(0, None)
    conditions.append(condition)
Exemple #54
0
def test_plot_snr():
    """Test plotting SNR estimate."""
    inv = read_inverse_operator(inv_fname)
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    plot_snr_estimate(evoked, inv)
    plt.close('all')
Exemple #55
0
###############################################################################################################################################
########## Load fwd and inv solutions from RS example data

subject = 'S0116'
subjects_dir = 'M:\\inverse_weighting\\'
parc = 'parc2018yeo7_400'
fwdFile = 'M:\\inverse_weighting\\S0116\\S0116_set02__220416_tsss_09_trans_MEG_ICA-py-fwd.fif'
invFile = 'M:\\inverse_weighting\\S0116\\S0116_set02__220416_tsss_09_trans_MEG_ICA-py-inv.fif'

# read fwd op
fwd = mne.read_forward_solution(fwdFile)
fwd_sol = fwd['sol'][
    'data']  # counterpart to forwardOperator, [sensors x sources]

# read and prepare inv op
inv = minnorm.read_inverse_operator(invFile)
invP = minnorm.prepare_inverse_operator(inv, 1, 1. / 9.)
inv_sol = minnorm.inverse._assemble_kernel(
    invP, None, 'MNE',
    None)[0]  # counterpart to forwardOperator, [sources x sensors]

# get source space
src = inv.get('src')
vert_lh = src[0].get('vertno')
vert_rh = src[1].get('vertno')

# get labels, vertices and src-identities
labels_parc = mne.read_labels_from_annot(subject,
                                         parc=parc,
                                         subjects_dir=subjects_dir)
src_ident_lh = np.full(len(vert_lh), -1)
Exemple #56
0
def test_apply_mne_inverse_epochs():
    """Test MNE with precomputed inverse operator on Epochs."""
    inverse_operator = read_inverse_operator(fname_full)
    label_lh = read_label(fname_label % 'Aud-lh')
    label_rh = read_label(fname_label % 'Aud-rh')
    event_id, tmin, tmax = 1, -0.2, 0.5
    raw = read_raw_fif(fname_raw)

    picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True,
                       eog=True, include=['STI 014'], exclude='bads')
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
    flat = dict(grad=1e-15, mag=1e-15)

    events = read_events(fname_event)[:15]
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, flat=flat)

    inverse_operator = prepare_inverse_operator(inverse_operator, nave=1,
                                                lambda2=lambda2,
                                                method="dSPM")
    for pick_ori in [None, "normal", "vector"]:
        stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                    label=label_lh, pick_ori=pick_ori)
        stcs2 = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                     label=label_lh, pick_ori=pick_ori,
                                     prepared=True)
        # test if using prepared and not prepared inverse operator give the
        # same result
        assert_array_almost_equal(stcs[0].data, stcs2[0].data)
        assert_array_almost_equal(stcs[0].times, stcs2[0].times)

        assert (len(stcs) == 2)
        assert (3 < stcs[0].data.max() < 10)
        assert (stcs[0].subject == 'sample')
    inverse_operator = read_inverse_operator(fname_full)

    stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                label=label_lh, pick_ori='normal')
    data = sum(stc.data for stc in stcs) / len(stcs)
    flip = label_sign_flip(label_lh, inverse_operator['src'])

    label_mean = np.mean(data, axis=0)
    label_mean_flip = np.mean(flip[:, np.newaxis] * data, axis=0)

    assert (label_mean.max() < label_mean_flip.max())

    # test extracting a BiHemiLabel
    inverse_operator = prepare_inverse_operator(inverse_operator, nave=1,
                                                lambda2=lambda2,
                                                method="dSPM")
    stcs_rh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                   label=label_rh, pick_ori="normal",
                                   prepared=True)
    stcs_bh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                   label=label_lh + label_rh,
                                   pick_ori="normal",
                                   prepared=True)

    n_lh = len(stcs[0].data)
    assert_array_almost_equal(stcs[0].data, stcs_bh[0].data[:n_lh])
    assert_array_almost_equal(stcs_rh[0].data, stcs_bh[0].data[n_lh:])

    # test without using a label (so delayed computation is used)
    stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
                                pick_ori="normal", prepared=True)
    assert (stcs[0].subject == 'sample')
    label_stc = stcs[0].in_label(label_rh)
    assert (label_stc.subject == 'sample')
    assert_array_almost_equal(stcs_rh[0].data, label_stc.data)
from my_settings import (epochs_folder, tf_folder, subjects_dir, mne_folder)
import mne
import sys
import numpy as np
import pandas as pd

from mne.minimum_norm import read_inverse_operator, source_induced_power

subject = sys.argv[1]

epochs = mne.read_epochs(epochs_folder + "%s_target-epo.fif" % subject)

inv = read_inverse_operator(mne_folder + "%s-inv.fif" % subject)

labels = mne.read_labels_from_annot(
    subject,
    parc='PALS_B12_Lobes',
    # regexp="Bro",
    subjects_dir=subjects_dir)
labels_selc = labels[9], labels[10]

frequencies = np.arange(8, 13, 1)  # define frequencies of interest
n_cycles = frequencies / 3.  # different number of cycle per frequency
method = "dSPM"

sides = ["left", "right"]
conditions = ["ctl", "ent"]
cor = ["correct", "incorrect"]
phase = ["in_phase", "out_phase"]
congrunet = ["cong", "incong"]
Exemple #58
0
def SN_functional_connectivity_betweenROIs_runs_BL(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]

    # stc_SD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/con_labels_'+method+'_bl_bands_SD_sub'+str(i)+'.json'
    # stc_LD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/con_labels_'+method+'_bl_bands_LD_sub'+str(i)+'.json'
    stc_F_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_F_sub' + str(
        i) + '.json'
    stc_M_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_M_sub' + str(
        i) + '.json'
    stc_O_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_O_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epoch_fname_fruit = data_path + meg + 'block_fruit_epochs-epo.fif'
    epoch_fname_odour = data_path + meg + 'block_odour_epochs-epo.fif'
    epoch_fname_milk = data_path + meg + 'block_milk_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_fruit = mne.read_epochs(epoch_fname_fruit, preload=True)
    epochs_odour = mne.read_epochs(epoch_fname_odour, preload=True)
    epochs_milk = mne.read_epochs(epoch_fname_milk, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_f = mne.epochs.combine_event_ids(
        epochs_fruit, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_o = mne.epochs.combine_event_ids(
        epochs_odour, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_m = mne.epochs.combine_event_ids(
        epochs_milk, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})

    epochs_f = epochs_f['words'].copy().crop(-.200, 0).resample(500)
    epochs_o = epochs_o['words'].copy().crop(-.200, 0).resample(500)
    epochs_m = epochs_m['words'].copy().crop(-.200, 0).resample(500)
    epochs_LD = epochs_ld['words'].copy().crop(-.200, 0).resample(500)

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_F = apply_inverse_epochs(epochs_f,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_O = apply_inverse_epochs(epochs_o,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_M = apply_inverse_epochs(epochs_m,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)

    stc_LD = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    for k in np.arange(0, 6):
        # print('[i,win,k]: ',i,win,k)
        morphed_labels[k].name = C.rois_labels[k]

    for f in np.arange(0, len(C.con_freq_band) - 1):
        print('[i,k,f]: ', i, k, f)
        f_min = C.con_freq_band[f]
        f_max = C.con_freq_band[f + 1]
        print(f_min, f_max)

        labels_ts_f = mne.extract_label_time_course(stc_F, morphed_labels, \
               src_SD, mode='mean_flip',return_generator=False)
        labels_ts_o = mne.extract_label_time_course(stc_O, morphed_labels, \
           src_SD, mode='mean_flip',return_generator=False)
        labels_ts_m = mne.extract_label_time_course(stc_M, morphed_labels, \
                   src_SD, mode='mean_flip',return_generator=False)

        labels_ts_ld= mne.extract_label_time_course(stc_LD, morphed_labels, \
               src_LD, mode='mean_flip',return_generator=False)

        con_F, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_f,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)
        con_O, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_o,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)
        con_M, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_m,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)

        # con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
        #      labels_ts_ld, method=method, mode='fourier',
        #     sfreq=500, fmin=f_min, fmax=f_max, faverage=True, n_jobs=10)
        # con_SD=(con_F+ con_O+ con_M)/3

        # con_labels_SD[f]= con_SD.reshape(6,6)
        # con_labels_LD[f]= con_LD.reshape(6,6)
        con_labels_F[f] = con_F.reshape(6, 6)
        con_labels_M[f] = con_M.reshape(6, 6)
        con_labels_O[f] = con_O.reshape(6, 6)

    # with open(stc_SD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(con_labels_SD, fp)

    # with open(stc_LD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(con_labels_LD, fp)

    with open(stc_F_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_F, fp)

    with open(stc_M_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_M, fp)

    with open(stc_O_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_O, fp)

    e = time.time()
    print(e - s)
reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
epochs.equalize_event_counts(event_id, copy=False)

###############################################################################
# Transform to source space

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
inverse_operator = read_inverse_operator(fname_inv)

# we'll only use one hemisphere to speed up this example
# instead of a second vertex array we'll pass an empty array
sample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)]

#    Let's average and compute inverse, then resample to speed things up
conditions = []
for cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']:  # order is important
    evoked = epochs[cond].average()
    evoked.resample(50)
    condition = apply_inverse(evoked, inverse_operator, lambda2, method)
    #    Let's only deal with t > 0, cropping to reduce multiple comparisons
    condition.crop(0, None)
    conditions.append(condition)
The inverse operator's source space is shown in 3D.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator

print(__doc__)

data_path = sample.data_path()
fname = data_path
fname += "/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif"

inv = read_inverse_operator(fname)

print("Method: %s" % inv["methods"])
print("fMRI prior: %s" % inv["fmri_prior"])
print("Number of sources: %s" % inv["nsource"])
print("Number of channels: %s" % inv["nchan"])

###############################################################################
# Show result on 3D source space
lh_points = inv["src"][0]["rr"]
lh_faces = inv["src"][0]["use_tris"]
rh_points = inv["src"][1]["rr"]
rh_faces = inv["src"][1]["use_tris"]
from mayavi import mlab  # noqa

mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))