Пример #1
0
def test_evoked_proj():
    """Test SSP proj operations
    """
    for proj in [True, False]:
        ave = read_evokeds(fname, condition=0, proj=proj)
        assert_true(all(p['active'] == proj for p in ave.info['projs']))

        # test adding / deleting proj
        if proj:
            assert_raises(ValueError, ave.add_proj, [],
                          {'remove_existing': True})
            assert_raises(ValueError, ave.del_proj, 0)
        else:
            projs = deepcopy(ave.info['projs'])
            n_proj = len(ave.info['projs'])
            ave.del_proj(0)
            assert_true(len(ave.info['projs']) == n_proj - 1)
            ave.add_proj(projs, remove_existing=False)
            assert_true(len(ave.info['projs']) == 2 * n_proj - 1)
            ave.add_proj(projs, remove_existing=True)
            assert_true(len(ave.info['projs']) == n_proj)

    ave = read_evokeds(fname, condition=0, proj=False)
    data = ave.data.copy()
    ave.apply_proj()
    assert_allclose(np.dot(ave._projector, data), ave.data)
Пример #2
0
def test_evoked_io_from_epochs():
    """Test IO of evoked data made from epochs
    """
    # offset our tmin so we don't get exactly a zero value when decimating
    with warnings.catch_warnings(record=True) as w:
        epochs = Epochs(raw, events[:4], event_id, tmin + 0.011, tmax,
                        picks=picks, baseline=(None, 0), decim=5)
    assert_true(len(w) == 1)
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'evoked.fif'))
    evoked2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0]
    assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
    assert_allclose(evoked.times, evoked2.times, rtol=1e-4,
                    atol=1 / evoked.info['sfreq'])

    # now let's do one with negative time
    with warnings.catch_warnings(record=True) as w:
        epochs = Epochs(raw, events[:4], event_id, 0.1, tmax,
                        picks=picks, baseline=(0.1, 0.2), decim=5)
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'evoked.fif'))
    evoked2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0]
    assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
    assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)

    # should be equivalent to a cropped original
    with warnings.catch_warnings(record=True) as w:
        epochs = Epochs(raw, events[:4], event_id, -0.2, tmax,
                        picks=picks, baseline=(0.1, 0.2), decim=5)
    evoked = epochs.average()
    evoked.crop(0.099, None)
    assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
    assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
Пример #3
0
def test_evoked_resample():
    """Test for resampling of evoked data
    """
    # upsample, write it out, read it in
    ave = read_evokeds(fname, 0)
    sfreq_normal = ave.info['sfreq']
    ave.resample(2 * sfreq_normal)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)
    ave_up = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    # compare it to the original
    ave_normal = read_evokeds(fname, 0)

    # and compare the original to the downsampled upsampled version
    ave_new = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_new.resample(sfreq_normal)

    assert_array_almost_equal(ave_normal.data, ave_new.data, 2)
    assert_array_almost_equal(ave_normal.times, ave_new.times)
    assert_equal(ave_normal.nave, ave_new.nave)
    assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)
    assert_equal(ave_normal.kind, ave_new.kind)
    assert_equal(ave_normal.last, ave_new.last)
    assert_equal(ave_normal.first, ave_new.first)

    # for the above to work, the upsampling just about had to, but
    # we'll add a couple extra checks anyway
    assert_true(len(ave_up.times) == 2 * len(ave_normal.times))
    assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
Пример #4
0
def test_evoked_proj():
    """Test SSP proj operations
    """
    for proj in [True, False]:
        ave = read_evokeds(fname, condition=0, proj=proj)
        assert_true(all(p['active'] == proj for p in ave.info['projs']))

        # test adding / deleting proj
        if proj:
            assert_raises(ValueError, ave.add_proj, [],
                          {'remove_existing': True})
            assert_raises(ValueError, ave.del_proj, 0)
        else:
            projs = deepcopy(ave.info['projs'])
            n_proj = len(ave.info['projs'])
            ave.del_proj(0)
            assert_true(len(ave.info['projs']) == n_proj - 1)
            ave.add_proj(projs, remove_existing=False)
            assert_true(len(ave.info['projs']) == 2 * n_proj - 1)
            ave.add_proj(projs, remove_existing=True)
            assert_true(len(ave.info['projs']) == n_proj)

    ave = read_evokeds(fname, condition=0, proj=False)
    data = ave.data.copy()
    ave.apply_proj()
    assert_allclose(np.dot(ave._projector, data), ave.data)
Пример #5
0
def test_evoked_standard_error():
    """Test calculation and read/write of standard error
    """
    epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0))
    evoked = [epochs.average(), epochs.standard_error()]
    io.write_evokeds(op.join(tempdir, 'evoked.fif'), evoked)
    evoked2 = read_evokeds(op.join(tempdir, 'evoked.fif'), [0, 1])
    evoked3 = [read_evokeds(op.join(tempdir, 'evoked.fif'), 'Unknown'),
               read_evokeds(op.join(tempdir, 'evoked.fif'), 'Unknown',
                            kind='standard_error')]
    for evoked_new in [evoked2, evoked3]:
        assert_true(evoked_new[0]._aspect_kind ==
                    FIFF.FIFFV_ASPECT_AVERAGE)
        assert_true(evoked_new[0].kind == 'average')
        assert_true(evoked_new[1]._aspect_kind ==
                    FIFF.FIFFV_ASPECT_STD_ERR)
        assert_true(evoked_new[1].kind == 'standard_error')
        for ave, ave2 in zip(evoked, evoked_new):
            assert_array_almost_equal(ave.data, ave2.data)
            assert_array_almost_equal(ave.times, ave2.times)
            assert_equal(ave.nave, ave2.nave)
            assert_equal(ave._aspect_kind, ave2._aspect_kind)
            assert_equal(ave.kind, ave2.kind)
            assert_equal(ave.last, ave2.last)
            assert_equal(ave.first, ave2.first)
Пример #6
0
def test_evoked_resample():
    """Test for resampling of evoked data
    """
    # upsample, write it out, read it in
    ave = read_evokeds(fname, 0)
    sfreq_normal = ave.info['sfreq']
    ave.resample(2 * sfreq_normal)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)
    ave_up = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    # compare it to the original
    ave_normal = read_evokeds(fname, 0)

    # and compare the original to the downsampled upsampled version
    ave_new = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_new.resample(sfreq_normal)

    assert_array_almost_equal(ave_normal.data, ave_new.data, 2)
    assert_array_almost_equal(ave_normal.times, ave_new.times)
    assert_equal(ave_normal.nave, ave_new.nave)
    assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)
    assert_equal(ave_normal.kind, ave_new.kind)
    assert_equal(ave_normal.last, ave_new.last)
    assert_equal(ave_normal.first, ave_new.first)

    # for the above to work, the upsampling just about had to, but
    # we'll add a couple extra checks anyway
    assert_true(len(ave_up.times) == 2 * len(ave_normal.times))
    assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
Пример #7
0
def test_evoked_to_nitime():
    """ Test to_nitime """
    ave = read_evokeds(fname, 0)
    evoked_ts = ave.to_nitime()
    assert_equal(evoked_ts.data, ave.data)

    picks2 = [1, 2]
    ave = read_evokeds(fname, 0)
    evoked_ts = ave.to_nitime(picks=picks2)
    assert_equal(evoked_ts.data, ave.data[picks2])
Пример #8
0
def test_evoked_to_nitime():
    """ Test to_nitime """
    ave = read_evokeds(fname, 0)
    evoked_ts = ave.to_nitime()
    assert_equal(evoked_ts.data, ave.data)

    picks2 = [1, 2]
    ave = read_evokeds(fname, 0)
    evoked_ts = ave.to_nitime(picks=picks2)
    assert_equal(evoked_ts.data, ave.data[picks2])
Пример #9
0
def test_evoked_detrend():
    """Test for detrending evoked data
    """
    ave = read_evokeds(fname, 0)
    ave_normal = read_evokeds(fname, 0)
    ave.detrend(0)
    ave_normal.data -= np.mean(ave_normal.data, axis=1)[:, np.newaxis]
    picks = pick_types(ave.info, meg=True, eeg=True, exclude='bads')
    assert_true(np.allclose(ave.data[picks], ave_normal.data[picks],
                            rtol=1e-8, atol=1e-16))
Пример #10
0
def test_evoked_detrend():
    """Test for detrending evoked data
    """
    ave = read_evokeds(fname, 0)
    ave_normal = read_evokeds(fname, 0)
    ave.detrend(0)
    ave_normal.data -= np.mean(ave_normal.data, axis=1)[:, np.newaxis]
    picks = pick_types(ave.info, meg=True, eeg=True, exclude='bads')
    assert_true(
        np.allclose(ave.data[picks],
                    ave_normal.data[picks],
                    rtol=1e-8,
                    atol=1e-16))
Пример #11
0
def test_make_field_map_eeg():
    """Test interpolation of EEG field onto head
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory')
    evoked.info['bads'] = ['MEG 2443', 'EEG 053']  # add some bads
    surf = get_head_surf('sample', subjects_dir=subjects_dir)
    # we must have trans if surface is in MRI coords
    assert_raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg')

    evoked = pick_types_evoked(evoked, meg=False, eeg=True)
    fmd = make_field_map(evoked,
                         trans_fname=trans_fname,
                         subject='sample',
                         subjects_dir=subjects_dir)

    # trans is necessary for EEG only
    assert_raises(RuntimeError,
                  make_field_map,
                  evoked,
                  trans_fname=None,
                  subject='sample',
                  subjects_dir=subjects_dir)

    fmd = make_field_map(evoked,
                         trans_fname=trans_fname,
                         subject='sample',
                         subjects_dir=subjects_dir)
    assert_true(len(fmd) == 1)
    assert_array_equal(fmd[0]['data'].shape, (2562, 59))  # maps data onto surf
    assert_true(len(fmd[0]['ch_names']), 59)
Пример #12
0
def test_gamma_map():
    """Test Gamma MAP inverse"""
    forward = read_forward_solution(fname_fwd, force_fixed=False,
                                    surf_ori=True)
    evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
    evoked.crop(tmin=0, tmax=0.3)

    cov = read_cov(fname_cov)
    cov = regularize(cov, evoked.info)

    alpha = 0.2
    stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                    xyz_same_gamma=True, update_mode=1)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 96397)

    stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                    xyz_same_gamma=False, update_mode=1)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 82010)

    # force fixed orientation
    stc, res = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                         xyz_same_gamma=False, update_mode=2,
                         loose=None, return_residual=True)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 83398)

    assert_array_almost_equal(evoked.times, res.times)
Пример #13
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evokeds(fname, 0)

    write_evokeds(op.join(tempdir, 'evoked.fif'), ave)
    ave2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0]

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evokeds(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    condition = 'Left Auditory'
    assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')
    assert_raises(ValueError, read_evokeds, fname, condition,
                  kind='standard_error')
    ave3 = read_evokeds(fname, condition)
    assert_array_almost_equal(ave.data, ave3.data, 19)

    # test deprecation warning for read_evoked and write_evoked
    # XXX should be deleted for 0.9 release
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        ave = read_evoked(fname, setno=0)
        assert_true(w[0].category == DeprecationWarning)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        write_evoked(op.join(tempdir, 'evoked.fif'), ave)
        assert_true(w[0].category == DeprecationWarning)

    # test read_evokeds and write_evokeds
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves1 = read_evokeds(fname)
    aves2 = read_evokeds(fname, [0, 1, 2, 3])
    aves3 = read_evokeds(fname, types)
    write_evokeds(op.join(tempdir, 'evoked.fif'), aves1)
    aves4 = read_evokeds(op.join(tempdir, 'evoked.fif'))
    for aves in [aves2, aves3, aves4]:
        for [av1, av2] in zip(aves1, aves):
            assert_array_almost_equal(av1.data, av2.data)
            assert_array_almost_equal(av1.times, av2.times)
            assert_equal(av1.nave, av2.nave)
            assert_equal(av1.kind, av2.kind)
            assert_equal(av1._aspect_kind, av2._aspect_kind)
            assert_equal(av1.last, av2.last)
            assert_equal(av1.first, av2.first)
            assert_equal(av1.comment, av2.comment)
Пример #14
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = io.read_evokeds(evoked_fname, 'Left Auditory',
                                  baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg')
        plot_evoked_topomap(evoked, times, ch_type='grad')
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True)

        p = plot_evoked_topomap(evoked, times, ch_type='grad',
                                show_names=lambda x: x.replace('MEG', ''))
        subplot = [x for x in p.get_children() if
                   isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(all('MEG' not in x.get_text()
                        for x in subplot.get_children()
                        if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if
                    isinstance(x, matplotlib.text.Text)]

        p = plot_evoked_topomap(evoked, times, ch_type='eeg')
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom')
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
Пример #15
0
 def compensate_mne(fname, comp):
     tmp_fname = '%s-%d-ave.fif' % (fname[:-4], comp)
     cmd = [
         'mne_compensate_data', '--in', fname, '--out', tmp_fname, '--grad',
         str(comp)
     ]
     run_subprocess(cmd)
     return read_evokeds(tmp_fname)[0]
Пример #16
0
def test_as_data_frame():
    """Test evoked Pandas exporter"""
    ave = read_evokeds(fname, 0)
    assert_raises(ValueError, ave.as_data_frame, picks=np.arange(400))
    df = ave.as_data_frame()
    assert_true((df.columns == ave.ch_names).all())
    df = ave.as_data_frame(use_time_index=False)
    assert_true('time' in df.columns)
    assert_array_equal(df.values[:, 1], ave.data[0] * 1e13)
    assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)
Пример #17
0
def test_as_data_frame():
    """Test evoked Pandas exporter"""
    ave = read_evokeds(fname, 0)
    assert_raises(ValueError, ave.as_data_frame, picks=np.arange(400))
    df = ave.as_data_frame()
    assert_true((df.columns == ave.ch_names).all())
    df = ave.as_data_frame(use_time_index=False)
    assert_true('time' in df.columns)
    assert_array_equal(df.values[:, 1], ave.data[0] * 1e13)
    assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)
Пример #18
0
def test_plot_evoked_field():
    trans_fname = op.join(data_dir, 'MEG', 'sample',
                          'sample_audvis_raw-trans.fif')
    evoked = io.read_evokeds(evoked_fname, condition='Left Auditory',
                               baseline=(-0.2, 0.0))
    evoked = pick_channels_evoked(evoked, evoked.ch_names[::10])  # speed
    for t in ['meg', None]:
        maps = make_field_map(evoked, trans_fname=trans_fname,
                              subject='sample', subjects_dir=subjects_dir,
                              n_jobs=1, ch_type=t)

        evoked.plot_field(maps, time=0.1)
Пример #19
0
def test_equalize_channels():
    """Test equalization of channels
    """
    evoked1 = read_evokeds(fname, condition=0, proj=True)
    evoked2 = evoked1.copy()
    ch_names = evoked1.ch_names[2:]
    evoked1.drop_channels(evoked1.ch_names[:1])
    evoked2.drop_channels(evoked2.ch_names[1:2])
    my_comparison = [evoked1, evoked2]
    equalize_channels(my_comparison)
    for e in my_comparison:
        assert_equal(ch_names, e.ch_names)
Пример #20
0
def test_equalize_channels():
    """Test equalization of channels
    """
    evoked1 = read_evokeds(fname, condition=0, proj=True)
    evoked2 = evoked1.copy()
    ch_names = evoked1.ch_names[2:]
    evoked1.drop_channels(evoked1.ch_names[:1])
    evoked2.drop_channels(evoked2.ch_names[1:2])
    my_comparison = [evoked1, evoked2]
    equalize_channels(my_comparison)
    for e in my_comparison:
        assert_equal(ch_names, e.ch_names)
Пример #21
0
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    trans_fname = op.join(data_dir, 'MEG', 'sample',
                          'sample_audvis_raw-trans.fif')
    evoked = io.read_evokeds(evoked_fname, condition='Left Auditory',
                             baseline=(-0.2, 0.0))
    plot_trans(evoked.info, trans_fname=trans_fname, subject='sample',
               subjects_dir=subjects_dir)
    assert_raises(ValueError, plot_trans, evoked.info, trans_fname=trans_fname,
                  subject='sample', subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
Пример #22
0
def test_pick_channels_mixin():
    """Test channel-picking functionality
    """
    evoked = read_evokeds(fname, condition=0, proj=True)
    ch_names = evoked.ch_names[:3]

    ch_names_orig = evoked.ch_names
    dummy = evoked.pick_channels(ch_names, copy=True)
    assert_equal(ch_names, dummy.ch_names)
    assert_equal(ch_names_orig, evoked.ch_names)
    assert_equal(len(ch_names_orig), len(evoked.data))

    evoked.pick_channels(ch_names)
    assert_equal(ch_names, evoked.ch_names)
    assert_equal(len(ch_names), len(evoked.data))
Пример #23
0
def test_pick_channels_mixin():
    """Test channel-picking functionality
    """
    evoked = read_evokeds(fname, condition=0, proj=True)
    ch_names = evoked.ch_names[:3]

    ch_names_orig = evoked.ch_names
    dummy = evoked.pick_channels(ch_names, copy=True)
    assert_equal(ch_names, dummy.ch_names)
    assert_equal(ch_names_orig, evoked.ch_names)
    assert_equal(len(ch_names_orig), len(evoked.data))

    evoked.pick_channels(ch_names)
    assert_equal(ch_names, evoked.ch_names)
    assert_equal(len(ch_names), len(evoked.data))
Пример #24
0
def test_comparision_with_c():
    """Test of average obtained vs C code
    """
    c_evoked = read_evokeds(evoked_nf_name, condition=0)
    epochs = Epochs(raw, events, event_id, tmin, tmax,
                    baseline=None, preload=True,
                    reject=None, flat=None)
    evoked = epochs.average()
    sel = pick_channels(c_evoked.ch_names, evoked.ch_names)
    evoked_data = evoked.data
    c_evoked_data = c_evoked.data[sel]

    assert_true(evoked.nave == c_evoked.nave)
    assert_array_almost_equal(evoked_data, c_evoked_data, 10)
    assert_array_almost_equal(evoked.times, c_evoked.times, 12)
Пример #25
0
def test_plot_evoked_field():
    trans_fname = op.join(data_dir, 'MEG', 'sample',
                          'sample_audvis_raw-trans.fif')
    evoked = io.read_evokeds(evoked_fname,
                             condition='Left Auditory',
                             baseline=(-0.2, 0.0))
    evoked = pick_channels_evoked(evoked, evoked.ch_names[::10])  # speed
    for t in ['meg', None]:
        maps = make_field_map(evoked,
                              trans_fname=trans_fname,
                              subject='sample',
                              subjects_dir=subjects_dir,
                              n_jobs=1,
                              ch_type=t)

        evoked.plot_field(maps, time=0.1)
Пример #26
0
def test_drop_channels_mixin():
    """Test channels-dropping functionality
    """
    evoked = read_evokeds(fname, condition=0, proj=True)
    drop_ch = evoked.ch_names[:3]
    ch_names = evoked.ch_names[3:]

    ch_names_orig = evoked.ch_names
    dummy = evoked.drop_channels(drop_ch, copy=True)
    assert_equal(ch_names, dummy.ch_names)
    assert_equal(ch_names_orig, evoked.ch_names)
    assert_equal(len(ch_names_orig), len(evoked.data))

    evoked.drop_channels(drop_ch)
    assert_equal(ch_names, evoked.ch_names)
    assert_equal(len(ch_names), len(evoked.data))
Пример #27
0
def test_drop_channels_mixin():
    """Test channels-dropping functionality
    """
    evoked = read_evokeds(fname, condition=0, proj=True)
    drop_ch = evoked.ch_names[:3]
    ch_names = evoked.ch_names[3:]

    ch_names_orig = evoked.ch_names
    dummy = evoked.drop_channels(drop_ch, copy=True)
    assert_equal(ch_names, dummy.ch_names)
    assert_equal(ch_names_orig, evoked.ch_names)
    assert_equal(len(ch_names_orig), len(evoked.data))

    evoked.drop_channels(drop_ch)
    assert_equal(ch_names, evoked.ch_names)
    assert_equal(len(ch_names), len(evoked.data))
Пример #28
0
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = Raw(raw_fname)
    fwd = read_forward_solution(fwd_fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
    cov = read_cov(cov_fname)
    label_names = ['Aud-lh', 'Aud-rh']
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                         '%s.label' % label)) for label in label_names]

    evoked_template = read_evokeds(ave_fname, condition=0, baseline=None)
    evoked_template = pick_types_evoked(evoked_template, meg=True, eeg=True,
                                        exclude=raw.info['bads'])

    snr = 6  # dB
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
    stc_data[0][:len(Ws[0])] = np.real(Ws[0])
    stc_data[1][:len(Ws[1])] = np.real(Ws[1])
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[1] = np.roll(stc_data[1], 80)
    stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
                              random_state=0)

    # Generate noisy evoked data
    iir_filter = [1, -0.9]
    evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
                             tmin=0.0, tmax=0.2, iir_filter=iir_filter)
    assert_array_almost_equal(evoked.times, stc.times)
    assert_true(len(evoked.data) == len(fwd['sol']['data']))

    # make a vertex that doesn't exist in fwd, should throw error
    stc_bad = stc.copy()
    mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']])
    stc_bad.vertno[0][0] = mv + 1
    assert_raises(RuntimeError, generate_evoked, fwd, stc_bad,
                  evoked_template, cov, snr, tmin=0.0, tmax=0.2)
Пример #29
0
def test_gamma_map():
    """Test Gamma MAP inverse"""
    forward = read_forward_solution(fname_fwd,
                                    force_fixed=False,
                                    surf_ori=True)
    evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
    evoked.crop(tmin=0, tmax=0.3)

    cov = read_cov(fname_cov)
    cov = regularize(cov, evoked.info)

    alpha = 0.2
    stc = gamma_map(evoked,
                    forward,
                    cov,
                    alpha,
                    tol=1e-5,
                    xyz_same_gamma=True,
                    update_mode=1)
    idx = np.argmax(np.sum(stc.data**2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 96397)

    stc = gamma_map(evoked,
                    forward,
                    cov,
                    alpha,
                    tol=1e-5,
                    xyz_same_gamma=False,
                    update_mode=1)
    idx = np.argmax(np.sum(stc.data**2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 82010)

    # force fixed orientation
    stc, res = gamma_map(evoked,
                         forward,
                         cov,
                         alpha,
                         tol=1e-5,
                         xyz_same_gamma=False,
                         update_mode=2,
                         loose=None,
                         return_residual=True)
    idx = np.argmax(np.sum(stc.data**2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 83398)

    assert_array_almost_equal(evoked.times, res.times)
Пример #30
0
def test_evoked_whiten():
    """Test whitening of evoked data"""
    evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0),
                          proj=True)
    cov = read_cov(cov_fname)

    ###########################################################################
    # Show result
    picks = pick_types(evoked.info, meg=True, eeg=True, ref_meg=False,
                       exclude='bads')

    noise_cov = regularize(cov, evoked.info, grad=0.1, mag=0.1, eeg=0.1,
                           exclude='bads')

    evoked_white = whiten_evoked(evoked, noise_cov, picks, diag=True)
    whiten_baseline_data = evoked_white.data[picks][:, evoked.times < 0]
    mean_baseline = np.mean(np.abs(whiten_baseline_data), axis=1)
    assert_true(np.all(mean_baseline < 1.))
    assert_true(np.all(mean_baseline > 0.2))
Пример #31
0
def test_plot_trans():
    """Test plotting of -trans.fif files
    """
    trans_fname = op.join(data_dir, 'MEG', 'sample',
                          'sample_audvis_raw-trans.fif')
    evoked = io.read_evokeds(evoked_fname,
                             condition='Left Auditory',
                             baseline=(-0.2, 0.0))
    plot_trans(evoked.info,
               trans_fname=trans_fname,
               subject='sample',
               subjects_dir=subjects_dir)
    assert_raises(ValueError,
                  plot_trans,
                  evoked.info,
                  trans_fname=trans_fname,
                  subject='sample',
                  subjects_dir=subjects_dir,
                  ch_type='bad-chtype')
Пример #32
0
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True)

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = read_evokeds(fname_evoked, condition=0)
        evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw = Raw(fname_raw)
        raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)
Пример #33
0
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True)

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = read_evokeds(fname_evoked, condition=0)
        evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw = Raw(fname_raw)
        raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)
Пример #34
0
def test_make_field_map_meg():
    """Test interpolation of MEG field onto helmet
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory')
    info = evoked.info
    surf = get_meg_helmet_surf(info)
    # let's reduce the number of channels by a bunch to speed it up
    info['bads'] = info['ch_names'][:200]
    # bad ch_type
    assert_raises(ValueError, _make_surface_mapping, info, surf, 'foo')
    # bad mode
    assert_raises(ValueError,
                  _make_surface_mapping,
                  info,
                  surf,
                  'meg',
                  mode='foo')
    # no picks
    evoked_eeg = pick_types_evoked(evoked, meg=False, eeg=True)
    assert_raises(RuntimeError, _make_surface_mapping, evoked_eeg.info, surf,
                  'meg')
    # bad surface def
    nn = surf['nn']
    del surf['nn']
    assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
    surf['nn'] = nn
    cf = surf['coord_frame']
    del surf['coord_frame']
    assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
    surf['coord_frame'] = cf

    # now do it with make_field_map
    evoked = pick_types_evoked(evoked, meg=True, eeg=False)
    fmd = make_field_map(evoked,
                         trans_fname=None,
                         subject='sample',
                         subjects_dir=subjects_dir)
    assert_true(len(fmd) == 1)
    assert_array_equal(fmd[0]['data'].shape, (304, 106))  # maps data onto surf
    assert_true(len(fmd[0]['ch_names']), 106)

    assert_raises(ValueError, make_field_map, evoked, ch_type='foobar')
Пример #35
0
def test_get_peak():
    """Test peak getter
    """

    evoked = read_evokeds(fname, condition=0, proj=True)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9)
    assert_raises(ValueError,
                  evoked.get_peak,
                  ch_type='mag',
                  tmin=0.02,
                  tmax=0.01)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo')
    assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')
    assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')

    ch_idx, time_idx = evoked.get_peak(ch_type='mag')
    assert_true(ch_idx in evoked.ch_names)
    assert_true(time_idx in evoked.times)

    ch_idx, time_idx = evoked.get_peak(ch_type='mag', time_as_index=True)
    assert_true(time_idx < len(evoked.times))

    data = np.array([[0., 1., 2.], [0., -3., 0]])

    times = np.array([.1, .2, .3])

    ch_idx, time_idx = _get_peak(data, times, mode='abs')
    assert_equal(ch_idx, 1)
    assert_equal(time_idx, 1)

    ch_idx, time_idx = _get_peak(data * -1, times, mode='neg')
    assert_equal(ch_idx, 0)
    assert_equal(time_idx, 2)

    ch_idx, time_idx = _get_peak(data, times, mode='pos')
    assert_equal(ch_idx, 0)
    assert_equal(time_idx, 2)

    assert_raises(ValueError, _get_peak, data + 1e3, times, mode='neg')
    assert_raises(ValueError, _get_peak, data - 1e3, times, mode='pos')
Пример #36
0
def test_get_peak():
    """Test peak getter
    """

    evoked = read_evokeds(fname, condition=0, proj=True)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=0.02,
                  tmax=0.01)
    assert_raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo')
    assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')
    assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')

    ch_idx, time_idx = evoked.get_peak(ch_type='mag')
    assert_true(ch_idx in evoked.ch_names)
    assert_true(time_idx in evoked.times)

    ch_idx, time_idx = evoked.get_peak(ch_type='mag',
                                       time_as_index=True)
    assert_true(time_idx < len(evoked.times))

    data = np.array([[0., 1.,  2.],
                     [0., -3.,  0]])

    times = np.array([.1, .2, .3])

    ch_idx, time_idx = _get_peak(data, times, mode='abs')
    assert_equal(ch_idx, 1)
    assert_equal(time_idx, 1)

    ch_idx, time_idx = _get_peak(data * -1, times, mode='neg')
    assert_equal(ch_idx, 0)
    assert_equal(time_idx, 2)

    ch_idx, time_idx = _get_peak(data, times, mode='pos')
    assert_equal(ch_idx, 0)
    assert_equal(time_idx, 2)

    assert_raises(ValueError, _get_peak, data + 1e3, times, mode='neg')
    assert_raises(ValueError, _get_peak, data - 1e3, times, mode='pos')
def test_make_field_map_eeg():
    """Test interpolation of EEG field onto head
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory')
    evoked.info['bads'] = ['MEG 2443', 'EEG 053']  # add some bads
    surf = get_head_surf('sample', subjects_dir=subjects_dir)
    # we must have trans if surface is in MRI coords
    assert_raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg')

    evoked = pick_types_evoked(evoked, meg=False, eeg=True)
    fmd = make_field_map(evoked, trans_fname=trans_fname,
                         subject='sample', subjects_dir=subjects_dir)

    # trans is necessary for EEG only
    assert_raises(RuntimeError, make_field_map, evoked, trans_fname=None,
                  subject='sample', subjects_dir=subjects_dir)

    fmd = make_field_map(evoked, trans_fname=trans_fname,
                         subject='sample', subjects_dir=subjects_dir)
    assert_true(len(fmd) == 1)
    assert_array_equal(fmd[0]['data'].shape, (2562, 59))  # maps data onto surf
    assert_true(len(fmd[0]['ch_names']), 59)
def test_make_field_map_meg():
    """Test interpolation of MEG field onto helmet
    """
    evoked = read_evokeds(evoked_fname, condition='Left Auditory')
    info = evoked.info
    surf = get_meg_helmet_surf(info)
    # let's reduce the number of channels by a bunch to speed it up
    info['bads'] = info['ch_names'][:200]
    # bad ch_type
    assert_raises(ValueError, _make_surface_mapping, info, surf, 'foo')
    # bad mode
    assert_raises(ValueError, _make_surface_mapping, info, surf, 'meg',
                  mode='foo')
    # no picks
    evoked_eeg = pick_types_evoked(evoked, meg=False, eeg=True)
    assert_raises(RuntimeError, _make_surface_mapping, evoked_eeg.info,
                  surf, 'meg')
    # bad surface def
    nn = surf['nn']
    del surf['nn']
    assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
    surf['nn'] = nn
    cf = surf['coord_frame']
    del surf['coord_frame']
    assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
    surf['coord_frame'] = cf

    # now do it with make_field_map
    evoked = pick_types_evoked(evoked, meg=True, eeg=False)
    fmd = make_field_map(evoked, trans_fname=None,
                         subject='sample', subjects_dir=subjects_dir)
    assert_true(len(fmd) == 1)
    assert_array_equal(fmd[0]['data'].shape, (304, 106))  # maps data onto surf
    assert_true(len(fmd[0]['ch_names']), 106)

    assert_raises(ValueError, make_field_map, evoked, ch_type='foobar')
Пример #39
0
def test_shift_time_evoked():
    """ Test for shifting of time scale
    """
    # Shift backward
    ave = read_evokeds(fname, 0)
    ave.shift_time(-0.1, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)

    # Shift forward twice the amount
    ave_bshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_bshift.shift_time(0.2, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_bshift)

    # Shift backward again
    ave_fshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_fshift.shift_time(-0.1, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_fshift)

    ave_normal = read_evokeds(fname, 0)
    ave_relative = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    assert_true(np.allclose(ave_normal.data, ave_relative.data,
                            atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)

    assert_equal(ave_normal.last, ave_relative.last)
    assert_equal(ave_normal.first, ave_relative.first)

    # Absolute time shift
    ave = read_evokeds(fname, 0)
    ave.shift_time(-0.3, relative=False)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)

    ave_absolute = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    assert_true(np.allclose(ave_normal.data, ave_absolute.data,
                            atol=1e-16, rtol=1e-3))
    assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
Пример #40
0
def test_shift_time_evoked():
    """ Test for shifting of time scale
    """
    # Shift backward
    ave = read_evokeds(fname, 0)
    ave.shift_time(-0.1, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)

    # Shift forward twice the amount
    ave_bshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_bshift.shift_time(0.2, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_bshift)

    # Shift backward again
    ave_fshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
    ave_fshift.shift_time(-0.1, relative=True)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_fshift)

    ave_normal = read_evokeds(fname, 0)
    ave_relative = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    assert_true(
        np.allclose(ave_normal.data, ave_relative.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)

    assert_equal(ave_normal.last, ave_relative.last)
    assert_equal(ave_normal.first, ave_relative.first)

    # Absolute time shift
    ave = read_evokeds(fname, 0)
    ave.shift_time(-0.3, relative=False)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)

    ave_absolute = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)

    assert_true(
        np.allclose(ave_normal.data, ave_absolute.data, atol=1e-16, rtol=1e-3))
    assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
Пример #41
0
which can be useful for reproducing research results.

The MEGSIM files will be dowloaded automatically.

The datasets are documented in:
Aine CJ, Sanfratello L, Ranken D, Best E, MacArthur JA, Wallace T,
Gilliam K, Donahue CH, Montano R, Bryant JE, Scott A, Stephen JM
(2012) MEG-SIM: A Web Portal for Testing MEG Analysis Methods using
Realistic Simulated and Empirical Data. Neuroinformatics 10:141-158
"""
print(__doc__)

from mne.io import read_evokeds
from mne.datasets.megsim import load_data

condition = 'visual'  # or 'auditory' or 'somatosensory'

# Load experimental RAW files for the visual condition
epochs_fnames = load_data(condition=condition,
                          data_format='single-trial',
                          data_type='simulation')

# Take only 10 trials from the same simulation setup.
epochs_fnames = [f for f in epochs_fnames if 'sim6_trial_' in f][:10]

evokeds = [read_evokeds(f)[0] for f in epochs_fnames]
mean_evoked = sum(evokeds[1:], evokeds[0])

# Visualize the average
mean_evoked.plot()
Пример #42
0
from mne.datasets import sample
from mne.io import read_evokeds
from mne.minimum_norm import apply_inverse, read_inverse_operator


data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori=None)

# Save result in stc files
stc.save('mne_%s_inverse' % method)

###############################################################################
# View activation time-series
plt.plot(1e3 * stc.times, stc.data[::100, :].T)
plt.xlabel('time (ms)')
plt.ylabel('%s value' % method)
plt.show()
Пример #43
0
condition = 'visual'  # or 'auditory' or 'somatosensory'

# Load experimental RAW files for the visual condition
raw_fnames = load_data(condition=condition, data_format='raw',
                       data_type='experimental')

# Load simulation evoked files for the visual condition
evoked_fnames = load_data(condition=condition, data_format='evoked',
                          data_type='simulation')

raw = Raw(raw_fnames[0])
events = find_events(raw, stim_channel="STI 014", shortest_event=1)

# Visualize raw file
raw.plot()

# Make an evoked file from the experimental data
picks = pick_types(raw.info, meg=True, eog=True, exclude='bads')

# Read epochs
event_id, tmin, tmax = 9, -0.2, 0.5
epochs = Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0),
                picks=picks, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()  # average epochs and get an Evoked dataset.
evoked.plot()

# Compare to the simulated data
evoked_sim = read_evokeds(evoked_fnames[0], condition=0)
evoked_sim.plot()
Пример #44
0
# Load simulation evoked files for the visual condition
evoked_fnames = load_data(condition=condition,
                          data_format='evoked',
                          data_type='simulation')

raw = Raw(raw_fnames[0])
events = find_events(raw, stim_channel="STI 014", shortest_event=1)

# Visualize raw file
raw.plot()

# Make an evoked file from the experimental data
picks = pick_types(raw.info, meg=True, eog=True, exclude='bads')

# Read epochs
event_id, tmin, tmax = 9, -0.2, 0.5
epochs = Epochs(raw,
                events,
                event_id,
                tmin,
                tmax,
                baseline=(None, 0),
                picks=picks,
                reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()  # average epochs and get an Evoked dataset.
evoked.plot()

# Compare to the simulated data
evoked_sim = read_evokeds(evoked_fnames[0], condition=0)
evoked_sim.plot()
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.viz import plot_sparse_source_estimates

data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'
subjects_dir = data_path + '/subjects'

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)
# Handling average file
condition = 'Left Auditory'
evoked = io.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0, tmax=0.3)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname, surf_ori=True)

cov = mne.cov.regularize(cov, evoked.info)

ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600])
evoked.plot(ylim=ylim, proj=True)

###############################################################################
# Run solver
alpha = 70  # regularization parameter between 0 and 100 (100 is high)
loose, depth = 0.2, 0.9  # loose orientation & depth weighting

# Compute dSPM solution to be used as weights in MxNE
Пример #46
0
#          Tal Linzen <*****@*****.**>
#
# License: BSD (3-clause)

print(__doc__)

import numpy as np
from mne.datasets import sample
from mne.io import read_evokeds

path = sample.data_path()
fname = path + '/MEG/sample/sample_audvis-ave.fif'

# load evoked and subtract baseline
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))

# plot magnetometer data as topomap at 1 time point : 100ms
evoked.plot_topomap(0.1, ch_type='mag', size=3, colorbar=False)

# set time instants in seconds (from 50 to 150ms in a step of 10ms)
times = np.arange(0.05, 0.15, 0.01)
# If times is set to None only 10 regularly spaced topographies will be shown

# plot magnetometer data as topomaps
evoked.plot_topomap(times, ch_type='mag')

# plot gradiometer data (plots the RMS for each pair of gradiometers)
evoked.plot_topomap(times, ch_type='grad')

# add channel labels and title
Пример #47
0
def test_mxne_inverse():
    """Test (TF-)MxNE inverse computation"""
    # Handling forward solution
    evoked = read_evokeds(fname_data, condition=1, baseline=(None, 0))

    # Read noise covariance matrix
    cov = read_cov(fname_cov)

    # Handling average file
    loose = None
    depth = 0.9

    evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
    evoked.crop(tmin=-0.1, tmax=0.4)

    evoked_l21 = copy.deepcopy(evoked)
    evoked_l21.crop(tmin=0.08, tmax=0.1)
    label = read_label(fname_label)
    weights_min = 0.5
    forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True)

    # Reduce source space to make test computation faster
    inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth, fixed=True)
    stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1.0 / 9.0, method="dSPM")
    stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0
    stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1.0

    # MxNE tests
    alpha = 60  # spatial regularization parameter

    stc_prox = mixed_norm(
        evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver="prox"
    )
    stc_cd = mixed_norm(
        evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver="cd"
    )
    assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_prox.data, stc_cd.data, 5)
    assert_true(stc_prox.vertno[1][0] in label.vertices)
    assert_true(stc_cd.vertno[1][0] in label.vertices)

    stc, _ = mixed_norm(
        evoked_l21,
        forward,
        cov,
        alpha,
        loose=None,
        depth=depth,
        maxit=500,
        tol=1e-4,
        active_set_size=10,
        weights=stc_dspm,
        weights_min=weights_min,
        return_residual=True,
    )

    assert_array_almost_equal(stc.times, evoked_l21.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)

    # Do with TF-MxNE for test memory savings
    alpha_space = 60.0  # spatial regularization parameter
    alpha_time = 1.0  # temporal regularization parameter

    stc, _ = tf_mixed_norm(
        evoked,
        forward,
        cov,
        alpha_space,
        alpha_time,
        loose=loose,
        depth=depth,
        maxit=100,
        tol=1e-4,
        tstep=4,
        wsize=16,
        window=0.1,
        weights=stc_dspm,
        weights_min=weights_min,
        return_residual=True,
    )

    assert_array_almost_equal(stc.times, evoked.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)
Пример #48
0
raw = Raw(data_path + '/MEG/sample/sample_audvis_raw.fif')
proj = read_proj(data_path + '/MEG/sample/sample_audvis_ecg_proj.fif')
raw.info['projs'] += proj
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

fwd = read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True)
fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])

cov = read_cov(cov_fname)

condition = 'Left Auditory'
evoked_template = read_evokeds(ave_fname, condition=condition, baseline=None)
evoked_template = pick_types_evoked(evoked_template,
                                    meg=True,
                                    eeg=True,
                                    exclude=raw.info['bads'])

label_names = ['Aud-lh', 'Aud-rh']
labels = [
    read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
    for ln in label_names
]

###############################################################################
# Generate source time courses and the correspond evoked data
snr = 6  # dB
tmin = -0.1
Пример #49
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = io.read_evokeds(evoked_fname,
                                 'Left Auditory',
                                 baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg')
        plot_evoked_topomap(evoked, times, ch_type='grad')
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True)

        p = plot_evoked_topomap(evoked,
                                times,
                                ch_type='grad',
                                show_names=lambda x: x.replace('MEG', ''))
        subplot = [
            x for x in p.get_children()
            if isinstance(x, matplotlib.axes.Subplot)
        ][0]
        assert_true(
            all('MEG' not in x.get_text() for x in subplot.get_children()
                if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [
                x.get_text() for x in p.get_children()
                if isinstance(x, matplotlib.text.Text)
            ]

        p = plot_evoked_topomap(evoked, times, ch_type='eeg')
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom')
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      0.1,
                      'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      times,
                      ch_type='eeg')
Пример #50
0
def test_mxne_inverse():
    """Test (TF-)MxNE inverse computation"""
    # Handling forward solution
    evoked = read_evokeds(fname_data, condition=1, baseline=(None, 0))

    # Read noise covariance matrix
    cov = read_cov(fname_cov)

    # Handling average file
    loose = None
    depth = 0.9

    evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
    evoked.crop(tmin=-0.1, tmax=0.4)

    evoked_l21 = copy.deepcopy(evoked)
    evoked_l21.crop(tmin=0.08, tmax=0.1)
    label = read_label(fname_label)
    weights_min = 0.5
    forward = read_forward_solution(fname_fwd, force_fixed=False,
                                    surf_ori=True)

    # Reduce source space to make test computation faster
    inverse_operator = make_inverse_operator(evoked.info, forward, cov,
                                             loose=loose, depth=depth,
                                             fixed=True)
    stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9.,
                             method='dSPM')
    stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0
    stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1.

    # MxNE tests
    alpha = 60  # spatial regularization parameter

    stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=None,
                          depth=0.9, maxit=1000, tol=1e-8, active_set_size=10,
                          solver='prox')
    stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=None,
                        depth=0.9, maxit=1000, tol=1e-8, active_set_size=10,
                        solver='cd')
    assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_prox.data, stc_cd.data, 5)
    assert_true(stc_prox.vertno[1][0] in label.vertices)
    assert_true(stc_cd.vertno[1][0] in label.vertices)

    stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=None,
                        depth=depth, maxit=500, tol=1e-4, active_set_size=10,
                        weights=stc_dspm, weights_min=weights_min,
                        return_residual=True)

    assert_array_almost_equal(stc.times, evoked_l21.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)

    # Do with TF-MxNE for test memory savings
    alpha_space = 60.  # spatial regularization parameter
    alpha_time = 1.  # temporal regularization parameter

    stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time,
                           loose=loose, depth=depth, maxit=100, tol=1e-4,
                           tstep=4, wsize=16, window=0.1, weights=stc_dspm,
                           weights_min=weights_min, return_residual=True)

    assert_array_almost_equal(stc.times, evoked.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)
Пример #51
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evokeds(fname, 0)

    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)
    ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0]

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evokeds(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    condition = 'Left Auditory'
    assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')
    assert_raises(ValueError,
                  read_evokeds,
                  fname,
                  condition,
                  kind='standard_error')
    ave3 = read_evokeds(fname, condition)
    assert_array_almost_equal(ave.data, ave3.data, 19)

    # test deprecation warning for read_evoked and write_evoked
    # XXX should be deleted for 0.9 release
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        ave = read_evoked(fname, setno=0)
        assert_true(w[0].category == DeprecationWarning)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        write_evoked(op.join(tempdir, 'evoked-ave.fif'), ave)
        assert_true(w[0].category == DeprecationWarning)

    # test read_evokeds and write_evokeds
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves1 = read_evokeds(fname)
    aves2 = read_evokeds(fname, [0, 1, 2, 3])
    aves3 = read_evokeds(fname, types)
    write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1)
    aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))
    for aves in [aves2, aves3, aves4]:
        for [av1, av2] in zip(aves1, aves):
            assert_array_almost_equal(av1.data, av2.data)
            assert_array_almost_equal(av1.times, av2.times)
            assert_equal(av1.nave, av2.nave)
            assert_equal(av1.kind, av2.kind)
            assert_equal(av1._aspect_kind, av2._aspect_kind)
            assert_equal(av1.last, av2.last)
            assert_equal(av1.first, av2.first)
            assert_equal(av1.comment, av2.comment)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        fname2 = op.join(tempdir, 'test-bad-name.fif')
        write_evokeds(fname2, ave)
        read_evokeds(fname2)
    assert_true(len(w) == 2)
Пример #52
0
 def compensate_mne(fname, comp):
     tmp_fname = '%s-%d-ave.fif' % (fname[:-4], comp)
     cmd = ['mne_compensate_data', '--in', fname,
            '--out', tmp_fname, '--grad', str(comp)]
     run_subprocess(cmd)
     return read_evokeds(tmp_fname)[0]
Пример #53
0
This example shows how to display topographies of SSP projection vectors.
The projections used are the ones correcting for ECG artifacts.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#         Denis A. Engemann <*****@*****.**>

# License: BSD (3-clause)

print(__doc__)

import matplotlib.pyplot as plt
from mne import read_proj, find_layout
from mne.io import read_evokeds
from mne.datasets import sample
from mne import viz

data_path = sample.data_path()

ecg_fname = data_path + "/MEG/sample/sample_audvis_ecg_proj.fif"
ave_fname = data_path + "/MEG/sample/sample_audvis-ave.fif"

evoked = read_evokeds(ave_fname, condition="Left Auditory")
projs = read_proj(ecg_fname)

layouts = [find_layout(evoked.info, k) for k in "meg", "eeg"]

plt.figure(figsize=(12, 6))
viz.plot_projs_topomap(projs, layout=layouts)
viz.tight_layout(w_pad=0.5)
Пример #54
0
# License: BSD (3-clause)

print(__doc__)

from mne import read_cov, whiten_evoked, pick_types
from mne.cov import regularize
from mne.io import read_evokeds
from mne.datasets import sample

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

# Reading
evoked = read_evokeds(fname, condition=0, baseline=(None, 0), proj=True)
noise_cov = read_cov(cov_fname)

###############################################################################
# Show result

# Pick channels to view
picks = pick_types(evoked.info, meg=True, eeg=True, exclude='bads')
evoked.plot(picks=picks)

noise_cov = regularize(noise_cov, evoked.info, grad=0.1, mag=0.1, eeg=0.1)

evoked_white = whiten_evoked(evoked, noise_cov, picks, diag=True)

# plot the whitened evoked data to see if baseline signals match the
# assumption of Gaussian whiten noise from which we expect values around
Пример #55
0
def _get_evoked():
    evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
    evoked.crop(0, 0.2)
    return evoked
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_sparse import tf_mixed_norm
from mne.viz import plot_sparse_source_estimates

data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)

# Handling average file
condition = 'Left visual'
evoked = io.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked = mne.pick_channels_evoked(evoked)
# We make the window slightly larger than what you'll eventually be interested
# in ([-0.05, 0.3]) to avoid edge effects.
evoked.crop(tmin=-0.1, tmax=0.4)

# Handling forward solution
forward = mne.read_forward_solution(fwd_fname, force_fixed=False,
                                    surf_ori=True)

cov = mne.cov.regularize(cov, evoked.info)

###############################################################################
# Run solver

# alpha_space regularization parameter is between 0 and 100 (100 is high)