Example #1
0
def make_phase_shuffled_surrogates_epochs(epochs, check_power=False):
    '''
    Make surrogate epochs using sklearn. Destroy phase information in each trial by randomization.
    The phases values are randomized in teh frequency domain.

    Parameters
    ----------
    Epochs Object.

    Output
    ------
    Surrogate Epochs object
    '''

    surrogate = epochs.copy()
    surr = surrogate.get_data()
    for trial in range(len(surrogate)):
        for channel in range(len(surrogate.ch_names)):
            surr[trial, channel, :] = randomize_phase(surr[trial, channel, :])
    surrogate._data = surr
    if check_power:
        from mne.time_frequency import compute_epochs_psd
        ps1, _ = compute_epochs_psd(epochs, epochs.picks)
        ps2, _ = compute_epochs_psd(surrogate, surrogate.picks)
        # np.array_equal does not pass the assertion, due to minor changes in power.
        assert np.allclose(ps1,
                           ps2), 'The power content does not match. Error.'

    return surrogate
Example #2
0
def make_phase_shuffled_surrogates_epochs(epochs, check_power=False):
    '''
    Make surrogate epochs using sklearn. Destroy phase information in each trial by randomization.
    The phases values are randomized in teh frequency domain.

    Parameters
    ----------
    Epochs Object.

    Output
    ------
    Surrogate Epochs object
    '''

    surrogate = epochs.copy()
    surr = surrogate.get_data()
    for trial in range(len(surrogate)):
        for channel in range(len(surrogate.ch_names)):
            surr[trial, channel, :] = randomize_phase(surr[trial, channel, :])
    surrogate._data = surr
    if check_power:
        from mne.time_frequency import compute_epochs_psd
        ps1, _ = compute_epochs_psd(epochs, epochs.picks)
        ps2, _ = compute_epochs_psd(surrogate, surrogate.picks)
        # np.array_equal does not pass the assertion, due to minor changes in power.
        assert np.allclose(ps1, ps2), 'The power content does not match. Error.'

    return surrogate
Example #3
0
def make_fftsurr_epochs(epochs, check_power=False):
    '''
    Make surrogate epochs using sklearn. Destroy each trial by shuffling the phase information.
    The shuffling is performed in the frequency domain only using fftsurr function from mlab.

    Parameters
    ----------
    Epochs Object.

    Output
    ------
    Surrogate Epochs object
    '''
    from matplotlib.mlab import fftsurr

    surrogate = epochs.copy()
    surr = surrogate.get_data()
    for trial in range(len(surrogate)):
        for channel in range(len(surrogate.ch_names)):
            surr[trial, channel, :] = fftsurr(surr[trial, channel, :])
    surrogate._data = surr
    if check_power:
        from mne.time_frequency import compute_epochs_psd
        ps1, _ = compute_epochs_psd(epochs, epochs.picks)
        ps2, _ = compute_epochs_psd(surrogate, surrogate.picks)
        assert np.allclose(ps1,
                           ps2), 'The power content does not match. Error.'

    return surrogate
Example #4
0
def make_fftsurr_epochs(epochs, check_power=False):
    '''
    Make surrogate epochs using sklearn. Destroy each trial by shuffling the phase information.
    The shuffling is performed in the frequency domain only using fftsurr function from mlab.

    Parameters
    ----------
    Epochs Object.

    Output
    ------
    Surrogate Epochs object
    '''
    from matplotlib.mlab import fftsurr

    surrogate = epochs.copy()
    surr = surrogate.get_data()
    for trial in range(len(surrogate)):
        for channel in range(len(surrogate.ch_names)):
            surr[trial, channel, :] = fftsurr(surr[trial, channel, :])
    surrogate._data = surr
    if check_power:
        from mne.time_frequency import compute_epochs_psd
        ps1, _ = compute_epochs_psd(epochs, epochs.picks)
        ps2, _ = compute_epochs_psd(surrogate, surrogate.picks)
        assert np.allclose(ps1, ps2), 'The power content does not match. Error.'

    return surrogate
Example #5
0
def test_psd_epochs():
    """Test PSD estimation on epochs
    """
    raw = io.Raw(raw_fname)

    exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053']  # bads + 2 more

    # picks MEG gradiometers
    picks = pick_types(raw.info, meg='mag', eeg=False, stim=False,
                       exclude=exclude)

    picks = picks[:2]

    n_fft = 512  # the FFT size (n_fft). Ideally a power of 2

    tmin, tmax, event_id = -0.5, 0.5, 1
    include = []
    raw.info['bads'] += ['MEG 2443']  # bads

    # picks MEG gradiometers
    picks = pick_types(raw.info, meg='grad', eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')

    events = read_events(event_fname)

    epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0),
                    reject=dict(grad=4000e-13, eog=150e-6), proj=False,
                    preload=True)

    tmin_full, tmax_full = -1, 1
    epochs_full = Epochs(raw, events[:10], event_id, tmax=tmax_full,
                         tmin=tmin_full, picks=picks,
                         baseline=(None, 0),
                         reject=dict(grad=4000e-13, eog=150e-6), proj=False,
                         preload=True)

    picks = pick_types(epochs.info, meg='grad', eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')
    psds, freqs = compute_epochs_psd(epochs[:1], fmin=2, fmax=300,
                                     n_fft=n_fft, picks=picks)

    psds_t, freqs_t = compute_epochs_psd(epochs_full[:1], fmin=2, fmax=300,
                                         tmin=tmin, tmax=tmax,
                                         n_fft=n_fft, picks=picks)
    # this one will fail if you add for example 0.1 to tmin
    assert_array_almost_equal(psds, psds_t, 27)

    psds_proj, _ = compute_epochs_psd(epochs[:1].apply_proj(), fmin=2,
                                      fmax=300, n_fft=n_fft, picks=picks)

    assert_array_almost_equal(psds, psds_proj)
    assert_true(psds.shape == (1, len(picks), len(freqs)))
    assert_true(np.sum(freqs < 0) == 0)
    assert_true(np.sum(psds < 0) == 0)
Example #6
0
def test_psd_epochs():
    """Test PSD estimation on epochs
    """
    raw = io.Raw(raw_fname)

    exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053']  # bads + 2 more

    # picks MEG gradiometers
    picks = pick_types(raw.info, meg='mag', eeg=False, stim=False,
                            exclude=exclude)

    picks = picks[:2]

    n_fft = 128  # the FFT size (n_fft). Ideally a power of 2

    tmin, tmax, event_id = -1, 1, 1
    include = []
    raw.info['bads'] += ['MEG 2443']  # bads

    # picks MEG gradiometers
    picks = pick_types(raw.info, meg='grad', eeg=False, eog=True,
                            stim=False, include=include, exclude='bads')

    events = read_events(event_fname)
    epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0),
                    reject=dict(grad=4000e-13, eog=150e-6), proj=False,
                    preload=True)

    picks = pick_types(epochs.info, meg='grad', eeg=False, eog=True,
                            stim=False, include=include, exclude='bads')
    psds, freqs = compute_epochs_psd(epochs[:1], fmin=2, fmax=300, n_fft=n_fft,
                                     picks=picks)
    psds_proj, _ = compute_epochs_psd(epochs[:1].apply_proj(), fmin=2,
                                      fmax=300, n_fft=n_fft, picks=picks)

    assert_array_almost_equal(psds, psds_proj)
    assert_true(psds.shape == (1, len(picks), len(freqs)))
    assert_true(np.sum(freqs < 0) == 0)
    assert_true(np.sum(psds < 0) == 0)
events = mne.read_events(event_fname)

tmin, tmax, event_id = -1., 1., 1
include = []
raw.info['bads'] += ['MEG 2443']  # bads

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

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, proj=True,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6))


n_fft = 256  # the FFT size. Ideally a power of 2
psds, freqs = compute_epochs_psd(epochs, fmin=2, fmax=200, n_fft=n_fft,
                                 n_jobs=2)

# average psds and save psds from first trial separately
average_psds = psds.mean(0)
average_psds = 10 * np.log10(average_psds)  # transform into dB
some_psds = 10 * np.log10(psds[12])


fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))

fig.suptitle('Single trial power', fontsize=12)

freq_mask = freqs < 150
freqs = freqs[freq_mask]

cmap = 'RdBu_r'
fig, ax = plt.subplots(1)
with FieldTripClient(host='localhost', port=1972,
                     tmax=150, wait_max=10) as rt_client:

    # get measurement info guessed by MNE-Python
    raw_info = rt_client.get_measurement_info()

    # select gradiometers
    picks = mne.pick_types(raw_info, meg='grad', eeg=False, eog=True,
                           stim=False, include=[], exclude=bads)

    n_fft = 256  # the FFT size. Ideally a power of 2
    n_samples = 2048  # time window on which to compute FFT
    for ii in range(20):
        epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks)
        psd, freqs = compute_epochs_psd(epoch, fmin=2, fmax=200, n_fft=n_fft)

        cmap = 'RdBu_r'
        freq_mask = freqs < 150
        freqs = freqs[freq_mask]
        log_psd = 10 * np.log10(psd[0])

        tmin = epoch.events[0][0] / raw_info['sfreq']
        tmax = (epoch.events[0][0] + n_samples) / raw_info['sfreq']

        if ii == 0:
            im = ax.imshow(log_psd[:, freq_mask].T, aspect='auto',
                           origin='lower', cmap=cmap)

            ax.set_yticks(np.arange(0, len(freqs), 10))
            ax.set_yticklabels(freqs[::10].round(1))
Example #9
0
                        exclude='bads')

epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    proj=True,
                    baseline=(None, 0),
                    reject=dict(grad=4000e-13, eog=150e-6))

n_fft = 256  # the FFT size. Ideally a power of 2
psds, freqs = compute_epochs_psd(epochs,
                                 fmin=2,
                                 fmax=200,
                                 n_fft=n_fft,
                                 n_jobs=2)

# average psds and save psds from first trial separately
average_psds = psds.mean(0)
average_psds = 10 * np.log10(average_psds)  # transform into dB
some_psds = 10 * np.log10(psds[12])

fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))

fig.suptitle('Single trial power', fontsize=12)

freq_mask = freqs < 150
freqs = freqs[freq_mask]
Example #10
0
    raw_info = rt_client.get_measurement_info()

    # select gradiometers
    picks = mne.pick_types(raw_info,
                           meg='grad',
                           eeg=False,
                           eog=True,
                           stim=False,
                           include=[],
                           exclude=bads)

    n_fft = 256  # the FFT size. Ideally a power of 2
    n_samples = 2048  # time window on which to compute FFT
    for ii in range(20):
        epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks)
        psd, freqs = compute_epochs_psd(epoch, fmin=2, fmax=200, n_fft=n_fft)

        cmap = 'RdBu_r'
        freq_mask = freqs < 150
        freqs = freqs[freq_mask]
        log_psd = 10 * np.log10(psd[0])

        tmin = epoch.events[0][0] / raw_info['sfreq']
        tmax = (epoch.events[0][0] + n_samples) / raw_info['sfreq']

        if ii == 0:
            im = ax.imshow(log_psd[:, freq_mask].T,
                           aspect='auto',
                           origin='lower',
                           cmap=cmap)