• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python io.read_raw_fif函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mne.io.read_raw_fif函数的典型用法代码示例。如果您正苦于以下问题:Python read_raw_fif函数的具体用法?Python read_raw_fif怎么用?Python read_raw_fif使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了read_raw_fif函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_saving_picked

def test_saving_picked():
    """Test saving picked CTF instances."""
    temp_dir = _TempDir()
    out_fname = op.join(temp_dir, 'test_py_raw.fif')
    raw = read_raw_ctf(op.join(ctf_dir, ctf_fname_1_trial))
    raw.crop(0, 1).load_data()
    assert raw.compensation_grade == get_current_comp(raw.info) == 0
    assert len(raw.info['comps']) == 5
    pick_kwargs = dict(meg=True, ref_meg=False, verbose=True)
    for comp_grade in [0, 1]:
        raw.apply_gradient_compensation(comp_grade)
        with catch_logging() as log:
            raw_pick = raw.copy().pick_types(**pick_kwargs)
        assert len(raw.info['comps']) == 5
        assert len(raw_pick.info['comps']) == 0
        log = log.getvalue()
        assert 'Removing 5 compensators' in log
        raw_pick.save(out_fname, overwrite=True)  # should work
        raw2 = read_raw_fif(out_fname)
        assert (raw_pick.ch_names == raw2.ch_names)
        assert_array_equal(raw_pick.times, raw2.times)
        assert_allclose(raw2[0:20][0], raw_pick[0:20][0], rtol=1e-6,
                        atol=1e-20)  # atol is very small but > 0

        raw2 = read_raw_fif(out_fname, preload=True)
        assert (raw_pick.ch_names == raw2.ch_names)
        assert_array_equal(raw_pick.times, raw2.times)
        assert_allclose(raw2[0:20][0], raw_pick[0:20][0], rtol=1e-6,
                        atol=1e-20)  # atol is very small but > 0
开发者ID:jhouck,项目名称:mne-python,代码行数:29,代码来源:test_ctf.py


示例2: test_chpi_subtraction

def test_chpi_subtraction():
    """Test subtraction of cHPI signals."""
    raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
    raw.info['bads'] = ['MEG0111']
    raw.del_proj()
    with catch_logging() as log:
        filter_chpi(raw, include_line=False, verbose=True)
    assert 'No average EEG' not in log.getvalue()
    assert '5 cHPI' in log.getvalue()
    # MaxFilter doesn't do quite as well as our algorithm with the last bit
    raw.crop(0, 16)
    # remove cHPI status chans
    raw_c = read_raw_fif(sss_hpisubt_fname).crop(0, 16).load_data()
    raw_c.pick_types(
        meg=True, eeg=True, eog=True, ecg=True, stim=True, misc=True)
    assert_meg_snr(raw, raw_c, 143, 624)

    # Degenerate cases
    raw_nohpi = read_raw_fif(test_fif_fname, preload=True)
    pytest.raises(RuntimeError, filter_chpi, raw_nohpi)

    # When MaxFliter downsamples, like::
    #     $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \
    #           -o test_move_anon_ds2_raw.fif
    # it can strip out some values of info, which we emulate here:
    raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')
    raw = raw.crop(0, 1).load_data().resample(600., npad='auto')
    raw.info['lowpass'] = 200.
    del raw.info['maxshield']
    del raw.info['hpi_results'][0]['moments']
    del raw.info['hpi_subsystem']['event_channel']
    with catch_logging() as log:
        filter_chpi(raw, verbose=True)
    pytest.raises(ValueError, filter_chpi, raw, t_window=-1)
    assert '2 cHPI' in log.getvalue()
开发者ID:SherazKhan,项目名称:mne-python,代码行数:35,代码来源:test_chpi.py


示例3: test_calculate_chpi_positions

def test_calculate_chpi_positions():
    """Test calculation of cHPI positions."""
    trans, rot, t = head_pos_to_trans_rot_t(read_head_pos(pos_fname))
    raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True,
                       add_eeg_ref=False)
    t -= raw.first_samp / raw.info['sfreq']
    quats = _calculate_chpi_positions(raw, verbose='debug')
    trans_est, rot_est, t_est = head_pos_to_trans_rot_t(quats)
    _compare_positions((trans, rot, t), (trans_est, rot_est, t_est), 0.003)

    # degenerate conditions
    raw_no_chpi = read_raw_fif(test_fif_fname, add_eeg_ref=False)
    assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
    raw_bad = raw.copy()
    for d in raw_bad.info['dig']:
        if d['kind'] == FIFF.FIFFV_POINT_HPI:
            d['coord_frame'] = 999
            break
    assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
    raw_bad = raw.copy()
    for d in raw_bad.info['dig']:
        if d['kind'] == FIFF.FIFFV_POINT_HPI:
            d['r'] = np.ones(3)
    raw_bad.crop(0, 1., copy=False)
    with warnings.catch_warnings(record=True):  # bad pos
        with catch_logging() as log_file:
            _calculate_chpi_positions(raw_bad, verbose=True)
    # ignore HPI info header and [done] footer
    assert_true('0/5 good' in log_file.getvalue().strip().split('\n')[-2])

    # half the rate cuts off cHPI coils
    with warnings.catch_warnings(record=True):  # uint cast suggestion
        raw.resample(300., npad='auto')
    assert_raises_regex(RuntimeError, 'above the',
                        _calculate_chpi_positions, raw)
开发者ID:jmontoyam,项目名称:mne-python,代码行数:35,代码来源:test_chpi.py


示例4: test_read_selection

def test_read_selection():
    """Test reading of selections."""
    # test one channel for each selection
    ch_names = ['MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043',
                'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031']
    sel_names = ['Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal',
                 'Right-parietal', 'Left-occipital', 'Right-occipital',
                 'Left-frontal', 'Right-frontal']

    raw = read_raw_fif(raw_fname)
    for i, name in enumerate(sel_names):
        sel = read_selection(name)
        assert_true(ch_names[i] in sel)
        sel_info = read_selection(name, info=raw.info)
        assert_equal(sel, sel_info)

    # test some combinations
    all_ch = read_selection(['L', 'R'])
    left = read_selection('L')
    right = read_selection('R')

    assert_true(len(all_ch) == len(left) + len(right))
    assert_true(len(set(left).intersection(set(right))) == 0)

    frontal = read_selection('frontal')
    occipital = read_selection('Right-occipital')
    assert_true(len(set(frontal).intersection(set(occipital))) == 0)

    ch_names_new = [ch.replace(' ', '') for ch in ch_names]
    raw_new = read_raw_fif(raw_new_fname)
    for i, name in enumerate(sel_names):
        sel = read_selection(name, info=raw_new.info)
        assert_true(ch_names_new[i] in sel)

    assert_raises(TypeError, read_selection, name, info='foo')
开发者ID:HSMin,项目名称:mne-python,代码行数:35,代码来源:test_selection.py


示例5: test_mne_c_design

def test_mne_c_design():
    """Test MNE-C filter design."""
    tempdir = _TempDir()
    temp_fname = op.join(tempdir, 'test_raw.fif')
    out_fname = op.join(tempdir, 'test_c_raw.fif')
    x = np.zeros((1, 10001))
    x[0, 5000] = 1.
    time_sl = slice(5000 - 4096, 5000 + 4097)
    sfreq = 1000.
    RawArray(x, create_info(1, sfreq, 'eeg')).save(temp_fname)

    tols = dict(rtol=1e-4, atol=1e-4)
    cmd = ('mne_process_raw', '--projoff', '--raw', temp_fname,
           '--save', out_fname)
    run_subprocess(cmd)
    h = design_mne_c_filter(sfreq, None, 40)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--highpass', '5', '--highpassw', '2.5'))
    h = design_mne_c_filter(sfreq, 5, 40, 2.5)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--lowpass', '1000', '--highpass', '10'))
    h = design_mne_c_filter(sfreq, 10, None, verbose=True)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)
开发者ID:annapasca,项目名称:mne-python,代码行数:28,代码来源:test_filter.py


示例6: test_bad_proj

def test_bad_proj():
    """Test dealing with bad projection application."""
    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[2:9:3]
    _check_warnings(raw, events, picks)
    # still bad
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    _check_warnings(raw, events)
    # "fixed"
    raw.info.normalize_proj()  # avoid projection warnings
    _check_warnings(raw, events, count=0)
    # eeg avg ref is okay
    raw = read_raw_fif(raw_fname, preload=True).pick_types(meg=False, eeg=True)
    raw.set_eeg_reference()
    _check_warnings(raw, events, count=0)
    raw.info['bads'] = raw.ch_names[:10]
    _check_warnings(raw, events, count=0)

    raw = read_raw_fif(raw_fname)
    assert_raises(ValueError, raw.del_proj, 'foo')
    n_proj = len(raw.info['projs'])
    raw.del_proj(0)
    assert_equal(len(raw.info['projs']), n_proj - 1)
    raw.del_proj()
    assert_equal(len(raw.info['projs']), 0)
开发者ID:hoechenberger,项目名称:mne-python,代码行数:28,代码来源:test_proj.py


示例7: test_set_eeg_reference

def test_set_eeg_reference():
    """Test rereference eeg data."""
    raw = read_raw_fif(fif_fname, preload=True)
    raw.info['projs'] = []

    # Test setting an average reference
    assert_true(not _has_eeg_average_ref_proj(raw.info['projs']))
    reref, ref_data = set_eeg_reference(raw)
    assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
    assert_true(not reref.info['projs'][0]['active'])
    assert_true(ref_data is None)
    reref.apply_proj()
    eeg_chans = [raw.ch_names[ch]
                 for ch in pick_types(raw.info, meg=False, eeg=True)]
    _test_reference(raw, reref, ref_data,
                    [ch for ch in eeg_chans if ch not in raw.info['bads']])

    # Test setting an average reference when one was already present
    with warnings.catch_warnings(record=True):
        reref, ref_data = set_eeg_reference(raw, copy=False)
    assert_true(ref_data is None)

    # Test setting an average reference on non-preloaded data
    raw_nopreload = read_raw_fif(fif_fname, preload=False)
    raw_nopreload.info['projs'] = []
    reref, ref_data = set_eeg_reference(raw_nopreload)
    assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
    assert_true(not reref.info['projs'][0]['active'])

    # Rereference raw data by creating a copy of original data
    reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'], copy=True)
    assert_true(reref.info['custom_ref_applied'])
    _test_reference(raw, reref, ref_data, ['EEG 001', 'EEG 002'])

    # Test that data is modified in place when copy=False
    reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'],
                                        copy=False)
    assert_true(raw is reref)

    # Test moving from custom to average reference
    reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'])
    reref, _ = set_eeg_reference(reref)
    assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
    assert_equal(reref.info['custom_ref_applied'], False)

    # When creating an average reference fails, make sure the
    # custom_ref_applied flag remains untouched.
    reref = raw.copy()
    reref.info['custom_ref_applied'] = True
    reref.pick_types(eeg=False)  # Cause making average ref fail
    assert_raises(ValueError, set_eeg_reference, reref)
    assert_true(reref.info['custom_ref_applied'])

    # Test moving from average to custom reference
    reref, ref_data = set_eeg_reference(raw)
    reref, _ = set_eeg_reference(reref, ['EEG 001', 'EEG 002'])
    assert_true(not _has_eeg_average_ref_proj(reref.info['projs']))
    assert_equal(reref.info['custom_ref_applied'], True)
开发者ID:olafhauk,项目名称:mne-python,代码行数:58,代码来源:test_reference.py


示例8: test_set_channel_types

def test_set_channel_types():
    """Test set_channel_types"""
    raw = read_raw_fif(raw_fname)
    # Error Tests
    # Test channel name exists in ch_names
    mapping = {'EEG 160': 'EEG060'}
    assert_raises(ValueError, raw.set_channel_types, mapping)
    # Test change to illegal channel type
    mapping = {'EOG 061': 'xxx'}
    assert_raises(ValueError, raw.set_channel_types, mapping)
    # Test changing type if in proj (avg eeg ref here)
    mapping = {'EEG 058': 'ecog', 'EEG 059': 'ecg', 'EEG 060': 'eog',
               'EOG 061': 'seeg', 'MEG 2441': 'eeg', 'MEG 2443': 'eeg',
               'MEG 2442': 'hbo'}
    assert_raises(RuntimeError, raw.set_channel_types, mapping)
    # Test type change
    raw2 = read_raw_fif(raw_fname)
    raw2.info['bads'] = ['EEG 059', 'EEG 060', 'EOG 061']
    with warnings.catch_warnings(record=True):  # MEG channel change
        assert_raises(RuntimeError, raw2.set_channel_types, mapping)  # has prj
    raw2.add_proj([], remove_existing=True)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        raw2.set_channel_types(mapping)
    assert_true(len(w) >= 1, msg=[str(ww.message) for ww in w])
    assert_true(all('The unit for channel' in str(ww.message) for ww in w))
    info = raw2.info
    assert_true(info['chs'][372]['ch_name'] == 'EEG 058')
    assert_true(info['chs'][372]['kind'] == FIFF.FIFFV_ECOG_CH)
    assert_true(info['chs'][372]['unit'] == FIFF.FIFF_UNIT_V)
    assert_true(info['chs'][372]['coil_type'] == FIFF.FIFFV_COIL_EEG)
    assert_true(info['chs'][373]['ch_name'] == 'EEG 059')
    assert_true(info['chs'][373]['kind'] == FIFF.FIFFV_ECG_CH)
    assert_true(info['chs'][373]['unit'] == FIFF.FIFF_UNIT_V)
    assert_true(info['chs'][373]['coil_type'] == FIFF.FIFFV_COIL_NONE)
    assert_true(info['chs'][374]['ch_name'] == 'EEG 060')
    assert_true(info['chs'][374]['kind'] == FIFF.FIFFV_EOG_CH)
    assert_true(info['chs'][374]['unit'] == FIFF.FIFF_UNIT_V)
    assert_true(info['chs'][374]['coil_type'] == FIFF.FIFFV_COIL_NONE)
    assert_true(info['chs'][375]['ch_name'] == 'EOG 061')
    assert_true(info['chs'][375]['kind'] == FIFF.FIFFV_SEEG_CH)
    assert_true(info['chs'][375]['unit'] == FIFF.FIFF_UNIT_V)
    assert_true(info['chs'][375]['coil_type'] == FIFF.FIFFV_COIL_EEG)
    for idx in pick_channels(raw.ch_names, ['MEG 2441', 'MEG 2443']):
        assert_true(info['chs'][idx]['kind'] == FIFF.FIFFV_EEG_CH)
        assert_true(info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_V)
        assert_true(info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_EEG)
    idx = pick_channels(raw.ch_names, ['MEG 2442'])[0]
    assert_true(info['chs'][idx]['kind'] == FIFF.FIFFV_FNIRS_CH)
    assert_true(info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_MOL)
    assert_true(info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO)

    # Test meaningful error when setting channel type with unknown unit
    raw.info['chs'][0]['unit'] = 0.
    ch_types = {raw.ch_names[0]: 'misc'}
    assert_raises(ValueError, raw.set_channel_types, ch_types)
开发者ID:Hugo-W,项目名称:mne-python,代码行数:56,代码来源:test_channels.py


示例9: test_raw

def test_raw():
    """Test bti conversion to Raw object."""
    for pdf, config, hs, exported in zip(pdf_fnames, config_fnames, hs_fnames,
                                         exported_fnames):
        # rx = 2 if 'linux' in pdf else 0
        pytest.raises(ValueError, read_raw_bti, pdf, 'eggs', preload=False)
        pytest.raises(ValueError, read_raw_bti, pdf, config, 'spam',
                      preload=False)
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        ex = read_raw_fif(exported, preload=True)
        ra = read_raw_bti(pdf, config, hs, preload=False)
        assert ('RawBTi' in repr(ra))
        assert_equal(ex.ch_names[:NCH], ra.ch_names[:NCH])
        assert_array_almost_equal(ex.info['dev_head_t']['trans'],
                                  ra.info['dev_head_t']['trans'], 7)
        assert len(ex.info['dig']) in (3563, 5154)
        assert_dig_allclose(ex.info, ra.info, limit=100)
        coil1, coil2 = [np.concatenate([d['loc'].flatten()
                                        for d in r_.info['chs'][:NCH]])
                        for r_ in (ra, ex)]
        assert_array_almost_equal(coil1, coil2, 7)

        loc1, loc2 = [np.concatenate([d['loc'].flatten()
                                      for d in r_.info['chs'][:NCH]])
                      for r_ in (ra, ex)]
        assert_allclose(loc1, loc2)

        assert_allclose(ra[:NCH][0], ex[:NCH][0])
        assert_array_equal([c['range'] for c in ra.info['chs'][:NCH]],
                           [c['range'] for c in ex.info['chs'][:NCH]])
        assert_array_equal([c['cal'] for c in ra.info['chs'][:NCH]],
                           [c['cal'] for c in ex.info['chs'][:NCH]])
        assert_array_equal(ra._cals[:NCH], ex._cals[:NCH])

        # check our transforms
        for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
            if ex.info[key] is None:
                pass
            else:
                assert (ra.info[key] is not None)
                for ent in ('to', 'from', 'trans'):
                    assert_allclose(ex.info[key][ent],
                                    ra.info[key][ent])

        ra.save(tmp_raw_fname)
        re = read_raw_fif(tmp_raw_fname)
        print(re)
        for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
            assert (isinstance(re.info[key], dict))
            this_t = re.info[key]['trans']
            assert_equal(this_t.shape, (4, 4))
            # check that matrix by is not identity
            assert (not np.allclose(this_t, np.eye(4)))
        os.remove(tmp_raw_fname)
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:55,代码来源:test_bti.py


示例10: test_hpi_info

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')
        assert_true(len(raw.info['hpi_subsystem']) > 0)
        raw.save(temp_name, overwrite=True)
        raw_2 = read_raw_fif(temp_name, allow_maxshield='yes')
        assert_equal(len(raw_2.info['hpi_subsystem']),
                     len(raw.info['hpi_subsystem']))
开发者ID:JuliaSprenger,项目名称:mne-python,代码行数:11,代码来源:test_chpi.py


示例11: test_calculate_chpi_positions

def test_calculate_chpi_positions():
    """Test calculation of cHPI positions."""
    # Check to make sure our fits match MF decently
    mf_quats = read_head_pos(pos_fname)
    raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
    # This is a little hack (aliasing while decimating) to make it much faster
    # for testing purposes only. We can relax this later if we find it breaks
    # something.
    raw_dec = _decimate_chpi(raw, 15)
    with catch_logging() as log:
        py_quats = _calculate_chpi_positions(raw_dec, t_step_max=1.,
                                             verbose='debug')
    assert_true(log.getvalue().startswith('HPIFIT'))
    _assert_quats(py_quats, mf_quats, dist_tol=0.004, angle_tol=2.5)

    # degenerate conditions
    raw_no_chpi = read_raw_fif(test_fif_fname)
    assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
    raw_bad = raw.copy()
    del raw_bad.info['hpi_meas'][0]['hpi_coils'][0]['coil_freq']
    assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
    raw_bad = raw.copy()
    for d in raw_bad.info['dig']:
        if d['kind'] == FIFF.FIFFV_POINT_HPI:
            d['coord_frame'] = FIFF.FIFFV_COORD_UNKNOWN
            break
    assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
    for d in raw_bad.info['dig']:
        if d['kind'] == FIFF.FIFFV_POINT_HPI:
            d['coord_frame'] = FIFF.FIFFV_COORD_HEAD
            d['r'] = np.ones(3)
    raw_bad.crop(0, 1.)
    picks = np.concatenate([np.arange(306, len(raw_bad.ch_names)),
                            pick_types(raw_bad.info, meg=True)[::16]])
    raw_bad.pick_channels([raw_bad.ch_names[pick] for pick in picks])
    with warnings.catch_warnings(record=True):  # bad pos
        with catch_logging() as log_file:
            _calculate_chpi_positions(raw_bad, t_step_min=1., verbose=True)
    # ignore HPI info header and [done] footer
    assert_true('0/5 good' in log_file.getvalue().strip().split('\n')[-2])

    # half the rate cuts off cHPI coils
    raw.info['lowpass'] /= 2.
    assert_raises_regex(RuntimeError, 'above the',
                        _calculate_chpi_positions, raw)

    # test on 5k artemis data
    raw = read_raw_artemis123(art_fname, preload=True)
    mf_quats = read_head_pos(art_mc_fname)
    with catch_logging() as log:
        py_quats = _calculate_chpi_positions(raw, t_step_min=2.,
                                             verbose='debug')
    _assert_quats(py_quats, mf_quats, dist_tol=0.004, angle_tol=2.5)
开发者ID:claire-braboszcz,项目名称:mne-python,代码行数:53,代码来源:test_chpi.py


示例12: test_read_selection

def test_read_selection():
    """Test reading of selections"""
    # test one channel for each selection
    ch_names = [
        "MEG 2211",
        "MEG 0223",
        "MEG 1312",
        "MEG 0412",
        "MEG 1043",
        "MEG 2042",
        "MEG 2032",
        "MEG 0522",
        "MEG 1031",
    ]
    sel_names = [
        "Vertex",
        "Left-temporal",
        "Right-temporal",
        "Left-parietal",
        "Right-parietal",
        "Left-occipital",
        "Right-occipital",
        "Left-frontal",
        "Right-frontal",
    ]

    raw = read_raw_fif(raw_fname)
    for i, name in enumerate(sel_names):
        sel = read_selection(name)
        assert_true(ch_names[i] in sel)
        sel_info = read_selection(name, info=raw.info)
        assert_equal(sel, sel_info)

    # test some combinations
    all_ch = read_selection(["L", "R"])
    left = read_selection("L")
    right = read_selection("R")

    assert_true(len(all_ch) == len(left) + len(right))
    assert_true(len(set(left).intersection(set(right))) == 0)

    frontal = read_selection("frontal")
    occipital = read_selection("Right-occipital")
    assert_true(len(set(frontal).intersection(set(occipital))) == 0)

    ch_names_new = [ch.replace(" ", "") for ch in ch_names]
    raw_new = read_raw_fif(raw_new_fname)
    for i, name in enumerate(sel_names):
        sel = read_selection(name, info=raw_new.info)
        assert_true(ch_names_new[i] in sel)

    assert_raises(TypeError, read_selection, name, info="foo")
开发者ID:mmagnuski,项目名称:mne-python,代码行数:52,代码来源:test_selection.py


示例13: test_set_channel_types

def test_set_channel_types():
    """Test set_channel_types."""
    raw = read_raw_fif(raw_fname)
    # Error Tests
    # Test channel name exists in ch_names
    mapping = {'EEG 160': 'EEG060'}
    pytest.raises(ValueError, raw.set_channel_types, mapping)
    # Test change to illegal channel type
    mapping = {'EOG 061': 'xxx'}
    pytest.raises(ValueError, raw.set_channel_types, mapping)
    # Test changing type if in proj (avg eeg ref here)
    mapping = {'EEG 058': 'ecog', 'EEG 059': 'ecg', 'EEG 060': 'eog',
               'EOG 061': 'seeg', 'MEG 2441': 'eeg', 'MEG 2443': 'eeg',
               'MEG 2442': 'hbo'}
    pytest.raises(RuntimeError, raw.set_channel_types, mapping)
    # Test type change
    raw2 = read_raw_fif(raw_fname)
    raw2.info['bads'] = ['EEG 059', 'EEG 060', 'EOG 061']
    pytest.raises(RuntimeError, raw2.set_channel_types, mapping)  # has prj
    raw2.add_proj([], remove_existing=True)
    with pytest.warns(RuntimeWarning, match='The unit for channel'):
        raw2.set_channel_types(mapping)
    info = raw2.info
    assert info['chs'][372]['ch_name'] == 'EEG 058'
    assert info['chs'][372]['kind'] == FIFF.FIFFV_ECOG_CH
    assert info['chs'][372]['unit'] == FIFF.FIFF_UNIT_V
    assert info['chs'][372]['coil_type'] == FIFF.FIFFV_COIL_EEG
    assert info['chs'][373]['ch_name'] == 'EEG 059'
    assert info['chs'][373]['kind'] == FIFF.FIFFV_ECG_CH
    assert info['chs'][373]['unit'] == FIFF.FIFF_UNIT_V
    assert info['chs'][373]['coil_type'] == FIFF.FIFFV_COIL_NONE
    assert info['chs'][374]['ch_name'] == 'EEG 060'
    assert info['chs'][374]['kind'] == FIFF.FIFFV_EOG_CH
    assert info['chs'][374]['unit'] == FIFF.FIFF_UNIT_V
    assert info['chs'][374]['coil_type'] == FIFF.FIFFV_COIL_NONE
    assert info['chs'][375]['ch_name'] == 'EOG 061'
    assert info['chs'][375]['kind'] == FIFF.FIFFV_SEEG_CH
    assert info['chs'][375]['unit'] == FIFF.FIFF_UNIT_V
    assert info['chs'][375]['coil_type'] == FIFF.FIFFV_COIL_EEG
    for idx in pick_channels(raw.ch_names, ['MEG 2441', 'MEG 2443']):
        assert info['chs'][idx]['kind'] == FIFF.FIFFV_EEG_CH
        assert info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_V
        assert info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_EEG
    idx = pick_channels(raw.ch_names, ['MEG 2442'])[0]
    assert info['chs'][idx]['kind'] == FIFF.FIFFV_FNIRS_CH
    assert info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_MOL
    assert info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO

    # Test meaningful error when setting channel type with unknown unit
    raw.info['chs'][0]['unit'] = 0.
    ch_types = {raw.ch_names[0]: 'misc'}
    pytest.raises(ValueError, raw.set_channel_types, ch_types)
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:52,代码来源:test_channels.py


示例14: test_cov_estimation_on_raw

def test_cov_estimation_on_raw():
    """Test estimation from raw (typically empty room)"""
    tempdir = _TempDir()
    raw = read_raw_fif(raw_fname, preload=True)
    cov_mne = read_cov(erm_cov_fname)

    # The pure-string uses the more efficient numpy-based method, the
    # the list gets triaged to compute_covariance (should be equivalent
    # but use more memory)
    for method in (None, ['empirical']):  # None is cast to 'empirical'
        cov = compute_raw_covariance(raw, tstep=None, method=method)
        assert_equal(cov.ch_names, cov_mne.ch_names)
        assert_equal(cov.nfree, cov_mne.nfree)
        assert_snr(cov.data, cov_mne.data, 1e4)

        cov = compute_raw_covariance(raw, method=method)  # tstep=0.2 (default)
        assert_equal(cov.nfree, cov_mne.nfree - 119)  # cutoff some samples
        assert_snr(cov.data, cov_mne.data, 1e2)

        # test IO when computation done in Python
        cov.save(op.join(tempdir, 'test-cov.fif'))  # test saving
        cov_read = read_cov(op.join(tempdir, 'test-cov.fif'))
        assert_true(cov_read.ch_names == cov.ch_names)
        assert_true(cov_read.nfree == cov.nfree)
        assert_array_almost_equal(cov.data, cov_read.data)

        # test with a subset of channels
        picks = pick_channels(raw.ch_names, include=raw.ch_names[:5])
        raw_pick = raw.copy().pick_channels(
            [raw.ch_names[pick] for pick in picks])
        raw_pick.info.normalize_proj()
        cov = compute_raw_covariance(raw_pick, picks=picks, tstep=None,
                                     method=method)
        assert_true(cov_mne.ch_names[:5] == cov.ch_names)
        assert_snr(cov.data, cov_mne.data[picks][:, picks], 1e4)
        cov = compute_raw_covariance(raw_pick, picks=picks, method=method)
        assert_snr(cov.data, cov_mne.data[picks][:, picks], 90)  # cutoff samps
        # make sure we get a warning with too short a segment
        raw_2 = read_raw_fif(raw_fname).crop(0, 1, copy=False)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            cov = compute_raw_covariance(raw_2, method=method)
        assert_true(any('Too few samples' in str(ww.message) for ww in w))
        # no epochs found due to rejection
        assert_raises(ValueError, compute_raw_covariance, raw, tstep=None,
                      method='empirical', reject=dict(eog=200e-6))
        # but this should work
        cov = compute_raw_covariance(raw.copy().crop(0, 10., copy=False),
                                     tstep=None, method=method,
                                     reject=dict(eog=1000e-6))
开发者ID:EmanuelaLiaci,项目名称:mne-python,代码行数:50,代码来源:test_cov.py


示例15: test_cov_estimation_on_raw

def test_cov_estimation_on_raw(method, tmpdir):
    """Test estimation from raw (typically empty room)."""
    tempdir = str(tmpdir)
    raw = read_raw_fif(raw_fname, preload=True)
    cov_mne = read_cov(erm_cov_fname)

    # The pure-string uses the more efficient numpy-based method, the
    # the list gets triaged to compute_covariance (should be equivalent
    # but use more memory)
    with pytest.warns(None):  # can warn about EEG ref
        cov = compute_raw_covariance(raw, tstep=None, method=method,
                                     rank='full')
    assert_equal(cov.ch_names, cov_mne.ch_names)
    assert_equal(cov.nfree, cov_mne.nfree)
    assert_snr(cov.data, cov_mne.data, 1e4)

    # tstep=0.2 (default)
    with pytest.warns(None):  # can warn about EEG ref
        cov = compute_raw_covariance(raw, method=method, rank='full')
    assert_equal(cov.nfree, cov_mne.nfree - 119)  # cutoff some samples
    assert_snr(cov.data, cov_mne.data, 1e2)

    # test IO when computation done in Python
    cov.save(op.join(tempdir, 'test-cov.fif'))  # test saving
    cov_read = read_cov(op.join(tempdir, 'test-cov.fif'))
    assert cov_read.ch_names == cov.ch_names
    assert cov_read.nfree == cov.nfree
    assert_array_almost_equal(cov.data, cov_read.data)

    # test with a subset of channels
    raw_pick = raw.copy().pick_channels(raw.ch_names[:5])
    raw_pick.info.normalize_proj()
    cov = compute_raw_covariance(raw_pick, tstep=None, method=method,
                                 rank='full')
    assert cov_mne.ch_names[:5] == cov.ch_names
    assert_snr(cov.data, cov_mne.data[:5, :5], 1e4)
    cov = compute_raw_covariance(raw_pick, method=method, rank='full')
    assert_snr(cov.data, cov_mne.data[:5, :5], 90)  # cutoff samps
    # make sure we get a warning with too short a segment
    raw_2 = read_raw_fif(raw_fname).crop(0, 1)
    with pytest.warns(RuntimeWarning, match='Too few samples'):
        cov = compute_raw_covariance(raw_2, method=method)
    # no epochs found due to rejection
    pytest.raises(ValueError, compute_raw_covariance, raw, tstep=None,
                  method='empirical', reject=dict(eog=200e-6))
    # but this should work
    cov = compute_raw_covariance(raw.copy().crop(0, 10.),
                                 tstep=None, method=method,
                                 reject=dict(eog=1000e-6),
                                 verbose='error')
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:50,代码来源:test_cov.py


示例16: test_get_set_sensor_positions

def test_get_set_sensor_positions():
    """Test get/set functions for sensor positions."""
    raw1 = read_raw_fif(raw_fname)
    picks = pick_types(raw1.info, meg=False, eeg=True)
    pos = np.array([ch['loc'][:3] for ch in raw1.info['chs']])[picks]
    raw_pos = raw1._get_channel_positions(picks=picks)
    assert_array_equal(raw_pos, pos)

    ch_name = raw1.info['ch_names'][13]
    pytest.raises(ValueError, raw1._set_channel_positions, [1, 2], ['name'])
    raw2 = read_raw_fif(raw_fname)
    raw2.info['chs'][13]['loc'][:3] = np.array([1, 2, 3])
    raw1._set_channel_positions([[1, 2, 3]], [ch_name])
    assert_array_equal(raw1.info['chs'][13]['loc'],
                       raw2.info['chs'][13]['loc'])
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:15,代码来源:test_channels.py


示例17: test_calculate_chpi_coil_locs

def test_calculate_chpi_coil_locs():
    """Test computing just cHPI locations."""
    raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
    # This is a little hack (aliasing while decimating) to make it much faster
    # for testing purposes only. We can relax this later if we find it breaks
    # something.
    raw_dec = _decimate_chpi(raw, 15)
    times, cHPI_digs = _calculate_chpi_coil_locs(raw_dec, verbose='debug')

    # spot check
    assert_allclose(times[9], 9.9, atol=1e-3)
    assert_allclose(cHPI_digs[9][2]['r'],
                    [-0.01937833, 0.00346804, 0.06331209], atol=1e-3)
    assert_allclose(cHPI_digs[9][2]['gof'], 0.9957976, atol=1e-3)

    assert_allclose(cHPI_digs[9][4]['r'],
                    [0.05442122, 0.00997692, 0.03721696], atol=1e-3)
    assert_allclose(cHPI_digs[9][4]['gof'], 0.075700080794629199, atol=1e-3)

    # test on 5k artemis data
    raw = read_raw_artemis123(art_fname, preload=True)
    times, cHPI_digs = _calculate_chpi_coil_locs(raw, verbose='debug')

    assert_allclose(times[2], 2.9, atol=1e-3)
    assert_allclose(cHPI_digs[2][0]['gof'], 0.9980471794552791, atol=1e-3)
    assert_allclose(cHPI_digs[2][0]['r'],
                    [-0.0157762, 0.06655744, 0.00545172], atol=1e-3)
开发者ID:claire-braboszcz,项目名称:mne-python,代码行数:27,代码来源:test_chpi.py


示例18: test_unsupervised_spatial_filter

def test_unsupervised_spatial_filter():
    """Test unsupervised spatial filter."""
    from sklearn.decomposition import PCA
    from sklearn.kernel_ridge import KernelRidge
    raw = io.read_raw_fif(raw_fname)
    events = read_events(event_name)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[1:13:3]
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    preload=True, baseline=None, verbose=False)

    # Test estimator
    assert_raises(ValueError, UnsupervisedSpatialFilter, KernelRidge(2))

    # Test fit
    X = epochs.get_data()
    n_components = 4
    usf = UnsupervisedSpatialFilter(PCA(n_components))
    usf.fit(X)
    usf1 = UnsupervisedSpatialFilter(PCA(n_components))

    # test transform
    assert_equal(usf.transform(X).ndim, 3)
    # test fit_transform
    assert_array_almost_equal(usf.transform(X), usf1.fit_transform(X))
    # assert shape
    assert_equal(usf.transform(X).shape[1], n_components)

    # Test with average param
    usf = UnsupervisedSpatialFilter(PCA(4), average=True)
    usf.fit_transform(X)
    assert_raises(ValueError, UnsupervisedSpatialFilter, PCA(4), 2)
开发者ID:Hugo-W,项目名称:mne-python,代码行数:33,代码来源:test_transformer.py


示例19: test_cov_mismatch

def test_cov_mismatch():
    """Test estimation with MEG<->Head mismatch."""
    raw = read_raw_fif(raw_fname).crop(0, 5).load_data()
    events = find_events(raw, stim_channel='STI 014')
    raw.pick_channels(raw.ch_names[:5])
    raw.add_proj([], remove_existing=True)
    epochs = Epochs(raw, events, None, tmin=-0.2, tmax=0., preload=True)
    for kind in ('shift', 'None'):
        epochs_2 = epochs.copy()
        # This should be fine
        with warnings.catch_warnings(record=True) as w:
            compute_covariance([epochs, epochs_2])
            assert_equal(len(w), 0)
            if kind == 'shift':
                epochs_2.info['dev_head_t']['trans'][:3, 3] += 0.001
            else:  # None
                epochs_2.info['dev_head_t'] = None
            assert_raises(ValueError, compute_covariance, [epochs, epochs_2])
            assert_equal(len(w), 0)
            compute_covariance([epochs, epochs_2], on_mismatch='ignore')
            assert_equal(len(w), 0)
            compute_covariance([epochs, epochs_2], on_mismatch='warn')
            assert_raises(ValueError, compute_covariance, epochs,
                          on_mismatch='x')
        assert_true(any('transform mismatch' in str(ww.message) for ww in w))
    # This should work
    epochs.info['dev_head_t'] = None
    epochs_2.info['dev_head_t'] = None
    compute_covariance([epochs, epochs_2], method=None)
开发者ID:jdammers,项目名称:mne-python,代码行数:29,代码来源:test_cov.py


示例20: test_plot_ica_overlay

def test_plot_ica_overlay():
    """Test plotting of ICA cleaning."""
    import matplotlib.pyplot as plt
    raw = _get_raw(preload=True)
    picks = _get_picks(raw)
    ica = ICA(noise_cov=read_cov(cov_fname), n_components=2,
              max_pca_components=3, n_pca_components=3)
    # can't use info.normalize_proj here because of how and when ICA and Epochs
    # objects do picking of Raw data
    with pytest.warns(RuntimeWarning, match='projection'):
        ica.fit(raw, picks=picks)
    # don't test raw, needs preload ...
    with pytest.warns(RuntimeWarning, match='projection'):
        ecg_epochs = create_ecg_epochs(raw, picks=picks)
    ica.plot_overlay(ecg_epochs.average())
    with pytest.warns(RuntimeWarning, match='projection'):
        eog_epochs = create_eog_epochs(raw, picks=picks)
    ica.plot_overlay(eog_epochs.average())
    pytest.raises(TypeError, ica.plot_overlay, raw[:2, :3][0])
    ica.plot_overlay(raw)
    plt.close('all')

    # smoke test for CTF
    raw = read_raw_fif(raw_ctf_fname)
    raw.apply_gradient_compensation(3)
    picks = pick_types(raw.info, meg=True, ref_meg=False)
    ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3)
    ica.fit(raw, picks=picks)
    with pytest.warns(RuntimeWarning, match='longer than'):
        ecg_epochs = create_ecg_epochs(raw)
    ica.plot_overlay(ecg_epochs.average())
    plt.close('all')
开发者ID:SherazKhan,项目名称:mne-python,代码行数:32,代码来源:test_ica.py



注:本文中的mne.io.read_raw_fif函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python io.read_raw_kit函数代码示例发布时间:2022-05-27
下一篇:
Python io.read_raw_edf函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap