Example #1
0
def test_make_info():
    """Test some create_info properties."""
    n_ch = np.longlong(1)
    info = create_info(n_ch, 1000., 'eeg')
    assert set(info.keys()) == set(RAW_INFO_FIELDS)

    coil_types = {ch['coil_type'] for ch in info['chs']}
    assert FIFF.FIFFV_COIL_EEG in coil_types

    pytest.raises(TypeError, create_info, ch_names='Test Ch', sfreq=1000)
    pytest.raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=-1000)
    pytest.raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=['eeg', 'eeg'])
    pytest.raises(TypeError, create_info, ch_names=[np.array([1])],
                  sfreq=1000)
    pytest.raises(KeyError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=np.array([1]))
    pytest.raises(KeyError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types='awesome')
    pytest.raises(TypeError, create_info, ['Test Ch'], sfreq=1000,
                  montage=np.array([1]))
    m = make_standard_montage('biosemi32')
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg')
    info.set_montage(m)
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    ch_pos_mon = m._get_ch_pos()
    ch_pos_mon = np.array(
        [ch_pos_mon[ch_name] for ch_name in info['ch_names']])
    # transform to head
    ch_pos_mon += (0., 0., 0.04014)
    assert_allclose(ch_pos, ch_pos_mon, atol=1e-5)
Example #2
0
def test_merge_info():
    """Test merging of multiple Info objects."""
    info_a = create_info(ch_names=["a", "b", "c"], sfreq=1000.0, ch_types=None)
    info_b = create_info(ch_names=["d", "e", "f"], sfreq=1000.0, ch_types=None)
    info_merged = _merge_info([info_a, info_b])
    assert_equal(info_merged["nchan"], 6)
    assert_equal(info_merged["ch_names"], ["a", "b", "c", "d", "e", "f"])
    assert_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.0, ch_types=None)
    # This will break because sfreq is not equal
    assert_raises(RuntimeError, _merge_info, [info_a, info_c])
    _force_update_info(info_a, info_c)
    assert_true(info_c["sfreq"] == info_a["sfreq"])
    assert_true(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
    assert_raises(ValueError, _force_update_info, info_a, dict([("sfreq", 1000.0)]))
    # KIT System-ID
    info_a["kit_system_id"] = 50
    assert_equal(_merge_info((info_a, info_b))["kit_system_id"], 50)
    info_b["kit_system_id"] = 50
    assert_equal(_merge_info((info_a, info_b))["kit_system_id"], 50)
    info_b["kit_system_id"] = 60
    assert_raises(ValueError, _merge_info, (info_a, info_b))
Example #3
0
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_equal(info_merged['nchan'], 6)
    assert_equal(info_merged['ch_names'], ['a', 'b', 'c', 'd', 'e', 'f'])
    assert_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
    assert_raises(RuntimeError, _merge_info, [info_a, info_c])
    _force_update_info(info_a, info_c)
    assert_true(info_c['sfreq'] == info_a['sfreq'])
    assert_true(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
    assert_raises(ValueError, _force_update_info, info_a,
                  dict([('sfreq', 1000.)]))
    # KIT System-ID
    info_a['kit_system_id'] = 50
    assert_equal(_merge_info((info_a, info_b))['kit_system_id'], 50)
    info_b['kit_system_id'] = 50
    assert_equal(_merge_info((info_a, info_b))['kit_system_id'], 50)
    info_b['kit_system_id'] = 60
    assert_raises(ValueError, _merge_info, (info_a, info_b))
Example #4
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info"""
    dig_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(dig_points=dig_points)
    assert_true(info['dig'])
    assert_array_equal(info['dig'][0]['r'], [-106.93, 99.80, 68.81])

    dig_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = dig_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(nasion, lpa, rpa, dig_points[3:], None)
    assert_true(info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info['dig'][idx]['r'],
                       np.array([1.3930, 13.1613, -4.6967]))
    assert_raises(ValueError, _make_dig_points, nasion[:2])
    assert_raises(ValueError, _make_dig_points, None, lpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, rpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, None,
                  dig_points[:, :2])
    assert_raises(ValueError, _make_dig_points, None, None, None, None,
                  dig_points[:, :2])
def test_make_dig_points():
    """Test application of Polhemus HSP to info."""
    extra_points = read_polhemus_fastscan(hsp_fname,
                                          on_header_missing='ignore')
    info = create_info(ch_names=['Test Ch'], sfreq=1000.)
    assert info['dig'] is None

    info['dig'] = _make_dig_points(extra_points=extra_points)
    assert (info['dig'])
    assert_allclose(info['dig'][0]['r'], [-.10693, .09980, .06881])

    elp_points = read_polhemus_fastscan(elp_fname, on_header_missing='ignore')
    nasion, lpa, rpa = elp_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000.)
    assert info['dig'] is None

    info['dig'] = _make_dig_points(nasion, lpa, rpa, elp_points[3:], None)
    assert (info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_allclose(info['dig'][idx]['r'], [.0013930, .0131613, -.0046967])
    pytest.raises(ValueError, _make_dig_points, nasion[:2])
    pytest.raises(ValueError, _make_dig_points, None, lpa[:2])
    pytest.raises(ValueError, _make_dig_points, None, None, rpa[:2])
    pytest.raises(ValueError, _make_dig_points, None, None, None,
                  elp_points[:, :2])
    pytest.raises(ValueError, _make_dig_points, None, None, None, None,
                  elp_points[:, :2])
Example #6
0
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_equal(info_merged['nchan'], 6)
    assert_equal(info_merged['ch_names'], ['a', 'b', 'c', 'd', 'e', 'f'])
    assert_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
    assert_raises(RuntimeError, _merge_info, [info_a, info_c])
    _force_update_info(info_a, info_c)
    assert_true(info_c['sfreq'] == info_a['sfreq'])
    assert_true(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
    assert_raises(ValueError, _force_update_info, info_a,
                  dict([('sfreq', 1000.)]))
    # KIT System-ID
    info_a['kit_system_id'] = 50
    assert_equal(_merge_info((info_a, info_b))['kit_system_id'], 50)
    info_b['kit_system_id'] = 50
    assert_equal(_merge_info((info_a, info_b))['kit_system_id'], 50)
    info_b['kit_system_id'] = 60
    assert_raises(ValueError, _merge_info, (info_a, info_b))
Example #7
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info"""
    dig_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(dig_points=dig_points)
    assert_true(info['dig'])
    assert_array_equal(info['dig'][0]['r'], [-106.93, 99.80, 68.81])

    dig_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = dig_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(nasion, lpa, rpa, dig_points[3:], None)
    assert_true(info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info['dig'][idx]['r'],
                       np.array([1.3930, 13.1613, -4.6967]))
    assert_raises(ValueError, _make_dig_points, nasion[:2])
    assert_raises(ValueError, _make_dig_points, None, lpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, rpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, None,
                  dig_points[:, :2])
    assert_raises(ValueError, _make_dig_points, None, None, None, None,
                  dig_points[:, :2])
Example #8
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info."""
    extra_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert info['dig'] is None

    info['dig'] = _make_dig_points(extra_points=extra_points)
    assert (info['dig'])
    assert_allclose(info['dig'][0]['r'], [-.10693, .09980, .06881])

    elp_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = elp_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert info['dig'] is None

    info['dig'] = _make_dig_points(nasion, lpa, rpa, elp_points[3:], None)
    assert (info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info['dig'][idx]['r'],
                       np.array([.0013930, .0131613, -.0046967]))
    pytest.raises(ValueError, _make_dig_points, nasion[:2])
    pytest.raises(ValueError, _make_dig_points, None, lpa[:2])
    pytest.raises(ValueError, _make_dig_points, None, None, rpa[:2])
    pytest.raises(ValueError, _make_dig_points, None, None, None,
                  elp_points[:, :2])
    pytest.raises(ValueError, _make_dig_points, None, None, None, None,
                  elp_points[:, :2])
Example #9
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info."""
    extra_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(extra_points=extra_points)
    assert_true(info['dig'])
    assert_allclose(info['dig'][0]['r'], [-.10693, .09980, .06881])

    elp_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = elp_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(nasion, lpa, rpa, elp_points[3:], None)
    assert_true(info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info['dig'][idx]['r'],
                       np.array([.0013930, .0131613, -.0046967]))
    assert_raises(ValueError, _make_dig_points, nasion[:2])
    assert_raises(ValueError, _make_dig_points, None, lpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, rpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, None,
                  elp_points[:, :2])
    assert_raises(ValueError, _make_dig_points, None, None, None, None,
                  elp_points[:, :2])
Example #10
0
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_equal(info_merged['nchan'], 6)
    assert_equal(info_merged['ch_names'], ['a', 'b', 'c', 'd', 'e', 'f'])
    assert_raises(ValueError, _merge_info, [info_a, info_a])
Example #11
0
def test_check_consistency():
    """Test consistency check of Info objects."""
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2['bads'] = ['b', 'foo', 'bar']
    pytest.raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2['sfreq'] = 'foo'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['highpass'] = '******'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['lowpass'] = '******'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['filename'] = 'foo'
    with warnings.catch_warnings(record=True) as w:
        info2._check_consistency()
    assert len(w) == 1
    assert (all('filename' in str(ww.message) for ww in w))

    # Silent type conversion to float
    info2 = info.copy()
    info2['sfreq'] = 1
    info2['highpass'] = 2
    info2['lowpass'] = 2
    info2._check_consistency()
    assert (isinstance(info2['sfreq'], float))
    assert (isinstance(info2['highpass'], float))
    assert (isinstance(info2['lowpass'], float))

    # Duplicate channel names
    info2 = info.copy()
    info2['chs'][2]['ch_name'] = 'b'
    pytest.raises(RuntimeError, info2._check_consistency)

    # Duplicates appended with running numbers
    with warnings.catch_warnings(record=True) as w:
        info3 = create_info(ch_names=['a', 'b', 'b', 'c', 'b'], sfreq=1000.)
    assert len(w) == 1
    assert (all('Channel names are not' in '%s' % ww.message for ww in w))
    assert_array_equal(info3['ch_names'], ['a', 'b-0', 'b-1', 'c', 'b-2'])
Example #12
0
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
Example #13
0
def test_duplicate_name_correction():
    """Test duplicate channel names with running number."""
    # When running number is possible
    info = create_info(['A', 'A', 'A'], 1000., verbose='error')
    assert info['ch_names'] == ['A-0', 'A-1', 'A-2']

    # When running number is not possible
    with pytest.raises(ValueError, match='Adding a running number'):
        create_info(['A', 'A', 'A-0'], 1000., verbose='error')
Example #14
0
def test_duplicate_name_correction():
    """Test duplicate channel names with running number."""
    # When running number is possible
    info = create_info(['A', 'A', 'A'], 1000., verbose='error')
    assert info['ch_names'] == ['A-0', 'A-1', 'A-2']

    # When running number is not possible
    with pytest.raises(ValueError, match='Adding a running number'):
        create_info(['A', 'A', 'A-0'], 1000., verbose='error')
Example #15
0
def test_check_consistency():
    """Test consistency check of Info objects."""
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2['bads'] = ['b', 'foo', 'bar']
    assert_raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2['sfreq'] = 'foo'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['highpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['lowpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['filename'] = 'foo'
    with warnings.catch_warnings(record=True) as w:
        info2._check_consistency()
    assert_equal(len(w), 1)
    assert_true(all('filename' in str(ww.message) for ww in w))

    # Silent type conversion to float
    info2 = info.copy()
    info2['sfreq'] = 1
    info2['highpass'] = 2
    info2['lowpass'] = 2
    info2._check_consistency()
    assert_true(isinstance(info2['sfreq'], float))
    assert_true(isinstance(info2['highpass'], float))
    assert_true(isinstance(info2['lowpass'], float))

    # Duplicate channel names
    info2 = info.copy()
    info2['chs'][2]['ch_name'] = 'b'
    assert_raises(RuntimeError, info2._check_consistency)

    # Duplicates appended with running numbers
    with warnings.catch_warnings(record=True) as w:
        info3 = create_info(ch_names=['a', 'b', 'b', 'c', 'b'], sfreq=1000.)
    assert_equal(len(w), 1)
    assert_true(all('Channel names are not' in '%s' % ww.message for ww in w))
    assert_array_equal(info3['ch_names'], ['a', 'b-0', 'b-1', 'c', 'b-2'])
Example #16
0
def test_long_names():
    """Test long name support."""
    info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., verbose='error')
    data = np.empty((2, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 13 + '-0', 'a' * 13 + '-1']
    info = create_info(['a' * 16] * 11, 1000., verbose='error')
    data = np.empty((11, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 12 + '-%s' % ii for ii in range(11)]
Example #17
0
def test_long_names():
    """Test long name support."""
    info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., verbose='error')
    data = np.empty((2, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 13 + '-0', 'a' * 13 + '-1']
    info = create_info(['a' * 16] * 11, 1000., verbose='error')
    data = np.empty((11, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 12 + '-%s' % ii for ii in range(11)]
Example #18
0
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
Example #19
0
def test_check_consistency():
    """Test consistency check of Info objects."""
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2['bads'] = ['b', 'foo', 'bar']
    pytest.raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2['sfreq'] = 'foo'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['highpass'] = '******'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['lowpass'] = '******'
    pytest.raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['filename'] = 'foo'
    with pytest.warns(RuntimeWarning, match='filename'):
        info2._check_consistency()

    # Silent type conversion to float
    info2 = info.copy()
    info2['sfreq'] = 1
    info2['highpass'] = 2
    info2['lowpass'] = 2
    info2._check_consistency()
    assert (isinstance(info2['sfreq'], float))
    assert (isinstance(info2['highpass'], float))
    assert (isinstance(info2['lowpass'], float))

    # Duplicate channel names
    info2 = info.copy()
    info2['chs'][2]['ch_name'] = 'b'
    pytest.raises(RuntimeError, info2._check_consistency)

    # Duplicates appended with running numbers
    with pytest.warns(RuntimeWarning, match='Channel names are not'):
        info3 = create_info(ch_names=['a', 'b', 'b', 'c', 'b'], sfreq=1000.)
    assert_array_equal(info3['ch_names'], ['a', 'b-0', 'b-1', 'c', 'b-2'])
def test_check_consistency():
    """Test consistency check of Info objects."""
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2['bads'] = ['b', 'foo', 'bar']
    assert_raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2['sfreq'] = 'foo'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['highpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['lowpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['filename'] = 'foo'
    with warnings.catch_warnings(record=True) as w:
        info2._check_consistency()
    assert_equal(len(w), 1)
    assert_true(all('filename' in str(ww.message) for ww in w))

    # Silent type conversion to float
    info2 = info.copy()
    info2['sfreq'] = 1
    info2['highpass'] = 2
    info2['lowpass'] = 2
    info2._check_consistency()
    assert_true(isinstance(info2['sfreq'], float))
    assert_true(isinstance(info2['highpass'], float))
    assert_true(isinstance(info2['lowpass'], float))

    # Duplicate channel names
    info2 = info.copy()
    info2['chs'][2]['ch_name'] = 'b'
    assert_raises(RuntimeError, info2._check_consistency)
Example #21
0
def test_make_info():
    """Test some create_info properties
    """
    n_ch = 1
    info = create_info(n_ch, 1000., 'eeg')
    assert_equal(sorted(info.keys()), sorted(RAW_INFO_FIELDS))

    coil_types = set([ch['coil_type'] for ch in info['chs']])
    assert_true(FIFF.FIFFV_COIL_EEG in coil_types)

    assert_raises(TypeError, create_info, ch_names='Test Ch', sfreq=1000)
    assert_raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=-1000)
    assert_raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=['eeg', 'eeg'])
    assert_raises(TypeError, create_info, ch_names=[np.array([1])],
                  sfreq=1000)
    assert_raises(TypeError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=np.array([1]))
    assert_raises(KeyError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types='awesome')
    assert_raises(TypeError, create_info, ['Test Ch'], sfreq=1000,
                  ch_types=None, montage=np.array([1]))
    m = read_montage('biosemi32')
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=m)
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)

    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    d = read_dig_montage(hsp_fname, None, elp_fname, names, unit='m',
                         transform=False)
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=d)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)

    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=[d, m])
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=[d, 'biosemi32'])
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
Example #22
0
def test_make_info():
    """Test some create_info properties
    """
    n_ch = 1
    info = create_info(n_ch, 1000., 'eeg')
    assert_equal(sorted(info.keys()), sorted(RAW_INFO_FIELDS))

    coil_types = set([ch['coil_type'] for ch in info['chs']])
    assert_true(FIFF.FIFFV_COIL_EEG in coil_types)

    assert_raises(TypeError, create_info, ch_names='Test Ch', sfreq=1000)
    assert_raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=-1000)
    assert_raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=['eeg', 'eeg'])
    assert_raises(TypeError, create_info, ch_names=[np.array([1])],
                  sfreq=1000)
    assert_raises(TypeError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types=np.array([1]))
    assert_raises(KeyError, create_info, ch_names=['Test Ch'], sfreq=1000,
                  ch_types='awesome')
    assert_raises(TypeError, create_info, ['Test Ch'], sfreq=1000,
                  ch_types=None, montage=np.array([1]))
    m = read_montage('biosemi32')
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=m)
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)

    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    d = read_dig_montage(hsp_fname, None, elp_fname, names, unit='m',
                         transform=False)
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=d)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)

    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=[d, m])
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg',
                       montage=[d, 'biosemi32'])
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    assert_array_equal(ch_pos, m.pos)
    idents = [p['ident'] for p in info['dig']]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
Example #23
0
def test_array_copy():
    """Test copying during construction."""
    info = create_info(1, 1000.)
    data = np.empty((1, 1000))
    # 'auto' (default)
    raw = RawArray(data, info)
    assert raw._data is data
    assert raw.info is not info
    raw = RawArray(data.astype(np.float32), info)
    assert raw._data is not data
    assert raw.info is not info
    # 'info' (more restrictive)
    raw = RawArray(data, info, copy='info')
    assert raw._data is data
    assert raw.info is not info
    with pytest.raises(ValueError, match="data copying was not .* copy='info"):
        RawArray(data.astype(np.float32), info, copy='info')
    # 'data'
    raw = RawArray(data, info, copy='data')
    assert raw._data is not data
    assert raw.info is info
    # 'both'
    raw = RawArray(data, info, copy='both')
    assert raw._data is not data
    assert raw.info is not info
    raw = RawArray(data.astype(np.float32), info, copy='both')
    assert raw._data is not data
    assert raw.info is not info
    # None
    raw = RawArray(data, info, copy=None)
    assert raw._data is data
    assert raw.info is info
    with pytest.raises(ValueError, match='data copying was not .* copy=None'):
        RawArray(data.astype(np.float32), info, copy=None)
Example #24
0
def test_long_names():
    """Test long name support."""
    info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., verbose='error')
    data = np.empty((2, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 15 + 'b', 'a' * 16]
    # and a way to get the old behavior
    raw.rename_channels({k: k[:13]
                         for k in raw.ch_names},
                        allow_duplicates=True,
                        verbose='error')
    assert raw.ch_names == ['a' * 13 + '-0', 'a' * 13 + '-1']
    info = create_info(['a' * 16] * 11, 1000., verbose='error')
    data = np.empty((11, 1000))
    raw = RawArray(data, info)
    assert raw.ch_names == ['a' * 16 + '-%s' % ii for ii in range(11)]
def eeglab2mne(file_name):
    """ Loads EEGLab epochs from Matlab and return MNE-python epochs"""
    # Convert from eeglab structure to mne Epochs
    import scipy.io as sio
    from itertools import product
    from mne.io.meas_info import create_info
    from mne.epochs import EpochsArray
    mat = sio.loadmat(file_name, squeeze_me=True, struct_as_record=False)
    event_id = dict()
    for visible, expect, reward in product('HL', 'EU', 'RP'):
        event_id['/'.join((visible, expect, reward))] = (
            1 * (visible == 'H') + 10 * (expect == 'U') +
            100 * (reward == 'P'))
    data = list()
    events = list()
    for visible, expect, reward in product('HL', 'EU', 'RP'):
        struct = visible + expect + reward
        eeg_data = mat[struct]
        n_chan, n_time, n_trials = eeg_data.shape
        data.append(eeg_data.transpose([2, 0, 1]))
        event = event_id['/'.join((visible, expect, reward))]
        events.append(np.ones(n_trials) * event)
    data = np.vstack(data)
    events = np.hstack(events)

    times = np.linspace(-1.8, 2., data.shape[2])
    sfreq = len(times) / np.ptp([times[0], times[-1]])
    chan_names = ['eeg_%s' % chan for chan in range(64)]
    chan_types = ['eeg' for ii in range(64)]
    events = np.c_[np.cumsum(np.ones_like(events)) * 5 * sfreq,
                   np.zeros_like(events), events]
    info = create_info(chan_names, sfreq, chan_types)
    epochs = EpochsArray(data, info, events=np.array(events, int), tmin=-1.8,
                         verbose=False, event_id=event_id)
    return epochs
Example #26
0
def _get_info(eeg, montage, eog=()):
    """Get measurement info."""
    info = _empty_info(sfreq=eeg.get_sample_frequency())

    # add the ch_names and info['chs'][idx]['loc']

    ch_names =[eeg.get_channel(i)[0] for i in range(eeg.get_channel_count())]
    print ch_names

    #elif isinstance(montage, string_types):
    #    path = op.dirname(montage)
    #else:  # if eeg.chanlocs is empty, we still need default chan names
    #    ch_names = ["EEG %03d" % ii for ii in range(eeg.get_channel_count())]

    #if montage is None:
    info = create_info(ch_names, eeg.get_sample_frequency(), ch_types='eeg')
    #else:
    #    _check_update_montage(info, montage, path=path,
    #                          update_ch_names=True)

    info['buffer_size_sec'] = 1.  # reasonable default
    # update the info dict

    if eog == 'auto':
        eog = _find_channels(ch_names)

    for idx, ch in enumerate(info['chs']):
        ch['cal'] = CAL
        if ch['ch_name'] in eog or idx in eog:
            ch['coil_type'] = FIFF.FIFFV_COIL_NONE
            ch['kind'] = FIFF.FIFFV_EOG_CH
    return info
Example #27
0
def test_array_copy():
    """Test copying during construction."""
    info = create_info(1, 1000.)
    data = np.empty((1, 1000))
    # 'auto' (default)
    raw = RawArray(data, info)
    assert raw._data is data
    assert raw.info is not info
    raw = RawArray(data.astype(np.float32), info)
    assert raw._data is not data
    assert raw.info is not info
    # 'info' (more restrictive)
    raw = RawArray(data, info, copy='info')
    assert raw._data is data
    assert raw.info is not info
    with pytest.raises(ValueError, match="data copying was not .* copy='info"):
        RawArray(data.astype(np.float32), info, copy='info')
    # 'data'
    raw = RawArray(data, info, copy='data')
    assert raw._data is not data
    assert raw.info is info
    # 'both'
    raw = RawArray(data, info, copy='both')
    assert raw._data is not data
    assert raw.info is not info
    raw = RawArray(data.astype(np.float32), info, copy='both')
    assert raw._data is not data
    assert raw.info is not info
    # None
    raw = RawArray(data, info, copy=None)
    assert raw._data is data
    assert raw.info is info
    with pytest.raises(ValueError, match='data copying was not .* copy=None'):
        RawArray(data.astype(np.float32), info, copy=None)
Example #28
0
def test_duplicate_name_correction():
    """Test duplicate channel names with running number."""
    # When running number is possible
    info = create_info(['A', 'A', 'A'], 1000., verbose='error')
    assert info['ch_names'] == ['A-0', 'A-1', 'A-2']

    # When running number is not possible but alpha numeric is
    info = create_info(['A', 'A', 'A-0'], 1000., verbose='error')
    assert info['ch_names'] == ['A-a', 'A-1', 'A-0']

    # When a single addition is not sufficient
    with pytest.raises(ValueError, match='Adding a single alphanumeric'):
        ch_n = ['A', 'A']
        # add all options for first duplicate channel (0)
        ch_n.extend([f'{ch_n[0]}-{c}' for c in string.ascii_lowercase + '0'])
        create_info(ch_n, 1000., verbose='error')
Example #29
0
def test_export_edf_annotations(tmp_path):
    """Test that exporting EDF preserves annotations."""
    rng = np.random.RandomState(123456)
    format = 'edf'
    ch_types = [
        'eeg', 'eeg', 'stim', 'ecog', 'ecog', 'seeg', 'eog', 'ecg', 'emg',
        'dbs', 'bio'
    ]
    ch_names = np.arange(len(ch_types)).astype(str).tolist()
    info = create_info(ch_names, sfreq=1000, ch_types=ch_types)
    data = rng.random(size=(len(ch_names), 2000)) * 1.e-5
    raw = RawArray(data, info)

    annotations = Annotations(onset=[0.01, 0.05, 0.90, 1.05],
                              duration=[0, 1, 0, 0],
                              description=['test1', 'test2', 'test3', 'test4'])
    raw.set_annotations(annotations)

    # export
    temp_fname = op.join(str(tmp_path), f'test.{format}')
    raw.export(temp_fname)

    # read in the file
    raw_read = read_raw_edf(temp_fname, preload=True)
    assert_array_equal(raw.annotations.onset, raw_read.annotations.onset)
    assert_array_equal(raw.annotations.duration, raw_read.annotations.duration)
    assert_array_equal(raw.annotations.description,
                       raw_read.annotations.description)
def load_FieldTrip_data(meg_fname):
    from mne.io.meas_info import create_info
    from mne.epochs import EpochsArray
    """XXX Here explain what this does"""
    # import information from fieldtrip data to get data shape
    ft_data = sio.loadmat(meg_fname[:-4] + '.mat', squeeze_me=True,
                          struct_as_record=True)['data']
    # import binary MEG data
    bin_data = np.fromfile(meg_fname[:-4] + '.dat', dtype=np.float32)
    Xdim = ft_data['Xdim'].item()
    bin_data = np.reshape(bin_data, Xdim[[2, 1, 0]]).transpose([2, 1, 0])

    # Create an MNE Epoch
    n_trial, n_chans, n_time = bin_data.shape
    sfreq = ft_data['fsample'].item()
    time = ft_data['time'].item()[0]
    tmin = min(time)
    chan_names = [str(label) for label in ft_data['label'].item()]
    chan_types = np.squeeze(np.concatenate(
        (np.tile(['grad', 'grad', 'mag'], (1, 102)),
         np.tile('misc', (1, n_chans - 306))), axis=1))
    info = create_info(chan_names, sfreq, chan_types)
    events = np.c_[np.cumsum(np.ones(n_trial)) * 5 * sfreq,
                   np.zeros(n_trial),
                   ft_data['trialinfo'].item()]
    epochs = EpochsArray(bin_data, info, events=events, tmin=tmin)

    return epochs
Example #31
0
def test_check_consistency():
    """Test consistency check of Info objects."""
    info = create_info(ch_names=["a", "b", "c"], sfreq=1000.0)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.0)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2["bads"] = ["b", "foo", "bar"]
    assert_raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2["sfreq"] = "foo"
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2["highpass"] = "******"
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2["lowpass"] = "******"
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2["filename"] = "foo"
    assert_raises(KeyError, info2._check_consistency)

    # Silent type conversion to float
    info2 = info.copy()
    info2["sfreq"] = 1
    info2["highpass"] = 2
    info2["lowpass"] = 2
    info2._check_consistency()
    assert_true(isinstance(info2["sfreq"], float))
    assert_true(isinstance(info2["highpass"], float))
    assert_true(isinstance(info2["lowpass"], float))

    # Duplicate channel names
    info2 = info.copy()
    info2["chs"][2]["ch_name"] = "b"
    assert_raises(RuntimeError, info2._check_consistency)
Example #32
0
def test_redundant():
    """Test some of the redundant properties of info."""
    # Indexing
    info = create_info(ch_names=["a", "b", "c"], sfreq=1000.0, ch_types=None)
    assert_equal(info["ch_names"][0], "a")
    assert_equal(info["ch_names"][1], "b")
    assert_equal(info["ch_names"][2], "c")

    # Equality
    assert_equal(info["ch_names"], info["ch_names"])
    assert_equal(info["ch_names"], ["a", "b", "c"])

    # No channels in info
    info = create_info(ch_names=[], sfreq=1000.0, ch_types=None)
    assert_equal(info["ch_names"], [])

    # List should be read-only
    info = create_info(ch_names=["a", "b", "c"], sfreq=1000.0, ch_types=None)
Example #33
0
def test_redundant():
    """Test some of the redundant properties of info"""
    # Indexing
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'][0], 'a')
    assert_equal(info['ch_names'][1], 'b')
    assert_equal(info['ch_names'][2], 'c')

    # Equality
    assert_equal(info['ch_names'], info['ch_names'])
    assert_equal(info['ch_names'], ['a', 'b', 'c'])

    # No channels in info
    info = create_info(ch_names=[], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'], [])

    # List should be read-only
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
Example #34
0
def test_redundant():
    """Test some of the redundant properties of info."""
    # Indexing
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
    assert info['ch_names'][0] == 'a'
    assert info['ch_names'][1] == 'b'
    assert info['ch_names'][2] == 'c'

    # Equality
    assert info['ch_names'] == info['ch_names']
    assert info['ch_names'] == ['a', 'b', 'c']

    # No channels in info
    info = create_info(ch_names=[], sfreq=1000., ch_types=None)
    assert info['ch_names'] == []

    # List should be read-only
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
Example #35
0
def test_redundant():
    """Test some of the redundant properties of info"""
    # Indexing
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'][0], 'a')
    assert_equal(info['ch_names'][1], 'b')
    assert_equal(info['ch_names'][2], 'c')

    # Equality
    assert_equal(info['ch_names'], info['ch_names'])
    assert_equal(info['ch_names'], ['a', 'b', 'c'])

    # No channels in info
    info = create_info(ch_names=[], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'], [])

    # List should be read-only
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
Example #36
0
    def __init__(self,
                 input_fname,
                 montage=None,
                 eog=None,
                 misc=(-4, -3, -2, -1),
                 stim_channel=None,
                 scale=1e-6,
                 sfreq=250,
                 missing_tol=1,
                 preload=True,
                 verbose=None):

        bci_info = {'missing_tol': missing_tol, 'stim_channel': stim_channel}
        if not eog:
            eog = list()
        if not misc:
            misc = list()

        nsamps, nchan = self._get_data_dims(input_fname)

        last_samps = [nsamps - 1]
        ch_names = ['EEG %03d' % num for num in range(1, nchan + 1)]
        ch_types = ['eeg'] * nchan
        if misc:
            misc_names = ['MISC %03d' % ii for ii in range(1, len(misc) + 1)]
            misc_types = ['misc'] * len(misc)
            for ii, mi in enumerate(misc):
                ch_names[mi] = misc_names[ii]
                ch_types[mi] = misc_types[ii]
        if eog:
            eog_names = ['EOG %03d' % ii for ii in range(len(eog))]
            eog_types = ['eog'] * len(eog)
            for ii, ei in enumerate(eog):
                ch_names[ei] = eog_names[ii]
                ch_types[ei] = eog_types[ii]
        if stim_channel:
            ch_names[stim_channel] = 'STI 014'
            ch_types[stim_channel] = 'stim'

        # mark last channel as the timestamp channel
        ch_names[-1] = "Timestamps"
        ch_types[-1] = "misc"

        # fix it for eog and misc marking
        info = create_info(ch_names, sfreq, ch_types, montage)
        info["buffer_size_sec"] = 1.
        super(RawOpenBCI, self).__init__(info,
                                         last_samps=last_samps,
                                         raw_extras=[bci_info],
                                         filenames=[input_fname],
                                         preload=False,
                                         verbose=verbose)
        # load data
        if preload:
            self.preload = preload
            logger.info('Reading raw data from %s...' % input_fname)
            self._data = self._read_segment()
Example #37
0
def test_create_info_grad(kwargs, want):
    """Test create_info behavior with grad coils."""
    info = create_info(6, 256, ["eeg", "misc", "grad", "grad", "mag", "hbo"])
    # Put these in an order such that grads get named "2" and "3", since
    # they get picked based first on coil_type then ch_name...
    assert [ch['ch_name'] for ch in info['chs']
            if ch['coil_type'] == FIFF.FIFFV_COIL_VV_PLANAR_T1] == ['2', '3']
    picks = pick_types(info, **kwargs)
    assert_array_equal(picks, want)
Example #38
0
def test_check_consistency():
    """Test consistency check of Info objects"""
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000.)

    # This should pass
    info._check_consistency()

    # Info without any channels
    info_empty = create_info(ch_names=[], sfreq=1000.)
    info_empty._check_consistency()

    # Bad channels that are not in the info object
    info2 = info.copy()
    info2['bads'] = ['b', 'foo', 'bar']
    assert_raises(RuntimeError, info2._check_consistency)

    # Bad data types
    info2 = info.copy()
    info2['sfreq'] = 'foo'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['highpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    info2 = info.copy()
    info2['lowpass'] = '******'
    assert_raises(ValueError, info2._check_consistency)

    # Silent type conversion to float
    info2 = info.copy()
    info2['sfreq'] = 1
    info2['highpass'] = 2
    info2['lowpass'] = 2
    info2._check_consistency()
    assert_true(isinstance(info2['sfreq'], float))
    assert_true(isinstance(info2['highpass'], float))
    assert_true(isinstance(info2['lowpass'], float))

    # Duplicate channel names
    info2 = info.copy()
    info2['chs'][2]['ch_name'] = 'b'
    assert_raises(RuntimeError, info2._check_consistency)
Example #39
0
def test_get_montage():
    """Test ContainsMixin.get_montage()."""
    ch_names = make_standard_montage('standard_1020').ch_names
    sfreq = 512
    data = np.zeros((len(ch_names), sfreq * 2))
    raw = RawArray(data, create_info(ch_names, sfreq, 'eeg'))
    raw.set_montage('standard_1020')

    assert len(raw.get_montage().ch_names) == len(ch_names)
    raw.info['bads'] = [ch_names[0]]
    assert len(raw.get_montage().ch_names) == len(ch_names)

    # test info
    raw = RawArray(data, create_info(ch_names, sfreq, 'eeg'))
    raw.set_montage('standard_1020')

    assert len(raw.info.get_montage().ch_names) == len(ch_names)
    raw.info['bads'] = [ch_names[0]]
    assert len(raw.info.get_montage().ch_names) == len(ch_names)
Example #40
0
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
Example #41
0
def test_array_epochs():
    """Test creating evoked from array
    """
    tempdir = _TempDir()

    # creating
    rng = np.random.RandomState(42)
    data1 = rng.randn(20, 60)
    sfreq = 1e3
    ch_names = ['EEG %03d' % (i + 1) for i in range(20)]
    types = ['eeg'] * 20
    info = create_info(ch_names, sfreq, types)
    evoked1 = EvokedArray(data1, info, tmin=-0.01)

    # save, read, and compare evokeds
    tmp_fname = op.join(tempdir, 'evkdary-ave.fif')
    evoked1.save(tmp_fname)
    evoked2 = read_evokeds(tmp_fname)[0]
    data2 = evoked2.data
    assert_allclose(data1, data2)
    assert_allclose(evoked1.times, evoked2.times)
    assert_equal(evoked1.first, evoked2.first)
    assert_equal(evoked1.last, evoked2.last)
    assert_equal(evoked1.kind, evoked2.kind)
    assert_equal(evoked1.nave, evoked2.nave)

    # now compare with EpochsArray (with single epoch)
    data3 = data1[np.newaxis, :, :]
    events = np.c_[10, 0, 1]
    evoked3 = EpochsArray(data3, info, events=events, tmin=-0.01).average()
    assert_allclose(evoked1.data, evoked3.data)
    assert_allclose(evoked1.times, evoked3.times)
    assert_equal(evoked1.first, evoked3.first)
    assert_equal(evoked1.last, evoked3.last)
    assert_equal(evoked1.kind, evoked3.kind)
    assert_equal(evoked1.nave, evoked3.nave)

    # test match between channels info and data
    ch_names = ['EEG %03d' % (i + 1) for i in range(19)]
    types = ['eeg'] * 19
    info = create_info(ch_names, sfreq, types)
    assert_raises(ValueError, EvokedArray, data1, info, tmin=-0.01)
Example #42
0
def test_array_epochs():
    """Test creating evoked from array
    """
    tempdir = _TempDir()

    # creating
    rng = np.random.RandomState(42)
    data1 = rng.randn(20, 60)
    sfreq = 1e3
    ch_names = ['EEG %03d' % (i + 1) for i in range(20)]
    types = ['eeg'] * 20
    info = create_info(ch_names, sfreq, types)
    evoked1 = EvokedArray(data1, info, tmin=-0.01)

    # save, read, and compare evokeds
    tmp_fname = op.join(tempdir, 'evkdary-ave.fif')
    evoked1.save(tmp_fname)
    evoked2 = read_evokeds(tmp_fname)[0]
    data2 = evoked2.data
    assert_allclose(data1, data2)
    assert_allclose(evoked1.times, evoked2.times)
    assert_equal(evoked1.first, evoked2.first)
    assert_equal(evoked1.last, evoked2.last)
    assert_equal(evoked1.kind, evoked2.kind)
    assert_equal(evoked1.nave, evoked2.nave)

    # now compare with EpochsArray (with single epoch)
    data3 = data1[np.newaxis, :, :]
    events = np.c_[10, 0, 1]
    evoked3 = EpochsArray(data3, info, events=events, tmin=-0.01).average()
    assert_allclose(evoked1.data, evoked3.data)
    assert_allclose(evoked1.times, evoked3.times)
    assert_equal(evoked1.first, evoked3.first)
    assert_equal(evoked1.last, evoked3.last)
    assert_equal(evoked1.kind, evoked3.kind)
    assert_equal(evoked1.nave, evoked3.nave)

    # test match between channels info and data
    ch_names = ['EEG %03d' % (i + 1) for i in range(19)]
    types = ['eeg'] * 19
    info = create_info(ch_names, sfreq, types)
    assert_raises(ValueError, EvokedArray, data1, info, tmin=-0.01)
Example #43
0
def test_channel_name_list():
    """Test the _ChannelNamesList object"""
    # Indexing
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'][0], 'a')
    assert_equal(info['ch_names'][1], 'b')
    assert_equal(info['ch_names'][2], 'c')

    # Equality
    assert_equal(info['ch_names'], info['ch_names'])
    assert_equal(info['ch_names'], ['a', 'b', 'c'])

    # No channels in info
    info = create_info(ch_names=[], sfreq=1000., ch_types=None)
    assert_equal(info['ch_names'], [])

    # List should be read-only
    info = create_info(ch_names=['a', 'b', 'c'], sfreq=1000., ch_types=None)

    def _test_assignment():
        info['ch_names'][0] = 'foo'
    assert_raises(RuntimeError, _test_assignment)

    def _test_concatenation():
        info['ch_names'] += ['foo']
    assert_raises(RuntimeError, _test_concatenation)

    def _test_appending():
        info['ch_names'].append('foo')
    assert_raises(RuntimeError, _test_appending)

    def _test_removal():
        del info['ch_names'][0]
    assert_raises(AttributeError, _test_removal)

    # Concatenation
    assert_equal(info['ch_names'] + ['d'], ['a', 'b', 'c', 'd'])

    # Representation
    assert_equal(repr(info['ch_names']),
                 "<ChannelNameList | 3 channels | a, b, c>")
Example #44
0
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])
Example #45
0
def test_picks_by_channels():
    """Test creating pick_lists"""

    rng = np.random.RandomState(909)

    test_data = rng.random_sample((4, 2000))
    ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
    ch_types = ['grad', 'mag', 'mag', 'eeg']
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 3)
    assert_equal(pick_list[0][0], 'mag')
    pick_list2 = _picks_by_type(raw.info, meg_combined=False)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], 'mag')

    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2) + 1)
    assert_equal(pick_list2[0][0], 'meg')

    test_data = rng.random_sample((4, 2000))
    ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
    ch_types = ['mag', 'mag', 'mag', 'mag']
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    # Make sure checks for list input work.
    assert_raises(ValueError, pick_channels, ch_names, 'MEG 001')
    assert_raises(ValueError, pick_channels, ch_names, ['MEG 001'], 'hi')

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 1)
    assert_equal(pick_list[0][0], 'mag')
    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], 'mag')
def test_picks_by_channels():
    """Test creating pick_lists"""

    rng = np.random.RandomState(909)

    test_data = rng.random_sample((4, 2000))
    ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
    ch_types = ['grad', 'mag', 'mag', 'eeg']
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 3)
    assert_equal(pick_list[0][0], 'mag')
    pick_list2 = _picks_by_type(raw.info, meg_combined=False)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], 'mag')

    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2) + 1)
    assert_equal(pick_list2[0][0], 'meg')

    test_data = rng.random_sample((4, 2000))
    ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
    ch_types = ['mag', 'mag', 'mag', 'mag']
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    # Make sure checks for list input work.
    assert_raises(ValueError, pick_channels, ch_names, 'MEG 001')
    assert_raises(ValueError, pick_channels, ch_names, ['MEG 001'], 'hi')

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 1)
    assert_equal(pick_list[0][0], 'mag')
    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], 'mag')
Example #47
0
def test_array_epochs():
    """Test creating epochs from array
    """

    # creating
    rng = np.random.RandomState(42)
    data = rng.random_sample((10, 20, 300))
    sfreq = 1e3
    ch_names = ["EEG %03d" % (i + 1) for i in range(20)]
    types = ["eeg"] * 20
    info = create_info(ch_names, sfreq, types)
    events = np.c_[np.arange(1, 600, 60), np.zeros(10), [1, 2] * 5]
    event_id = {"a": 1, "b": 2}
    epochs = EpochsArray(data, info, events=events, event_id=event_id, tmin=-0.2)

    # saving
    temp_fname = op.join(tempdir, "test-epo.fif")
    epochs.save(temp_fname)
    epochs2 = read_epochs(temp_fname)
    data2 = epochs2.get_data()
    assert_allclose(data, data2)
    assert_allclose(epochs.times, epochs2.times)
    assert_equal(epochs.event_id, epochs2.event_id)
    assert_array_equal(epochs.events, epochs2.events)

    # plotting
    import matplotlib

    matplotlib.use("Agg")  # for testing don't use X server
    epochs[0].plot()

    # indexing
    assert_array_equal(np.unique(epochs["a"].events[:, 2]), np.array([1]))
    assert_equal(len(epochs[:2]), 2)
    data[0, 5, 150] = 3000
    data[1, :, :] = 0
    data[2, 5, 210] = 3000
    data[3, 5, 260] = 0
    epochs = EpochsArray(
        data,
        info,
        events=events,
        event_id=event_id,
        tmin=0,
        reject=dict(eeg=1000),
        flat=dict(eeg=1e-1),
        reject_tmin=0.1,
        reject_tmax=0.2,
    )
    assert_equal(len(epochs), len(events) - 2)
    assert_equal(epochs.drop_log[0], ["EEG 006"])
    assert_equal(len(events), len(epochs.selection))
Example #48
0
    def __init__(self, input_fname, montage=None, eog=None,
                 misc=(-4, -3, -2, -1), stim_channel=None, scale=1e-6, sfreq=250,
                 missing_tol=1, preload=True, verbose=None):

        bci_info = {'missing_tol': missing_tol, 'stim_channel': stim_channel}
        openbci_channames = ["FP1", "FP2", "C3", "C4", "P7", "P8", "O1", "O2", "F7", "F8", "F3", "F4", "T7", "T8", "P3", "P4"]
        if not eog:
            eog = list()
        if not misc:
            misc = list()
        nsamps, nchan = self._get_data_dims(input_fname)

        last_samps = [nsamps - 1]
        ch_names = ['EEG %03d' % num for num in range(1, nchan + 1)]
        ch_names[:nchan-4] = openbci_channames[:nchan-4]
        ch_types = ['eeg'] * nchan

        

        if misc:
            misc_names = ['MISC %03d' % ii for ii in range(1, len(misc) + 1)]
            misc_types = ['misc'] * len(misc)
            for ii, mi in enumerate(misc):
                ch_names[mi] = misc_names[ii]
                ch_types[mi] = misc_types[ii]
        if eog:
            eog_names = ['EOG %03d' % ii for ii in range(len(eog))]
            eog_types = ['eog'] * len(eog)
            for ii, ei in enumerate(eog):
                ch_names[ei] = eog_names[ii]
                ch_types[ei] = eog_types[ii]
        if stim_channel:
            ch_names[stim_channel] = 'STI 014'
            ch_types[stim_channel] = 'stim'

        # mark last channel as the timestamp channel
        ch_names[-1] = "Timestamps"
        ch_types[-1] = "misc"

        # fix it for eog and misc marking
        info = create_info(ch_names, sfreq, ch_types, montage)
        info["buffer_size_sec"] = 1.
        super(RawOpenBCI, self).__init__(info, last_samps=last_samps,
                                         raw_extras=[bci_info],
                                         filenames=[input_fname],
                                         preload=False, verbose=verbose)
        # load data
        if preload:
            self.preload = preload
            logger.info('Reading raw data from %s...' % input_fname)
            self._data = self._read_segment()
Example #49
0
def test_make_info():
    """Test some create_info properties."""
    n_ch = 1
    info = create_info(n_ch, 1000.0, "eeg")
    assert_equal(sorted(info.keys()), sorted(RAW_INFO_FIELDS))

    coil_types = set([ch["coil_type"] for ch in info["chs"]])
    assert_true(FIFF.FIFFV_COIL_EEG in coil_types)

    assert_raises(TypeError, create_info, ch_names="Test Ch", sfreq=1000)
    assert_raises(ValueError, create_info, ch_names=["Test Ch"], sfreq=-1000)
    assert_raises(ValueError, create_info, ch_names=["Test Ch"], sfreq=1000, ch_types=["eeg", "eeg"])
    assert_raises(TypeError, create_info, ch_names=[np.array([1])], sfreq=1000)
    assert_raises(TypeError, create_info, ch_names=["Test Ch"], sfreq=1000, ch_types=np.array([1]))
    assert_raises(KeyError, create_info, ch_names=["Test Ch"], sfreq=1000, ch_types="awesome")
    assert_raises(TypeError, create_info, ["Test Ch"], sfreq=1000, ch_types=None, montage=np.array([1]))
    m = read_montage("biosemi32")
    info = create_info(ch_names=m.ch_names, sfreq=1000.0, ch_types="eeg", montage=m)
    ch_pos = [ch["loc"][:3] for ch in info["chs"]]
    assert_array_equal(ch_pos, m.pos)

    names = ["nasion", "lpa", "rpa", "1", "2", "3", "4", "5"]
    d = read_dig_montage(hsp_fname, None, elp_fname, names, unit="m", transform=False)
    info = create_info(ch_names=m.ch_names, sfreq=1000.0, ch_types="eeg", montage=d)
    idents = [p["ident"] for p in info["dig"]]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)

    info = create_info(ch_names=m.ch_names, sfreq=1000.0, ch_types="eeg", montage=[d, m])
    ch_pos = [ch["loc"][:3] for ch in info["chs"]]
    assert_array_equal(ch_pos, m.pos)
    idents = [p["ident"] for p in info["dig"]]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
    info = create_info(ch_names=m.ch_names, sfreq=1000.0, ch_types="eeg", montage=[d, "biosemi32"])
    ch_pos = [ch["loc"][:3] for ch in info["chs"]]
    assert_array_equal(ch_pos, m.pos)
    idents = [p["ident"] for p in info["dig"]]
    assert_true(FIFF.FIFFV_POINT_NASION in idents)
Example #50
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info."""
    extra_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=["Test Ch"], sfreq=1000.0, ch_types=None)
    assert_false(info["dig"])

    info["dig"] = _make_dig_points(extra_points=extra_points)
    assert_true(info["dig"])
    assert_allclose(info["dig"][0]["r"], [-0.10693, 0.09980, 0.06881])

    elp_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = elp_points[:3]
    info = create_info(ch_names=["Test Ch"], sfreq=1000.0, ch_types=None)
    assert_false(info["dig"])

    info["dig"] = _make_dig_points(nasion, lpa, rpa, elp_points[3:], None)
    assert_true(info["dig"])
    idx = [d["ident"] for d in info["dig"]].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info["dig"][idx]["r"], np.array([0.0013930, 0.0131613, -0.0046967]))
    assert_raises(ValueError, _make_dig_points, nasion[:2])
    assert_raises(ValueError, _make_dig_points, None, lpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, rpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, None, elp_points[:, :2])
    assert_raises(ValueError, _make_dig_points, None, None, None, None, elp_points[:, :2])
Example #51
0
def test_picks_by_channels():
    """Test creating pick_lists"""

    rng = np.random.RandomState(909)

    test_data = rng.random_sample((4, 2000))
    ch_names = ["MEG %03d" % i for i in [1, 2, 3, 4]]
    ch_types = ["grad", "mag", "mag", "eeg"]
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 3)
    assert_equal(pick_list[0][0], "mag")
    pick_list2 = _picks_by_type(raw.info, meg_combined=False)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], "mag")

    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2) + 1)
    assert_equal(pick_list2[0][0], "meg")

    test_data = rng.random_sample((4, 2000))
    ch_names = ["MEG %03d" % i for i in [1, 2, 3, 4]]
    ch_types = ["mag", "mag", "mag", "mag"]
    sfreq = 250.0
    info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
    raw = RawArray(test_data, info)

    pick_list = _picks_by_type(raw.info)
    assert_equal(len(pick_list), 1)
    assert_equal(pick_list[0][0], "mag")
    pick_list2 = _picks_by_type(raw.info, meg_combined=True)
    assert_equal(len(pick_list), len(pick_list2))
    assert_equal(pick_list2[0][0], "mag")
Example #52
0
def add_channels(inst, data, ch_names, ch_types):
    from mne.io import _BaseRaw, RawArray
    from mne.epochs import _BaseEpochs, EpochsArray
    from mne import create_info
    if 'meg' in ch_types or 'eeg' in ch_types:
        return NotImplementedError('Can only add misc, stim and ieeg channels')
    info = create_info(ch_names=ch_names, sfreq=inst.info['sfreq'],
                       ch_types=ch_types)
    if isinstance(inst, _BaseRaw):
        for key in ('buffer_size_sec', 'filename'):
            info[key] = inst.info[key]
        new_inst = RawArray(data, info=info, first_samp=inst._first_samps[0])
    elif isinstance(inst, _BaseEpochs):
        new_inst = EpochsArray(data, info=info)
    else:
        raise ValueError('unknown inst type')
    return inst.add_channels([new_inst], copy=True)
Example #53
0
def test_pick_seeg():
    names = 'A1 A2 Fz O OTp1 OTp2 OTp3'.split()
    types = 'mag mag eeg eeg seeg seeg seeg'.split()
    info = create_info(names, 1024., types)
    idx = channel_indices_by_type(info)
    assert_array_equal(idx['mag'], [0, 1])
    assert_array_equal(idx['eeg'], [2, 3])
    assert_array_equal(idx['seeg'], [4, 5, 6])
    assert_array_equal(pick_types(info, meg=False, seeg=True), [4, 5, 6])
    for i, t in enumerate(types):
        assert_equal(channel_type(info, i), types[i])
    raw = RawArray(zeros((len(names), 10)), info)
    events = array([[1, 0, 0], [2, 0, 0]]).astype('d')
    epochs = Epochs(raw, events, {'event': 0}, -1e-5, 1e-5)
    evoked = epochs.average(pick_types(epochs.info, meg=True, seeg=True))
    e_seeg = pick_types_evoked(evoked, meg=False, seeg=True)
    for l, r in zip(e_seeg.ch_names, names[4:]):
        assert_equal(l, r)
Example #54
0
def test_pick_seeg():
    """Test picking with SEEG
    """
    names = "A1 A2 Fz O OTp1 OTp2 OTp3".split()
    types = "mag mag eeg eeg seeg seeg seeg".split()
    info = create_info(names, 1024.0, types)
    idx = channel_indices_by_type(info)
    assert_array_equal(idx["mag"], [0, 1])
    assert_array_equal(idx["eeg"], [2, 3])
    assert_array_equal(idx["seeg"], [4, 5, 6])
    assert_array_equal(pick_types(info, meg=False, seeg=True), [4, 5, 6])
    for i, t in enumerate(types):
        assert_equal(channel_type(info, i), types[i])
    raw = RawArray(np.zeros((len(names), 10)), info)
    events = np.array([[1, 0, 0], [2, 0, 0]]).astype("d")
    epochs = Epochs(raw, events, {"event": 0}, -1e-5, 1e-5)
    evoked = epochs.average(pick_types(epochs.info, meg=True, seeg=True))
    e_seeg = evoked.pick_types(meg=False, seeg=True, copy=True)
    for l, r in zip(e_seeg.ch_names, names[4:]):
        assert_equal(l, r)