Exemplo n.º 1
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.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', vmin=np.min)
        plot_evoked_topomap(evoked, times, ch_type='grad', vmin=np.min,
                            vmax=np.max)
        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.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')
Exemplo n.º 2
0
def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(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')
    with warnings.catch_warnings(True):  # delaunay triangulation warning
        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
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
    plt.close('all')
Exemplo n.º 3
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter("always", UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = 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

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
        plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp["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")
Exemplo n.º 4
0
def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(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="grad")
    plot_evoked_topomap(evoked, times, ch_type="planar1")
    plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
    plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
Exemplo n.º 5
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    pytest.raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Exemplo n.º 6
0
def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    import matplotlib.pyplot as plt
    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    assert_raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
Exemplo n.º 7
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.read_evoked(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')
        with warnings.catch_warnings(record=True):  # delaunay triangulation warning
            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.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')
Exemplo n.º 8
0
def test_plot_topomap():
    """Test topomap plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 8
    fast_test = {"res": res, "contours": 0, "sensors": False}
    evoked = read_evokeds(evoked_fname, 'Left Auditory', baseline=(None, 0))

    # Test animation
    _, anim = evoked.animate_topomap(ch_type='grad',
                                     times=[0, 0.1],
                                     butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close('all')

    ev_bad = evoked.copy().pick_types(meg=False, eeg=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    plt_topomap = partial(ev_bad.plot_topomap, **fast_test)
    plt_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, plt_topomap, ch_type='mag')
    assert_raises(TypeError, plt_topomap, head_pos='foo')
    assert_raises(KeyError, plt_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, plt_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, plt_topomap, times=[-100])  # bad time
    assert_raises(ValueError, plt_topomap, times=[[0]])  # bad time

    evoked.plot_topomap([0.1],
                        ch_type='eeg',
                        scale=1,
                        res=res,
                        contours=[-100, 0, 100])
    plt_topomap = partial(evoked.plot_topomap, **fast_test)
    plt_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    plt_topomap(axes=axes, colorbar=False)
    plt.close('all')
    plt_topomap(times=[-0.1, 0.2])
    plt.close('all')
    evoked_grad = evoked.copy().crop(0, 0).pick_types(meg='grad')
    mask = np.zeros((204, 1), bool)
    mask[[0, 3, 5, 6]] = True
    names = []

    def proc_names(x):
        names.append(x)
        return x[4:]

    evoked_grad.plot_topomap(ch_type='grad',
                             times=[0],
                             mask=mask,
                             show_names=proc_names,
                             **fast_test)
    assert_equal(sorted(names),
                 ['MEG 011x', 'MEG 012x', 'MEG 013x', 'MEG 014x'])
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    plt_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    plt_topomap(times, ch_type='grad', mask=mask)
    plt_topomap(times, ch_type='planar1')
    plt_topomap(times, ch_type='planar2')
    plt_topomap(times,
                ch_type='grad',
                mask=mask,
                show_names=True,
                mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, plt_topomap, times, ch_type='eeg', average=-1e3)
    assert_raises(ValueError, plt_topomap, times, ch_type='eeg', average='x')

    p = plt_topomap(times,
                    ch_type='grad',
                    image_interp='bilinear',
                    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)))

    # Plot array
    for ch_type in ('mag', 'grad'):
        evoked_ = evoked.copy().pick_types(eeg=False, meg=ch_type)
        plot_topomap(evoked_.data[:, 0], evoked_.info, **fast_test)
    # fail with multiple channel types
    assert_raises(ValueError, plot_topomap, evoked.data[0, :], evoked.info)

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

    p = plt_topomap(times, ch_type='eeg', average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = plt_topomap(times, ch_type='eeg', title='Custom')
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        plt_topomap(times, ch_type='mag', layout=None)
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  0.1,
                  'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname,
                          'Left Auditory',
                          baseline=(None, 0),
                          proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        fig1 = evoked.plot_topomap('interactive',
                                   'mag',
                                   proj='interactive',
                                   **fast_test)
        _fake_click(fig1, fig1.axes[1], (0.5, 0.5))  # click slider
    data_max = np.max(fig1.axes[0].images[0]._A)
    fig2 = plt.gcf()
    _fake_click(fig2, fig2.axes[0], (0.075, 0.775))  # toggle projector
    # make sure projector gets toggled
    assert_true(np.max(fig1.axes[0].images[0]._A) != data_max)

    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res, colorbar=True)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:])  # grads
    plt.close('all')
    # XXX This one fails due to grads being combined but this proj having
    # all zeros in the grad values -> matplotlib contour error
    # plot_projs_topomap(read_info(triux_fname)['projs'][:1])  # mags
    # plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos,
                                    'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt', **fast_test)

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines, **fast_test)
    plt.close('all')

    # Test interactive cmap
    fig = plot_evoked_topomap(evoked,
                              times=[0., 0.1],
                              ch_type='eeg',
                              cmap=('Reds', True),
                              title='title',
                              **fast_test)
    fig.canvas.key_press_event('up')
    fig.canvas.key_press_event(' ')
    fig.canvas.key_press_event('down')
    cbar = fig.get_axes()[0].CB  # Fake dragging with mouse.
    ax = cbar.cbar.ax
    _fake_click(fig, ax, (0.1, 0.1))
    _fake_click(fig, ax, (0.1, 0.2), kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    _fake_click(fig, ax, (0.1, 0.1), button=3)
    _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion')
    _fake_click(fig, ax, (0.1, 0.3), kind='release')

    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up

    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687),
                      radius=.46,
                      clip_on=True,
                      transform=plt.gca().transAxes)

    outlines['patch'] = patch
    plot_evoked_topomap(evoked,
                        times,
                        ch_type='eeg',
                        outlines=outlines,
                        **fast_test)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  times,
                  ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times='peaks', axes=axes, **fast_test)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Exemplo n.º 9
0
def run():
    import matplotlib.pyplot as plt

    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("--raw", dest="raw_in",
                      help="Input raw FIF file", metavar="FILE")
    parser.add_option("--proj", dest="proj_in",
                      help="Projector file", metavar="FILE",
                      default='')
    parser.add_option("--eve", dest="eve_in",
                      help="Events file", metavar="FILE",
                      default='')
    parser.add_option("-d", "--duration", dest="duration", type="float",
                      help="Time window for plotting (sec)",
                      default=10.0)
    parser.add_option("-t", "--start", dest="start", type="float",
                      help="Initial start time for plotting",
                      default=0.0)
    parser.add_option("-n", "--n_channels", dest="n_channels", type="int",
                      help="Number of channels to plot at a time",
                      default=20)
    parser.add_option("-o", "--order", dest="order",
                      help="Order for plotting ('type' or 'original')",
                      default='type')
    parser.add_option("-p", "--preload", dest="preload",
                      help="Preload raw data (for faster navigaton)",
                      default=False)
    parser.add_option("-s", "--show_options", dest="show_options",
                      help="Show projection options dialog",
                      default=False)

    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    raw = mne.io.Raw(raw_in, preload=preload)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info['projs'] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None
    raw.plot(duration=duration, start=start, n_channels=n_channels,
             order=order, show_options=show_options, events=events)
    plt.show(block=True)
Exemplo n.º 10
0
###############################################################################
# We can check where the channels reside with ``plot_sensors``. Notice that
# this method (along with many other MNE plotting functions) is callable using
# any MNE data container where the channel information is available.
raw.plot_sensors(kind='3d', ch_type='mag', ch_groups='position')

###############################################################################
# We used ``ch_groups='position'`` to color code the different regions. It uses
# the same algorithm for dividing the regions as ``order='position'`` of
# :func:`raw.plot <mne.io.Raw.plot>`. You can also pass a list of picks to
# color any channel group with different colors.
#
# Now let's add some ssp projectors to the raw data. Here we read them from a
# file and plot them.
projs = mne.read_proj(op.join(data_path, 'sample_audvis_eog-proj.fif'))
raw.add_proj(projs)
raw.plot_projs_topomap()

###############################################################################
# Note that the projections in ``raw.info['projs']`` can be visualized using
# :meth:`raw.plot_projs_topomap <mne.io.Raw.plot_projs_topomap>` or calling
# :func:`proj.plot_topomap <mne.Projection.plot_topomap>`
#
# more examples can be found in
# :ref:`sphx_glr_auto_examples_io_plot_read_proj.py`
projs[0].plot_topomap()

###############################################################################
# The first three projectors that we see are the SSP vectors from empty room
# measurements to compensate for the noise. The fourth one is the average EEG
Exemplo n.º 11
0
def gen_html_report(p, subjects, structurals, run_indices=None):
    """Generates HTML reports"""
    import matplotlib.pyplot as plt
    from ._mnefun import (_load_trans_to, plot_good_coils, _head_pos_annot,
                          _get_bem_src_trans, safe_inserter, _prebad,
                          _load_meg_bads, mlab_offscreen, _fix_raw_eog_cals,
                          _handle_dict, _get_t_window, plot_chpi_snr_raw)
    if run_indices is None:
        run_indices = [None] * len(subjects)
    style = {'axes.spines.right': 'off', 'axes.spines.top': 'off',
             'axes.grid': True}
    time_kwargs = dict()
    if 'time_unit' in mne.fixes._get_args(mne.viz.plot_evoked):
        time_kwargs['time_unit'] = 's'
    for si, subj in enumerate(subjects):
        struc = structurals[si]
        report = Report(verbose=False)
        print('  Processing subject %s/%s (%s)'
              % (si + 1, len(subjects), subj))

        # raw
        fnames = get_raw_fnames(p, subj, 'raw', erm=False, add_splits=False,
                                run_indices=run_indices[si])
        for fname in fnames:
            if not op.isfile(fname):
                raise RuntimeError('Cannot create reports until raw data '
                                   'exist, missing:\n%s' % fname)
        raw = [read_raw_fif(fname, allow_maxshield='yes')
               for fname in fnames]
        _fix_raw_eog_cals(raw)
        prebad_file = _prebad(p, subj)
        for r in raw:
            _load_meg_bads(r, prebad_file, disp=False)
        raw = mne.concatenate_raws(raw)

        # sss
        sss_fnames = get_raw_fnames(p, subj, 'sss', False, False,
                                    run_indices[si])
        has_sss = all(op.isfile(fname) for fname in sss_fnames)
        sss_info = mne.io.read_raw_fif(sss_fnames[0]) if has_sss else None
        bad_file = get_bad_fname(p, subj)
        if bad_file is not None:
            sss_info.load_bad_channels(bad_file)
        sss_info = sss_info.info

        # pca
        pca_fnames = get_raw_fnames(p, subj, 'pca', False, False,
                                    run_indices[si])
        has_pca = all(op.isfile(fname) for fname in pca_fnames)

        # whitening and source localization
        inv_dir = op.join(p.work_dir, subj, p.inverse_dir)

        has_fwd = op.isfile(op.join(p.work_dir, subj, p.forward_dir,
                                    subj + p.inv_tag + '-fwd.fif'))

        with plt.style.context(style):
            ljust = 25
            #
            # Head coils
            #
            section = 'Good HPI count'
            if p.report_params.get('good_hpi_count', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    _, _, fit_data = _head_pos_annot(p, fname, prefix='      ')
                    assert fit_data is not None
                    fig = plot_good_coils(fit_data, show=False)
                    fig.set_size_inches(10, 2)
                    fig.tight_layout()
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # cHPI SNR
            #
            section = 'cHPI SNR'
            if p.report_params.get('chpi_snr', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    raw = mne.io.read_raw_fif(fname, allow_maxshield='yes')
                    t_window = _get_t_window(p, raw)
                    fig = plot_chpi_snr_raw(raw, t_window, show=False,
                                            verbose=False)
                    fig.set_size_inches(10, 5)
                    fig.subplots_adjust(0.1, 0.1, 0.8, 0.95,
                                        wspace=0, hspace=0.5)
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                report.add_figs_to_section(figs, captions, section,
                                           image_format='png')  # svd too slow
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Head movement
            #
            section = 'Head movement'
            if p.report_params.get('head_movement', True) and p.movecomp:
                print(('    %s ... ' % section).ljust(ljust), end='')
                t0 = time.time()
                trans_to = _load_trans_to(p, subj, run_indices[si], raw)
                figs = list()
                captions = list()
                for fname in fnames:
                    pos, _, _ = _head_pos_annot(p, fname, prefix='      ')
                    fig = plot_head_positions(pos=pos, destination=trans_to,
                                              info=raw.info, show=False)
                    for ax in fig.axes[::2]:
                        """
                        # tighten to the sensor limits
                        assert ax.lines[0].get_color() == (0., 0., 0., 1.)
                        mn, mx = np.inf, -np.inf
                        for line in ax.lines:
                            ydata = line.get_ydata()
                            if np.isfinite(ydata).any():
                                mn = min(np.nanmin(ydata), mn)
                                mx = max(np.nanmax(line.get_ydata()), mx)
                        """
                        # always show at least 10cm span, and use tight limits
                        # if greater than that
                        coord = ax.lines[0].get_ydata()
                        for line in ax.lines:
                            if line.get_color() == 'r':
                                extra = line.get_ydata()[0]
                        mn, mx = coord.min(), coord.max()
                        md = (mn + mx) / 2.
                        mn = min([mn, md - 50., extra])
                        mx = max([mx, md + 50., extra])
                        assert (mn <= coord).all()
                        assert (mx >= coord).all()
                        ax.set_ylim(mn, mx)
                    fig.set_size_inches(10, 6)
                    fig.tight_layout()
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                del trans_to
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Raw segments
            #
            if op.isfile(pca_fnames[0]):
                raw_pca = mne.concatenate_raws(
                    [mne.io.read_raw_fif(fname) for fname in pca_fnames])
            section = 'Raw segments'
            if p.report_params.get('raw_segments', True) and has_pca:
                times = np.linspace(raw.times[0], raw.times[-1], 12)[1:-1]
                raw_plot = list()
                for t in times:
                    this_raw = raw_pca.copy().crop(t - 0.5, t + 0.5)
                    this_raw.load_data()
                    this_raw._data[:] -= np.mean(this_raw._data, axis=-1,
                                                 keepdims=True)
                    raw_plot.append(this_raw)
                raw_plot = mne.concatenate_raws(raw_plot)
                for key in ('BAD boundary', 'EDGE boundary'):
                    raw_plot.annotations.delete(
                        np.where(raw_plot.annotations.description == key)[0])
                new_events = np.linspace(
                    0, int(round(10 * raw.info['sfreq'])) - 1, 11).astype(int)
                new_events += raw_plot.first_samp
                new_events = np.array([new_events,
                                       np.zeros_like(new_events),
                                       np.ones_like(new_events)]).T
                fig = raw_plot.plot(group_by='selection', butterfly=True,
                                    events=new_events)
                fig.axes[0].lines[-1].set_zorder(10)  # events
                fig.axes[0].set(xticks=np.arange(0, len(times)) + 0.5)
                xticklabels = ['%0.1f' % t for t in times]
                fig.axes[0].set(xticklabels=xticklabels)
                fig.axes[0].set(xlabel='Center of 1-second segments')
                fig.axes[0].grid(False)
                for _ in range(len(fig.axes) - 1):
                    fig.delaxes(fig.axes[-1])
                fig.set(figheight=(fig.axes[0].get_yticks() != 0).sum(),
                        figwidth=12)
                fig.subplots_adjust(0.0, 0.0, 1, 1, 0, 0)
                report.add_figs_to_section(fig, 'Processed', section,
                                           image_format='png')  # svg too slow

            #
            # PSD
            #
            section = 'PSD'
            if p.report_params.get('psd', True) and has_pca:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                if p.lp_trans == 'auto':
                    lp_trans = 0.25 * p.lp_cut
                else:
                    lp_trans = p.lp_trans
                n_fft = 8192
                fmax = raw.info['lowpass']
                figs = [raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False)]
                captions = ['%s: Raw' % section]
                fmax = p.lp_cut + 2 * lp_trans
                figs.append(raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False))
                captions.append('%s: Raw (zoomed)' % section)
                if op.isfile(pca_fnames[0]):
                    figs.append(raw_pca.plot_psd(fmax=fmax, n_fft=n_fft,
                                                 show=False))
                    captions.append('%s: Processed' % section)
                # shared y limits
                n = len(figs[0].axes) // 2
                for ai, axes in enumerate(list(zip(
                        *[f.axes for f in figs]))[:n]):
                    ylims = np.array([ax.get_ylim() for ax in axes])
                    ylims = [np.min(ylims[:, 0]), np.max(ylims[:, 1])]
                    for ax in axes:
                        ax.set_ylim(ylims)
                        ax.set(title='')
                for fig in figs:
                    fig.set_size_inches(8, 8)
                    with warnings.catch_warnings(record=True):
                        fig.tight_layout()
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # SSP
            #
            section = 'SSP topomaps'

            proj_nums = _handle_dict(p.proj_nums, subj)
            if p.report_params.get('ssp_topomaps', True) and has_pca and \
                    np.sum(proj_nums) > 0:
                assert sss_info is not None
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = []
                comments = []
                proj_files = get_proj_fnames(p, subj)
                if p.proj_extra is not None:
                    comments.append('Custom')
                    projs = read_proj(op.join(p.work_dir, subj, p.pca_dir,
                                              p.proj_extra))
                    figs.append(plot_projs_topomap(projs, info=sss_info,
                                                   show=False))
                if any(proj_nums[0]):  # ECG
                    if 'preproc_ecg-proj.fif' in proj_files:
                        comments.append('ECG')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_ecg-proj.fif'), sss_info,
                            proj_nums[0], p.proj_meg, 'ECG'))
                if any(proj_nums[1]):  # EOG
                    if 'preproc_blink-proj.fif' in proj_files:
                        comments.append('Blink')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_blink-proj.fif'), sss_info,
                            proj_nums[1], p.proj_meg, 'EOG'))
                if any(proj_nums[2]):  # ERM
                    if 'preproc_cont-proj.fif' in proj_files:
                        comments.append('Continuous')
                        figs.append(_proj_fig(op.join(
                            p.work_dir, subj, p.pca_dir,
                            'preproc_cont-proj.fif'), sss_info,
                            proj_nums[2], p.proj_meg, 'ERM'))
                captions = [section] + [None] * (len(comments) - 1)
                report.add_figs_to_section(
                     figs, captions, section, image_format='svg',
                     comments=comments)
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Source alignment
            #
            section = 'Source alignment'
            source_alignment = p.report_params.get('source_alignment', True)
            if source_alignment is True or isinstance(source_alignment, dict) \
                    and has_sss and has_fwd:
                assert sss_info is not None
                kwargs = source_alignment
                if isinstance(source_alignment, dict):
                    kwargs = dict(**source_alignment)
                else:
                    assert source_alignment is True
                    kwargs = dict()
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                captions = [section]
                try:
                    from mayavi import mlab
                except ImportError:
                    warnings.warn('Cannot plot alignment in Report, mayavi '
                                  'could not be imported')
                else:
                    subjects_dir = mne.utils.get_subjects_dir(
                        p.subjects_dir, raise_error=True)
                    bem, src, trans, _ = _get_bem_src_trans(
                        p, sss_info, subj, struc)
                    if len(mne.pick_types(sss_info)):
                        coord_frame = 'meg'
                    else:
                        coord_frame = 'head'
                    with mlab_offscreen():
                        fig = mlab.figure(bgcolor=(0., 0., 0.),
                                          size=(1000, 1000))
                        for key, val in (
                                ('info', sss_info),
                                ('subjects_dir', subjects_dir), ('bem', bem),
                                ('dig', True), ('coord_frame', coord_frame),
                                ('show_axes', True), ('fig', fig),
                                ('trans', trans), ('src', src)):
                            kwargs[key] = kwargs.get(key, val)
                        try_surfs = ['head-dense', 'head', 'inner_skull']
                        for surf in try_surfs:
                            try:
                                mne.viz.plot_alignment(surfaces=surf, **kwargs)
                            except Exception:
                                pass
                            else:
                                break
                        else:
                            raise RuntimeError('Could not plot any surface '
                                               'for alignment:\n%s'
                                               % (try_surfs,))
                        fig.scene.parallel_projection = True
                        view = list()
                        for ai, angle in enumerate([180, 90, 0]):
                            mlab.view(angle, 90, focalpoint=(0., 0., 0.),
                                      distance=0.6, figure=fig)
                            view.append(mlab.screenshot(figure=fig))
                        mlab.close(fig)
                    view = trim_bg(np.concatenate(view, axis=1), 0)
                    report.add_figs_to_section(view, captions, section)
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)
            #
            # SNR
            #
            section = 'SNR'
            if p.report_params.get('snr', None) is not None:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                snrs = p.report_params['snr']
                if not isinstance(snrs, (list, tuple)):
                    snrs = [snrs]
                for snr in snrs:
                    assert isinstance(snr, dict)
                    analysis = snr['analysis']
                    name = snr['name']
                    times = snr.get('times', [0.1])
                    inv_dir = op.join(p.work_dir, subj, p.inverse_dir)
                    fname_inv = op.join(inv_dir,
                                        safe_inserter(snr['inv'], subj))
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_inv):
                        print('    Missing inv: %s'
                              % op.basename(fname_inv), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        inv = mne.minimum_norm.read_inverse_operator(fname_inv)
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        title = ('%s<br>%s["%s"] (N=%d)'
                                 % (section, analysis, name, this_evoked.nave))
                        figs = plot_snr_estimate(this_evoked, inv,
                                                 verbose=False)
                        figs.axes[0].set_ylim(auto=True)
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name,
                                       this_evoked.nave))
                        report.add_figs_to_section(
                            figs, captions, section=section,
                            image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            #
            # BEM
            #
            section = 'BEM'
            if p.report_params.get('bem', True) and has_fwd:
                caption = '%s<br>%s' % (section, struc)
                bem, src, trans, _ = _get_bem_src_trans(
                    p, raw.info, subj, struc)
                if not bem['is_sphere']:
                    subjects_dir = mne.utils.get_subjects_dir(
                        p.subjects_dir, raise_error=True)
                    mri_fname = op.join(subjects_dir, struc, 'mri', 'T1.mgz')
                    if not op.isfile(mri_fname):
                        warnings.warn(
                            'Could not find MRI:\n%s\nIf using surrogate '
                            'subjects, use '
                            'params.report_params["bem"] = False to avoid '
                            'this warning', stacklevel=2)
                    else:
                        t0 = time.time()
                        print(('    %s ... ' % section).ljust(ljust), end='')
                        report.add_bem_to_section(struc, caption, section,
                                                  decim=10, n_jobs=1,
                                                  subjects_dir=subjects_dir)
                        print('%5.1f sec' % ((time.time() - t0),))
                else:
                    print('    %s skipped (sphere)' % section)
            else:
                print('    %s skipped' % section)

            #
            # Whitening
            #
            section = 'Whitening'
            if p.report_params.get('whitening', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')

                whitenings = p.report_params['whitening']
                if not isinstance(whitenings, (list, tuple)):
                    whitenings = [whitenings]
                for whitening in whitenings:
                    assert isinstance(whitening, dict)
                    analysis = whitening['analysis']
                    name = whitening['name']
                    cov_name = op.join(p.work_dir, subj, p.cov_dir,
                                       safe_inserter(whitening['cov'], subj))
                    # Load the inverse
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(cov_name):
                        print('    Missing cov: %s'
                              % op.basename(cov_name), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        noise_cov = mne.read_cov(cov_name)
                        evo = mne.read_evokeds(fname_evoked, name)
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name, evo.nave))
                        fig = evo.plot_white(noise_cov, **time_kwargs)
                        report.add_figs_to_section(
                            fig, captions, section=section, image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # Sensor space plots
            #
            section = 'Responses'
            if p.report_params.get('sensor', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                sensors = p.report_params['sensor']
                if not isinstance(sensors, (list, tuple)):
                    sensors = [sensors]
                for sensor in sensors:
                    assert isinstance(sensor, dict)
                    analysis = sensor['analysis']
                    name = sensor['name']
                    times = sensor.get('times', [0.1, 0.2])
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        figs = this_evoked.plot_joint(
                            times, show=False, ts_args=dict(**time_kwargs),
                            topomap_args=dict(outlines='head', **time_kwargs))
                        if not isinstance(figs, (list, tuple)):
                            figs = [figs]
                        captions = ('%s<br>%s["%s"] (N=%d)'
                                    % (section, analysis, name,
                                       this_evoked.nave))
                        captions = [captions] + [None] * (len(figs) - 1)
                        report.add_figs_to_section(
                            figs, captions, section=section,
                            image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))

            #
            # Source estimation
            #
            section = 'Source estimation'
            if p.report_params.get('source', False):
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                sources = p.report_params['source']
                if not isinstance(sources, (list, tuple)):
                    sources = [sources]
                for source in sources:
                    assert isinstance(source, dict)
                    analysis = source['analysis']
                    name = source['name']
                    times = source.get('times', [0.1, 0.2])
                    # Load the inverse
                    inv_dir = op.join(p.work_dir, subj, p.inverse_dir)
                    fname_inv = op.join(inv_dir,
                                        safe_inserter(source['inv'], subj))
                    fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif'
                                           % (analysis, p.lp_cut, p.inv_tag,
                                              p.eq_tag, subj))
                    if not op.isfile(fname_inv):
                        print('    Missing inv: %s'
                              % op.basename(fname_inv), end='')
                    elif not op.isfile(fname_evoked):
                        print('    Missing evoked: %s'
                              % op.basename(fname_evoked), end='')
                    else:
                        inv = mne.minimum_norm.read_inverse_operator(fname_inv)
                        this_evoked = mne.read_evokeds(fname_evoked, name)
                        title = ('%s<br>%s["%s"] (N=%d)'
                                 % (section, analysis, name, this_evoked.nave))
                        stc = mne.minimum_norm.apply_inverse(
                            this_evoked, inv,
                            lambda2=source.get('lambda2', 1. / 9.),
                            method=source.get('method', 'dSPM'))
                        stc = abs(stc)
                        # get clim using the reject_tmin <->reject_tmax
                        stc_crop = stc.copy().crop(
                            p.reject_tmin, p.reject_tmax)
                        clim = source.get('clim', dict(kind='percent',
                                                       lims=[82, 90, 98]))
                        out = mne.viz._3d._limits_to_control_points(
                             clim, stc_crop.data, 'viridis',
                             transparent=True)  # dummy cmap
                        if isinstance(out[0], (list, tuple, np.ndarray)):
                            clim = out[0]  # old MNE
                        else:
                            clim = out[1]  # new MNE (0.17+)
                        clim = dict(kind='value', lims=clim)
                        if not isinstance(stc, mne.SourceEstimate):
                            print('Only surface source estimates currently '
                                  'supported')
                        else:
                            subjects_dir = mne.utils.get_subjects_dir(
                                p.subjects_dir, raise_error=True)
                            with mlab_offscreen():
                                brain = stc.plot(
                                    hemi=source.get('hemi', 'split'),
                                    views=source.get('views', ['lat', 'med']),
                                    size=source.get('size', (800, 600)),
                                    colormap=source.get('colormap', 'viridis'),
                                    transparent=source.get('transparent',
                                                           True),
                                    foreground='k', background='w',
                                    clim=clim, subjects_dir=subjects_dir,
                                    )
                                imgs = list()
                                for t in times:
                                    brain.set_time(t)
                                    imgs.append(
                                        trim_bg(brain.screenshot(), 255))
                                brain.close()
                            captions = ['%2.3f sec' % t for t in times]
                            report.add_slider_to_section(
                                imgs, captions=captions, section=section,
                                title=title, image_format='png')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

        report_fname = get_report_fnames(p, subj)[0]
        report.save(report_fname, open_browser=False, overwrite=True)
Exemplo n.º 12
0
def mne_raw(path=None, proj=False, **kwargs):
    """
    Returns a mne.fiff.Raw object with added projections if appropriate.

    Parameters
    ----------
    path : None | str(path)
        path to the raw fiff file. If ``None``, a file can be chosen form a
        file dialog.
    proj : bool | str(path)
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to mne.fiff.Raw
        initialization.

    """
    if path is None:
        path = ui.ask_file("Pick a Raw Fiff File", "Pick a Raw Fiff File",
                           [('Functional image file (*.fif)', '*.fif'),
                            ('KIT Raw File (*.sqd,*.con', '*.sqd;*.con')])
        if not path:
            return

    if not os.path.isfile(path):
        raise IOError("%r is not a file" % path)

    if isinstance(path, basestring):
        _, ext = os.path.splitext(path)
        if ext.startswith('.fif'):
            raw = mne.fiff.Raw(path, **kwargs)
        elif ext in ('.sqd', '.con'):
            from mne.fiff.kit import read_raw_kit
            raw = read_raw_kit(path, **kwargs)
        else:
            raise ValueError("Unknown extension: %r" % ext)
    else:
        raw = mne.fiff.Raw(path, **kwargs)

    if proj:
        if proj == True:
            proj = '{raw}*proj.fif'

        if '{raw}' in proj:
            raw_file = raw.info['filename']
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip('raw')
            proj = proj.format(raw=raw_root)

        if '*' in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
Exemplo n.º 13
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-i",
                      "--in",
                      dest="raw_in",
                      help="Input raw FIF file",
                      metavar="FILE")
    parser.add_option("--tmin",
                      dest="tmin",
                      type="float",
                      help="Time before event in seconds",
                      default=-0.2)
    parser.add_option("--tmax",
                      dest="tmax",
                      type="float",
                      help="Time after event in seconds",
                      default=0.2)
    parser.add_option("-g",
                      "--n-grad",
                      dest="n_grad",
                      type="int",
                      help="Number of SSP vectors for gradiometers",
                      default=2)
    parser.add_option("-m",
                      "--n-mag",
                      dest="n_mag",
                      type="int",
                      help="Number of SSP vectors for magnetometers",
                      default=2)
    parser.add_option("-e",
                      "--n-eeg",
                      dest="n_eeg",
                      type="int",
                      help="Number of SSP vectors for EEG",
                      default=2)
    parser.add_option("--l-freq",
                      dest="l_freq",
                      type="float",
                      help="Filter low cut-off frequency in Hz",
                      default=1)
    parser.add_option("--h-freq",
                      dest="h_freq",
                      type="float",
                      help="Filter high cut-off frequency in Hz",
                      default=35)
    parser.add_option("--eog-l-freq",
                      dest="eog_l_freq",
                      type="float",
                      help="Filter low cut-off frequency in Hz used for "
                      "EOG event detection",
                      default=1)
    parser.add_option("--eog-h-freq",
                      dest="eog_h_freq",
                      type="float",
                      help="Filter high cut-off frequency in Hz used for "
                      "EOG event detection",
                      default=10)
    parser.add_option("-p",
                      "--preload",
                      dest="preload",
                      help="Temporary file used during computation (to "
                      "save memory)",
                      default=True)
    parser.add_option("-a",
                      "--average",
                      dest="average",
                      action="store_true",
                      help="Compute SSP after averaging",
                      default=False)  # XXX: change to default=True in 0.17
    parser.add_option("--proj",
                      dest="proj",
                      help="Use SSP projections from a fif file.",
                      default=None)
    parser.add_option("--filtersize",
                      dest="filter_length",
                      type="int",
                      help="Number of taps to use for filtering",
                      default=2048)
    parser.add_option("-j",
                      "--n-jobs",
                      dest="n_jobs",
                      type="int",
                      help="Number of jobs to run in parallel",
                      default=1)
    parser.add_option("--rej-grad",
                      dest="rej_grad",
                      type="float",
                      help="Gradiometers rejection parameter in fT/cm (peak "
                      "to peak amplitude)",
                      default=2000)
    parser.add_option("--rej-mag",
                      dest="rej_mag",
                      type="float",
                      help="Magnetometers rejection parameter in fT (peak to "
                      "peak amplitude)",
                      default=3000)
    parser.add_option("--rej-eeg",
                      dest="rej_eeg",
                      type="float",
                      help="EEG rejection parameter in uV (peak to peak "
                      "amplitude)",
                      default=50)
    parser.add_option("--rej-eog",
                      dest="rej_eog",
                      type="float",
                      help="EOG rejection parameter in uV (peak to peak "
                      "amplitude)",
                      default=1e9)
    parser.add_option("--avg-ref",
                      dest="avg_ref",
                      action="store_true",
                      help="Add EEG average reference proj",
                      default=False)
    parser.add_option("--no-proj",
                      dest="no_proj",
                      action="store_true",
                      help="Exclude the SSP projectors currently in the "
                      "fiff file",
                      default=False)
    parser.add_option("--bad",
                      dest="bad_fname",
                      help="Text file containing bad channels list "
                      "(one per line)",
                      default=None)
    parser.add_option("--event-id",
                      dest="event_id",
                      type="int",
                      help="ID to use for events",
                      default=998)
    parser.add_option("--event-raw",
                      dest="raw_event_fname",
                      help="raw file to use for event detection",
                      default=None)
    parser.add_option("--tstart",
                      dest="tstart",
                      type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("-c",
                      "--channel",
                      dest="ch_name",
                      type="string",
                      help="Custom EOG channel(s), comma separated",
                      default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    eog_l_freq = options.eog_l_freq
    eog_h_freq = options.eog_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    ch_name = options.ch_name

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    eog_event_fname = prefix + '_eog-eve.fif'

    if average:
        eog_proj_fname = prefix + '_eog_avg-proj.fif'
    else:
        eog_proj_fname = prefix + '_eog-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    projs, events = mne.preprocessing.compute_proj_eog(
        raw=raw,
        raw_event=raw_event,
        tmin=tmin,
        tmax=tmax,
        n_grad=n_grad,
        n_mag=n_mag,
        n_eeg=n_eeg,
        l_freq=l_freq,
        h_freq=h_freq,
        average=average,
        filter_length=filter_length,
        n_jobs=n_jobs,
        reject=reject,
        flat=flat,
        bads=bads,
        avg_ref=avg_ref,
        no_proj=no_proj,
        event_id=event_id,
        eog_l_freq=eog_l_freq,
        eog_h_freq=eog_h_freq,
        tstart=tstart,
        ch_name=ch_name,
        copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the eog projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, str) and os.path.exists(preload):
        os.remove(preload)

    print("Writing EOG projections in %s" % eog_proj_fname)
    mne.write_proj(eog_proj_fname, projs)

    print("Writing EOG events in %s" % eog_event_fname)
    mne.write_events(eog_event_fname, events)
Exemplo n.º 14
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)
Exemplo n.º 15
0
                    event_id=event_dict,
                    event_color=dict(button='red', face='blue'),
                    group_by='selection',
                    butterfly=True)

# %%
# Plotting projectors from an ``Epochs`` object
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# In the plot above we can see heartbeat artifacts in the magnetometer
# channels, so before we continue let's load ECG projectors from disk and apply
# them to the data:

ecg_proj_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                             'sample_audvis_ecg-proj.fif')
ecg_projs = mne.read_proj(ecg_proj_file)
epochs.add_proj(ecg_projs)
epochs.apply_proj()

# %%
# Just as we saw in the :ref:`tut-section-raw-plot-proj` section, we can plot
# the projectors present in an `~mne.Epochs` object using the same
# `~mne.Epochs.plot_projs_topomap` method. Since the original three
# empty-room magnetometer projectors were inherited from the
# `~mne.io.Raw` file, and we added two ECG projectors for each sensor
# type, we should see nine projector topomaps:

epochs.plot_projs_topomap(vlim='joint')

# %%
# Note that these field maps illustrate aspects of the signal that *have
from mne import fiff, read_proj, read_selection
from mne.datasets import sample

###############################################################################
# Set parameters
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_eog_proj.fif'

# Setup for reading the raw data
raw = fiff.Raw(raw_fname, preload=True)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Add SSP projection vectors to reduce EOG and ECG artifacts
projs = read_proj(proj_fname)
raw.add_proj(projs, remove_existing=True)

tmin, tmax = 0, 60  # use the first 60s of data
fmin, fmax = 2, 300  # look at frequencies between 2 and 300Hz
n_fft = 2048  # the FFT size (NFFT). Ideally a power of 2

plt.ion()

# Let's first check out all channel types
raw.plot_psds(area_mode='range', tmax=10.0)

# Now let's focus on a smaller subset:
# Pick MEG magnetometers in the Left-temporal region
selection = read_selection('Left-temporal')
picks = fiff.pick_types(raw.info,
Exemplo n.º 17
0
def mne_raw(path=None, proj=False, **kwargs):
    """Load a :class:`mne.io.Raw` object

    Parameters
    ----------
    path : None | str
        path to a raw fiff or sqd file. If no path is supplied, a file can be
        chosen from a file dialog.
    proj : bool | str
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to :class:`mne.io.Raw`
        initialization.
    """
    if path is None:
        path = ui.ask_file("Pick a raw data file", "Pick a raw data file",
                           [('Functional image file (*.fif)', '*.fif'),
                            ('KIT Raw File (*.sqd,*.con', '*.sqd;*.con')])
        if not path:
            return

    if isinstance(path, str):
        _, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext.startswith('.fif'):
            raw = mne.io.read_raw_fif(path, **kwargs)
        elif ext in ('.sqd', '.con'):
            raw = mne.io.read_raw_kit(path, **kwargs)
        else:
            raise ValueError("Unknown extension: %r" % ext)
    elif isinstance(path, Iterable):
        # MNE Raw supports list of file-names
        raw = mne.io.read_raw_fif(path, **kwargs)
    else:
        raise TypeError("path=%r" % (path, ))

    if proj:
        if proj is True:
            proj = '{raw}*proj.fif'

        if '{raw}' in proj:
            raw_file = raw.filenames[0]
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip('raw')
            proj = proj.format(raw=raw_root)

        if '*' in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
Exemplo n.º 18
0
print __doc__

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import ar_raw
from mne.datasets import sample
data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_ecg_proj.fif'

raw = mne.fiff.Raw(raw_fname)
proj = mne.read_proj(proj_fname)
raw.info['projs'] += proj
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

# Set up pick list: Gradiometers - bad channels
picks = mne.fiff.pick_types(raw.info, meg='grad', exclude='bads')

order = 5  # define model order
picks = picks[:5]

# Estimate AR models on raw data
coefs = ar_raw(raw, order=order, picks=picks, tmin=60, tmax=180)
mean_coefs = np.mean(coefs, axis=0)  # mean model across channels

filt = np.r_[1, -mean_coefs]  # filter coefficient
d, times = raw[0, 1e4:2e4]  # look at one channel from now on
Exemplo n.º 19
0
print __doc__

import pylab as pl
import mne
import sys
subjID = sys.argv[1]
#listPrefix = sys.argv[2]
study = sys.argv[2]

#from mne.datasets import sample
data_path = '/cluster/kuperberg/SemPrMM/MEG/data/' + subjID
ecg_fname = data_path + '/ssp/' + subjID + '_' + study + 'Run1_eog_proj.fif'
#print ecg_fname
ave_fname = data_path + '/ave_projon/' + subjID + '_' + study + 'Run1-ave.fif'

evoked = mne.fiff.read_evoked(ave_fname, setno='Related')
projs = mne.read_proj(ecg_fname)
#lay = mne.layouts.read_layout('/autofs/homes/001/candida/.mne/lout/std2_70elec.lout')
#print lay

layouts = [
    mne.layouts.read_layout('Vectorview-all'),
    mne.layouts.read_layout(
        '/autofs/homes/001/candida/.mne/lout/std2_70elec.lout')
]

pl.figure(figsize=(10, 6))
mne.viz.plot_projs_topomap(projs, layout=layouts)
mne.viz.tight_layout()
Exemplo n.º 20
0
def run():
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-i",
                      "--in",
                      dest="raw_in",
                      help="Input raw FIF file",
                      metavar="FILE")
    parser.add_option("--tmin",
                      dest="tmin",
                      type="float",
                      help="Time before event in seconds",
                      default=-0.2)
    parser.add_option("--tmax",
                      dest="tmax",
                      type="float",
                      help="Time after event in seconds",
                      default=0.4)
    parser.add_option("-g",
                      "--n-grad",
                      dest="n_grad",
                      type="int",
                      help="Number of SSP vectors for gradiometers",
                      default=2)
    parser.add_option("-m",
                      "--n-mag",
                      dest="n_mag",
                      type="int",
                      help="Number of SSP vectors for magnetometers",
                      default=2)
    parser.add_option("-e",
                      "--n-eeg",
                      dest="n_eeg",
                      type="int",
                      help="Number of SSP vectors for EEG",
                      default=2)
    parser.add_option("--l-freq",
                      dest="l_freq",
                      type="float",
                      help="Filter low cut-off frequency in Hz",
                      default=1)
    parser.add_option("--h-freq",
                      dest="h_freq",
                      type="float",
                      help="Filter high cut-off frequency in Hz",
                      default=100)
    parser.add_option("--ecg-l-freq",
                      dest="ecg_l_freq",
                      type="float",
                      help="Filter low cut-off frequency in Hz used "
                      "for ECG event detection",
                      default=5)
    parser.add_option("--ecg-h-freq",
                      dest="ecg_h_freq",
                      type="float",
                      help="Filter high cut-off frequency in Hz used "
                      "for ECG event detection",
                      default=35)
    parser.add_option("-p",
                      "--preload",
                      dest="preload",
                      help="Temporary file used during computation "
                      "(to save memory)",
                      default=True)
    parser.add_option("-a",
                      "--average",
                      dest="average",
                      action="store_true",
                      help="Compute SSP after averaging",
                      default=False)
    parser.add_option("--proj",
                      dest="proj",
                      help="Use SSP projections from a fif file.",
                      default=None)
    parser.add_option("--filtersize",
                      dest="filter_length",
                      type="int",
                      help="Number of taps to use for filtering",
                      default=2048)
    parser.add_option("-j",
                      "--n-jobs",
                      dest="n_jobs",
                      type="int",
                      help="Number of jobs to run in parallel",
                      default=1)
    parser.add_option("-c",
                      "--channel",
                      dest="ch_name",
                      help="Channel to use for ECG detection "
                      "(Required if no ECG found)",
                      default=None)
    parser.add_option("--rej-grad",
                      dest="rej_grad",
                      type="float",
                      help="Gradiometers rejection parameter "
                      "in fT/cm (peak to peak amplitude)",
                      default=2000)
    parser.add_option("--rej-mag",
                      dest="rej_mag",
                      type="float",
                      help="Magnetometers rejection parameter "
                      "in fT (peak to peak amplitude)",
                      default=3000)
    parser.add_option("--rej-eeg",
                      dest="rej_eeg",
                      type="float",
                      help="EEG rejection parameter in uV "
                      "(peak to peak amplitude)",
                      default=50)
    parser.add_option("--rej-eog",
                      dest="rej_eog",
                      type="float",
                      help="EOG rejection parameter in uV "
                      "(peak to peak amplitude)",
                      default=250)
    parser.add_option("--avg-ref",
                      dest="avg_ref",
                      action="store_true",
                      help="Add EEG average reference proj",
                      default=False)
    parser.add_option("--no-proj",
                      dest="no_proj",
                      action="store_true",
                      help="Exclude the SSP projectors currently "
                      "in the fiff file",
                      default=False)
    parser.add_option("--bad",
                      dest="bad_fname",
                      help="Text file containing bad channels list "
                      "(one per line)",
                      default=None)
    parser.add_option("--event-id",
                      dest="event_id",
                      type="int",
                      help="ID to use for events",
                      default=999)
    parser.add_option("--event-raw",
                      dest="raw_event_fname",
                      help="raw file to use for event detection",
                      default=None)
    parser.add_option("--tstart",
                      dest="tstart",
                      type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("--qrsthr",
                      dest="qrs_threshold",
                      type="string",
                      help="QRS detection threshold. Between 0 and 1. Can "
                      "also be 'auto' for automatic selection",
                      default='auto')

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    ecg_l_freq = options.ecg_l_freq
    ecg_h_freq = options.ecg_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    ch_name = options.ch_name
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    qrs_threshold = options.qrs_threshold
    if qrs_threshold != 'auto':
        try:
            qrs_threshold = float(qrs_threshold)
        except ValueError:
            raise ValueError('qrsthr must be "auto" or a float')

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    ecg_event_fname = prefix + '_ecg-eve.fif'

    if average:
        ecg_proj_fname = prefix + '_ecg_avg-proj.fif'
    else:
        ecg_proj_fname = prefix + '_ecg-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    cpe = mne.preprocessing.compute_proj_ecg
    projs, events = cpe(raw,
                        raw_event,
                        tmin,
                        tmax,
                        n_grad,
                        n_mag,
                        n_eeg,
                        l_freq,
                        h_freq,
                        average,
                        filter_length,
                        n_jobs,
                        ch_name,
                        reject,
                        flat,
                        bads,
                        avg_ref,
                        no_proj,
                        event_id,
                        ecg_l_freq,
                        ecg_h_freq,
                        tstart,
                        qrs_threshold,
                        copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the ecg projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing ECG projections in %s" % ecg_proj_fname)
    mne.write_proj(ecg_proj_fname, projs)

    print("Writing ECG events in %s" % ecg_event_fname)
    mne.write_events(ecg_event_fname, events)
Exemplo n.º 21
0
=================================
Plot SSP projections topographies
=================================

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
import mne
from mne.datasets import sample
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 = mne.fiff.read_evoked(ave_fname, setno='Left Auditory')
projs = mne.read_proj(ecg_fname)

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

plt.figure(figsize=(12, 6))
mne.viz.plot_projs_topomap(projs, layout=layouts)
mne.viz.tight_layout(w_pad=0.5)
Exemplo n.º 22
0
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.time_frequency import fit_iir_model_raw
from mne.viz import plot_sparse_source_estimates
from mne.simulation import simulate_sparse_stc, simulate_evoked

print(__doc__)

# %%
# Load real data as templates:
data_path = sample.data_path()
meg_path = data_path / 'MEG' / 'sample'
raw = mne.io.read_raw_fif(meg_path / 'sample_audvis_raw.fif')
proj = mne.read_proj(meg_path / 'sample_audvis_ecg-proj.fif')
raw.add_proj(proj)
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

fwd_fname = meg_path / 'sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = meg_path / 'sample_audvis-no-filter-ave.fif'
cov_fname = meg_path / 'sample_audvis-cov.fif'

fwd = mne.read_forward_solution(fwd_fname)
fwd = mne.pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
cov = mne.read_cov(cov_fname)
info = mne.io.read_info(ave_fname)

label_names = ['Aud-lh', 'Aud-rh']
labels = [
    mne.read_label(meg_path / 'labels' / f'{ln}.label') for ln in label_names
Exemplo n.º 23
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type='mag', outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type='eeg', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
        evoked.plot_topomap(times, ch_type='planar1', res=res)
        evoked.plot_topomap(times, ch_type='planar2', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                            show_names=True, mask_params={'marker': 'x'})
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average=-1000)
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average='hahahahah')

        p = evoked.plot_topomap(times, ch_type='grad', res=res,
                                show_names=lambda x: x.replace('MEG', ''),
                                image_interp='bilinear')
        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 = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0), proj=False)
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
        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 = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs, res=res)
        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)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info['dig'][85]
        plot_evoked_topomap(evoked, times, ch_type='eeg')

        # Remove digitization points. Now topomap should fail
        evoked.info['dig'] = None
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
Exemplo n.º 24
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.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', vmin=np.min)
        plot_evoked_topomap(evoked,
                            times,
                            ch_type='grad',
                            vmin=np.min,
                            vmax=np.max)
        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.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')
Exemplo n.º 25
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle

    # evoked
    warnings.simplefilter("always")
    res = 16
    evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
    # Test animation
    _, anim = evoked.animate_topomap(ch_type="grad", times=[0, 0.1], butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close("all")

    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type="mag")
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos="foo")
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo="bar"))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close("all")
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close("all")
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close("all")
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type="mag", outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type="eeg", res=res, scale=1)
    evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res)
    evoked.plot_topomap(times, ch_type="planar1", res=res)
    evoked.plot_topomap(times, ch_type="planar2", res=res)
    evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res, show_names=True, mask_params={"marker": "x"})
    plt.close("all")
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average="hahahahah")

    p = evoked.plot_topomap(
        times, ch_type="grad", res=res, show_names=lambda x: x.replace("MEG", ""), image_interp="bilinear"
    )
    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 = evoked.plot_topomap(times, ch_type="eeg", res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type="eeg", title="Custom", res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], "Custom")
    plt.close("all")

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter("always")
        evoked.plot_topomap(times, ch_type="mag", layout=None, res=res)
    assert_raises(
        RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
    )  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter("always")
        evoked.plot_topomap(0.1, "mag", proj="interactive", res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter("always")
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
    plot_projs_topomap(projs, res=res)
    plt.close("all")
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close("all")
    for ch in evoked.info["chs"]:
        if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
            ch["loc"].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info["dig"][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, "head")
    assert_true("head" in outlines.keys())
    assert_true("nose" in outlines.keys())
    assert_true("ear_left" in outlines.keys())
    assert_true("ear_right" in outlines.keys())
    assert_true("autoshrink" in outlines.keys())
    assert_true(outlines["autoshrink"])
    assert_true("clip_radius" in outlines.keys())
    assert_array_equal(outlines["clip_radius"], 0.5)

    pos, outlines = _check_outlines(pos, "skirt")
    assert_true("head" in outlines.keys())
    assert_true("nose" in outlines.keys())
    assert_true("ear_left" in outlines.keys())
    assert_true("ear_right" in outlines.keys())
    assert_true("autoshrink" in outlines.keys())
    assert_true(not outlines["autoshrink"])
    assert_true("clip_radius" in outlines.keys())
    assert_array_equal(outlines["clip_radius"], 0.625)

    pos, outlines = _check_outlines(pos, "skirt", head_pos={"scale": [1.2, 1.2]})
    assert_array_equal(outlines["clip_radius"], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type="eeg", outlines="skirt")

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type="eeg", outlines=outlines)
    plt.close("all")

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=0.46, clip_on=True, transform=plt.gca().transAxes)

    outlines["patch"] = patch
    plot_evoked_topomap(evoked, times, ch_type="eeg", outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info["dig"] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
    plt.close("all")

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close("all")

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times="peaks", axes=axes)
    plt.close("all")
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Exemplo n.º 26
0
                        reject,
                        flat,
                        bads,
                        avg_ref,
                        no_proj,
                        event_id,
                        ecg_l_freq,
                        ecg_h_freq,
                        tstart,
                        qrs_threshold,
                        copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the ecg projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing ECG projections in %s" % ecg_proj_fname)
    mne.write_proj(ecg_proj_fname, projs)

    print("Writing ECG events in %s" % ecg_event_fname)
    mne.write_events(ecg_event_fname, events)
Exemplo n.º 27
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname,
                              'Left Auditory',
                              baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type='mag', outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type='eeg', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
        evoked.plot_topomap(times, ch_type='planar1', res=res)
        evoked.plot_topomap(times, ch_type='planar2', res=res)
        evoked.plot_topomap(times,
                            ch_type='grad',
                            mask=mask,
                            res=res,
                            show_names=True,
                            mask_params={'marker': 'x'})
        assert_raises(ValueError,
                      evoked.plot_topomap,
                      times,
                      ch_type='eeg',
                      res=res,
                      average=-1000)
        assert_raises(ValueError,
                      evoked.plot_topomap,
                      times,
                      ch_type='eeg',
                      res=res,
                      average='hahahahah')

        p = evoked.plot_topomap(times,
                                ch_type='grad',
                                res=res,
                                show_names=lambda x: x.replace('MEG', ''),
                                image_interp='bilinear')
        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 = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      0.1,
                      'mag',
                      proj='interactive')  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname,
                              'Left Auditory',
                              baseline=(None, 0),
                              proj=False)
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
        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 = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs, res=res)
        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)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info['dig'][85]
        plot_evoked_topomap(evoked, times, ch_type='eeg')

        # Remove digitization points. Now topomap should fail
        evoked.info['dig'] = None
        assert_raises(RuntimeError,
                      plot_evoked_topomap,
                      evoked,
                      times,
                      ch_type='eeg')
Exemplo n.º 28
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory', baseline=(None, 0))
    # Test animation
    _, anim = evoked.animate_topomap(ch_type='grad',
                                     times=[0, 0.1],
                                     butterfly=False)
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close('all')

    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, plots EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times,
                        ch_type='grad',
                        mask=mask,
                        res=res,
                        show_names=True,
                        mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError,
                  evoked.plot_topomap,
                  times,
                  ch_type='eeg',
                  res=res,
                  average=-1000)
    assert_raises(ValueError,
                  evoked.plot_topomap,
                  times,
                  ch_type='eeg',
                  res=res,
                  average='hahahahah')

    p = evoked.plot_topomap(times,
                            ch_type='grad',
                            res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    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 = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  0.1,
                  'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname,
                          'Left Auditory',
                          baseline=(None, 0),
                          proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos,
                                    'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt')

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines)
    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687),
                      radius=.46,
                      clip_on=True,
                      transform=plt.gca().transAxes)

    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError,
                  plot_evoked_topomap,
                  evoked,
                  times,
                  ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    with warnings.catch_warnings(record=True):  # rightmost column
        evoked.plot_topomap(times='peaks', axes=axes)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
Exemplo n.º 29
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    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 = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos[:, :2]
    pos, outlines = _check_outlines(pos, 'head')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.5)

    pos, outlines = _check_outlines(pos, 'skirt')
    assert_true('head' in outlines.keys())
    assert_true('nose' in outlines.keys())
    assert_true('ear_left' in outlines.keys())
    assert_true('ear_right' in outlines.keys())
    assert_true('autoshrink' in outlines.keys())
    assert_true(not outlines['autoshrink'])
    assert_true('clip_radius' in outlines.keys())
    assert_array_equal(outlines['clip_radius'], 0.625)

    pos, outlines = _check_outlines(pos, 'skirt',
                                    head_pos={'scale': [1.2, 1.2]})
    assert_array_equal(outlines['clip_radius'], 0.75)

    # Plot skirt
    evoked.plot_topomap(times, ch_type='eeg', outlines='skirt')

    # Pass custom outlines without patch
    evoked.plot_topomap(times, ch_type='eeg', outlines=outlines)
    plt.close('all')

    # Pass custom outlines with patch callable
    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines=outlines)

    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')

    # Error for missing names
    n_channels = len(pos)
    data = np.ones(n_channels)
    assert_raises(ValueError, plot_topomap, data, pos, show_names=True)

    # Test error messages for invalid pos parameter
    pos_1d = np.zeros(n_channels)
    pos_3d = np.zeros((n_channels, 2, 2))
    assert_raises(ValueError, plot_topomap, data, pos_1d)
    assert_raises(ValueError, plot_topomap, data, pos_3d)
    assert_raises(ValueError, plot_topomap, data, pos[:3, :])

    pos_x = pos[:, :1]
    pos_xyz = np.c_[pos, np.zeros(n_channels)[:, np.newaxis]]
    assert_raises(ValueError, plot_topomap, data, pos_x)
    assert_raises(ValueError, plot_topomap, data, pos_xyz)

    # An #channels x 4 matrix should work though. In this case (x, y, width,
    # height) is assumed.
    pos_xywh = np.c_[pos, np.zeros((n_channels, 2))]
    plot_topomap(data, pos_xywh)
    plt.close('all')

    # Test peak finder
    axes = [plt.subplot(131), plt.subplot(132)]
    evoked.plot_topomap(times='peaks', axes=axes)
    plt.close('all')
    evoked.data = np.zeros(evoked.data.shape)
    evoked.data[50][1] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[1])
    evoked.data[80][100] = 1
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 100]])
    evoked.data[2][95] = 2
    assert_array_equal(_find_peaks(evoked, 10), evoked.times[[1, 95]])
    assert_array_equal(_find_peaks(evoked, 1), evoked.times[95])
raw.set_annotations(annotations)
del onsets, durations, descriptions

###############################################################################
# Here we compute the saccade and EOG projectors for magnetometers and add
# them to the raw data. The projectors are added to both runs.
saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,
                            baseline=(None, None),
                            reject_by_annotation=False)

projs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,
                                        desc_prefix='saccade')
if use_precomputed:
    proj_fname = op.join(data_path, 'MEG', 'bst_auditory',
                         'bst_auditory-eog-proj.fif')
    projs_eog = mne.read_proj(proj_fname)[0]
else:
    projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),
                                                      n_mag=1, n_eeg=0)
raw.add_proj(projs_saccade)
raw.add_proj(projs_eog)
del saccade_epochs, saccades_events, projs_eog, projs_saccade  # To save memory

###############################################################################
# Visually inspect the effects of projections. Click on 'proj' button at the
# bottom right corner to toggle the projectors on/off. EOG events can be
# plotted by adding the event list as a keyword argument. As the bad segments
# and saccades were added as annotations to the raw data, they are plotted as
# well.
raw.plot(block=True)
Exemplo n.º 31
0
def _proj_fig(fname, info, proj_nums, proj_meg, kind):
    import matplotlib.pyplot as plt
    proj_nums = np.array(proj_nums, int)
    assert proj_nums.shape == (3,)
    projs = read_proj(fname)
    epochs = fname.replace('-proj.fif', '-epo.fif')
    n_col = proj_nums.max()
    rs_topo = 3
    if op.isfile(epochs):
        epochs = mne.read_epochs(epochs)
        evoked = epochs.average()
        rs_trace = 2
    else:
        rs_trace = 0
    n_row = proj_nums.astype(bool).sum() * (rs_topo + rs_trace)
    shape = (n_row, n_col)
    fig = plt.figure(figsize=(n_col * 2, n_row * 0.75))
    used = np.zeros(len(projs), int)
    ri = 0
    for count, ch_type in zip(proj_nums, ('grad', 'mag', 'eeg')):
        if count == 0:
            continue
        if ch_type == 'eeg':
            meg, eeg = False, True
        else:
            meg, eeg = ch_type, False
        ch_names = [info['ch_names'][pick]
                    for pick in mne.pick_types(info, meg=meg, eeg=eeg)]
        idx = np.where([np.in1d(ch_names, proj['data']['col_names']).all()
                        for proj in projs])[0]
        if len(idx) != count:
            raise RuntimeError('Expected %d %s projector%s for channel type '
                               '%s based on proj_nums but got %d in %s'
                               % (count, kind, _pl(count), ch_type, len(idx),
                                  fname))
        if proj_meg == 'separate':
            assert not used[idx].any()
        else:
            assert (used[idx] <= 1).all()
        used[idx] += 1
        these_projs = [deepcopy(projs[ii]) for ii in idx]
        for proj in these_projs:
            sub_idx = [proj['data']['col_names'].index(name)
                       for name in ch_names]
            proj['data']['data'] = proj['data']['data'][:, sub_idx]
            proj['data']['col_names'] = ch_names
        topo_axes = [plt.subplot2grid(
            shape, (ri * (rs_topo + rs_trace), ci),
            rowspan=rs_topo) for ci in range(count)]
        # topomaps
        with warnings.catch_warnings(record=True):
            plot_projs_topomap(these_projs, info=info, show=False,
                               axes=topo_axes)
        plt.setp(topo_axes, title='', xlabel='')
        topo_axes[0].set(ylabel=ch_type)
        if rs_trace:
            trace_axes = [plt.subplot2grid(
                shape, (ri * (rs_topo + rs_trace) + rs_topo, ci),
                rowspan=rs_trace) for ci in range(count)]
            for proj, ax in zip(these_projs, trace_axes):
                this_evoked = evoked.copy().pick_channels(ch_names)
                p = proj['data']['data']
                assert p.shape == (1, len(this_evoked.data))
                with warnings.catch_warnings(record=True):  # tight_layout
                    this_evoked.plot(
                        picks=np.arange(len(this_evoked.data)), axes=[ax])
                ax.texts = []
                trace = np.dot(p, this_evoked.data)[0]
                trace *= 0.8 * (np.abs(ax.get_ylim()).max() /
                                np.abs(trace).max())
                ax.plot(this_evoked.times, trace, color='#9467bd')
                ax.set(title='', ylabel='', xlabel='')
        ri += 1
    assert used.all() and (used <= 2).all()
    fig.subplots_adjust(0.1, 0.1, 0.95, 1, 0.3, 0.3)
    return fig
Exemplo n.º 32
0
def run():
    """Run command."""
    import matplotlib.pyplot as plt
    from mne.commands.utils import get_optparser, _add_verbose_flag
    from mne.viz import _RAW_CLIP_DEF

    parser = get_optparser(__file__, usage='usage: %prog raw [options]')

    parser.add_option("--raw",
                      dest="raw_in",
                      help="Input raw FIF file (can also be specified "
                      "directly as an argument without the --raw prefix)",
                      metavar="FILE")
    parser.add_option("--proj",
                      dest="proj_in",
                      help="Projector file",
                      metavar="FILE",
                      default='')
    parser.add_option("--eve",
                      dest="eve_in",
                      help="Events file",
                      metavar="FILE",
                      default='')
    parser.add_option("-d",
                      "--duration",
                      dest="duration",
                      type="float",
                      help="Time window for plotting (sec)",
                      default=10.0)
    parser.add_option("-t",
                      "--start",
                      dest="start",
                      type="float",
                      help="Initial start time for plotting",
                      default=0.0)
    parser.add_option("-n",
                      "--n_channels",
                      dest="n_channels",
                      type="int",
                      help="Number of channels to plot at a time",
                      default=20)
    parser.add_option("-o",
                      "--order",
                      dest="group_by",
                      help="Order to use for grouping during plotting "
                      "('type' or 'original')",
                      default='type')
    parser.add_option("-p",
                      "--preload",
                      dest="preload",
                      help="Preload raw data (for faster navigaton)",
                      default=False,
                      action="store_true")
    parser.add_option("-s",
                      "--show_options",
                      dest="show_options",
                      help="Show projection options dialog",
                      default=False)
    parser.add_option("--allowmaxshield",
                      dest="maxshield",
                      help="Allow loading MaxShield processed data",
                      action="store_true")
    parser.add_option("--highpass",
                      dest="highpass",
                      type="float",
                      help="Display high-pass filter corner frequency",
                      default=-1)
    parser.add_option("--lowpass",
                      dest="lowpass",
                      type="float",
                      help="Display low-pass filter corner frequency",
                      default=-1)
    parser.add_option("--filtorder",
                      dest="filtorder",
                      type="int",
                      help="Display filtering IIR order (or 0 to use FIR)",
                      default=4)
    parser.add_option("--clipping",
                      dest="clipping",
                      help="Enable trace clipping mode, either 'clamp' or "
                      "'transparent'",
                      default=_RAW_CLIP_DEF)
    parser.add_option("--filterchpi",
                      dest="filterchpi",
                      help="Enable filtering cHPI signals.",
                      default=None,
                      action="store_true")
    _add_verbose_flag(parser)
    options, args = parser.parse_args()

    if len(args):
        raw_in = args[0]
    else:
        raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    group_by = options.group_by
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in
    maxshield = options.maxshield
    highpass = options.highpass
    lowpass = options.lowpass
    filtorder = options.filtorder
    clipping = options.clipping
    if isinstance(clipping, str):
        if clipping.lower() == 'none':
            clipping = None
        else:
            try:
                clipping = float(clipping)  # allow float and convert it
            except ValueError:
                pass
    filterchpi = options.filterchpi
    verbose = options.verbose

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    kwargs = dict(preload=preload)
    if maxshield:
        kwargs.update(allow_maxshield='yes')
    raw = mne.io.read_raw(raw_in, **kwargs)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info['projs'] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None

    if filterchpi:
        if not preload:
            raise RuntimeError(
                'Raw data must be preloaded for chpi, use --preload')
        raw = mne.chpi.filter_chpi(raw)

    highpass = None if highpass < 0 or filtorder < 0 else highpass
    lowpass = None if lowpass < 0 or filtorder < 0 else lowpass
    raw.plot(duration=duration,
             start=start,
             n_channels=n_channels,
             group_by=group_by,
             show_options=show_options,
             events=events,
             highpass=highpass,
             lowpass=lowpass,
             filtorder=filtorder,
             clipping=clipping,
             verbose=verbose)
    plt.show(block=True)
Exemplo n.º 33
0
def run():
    """Run command."""
    import matplotlib.pyplot as plt

    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE")
    parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default="")
    parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default="")
    parser.add_option(
        "-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0
    )
    parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0)
    parser.add_option(
        "-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20
    )
    parser.add_option("-o", "--order", dest="order", help="Order for plotting ('type' or 'original')", default="type")
    parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False)
    parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False)
    parser.add_option(
        "--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true"
    )
    parser.add_option(
        "--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", default=-1
    )
    parser.add_option(
        "--lowpass", dest="lowpass", type="float", help="Display low-pass filter corner frequency", default=-1
    )
    parser.add_option("--filtorder", dest="filtorder", type="int", help="Display filtering IIR order", default=4)
    parser.add_option(
        "--clipping",
        dest="clipping",
        help="Enable trace clipping mode, either 'clip' or " "'transparent'",
        default=None,
    )
    parser.add_option("--filterchpi", dest="filterchpi", help="Enable filtering cHPI signals.", default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in
    maxshield = options.maxshield
    highpass = options.highpass
    lowpass = options.lowpass
    filtorder = options.filtorder
    clipping = options.clipping
    filterchpi = options.filterchpi

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    raw = mne.io.read_raw_fif(raw_in, preload=preload, allow_maxshield=maxshield)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info["projs"] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None

    if filterchpi:
        if not preload:
            raise RuntimeError("Raw data must be preloaded for chpi, use --preload")
        raw = mne.chpi.filter_chpi(raw)

    highpass = None if highpass < 0 or filtorder <= 0 else highpass
    lowpass = None if lowpass < 0 or filtorder <= 0 else lowpass
    filtorder = 4 if filtorder <= 0 else filtorder
    raw.plot(
        duration=duration,
        start=start,
        n_channels=n_channels,
        order=order,
        show_options=show_options,
        events=events,
        highpass=highpass,
        lowpass=lowpass,
        filtorder=filtorder,
        clipping=clipping,
    )
    plt.show(block=True)
Exemplo n.º 34
0
###############################################################################
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)

# delete EEG projections (we know it's the last one)
raw.del_proj(-1)
# add ECG projs for magnetometers
[raw.add_proj(p) for p in mne.read_proj(ecg_fname) if 'axial' in p['desc']]

# pick magnetometer channels
picks = mne.pick_types(raw.info,
                       meg='mag',
                       stim=False,
                       eog=True,
                       include=[],
                       exclude='bads')

# We will make of the proj `delayed` option to
# interactively select projections at the evoked stage.
# more information can be found in the example/plot_evoked_delayed_ssp.py
epochs = mne.Epochs(raw,
                    events,
                    event_id,
=================================
Plot SSP projections topographies
=================================

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 <*****@*****.**>
#         Teon Brooks <*****@*****.**>

# License: BSD (3-clause)

from mne import read_proj, read_evokeds
from mne.datasets import sample

print(__doc__)

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',
                      baseline=(None, 0.))

projs = read_proj(ecg_fname)
evoked.add_proj(projs)

evoked.plot_projs_topomap()
Exemplo n.º 36
0
def mne_raw(path=None, proj=False, **kwargs):
    """
    Returns a mne Raw object with added projections if appropriate.

    Parameters
    ----------
    path : None | str(path)
        path to the raw fiff file. If ``None``, a file can be chosen form a
        file dialog.
    proj : bool | str(path)
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to mne Raw initialization.

    """
    if path is None:
        path = ui.ask_file("Pick a Raw Fiff File", "Pick a Raw Fiff File",
                           [('Functional image file (*.fif)', '*.fif'),
                            ('KIT Raw File (*.sqd,*.con', '*.sqd;*.con')])
        if not path:
            return

    if not os.path.isfile(path):
        raise IOError("%r is not a file" % path)

    if isinstance(path, basestring):
        _, ext = os.path.splitext(path)
        if ext.startswith('.fif'):
            raw = _mne_Raw(path, **kwargs)
        elif ext in ('.sqd', '.con'):
            raw = _mne_read_raw_kit(path, **kwargs)
        else:
            raise ValueError("Unknown extension: %r" % ext)
    else:
        raw = _mne_Raw(path, **kwargs)

    if proj:
        if proj is True:
            proj = '{raw}*proj.fif'

        if '{raw}' in proj:
            raw_file = raw.info['filename']
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip('raw')
            proj = proj.format(raw=raw_root)

        if '*' in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
Exemplo n.º 37
0
    parser.add_option("-s", "--show_options", dest="show_options",
                    help="Show projection options dialog",
                    default=False)
    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in

    if raw_in is None:
        parser.print_help()
        sys.exit(-1)

    raw = mne.fiff.Raw(raw_in, preload=preload)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info['projs'] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None
    fig = raw.plot(duration=duration, start=start, n_channels=n_channels,
                   order=order, show_options=show_options, events=events)
    pl.show(block=True)
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.time_frequency import fit_iir_model_raw
from mne.viz import plot_sparse_source_estimates
from mne.simulation import simulate_sparse_stc, simulate_evoked

print(__doc__)

###############################################################################
# Load real data as templates
data_path = sample.data_path()

raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
proj = mne.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 = mne.read_forward_solution(fwd_fname)
fwd = mne.pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
cov = mne.read_cov(cov_fname)
info = mne.io.read_info(ave_fname)

label_names = ['Aud-lh', 'Aud-rh']
labels = [
    mne.read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
Exemplo n.º 39
0
def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter("always", UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
        evoked.plot_topomap(0.1, "mag", layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type="mag", outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type="eeg", res=res)
        evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res)
        evoked.plot_topomap(times, ch_type="planar1", res=res)
        evoked.plot_topomap(times, ch_type="planar2", res=res)
        evoked.plot_topomap(times, ch_type="grad", mask=mask, res=res, show_names=True, mask_params={"marker": "x"})
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average=-1000)
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type="eeg", res=res, average="hahahahah")

        p = evoked.plot_topomap(
            times, ch_type="grad", res=res, show_names=lambda x: x.replace("MEG", ""), image_interp="bilinear"
        )
        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 = evoked.plot_topomap(times, ch_type="eeg", res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type="eeg", title="Custom", res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], "Custom")

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type="mag", layout=None, res=res)
        assert_raises(
            RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
        )  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
        evoked.plot_topomap(0.1, "mag", proj="interactive", res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
        plot_projs_topomap(projs, res=res)
        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)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info["dig"][85]
        plot_evoked_topomap(evoked, times, ch_type="eeg")

        # Remove digitization points. Now topomap should fail
        evoked.info["dig"] = None
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
Exemplo n.º 40
0
def run():
    import matplotlib.pyplot as plt

    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("--raw",
                      dest="raw_in",
                      help="Input raw FIF file",
                      metavar="FILE")
    parser.add_option("--proj",
                      dest="proj_in",
                      help="Projector file",
                      metavar="FILE",
                      default='')
    parser.add_option("--eve",
                      dest="eve_in",
                      help="Events file",
                      metavar="FILE",
                      default='')
    parser.add_option("-d",
                      "--duration",
                      dest="duration",
                      type="float",
                      help="Time window for plotting (sec)",
                      default=10.0)
    parser.add_option("-t",
                      "--start",
                      dest="start",
                      type="float",
                      help="Initial start time for plotting",
                      default=0.0)
    parser.add_option("-n",
                      "--n_channels",
                      dest="n_channels",
                      type="int",
                      help="Number of channels to plot at a time",
                      default=20)
    parser.add_option("-o",
                      "--order",
                      dest="order",
                      help="Order for plotting ('type' or 'original')",
                      default='type')
    parser.add_option("-p",
                      "--preload",
                      dest="preload",
                      help="Preload raw data (for faster navigaton)",
                      default=False)
    parser.add_option("-s",
                      "--show_options",
                      dest="show_options",
                      help="Show projection options dialog",
                      default=False)
    parser.add_option("--allowmaxshield",
                      dest="maxshield",
                      help="Allow loading MaxShield processed data",
                      action="store_true")
    parser.add_option("--highpass",
                      dest="highpass",
                      type="float",
                      help="Display high-pass filter corner frequency",
                      default=-1)
    parser.add_option("--lowpass",
                      dest="lowpass",
                      type="float",
                      help="Display low-pass filter corner frequency",
                      default=-1)
    parser.add_option("--filtorder",
                      dest="filtorder",
                      type="int",
                      help="Display filtering IIR order",
                      default=4)
    parser.add_option("--clipping",
                      dest="clipping",
                      help="Enable trace clipping mode, either 'clip' or "
                      "'transparent'",
                      default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in
    maxshield = options.maxshield
    highpass = options.highpass
    lowpass = options.lowpass
    filtorder = options.filtorder
    clipping = options.clipping

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    raw = mne.io.Raw(raw_in, preload=preload, allow_maxshield=maxshield)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info['projs'] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None
    highpass = None if highpass < 0 or filtorder <= 0 else highpass
    lowpass = None if lowpass < 0 or filtorder <= 0 else lowpass
    filtorder = 4 if filtorder <= 0 else filtorder
    raw.plot(duration=duration,
             start=start,
             n_channels=n_channels,
             order=order,
             show_options=show_options,
             events=events,
             highpass=highpass,
             lowpass=lowpass,
             filtorder=filtorder,
             clipping=clipping)
    plt.show(block=True)
Exemplo n.º 41
0
def run():
    """Run command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-i", "--in", dest="raw_in",
                      help="Input raw FIF file", metavar="FILE")
    parser.add_option("--tmin", dest="tmin", type="float",
                      help="Time before event in seconds", default=-0.2)
    parser.add_option("--tmax", dest="tmax", type="float",
                      help="Time after event in seconds", default=0.2)
    parser.add_option("-g", "--n-grad", dest="n_grad", type="int",
                      help="Number of SSP vectors for gradiometers",
                      default=2)
    parser.add_option("-m", "--n-mag", dest="n_mag", type="int",
                      help="Number of SSP vectors for magnetometers",
                      default=2)
    parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int",
                      help="Number of SSP vectors for EEG", default=2)
    parser.add_option("--l-freq", dest="l_freq", type="float",
                      help="Filter low cut-off frequency in Hz",
                      default=1)
    parser.add_option("--h-freq", dest="h_freq", type="float",
                      help="Filter high cut-off frequency in Hz",
                      default=35)
    parser.add_option("--eog-l-freq", dest="eog_l_freq", type="float",
                      help="Filter low cut-off frequency in Hz used for "
                      "EOG event detection", default=1)
    parser.add_option("--eog-h-freq", dest="eog_h_freq", type="float",
                      help="Filter high cut-off frequency in Hz used for "
                      "EOG event detection", default=10)
    parser.add_option("-p", "--preload", dest="preload",
                      help="Temporary file used during computation (to "
                      "save memory)", default=True)
    parser.add_option("-a", "--average", dest="average", action="store_true",
                      help="Compute SSP after averaging",
                      default=False)  # XXX: change to default=True in 0.17
    parser.add_option("--proj", dest="proj",
                      help="Use SSP projections from a fif file.",
                      default=None)
    parser.add_option("--filtersize", dest="filter_length", type="int",
                      help="Number of taps to use for filtering",
                      default=2048)
    parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int",
                      help="Number of jobs to run in parallel", default=1)
    parser.add_option("--rej-grad", dest="rej_grad", type="float",
                      help="Gradiometers rejection parameter in fT/cm (peak "
                      "to peak amplitude)", default=2000)
    parser.add_option("--rej-mag", dest="rej_mag", type="float",
                      help="Magnetometers rejection parameter in fT (peak to "
                      "peak amplitude)", default=3000)
    parser.add_option("--rej-eeg", dest="rej_eeg", type="float",
                      help="EEG rejection parameter in uV (peak to peak "
                      "amplitude)", default=50)
    parser.add_option("--rej-eog", dest="rej_eog", type="float",
                      help="EOG rejection parameter in uV (peak to peak "
                      "amplitude)", default=1e9)
    parser.add_option("--avg-ref", dest="avg_ref", action="store_true",
                      help="Add EEG average reference proj",
                      default=False)
    parser.add_option("--no-proj", dest="no_proj", action="store_true",
                      help="Exclude the SSP projectors currently in the "
                      "fiff file",  default=False)
    parser.add_option("--bad", dest="bad_fname",
                      help="Text file containing bad channels list "
                      "(one per line)", default=None)
    parser.add_option("--event-id", dest="event_id", type="int",
                      help="ID to use for events", default=998)
    parser.add_option("--event-raw", dest="raw_event_fname",
                      help="raw file to use for event detection", default=None)
    parser.add_option("--tstart", dest="tstart", type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("-c", "--channel", dest="ch_name", type="string",
                      help="Custom EOG channel(s), comma separated",
                      default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    eog_l_freq = options.eog_l_freq
    eog_h_freq = options.eog_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    ch_name = options.ch_name

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    eog_event_fname = prefix + '_eog-eve.fif'

    if average:
        eog_proj_fname = prefix + '_eog_avg-proj.fif'
    else:
        eog_proj_fname = prefix + '_eog-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    projs, events = mne.preprocessing.compute_proj_eog(
        raw=raw, raw_event=raw_event, tmin=tmin, tmax=tmax, n_grad=n_grad,
        n_mag=n_mag, n_eeg=n_eeg, l_freq=l_freq, h_freq=h_freq,
        average=average, filter_length=filter_length,
        n_jobs=n_jobs, reject=reject, flat=flat, bads=bads,
        avg_ref=avg_ref, no_proj=no_proj, event_id=event_id,
        eog_l_freq=eog_l_freq, eog_h_freq=eog_h_freq,
        tstart=tstart, ch_name=ch_name, copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the eog projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing EOG projections in %s" % eog_proj_fname)
    mne.write_proj(eog_proj_fname, projs)

    print("Writing EOG events in %s" % eog_event_fname)
    mne.write_events(eog_event_fname, events)
###############################################################################
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg_proj.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)

# delete EEG projections (we know it's the last one)
raw.del_proj(-1)
# add ECG projs for magnetometers
[raw.add_proj(p) for p in mne.read_proj(ecg_fname) if 'axial' in p['desc']]

# pick magnetometer channels
picks = mne.pick_types(raw.info, meg='mag', stim=False, eog=True,
                       include=[], exclude='bads')

# We will make of the proj `delayed` option to
# interactively select projections at the evoked stage.
# more information can be found in the example/plot_evoked_delayed_ssp.py
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(mag=4e-12), proj='delayed')

evoked = epochs.average()  # average epochs and get an Evoked dataset.

###############################################################################
# Interactively select / deselect the SSP projection vectors
Exemplo n.º 43
0
def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(None, ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    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 = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    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)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos
    pos, outlines = _check_outlines(pos, 'head')
    # test 1: pass custom outlines without patch

    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)

    # test 2: pass custom outlines with patch callable
    outlines['patch'] = patch
    plot_evoked_topomap(evoked, times, ch_type='eeg', outlines='head')
    # Remove digitization points. Now topomap should fail
    evoked.info['dig'] = None
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  times, ch_type='eeg')
    plt.close('all')
Exemplo n.º 44
0
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    projs, events = mne.preprocessing.compute_proj_eog(raw=raw,
                    raw_event=raw_event, tmin=tmin, tmax=tmax, n_grad=n_grad,
                    n_mag=n_mag, n_eeg=n_eeg, l_freq=l_freq, h_freq=h_freq,
                    average=average, filter_length=filter_length,
                    n_jobs=n_jobs, reject=reject, flat=flat, bads=bads,
                    avg_ref=avg_ref, no_proj=no_proj, event_id=event_id,
                    eog_l_freq=eog_l_freq, eog_h_freq=eog_h_freq, 
                    tstart=tstart, ch_name=ch_name, copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the eog projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing EOG projections in %s" % eog_proj_fname)
    mne.write_proj(eog_proj_fname, projs)

    print("Writing EOG events in %s" % eog_event_fname)
    mne.write_events(eog_event_fname, events)
Exemplo n.º 45
0
from scipy import signal
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import fit_iir_model_raw
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'

raw = mne.io.read_raw_fif(raw_fname)
proj = mne.read_proj(proj_fname)
raw.info['projs'] += proj
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

# Set up pick list: Gradiometers - bad channels
picks = mne.pick_types(raw.info, meg='grad', exclude='bads')

order = 5  # define model order
picks = picks[:1]

# Estimate AR models on raw data
b, a = fit_iir_model_raw(raw, order=order, picks=picks, tmin=60, tmax=180)
d, times = raw[0, 10000:20000]  # look at one channel from now on
d = d.ravel()  # make flat vector
innovation = signal.convolve(d, a, 'valid')
d_ = signal.lfilter(b, a, innovation)  # regenerate the signal
Exemplo n.º 46
0
def apply_preprocessing_combined(p, subjects, run_indices):
    """Actually apply and save the preprocessing (projs, filtering)

    Can only run after do_preprocessing_combined is done.
    Filters data, adds projection vectors, and saves to disk
    (overwriting old files).

    Parameters
    ----------
    p : instance of Parameters
        Analysis parameters.
    subjects : list of str
        Subject names to analyze (e.g., ['Eric_SoP_001', ...]).
    run_indices : array-like | None
        Run indices to include.
    """
    # Now actually save some data
    for si, subj in enumerate(subjects):
        if p.disp_files:
            print('  Applying processing to subject %g/%g.' %
                  (si + 1, len(subjects)))
        pca_dir = op.join(p.work_dir, subj, p.pca_dir)
        names_in = get_raw_fnames(p, subj, 'sss', False, False,
                                  run_indices[si])
        names_out = get_raw_fnames(p, subj, 'pca', False, False,
                                   run_indices[si])
        erm_in = get_raw_fnames(p, subj, 'sss', 'only')
        erm_out = get_raw_fnames(p, subj, 'pca', 'only')
        bad_file = get_bad_fname(p, subj)
        all_proj = op.join(pca_dir, 'preproc_all-proj.fif')
        projs = read_proj(all_proj)
        fir_kwargs = _get_fir_kwargs(p.fir_design)[0]
        if len(erm_in) > 0:
            for ii, (r, o) in enumerate(zip(erm_in, erm_out)):
                if p.disp_files:
                    print('    Processing erm file %d/%d.' %
                          (ii + 1, len(erm_in)))
            raw = _raw_LRFCP(raw_names=r,
                             sfreq=None,
                             l_freq=p.hp_cut,
                             h_freq=p.lp_cut,
                             n_jobs=p.n_jobs_fir,
                             n_jobs_resample=p.n_jobs_resample,
                             projs=projs,
                             bad_file=bad_file,
                             disp_files=False,
                             method='fir',
                             apply_proj=False,
                             filter_length=p.filter_length,
                             force_bads=True,
                             l_trans=p.hp_trans,
                             h_trans=p.lp_trans,
                             phase=p.phase,
                             fir_window=p.fir_window,
                             pick=False,
                             **fir_kwargs)
            raw.save(o, overwrite=True, buffer_size_sec=None)
        for ii, (r, o) in enumerate(zip(names_in, names_out)):
            if p.disp_files:
                print('    Processing file %d/%d.' % (ii + 1, len(names_in)))
            raw = _raw_LRFCP(raw_names=r,
                             sfreq=None,
                             l_freq=p.hp_cut,
                             h_freq=p.lp_cut,
                             n_jobs=p.n_jobs_fir,
                             n_jobs_resample=p.n_jobs_resample,
                             projs=projs,
                             bad_file=bad_file,
                             disp_files=False,
                             method='fir',
                             apply_proj=False,
                             filter_length=p.filter_length,
                             force_bads=False,
                             l_trans=p.hp_trans,
                             h_trans=p.lp_trans,
                             phase=p.phase,
                             fir_window=p.fir_window,
                             pick=False,
                             **fir_kwargs)
            raw.save(o, overwrite=True, buffer_size_sec=None)
        # look at raw_clean for ExG events
        if p.plot_raw:
            from ._viz import _viz_raw_ssp_events
            _viz_raw_ssp_events(p, subj, run_indices[si])
print(__doc__)

###############################################################################
# Set parameters
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_eog-proj.fif'

tmin, tmax = 0, 60  # use the first 60s of data

# Setup for reading the raw data (to save memory, crop before loading)
raw = io.read_raw_fif(raw_fname).crop(tmin, tmax).load_data()
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Add SSP projection vectors to reduce EOG and ECG artifacts
projs = read_proj(proj_fname)
raw.add_proj(projs, remove_existing=True)


fmin, fmax = 2, 300  # look at frequencies between 2 and 300Hz
n_fft = 2048  # the FFT size (n_fft). Ideally a power of 2

# Let's first check out all channel types
raw.plot_psd(area_mode='range', tmax=10.0, show=False)

# Now let's focus on a smaller subset:
# Pick MEG magnetometers in the Left-temporal region
selection = read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads', selection=selection)
Exemplo n.º 48
0
def mne_raw(path=None, proj=False, **kwargs):
    """Load a :class:`mne.io.Raw` object

    Parameters
    ----------
    path : None | str
        path to a raw fiff or sqd file. If no path is supplied, a file can be
        chosen from a file dialog.
    proj : bool | str
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to :class:`mne.io.Raw`
        initialization.
    """
    if path is None:
        path = ui.ask_file(
            "Pick a raw data file",
            "Pick a raw data file",
            [("Functional image file (*.fif)", "*.fif"), ("KIT Raw File (*.sqd,*.con", "*.sqd;*.con")],
        )
        if not path:
            return

    if isinstance(path, basestring):
        _, ext = os.path.splitext(path)
        if ext.startswith(".fif"):
            raw = mne.io.read_raw_fif(path, add_eeg_ref=False, **kwargs)
        elif ext in (".sqd", ".con"):
            raw = mne.io.read_raw_kit(path, **kwargs)
        else:
            raise ValueError("Unknown extension: %r" % ext)
    else:
        # MNE Raw supports list of file-names
        raw = mne.io.read_raw_fif(path, add_eeg_ref=False, **kwargs)

    if proj:
        if proj is True:
            proj = "{raw}*proj.fif"

        if "{raw}" in proj:
            raw_file = raw.info["filename"]
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip("raw")
            proj = proj.format(raw=raw_root)

        if "*" in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
Exemplo n.º 49
0
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.time_frequency import fit_iir_model_raw
from mne.viz import plot_sparse_source_estimates
from mne.simulation import simulate_sparse_stc, simulate_evoked

print(__doc__)

###############################################################################
# Load real data as templates
data_path = sample.data_path()

raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
proj = mne.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 = mne.read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True)
fwd = mne.pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
cov = mne.read_cov(cov_fname)
info = mne.io.read_info(ave_fname)

label_names = ['Aud-lh', 'Aud-rh']
labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
          for ln in label_names]
from mne import (read_proj, read_forward_solution, read_cov, read_label,
                 pick_types_forward, pick_types)
from mne.io import Raw, read_info
from mne.datasets import sample
from mne.time_frequency import fit_iir_model_raw
from mne.viz import plot_sparse_source_estimates
from mne.simulation import simulate_sparse_stc, simulate_evoked

print(__doc__)

###############################################################################
# Load real data as templates
data_path = sample.data_path()

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)
info = read_info(ave_fname)

label_names = ['Aud-lh', 'Aud-rh']
labels = [
    read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
Exemplo n.º 51
0
# align with the raw data.
#
# We can check where the channels reside with ``plot_sensors``. Notice that
# this method (along with many other MNE plotting functions) is callable using
# any MNE data container where the channel information is available.
raw.plot_sensors(kind='3d', ch_type='mag', ch_groups='position')

###############################################################################
# We used ``ch_groups='position'`` to color code the different regions. It uses
# the same algorithm for dividing the regions as ``order='position'`` of
# :func:`raw.plot <mne.io.Raw.plot>`. You can also pass a list of picks to
# color any channel group with different colors.
#
# Now let's add some ssp projectors to the raw data. Here we read them from a
# file and plot them.
projs = mne.read_proj(op.join(data_path, 'sample_audvis_eog-proj.fif'))
raw.add_proj(projs)
raw.plot_projs_topomap()

###############################################################################
# The first three projectors that we see are the SSP vectors from empty room
# measurements to compensate for the noise. The fourth one is the average EEG
# reference. These are already applied to the data and can no longer be
# removed. The next six are the EOG projections that we added. Every data
# channel type has two projection vectors each. Let's try the raw browser
# again.
raw.plot()

###############################################################################
# Now click the `proj` button at the lower right corner of the browser
# window. A selection dialog should appear, where you can toggle the projectors
Exemplo n.º 52
0
def run():
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("-i", "--in", dest="raw_in",
                      help="Input raw FIF file", metavar="FILE")
    parser.add_option("--tmin", dest="tmin", type="float",
                      help="Time before event in seconds",
                      default=-0.2)
    parser.add_option("--tmax", dest="tmax", type="float",
                      help="Time after event in seconds",
                      default=0.4)
    parser.add_option("-g", "--n-grad", dest="n_grad", type="int",
                      help="Number of SSP vectors for gradiometers",
                      default=2)
    parser.add_option("-m", "--n-mag", dest="n_mag", type="int",
                      help="Number of SSP vectors for magnetometers",
                      default=2)
    parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int",
                      help="Number of SSP vectors for EEG",
                      default=2)
    parser.add_option("--l-freq", dest="l_freq", type="float",
                      help="Filter low cut-off frequency in Hz",
                      default=1)
    parser.add_option("--h-freq", dest="h_freq", type="float",
                      help="Filter high cut-off frequency in Hz",
                      default=100)
    parser.add_option("--ecg-l-freq", dest="ecg_l_freq", type="float",
                      help="Filter low cut-off frequency in Hz used "
                      "for ECG event detection",
                      default=5)
    parser.add_option("--ecg-h-freq", dest="ecg_h_freq", type="float",
                      help="Filter high cut-off frequency in Hz used "
                      "for ECG event detection",
                      default=35)
    parser.add_option("-p", "--preload", dest="preload",
                      help="Temporary file used during computation "
                      "(to save memory)",
                      default=True)
    parser.add_option("-a", "--average", dest="average", action="store_true",
                      help="Compute SSP after averaging",
                      default=False)
    parser.add_option("--proj", dest="proj",
                      help="Use SSP projections from a fif file.",
                      default=None)
    parser.add_option("--filtersize", dest="filter_length", type="int",
                      help="Number of taps to use for filtering",
                      default=2048)
    parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int",
                      help="Number of jobs to run in parallel",
                      default=1)
    parser.add_option("-c", "--channel", dest="ch_name",
                      help="Channel to use for ECG detection "
                      "(Required if no ECG found)",
                      default=None)
    parser.add_option("--rej-grad", dest="rej_grad", type="float",
                      help="Gradiometers rejection parameter "
                      "in fT/cm (peak to peak amplitude)",
                      default=2000)
    parser.add_option("--rej-mag", dest="rej_mag", type="float",
                      help="Magnetometers rejection parameter "
                      "in fT (peak to peak amplitude)",
                      default=3000)
    parser.add_option("--rej-eeg", dest="rej_eeg", type="float",
                      help="EEG rejection parameter in uV "
                      "(peak to peak amplitude)",
                      default=50)
    parser.add_option("--rej-eog", dest="rej_eog", type="float",
                      help="EOG rejection parameter in uV "
                      "(peak to peak amplitude)",
                      default=250)
    parser.add_option("--avg-ref", dest="avg_ref", action="store_true",
                      help="Add EEG average reference proj",
                      default=False)
    parser.add_option("--no-proj", dest="no_proj", action="store_true",
                      help="Exclude the SSP projectors currently "
                      "in the fiff file",
                      default=False)
    parser.add_option("--bad", dest="bad_fname",
                      help="Text file containing bad channels list "
                      "(one per line)",
                      default=None)
    parser.add_option("--event-id", dest="event_id", type="int",
                      help="ID to use for events",
                      default=999)
    parser.add_option("--event-raw", dest="raw_event_fname",
                      help="raw file to use for event detection",
                      default=None)
    parser.add_option("--tstart", dest="tstart", type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("--qrsthr", dest="qrs_threshold", type="string",
                      help="QRS detection threshold. Between 0 and 1. Can "
                      "also be 'auto' for automatic selection",
                      default='auto')

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    ecg_l_freq = options.ecg_l_freq
    ecg_h_freq = options.ecg_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    ch_name = options.ch_name
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    qrs_threshold = options.qrs_threshold
    if qrs_threshold != 'auto':
        try:
            qrs_threshold = float(qrs_threshold)
        except ValueError:
            raise ValueError('qrsthr must be "auto" or a float')

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    ecg_event_fname = prefix + '_ecg-eve.fif'

    if average:
        ecg_proj_fname = prefix + '_ecg_avg-proj.fif'
    else:
        ecg_proj_fname = prefix + '_ecg-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    cpe = mne.preprocessing.compute_proj_ecg
    projs, events = cpe(raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg,
                        l_freq, h_freq, average, filter_length, n_jobs,
                        ch_name, reject, flat, bads, avg_ref, no_proj,
                        event_id, ecg_l_freq, ecg_h_freq, tstart,
                        qrs_threshold, copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the ecg projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing ECG projections in %s" % ecg_proj_fname)
    mne.write_proj(ecg_proj_fname, projs)

    print("Writing ECG events in %s" % ecg_event_fname)
    mne.write_events(ecg_event_fname, events)
annotations = mne.Annotations(onsets, durations, descriptions)
raw.annotations = annotations
del onsets, durations, descriptions

###############################################################################
# Here we compute the saccade and EOG projectors for magnetometers and add
# them to the raw data. The projectors are added to both runs.
saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,
                            reject_by_annotation=False)

projs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,
                                        desc_prefix='saccade')
if use_precomputed:
    proj_fname = op.join(data_path, 'MEG', 'bst_auditory',
                         'bst_auditory-eog-proj.fif')
    projs_eog = mne.read_proj(proj_fname)[0]
else:
    projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),
                                                      n_mag=1, n_eeg=0)
raw.add_proj(projs_saccade)
raw.add_proj(projs_eog)
del saccade_epochs, saccades_events, projs_eog, projs_saccade  # To save memory

###############################################################################
# Visually inspect the effects of projections. Click on 'proj' button at the
# bottom right corner to toggle the projectors on/off. EOG events can be
# plotted by adding the event list as a keyword argument. As the bad segments
# and saccades were added as annotations to the raw data, they are plotted as
# well.
raw.plot(block=True)
Exemplo n.º 54
0
def do_preprocessing_combined(p, subjects, run_indices):
    """Do preprocessing on all raw files together.

    Calculates projection vectors to use to clean data.

    Parameters
    ----------
    p : instance of Parameters
        Analysis parameters.
    subjects : list of str
        Subject names to analyze (e.g., ['Eric_SoP_001', ...]).
    run_indices : array-like | None
        Run indices to include.
    """
    drop_logs = list()
    for si, subj in enumerate(subjects):
        proj_nums = _proj_nums(p, subj)
        ecg_channel = _handle_dict(p.ecg_channel, subj)
        flat = _handle_dict(p.flat, subj)
        if p.disp_files:
            print('  Preprocessing subject %g/%g (%s).' %
                  (si + 1, len(subjects), subj))
        pca_dir = _get_pca_dir(p, subj)
        bad_file = get_bad_fname(p, subj, check_exists=False)

        # Create SSP projection vectors after marking bad channels
        raw_names = get_raw_fnames(p, subj, 'sss', False, False,
                                   run_indices[si])
        empty_names = get_raw_fnames(p, subj, 'sss', 'only')
        for r in raw_names + empty_names:
            if not op.isfile(r):
                raise NameError('File not found (' + r + ')')

        fir_kwargs, old_kwargs = _get_fir_kwargs(p.fir_design)
        if isinstance(p.auto_bad, float):
            print('    Creating post SSS bad channel file:\n'
                  '        %s' % bad_file)
            # do autobad
            raw = _raw_LRFCP(raw_names,
                             p.proj_sfreq,
                             None,
                             None,
                             p.n_jobs_fir,
                             p.n_jobs_resample,
                             list(),
                             None,
                             p.disp_files,
                             method='fir',
                             filter_length=p.filter_length,
                             apply_proj=False,
                             force_bads=False,
                             l_trans=p.hp_trans,
                             h_trans=p.lp_trans,
                             phase=p.phase,
                             fir_window=p.fir_window,
                             pick=True,
                             skip_by_annotation='edge',
                             **fir_kwargs)
            events = fixed_len_events(p, raw)
            rtmin = p.reject_tmin \
                if p.reject_tmin is not None else p.tmin
            rtmax = p.reject_tmax \
                if p.reject_tmax is not None else p.tmax
            # do not mark eog channels bad
            meg, eeg = 'meg' in raw, 'eeg' in raw
            picks = pick_types(raw.info,
                               meg=meg,
                               eeg=eeg,
                               eog=False,
                               exclude=[])
            assert p.auto_bad_flat is None or isinstance(p.auto_bad_flat, dict)
            assert p.auto_bad_reject is None or \
                isinstance(p.auto_bad_reject, dict) or \
                p.auto_bad_reject == 'auto'
            if p.auto_bad_reject == 'auto':
                print('    Auto bad channel selection active. '
                      'Will try using Autoreject module to '
                      'compute rejection criterion.')
                try:
                    from autoreject import get_rejection_threshold
                except ImportError:
                    raise ImportError('     Autoreject module not installed.\n'
                                      '     Noisy channel detection parameter '
                                      '     not defined. To use autobad '
                                      '     channel selection either define '
                                      '     rejection criteria or install '
                                      '     Autoreject module.\n')
                print('    Computing thresholds.\n', end='')
                temp_epochs = Epochs(raw,
                                     events,
                                     event_id=None,
                                     tmin=rtmin,
                                     tmax=rtmax,
                                     baseline=_get_baseline(p),
                                     proj=True,
                                     reject=None,
                                     flat=None,
                                     preload=True,
                                     decim=1)
                kwargs = dict()
                if 'verbose' in get_args(get_rejection_threshold):
                    kwargs['verbose'] = False
                reject = get_rejection_threshold(temp_epochs, **kwargs)
                reject = {kk: vv for kk, vv in reject.items()}
            elif p.auto_bad_reject is None and p.auto_bad_flat is None:
                raise RuntimeError('Auto bad channel detection active. Noisy '
                                   'and flat channel detection '
                                   'parameters not defined. '
                                   'At least one criterion must be defined.')
            else:
                reject = p.auto_bad_reject
            if 'eog' in reject.keys():
                reject.pop('eog', None)
            epochs = Epochs(raw,
                            events,
                            None,
                            tmin=rtmin,
                            tmax=rtmax,
                            baseline=_get_baseline(p),
                            picks=picks,
                            reject=reject,
                            flat=p.auto_bad_flat,
                            proj=True,
                            preload=True,
                            decim=1,
                            reject_tmin=rtmin,
                            reject_tmax=rtmax)
            # channel scores from drop log
            drops = Counter([ch for d in epochs.drop_log for ch in d])
            # get rid of non-channel reasons in drop log
            scores = {
                kk: vv
                for kk, vv in drops.items() if kk in epochs.ch_names
            }
            ch_names = np.array(list(scores.keys()))
            # channel scores expressed as percentile and rank ordered
            counts = (100 * np.array([scores[ch] for ch in ch_names], float) /
                      len(epochs.drop_log))
            order = np.argsort(counts)[::-1]
            # boolean array masking out channels with <= % epochs dropped
            mask = counts[order] > p.auto_bad
            badchs = ch_names[order[mask]]
            if len(badchs) > 0:
                # Make sure we didn't get too many bad MEG or EEG channels
                for m, e, thresh in zip(
                    [True, False], [False, True],
                    [p.auto_bad_meg_thresh, p.auto_bad_eeg_thresh]):
                    picks = pick_types(epochs.info, meg=m, eeg=e, exclude=[])
                    if len(picks) > 0:
                        ch_names = [epochs.ch_names[pp] for pp in picks]
                        n_bad_type = sum(ch in ch_names for ch in badchs)
                        if n_bad_type > thresh:
                            stype = 'meg' if m else 'eeg'
                            raise RuntimeError('Too many bad %s channels '
                                               'found: %s > %s' %
                                               (stype, n_bad_type, thresh))

                print('    The following channels resulted in greater than '
                      '{:.0f}% trials dropped:\n'.format(p.auto_bad * 100))
                print(badchs)
                with open(bad_file, 'w') as f:
                    f.write('\n'.join(badchs))
        if not op.isfile(bad_file):
            print('    Clearing bad channels (no file %s)' %
                  op.sep.join(bad_file.split(op.sep)[-3:]))
            bad_file = None

        ecg_t_lims = _handle_dict(p.ecg_t_lims, subj)
        ecg_f_lims = p.ecg_f_lims

        ecg_eve = op.join(pca_dir, 'preproc_ecg-eve.fif')
        ecg_epo = op.join(pca_dir, 'preproc_ecg-epo.fif')
        ecg_proj = op.join(pca_dir, 'preproc_ecg-proj.fif')
        all_proj = op.join(pca_dir, 'preproc_all-proj.fif')

        get_projs_from = _handle_dict(p.get_projs_from, subj)
        if get_projs_from is None:
            get_projs_from = np.arange(len(raw_names))
        pre_list = [
            r for ri, r in enumerate(raw_names) if ri in get_projs_from
        ]

        projs = list()
        raw_orig = _raw_LRFCP(raw_names=pre_list,
                              sfreq=p.proj_sfreq,
                              l_freq=None,
                              h_freq=None,
                              n_jobs=p.n_jobs_fir,
                              n_jobs_resample=p.n_jobs_resample,
                              projs=projs,
                              bad_file=bad_file,
                              disp_files=p.disp_files,
                              method='fir',
                              filter_length=p.filter_length,
                              force_bads=False,
                              l_trans=p.hp_trans,
                              h_trans=p.lp_trans,
                              phase=p.phase,
                              fir_window=p.fir_window,
                              pick=True,
                              skip_by_annotation='edge',
                              **fir_kwargs)

        # Apply any user-supplied extra projectors
        if p.proj_extra is not None:
            if p.disp_files:
                print('    Adding extra projectors from "%s".' % p.proj_extra)
            projs.extend(read_proj(op.join(pca_dir, p.proj_extra)))

        proj_kwargs, p_sl = _get_proj_kwargs(p)
        #
        # Calculate and apply ERM projectors
        #
        if not p.cont_as_esss:
            if any(proj_nums[2]):
                assert proj_nums[2][2] == 0  # no EEG projectors for ERM
                if len(empty_names) == 0:
                    raise RuntimeError('Cannot compute empty-room projectors '
                                       'from continuous raw data')
                if p.disp_files:
                    print('    Computing continuous projectors using ERM.')
                # Use empty room(s), but processed the same way
                projs.extend(_compute_erm_proj(p, subj, projs, 'sss',
                                               bad_file))
            else:
                cont_proj = op.join(pca_dir, 'preproc_cont-proj.fif')
                _safe_remove(cont_proj)

        #
        # Calculate and apply the ECG projectors
        #
        if any(proj_nums[0]):
            if p.disp_files:
                print('    Computing ECG projectors...', end='')
            raw = raw_orig.copy()

            raw.filter(ecg_f_lims[0],
                       ecg_f_lims[1],
                       n_jobs=p.n_jobs_fir,
                       method='fir',
                       filter_length=p.filter_length,
                       l_trans_bandwidth=0.5,
                       h_trans_bandwidth=0.5,
                       phase='zero-double',
                       fir_window='hann',
                       skip_by_annotation='edge',
                       **old_kwargs)
            raw.add_proj(projs)
            raw.apply_proj()
            find_kwargs = dict()
            if 'reject_by_annotation' in get_args(find_ecg_events):
                find_kwargs['reject_by_annotation'] = True
            elif len(raw.annotations) > 0:
                print('    WARNING: ECG event detection will not make use of '
                      'annotations, please update MNE-Python')
            # We've already filtered the data channels above, but this
            # filters the ECG channel
            ecg_events = find_ecg_events(raw,
                                         999,
                                         ecg_channel,
                                         0.,
                                         ecg_f_lims[0],
                                         ecg_f_lims[1],
                                         qrs_threshold='auto',
                                         return_ecg=False,
                                         **find_kwargs)[0]
            use_reject, use_flat = _restrict_reject_flat(
                _handle_dict(p.ssp_ecg_reject, subj), flat, raw)
            ecg_epochs = Epochs(raw,
                                ecg_events,
                                999,
                                ecg_t_lims[0],
                                ecg_t_lims[1],
                                baseline=None,
                                reject=use_reject,
                                flat=use_flat,
                                preload=True)
            print('  obtained %d epochs from %d events.' %
                  (len(ecg_epochs), len(ecg_events)))
            if len(ecg_epochs) >= 20:
                write_events(ecg_eve, ecg_epochs.events)
                ecg_epochs.save(ecg_epo, **_get_epo_kwargs())
                desc_prefix = 'ECG-%s-%s' % tuple(ecg_t_lims)
                pr = compute_proj_wrap(ecg_epochs,
                                       p.proj_ave,
                                       n_grad=proj_nums[0][0],
                                       n_mag=proj_nums[0][1],
                                       n_eeg=proj_nums[0][2],
                                       desc_prefix=desc_prefix,
                                       **proj_kwargs)
                assert len(pr) == np.sum(proj_nums[0][::p_sl])
                write_proj(ecg_proj, pr)
                projs.extend(pr)
            else:
                _raise_bad_epochs(raw, ecg_epochs, ecg_events, 'ECG')
            del raw, ecg_epochs, ecg_events
        else:
            _safe_remove([ecg_proj, ecg_eve, ecg_epo])

        #
        # Next calculate and apply the EOG projectors
        #
        for idx, kind in ((1, 'EOG'), (3, 'HEOG'), (4, 'VEOG')):
            _compute_add_eog(p, subj, raw_orig, projs, proj_nums[idx], kind,
                             pca_dir, flat, proj_kwargs, old_kwargs, p_sl)
        del proj_nums

        # save the projectors
        write_proj(all_proj, projs)

        #
        # Look at raw_orig for trial DQs now, it will be quick
        #
        raw_orig.filter(p.hp_cut,
                        p.lp_cut,
                        n_jobs=p.n_jobs_fir,
                        method='fir',
                        filter_length=p.filter_length,
                        l_trans_bandwidth=p.hp_trans,
                        phase=p.phase,
                        h_trans_bandwidth=p.lp_trans,
                        fir_window=p.fir_window,
                        skip_by_annotation='edge',
                        **fir_kwargs)
        raw_orig.add_proj(projs)
        raw_orig.apply_proj()
        # now let's epoch with 1-sec windows to look for DQs
        events = fixed_len_events(p, raw_orig)
        reject = _handle_dict(p.reject, subj)
        use_reject, use_flat = _restrict_reject_flat(reject, flat, raw_orig)
        epochs = Epochs(raw_orig,
                        events,
                        None,
                        p.tmin,
                        p.tmax,
                        preload=False,
                        baseline=_get_baseline(p),
                        reject=use_reject,
                        flat=use_flat,
                        proj=True)
        try:
            epochs.drop_bad()
        except AttributeError:  # old way
            epochs.drop_bad_epochs()
        drop_logs.append(epochs.drop_log)
        del raw_orig
        del epochs
    if p.plot_drop_logs:
        for subj, drop_log in zip(subjects, drop_logs):
            plot_drop_log(drop_log, p.drop_thresh, subject=subj)