Exemple #1
0
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True):
    """Read in real MEG data. Used to test deprecated dics_* functions."""
    """Read in data used in tests."""
    if read_all_forward:
        fwd_free, fwd_surf, fwd_fixed, fwd_vol, _ = _load_forward()
    label_fname = op.join(data_path, 'MEG', 'sample', 'labels', 'Aud-lh.label')
    label = mne.read_label(label_fname)
    events = mne.read_events(fname_event)[:10]
    raw = mne.io.read_raw_fif(fname_raw, preload=False)
    raw.add_proj([], remove_existing=True)  # we'll subselect so remove proj
    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=True,
                           eog=True,
                           exclude='bads',
                           selection=left_temporal_channels)

    # Read epochs
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        proj=True,
                        picks=picks,
                        baseline=(None, 0),
                        preload=True,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    epochs.resample(200, npad=0, n_jobs=2)
    evoked = epochs.average().crop(0, None)

    # Computing the data and noise cross-spectral density matrices
    if compute_csds:
        data_csd = csd_multitaper(epochs,
                                  tmin=0.045,
                                  tmax=None,
                                  fmin=8,
                                  fmax=12,
                                  bandwidth=72.72).sum()
        noise_csd = csd_multitaper(epochs,
                                   tmin=None,
                                   tmax=0,
                                   fmin=8,
                                   fmax=12,
                                   bandwidth=72.72).sum()
    else:
        data_csd, noise_csd = None, None

    return (raw, epochs, evoked, data_csd, noise_csd, label, fwd_free,
            fwd_surf, fwd_fixed, fwd_vol)
Exemple #2
0
def test_csd_multitaper():
    """Test computing cross-spectral density using multitapers."""
    epochs = _generate_coherence_data()
    sfreq = epochs.info['sfreq']
    _test_fourier_multitaper_parameters(epochs, csd_multitaper,
                                        csd_array_multitaper)

    # Compute CSDs using various parameters
    times = [(None, None), (1, 9)]
    as_arrays = [False, True]
    adaptives = [False, True]
    parameters = product(times, as_arrays, adaptives)
    for (tmin, tmax), as_array, adaptive in parameters:
        if as_array:
            csd = csd_array_multitaper(epochs.get_data(), sfreq, epochs.tmin,
                                       adaptive=adaptive, fmin=9, fmax=23,
                                       tmin=tmin, tmax=tmax,
                                       ch_names=epochs.ch_names)
        else:
            csd = csd_multitaper(epochs, adaptive=adaptive, fmin=9, fmax=23,
                                 tmin=tmin, tmax=tmax)
        if tmin is None and tmax is None:
            assert csd.tmin == 0 and csd.tmax == 9.98
        else:
            assert csd.tmin == tmin and csd.tmax == tmax
        csd = csd.mean([9.9, 14.9, 21.9], [10.1, 15.1, 22.1])
        _test_csd_matrix(csd)

    # Test equivalence with PSD
    psd, psd_freqs = psd_multitaper(epochs, fmin=1e-3,
                                    normalization='full')  # omit DC
    csd = csd_multitaper(epochs)
    assert_allclose(psd_freqs, csd.frequencies)
    csd = np.array([np.diag(csd.get_data(index=ii))
                    for ii in range(len(csd))]).T
    assert_allclose(psd[0], csd)

    # For the next test, generate a simple sine wave with a known power
    times = np.arange(20 * sfreq) / sfreq  # 20 seconds of signal
    signal = np.sin(2 * np.pi * 10 * times)[None, None, :]  # 10 Hz wave
    signal_power_per_sample = sum_squared(signal) / len(times)

    # Power per sample should not depend on time window length
    for tmax in [12, 18]:
        t_mask = (times <= tmax)
        n_samples = sum(t_mask)
        n_fft = len(times)

        # Power per sample should not depend on number of tapers
        for n_tapers in [1, 2, 5]:
            bandwidth = sfreq / float(n_samples) * (n_tapers + 1)
            csd_mt = csd_array_multitaper(signal, sfreq, tmax=tmax,
                                          bandwidth=bandwidth,
                                          n_fft=n_fft).sum().get_data()
            mt_power_per_sample = np.abs(csd_mt[0, 0]) * sfreq / n_fft
            assert abs(signal_power_per_sample - mt_power_per_sample) < 0.001
Exemple #3
0
def test_csd_multitaper():
    """Test computing cross-spectral density using multitapers."""
    epochs = _generate_coherence_data()
    sfreq = epochs.info['sfreq']
    _test_fourier_multitaper_parameters(epochs, csd_multitaper,
                                        csd_array_multitaper)

    # Compute CSDs using various parameters
    times = [(None, None), (1, 9)]
    as_arrays = [False, True]
    adaptives = [False, True]
    parameters = product(times, as_arrays, adaptives)
    for (tmin, tmax), as_array, adaptive in parameters:
        if as_array:
            csd = csd_array_multitaper(epochs.get_data(), sfreq, epochs.tmin,
                                       adaptive=adaptive, fmin=9, fmax=23,
                                       tmin=tmin, tmax=tmax,
                                       ch_names=epochs.ch_names)
        else:
            csd = csd_multitaper(epochs, adaptive=adaptive, fmin=9, fmax=23,
                                 tmin=tmin, tmax=tmax)
        if tmin is None and tmax is None:
            assert csd.tmin == 0 and csd.tmax == 9.98
        else:
            assert csd.tmin == tmin and csd.tmax == tmax
        csd = csd.mean([9.9, 14.9, 21.9], [10.1, 15.1, 22.1])
        _test_csd_matrix(csd)

    # Test equivalence with PSD
    psd, psd_freqs = psd_multitaper(epochs, fmin=1e-3,
                                    normalization='full')  # omit DC
    csd = csd_multitaper(epochs)
    assert_allclose(psd_freqs, csd.frequencies)
    csd = np.array([np.diag(csd.get_data(index=ii))
                    for ii in range(len(csd))]).T
    assert_allclose(psd[0], csd)

    # For the next test, generate a simple sine wave with a known power
    times = np.arange(20 * sfreq) / sfreq  # 20 seconds of signal
    signal = np.sin(2 * np.pi * 10 * times)[None, None, :]  # 10 Hz wave
    signal_power_per_sample = sum_squared(signal) / len(times)

    # Power per sample should not depend on time window length
    for tmax in [12, 18]:
        t_mask = (times <= tmax)
        n_samples = sum(t_mask)
        n_fft = len(times)

        # Power per sample should not depend on number of tapers
        for n_tapers in [1, 2, 5]:
            bandwidth = sfreq / float(n_samples) * (n_tapers + 1)
            csd_mt = csd_array_multitaper(signal, sfreq, tmax=tmax,
                                          bandwidth=bandwidth,
                                          n_fft=n_fft).sum().get_data()
            mt_power_per_sample = np.abs(csd_mt[0, 0]) * sfreq / n_fft
            assert abs(signal_power_per_sample - mt_power_per_sample) < 0.001
Exemple #4
0
def test_csd_multitaper():
    """Test computing cross-spectral density using multitapers."""
    epochs = _generate_coherence_data()
    sfreq = epochs.info['sfreq']
    _test_fourier_multitaper_parameters(epochs, csd_multitaper,
                                        csd_array_multitaper)

    # Compute CSDs using various parameters
    times = [(None, None), (1, 9)]
    as_arrays = [False, True]
    adaptives = [False, True]
    parameters = product(times, as_arrays, adaptives)
    for (tmin, tmax), as_array, adaptive in parameters:
        if as_array:
            csd = csd_array_multitaper(epochs.get_data(),
                                       sfreq,
                                       epochs.tmin,
                                       adaptive=adaptive,
                                       fmin=9,
                                       fmax=23,
                                       tmin=tmin,
                                       tmax=tmax)
        else:
            csd = csd_multitaper(epochs,
                                 adaptive=adaptive,
                                 fmin=9,
                                 fmax=23,
                                 tmin=tmin,
                                 tmax=tmax)
        csd = csd.mean([9.9, 14.9, 21.9], [10.1, 15.1, 22.1])
        _test_csd_matrix(csd)

    # For the next test, generate a simple sine wave with a known power
    times = np.arange(20 * sfreq) / sfreq  # 20 seconds of signal
    signal = np.sin(2 * np.pi * 10 * times)[None, None, :]  # 10 Hz wave
    signal_power_per_sample = sum_squared(signal) / len(times)

    # Power per sample should not depend on time window length
    for tmax in [12, 18]:
        t_mask = (times <= tmax)
        n_samples = sum(t_mask)
        n_fft = len(times)

        # Power per sample should not depend on number of tapers
        for n_tapers in [1, 2, 5]:
            bandwidth = sfreq / float(n_samples) * (n_tapers + 1)
            csd_mt = csd_array_multitaper(signal,
                                          sfreq,
                                          tmax=tmax,
                                          bandwidth=bandwidth,
                                          n_fft=n_fft).sum().get_data()
            mt_power_per_sample = np.abs(csd_mt[0, 0]) * sfreq / n_fft
            assert abs(signal_power_per_sample - mt_power_per_sample) < 0.001
Exemple #5
0
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True):
    """Read in real MEG data. Used to test deprecated dics_* functions."""
    """Read in data used in tests."""
    if read_all_forward:
        fwd_free, fwd_surf, fwd_fixed, fwd_vol, _ = _load_forward()
    label_fname = op.join(data_path, 'MEG', 'sample', 'labels', 'Aud-lh.label')
    label = mne.read_label(label_fname)
    events = mne.read_events(fname_event)[:10]
    raw = mne.io.read_raw_fif(fname_raw, preload=False)
    raw.add_proj([], remove_existing=True)  # we'll subselect so remove proj
    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info, meg=True, eeg=False,
                           stim=True, eog=True, exclude='bads',
                           selection=left_temporal_channels)

    # Read epochs
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        picks=picks, baseline=(None, 0), preload=True,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    epochs.resample(200, npad=0, n_jobs=2)
    evoked = epochs.average().crop(0, None)

    # Computing the data and noise cross-spectral density matrices
    if compute_csds:
        data_csd = csd_multitaper(epochs, tmin=0.045, tmax=None, fmin=8,
                                  fmax=12, bandwidth=72.72).sum()
        noise_csd = csd_multitaper(epochs, tmin=None, tmax=0, fmin=8, fmax=12,
                                   bandwidth=72.72).sum()
    else:
        data_csd, noise_csd = None, None

    return (raw, epochs, evoked, data_csd, noise_csd, label, fwd_free,
            fwd_surf, fwd_fixed, fwd_vol)
Exemple #6
0
# Make some epochs, based on events with trigger code 1
epochs = mne.Epochs(raw,
                    events,
                    event_id=1,
                    tmin=-0.2,
                    tmax=1,
                    picks=picks,
                    baseline=(None, 0),
                    reject=dict(grad=4000e-13),
                    preload=True)

###############################################################################
# Computing CSD matrices using short-term Fourier transform and (adaptive)
# multitapers is straightforward:
csd_fft = csd_fourier(epochs, fmin=15, fmax=20, n_jobs=n_jobs)
csd_mt = csd_multitaper(epochs, fmin=15, fmax=20, adaptive=True, n_jobs=n_jobs)

###############################################################################
# When computing the CSD with Morlet wavelets, you specify the exact
# frequencies at which to compute it. For each frequency, a corresponding
# wavelet will be constructed and convolved with the signal, resulting in a
# time-frequency decomposition.
#
# The CSD is constructed by computing the correlation between the
# time-frequency representations between all sensor-to-sensor pairs. The
# time-frequency decomposition originally has the same sampling rate as the
# signal, in our case ~600Hz. This means the decomposition is over-specified in
# time and we may not need to use all samples during our CSD computation, just
# enough to get a reliable correlation statistic. By specifying ``decim=10``,
# we use every 10th sample, which will greatly speed up the computation and
# will have a minimal effect on the CSD.
Exemple #7
0
def windowed_gcoh(Fs, wnd, slideby, X_cm, ch_w_ref, ch_picks, info, dpss_bw=7, dpss=None, f=None, findx=None):
    N       = X_cm.shape[0]

    ###  drop reference channel
    hf_wnd  = wnd//2

    _X    =_N.array(X_cm[:, ch_w_ref])

    ws = _N.hamming(21)
    ws /= _N.sum(ws)
    for i in range(_X.shape[1]):
        tx = _X[:, i]
        tp = _ssig.filtfilt(ws, 1, tx)
        _X[:, i] = _X[:, i] - tp

    X = _N.empty((1, _X.shape[1], _X.shape[0]))
    X[0] = _X.T
    #  params

    ns      = int(_N.round(X.shape[2]/slideby)) - wnd//slideby

    if dpss is None:
        dpss, eigvals, adaptive = mtf.multitaper._compute_mt_params(wnd, Fs, dpss_bw, True, True)
    #epochs = mne.EpochsArray(X, info)
    epochs = mne.EpochsArray(X[:, ch_picks], info)

    fMin = 5
    fMax = 50
    if f is None:
        f, findx = _chrf.getfgrid(Fs, wnd, [fMin, fMax])

        if len(_N.where(f == fMax)[0]) == 1:  #  csd treats lims as [fMin fMax)?
            findx = _N.array(findx[0:-1])

    n_picked_chs = len(ch_picks)
    EVS  = _N.empty((ns, len(findx), n_picked_chs, n_picked_chs), dtype=_N.complex)

    csd_all_freq = _N.empty((len(findx), n_picked_chs), dtype=_N.complex)

    dSv = _N.zeros((n_picked_chs, n_picked_chs))

    n_bins = (N - wnd) // slideby + 1

    Cvec   = _N.zeros((n_bins, len(findx), 2, n_picked_chs), dtype=_N.complex)
    Ctot   = _N.zeros((n_bins, len(findx)))


    for ni in range(n_bins):
        t0 = ni*slideby
        t1 = t0 + wnd

        X[0, t0:t1]
        print("%(0)d  %(1)d" % {"0" : t0, "1" : t1})

        csd = mtf.csd_multitaper(epochs, tmin=(t0/Fs), tmax=(t1/Fs), fmin=fMin, fmax=fMax, n_fft=wnd, bandwidth=dpss_bw, adaptive=False, low_bias=True, projs=None, n_jobs=1, verbose=False)

        for fi in range(len(findx)):
            csd_dat = csd.get_data(index=fi)
            U, Sv, Vh = _N.linalg.svd(csd_dat)
            #_N.fill_diagonal(dSv, Sv);
            Ctot[ni, fi]=Sv[0]**2/_N.sum(Sv**2)
            Cvec[ni, fi]=U[:,0:2].T

    return f, findx, Ctot, Cvec
Exemple #8
0
                    tmin,
                    tmax,
                    proj=True,
                    picks=picks,
                    baseline=(None, 0),
                    preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12))
evoked = epochs.average()

# Read forward operator
forward = mne.read_forward_solution(fname_fwd)

# Computing the data and noise cross-spectral density matrices using
# multitapers. The time-frequency window was chosen on the basis of
# spectrograms from example time_frequency/plot_time_frequency.py
data_csd = csd_multitaper(epochs, tmin=0.04, tmax=0.15, fmin=6, fmax=10)
noise_csd = csd_multitaper(epochs, tmin=-0.11, tmax=0.0, fmin=6, fmax=10)

# Average the CSDs across the frequencies
data_csd = data_csd.mean()
noise_csd = noise_csd.mean()

evoked = epochs.average()

# Compute DICS spatial filter and estimate source time courses on evoked data
stc = dics(evoked, forward, noise_csd, data_csd, reg=0.05)

plt.figure()
ts_show = -30  # show the 40 largest responses
plt.plot(1e3 * stc.times,
         stc.data[np.argsort(stc.data.max(axis=1))[ts_show:]].T)
Exemple #9
0
                                      meg=True,
                                      mindist=1.0,
                                      n_jobs=8)
    mne.write_forward_solution("{dir}nc_{meg}_4-fwd.fif".format(dir=meg_dir,
                                                                meg=meg),
                               fwd_b,
                               overwrite=True)

    # calculate DICS filters across all conditions
    # force-append epo_a+b only for calc csd here
    #override coil positions of block b with those of block a for concatenation (sensor level only!!)
    epo_b.info['dev_head_t'] = epo_a.info['dev_head_t']
    #concatenate data of both blocks
    epo = mne.concatenate_epochs([epo_a, epo_b])
    # calculate DICS filters across all conditions
    csd = csd_multitaper(epo, fmin=7, fmax=14, bandwidth=1)
    #csd = csd_multitaper(epo,fmin=7,fmax=14,bandwidth=1,adaptive=True)
    #csd = csd_morlet(epo, frequencies=freqs, n_jobs=8, n_cycles=7, decim=3)
    #filters_a = make_dics(epo_a.info,fwd_a,csd,pick_ori='max power',rank='full',weight_norm="unit-noise-gain",normalize_fwd=False,real_filter=True)
    filters_a = make_dics(epo_a.info,
                          fwd_a,
                          csd,
                          pick_ori=None,
                          rank='full',
                          weight_norm=None,
                          normalize_fwd=False,
                          real_filter=False)
    filters_b = make_dics(epo_b.info,
                          fwd_b,
                          csd,
                          pick_ori=None,
Exemple #10
0
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True):
    """Read in data used in tests."""
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)[:10]
    raw = mne.io.read_raw_fif(fname_raw, preload=False)
    raw.add_proj([], remove_existing=True)  # we'll subselect so remove proj
    forward = mne.read_forward_solution(fname_fwd)
    if read_all_forward:
        forward_surf_ori = _read_forward_solution_meg(fname_fwd, surf_ori=True)
        forward_fixed = _read_forward_solution_meg(fname_fwd,
                                                   force_fixed=True,
                                                   use_cps=False)
        forward_vol = mne.read_forward_solution(fname_fwd_vol)
        forward_vol = mne.convert_forward_solution(forward_vol, surf_ori=True)
    else:
        forward_surf_ori = None
        forward_fixed = None
        forward_vol = None

    event_id, tmin, tmax = 1, tmin, tmax

    # Setup for reading the raw data
    raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels

    # Set up pick list: MEG - bad channels
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=True,
                           eog=True,
                           exclude='bads',
                           selection=left_temporal_channels)

    # Read epochs
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        proj=True,
                        picks=picks,
                        baseline=(None, 0),
                        preload=True,
                        reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
    epochs.resample(200, npad=0, n_jobs=2)
    evoked = epochs.average().crop(0, None)

    # Computing the data and noise cross-spectral density matrices
    if compute_csds:
        data_csd = csd_multitaper(epochs,
                                  tmin=0.045,
                                  tmax=None,
                                  fmin=8,
                                  fmax=12,
                                  bandwidth=72.72)
        noise_csd = csd_multitaper(epochs,
                                   tmin=None,
                                   tmax=0.0,
                                   fmin=8,
                                   fmax=12,
                                   bandwidth=72.72)
    else:
        data_csd, noise_csd = None, None

    return raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
# interpreting a CSD matrix with mixed sensor types, be aware that the
# measurement units, and thus the scalings, differ across sensors. In this
# example, for speed and clarity, we select a single channel type:
# gradiometers.
picks = mne.pick_types(raw.info, meg='grad')

# Make some epochs, based on events with trigger code 1
epochs = mne.Epochs(raw, events, event_id=1, tmin=0, tmax=1,
                    picks=picks, baseline=(None, 0),
                    reject=dict(grad=4000e-13), preload=True)

###############################################################################
# Computing CSD matrices using short-term Fourier transform and (adaptive)
# multitapers is straightforward:
csd_fft = csd_fourier(epochs, fmin=15, fmax=20, n_jobs=n_jobs)
csd_mt = csd_multitaper(epochs, fmin=15, fmax=20, adaptive=True, n_jobs=n_jobs)

###############################################################################
# When computing the CSD with Morlet wavelets, you specify the exact
# frequencies at which to compute it. For each frequency, a corresponding
# wavelet will be constructed and convolved with the signal, resulting in a
# time-frequency decomposition.
#
# The CSD is constructed by computing the correlation between the
# time-frequency representations between all sensor-to-sensor pairs. The
# time-frequency decomposition originally has the same sampling rate as the
# signal, in our case ~600Hz. This means the decomposition is over-specified in
# time and we may not need to use all samples during our CSD computation, just
# enough to get a reliable correlation statistic. By specifying ``decim=10``,
# we use every 10th sample, which will greatly speed up the computation and
# will have a minimal effect on the CSD.