コード例 #1
0
ファイル: caller.py プロジェクト: jaeilepp/eggie
    def computeSspProj(self, events, tmin, tmax, event_id, n_eeg):
        """
        Computes SSP projection vectors and adds them to the raw data.
        Parameters:
        events    - A list of events for creating the epochs.
        tmin      - Starting time before event for the epochs.
        tmax      - Ending time after the event for the epochs.
        event_id  - The id of the event to consider.
        n_eeg     - The number of vectors for EEG channels.
        """
        # Extract EOG epochs from raw data
        try:
            eog_epochs = mne.Epochs(self.raw,
                                    events,
                                    event_id=event_id,
                                    tmin=tmin,
                                    tmax=tmax)
        except Exception as e:
            print "Could not create epochs.\n"
            print str(e)
            return []

        # Average EOG epochs
        try:
            eog_evoked = eog_epochs.average()

            # Compute SSPs
            proj = mne.compute_proj_evoked(eog_evoked, n_eeg=n_eeg)
            self.raw.add_proj(proj)
        except Exception as e:
            print "Error while computing projections.\n"
            print str(e)
            return []
        return proj
コード例 #2
0
ファイル: test_proj.py プロジェクト: oryondark/mne-python
def test_compute_proj_epochs():
    """Test SSP computation on epochs"""
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = Raw(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                       exclude=[])
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, 'proj.fif.gz'), projs)
    for p_fname in [proj_fname, proj_gz_fname,
                    op.join(tempdir, 'proj.fif.gz')]:
        projs2 = read_proj(p_fname)

        assert_true(len(projs) == len(projs2))

        for p1, p2 in zip(projs, projs2):
            assert_true(p1['desc'] == p2['desc'])
            assert_true(p1['data']['col_names'] == p2['data']['col_names'])
            assert_true(p1['active'] == p2['active'])
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'foo.fif'))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert_true(len(projs_evoked) == 2)
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=2)
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)
コード例 #3
0
def test_plot_joint():
    """Test joint plot."""
    evoked = _get_epochs().average()
    evoked.plot_joint(ts_args=dict(time_unit='s'),
                      topomap_args=dict(time_unit='s'))

    def return_inds(d):  # to test function kwarg to zorder arg of evoked.plot
        return list(range(d.shape[0]))
    evoked.plot_joint(title='test', topomap_args=dict(contours=0, res=8,
                                                      time_unit='ms'),
                      ts_args=dict(spatial_colors=True, zorder=return_inds,
                                   time_unit='s'))
    pytest.raises(ValueError, evoked.plot_joint, ts_args=dict(axes=True,
                                                              time_unit='s'))

    axes = plt.subplots(nrows=3)[-1].flatten().tolist()
    evoked.plot_joint(times=[0], picks=[6, 7, 8], ts_args=dict(axes=axes[0]),
                      topomap_args={"axes": axes[1:], "time_unit": "s"})
    with pytest.raises(ValueError, match='array of length 6'):
        evoked.plot_joint(picks=[6, 7, 8], ts_args=dict(axes=axes[0]),
                          topomap_args=dict(axes=axes[2:]))
    plt.close('all')

    # test proj options
    assert len(evoked.info['projs']) == 0
    evoked.pick_types(meg=True)
    evoked.add_proj(compute_proj_evoked(
        evoked, n_mag=1, n_grad=1, meg='combined'))
    assert len(evoked.info['projs']) == 1
    with pytest.raises(ValueError, match='must match ts_args'):
        evoked.plot_joint(ts_args=dict(proj=True),
                          topomap_args=dict(proj=False))
    evoked.plot_joint(ts_args=dict(proj='reconstruct'),
                      topomap_args=dict(proj='reconstruct'))
    plt.close('all')
コード例 #4
0
def test_plot_joint():
    """Test joint plot."""
    evoked = _get_epochs().average()
    evoked.plot_joint(ts_args=dict(time_unit='s'),
                      topomap_args=dict(time_unit='s'))

    def return_inds(d):  # to test function kwarg to zorder arg of evoked.plot
        return list(range(d.shape[0]))

    evoked.plot_joint(title='test',
                      topomap_args=dict(contours=0, res=8, time_unit='ms'),
                      ts_args=dict(spatial_colors=True,
                                   zorder=return_inds,
                                   time_unit='s'))
    with pytest.raises(ValueError, match='If one of `ts_args` and'):
        evoked.plot_joint(ts_args=dict(axes=True, time_unit='s'))

    axes = plt.subplots(nrows=3)[-1].flatten().tolist()
    evoked.plot_joint(times=[0],
                      picks=[6, 7, 8],
                      ts_args=dict(axes=axes[0]),
                      topomap_args={
                          "axes": axes[1:],
                          "time_unit": "s"
                      })
    with pytest.raises(ValueError, match='array of length 6'):
        evoked.plot_joint(picks=[6, 7, 8],
                          ts_args=dict(axes=axes[0]),
                          topomap_args=dict(axes=axes[2:]))
    plt.close('all')

    # test proj options
    assert len(evoked.info['projs']) == 0
    evoked.pick_types(meg=True)
    evoked.add_proj(
        compute_proj_evoked(evoked, n_mag=1, n_grad=1, meg='combined'))
    assert len(evoked.info['projs']) == 1
    with pytest.raises(ValueError, match='must match ts_args'):
        evoked.plot_joint(ts_args=dict(proj=True),
                          topomap_args=dict(proj=False))
    evoked.plot_joint(ts_args=dict(proj='reconstruct'),
                      topomap_args=dict(proj='reconstruct'))
    plt.close('all')

    # test sEEG (gh:8733)
    evoked.del_proj().pick_types('mag')  # avoid overlapping positions error
    mapping = {ch_name: 'seeg' for ch_name in evoked.ch_names}
    with pytest.warns(RuntimeWarning, match='The unit .* has changed from .*'):
        evoked.set_channel_types(mapping)
    evoked.plot_joint()

    # test DBS (gh:8739)
    evoked = _get_epochs().average().pick_types('mag')
    mapping = {ch_name: 'dbs' for ch_name in evoked.ch_names}
    with pytest.warns(RuntimeWarning, match='The unit for'):
        evoked.set_channel_types(mapping)
    evoked.plot_joint()
    plt.close('all')
コード例 #5
0
def test_plot_topomap_interactive():
    """Test interactive topomap projection plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    evoked.pick_types(meg='mag')
    evoked.info['projs'] = []
    assert not evoked.proj
    evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))

    plt.close('all')
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.gca()

    kwargs = dict(vmin=-240,
                  vmax=240,
                  times=[0.1],
                  colorbar=False,
                  axes=ax,
                  res=8,
                  time_unit='s')
    evoked.copy().plot_topomap(proj=False, **kwargs)
    canvas.draw()
    image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj=True, **kwargs)
    canvas.draw()
    image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert not np.array_equal(image_noproj, image_proj)
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj='interactive', **kwargs)
    canvas.draw()
    image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive)
    assert not np.array_equal(image_proj, image_interactive)
    assert len(plt.get_fignums()) == 2

    proj_fig = plt.figure(plt.get_fignums()[-1])
    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(canvas.tostring_rgb(),
                                            dtype='uint8')
    assert_array_equal(image_proj, image_interactive_click)
    assert not np.array_equal(image_noproj, image_interactive_click)

    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(canvas.tostring_rgb(),
                                            dtype='uint8')
    assert_array_equal(image_noproj, image_interactive_click)
    assert not np.array_equal(image_proj, image_interactive_click)
コード例 #6
0
ファイル: test_topomap.py プロジェクト: SherazKhan/mne-python
def test_plot_topomap_interactive():
    """Test interactive topomap projection plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    evoked.pick_types(meg='mag')
    evoked.info['projs'] = []
    assert not evoked.proj
    evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))

    plt.close('all')
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.gca()

    kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax,
                  res=8, time_unit='s')
    evoked.copy().plot_topomap(proj=False, **kwargs)
    canvas.draw()
    image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj=True, **kwargs)
    canvas.draw()
    image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert not np.array_equal(image_noproj, image_proj)
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj='interactive', **kwargs)
    canvas.draw()
    image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive)
    assert not np.array_equal(image_proj, image_interactive)
    assert len(plt.get_fignums()) == 2

    proj_fig = plt.figure(plt.get_fignums()[-1])
    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_proj, image_interactive_click)
    assert not np.array_equal(image_noproj, image_interactive_click)

    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive_click)
    assert not np.array_equal(image_proj, image_interactive_click)
コード例 #7
0
ファイル: test_proj.py プロジェクト: sudo-nim/mne-python
def test_compute_proj():
    """Test SSP computation"""
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = Raw(raw_fname)
    events = read_events(event_fname)
    exclude = []
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                            exclude=exclude)
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                        baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0)

    projs2 = read_proj(proj_fname)

    assert_true(len(projs) == len(projs2))

    for p1, p2 in zip(projs, projs2):
        assert_true(p1['desc'] == p2['desc'])
        assert_true(p1['data']['col_names'] == p2['data']['col_names'])
        assert_true(p1['active'] == p2['active'])
        # compare with sign invariance
        p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
        p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
        if bad_ch in p1['data']['col_names']:
            bad = p1['data']['col_names'].index('MEG 2443')
            mask = np.ones(p1_data.size, dtype=np.bool)
            mask[bad] = False
            p1_data = p1_data[:, mask]
            p2_data = p2_data[:, mask]
        corr = np.corrcoef(p1_data, p2_data)[0, 1]
        assert_array_almost_equal(corr, 1.0, 7)

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save('foo.fif')

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
コード例 #8
0
ファイル: test_proj.py プロジェクト: mh105/mne-python
def test_plot_projs_joint():
    """Test plot_projs_joint."""
    evoked = read_evokeds(evoked_fname)[0].apply_baseline((None, 0))
    evoked.info['bads'] = []
    n_mag, n_grad, n_eeg = 9, 10, 11
    n_mag_proj, n_grad_proj, n_eeg_proj = 2, 2, 1
    # We pick in this weird order to ensure our plotting order follows it
    picks = np.concatenate([
        pick_types(evoked.info, meg='grad')[:n_grad],
        pick_types(evoked.info, meg=False, eeg=True)[:n_eeg],
        pick_types(evoked.info, meg='mag')[:n_mag],
    ])
    evoked.pick(picks)
    assert len(evoked.ch_names) == n_mag + n_grad + n_eeg
    assert evoked.get_channel_types(unique=True) == ['grad', 'eeg', 'mag']
    projs = compute_proj_evoked(evoked,
                                n_mag=n_mag_proj,
                                n_grad=n_grad_proj,
                                n_eeg=n_eeg_proj)
    assert len(projs) == 5
    with pytest.warns(RuntimeWarning, match='aliasing'):
        evoked.crop(-0.1, 0.1).decimate(10)
    topomap_kwargs = dict(res=8, contours=0, sensors=False)
    fig = plot_projs_joint(projs,
                           evoked,
                           topomap_kwargs=topomap_kwargs,
                           verbose='error')
    ylab = fig.axes[0].get_ylabel()
    assert ylab.startswith('Grad'), ylab
    ylab = fig.axes[4].get_ylabel()
    assert ylab.startswith('EEG'), ylab
    ylab = fig.axes[7].get_ylabel()
    assert ylab.startswith('Mag'), ylab
    mag_trace_ax_idx = 10
    mag_trace_ax = fig.axes[mag_trace_ax_idx]
    assert mag_trace_ax.get_ylabel() == ''
    assert len(mag_trace_ax.lines) == n_mag + 2 * n_mag_proj
    old_len = len(mag_trace_ax.lines)
    assert len(fig.axes) == 11  # 3x4
    fig = plot_projs_joint(projs,
                           evoked,
                           picks_trace='MEG 0111',
                           topomap_kwargs=topomap_kwargs,
                           verbose='error')
    assert len(fig.axes[mag_trace_ax_idx].lines) == old_len + 1
コード例 #9
0
ファイル: test_evoked.py プロジェクト: aces/EEG2BIDS
def test_plot_evoked_reconstruct(picks, rlims, avg_proj):
    """Test proj="reconstruct"."""
    evoked = _get_epochs(picks=picks).average()
    if avg_proj:
        evoked.set_eeg_reference(projection=True).apply_proj()
        assert len(evoked.info['projs']) == 1
        assert evoked.proj is True
    else:
        assert len(evoked.info['projs']) == 0
        assert evoked.proj is False
    fig = evoked.plot(proj=True,
                      hline=[1],
                      exclude=[],
                      window_title='foo',
                      time_unit='s')
    amplitudes = _get_amplitudes(fig)
    assert len(amplitudes) == len(picks)
    assert evoked.proj is avg_proj

    fig = evoked.plot(proj='reconstruct', exclude=[])
    amplitudes_recon = _get_amplitudes(fig)
    if avg_proj is False:
        assert_allclose(amplitudes, amplitudes_recon)
    proj = compute_proj_evoked(evoked.copy().crop(None, 0).apply_proj())
    evoked.add_proj(proj)
    assert len(evoked.info['projs']) == 2 if len(picks) == 3 else 4
    fig = evoked.plot(proj=True, exclude=[])
    amplitudes_proj = _get_amplitudes(fig)
    fig = evoked.plot(proj='reconstruct', exclude=[])
    amplitudes_recon = _get_amplitudes(fig)
    assert len(amplitudes_recon) == len(picks)
    norm = np.linalg.norm(amplitudes)
    norm_proj = np.linalg.norm(amplitudes_proj)
    norm_recon = np.linalg.norm(amplitudes_recon)
    r = np.dot(amplitudes_recon.ravel(),
               amplitudes.ravel()) / (norm_recon * norm)
    assert rlims[0] < r < rlims[1]
    assert 1.05 * norm_proj < norm_recon
    if not avg_proj:
        assert norm_proj < norm * 0.9

    cov = read_cov(cov_fname)
    with pytest.raises(ValueError, match='Cannot use proj="reconstruct"'):
        evoked.plot(noise_cov=cov, proj='reconstruct')
    plt.close('all')
コード例 #10
0
raw.notch_filter(np.arange(60, 181, 60))

events = mne.find_events(raw, stim_channel='UPPT001')

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       exclude='bads')

# Compute epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=False)

# compute evoked
evoked = epochs.average()

# remove physiological artifacts (eyeblinks, heartbeats) using SSP on baseline
evoked.add_proj(mne.compute_proj_evoked(evoked.crop(tmax=0, copy=True)))
evoked.apply_proj()

# fix stim artifact
mne.preprocessing.fix_stim_artifact(evoked)

# correct delays due to hardware (stim artifact is at 4 ms)
evoked.shift_time(-0.004)

# plot the result
evoked.plot()

# show topomaps
evoked.plot_topomap(times=np.array([0.016, 0.030, 0.060, 0.070]))
コード例 #11
0
def compute_proj_wrap(epochs, average, **kwargs):
    if average:
        return compute_proj_evoked(epochs.average(), **kwargs)
    else:
        return compute_proj_epochs(epochs, **kwargs)
コード例 #12
0
def compute_proj_ecg(in_path, in_fif_fname, tmin, tmax, n_grad, n_mag, n_eeg,
                     l_freq, h_freq, average, filter_length, n_jobs, ch_name,
                     reject, avg_ref, bads, preload, flat):
    """Compute SSP/PCA projections for ECG/EOG artifacts

    Parameters
    ----------
    in_fif_fname: string
        Raw fif File
    XXX
    """
    if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'):
        prefix = in_fif_fname[:-8]
    else:
        prefix = in_fif_fname[:-4]
    ecg_event_fname = in_path + 'ssp/' + prefix + '_ecg-eve.fif'

    if average:
        ecg_proj_fname = in_path + 'ssp/' + prefix + '_ecg_avg_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_ecg_avg_proj_raw.fif'

    else:
        ecg_proj_fname = in_path + 'ssp/' + prefix + '_ecg_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_ecg_proj_raw.fif'

    print 'Reading fif File'
    in_fif_fname = in_path + in_fif_fname
    raw = mne.fiff.Raw(in_fif_fname, preload=preload)

    #    if (in_path == '/cluster/kuperberg/SemPrMM/MEG/data/ya30/'):
    # save after 84s of MEG data in FIF file
    #      raw = raw[: , 84:]
    #raw.save('sample_audvis_meg_raw.fif', tmin=84)

    print 'Running ECG SSP computation'

    ecg_events, _, _ = mne.artifacts.find_ecg_events(raw, ch_name=ch_name)
    print "Writing ECG events in %s" % ecg_event_fname
    mne.write_events(ecg_event_fname, ecg_events)
    make_lingua(ecg_event_fname)

    if avg_ref:
        print "Adding average EEG reference projection."
        eeg_proj = mne.fiff.proj.make_eeg_average_ref_proj(raw.info)
        raw.info['projs'].append(eeg_proj)

    print 'Computing ECG projector'

    # Handler rejection parameters
    if len(mne.fiff.pick_types(raw.info, meg='grad', eeg=False,
                               eog=False)) == 0:
        del reject['grad']
    if len(mne.fiff.pick_types(raw.info, meg='mag', eeg=False,
                               eog=False)) == 0:
        del reject['mag']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=True, eog=False)) == 0:
        del reject['eeg']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=False, eog=True)) == 0:
        del reject['eog']

    picks = mne.fiff.pick_types(raw.info,
                                meg=True,
                                eeg=True,
                                eog=True,
                                exclude=raw.info['bads'] + bads)
    if l_freq is None and h_freq is not None:
        raw.high_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is None:
        raw.low_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is not None:
        raw.band_pass_filter(picks, l_freq, h_freq, filter_length, n_jobs)

    epochs_ecg = mne.Epochs(raw,
                            ecg_events,
                            None,
                            tmin,
                            tmax,
                            baseline=None,
                            picks=picks,
                            reject=reject,
                            proj=True)
    print epochs_ecg
    projs_init = raw.info['projs']

    if average:
        evoked_ecg = epochs_ecg.average()
        projs_ecg = mne.compute_proj_evoked(evoked_ecg,
                                            n_grad=n_grad,
                                            n_mag=n_mag,
                                            n_eeg=n_eeg)
    else:
        print epochs_ecg, n_grad, n_mag, n_eeg
        projs_ecg = mne.compute_proj_epochs(epochs_ecg,
                                            n_grad=n_grad,
                                            n_mag=n_mag,
                                            n_eeg=n_eeg)

    print "Writing ECG projections in %s" % ecg_proj_fname
    mne.write_proj(
        ecg_proj_fname, projs_ecg + projs_init
    )  ## Original Projections written along with the ecg projections.

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

    return in_fif_fname, ecg_proj_fname, out_fif_fname
コード例 #13
0
ファイル: test_proj.py プロジェクト: starzynski/mne-python
def test_compute_proj():
    """Test SSP computation"""
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = Raw(raw_fname, preload=True)
    events = read_events(event_fname)
    exclude = []
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                            exclude=exclude)
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                        baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj('proj.fif.gz', projs)
    for p_fname in [proj_fname, proj_gz_fname, 'proj.fif.gz']:
        projs2 = read_proj(p_fname)

        assert_true(len(projs) == len(projs2))

        for p1, p2 in zip(projs, projs2):
            assert_true(p1['desc'] == p2['desc'])
            assert_true(p1['data']['col_names'] == p2['data']['col_names'])
            assert_true(p1['active'] == p2['active'])
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save('foo.fif')

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=2)
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_array_equal(proj, proj_par)

    # Test that the raw projectors work
    for ii in (1, 2, 4, 8, 12, 24):
        raw = Raw(raw_fname)
        projs = compute_proj_raw(raw, duration=ii-0.1, n_grad=1, n_mag=1,
                                 n_eeg=0)

        # test that you can compute the projection matrix
        projs = activate_proj(projs)
        proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

        assert_true(nproj == 2)
        assert_true(U.shape[1] == 2)

        # test that you can save them
        raw.info['projs'] += projs
        raw.save('foo_%d_raw.fif' % ii)

    # Test that purely continuous (no duration) raw projection works
    raw = Raw(raw_fname)
    projs = compute_proj_raw(raw, duration=None, n_grad=1, n_mag=1, n_eeg=0)

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    raw.info['projs'] += projs
    raw.save('foo_rawproj_continuous_raw.fif')
コード例 #14
0
def compute_proj_ecg(in_path, in_fif_fname, tmin, tmax, n_grad, n_mag, n_eeg, l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, avg_ref, bads, preload, flat):

    """Compute SSP/PCA projections for ECG/EOG artifacts

    Parameters
    ----------
    in_fif_fname: string
        Raw fif File
    XXX
    """
    if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'):
        prefix = in_fif_fname[:-8]
    else:
        prefix = in_fif_fname[:-4]
    ecg_event_fname = in_path + 'ssp/' + prefix + '_ecg-eve.fif'

    if average:
         ecg_proj_fname = in_path + 'ssp/' + prefix + '_ecg_avg_proj.fif'
         out_fif_fname = in_path + 'ssp/' + prefix + '_ecg_avg_proj_raw.fif'

    else:
         ecg_proj_fname = in_path + 'ssp/' + prefix + '_ecg_proj.fif'
         out_fif_fname = in_path + 'ssp/' + prefix + '_ecg_proj_raw.fif'

    
    print 'Reading fif File'
    in_fif_fname = in_path + in_fif_fname
    raw = mne.fiff.Raw(in_fif_fname, preload=preload)
    
#    if (in_path == '/cluster/kuperberg/SemPrMM/MEG/data/ya30/'):
    # save after 84s of MEG data in FIF file
 #      raw = raw[: , 84:]
       #raw.save('sample_audvis_meg_raw.fif', tmin=84)

    print 'Running ECG SSP computation'

    ecg_events, _, _ = mne.artifacts.find_ecg_events(raw, ch_name=ch_name)
    print "Writing ECG events in %s" % ecg_event_fname
    mne.write_events(ecg_event_fname, ecg_events)
    make_lingua(ecg_event_fname)
    
    if avg_ref:
        print "Adding average EEG reference projection."
        eeg_proj = mne.fiff.proj.make_eeg_average_ref_proj(raw.info)
        raw.info['projs'].append(eeg_proj)


    print 'Computing ECG projector'

    # Handler rejection parameters
    if len(mne.fiff.pick_types(raw.info, meg='grad', eeg=False, eog=False)) == 0:
        del reject['grad']
    if len(mne.fiff.pick_types(raw.info, meg='mag', eeg=False, eog=False)) == 0:
        del reject['mag']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=True, eog=False)) == 0:
        del reject['eeg']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=False, eog=True)) == 0:
        del reject['eog']

    picks = mne.fiff.pick_types(raw.info, meg=True, eeg=True, eog=True,
                                exclude=raw.info['bads'] + bads)
    if l_freq is None and h_freq is not None:
        raw.high_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is None:
        raw.low_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is not None:
        raw.band_pass_filter(picks, l_freq, h_freq, filter_length, n_jobs)

    epochs_ecg = mne.Epochs(raw, ecg_events, None, tmin, tmax, baseline=None,
                        picks=picks, reject=reject, proj=True)
    print epochs_ecg
    projs_init = raw.info['projs'] 

    if average:
         evoked_ecg = epochs_ecg.average()
         projs_ecg = mne.compute_proj_evoked(evoked_ecg, n_grad=n_grad, n_mag=n_mag,
                                         n_eeg=n_eeg)
    else:
         print epochs_ecg, n_grad, n_mag, n_eeg
         projs_ecg = mne.compute_proj_epochs(epochs_ecg, n_grad=n_grad, n_mag=n_mag,
                                            n_eeg=n_eeg)


    print "Writing ECG projections in %s" % ecg_proj_fname
    mne.write_proj(ecg_proj_fname, projs_ecg + projs_init) ## Original Projections written along with the ecg projections. 

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

    return in_fif_fname, ecg_proj_fname, out_fif_fname
コード例 #15
0
ファイル: test_proj.py プロジェクト: Vincent-wq/mne-python
def test_compute_proj_epochs(tmp_path):
    """Test SSP computation on epochs."""
    tempdir = str(tmp_path)
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info,
                       meg=True,
                       eeg=False,
                       stim=False,
                       eog=False,
                       exclude=[])
    epochs = Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=None,
                    proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, 'test-proj.fif.gz'), projs)
    for p_fname in [
            proj_fname, proj_gz_fname,
            op.join(tempdir, 'test-proj.fif.gz')
    ]:
        projs2 = read_proj(p_fname)

        assert len(projs) == len(projs2)

        for p1, p2 in zip(projs, projs2):
            assert p1['desc'] == p2['desc']
            assert p1['data']['col_names'] == p2['data']['col_names']
            assert p1['active'] == p2['active']
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)
            if p2['explained_var']:
                assert_array_almost_equal(p1['explained_var'],
                                          p2['explained_var'])

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert nproj == 2
    assert U.shape[1] == 2

    # test that you can save them
    with epochs.info._unlock():
        epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'foo-ave.fif'))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert len(projs_evoked) == 2
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs,
                                n_grad=1,
                                n_mag=1,
                                n_eeg=0,
                                n_jobs=1,
                                desc_prefix='foobar')
    assert all('foobar' in x['desc'] for x in projs)
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)

    # test warnings on bad filenames
    proj_badname = op.join(tempdir, 'test-bad-name.fif.gz')
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        write_proj(proj_badname, projs)
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        read_proj(proj_badname)

    # bad inputs
    fname = op.join(tempdir, 'out-proj.fif')
    with pytest.raises(TypeError, match='projs'):
        write_proj(fname, 'foo')
    with pytest.raises(TypeError, match=r'projs\[0\] must be .*'):
        write_proj(fname, ['foo'])
コード例 #16
0
ファイル: test_proj.py プロジェクト: nwilming/mne-python
def test_compute_proj_epochs():
    """Test SSP computation on epochs."""
    tempdir = _TempDir()
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = "MEG 2443"
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, exclude=[])
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, "test-proj.fif.gz"), projs)
    for p_fname in [proj_fname, proj_gz_fname, op.join(tempdir, "test-proj.fif.gz")]:
        projs2 = read_proj(p_fname)

        assert_true(len(projs) == len(projs2))

        for p1, p2 in zip(projs, projs2):
            assert_true(p1["desc"] == p2["desc"])
            assert_true(p1["data"]["col_names"] == p2["data"]["col_names"])
            assert_true(p1["active"] == p2["active"])
            # compare with sign invariance
            p1_data = p1["data"]["data"] * np.sign(p1["data"]["data"][0, 0])
            p2_data = p2["data"]["data"] * np.sign(p2["data"]["data"][0, 0])
            if bad_ch in p1["data"]["col_names"]:
                bad = p1["data"]["col_names"].index("MEG 2443")
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)
            if p2["explained_var"]:
                assert_array_almost_equal(p1["explained_var"], p2["explained_var"])

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    epochs.info["projs"] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, "foo-ave.fif"))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert_true(len(projs_evoked) == 2)
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=2, desc_prefix="foobar")
    assert_true(all("foobar" in x["desc"] for x in projs))
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)

    # test warnings on bad filenames
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        proj_badname = op.join(tempdir, "test-bad-name.fif.gz")
        write_proj(proj_badname, projs)
        read_proj(proj_badname)
    assert_naming(w, "test_proj.py", 2)
コード例 #17
0
def test_compute_proj_epochs():
    """Test SSP computation on epochs"""
    tempdir = _TempDir()
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = Raw(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info,
                       meg=True,
                       eeg=False,
                       stim=False,
                       eog=False,
                       exclude=[])
    epochs = Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=None,
                    proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, 'test-proj.fif.gz'), projs)
    for p_fname in [
            proj_fname, proj_gz_fname,
            op.join(tempdir, 'test-proj.fif.gz')
    ]:
        projs2 = read_proj(p_fname)

        assert_true(len(projs) == len(projs2))

        for p1, p2 in zip(projs, projs2):
            assert_true(p1['desc'] == p2['desc'])
            assert_true(p1['data']['col_names'] == p2['data']['col_names'])
            assert_true(p1['active'] == p2['active'])
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)
            if p2['explained_var']:
                assert_array_almost_equal(p1['explained_var'],
                                          p2['explained_var'])

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert_true(nproj == 2)
    assert_true(U.shape[1] == 2)

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'foo-ave.fif'))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert_true(len(projs_evoked) == 2)
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs,
                                n_grad=1,
                                n_mag=1,
                                n_eeg=0,
                                n_jobs=2,
                                desc_prefix='foobar')
    assert_true(all('foobar' in x['desc'] for x in projs))
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)

    # test warnings on bad filenames
    clean_warning_registry()
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        proj_badname = op.join(tempdir, 'test-bad-name.fif.gz')
        write_proj(proj_badname, projs)
        read_proj(proj_badname)
        print([ww.message for ww in w])
    assert_equal(len(w), 2)
コード例 #18
0
        try:
            raw = mne.io.read_raw_fif(fname_raw)
        except FileNotFoundError:
            raw = mne.io.read_raw_fif(fname_mp_raw)
        # TODO: replace with proper solution
        raw = _handle_events_reading(events_fname, raw)
        events, event_id = mne.events_from_annotations(raw)
        event_id = {key: value for key, value in event_id.items()
                    if key in evts_labels}
        epochs = mne.Epochs(raw, events, event_id, tmin=-.2, tmax=1,
                            baseline=baseline, reject=reject, verbose=False)

        # compute the SSP
        evoked = epochs.average()
        ev_proj = evoked.copy().crop(-.1, .03)
        projs = mne.compute_proj_evoked(ev_proj, n_mag=3)

        # apply projector individually
        evokeds = [evoked.copy().add_proj(proj).apply_proj() for proj in projs]

        # 1. plot before and after summary
        fig = plt.figure(figsize=(18, 8))
        gs = gridspec.GridSpec(1, 2)
        axes = [plt.subplot(gs[0]), plt.subplot(gs[1])]
        # plot evoked
        evoked.crop(-.1,.1).plot(titles={'mag': 'Before: Original Evoked'},
                                 show=False,
                                 axes=axes[0], ylim=ylim)
        # remove all
        evoked_proj = evoked.copy().add_proj(projs).apply_proj()
        evoked_proj.plot(titles={'mag': 'After: Evoked - First 3 PCs'},
コード例 #19
0
events = mne.find_events(raw, stim_channel='UPPT001')

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       exclude='bads')

# Compute epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=False)

# compute evoked
evoked = epochs.average()

# remove physiological artifacts (eyeblinks, heartbeats) using SSP on baseline
evoked.add_proj(mne.compute_proj_evoked(evoked.copy().crop(tmax=0)))
evoked.apply_proj()

# fix stim artifact
mne.preprocessing.fix_stim_artifact(evoked)

# correct delays due to hardware (stim artifact is at 4 ms)
evoked.shift_time(-0.004)

# plot the result
evoked.plot(time_unit='s')

# show topomaps
evoked.plot_topomap(times=np.array([0.016, 0.030, 0.060, 0.070]),
                    time_unit='s')
コード例 #20
0
def compute_proj_eog(in_path, in_fif_fname, tmin, tmax, n_grad, n_mag, n_eeg, l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, avg_ref, bads, preload):

	#####Defining filenames
	
    if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'):
        prefix = in_fif_fname[:-8]
    else:
        prefix = in_fif_fname[:-4]

    eog_event_fname = in_path + 'ssp/'+ prefix + '_PYeog-eve.fif'

    if average:
        eog_proj_fname = in_path + 'ssp/' + prefix + '_eog_avg_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_eog_avg_proj_raw.fif'

    else:
        eog_proj_fname = in_path + 'ssp/' + prefix + '_PYeog_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_PYeog_proj_raw.fif'

	####Reading in raw data

    in_fif_fname = in_path + in_fif_fname
    raw = mne.fiff.Raw(in_fif_fname, preload=preload)

    print 'Running EOG SSP computation'

    eog_events, _= mne.artifacts.find_eog_events(raw)  # since our copy of the mne.artifacts.events.py script returns two parameters. 
    print "Writing EOG events in %s" % eog_event_fname
    mne.write_events(eog_event_fname, eog_events)
    make_lingua(eog_event_fname)

    print 'Computing EOG projector'

    # Handler rejection parameters
    if len(mne.fiff.pick_types(raw.info, meg='grad', eeg=False, ecg=False)) == 0:
        del reject['grad']
    if len(mne.fiff.pick_types(raw.info, meg='mag', eeg=False, ecg=False)) == 0:
        del reject['mag']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=True, ecg=False)) == 0:
        del reject['eeg']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=False, ecg=True)) == 0:
        del reject['ecg']

    picks_eog = mne.fiff.pick_types(raw.info, meg=True, eeg=True, ecg=True,
                                exclude=raw.info['bads'] + bads)
    if l_freq is None and h_freq is not None:
        raw.high_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is None:
        raw.low_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is not None:
        raw.band_pass_filter(picks_eog, l_freq, h_freq, filter_length, n_jobs)

    epochs_eog = mne.Epochs(raw, eog_events, None, tmin, tmax, baseline=None,
                        picks=picks_eog, reject=reject, proj=True)

    projs_init = raw.info['projs']

    if average:
         evoked_eog = epochs_eog.average()
         projs_eog = mne.compute_proj_evoked(evoked_eog, n_grad=n_grad, n_mag=n_mag,
                                         n_eeg=n_eeg)
    else:
         print epochs_eog, n_grad, n_mag, n_eeg
         projs_eog = mne.compute_proj_epochs(epochs_eog, n_grad=n_grad, n_mag=n_mag,
                                            n_eeg=n_eeg)


    print "Writing EOG projections in %s" % eog_proj_fname
    mne.write_proj(eog_proj_fname, projs_eog)
    
    return in_fif_fname, eog_proj_fname, out_fif_fname
コード例 #21
0
events = mne.find_events(raw, stim_channel='UPPT001')

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       exclude='bads')

# Compute epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=False)

# compute evoked
evoked = epochs.average()

# remove physiological artifacts (eyeblinks, heartbeats) using SSP on baseline
evoked.add_proj(mne.compute_proj_evoked(evoked.copy().crop(tmax=0)))
evoked.apply_proj()

# fix stim artifact
mne.preprocessing.fix_stim_artifact(evoked)

# correct delays due to hardware (stim artifact is at 4 ms)
evoked.shift_time(-0.004)

# plot the result
evoked.plot(time_unit='s')

# show topomaps
evoked.plot_topomap(times=np.array([0.016, 0.030, 0.060, 0.070]),
                    time_unit='s')
コード例 #22
0
def test_plot_topomap_interactive(constrained_layout):
    """Test interactive topomap projection plotting."""
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    evoked.pick_types(meg='mag')
    evoked.info['projs'] = []
    assert not evoked.proj
    evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))

    plt.close('all')
    fig, ax = plt.subplots(constrained_layout=constrained_layout)
    canvas = fig.canvas

    kwargs = dict(vmin=-240,
                  vmax=240,
                  times=[0.1],
                  colorbar=False,
                  axes=ax,
                  res=8,
                  time_unit='s')
    evoked.copy().plot_topomap(proj=False, **kwargs)
    canvas.draw()
    image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj=True, **kwargs)
    canvas.draw()
    image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert not np.array_equal(image_noproj, image_proj)
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj='interactive', **kwargs)
    canvas.draw()
    image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive)
    assert not np.array_equal(image_proj, image_interactive)
    assert len(plt.get_fignums()) == 2

    proj_fig = plt.figure(plt.get_fignums()[-1])
    assert len(proj_fig.axes[0].lines) == 2
    for line in proj_fig.axes[0].lines:
        assert not line.get_visible()
    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    assert len(proj_fig.axes[0].lines) == 2
    for line in proj_fig.axes[0].lines:
        assert line.get_visible()
    canvas.draw()
    image_interactive_click = np.frombuffer(canvas.tostring_rgb(),
                                            dtype='uint8')
    corr = np.corrcoef(image_proj.ravel(), image_interactive_click.ravel())[0,
                                                                            1]
    assert 0.99 < corr <= 1
    corr = np.corrcoef(image_noproj.ravel(),
                       image_interactive_click.ravel())[0, 1]
    assert 0.85 < corr < 0.9

    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(canvas.tostring_rgb(),
                                            dtype='uint8')
    corr = np.corrcoef(image_noproj.ravel(),
                       image_interactive_click.ravel())[0, 1]
    assert 0.99 < corr <= 1
    corr = np.corrcoef(image_proj.ravel(), image_interactive_click.ravel())[0,
                                                                            1]
    assert 0.85 < corr < 0.9
コード例 #23
0
raw.notch_filter(np.arange(60, 181, 60))

events = mne.find_events(raw, stim_channel='UPPT001')

# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
                       exclude='bads')

# Compute epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=False)

# compute evoked
evoked = epochs.average()

# remove physiological artifacts (eyeblinks, heartbeats) using SSP on baseline
evoked.add_proj(mne.compute_proj_evoked(evoked.crop(tmax=0, copy=True)))
evoked.apply_proj()

# fix stim artifact
mne.preprocessing.fix_stim_artifact(evoked)

# correct delays due to hardware (stim artifact is at 4 ms)
evoked.shift_time(-0.004)

# plot the result
evoked.plot()

# show topomaps
evoked.plot_topomap(times=np.array([0.016, 0.030, 0.060, 0.070]))
コード例 #24
0
def compute_proj_eog(in_path, in_fif_fname, tmin, tmax, n_grad, n_mag, n_eeg,
                     l_freq, h_freq, average, filter_length, n_jobs, ch_name,
                     reject, avg_ref, bads, preload):

    #####Defining filenames

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

    eog_event_fname = in_path + 'ssp/' + prefix + '_PYeog-eve.fif'

    if average:
        eog_proj_fname = in_path + 'ssp/' + prefix + '_eog_avg_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_eog_avg_proj_raw.fif'

    else:
        eog_proj_fname = in_path + 'ssp/' + prefix + '_PYeog_proj.fif'
        out_fif_fname = in_path + 'ssp/' + prefix + '_PYeog_proj_raw.fif'

####Reading in raw data

    in_fif_fname = in_path + in_fif_fname
    raw = mne.fiff.Raw(in_fif_fname, preload=preload)

    print 'Running EOG SSP computation'

    eog_events, _ = mne.artifacts.find_eog_events(
        raw
    )  # since our copy of the mne.artifacts.events.py script returns two parameters.
    print "Writing EOG events in %s" % eog_event_fname
    mne.write_events(eog_event_fname, eog_events)
    make_lingua(eog_event_fname)

    print 'Computing EOG projector'

    # Handler rejection parameters
    if len(mne.fiff.pick_types(raw.info, meg='grad', eeg=False,
                               ecg=False)) == 0:
        del reject['grad']
    if len(mne.fiff.pick_types(raw.info, meg='mag', eeg=False,
                               ecg=False)) == 0:
        del reject['mag']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=True, ecg=False)) == 0:
        del reject['eeg']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=False, ecg=True)) == 0:
        del reject['ecg']

    picks_eog = mne.fiff.pick_types(raw.info,
                                    meg=True,
                                    eeg=True,
                                    ecg=True,
                                    exclude=raw.info['bads'] + bads)
    if l_freq is None and h_freq is not None:
        raw.high_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is None:
        raw.low_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is not None:
        raw.band_pass_filter(picks_eog, l_freq, h_freq, filter_length, n_jobs)

    epochs_eog = mne.Epochs(raw,
                            eog_events,
                            None,
                            tmin,
                            tmax,
                            baseline=None,
                            picks=picks_eog,
                            reject=reject,
                            proj=True)

    projs_init = raw.info['projs']

    if average:
        evoked_eog = epochs_eog.average()
        projs_eog = mne.compute_proj_evoked(evoked_eog,
                                            n_grad=n_grad,
                                            n_mag=n_mag,
                                            n_eeg=n_eeg)
    else:
        print epochs_eog, n_grad, n_mag, n_eeg
        projs_eog = mne.compute_proj_epochs(epochs_eog,
                                            n_grad=n_grad,
                                            n_mag=n_mag,
                                            n_eeg=n_eeg)

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

    return in_fif_fname, eog_proj_fname, out_fif_fname
コード例 #25
0
def compute_proj_ecg(in_fif_fname, tmin, tmax, n_grad, n_mag, n_eeg, l_freq,
                     h_freq, average, preload, filter_length, n_jobs, ch_name,
                     reject, avg_ref, bads):
    """Compute SSP/PCA projections for ECG artifacts

    Parameters
    ----------
    in_fif_fname: string
        Raw fif File
    XXX
    """
    # Reading fif File
    raw = mne.fiff.Raw(in_fif_fname, preload=preload)

    if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'):
        prefix = in_fif_fname[:-8]
    else:
        prefix = in_fif_fname[:-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'

    print 'Running ECG SSP computation'

    ecg_events, _, _ = mne.artifacts.find_ecg_events(raw, ch_name=ch_name)
    print "Writing ECG events in %s" % ecg_event_fname
    mne.write_events(ecg_event_fname, ecg_events)

    if avg_ref:
        print "Adding average EEG reference projection."
        eeg_proj = mne.fiff.proj.make_eeg_average_ref_proj(raw.info)
        raw.info['projs'].append(eeg_proj)

    print 'Computing ECG projector'

    # Handler rejection parameters
    if len(mne.fiff.pick_types(raw.info, meg='grad', eeg=False, eog=False)) == 0:
        del reject['grad']
    if len(mne.fiff.pick_types(raw.info, meg='mag', eeg=False, eog=False)) == 0:
        del reject['mag']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=True, eog=False)) == 0:
        del reject['eeg']
    if len(mne.fiff.pick_types(raw.info, meg=False, eeg=False, eog=True)) == 0:
        del reject['eog']

    picks = mne.fiff.pick_types(raw.info, meg=True, eeg=True, eog=True,
                                exclude=raw.info['bads'] + bads)
    if l_freq is None and h_freq is not None:
        raw.high_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is None:
        raw.low_pass_filter(picks, h_freq, filter_length, n_jobs)
    if l_freq is not None and h_freq is not None:
        raw.band_pass_filter(picks, l_freq, h_freq, filter_length, n_jobs)

    epochs = mne.Epochs(raw, ecg_events, None, tmin, tmax, baseline=None,
                        picks=picks, reject=reject, proj=True)

    projs_init = raw.info['projs']

    if average:
        evoked = epochs.average()
        projs = mne.compute_proj_evoked(evoked, n_grad=n_grad, n_mag=n_mag,
                                        n_eeg=n_eeg)
    else:
        projs = mne.compute_proj_epochs(epochs, n_grad=n_grad, n_mag=n_mag,
                                        n_eeg=n_eeg)

    if preload is not None and os.path.exists(preload):
        os.remove(preload)

    print "Writing ECG projections in %s" % ecg_proj_fname
    mne.write_proj(ecg_proj_fname, projs + projs_init)
    print 'Done.'
コード例 #26
0
ファイル: test_proj.py プロジェクト: jhouck/mne-python
def test_compute_proj_epochs():
    """Test SSP computation on epochs."""
    tempdir = _TempDir()
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                       exclude=[])
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, 'test-proj.fif.gz'), projs)
    for p_fname in [proj_fname, proj_gz_fname,
                    op.join(tempdir, 'test-proj.fif.gz')]:
        projs2 = read_proj(p_fname)

        assert len(projs) == len(projs2)

        for p1, p2 in zip(projs, projs2):
            assert p1['desc'] == p2['desc']
            assert p1['data']['col_names'] == p2['data']['col_names']
            assert p1['active'] == p2['active']
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)
            if p2['explained_var']:
                assert_array_almost_equal(p1['explained_var'],
                                          p2['explained_var'])

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert nproj == 2
    assert U.shape[1] == 2

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'foo-ave.fif'))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert len(projs_evoked) == 2
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1,
                                desc_prefix='foobar')
    assert all('foobar' in x['desc'] for x in projs)
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)

    # test warnings on bad filenames
    proj_badname = op.join(tempdir, 'test-bad-name.fif.gz')
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        write_proj(proj_badname, projs)
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        read_proj(proj_badname)