Esempio n. 1
0
def test_dics_source_power():
    """Test old DICS source power computation."""
    raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()
    epochs.crop(0, None)
    reg = 0.05

    stc_source_power = dics_source_power(epochs.info, forward, noise_csd,
                                         data_csd, label=label, reg=reg)

    max_source_idx = np.argmax(stc_source_power.data)
    max_source_power = np.max(stc_source_power.data)

    # TODO: Maybe these could be more directly compared to dics() results?
    assert max_source_idx == 1
    assert 0.004 < max_source_power < 0.005

    # Test picking normal orientation
    stc_normal = dics_source_power(epochs.info, forward_surf_ori, noise_csd,
                                   data_csd, pick_ori="normal", label=label,
                                   reg=reg)
    assert stc_normal.data.shape == stc_source_power.data.shape

    # The normal orientation results should always be smaller than free
    # orientation results
    assert (np.abs(stc_normal.data) <= stc_source_power.data).all()

    # Test if fixed forward operator is detected when picking normal
    # orientation
    raises(ValueError, dics_source_power, raw.info, forward_fixed, noise_csd,
           data_csd, pick_ori="normal")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    raises(ValueError, dics_source_power, raw.info, forward, noise_csd,
           data_csd, pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    raises(ValueError, dics_source_power, epochs.info, forward_vol, noise_csd,
           data_csd, pick_ori="normal")

    # Test detection of different frequencies in noise and data CSD objects
    noise_csd.frequencies = [1, 2]
    data_csd.frequencies = [1, 2, 3]
    raises(ValueError, dics_source_power, epochs.info, forward, noise_csd,
           data_csd)

    # Test detection of uneven frequency spacing
    data_csd.frequencies = [1, 3, 4]
    data_csd._data = data_csd._data.repeat(3, axis=1)
    noise_csd = data_csd
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        dics_source_power(epochs.info, forward, noise_csd, data_csd)
    assert len(w) == 2  # Also deprecation warning
Esempio n. 2
0
    fname = out_dir + '%s_%s_LCMV_blank_clean' % (subj, conds[c])
    stc.save(fname)
    stc = lcmv(evoked_ds[c], forward, cov_base, data_cov, reg=0.01,
               pick_ori='max-power')
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    fname = out_dir + '%s_%s_LCMV_base_clean' % (subj, conds[c])
    stc.save(fname)

    # finally, compute DICS per band
    for band in bands:
        data_csd = compute_epochs_csd(epochs[conds[c]], mode='multitaper',
                                      tmin=tmin, tmax=tmax + btmax,
                                      fmin=band[0], fmax=band[1])
        noise_csd = compute_epochs_csd(epochs[conds[c]], mode='multitaper',
                                       tmin=btmin, tmax=btmax,
                                       fmin=band[0], fmax=band[1])
        stc = dics(evoked[c], forward, noise_csd, data_csd)
        stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                         vertices_to, morph_mat)
        stc.resample(20)
        fname = out_dir + '%s_%s_DICSevoked_%dto%d_clean' % (subj, conds[c],
                                                       band[0], band[1])
        stc.save(fname)
        stc = dics_source_power(epochs.info, forward, noise_csd, data_csd)
        stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                         vertices_to, morph_mat)
        fname = out_dir + '%s_%s_DICSepochs_%dto%d_clean' % (subj, conds[c],
                                                       band[0], band[1])
        stc.save(fname)
Esempio n. 3
0
def test_tf_dics():
    """Test TF beamforming based on DICS
    """
    tmin, tmax, tstep = -0.2, 0.2, 0.1
    raw, epochs, _, _, _, label, forward, _, _, _ =\
        _get_data(tmin, tmax, read_all_forward=False, compute_csds=False)

    freq_bins = [(4, 20), (30, 55)]
    win_lengths = [0.2, 0.2]
    reg = 0.001

    noise_csds = []
    for freq_bin, win_length in zip(freq_bins, win_lengths):
        noise_csd = csd_epochs(epochs, mode='fourier',
                               fmin=freq_bin[0], fmax=freq_bin[1],
                               fsum=True, tmin=tmin,
                               tmax=tmin + win_length)
        noise_csds.append(noise_csd)

    stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths,
                   freq_bins, reg=reg, label=label)

    assert_true(len(stcs) == len(freq_bins))
    assert_true(stcs[0].shape[1] == 4)

    # Manually calculating source power in several time windows to compare
    # results and test overlapping
    source_power = []
    time_windows = [(-0.1, 0.1), (0.0, 0.2)]
    for time_window in time_windows:
        data_csd = csd_epochs(epochs, mode='fourier',
                              fmin=freq_bins[0][0],
                              fmax=freq_bins[0][1], fsum=True,
                              tmin=time_window[0], tmax=time_window[1])
        noise_csd = csd_epochs(epochs, mode='fourier',
                               fmin=freq_bins[0][0],
                               fmax=freq_bins[0][1], fsum=True,
                               tmin=-0.2, tmax=0.0)
        data_csd.data /= data_csd.n_fft
        noise_csd.data /= noise_csd.n_fft
        stc_source_power = dics_source_power(epochs.info, forward, noise_csd,
                                             data_csd, reg=reg, label=label)
        source_power.append(stc_source_power.data)

    # Averaging all time windows that overlap the time period 0 to 100 ms
    source_power = np.mean(source_power, axis=0)

    # Selecting the first frequency bin in tf_dics results
    stc = stcs[0]

    # Comparing tf_dics results with dics_source_power results
    assert_array_almost_equal(stc.data[:, 2], source_power[:, 0])

    # Test if using unsupported max-power orientation is detected
    assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax,
                  tstep, win_lengths, freq_bins=freq_bins,
                  pick_ori='max-power')

    # Test if incorrect number of noise CSDs is detected
    assert_raises(ValueError, tf_dics, epochs, forward, [noise_csds[0]], tmin,
                  tmax, tstep, win_lengths, freq_bins=freq_bins)

    # Test if freq_bins and win_lengths incompatibility is detected
    assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax,
                  tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins)

    # Test if time step exceeding window lengths is detected
    assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax,
                  tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins)

    # Test if incorrect number of mt_bandwidths is detected
    assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax,
                  tstep, win_lengths, freq_bins, mode='multitaper',
                  mt_bandwidths=[20])

    # Pass only one epoch to test if subtracting evoked responses yields zeros
    stcs = tf_dics(epochs[0], forward, noise_csds, tmin, tmax, tstep,
                   win_lengths, freq_bins, subtract_evoked=True, reg=reg,
                   label=label)

    assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
Esempio n. 4
0
def test_dics_source_power():
    """Test DICS source power computation
    """
    raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    stc_source_power = dics_source_power(epochs.info, forward, noise_csd,
                                         data_csd, label=label)

    max_source_idx = np.argmax(stc_source_power.data)
    max_source_power = np.max(stc_source_power.data)

    # TODO: Maybe these could be more directly compared to dics() results?
    assert_true(max_source_idx == 0)
    assert_true(0.5 < max_source_power < 1.15)

    # Test picking normal orientation and using a list of CSD matrices
    stc_normal = dics_source_power(epochs.info, forward_surf_ori,
                                   [noise_csd] * 2, [data_csd] * 2,
                                   pick_ori="normal", label=label)

    assert_true(stc_normal.data.shape == (stc_source_power.data.shape[0], 2))

    # The normal orientation results should always be smaller than free
    # orientation results
    assert_true((np.abs(stc_normal.data[:, 0]) <=
                 stc_source_power.data[:, 0]).all())

    # Test if fixed forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError, dics_source_power, raw.info, forward_fixed,
                  noise_csd, data_csd, pick_ori="normal")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError, dics_source_power, raw.info, forward, noise_csd,
                  data_csd, pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError, dics_source_power, epochs.info, forward_vol,
                  noise_csd, data_csd, pick_ori="normal")

    # Test detection of different number of CSD matrices provided
    assert_raises(ValueError, dics_source_power, epochs.info, forward,
                  [noise_csd] * 2, [data_csd] * 3)

    # Test detection of different frequencies in noise and data CSD objects
    noise_csd.frequencies = [1, 2]
    data_csd.frequencies = [1, 2, 3]
    assert_raises(ValueError, dics_source_power, epochs.info, forward,
                  noise_csd, data_csd)

    # Test detection of uneven frequency spacing
    data_csds = [cp.deepcopy(data_csd) for i in range(3)]
    frequencies = [1, 3, 4]
    for freq, data_csd in zip(frequencies, data_csds):
        data_csd.frequencies = [freq]
    noise_csds = data_csds
    with warnings.catch_warnings(record=True) as w:
        dics_source_power(epochs.info, forward, noise_csds, data_csds)
    assert len(w) == 1
# Read epochs
event_id, tmin, tmax = 1, -0.2, 0.5
events = mne.read_events(event_fname)
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))
evoked = epochs.average()

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

# Computing the data and noise cross-spectral density matrices
# The time-frequency window was chosen on the basis of spectrograms from
# example time_frequency/plot_time_frequency.py
# We use Morlet wavelets to estimate the CSD for two specific frequencies.
data_csds = csd_morlet(epochs, tmin=0.04, tmax=0.15, frequencies=[18, 27])
noise_csds = csd_morlet(epochs, tmin=-0.11, tmax=-0.001, frequencies=[18, 27])

# Compute DICS spatial filter and estimate source power
stc = dics_source_power(epochs.info, forward, noise_csds, data_csds)

# Plot the power maps at both frequencies
for i, freq in enumerate(data_csds.frequencies):
    message = 'DICS source power at %0.1f Hz' % freq
    brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir,
                     time_label=message, figure=i)
    brain.set_data_time_index(i)
    brain.show_view('lateral')
    # Uncomment line below to save images
    # brain.save_image('DICS_source_power_freq_%d.png' % csd.freqs[0])
Esempio n. 6
0
    stc20.save(stc20_fname, ftype='stc')

    ##40 hz#######################################################
    data_csd40 = csd_epochs(epochs40,
                            mode='multitaper',
                            tmin=0.01,
                            tmax=0.50,
                            fmin=35,
                            fmax=45)
    noise_csd40 = csd_epochs(epochs40,
                             mode='multitaper',
                             tmin=-0.49,
                             tmax=0.00,
                             fmin=35,
                             fmax=45)
    stc40_2 = dics_source_power(epochs40.info, fwd40, noise_csd40, data_csd40)
    # Compute DICS spatial filter and estimate source power
    stc40_3 = dics(evoked40, fwd40, noise_csd40, data_csd40, reg=0.05)

    stc40_2.save(stc40_fname2, ftype='stc')
    stc40_3.save(stc40_fname3, ftype='stc')
    ################################################################
    ####30 hz#######################################################
    data_csd30 = csd_epochs(epochs30,
                            mode='multitaper',
                            tmin=0.01,
                            tmax=0.50,
                            fmin=25,
                            fmax=35)
    noise_csd30 = csd_epochs(epochs30,
                             mode='multitaper',
def test_tf_dics():
    """Test TF beamforming based on DICS
    """
    tmin, tmax, tstep = -0.2, 0.2, 0.1
    raw, epochs, _, _, _, label, forward, _, _, _ =\
        _get_data(tmin, tmax, read_all_forward=False, compute_csds=False)

    freq_bins = [(4, 20), (30, 55)]
    win_lengths = [0.2, 0.2]
    reg = 0.001

    noise_csds = []
    for freq_bin, win_length in zip(freq_bins, win_lengths):
        noise_csd = compute_epochs_csd(epochs,
                                       mode='fourier',
                                       fmin=freq_bin[0],
                                       fmax=freq_bin[1],
                                       fsum=True,
                                       tmin=tmin,
                                       tmax=tmin + win_length)
        noise_csds.append(noise_csd)

    stcs = tf_dics(epochs,
                   forward,
                   noise_csds,
                   tmin,
                   tmax,
                   tstep,
                   win_lengths,
                   freq_bins,
                   reg=reg,
                   label=label)

    assert_true(len(stcs) == len(freq_bins))
    assert_true(stcs[0].shape[1] == 4)

    # Manually calculating source power in several time windows to compare
    # results and test overlapping
    source_power = []
    time_windows = [(-0.1, 0.1), (0.0, 0.2)]
    for time_window in time_windows:
        data_csd = compute_epochs_csd(epochs,
                                      mode='fourier',
                                      fmin=freq_bins[0][0],
                                      fmax=freq_bins[0][1],
                                      fsum=True,
                                      tmin=time_window[0],
                                      tmax=time_window[1])
        noise_csd = compute_epochs_csd(epochs,
                                       mode='fourier',
                                       fmin=freq_bins[0][0],
                                       fmax=freq_bins[0][1],
                                       fsum=True,
                                       tmin=-0.2,
                                       tmax=0.0)
        data_csd.data /= data_csd.n_fft
        noise_csd.data /= noise_csd.n_fft
        stc_source_power = dics_source_power(epochs.info,
                                             forward,
                                             noise_csd,
                                             data_csd,
                                             reg=reg,
                                             label=label)
        source_power.append(stc_source_power.data)

    # Averaging all time windows that overlap the time period 0 to 100 ms
    source_power = np.mean(source_power, axis=0)

    # Selecting the first frequency bin in tf_dics results
    stc = stcs[0]

    # Comparing tf_dics results with dics_source_power results
    assert_array_almost_equal(stc.data[:, 2], source_power[:, 0])

    # Test if using unsupported max-power orientation is detected
    assert_raises(ValueError,
                  tf_dics,
                  epochs,
                  forward,
                  noise_csds,
                  tmin,
                  tmax,
                  tstep,
                  win_lengths,
                  freq_bins=freq_bins,
                  pick_ori='max-power')

    # Test if incorrect number of noise CSDs is detected
    assert_raises(ValueError,
                  tf_dics,
                  epochs,
                  forward, [noise_csds[0]],
                  tmin,
                  tmax,
                  tstep,
                  win_lengths,
                  freq_bins=freq_bins)

    # Test if freq_bins and win_lengths incompatibility is detected
    assert_raises(ValueError,
                  tf_dics,
                  epochs,
                  forward,
                  noise_csds,
                  tmin,
                  tmax,
                  tstep,
                  win_lengths=[0, 1, 2],
                  freq_bins=freq_bins)

    # Test if time step exceeding window lengths is detected
    assert_raises(ValueError,
                  tf_dics,
                  epochs,
                  forward,
                  noise_csds,
                  tmin,
                  tmax,
                  tstep=0.15,
                  win_lengths=[0.2, 0.1],
                  freq_bins=freq_bins)

    # Test if incorrect number of mt_bandwidths is detected
    assert_raises(ValueError,
                  tf_dics,
                  epochs,
                  forward,
                  noise_csds,
                  tmin,
                  tmax,
                  tstep,
                  win_lengths,
                  freq_bins,
                  mode='multitaper',
                  mt_bandwidths=[20])

    # Pass only one epoch to test if subtracting evoked responses yields zeros
    stcs = tf_dics(epochs[0],
                   forward,
                   noise_csds,
                   tmin,
                   tmax,
                   tstep,
                   win_lengths,
                   freq_bins,
                   subtract_evoked=True,
                   reg=reg,
                   label=label)

    assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
def test_dics_source_power():
    """Test DICS source power computation
    """
    raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    stc_source_power = dics_source_power(epochs.info,
                                         forward,
                                         noise_csd,
                                         data_csd,
                                         label=label)

    max_source_idx = np.argmax(stc_source_power.data)
    max_source_power = np.max(stc_source_power.data)

    # TODO: Maybe these could be more directly compared to dics() results?
    assert_true(max_source_idx == 0)
    assert_true(0.5 < max_source_power < 1.15)

    # Test picking normal orientation and using a list of CSD matrices
    stc_normal = dics_source_power(epochs.info,
                                   forward_surf_ori, [noise_csd] * 2,
                                   [data_csd] * 2,
                                   pick_ori="normal",
                                   label=label)

    assert_true(stc_normal.data.shape == (stc_source_power.data.shape[0], 2))

    # The normal orientation results should always be smaller than free
    # orientation results
    assert_true(
        (np.abs(stc_normal.data[:, 0]) <= stc_source_power.data[:, 0]).all())

    # Test if fixed forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  dics_source_power,
                  raw.info,
                  forward_fixed,
                  noise_csd,
                  data_csd,
                  pick_ori="normal")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError,
                  dics_source_power,
                  raw.info,
                  forward,
                  noise_csd,
                  data_csd,
                  pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  dics_source_power,
                  epochs.info,
                  forward_vol,
                  noise_csd,
                  data_csd,
                  pick_ori="normal")

    # Test detection of different number of CSD matrices provided
    assert_raises(ValueError, dics_source_power, epochs.info, forward,
                  [noise_csd] * 2, [data_csd] * 3)

    # Test detection of different frequencies in noise and data CSD objects
    noise_csd.frequencies = [1, 2]
    data_csd.frequencies = [1, 2, 3]
    assert_raises(ValueError, dics_source_power, epochs.info, forward,
                  noise_csd, data_csd)

    # Test detection of uneven frequency spacing
    data_csds = [cp.deepcopy(data_csd) for i in range(3)]
    frequencies = [1, 3, 4]
    for freq, data_csd in zip(frequencies, data_csds):
        data_csd.frequencies = [freq]
    noise_csds = data_csds
    with warnings.catch_warnings(record=True) as w:
        dics_source_power(epochs.info, forward, noise_csds, data_csds)
    assert len(w) == 1
Esempio n. 9
0
    else:
        label = avg_label[1].morph(subject_to=s)

    epochs_fname = home + '/data/meg/stop/parsed/%s_stop_parsed_matched_clean_BP1-100_DS300-epo.fif.gz' % s
    epochs = mne.read_epochs(epochs_fname, proj=True)
    fwd_fname = home + '/data/meg/stop/%s_task-5-fwd.fif' % s
    fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)

    # calculate source power estimates for the whole brain
    # quick hack in tmax ot make it the same length as btmax
    data_csds = compute_epochs_csd(epochs[cond], mode='multitaper',
                                   tmin=tmin, tmax=tmax + btmax,
                                   fmin=band[0], fmax=band[1],
                                   fsum=False)
    noise_csds = compute_epochs_csd(epochs[cond], mode='multitaper',
                                    tmin=btmin, tmax=btmax,
                                    fmin=band[0], fmax=band[1],
                                    fsum=False)
    stc = dics_source_power(epochs.info, fwd, noise_csds, data_csds)
    ts = mne.extract_label_time_course(stc, label, fwd['src'])
    data.append(ts)

# export one CSV file
fname = out_dir + '%s_%s_%02dto%02d_tmin%.2f.csv' % (cond, roi_pretty, band[0],
                                                     band[1], tmin)
fid = open(fname, 'w')
fid.write('subj,power\n')
for j, d in enumerate(data):
    fid.write('%s,' % subjs[j] + ','.join(['%e' % t for t in d[0]]) + '\n')
fid.close()
Esempio n. 10
0
def test_dics_source_power():
    """Test old DICS source power computation."""
    raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()
    epochs.crop(0, None)
    reg = 0.05

    stc_source_power = dics_source_power(epochs.info,
                                         forward,
                                         noise_csd,
                                         data_csd,
                                         label=label,
                                         reg=reg)

    max_source_idx = np.argmax(stc_source_power.data)
    max_source_power = np.max(stc_source_power.data)

    # TODO: Maybe these could be more directly compared to dics() results?
    assert max_source_idx == 1
    assert 0.004 < max_source_power < 0.005

    # Test picking normal orientation
    stc_normal = dics_source_power(epochs.info,
                                   forward_surf_ori,
                                   noise_csd,
                                   data_csd,
                                   pick_ori="normal",
                                   label=label,
                                   reg=reg)
    assert stc_normal.data.shape == stc_source_power.data.shape

    # The normal orientation results should always be smaller than free
    # orientation results
    assert (np.abs(stc_normal.data) <= stc_source_power.data).all()

    # Test if fixed forward operator is detected when picking normal
    # orientation
    raises(ValueError,
           dics_source_power,
           raw.info,
           forward_fixed,
           noise_csd,
           data_csd,
           pick_ori="normal")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    raises(ValueError,
           dics_source_power,
           raw.info,
           forward,
           noise_csd,
           data_csd,
           pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    raises(ValueError,
           dics_source_power,
           epochs.info,
           forward_vol,
           noise_csd,
           data_csd,
           pick_ori="normal")

    # Test detection of different frequencies in noise and data CSD objects
    noise_csd.frequencies = [1, 2]
    data_csd.frequencies = [1, 2, 3]
    raises(ValueError, dics_source_power, epochs.info, forward, noise_csd,
           data_csd)

    # Test detection of uneven frequency spacing
    data_csd.frequencies = [1, 3, 4]
    data_csd._data = data_csd._data.repeat(3, axis=1)
    noise_csd = data_csd
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        dics_source_power(epochs.info, forward, noise_csd, data_csd)
    assert len(w) == 1