def test_read_write_info(): """Test IO of info """ tempdir = _TempDir() info = read_info(raw_fname) temp_file = op.join(tempdir, 'info.fif') # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 = info2['dev_head_t']['trans'] assert_true(len(info['chs']) == len(info2['chs'])) assert_array_equal(t1, t2) # proc_history (e.g., GH#1875) creator = u'é' info = read_info(chpi_fname) info['proc_history'][0]['creator'] = creator info['hpi_meas'][0]['creator'] = creator info['subject_info']['his_id'] = creator write_info(temp_file, info) info = read_info(temp_file) assert_equal(info['proc_history'][0]['creator'], creator) assert_equal(info['hpi_meas'][0]['creator'], creator) assert_equal(info['subject_info']['his_id'], creator)
def test_read_write_info(): """Test IO of info.""" tempdir = _TempDir() info = read_info(raw_fname) temp_file = op.join(tempdir, 'info.fif') # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 = info2['dev_head_t']['trans'] assert_true(len(info['chs']) == len(info2['chs'])) assert_array_equal(t1, t2) # proc_history (e.g., GH#1875) creator = u'é' info = read_info(chpi_fname) info['proc_history'][0]['creator'] = creator info['hpi_meas'][0]['creator'] = creator info['subject_info']['his_id'] = creator if info['gantry_angle'] is None: # future testing data may include it info['gantry_angle'] = 0. # Elekta supine position gantry_angle = info['gantry_angle'] write_info(temp_file, info) info = read_info(temp_file) assert_equal(info['proc_history'][0]['creator'], creator) assert_equal(info['hpi_meas'][0]['creator'], creator) assert_equal(info['subject_info']['his_id'], creator) assert_equal(info['gantry_angle'], gantry_angle)
def test_csr_csc(): """Test CSR and CSC.""" info = read_info(sss_ctc_fname) info = pick_info(info, pick_types(info, meg=True, exclude=[])) sss_ctc = info['proc_history'][0]['max_info']['sss_ctc'] ct = sss_ctc['decoupler'].copy() # CSC assert isinstance(ct, sparse.csc_matrix) tempdir = _TempDir() fname = op.join(tempdir, 'test.fif') write_info(fname, info) info_read = read_info(fname) ct_read = info_read['proc_history'][0]['max_info']['sss_ctc']['decoupler'] assert isinstance(ct_read, sparse.csc_matrix) assert_array_equal(ct_read.toarray(), ct.toarray()) # Now CSR csr = ct.tocsr() assert isinstance(csr, sparse.csr_matrix) assert_array_equal(csr.toarray(), ct.toarray()) info['proc_history'][0]['max_info']['sss_ctc']['decoupler'] = csr fname = op.join(tempdir, 'test1.fif') write_info(fname, info) info_read = read_info(fname) ct_read = info_read['proc_history'][0]['max_info']['sss_ctc']['decoupler'] assert isinstance(ct_read, sparse.csc_matrix) # this gets cast to CSC assert_array_equal(ct_read.toarray(), ct.toarray())
def test_helmet(): """Test loading helmet surfaces.""" base_dir = op.join(op.dirname(__file__), '..', 'io') fname_raw = op.join(base_dir, 'tests', 'data', 'test_raw.fif') fname_kit_raw = op.join(base_dir, 'kit', 'tests', 'data', 'test_bin_raw.fif') fname_bti_raw = op.join(base_dir, 'bti', 'tests', 'data', 'exported4D_linux_raw.fif') fname_ctf_raw = op.join(base_dir, 'tests', 'data', 'test_ctf_raw.fif') fname_trans = op.join(base_dir, 'tests', 'data', 'sample-audvis-raw-trans.txt') trans = _get_trans(fname_trans)[0] new_info = read_info(fname_raw) artemis_info = new_info.copy() for pick in pick_types(new_info): new_info['chs'][pick]['coil_type'] = 9999 artemis_info['chs'][pick]['coil_type'] = \ FIFF.FIFFV_COIL_ARTEMIS123_GRAD for info, n, name in [(read_info(fname_raw), 304, '306m'), (read_info(fname_kit_raw), 304, 'KIT'), (read_info(fname_bti_raw), 304, 'Magnes'), (read_info(fname_ctf_raw), 342, 'CTF'), (new_info, 102, 'unknown'), (artemis_info, 102, 'ARTEMIS123') ]: with catch_logging() as log: helmet = get_meg_helmet_surf(info, trans, verbose=True) log = log.getvalue() assert name in log assert_equal(len(helmet['rr']), n) assert_equal(len(helmet['rr']), len(helmet['nn']))
def test_read_write_info(): """Test IO of info.""" tempdir = _TempDir() info = read_info(raw_fname) temp_file = op.join(tempdir, 'info.fif') # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 = info2['dev_head_t']['trans'] assert (len(info['chs']) == len(info2['chs'])) assert_array_equal(t1, t2) # proc_history (e.g., GH#1875) creator = u'é' info = read_info(chpi_fname) info['proc_history'][0]['creator'] = creator info['hpi_meas'][0]['creator'] = creator info['subject_info']['his_id'] = creator info['subject_info']['weight'] = 11.1 info['subject_info']['height'] = 2.3 if info['gantry_angle'] is None: # future testing data may include it info['gantry_angle'] = 0. # Elekta supine position gantry_angle = info['gantry_angle'] meas_id = info['meas_id'] write_info(temp_file, info) info = read_info(temp_file) assert info['proc_history'][0]['creator'] == creator assert info['hpi_meas'][0]['creator'] == creator assert info['subject_info']['his_id'] == creator assert info['gantry_angle'] == gantry_angle assert info['subject_info']['height'] == 2.3 assert info['subject_info']['weight'] == 11.1 for key in ['secs', 'usecs', 'version']: assert info['meas_id'][key] == meas_id[key] assert_array_equal(info['meas_id']['machid'], meas_id['machid']) # Test that writing twice produces the same file m1 = hashlib.md5() with open(temp_file, 'rb') as fid: m1.update(fid.read()) m1 = m1.hexdigest() temp_file_2 = op.join(tempdir, 'info2.fif') assert temp_file_2 != temp_file write_info(temp_file_2, info) m2 = hashlib.md5() with open(temp_file_2, 'rb') as fid: m2.update(fid.read()) m2 = m2.hexdigest() assert m1 == m2
def test_read_write_info(): """Test IO of info """ info = io.read_info(raw_fname) temp_file = op.join(tempdir, 'info.fif') # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] io.write_info(temp_file, info) info2 = io.read_info(temp_file) t2 = info2['dev_head_t']['trans'] assert_true(len(info['chs']) == len(info2['chs'])) assert_array_equal(t1, t2)
def test_make_sphere_model(): """Test making a sphere model.""" info = read_info(fname_raw) pytest.raises(ValueError, make_sphere_model, 'foo', 'auto', info) pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', None) pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', info, relative_radii=(), sigmas=()) pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', info, relative_radii=(1,)) # wrong number of radii # here we just make sure it works -- the functionality is actually # tested more extensively e.g. in the forward and dipole code with catch_logging() as log: bem = make_sphere_model('auto', 'auto', info, verbose=True) log = log.getvalue() assert ' RV = ' in log for line in log.split('\n'): if ' RV = ' in line: val = float(line.split()[-2]) assert val < 0.01 # actually decent fitting break assert '3 layers' in repr(bem) assert 'Sphere ' in repr(bem) assert ' mm' in repr(bem) bem = make_sphere_model('auto', None, info) assert 'no layers' in repr(bem) assert 'Sphere ' in repr(bem) pytest.raises(ValueError, make_sphere_model, sigmas=(0.33,), relative_radii=(1.0,))
def test_priors(): """Test prior computations.""" # Depth prior fwd = read_forward_solution(fname_meeg) assert not is_fixed_orient(fwd) n_sources = fwd['nsource'] info = read_info(fname_evoked) depth_prior = compute_depth_prior(fwd, info, exp=0.8) assert depth_prior.shape == (3 * n_sources,) depth_prior = compute_depth_prior(fwd, info, exp=0.) assert_array_equal(depth_prior, 1.) with pytest.raises(ValueError, match='must be "whiten"'): compute_depth_prior(fwd, info, limit_depth_chs='foo') with pytest.raises(ValueError, match='noise_cov must be a Covariance'): compute_depth_prior(fwd, info, limit_depth_chs='whiten') fwd_fixed = convert_forward_solution(fwd, force_fixed=True) with pytest.deprecated_call(): depth_prior = compute_depth_prior( fwd_fixed['sol']['data'], info, is_fixed_ori=True) assert depth_prior.shape == (n_sources,) # Orientation prior orient_prior = compute_orient_prior(fwd, 1.) assert_array_equal(orient_prior, 1.) orient_prior = compute_orient_prior(fwd_fixed, 0.) assert_array_equal(orient_prior, 1.) with pytest.raises(ValueError, match='oriented in surface coordinates'): compute_orient_prior(fwd, 0.5) fwd_surf_ori = convert_forward_solution(fwd, surf_ori=True) orient_prior = compute_orient_prior(fwd_surf_ori, 0.5) assert all(np.in1d(orient_prior, (0.5, 1.))) with pytest.raises(ValueError, match='between 0 and 1'): compute_orient_prior(fwd_surf_ori, -0.5) with pytest.raises(ValueError, match='with fixed orientation'): compute_orient_prior(fwd_fixed, 0.5)
def test_rename_channels(): """Test rename channels""" info = read_info(raw_fname) # Error Tests # Test channel name exists in ch_names mapping = {'EEG 160': 'EEG060'} assert_raises(ValueError, rename_channels, info, mapping) # Test improper mapping configuration mapping = {'MEG 2641': 1.0} assert_raises(ValueError, rename_channels, info, mapping) # Test non-unique mapping configuration mapping = {'MEG 2641': 'MEG 2642'} assert_raises(ValueError, rename_channels, info, mapping) # Test bad input assert_raises(ValueError, rename_channels, info, 1.) # Test successful changes # Test ch_name and ch_names are changed info2 = deepcopy(info) # for consistency at the start of each test info2['bads'] = ['EEG 060', 'EOG 061'] mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'} rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EEG060') assert_true(info2['ch_names'][374] == 'EEG060') assert_true(info2['chs'][375]['ch_name'] == 'EOG061') assert_true(info2['ch_names'][375] == 'EOG061') assert_array_equal(['EEG060', 'EOG061'], info2['bads']) info2 = deepcopy(info) rename_channels(info2, lambda x: x.replace(' ', '')) assert_true(info2['chs'][373]['ch_name'] == 'EEG059') info2 = deepcopy(info) info2['bads'] = ['EEG 060', 'EEG 060'] rename_channels(info2, mapping) assert_array_equal(['EEG060', 'EEG060'], info2['bads'])
def test_head_translation(): """Test Maxwell filter head translation""" with warnings.catch_warnings(record=True): # maxshield raw = Raw(raw_fname, allow_maxshield=True).crop(0., 1., False) # First try with an unchanged destination raw_sss = maxwell_filter(raw, destination=raw_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore') assert_meg_snr(raw_sss, Raw(sss_std_fname).crop(0., 1., False), 200.) # Now with default with warnings.catch_warnings(record=True): with catch_logging() as log: raw_sss = maxwell_filter(raw, destination=mf_head_origin, origin=mf_head_origin, regularize=None, bad_condition='ignore', verbose='warning') assert_true('over 25 mm' in log.getvalue()) assert_meg_snr(raw_sss, Raw(sss_trans_default_fname), 125.) destination = np.eye(4) destination[2, 3] = 0.04 assert_allclose(raw_sss.info['dev_head_t']['trans'], destination) # Now to sample's head pos with warnings.catch_warnings(record=True): with catch_logging() as log: raw_sss = maxwell_filter(raw, destination=sample_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore', verbose='warning') assert_true('= 25.6 mm' in log.getvalue()) assert_meg_snr(raw_sss, Raw(sss_trans_sample_fname), 350.) assert_allclose(raw_sss.info['dev_head_t']['trans'], read_info(sample_fname)['dev_head_t']['trans']) # Degenerate cases assert_raises(RuntimeError, maxwell_filter, raw, destination=mf_head_origin, coord_frame='meg') assert_raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
def test_head_translation(): """Test Maxwell filter head translation.""" raw = read_crop(raw_fname, (0., 1.)) # First try with an unchanged destination with use_coil_def(elekta_def_fname): raw_sss = maxwell_filter(raw, destination=raw_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore') assert_meg_snr(raw_sss, read_crop(sss_std_fname, (0., 1.)), 200.) # Now with default with use_coil_def(elekta_def_fname): with pytest.warns(RuntimeWarning, match='over 25 mm'): raw_sss = maxwell_filter(raw, destination=mf_head_origin, origin=mf_head_origin, regularize=None, bad_condition='ignore', verbose=True) assert_meg_snr(raw_sss, read_crop(sss_trans_default_fname), 125.) destination = np.eye(4) destination[2, 3] = 0.04 assert_allclose(raw_sss.info['dev_head_t']['trans'], destination) # Now to sample's head pos with pytest.warns(RuntimeWarning, match='= 25.6 mm'): raw_sss = maxwell_filter(raw, destination=sample_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore', verbose=True) assert_meg_snr(raw_sss, read_crop(sss_trans_sample_fname), 13., 100.) assert_allclose(raw_sss.info['dev_head_t']['trans'], read_info(sample_fname)['dev_head_t']['trans']) # Degenerate cases pytest.raises(RuntimeError, maxwell_filter, raw, destination=mf_head_origin, coord_frame='meg') pytest.raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
def test_rename_channels(): """Test rename channels """ info = read_info(raw_fname) # Error Tests # Test channel name exists in ch_names mapping = {'EEG 160': 'EEG060'} assert_raises(ValueError, rename_channels, info, mapping) # Test change to EEG channel mapping = {'EOG 061': ('EEG 061', 'eeg')} with warnings.catch_warnings(record=True): assert_raises(ValueError, rename_channels, info, mapping) # Test change to illegal channel type mapping = {'EOG 061': ('MEG 061', 'meg')} with warnings.catch_warnings(record=True): assert_raises(ValueError, rename_channels, info, mapping) # Test channel type which you are changing from e.g. MEG mapping = {'MEG 2641': ('MEG2641', 'eeg')} with warnings.catch_warnings(record=True): assert_raises(ValueError, rename_channels, info, mapping) # Test improper mapping configuration mapping = {'MEG 2641': 1.0} assert_raises(ValueError, rename_channels, info, mapping) # Test successful changes # Test ch_name and ch_names are changed info2 = deepcopy(info) # for consistency at the start of each test info2['bads'] = ['EEG 060', 'EOG 061'] mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'} rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EEG060') assert_true(info2['ch_names'][374] == 'EEG060') assert_true('EEG060' in info2['bads']) assert_true(info2['chs'][375]['ch_name'] == 'EOG061') assert_true(info2['ch_names'][375] == 'EOG061') assert_true('EOG061' in info2['bads'])
def test_make_sphere_model(): """Test making a sphere model""" info = read_info(fname_raw) assert_raises(ValueError, make_sphere_model, 'foo', 'auto', info) assert_raises(ValueError, make_sphere_model, 'auto', 'auto', None) # here we just make sure it works -- the functionality is actually # tested more extensively e.g. in the forward and dipole code make_sphere_model('auto', 'auto', info)
def test_multipolar_bases(): """Test multipolar moment basis calculation using sensor information.""" from scipy.io import loadmat # Test our basis calculations info = read_info(raw_fname) with use_coil_def(elekta_def_fname): coils = _prep_meg_channels(info, accurate=True, do_es=True)[0] # Check against a known benchmark sss_data = loadmat(bases_fname) exp = dict(int_order=int_order, ext_order=ext_order) for origin in ((0, 0, 0.04), (0, 0.02, 0.02)): o_str = ''.join('%d' % (1000 * n) for n in origin) exp.update(origin=origin) S_tot = _sss_basis_basic(exp, coils, method='alternative') # Test our real<->complex conversion functions S_tot_complex = _bases_real_to_complex(S_tot, int_order, ext_order) S_tot_round = _bases_complex_to_real(S_tot_complex, int_order, ext_order) assert_allclose(S_tot, S_tot_round, atol=1e-7) S_tot_mat = np.concatenate([sss_data['Sin' + o_str], sss_data['Sout' + o_str]], axis=1) S_tot_mat_real = _bases_complex_to_real(S_tot_mat, int_order, ext_order) S_tot_mat_round = _bases_real_to_complex(S_tot_mat_real, int_order, ext_order) assert_allclose(S_tot_mat, S_tot_mat_round, atol=1e-7) assert_allclose(S_tot_complex, S_tot_mat, rtol=1e-4, atol=1e-8) assert_allclose(S_tot, S_tot_mat_real, rtol=1e-4, atol=1e-8) # Now normalize our columns S_tot /= np.sqrt(np.sum(S_tot * S_tot, axis=0))[np.newaxis] S_tot_complex /= np.sqrt(np.sum( (S_tot_complex * S_tot_complex.conj()).real, axis=0))[np.newaxis] # Check against a known benchmark S_tot_mat = np.concatenate([sss_data['SNin' + o_str], sss_data['SNout' + o_str]], axis=1) # Check this roundtrip S_tot_mat_real = _bases_complex_to_real(S_tot_mat, int_order, ext_order) S_tot_mat_round = _bases_real_to_complex(S_tot_mat_real, int_order, ext_order) assert_allclose(S_tot_mat, S_tot_mat_round, atol=1e-7) assert_allclose(S_tot_complex, S_tot_mat, rtol=1e-4, atol=1e-8) # Now test our optimized version S_tot = _sss_basis_basic(exp, coils) with use_coil_def(elekta_def_fname): S_tot_fast = _trans_sss_basis( exp, all_coils=_prep_mf_coils(info), trans=info['dev_head_t']) # there are some sign differences for columns (order/degrees) # in here, likely due to Condon-Shortley. Here we use a # Magnetometer channel to figure out the flips because the # gradiometer channels have effectively zero values for first three # external components (i.e., S_tot[grad_picks, 80:83]) flips = (np.sign(S_tot_fast[2]) != np.sign(S_tot[2])) flips = 1 - 2 * flips assert_allclose(S_tot, S_tot_fast * flips, atol=1e-16)
def test_merge_info(): """Test merging of multiple Info objects.""" info_a = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.) info_b = create_info(ch_names=['d', 'e', 'f'], sfreq=1000.) info_merged = _merge_info([info_a, info_b]) assert info_merged['nchan'], 6 assert info_merged['ch_names'], ['a', 'b', 'c', 'd', 'e', 'f'] pytest.raises(ValueError, _merge_info, [info_a, info_a]) # Testing for force updates before merging info_c = create_info(ch_names=['g', 'h', 'i'], sfreq=500.) # This will break because sfreq is not equal pytest.raises(RuntimeError, _merge_info, [info_a, info_c]) _force_update_info(info_a, info_c) assert (info_c['sfreq'] == info_a['sfreq']) assert (info_c['ch_names'][0] != info_a['ch_names'][0]) # Make sure it works now _merge_info([info_a, info_c]) # Check that you must supply Info pytest.raises(ValueError, _force_update_info, info_a, dict([('sfreq', 1000.)])) # KIT System-ID info_a._unlocked = info_b._unlocked = True info_a['kit_system_id'] = 50 assert _merge_info((info_a, info_b))['kit_system_id'] == 50 info_b['kit_system_id'] = 50 assert _merge_info((info_a, info_b))['kit_system_id'] == 50 info_b['kit_system_id'] = 60 pytest.raises(ValueError, _merge_info, (info_a, info_b)) # hpi infos info_d = create_info(ch_names=['d', 'e', 'f'], sfreq=1000.) info_merged = _merge_info([info_a, info_d]) assert not info_merged['hpi_meas'] assert not info_merged['hpi_results'] info_a['hpi_meas'] = [{'f1': 3, 'f2': 4}] assert _merge_info([info_a, info_d])['hpi_meas'] == info_a['hpi_meas'] info_d._unlocked = True info_d['hpi_meas'] = [{'f1': 3, 'f2': 4}] assert _merge_info([info_a, info_d])['hpi_meas'] == info_d['hpi_meas'] # This will break because of inconsistency info_d['hpi_meas'] = [{'f1': 3, 'f2': 5}] pytest.raises(ValueError, _merge_info, [info_a, info_d]) info_0 = read_info(raw_fname) info_0['bads'] = ['MEG 2443', 'EEG 053'] assert len(info_0['chs']) == 376 assert len(info_0['dig']) == 146 info_1 = create_info(["STI YYY"], info_0['sfreq'], ['stim']) assert info_1['bads'] == [] info_out = _merge_info([info_0, info_1], force_update_to_first=True) assert len(info_out['chs']) == 377 assert len(info_out['bads']) == 2 assert len(info_out['dig']) == 146 assert len(info_0['chs']) == 376 assert len(info_0['bads']) == 2 assert len(info_0['dig']) == 146
def test_hpi_info(tmpdir): """Test getting HPI info.""" temp_name = op.join(str(tmpdir), 'temp_raw.fif') for fname in (chpi_fif_fname, sss_fif_fname): raw = read_raw_fif(fname, allow_maxshield='yes').crop(0, 0.1) assert len(raw.info['hpi_subsystem']) > 0 raw.save(temp_name, overwrite=True) info = read_info(temp_name) assert len(info['hpi_subsystem']) == len(raw.info['hpi_subsystem'])
def test_pick_chpi(): """Test picking cHPI.""" # Make sure we don't mis-classify cHPI channels info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif')) _assert_channel_types(info) channel_types = {channel_type(info, idx) for idx in range(info['nchan'])} assert 'chpi' in channel_types assert 'seeg' not in channel_types assert 'ecog' not in channel_types
def test_pick_chpi(): """Test picking cHPI """ # Make sure we don't mis-classify cHPI channels info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif')) channel_types = set([channel_type(info, idx) for idx in range(info['nchan'])]) assert_true('chpi' in channel_types) assert_true('seeg' not in channel_types)
def test_pick_chpi(): """Test picking cHPI.""" # Make sure we don't mis-classify cHPI channels info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif')) channel_types = set([channel_type(info, idx) for idx in range(info['nchan'])]) assert_true('chpi' in channel_types) assert_true('seeg' not in channel_types) assert_true('ecog' not in channel_types)
def test_multipolar_bases(): """Test multipolar moment basis calculation using sensor information""" from scipy.io import loadmat # Test our basis calculations info = read_info(raw_fname) coils = _prep_meg_channels(info, accurate=True, elekta_defs=True, do_es=True)[0] # Check against a known benchmark sss_data = loadmat(bases_fname) exp = dict(int_order=int_order, ext_order=ext_order) for origin in ((0, 0, 0.04), (0, 0.02, 0.02)): o_str = ''.join('%d' % (1000 * n) for n in origin) exp.update(origin=origin) S_tot = _sss_basis_basic(exp, coils, method='alternative') # Test our real<->complex conversion functions S_tot_complex = _bases_real_to_complex(S_tot, int_order, ext_order) S_tot_round = _bases_complex_to_real(S_tot_complex, int_order, ext_order) assert_allclose(S_tot, S_tot_round, atol=1e-7) S_tot_mat = np.concatenate([sss_data['Sin' + o_str], sss_data['Sout' + o_str]], axis=1) S_tot_mat_real = _bases_complex_to_real(S_tot_mat, int_order, ext_order) S_tot_mat_round = _bases_real_to_complex(S_tot_mat_real, int_order, ext_order) assert_allclose(S_tot_mat, S_tot_mat_round, atol=1e-7) assert_allclose(S_tot_complex, S_tot_mat, rtol=1e-4, atol=1e-8) assert_allclose(S_tot, S_tot_mat_real, rtol=1e-4, atol=1e-8) # Now normalize our columns S_tot /= np.sqrt(np.sum(S_tot * S_tot, axis=0))[np.newaxis] S_tot_complex /= np.sqrt(np.sum( (S_tot_complex * S_tot_complex.conj()).real, axis=0))[np.newaxis] # Check against a known benchmark S_tot_mat = np.concatenate([sss_data['SNin' + o_str], sss_data['SNout' + o_str]], axis=1) # Check this roundtrip S_tot_mat_real = _bases_complex_to_real(S_tot_mat, int_order, ext_order) S_tot_mat_round = _bases_real_to_complex(S_tot_mat_real, int_order, ext_order) assert_allclose(S_tot_mat, S_tot_mat_round, atol=1e-7) assert_allclose(S_tot_complex, S_tot_mat, rtol=1e-4, atol=1e-8) # Now test our optimized version S_tot = _sss_basis_basic(exp, coils) S_tot_fast = _trans_sss_basis( exp, all_coils=_prep_mf_coils(info), trans=info['dev_head_t']) # there are some sign differences for columns (order/degrees) # in here, likely due to Condon-Shortley. Here we use a # Magnetometer channel to figure out the flips because the # gradiometer channels have effectively zero values for first three # external components (i.e., S_tot[grad_picks, 80:83]) flips = (np.sign(S_tot_fast[2]) != np.sign(S_tot[2])) flips = 1 - 2 * flips assert_allclose(S_tot, S_tot_fast * flips, atol=1e-16)
def test_pick_chpi(): """Test picking cHPI.""" # Make sure we don't mis-classify cHPI channels info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif')) _assert_channel_types(info) channel_types = _get_channel_types(info) assert 'chpi' in channel_types assert 'seeg' not in channel_types assert 'ecog' not in channel_types
def test_anonymize(tmpdir): """Test mne anonymize.""" check_usage(mne_anonymize) out_fname = op.join(tmpdir, 'anon_test_raw.fif') with ArgvSetter(('-f', raw_fname, '-o', out_fname)): mne_anonymize.run() info = read_info(out_fname) assert(op.exists(out_fname)) assert_equal(info['meas_date'], (946684800, 0))
def test_rename_channels(): """Test rename channels """ info = read_info(raw_fname) # Error Tests # Test channel name exists in ch_names mapping = {'EEG 160': 'EEG060'} assert_raises(ValueError, rename_channels, info, mapping) # Test change to EEG channel mapping = {'EOG 061': ('EEG 061', 'eeg')} assert_raises(ValueError, rename_channels, info, mapping) # Test change to illegal channel type mapping = {'EOG 061': ('MEG 061', 'meg')} assert_raises(ValueError, rename_channels, info, mapping) # Test channel type which you are changing from e.g. MEG mapping = {'MEG 2641': ('MEG2641', 'eeg')} assert_raises(ValueError, rename_channels, info, mapping) # Test improper mapping configuration mapping = {'MEG 2641': 1.0} assert_raises(ValueError, rename_channels, info, mapping) # Test duplicate named channels mapping = {'EEG 060': 'EOG 061'} assert_raises(ValueError, rename_channels, info, mapping) # Test successful changes # Test ch_name and ch_names are changed info2 = deepcopy(info) # for consistency at the start of each test info2['bads'] = ['EEG 060', 'EOG 061'] mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'} rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EEG060') assert_true(info2['ch_names'][374] == 'EEG060') assert_true('EEG060' in info2['bads']) assert_true(info2['chs'][375]['ch_name'] == 'EOG061') assert_true(info2['ch_names'][375] == 'EOG061') assert_true('EOG061' in info2['bads']) # Test type change info2 = deepcopy(info) info2['bads'] = ['EEG 059', 'EEG 060', 'EOG 061'] mapping = { 'EEG 060': ('EOG 060', 'eog'), 'EEG 059': ('EOG 059', 'eog'), 'EOG 061': ("OT'7", 'seeg') } rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EOG 060') assert_true(info2['ch_names'][374] == 'EOG 060') assert_true('EOG 060' in info2['bads']) assert_true(info2['chs'][374]['kind'] is FIFF.FIFFV_EOG_CH) assert_true(info2['chs'][373]['ch_name'] == 'EOG 059') assert_true(info2['ch_names'][373] == 'EOG 059') assert_true('EOG 059' in info2['bads']) assert_true(info2['chs'][373]['kind'] is FIFF.FIFFV_EOG_CH) assert_true(info2['chs'][375]['ch_name'] == "OT'7") assert_true(info2['ch_names'][375] == "OT'7") assert_true("OT'7" in info2['bads']) assert_true(info2['chs'][375]['kind'] is FIFF.FIFFV_SEEG_CH)
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info["bads"] += ["MEG 0113"] ch_names = [info["ch_names"][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose="error")
def test_io_coord_frame(tmp_path): """Test round trip for coordinate frame.""" fname = tmp_path / 'test.fif' for ch_type in ('eeg', 'seeg', 'ecog', 'dbs', 'hbo', 'hbr'): info = create_info( ch_names=['Test Ch'], sfreq=1000., ch_types=[ch_type]) info['chs'][0]['loc'][:3] = [0.05, 0.01, -0.03] write_info(fname, info) info2 = read_info(fname) assert info2['chs'][0]['coord_frame'] == FIFF.FIFFV_COORD_HEAD
def test_plot_projs_topomap(): """Test plot_projs_topomap.""" projs = read_proj(ecg_fname) info = read_info(raw_fname) fast_test = {"res": 8, "contours": 0, "sensors": False} plot_projs_topomap(projs, info=info, colorbar=True, **fast_test) plt.close('all') ax = plt.subplot(111) projs[3].plot_topomap() plot_projs_topomap(projs[:1], axes=ax, **fast_test) # test axes param plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test) plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][:1], **fast_test) plt.close('all') eeg_avg = make_eeg_average_ref_proj(info) pytest.raises(RuntimeError, eeg_avg.plot_topomap) # no layout eeg_avg.plot_topomap(info=info, **fast_test) plt.close('all')
def test_plot_projs_topomap(): """Test plot_projs_topomap.""" projs = read_proj(ecg_fname) info = read_info(raw_fname) fast_test = {"res": 8, "contours": 0, "sensors": False} plot_projs_topomap(projs, info=info, colorbar=True, **fast_test) plt.close('all') ax = plt.subplot(111) projs[3].plot_topomap() plot_projs_topomap(projs[:1], axes=ax, **fast_test) # test axes param plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test) plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test) plt.close('all') eeg_avg = make_eeg_average_ref_proj(info) pytest.raises(RuntimeError, eeg_avg.plot_topomap) # no layout eeg_avg.plot_topomap(info=info, **fast_test) plt.close('all')
def test_rename_channels(): """Test rename channels """ info = read_info(raw_fname) # Error Tests # Test channel name exists in ch_names mapping = {'EEG 160': 'EEG060'} assert_raises(ValueError, rename_channels, info, mapping) # Test change to EEG channel mapping = {'EOG 061': ('EEG 061', 'eeg')} assert_raises(ValueError, rename_channels, info, mapping) # Test change to illegal channel type mapping = {'EOG 061': ('MEG 061', 'meg')} assert_raises(ValueError, rename_channels, info, mapping) # Test channel type which you are changing from e.g. MEG mapping = {'MEG 2641': ('MEG2641', 'eeg')} assert_raises(ValueError, rename_channels, info, mapping) # Test improper mapping configuration mapping = {'MEG 2641': 1.0} assert_raises(ValueError, rename_channels, info, mapping) # Test successful changes # Test ch_name and ch_names are changed info2 = deepcopy(info) # for consistency at the start of each test info2['bads'] = ['EEG 060', 'EOG 061'] mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'} rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EEG060') assert_true(info2['ch_names'][374] == 'EEG060') assert_true('EEG060' in info2['bads']) assert_true(info2['chs'][375]['ch_name'] == 'EOG061') assert_true(info2['ch_names'][375] == 'EOG061') assert_true('EOG061' in info2['bads']) # Test type change info2 = deepcopy(info) info2['bads'] = ['EEG 059', 'EEG 060', 'EOG 061'] mapping = {'EEG 060': ('EOG 060', 'eog'), 'EEG 059': ('EOG 059', 'eog'), 'EOG 061': ("OT'7", 'seeg')} rename_channels(info2, mapping) assert_true(info2['chs'][374]['ch_name'] == 'EOG 060') assert_true(info2['ch_names'][374] == 'EOG 060') assert_true('EOG 060' in info2['bads']) assert_true(info2['chs'][374]['kind'] == FIFF.FIFFV_EOG_CH) assert_true(info2['chs'][373]['ch_name'] == 'EOG 059') assert_true(info2['ch_names'][373] == 'EOG 059') assert_true('EOG 059' in info2['bads']) assert_true(info2['chs'][373]['kind'] == FIFF.FIFFV_EOG_CH) assert_true(info2['chs'][375]['ch_name'] == "OT'7") assert_true(info2['ch_names'][375] == "OT'7") assert_true("OT'7" in info2['bads']) assert_true(info2['chs'][375]['kind'] == FIFF.FIFFV_SEEG_CH) # Test change of type without change of name mapping = {'EEG 060': ('EEG 060', 'seeg')} info2 = deepcopy(info) rename_channels(info2, mapping) assert_true(info2['chs'][374]['kind'] == FIFF.FIFFV_SEEG_CH)
def test_quaternions(): """Test quaternion calculations.""" rots = [np.eye(3)] for fname in [test_fif_fname, ctf_fname, hp_fif_fname]: rots += [read_info(fname)['dev_head_t']['trans'][:3, :3]] # nasty numerical cases rots += [ np.array([ [-0.99978541, -0.01873462, -0.00898756], [-0.01873462, 0.62565561, 0.77987608], [-0.00898756, 0.77987608, -0.62587152], ]) ] rots += [ np.array([ [0.62565561, -0.01873462, 0.77987608], [-0.01873462, -0.99978541, -0.00898756], [0.77987608, -0.00898756, -0.62587152], ]) ] rots += [ np.array([ [-0.99978541, -0.00898756, -0.01873462], [-0.00898756, -0.62587152, 0.77987608], [-0.01873462, 0.77987608, 0.62565561], ]) ] for rot in rots: assert_allclose(rot, quat_to_rot(rot_to_quat(rot)), rtol=1e-5, atol=1e-5) rot = rot[np.newaxis, np.newaxis, :, :] assert_allclose(rot, quat_to_rot(rot_to_quat(rot)), rtol=1e-5, atol=1e-5) # let's make sure our angle function works in some reasonable way for ii in range(3): for jj in range(3): a = np.zeros(3) b = np.zeros(3) a[ii] = 1. b[jj] = 1. expected = np.pi if ii != jj else 0. assert_allclose(_angle_between_quats(a, b), expected, atol=1e-5) y_180 = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1.]]) assert_allclose(_angle_between_quats(rot_to_quat(y_180), np.zeros(3)), np.pi) h_180_attitude_90 = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1.]]) assert_allclose( _angle_between_quats(rot_to_quat(h_180_attitude_90), np.zeros(3)), np.pi)
def test_merge_info(): """Test merging of multiple Info objects.""" info_a = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None) info_b = create_info(ch_names=['d', 'e', 'f'], sfreq=1000., ch_types=None) info_merged = _merge_info([info_a, info_b]) assert info_merged['nchan'], 6 assert info_merged['ch_names'], ['a', 'b', 'c', 'd', 'e', 'f'] pytest.raises(ValueError, _merge_info, [info_a, info_a]) # Testing for force updates before merging info_c = create_info(ch_names=['g', 'h', 'i'], sfreq=500., ch_types=None) # This will break because sfreq is not equal pytest.raises(RuntimeError, _merge_info, [info_a, info_c]) _force_update_info(info_a, info_c) assert (info_c['sfreq'] == info_a['sfreq']) assert (info_c['ch_names'][0] != info_a['ch_names'][0]) # Make sure it works now _merge_info([info_a, info_c]) # Check that you must supply Info pytest.raises(ValueError, _force_update_info, info_a, dict([('sfreq', 1000.)])) # KIT System-ID info_a['kit_system_id'] = 50 assert _merge_info((info_a, info_b))['kit_system_id'] == 50 info_b['kit_system_id'] = 50 assert _merge_info((info_a, info_b))['kit_system_id'] == 50 info_b['kit_system_id'] = 60 pytest.raises(ValueError, _merge_info, (info_a, info_b)) # hpi infos info_d = create_info(ch_names=['d', 'e', 'f'], sfreq=1000., ch_types=None) info_merged = _merge_info([info_a, info_d]) assert not info_merged['hpi_meas'] assert not info_merged['hpi_results'] info_a['hpi_meas'] = [{'f1': 3, 'f2': 4}] assert _merge_info([info_a, info_d])['hpi_meas'] == info_a['hpi_meas'] info_d['hpi_meas'] = [{'f1': 3, 'f2': 4}] assert _merge_info([info_a, info_d])['hpi_meas'] == info_d['hpi_meas'] # This will break because of inconsistency info_d['hpi_meas'] = [{'f1': 3, 'f2': 5}] pytest.raises(ValueError, _merge_info, [info_a, info_d]) info_0 = read_info(raw_fname) info_0['bads'] = ['MEG 2443', 'EEG 053'] assert len(info_0['chs']) == 376 assert len(info_0['dig']) == 146 info_1 = create_info(["STI XXX"], info_0['sfreq'], ['stim']) assert info_1['bads'] == [] info_out = _merge_info([info_0, info_1], force_update_to_first=True) assert len(info_out['chs']) == 377 assert len(info_out['bads']) == 2 assert len(info_out['dig']) == 146 assert len(info_0['chs']) == 376 assert len(info_0['bads']) == 2 assert len(info_0['dig']) == 146
def test_cov_order(): """Test covariance ordering""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) with warnings.catch_warnings(record=True): # no avg ref present prepare_noise_cov(cov, info, ch_names, verbose='error')
def test_pick_ref(): """Test picking ref_meg channels.""" info = read_info(ctf_fname) picks_by_type = [('stim', [0]), ('eog', [306, 307]), ('ecg', [308]), ('misc', [1]), ('mag', np.arange(31, 306)), ('ref_meg', np.arange(2, 31))] assert_indexing(info, picks_by_type, all_data=False) picks_by_type.append(('mag', np.concatenate([picks_by_type.pop(-1)[1], picks_by_type.pop(-1)[1]]))) assert_indexing(info, picks_by_type, ref_meg=True, all_data=False)
def test_auto_topomap_coords(): """Test mapping of coordinates in 3D space to 2D.""" info = read_info(fif_fname) picks = pick_types(info, meg=False, eeg=True, eog=False, stim=False) # Remove extra digitization point, so EEG digitization points match up # with the EEG channels del info['dig'][85] # Remove head origin from channel locations, so mapping with digitization # points yields the same result dig_kinds = (FIFF.FIFFV_POINT_CARDINAL, FIFF.FIFFV_POINT_EEG, FIFF.FIFFV_POINT_EXTRA) _, origin_head, _ = fit_sphere_to_headshape(info, dig_kinds, units='m') for ch in info['chs']: ch['loc'][:3] -= origin_head # Use channel locations l0 = _auto_topomap_coords(info, picks) # Remove electrode position information, use digitization points from now # on. for ch in info['chs']: ch['loc'].fill(np.nan) l1 = _auto_topomap_coords(info, picks) assert_allclose(l1, l0, atol=1e-3) # Test plotting mag topomap without channel locations: it should fail mag_picks = pick_types(info, meg='mag') pytest.raises(ValueError, _auto_topomap_coords, info, mag_picks) # Test function with too many EEG digitization points: it should fail info['dig'].append({'r': [1, 2, 3], 'kind': FIFF.FIFFV_POINT_EEG}) pytest.raises(ValueError, _auto_topomap_coords, info, picks) # Test function with too little EEG digitization points: it should fail info['dig'] = info['dig'][:-2] pytest.raises(ValueError, _auto_topomap_coords, info, picks) # Electrode positions must be unique info['dig'].append(info['dig'][-1]) pytest.raises(ValueError, _auto_topomap_coords, info, picks) # Test function without EEG digitization points: it should fail info['dig'] = [d for d in info['dig'] if d['kind'] != FIFF.FIFFV_POINT_EEG] pytest.raises(RuntimeError, _auto_topomap_coords, info, picks) # Test function without any digitization points, it should fail info['dig'] = None pytest.raises(RuntimeError, _auto_topomap_coords, info, picks) info['dig'] = [] pytest.raises(RuntimeError, _auto_topomap_coords, info, picks)
def test_auto_topomap_coords(): """Test mapping of coordinates in 3D space to 2D""" info = read_info(fif_fname) picks = pick_types(info, meg=False, eeg=True, eog=False, stim=False) # Remove extra digitization point, so EEG digitization points match up # with the EEG channels del info['dig'][85] # Remove head origin from channel locations, so mapping with digitization # points yields the same result dig_kinds = (FIFF.FIFFV_POINT_CARDINAL, FIFF.FIFFV_POINT_EEG, FIFF.FIFFV_POINT_EXTRA) _, origin_head, _ = fit_sphere_to_headshape(info, dig_kinds, units='m') for ch in info['chs']: ch['loc'][:3] -= origin_head # Use channel locations l0 = _auto_topomap_coords(info, picks) # Remove electrode position information, use digitization points from now # on. for ch in info['chs']: ch['loc'].fill(np.nan) l1 = _auto_topomap_coords(info, picks) assert_allclose(l1, l0, atol=1e-3) # Test plotting mag topomap without channel locations: it should fail mag_picks = pick_types(info, meg='mag') assert_raises(ValueError, _auto_topomap_coords, info, mag_picks) # Test function with too many EEG digitization points: it should fail info['dig'].append({'r': [1, 2, 3], 'kind': FIFF.FIFFV_POINT_EEG}) assert_raises(ValueError, _auto_topomap_coords, info, picks) # Test function with too little EEG digitization points: it should fail info['dig'] = info['dig'][:-2] assert_raises(ValueError, _auto_topomap_coords, info, picks) # Electrode positions must be unique info['dig'].append(info['dig'][-1]) assert_raises(ValueError, _auto_topomap_coords, info, picks) # Test function without EEG digitization points: it should fail info['dig'] = [d for d in info['dig'] if d['kind'] != FIFF.FIFFV_POINT_EEG] assert_raises(RuntimeError, _auto_topomap_coords, info, picks) # Test function without any digitization points, it should fail info['dig'] = None assert_raises(RuntimeError, _auto_topomap_coords, info, picks) info['dig'] = [] assert_raises(RuntimeError, _auto_topomap_coords, info, picks)
def test_hpi_info(): """Test getting HPI info.""" tempdir = _TempDir() temp_name = op.join(tempdir, 'temp_raw.fif') for fname in (chpi_fif_fname, sss_fif_fname): raw = read_raw_fif(fname, allow_maxshield='yes').crop(0, 0.1) assert_true(len(raw.info['hpi_subsystem']) > 0) raw.save(temp_name, overwrite=True) info = read_info(temp_name) assert_equal(len(info['hpi_subsystem']), len(raw.info['hpi_subsystem']))
def test_plot_topomap_bads_grad(): """Test plotting topomap with bad gradiometer channels (gh-8802).""" import matplotlib.pyplot as plt data = np.random.RandomState(0).randn(203) info = read_info(evoked_fname) info['bads'] = ['MEG 2242'] picks = pick_types(info, meg='grad') info = pick_info(info, picks) assert len(info['chs']) == 203 plot_topomap(data, info, res=8) plt.close('all')
def test_quaternions(): """Test quaternion calculations """ rots = [np.eye(3)] for fname in [test_fif_fname, ctf_fname, hp_fif_fname]: rots += [read_info(fname)['dev_head_t']['trans'][:3, :3]] for rot in rots: assert_allclose(rot, _quat_to_rot(_rot_to_quat(rot)), rtol=1e-5, atol=1e-5) rot = rot[np.newaxis, np.newaxis, :, :] assert_allclose(rot, _quat_to_rot(_rot_to_quat(rot)), rtol=1e-5, atol=1e-5)
def test_plot_alignment_surf(renderer): """Test plotting of a surface.""" info = read_info(evoked_fname) fig = plot_alignment(info, read_trans(trans_fname), subject='sample', subjects_dir=subjects_dir, meg=False, eeg=False, dig=False, surfaces=['white', 'head']) _assert_n_actors(fig, renderer, 3) # left and right hemis plus head
def test_dig_mri_distances(dig_kinds, exclude, count, bounds, outliers): """Test the trans obtained by coregistration.""" info = read_info(fname_raw) dists = dig_mri_distances(info, fname_trans, 'sample', subjects_dir, dig_kinds=dig_kinds, exclude_frontal=exclude) assert dists.shape == (count, ) assert bounds[0] < np.mean(dists) < bounds[1] assert np.sum(dists > 0.03) == outliers
def test_pickle(fname_info, unlocked): """Test that Info can be (un)pickled.""" if fname_info == 'create_info': info = create_info(3, 1000., 'eeg') else: info = read_info(fname_info) assert not info._unlocked info._unlocked = unlocked data = pickle.dumps(info) info_un = pickle.loads(data) assert isinstance(info_un, Info) assert_object_equal(info, info_un) assert info_un._unlocked == unlocked
def test_plot_projs_topomap(): """Test plot_projs_topomap.""" import matplotlib.pyplot as plt with warnings.catch_warnings(record=True): # file conventions warnings.simplefilter('always') projs = read_proj(ecg_fname) info = read_info(raw_fname) fast_test = {"res": 8, "contours": 0, "sensors": False} plot_projs_topomap(projs, info=info, colorbar=True, **fast_test) plt.close('all') ax = plt.subplot(111) projs[3].plot_topomap() plot_projs_topomap(projs[:1], axes=ax, **fast_test) # test axes param plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test) plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][:1], **fast_test) plt.close('all') eeg_avg = make_eeg_average_ref_proj(info) assert_raises(RuntimeError, eeg_avg.plot_topomap) # no layout eeg_avg.plot_topomap(info=info, **fast_test) plt.close('all')
def test_plot_projs_topomap(): """Test plot_projs_topomap.""" import matplotlib.pyplot as plt with warnings.catch_warnings(record=True): # file conventions warnings.simplefilter('always') projs = read_proj(ecg_fname) info = read_info(raw_fname) fast_test = {"res": 8, "contours": 0, "sensors": False} plot_projs_topomap(projs, info=info, colorbar=True, **fast_test) plt.close('all') ax = plt.subplot(111) projs[3].plot_topomap() plot_projs_topomap(projs[:1], axes=ax, **fast_test) # test axes param plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test) plt.close('all') plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test) plt.close('all') eeg_avg = make_eeg_average_ref_proj(info) assert_raises(RuntimeError, eeg_avg.plot_topomap) # no layout eeg_avg.plot_topomap(info=info, **fast_test) plt.close('all')
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [ info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True) ] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error')
def test_make_sphere_model(): """Test making a sphere model""" info = read_info(fname_raw) assert_raises(ValueError, make_sphere_model, 'foo', 'auto', info) assert_raises(ValueError, make_sphere_model, 'auto', 'auto', None) # here we just make sure it works -- the functionality is actually # tested more extensively e.g. in the forward and dipole code bem = make_sphere_model('auto', 'auto', info) assert_true('3 layers' in repr(bem)) assert_true('Sphere ' in repr(bem)) assert_true(' mm' in repr(bem)) bem = make_sphere_model('auto', None, info) assert_true('no layers' in repr(bem)) assert_true('Sphere ' in repr(bem))
def test_field_round_trip(tmpdir): """Test round-trip for new fields.""" info = create_info(1, 1000., 'eeg') for key in ('file_id', 'meas_id'): info[key] = _generate_meas_id() info['device_info'] = dict( type='a', model='b', serial='c', site='d') info['helium_info'] = dict( he_level_raw=1., helium_level=2., orig_file_guid='e', meas_date=(1, 2)) fname = tmpdir.join('temp-info.fif') write_info(fname, info) info_read = read_info(fname) info_read['dig'] = None # XXX eventually this should go away assert_object_equal(info, info_read)
def test_plot_projs_topomap(): """Test plot_projs_topomap.""" projs = read_proj(ecg_fname) info = read_info(raw_fname) fast_test = {"res": 8, "contours": 0, "sensors": False} plot_projs_topomap(projs, info=info, colorbar=True, **fast_test) plt.close('all') ax = plt.subplot(111) projs[3].plot_topomap(info) plot_projs_topomap(projs[:1], info, axes=ax, **fast_test) # test axes plt.close('all') triux_info = read_info(triux_fname) plot_projs_topomap(triux_info['projs'][-1:], triux_info, **fast_test) plt.close('all') plot_projs_topomap(triux_info['projs'][:1], triux_info, **fast_test) plt.close('all') eeg_avg = make_eeg_average_ref_proj(info) eeg_avg.plot_topomap(info, **fast_test) plt.close('all') # test vlims for vlim in ('joint', (-1, 1), (None, 0.5), (0.5, None), (None, None)): plot_projs_topomap(projs[:-1], info, vlim=vlim, colorbar=True) plt.close('all')
def test_make_sphere_model(): """Test making a sphere model""" info = read_info(fname_raw) assert_raises(ValueError, make_sphere_model, "foo", "auto", info) assert_raises(ValueError, make_sphere_model, "auto", "auto", None) # here we just make sure it works -- the functionality is actually # tested more extensively e.g. in the forward and dipole code bem = make_sphere_model("auto", "auto", info) assert_true("3 layers" in repr(bem)) assert_true("Sphere " in repr(bem)) assert_true(" mm" in repr(bem)) bem = make_sphere_model("auto", None, info) assert_true("no layers" in repr(bem)) assert_true("Sphere " in repr(bem))
def test_magnetic_dipole(): """Test basic magnetic dipole forward calculation.""" trans = Transform('mri', 'head') info = read_info(fname_raw) picks = pick_types(info, meg=True, eeg=False, exclude=[]) info = pick_info(info, picks[:12]) coils = _create_meg_coils(info['chs'], 'normal', trans) # magnetic dipole at device origin r0 = np.array([0., 13., -6.]) for ch, coil in zip(info['chs'], coils): rr = (ch['loc'][:3] + r0) / 2. far_fwd = _magnetic_dipole_field_vec(r0[np.newaxis, :], [coil]) near_fwd = _magnetic_dipole_field_vec(rr[np.newaxis, :], [coil]) ratio = 8. if ch['ch_name'][-1] == '1' else 16. # grad vs mag assert_allclose(np.median(near_fwd / far_fwd), ratio, atol=1e-1)
def test_read_write_info(): """Test IO of info.""" tempdir = _TempDir() info = read_info(raw_fname) temp_file = op.join(tempdir, "info.fif") # check for bug `#1198` info["dev_head_t"]["trans"] = np.eye(4) t1 = info["dev_head_t"]["trans"] write_info(temp_file, info) info2 = read_info(temp_file) t2 = info2["dev_head_t"]["trans"] assert_true(len(info["chs"]) == len(info2["chs"])) assert_array_equal(t1, t2) # proc_history (e.g., GH#1875) creator = u"é" info = read_info(chpi_fname) info["proc_history"][0]["creator"] = creator info["hpi_meas"][0]["creator"] = creator info["subject_info"]["his_id"] = creator write_info(temp_file, info) info = read_info(temp_file) assert_equal(info["proc_history"][0]["creator"], creator) assert_equal(info["hpi_meas"][0]["creator"], creator) assert_equal(info["subject_info"]["his_id"], creator)
def test_read_write_info(): """Test IO of info.""" tempdir = _TempDir() info = read_info(raw_fname) temp_file = op.join(tempdir, 'info.fif') # check for bug `#1198` info['dev_head_t']['trans'] = np.eye(4) t1 = info['dev_head_t']['trans'] write_info(temp_file, info) info2 = read_info(temp_file) t2 = info2['dev_head_t']['trans'] assert_true(len(info['chs']) == len(info2['chs'])) assert_array_equal(t1, t2) # proc_history (e.g., GH#1875) creator = u'é' info = read_info(chpi_fname) info['proc_history'][0]['creator'] = creator info['hpi_meas'][0]['creator'] = creator info['subject_info']['his_id'] = creator write_info(temp_file, info) info = read_info(temp_file) assert_equal(info['proc_history'][0]['creator'], creator) assert_equal(info['hpi_meas'][0]['creator'], creator) assert_equal(info['subject_info']['his_id'], creator)
def read_info_custom(fname): """Read info from .fif or from .ds""" from os.path import splitext _, ext = splitext(fname) if ext == '.fif': from mne.io import read_info info = read_info(fname) elif ext == '.ds': from mne.io import read_raw_ctf with nostdout(): raw = read_raw_ctf(fname) info = raw.info else: raise RuntimeError('Unknown format for {}'.format(fname)) return info
def test_field_round_trip(tmp_path): """Test round-trip for new fields.""" info = create_info(1, 1000., 'eeg') with info._unlock(): for key in ('file_id', 'meas_id'): info[key] = _generate_meas_id() info['device_info'] = dict(type='a', model='b', serial='c', site='d') info['helium_info'] = dict(he_level_raw=1., helium_level=2., orig_file_guid='e', meas_date=(1, 2)) fname = tmp_path / 'temp-info.fif' write_info(fname, info) info_read = read_info(fname) assert_object_equal(info, info_read)
def test_rename_channels(): """Test rename channels.""" info = read_info(raw_fname) # Error Tests # Test channel name exists in ch_names mapping = {'EEG 160': 'EEG060'} pytest.raises(ValueError, rename_channels, info, mapping) # Test improper mapping configuration mapping = {'MEG 2641': 1.0} pytest.raises(TypeError, rename_channels, info, mapping) # Test non-unique mapping configuration mapping = {'MEG 2641': 'MEG 2642'} pytest.raises(ValueError, rename_channels, info, mapping) # Test bad input pytest.raises(ValueError, rename_channels, info, 1.) pytest.raises(ValueError, rename_channels, info, 1.) # Test name too long (channel names must be less than 15 characters) A16 = 'A' * 16 mapping = {'MEG 2641': A16} pytest.raises(ValueError, rename_channels, info, mapping) # Test successful changes # Test ch_name and ch_names are changed info2 = deepcopy(info) # for consistency at the start of each test info2['bads'] = ['EEG 060', 'EOG 061'] mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'} rename_channels(info2, mapping) assert info2['chs'][374]['ch_name'] == 'EEG060' assert info2['ch_names'][374] == 'EEG060' assert info2['chs'][375]['ch_name'] == 'EOG061' assert info2['ch_names'][375] == 'EOG061' assert_array_equal(['EEG060', 'EOG061'], info2['bads']) info2 = deepcopy(info) rename_channels(info2, lambda x: x.replace(' ', '')) assert info2['chs'][373]['ch_name'] == 'EEG059' info2 = deepcopy(info) info2['bads'] = ['EEG 060', 'EEG 060'] rename_channels(info2, mapping) assert_array_equal(['EEG060', 'EEG060'], info2['bads']) # test that keys in Raw._orig_units will be renamed, too raw = read_raw_fif(raw_fname).crop(0, 0.1) old, new = 'EEG 060', 'New' raw._orig_units = {old: 'V'} raw.rename_channels({old: new}) assert old not in raw._orig_units assert new in raw._orig_units
def test_plot_head_positions(): """Test plotting of head positions.""" info = read_info(evoked_fname) pos = np.random.RandomState(0).randn(4, 10) pos[:, 0] = np.arange(len(pos)) destination = (0., 0., 0.04) with pytest.warns(None): # old MPL will cause a warning plot_head_positions(pos) plot_head_positions(pos, mode='field', info=info, destination=destination) plot_head_positions([pos, pos]) # list support pytest.raises(ValueError, plot_head_positions, ['pos']) pytest.raises(ValueError, plot_head_positions, pos[:, :9]) pytest.raises(ValueError, plot_head_positions, pos, 'foo') with pytest.raises(ValueError, match='shape'): plot_head_positions(pos, axes=1.)
def test_helmet(): """Test loading helmet surfaces.""" base_dir = op.join(op.dirname(__file__), '..', 'io') fname_raw = op.join(base_dir, 'tests', 'data', 'test_raw.fif') fname_kit_raw = op.join(base_dir, 'kit', 'tests', 'data', 'test_bin_raw.fif') fname_bti_raw = op.join(base_dir, 'bti', 'tests', 'data', 'exported4D_linux_raw.fif') fname_ctf_raw = op.join(base_dir, 'tests', 'data', 'test_ctf_raw.fif') fname_trans = op.join(base_dir, 'tests', 'data', 'sample-audvis-raw-trans.txt') trans = _get_trans(fname_trans)[0] for fname in [fname_raw, fname_kit_raw, fname_bti_raw, fname_ctf_raw]: helmet = get_meg_helmet_surf(read_info(fname), trans) assert_equal(len(helmet['rr']), 304) # they all have 304 verts assert_equal(len(helmet['rr']), len(helmet['nn']))