Exemple #1
0
def _sortlist(label_list, stc, src):
    sort_list = []
    sort_list.append(label_list[0])
    for test_fn in label_list[1:]:
        test_label = mne.read_label(test_fn)
        i = 0
        insert = False
        while (i < len(sort_list)) and insert == False:
            class_label = mne.read_label(sort_list[i])
            class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip')
            test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip')
            class_pca = np.squeeze(class_pca)
            test_pca = np.squeeze(test_pca)
            class_pow = np.sum(class_pca ** 2)
            test_pow = np.sum(test_pca ** 2)
            # sort the list
            if test_pow < class_pow:
                sort_list.insert(i, test_fn)
                insert = True
            i = i + 1
             
        if insert == False:
            sort_list.append(test_fn)
       
    return sort_list
Exemple #2
0
def test_label_io():
    """Test IO of label files
    """
    label = read_label(label_fname)
    label.save('foo')
    label2 = read_label('foo-lh.label')
    assert_labels_equal(label, label2)
def test_label_io():
    """Test IO of label files
    """
    label = read_label(label_fname)
    label.save(op.join(tempdir, 'foo'))
    label2 = read_label(op.join(tempdir, 'foo-lh.label'))
    assert_labels_equal(label, label2)
Exemple #4
0
def test_source_space():
    "Test SourceSpace Dimension"
    subject = 'fsaverage'
    data_path = mne.datasets.sample.data_path()
    mri_sdir = os.path.join(data_path, 'subjects')
    mri_dir = os.path.join(mri_sdir, subject)
    label_dir = os.path.join(mri_dir, 'label')
    label_ba1 = mne.read_label(os.path.join(label_dir, 'lh.BA1.label'))
    label_v1 = mne.read_label(os.path.join(label_dir, 'lh.V1.label'))
    label_mt = mne.read_label(os.path.join(label_dir, 'lh.MT.label'))
    label_ba1_v1 = label_ba1 + label_v1
    label_v1_mt = label_v1 + label_mt

    src = datasets._mne_source_space(subject, 'ico-5', mri_sdir)
    source = SourceSpace.from_mne_source_spaces(src, 'ico-5', mri_sdir)
    source_v1 = source[source.dimindex(label_v1)]
    eq_(source_v1, SourceSpace.from_mne_source_spaces(src, 'ico-5', mri_sdir,
                                                      label=label_v1))
    source_ba1_v1 = source[source.dimindex(label_ba1_v1)]
    source_v1_mt = source[source.dimindex(label_v1_mt)]
    source_v1_intersection = source_ba1_v1.intersect(source_v1_mt)
    assert_source_space_equal(source_v1, source_v1_intersection)

    # index from label
    index = source.index_for_label(label_v1)
    assert_array_equal(index.source[index.x].vertno[0],
                       np.intersect1d(source.lh_vertno, label_v1.vertices, 1))

    # parcellation and cluster localization
    parc = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=mri_sdir)
    indexes = [source.index_for_label(label) for label in parc
               if len(label) > 10]
    x = np.vstack([index.x for index in indexes])
    ds = source._cluster_properties(x)
    for i in xrange(ds.n_cases):
        eq_(ds[i, 'location'], parc[i].name)

    # multiple labels
    lingual_index = source.dimindex('lingual-lh')
    cuneus_index = source.dimindex('cuneus-lh')
    assert_array_equal(source.dimindex(('cuneus-lh', 'lingual-lh')),
                       np.logical_or(cuneus_index, lingual_index))
    lingual_source = source[lingual_index]
    cuneus_source = source[cuneus_index]
    assert_raises(IndexError, lingual_source.dimindex, cuneus_source)
    sub_source = source[source.dimindex(('cuneus-lh', 'lingual-lh'))]
    eq_(sub_source[sub_source.dimindex('lingual-lh')], lingual_source)
    eq_(sub_source[sub_source.dimindex('cuneus-lh')], cuneus_source)
    eq_(len(sub_source), len(lingual_source) + len(cuneus_source))

    # indexing
    tgt = np.hstack(sub_source.vertno)
    assert_array_equal([i for i in sub_source], tgt)
    assert_array_equal([sub_source[i] for i in xrange(len(sub_source))], tgt)
    # hemisphere indexing
    lh = source.dimindex('lh')
    source_lh = source[lh]
    eq_(source_lh.dimindex('rh'), slice(0, 0))
    eq_(source_lh.dimindex('lh'), slice(0, len(source_lh)))
Exemple #5
0
def test_label_subject():
    """Test label subject name extraction."""
    label = read_label(label_fname)
    assert_is(label.subject, None)
    assert ('unknown' in repr(label))
    label = read_label(label_fname, subject='fsaverage')
    assert (label.subject == 'fsaverage')
    assert ('fsaverage' in repr(label))
Exemple #6
0
def test_label_subject():
    """Test label subject name extraction
    """
    label = read_label(label_fname)
    assert_is(label.subject, None)
    assert_true("unknown" in repr(label))
    label = read_label(label_fname, subject="fsaverage")
    assert_true(label.subject == "fsaverage")
    assert_true("fsaverage" in repr(label))
Exemple #7
0
def test_label_io():
    """Test IO of label files
    """
    label = read_label(label_fname)
    write_label('foo', label)
    label2 = read_label('foo-lh.label')

    for key in label.keys():
        if key in ['comment', 'hemi']:
            assert_true(label[key] == label2[key])
        else:
            assert_array_almost_equal(label[key], label2[key], 5)
Exemple #8
0
def test_source_space():
    "Test SourceSpace Dimension"
    subject = 'fsaverage'
    data_path = mne.datasets.sample.data_path()
    mri_sdir = os.path.join(data_path, 'subjects')
    mri_dir = os.path.join(mri_sdir, subject)
    src_path = os.path.join(mri_dir, 'bem', subject + '-ico-5-src.fif')
    label_dir = os.path.join(mri_dir, 'label')
    label_ba1 = mne.read_label(os.path.join(label_dir, 'lh.BA1.label'))
    label_v1 = mne.read_label(os.path.join(label_dir, 'lh.V1.label'))
    label_mt = mne.read_label(os.path.join(label_dir, 'lh.MT.label'))
    label_ba1_v1 = label_ba1 + label_v1
    label_v1_mt = label_v1 + label_mt

    src = mne.read_source_spaces(src_path)
    source = SourceSpace((src[0]['vertno'], src[1]['vertno']), subject,
                         'ico-5', mri_sdir)
    index = source.dimindex(label_v1)
    source_v1 = source[index]
    index = source.dimindex(label_ba1_v1)
    source_ba1_v1 = source[index]
    index = source.dimindex(label_v1_mt)
    source_v1_mt = source[index]
    index = source_ba1_v1.dimindex(source_v1_mt)
    source_v1_intersection = source_ba1_v1[index]
    assert_source_space_equal(source_v1, source_v1_intersection)

    # index from label
    index = source.index_for_label(label_v1)
    assert_array_equal(index.source[index.x].vertno[0],
                       np.intersect1d(source.lh_vertno, label_v1.vertices, 1))

    # parcellation and cluster localization
    parc = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=mri_sdir)
    indexes = [source.index_for_label(label) for label in parc
               if len(label) > 10]
    x = np.vstack([index.x for index in indexes])
    ds = source._cluster_properties(x)
    for i in xrange(ds.n_cases):
        eq_(ds[i, 'location'], parc[i].name)

    # multiple labels
    lingual_index = source.dimindex('lingual-lh')
    cuneus_index = source.dimindex('cuneus-lh')
    assert_array_equal(source.dimindex(('cuneus-lh', 'lingual-lh')),
                       np.logical_or(cuneus_index, lingual_index))
    lingual_source = source[lingual_index]
    cuneus_source = source[cuneus_index]
    sub_source = source[source.dimindex(('cuneus-lh', 'lingual-lh'))]
    eq_(sub_source[sub_source.dimindex('lingual-lh')], lingual_source)
    eq_(sub_source[sub_source.dimindex('cuneus-lh')], cuneus_source)
    eq_(len(sub_source), len(lingual_source) + len(cuneus_source))
Exemple #9
0
def _merge_rois(mer_path, label_list):
    """
    Function to merge a list of given labels.

    Parameters
    ----------
    mer_path: str
        The directory for storing merged ROIs.
    label_list: list
        Labels to be merged
    """
    class_list = []
    class_list.append(label_list[0])
    for test_fn in label_list[1:]:
        test_label = mne.read_label(test_fn)
        i = 0
        belong = False
        while (i < len(class_list)) and (belong is False):
            class_label = mne.read_label(class_list[i])
            label_name = class_label.name
            if test_label.hemi != class_label.hemi:
                i = i + 1
                continue
            overlapped = len(np.intersect1d(test_label.vertices,
                                            class_label.vertices))
            if overlapped > 0:
                com_label = test_label + class_label
                pre_test = test_label.name.split('_')[0]
                pre_class = class_label.name.split('_')[0]
                # label_name = pre_class + '_%s-%s' %(pre_test,class_label.name.split('-')[-1])
                if pre_test != pre_class:
                    pre_class += ',%s' % pre_test
                    pre_class = list(set(pre_class.split(',')))
                    new_pre = ''
                    for pre in pre_class[:-1]:
                        new_pre += '%s,' % pre
                    new_pre = pre_class[-1]
                    label_name = '%s_' % (new_pre) + \
                        class_label.name.split('_')[-1]
                os.remove(class_list[i])
                os.remove(test_fn)
                fn_newlabel = mer_path + '%s.label' %label_name
                if os.path.isfile(fn_newlabel):
                    fn_newlabel = fn_newlabel[:fn_newlabel.rfind('_')] + '_new, %s' % fn_newlabel.split('_')[-1]
                mne.write_label(fn_newlabel, com_label)
                class_list[i] = fn_newlabel
                belong = True
            i = i + 1
        if belong is False:
            class_list.append(test_fn)
    return len(class_list)
def _cluster_rois(sel_path, label_list, stc, src, min_dist, weight, mni_subject='fsaverage'):
    """
    subfunctions of merge_ROIs
    ----------
    mer_path: str
        The directory for storing merged ROIs.
    label_list: list
        Labels to be merged
    """
    class_list = []
    class_list.append(label_list[0])
    for test_fn in label_list[1:]:
        test_label = mne.read_label(test_fn)
        i = 0
        belong = False
        while (i < len(class_list)) and (belong is False):
            class_label = mne.read_label(class_list[i])
            if test_label.hemi != class_label.hemi:
                i = i + 1
                continue
            else:           
                # Get the representative STCs for class label and test label
                class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip')
                test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip')
                
                # Mark the more apparent ROI
                exch = False
                class_pca_pow = np.sum(class_pca ** 2)
                test_pca_pow = np.sum(test_pca ** 2)
                max_pca = class_pca
                if np.max(class_pca_pow) < np.max(test_pca_pow):
                    max_pca = test_pca
                    exch = True
                
                # Compute the similarity
                thre = max_pca.std() * weight
                diff =  np.abs(np.linalg.norm(class_pca) - np.linalg.norm(test_pca))
                if diff < thre:
                    if exch == True:
                        os.remove(class_list[i])
                        class_list[i] = test_fn
                    elif exch == False:
                        os.remove(test_fn)
                    belong = True
                i = i + 1
                
        if belong is False:
            class_list.append(test_fn)
                
    return len(class_list)
Exemple #11
0
def test_label_io():
    """Test IO of label files
    """
    label = read_label(label_fname)
    label.save(op.join(tempdir, 'foo'))
    label2 = read_label(op.join(tempdir, 'foo-lh.label'))
    assert_labels_equal(label, label2)

    # pickling
    dest = op.join(tempdir, 'foo.pickled')
    with open(dest, 'w') as fid:
        pickle.dump(label, fid, pickle.HIGHEST_PROTOCOL)
    with open(dest) as fid:
        label2 = pickle.load(fid)
    assert_labels_equal(label, label2)
Exemple #12
0
def test_label_time_course():
    """Test extracting label data from SourceEstimate"""
    values, times, vertices = label_time_courses(real_label_fname, stc_fname)
    stc = read_source_estimate(stc_fname)
    label_lh = read_label(real_label_fname)
    stc_lh = stc.in_label(label_lh)
    assert_array_almost_equal(stc_lh.data, values)
    assert_array_almost_equal(stc_lh.times, times)
    assert_array_almost_equal(stc_lh.vertno[0], vertices)

    label_rh = read_label(real_label_rh_fname)
    stc_rh = stc.in_label(label_rh)
    label_bh = label_rh + label_lh
    stc_bh = stc.in_label(label_bh)
    assert_array_equal(stc_bh.data, np.vstack((stc_lh.data, stc_rh.data)))
Exemple #13
0
def _get_fwd_labels():
    fwd = read_forward_solution(fname_fwd)
    fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=False)
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                         '%s.label' % label)) for label in label_names]
    return fwd, labels
Exemple #14
0
def test_generate_sparse_stc():
    """ Test generation of sparse source estimate """
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                         '%s.label' % label)) for label in label_names]

    n_times = 10
    tmin = 0
    tstep = 1e-3

    stc_data = np.ones((len(labels), n_times))\
                     * np.arange(len(labels))[:, None]
    stc_1 = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep, 0)

    for i, label in enumerate(labels):
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc_1.vertno[hemi_idx], label.vertices)
        idx = np.searchsorted(stc_1.vertno[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc_1.vertno[0])

        assert_true(np.all(stc_1.data[idx] == float(i)))

    assert_true(stc_1.data.shape[0] == len(labels))
    assert_true(stc_1.data.shape[1] == n_times)

    # make sure we get the same result when using the same seed
    stc_2 = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep, 0)

    assert_array_equal(stc_1.lh_vertno, stc_2.lh_vertno)
    assert_array_equal(stc_1.rh_vertno, stc_2.rh_vertno)
Exemple #15
0
def test_morph():
    """Test inter-subject label morphing
    """
    label_orig = read_label(real_label_fname)
    label_orig.subject = 'sample'
    # should work for specifying vertices for both hemis, or just the
    # hemi of the given label
    vals = list()
    for grade in [5, [np.arange(10242), np.arange(10242)], np.arange(10242)]:
        label = label_orig.copy()
        # this should throw an error because the label has all zero values
        assert_raises(ValueError, label.morph, 'sample', 'fsaverage')
        label.values.fill(1)
        label = label.morph(None, 'fsaverage', 5, grade, subjects_dir, 1)
        label = label.morph('fsaverage', 'sample', 5, None, subjects_dir, 2)
        assert_true(np.mean(in1d(label_orig.vertices, label.vertices)) == 1.0)
        assert_true(len(label.vertices) < 3 * len(label_orig.vertices))
        vals.append(label.vertices)
    assert_array_equal(vals[0], vals[1])
    # make sure label smoothing can run
    assert_equal(label.subject, 'sample')
    verts = [np.arange(10242), np.arange(10242)]
    for hemi in ['lh', 'rh']:
        label.hemi = hemi
        label.morph(None, 'fsaverage', 5, verts, subjects_dir, 2)
    assert_raises(TypeError, label.morph, None, 1, 5, verts,
                  subjects_dir, 2)
    assert_raises(TypeError, label.morph, None, 'fsaverage', 5.5, verts,
                  subjects_dir, 2)
    with warnings.catch_warnings(record=True):  # morph map could be missing
        label.smooth(subjects_dir=subjects_dir)  # make sure this runs
Exemple #16
0
def test_label_in_src():
    """Test label in src"""
    src = read_source_spaces(src_fname)
    label = read_label(v1_label_fname)

    # construct label from source space vertices
    vert_in_src = np.intersect1d(label.vertices, src[0]['vertno'], True)
    where = in1d(label.vertices, vert_in_src)
    pos_in_src = label.pos[where]
    values_in_src = label.values[where]
    label_src = Label(vert_in_src, pos_in_src, values_in_src,
                      hemi='lh').fill(src)

    # check label vertices
    vertices_status = in1d(src[0]['nearest'], label.vertices)
    vertices_in = np.nonzero(vertices_status)[0]
    vertices_out = np.nonzero(np.logical_not(vertices_status))[0]
    assert_array_equal(label_src.vertices, vertices_in)
    assert_array_equal(in1d(vertices_out, label_src.vertices), False)

    # check values
    value_idx = digitize(src[0]['nearest'][vertices_in], vert_in_src, True)
    assert_array_equal(label_src.values, values_in_src[value_idx])

    # test exception
    vertices = np.append([-1], vert_in_src)
    assert_raises(ValueError, Label(vertices, hemi='lh').fill, src)
Exemple #17
0
def test_morph():
    """Test inter-subject label morphing
    """
    label_orig = read_label(real_label_fname)
    label_orig.subject = "sample"
    # should work for specifying vertices for both hemis, or just the
    # hemi of the given label
    vals = list()
    for grade in [5, [np.arange(10242), np.arange(10242)], np.arange(10242)]:
        label = label_orig.copy()
        # this should throw an error because the label has all zero values
        assert_raises(ValueError, label.morph, "sample", "fsaverage")
        label.values.fill(1)
        label.morph(None, "fsaverage", 5, grade, subjects_dir, 1, copy=False)
        label.morph("fsaverage", "sample", 5, None, subjects_dir, 2, copy=False)
        assert_true(np.mean(in1d(label_orig.vertices, label.vertices)) == 1.0)
        assert_true(len(label.vertices) < 3 * len(label_orig.vertices))
        vals.append(label.vertices)
    assert_array_equal(vals[0], vals[1])
    # make sure label smoothing can run
    assert_equal(label.subject, "sample")
    verts = [np.arange(10242), np.arange(10242)]
    for hemi in ["lh", "rh"]:
        label.hemi = hemi
        label.morph(None, "fsaverage", 5, verts, subjects_dir, 2)
    assert_raises(TypeError, label.morph, None, 1, 5, verts, subjects_dir, 2)
    assert_raises(TypeError, label.morph, None, "fsaverage", 5.5, verts, subjects_dir, 2)
    label.smooth(subjects_dir=subjects_dir)  # make sure this runs
Exemple #18
0
def test_morph():
    """Test inter-subject label morphing
    """
    label_orig = read_label(real_label_fname)
    label_orig.subject = 'sample'
    # should work for specifying vertices for both hemis, or just the
    # hemi of the given label
    vals = list()
    for grade in [5, [np.arange(10242), np.arange(10242)], np.arange(10242)]:
        label = label_orig.copy()
        # this should throw an error because the label has all zero values
        assert_raises(ValueError, label.morph, 'sample', 'fsaverage')
        label.values.fill(1)
        label.morph(None, 'fsaverage', 5, grade, subjects_dir, 2,
                    copy=False)
        label.morph('fsaverage', 'sample', 5, None, subjects_dir, 2,
                    copy=False)
        assert_true(np.mean(in1d(label_orig.vertices, label.vertices)) == 1.0)
        assert_true(len(label.vertices) < 3 * len(label_orig.vertices))
        vals.append(label.vertices)
    assert_array_equal(vals[0], vals[1])
    # make sure label smoothing can run
    label.morph(label.subject, 'fsaverage', 5,
                [np.arange(10242), np.arange(10242)], subjects_dir, 2,
                copy=False)
    # subject name should be inferred now
    label.smooth(subjects_dir=subjects_dir)
Exemple #19
0
def fiff_mne(ds, fwd='{fif}*fwd.fif', cov='{fif}*cov.fif', label=None, name=None,
             tstart= -0.1, tstop=0.6, baseline=(None, 0)):
    """
    adds data from one label as

    """
    if name is None:
        if label:
            _, lbl = os.path.split(label)
            lbl, _ = os.path.splitext(lbl)
            name = lbl.replace('-', '_')
        else:
            name = 'stc'

    info = ds.info['info']

    raw = ds.info['raw']
    fif_name = raw.info['filename']
    fif_name, _ = os.path.splitext(fif_name)
    if fif_name.endswith('raw'):
        fif_name = fif_name[:-3]

    fwd = fwd.format(fif=fif_name)
    if '*' in fwd:
        d, n = os.path.split(fwd)
        names = fnmatch.filter(os.listdir(d), n)
        if len(names) == 1:
            fwd = os.path.join(d, names[0])
        else:
            raise IOError("No unique fwd file matching %r" % fwd)

    cov = cov.format(fif=fif_name)
    if '*' in cov:
        d, n = os.path.split(cov)
        names = fnmatch.filter(os.listdir(d), n)
        if len(names) == 1:
            cov = os.path.join(d, names[0])
        else:
            raise IOError("No unique cov file matching %r" % cov)

    fwd = mne.read_forward_solution(fwd, force_fixed=False, surf_ori=True)
    cov = mne.Covariance(cov)
    inv = _mn.make_inverse_operator(info, fwd, cov, loose=0.2, depth=0.8)
    epochs = mne_Epochs(ds, tstart=tstart, tstop=tstop, baseline=baseline)

    # mne example:
    snr = 3.0
    lambda2 = 1.0 / snr ** 2

    if label is not None:
        label = mne.read_label(label)
    stcs = _mn.apply_inverse_epochs(epochs, inv, lambda2, dSPM=False, label=label)

    x = np.vstack(s.data.mean(0) for s in stcs)
    s = stcs[0]
    dims = ('case', var(s.times, 'time'),)
    ds[name] = ndvar(x, dims, properties=None, info='')

    return stcs
Exemple #20
0
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True,
              epochs_preload=True, data_cov=True):
    """Read in data used in tests."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)
    if all_forward:
        forward_surf_ori = _read_forward_solution_meg(
            fname_fwd, surf_ori=True)
        forward_fixed = _read_forward_solution_meg(
            fname_fwd, force_fixed=True, surf_ori=True, use_cps=False)
        forward_vol = _read_forward_solution_meg(fname_fwd_vol)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bad channels
    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True,
                           eog=True, ref_meg=False, exclude='bads',
                           selection=left_temporal_channels)
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    raw.info.normalize_proj()  # avoid projection warnings

    if epochs:
        # Read epochs
        epochs = mne.Epochs(
            raw, events, event_id, tmin, tmax, proj=True,
            baseline=(None, 0), preload=epochs_preload,
            reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
        if epochs_preload:
            epochs.resample(200, npad=0, n_jobs=2)
        epochs.crop(0, None)
        evoked = epochs.average()
        info = evoked.info
    else:
        epochs = None
        evoked = None
        info = raw.info

    noise_cov = mne.read_cov(fname_cov)
    noise_cov['projs'] = []  # avoid warning
    with warnings.catch_warnings(record=True):  # bad proj
        noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05,
                                       eeg=0.1, proj=True)
    if data_cov:
        with warnings.catch_warnings(record=True):  # too few samples
            data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145)
    else:
        data_cov = None

    return raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
Exemple #21
0
def test_simulate_stc():
    """ Test generation of source estimate """
    fwd = read_forward_solution_meg(fname_fwd, force_fixed=True)
    labels = [read_label(op.join(data_path, "MEG", "sample", "labels", "%s.label" % label)) for label in label_names]
    mylabels = []
    for i, label in enumerate(labels):
        new_label = Label(
            vertices=label.vertices,
            pos=label.pos,
            values=2 * i * np.ones(len(label.values)),
            hemi=label.hemi,
            comment=label.comment,
        )
        mylabels.append(new_label)

    n_times = 10
    tmin = 0
    tstep = 1e-3

    stc_data = np.ones((len(labels), n_times))
    stc = simulate_stc(fwd["src"], mylabels, stc_data, tmin, tstep)

    for label in labels:
        if label.hemi == "lh":
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        assert_true(np.all(stc.data[idx] == 1.0))
        assert_true(stc.data[idx].shape[1] == n_times)

    # test with function
    def fun(x):
        return x ** 2

    stc = simulate_stc(fwd["src"], mylabels, stc_data, tmin, tstep, fun)

    # the first label has value 0, the second value 2, the third value 6

    for i, label in enumerate(labels):
        if label.hemi == "lh":
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        res = ((2.0 * i) ** 2.0) * np.ones((len(idx), n_times))
        assert_array_almost_equal(stc.data[idx], res)
Exemple #22
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 #23
0
def split_label(label, fwd_fname, name1='{name}_post', name2='{name}_ant',
                divide=np.median):
    """
    Splits an mne Label object into two labels along its principal axis. The
    principle axis is determined using principal component analysis (PCA).
    Returns 2 mne Label instances ``(label1, label2)``.


    Parameters
    ----------

    label : mne Label
        Source label, which is to be split.
    fwd_fname : str(path)
        Filename to a fwd file (used to load the source space which is needed
        to constrain the label points to those that are relevant for the
        source space).
    name1, name2 : str
        Name for the new labels. '{name}' will be formatted with the input
        label's name.
    divide : func
        Function that takes the one-dimensional array of point location among
        the principal axis and returns the point at which the points should be
        split (default is the median).

    """
    source_space = mne.read_source_spaces(fwd_fname)
    if isinstance(label, basestring):
        label = mne.read_label(label)

    hemi = (label.hemi == 'rh')
    ss_vert = source_space[hemi]['vertno']
    idx = np.array(map(ss_vert.__contains__, label.vertices))

    # centered label coordinates
    cpos = label.pos - np.mean(label.pos, 0)

    # project all label coords onto pca-0 of the label's source space coords
    cpos_i = cpos[idx]
    node = mdp.nodes.PCANode(output_dim=1)
    node.train(cpos_i)
    proj = node.execute(cpos)[:, 0]
    if node.v[1, 0] < 0:
        proj *= -1

    div = divide(proj[idx])

    ip = proj < div
    ia = proj >= div

    out = []
    for idx, name in [(ip, name1), (ia, name2)]:
        label_name = name.format(name=label.name)
        lblout = mne.label.Label(label.vertices[idx], label.pos[idx],
                                 label.values[idx], label.hemi,
                                 comment=label.comment, name=label_name)
        out.append(lblout)

    return tuple(out)
Exemple #24
0
def test_label_io_and_time_course_estimates():
    """Test IO for label + stc files."""
    stc = read_source_estimate(stc_fname)
    label = read_label(real_label_fname)
    stc_label = stc.in_label(label)

    assert (len(stc_label.times) == stc_label.data.shape[1])
    assert (len(stc_label.vertices[0]) == stc_label.data.shape[0])
Exemple #25
0
def labels_to_annot(subject, fol, parc, overwrite=True):
    for hemi in ["lh", "lr"]:
        labels = []
        for label_file in glob.glob(os.path.join(fol, "*{}.label".format(hemi))):
            label = mne.read_label(label_file)
            labels.append(label)
        print("write {} labels to annot file".format(hemi))
        mne.write_labels_to_annot(labels, subject, parc, overwrite, hemi=hemi)
Exemple #26
0
def test_generate_stc_single_hemi():
    """Test generation of source estimate, single hemi."""
    fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
    labels_single_hemi = [read_label(op.join(data_path, 'MEG', 'sample',
                                             'labels', '%s.label' % label))
                          for label in label_names_single_hemi]
    mylabels = []
    for i, label in enumerate(labels_single_hemi):
        new_label = Label(vertices=label.vertices,
                          pos=label.pos,
                          values=2 * i * np.ones(len(label.values)),
                          hemi=label.hemi,
                          comment=label.comment)
        mylabels.append(new_label)

    n_times = 10
    tmin = 0
    tstep = 1e-3

    stc_data = np.ones((len(labels_single_hemi), n_times))
    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep)

    for label in labels_single_hemi:
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        assert (np.all(stc.data[idx] == 1.0))
        assert (stc.data[idx].shape[1] == n_times)

    # test with function
    def fun(x):
        return x ** 2
    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep, fun)

    # the first label has value 0, the second value 2, the third value 6

    for i, label in enumerate(labels_single_hemi):
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        res = ((2. * i) ** 2.) * np.ones((len(idx), n_times))
        assert_array_almost_equal(stc.data[idx], res)
Exemple #27
0
def test_read_labels_from_annot_annot2labels():
    """Test reading labels from parc. by comparing with mne_annot2labels."""
    label_fnames = glob.glob(label_dir + '/*.label')
    label_fnames.sort()
    labels_mne = [read_label(fname) for fname in label_fnames]
    labels = read_labels_from_annot('sample', subjects_dir=subjects_dir)

    # we have the same result, mne does not fill pos, so ignore it
    _assert_labels_equal(labels, labels_mne, ignore_pos=True)
def _cluster_rois(sel_path, label_list, stc, src):
    """
    subfunctions of merge_ROIs
    ----------
    mer_path: str
        The directory for storing merged ROIs.
    label_list: list
        Labels to be merged
    """
    class_list = []
    class_list.append(label_list[0])
    for test_fn in label_list[1:]:
        test_label = mne.read_label(test_fn)
        i = 0
        belong = False
        while (i < len(class_list)) and (belong is False):
            class_label = mne.read_label(class_list[i])
            if test_label.hemi != class_label.hemi:
                i = i + 1
                continue
            else:
                class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip')
                test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip')
                class_pow = np.sum(class_pca ** 2)
                test_pow = np.sum(test_pca ** 2)
                max_pca = class_pca
                exch = False
                if class_pow < test_pow:
                    max_pca = test_pca
                    exch = True
                thre = max_pca.std() * 0.8
                diff =  np.abs(np.linalg.norm(class_pca) - np.linalg.norm(test_pca))
                if diff < thre:
                    if exch == True:
                        os.remove(class_list[i])
                        class_list[i] = test_fn
                    elif exch == False:
                        os.remove(test_fn)
                    belong = True
                i = i + 1
        if belong is False:
            class_list.append(test_fn)
                
    return len(class_list)
Exemple #29
0
def test_label_time_course():
    """Test extracting label data from SourceEstimate"""
    values, times, vertices = label_time_courses(real_label_fname, stc_fname)
    stc = read_source_estimate(stc_fname)
    label_lh = read_label(real_label_fname)
    stc_lh = stc.in_label(label_lh)
    assert_array_almost_equal(stc_lh.data, values)
    assert_array_almost_equal(stc_lh.times, times)
    assert_array_almost_equal(stc_lh.vertno[0], vertices)

    label_rh = read_label(real_label_rh_fname)
    stc_rh = stc.in_label(label_rh)
    label_bh = label_rh + label_lh
    label_bh_2 = label_lh + label_rh
    label_bh_3 = label_bh + label_bh_2
    assert_true(repr(label_bh))  # test __repr__
    for check in (label_bh, label_bh_2, label_bh_3):
        stc_bh = stc.in_label(check)
        assert_array_equal(stc_bh.data, np.vstack((stc_lh.data, stc_rh.data)))
Exemple #30
0
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True,
              epochs_preload=True, data_cov=True):
    """Read in data used in tests
    """
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.fiff.Raw(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)
    if all_forward:
        forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True)
        forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True,
                                                  surf_ori=True)
        forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    if epochs:
        # Set up pick list: MEG - bad channels
        left_temporal_channels = mne.read_selection('Left-temporal')
        picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False,
                                    stim=True, eog=True, ref_meg=False,
                                    exclude='bads',
                                    selection=left_temporal_channels)

        # Read epochs
        epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                            picks=picks, baseline=(None, 0),
                            preload=epochs_preload,
                            reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
        if epochs_preload:
            epochs.resample(200, npad=0, n_jobs=2)
        evoked = epochs.average()
        info = evoked.info
    else:
        epochs = None
        evoked = None
        info = raw.info

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov, info,
                                   mag=0.05, grad=0.05, eeg=0.1, proj=True)
    if data_cov:
        data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    else:
        data_cov = None

    return raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
Exemple #31
0
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,
                                          labels=labels,
                                          lambda2=lambda2,
                                          pick_ori='normal',
                                          mode=mode,
Exemple #32
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked,
                   fwd,
                   noise_cov,
                   data_cov,
                   reg=0.01,
                   max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105, tmax)
        assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked,
                              forward_surf_ori,
                              noise_cov,
                              data_cov,
                              reg=0.01,
                              pick_ori="normal")
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.04 < tmax < 0.11, tmax)
            assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked,
                             fwd,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             pick_ori="max-power",
                             max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.08 < tmax < 0.11, tmax)
        assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc))

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label,
                                                     fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())

        # Test NAI weight normalization:
        stc_nai = lcmv(evoked,
                       fwd,
                       noise_cov=noise_cov,
                       data_cov=data_cov,
                       reg=0.01,
                       pick_ori='max-power',
                       weight_norm='nai',
                       max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if missing of data covariance matrix is detected
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=noise_cov,
                  data_cov=None,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=None,
                  data_cov=data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_surf_ori,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal",
                  weight_norm='nai')
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori=None,
                  weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throw
    # an error
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  weight_norm=None,
                  max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs,
                        forward_fixed,
                        noise_cov,
                        data_cov,
                        reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs,
                             forward_fixed,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Exemple #33
0
def test_make_lcmv(tmpdir, reg, proj):
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data(proj=proj)

    for fwd in [forward, forward_vol]:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov)
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.08 < tmax < 0.14, tmax
        assert 0.9 < np.max(max_stc) < 3., np.max(max_stc)

        if fwd is forward:
            # Test picking normal orientation (surface source space only).
            filters = make_lcmv(evoked.info, forward_surf_ori, data_cov,
                                reg=reg, noise_cov=noise_cov,
                                pick_ori='normal', weight_norm=None)
            stc_normal = apply_lcmv(evoked, filters, max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            lower = 0.04 if proj else 0.025
            assert lower < tmax < 0.14, tmax
            lower = 3e-7 if proj else 2e-7
            assert lower < np.max(max_stc) < 3e-6, np.max(max_stc)

            # No weight normalization was applied, so the amplitude of normal
            # orientation results should always be smaller than free
            # orientation results.
            assert (np.abs(stc_normal.data) <= stc.data).all()

        # Test picking source orientation maximizing output source power
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov, pick_ori='max-power')
        stc_max_power = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        lower = 0.08 if proj else 0.04
        assert lower < tmax < 0.12, tmax
        assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label, fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_array_less(np.abs(mean_stc - mean_stc_max_pow), 1.0)

        # Test NAI weight normalization:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov, pick_ori='max-power',
                            weight_norm='nai')
        stc_nai = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0, exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info, trans=None, src=src,
                                           bem=sphere, eeg=False, meg=True)

    # Test that we get an error if not reducing rank
    with pytest.raises(ValueError):  # Singular matrix or complex spectrum
        make_lcmv(
            evoked.info, fwd_sphere, data_cov, reg=0.1,
            noise_cov=noise_cov, weight_norm='unit-noise-gain',
            pick_ori='max-power', reduce_rank=False, rank='full')

    # Now let's reduce it
    filters = make_lcmv(evoked.info, fwd_sphere, data_cov, reg=0.1,
                        noise_cov=noise_cov, weight_norm='unit-noise-gain',
                        pick_ori='max-power', reduce_rank=True)
    stc_sphere = apply_lcmv(evoked, filters, max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    lower = 0.08 if proj else 0.04
    assert lower < tmax < 0.15, tmax
    assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # __repr__
    assert len(evoked.ch_names) == 22
    assert len(evoked.info['projs']) == (4 if proj else 0)
    assert len(evoked.info['bads']) == 2
    rank = 17 if proj else 20
    assert 'LCMV' in repr(filters)
    assert 'unknown subject' not in repr(filters)
    assert '484' in repr(filters)
    assert '20' in repr(filters)
    assert 'rank %s' % rank in repr(filters)

    # I/O
    fname = op.join(str(tmpdir), 'filters.h5')
    with pytest.warns(RuntimeWarning, match='-lcmv.h5'):
        filters.save(fname)
    filters_read = read_beamformer(fname)
    assert isinstance(filters, Beamformer)
    assert isinstance(filters_read, Beamformer)
    # deal with object_diff strictness
    filters_read['rank'] = int(filters_read['rank'])
    filters['rank'] = int(filters['rank'])
    assert object_diff(filters, filters_read) == ''

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='max-power')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if volume forward operator is detected when picking normal
    # orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol,
                  data_cov=data_cov, reg=0.01, noise_cov=None,
                  pick_ori='max-power')

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    pytest.raises(ValueError, apply_lcmv, evoked_ch, filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    # also test here that no warnings are thrown - implemented to check whether
    # src should not be None warning occurs
    with pytest.warns(None) as w:
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert len(w) == 0
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    if proj:
        raw_proj = deepcopy(raw)
        raw_proj.del_proj()
        with pytest.raises(ValueError, match='do not match the projections'):
            apply_lcmv_raw(raw_proj, filters, max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
                  data_cov, noise_cov=noise_cov, pick_ori=None,
                  weight_norm='nai', reduce_rank=True)
    pytest.raises(NotImplementedError, make_lcmv, evoked.info,
                  forward_surf_ori, data_cov, noise_cov=noise_cov,
                  pick_ori='normal', weight_norm='nai', reduce_rank=True)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # check whether a filters object without src_type throws expected warning
    del filters['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning, match='spatial filter does not contain '
                      'src_type'):
        apply_lcmv(evoked, filters, max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')
    stcs_ = apply_lcmv_epochs(epochs, filters, return_generator=True,
                              max_ori_out='signed')
    assert_array_equal(stcs[0].data, next(stcs_).data)

    epochs.drop_bad()
    assert (len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    filters = make_lcmv(evoked.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stc_fixed = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov, label=label)
    stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)

    # Test condition where the filters weights are zero. There should not be
    # any divide-by-zero errors
    zero_cov = data_cov.copy()
    zero_cov['data'][:] = 0
    filters = make_lcmv(epochs.info, forward_fixed, zero_cov, reg=0.01,
                        noise_cov=noise_cov)
    assert_array_equal(filters['weights'], 0)

    # Test condition where one channel type is picked
    # (avoid "grad data rank (13) did not match the noise rank (None)")
    data_cov_grad = mne.pick_channels_cov(
        data_cov, [ch_name for ch_name in epochs.info['ch_names']
                   if ch_name.endswith(('2', '3'))])
    assert len(data_cov_grad['names']) > 4
    make_lcmv(epochs.info, forward_fixed, data_cov_grad, reg=0.01,
              noise_cov=noise_cov)
Exemple #34
0
#twin       = [0.673,0.809]
twin = (0.673, 0.809)

ori = 'None'

wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG"
###############################################################################
DATA = []
SUBJECT = []
COND = []
ROI = []

subjects_dir = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri/'

for l, labeltag in enumerate(label_list):
    label = mne.read_label(label_path + '/' + labeltag)

    # get the indexes of vertices of interest (VertOI)
    path = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps'
    stc_fname = (path + '/IcaCorr_p005uncorr_MEEG_' + condition[0] + '-' +
                 condition[-1] + '_twin' + str(twin[0]) + '-' + str(twin[1]) +
                 'ms_pick_oriNone_dSPM_ico-5-fwd-fsaverage.stc-lh.stc')
    stc = mne.read_source_estimate(stc_fname)
    stc_label = stc.in_label(label)
    VertOI = np.where(np.abs(stc_label.data) > 0)[0]

    #################################
    # load a specific STC morphed on fsaverage to get shape info
    stc0_path = (wdir + '/' + ListSubj[0] + '/mne_python/STCS/IcaCorr_' + mod +
                 '_' + ListSubj[0] + '_' + condition[0] + '_pick_ori' + ori +
                 '_' + method + '_ico-5-fwd-fsaverage.fif-rh.stc')
Exemple #35
0
def test_select_sources():
    """Test the selection of sources for simulation."""
    subject = 'sample'
    label_file = op.join(subjects_dir, subject, 'label', 'aparc',
                         'temporalpole-rh.label')

    # Regardless of other parameters, using extent 0 should always yield a
    # a single source.
    tp_label = read_label(label_file)
    tp_label.values[:] = 1
    labels = ['lh', tp_label]
    locations = ['random', 'center']
    for label, location in product(labels, locations):
        label = select_sources(subject,
                               label,
                               location,
                               extent=0,
                               subjects_dir=subjects_dir)
        assert (len(label.vertices) == 1)

    # As we increase the extent, the new region should contain the previous
    # one.
    label = select_sources(subject,
                           'lh',
                           0,
                           extent=0,
                           subjects_dir=subjects_dir)
    for extent in range(1, 3):
        new_label = select_sources(subject,
                                   'lh',
                                   0,
                                   extent=extent * 2,
                                   subjects_dir=subjects_dir)
        assert (set(new_label.vertices) > set(label.vertices))
        assert (new_label.hemi == 'lh')
        label = new_label

    # With a large enough extent and not allowing growing outside the label,
    # every vertex of the label should be in the region.
    label = select_sources(subject,
                           tp_label,
                           0,
                           extent=30,
                           grow_outside=False,
                           subjects_dir=subjects_dir)
    assert (set(label.vertices) == set(tp_label.vertices))

    # Without this restriction, we should get new vertices.
    label = select_sources(subject,
                           tp_label,
                           0,
                           extent=30,
                           grow_outside=True,
                           subjects_dir=subjects_dir)
    assert (set(label.vertices) > set(tp_label.vertices))

    # Other parameters are taken into account.
    label = select_sources(subject,
                           tp_label,
                           0,
                           extent=10,
                           grow_outside=False,
                           subjects_dir=subjects_dir,
                           name='mne')
    assert (label.name == 'mne')
    assert (label.hemi == 'rh')
Exemple #36
0
def set_marsatlas(subject, src, hemi='both', json_fname='default'):

    if json_fname == 'default':
        read_dir = op.join(op.abspath(__package__), 'config')
        json_fname = op.join(read_dir, 'db_coords.json')

    raw_dir, prep_dir, trans_dir, mri_dir, src_dir, bem_dir, fwd_dir, hga_dir = read_directories(
        json_fname)

    read_dir = op.abspath(__file__).replace('vis.py', 'textures')
    cortical_text = np.load(op.join(read_dir, 'cortical.npy'))
    subcort_text = np.load(op.join(read_dir, 'subcortical.npy'))

    rgb_marsatlas = []
    for s in src:
        if s['type'] == 'surf':
            textures = cortical_text
            if (hemi == 'both' or hemi == 'lh') and s['id'] == 101:
                labels_lh = mne.read_label(
                    op.join(src_dir.format(subject),
                            '{0}_{1}-lab-lh.label'.format(subject, s['type'])))
                all_src = np.full((s['np'], 3), 1.)
                for v, p in zip(labels_lh.vertices, labels_lh.values - 1):
                    all_src[int(v), :] = textures[int(p), :]
                rgb_marsatlas.append(all_src)

            if (hemi == 'both' or hemi == 'rh') and s['id'] == 102:
                labels_rh = mne.read_label(
                    op.join(src_dir.format(subject),
                            '{0}_{1}-lab-rh.label'.format(subject, s['type'])))
                all_src = np.full((s['np'], 3), 1.)
                for v, p in zip(labels_rh.vertices, labels_rh.values - 101):
                    all_src[int(v), :] = textures[int(p), :]
                rgb_marsatlas.append(all_src)

        if s['type'] == 'vol':
            textures = subcort_text
            if (hemi == 'both'
                    or hemi == 'lh') and s['seg_name'].endswith('lh'):
                labels_lh = mne.read_label(
                    op.join(src_dir.format(subject),
                            '{0}_{1}-lab-lh.label'.format(subject, s['type'])))
                all_src = np.full((labels_lh.pos.shape[0], 3), 1.)
                for v, p in zip(labels_lh.vertices, labels_lh.values - 200):
                    all_src[int(v), :] = textures[int(p), :]
                rgb_marsatlas.append(all_src)

            if (hemi == 'both'
                    or hemi == 'rh') and s['seg_name'].endswith('rh'):
                labels_rh = mne.read_label(
                    op.join(src_dir.format(subject),
                            '{0}_{1}-lab-rh.label'.format(subject, s['type'])))
                all_src = np.full((labels_rh.pos.shape[0], 3), 1.)
                for v, p in zip(labels_rh.vertices, labels_rh.values - 208):
                    all_src[int(v), :] = textures[int(p), :]
                rgb_marsatlas.append(all_src)

    rgb_marsatlas = np.vstack(tuple(rgb_marsatlas))
    rgb_marsatlas = list(rgb_marsatlas)

    return rgb_marsatlas
Exemple #37
0
def test_copy():
    """Test label copying."""
    label = read_label(label_fname)
    label_2 = label.copy()
    label_2.pos += 1
    assert_array_equal(label.pos, label_2.pos - 1)
Exemple #38
0
# Compute inverse solution and for each epoch. By using "return_generator=True"
# stcs will be a generator object instead of a list.
snr = 1.0  # use lower SNR for single epochs
lambda2 = 1.0 / snr**2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
stcs = apply_inverse_epochs(epochs,
                            inverse_operator,
                            lambda2,
                            method,
                            pick_ori="normal",
                            return_generator=True)

# Read some labels
names = ['Aud-lh', 'Aud-rh', 'Vis-lh', 'Vis-rh']
labels = [
    mne.read_label(data_path + '/MEG/sample/labels/%s.label' % name)
    for name in names
]

# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs,
                                         labels,
                                         src,
                                         mode='mean_flip',
                                         return_generator=True)

fmin, fmax = 5., 40.
sfreq = raw.info['sfreq']  # the sampling frequency
Exemple #39
0
# Load epochs
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=(None, 0),
                    reject=reject,
                    preload=True)

# Compute a source estimate per frequency band including and excluding the
# evoked response
frequencies = np.arange(7, 30, 2)  # define frequencies of interest
label = mne.read_label(fname_label)
n_cycles = frequencies / 3.  # different number of cycle per frequency

# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()

import matplotlib.pyplot as plt
plt.close('all')

for ii, (this_epochs, title) in enumerate(
        zip([epochs, epochs_induced], ['evoked + induced', 'induced only'])):
    # compute the source space power and phase lock
    power, phase_lock = source_induced_power(this_epochs,
                                             inverse_operator,
                                             frequencies,
                                             label,
Exemple #40
0
def test_generate_stc_single_hemi():
    """ Test generation of source estimate, single hemi """
    fwd = read_forward_solution_meg(fname_fwd, force_fixed=True)
    labels_single_hemi = [
        read_label(
            op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label))
        for label in label_names_single_hemi
    ]
    mylabels = []
    for i, label in enumerate(labels_single_hemi):
        new_label = Label(vertices=label.vertices,
                          pos=label.pos,
                          values=2 * i * np.ones(len(label.values)),
                          hemi=label.hemi,
                          comment=label.comment)
        mylabels.append(new_label)

    n_times = 10
    tmin = 0
    tstep = 1e-3

    stc_data = np.ones((len(labels_single_hemi), n_times))
    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep)

    for label in labels_single_hemi:
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        assert_true(np.all(stc.data[idx] == 1.0))
        assert_true(stc.data[idx].shape[1] == n_times)

    # test with function
    def fun(x):
        return x**2

    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep, fun)

    # the first label has value 0, the second value 2, the third value 6

    for i, label in enumerate(labels_single_hemi):
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        res = ((2. * i)**2.) * np.ones((len(idx), n_times))
        assert_array_almost_equal(stc.data[idx], res)
Exemple #41
0
def test_simulate_stc():
    """Test generation of source estimate."""
    fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                         '%s.label' % label)) for label in label_names]
    mylabels = []
    for i, label in enumerate(labels):
        new_label = Label(vertices=label.vertices,
                          pos=label.pos,
                          values=2 * i * np.ones(len(label.values)),
                          hemi=label.hemi,
                          comment=label.comment)
        mylabels.append(new_label)

    n_times = 10
    tmin = 0
    tstep = 1e-3

    stc_data = np.ones((len(labels), n_times))
    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep)
    assert_equal(stc.subject, 'sample')

    for label in labels:
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        assert (np.all(stc.data[idx] == 1.0))
        assert (stc.data[idx].shape[1] == n_times)

    # test with function
    def fun(x):
        return x ** 2
    stc = simulate_stc(fwd['src'], mylabels, stc_data, tmin, tstep, fun)

    # the first label has value 0, the second value 2, the third value 6

    for i, label in enumerate(labels):
        if label.hemi == 'lh':
            hemi_idx = 0
        else:
            hemi_idx = 1

        idx = np.intersect1d(stc.vertices[hemi_idx], label.vertices)
        idx = np.searchsorted(stc.vertices[hemi_idx], idx)

        if hemi_idx == 1:
            idx += len(stc.vertices[0])

        res = ((2. * i) ** 2.) * np.ones((len(idx), n_times))
        assert_array_almost_equal(stc.data[idx], res)

    # degenerate conditions
    label_subset = mylabels[:2]
    data_subset = stc_data[:2]
    stc = simulate_stc(fwd['src'], label_subset, data_subset, tmin, tstep, fun)
    pytest.raises(ValueError, simulate_stc, fwd['src'],
                  label_subset, data_subset[:-1], tmin, tstep, fun)
    pytest.raises(RuntimeError, simulate_stc, fwd['src'], label_subset * 2,
                  np.concatenate([data_subset] * 2, axis=0), tmin, tstep, fun)
Exemple #42
0
def test_simulate_sparse_stc():
    """ Test generation of sparse source estimate """
    fwd = read_forward_solution_meg(fname_fwd, force_fixed=True)
    labels = [
        read_label(
            op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label))
        for label in label_names
    ]

    n_times = 10
    tmin = 0
    tstep = 1e-3
    times = np.arange(n_times, dtype=np.float) * tstep + tmin

    assert_raises(ValueError,
                  simulate_sparse_stc,
                  fwd['src'],
                  len(labels),
                  times,
                  labels=labels,
                  location='center',
                  subject='sample',
                  subjects_dir=subjects_dir)  # no non-zero values
    for label in labels:
        label.values.fill(1.)
    for location in ('random', 'center'):
        random_state = 0 if location == 'random' else None
        stc_1 = simulate_sparse_stc(fwd['src'],
                                    len(labels),
                                    times,
                                    labels=labels,
                                    random_state=random_state,
                                    location=location,
                                    subjects_dir=subjects_dir)
        assert_equal(stc_1.subject, 'sample')

        assert_true(stc_1.data.shape[0] == len(labels))
        assert_true(stc_1.data.shape[1] == n_times)

        # make sure we get the same result when using the same seed
        stc_2 = simulate_sparse_stc(fwd['src'],
                                    len(labels),
                                    times,
                                    labels=labels,
                                    random_state=random_state,
                                    location=location,
                                    subjects_dir=subjects_dir)

        assert_array_equal(stc_1.lh_vertno, stc_2.lh_vertno)
        assert_array_equal(stc_1.rh_vertno, stc_2.rh_vertno)
    # Degenerate cases
    assert_raises(ValueError,
                  simulate_sparse_stc,
                  fwd['src'],
                  len(labels),
                  times,
                  labels=labels,
                  location='center',
                  subject='foo',
                  subjects_dir=subjects_dir)  # wrong subject
    del fwd['src'][0]['subject_his_id']
    assert_raises(ValueError,
                  simulate_sparse_stc,
                  fwd['src'],
                  len(labels),
                  times,
                  labels=labels,
                  location='center',
                  subjects_dir=subjects_dir)  # no subject
    assert_raises(ValueError,
                  simulate_sparse_stc,
                  fwd['src'],
                  len(labels),
                  times,
                  labels=labels,
                  location='foo')  # bad location
Exemple #43
0
def test_tf_lcmv():
    """Test TF beamforming based on LCMV."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)

    event_id, tmin, tmax = 1, -0.2, 0.2

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=True,
                           eog=True,
                           exclude='bads',
                           selection=left_temporal_channels)
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    raw.info.normalize_proj()  # avoid projection warnings
    del picks

    # Read epochs
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        proj=True,
                        baseline=None,
                        preload=False,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    epochs.drop_bad()

    freq_bins = [(4, 12), (15, 40)]
    time_windows = [(-0.1, 0.1), (0.0, 0.2)]
    win_lengths = [0.2, 0.2]
    tstep = 0.1
    reg = 0.05

    source_power = []
    noise_covs = []
    for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths):
        raw_band = raw.copy()
        raw_band.filter(l_freq,
                        h_freq,
                        method='iir',
                        n_jobs=1,
                        iir_params=dict(output='ba'))
        epochs_band = mne.Epochs(raw_band,
                                 epochs.events,
                                 epochs.event_id,
                                 tmin=tmin,
                                 tmax=tmax,
                                 baseline=None,
                                 proj=True)
        with warnings.catch_warnings(record=True):  # not enough samples
            noise_cov = compute_covariance(epochs_band,
                                           tmin=tmin,
                                           tmax=tmin + win_length)
        noise_cov = mne.cov.regularize(noise_cov,
                                       epochs_band.info,
                                       mag=reg,
                                       grad=reg,
                                       eeg=reg,
                                       proj=True)
        noise_covs.append(noise_cov)
        del raw_band  # to save memory

        # Manually calculating source power in on frequency band and several
        # time windows to compare to tf_lcmv results and test overlapping
        if (l_freq, h_freq) == freq_bins[0]:
            for time_window in time_windows:
                with warnings.catch_warnings(record=True):  # bad samples
                    data_cov = compute_covariance(epochs_band,
                                                  tmin=time_window[0],
                                                  tmax=time_window[1])
                with warnings.catch_warnings(record=True):  # bad proj
                    stc_source_power = _lcmv_source_power(epochs.info,
                                                          forward,
                                                          noise_cov,
                                                          data_cov,
                                                          reg=reg,
                                                          label=label)
                source_power.append(stc_source_power.data)

    with warnings.catch_warnings(record=True):
        stcs = tf_lcmv(epochs,
                       forward,
                       noise_covs,
                       tmin,
                       tmax,
                       tstep,
                       win_lengths,
                       freq_bins,
                       reg=reg,
                       label=label)

    assert_true(len(stcs) == len(freq_bins))
    assert_true(stcs[0].shape[1] == 4)

    # Averaging all time windows that overlap the time period 0 to 100 ms
    source_power = np.mean(source_power, axis=0)

    # Selecting the first frequency bin in tf_lcmv results
    stc = stcs[0]

    # Comparing tf_lcmv results with _lcmv_source_power results
    assert_array_almost_equal(stc.data[:, 2], source_power[:, 0])

    # Test if using unsupported max-power orientation is detected
    assert_raises(ValueError,
                  tf_lcmv,
                  epochs,
                  forward,
                  noise_covs,
                  tmin,
                  tmax,
                  tstep,
                  win_lengths,
                  freq_bins=freq_bins,
                  pick_ori='max-power')

    # Test if incorrect number of noise CSDs is detected
    # Test if incorrect number of noise covariances is detected
    assert_raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin,
                  tmax, tstep, win_lengths, freq_bins)

    # Test if freq_bins and win_lengths incompatibility is detected
    assert_raises(ValueError,
                  tf_lcmv,
                  epochs,
                  forward,
                  noise_covs,
                  tmin,
                  tmax,
                  tstep,
                  win_lengths=[0, 1, 2],
                  freq_bins=freq_bins)

    # Test if time step exceeding window lengths is detected
    assert_raises(ValueError,
                  tf_lcmv,
                  epochs,
                  forward,
                  noise_covs,
                  tmin,
                  tmax,
                  tstep=0.15,
                  win_lengths=[0.2, 0.1],
                  freq_bins=freq_bins)

    # Test correct detection of preloaded epochs objects that do not contain
    # the underlying raw object
    epochs_preloaded = mne.Epochs(raw,
                                  events,
                                  event_id,
                                  tmin,
                                  tmax,
                                  proj=True,
                                  baseline=(None, 0),
                                  preload=True)
    epochs_preloaded._raw = None
    with warnings.catch_warnings(record=True):  # not enough samples
        assert_raises(ValueError, tf_lcmv, epochs_preloaded, forward,
                      noise_covs, tmin, tmax, tstep, win_lengths, freq_bins)

    with warnings.catch_warnings(record=True):  # not enough samples
        # Pass only one epoch to test if subtracting evoked
        # responses yields zeros
        stcs = tf_lcmv(epochs[0],
                       forward,
                       noise_covs,
                       tmin,
                       tmax,
                       tstep,
                       win_lengths,
                       freq_bins,
                       subtract_evoked=True,
                       reg=reg,
                       label=label)

    assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
Exemple #44
0
def _get_data(tmin=-0.1,
              tmax=0.15,
              all_forward=True,
              epochs=True,
              epochs_preload=True,
              data_cov=True):
    """Read in data used in tests."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)
    if all_forward:
        forward_surf_ori = _read_forward_solution_meg(fname_fwd, surf_ori=True)
        forward_fixed = _read_forward_solution_meg(fname_fwd,
                                                   force_fixed=True,
                                                   surf_ori=True)
        forward_vol = _read_forward_solution_meg(fname_fwd_vol, surf_ori=True)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bad channels
    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=True,
                           eog=True,
                           ref_meg=False,
                           exclude='bads',
                           selection=left_temporal_channels)
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    raw.info.normalize_proj()  # avoid projection warnings

    if epochs:
        # Read epochs
        epochs = mne.Epochs(raw,
                            events,
                            event_id,
                            tmin,
                            tmax,
                            proj=True,
                            baseline=(None, 0),
                            preload=epochs_preload,
                            reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
        if epochs_preload:
            epochs.resample(200, npad=0, n_jobs=2)
        epochs.crop(0, None)
        evoked = epochs.average()
        info = evoked.info
    else:
        epochs = None
        evoked = None
        info = raw.info

    noise_cov = mne.read_cov(fname_cov)
    noise_cov['projs'] = []  # avoid warning
    with warnings.catch_warnings(record=True):  # bad proj
        noise_cov = mne.cov.regularize(noise_cov,
                                       info,
                                       mag=0.05,
                                       grad=0.05,
                                       eeg=0.1,
                                       proj=True)
    if data_cov:
        with warnings.catch_warnings(record=True):  # too few samples
            data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145)
    else:
        data_cov = None

    return raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
Exemple #45
0
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True):
    """Read in data used in tests
    """
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)[:10]
    raw = mne.fiff.Raw(fname_raw, preload=False)
    forward = mne.read_forward_solution(fname_fwd)
    if read_all_forward:
        forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True)
        forward_fixed = mne.read_forward_solution(fname_fwd,
                                                  force_fixed=True,
                                                  surf_ori=True)
        forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.fiff.pick_types(raw.info,
                                meg=True,
                                eeg=False,
                                stim=True,
                                eog=True,
                                exclude='bads',
                                selection=left_temporal_channels)

    # Read epochs
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        proj=True,
                        picks=picks,
                        baseline=(None, 0),
                        preload=True,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    epochs.resample(200, npad=0, n_jobs=2)
    evoked = epochs.average()

    # Computing the data and noise cross-spectral density matrices
    if compute_csds:
        data_csd = compute_epochs_csd(epochs,
                                      mode='multitaper',
                                      tmin=0.04,
                                      tmax=None,
                                      fmin=8,
                                      fmax=12,
                                      mt_bandwidth=72.72)
        noise_csd = compute_epochs_csd(epochs,
                                       mode='multitaper',
                                       tmin=None,
                                       tmax=0.0,
                                       fmin=8,
                                       fmax=12,
                                       mt_bandwidth=72.72)
    else:
        data_csd, noise_csd = None, None

    return raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
Exemple #46
0
def _get_data(tmin=-0.1,
              tmax=0.15,
              all_forward=True,
              epochs=True,
              epochs_preload=True,
              data_cov=True):
    """Read in data used in tests
    """
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.Raw(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)
    if all_forward:
        forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True)
        forward_fixed = mne.read_forward_solution(fname_fwd,
                                                  force_fixed=True,
                                                  surf_ori=True)
        forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    if epochs:
        # Set up pick list: MEG - bad channels
        left_temporal_channels = mne.read_selection('Left-temporal')
        picks = mne.pick_types(raw.info,
                               meg=True,
                               eeg=False,
                               stim=True,
                               eog=True,
                               ref_meg=False,
                               exclude='bads',
                               selection=left_temporal_channels)

        # Read epochs
        epochs = mne.Epochs(raw,
                            events,
                            event_id,
                            tmin,
                            tmax,
                            proj=True,
                            picks=picks,
                            baseline=(None, 0),
                            preload=epochs_preload,
                            reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
        if epochs_preload:
            epochs.resample(200, npad=0, n_jobs=2)
        evoked = epochs.average()
        info = evoked.info
    else:
        epochs = None
        evoked = None
        info = raw.info

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov,
                                   info,
                                   mag=0.05,
                                   grad=0.05,
                                   eeg=0.1,
                                   proj=True)
    if data_cov:
        data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    else:
        data_cov = None

    return raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
Exemple #47
0
def read_texture_label(filename):
    label = mne.read_label(filename, subject=None, color=None)

    return label
stc_out_dir = "/home/ying/dropbox_unsync/MEG_scene_neil/MEG_EEG_DATA/Result_MAT/" \
            + "source_solution/dSPM_%s_ave_per_im/" % MEGorEEG[isMEG]
fname_suffix = "1_110Hz_notch_ica_ave_alpha15.0_no_aspect"

# read ROI labels
labeldir1 = labeldir + "%s/" % subj
# load and merge the labels
labels_bihemi = list()
lr_label_list = list()
lr_label_names = list()
for j in range(len(ROI_bihemi_names)):
    for hemi in ['lh', 'rh']:
        print subj, j, hemi
        tmp_label_path = labeldir1 + "%s_%s-%s.label" % (
            subj, ROI_bihemi_names[j], hemi)
        tmp_label = mne.read_label(tmp_label_path)
        lr_label_list.append(tmp_label)
        lr_label_names.append(ROI_bihemi_names[j] + "_" + hemi)
for j in range(len(ROI_bihemi_names)):
    labels_bihemi.append(lr_label_list[2 * j] + lr_label_list[2 * j + 1])

labels = labels_bihemi
fwd = mne.read_forward_solution(fwd1_fname, force_fixed=True, surf_ori=True)
print "difference of G"
print np.max(np.abs(fwd['sol']['data'])) / np.min(np.abs(fwd['sol']['data']))

m = fwd['sol']['ncol']
ind0, ind1 = fwd['src'][0]['inuse'], fwd['src'][1]['inuse']
# positions of dipoles
rr = np.vstack(
    [fwd['src'][0]['rr'][ind0 == 1, :], fwd['src'][1]['rr'][ind1 == 1, :]])
subject_id = "fsaverage"
hemi = "split"
#surf = "smoothwm"
surf = 'inflated'
brain = Brain(subject_id, hemi, surf)
import os, random

list_dirs = os.walk(subject_path + '/func_labels/')
src = inverse_operator['src']
dipoles = []
color = ['#990033', '#9900CC', '#FF6600', '#FF3333', '#00CC33']
for root, dirs, files in list_dirs:
    for f in files:
        label_fname = os.path.join(root, f)
        label = mne.read_label(label_fname)
        #label.values.fill(1.0)
        #label_morph = label.morph(subject_from='fsaverage', subject_to=subject, smooth=5,
        #                        n_jobs=1, copy=True)
        stc_label = stc_avg.in_label(label)
        src_pow = np.sum(stc_label.data**2, axis=1)
        if label.hemi == 'lh':
            seed_vertno = stc_label.vertno[0][np.argmax(
                src_pow)]  #Get the max MNE value within each ROI
            brain.add_foci(seed_vertno,
                           coords_as_verts=True,
                           hemi='lh',
                           color=random.choice(color),
                           scale_factor=0.6)
        elif label.hemi == 'rh':
            seed_vertno = stc_label.vertno[1][np.argmax(src_pow)]
subjects=  ['MRI_meg16_0030' ,#0
            'MRI_meg16_0032' ,#1
            'MRI_meg16_0034' ,#2
            'MRI_meg16_0035' ,#3
            'MRI_meg16_0042' ,#4
            'MRI_meg16_0045' ,#5
            'MRI_meg16_0052' ,#6
            'MRI_meg16_0056' ,#7
    	       'MRI_meg16_0069' ,#8
 	       'MRI_meg16_0070' ,#9
            'MRI_meg16_0072' ,#10
            'MRI_meg16_0073' ,#11
            'MRI_meg16_0075' ,#12
            'MRI_meg16_0078' ,#13
            'MRI_meg16_0082' ,#14
            'MRI_meg16_0086' ,#15
            'MRI_meg16_0097' ,#16
            'MRI_meg16_0122' ,#17
            'MRI_meg16_0125' ,#18
            ]


ll = []
for ss in subject_inds:
 ll.append(list_all[ss])



labellist_path = [label_path+'vis_final-lh.label',label_path+'auditory_final-lh.label',label_path+'hand_c2-lh.label']#[ 'lh.posterior_fusiform','rh.posterior_fusiform', 'lh.lateraloccipital','rh.lateraloccipital','lh.precentral','rh.precentral', 'lh.ATL_latmed','rh.ATL_latmed']#labellist = [ 'leftATL-lh','rightATL-rh']#, 'medialtempright-rh','medialtempleft-lh']'lh.postcentral','rh.postcentral',
labellist1=[mne.read_label(label) for label in labellist_path]
import mne
from mne.datasets import sample
import matplotlib.pyplot as plt

print(__doc__)

data_path = sample.data_path()
os.environ['SUBJECTS_DIR'] = data_path + '/subjects'
meg_path = data_path + '/MEG/sample'

# load the stc
stc = mne.read_source_estimate(meg_path + '/sample_audvis-meg')

# load the labels
aud_lh = mne.read_label(meg_path + '/labels/Aud-lh.label')
aud_rh = mne.read_label(meg_path + '/labels/Aud-rh.label')

# extract the time course for different labels from the stc
stc_lh = stc.in_label(aud_lh)
stc_rh = stc.in_label(aud_rh)
stc_bh = stc.in_label(aud_lh + aud_rh)

# calculate center of mass and transform to mni coordinates
vtx, _, t_lh = stc_lh.center_of_mass('sample')
mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0]
vtx, _, t_rh = stc_rh.center_of_mass('sample')
mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0]

# plot the activation
plt.figure()
Exemple #52
0
import bct
import os
import datetime
from mne.label import read_labels_from_annot

subjects = ['CC110033', 'CC110037', 'CC110045']
subject = subjects[0]

data_path = '/cluster/transcend/sheraz/Dropbox/mne-camcan-data/'
subjects_dir = op.join(data_path, 'recons')
subject_dir = op.join(subjects_dir, subject)
bem_dir = op.join(subject_dir, 'bem')
trans_file = op.join(data_path, 'trans', subject + '-trans.fif')
labels_fname = glob.glob(op.join(data_path, 'labels', '*.label'))
labels = [
    mne.read_label(label, subject='fsaverageSK', color='r')
    for label in labels_fname
]
for index, label in enumerate(labels):
    label.values.fill(1.0)
    labels[index] = label

labels = [
    label.morph('fsaverageSK', subject, subjects_dir=subjects_dir)
    for label in labels
]
labels = read_labels_from_annot(subject,
                                'aparc',
                                'both',
                                subjects_dir=subjects_dir)
def test_resolution_matrix():
    """Test make_inverse_resolution_matrix() function."""
    # read forward solution
    forward = mne.read_forward_solution(fname_fwd)
    # forward operator with fixed source orientations
    forward_fxd = mne.convert_forward_solution(forward, surf_ori=True,
                                               force_fixed=True)

    # noise covariance matrix
    noise_cov = mne.read_cov(fname_cov)
    # evoked data for info
    evoked = mne.read_evokeds(fname_evoked, 0)

    # make inverse operator from forward solution
    # free source orientation
    inverse_operator = mne.minimum_norm.make_inverse_operator(
        info=evoked.info, forward=forward, noise_cov=noise_cov, loose=1.,
        depth=None)
    # fixed source orientation
    inverse_operator_fxd = mne.minimum_norm.make_inverse_operator(
        info=evoked.info, forward=forward, noise_cov=noise_cov, loose=0.,
        depth=None, fixed=True)

    # regularisation parameter based on SNR
    snr = 3.0
    lambda2 = 1.0 / snr ** 2
    # resolution matrices for free source orientation
    # compute resolution matrix for MNE with free source orientations
    rm_mne_free = make_inverse_resolution_matrix(forward, inverse_operator,
                                                 method='MNE', lambda2=lambda2)
    # compute resolution matrix for MNE, fwd fixed and inv free
    rm_mne_fxdfree = make_inverse_resolution_matrix(forward_fxd,
                                                    inverse_operator,
                                                    method='MNE',
                                                    lambda2=lambda2)
    # resolution matrices for fixed source orientation
    # compute resolution matrix for MNE
    rm_mne = make_inverse_resolution_matrix(forward_fxd, inverse_operator_fxd,
                                            method='MNE', lambda2=lambda2)
    # compute resolution matrix for sLORETA
    rm_lor = make_inverse_resolution_matrix(forward_fxd, inverse_operator_fxd,
                                            method='sLORETA', lambda2=lambda2)
    # rectify resolution matrix for sLORETA before determining maxima
    rm_lor_abs = np.abs(rm_lor)

    # get maxima per column
    maxidxs = rm_lor_abs.argmax(axis=0)
    # create array with the expected stepwise increase in maximum indices
    goodidxs = np.arange(0, len(maxidxs), 1)

    # Tests
    # Does sLORETA have zero dipole localization error for columns/PSFs?
    assert_array_equal(maxidxs, goodidxs)
    # MNE resolution matrices symmetric?
    assert_array_almost_equal(rm_mne, rm_mne.T)
    assert_array_almost_equal(rm_mne_free, rm_mne_free.T)

    # Some arbitrary vertex numbers
    idx = [1, 100, 400]
    # check various summary and normalisation options
    for mode in [None, 'sum', 'mean', 'maxval', 'maxnorm', 'pca']:
        n_comps = [1, 3]
        if mode in [None, 'sum', 'mean']:
            n_comps = [1]
        for n_comp in n_comps:
            for norm in [None, 'max', 'norm', True]:
                stc_psf = get_point_spread(
                    rm_mne, forward_fxd['src'], idx, mode=mode, n_comp=n_comp,
                    norm=norm, return_pca_vars=False)
                stc_ctf = get_cross_talk(
                    rm_mne, forward_fxd['src'], idx, mode=mode, n_comp=n_comp,
                    norm=norm, return_pca_vars=False)
                # for MNE, PSF/CTFs for same vertices should be the same
                assert_array_almost_equal(stc_psf.data, stc_ctf.data)

    # check SVD variances
    stc_psf, s_vars_psf = get_point_spread(
        rm_mne, forward_fxd['src'], idx, mode=mode, n_comp=n_comp,
        norm='norm', return_pca_vars=True)
    stc_ctf, s_vars_ctf = get_cross_talk(
        rm_mne, forward_fxd['src'], idx, mode=mode, n_comp=n_comp,
        norm='norm', return_pca_vars=True)
    assert_array_almost_equal(s_vars_psf, s_vars_ctf)
    # variances for SVD components should be ordered
    assert s_vars_psf[0] > s_vars_psf[1] > s_vars_psf[2]
    # all variances should sum up to 100
    assert_allclose(s_vars_psf.sum(), 100.)

    # Test application of free inv to fixed fwd
    assert_equal(rm_mne_fxdfree.shape, (3 * rm_mne.shape[0],
                 rm_mne.shape[0]))

    # Test PSF/CTF for labels
    label = mne.read_label(fname_label)
    # must be list of Label
    label = [label]
    label2 = 2 * label
    # get relevant vertices in source space
    verts = _vertices_for_get_psf_ctf(label, forward_fxd['src'])[0]

    stc_psf_label = get_point_spread(rm_mne, forward_fxd['src'], label,
                                     norm='max')
    # for list of indices
    stc_psf_idx = get_point_spread(rm_mne, forward_fxd['src'], verts,
                                   norm='max')
    stc_ctf_label = get_cross_talk(rm_mne, forward_fxd['src'], label,
                                   norm='max')
    # For MNE, PSF and CTF for same vertices should be the same
    assert_array_almost_equal(stc_psf_label.data, stc_ctf_label.data)
    # test multiple labels
    stc_psf_label2 = get_point_spread(rm_mne, forward_fxd['src'], label2,
                                      norm='max')
    m, n = stc_psf_label.data.shape
    assert_array_equal(
        stc_psf_label.data, stc_psf_label2[0].data)
    assert_array_equal(
        stc_psf_label.data, stc_psf_label2[1].data)
    assert_array_equal(
        stc_psf_label.data, stc_psf_idx.data)
# w = mne.read_w(env.fsl + '/mni/bem/cortex-3-rh.w')
# y_voxels = w['vertices']

Y = cortex[:, y_voxels]

alphas = np.logspace(-4, -.5, 20)

my_sub_vertices = []
# in nice order from anterior to posterior in the cortex (cingulate is last)
label_names = [
    'medialdorsal', 'va', 'vl', 'vp', 'lateraldorsal', 'lateralposterior',
    'pulvinar', 'anteriornuclei'
]
# label_names = ['medialdorsal', 'va', 'vl', 'vp', 'pulvinar', 'anteriornuclei']
for l in label_names:
    v = mne.read_label(env.fsl + '/mni/label/rh.' + l + '.label')
    my_sub_vertices.append(v.vertices)

num_subjects = cortex.shape[0]

# X = np.zeros([num_subjects, len(my_sub_vertices)])
# for r, roi in enumerate(my_sub_vertices):
#     X[:, r] = scipy.stats.nanmean(subcortex[:, roi], axis=1)
X = subcortex

# lasso_cv = linear_model.LassoCV(alphas=alphas)
# k_fold = cross_validation.KFold(X.shape[0], 10)
# scores = np.zeros([len(k_fold), len(y_voxels)])
# alphas = np.zeros([len(k_fold), len(y_voxels)])
# for k, (train, test) in enumerate(k_fold):
#     print 'fold {%d}' % k
Exemple #55
0
def test_psf_ctf():
    """Test computation of PSFs and CTFs for linear estimators."""
    forward = read_forward_solution(fname_fwd)
    labels = [mne.read_label(ss) for ss in fname_label]

    method = 'MNE'
    n_svd_comp = 2

    # make sure it works for both types of inverses
    for fname_inv in (fname_inv_meg, fname_inv_meeg):
        inverse_operator = read_inverse_operator(fname_inv)
        # Test PSFs (then CTFs)
        for mode in ('sum', 'svd'):
            with pytest.deprecated_call():
                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,
                                                        use_cps=True)

            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 (n_vert == should_n_vert)
            assert (n_samples == should_n_samples)

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

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

            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 (n_vert == should_n_vert)
            assert (n_samples == should_n_samples)
def _read_labels_parallel(files_chunk):
    labels = []
    for label_fname in files_chunk:
        label = mne.read_label(label_fname)
        labels.append(label)
    return labels
Exemple #57
0
def test_tf_lcmv():
    """Test TF beamforming based on LCMV."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)

    event_id, tmin, tmax = 1, -0.2, 0.2

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info, selection=left_temporal_channels)
    picks = picks[::2]  # decimate for speed
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    raw.info.normalize_proj()  # avoid projection warnings
    del picks

    # Read epochs
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        baseline=None, preload=False, reject=reject)
    epochs.load_data()

    freq_bins = [(4, 12), (15, 40)]
    time_windows = [(-0.1, 0.1), (0.0, 0.2)]
    win_lengths = [0.2, 0.2]
    tstep = 0.1
    reg = 0.05

    source_power = []
    noise_covs = []
    for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths):
        raw_band = raw.copy()
        raw_band.filter(l_freq, h_freq, method='iir', n_jobs=1,
                        iir_params=dict(output='ba'))
        epochs_band = mne.Epochs(
            raw_band, epochs.events, epochs.event_id, tmin=tmin, tmax=tmax,
            baseline=None, proj=True)
        noise_cov = mne.compute_covariance(
            epochs_band, tmin=tmin, tmax=tmin + win_length)
        noise_cov = mne.cov.regularize(
            noise_cov, epochs_band.info, mag=reg, grad=reg, eeg=reg,
            proj=True, rank=None)
        noise_covs.append(noise_cov)
        del raw_band  # to save memory

        # Manually calculating source power in on frequency band and several
        # time windows to compare to tf_lcmv results and test overlapping
        if (l_freq, h_freq) == freq_bins[0]:
            for time_window in time_windows:
                data_cov = mne.compute_covariance(
                    epochs_band, tmin=time_window[0], tmax=time_window[1])
                stc_source_power = _lcmv_source_power(
                    epochs.info, forward, noise_cov, data_cov,
                    reg=reg, label=label, weight_norm='unit-noise-gain')
                source_power.append(stc_source_power.data)

    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
                  tstep, win_lengths, freq_bins, reg=reg, label=label)
    stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep,
                   win_lengths, freq_bins, reg=reg, label=label, raw=raw)

    assert (len(stcs) == len(freq_bins))
    assert (stcs[0].shape[1] == 4)

    # Averaging all time windows that overlap the time period 0 to 100 ms
    source_power = np.mean(source_power, axis=0)

    # Selecting the first frequency bin in tf_lcmv results
    stc = stcs[0]

    # Comparing tf_lcmv results with _lcmv_source_power results
    assert_array_almost_equal(stc.data[:, 2], source_power[:, 0])

    # Test if using unsupported max-power orientation is detected
    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
                  tstep, win_lengths, freq_bins=freq_bins,
                  pick_ori='max-power')

    # Test if incorrect number of noise CSDs is detected
    # Test if incorrect number of noise covariances is detected
    pytest.raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin,
                  tmax, tstep, win_lengths, freq_bins)

    # Test if freq_bins and win_lengths incompatibility is detected
    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
                  tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins)

    # Test if time step exceeding window lengths is detected
    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
                  tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins)

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs=None,
                  tmin=tmin, tmax=tmax, tstep=tstep, win_lengths=win_lengths,
                  freq_bins=freq_bins)

    # Test if unsupported weight normalization specification is detected
    pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
                  tstep, win_lengths, freq_bins, weight_norm='nai')

    # Test unsupported pick_ori (vector not supported here)
    with pytest.raises(ValueError, match='pick_ori'):
        tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths,
                freq_bins, pick_ori='vector')
    # Test correct detection of preloaded epochs objects that do not contain
    # the underlying raw object
    epochs_preloaded = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                                  baseline=(None, 0), preload=True)
    epochs_preloaded._raw = None
    pytest.raises(ValueError, tf_lcmv, epochs_preloaded, forward,
                  noise_covs, tmin, tmax, tstep, win_lengths, freq_bins)

    # Pass only one epoch to test if subtracting evoked
    # responses yields zeros
    with pytest.warns(RuntimeWarning,
                      match='Too few samples .* estimate may be unreliable'):
        stcs = tf_lcmv(epochs[0], forward, noise_covs, tmin, tmax, tstep,
                       win_lengths, freq_bins, subtract_evoked=True, reg=reg,
                       label=label, raw=raw)

    assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
Exemple #58
0
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True,
              epochs_preload=True, data_cov=True, proj=True):
    """Read in data used in tests."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    forward = mne.read_forward_solution(fname_fwd)
    if all_forward:
        forward_surf_ori = _read_forward_solution_meg(
            fname_fwd, surf_ori=True)
        forward_fixed = _read_forward_solution_meg(
            fname_fwd, force_fixed=True, surf_ori=True, use_cps=False)
        forward_vol = _read_forward_solution_meg(fname_fwd_vol)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bad channels
    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info, selection=left_temporal_channels)
    picks = picks[::2]  # decimate for speed
    # add a couple channels we will consider bad
    bad_picks = [100, 101]
    bads = [raw.ch_names[pick] for pick in bad_picks]
    assert not any(pick in picks for pick in bad_picks)
    picks = np.concatenate([picks, bad_picks])
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    del picks

    raw.info['bads'] = bads  # add more bads
    if proj:
        raw.info.normalize_proj()  # avoid projection warnings
    else:
        raw.del_proj()

    if epochs:
        # Read epochs
        epochs = mne.Epochs(
            raw, events, event_id, tmin, tmax, proj=True,
            baseline=(None, 0), preload=epochs_preload, reject=reject)
        if epochs_preload:
            epochs.resample(200, npad=0)
        epochs.crop(0, None)
        evoked = epochs.average()
        info = evoked.info
    else:
        epochs = None
        evoked = None
        info = raw.info

    noise_cov = mne.read_cov(fname_cov)
    noise_cov['projs'] = []  # avoid warning
    noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05,
                                   eeg=0.1, proj=True, rank=None)
    if data_cov:
        data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145)
    else:
        data_cov = None

    return raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
for subject in SUBJECTS:
 
    allepochs = mne.read_epochs(savepath + subject + '/' + subject + '_isi-epo.fif')
    # Sort epochs according to experimental conditions in the post-stimulus interval
    slow_epo_isi = allepochs.__getitem__('V1')
    fast_epo_isi = allepochs.__getitem__('V3')
    
    fname_inv = savepath + subject + '/' + subject + '_inv'
    inverse_operator = read_inverse_operator(fname_inv, verbose=None)
    src = inverse_operator['src'] 
    
    snr = 1.0  # use lower SNR for single epochs
    lambda2 = 1.0 / snr ** 2
    
    # Read labels for V1 and MT 
    v1_label = mne.read_label(datapath + 'Results_Alpha_and_Gamma/' + subject + '/' + subject + '_V1_rh.label')
    mt_label = mne.read_label(datapath + 'Results_Alpha_and_Gamma/' + subject + '/' + subject + '_MT_rh.label')
    
    # Compute inverse solution for each epochs 
    stcs_slow_v1 = apply_inverse_epochs(slow_epo_isi, inverse_operator, lambda2, method='sLORETA',
                                        pick_ori="normal", return_generator=True)
    stcs_slow_mt = apply_inverse_epochs(slow_epo_isi, inverse_operator, lambda2, method='sLORETA',
                                     pick_ori="normal", return_generator=True)
    
    #extract time courses from vertices
    src = inverse_operator['src']  # the source space used
    seed_ts_slow_v1 = mne.extract_label_time_course(stcs_slow_v1, v1_label, src, mode='mean_flip', verbose='error')
    seed_ts_slow_mt = mne.extract_label_time_course(stcs_slow_mt, mt_label, src, mode='mean_flip', verbose='error')
    
    comb_ts_slow = list(zip(seed_ts_slow_v1, seed_ts_slow_mt))
Exemple #60
0
from mne.connectivity import seed_target_indices, spectral_connectivity

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
label_name_lh = 'Aud-lh'
fname_label_lh = data_path + '/MEG/sample/labels/%s.label' % label_name_lh

event_id, tmin, tmax = 1, -0.2, 0.5
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data
inverse_operator = read_inverse_operator(fname_inv)
label_lh = mne.read_label(fname_label_lh)
raw = Raw(fname_raw)
events = mne.read_events(fname_event)

# Add a bad channel
raw.info['bads'] += ['MEG 2443']

# pick MEG channels
picks = pick_types(raw.info,
                   meg=True,
                   eeg=False,
                   stim=False,
                   eog=True,
                   exclude='bads')

# Read epochs