def test_add_patch_info(): """Test adding patch info to source space.""" # let's setup a small source space src = read_source_spaces(fname_small) src_new = read_source_spaces(fname_small) for s in src_new: s['nearest'] = None s['nearest_dist'] = None s['pinfo'] = None # test that no patch info is added for small dist_limit try: add_source_space_distances(src_new, dist_limit=0.00001) except RuntimeError: # what we throw when scipy version is wrong pass else: assert all(s['nearest'] is None for s in src_new) assert all(s['nearest_dist'] is None for s in src_new) assert all(s['pinfo'] is None for s in src_new) # now let's use one that works add_source_space_distances(src_new) for s1, s2 in zip(src, src_new): assert_array_equal(s1['nearest'], s2['nearest']) assert_allclose(s1['nearest_dist'], s2['nearest_dist'], atol=1e-7) assert_equal(len(s1['pinfo']), len(s2['pinfo'])) for p1, p2 in zip(s1['pinfo'], s2['pinfo']): assert_array_equal(p1, p2)
def test_add_patch_info(): """Test adding patch info to source space""" # let's setup a small source space src = read_source_spaces(fname_small) src_new = read_source_spaces(fname_small) for s in src_new: s['nearest'] = None s['nearest_dist'] = None s['pinfo'] = None # test that no patch info is added for small dist_limit try: add_source_space_distances(src_new, dist_limit=0.00001) except RuntimeError: # what we throw when scipy version is wrong pass else: assert_true(all(s['nearest'] is None for s in src_new)) assert_true(all(s['nearest_dist'] is None for s in src_new)) assert_true(all(s['pinfo'] is None for s in src_new)) # now let's use one that works add_source_space_distances(src_new) for s1, s2 in zip(src, src_new): assert_array_equal(s1['nearest'], s2['nearest']) assert_allclose(s1['nearest_dist'], s2['nearest_dist'], atol=1e-7) assert_equal(len(s1['pinfo']), len(s2['pinfo'])) for p1, p2 in zip(s1['pinfo'], s2['pinfo']): assert_array_equal(p1, p2)
def test_crop(): """Test cropping raw files """ # split a concatenated file to test a difficult case raw = Raw([fif_fname, fif_fname], preload=False) split_size = 10. # in seconds sfreq = raw.info['sfreq'] nsamp = (raw.last_samp - raw.first_samp + 1) # do an annoying case (off-by-one splitting) tmins = np.r_[1., np.round(np.arange(0., nsamp - 1, split_size * sfreq))] tmins = np.sort(tmins) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.crop(tmin, tmax, True) all_raw_2 = concatenate_raws(raws, preload=False) assert_equal(raw.first_samp, all_raw_2.first_samp) assert_equal(raw.last_samp, all_raw_2.last_samp) assert_array_equal(raw[:, :][0], all_raw_2[:, :][0]) tmins = np.round(np.arange(0., nsamp - 1, split_size * sfreq)) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq # going in revere order so the last fname is the first file (need it later) raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.copy() raws[ri].crop(tmin, tmax, False) # test concatenation of split file all_raw_1 = concatenate_raws(raws, preload=False) all_raw_2 = raw.crop(0, None, True) for ar in [all_raw_1, all_raw_2]: assert_equal(raw.first_samp, ar.first_samp) assert_equal(raw.last_samp, ar.last_samp) assert_array_equal(raw[:, :][0], ar[:, :][0]) # test shape consistency of cropped raw data = np.zeros((1, 1002001)) info = create_info(1, 1000) raw = RawArray(data, info) for tmin in range(0, 1001, 100): raw1 = raw.crop(tmin=tmin, tmax=tmin + 2, copy=True) assert_equal(raw1[:][0].shape, (1, 2001))
def test_crop(): """Test cropping raw files """ # split a concatenated file to test a difficult case raw = Raw([fif_fname, fif_fname], preload=False) split_size = 10. # in seconds sfreq = raw.info['sfreq'] nsamp = (raw.last_samp - raw.first_samp + 1) # do an annoying case (off-by-one splitting) tmins = np.r_[1., np.round(np.arange(0., nsamp - 1, split_size * sfreq))] tmins = np.sort(tmins) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.crop(tmin, tmax, True) all_raw_2 = concatenate_raws(raws, preload=False) assert_equal(raw.first_samp, all_raw_2.first_samp) assert_equal(raw.last_samp, all_raw_2.last_samp) assert_array_equal(raw[:, :][0], all_raw_2[:, :][0]) tmins = np.round(np.arange(0., nsamp - 1, split_size * sfreq)) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq # going in revere order so the last fname is the first file (need it later) raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.copy() raws[ri].crop(tmin, tmax, False) # test concatenation of split file all_raw_1 = concatenate_raws(raws, preload=False) all_raw_2 = raw.crop(0, None, True) for ar in [all_raw_1, all_raw_2]: assert_equal(raw.first_samp, ar.first_samp) assert_equal(raw.last_samp, ar.last_samp) assert_array_equal(raw[:, :][0], ar[:, :][0]) # test shape consistency of cropped raw data = np.zeros((1, 1002001)) info = create_info(1, 1000) raw = RawArray(data, info) for tmin in range(0, 1001, 100): raw1 = raw.crop(tmin=tmin, tmax=tmin + 2, copy=True) assert_equal(raw1[:][0].shape, (1, 2001))
def test_drop_epochs_mult(): """Test that subselecting epochs or making less epochs is equivalent""" for preload in [True, False]: epochs1 = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks, reject=reject, preload=preload)['a'] epochs2 = Epochs(raw, events, {'a': 1}, tmin, tmax, picks=picks, reject=reject, preload=preload) if preload: # In the preload case you cannot know the bads if already ignored assert_equal(len(epochs1.drop_log), len(epochs2.drop_log)) for d1, d2 in zip(epochs1.drop_log, epochs2.drop_log): if d1 == ['IGNORED']: assert_true(d2 == ['IGNORED']) if d1 != ['IGNORED'] and d1 != []: assert_true((d2 == d1) or (d2 == ['IGNORED'])) if d1 == []: assert_true(d2 == []) assert_array_equal(epochs1.events, epochs2.events) assert_array_equal(epochs1.selection, epochs2.selection) else: # In the non preload is should be exactly the same assert_equal(epochs1.drop_log, epochs2.drop_log) assert_array_equal(epochs1.events, epochs2.events) assert_array_equal(epochs1.selection, epochs2.selection)
def test_add_source_space_distances_limited(): """Test adding distances to source space with a dist_limit.""" tempdir = _TempDir() src = read_source_spaces(fname) src_new = read_source_spaces(fname) del src_new[0]['dist'] del src_new[1]['dist'] n_do = 200 # limit this for speed src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy() src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy() out_name = op.join(tempdir, 'temp-src.fif') try: add_source_space_distances(src_new, dist_limit=0.007) except RuntimeError: # what we throw when scipy version is wrong raise SkipTest('dist_limit requires scipy > 0.13') write_source_spaces(out_name, src_new) src_new = read_source_spaces(out_name) for so, sn in zip(src, src_new): assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32)) assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32)) do = so['dist'] dn = sn['dist'] # clean out distances > 0.007 in C code do.data[do.data > 0.007] = 0 do.eliminate_zeros() # make sure we have some comparable distances assert np.sum(do.data < 0.007) > 400 # do comparison over the region computed d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]] assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname).crop(0, 1, False) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand'] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info['subject_info'] = subject_info out_fname = op.join(tempdir, 'test_subj_info_raw.fif') raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info['subject_info'][key]) assert_equal(raw.info['meas_date'], raw_read.info['meas_date']) raw.anonymize() raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for this_raw in (raw, raw_read): assert_true(this_raw.info.get('subject_info') is None) assert_equal(this_raw.info['meas_date'], [0, 0]) assert_equal(raw.info['file_id']['secs'], 0) assert_equal(raw.info['meas_id']['secs'], 0) # When we write out with raw.save, these get overwritten with the # new save time assert_true(raw_read.info['file_id']['secs'] > 0) assert_true(raw_read.info['meas_id']['secs'] > 0)
def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname).crop(0, 1, False) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand'] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info['subject_info'] = subject_info out_fname = op.join(tempdir, 'test_subj_info_raw.fif') raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info['subject_info'][key]) raw_read.anonymize() assert_true(raw_read.info.get('subject_info') is None) out_fname_anon = op.join(tempdir, 'test_subj_info_anon_raw.fif') raw_read.save(out_fname_anon, overwrite=True) raw_read = Raw(out_fname_anon) assert_true(raw_read.info.get('subject_info') is None)
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] io.write_evokeds(op.join(tempdir, 'evoked.fif'), evoked) evoked2 = read_evokeds(op.join(tempdir, 'evoked.fif'), [0, 1]) evoked3 = [read_evokeds(op.join(tempdir, 'evoked.fif'), 'Unknown'), read_evokeds(op.join(tempdir, 'evoked.fif'), 'Unknown', kind='standard_error')] for evoked_new in [evoked2, evoked3]: assert_true(evoked_new[0]._aspect_kind == FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked_new[0].kind == 'average') assert_true(evoked_new[1]._aspect_kind == FIFF.FIFFV_ASPECT_STD_ERR) assert_true(evoked_new[1].kind == 'standard_error') for ave, ave2 in zip(evoked, evoked_new): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname).crop(0, 1, copy=False) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = [ 'id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand' ] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info['subject_info'] = subject_info out_fname = op.join(tempdir, 'test_subj_info_raw.fif') raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info['subject_info'][key]) assert_equal(raw.info['meas_date'], raw_read.info['meas_date']) raw.anonymize() raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for this_raw in (raw, raw_read): assert_true(this_raw.info.get('subject_info') is None) assert_equal(this_raw.info['meas_date'], [0, 0]) assert_equal(raw.info['file_id']['secs'], 0) assert_equal(raw.info['meas_id']['secs'], 0) # When we write out with raw.save, these get overwritten with the # new save time assert_true(raw_read.info['file_id']['secs'] > 0) assert_true(raw_read.info['meas_id']['secs'] > 0)
def test_volume_source_space(): """Test setting up volume source spaces """ tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises( IOError, setup_volume_source_space, 'sample', temp_name, pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert_equal(repr(src), repr(src_new)) assert_equal(src.kind, 'volume')
def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname) raw.crop(0, 1, False) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand'] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info['subject_info'] = subject_info out_fname = op.join(tempdir, 'test_subj_info_raw.fif') raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info['subject_info'][key]) raw_read.anonymize() assert_true(raw_read.info.get('subject_info') is None) out_fname_anon = op.join(tempdir, 'test_subj_info_anon_raw.fif') raw_read.save(out_fname_anon, overwrite=True) raw_read = Raw(out_fname_anon) assert_true(raw_read.info.get('subject_info') is None)
def test_add_source_space_distances_limited(): """Test adding distances to source space with a dist_limit""" tempdir = _TempDir() src = read_source_spaces(fname) src_new = read_source_spaces(fname) del src_new[0]['dist'] del src_new[1]['dist'] n_do = 200 # limit this for speed src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy() src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy() out_name = op.join(tempdir, 'temp-src.fif') try: add_source_space_distances(src_new, dist_limit=0.007) except RuntimeError: # what we throw when scipy version is wrong raise SkipTest('dist_limit requires scipy > 0.13') write_source_spaces(out_name, src_new) src_new = read_source_spaces(out_name) for so, sn in zip(src, src_new): assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32)) assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32)) do = so['dist'] dn = sn['dist'] # clean out distances > 0.007 in C code do.data[do.data > 0.007] = 0 do.eliminate_zeros() # make sure we have some comparable distances assert_true(np.sum(do.data < 0.007) > 400) # do comparison over the region computed d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]] assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
def test_volume_source_space(): """Test setting up volume source spaces.""" tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space( 'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') pytest.raises(IOError, setup_volume_source_space, 'sample', pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert repr(src) == repr(src_new) assert src.kind == 'volume' # Spheres sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1, relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0)) src = setup_volume_source_space(pos=10) src_new = setup_volume_source_space(pos=10, sphere=sphere) _compare_source_spaces(src, src_new, mode='exact') pytest.raises(ValueError, setup_volume_source_space, sphere='foo') # Need a radius sphere = make_sphere_model(head_radius=None) pytest.raises(ValueError, setup_volume_source_space, sphere=sphere)
def test_volume_source_space(): """Test setting up volume source spaces.""" tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space( 'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') pytest.raises(IOError, setup_volume_source_space, 'sample', pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert repr(src) == repr(src_new) assert src.kind == 'volume' # Spheres sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1, relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0)) src = setup_volume_source_space(pos=10) src_new = setup_volume_source_space(pos=10, sphere=sphere) _compare_source_spaces(src, src_new, mode='exact') pytest.raises(ValueError, setup_volume_source_space, sphere='foo') # Need a radius sphere = make_sphere_model(head_radius=None) pytest.raises(ValueError, setup_volume_source_space, sphere=sphere)
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] fiff.write_evoked(op.join(tempdir, 'evoked.fif'), evoked) evoked2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1]) evoked3 = [ read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown'), read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown', kind='standard_error') ] for evoked_new in [evoked2, evoked3]: assert_true( evoked_new[0]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked_new[0].kind == 'average') assert_true( evoked_new[1]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR) assert_true(evoked_new[1].kind == 'standard_error') for ave, ave2 in zip(evoked, evoked_new): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_make_field_map_meeg(): """Test making a M/EEG field map onto helmet & head.""" evoked = read_evokeds(evoked_fname, baseline=(-0.2, 0.0))[0] picks = pick_types(evoked.info, meg=True, eeg=True) picks = picks[::10] evoked.pick_channels([evoked.ch_names[p] for p in picks]) evoked.info.normalize_proj() maps = make_field_map(evoked, trans_fname, subject='sample', subjects_dir=subjects_dir, n_jobs=1, verbose='debug') assert_equal(maps[0]['data'].shape, (642, 6)) # EEG->Head assert_equal(maps[1]['data'].shape, (304, 31)) # MEG->Helmet # reasonable ranges maxs = (1.2, 2.0) # before #4418, was (1.1, 2.0) mins = (-0.8, -1.3) # before #4418, was (-0.6, -1.2) assert_equal(len(maxs), len(maps)) for map_, max_, min_ in zip(maps, maxs, mins): assert_allclose(map_['data'].max(), max_, rtol=5e-2) assert_allclose(map_['data'].min(), min_, rtol=5e-2) # calculated from correct looking mapping on 2015/12/26 assert_allclose( np.sqrt(np.sum(maps[0]['data']**2)), 19.0903, # 16.6088, atol=1e-3, rtol=1e-3) assert_allclose( np.sqrt(np.sum(maps[1]['data']**2)), 19.4748, # 20.1245, atol=1e-3, rtol=1e-3)
def test_drop_epochs_mult(): """Test that subselecting epochs or making less epochs is equivalent""" for preload in [True, False]: epochs1 = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks, reject=reject, preload=preload)['a'] epochs2 = Epochs(raw, events, {'a': 1}, tmin, tmax, picks=picks, reject=reject, preload=preload) if preload: # In the preload case you cannot know the bads if already ignored assert_equal(len(epochs1.drop_log), len(epochs2.drop_log)) for d1, d2 in zip(epochs1.drop_log, epochs2.drop_log): if d1 == ['IGNORED']: assert_true(d2 == ['IGNORED']) if d1 != ['IGNORED'] and d1 != []: assert_true((d2 == d1) or (d2 == ['IGNORED'])) if d1 == []: assert_true(d2 == []) assert_array_equal(epochs1.events, epochs2.events) assert_array_equal(epochs1.selection, epochs2.selection) else: # In the non preload is should be exactly the same assert_equal(epochs1.drop_log, epochs2.drop_log) assert_array_equal(epochs1.events, epochs2.events) assert_array_equal(epochs1.selection, epochs2.selection)
def test_morphed_source_space_return(): """Test returning a morphed source space to the original subject""" # let's create some random data on fsaverage data = rng.randn(20484, 1) tmin, tstep = 0, 1. src_fs = read_source_spaces(fname_fs) stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage') # Create our morph source space src_morph = morph_source_spaces(src_fs, 'sample', subjects_dir=subjects_dir) # Morph the data over using standard methods stc_morph = stc_fs.morph('sample', [s['vertno'] for s in src_morph], smooth=1, subjects_dir=subjects_dir) # We can now pretend like this was real data we got e.g. from an inverse. # To be complete, let's remove some vertices keeps = [np.sort(rng.permutation(np.arange(len(v)))[:len(v) - 10]) for v in stc_morph.vertices] stc_morph = SourceEstimate( np.concatenate([stc_morph.lh_data[keeps[0]], stc_morph.rh_data[keeps[1]]]), [v[k] for v, k in zip(stc_morph.vertices, keeps)], tmin, tstep, 'sample') # Return it to the original subject stc_morph_return = stc_morph.to_original_src( src_fs, subjects_dir=subjects_dir) # Compare to the original data stc_morph_morph = stc_morph.morph('fsaverage', stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir) assert_equal(stc_morph_return.subject, stc_morph_morph.subject) for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert_true(corr > 0.99, corr) # Degenerate cases stc_morph.subject = None # no .subject provided assert_raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='fsaverage', subjects_dir=subjects_dir) stc_morph.subject = 'sample' del src_fs[0]['subject_his_id'] # no name in src_fsaverage assert_raises(ValueError, stc_morph.to_original_src, src_fs, subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'fsaverage' # name mismatch assert_raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='foo', subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'sample' src = read_source_spaces(fname) # wrong source space assert_raises(RuntimeError, stc_morph.to_original_src, src, subjects_dir=subjects_dir)
def test_morphed_source_space_return(): """Test returning a morphed source space to the original subject""" # let's create some random data on fsaverage data = rng.randn(20484, 1) tmin, tstep = 0, 1. src_fs = read_source_spaces(fname_fs) stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage') # Create our morph source space src_morph = morph_source_spaces(src_fs, 'sample', subjects_dir=subjects_dir) # Morph the data over using standard methods stc_morph = stc_fs.morph('sample', [s['vertno'] for s in src_morph], smooth=1, subjects_dir=subjects_dir) # We can now pretend like this was real data we got e.g. from an inverse. # To be complete, let's remove some vertices keeps = [np.sort(rng.permutation(np.arange(len(v)))[:len(v) - 10]) for v in stc_morph.vertices] stc_morph = SourceEstimate( np.concatenate([stc_morph.lh_data[keeps[0]], stc_morph.rh_data[keeps[1]]]), [v[k] for v, k in zip(stc_morph.vertices, keeps)], tmin, tstep, 'sample') # Return it to the original subject stc_morph_return = stc_morph.to_original_src( src_fs, subjects_dir=subjects_dir) # Compare to the original data stc_morph_morph = stc_morph.morph('fsaverage', stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir) assert_equal(stc_morph_return.subject, stc_morph_morph.subject) for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert_true(corr > 0.99, corr) # Degenerate cases stc_morph.subject = None # no .subject provided assert_raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='fsaverage', subjects_dir=subjects_dir) stc_morph.subject = 'sample' del src_fs[0]['subject_his_id'] # no name in src_fsaverage assert_raises(ValueError, stc_morph.to_original_src, src_fs, subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'fsaverage' # name mismatch assert_raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='foo', subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'sample' src = read_source_spaces(fname) # wrong source space assert_raises(RuntimeError, stc_morph.to_original_src, src, subjects_dir=subjects_dir)
def test_crop(): """Test cropping raw files """ # split a concatenated file to test a difficult case raw = Raw([fif_fname, fif_fname], preload=False) split_size = 10.0 # in seconds sfreq = raw.info["sfreq"] nsamp = raw.last_samp - raw.first_samp + 1 # do an annoying case (off-by-one splitting) tmins = np.r_[1.0, np.round(np.arange(0.0, nsamp - 1, split_size * sfreq))] tmins = np.sort(tmins) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.crop(tmin, tmax, True) all_raw_2 = concatenate_raws(raws, preload=False) assert_equal(raw.first_samp, all_raw_2.first_samp) assert_equal(raw.last_samp, all_raw_2.last_samp) assert_array_equal(raw[:, :][0], all_raw_2[:, :][0]) tmins = np.round(np.arange(0.0, nsamp - 1, split_size * sfreq)) tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1])) tmaxs /= sfreq tmins /= sfreq # going in revere order so the last fname is the first file (need it later) raws = [None] * len(tmins) for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)): raws[ri] = raw.copy() raws[ri].crop(tmin, tmax, False) # test concatenation of split file all_raw_1 = concatenate_raws(raws, preload=False) all_raw_2 = raw.crop(0, None, True) for ar in [all_raw_1, all_raw_2]: assert_equal(raw.first_samp, ar.first_samp) assert_equal(raw.last_samp, ar.last_samp) assert_array_equal(raw[:, :][0], ar[:, :][0])
def test_legendre_val(): """Test Legendre polynomial (derivative) equivalence.""" rng = np.random.RandomState(0) # check table equiv xs = np.linspace(-1., 1., 1000) n_terms = 100 # True, numpy vals_np = legendre.legvander(xs, n_terms - 1) # Table approximation for nc, interp in zip([100, 50], ['nearest', 'linear']): lut, n_fact = _get_legen_table('eeg', n_coeff=nc, force_calc=True) lut_fun = interp1d(np.linspace(-1, 1, lut.shape[0]), lut, interp, axis=0) vals_i = lut_fun(xs) # Need a "1:" here because we omit the first coefficient in our table! assert_allclose(vals_np[:, 1:vals_i.shape[1] + 1], vals_i, rtol=1e-2, atol=5e-3) # Now let's look at our sums ctheta = rng.rand(20, 30) * 2.0 - 1.0 beta = rng.rand(20, 30) * 0.8 c1 = _comp_sum_eeg(beta.flatten(), ctheta.flatten(), lut_fun, n_fact) c1.shape = beta.shape # compare to numpy n = np.arange(1, n_terms, dtype=float)[:, np.newaxis, np.newaxis] coeffs = np.zeros((n_terms, ) + beta.shape) coeffs[1:] = (np.cumprod([beta] * (n_terms - 1), axis=0) * (2.0 * n + 1.0) * (2.0 * n + 1.0) / n) # can't use tensor=False here b/c it isn't in old numpy c2 = np.empty((20, 30)) for ci1 in range(20): for ci2 in range(30): c2[ci1, ci2] = legendre.legval(ctheta[ci1, ci2], coeffs[:, ci1, ci2]) assert_allclose(c1, c2, 1e-2, 1e-3) # close enough... # compare fast and slow for MEG ctheta = rng.rand(20 * 30) * 2.0 - 1.0 beta = rng.rand(20 * 30) * 0.8 lut, n_fact = _get_legen_table('meg', n_coeff=10, force_calc=True) fun = interp1d(np.linspace(-1, 1, lut.shape[0]), lut, 'nearest', axis=0) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False) lut, n_fact = _get_legen_table('meg', n_coeff=20, force_calc=True) fun = interp1d(np.linspace(-1, 1, lut.shape[0]), lut, 'linear', axis=0) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False)
def test_triangle_neighbors(): """Test efficient vertex neighboring triangles for surfaces""" this = read_source_spaces(fname)[0] this["neighbor_tri"] = [list() for _ in range(this["np"])] for p in range(this["ntri"]): verts = this["tris"][p] this["neighbor_tri"][verts[0]].append(p) this["neighbor_tri"][verts[1]].append(p) this["neighbor_tri"][verts[2]].append(p) this["neighbor_tri"] = [np.array(nb, int) for nb in this["neighbor_tri"]] neighbor_tri = _triangle_neighbors(this["tris"], this["np"]) assert_true(np.array_equal(nt1, nt2) for nt1, nt2 in zip(neighbor_tri, this["neighbor_tri"]))
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates """ # obtained using "tksurfer (sample/fsaverage) (l/r)h white" vertices = [100960, 7620, 150549, 96761] coords_s = np.array([[-60.86, -11.18, -3.19], [-36.46, -93.18, -2.36], [-38.00, 50.08, -10.61], [47.14, 8.01, 46.93]]) coords_f = np.array([[-41.28, -40.04, 18.20], [-6.05, 49.74, -18.15], [-61.71, -14.55, 20.52], [21.70, -60.84, 25.02]]) hemis = [0, 0, 0, 1] for coords, subject in zip([coords_s, coords_f], ['sample', 'fsaverage']): coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir) # less than 1mm error assert_allclose(coords, coords_2, atol=1.0)
def test_triangle_neighbors(): """Test efficient vertex neighboring triangles for surfaces.""" this = read_source_spaces(fname)[0] this['neighbor_tri'] = [list() for _ in range(this['np'])] for p in range(this['ntri']): verts = this['tris'][p] this['neighbor_tri'][verts[0]].append(p) this['neighbor_tri'][verts[1]].append(p) this['neighbor_tri'][verts[2]].append(p) this['neighbor_tri'] = [np.array(nb, int) for nb in this['neighbor_tri']] neighbor_tri = _triangle_neighbors(this['tris'], this['np']) assert all(np.array_equal(nt1, nt2) for nt1, nt2 in zip(neighbor_tri, this['neighbor_tri']))
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates """ # obtained using "tksurfer (sample/fsaverage) (l/r)h white" vertices = [100960, 7620, 150549, 96761] coords_s = np.array([[-60.86, -11.18, -3.19], [-36.46, -93.18, -2.36], [-38.00, 50.08, -10.61], [47.14, 8.01, 46.93]]) coords_f = np.array([[-41.28, -40.04, 18.20], [-6.05, 49.74, -18.15], [-61.71, -14.55, 20.52], [21.70, -60.84, 25.02]]) hemis = [0, 0, 0, 1] for coords, subject in zip([coords_s, coords_f], ['sample', 'fsaverage']): coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir) # less than 1mm error assert_allclose(coords, coords_2, atol=1.0)
def test_legendre_val(): """Test Legendre polynomial (derivative) equivalence """ rng = np.random.RandomState(0) # check table equiv xs = np.linspace(-1., 1., 1000) n_terms = 100 # True, numpy vals_np = legendre.legvander(xs, n_terms - 1) # Table approximation for fun, nc in zip([_get_legen_lut_fast, _get_legen_lut_accurate], [100, 50]): lut, n_fact = _get_legen_table('eeg', n_coeff=nc, force_calc=True) vals_i = fun(xs, lut) # Need a "1:" here because we omit the first coefficient in our table! assert_allclose(vals_np[:, 1:vals_i.shape[1] + 1], vals_i, rtol=1e-2, atol=5e-3) # Now let's look at our sums ctheta = rng.rand(20, 30) * 2.0 - 1.0 beta = rng.rand(20, 30) * 0.8 lut_fun = partial(fun, lut=lut) c1 = _comp_sum_eeg(beta.flatten(), ctheta.flatten(), lut_fun, n_fact) c1.shape = beta.shape # compare to numpy n = np.arange(1, n_terms, dtype=float)[:, np.newaxis, np.newaxis] coeffs = np.zeros((n_terms,) + beta.shape) coeffs[1:] = (np.cumprod([beta] * (n_terms - 1), axis=0) * (2.0 * n + 1.0) * (2.0 * n + 1.0) / n) # can't use tensor=False here b/c it isn't in old numpy c2 = np.empty((20, 30)) for ci1 in range(20): for ci2 in range(30): c2[ci1, ci2] = legendre.legval(ctheta[ci1, ci2], coeffs[:, ci1, ci2]) assert_allclose(c1, c2, 1e-2, 1e-3) # close enough... # compare fast and slow for MEG ctheta = rng.rand(20 * 30) * 2.0 - 1.0 beta = rng.rand(20 * 30) * 0.8 lut, n_fact = _get_legen_table('meg', n_coeff=10, force_calc=True) fun = partial(_get_legen_lut_fast, lut=lut) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False) lut, n_fact = _get_legen_table('meg', n_coeff=20, force_calc=True) fun = partial(_get_legen_lut_accurate, lut=lut) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False)
def test_output_formats(): """Test saving and loading raw data using multiple formats """ formats = ["short", "int", "single", "double"] tols = [1e-4, 1e-7, 1e-7, 1e-15] # let's fake a raw file with different formats raw = Raw(fif_fname, preload=True) raw.crop(0, 1, copy=False) temp_file = op.join(tempdir, "raw.fif") for ii, (format, tol) in enumerate(zip(formats, tols)): # Let's test the overwriting error throwing while we're at it if ii > 0: assert_raises(IOError, raw.save, temp_file, format=format) raw.save(temp_file, format=format, overwrite=True) raw2 = Raw(temp_file) raw2_data = raw2[:, :][0] assert_allclose(raw2_data, raw._data, rtol=tol, atol=1e-25) assert_true(raw2.orig_format == format)
def test_output_formats(): """Test saving and loading raw data using multiple formats """ tempdir = _TempDir() formats = ['short', 'int', 'single', 'double'] tols = [1e-4, 1e-7, 1e-7, 1e-15] # let's fake a raw file with different formats raw = Raw(test_fif_fname).crop(0, 1, copy=False) temp_file = op.join(tempdir, 'raw.fif') for ii, (fmt, tol) in enumerate(zip(formats, tols)): # Let's test the overwriting error throwing while we're at it if ii > 0: assert_raises(IOError, raw.save, temp_file, fmt=fmt) raw.save(temp_file, fmt=fmt, overwrite=True) raw2 = Raw(temp_file) raw2_data = raw2[:, :][0] assert_allclose(raw2_data, raw[:, :][0], rtol=tol, atol=1e-25) assert_equal(raw2.orig_format, fmt)
def test_output_formats(): """Test saving and loading raw data using multiple formats """ tempdir = _TempDir() formats = ['short', 'int', 'single', 'double'] tols = [1e-4, 1e-7, 1e-7, 1e-15] # let's fake a raw file with different formats raw = Raw(test_fif_fname).crop(0, 1, copy=False) temp_file = op.join(tempdir, 'raw.fif') for ii, (fmt, tol) in enumerate(zip(formats, tols)): # Let's test the overwriting error throwing while we're at it if ii > 0: assert_raises(IOError, raw.save, temp_file, fmt=fmt) raw.save(temp_file, fmt=fmt, overwrite=True) raw2 = Raw(temp_file) raw2_data = raw2[:, :][0] assert_allclose(raw2_data, raw[:, :][0], rtol=tol, atol=1e-25) assert_equal(raw2.orig_format, fmt)
def test_volume_source_space(): """Test setting up volume source spaces """ tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=bem, surface=surf, mri=fname_mri, subjects_dir=subjects_dir) _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises(IOError, setup_volume_source_space, 'sample', temp_name, pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir)
def test_add_source_space_distances(): """Test adding distances to source space.""" tempdir = _TempDir() src = read_source_spaces(fname) src_new = read_source_spaces(fname) del src_new[0]['dist'] del src_new[1]['dist'] n_do = 19 # limit this for speed src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy() src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy() out_name = op.join(tempdir, 'temp-src.fif') n_jobs = 2 assert n_do % n_jobs != 0 add_source_space_distances(src_new, n_jobs=n_jobs) write_source_spaces(out_name, src_new) src_new = read_source_spaces(out_name) # iterate over both hemispheres for so, sn in zip(src, src_new): v = so['vertno'][:n_do] assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32)) assert_array_equal(sn['dist_limit'], np.array([np.inf], np.float32)) do = so['dist'] dn = sn['dist'] # clean out distances > 0.007 in C code (some residual), and Python ds = list() for d in [do, dn]: d.data[d.data > 0.007] = 0 d = d[v][:, v] d.eliminate_zeros() ds.append(d) # make sure we actually calculated some comparable distances assert np.sum(ds[0].data < 0.007) > 10 # do comparison d = ds[0] - ds[1] assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-9)
def test_add_source_space_distances(): """Test adding distances to source space""" tempdir = _TempDir() src = read_source_spaces(fname) src_new = read_source_spaces(fname) del src_new[0]['dist'] del src_new[1]['dist'] n_do = 19 # limit this for speed src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy() src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy() out_name = op.join(tempdir, 'temp-src.fif') n_jobs = 2 assert_true(n_do % n_jobs != 0) add_source_space_distances(src_new, n_jobs=n_jobs) write_source_spaces(out_name, src_new) src_new = read_source_spaces(out_name) # iterate over both hemispheres for so, sn in zip(src, src_new): v = so['vertno'][:n_do] assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32)) assert_array_equal(sn['dist_limit'], np.array([np.inf], np.float32)) do = so['dist'] dn = sn['dist'] # clean out distances > 0.007 in C code (some residual), and Python ds = list() for d in [do, dn]: d.data[d.data > 0.007] = 0 d = d[v][:, v] d.eliminate_zeros() ds.append(d) # make sure we actually calculated some comparable distances assert_true(np.sum(ds[0].data < 0.007) > 10) # do comparison d = ds[0] - ds[1] assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-9)
def test_volume_source_space(): """Test setting up volume source spaces.""" tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space( 'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises(IOError, setup_volume_source_space, 'sample', pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert_equal(repr(src), repr(src_new)) assert_equal(src.kind, 'volume')
def test_compensation_raw_mne(): """Test Raw compensation by comparing with MNE """ tempdir = _TempDir() def compensate_mne(fname, grad): tmp_fname = op.join(tempdir, 'mne_ctf_test_raw.fif') cmd = ['mne_process_raw', '--raw', fname, '--save', tmp_fname, '--grad', str(grad), '--projoff', '--filteroff'] run_subprocess(cmd) return Raw(tmp_fname, preload=True) for grad in [0, 2, 3]: raw_py = Raw(ctf_comp_fname, preload=True, compensation=grad) raw_c = compensate_mne(ctf_comp_fname, grad) assert_allclose(raw_py._data, raw_c._data, rtol=1e-6, atol=1e-17) assert_equal(raw_py.info['nchan'], raw_c.info['nchan']) for ch_py, ch_c in zip(raw_py.info['chs'], raw_c.info['chs']): for key in ('ch_name', 'coil_type', 'scanno', 'logno', 'unit', 'coord_frame', 'kind'): assert_equal(ch_py[key], ch_c[key]) for key in ('loc', 'unit_mul', 'range', 'cal'): assert_allclose(ch_py[key], ch_c[key])
def test_make_field_map_meeg(): """Test making a M/EEG field map onto helmet & head.""" evoked = read_evokeds(evoked_fname, baseline=(-0.2, 0.0))[0] picks = pick_types(evoked.info, meg=True, eeg=True) picks = picks[::10] evoked.pick_channels([evoked.ch_names[p] for p in picks]) evoked.info.normalize_proj() maps = make_field_map(evoked, trans_fname, subject='sample', subjects_dir=subjects_dir, n_jobs=1, verbose='debug') assert_equal(maps[0]['data'].shape, (642, 6)) # EEG->Head assert_equal(maps[1]['data'].shape, (304, 31)) # MEG->Helmet # reasonable ranges maxs = (1.2, 2.0) # before #4418, was (1.1, 2.0) mins = (-0.8, -1.3) # before #4418, was (-0.6, -1.2) assert_equal(len(maxs), len(maps)) for map_, max_, min_ in zip(maps, maxs, mins): assert_allclose(map_['data'].max(), max_, rtol=5e-2) assert_allclose(map_['data'].min(), min_, rtol=5e-2) # calculated from correct looking mapping on 2015/12/26 assert_allclose(np.sqrt(np.sum(maps[0]['data'] ** 2)), 19.0903, # 16.6088, atol=1e-3, rtol=1e-3) assert_allclose(np.sqrt(np.sum(maps[1]['data'] ** 2)), 19.4748, # 20.1245, atol=1e-3, rtol=1e-3)
def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname).crop(0, 1, False) assert_true(raw.info["subject_info"] is None) # fake some subject data keys = ["id", "his_id", "last_name", "first_name", "birthday", "sex", "hand"] vals = [1, "foobar", "bar", "foo", (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info["subject_info"] = subject_info out_fname = op.join(tempdir, "test_subj_info_raw.fif") raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info["subject_info"][key]) raw_read.anonymize() assert_true(raw_read.info.get("subject_info") is None) out_fname_anon = op.join(tempdir, "test_subj_info_anon_raw.fif") raw_read.save(out_fname_anon, overwrite=True) raw_read = Raw(out_fname_anon) assert_true(raw_read.info.get("subject_info") is None)
def test_morphed_source_space_return(): """Test returning a morphed source space to the original subject.""" # let's create some random data on fsaverage data = rng.randn(20484, 1) tmin, tstep = 0, 1. src_fs = read_source_spaces(fname_fs) stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage') # Create our morph source space src_morph = morph_source_spaces(src_fs, 'sample', subjects_dir=subjects_dir) # Morph the data over using standard methods with pytest.warns(RuntimeWarning, match='vertices not included'): stc_morph = SourceMorph(subject_to='sample', subject_from='fsaverage', spacing=[s['vertno'] for s in src_morph], smooth=1, subjects_dir=subjects_dir)(stc_fs) # We can now pretend like this was real data we got e.g. from an inverse. # To be complete, let's remove some vertices keeps = [np.sort(rng.permutation(np.arange(len(v)))[:len(v) - 10]) for v in stc_morph.vertices] stc_morph = SourceEstimate( np.concatenate([stc_morph.lh_data[keeps[0]], stc_morph.rh_data[keeps[1]]]), [v[k] for v, k in zip(stc_morph.vertices, keeps)], tmin, tstep, 'sample') # Return it to the original subject stc_morph_return = stc_morph.to_original_src( src_fs, subjects_dir=subjects_dir) # Compare to the original data with pytest.warns(RuntimeWarning, match='vertices not included'): stc_morph_morph = SourceMorph(subject_to='fsaverage', spacing=stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir)(stc_morph) assert_equal(stc_morph_return.subject, stc_morph_morph.subject) for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Explicitly test having two vertices map to the same target vertex. We # simulate this by having two vertices be at the same position. src_fs2 = src_fs.copy() vert1, vert2 = src_fs2[0]['vertno'][:2] src_fs2[0]['rr'][vert1] = src_fs2[0]['rr'][vert2] stc_morph_return = stc_morph.to_original_src( src_fs2, subjects_dir=subjects_dir) # test to_original_src method result equality for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Degenerate cases stc_morph.subject = None # no .subject provided pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='fsaverage', subjects_dir=subjects_dir) stc_morph.subject = 'sample' del src_fs[0]['subject_his_id'] # no name in src_fsaverage pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'fsaverage' # name mismatch pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='foo', subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'sample' src = read_source_spaces(fname) # wrong source space pytest.raises(RuntimeError, stc_morph.to_original_src, src, subjects_dir=subjects_dir)
def _compare_source_spaces(src0, src1, mode='exact'): """Compare two source spaces Note: this function is also used by forward/tests/test_make_forward.py """ for s0, s1 in zip(src0, src1): for name in ['nuse', 'ntri', 'np', 'type', 'id']: print(name) assert_equal(s0[name], s1[name]) for name in ['subject_his_id']: if name in s0 or name in s1: print(name) assert_equal(s0[name], s1[name]) for name in ['interpolator']: if name in s0 or name in s1: print(name) diffs = (s0['interpolator'] - s1['interpolator']).data if len(diffs) > 0: assert_true(np.sqrt(np.mean(diffs ** 2)) < 0.05) # 5% for name in ['nn', 'rr', 'nuse_tri', 'coord_frame', 'tris']: print(name) if s0[name] is None: assert_true(s1[name] is None) else: if mode == 'exact': assert_array_equal(s0[name], s1[name]) elif mode == 'approx': assert_allclose(s0[name], s1[name], rtol=1e-3, atol=1e-4) else: raise RuntimeError('unknown mode') if mode == 'exact': for name in ['inuse', 'vertno', 'use_tris']: assert_array_equal(s0[name], s1[name]) # these fields will exist if patch info was added, these are # not tested in mode == 'approx' for name in ['nearest', 'nearest_dist']: print(name) if s0[name] is None: assert_true(s1[name] is None) else: assert_array_equal(s0[name], s1[name]) for name in ['dist_limit']: print(name) assert_true(s0[name] == s1[name]) for name in ['dist']: if s0[name] is not None: assert_equal(s1[name].shape, s0[name].shape) assert_true(len((s0['dist'] - s1['dist']).data) == 0) for name in ['pinfo']: if s0[name] is not None: assert_true(len(s0[name]) == len(s1[name])) for p1, p2 in zip(s0[name], s1[name]): assert_true(all(p1 == p2)) elif mode == 'approx': # deal with vertno, inuse, and use_tris carefully assert_array_equal(s0['vertno'], np.where(s0['inuse'])[0]) assert_array_equal(s1['vertno'], np.where(s1['inuse'])[0]) assert_equal(len(s0['vertno']), len(s1['vertno'])) agreement = np.mean(s0['inuse'] == s1['inuse']) assert_true(agreement > 0.99) if agreement < 1.0: # make sure mismatched vertno are within 1.5mm v0 = np.setdiff1d(s0['vertno'], s1['vertno']) v1 = np.setdiff1d(s1['vertno'], s0['vertno']) dists = cdist(s0['rr'][v0], s1['rr'][v1]) assert_allclose(np.min(dists, axis=1), np.zeros(len(v0)), atol=1.5e-3) if s0['use_tris'] is not None: # for "spacing" assert_array_equal(s0['use_tris'].shape, s1['use_tris'].shape) else: assert_true(s1['use_tris'] is None) assert_true(np.mean(s0['use_tris'] == s1['use_tris']) > 0.99) # The above "if s0[name] is not None" can be removed once the sample # dataset is updated to have a source space with distance info for name in ['working_dir', 'command_line']: if mode == 'exact': assert_equal(src0.info[name], src1.info[name]) elif mode == 'approx': print(name) if name in src0.info: assert_true(name in src1.info) else: assert_true(name not in src1.info)
def test_io_raw(): """Test IO for raw data (Neuromag + CTF + gz) """ # test unicode io for chars in [b"\xc3\xa4\xc3\xb6\xc3\xa9", b"a"]: with Raw(fif_fname) as r: desc1 = r.info["description"] = chars.decode("utf-8") temp_file = op.join(tempdir, "raw.fif") r.save(temp_file, overwrite=True) with Raw(temp_file) as r2: desc2 = r2.info["description"] assert_equal(desc1, desc2) # Let's construct a simple test for IO first raw = Raw(fif_fname, preload=True) raw.crop(0, 3.5) # put in some data that we know the values of data = np.random.randn(raw._data.shape[0], raw._data.shape[1]) raw._data[:, :] = data # save it somewhere fname = op.join(tempdir, "test_copy_raw.fif") raw.save(fname, buffer_size_sec=1.0) # read it in, make sure the whole thing matches raw = Raw(fname) assert_true(np.allclose(data, raw[:, :][0], 1e-6, 1e-20)) # let's read portions across the 1-sec tag boundary, too inds = raw.time_as_index([1.75, 2.25]) sl = slice(inds[0], inds[1]) assert_true(np.allclose(data[:, sl], raw[:, sl][0], 1e-6, 1e-20)) # now let's do some real I/O fnames_in = [fif_fname, fif_gz_fname, ctf_fname] fnames_out = ["raw.fif", "raw.fif.gz", "raw.fif"] for fname_in, fname_out in zip(fnames_in, fnames_out): fname_out = op.join(tempdir, fname_out) raw = Raw(fname_in) nchan = raw.info["nchan"] ch_names = raw.info["ch_names"] meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == "M"] n_channels = 100 meg_channels_idx = meg_channels_idx[:n_channels] start, stop = raw.time_as_index([0, 5]) data, times = raw[meg_channels_idx, start : (stop + 1)] meg_ch_names = [ch_names[k] for k in meg_channels_idx] # Set up pick list: MEG + STI 014 - bad channels include = ["STI 014"] include += meg_ch_names picks = pick_types( raw.info, meg=True, eeg=False, stim=True, misc=True, ref_meg=True, include=include, exclude="bads" ) # Writing with drop_small_buffer True raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True, overwrite=True) raw2 = Raw(fname_out, preload=True) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(times2.max() <= 3) # Writing raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True) if fname_in == fif_fname or fname_in == fif_fname + ".gz": assert_true(len(raw.info["dig"]) == 146) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(np.allclose(data, data2, 1e-6, 1e-20)) assert_allclose(times, times2) assert_allclose(raw.info["sfreq"], raw2.info["sfreq"], rtol=1e-5) # check transformations for trans in ["dev_head_t", "dev_ctf_t", "ctf_head_t"]: if raw.info[trans] is None: assert_true(raw2.info[trans] is None) else: assert_array_equal(raw.info[trans]["trans"], raw2.info[trans]["trans"]) # check transformation 'from' and 'to' if trans.startswith("dev"): from_id = FIFF.FIFFV_COORD_DEVICE else: from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD if trans[4:8] == "head": to_id = FIFF.FIFFV_COORD_HEAD else: to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD for raw_ in [raw, raw2]: assert_true(raw_.info[trans]["from"] == from_id) assert_true(raw_.info[trans]["to"] == to_id) if fname_in == fif_fname or fname_in == fif_fname + ".gz": assert_allclose(raw.info["dig"][0]["r"], raw2.info["dig"][0]["r"]) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") raw_badname = op.join(tempdir, "test-bad-name.fif.gz") raw.save(raw_badname) Raw(raw_badname) assert_true(len(w) > 0) # len(w) should be 2 but Travis sometimes has more
def test_io_raw(): """Test IO for raw data (Neuromag + CTF + gz) """ tempdir = _TempDir() # test unicode io for chars in [b'\xc3\xa4\xc3\xb6\xc3\xa9', b'a']: with Raw(fif_fname) as r: assert_true('Raw' in repr(r)) assert_true(op.basename(fif_fname) in repr(r)) desc1 = r.info['description'] = chars.decode('utf-8') temp_file = op.join(tempdir, 'raw.fif') r.save(temp_file, overwrite=True) with Raw(temp_file) as r2: desc2 = r2.info['description'] assert_equal(desc1, desc2) # Let's construct a simple test for IO first raw = Raw(fif_fname).crop(0, 3.5, False) raw.load_data() # put in some data that we know the values of data = rng.randn(raw._data.shape[0], raw._data.shape[1]) raw._data[:, :] = data # save it somewhere fname = op.join(tempdir, 'test_copy_raw.fif') raw.save(fname, buffer_size_sec=1.0) # read it in, make sure the whole thing matches raw = Raw(fname) assert_allclose(data, raw[:, :][0], rtol=1e-6, atol=1e-20) # let's read portions across the 1-sec tag boundary, too inds = raw.time_as_index([1.75, 2.25]) sl = slice(inds[0], inds[1]) assert_allclose(data[:, sl], raw[:, sl][0], rtol=1e-6, atol=1e-20) # now let's do some real I/O fnames_in = [fif_fname, test_fif_gz_fname, ctf_fname] fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif'] for fname_in, fname_out in zip(fnames_in, fnames_out): fname_out = op.join(tempdir, fname_out) raw = Raw(fname_in) nchan = raw.info['nchan'] ch_names = raw.info['ch_names'] meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == 'M'] n_channels = 100 meg_channels_idx = meg_channels_idx[:n_channels] start, stop = raw.time_as_index([0, 5]) data, times = raw[meg_channels_idx, start:(stop + 1)] meg_ch_names = [ch_names[k] for k in meg_channels_idx] # Set up pick list: MEG + STI 014 - bad channels include = ['STI 014'] include += meg_ch_names picks = pick_types(raw.info, meg=True, eeg=False, stim=True, misc=True, ref_meg=True, include=include, exclude='bads') # Writing with drop_small_buffer True raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True, overwrite=True) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(times2.max() <= 3) # Writing raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_equal(len(raw.info['dig']), 146) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_allclose(data, data2, rtol=1e-6, atol=1e-20) assert_allclose(times, times2) assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5) # check transformations for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']: if raw.info[trans] is None: assert_true(raw2.info[trans] is None) else: assert_array_equal(raw.info[trans]['trans'], raw2.info[trans]['trans']) # check transformation 'from' and 'to' if trans.startswith('dev'): from_id = FIFF.FIFFV_COORD_DEVICE else: from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD if trans[4:8] == 'head': to_id = FIFF.FIFFV_COORD_HEAD else: to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD for raw_ in [raw, raw2]: assert_equal(raw_.info[trans]['from'], from_id) assert_equal(raw_.info[trans]['to'], to_id) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r']) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") raw_badname = op.join(tempdir, 'test-bad-name.fif.gz') raw.save(raw_badname) Raw(raw_badname) assert_naming(w, 'test_raw_fiff.py', 2)
def test_morphed_source_space_return(): """Test returning a morphed source space to the original subject.""" # let's create some random data on fsaverage data = rng.randn(20484, 1) tmin, tstep = 0, 1. src_fs = read_source_spaces(fname_fs) stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage') n_verts_fs = sum(len(s['vertno']) for s in src_fs) # Create our morph source space src_morph = morph_source_spaces(src_fs, 'sample', subjects_dir=subjects_dir) n_verts_sample = sum(len(s['vertno']) for s in src_morph) assert n_verts_fs == n_verts_sample # Morph the data over using standard methods stc_morph = compute_source_morph( src_fs, 'fsaverage', 'sample', spacing=[s['vertno'] for s in src_morph], smooth=1, subjects_dir=subjects_dir, warn=False).apply(stc_fs) assert stc_morph.data.shape[0] == n_verts_sample # We can now pretend like this was real data we got e.g. from an inverse. # To be complete, let's remove some vertices keeps = [np.sort(rng.permutation(np.arange(len(v)))[:len(v) - 10]) for v in stc_morph.vertices] stc_morph = SourceEstimate( np.concatenate([stc_morph.lh_data[keeps[0]], stc_morph.rh_data[keeps[1]]]), [v[k] for v, k in zip(stc_morph.vertices, keeps)], tmin, tstep, 'sample') # Return it to the original subject stc_morph_return = stc_morph.to_original_src( src_fs, subjects_dir=subjects_dir) # This should fail (has too many verts in SourceMorph) with pytest.warns(RuntimeWarning, match='vertices not included'): morph = compute_source_morph( src_morph, subject_from='sample', spacing=stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='vertices do not match'): morph.apply(stc_morph) # Compare to the original data with pytest.warns(RuntimeWarning, match='vertices not included'): stc_morph_morph = compute_source_morph( src=stc_morph, subject_from='sample', spacing=stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir).apply(stc_morph) assert_equal(stc_morph_return.subject, stc_morph_morph.subject) for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Explicitly test having two vertices map to the same target vertex. We # simulate this by having two vertices be at the same position. src_fs2 = src_fs.copy() vert1, vert2 = src_fs2[0]['vertno'][:2] src_fs2[0]['rr'][vert1] = src_fs2[0]['rr'][vert2] stc_morph_return = stc_morph.to_original_src( src_fs2, subjects_dir=subjects_dir) # test to_original_src method result equality for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Degenerate cases stc_morph.subject = None # no .subject provided pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='fsaverage', subjects_dir=subjects_dir) stc_morph.subject = 'sample' del src_fs[0]['subject_his_id'] # no name in src_fsaverage pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'fsaverage' # name mismatch pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='foo', subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'sample' src = read_source_spaces(fname) # wrong source space pytest.raises(RuntimeError, stc_morph.to_original_src, src, subjects_dir=subjects_dir)
def test_io_raw(): """Test IO for raw data (Neuromag + CTF + gz) """ tempdir = _TempDir() # test unicode io for chars in [b'\xc3\xa4\xc3\xb6\xc3\xa9', b'a']: with Raw(fif_fname) as r: assert_true('Raw' in repr(r)) assert_true(op.basename(fif_fname) in repr(r)) desc1 = r.info['description'] = chars.decode('utf-8') temp_file = op.join(tempdir, 'raw.fif') r.save(temp_file, overwrite=True) with Raw(temp_file) as r2: desc2 = r2.info['description'] assert_equal(desc1, desc2) # Let's construct a simple test for IO first raw = Raw(fif_fname).crop(0, 3.5) raw.load_data() # put in some data that we know the values of data = rng.randn(raw._data.shape[0], raw._data.shape[1]) raw._data[:, :] = data # save it somewhere fname = op.join(tempdir, 'test_copy_raw.fif') raw.save(fname, buffer_size_sec=1.0) # read it in, make sure the whole thing matches raw = Raw(fname) assert_allclose(data, raw[:, :][0], rtol=1e-6, atol=1e-20) # let's read portions across the 1-sec tag boundary, too inds = raw.time_as_index([1.75, 2.25]) sl = slice(inds[0], inds[1]) assert_allclose(data[:, sl], raw[:, sl][0], rtol=1e-6, atol=1e-20) # now let's do some real I/O fnames_in = [fif_fname, test_fif_gz_fname, ctf_fname] fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif'] for fname_in, fname_out in zip(fnames_in, fnames_out): fname_out = op.join(tempdir, fname_out) raw = Raw(fname_in) nchan = raw.info['nchan'] ch_names = raw.info['ch_names'] meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == 'M'] n_channels = 100 meg_channels_idx = meg_channels_idx[:n_channels] start, stop = raw.time_as_index([0, 5]) data, times = raw[meg_channels_idx, start:(stop + 1)] meg_ch_names = [ch_names[k] for k in meg_channels_idx] # Set up pick list: MEG + STI 014 - bad channels include = ['STI 014'] include += meg_ch_names picks = pick_types(raw.info, meg=True, eeg=False, stim=True, misc=True, ref_meg=True, include=include, exclude='bads') # Writing with drop_small_buffer True raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True, overwrite=True) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(times2.max() <= 3) # Writing raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_equal(len(raw.info['dig']), 146) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_allclose(data, data2, rtol=1e-6, atol=1e-20) assert_allclose(times, times2) assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5) # check transformations for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']: if raw.info[trans] is None: assert_true(raw2.info[trans] is None) else: assert_array_equal(raw.info[trans]['trans'], raw2.info[trans]['trans']) # check transformation 'from' and 'to' if trans.startswith('dev'): from_id = FIFF.FIFFV_COORD_DEVICE else: from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD if trans[4:8] == 'head': to_id = FIFF.FIFFV_COORD_HEAD else: to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD for raw_ in [raw, raw2]: assert_equal(raw_.info[trans]['from'], from_id) assert_equal(raw_.info[trans]['to'], to_id) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r']) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") raw_badname = op.join(tempdir, 'test-bad-name.fif.gz') raw.save(raw_badname) Raw(raw_badname) assert_naming(w, 'test_raw_fiff.py', 2)
def _compare_source_spaces(src0, src1, mode='exact'): """Compare two source spaces Note: this function is also used by forward/tests/test_make_forward.py """ for s0, s1 in zip(src0, src1): for name in ['nuse', 'ntri', 'np', 'type', 'id']: print(name) assert_equal(s0[name], s1[name]) for name in ['subject_his_id']: if name in s0 or name in s1: print(name) assert_equal(s0[name], s1[name]) for name in ['interpolator']: if name in s0 or name in s1: print(name) diffs = (s0['interpolator'] - s1['interpolator']).data if len(diffs) > 0: assert_true(np.sqrt(np.mean(diffs**2)) < 0.05) # 5% for name in ['nn', 'rr', 'nuse_tri', 'coord_frame', 'tris']: print(name) if s0[name] is None: assert_true(s1[name] is None) else: if mode == 'exact': assert_array_equal(s0[name], s1[name]) elif mode == 'approx': assert_allclose(s0[name], s1[name], rtol=1e-3, atol=1e-4) else: raise RuntimeError('unknown mode') if mode == 'exact': for name in ['inuse', 'vertno', 'use_tris']: assert_array_equal(s0[name], s1[name]) # these fields will exist if patch info was added, these are # not tested in mode == 'approx' for name in ['nearest', 'nearest_dist']: print(name) if s0[name] is None: assert_true(s1[name] is None) else: assert_array_equal(s0[name], s1[name]) for name in ['dist_limit']: print(name) assert_true(s0[name] == s1[name]) for name in ['dist']: if s0[name] is not None: assert_equal(s1[name].shape, s0[name].shape) assert_true(len((s0['dist'] - s1['dist']).data) == 0) for name in ['pinfo']: if s0[name] is not None: assert_true(len(s0[name]) == len(s1[name])) for p1, p2 in zip(s0[name], s1[name]): assert_true(all(p1 == p2)) elif mode == 'approx': # deal with vertno, inuse, and use_tris carefully assert_array_equal(s0['vertno'], np.where(s0['inuse'])[0]) assert_array_equal(s1['vertno'], np.where(s1['inuse'])[0]) assert_equal(len(s0['vertno']), len(s1['vertno'])) agreement = np.mean(s0['inuse'] == s1['inuse']) assert_true(agreement > 0.99) if agreement < 1.0: # make sure mismatched vertno are within 1.5mm v0 = np.setdiff1d(s0['vertno'], s1['vertno']) v1 = np.setdiff1d(s1['vertno'], s0['vertno']) dists = cdist(s0['rr'][v0], s1['rr'][v1]) assert_allclose(np.min(dists, axis=1), np.zeros(len(v0)), atol=1.5e-3) if s0['use_tris'] is not None: # for "spacing" assert_array_equal(s0['use_tris'].shape, s1['use_tris'].shape) else: assert_true(s1['use_tris'] is None) assert_true(np.mean(s0['use_tris'] == s1['use_tris']) > 0.99) # The above "if s0[name] is not None" can be removed once the sample # dataset is updated to have a source space with distance info for name in ['working_dir', 'command_line']: if mode == 'exact': assert_equal(src0.info[name], src1.info[name]) elif mode == 'approx': print(name) if name in src0.info: assert_true(name in src1.info) else: assert_true(name not in src1.info)
def _compare_source_spaces(src0, src1, mode="exact"): """Compare two source spaces Note: this function is also used by forward/tests/test_make_forward.py """ for s0, s1 in zip(src0, src1): for name in ["nuse", "ntri", "np", "type", "id"]: print(name) assert_equal(s0[name], s1[name]) for name in ["subject_his_id"]: if name in s0 or name in s1: print(name) assert_equal(s0[name], s1[name]) for name in ["interpolator"]: if name in s0 or name in s1: print(name) diffs = (s0["interpolator"] - s1["interpolator"]).data assert_true(np.sqrt(np.mean(diffs ** 2)) < 0.05) # 5% for name in ["nn", "rr", "nuse_tri", "coord_frame", "tris"]: print(name) if s0[name] is None: assert_true(s1[name] is None) else: if mode == "exact": assert_array_equal(s0[name], s1[name]) elif mode == "approx": assert_allclose(s0[name], s1[name], rtol=1e-3, atol=1e-4) else: raise RuntimeError("unknown mode") if mode == "exact": for name in ["inuse", "vertno", "use_tris"]: assert_array_equal(s0[name], s1[name]) # these fields will exist if patch info was added, these are # not tested in mode == 'approx' for name in ["nearest", "nearest_dist"]: print(name) if s0[name] is None: assert_true(s1[name] is None) else: assert_array_equal(s0[name], s1[name]) for name in ["dist_limit"]: print(name) assert_true(s0[name] == s1[name]) for name in ["dist"]: if s0[name] is not None: assert_equal(s1[name].shape, s0[name].shape) assert_true(len((s0["dist"] - s1["dist"]).data) == 0) for name in ["pinfo"]: if s0[name] is not None: assert_true(len(s0[name]) == len(s1[name])) for p1, p2 in zip(s0[name], s1[name]): assert_true(all(p1 == p2)) elif mode == "approx": # deal with vertno, inuse, and use_tris carefully assert_array_equal(s0["vertno"], np.where(s0["inuse"])[0]) assert_array_equal(s1["vertno"], np.where(s1["inuse"])[0]) assert_equal(len(s0["vertno"]), len(s1["vertno"])) agreement = np.mean(s0["inuse"] == s1["inuse"]) assert_true(agreement > 0.99) if agreement < 1.0: # make sure mismatched vertno are within 1.5mm v0 = np.setdiff1d(s0["vertno"], s1["vertno"]) v1 = np.setdiff1d(s1["vertno"], s0["vertno"]) dists = cdist(s0["rr"][v0], s1["rr"][v1]) assert_allclose(np.min(dists, axis=1), np.zeros(len(v0)), atol=1.5e-3) if s0["use_tris"] is not None: # for "spacing" assert_array_equal(s0["use_tris"].shape, s1["use_tris"].shape) else: assert_true(s1["use_tris"] is None) assert_true(np.mean(s0["use_tris"] == s1["use_tris"]) > 0.99) # The above "if s0[name] is not None" can be removed once the sample # dataset is updated to have a source space with distance info for name in ["working_dir", "command_line"]: if mode == "exact": assert_equal(src0.info[name], src1.info[name]) elif mode == "approx": print(name) if name in src0.info: assert_true(name in src1.info) else: assert_true(name not in src1.info)