def test_other_volume_source_spaces(): """Test setting up other volume source spaces""" # these are split off because they require the MNE tools, and # Travis doesn't seem to like them # let's try the spherical one (no bem or surf supplied) tempdir = _TempDir() temp_name = op.join(tempdir, 'temp-src.fif') run_subprocess(['mne_volume_source_space', '--grid', '7.0', '--src', temp_name, '--mri', fname_mri]) src = read_source_spaces(temp_name) src_new = setup_volume_source_space('sample', temp_name, pos=7.0, mri=fname_mri, subjects_dir=subjects_dir) _compare_source_spaces(src, src_new, mode='approx') del src del src_new assert_raises(ValueError, setup_volume_source_space, 'sample', temp_name, pos=7.0, sphere=[1., 1.], mri=fname_mri, # bad sphere subjects_dir=subjects_dir) # now without MRI argument, it should give an error when we try # to read it run_subprocess(['mne_volume_source_space', '--grid', '7.0', '--src', temp_name]) assert_raises(ValueError, read_source_spaces, temp_name)
def test_morph_source_spaces(): """Test morphing of source spaces.""" src = read_source_spaces(fname_fs) src_morph = read_source_spaces(fname_morph) src_morph_py = morph_source_spaces(src, 'sample', subjects_dir=subjects_dir) _compare_source_spaces(src_morph, src_morph_py, mode='approx')
def test_source_space_from_label(): """Test generating a source space from volume label.""" tempdir = _TempDir() aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz') label_names = get_volume_labels_from_aseg(aseg_fname) volume_label = label_names[int(np.random.rand() * len(label_names))] # Test pos as dict pos = dict() pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=pos, volume_label=volume_label, mri=aseg_fname) # Test no mri provided pytest.raises(RuntimeError, setup_volume_source_space, 'sample', mri=None, volume_label=volume_label) # Test invalid volume label pytest.raises(ValueError, setup_volume_source_space, 'sample', volume_label='Hello World!', mri=aseg_fname) src = setup_volume_source_space('sample', subjects_dir=subjects_dir, volume_label=volume_label, mri=aseg_fname, add_interpolator=False) assert_equal(volume_label, src[0]['seg_name']) # test reading and writing out_name = op.join(tempdir, 'temp-src.fif') write_source_spaces(out_name, src) src_from_file = read_source_spaces(out_name) _compare_source_spaces(src, src_from_file, mode='approx')
def test_simulate_round_trip(): """Test simulate_raw round trip calculations.""" # Check a diagonal round-trip raw, src, stc, trans, sphere = _get_data() raw.pick_types(meg=True, stim=True) bem = read_bem_solution(bem_1_fname) old_bem = bem.copy() old_src = src.copy() old_trans = trans.copy() fwd = make_forward_solution(raw.info, trans, src, bem) # no omissions assert (sum(len(s['vertno']) for s in src) == sum(len(s['vertno']) for s in fwd['src']) == 36) # make sure things were not modified assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) data = np.eye(fwd['nsource']) raw.crop(0, (len(data) - 1) / raw.info['sfreq']) stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0, 1. / raw.info['sfreq']) for use_cps in (False, True): this_raw = simulate_raw(raw, stc, trans, src, bem, cov=None, use_cps=use_cps) this_raw.pick_types(meg=True, eeg=True) assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) this_fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=use_cps) assert_allclose(this_raw[:][0], this_fwd['sol']['data'], atol=1e-12, rtol=1e-6)
def _compare_forwards(fwd, fwd_py, n_sensors, n_src, meg_rtol=1e-4, meg_atol=1e-9, eeg_rtol=1e-3, eeg_atol=1e-3): """Helper to test forwards""" # check source spaces assert_equal(len(fwd['src']), len(fwd_py['src'])) _compare_source_spaces(fwd['src'], fwd_py['src'], mode='approx') for surf_ori in [False, True]: if surf_ori: # use copy here to leave our originals unmodified fwd = convert_forward_solution(fwd, surf_ori, copy=True) fwd_py = convert_forward_solution(fwd, surf_ori, copy=True) for key in ['nchan', 'source_nn', 'source_rr', 'source_ori', 'surf_ori', 'coord_frame', 'nsource']: print(key) assert_allclose(fwd_py[key], fwd[key], rtol=1e-4, atol=1e-7) assert_allclose(fwd_py['mri_head_t']['trans'], fwd['mri_head_t']['trans'], rtol=1e-5, atol=1e-8) assert_equal(fwd_py['sol']['data'].shape, (n_sensors, n_src)) assert_equal(len(fwd['sol']['row_names']), n_sensors) assert_equal(len(fwd_py['sol']['row_names']), n_sensors) # check MEG assert_allclose(fwd['sol']['data'][:306], fwd_py['sol']['data'][:306], rtol=meg_rtol, atol=meg_atol, err_msg='MEG mismatch') # check EEG if fwd['sol']['data'].shape[0] > 306: assert_allclose(fwd['sol']['data'][306:], fwd_py['sol']['data'][306:], rtol=eeg_rtol, atol=eeg_atol, err_msg='EEG mismatch')
def _compare_forwards(fwd, fwd_py, n_sensors, n_src, meg_rtol=1e-4, meg_atol=1e-9, eeg_rtol=1e-3, eeg_atol=1e-3): """Helper to test forwards""" # check source spaces assert_equal(len(fwd["src"]), len(fwd_py["src"])) _compare_source_spaces(fwd["src"], fwd_py["src"], mode="approx") for surf_ori in [False, True]: if surf_ori: # use copy here to leave our originals unmodified fwd = convert_forward_solution(fwd, surf_ori, copy=True) fwd_py = convert_forward_solution(fwd, surf_ori, copy=True) for key in ["nchan", "source_nn", "source_rr", "source_ori", "surf_ori", "coord_frame", "nsource"]: print(key) assert_allclose(fwd_py[key], fwd[key], rtol=1e-4, atol=1e-7) assert_allclose(fwd_py["mri_head_t"]["trans"], fwd["mri_head_t"]["trans"], rtol=1e-5, atol=1e-8) assert_equal(fwd_py["sol"]["data"].shape, (n_sensors, n_src)) assert_equal(len(fwd["sol"]["row_names"]), n_sensors) assert_equal(len(fwd_py["sol"]["row_names"]), n_sensors) # check MEG assert_allclose( fwd["sol"]["data"][:306], fwd_py["sol"]["data"][:306], rtol=meg_rtol, atol=meg_atol, err_msg="MEG mismatch" ) # check EEG if fwd["sol"]["data"].shape[0] > 306: assert_allclose( fwd["sol"]["data"][306:], fwd_py["sol"]["data"][306:], rtol=eeg_rtol, atol=eeg_atol, err_msg="EEG mismatch", )
def test_simulate_round_trip(raw_data): """Test simulate_raw round trip calculations.""" # Check a diagonal round-trip raw, src, stc, trans, sphere = raw_data raw.pick_types(meg=True, stim=True) bem = read_bem_solution(bem_1_fname) old_bem = bem.copy() old_src = src.copy() old_trans = trans.copy() fwd = make_forward_solution(raw.info, trans, src, bem) # no omissions assert (sum(len(s['vertno']) for s in src) == sum(len(s['vertno']) for s in fwd['src']) == 36) # make sure things were not modified assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) data = np.eye(fwd['nsource']) raw.crop(0, (len(data) - 1) / raw.info['sfreq']) stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0, 1. / raw.info['sfreq']) for use_fwd in (None, fwd): if use_fwd is None: use_trans, use_src, use_bem = trans, src, bem else: use_trans = use_src = use_bem = None with pytest.deprecated_call(): this_raw = simulate_raw(raw, stc, use_trans, use_src, use_bem, cov=None, forward=use_fwd) this_raw.pick_types(meg=True, eeg=True) assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) this_fwd = convert_forward_solution(fwd, force_fixed=True) assert_allclose(this_raw[:][0], this_fwd['sol']['data'], atol=1e-12, rtol=1e-6) with pytest.raises(ValueError, match='If forward is not None then'): simulate_raw(raw.info, stc, trans, src, bem, forward=fwd) # Not iterable with pytest.raises(TypeError, match='SourceEstimate, tuple, or iterable'): simulate_raw(raw.info, 0., trans, src, bem, None) # STC with a source that `src` does not have assert 0 not in src[0]['vertno'] vertices = [[0, fwd['src'][0]['vertno'][0]], []] stc_bad = SourceEstimate(data[:2], vertices, 0, 1. / raw.info['sfreq']) with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, trans, src, bem) assert 0 not in fwd['src'][0]['vertno'] with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, None, None, None, forward=fwd) # dev_head_t mismatch fwd['info']['dev_head_t']['trans'][0, 0] = 1. with pytest.raises(ValueError, match='dev_head_t.*does not match'): simulate_raw(raw.info, stc, None, None, None, forward=fwd)
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') # The one in the sample dataset (uses bem as bounds) src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=fname_bem, 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')
def test_write_source_space(): """Test reading and writing of source spaces.""" tempdir = _TempDir() src0 = read_source_spaces(fname, patch_stats=False) write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0) src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), patch_stats=False) _compare_source_spaces(src0, src1) # test warnings on bad filenames src_badname = op.join(tempdir, 'test-bad-name.fif.gz') with pytest.warns(RuntimeWarning, match='-src.fif'): write_source_spaces(src_badname, src0) with pytest.warns(RuntimeWarning, match='-src.fif'): read_source_spaces(src_badname)
def test_write_source_space(): """Test reading and writing of source spaces """ tempdir = _TempDir() src0 = read_source_spaces(fname, add_geom=False) write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0) src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), add_geom=False) _compare_source_spaces(src0, src1) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') src_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_source_spaces(src_badname, src0) read_source_spaces(src_badname) assert_equal(len(w), 2)
def test_setup_source_space_spacing(tmpdir, spacing): """Test setting up surface source spaces using a given spacing.""" tempdir = str(tmpdir) copytree(op.join(subjects_dir, 'sample'), op.join(tempdir, 'sample')) args = [] if spacing == 7 else ['--spacing', str(spacing)] with modified_env(SUBJECTS_DIR=tempdir, SUBJECT='sample'): run_subprocess(['mne_setup_source_space'] + args) src = read_source_spaces(op.join(tempdir, 'sample', 'bem', 'sample-%d-src.fif' % spacing)) src_new = setup_source_space('sample', spacing=spacing, add_dist=False, subjects_dir=subjects_dir) _compare_source_spaces(src, src_new, mode='approx', nearest=True) # Degenerate conditions with pytest.raises(TypeError, match='spacing must be.*got.*float.*'): setup_source_space('sample', 7., subjects_dir=subjects_dir) with pytest.raises(ValueError, match='spacing must be >= 2, got 1'): setup_source_space('sample', 1, subjects_dir=subjects_dir)
def _compare_forwards(fwd, fwd_py, n_sensors, n_src, meg_rtol=1e-4, meg_atol=1e-9, eeg_rtol=1e-3, eeg_atol=1e-3): """Test forwards.""" # check source spaces assert_equal(len(fwd['src']), len(fwd_py['src'])) _compare_source_spaces(fwd['src'], fwd_py['src'], mode='approx') for surf_ori, force_fixed in product([False, True], [False, True]): # use copy here to leave our originals unmodified fwd = convert_forward_solution(fwd, surf_ori, force_fixed, copy=True, use_cps=True) fwd_py = convert_forward_solution(fwd_py, surf_ori, force_fixed, copy=True, use_cps=True) check_src = n_src // 3 if force_fixed else n_src for key in ('nchan', 'source_rr', 'source_ori', 'surf_ori', 'coord_frame', 'nsource'): assert_allclose(fwd_py[key], fwd[key], rtol=1e-4, atol=1e-7, err_msg=key) # In surf_ori=True only Z matters for source_nn if surf_ori and not force_fixed: ori_sl = slice(2, None, 3) else: ori_sl = slice(None) assert_allclose(fwd_py['source_nn'][ori_sl], fwd['source_nn'][ori_sl], rtol=1e-4, atol=1e-6) assert_allclose(fwd_py['mri_head_t']['trans'], fwd['mri_head_t']['trans'], rtol=1e-5, atol=1e-8) assert_equal(fwd_py['sol']['data'].shape, (n_sensors, check_src)) assert_equal(len(fwd['sol']['row_names']), n_sensors) assert_equal(len(fwd_py['sol']['row_names']), n_sensors) # check MEG assert_allclose(fwd['sol']['data'][:306, ori_sl], fwd_py['sol']['data'][:306, ori_sl], rtol=meg_rtol, atol=meg_atol, err_msg='MEG mismatch') # check EEG if fwd['sol']['data'].shape[0] > 306: assert_allclose(fwd['sol']['data'][306:, ori_sl], fwd_py['sol']['data'][306:, ori_sl], rtol=eeg_rtol, atol=eeg_atol, err_msg='EEG mismatch')
def _compare_forwards(fwd, fwd_py, n_sensors, n_src, meg_rtol=1e-4, meg_atol=1e-9, eeg_rtol=1e-3, eeg_atol=1e-3): """Helper to test forwards""" # check source spaces assert_equal(len(fwd["src"]), len(fwd_py["src"])) _compare_source_spaces(fwd["src"], fwd_py["src"], mode="approx") for surf_ori, force_fixed in product([False, True], [False, True]): # use copy here to leave our originals unmodified fwd = convert_forward_solution(fwd, surf_ori, force_fixed, copy=True) fwd_py = convert_forward_solution(fwd_py, surf_ori, force_fixed, copy=True) check_src = n_src // 3 if force_fixed else n_src for key in ("nchan", "source_rr", "source_ori", "surf_ori", "coord_frame", "nsource"): assert_allclose(fwd_py[key], fwd[key], rtol=1e-4, atol=1e-7, err_msg=key) # In surf_ori=True only Z matters for source_nn if surf_ori and not force_fixed: ori_sl = slice(2, None, 3) else: ori_sl = slice(None) assert_allclose(fwd_py["source_nn"][ori_sl], fwd["source_nn"][ori_sl], rtol=1e-4, atol=1e-6) assert_allclose(fwd_py["mri_head_t"]["trans"], fwd["mri_head_t"]["trans"], rtol=1e-5, atol=1e-8) assert_equal(fwd_py["sol"]["data"].shape, (n_sensors, check_src)) assert_equal(len(fwd["sol"]["row_names"]), n_sensors) assert_equal(len(fwd_py["sol"]["row_names"]), n_sensors) # check MEG assert_allclose( fwd["sol"]["data"][:306, ori_sl], fwd_py["sol"]["data"][:306, ori_sl], rtol=meg_rtol, atol=meg_atol, err_msg="MEG mismatch", ) # check EEG if fwd["sol"]["data"].shape[0] > 306: assert_allclose( fwd["sol"]["data"][306:, ori_sl], fwd_py["sol"]["data"][306:, ori_sl], rtol=eeg_rtol, atol=eeg_atol, err_msg="EEG mismatch", )
def test_other_volume_source_spaces(): """Test setting up other volume source spaces.""" # these are split off because they require the MNE tools, and # Travis doesn't seem to like them # let's try the spherical one (no bem or surf supplied) tempdir = _TempDir() temp_name = op.join(tempdir, 'temp-src.fif') run_subprocess(['mne_volume_source_space', '--grid', '7.0', '--src', temp_name, '--mri', fname_mri]) src = read_source_spaces(temp_name) src_new = setup_volume_source_space(None, pos=7.0, mri=fname_mri, subjects_dir=subjects_dir) # we use a more accurate elimination criteria, so let's fix the MNE-C # source space assert len(src_new[0]['vertno']) == 7497 assert len(src) == 1 assert len(src_new) == 1 good_mask = np.in1d(src[0]['vertno'], src_new[0]['vertno']) src[0]['inuse'][src[0]['vertno'][~good_mask]] = 0 assert src[0]['inuse'].sum() == 7497 src[0]['vertno'] = src[0]['vertno'][good_mask] assert len(src[0]['vertno']) == 7497 src[0]['nuse'] = len(src[0]['vertno']) assert src[0]['nuse'] == 7497 _compare_source_spaces(src_new, src, mode='approx') assert 'volume, shape' in repr(src) del src del src_new pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=7.0, sphere=[1., 1.], mri=fname_mri, # bad sphere subjects_dir=subjects_dir) # now without MRI argument, it should give an error when we try # to read it run_subprocess(['mne_volume_source_space', '--grid', '7.0', '--src', temp_name]) pytest.raises(ValueError, read_source_spaces, temp_name)
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_discrete_source_space(): """Test setting up (and reading/writing) discrete source spaces """ tempdir = _TempDir() src = read_source_spaces(fname) v = src[0]['vertno'] # let's make a discrete version with the C code, and with ours temp_name = op.join(tempdir, 'temp-src.fif') try: # save temp_pos = op.join(tempdir, 'temp-pos.txt') np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]]) # let's try the spherical one (no bem or surf supplied) run_subprocess(['mne_volume_source_space', '--meters', '--pos', temp_pos, '--src', temp_name]) src_c = read_source_spaces(temp_name) pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v]) src_new = setup_volume_source_space('sample', None, pos=pos_dict, subjects_dir=subjects_dir) _compare_source_spaces(src_c, src_new, mode='approx') assert_allclose(src[0]['rr'][v], src_new[0]['rr'], rtol=1e-3, atol=1e-6) assert_allclose(src[0]['nn'][v], src_new[0]['nn'], rtol=1e-3, atol=1e-6) # now do writing write_source_spaces(temp_name, src_c) src_c2 = read_source_spaces(temp_name) _compare_source_spaces(src_c, src_c2) # now do MRI assert_raises(ValueError, setup_volume_source_space, 'sample', pos=pos_dict, mri=fname_mri) assert_equal(repr(src_new), repr(src_c)) assert_equal(src_new.kind, 'discrete') finally: if op.isfile(temp_name): os.remove(temp_name)
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(tmpdir): """Test setting up volume source spaces.""" src = read_source_spaces(fname_vol) temp_name = tmpdir.join('temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm bem_sol = read_bem_solution(fname_bem_3_sol) bem = read_bem_solution(fname_bem_sol) # The one in the testing dataset (uses bem as bounds) for this_bem, this_surf in zip( (bem, fname_bem, fname_bem_3, bem_sol, fname_bem_3_sol, None), (None, None, None, None, None, surf)): src_new = setup_volume_source_space('sample', pos=7.0, bem=this_bem, surface=this_surf, 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') with pytest.raises(IOError, match='surface file.*not found'): setup_volume_source_space('sample', surface='foo', mri=fname_mri, subjects_dir=subjects_dir) bem['surfs'][-1]['coord_frame'] = FIFF.FIFFV_COORD_HEAD with pytest.raises(ValueError, match='BEM is not in MRI coord.* got head'): setup_volume_source_space('sample', bem=bem, mri=fname_mri, subjects_dir=subjects_dir) bem['surfs'] = bem['surfs'][:-1] # no inner skull surf with pytest.raises(ValueError, match='Could not get inner skul.*from BEM'): setup_volume_source_space('sample', bem=bem, mri=fname_mri, subjects_dir=subjects_dir) del bem 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)) with pytest.deprecated_call(match='sphere_units'): src = setup_volume_source_space(pos=10, sphere=(0., 0., 0., 90)) src_new = setup_volume_source_space(pos=10, sphere=sphere) _compare_source_spaces(src, src_new, mode='exact') with pytest.raises(ValueError, match='sphere, if str'): setup_volume_source_space(sphere='foo') # Need a radius sphere = make_sphere_model(head_radius=None) with pytest.raises(ValueError, match='be spherical with multiple layers'): setup_volume_source_space(sphere=sphere)
def test_discrete_source_space(tmpdir): """Test setting up (and reading/writing) discrete source spaces.""" src = read_source_spaces(fname) v = src[0]['vertno'] # let's make a discrete version with the C code, and with ours temp_name = tmpdir.join('temp-src.fif') # save temp_pos = tmpdir.join('temp-pos.txt') np.savetxt(str(temp_pos), np.c_[src[0]['rr'][v], src[0]['nn'][v]]) # let's try the spherical one (no bem or surf supplied) run_subprocess([ 'mne_volume_source_space', '--meters', '--pos', temp_pos, '--src', temp_name ]) src_c = read_source_spaces(temp_name) pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v]) src_new = setup_volume_source_space(pos=pos_dict) assert src_new.kind == 'discrete' _compare_source_spaces(src_c, src_new, mode='approx') assert_allclose(src[0]['rr'][v], src_new[0]['rr'], rtol=1e-3, atol=1e-6) assert_allclose(src[0]['nn'][v], src_new[0]['nn'], rtol=1e-3, atol=1e-6) # now do writing write_source_spaces(temp_name, src_c, overwrite=True) src_c2 = read_source_spaces(temp_name) _compare_source_spaces(src_c, src_c2) # now do MRI pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=pos_dict, mri=fname_mri) assert repr(src_new).split('~')[0] == repr(src_c).split('~')[0] assert ' kB' in repr(src_new) assert src_new.kind == 'discrete' assert _get_src_type(src_new, None) == 'discrete'
def test_discrete_source_space(): """Test setting up (and reading/writing) discrete source spaces """ tempdir = _TempDir() src = read_source_spaces(fname) v = src[0]['vertno'] # let's make a discrete version with the C code, and with ours temp_name = op.join(tempdir, 'temp-src.fif') try: # save temp_pos = op.join(tempdir, 'temp-pos.txt') np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]]) # let's try the spherical one (no bem or surf supplied) run_subprocess(['mne_volume_source_space', '--meters', '--pos', temp_pos, '--src', temp_name]) src_c = read_source_spaces(temp_name) pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v]) src_new = setup_volume_source_space('sample', None, pos=pos_dict, subjects_dir=subjects_dir) _compare_source_spaces(src_c, src_new, mode='approx') assert_allclose(src[0]['rr'][v], src_new[0]['rr'], rtol=1e-3, atol=1e-6) assert_allclose(src[0]['nn'][v], src_new[0]['nn'], rtol=1e-3, atol=1e-6) # now do writing write_source_spaces(temp_name, src_c) src_c2 = read_source_spaces(temp_name) _compare_source_spaces(src_c, src_c2) # now do MRI assert_raises(ValueError, setup_volume_source_space, 'sample', pos=pos_dict, mri=fname_mri) finally: if op.isfile(temp_name): os.remove(temp_name)
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_other_volume_source_spaces(): """Test setting up other volume source spaces""" # these are split off because they require the MNE tools, and # Travis doesn't seem to like them # let's try the spherical one (no bem or surf supplied) tempdir = _TempDir() temp_name = op.join(tempdir, 'temp-src.fif') run_subprocess([ 'mne_volume_source_space', '--grid', '7.0', '--src', temp_name, '--mri', fname_mri ]) src = read_source_spaces(temp_name) src_new = setup_volume_source_space('sample', temp_name, pos=7.0, mri=fname_mri, subjects_dir=subjects_dir) _compare_source_spaces(src, src_new, mode='approx') assert_true('volume, shape' in repr(src)) del src del src_new assert_raises( ValueError, setup_volume_source_space, 'sample', temp_name, pos=7.0, sphere=[1., 1.], mri=fname_mri, # bad sphere subjects_dir=subjects_dir) # now without MRI argument, it should give an error when we try # to read it run_subprocess( ['mne_volume_source_space', '--grid', '7.0', '--src', temp_name]) assert_raises(ValueError, read_source_spaces, temp_name)
def test_setup_source_space(tmpdir): """Test setting up ico, oct, and all source spaces.""" fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem', 'fsaverage-ico-5-src.fif') # first lets test some input params for spacing in ('oct', 'oct6e'): with pytest.raises(ValueError, match='subdivision must be an integer'): setup_source_space('sample', spacing=spacing, add_dist=False, subjects_dir=subjects_dir) for spacing in ('oct0', 'oct-4'): with pytest.raises(ValueError, match='oct subdivision must be >= 1'): setup_source_space('sample', spacing=spacing, add_dist=False, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='ico subdivision must be >= 0'): setup_source_space('sample', spacing='ico-4', add_dist=False, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='must be a string with values'): setup_source_space('sample', spacing='7emm', add_dist=False, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='must be a string with values'): setup_source_space('sample', spacing='alls', add_dist=False, subjects_dir=subjects_dir) # ico 5 (fsaverage) - write to temp file src = read_source_spaces(fname_ico) with pytest.warns(None): # sklearn equiv neighbors src_new = setup_source_space('fsaverage', spacing='ico5', subjects_dir=subjects_dir, add_dist=False) _compare_source_spaces(src, src_new, mode='approx') assert_equal(repr(src), repr(src_new)) assert_equal(repr(src).count('surface ('), 2) assert_array_equal(src[0]['vertno'], np.arange(10242)) assert_array_equal(src[1]['vertno'], np.arange(10242)) # oct-6 (sample) - auto filename + IO src = read_source_spaces(fname) temp_name = tmpdir.join('temp-src.fif') with pytest.warns(None): # sklearn equiv neighbors src_new = setup_source_space('sample', spacing='oct6', subjects_dir=subjects_dir, add_dist=False) write_source_spaces(temp_name, src_new, overwrite=True) assert_equal(src_new[0]['nuse'], 4098) _compare_source_spaces(src, src_new, mode='approx', nearest=False) src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx', nearest=False) # all source points - no file writing src_new = setup_source_space('sample', spacing='all', subjects_dir=subjects_dir, add_dist=False) assert src_new[0]['nuse'] == len(src_new[0]['rr']) assert src_new[1]['nuse'] == len(src_new[1]['rr']) # dense source space to hit surf['inuse'] lines of _create_surf_spacing pytest.raises(RuntimeError, setup_source_space, 'sample', spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
def test_setup_source_space(): """Test setting up ico, oct, and all source spaces """ tempdir = _TempDir() fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem', 'fsaverage-ico-5-src.fif') # first lets test some input params assert_raises(ValueError, setup_source_space, 'sample', spacing='oct', add_dist=False) assert_raises(ValueError, setup_source_space, 'sample', spacing='octo', add_dist=False) assert_raises(ValueError, setup_source_space, 'sample', spacing='oct6e', add_dist=False) assert_raises(ValueError, setup_source_space, 'sample', spacing='7emm', add_dist=False) assert_raises(ValueError, setup_source_space, 'sample', spacing='alls', add_dist=False) assert_raises(IOError, setup_source_space, 'sample', spacing='oct6', subjects_dir=subjects_dir, add_dist=False) # ico 5 (fsaverage) - write to temp file src = read_source_spaces(fname_ico) temp_name = op.join(tempdir, 'temp-src.fif') with warnings.catch_warnings(record=True): # sklearn equiv neighbors warnings.simplefilter('always') src_new = setup_source_space('fsaverage', temp_name, spacing='ico5', subjects_dir=subjects_dir, add_dist=False, overwrite=True) _compare_source_spaces(src, src_new, mode='approx') assert_equal(repr(src), repr(src_new)) assert_equal(repr(src).count('surface ('), 2) assert_array_equal(src[0]['vertno'], np.arange(10242)) assert_array_equal(src[1]['vertno'], np.arange(10242)) # oct-6 (sample) - auto filename + IO src = read_source_spaces(fname) temp_name = op.join(tempdir, 'temp-src.fif') with warnings.catch_warnings(record=True): # sklearn equiv neighbors warnings.simplefilter('always') src_new = setup_source_space('sample', temp_name, spacing='oct6', subjects_dir=subjects_dir, overwrite=True, add_dist=False) _compare_source_spaces(src, src_new, mode='approx', nearest=False) src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx', nearest=False) # all source points - no file writing src_new = setup_source_space('sample', None, spacing='all', subjects_dir=subjects_dir, add_dist=False) assert_true(src_new[0]['nuse'] == len(src_new[0]['rr'])) assert_true(src_new[1]['nuse'] == len(src_new[1]['rr'])) # dense source space to hit surf['inuse'] lines of _create_surf_spacing assert_raises(RuntimeError, setup_source_space, 'sample', None, spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
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 bem_surfs = read_bem_surfaces(fname_bem) bem = ConductorModel(is_sphere=False, surfs=bem_surfs) # The one in the testing dataset (uses bem as bounds) for this_bem, this_surf in zip((bem, fname_bem, None), (None, None, surf)): src_new = setup_volume_source_space('sample', pos=7.0, bem=this_bem, surface=this_surf, 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_combine_source_spaces(): """Test combining source spaces.""" tempdir = _TempDir() aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz') label_names = get_volume_labels_from_aseg(aseg_fname) volume_labels = [label_names[int(np.random.rand() * len(label_names))] for ii in range(2)] # get a surface source space (no need to test creation here) srf = read_source_spaces(fname, patch_stats=False) # setup 2 volume source spaces vol = setup_volume_source_space('sample', subjects_dir=subjects_dir, volume_label=volume_labels[0], mri=aseg_fname, add_interpolator=False) # setup a discrete source space rr = rng.randint(0, 20, (100, 3)) * 1e-3 nn = np.zeros(rr.shape) nn[:, -1] = 1 pos = {'rr': rr, 'nn': nn} disc = setup_volume_source_space('sample', subjects_dir=subjects_dir, pos=pos, verbose='error') # combine source spaces src = srf + vol + disc # test addition of source spaces assert_equal(type(src), SourceSpaces) assert_equal(len(src), 4) # test reading and writing src_out_name = op.join(tempdir, 'temp-src.fif') src.save(src_out_name) src_from_file = read_source_spaces(src_out_name) _compare_source_spaces(src, src_from_file, mode='approx') assert_equal(repr(src), repr(src_from_file)) assert_equal(src.kind, 'mixed') # test that all source spaces are in MRI coordinates coord_frames = np.array([s['coord_frame'] for s in src]) assert (coord_frames == FIFF.FIFFV_COORD_MRI).all() # test errors for export_volume image_fname = op.join(tempdir, 'temp-image.mgz') # source spaces with no volume pytest.raises(ValueError, srf.export_volume, image_fname, verbose='error') # unrecognized source type disc2 = disc.copy() disc2[0]['type'] = 'kitty' src_unrecognized = src + disc2 pytest.raises(ValueError, src_unrecognized.export_volume, image_fname, verbose='error') # unrecognized file type bad_image_fname = op.join(tempdir, 'temp-image.png') # vertices outside vol space warning pytest.raises(ValueError, src.export_volume, bad_image_fname, verbose='error') # mixed coordinate frames disc3 = disc.copy() disc3[0]['coord_frame'] = 10 src_mixed_coord = src + disc3 pytest.raises(ValueError, src_mixed_coord.export_volume, image_fname, verbose='error')
def test_simulate_round_trip(raw_data): """Test simulate_raw round trip calculations.""" # Check a diagonal round-trip raw, src, stc, trans, sphere = raw_data raw.pick_types(meg=True, stim=True) bem = read_bem_solution(bem_1_fname) old_bem = bem.copy() old_src = src.copy() old_trans = trans.copy() fwd = make_forward_solution(raw.info, trans, src, bem) # no omissions assert (sum(len(s['vertno']) for s in src) == sum(len(s['vertno']) for s in fwd['src']) == 36) # make sure things were not modified assert ( old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) data = np.eye(fwd['nsource']) raw.crop(0, (len(data) - 1) / raw.info['sfreq']) stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0, 1. / raw.info['sfreq']) for use_fwd in (None, fwd): if use_fwd is None: use_trans, use_src, use_bem = trans, src, bem else: use_trans = use_src = use_bem = None with pytest.deprecated_call(): this_raw = simulate_raw(raw, stc, use_trans, use_src, use_bem, cov=None, forward=use_fwd) this_raw.pick_types(meg=True, eeg=True) assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0] ['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) this_fwd = convert_forward_solution(fwd, force_fixed=True) assert_allclose(this_raw[:][0], this_fwd['sol']['data'], atol=1e-12, rtol=1e-6) with pytest.raises(ValueError, match='If forward is not None then'): simulate_raw(raw.info, stc, trans, src, bem, forward=fwd) # Not iterable with pytest.raises(TypeError, match='SourceEstimate, tuple, or iterable'): simulate_raw(raw.info, 0., trans, src, bem, None) # STC with a source that `src` does not have assert 0 not in src[0]['vertno'] vertices = [[0, fwd['src'][0]['vertno'][0]], []] stc_bad = SourceEstimate(data[:2], vertices, 0, 1. / raw.info['sfreq']) with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, trans, src, bem) assert 0 not in fwd['src'][0]['vertno'] with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, None, None, None, forward=fwd) # dev_head_t mismatch fwd['info']['dev_head_t']['trans'][0, 0] = 1. with pytest.raises(ValueError, match='dev_head_t.*does not match'): simulate_raw(raw.info, stc, None, None, None, forward=fwd)
def test_combine_source_spaces(tmpdir): """Test combining source spaces.""" import nibabel as nib rng = np.random.RandomState(2) volume_labels = ['Brain-Stem', 'Right-Hippocampus'] # two fairly large # create a sparse surface source space to ensure all get mapped # when mri_resolution=False srf = setup_source_space('sample', 'oct3', add_dist=False, subjects_dir=subjects_dir) # setup 2 volume source spaces vol = setup_volume_source_space('sample', subjects_dir=subjects_dir, volume_label=volume_labels[0], mri=aseg_fname, add_interpolator=False) # setup a discrete source space rr = rng.randint(0, 11, (20, 3)) * 5e-3 nn = np.zeros(rr.shape) nn[:, -1] = 1 pos = {'rr': rr, 'nn': nn} disc = setup_volume_source_space('sample', subjects_dir=subjects_dir, pos=pos, verbose='error') # combine source spaces assert srf.kind == 'surface' assert vol.kind == 'volume' assert disc.kind == 'discrete' src = srf + vol + disc assert src.kind == 'mixed' assert srf.kind == 'surface' assert vol.kind == 'volume' assert disc.kind == 'discrete' # test addition of source spaces assert len(src) == 4 # test reading and writing src_out_name = tmpdir.join('temp-src.fif') src.save(src_out_name) src_from_file = read_source_spaces(src_out_name) _compare_source_spaces(src, src_from_file, mode='approx') assert repr(src).split('~')[0] == repr(src_from_file).split('~')[0] assert_equal(src.kind, 'mixed') # test that all source spaces are in MRI coordinates coord_frames = np.array([s['coord_frame'] for s in src]) assert (coord_frames == FIFF.FIFFV_COORD_MRI).all() # test errors for export_volume image_fname = tmpdir.join('temp-image.mgz') # source spaces with no volume with pytest.raises(ValueError, match='at least one volume'): srf.export_volume(image_fname, verbose='error') # unrecognized source type disc2 = disc.copy() disc2[0]['type'] = 'kitty' with pytest.raises(ValueError, match='Invalid value'): src + disc2 del disc2 # unrecognized file type bad_image_fname = tmpdir.join('temp-image.png') # vertices outside vol space warning pytest.raises(ValueError, src.export_volume, bad_image_fname, verbose='error') # mixed coordinate frames disc3 = disc.copy() disc3[0]['coord_frame'] = 10 src_mixed_coord = src + disc3 with pytest.raises(ValueError, match='must be in head coordinates'): src_mixed_coord.export_volume(image_fname, verbose='error') # now actually write it fname_img = tmpdir.join('img.nii') for mri_resolution in (False, 'sparse', True): for src, up in ((vol, 705), (srf + vol, 27272), (disc + vol, 705)): src.export_volume(fname_img, use_lut=False, mri_resolution=mri_resolution, overwrite=True) img_data = _get_img_fdata(nib.load(str(fname_img))) n_src = img_data.astype(bool).sum() n_want = sum(s['nuse'] for s in src) if mri_resolution is True: n_want += up assert n_src == n_want, src # gh-8004 temp_aseg = tmpdir.join('aseg.mgz') aseg_img = nib.load(aseg_fname) aseg_affine = aseg_img.affine aseg_affine[:3, :3] *= 0.7 new_aseg = nib.MGHImage(aseg_img.dataobj, aseg_affine) nib.save(new_aseg, str(temp_aseg)) lh_cereb = mne.setup_volume_source_space( "sample", mri=temp_aseg, volume_label="Left-Cerebellum-Cortex", add_interpolator=False, subjects_dir=subjects_dir) src = srf + lh_cereb with pytest.warns(RuntimeWarning, match='2 surf vertices lay outside'): src.export_volume(image_fname, mri_resolution="sparse", overwrite=True)
def test_combine_source_spaces(tmpdir): """Test combining source spaces.""" aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz') label_names = get_volume_labels_from_aseg(aseg_fname) volume_labels = [ label_names[int(np.random.rand() * len(label_names))] for ii in range(2) ] # get a surface source space (no need to test creation here) srf = read_source_spaces(fname, patch_stats=False) # setup 2 volume source spaces vol = setup_volume_source_space('sample', subjects_dir=subjects_dir, volume_label=volume_labels[0], mri=aseg_fname, add_interpolator=False) # setup a discrete source space rr = rng.randint(0, 20, (100, 3)) * 1e-3 nn = np.zeros(rr.shape) nn[:, -1] = 1 pos = {'rr': rr, 'nn': nn} disc = setup_volume_source_space('sample', subjects_dir=subjects_dir, pos=pos, verbose='error') # combine source spaces src = srf + vol + disc # test addition of source spaces assert_equal(type(src), SourceSpaces) assert_equal(len(src), 4) # test reading and writing src_out_name = tmpdir.join('temp-src.fif') src.save(src_out_name) src_from_file = read_source_spaces(src_out_name) _compare_source_spaces(src, src_from_file, mode='approx') assert_equal(repr(src), repr(src_from_file)) assert_equal(src.kind, 'mixed') # test that all source spaces are in MRI coordinates coord_frames = np.array([s['coord_frame'] for s in src]) assert (coord_frames == FIFF.FIFFV_COORD_MRI).all() # test errors for export_volume image_fname = tmpdir.join('temp-image.mgz') # source spaces with no volume pytest.raises(ValueError, srf.export_volume, image_fname, verbose='error') # unrecognized source type disc2 = disc.copy() disc2[0]['type'] = 'kitty' src_unrecognized = src + disc2 pytest.raises(ValueError, src_unrecognized.export_volume, image_fname, verbose='error') # unrecognized file type bad_image_fname = tmpdir.join('temp-image.png') # vertices outside vol space warning pytest.raises(ValueError, src.export_volume, bad_image_fname, verbose='error') # mixed coordinate frames disc3 = disc.copy() disc3[0]['coord_frame'] = 10 src_mixed_coord = src + disc3 pytest.raises(ValueError, src_mixed_coord.export_volume, image_fname, verbose='error')