def test_stc_methods(): """Test stc methods lh_data, rh_data, bin(), center_of_mass(), resample() """ stc = read_source_estimate(fname_stc) # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin bin = stc.bin(.12) a = np.array((1, ), dtype=stc.data.dtype) a[0] = np.mean(stc.data[0, stc.times < .12]) assert a[0] == bin.data[0, 0] assert_raises(ValueError, stc.center_of_mass, 'sample') stc.lh_data[:] = 0 vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir) assert_true(hemi == 1) # XXX Should design a fool-proof test case, but here were the results: assert_equal(vertex, 124791) assert_equal(np.round(t, 2), 0.12) stc = read_source_estimate(fname_stc) stc.subject = 'sample' label_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] label_rh = read_labels_from_annot('sample', 'aparc', 'rh', subjects_dir=subjects_dir)[0] label_both = label_lh + label_rh for label in (label_lh, label_rh, label_both): assert_true(isinstance(stc.shape, tuple) and len(stc.shape) == 2) stc_label = stc.in_label(label) if label.hemi != 'both': if label.hemi == 'lh': verts = stc_label.vertices[0] else: # label.hemi == 'rh': verts = stc_label.vertices[1] n_vertices_used = len(label.get_vertices_used(verts)) assert_equal(len(stc_label.data), n_vertices_used) stc_lh = stc.in_label(label_lh) assert_raises(ValueError, stc_lh.in_label, label_rh) label_lh.subject = 'foo' assert_raises(RuntimeError, stc.in_label, label_lh) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert_true(stc_new.data.shape[1] == stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_stc_methods(): """Test stc methods lh_data, rh_data, bin(), resample().""" stc_ = read_source_estimate(fname_stc) # Make a vector version of the above source estimate x = stc_.data[:, np.newaxis, :] yz = np.zeros((x.shape[0], 2, x.shape[2])) vec_stc_ = VectorSourceEstimate(np.concatenate((x, yz), 1), stc_.vertices, stc_.tmin, stc_.tstep, stc_.subject) for stc in [stc_, vec_stc_]: # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin binned = stc.bin(.12) a = np.mean(stc.data[..., :np.searchsorted(stc.times, .12)], axis=-1) assert_array_equal(a, binned.data[..., 0]) stc = read_source_estimate(fname_stc) stc.subject = 'sample' label_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] label_rh = read_labels_from_annot('sample', 'aparc', 'rh', subjects_dir=subjects_dir)[0] label_both = label_lh + label_rh for label in (label_lh, label_rh, label_both): assert (isinstance(stc.shape, tuple) and len(stc.shape) == 2) stc_label = stc.in_label(label) if label.hemi != 'both': if label.hemi == 'lh': verts = stc_label.vertices[0] else: # label.hemi == 'rh': verts = stc_label.vertices[1] n_vertices_used = len(label.get_vertices_used(verts)) assert_equal(len(stc_label.data), n_vertices_used) stc_lh = stc.in_label(label_lh) pytest.raises(ValueError, stc_lh.in_label, label_rh) label_lh.subject = 'foo' pytest.raises(RuntimeError, stc.in_label, label_lh) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert (stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert (stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert (stc_new.data.shape[1] == stc.data.shape[1]) assert (stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_stc_methods(): """Test stc methods lh_data, rh_data, bin, center_of_mass, resample""" stc = read_source_estimate(fname_stc) # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin bin = stc.bin(.12) a = np.array((1,), dtype=stc.data.dtype) a[0] = np.mean(stc.data[0, stc.times < .12]) assert a[0] == bin.data[0, 0] assert_raises(ValueError, stc.center_of_mass, 'sample') assert_raises(TypeError, stc.center_of_mass, 'sample', subjects_dir=subjects_dir, surf=1) stc.lh_data[:] = 0 vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir) assert_true(hemi == 1) # XXX Should design a fool-proof test case, but here were the results: assert_equal(vertex, 124791) assert_equal(np.round(t, 2), 0.12) stc = read_source_estimate(fname_stc) stc.subject = 'sample' label_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] label_rh = read_labels_from_annot('sample', 'aparc', 'rh', subjects_dir=subjects_dir)[0] label_both = label_lh + label_rh for label in (label_lh, label_rh, label_both): assert_true(isinstance(stc.shape, tuple) and len(stc.shape) == 2) stc_label = stc.in_label(label) if label.hemi != 'both': if label.hemi == 'lh': verts = stc_label.vertices[0] else: # label.hemi == 'rh': verts = stc_label.vertices[1] n_vertices_used = len(label.get_vertices_used(verts)) assert_equal(len(stc_label.data), n_vertices_used) stc_lh = stc.in_label(label_lh) assert_raises(ValueError, stc_lh.in_label, label_rh) label_lh.subject = 'foo' assert_raises(RuntimeError, stc.in_label, label_lh) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert_true(stc_new.data.shape[1] == stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_stc_methods(): """Test stc methods lh_data, rh_data, bin(), resample().""" stc_ = read_source_estimate(fname_stc) # Make a vector version of the above source estimate x = stc_.data[:, np.newaxis, :] yz = np.zeros((x.shape[0], 2, x.shape[2])) vec_stc_ = VectorSourceEstimate( np.concatenate((x, yz), 1), stc_.vertices, stc_.tmin, stc_.tstep, stc_.subject ) for stc in [stc_, vec_stc_]: # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin binned = stc.bin(.12) a = np.mean(stc.data[..., :np.searchsorted(stc.times, .12)], axis=-1) assert_array_equal(a, binned.data[..., 0]) stc = read_source_estimate(fname_stc) stc.subject = 'sample' label_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] label_rh = read_labels_from_annot('sample', 'aparc', 'rh', subjects_dir=subjects_dir)[0] label_both = label_lh + label_rh for label in (label_lh, label_rh, label_both): assert (isinstance(stc.shape, tuple) and len(stc.shape) == 2) stc_label = stc.in_label(label) if label.hemi != 'both': if label.hemi == 'lh': verts = stc_label.vertices[0] else: # label.hemi == 'rh': verts = stc_label.vertices[1] n_vertices_used = len(label.get_vertices_used(verts)) assert_equal(len(stc_label.data), n_vertices_used) stc_lh = stc.in_label(label_lh) pytest.raises(ValueError, stc_lh.in_label, label_rh) label_lh.subject = 'foo' pytest.raises(RuntimeError, stc.in_label, label_lh) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert (stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert (stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert (stc_new.data.shape[1] == stc.data.shape[1]) assert (stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_spatial_inter_hemi_connectivity(): """Test spatial connectivity between hemispheres""" # trivial cases conn = spatial_inter_hemi_connectivity(fname_src_3, 5e-6) assert_equal(conn.data.size, 0) conn = spatial_inter_hemi_connectivity(fname_src_3, 5e6) assert_equal(conn.data.size, np.prod(conn.shape) // 2) # actually interesting case (1cm), should be between 2 and 10% of verts src = read_source_spaces(fname_src_3) conn = spatial_inter_hemi_connectivity(src, 10e-3) conn = conn.tocsr() n_src = conn.shape[0] assert_true(n_src * 0.02 < conn.data.size < n_src * 0.10) assert_equal(conn[:src[0]['nuse'], :src[0]['nuse']].data.size, 0) assert_equal(conn[-src[1]['nuse']:, -src[1]['nuse']:].data.size, 0) c = (conn.T + conn) / 2. - conn c.eliminate_zeros() assert_equal(c.data.size, 0) # check locations upper_right = conn[:src[0]['nuse'], src[0]['nuse']:].toarray() assert_equal(upper_right.sum(), conn.sum() // 2) good_labels = ['S_pericallosal', 'Unknown', 'G_and_S_cingul-Mid-Post', 'G_cuneus'] for hi, hemi in enumerate(('lh', 'rh')): has_neighbors = src[hi]['vertno'][np.where(np.any(upper_right, axis=1 - hi))[0]] labels = read_labels_from_annot('sample', 'aparc.a2009s', hemi, subjects_dir=subjects_dir) use_labels = [l.name[:-3] for l in labels if np.in1d(l.vertices, has_neighbors).any()] assert_true(set(use_labels) - set(good_labels) == set())
def convert_label2label(annot_fname, subjects_list, srcsubject='fsaverage', subjects_dir=None, freesurfer_home=None): ''' Python wrapper for Freesurfer mri_label2label function. Converts all labels in annot_fname from source subject to target subject given the subjects directory. Both hemispheres are considered. The registration method used it surface. Parameters ---------- annot_fname: str The name of the annotation (or parcellation). subjects_list: list or str Subject names to which the labels have to be transformed to (the target subjects). Can be provided as a list or a string. srcsubject: str The name of the source subject to be used. The source subject should contain the labels in the correct folders already. Default - fsaverage. subjects_dir: str The subjects directory, if not provided, then the environment value is used. freesurfer_home: str The freeesurfer home path, if not provided, the environment value is used. Reference: https://surfer.nmr.mgh.harvard.edu/fswiki/mri_label2label ''' if subjects_list: subjects_list = get_files_from_list(subjects_list) else: raise RuntimeError('No subjects are specified.') subjects_dir = check_env_variables(subjects_dir, key='SUBJECTS_DIR') freesurfer_home = check_env_variables(freesurfer_home, key='FREESURFER_HOME') freesurfer_bin = os.path.join(freesurfer_home, 'bin', '') # obtain the names of labels in parcellation from mne.label import read_labels_from_annot labels = read_labels_from_annot(srcsubject, parc=annot_fname) lnames = [l.name.rsplit('-')[0] if l.hemi is 'lh' else '' for l in labels] lnames = filter(None, lnames) # remove empty strings # convert the labels from source subject to target subject from subprocess import call for subj in subjects_list: # the target subject is subj provided print 'Converting labels from %s to %s' % (srcsubject, subj) for label in lnames: for hemi in ['lh', 'rh']: srclabel = os.path.join(subjects_dir, srcsubject, 'label', hemi + '.' + label + '.label') trglabel = os.path.join(subjects_dir, subj, 'label', hemi + '.' + label + '.label') retcode = call([freesurfer_bin + 'mri_label2label', '--srclabel', srclabel, '--srcsubject', srcsubject, '--trglabel', trglabel, '--trgsubject', subj, '--regmethod', 'surface', '--hemi', hemi]) if retcode != 0: retcode_error('mri_label2label') continue print 'Labels for %d subjects have been transformed from source %s' %(len(subjects_list), srcsubject)
def test_expand(): """Test stc expansion """ stc = read_source_estimate(fname, 'sample') assert_true('sample' in repr(stc)) labels_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir) stc_limited = stc.in_label(labels_lh[0] + labels_lh[1]) stc_new = stc_limited.copy() stc_new.data.fill(0) for label in labels_lh[:2]: stc_new += stc.in_label(label).expand(stc_limited.vertno) # make sure we can't add unless vertno agree assert_raises(ValueError, stc.__add__, stc.in_label(labels_lh[0]))
def test_expand(): """Test stc expansion """ stc = read_source_estimate(fname_stc, 'sample') assert_true('sample' in repr(stc)) labels_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir) new_label = labels_lh[0] + labels_lh[1] stc_limited = stc.in_label(new_label) stc_new = stc_limited.copy() stc_new.data.fill(0) for label in labels_lh[:2]: stc_new += stc.in_label(label).expand(stc_limited.vertices) # make sure we can't add unless vertno agree assert_raises(ValueError, stc.__add__, stc.in_label(labels_lh[0]))
def test_extract_label_time_course_equiv(): """Test extraction of label time courses from stc equivalences.""" label = read_labels_from_annot('sample', 'aparc', 'lh', regexp='transv', subjects_dir=subjects_dir) assert len(label) == 1 label = label[0] inv = read_inverse_operator(fname_inv) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01) stc = apply_inverse(evoked, inv, pick_ori='normal', label=label) stc_full = apply_inverse(evoked, inv, pick_ori='normal') stc_in_label = stc_full.in_label(label) mean = stc.extract_label_time_course(label, inv['src']) mean_2 = stc_in_label.extract_label_time_course(label, inv['src']) assert_allclose(mean, mean_2) inv['src'][0]['vertno'] = np.array([], int) assert len(stc_in_label.vertices[0]) == 22 with pytest.raises(ValueError, match='22/22 left hemisphere.*missing'): stc_in_label.extract_label_time_course(label, inv['src'])
def test_stc_methods(): """Test stc methods lh_data, rh_data, bin(), center_of_mass(), resample() """ fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc = read_source_estimate(fname) # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin bin = stc.bin(.12) a = np.array((1, ), dtype=stc.data.dtype) a[0] = np.mean(stc.data[0, stc.times < .12]) assert a[0] == bin.data[0, 0] assert_raises(ValueError, stc.center_of_mass, 'sample') stc.lh_data[:] = 0 vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir) assert_true(hemi == 1) # XXX Should design a fool-proof test case, but here were the results: assert_true(vertex == 90186) assert_true(np.round(t, 3) == 0.123) stc = read_source_estimate(fname) label = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] stc_label = stc.in_label(label) n_vertices_used = len(label.get_vertices_used(stc_label.vertno[0])) assert_equal(len(stc_label.data), n_vertices_used) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert_true(stc_new.data.shape[1] == stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_stc_methods(): """Test stc methods lh_data, rh_data, bin(), center_of_mass(), resample() """ fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg') stc = read_source_estimate(fname) # lh_data / rh_data assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)]) assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):]) # bin bin = stc.bin(.12) a = np.array((1,), dtype=stc.data.dtype) a[0] = np.mean(stc.data[0, stc.times < .12]) assert a[0] == bin.data[0, 0] assert_raises(ValueError, stc.center_of_mass, 'sample') stc.lh_data[:] = 0 vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir) assert_true(hemi == 1) # XXX Should design a fool-proof test case, but here were the results: assert_true(vertex == 90186) assert_true(np.round(t, 3) == 0.123) stc = read_source_estimate(fname) label = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir)[0] stc_label = stc.in_label(label) n_vertices_used = len(label.get_vertices_used(stc_label.vertno[0])) assert_equal(len(stc_label.data), n_vertices_used) stc_new = deepcopy(stc) o_sfreq = 1.0 / stc.tstep # note that using no padding for this STC reduces edge ringing... stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2) assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep / 2) stc_new.resample(o_sfreq, npad=0) assert_true(stc_new.data.shape[1] == stc.data.shape[1]) assert_true(stc_new.tstep == stc.tstep) assert_array_almost_equal(stc_new.data, stc.data, 5)
def test_expand(): """Test stc expansion.""" stc_ = read_source_estimate(fname_stc, 'sample') vec_stc_ = VectorSourceEstimate(np.zeros((stc_.data.shape[0], 3, stc_.data.shape[1])), stc_.vertices, stc_.tmin, stc_.tstep, stc_.subject) for stc in [stc_, vec_stc_]: assert ('sample' in repr(stc)) labels_lh = read_labels_from_annot('sample', 'aparc', 'lh', subjects_dir=subjects_dir) new_label = labels_lh[0] + labels_lh[1] stc_limited = stc.in_label(new_label) stc_new = stc_limited.copy() stc_new.data.fill(0) for label in labels_lh[:2]: stc_new += stc.in_label(label).expand(stc_limited.vertices) pytest.raises(TypeError, stc_new.expand, stc_limited.vertices[0]) pytest.raises(ValueError, stc_new.expand, [stc_limited.vertices[0]]) # make sure we can't add unless vertno agree pytest.raises(ValueError, stc.__add__, stc.in_label(labels_lh[0]))
def test_extract_label_time_course(): """Test extraction of label time courses from stc """ n_stcs = 3 n_times = 50 src = read_inverse_operator(fname_inv)['src'] vertices = [src[0]['vertno'], src[1]['vertno']] n_verts = len(vertices[0]) + len(vertices[1]) # get some labels labels_lh = read_labels_from_annot('sample', hemi='lh', subjects_dir=subjects_dir) labels_rh = read_labels_from_annot('sample', hemi='rh', subjects_dir=subjects_dir) labels = list() labels.extend(labels_lh[:5]) labels.extend(labels_rh[:4]) n_labels = len(labels) label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) label_maxs = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) # compute the mean with sign flip label_means_flipped = np.zeros_like(label_means) for i, label in enumerate(labels): label_means_flipped[i] = i * np.mean(label_sign_flip(label, src)) # generate some stc's with known data stcs = list() for i in range(n_stcs): data = np.zeros((n_verts, n_times)) # set the value of the stc within each label for j, label in enumerate(labels): if label.hemi == 'lh': idx = np.intersect1d(vertices[0], label.vertices) idx = np.searchsorted(vertices[0], idx) elif label.hemi == 'rh': idx = np.intersect1d(vertices[1], label.vertices) idx = len(vertices[0]) + np.searchsorted(vertices[1], idx) data[idx] = label_means[j] this_stc = SourceEstimate(data, vertices, 0, 1) stcs.append(this_stc) # test some invalid inputs assert_raises(ValueError, extract_label_time_course, stcs, labels, src, mode='notamode') # have an empty label empty_label = labels[0].copy() empty_label.vertices += 1000000 assert_raises(ValueError, extract_label_time_course, stcs, empty_label, src, mode='mean') # but this works: tc = extract_label_time_course(stcs, empty_label, src, mode='mean', allow_empty=True) for arr in tc: assert_true(arr.shape == (1, n_times)) assert_array_equal(arr, np.zeros((1, n_times))) # test the different modes modes = ['mean', 'mean_flip', 'pca_flip', 'max'] for mode in modes: label_tc = extract_label_time_course(stcs, labels, src, mode=mode) label_tc_method = [ stc.extract_label_time_course(labels, src, mode=mode) for stc in stcs ] assert_true(len(label_tc) == n_stcs) assert_true(len(label_tc_method) == n_stcs) for tc1, tc2 in zip(label_tc, label_tc_method): assert_true(tc1.shape == (n_labels, n_times)) assert_true(tc2.shape == (n_labels, n_times)) assert_true(np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16)) if mode == 'mean': assert_array_almost_equal(tc1, label_means) if mode == 'mean_flip': assert_array_almost_equal(tc1, label_means_flipped) if mode == 'max': assert_array_almost_equal(tc1, label_maxs) # test label with very few vertices (check SVD conditionals) label = Label(vertices=src[0]['vertno'][:2], hemi='lh') x = label_sign_flip(label, src) assert_true(len(x) == 2) label = Label(vertices=[], hemi='lh') x = label_sign_flip(label, src) assert_true(x.size == 0)
def test_extract_label_time_course(kind, vector): """Test extraction of label time courses from (Mixed)SourceEstimate.""" n_stcs = 3 n_times = 50 src = read_inverse_operator(fname_inv)['src'] if kind == 'mixed': label_names = ('Left-Cerebellum-Cortex', 'Right-Cerebellum-Cortex') src += setup_volume_source_space('sample', pos=20., volume_label=label_names, subjects_dir=subjects_dir, add_interpolator=False) klass = MixedVectorSourceEstimate else: klass = VectorSourceEstimate if not vector: klass = klass._scalar_class vertices = [s['vertno'] for s in src] n_verts = np.array([len(v) for v in vertices]) vol_means = np.arange(-1, 1 - len(src), -1) vol_means_t = np.repeat(vol_means[:, np.newaxis], n_times, axis=1) # get some labels labels_lh = read_labels_from_annot('sample', hemi='lh', subjects_dir=subjects_dir) labels_rh = read_labels_from_annot('sample', hemi='rh', subjects_dir=subjects_dir) labels = list() labels.extend(labels_lh[:5]) labels.extend(labels_rh[:4]) n_labels = len(labels) label_tcs = dict(mean=np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))) label_tcs['max'] = label_tcs['mean'] # compute the mean with sign flip label_tcs['mean_flip'] = np.zeros_like(label_tcs['mean']) for i, label in enumerate(labels): label_tcs['mean_flip'][i] = i * np.mean(label_sign_flip( label, src[:2])) # generate some stc's with known data stcs = list() pad = (((0, 0), (2, 0), (0, 0)), 'constant') for i in range(n_stcs): data = np.zeros((n_verts.sum(), n_times)) # set the value of the stc within each label for j, label in enumerate(labels): if label.hemi == 'lh': idx = np.intersect1d(vertices[0], label.vertices) idx = np.searchsorted(vertices[0], idx) elif label.hemi == 'rh': idx = np.intersect1d(vertices[1], label.vertices) idx = len(vertices[0]) + np.searchsorted(vertices[1], idx) data[idx] = label_tcs['mean'][j] for j in range(len(vol_means)): offset = n_verts[:2 + j].sum() data[offset:offset + n_verts[j]] = vol_means[j] if vector: # the values it on the Z axis data = np.pad(data[:, np.newaxis], *pad) this_stc = klass(data, vertices, 0, 1) stcs.append(this_stc) if vector: for key in label_tcs: label_tcs[key] = np.pad(label_tcs[key][:, np.newaxis], *pad) vol_means_t = np.pad(vol_means_t[:, np.newaxis], *pad) # test some invalid inputs with pytest.raises(ValueError, match="Invalid value for the 'mode'"): extract_label_time_course(stcs, labels, src, mode='notamode') # have an empty label empty_label = labels[0].copy() empty_label.vertices += 1000000 with pytest.raises(ValueError, match='does not contain any vertices'): extract_label_time_course(stcs, empty_label, src) # but this works: with pytest.warns(RuntimeWarning, match='does not contain any vertices'): tc = extract_label_time_course(stcs, empty_label, src, allow_empty=True) end_shape = (3, n_times) if vector else (n_times, ) for arr in tc: assert arr.shape == (1 + len(vol_means), ) + end_shape assert_array_equal(arr[:1], np.zeros((1, ) + end_shape)) if len(vol_means): assert_array_equal(arr[1:], vol_means_t) # test the different modes modes = ['mean', 'mean_flip', 'pca_flip', 'max', 'auto'] for mode in modes: if vector and mode not in ('mean', 'max', 'auto'): with pytest.raises(ValueError, match='when using a vector'): extract_label_time_course(stcs, labels, src, mode=mode) continue label_tc = extract_label_time_course(stcs, labels, src, mode=mode) label_tc_method = [ stc.extract_label_time_course(labels, src, mode=mode) for stc in stcs ] assert (len(label_tc) == n_stcs) assert (len(label_tc_method) == n_stcs) for tc1, tc2 in zip(label_tc, label_tc_method): assert tc1.shape == (n_labels + len(vol_means), ) + end_shape assert tc2.shape == (n_labels + len(vol_means), ) + end_shape assert_allclose(tc1, tc2, rtol=1e-8, atol=1e-16) if mode == 'auto': use_mode = 'mean' if vector else 'mean_flip' else: use_mode = mode # XXX we don't check pca_flip, probably should someday... if use_mode in ('mean', 'max', 'mean_flip'): assert_array_almost_equal(tc1[:n_labels], label_tcs[use_mode]) assert_array_almost_equal(tc1[n_labels:], vol_means_t) # test label with very few vertices (check SVD conditionals) label = Label(vertices=src[0]['vertno'][:2], hemi='lh') x = label_sign_flip(label, src[:2]) assert (len(x) == 2) label = Label(vertices=[], hemi='lh') x = label_sign_flip(label, src[:2]) assert (x.size == 0)
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) event_id = 1 event_overlap = 8 event_length = 30 spacing = 'ico5' lf, hf = 14., 30. #def process_maxfilter(subject): raw_fname = op.join(data_path, 'rest', 'sub-' + subject, 'meg', 'rest_raw.fif') raw = mne.io.read_raw_fif(raw_fname, preload=True) raw_length = (raw.last_samp - raw.first_samp) / raw.info['sfreq'] raw.info['bads'] += [u'MEG2113', u'MEG1941', u'MEG1412', u'MEG2331'] raw = mne.preprocessing.maxwell_filter(raw,
# label_name = 'frontalpole' # label_name = 'V4' label_name = 'V1_V2' # label_name = 'AC' # labels, label_colors = mne.labels_from_parc('fsaverage', # parc='aparc', # subjects_dir=subjects_dir) postfix = "_%s" % label_name fname_inv = data_path + '/trans_sss_filt-2-45_ds8_meg-oct-6-inv.fif' inverse_operator = read_inverse_operator(fname_inv) if label_name == 'frontalpole': labels = read_labels_from_annot(subject, parc='aparc.split' '-small', hemi='both', subjects_dir=subjects_dir, regexp=label_name) label = labels[0] + labels[1] else: rh_label = mne.read_label(data_path + '/individual/' '%s-rh.label' % label_name) # label = rh_label lh_label = mne.read_label(data_path + '/individual/' '%s-lh.label' % label_name) label = lh_label + rh_label label_names = [] for label_name in label_names: rh_label = mne.read_label(data_path + '/individual/' '%s-rh.label' % label_name)
def test_extract_label_time_course(): """Test extraction of label time courses from stc """ n_stcs = 3 n_times = 50 src = read_inverse_operator(fname_inv)['src'] vertices = [src[0]['vertno'], src[1]['vertno']] n_verts = len(vertices[0]) + len(vertices[1]) # get some labels labels_lh = read_labels_from_annot('sample', hemi='lh', subjects_dir=subjects_dir) labels_rh = read_labels_from_annot('sample', hemi='rh', subjects_dir=subjects_dir) labels = list() labels.extend(labels_lh[:5]) labels.extend(labels_rh[:4]) n_labels = len(labels) label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) label_maxs = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) # compute the mean with sign flip label_means_flipped = np.zeros_like(label_means) for i, label in enumerate(labels): label_means_flipped[i] = i * np.mean(label_sign_flip(label, src)) # generate some stc's with known data stcs = list() for i in range(n_stcs): data = np.zeros((n_verts, n_times)) # set the value of the stc within each label for j, label in enumerate(labels): if label.hemi == 'lh': idx = np.intersect1d(vertices[0], label.vertices) idx = np.searchsorted(vertices[0], idx) elif label.hemi == 'rh': idx = np.intersect1d(vertices[1], label.vertices) idx = len(vertices[0]) + np.searchsorted(vertices[1], idx) data[idx] = label_means[j] this_stc = SourceEstimate(data, vertices, 0, 1) stcs.append(this_stc) # test some invalid inputs assert_raises(ValueError, extract_label_time_course, stcs, labels, src, mode='notamode') # have an empty label empty_label = labels[0].copy() empty_label.vertices += 1000000 assert_raises(ValueError, extract_label_time_course, stcs, empty_label, src, mode='mean') # but this works: with warnings.catch_warnings(record=True): # empty label tc = extract_label_time_course(stcs, empty_label, src, mode='mean', allow_empty=True) for arr in tc: assert_true(arr.shape == (1, n_times)) assert_array_equal(arr, np.zeros((1, n_times))) # test the different modes modes = ['mean', 'mean_flip', 'pca_flip', 'max'] for mode in modes: label_tc = extract_label_time_course(stcs, labels, src, mode=mode) label_tc_method = [stc.extract_label_time_course(labels, src, mode=mode) for stc in stcs] assert_true(len(label_tc) == n_stcs) assert_true(len(label_tc_method) == n_stcs) for tc1, tc2 in zip(label_tc, label_tc_method): assert_true(tc1.shape == (n_labels, n_times)) assert_true(tc2.shape == (n_labels, n_times)) assert_true(np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16)) if mode == 'mean': assert_array_almost_equal(tc1, label_means) if mode == 'mean_flip': assert_array_almost_equal(tc1, label_means_flipped) if mode == 'max': assert_array_almost_equal(tc1, label_maxs) # test label with very few vertices (check SVD conditionals) label = Label(vertices=src[0]['vertno'][:2], hemi='lh') x = label_sign_flip(label, src) assert_true(len(x) == 2) label = Label(vertices=[], hemi='lh') x = label_sign_flip(label, src) assert_true(x.size == 0)