Esempio n. 1
0
def test_continuous_regression_with_overlap():
    """Test regression with overlap correction."""
    signal = np.zeros(100000)
    times = [1000, 2500, 3000, 5000, 5250, 7000, 7250, 8000]
    events = np.zeros((len(times), 3), int)
    events[:, 2] = 1
    events[:, 0] = times
    signal[events[:, 0]] = 1.
    effect = hann(101)
    signal = np.convolve(signal, effect)[:len(signal)]
    raw = RawArray(signal[np.newaxis, :], mne.create_info(1, 100, 'eeg'))

    assert_allclose(
        effect,
        linear_regression_raw(raw, events, {1: 1}, tmin=0)[1].data.flatten())

    # test that sklearn solvers can be used
    from sklearn.linear_model import ridge_regression

    def solver(X, y):
        return ridge_regression(X, y, alpha=0., solver="cholesky")

    assert_allclose(
        effect,
        linear_regression_raw(raw, events, tmin=0,
                              solver=solver)['1'].data.flatten())

    # test bad solvers
    def solT(X, y):
        return ridge_regression(X, y, alpha=0., solver="cholesky").T

    pytest.raises(ValueError, linear_regression_raw, raw, events, solver=solT)
    pytest.raises(ValueError, linear_regression_raw, raw, events, solver='err')
    pytest.raises(TypeError, linear_regression_raw, raw, events, solver=0)
Esempio n. 2
0
def test_continuous_regression_with_overlap():
    """Test regression with overlap correction."""
    signal = np.zeros(100000)
    times = [1000, 2500, 3000, 5000, 5250, 7000, 7250, 8000]
    events = np.zeros((len(times), 3), int)
    events[:, 2] = 1
    events[:, 0] = times
    signal[events[:, 0]] = 1.
    effect = hann(101)
    signal = np.convolve(signal, effect)[:len(signal)]
    raw = RawArray(signal[np.newaxis, :], mne.create_info(1, 100, 'eeg'))

    assert_allclose(effect, linear_regression_raw(
        raw, events, {1: 1}, tmin=0)[1].data.flatten())

    # test that sklearn solvers can be used
    from sklearn.linear_model.ridge import ridge_regression

    def solver(X, y):
        return ridge_regression(X, y, alpha=0.)
    assert_allclose(effect, linear_regression_raw(
        raw, events, tmin=0, solver=solver)['1'].data.flatten())

    # test bad solvers
    def solT(X, y):
        return ridge_regression(X, y, alpha=0.).T
    assert_raises(ValueError, linear_regression_raw, raw, events, solver=solT)
    assert_raises(ValueError, linear_regression_raw, raw, events, solver='err')
    assert_raises(TypeError, linear_regression_raw, raw, events, solver=0)
Esempio n. 3
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data."""
    tmin, tmax = -.1, .5

    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.apply_proj()
    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=None, reject=None)

    revokeds = linear_regression_raw(raw, events, event_id,
                                     tmin=tmin, tmax=tmax,
                                     reject=None)

    # Check that evokeds and revokeds are nearly equivalent
    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data, rtol=1e-15)

    # Test events that will lead to "duplicate" errors
    old_latency = events[1, 0]
    events[1, 0] = events[0, 0]
    assert_raises(ValueError, linear_regression_raw,
                  raw, events, event_id, tmin, tmax)

    events[1, 0] = old_latency
    events[:, 0] = range(len(events))
    assert_raises(ValueError, linear_regression_raw, raw,
                  events, event_id, tmin, tmax, decim=2)
Esempio n. 4
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data"""
    tmin, tmax = -.1, .5

    raw = mne.io.Raw(raw_fname, preload=True)
    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        baseline=None,
                        reject=None)

    revokeds = linear_regression_raw(raw,
                                     events,
                                     event_id,
                                     tmin=tmin,
                                     tmax=tmax,
                                     reject=None)

    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data, epochs[cond].average().data)
Esempio n. 5
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data"""
    tmin, tmax = -.1, .5

    raw = mne.io.Raw(raw_fname, preload=True)
    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=None, reject=None)

    revokeds = linear_regression_raw(raw, events, event_id,
                                     tmin=tmin, tmax=tmax,
                                     reject=None)

    # Check that evokeds and revokeds are nearly equivalent
    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data)

    # Test events that will lead to "duplicate" errors
    old_latency = events[1, 0]
    events[1, 0] = events[0, 0]
    assert_raises(ValueError, linear_regression_raw,
                  raw, events, event_id, tmin, tmax)

    events[1, 0] = old_latency
    events[:, 0] = range(len(events))
    assert_raises(ValueError, linear_regression_raw, raw,
                  events, event_id, tmin, tmax, decim=2)
Esempio n. 6
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data."""
    tmin, tmax = -.1, .5

    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.apply_proj()

    # a sampling of frequency where rounding and truncation yield
    # different results checks conversion from samples to times is
    # consistent across Epochs and linear_regression_raw
    with raw.info._unlock():
        raw.info['sfreq'] = 128

    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        baseline=None,
                        reject=None)

    revokeds = linear_regression_raw(raw,
                                     events,
                                     event_id,
                                     tmin=tmin,
                                     tmax=tmax,
                                     reject=None)

    # Check that evokeds and revokeds are nearly equivalent
    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data,
                        rtol=1e-15)

    # Test events that will lead to "duplicate" errors
    old_latency = events[1, 0]
    events[1, 0] = events[0, 0]
    pytest.raises(ValueError, linear_regression_raw, raw, events, event_id,
                  tmin, tmax)

    events[1, 0] = old_latency
    events[:, 0] = range(len(events))
    pytest.raises(ValueError,
                  linear_regression_raw,
                  raw,
                  events,
                  event_id,
                  tmin,
                  tmax,
                  decim=2)
Esempio n. 7
0
def test_continuous_regression_with_overlap():
    """Test regression with overlap correction"""
    signal = np.zeros(100000)
    times = [1000, 2500, 3000, 5000, 5250, 7000, 7250, 8000]
    events = np.zeros((len(times), 3), int)
    events[:, 2] = 1
    events[:, 0] = times
    signal[events[:, 0]] = 1.
    effect = hann(101)
    signal = np.convolve(signal, effect)[:len(signal)]
    raw = RawArray(signal[np.newaxis, :], mne.create_info(1, 100, 'eeg'))

    assert_allclose(effect,
                    linear_regression_raw(raw, events, {1: 1}, tmin=0)[1]
                    .data.flatten())
Esempio n. 8
0
def erp_regression(raw, events, event_id, tmin, tmax, reject, baseline):
    """This function processes the linear least-squares fitting of the 
    event-related potential of raw data
    Estimation of ERP compared to actual ERP"""

    from mne.stats.regression import linear_regression_raw
    # standard epoching
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        reject=None,
                        baseline=None,
                        preload=True)

    epochs.resample(150, npad='auto', n_jobs=1)

    evokeds = linear_regression_raw(raw,
                                    events=events,
                                    event_id=event_id,
                                    reject=None,
                                    tmin=tmin,
                                    tmax=tmax)
    # linear_regression_raw returns a dict of evokeds
    # select a condition similar to mne.Epochs objects

    cond = raw_input(
        "Please input the event ID you wish to plot the regression for: ")
    if cond in event_id == True:
        fig, (ax1, ax2, ax3) = fig.subplots(3, 1)
        params = dict(spatial_colors=True,
                      show=False,
                      ylim=dict(eeg=(-10, 10)))
        epochs[cond].average().plot(axes=ax1, **params)
        evokeds[cond].plot(axes=ax2, **params)
        contrast = mne.combine_evoked([evokeds[cond], -epochs[cond].average()],
                                      weights='equal')
        contrast.plot(axes=ax3, **params)
        ax1.set_title("Traditional averaging")
        ax2.set_title("rERF")
        ax3.set_title("Difference")
        plt.show()
Esempio n. 9
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data"""
    tmin, tmax = -.1, .5

    raw = mne.io.Raw(raw_fname, preload=True)
    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=None, reject=None)

    revokeds = linear_regression_raw(raw, events, event_id,
                                     tmin=tmin, tmax=tmax,
                                     reject=None)

    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data)
Esempio n. 10
0
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data."""
    tmin, tmax = -.1, .5

    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.apply_proj()

    # a sampling of frequency where rounding and truncation yield
    # different results checks conversion from samples to times is
    # consistent across Epochs and linear_regression_raw
    raw.info['sfreq'] = 128

    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=None, reject=None)

    revokeds = linear_regression_raw(raw, events, event_id,
                                     tmin=tmin, tmax=tmax,
                                     reject=None)

    # Check that evokeds and revokeds are nearly equivalent
    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data, rtol=1e-15)

    # Test events that will lead to "duplicate" errors
    old_latency = events[1, 0]
    events[1, 0] = events[0, 0]
    pytest.raises(ValueError, linear_regression_raw,
                  raw, events, event_id, tmin, tmax)

    events[1, 0] = old_latency
    events[:, 0] = range(len(events))
    pytest.raises(ValueError, linear_regression_raw, raw,
                  events, event_id, tmin, tmax, decim=2)
Esempio n. 11
0
                             tmax=tmax,
                             use_good_sensors=False)
    #  save_epochs_as_txt(epochs, os.path.join('pics', basename))

    fig, axes = plt.subplots(1, 1)
    raw.plot_sensors(show_names=True, axes=axes, show=False)
    fig.savefig(os.path.join('pics', basename + '_sensor.png'), dpi=300)

    fig, axes = plt.subplots(3, 1)
    plot_tasks_in_timeline(raw, epochs, axes=axes)
    fig.savefig(os.path.join('pics', basename + '_task.png'), dpi=600)

    evoked = epochs.average()
    evokeds = linear_regression_raw(raw,
                                    events=epochs.events,
                                    event_id=epochs.event_id,
                                    reject=None,
                                    tmin=tmin,
                                    tmax=tmax)
    for e in epochs.event_id.keys():
        print(e)
        fig, axes = plt.subplots(2, 1)
        fig, title = plot_evoked(evokeds[e], axes=axes[0:2], title=basename)
        fig.savefig(os.path.join('pics', title + e + '_ts_.png'), dpi=300)
    fig, axes = plt.subplots(2, 1)
    fig, title = plot_evoked(evoked, axes=axes[0:2], title=basename)
    fig.savefig(os.path.join('pics', title + '_ts_.png'), dpi=300)

    times = np.arange(0, 0.5, 0.05)
    fig, axes = plt.subplots(6, times.shape[0])
    idx = 0
    for e in epochs.event_id.keys():
Esempio n. 12
0
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    reject=None,
                    baseline=None,
                    preload=True,
                    verbose=False,
                    decim=4)

# rERF
evokeds = linear_regression_raw(raw,
                                events=events,
                                event_id=event_id,
                                reject=None,
                                tmin=tmin,
                                tmax=tmax,
                                decim=4)
# linear_regression_raw returns a dict of evokeds
# select conditions similarly to mne.Epochs objects

# plot both results
cond = "faces"
fig, (ax1, ax2) = plt.subplots(1, 2)
epochs[cond].average().plot(axes=ax1, show=False)
evokeds[cond].plot(axes=ax2, show=False)
ax1.set_title("Traditional averaging")
ax2.set_title("rERF")
plt.show()
raw = mne.io.Raw(raw_fname, preload=True)  # Take first run

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
raw.filter(1, 45, method='iir')

events = mne.find_events(raw, stim_channel='UPPT001')
event_id = dict(faces=1, scrambled=2)
tmin, tmax = -.1, .5

raw.pick_types(meg=True)

# regular epoching
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, reject=None,
                    baseline=None, preload=True, verbose=False, decim=4)

# rERF
evokeds = linear_regression_raw(raw, events=events, event_id=event_id,
                                reject=None, tmin=tmin, tmax=tmax,
                                decim=4)
# linear_regression_raw returns a dict of evokeds
# select conditions similarly to mne.Epochs objects

# plot both results
cond = "faces"
fig, (ax1, ax2) = plt.subplots(1, 2)
epochs[cond].average().plot(axes=ax1, show=False)
evokeds[cond].plot(axes=ax2, show=False)
ax1.set_title("Traditional averaging")
ax2.set_title("rERF")
plt.show()
Esempio n. 14
0
                                     (RG_UB_events['A_index'] > 0).values
                                 ).astype(int)
                RG_UB_events.loc[:, 'Intercept'] = 1

                RG_UB_keys = [
                    s + '_' + 'IDX' + str(index_splits.index(idx)) for s in
                    ['RG_UB_Auditory', 'RG_UB_Visual', 'RG_UB_Interaction']
                ]
                RG_UB_events2 = RG_UB_events[[
                    "stim_onset", "button_press", "Intercept"
                ]].astype(int).values
                RG_UB_covariates = RG_UB_events[RG_UB_keys]
                UB_RG = linear_regression_raw(raw_tsss_mc,
                                              events=RG_UB_events2,
                                              event_id={},
                                              covariates=RG_UB_covariates,
                                              tmin=-0.15,
                                              tmax=1.,
                                              reject=None)
                REG_list.extend([UB_RG[cond] for cond in RG_UB_keys])

                RG_LB_events = pd.concat([LB_A, LB_V, LB_AVC])
                RG_LB_events.loc[:, 'RG_LB_Auditory' + '_' + 'IDX' +
                                 str(index_splits.index(idx))] = (
                                     RG_LB_events['A_index'] >
                                     0).astype(int).values
                RG_LB_events.loc[:, 'RG_LB_Visual' + '_' + 'IDX' +
                                 str(index_splits.index(idx))] = (
                                     RG_LB_events['V_index'] >
                                     0).astype(int).values
                RG_LB_events.loc[:, 'RG_LB_Interaction' + '_' + 'IDX' +