Пример #1
0
def test_no_conversion():
    """ Test bti no-conversion option """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, convert=False)
        raw_con = read_raw_bti(pdf, config, hs, convert=True)

        bti_info = _read_bti_header(pdf, config)
        dev_ctf_t = _correct_trans(bti_info["bti_transform"][0])
        assert_array_equal(dev_ctf_t, raw.info["dev_ctf_t"]["trans"])
        assert_array_equal(raw.info["dev_head_t"]["trans"], np.eye(4))
        assert_array_equal(raw.info["ctf_head_t"]["trans"], np.eye(4))
        dig, t = _process_bti_headshape(hs, convert=False, use_hpi=False)
        assert_array_equal(t["trans"], np.eye(4))

        for ii, (old, new, con) in enumerate(zip(dig, raw.info["dig"], raw_con.info["dig"])):
            assert_equal(old["ident"], new["ident"])
            assert_array_equal(old["r"], new["r"])
            assert_true(not np.allclose(old["r"], con["r"]))

            if ii > 10:
                break

        ch_map = dict((ch["chan_label"], ch["coil_trans"]) for ch in bti_info["chs"])

        for ii, ch_label in enumerate(raw.bti_ch_labels):
            if not ch_label.startswith("A"):
                continue
            t1 = _correct_trans(ch_map[ch_label])
            t2 = raw.info["chs"][ii]["coil_trans"]
            t3 = raw_con.info["chs"][ii]["coil_trans"]
            assert_array_equal(t1, t2)
            assert_true(not np.allclose(t1, t3))
Пример #2
0
def test_info_no_rename_no_reorder_no_pdf():
    """Test private renaming, reordering and partial construction option."""
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        info, bti_info = _get_bti_info(
            pdf_fname=pdf, config_fname=config, head_shape_fname=hs,
            rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=False,
            ecg_ch='E31', eog_ch=('E63', 'E64'),
            rename_channels=False, sort_by_ch_name=False)
        info2, bti_info = _get_bti_info(
            pdf_fname=None, config_fname=config, head_shape_fname=hs,
            rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=False,
            ecg_ch='E31', eog_ch=('E63', 'E64'),
            rename_channels=False, sort_by_ch_name=False)

        assert_equal(info['ch_names'],
                     [ch['ch_name'] for ch in info['chs']])
        assert_equal([n for n in info['ch_names'] if n.startswith('A')][:5],
                     ['A22', 'A2', 'A104', 'A241', 'A138'])
        assert_equal([n for n in info['ch_names'] if n.startswith('A')][-5:],
                     ['A133', 'A158', 'A44', 'A134', 'A216'])

        info = pick_info(info, pick_types(info, meg=True, stim=True,
                                          resp=True))
        info2 = pick_info(info2, pick_types(info2, meg=True, stim=True,
                                            resp=True))

        assert_true(info['sfreq'] is not None)
        assert_true(info['lowpass'] is not None)
        assert_true(info['highpass'] is not None)
        assert_true(info['meas_date'] is not None)

        assert_equal(info2['sfreq'], None)
        assert_equal(info2['lowpass'], None)
        assert_equal(info2['highpass'], None)
        assert_equal(info2['meas_date'], None)

        assert_equal(info['ch_names'], info2['ch_names'])
        assert_equal(info['ch_names'], info2['ch_names'])
        for key in ['dev_ctf_t', 'dev_head_t', 'ctf_head_t']:
            assert_array_equal(info[key]['trans'], info2[key]['trans'])

        assert_array_equal(
            np.array([ch['loc'] for ch in info['chs']]),
            np.array([ch['loc'] for ch in info2['chs']]))

    # just check reading data | corner case
    raw1 = read_raw_bti(
        pdf_fname=pdf, config_fname=config, head_shape_fname=None,
        sort_by_ch_name=False, preload=True)
    # just check reading data | corner case
    raw2 = read_raw_bti(
        pdf_fname=pdf, config_fname=config, head_shape_fname=None,
        rename_channels=False,
        sort_by_ch_name=True, preload=True)

    sort_idx = [raw1.bti_ch_labels.index(ch) for ch in raw2.bti_ch_labels]
    raw1._data = raw1._data[sort_idx]
    assert_array_equal(raw1._data, raw2._data)
    assert_array_equal(raw2.bti_ch_labels, raw2.ch_names)
Пример #3
0
def test_info_no_rename_no_reorder_no_pdf():
    """Test private renaming, reordering and partial construction option."""
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        info, bti_info = _get_bti_info(
            pdf_fname=pdf, config_fname=config, head_shape_fname=hs,
            rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=False,
            ecg_ch='E31', eog_ch=('E63', 'E64'),
            rename_channels=False, sort_by_ch_name=False)
        info2, bti_info = _get_bti_info(
            pdf_fname=None, config_fname=config, head_shape_fname=hs,
            rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=False,
            ecg_ch='E31', eog_ch=('E63', 'E64'),
            rename_channels=False, sort_by_ch_name=False)

        assert_equal(info['ch_names'],
                     [ch['ch_name'] for ch in info['chs']])
        assert_equal([n for n in info['ch_names'] if n.startswith('A')][:5],
                     ['A22', 'A2', 'A104', 'A241', 'A138'])
        assert_equal([n for n in info['ch_names'] if n.startswith('A')][-5:],
                     ['A133', 'A158', 'A44', 'A134', 'A216'])

        info = pick_info(info, pick_types(info, meg=True, stim=True,
                                          resp=True))
        info2 = pick_info(info2, pick_types(info2, meg=True, stim=True,
                                            resp=True))

        assert (info['sfreq'] is not None)
        assert (info['lowpass'] is not None)
        assert (info['highpass'] is not None)
        assert (info['meas_date'] is not None)

        assert_equal(info2['sfreq'], None)
        assert_equal(info2['lowpass'], None)
        assert_equal(info2['highpass'], None)
        assert_equal(info2['meas_date'], None)

        assert_equal(info['ch_names'], info2['ch_names'])
        assert_equal(info['ch_names'], info2['ch_names'])
        for key in ['dev_ctf_t', 'dev_head_t', 'ctf_head_t']:
            assert_array_equal(info[key]['trans'], info2[key]['trans'])

        assert_array_equal(
            np.array([ch['loc'] for ch in info['chs']]),
            np.array([ch['loc'] for ch in info2['chs']]))

    # just check reading data | corner case
    raw1 = read_raw_bti(
        pdf_fname=pdf, config_fname=config, head_shape_fname=None,
        sort_by_ch_name=False, preload=True)
    # just check reading data | corner case
    raw2 = read_raw_bti(
        pdf_fname=pdf, config_fname=config, head_shape_fname=None,
        rename_channels=False,
        sort_by_ch_name=True, preload=True)

    sort_idx = [raw1.bti_ch_labels.index(ch) for ch in raw2.bti_ch_labels]
    raw1._data = raw1._data[sort_idx]
    assert_array_equal(raw1._data, raw2._data)
    assert_array_equal(raw2.bti_ch_labels, raw2.ch_names)
def test_bytes_io():
    """ Test bti bytes-io API """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, convert=True)

        with open(pdf, 'rb') as fid:
            pdf = six.BytesIO(fid.read())
        with open(config, 'rb') as fid:
            config = six.BytesIO(fid.read())
        with open(hs, 'rb') as fid:
            hs = six.BytesIO(fid.read())
        raw2 = read_raw_bti(pdf, config, hs, convert=True)
        repr(raw2)
        assert_array_equal(raw._data, raw2._data)
Пример #5
0
def test_bytes_io():
    """ Test bti bytes-io API """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, convert=True, preload=False)

        with open(pdf, 'rb') as fid:
            pdf = six.BytesIO(fid.read())
        with open(config, 'rb') as fid:
            config = six.BytesIO(fid.read())
        with open(hs, 'rb') as fid:
            hs = six.BytesIO(fid.read())
        raw2 = read_raw_bti(pdf, config, hs, convert=True, preload=False)
        repr(raw2)
        assert_array_equal(raw[:][0], raw2[:][0])
Пример #6
0
def test_bytes_io():
    """ Test bti bytes-io API """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, convert=True)

        with open(pdf, "rb") as fid:
            pdf = six.BytesIO(fid.read())
        with open(config, "rb") as fid:
            config = six.BytesIO(fid.read())
        with open(hs, "rb") as fid:
            hs = six.BytesIO(fid.read())
        raw2 = read_raw_bti(pdf, config, hs, convert=True)
        repr(raw2)
        assert_array_equal(raw._data, raw2._data)
Пример #7
0
def test_bytes_io():
    """Test bti bytes-io API."""
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, convert=True, preload=False)

        with open(pdf, 'rb') as fid:
            pdf = BytesIO(fid.read())
        with open(config, 'rb') as fid:
            config = BytesIO(fid.read())
        with open(hs, 'rb') as fid:
            hs = BytesIO(fid.read())

        raw2 = read_raw_bti(pdf, config, hs, convert=True, preload=False)
        repr(raw2)
        assert_array_equal(raw[:][0], raw2[:][0])
Пример #8
0
def _read_raw(raw_fname, electrode=None, hsp=None, hpi=None, config=None,
              verbose=None):
    """Read a raw file into MNE, making inferences based on extension."""
    fname, ext = _parse_ext(raw_fname)

    # KIT systems
    if ext in ['.con', '.sqd']:
        raw = io.read_raw_kit(raw_fname, elp=electrode, hsp=hsp,
                              mrk=hpi, preload=False)

    # Neuromag or converted-to-fif systems
    elif ext in ['.fif', '.gz']:
        raw = io.read_raw_fif(raw_fname, preload=False)

    # BTi systems
    elif ext == '.pdf':
        if os.path.isfile(raw_fname):
            raw = io.read_raw_bti(raw_fname, config_fname=config,
                                  head_shape_fname=hsp,
                                  preload=False, verbose=verbose)

    # CTF systems
    elif ext == '.ds':
        raw = io.read_raw_ctf(raw_fname)
    else:
        raise ValueError("Raw file name extension must be one of %\n"
                         "Got %" % (ALLOWED_EXTENSIONS, ext))
    return raw
Пример #9
0
def test_bytes_io():
    """ Test bti bytes-io API """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        with warnings.catch_warnings(record=True):  # weight tables
            raw = read_raw_bti(pdf, config, hs, convert=True, preload=False)

        with open(pdf, 'rb') as fid:
            pdf = six.BytesIO(fid.read())
        with open(config, 'rb') as fid:
            config = six.BytesIO(fid.read())
        with open(hs, 'rb') as fid:
            hs = six.BytesIO(fid.read())
        with warnings.catch_warnings(record=True):  # weight tables
            raw2 = read_raw_bti(pdf, config, hs, convert=True, preload=False)
        repr(raw2)
        assert_array_equal(raw[:][0], raw2[:][0])
Пример #10
0
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
        assert_raises(ValueError, read_raw_bti, pdf, 'eggs')
        assert_raises(ValueError, read_raw_bti, pdf, config, 'spam')
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        with Raw(exported, preload=True) as ex:
            with read_raw_bti(pdf, config, hs) as 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)
                dig1, dig2 = [np.array([d['r'] for d in r_.info['dig']])
                              for r_ in (ra, ex)]
                assert_array_equal(dig1, dig2)

                coil1, coil2 = [np.concatenate([d['coil_trans'].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_array_equal(loc1, loc2)

                assert_array_equal(ra._data[:NCH], ex._data[:NCH])
                assert_array_equal(ra.cals[:NCH], ex.cals[:NCH])
                ra.save(tmp_raw_fname)
            with Raw(tmp_raw_fname) as r:
                print(r)
        os.remove(tmp_raw_fname)
Пример #11
0
def test_plot_alignment_meg(renderer, system):
    """Test plotting of MEG sensors + helmet."""
    if system == 'Neuromag':
        this_info = read_info(evoked_fname)
    elif system == 'CTF':
        this_info = read_raw_ctf(ctf_fname).info
    elif system == 'BTi':
        this_info = read_raw_bti(pdf_fname,
                                 config_fname,
                                 hs_fname,
                                 convert=True,
                                 preload=False).info
    else:
        assert system == 'KIT'
        this_info = read_raw_kit(sqd_fname).info

    meg = ['helmet', 'sensors']
    if system == 'KIT':
        meg.append('ref')
    fig = plot_alignment(this_info,
                         read_trans(trans_fname),
                         subject='sample',
                         subjects_dir=subjects_dir,
                         meg=meg,
                         eeg=False)
    # count the number of objects: should be n_meg_ch + 1 (helmet) + 1 (head)
    use_info = pick_info(
        this_info,
        pick_types(this_info,
                   meg=True,
                   eeg=False,
                   ref_meg='ref' in meg,
                   exclude=()))
    n_actors = use_info['nchan'] + 2
    _assert_n_actors(fig, renderer, n_actors)
Пример #12
0
def test_bytes_io():
    """ Test bti bytes-io API """
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        with warnings.catch_warnings(record=True):  # weight tables
            raw = read_raw_bti(pdf, config, hs, convert=True, preload=False)

        with open(pdf, "rb") as fid:
            pdf = six.BytesIO(fid.read())
        with open(config, "rb") as fid:
            config = six.BytesIO(fid.read())
        with open(hs, "rb") as fid:
            hs = six.BytesIO(fid.read())
        with warnings.catch_warnings(record=True):  # weight tables
            raw2 = read_raw_bti(pdf, config, hs, convert=True, preload=False)
        repr(raw2)
        assert_array_equal(raw[:][0], raw2[:][0])
Пример #13
0
def test_pick_refs():
    """Test picking of reference sensors
    """
    infos = list()
    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    infos.append(raw_kit.info)
    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    with warnings.catch_warnings(record=True):  # weight tables
        raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    infos.append(raw_bti.info)
    # CTF
    fname_ctf_raw = op.join(io_dir, 'tests', 'data', 'test_ctf_comp_raw.fif')
    raw_ctf = read_raw_fif(fname_ctf_raw, add_eeg_ref=False)
    raw_ctf.apply_gradient_compensation(2)
    infos.append(raw_ctf.info)
    for info in infos:
        info['bads'] = []
        assert_raises(ValueError, pick_types, info, meg='foo')
        assert_raises(ValueError, pick_types, info, ref_meg='foo')
        picks_meg_ref = pick_types(info, meg=True, ref_meg=True)
        picks_meg = pick_types(info, meg=True, ref_meg=False)
        picks_ref = pick_types(info, meg=False, ref_meg=True)
        assert_array_equal(picks_meg_ref,
                           np.sort(np.concatenate([picks_meg, picks_ref])))
        picks_grad = pick_types(info, meg='grad', ref_meg=False)
        picks_ref_grad = pick_types(info, meg=False, ref_meg='grad')
        picks_meg_ref_grad = pick_types(info, meg='grad', ref_meg='grad')
        assert_array_equal(
            picks_meg_ref_grad,
            np.sort(np.concatenate([picks_grad, picks_ref_grad])))
        picks_mag = pick_types(info, meg='mag', ref_meg=False)
        picks_ref_mag = pick_types(info, meg=False, ref_meg='mag')
        picks_meg_ref_mag = pick_types(info, meg='mag', ref_meg='mag')
        assert_array_equal(picks_meg_ref_mag,
                           np.sort(np.concatenate([picks_mag, picks_ref_mag])))
        assert_array_equal(picks_meg,
                           np.sort(np.concatenate([picks_mag, picks_grad])))
        assert_array_equal(
            picks_ref, np.sort(np.concatenate([picks_ref_mag,
                                               picks_ref_grad])))
        assert_array_equal(
            picks_meg_ref,
            np.sort(
                np.concatenate(
                    [picks_grad, picks_mag, picks_ref_grad, picks_ref_mag])))
        for pick in (picks_meg_ref, picks_meg, picks_ref, picks_grad,
                     picks_ref_grad, picks_meg_ref_grad, picks_mag,
                     picks_ref_mag, picks_meg_ref_mag):
            if len(pick) > 0:
                pick_info(info, pick)
Пример #14
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts
    """
    evoked = read_evokeds(evoked_fname)[0]
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
    # KIT ref sensor coil def not defined
    assert_raises(RuntimeError, plot_trans, infos['KIT'], None,
                  meg_sensors=True, ref_meg=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    # EEG only with strange options
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked.copy().pick_types(meg=False, eeg=True).info,
                   trans=trans_fname, meg_sensors=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
Пример #15
0
def test_find_ch_connectivity():
    """Test computing the connectivity matrix."""
    data_path = testing.data_path()

    raw = read_raw_fif(raw_fname, preload=True)
    sizes = {'mag': 828, 'grad': 1700, 'eeg': 386}
    nchans = {'mag': 102, 'grad': 204, 'eeg': 60}
    for ch_type in ['mag', 'grad', 'eeg']:
        conn, ch_names = find_ch_connectivity(raw.info, ch_type)
        # Silly test for checking the number of neighbors.
        assert_equal(conn.getnnz(), sizes[ch_type])
        assert_equal(len(ch_names), nchans[ch_type])
    pytest.raises(ValueError, find_ch_connectivity, raw.info, None)

    # Test computing the conn matrix with gradiometers.
    conn, ch_names = _compute_ch_connectivity(raw.info, 'grad')
    assert_equal(conn.getnnz(), 2680)

    # Test ch_type=None.
    raw.pick_types(meg='mag')
    find_ch_connectivity(raw.info, None)

    bti_fname = op.join(data_path, 'BTi', 'erm_HFH', 'c,rfDC')
    bti_config_name = op.join(data_path, 'BTi', 'erm_HFH', 'config')
    raw = read_raw_bti(bti_fname, bti_config_name, None)
    _, ch_names = find_ch_connectivity(raw.info, 'mag')
    assert 'A1' in ch_names

    ctf_fname = op.join(data_path, 'CTF', 'testdata_ctf_short.ds')
    raw = read_raw_ctf(ctf_fname)
    _, ch_names = find_ch_connectivity(raw.info, 'mag')
    assert 'MLC11' in ch_names

    pytest.raises(ValueError, find_ch_connectivity, raw.info, 'eog')
Пример #16
0
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)
Пример #17
0
def test_find_ch_connectivity():
    """Test computing the connectivity matrix."""
    data_path = testing.data_path()

    raw = read_raw_fif(raw_fname, preload=True)
    sizes = {'mag': 828, 'grad': 1700, 'eeg': 386}
    nchans = {'mag': 102, 'grad': 204, 'eeg': 60}
    for ch_type in ['mag', 'grad', 'eeg']:
        conn, ch_names = find_ch_connectivity(raw.info, ch_type)
        # Silly test for checking the number of neighbors.
        assert_equal(conn.getnnz(), sizes[ch_type])
        assert_equal(len(ch_names), nchans[ch_type])
    assert_raises(ValueError, find_ch_connectivity, raw.info, None)

    # Test computing the conn matrix with gradiometers.
    conn, ch_names = _compute_ch_connectivity(raw.info, 'grad')
    assert_equal(conn.getnnz(), 2680)

    # Test ch_type=None.
    raw.pick_types(meg='mag')
    find_ch_connectivity(raw.info, None)

    bti_fname = op.join(data_path, 'BTi', 'erm_HFH', 'c,rfDC')
    bti_config_name = op.join(data_path, 'BTi', 'erm_HFH', 'config')
    raw = read_raw_bti(bti_fname, bti_config_name, None)
    _, ch_names = find_ch_connectivity(raw.info, 'mag')
    assert_true('A1' in ch_names)

    ctf_fname = op.join(data_path, 'CTF', 'testdata_ctf_short.ds')
    raw = read_raw_ctf(ctf_fname)
    _, ch_names = find_ch_connectivity(raw.info, 'mag')
    assert_true('MLC11' in ch_names)

    assert_raises(ValueError, find_ch_connectivity, raw.info, 'eog')
Пример #18
0
def test_no_conversion():
    """ Test bti no-conversion option """

    get_info = partial(_get_bti_info,
                       rotation_x=0.0,
                       translation=(0.0, 0.02, 0.11),
                       convert=False,
                       ecg_ch='E31',
                       eog_ch=('E63', 'E64'),
                       rename_channels=False,
                       sort_by_ch_name=False)

    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw_info, _ = get_info(pdf, config, hs, convert=False)
        raw_info_con = read_raw_bti(pdf_fname=pdf,
                                    config_fname=config,
                                    head_shape_fname=hs,
                                    convert=True,
                                    preload=False).info

        pick_info(raw_info_con,
                  pick_types(raw_info_con, meg=True, ref_meg=True),
                  copy=False)
        pick_info(raw_info,
                  pick_types(raw_info, meg=True, ref_meg=True),
                  copy=False)
        bti_info = _read_bti_header(pdf, config)
        dev_ctf_t = _correct_trans(bti_info['bti_transform'][0])
        assert_array_equal(dev_ctf_t, raw_info['dev_ctf_t']['trans'])
        assert_array_equal(raw_info['dev_head_t']['trans'], np.eye(4))
        assert_array_equal(raw_info['ctf_head_t']['trans'], np.eye(4))
        dig, t = _process_bti_headshape(hs, convert=False, use_hpi=False)
        assert_array_equal(t['trans'], np.eye(4))

        for ii, (old, new, con) in enumerate(
                zip(dig, raw_info['dig'], raw_info_con['dig'])):
            assert_equal(old['ident'], new['ident'])
            assert_array_equal(old['r'], new['r'])
            assert_true(not np.allclose(old['r'], con['r']))

            if ii > 10:
                break

        ch_map = dict((ch['chan_label'], ch['loc']) for ch in bti_info['chs'])

        for ii, ch_label in enumerate(raw_info['ch_names']):
            if not ch_label.startswith('A'):
                continue
            t1 = ch_map[ch_label]  # correction already performed in bti_info
            t2 = raw_info['chs'][ii]['loc']
            t3 = raw_info_con['chs'][ii]['loc']
            assert_allclose(t1, t2, atol=1e-15)
            assert_true(not np.allclose(t1, t3))
            idx_a = raw_info_con['ch_names'].index('MEG 001')
            idx_b = raw_info['ch_names'].index('A22')
            assert_equal(raw_info_con['chs'][idx_a]['coord_frame'],
                         FIFF.FIFFV_COORD_DEVICE)
            assert_equal(raw_info['chs'][idx_b]['coord_frame'],
                         FIFF.FIFFV_MNE_COORD_4D_HEAD)
Пример #19
0
def test_no_conversion():
    """ Test bti no-conversion option """

    get_info = partial(
        _get_bti_info,
        rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=False,
        ecg_ch='E31', eog_ch=('E63', 'E64'),
        rename_channels=False, sort_by_ch_name=False)

    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        with warnings.catch_warnings(record=True):  # weight tables
            raw_info, _ = get_info(pdf, config, hs, convert=False)
        with warnings.catch_warnings(record=True):  # weight tables
            raw_info_con = read_raw_bti(
                pdf_fname=pdf, config_fname=config, head_shape_fname=hs,
                convert=True, preload=False).info

        pick_info(raw_info_con,
                  pick_types(raw_info_con, meg=True, ref_meg=True),
                  copy=False)
        pick_info(raw_info,
                  pick_types(raw_info, meg=True, ref_meg=True), copy=False)
        bti_info = _read_bti_header(pdf, config)
        dev_ctf_t = _correct_trans(bti_info['bti_transform'][0])
        assert_array_equal(dev_ctf_t, raw_info['dev_ctf_t']['trans'])
        assert_array_equal(raw_info['dev_head_t']['trans'], np.eye(4))
        assert_array_equal(raw_info['ctf_head_t']['trans'], np.eye(4))
        dig, t = _process_bti_headshape(hs, convert=False, use_hpi=False)
        assert_array_equal(t['trans'], np.eye(4))

        for ii, (old, new, con) in enumerate(zip(
                dig, raw_info['dig'], raw_info_con['dig'])):
            assert_equal(old['ident'], new['ident'])
            assert_array_equal(old['r'], new['r'])
            assert_true(not np.allclose(old['r'], con['r']))

            if ii > 10:
                break

        ch_map = dict((ch['chan_label'],
                       ch['loc']) for ch in bti_info['chs'])

        for ii, ch_label in enumerate(raw_info['ch_names']):
            if not ch_label.startswith('A'):
                continue
            t1 = ch_map[ch_label]  # correction already performed in bti_info
            t2 = raw_info['chs'][ii]['loc']
            t3 = raw_info_con['chs'][ii]['loc']
            assert_allclose(t1, t2, atol=1e-15)
            assert_true(not np.allclose(t1, t3))
            idx_a = raw_info_con['ch_names'].index('MEG 001')
            idx_b = raw_info['ch_names'].index('A22')
            assert_equal(
                raw_info_con['chs'][idx_a]['coord_frame'],
                FIFF.FIFFV_COORD_DEVICE)
            assert_equal(
                raw_info['chs'][idx_b]['coord_frame'],
                FIFF.FIFFV_MNE_COORD_4D_HEAD)
Пример #20
0
def test_pick_refs():
    """Test picking of reference sensors
    """
    infos = list()
    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    infos.append(raw_kit.info)
    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    with warnings.catch_warnings(record=True):  # weight tables
        raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    infos.append(raw_bti.info)
    # CTF
    fname_ctf_raw = op.join(io_dir, 'tests', 'data', 'test_ctf_comp_raw.fif')
    raw_ctf = read_raw_fif(fname_ctf_raw, add_eeg_ref=False)
    raw_ctf.apply_gradient_compensation(2)
    infos.append(raw_ctf.info)
    for info in infos:
        info['bads'] = []
        assert_raises(ValueError, pick_types, info, meg='foo')
        assert_raises(ValueError, pick_types, info, ref_meg='foo')
        picks_meg_ref = pick_types(info, meg=True, ref_meg=True)
        picks_meg = pick_types(info, meg=True, ref_meg=False)
        picks_ref = pick_types(info, meg=False, ref_meg=True)
        assert_array_equal(picks_meg_ref,
                           np.sort(np.concatenate([picks_meg, picks_ref])))
        picks_grad = pick_types(info, meg='grad', ref_meg=False)
        picks_ref_grad = pick_types(info, meg=False, ref_meg='grad')
        picks_meg_ref_grad = pick_types(info, meg='grad', ref_meg='grad')
        assert_array_equal(picks_meg_ref_grad,
                           np.sort(np.concatenate([picks_grad,
                                                   picks_ref_grad])))
        picks_mag = pick_types(info, meg='mag', ref_meg=False)
        picks_ref_mag = pick_types(info, meg=False, ref_meg='mag')
        picks_meg_ref_mag = pick_types(info, meg='mag', ref_meg='mag')
        assert_array_equal(picks_meg_ref_mag,
                           np.sort(np.concatenate([picks_mag,
                                                   picks_ref_mag])))
        assert_array_equal(picks_meg,
                           np.sort(np.concatenate([picks_mag, picks_grad])))
        assert_array_equal(picks_ref,
                           np.sort(np.concatenate([picks_ref_mag,
                                                   picks_ref_grad])))
        assert_array_equal(picks_meg_ref, np.sort(np.concatenate(
            [picks_grad, picks_mag, picks_ref_grad, picks_ref_mag])))
        for pick in (picks_meg_ref, picks_meg, picks_ref,
                     picks_grad, picks_ref_grad, picks_meg_ref_grad,
                     picks_mag, picks_ref_mag, picks_meg_ref_mag):
            if len(pick) > 0:
                pick_info(info, pick)
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
        assert_raises(ValueError, read_raw_bti, pdf, 'eggs')
        assert_raises(ValueError, read_raw_bti, pdf, config, 'spam')
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        ex = Raw(exported, preload=True)
        ra = read_raw_bti(pdf, config, hs)
        assert_true('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)
        dig1, dig2 = [
            np.array([d['r'] for d in r_.info['dig']]) for r_ in (ra, ex)
        ]
        assert_array_almost_equal(dig1, dig2, 18)
        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_array_equal(ra._data[:NCH], ex._data[: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_true(ra.info[key] is not None)
                for ent in ('to', 'from', 'trans'):
                    assert_allclose(ex.info[key][ent], ra.info[key][ent])

        # Make sure concatenation works
        raw_concat = concatenate_raws([ra.copy(), ra])
        assert_equal(raw_concat.n_times, 2 * ra.n_times)

        ra.save(tmp_raw_fname)
        re = Raw(tmp_raw_fname)
        print(re)
        for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
            assert_true(isinstance(re.info[key], dict))
            this_t = re.info[key]['trans']
            assert_equal(this_t.shape, (4, 4))
            # cehck that matrix by is not identity
            assert_true(not np.allclose(this_t, np.eye(4)))
        os.remove(tmp_raw_fname)
Пример #22
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option('-p', '--pdf', dest='pdf_fname',
                      help='Input data file name', metavar='FILE')
    parser.add_option('-c', '--config', dest='config_fname',
                      help='Input config file name', metavar='FILE',
                      default='config')
    parser.add_option('--head_shape', dest='head_shape_fname',
                      help='Headshape file name', metavar='FILE',
                      default='hs_file')
    parser.add_option('-o', '--out_fname', dest='out_fname',
                      help='Name of the resulting fiff file',
                      default='as_data_fname')
    parser.add_option('-r', '--rotation_x', dest='rotation_x', type='float',
                      help='Compensatory rotation about Neuromag x axis, deg',
                      default=2.0)
    parser.add_option('-T', '--translation', dest='translation', type='str',
                      help='Default translation, meter',
                      default=(0.00, 0.02, 0.11))
    parser.add_option('--ecg_ch', dest='ecg_ch', type='str',
                      help='4D ECG channel name',
                      default='E31')
    parser.add_option('--eog_ch', dest='eog_ch', type='str',
                      help='4D EOG channel names',
                      default='E63,E64')

    options, args = parser.parse_args()

    pdf_fname = options.pdf_fname
    if pdf_fname is None:
        parser.print_help()
        sys.exit(1)

    config_fname = options.config_fname
    head_shape_fname = options.head_shape_fname
    out_fname = options.out_fname
    rotation_x = options.rotation_x
    translation = options.translation
    ecg_ch = options.ecg_ch
    eog_ch = options.ecg_ch.split(',')

    if out_fname == 'as_data_fname':
        out_fname = pdf_fname + '_raw.fif'

    raw = read_raw_bti(pdf_fname=pdf_fname, config_fname=config_fname,
                       head_shape_fname=head_shape_fname,
                       rotation_x=rotation_x, translation=translation,
                       ecg_ch=ecg_ch, eog_ch=eog_ch)

    raw.save(out_fname)
    raw.close()
    if is_main:
        sys.exit(0)
Пример #23
0
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
        assert_raises(ValueError, read_raw_bti, pdf, 'eggs', preload=False)
        assert_raises(ValueError, read_raw_bti, pdf, config, 'spam',
                      preload=False)
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        ex = Raw(exported, preload=True)
        with warnings.catch_warnings(record=True):  # weight tables
            ra = read_raw_bti(pdf, config, hs, preload=False)
        assert_true('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)
        with warnings.catch_warnings(record=True):  # headshape
            assert_dig_allclose(ex.info, ra.info)
        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_true(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 = Raw(tmp_raw_fname)
        print(re)
        for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
            assert_true(isinstance(re.info[key], dict))
            this_t = re.info[key]['trans']
            assert_equal(this_t.shape, (4, 4))
            # cehck that matrix by is not identity
            assert_true(not np.allclose(this_t, np.eye(4)))
        os.remove(tmp_raw_fname)
Пример #24
0
def test_crop():
    """ Test crop raw """
    raw = read_raw_bti(pdf_fnames[0], config_fnames[0], hs_fnames[0])
    y, t = raw[:]
    t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
    mask = (t0 <= t) * (t <= t1)
    raw_ = raw.crop(t0, t1)
    y_, _ = raw_[:]
    assert_true(y_.shape[1] == mask.sum())
    assert_true(y_.shape[0] == y.shape[0])
Пример #25
0
def test_crop():
    """ Test crop raw """
    raw = read_raw_bti(pdf_fnames[0], config_fnames[0], hs_fnames[0])
    y, t = raw[:]
    t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
    mask = (t0 <= t) * (t <= t1)
    raw_ = raw.crop(t0, t1)
    y_, _ = raw_[:]
    assert_true(y_.shape[1] == mask.sum())
    assert_true(y_.shape[0] == y.shape[0])
Пример #26
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option('-p', '--pdf', dest='pdf_fname',
                      help='Input data file name', metavar='FILE')
    parser.add_option('-c', '--config', dest='config_fname',
                      help='Input config file name', metavar='FILE',
                      default='config')
    parser.add_option('--head_shape', dest='head_shape_fname',
                      help='Headshape file name', metavar='FILE',
                      default='hs_file')
    parser.add_option('-o', '--out_fname', dest='out_fname',
                      help='Name of the resulting fiff file',
                      default='as_data_fname')
    parser.add_option('-r', '--rotation_x', dest='rotation_x', type='float',
                      help='Compensatory rotation about Neuromag x axis, deg',
                      default=2.0)
    parser.add_option('-T', '--translation', dest='translation', type='str',
                      help='Default translation, meter',
                      default=(0.00, 0.02, 0.11))
    parser.add_option('--ecg_ch', dest='ecg_ch', type='str',
                      help='4D ECG channel name',
                      default='E31')
    parser.add_option('--eog_ch', dest='eog_ch', type='str',
                      help='4D EOG channel names',
                      default='E63,E64')

    options, args = parser.parse_args()

    pdf_fname = options.pdf_fname
    if pdf_fname is None:
        parser.print_help()
        sys.exit(1)

    config_fname = options.config_fname
    head_shape_fname = options.head_shape_fname
    out_fname = options.out_fname
    rotation_x = options.rotation_x
    translation = options.translation
    ecg_ch = options.ecg_ch
    eog_ch = options.ecg_ch.split(',')

    if out_fname == 'as_data_fname':
        out_fname = pdf_fname + '_raw.fif'

    raw = read_raw_bti(pdf_fname=pdf_fname, config_fname=config_fname,
                       head_shape_fname=head_shape_fname,
                       rotation_x=rotation_x, translation=translation,
                       ecg_ch=ecg_ch, eog_ch=eog_ch)

    raw.save(out_fname)
    raw.close()
Пример #27
0
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
        assert_raises(ValueError, read_raw_bti, pdf, 'eggs')
        assert_raises(ValueError, read_raw_bti, pdf, config, 'spam')
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        ex = Raw(exported, preload=True)
        ra = read_raw_bti(pdf, config, hs)
        assert_true('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)
        dig1, dig2 = [np.array([d['r'] for d in r_.info['dig']])
                      for r_ in (ra, ex)]
        assert_array_almost_equal(dig1, dig2, 18)
        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_array_equal(ra._data[:NCH], ex._data[: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_true(ra.info[key] is not None)
                for ent in ('to', 'from', 'trans'):
                    assert_allclose(ex.info[key][ent],
                                    ra.info[key][ent])

        # Make sure concatenation works
        raw_concat = concatenate_raws([ra.copy(), ra])
        assert_equal(raw_concat.n_times, 2 * ra.n_times)

        ra.save(tmp_raw_fname)
        re = Raw(tmp_raw_fname)
        print(re)
        for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
            assert_true(isinstance(re.info[key], dict))
            this_t = re.info[key]['trans']
            assert_equal(this_t.shape, (4, 4))
            # cehck that matrix by is not identity
            assert_true(not np.allclose(this_t, np.eye(4)))
        os.remove(tmp_raw_fname)
Пример #28
0
def _read_raw(raw_fpath,
              electrode=None,
              hsp=None,
              hpi=None,
              allow_maxshield=False,
              config=None,
              **kwargs):
    """Read a raw file into MNE, making inferences based on extension."""
    _, ext = _parse_ext(raw_fpath)

    # KIT systems
    if ext in ['.con', '.sqd']:
        raw = io.read_raw_kit(raw_fpath,
                              elp=electrode,
                              hsp=hsp,
                              mrk=hpi,
                              preload=False,
                              **kwargs)

    # BTi systems
    elif ext == '.pdf':
        raw = io.read_raw_bti(raw_fpath,
                              config_fname=config,
                              head_shape_fname=hsp,
                              preload=False,
                              **kwargs)

    elif ext == '.fif':
        raw = reader[ext](raw_fpath, allow_maxshield, **kwargs)

    elif ext in ['.ds', '.vhdr', '.set', '.edf', '.bdf', '.EDF']:
        raw_fpath = Path(raw_fpath)
        # handle EDF extension upper/lower casing
        if ext == '.edf' and not raw_fpath.exists():
            raw_fpath = raw_fpath.with_suffix('.EDF')
        elif ext == '.EDF' and not raw_fpath.exists():
            raw_fpath = raw_fpath.with_suffix('.edf')
        raw = reader[ext](raw_fpath, **kwargs)

    # MEF and NWB are allowed, but not yet implemented
    elif ext in ['.mef', '.nwb']:
        raise ValueError(f'Got "{ext}" as extension. This is an allowed '
                         f'extension but there is no IO support for this '
                         f'file format yet.')

    # No supported data found ...
    # ---------------------------
    else:
        raise ValueError(f'Raw file name extension must be one '
                         f'of {ALLOWED_DATATYPE_EXTENSIONS}\n'
                         f'Got {ext}')
    return raw
Пример #29
0
def _read_raw(raw_path,
              electrode=None,
              hsp=None,
              hpi=None,
              allow_maxshield=False,
              config_path=None,
              **kwargs):
    """Read a raw file into MNE, making inferences based on extension."""
    _, ext = _parse_ext(raw_path)

    # KIT systems
    if ext in ['.con', '.sqd']:
        raw = io.read_raw_kit(raw_path,
                              elp=electrode,
                              hsp=hsp,
                              mrk=hpi,
                              preload=False,
                              **kwargs)

    # BTi systems
    elif ext == '.pdf':
        raw = io.read_raw_bti(
            pdf_fname=str(raw_path),  # FIXME MNE should accept Path!
            config_fname=str(config_path),  # FIXME MNE should accept Path!
            head_shape_fname=hsp,
            preload=False,
            **kwargs)

    elif ext == '.fif':
        raw = reader[ext](raw_path, allow_maxshield, **kwargs)

    elif ext in ['.ds', '.vhdr', '.set', '.edf', '.bdf', '.EDF', '.snirf']:
        if (ext == '.snirf'
                and not check_version('mne', '1.0')):  # pragma: no cover
            raise RuntimeError(
                'fNIRS support in MNE-BIDS requires MNE-Python version 1.0')
        raw_path = Path(raw_path)
        raw = reader[ext](raw_path, **kwargs)

    # MEF and NWB are allowed, but not yet implemented
    elif ext in ['.mef', '.nwb']:
        raise ValueError(f'Got "{ext}" as extension. This is an allowed '
                         f'extension but there is no IO support for this '
                         f'file format yet.')

    # No supported data found ...
    # ---------------------------
    else:
        raise ValueError(f'Raw file name extension must be one '
                         f'of {ALLOWED_DATATYPE_EXTENSIONS}\n'
                         f'Got {ext}')
    return raw
Пример #30
0
def _read_raw(raw_fpath,
              electrode=None,
              hsp=None,
              hpi=None,
              config=None,
              verbose=None,
              **kwargs):
    """Read a raw file into MNE, making inferences based on extension."""
    _, ext = _parse_ext(raw_fpath)

    # KIT systems
    if ext in ['.con', '.sqd']:
        raw = io.read_raw_kit(raw_fpath,
                              elp=electrode,
                              hsp=hsp,
                              mrk=hpi,
                              preload=False,
                              **kwargs)

    # BTi systems
    elif ext == '.pdf':
        raw = io.read_raw_bti(raw_fpath,
                              config_fname=config,
                              head_shape_fname=hsp,
                              preload=False,
                              verbose=verbose,
                              **kwargs)

    elif ext == '.fif':
        raw = reader[ext](raw_fpath, **kwargs)

    elif ext in ['.ds', '.vhdr', '.set']:
        raw = reader[ext](raw_fpath, **kwargs)

    # EDF (european data format) or BDF (biosemi) format
    # TODO: integrate with lines above once MNE can read
    # annotations with preload=False
    elif ext in ['.edf', '.bdf']:
        raw = reader[ext](raw_fpath, preload=True, **kwargs)

    # MEF and NWB are allowed, but not yet implemented
    elif ext in ['.mef', '.nwb']:
        raise ValueError(
            'Got "{}" as extension. This is an allowed extension '
            'but there is no IO support for this file format yet.'.format(ext))

    # No supported data found ...
    # ---------------------------
    else:
        raise ValueError('Raw file name extension must be one of {}\n'
                         'Got {}'.format(ALLOWED_EXTENSIONS, ext))
    return raw
def _read_raw_bti(raw_fid, config_fid, convert, verbose=None):
    """Convert and raw file from HCP input"""
    raw = read_raw_bti(  # no convrt + no rename for HCP compatibility
        raw_fid,
        config_fid,
        convert=convert,
        head_shape_fname=None,
        sort_by_ch_name=False,
        rename_channels=False,
        preload=False,
        verbose=verbose)

    return raw
Пример #32
0
def test_crop_append():
    """ Test crop and append raw """
    raw = read_raw_bti(pdf_fnames[0], config_fnames[0], hs_fnames[0])
    raw.preload_data()  # currently does nothing
    y, t = raw[:]
    t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
    mask = (t0 <= t) * (t <= t1)
    raw_ = raw.crop(t0, t1)
    y_, _ = raw_[:]
    assert_true(y_.shape[1] == mask.sum())
    assert_true(y_.shape[0] == y.shape[0])

    raw2 = raw.copy()
    assert_raises(RuntimeError, raw.append, raw2, preload=False)
    raw.append(raw2)
    assert_allclose(np.tile(raw2[:, :][0], (1, 2)), raw[:, :][0])
def test_crop_append():
    """ Test crop and append raw """
    raw = read_raw_bti(pdf_fnames[0], config_fnames[0], hs_fnames[0])
    raw.load_data()  # currently does nothing
    y, t = raw[:]
    t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
    mask = (t0 <= t) * (t <= t1)
    raw_ = raw.crop(t0, t1)
    y_, _ = raw_[:]
    assert_true(y_.shape[1] == mask.sum())
    assert_true(y_.shape[0] == y.shape[0])

    raw2 = raw.copy()
    assert_raises(RuntimeError, raw.append, raw2, preload=False)
    raw.append(raw2)
    assert_allclose(np.tile(raw2[:, :][0], (1, 2)), raw[:, :][0])
Пример #34
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    from mayavi import mlab
    evoked = read_evokeds(evoked_fname)[0]
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
                   subjects_dir=subjects_dir, ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError, plot_trans, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError, plot_trans, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info, meg_sensors=True, dig=True, coord_frame=coord_frame,
                   trans=trans_fname, subject='sample',
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info, subject='sample', trans=trans_fname,
                   source='outer_skin', meg_sensors=True, skull=True,
                   eeg_sensors=['original', 'projected'], ecog_sensors=True,
                   brain='white', head=True, subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
Пример #35
0
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
        assert_raises(ValueError, read_raw_bti, pdf, 'eggs')
        assert_raises(ValueError, read_raw_bti, pdf, config, 'spam')
        if op.exists(tmp_raw_fname):
            os.remove(tmp_raw_fname)
        with Raw(exported, preload=True) as ex:
            with read_raw_bti(pdf, config, hs) as ra:
                assert_true('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)
                dig1, dig2 = [
                    np.array([d['r'] for d in r_.info['dig']])
                    for r_ in (ra, ex)
                ]
                assert_array_equal(dig1, dig2)

                coil1, coil2 = [
                    np.concatenate([
                        d['coil_trans'].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_array_equal(loc1, loc2)

                assert_array_equal(ra._data[:NCH], ex._data[:NCH])
                assert_array_equal(ra._cals[:NCH], ex._cals[:NCH])
                # Make sure concatenation works
                raw_concat = concatenate_raws([ra.copy(), ra])
                assert_equal(raw_concat.n_times, 2 * ra.n_times)

                ra.save(tmp_raw_fname)
            with Raw(tmp_raw_fname) as r:
                print(r)
        os.remove(tmp_raw_fname)
Пример #36
0
def test_transforms():
    """ Test transformations """
    bti_trans = (0.0, 0.02, 0.11)
    bti_dev_t = Transform("ctf_meg", "meg", _get_bti_dev_t(0.0, bti_trans))
    for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs)
        dev_ctf_t = raw.info["dev_ctf_t"]
        dev_head_t_old = raw.info["dev_head_t"]
        ctf_head_t = raw.info["ctf_head_t"]

        # 1) get BTI->Neuromag
        bti_dev_t = Transform("ctf_meg", "meg", _get_bti_dev_t(0.0, bti_trans))

        # 2) get Neuromag->BTI head
        t = combine_transforms(invert_transform(bti_dev_t), dev_ctf_t, "meg", "ctf_head")
        # 3) get Neuromag->head
        dev_head_t_new = combine_transforms(t, ctf_head_t, "meg", "head")

        assert_array_equal(dev_head_t_new["trans"], dev_head_t_old["trans"])
Пример #37
0
def test_no_loc_none(monkeypatch):
    """Test that we don't set loc to None when no trans is found."""
    ch_name = 'MLzA'

    def _read_config_bad(*args, **kwargs):
        cfg = _read_config(*args, **kwargs)
        idx = [ch['name'] for ch in cfg['chs']].index(ch_name)
        del cfg['chs'][idx]['dev']['transform']
        return cfg

    monkeypatch.setattr(mne.io.bti.bti, '_read_config', _read_config_bad)
    kwargs = dict(pdf_fname=pdf_fnames[0],
                  config_fname=config_fnames[0],
                  head_shape_fname=hs_fnames[0],
                  rename_channels=False,
                  sort_by_ch_name=False)
    raw = read_raw_bti(**kwargs)
    idx = raw.ch_names.index(ch_name)
    assert_allclose(raw.info['chs'][idx]['loc'], np.full(12, np.nan))
Пример #38
0
def test_transforms():
    """Test transformations."""
    bti_trans = (0.0, 0.02, 0.11)
    bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans))
    for pdf, config, hs, in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, preload=False)
        dev_ctf_t = raw.info['dev_ctf_t']
        dev_head_t_old = raw.info['dev_head_t']
        ctf_head_t = raw.info['ctf_head_t']

        # 1) get BTI->Neuromag
        bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans))

        # 2) get Neuromag->BTI head
        t = combine_transforms(invert_transform(bti_dev_t), dev_ctf_t, 'meg',
                               'ctf_head')
        # 3) get Neuromag->head
        dev_head_t_new = combine_transforms(t, ctf_head_t, 'meg', 'head')

        assert_array_equal(dev_head_t_new['trans'], dev_head_t_old['trans'])
Пример #39
0
def test_transforms():
    """Test transformations."""
    bti_trans = (0.0, 0.02, 0.11)
    bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans))
    for pdf, config, hs, in zip(pdf_fnames, config_fnames, hs_fnames):
        raw = read_raw_bti(pdf, config, hs, preload=False)
        dev_ctf_t = raw.info['dev_ctf_t']
        dev_head_t_old = raw.info['dev_head_t']
        ctf_head_t = raw.info['ctf_head_t']

        # 1) get BTI->Neuromag
        bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans))

        # 2) get Neuromag->BTI head
        t = combine_transforms(invert_transform(bti_dev_t), dev_ctf_t,
                               'meg', 'ctf_head')
        # 3) get Neuromag->head
        dev_head_t_new = combine_transforms(t, ctf_head_t, 'meg', 'head')

        assert_array_equal(dev_head_t_new['trans'], dev_head_t_old['trans'])
Пример #40
0
def test_find_ch_adjacency():
    """Test computing the adjacency matrix."""
    raw = read_raw_fif(raw_fname, preload=True)
    sizes = {'mag': 828, 'grad': 1700, 'eeg': 384}
    nchans = {'mag': 102, 'grad': 204, 'eeg': 60}
    for ch_type in ['mag', 'grad', 'eeg']:
        conn, ch_names = find_ch_adjacency(raw.info, ch_type)
        # Silly test for checking the number of neighbors.
        assert_equal(conn.getnnz(), sizes[ch_type])
        assert_equal(len(ch_names), nchans[ch_type])
    pytest.raises(ValueError, find_ch_adjacency, raw.info, None)

    # Test computing the conn matrix with gradiometers.
    conn, ch_names = _compute_ch_adjacency(raw.info, 'grad')
    assert_equal(conn.getnnz(), 2680)

    # Test ch_type=None.
    raw.pick_types(meg='mag')
    find_ch_adjacency(raw.info, None)

    bti_fname = op.join(testing_path, 'BTi', 'erm_HFH', 'c,rfDC')
    bti_config_name = op.join(testing_path, 'BTi', 'erm_HFH', 'config')
    raw = read_raw_bti(bti_fname, bti_config_name, None)
    _, ch_names = find_ch_adjacency(raw.info, 'mag')
    assert 'A1' in ch_names

    ctf_fname = op.join(testing_path, 'CTF', 'testdata_ctf_short.ds')
    raw = read_raw_ctf(ctf_fname)
    _, ch_names = find_ch_adjacency(raw.info, 'mag')
    assert 'MLC11' in ch_names

    pytest.raises(ValueError, find_ch_adjacency, raw.info, 'eog')

    raw_kit = read_raw_kit(fname_kit_157)
    neighb, ch_names = find_ch_adjacency(raw_kit.info, 'mag')
    assert neighb.data.size == 1329
    assert ch_names[0] == 'MEG 001'
Пример #41
0
def test_plot_alignment():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = _TempDir()
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{'coord_frame': 5, 'ident': 1, 'kind': 1,
            'r': [-0.08061612, -0.02908875, -0.04131077]},
           {'coord_frame': 5, 'ident': 2, 'kind': 1,
            'r': [0.00146763, 0.08506715, -0.03483611]},
           {'coord_frame': 5, 'ident': 3, 'kind': 1,
            'r': [0.08436285, -0.02850276, -0.04127743]}]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        meg = ['helmet', 'sensors']
        if system == 'KIT':
            meg.append('ref')
        plot_alignment(info, trans_fname, subject='sample',
                       subjects_dir=subjects_dir, meg=meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(TypeError, plot_alignment, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    assert_raises(TypeError, plot_alignment, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir, src='foo')
    assert_raises(ValueError, plot_alignment, info, trans_fname,
                  subject='fsaverage', subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir, head=True, skull=True,
                    brain='white')
    mlab.close(all=True)
    # no-head version
    mlab.close(all=True)
    # all coord frames
    assert_raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    for coord_frame in ('meg', 'head', 'mri'):
        plot_alignment(info, meg=['helmet', 'sensors'], dig=True,
                       coord_frame=coord_frame, trans=trans_fname,
                       subject='sample', mri_fiducials=fiducials_path,
                       subjects_dir=subjects_dir, src=sample_src)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_alignment(evoked_eeg_ecog.info, subject='sample',
                       trans=trans_fname, subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'], ecog=True)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])

    sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto')
    bem_sol = read_bem_solution(op.join(subjects_dir, 'sample', 'bem',
                                        'sample-1280-1280-1280-bem-sol.fif'))
    bem_surfs = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
                                          'sample-1280-1280-1280-bem.fif'))
    sample_src[0]['coord_frame'] = 4  # hack for coverage
    plot_alignment(info, subject='sample', eeg='projected',
                   meg='helmet', bem=sphere, dig=True,
                   surfaces=['brain', 'inner_skull', 'outer_skull',
                             'outer_skin'])
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain'], src=sample_src)
    plot_alignment(info, trans_fname, subject='sample', meg=[],
                   subjects_dir=subjects_dir, bem=bem_sol, eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    plot_alignment(info, trans_fname, subject='sample',
                   meg=True, subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'], bem=bem_surfs)
    sphere = make_sphere_model('auto', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(info, eeg='projected', meg='helmet', bem=sphere,
                   src=src, dig=True, surfaces=['brain', 'inner_skull',
                                                'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    plot_alignment(info, trans_fname, subject='sample', meg=False,
                   coord_frame='mri', subjects_dir=subjects_dir,
                   surfaces=['brain'], bem=sphere, show_axes=True)

    # one layer bem with skull surfaces:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['brain', 'head', 'inner_skull'], bem=sphere)
    # wrong eeg value:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, eeg='foo')
    # wrong meg value:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, meg='bar')
    # multiple brain surfaces:
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
    assert_raises(TypeError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=[1])
    assert_raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['foo'])
    mlab.close(all=True)
Пример #42
0
def test_plot_alignment(tmpdir, renderer):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{
        'coord_frame': 5,
        'ident': 1,
        'kind': 1,
        'r': [-0.08061612, -0.02908875, -0.04131077]
    }, {
        'coord_frame': 5,
        'ident': 2,
        'kind': 1,
        'r': [0.00146763, 0.08506715, -0.03483611]
    }, {
        'coord_frame': 5,
        'ident': 3,
        'kind': 1,
        'r': [0.08436285, -0.02850276, -0.04127743]
    }]
    write_dig(fiducials_path, fid, 5)

    renderer._close_all()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    bti = read_raw_bti(pdf_fname,
                       config_fname,
                       hs_fname,
                       convert=True,
                       preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        meg = ['helmet', 'sensors']
        if system == 'KIT':
            meg.append('ref')
        fig = plot_alignment(info,
                             trans_fname,
                             subject='sample',
                             subjects_dir=subjects_dir,
                             meg=meg)
        rend = renderer._Renderer(fig=fig)
        rend.close()
    # KIT ref sensor coil def is defined
    renderer._close_all()
    info = infos['Neuromag']
    pytest.raises(TypeError,
                  plot_alignment,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    pytest.raises(OSError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    pytest.raises(ValueError,
                  plot_alignment,
                  info,
                  trans_fname,
                  subject='fsaverage',
                  subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir,
                    head=True,
                    skull=True,
                    brain='white')
    renderer._close_all()
    # no-head version
    renderer._close_all()
    # all coord frames
    pytest.raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    for coord_frame in ('meg', 'head', 'mri'):
        fig = plot_alignment(info,
                             meg=['helmet', 'sensors'],
                             dig=True,
                             coord_frame=coord_frame,
                             trans=trans_fname,
                             subject='sample',
                             mri_fiducials=fiducials_path,
                             subjects_dir=subjects_dir,
                             src=src_fname)
    renderer._close_all()
    # EEG only with strange options
    evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({
        'EEG 001': 'ecog',
        'EEG 002': 'seeg'
    })
    with pytest.warns(RuntimeWarning, match='Cannot plot MEG'):
        plot_alignment(evoked_eeg_ecog_seeg.info,
                       subject='sample',
                       trans=trans_fname,
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'],
                       ecog=True,
                       seeg=True)
    renderer._close_all()

    sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto')
    bem_sol = read_bem_solution(
        op.join(subjects_dir, 'sample', 'bem',
                'sample-1280-1280-1280-bem-sol.fif'))
    bem_surfs = read_bem_surfaces(
        op.join(subjects_dir, 'sample', 'bem',
                'sample-1280-1280-1280-bem.fif'))
    sample_src[0]['coord_frame'] = 4  # hack for coverage
    plot_alignment(
        info,
        subject='sample',
        eeg='projected',
        meg='helmet',
        bem=sphere,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg='helmet',
                   subjects_dir=subjects_dir,
                   eeg='projected',
                   bem=sphere,
                   surfaces=['head', 'brain'],
                   src=sample_src)
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=[],
                   subjects_dir=subjects_dir,
                   bem=bem_sol,
                   eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info,
                   trans_fname,
                   subject='sample',
                   meg=True,
                   subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'],
                   bem=bem_surfs)
    # single-layer BEM can still plot head surface
    assert bem_surfs[-1]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN
    bem_sol_homog = read_bem_solution(
        op.join(subjects_dir, 'sample', 'bem', 'sample-1280-bem-sol.fif'))
    for use_bem in (bem_surfs[-1:], bem_sol_homog):
        with catch_logging() as log:
            plot_alignment(info,
                           trans_fname,
                           subject='sample',
                           meg=True,
                           subjects_dir=subjects_dir,
                           surfaces=['head', 'inner_skull'],
                           bem=use_bem,
                           verbose=True)
        log = log.getvalue()
        assert 'not find the surface for head in the provided BEM model' in log
    # sphere model
    sphere = make_sphere_model('auto', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(
        info,
        eeg='projected',
        meg='helmet',
        bem=sphere,
        src=src,
        dig=True,
        surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    # no info is permitted
    fig = plot_alignment(trans=trans_fname,
                         subject='sample',
                         meg=False,
                         coord_frame='mri',
                         subjects_dir=subjects_dir,
                         surfaces=['brain'],
                         bem=sphere,
                         show_axes=True)
    renderer._close_all()
    if renderer.get_3d_backend() == 'mayavi':
        import mayavi  # noqa: F401 analysis:ignore
        assert isinstance(fig, mayavi.core.scene.Scene)

    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, [0])
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    with use_coil_def(coil_def_fname):
        plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True)

    # one layer bem with skull surfaces:
    with pytest.raises(ValueError, match='sphere conductor model must have'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['brain', 'head', 'inner_skull'],
                       bem=sphere)
    # wrong eeg value:
    with pytest.raises(ValueError, match='eeg must only contain'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       eeg='foo')
    # wrong meg value:
    with pytest.raises(ValueError, match='meg must only contain'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       meg='bar')
    # multiple brain surfaces:
    with pytest.raises(ValueError, match='Only one brain surface can be plot'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['white', 'pial'])
    with pytest.raises(TypeError, match='all entries in surfaces must be'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=[1])
    with pytest.raises(ValueError, match='Unknown surface type'):
        plot_alignment(info=info,
                       trans=trans_fname,
                       subject='sample',
                       subjects_dir=subjects_dir,
                       surfaces=['foo'])
    fwd_fname = op.join(data_dir, 'MEG', 'sample',
                        'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
    fwd = read_forward_solution(fwd_fname)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')
    fwd = convert_forward_solution(fwd, force_fixed=True)
    plot_alignment(subject='sample',
                   subjects_dir=subjects_dir,
                   trans=trans_fname,
                   fwd=fwd,
                   surfaces='white',
                   coord_frame='head')

    renderer._close_all()
Пример #43
0
def test_plot_trans():
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    with warnings.catch_warnings(record=True):  # 4D weight tables
        bti = read_raw_bti(pdf_fname,
                           config_fname,
                           hs_fname,
                           convert=True,
                           preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        ref_meg = False if system == 'KIT' else True
        plot_trans(info,
                   trans_fname,
                   subject='sample',
                   meg_sensors=True,
                   subjects_dir=subjects_dir,
                   ref_meg=ref_meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True)
    mlab.close(all=True)
    info = infos['Neuromag']
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
    assert_raises(TypeError,
                  plot_trans,
                  'foo',
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir)
    assert_raises(TypeError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  src='foo')
    assert_raises(ValueError,
                  plot_trans,
                  info,
                  trans_fname,
                  subject='fsaverage',
                  subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir)
    mlab.close(all=True)
    # no-head version
    plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
    mlab.close(all=True)
    # all coord frames
    for coord_frame in ('meg', 'head', 'mri'):
        plot_trans(info,
                   meg_sensors=True,
                   dig=True,
                   coord_frame=coord_frame,
                   trans=trans_fname,
                   subject='sample',
                   subjects_dir=subjects_dir)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'})
    with warnings.catch_warnings(record=True) as w:
        plot_trans(evoked_eeg_ecog.info,
                   subject='sample',
                   trans=trans_fname,
                   source='outer_skin',
                   meg_sensors=True,
                   skull=True,
                   eeg_sensors=['original', 'projected'],
                   ecog_sensors=True,
                   brain='white',
                   head=True,
                   subjects_dir=subjects_dir)
    mlab.close(all=True)
    assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
def test_pick_refs():
    """Test picking of reference sensors."""
    infos = list()
    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    infos.append(raw_kit.info)
    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    infos.append(raw_bti.info)
    # CTF
    fname_ctf_raw = op.join(io_dir, 'tests', 'data', 'test_ctf_comp_raw.fif')
    raw_ctf = read_raw_fif(fname_ctf_raw)
    raw_ctf.apply_gradient_compensation(2)
    for info in infos:
        info['bads'] = []
        pytest.raises(ValueError, pick_types, info, meg='foo')
        pytest.raises(ValueError, pick_types, info, ref_meg='foo')
        picks_meg_ref = pick_types(info, meg=True, ref_meg=True)
        picks_meg = pick_types(info, meg=True, ref_meg=False)
        picks_ref = pick_types(info, meg=False, ref_meg=True)
        assert_array_equal(picks_meg_ref,
                           np.sort(np.concatenate([picks_meg, picks_ref])))
        picks_grad = pick_types(info, meg='grad', ref_meg=False)
        picks_ref_grad = pick_types(info, meg=False, ref_meg='grad')
        picks_meg_ref_grad = pick_types(info, meg='grad', ref_meg='grad')
        assert_array_equal(picks_meg_ref_grad,
                           np.sort(np.concatenate([picks_grad,
                                                   picks_ref_grad])))
        picks_mag = pick_types(info, meg='mag', ref_meg=False)
        picks_ref_mag = pick_types(info, meg=False, ref_meg='mag')
        picks_meg_ref_mag = pick_types(info, meg='mag', ref_meg='mag')
        assert_array_equal(picks_meg_ref_mag,
                           np.sort(np.concatenate([picks_mag,
                                                   picks_ref_mag])))
        assert_array_equal(picks_meg,
                           np.sort(np.concatenate([picks_mag, picks_grad])))
        assert_array_equal(picks_ref,
                           np.sort(np.concatenate([picks_ref_mag,
                                                   picks_ref_grad])))
        assert_array_equal(picks_meg_ref, np.sort(np.concatenate(
            [picks_grad, picks_mag, picks_ref_grad, picks_ref_mag])))

        for pick in (picks_meg_ref, picks_meg, picks_ref,
                     picks_grad, picks_ref_grad, picks_meg_ref_grad,
                     picks_mag, picks_ref_mag, picks_meg_ref_mag):
            if len(pick) > 0:
                pick_info(info, pick)

    # test CTF expected failures directly
    info = raw_ctf.info
    info['bads'] = []
    picks_meg_ref = pick_types(info, meg=True, ref_meg=True)
    picks_meg = pick_types(info, meg=True, ref_meg=False)
    picks_ref = pick_types(info, meg=False, ref_meg=True)
    picks_mag = pick_types(info, meg='mag', ref_meg=False)
    picks_ref_mag = pick_types(info, meg=False, ref_meg='mag')
    picks_meg_ref_mag = pick_types(info, meg='mag', ref_meg='mag')
    for pick in (picks_meg_ref, picks_ref, picks_ref_mag, picks_meg_ref_mag):
        if len(pick) > 0:
            pick_info(info, pick)

    for pick in (picks_meg, picks_mag):
        if len(pick) > 0:
            with catch_logging() as log:
                pick_info(info, pick, verbose=True)
            assert ('Removing {} compensators'.format(len(info['comps']))
                    in log.getvalue())
Пример #45
0
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_alignment, set_3d_title

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = {
    'Neuromag':
    read_raw_fif(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif'),
    'CTF 275':
    read_raw_ctf(spm_face.data_path() +
                 '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    'Magnes 3600wh':
    read_raw_bti(op.join(bti_path, 'test_pdf_linux'),
                 op.join(bti_path, 'test_config_linux'),
                 op.join(bti_path, 'test_hs_linux')),
    'KIT':
    read_raw_kit(op.join(kit_path, 'test.sqd')),
    'Artemis123':
    read_raw_artemis123(
        op.join(testing.data_path(), 'ARTEMIS123',
                'Artemis_Data_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')),
}

for system, raw in sorted(raws.items()):
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
    if system != 'KIT':
        meg.append('ref')
    fig = plot_alignment(raw.info,
Пример #46
0
def test_plot_alignment(tmpdir):
    """Test plotting of -trans.fif files and MEG sensor layouts."""
    # generate fiducials file for testing
    tempdir = str(tmpdir)
    fiducials_path = op.join(tempdir, 'fiducials.fif')
    fid = [{'coord_frame': 5, 'ident': 1, 'kind': 1,
            'r': [-0.08061612, -0.02908875, -0.04131077]},
           {'coord_frame': 5, 'ident': 2, 'kind': 1,
            'r': [0.00146763, 0.08506715, -0.03483611]},
           {'coord_frame': 5, 'ident': 3, 'kind': 1,
            'r': [0.08436285, -0.02850276, -0.04127743]}]
    write_dig(fiducials_path, fid, 5)

    mlab = _import_mlab()
    evoked = read_evokeds(evoked_fname)[0]
    sample_src = read_source_spaces(src_fname)
    bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
                       preload=False).info
    infos = dict(
        Neuromag=evoked.info,
        CTF=read_raw_ctf(ctf_fname).info,
        BTi=bti,
        KIT=read_raw_kit(sqd_fname).info,
    )
    for system, info in infos.items():
        meg = ['helmet', 'sensors']
        if system == 'KIT':
            meg.append('ref')
        plot_alignment(info, trans_fname, subject='sample',
                       subjects_dir=subjects_dir, meg=meg)
        mlab.close(all=True)
    # KIT ref sensor coil def is defined
    mlab.close(all=True)
    info = infos['Neuromag']
    pytest.raises(TypeError, plot_alignment, 'foo', trans_fname,
                  subject='sample', subjects_dir=subjects_dir)
    pytest.raises(TypeError, plot_alignment, info, trans_fname,
                  subject='sample', subjects_dir=subjects_dir, src='foo')
    pytest.raises(ValueError, plot_alignment, info, trans_fname,
                  subject='fsaverage', subjects_dir=subjects_dir,
                  src=sample_src)
    sample_src.plot(subjects_dir=subjects_dir, head=True, skull=True,
                    brain='white')
    mlab.close(all=True)
    # no-head version
    mlab.close(all=True)
    # all coord frames
    pytest.raises(ValueError, plot_alignment, info)
    plot_alignment(info, surfaces=[])
    for coord_frame in ('meg', 'head', 'mri'):
        plot_alignment(info, meg=['helmet', 'sensors'], dig=True,
                       coord_frame=coord_frame, trans=trans_fname,
                       subject='sample', mri_fiducials=fiducials_path,
                       subjects_dir=subjects_dir, src=sample_src)
        mlab.close(all=True)
    # EEG only with strange options
    evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True)
    evoked_eeg_ecog_seeg.info['projs'] = []  # "remove" avg proj
    evoked_eeg_ecog_seeg.set_channel_types({'EEG 001': 'ecog',
                                            'EEG 002': 'seeg'})
    with pytest.warns(RuntimeWarning, match='Cannot plot MEG'):
        plot_alignment(evoked_eeg_ecog_seeg.info, subject='sample',
                       trans=trans_fname, subjects_dir=subjects_dir,
                       surfaces=['white', 'outer_skin', 'outer_skull'],
                       meg=['helmet', 'sensors'],
                       eeg=['original', 'projected'], ecog=True, seeg=True)
    mlab.close(all=True)

    sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto')
    bem_sol = read_bem_solution(op.join(subjects_dir, 'sample', 'bem',
                                        'sample-1280-1280-1280-bem-sol.fif'))
    bem_surfs = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
                                          'sample-1280-1280-1280-bem.fif'))
    sample_src[0]['coord_frame'] = 4  # hack for coverage
    plot_alignment(info, subject='sample', eeg='projected',
                   meg='helmet', bem=sphere, dig=True,
                   surfaces=['brain', 'inner_skull', 'outer_skull',
                             'outer_skin'])
    plot_alignment(info, trans_fname, subject='sample', meg='helmet',
                   subjects_dir=subjects_dir, eeg='projected', bem=sphere,
                   surfaces=['head', 'brain'], src=sample_src)
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info, trans_fname, subject='sample', meg=[],
                   subjects_dir=subjects_dir, bem=bem_sol, eeg=True,
                   surfaces=['head', 'inflated', 'outer_skull', 'inner_skull'])
    assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI
               for surf in bem_sol['surfs'])
    plot_alignment(info, trans_fname, subject='sample',
                   meg=True, subjects_dir=subjects_dir,
                   surfaces=['head', 'inner_skull'], bem=bem_surfs)
    sphere = make_sphere_model('auto', 'auto', evoked.info)
    src = setup_volume_source_space(sphere=sphere)
    plot_alignment(info, eeg='projected', meg='helmet', bem=sphere,
                   src=src, dig=True, surfaces=['brain', 'inner_skull',
                                                'outer_skull', 'outer_skin'])
    sphere = make_sphere_model('auto', None, evoked.info)  # one layer
    plot_alignment(info, trans_fname, subject='sample', meg=False,
                   coord_frame='mri', subjects_dir=subjects_dir,
                   surfaces=['brain'], bem=sphere, show_axes=True)

    # 3D coil with no defined draw (ConvexHull)
    info_cube = pick_info(info, [0])
    info['dig'] = None
    info_cube['chs'][0]['coil_type'] = 9999
    with pytest.raises(RuntimeError, match='coil definition not found'):
        plot_alignment(info_cube, meg='sensors', surfaces=())
    coil_def_fname = op.join(tempdir, 'temp')
    with open(coil_def_fname, 'w') as fid:
        fid.write(coil_3d)
    with use_coil_def(coil_def_fname):
        plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True)

    # one layer bem with skull surfaces:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['brain', 'head', 'inner_skull'], bem=sphere)
    # wrong eeg value:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, eeg='foo')
    # wrong meg value:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir, meg='bar')
    # multiple brain surfaces:
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['white', 'pial'])
    pytest.raises(TypeError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=[1])
    pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  surfaces=['foo'])
    mlab.close(all=True)
Пример #47
0
def test_other_systems():
    """Test Maxwell filtering on KIT, BTI, and CTF files
    """
    io_dir = op.join(op.dirname(__file__), '..', '..', 'io')

    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    with warnings.catch_warnings(record=True):  # head fit
        assert_raises(RuntimeError, maxwell_filter, raw_kit)
    raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 65, 65)
    # XXX this KIT origin fit is terrible! Eventually we should get a
    # corrected HSP file with proper coverage
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            assert_raises(RuntimeError, maxwell_filter, raw_kit,
                          ignore_ref=True, regularize=None)  # bad condition
            raw_sss = maxwell_filter(raw_kit, origin='auto',
                                     ignore_ref=True, bad_condition='warning',
                                     verbose='warning')
    log_file = log_file.getvalue()
    assert_true('badly conditioned' in log_file)
    assert_true('more than 20 mm from' in log_file)
    # fits can differ slightly based on scipy version, so be lenient here
    _assert_n_free(raw_sss, 28, 34)  # bad origin == brutal reg
    # Let's set the origin
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                     ignore_ref=True, bad_condition='warning',
                                     regularize=None, verbose='warning')
    log_file = log_file.getvalue()
    assert_true('badly conditioned' in log_file)
    _assert_n_free(raw_sss, 80)
    # Now with reg
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                     ignore_ref=True, verbose=True)
    log_file = log_file.getvalue()
    assert_true('badly conditioned' not in log_file)
    _assert_n_free(raw_sss, 65)

    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    with warnings.catch_warnings(record=True):  # weght table
        raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    raw_sss = maxwell_filter(raw_bti)
    _assert_n_free(raw_sss, 70)

    # CTF
    fname_ctf_raw = op.join(io_dir, 'tests', 'data', 'test_ctf_comp_raw.fif')
    raw_ctf = Raw(fname_ctf_raw, compensation=2)
    assert_raises(RuntimeError, maxwell_filter, raw_ctf)  # compensated
    raw_ctf = Raw(fname_ctf_raw)
    assert_raises(ValueError, maxwell_filter, raw_ctf)  # cannot fit headshape
    raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04))
    _assert_n_free(raw_sss, 68)
    raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 70)
Пример #48
0
def test_other_systems():
    """Test Maxwell filtering on KIT, BTI, and CTF files
    """
    io_dir = op.join(op.dirname(__file__), "..", "..", "io")

    # KIT
    kit_dir = op.join(io_dir, "kit", "tests", "data")
    sqd_path = op.join(kit_dir, "test.sqd")
    mrk_path = op.join(kit_dir, "test_mrk.sqd")
    elp_path = op.join(kit_dir, "test_elp.txt")
    hsp_path = op.join(kit_dir, "test_hsp.txt")
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    assert_raises(RuntimeError, maxwell_filter, raw_kit)
    raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 65)
    # XXX this KIT origin fit is terrible! Eventually we should get a
    # corrected HSP file with proper coverage
    with catch_logging() as log_file:
        assert_raises(RuntimeError, maxwell_filter, raw_kit, ignore_ref=True, regularize=None)  # bad condition
        raw_sss = maxwell_filter(raw_kit, origin="auto", ignore_ref=True, bad_condition="warning", verbose="warning")
    log_file = log_file.getvalue()
    assert_true("badly conditioned" in log_file)
    assert_true("more than 20 mm from" in log_file)
    # fits can differ slightly based on scipy version, so be lenient here
    _assert_n_free(raw_sss, 28, 34)  # bad origin == brutal reg
    # Let's set the origin
    with catch_logging() as log_file:
        raw_sss = maxwell_filter(
            raw_kit,
            origin=(0.0, 0.0, 0.04),
            ignore_ref=True,
            bad_condition="warning",
            regularize=None,
            verbose="warning",
        )
    log_file = log_file.getvalue()
    assert_true("badly conditioned" in log_file)
    _assert_n_free(raw_sss, 80)
    # Now with reg
    with catch_logging() as log_file:
        raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, verbose=True)
    log_file = log_file.getvalue()
    assert_true("badly conditioned" not in log_file)
    _assert_n_free(raw_sss, 65)

    # BTi
    bti_dir = op.join(io_dir, "bti", "tests", "data")
    bti_pdf = op.join(bti_dir, "test_pdf_linux")
    bti_config = op.join(bti_dir, "test_config_linux")
    bti_hs = op.join(bti_dir, "test_hs_linux")
    raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    raw_sss = maxwell_filter(raw_bti)
    _assert_n_free(raw_sss, 70)

    # CTF
    fname_ctf_raw = op.join(io_dir, "tests", "data", "test_ctf_comp_raw.fif")
    raw_ctf = Raw(fname_ctf_raw, compensation=2)
    assert_raises(RuntimeError, maxwell_filter, raw_ctf)  # compensated
    raw_ctf = Raw(fname_ctf_raw)
    assert_raises(ValueError, maxwell_filter, raw_ctf)  # cannot fit headshape
    raw_sss = maxwell_filter(raw_ctf, origin=(0.0, 0.0, 0.04))
    _assert_n_free(raw_sss, 68)
    raw_sss = maxwell_filter(raw_ctf, origin=(0.0, 0.0, 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 70)
Пример #49
0
def test_make_forward_solution_kit():
    """Test making fwd using KIT, BTI, and CTF (compensated) files
    """
    kit_dir = op.join(op.dirname(__file__), "..", "..", "io", "kit", "tests", "data")
    sqd_path = op.join(kit_dir, "test.sqd")
    mrk_path = op.join(kit_dir, "test_mrk.sqd")
    elp_path = op.join(kit_dir, "test_elp.txt")
    hsp_path = op.join(kit_dir, "test_hsp.txt")
    trans_path = op.join(kit_dir, "trans-sample.fif")
    fname_kit_raw = op.join(kit_dir, "test_bin_raw.fif")

    bti_dir = op.join(op.dirname(__file__), "..", "..", "io", "bti", "tests", "data")
    bti_pdf = op.join(bti_dir, "test_pdf_linux")
    bti_config = op.join(bti_dir, "test_config_linux")
    bti_hs = op.join(bti_dir, "test_hs_linux")
    fname_bti_raw = op.join(bti_dir, "exported4D_linux_raw.fif")

    fname_ctf_raw = op.join(op.dirname(__file__), "..", "..", "io", "tests", "data", "test_ctf_comp_raw.fif")

    # first set up a small testing source space
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, "sample-oct-2-src.fif")
    src = setup_source_space("sample", fname_src_small, "oct2", subjects_dir=subjects_dir, add_dist=False)
    n_src = 108  # this is the resulting # of verts in fwd

    # first use mne-C: convert file, make forward solution
    fwd = _do_forward_solution(
        "sample",
        fname_kit_raw,
        src=fname_src_small,
        bem=fname_bem_meg,
        mri=trans_path,
        eeg=False,
        meg=True,
        subjects_dir=subjects_dir,
    )
    assert_true(isinstance(fwd, Forward))

    # now let's use python with the same raw file
    fwd_py = make_forward_solution(fname_kit_raw, trans_path, src, fname_bem_meg, eeg=False, meg=True)
    _compare_forwards(fwd, fwd_py, 157, n_src)
    assert_true(isinstance(fwd_py, Forward))

    # now let's use mne-python all the way
    raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    # without ignore_ref=True, this should throw an error:
    assert_raises(
        NotImplementedError,
        make_forward_solution,
        raw_py.info,
        src=src,
        eeg=False,
        meg=True,
        bem=fname_bem_meg,
        trans=trans_path,
    )

    # check that asking for eeg channels (even if they don't exist) is handled
    meg_only_info = pick_info(raw_py.info, pick_types(raw_py.info, meg=True, eeg=False))
    fwd_py = make_forward_solution(
        meg_only_info, src=src, meg=True, eeg=True, bem=fname_bem_meg, trans=trans_path, ignore_ref=True
    )
    _compare_forwards(fwd, fwd_py, 157, n_src, meg_rtol=1e-3, meg_atol=1e-7)

    # BTI python end-to-end versus C
    fwd = _do_forward_solution(
        "sample",
        fname_bti_raw,
        src=fname_src_small,
        bem=fname_bem_meg,
        mri=trans_path,
        eeg=False,
        meg=True,
        subjects_dir=subjects_dir,
    )
    with warnings.catch_warnings(record=True):  # weight tables
        raw_py = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    fwd_py = make_forward_solution(raw_py.info, src=src, eeg=False, meg=True, bem=fname_bem_meg, trans=trans_path)
    _compare_forwards(fwd, fwd_py, 248, n_src)

    # now let's test CTF w/compensation
    fwd_py = make_forward_solution(fname_ctf_raw, fname_trans, src, fname_bem_meg, eeg=False, meg=True)

    fwd = _do_forward_solution(
        "sample",
        fname_ctf_raw,
        mri=fname_trans,
        src=fname_src_small,
        bem=fname_bem_meg,
        eeg=False,
        meg=True,
        subjects_dir=subjects_dir,
    )
    _compare_forwards(fwd, fwd_py, 274, n_src)

    # CTF with compensation changed in python
    ctf_raw = Raw(fname_ctf_raw, compensation=2)

    fwd_py = make_forward_solution(ctf_raw.info, fname_trans, src, fname_bem_meg, eeg=False, meg=True)
    with warnings.catch_warnings(record=True):
        fwd = _do_forward_solution(
            "sample",
            ctf_raw,
            mri=fname_trans,
            src=fname_src_small,
            bem=fname_bem_meg,
            eeg=False,
            meg=True,
            subjects_dir=subjects_dir,
        )
    _compare_forwards(fwd, fwd_py, 274, n_src)
Пример #50
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import Raw, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.datasets import sample, spm_face
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = dict(
    Neuromag=Raw(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif'),
    CTF_275=read_raw_ctf(spm_face.data_path() +
                         '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    Magnes_3600wh=read_raw_bti(bti_path + 'test_pdf_linux',
                               bti_path + 'test_config_linux',
                               bti_path + 'test_hs_linux'),
    KIT=read_raw_kit(kit_path + 'test.sqd'),
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info, trans=None, dig=False, eeg_sensors=False,
                     meg_sensors=True, coord_frame='meg', ref_meg=ref_meg)
    mlab.title(system)
Пример #51
0
    parser.add_option('--eog_ch', dest='eog_ch', type='str',
                    help='4D EOG channel names',
                    default='E63,E64')

    options, args = parser.parse_args()

    pdf_fname = options.pdf_fname
    if pdf_fname is None:
        parser.print_help()
        sys.exit(1)

    config_fname = options.config_fname
    head_shape_fname = options.head_shape_fname
    out_fname = options.out_fname
    rotation_x = options.rotation_x
    translation = options.translation
    ecg_ch = options.ecg_ch
    eog_ch = options.ecg_ch.split(',')

    if out_fname == 'as_data_fname':
        out_fname = pdf_fname + '_raw.fif'

    raw = read_raw_bti(pdf_fname=pdf_fname, config_fname=config_fname,
                       head_shape_fname=head_shape_fname,
                       rotation_x=rotation_x, translation=translation,
                       ecg_ch=ecg_ch, eog_ch=eog_ch)

    raw.save(out_fname)
    raw.close()
    sys.exit(0)
Пример #52
0
def test_other_systems():
    """Test Maxwell filtering on KIT, BTI, and CTF files."""
    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    with warnings.catch_warnings(record=True):  # head fit
        assert_raises(RuntimeError, maxwell_filter, raw_kit)
    raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 65, 65)
    raw_sss_auto = maxwell_filter(raw_kit,
                                  origin=(0., 0., 0.04),
                                  ignore_ref=True,
                                  mag_scale='auto')
    assert_allclose(raw_sss._data, raw_sss_auto._data)
    # XXX this KIT origin fit is terrible! Eventually we should get a
    # corrected HSP file with proper coverage
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            assert_raises(RuntimeError,
                          maxwell_filter,
                          raw_kit,
                          ignore_ref=True,
                          regularize=None)  # bad condition
            raw_sss = maxwell_filter(raw_kit,
                                     origin='auto',
                                     ignore_ref=True,
                                     bad_condition='warning',
                                     verbose='warning')
    log_file = log_file.getvalue()
    assert_true('badly conditioned' in log_file)
    assert_true('more than 20 mm from' in log_file)
    # fits can differ slightly based on scipy version, so be lenient here
    _assert_n_free(raw_sss, 28, 34)  # bad origin == brutal reg
    # Let's set the origin
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit,
                                     origin=(0., 0., 0.04),
                                     ignore_ref=True,
                                     bad_condition='warning',
                                     regularize=None,
                                     verbose='warning')
    log_file = log_file.getvalue()
    assert_true('badly conditioned' in log_file)
    _assert_n_free(raw_sss, 80)
    # Now with reg
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit,
                                     origin=(0., 0., 0.04),
                                     ignore_ref=True,
                                     verbose=True)
    log_file = log_file.getvalue()
    assert_true('badly conditioned' not in log_file)
    _assert_n_free(raw_sss, 65)

    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    with warnings.catch_warnings(record=True):  # weght table
        raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    picks = pick_types(raw_bti.info, meg='mag', exclude=())
    power = np.sqrt(np.sum(raw_bti[picks][0]**2))
    raw_sss = maxwell_filter(raw_bti)
    _assert_n_free(raw_sss, 70)
    _assert_shielding(raw_sss, power, 0.5)
    raw_sss_auto = maxwell_filter(raw_bti, mag_scale='auto', verbose=True)
    _assert_shielding(raw_sss_auto, power, 0.7)

    # CTF
    raw_ctf = read_crop(fname_ctf_raw)
    assert_equal(raw_ctf.compensation_grade, 3)
    assert_raises(RuntimeError, maxwell_filter, raw_ctf)  # compensated
    raw_ctf.apply_gradient_compensation(0)
    assert_raises(ValueError, maxwell_filter, raw_ctf)  # cannot fit headshape
    raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04))
    _assert_n_free(raw_sss, 68)
    _assert_shielding(raw_sss, raw_ctf, 1.8)
    raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 70)
    _assert_shielding(raw_sss, raw_ctf, 12)
    raw_sss_auto = maxwell_filter(raw_ctf,
                                  origin=(0., 0., 0.04),
                                  ignore_ref=True,
                                  mag_scale='auto')
    assert_allclose(raw_sss._data, raw_sss_auto._data)
Пример #53
0
def test_other_systems():
    """Test Maxwell filtering on KIT, BTI, and CTF files."""
    # KIT
    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    with pytest.warns(RuntimeWarning, match='fit'):
        pytest.raises(RuntimeError, maxwell_filter, raw_kit)
    with catch_logging() as log:
        raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                 ignore_ref=True, verbose=True)
    assert '12/15 out' in log.getvalue()  # homogeneous fields removed
    _assert_n_free(raw_sss, 65, 65)
    raw_sss_auto = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                  ignore_ref=True, mag_scale='auto')
    assert_allclose(raw_sss._data, raw_sss_auto._data)
    # XXX this KIT origin fit is terrible! Eventually we should get a
    # corrected HSP file with proper coverage
    with pytest.warns(RuntimeWarning, match='more than 20 mm'):
        with catch_logging() as log:
            pytest.raises(RuntimeError, maxwell_filter, raw_kit,
                          ignore_ref=True, regularize=None)  # bad condition
            raw_sss = maxwell_filter(raw_kit, origin='auto',
                                     ignore_ref=True, bad_condition='info',
                                     verbose=True)
    log = log.getvalue()
    assert 'badly conditioned' in log
    assert 'more than 20 mm from' in log
    # fits can differ slightly based on scipy version, so be lenient here
    _assert_n_free(raw_sss, 28, 34)  # bad origin == brutal reg
    # Let's set the origin
    with catch_logging() as log:
        raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                 ignore_ref=True, bad_condition='info',
                                 regularize=None, verbose=True)
    log = log.getvalue()
    assert 'badly conditioned' in log
    assert '80/80 in, 12/15 out' in log
    _assert_n_free(raw_sss, 80)
    # Now with reg
    with catch_logging() as log:
        raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
                                 ignore_ref=True, verbose=True)
    log = log.getvalue()
    assert 'badly conditioned' not in log
    assert '12/15 out' in log
    _assert_n_free(raw_sss, 65)

    # BTi
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    raw_bti = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    picks = pick_types(raw_bti.info, meg='mag', exclude=())
    power = np.sqrt(np.sum(raw_bti[picks][0] ** 2))
    raw_sss = maxwell_filter(raw_bti)
    _assert_n_free(raw_sss, 70)
    _assert_shielding(raw_sss, power, 0.5)
    raw_sss_auto = maxwell_filter(raw_bti, mag_scale='auto', verbose=True)
    _assert_shielding(raw_sss_auto, power, 0.7)

    # CTF
    raw_ctf = read_crop(fname_ctf_raw)
    assert_equal(raw_ctf.compensation_grade, 3)
    pytest.raises(RuntimeError, maxwell_filter, raw_ctf)  # compensated
    raw_ctf.apply_gradient_compensation(0)
    pytest.raises(ValueError, maxwell_filter, raw_ctf)  # cannot fit headshape
    raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04))
    _assert_n_free(raw_sss, 68)
    _assert_shielding(raw_sss, raw_ctf, 1.8)
    with catch_logging() as log:
        raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04),
                                 ignore_ref=True, verbose=True)
    assert ', 12/15 out' in log.getvalue()  # homogeneous fields removed
    _assert_n_free(raw_sss, 70)
    _assert_shielding(raw_sss, raw_ctf, 12)
    raw_sss_auto = maxwell_filter(raw_ctf, origin=(0., 0., 0.04),
                                  ignore_ref=True, mag_scale='auto')
    assert_allclose(raw_sss._data, raw_sss_auto._data)
    with catch_logging() as log:
        maxwell_filter(raw_ctf, origin=(0., 0., 0.04), regularize=None,
                       ignore_ref=True, verbose=True)
    assert '80/80 in, 12/15 out' in log.getvalue()  # homogeneous fields
Пример #54
0
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.io import read_raw_artemis123
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_alignment

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = {
    'Neuromag': read_raw_fif(sample.data_path() +
                             '/MEG/sample/sample_audvis_raw.fif'),
    'CTF 275': read_raw_ctf(spm_face.data_path() +
                            '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    'Magnes 3600wh': read_raw_bti(op.join(bti_path, 'test_pdf_linux'),
                                  op.join(bti_path, 'test_config_linux'),
                                  op.join(bti_path, 'test_hs_linux')),
    'KIT': read_raw_kit(op.join(kit_path, 'test.sqd')),
    'Artemis123': read_raw_artemis123(op.join(
        testing.data_path(), 'ARTEMIS123',
        'Artemis_Data_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')),
}

for system, raw in sorted(raws.items()):
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
    if system != 'KIT':
        meg.append('ref')
    fig = plot_alignment(raw.info, trans=None, dig=False, eeg=False,
                         surfaces=[], meg=meg, coord_frame='meg',
                         verbose=True)
Пример #55
0
def test_make_forward_solution_kit():
    """Test making fwd using KIT, BTI, and CTF (compensated) files."""
    kit_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'kit',
                      'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    trans_path = op.join(kit_dir, 'trans-sample.fif')
    fname_kit_raw = op.join(kit_dir, 'test_bin_raw.fif')

    bti_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'bti',
                      'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    fname_bti_raw = op.join(bti_dir, 'exported4D_linux_raw.fif')

    fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'io', 'tests',
                            'data', 'test_ctf_comp_raw.fif')

    # first set up a small testing source space
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif')
    src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir,
                             add_dist=False)
    write_source_spaces(fname_src_small, src)  # to enable working with MNE-C
    n_src = 108  # this is the resulting # of verts in fwd

    # first use mne-C: convert file, make forward solution
    fwd = _do_forward_solution('sample', fname_kit_raw, src=fname_src_small,
                               bem=fname_bem_meg, mri=trans_path,
                               eeg=False, meg=True, subjects_dir=subjects_dir)
    assert (isinstance(fwd, Forward))

    # now let's use python with the same raw file
    fwd_py = make_forward_solution(fname_kit_raw, trans_path, src,
                                   fname_bem_meg, eeg=False, meg=True)
    _compare_forwards(fwd, fwd_py, 157, n_src)
    assert (isinstance(fwd_py, Forward))

    # now let's use mne-python all the way
    raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    # without ignore_ref=True, this should throw an error:
    pytest.raises(NotImplementedError, make_forward_solution, raw_py.info,
                  src=src, eeg=False, meg=True,
                  bem=fname_bem_meg, trans=trans_path)

    # check that asking for eeg channels (even if they don't exist) is handled
    meg_only_info = pick_info(raw_py.info, pick_types(raw_py.info, meg=True,
                                                      eeg=False))
    fwd_py = make_forward_solution(meg_only_info, src=src, meg=True, eeg=True,
                                   bem=fname_bem_meg, trans=trans_path,
                                   ignore_ref=True)
    _compare_forwards(fwd, fwd_py, 157, n_src,
                      meg_rtol=1e-3, meg_atol=1e-7)

    # BTI python end-to-end versus C
    fwd = _do_forward_solution('sample', fname_bti_raw, src=fname_src_small,
                               bem=fname_bem_meg, mri=trans_path,
                               eeg=False, meg=True, subjects_dir=subjects_dir)
    raw_py = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    fwd_py = make_forward_solution(raw_py.info, src=src, eeg=False, meg=True,
                                   bem=fname_bem_meg, trans=trans_path)
    _compare_forwards(fwd, fwd_py, 248, n_src)

    # now let's test CTF w/compensation
    fwd_py = make_forward_solution(fname_ctf_raw, fname_trans, src,
                                   fname_bem_meg, eeg=False, meg=True)

    fwd = _do_forward_solution('sample', fname_ctf_raw, mri=fname_trans,
                               src=fname_src_small, bem=fname_bem_meg,
                               eeg=False, meg=True, subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, n_src)

    # CTF with compensation changed in python
    ctf_raw = read_raw_fif(fname_ctf_raw)
    ctf_raw.info['bads'] = ['MRO24-2908']  # test that it works with some bads
    ctf_raw.apply_gradient_compensation(2)

    fwd_py = make_forward_solution(ctf_raw.info, fname_trans, src,
                                   fname_bem_meg, eeg=False, meg=True)
    fwd = _do_forward_solution('sample', ctf_raw, mri=fname_trans,
                               src=fname_src_small, bem=fname_bem_meg,
                               eeg=False, meg=True,
                               subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, n_src)

    temp_dir = _TempDir()
    fname_temp = op.join(temp_dir, 'test-ctf-fwd.fif')
    write_forward_solution(fname_temp, fwd_py)
    fwd_py2 = read_forward_solution(fname_temp)
    _compare_forwards(fwd_py, fwd_py2, 274, n_src)
    repr(fwd_py)
Пример #56
0
logging.getLogger('log').addHandler(console)

# print a.ch_names
# print len(a)
# print a[0][0]
# print len(a[0][0])
# print len(a[0][1])
# print a.info

for pre, con in paths:
    for ind in con:

        logger.info('Individual %s', ind)
        indf = pre + ind

        a = read_raw_bti(smaqepath + indf + '/e,rfhp1.0Hz', verbose=False)

        for band, lf, hf in lband:
            fa = mne.filter.band_pass_filter(a)

            nchannels = len([cn for cn in a.info['ch_names'] if 'MEG' in cn])
            data = np.zeros((nchannels, len(a)))
            lcnames = []
            ic = 0
            for i, cn in enumerate(a.ch_names):
                if 'MEG' in cn:
                    #print cn
                    lcnames.append(cn)
                    data[ic] = a[i][0][0]
                    ic += 1
Пример #57
0
def test_make_forward_solution_kit():
    """Test making fwd using KIT, BTI, and CTF (compensated) files."""
    kit_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'kit', 'tests',
                      'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    trans_path = op.join(kit_dir, 'trans-sample.fif')
    fname_kit_raw = op.join(kit_dir, 'test_bin_raw.fif')

    bti_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'bti', 'tests',
                      'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    fname_bti_raw = op.join(bti_dir, 'exported4D_linux_raw.fif')

    fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'io', 'tests',
                            'data', 'test_ctf_comp_raw.fif')

    # first set up a small testing source space
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif')
    src = setup_source_space('sample',
                             'oct2',
                             subjects_dir=subjects_dir,
                             add_dist=False)
    write_source_spaces(fname_src_small, src)  # to enable working with MNE-C
    n_src = 108  # this is the resulting # of verts in fwd

    # first use mne-C: convert file, make forward solution
    fwd = _do_forward_solution('sample',
                               fname_kit_raw,
                               src=fname_src_small,
                               bem=fname_bem_meg,
                               mri=trans_path,
                               eeg=False,
                               meg=True,
                               subjects_dir=subjects_dir)
    assert_true(isinstance(fwd, Forward))

    # now let's use python with the same raw file
    fwd_py = make_forward_solution(fname_kit_raw,
                                   trans_path,
                                   src,
                                   fname_bem_meg,
                                   eeg=False,
                                   meg=True)
    _compare_forwards(fwd, fwd_py, 157, n_src)
    assert_true(isinstance(fwd_py, Forward))

    # now let's use mne-python all the way
    raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    # without ignore_ref=True, this should throw an error:
    assert_raises(NotImplementedError,
                  make_forward_solution,
                  raw_py.info,
                  src=src,
                  eeg=False,
                  meg=True,
                  bem=fname_bem_meg,
                  trans=trans_path)

    # check that asking for eeg channels (even if they don't exist) is handled
    meg_only_info = pick_info(raw_py.info,
                              pick_types(raw_py.info, meg=True, eeg=False))
    fwd_py = make_forward_solution(meg_only_info,
                                   src=src,
                                   meg=True,
                                   eeg=True,
                                   bem=fname_bem_meg,
                                   trans=trans_path,
                                   ignore_ref=True)
    _compare_forwards(fwd, fwd_py, 157, n_src, meg_rtol=1e-3, meg_atol=1e-7)

    # BTI python end-to-end versus C
    fwd = _do_forward_solution('sample',
                               fname_bti_raw,
                               src=fname_src_small,
                               bem=fname_bem_meg,
                               mri=trans_path,
                               eeg=False,
                               meg=True,
                               subjects_dir=subjects_dir)
    with warnings.catch_warnings(record=True):  # weight tables
        raw_py = read_raw_bti(bti_pdf, bti_config, bti_hs, preload=False)
    fwd_py = make_forward_solution(raw_py.info,
                                   src=src,
                                   eeg=False,
                                   meg=True,
                                   bem=fname_bem_meg,
                                   trans=trans_path)
    _compare_forwards(fwd, fwd_py, 248, n_src)

    # now let's test CTF w/compensation
    fwd_py = make_forward_solution(fname_ctf_raw,
                                   fname_trans,
                                   src,
                                   fname_bem_meg,
                                   eeg=False,
                                   meg=True)

    fwd = _do_forward_solution('sample',
                               fname_ctf_raw,
                               mri=fname_trans,
                               src=fname_src_small,
                               bem=fname_bem_meg,
                               eeg=False,
                               meg=True,
                               subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, n_src)

    # CTF with compensation changed in python
    ctf_raw = read_raw_fif(fname_ctf_raw)
    ctf_raw.apply_gradient_compensation(2)

    fwd_py = make_forward_solution(ctf_raw.info,
                                   fname_trans,
                                   src,
                                   fname_bem_meg,
                                   eeg=False,
                                   meg=True)
    with warnings.catch_warnings(record=True):
        fwd = _do_forward_solution('sample',
                                   ctf_raw,
                                   mri=fname_trans,
                                   src=fname_src_small,
                                   bem=fname_bem_meg,
                                   eeg=False,
                                   meg=True,
                                   subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, n_src)
Пример #58
0
def test_make_forward_solution_kit():
    """Test making fwd using KIT, BTI, and CTF (compensated) files
    """
    fname_bem = op.join(subjects_dir, 'sample', 'bem',
                        'sample-5120-bem-sol.fif')
    kit_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'kit',
                      'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    mri_path = op.join(kit_dir, 'trans-sample.fif')
    fname_kit_raw = op.join(kit_dir, 'test_bin_raw.fif')

    bti_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'bti',
                      'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs = op.join(bti_dir, 'test_hs_linux')
    fname_bti_raw = op.join(bti_dir, 'exported4D_linux_raw.fif')

    fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'io', 'tests',
                            'data', 'test_ctf_comp_raw.fif')

    # first set up a testing source space
    fname_src = op.join(temp_dir, 'oct2-src.fif')
    src = setup_source_space('sample', fname_src, 'oct2',
                             subjects_dir=subjects_dir)

    # first use mne-C: convert file, make forward solution
    fwd = do_forward_solution('sample', fname_kit_raw, src=fname_src,
                              mindist=0.0, bem=fname_bem, mri=mri_path,
                              eeg=False, meg=True, subjects_dir=subjects_dir)
    assert_true(isinstance(fwd, Forward))

    # now let's use python with the same raw file
    fwd_py = make_forward_solution(fname_kit_raw, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=mri_path)
    _compare_forwards(fwd, fwd_py, 157, 108)
    assert_true(isinstance(fwd_py, Forward))

    # now let's use mne-python all the way
    raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    # without ignore_ref=True, this should throw an error:
    assert_raises(NotImplementedError, make_forward_solution, raw_py.info,
                  mindist=0.0, src=src, eeg=False, meg=True,
                  bem=fname_bem, mri=mri_path)
    fwd_py = make_forward_solution(raw_py.info, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=mri_path,
                                   ignore_ref=True)
    _compare_forwards(fwd, fwd_py, 157, 108,
                      meg_rtol=1e-3, meg_atol=1e-7)

    # BTI python end-to-end versus C
    fwd = do_forward_solution('sample', fname_bti_raw, src=fname_src,
                              mindist=0.0, bem=fname_bem, mri=mri_path,
                              eeg=False, meg=True, subjects_dir=subjects_dir)
    raw_py = read_raw_bti(bti_pdf, bti_config, bti_hs)
    fwd_py = make_forward_solution(raw_py.info, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=mri_path)
    _compare_forwards(fwd, fwd_py, 248, 108)

    # now let's test CTF w/compensation
    fwd_py = make_forward_solution(fname_ctf_raw, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=fname_mri)

    fwd = do_forward_solution('sample', fname_ctf_raw, src=fname_src,
                              mindist=0.0, bem=fname_bem, mri=fname_mri,
                              eeg=False, meg=True, subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, 108)

    # CTF with compensation changed in python
    ctf_raw = Raw(fname_ctf_raw, compensation=2)

    fwd_py = make_forward_solution(ctf_raw.info, mindist=0.0,
                                   src=src, eeg=False, meg=True,
                                   bem=fname_bem, mri=fname_mri)
    with warnings.catch_warnings(record=True):
        fwd = do_forward_solution('sample', ctf_raw, src=fname_src,
                                  mindist=0.0, bem=fname_bem, mri=fname_mri,
                                  eeg=False, meg=True,
                                  subjects_dir=subjects_dir)
    _compare_forwards(fwd, fwd_py, 274, 108)