def label_psd(epoch_vector, fs=None):
    '''Calculate the source level power spectral density from the label epochs'''
    # from scipy.signal import welch
    # freq_bins, epoch_spectra =  welch(epoch_vector, fs=fs, window='hanning') 
    
    from mne.time_frequency.multitaper import psd_array_multitaper
    epoch_spectra, freq_bins = psd_array_multitaper(epoch_vector, 
                                                    fs, 
                                                    fmin=1, fmax=45,
                                                    bandwidth=2, 
                                                    n_jobs=1, 
                                                    adaptive=True, 
                                                    low_bias=True) 
    
    return freq_bins, np.median(epoch_spectra, axis=0) 
Beispiel #2
0
def test_source_psd_epochs():
    """Test multi-taper source PSD computation in label from epochs."""
    raw = read_raw_fif(fname_data)
    inverse_operator = read_inverse_operator(fname_inv)
    label = read_label(fname_label)

    event_id, tmin, tmax = 1, -0.2, 0.5
    lambda2, method = 1. / 9., 'dSPM'
    bandwidth = 8.
    fmin, fmax = 0, 100

    picks = pick_types(raw.info,
                       meg=True,
                       eeg=False,
                       stim=True,
                       ecg=True,
                       eog=True,
                       include=['STI 014'],
                       exclude='bads')
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

    events = find_events(raw, stim_channel='STI 014')
    epochs = Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=(None, 0),
                    reject=reject)

    # only look at one epoch
    epochs.drop_bad()
    one_epochs = epochs[:1]

    inv = prepare_inverse_operator(inverse_operator,
                                   nave=1,
                                   lambda2=1. / 9.,
                                   method="dSPM")
    # return list
    stc_psd = compute_source_psd_epochs(one_epochs,
                                        inv,
                                        lambda2=lambda2,
                                        method=method,
                                        pick_ori="normal",
                                        label=label,
                                        bandwidth=bandwidth,
                                        fmin=fmin,
                                        fmax=fmax,
                                        prepared=True)[0]

    # return generator
    stcs = compute_source_psd_epochs(one_epochs,
                                     inv,
                                     lambda2=lambda2,
                                     method=method,
                                     pick_ori="normal",
                                     label=label,
                                     bandwidth=bandwidth,
                                     fmin=fmin,
                                     fmax=fmax,
                                     return_generator=True,
                                     prepared=True)

    for stc in stcs:
        stc_psd_gen = stc

    assert_array_almost_equal(stc_psd.data, stc_psd_gen.data)

    # compare with direct computation
    stc = apply_inverse_epochs(one_epochs,
                               inv,
                               lambda2=lambda2,
                               method=method,
                               pick_ori="normal",
                               label=label,
                               prepared=True)[0]

    sfreq = epochs.info['sfreq']
    psd, freqs = psd_array_multitaper(stc.data,
                                      sfreq=sfreq,
                                      bandwidth=bandwidth,
                                      fmin=fmin,
                                      fmax=fmax)

    assert_array_almost_equal(psd, stc_psd.data)
    assert_array_almost_equal(freqs, stc_psd.times)

    # Check corner cases caused by tiny bandwidth
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        compute_source_psd_epochs(one_epochs,
                                  inv,
                                  lambda2=lambda2,
                                  method=method,
                                  pick_ori="normal",
                                  label=label,
                                  bandwidth=0.01,
                                  low_bias=True,
                                  fmin=fmin,
                                  fmax=fmax,
                                  return_generator=False,
                                  prepared=True)
        compute_source_psd_epochs(one_epochs,
                                  inv,
                                  lambda2=lambda2,
                                  method=method,
                                  pick_ori="normal",
                                  label=label,
                                  bandwidth=0.01,
                                  low_bias=False,
                                  fmin=fmin,
                                  fmax=fmax,
                                  return_generator=False,
                                  prepared=True)
    assert_true(len(w) >= 2)
    assert_true(any('not properly use' in str(ww.message) for ww in w))
    assert_true(any('Bandwidth too small' in str(ww.message) for ww in w))
Beispiel #3
0
def test_source_psd_epochs(method):
    """Test multi-taper source PSD computation in label from epochs."""
    raw = read_raw_fif(fname_data)
    inverse_operator = read_inverse_operator(fname_inv)
    label = read_label(fname_label)

    event_id, tmin, tmax = 1, -0.2, 0.5
    lambda2 = 1. / 9.
    bandwidth = 8.
    fmin, fmax = 0, 100

    picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
                       ecg=True, eog=True, include=['STI 014'],
                       exclude='bads')
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

    events = find_events(raw, stim_channel='STI 014')
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject)

    # only look at one epoch
    epochs.drop_bad()
    one_epochs = epochs[:1]

    inv = prepare_inverse_operator(inverse_operator, nave=1,
                                   lambda2=1. / 9., method="dSPM")
    # return list
    stc_psd = compute_source_psd_epochs(one_epochs, inv,
                                        lambda2=lambda2, method=method,
                                        pick_ori="normal", label=label,
                                        bandwidth=bandwidth,
                                        fmin=fmin, fmax=fmax,
                                        prepared=True)[0]

    # return generator
    stcs = compute_source_psd_epochs(one_epochs, inv,
                                     lambda2=lambda2, method=method,
                                     pick_ori="normal", label=label,
                                     bandwidth=bandwidth,
                                     fmin=fmin, fmax=fmax,
                                     return_generator=True,
                                     prepared=True)

    for stc in stcs:
        stc_psd_gen = stc

    assert_allclose(stc_psd.data, stc_psd_gen.data, atol=1e-7)

    # compare with direct computation
    stc = apply_inverse_epochs(one_epochs, inv,
                               lambda2=lambda2, method=method,
                               pick_ori="normal", label=label,
                               prepared=True)[0]

    sfreq = epochs.info['sfreq']
    psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq,
                                      bandwidth=bandwidth, fmin=fmin,
                                      fmax=fmax)

    assert_allclose(psd, stc_psd.data, atol=1e-7)
    assert_allclose(freqs, stc_psd.times)

    # Check corner cases caused by tiny bandwidth
    with pytest.raises(ValueError, match='use a value of at least'):
        compute_source_psd_epochs(
            one_epochs, inv, lambda2=lambda2, method=method,
            pick_ori="normal", label=label, bandwidth=0.01, low_bias=True,
            fmin=fmin, fmax=fmax, return_generator=False, prepared=True)
Beispiel #4
0
average_random_phase_height_sorted = average_random_phase[position_sorted_indices, :, :]
std_random_phase_height_sorted = std_random_phase[position_sorted_indices, :, :]

average_modular_height_sorted = average_modular[position_sorted_indices, :, :]
std_modular_height_sorted = std_modular[position_sorted_indices, :, :]

average_amplitude_height_sorted = average_amplitude[position_sorted_indices, :, :]
std_amplitude_height_sorted = std_amplitude[position_sorted_indices, :, :]

# </editor-fold>


# -------------------------------------------------
# <editor-fold desc="VISUALISE">
psd_imf, fs = mt.psd_array_multitaper(imfs[:, :, :20000],
                                      sfreq=const_comm.SAMPLING_FREQUENCY/imf_subsampling_factor,
                                      fmin=1, fmax=3000, bandwidth=6, verbose=0)

peak_freqs = fs[np.argmax(psd_imf[:, :, :], axis=2)]
peak_freqs = np.mean(peak_freqs[:2, :], axis=0)


plt.figure(40)
plot_indices = np.arange(0, 12)
for i in plot_indices:
    plt.subplot(len(plot_indices), 1, i+1)
    plt.plot(fs, psd_imf[40, i, :])


show = [average_phase_height_sorted, std_phase_height_sorted]
min_imf_to_show = 13
def test_source_psd_epochs():
    """Test multi-taper source PSD computation in label from epochs."""
    raw = read_raw_fif(fname_data)
    inverse_operator = read_inverse_operator(fname_inv)
    label = read_label(fname_label)

    event_id, tmin, tmax = 1, -0.2, 0.5
    lambda2, method = 1. / 9., 'dSPM'
    bandwidth = 8.
    fmin, fmax = 0, 100

    picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
                       ecg=True, eog=True, include=['STI 014'],
                       exclude='bads')
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

    events = find_events(raw, stim_channel='STI 014')
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject)

    # only look at one epoch
    epochs.drop_bad()
    one_epochs = epochs[:1]

    inv = prepare_inverse_operator(inverse_operator, nave=1,
                                   lambda2=1. / 9., method="dSPM")
    # return list
    stc_psd = compute_source_psd_epochs(one_epochs, inv,
                                        lambda2=lambda2, method=method,
                                        pick_ori="normal", label=label,
                                        bandwidth=bandwidth,
                                        fmin=fmin, fmax=fmax,
                                        prepared=True)[0]

    # return generator
    stcs = compute_source_psd_epochs(one_epochs, inv,
                                     lambda2=lambda2, method=method,
                                     pick_ori="normal", label=label,
                                     bandwidth=bandwidth,
                                     fmin=fmin, fmax=fmax,
                                     return_generator=True,
                                     prepared=True)

    for stc in stcs:
        stc_psd_gen = stc

    assert_array_almost_equal(stc_psd.data, stc_psd_gen.data)

    # compare with direct computation
    stc = apply_inverse_epochs(one_epochs, inv,
                               lambda2=lambda2, method=method,
                               pick_ori="normal", label=label,
                               prepared=True)[0]

    sfreq = epochs.info['sfreq']
    psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq,
                                      bandwidth=bandwidth, fmin=fmin,
                                      fmax=fmax)

    assert_array_almost_equal(psd, stc_psd.data)
    assert_array_almost_equal(freqs, stc_psd.times)

    # Check corner cases caused by tiny bandwidth
    with pytest.raises(ValueError, match='use a value of at least'):
        compute_source_psd_epochs(
            one_epochs, inv, lambda2=lambda2, method=method,
            pick_ori="normal", label=label, bandwidth=0.01, low_bias=True,
            fmin=fmin, fmax=fmax, return_generator=False, prepared=True)