Exemple #1
0
def test_compute_epochs_csd_on_artificial_data():
    """Test computing CSD on artificial data
    """
    epochs, epochs_sin = _get_data()
    sfreq = epochs_sin.info['sfreq']

    # Computing signal power in the time domain
    signal_power = sum_squared(epochs_sin._data)
    signal_power_per_sample = signal_power / len(epochs_sin.times)

    # Computing signal power in the frequency domain
    data_csd_fourier = compute_epochs_csd(epochs_sin, mode='fourier')
    data_csd_mt = compute_epochs_csd(epochs_sin, mode='multitaper')
    fourier_power = np.abs(data_csd_fourier.data[0, 0]) * sfreq
    mt_power = np.abs(data_csd_mt.data[0, 0]) * sfreq
    assert_true(abs(fourier_power - signal_power) <= 0.5)
    assert_true(abs(mt_power - signal_power) <= 1)

    # Power per sample should not depend on time window length
    for tmax in [0.2, 0.4, 0.6, 0.8]:
        for add_n_fft in [30, 0, 30]:
            t_mask = (epochs_sin.times >= 0) & (epochs_sin.times <= tmax)
            n_samples = sum(t_mask)
            n_fft = n_samples + add_n_fft

            data_csd_fourier = compute_epochs_csd(epochs_sin,
                                                  mode='fourier',
                                                  tmin=None,
                                                  tmax=tmax,
                                                  fmin=0,
                                                  fmax=np.inf,
                                                  n_fft=n_fft)
            fourier_power_per_sample = np.abs(data_csd_fourier.data[0, 0]) *\
                sfreq / data_csd_fourier.n_fft
            assert_true(
                abs(signal_power_per_sample -
                    fourier_power_per_sample) < 0.003)
        # Power per sample should not depend on number of tapers
        for n_tapers in [1, 2, 3, 5]:
            for add_n_fft in [30, 0, 30]:
                mt_bandwidth = sfreq / float(n_samples) * (n_tapers + 1)
                data_csd_mt = compute_epochs_csd(epochs_sin,
                                                 mode='multitaper',
                                                 tmin=None,
                                                 tmax=tmax,
                                                 fmin=0,
                                                 fmax=np.inf,
                                                 mt_bandwidth=mt_bandwidth,
                                                 n_fft=n_fft)
                mt_power_per_sample = np.abs(data_csd_mt.data[0, 0]) *\
                    sfreq / data_csd_mt.n_fft
                # The estimate of power gets worse for small time windows when
                # more tapers are used
                if n_tapers == 5 and tmax == 0.2:
                    delta = 0.05
                else:
                    delta = 0.004
                assert_true(
                    abs(signal_power_per_sample - mt_power_per_sample) < delta)
Exemple #2
0
def test_compute_epochs_csd():
    """Test computing cross-spectral density from epochs
    """
    epochs, epochs_sin = _get_data()
    # Check that wrong parameters are recognized
    assert_raises(ValueError, compute_epochs_csd, epochs, mode="notamode")
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=20.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0.15, tmax=0.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0, tmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=10, tmax=11)

    data_csd_mt = compute_epochs_csd(epochs, mode="multitaper", fmin=8, fmax=12, tmin=0.04, tmax=0.15)
    data_csd_fourier = compute_epochs_csd(epochs, mode="fourier", fmin=8, fmax=12, tmin=0.04, tmax=0.15)

    # Check shape of the CSD matrix
    n_chan = len(data_csd_mt.ch_names)
    assert_equal(data_csd_mt.data.shape, (n_chan, n_chan))
    assert_equal(data_csd_fourier.data.shape, (n_chan, n_chan))

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(data_csd_mt.data).T.conj(), np.triu(data_csd_mt.data))
    assert_array_equal(np.tril(data_csd_fourier.data).T.conj(), np.triu(data_csd_fourier.data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    power, _ = induced_power(epochs.get_data(), epochs.info["sfreq"], [10], n_cycles=0.6)
    power = np.mean(power, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = data_csd_mt.data.diagonal().argmax()
    max_ch_fourier = data_csd_fourier.data.diagonal().argmax()
    assert_equal(max_ch_mt, max_ch_power)
    assert_equal(max_ch_fourier, max_ch_power)

    # Maximum CSD should occur for specific channel
    ch_csd_mt = [np.abs(data_csd_mt.data[max_ch_power][i]) if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = [np.abs(data_csd_fourier.data[max_ch_power][i]) if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert_equal(max_ch_csd_mt, max_ch_csd_fourier)

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    csd_fsum = compute_epochs_csd(epochs, mode="fourier", fmin=8, fmax=20, fsum=True)
    csds = compute_epochs_csd(epochs, mode="fourier", fmin=8, fmax=20, fsum=False)
    freqs = [csd.frequencies[0] for csd in csds]

    csd_sum = np.zeros_like(csd_fsum.data)
    for csd in csds:
        csd_sum += csd.data

    assert len(csds) == 2
    assert len(csd_fsum.frequencies) == 2
    assert_array_equal(csd_fsum.frequencies, freqs)
    assert_array_equal(csd_fsum.data, csd_sum)
Exemple #3
0
def test_compute_epochs_csd_on_artificial_data():
    """Test computing CSD on artificial data
    """
    epochs, epochs_sin = _get_data()
    sfreq = epochs_sin.info['sfreq']

    # Computing signal power in the time domain
    signal_power = sum_squared(epochs_sin._data)
    signal_power_per_sample = signal_power / len(epochs_sin.times)

    # Computing signal power in the frequency domain
    data_csd_fourier = compute_epochs_csd(epochs_sin, mode='fourier')
    data_csd_mt = compute_epochs_csd(epochs_sin, mode='multitaper')
    fourier_power = np.abs(data_csd_fourier.data[0, 0]) * sfreq
    mt_power = np.abs(data_csd_mt.data[0, 0]) * sfreq
    assert_almost_equal(fourier_power, signal_power, delta=0.5)
    assert_almost_equal(mt_power, signal_power, delta=1)

    # Power per sample should not depend on time window length
    for tmax in [0.2, 0.4, 0.6, 0.8]:
        for add_n_fft in [30, 0, 30]:
            t_mask = (epochs_sin.times >= 0) & (epochs_sin.times <= tmax)
            n_samples = sum(t_mask)
            n_fft = n_samples + add_n_fft

            data_csd_fourier = compute_epochs_csd(epochs_sin, mode='fourier',
                                                  tmin=None, tmax=tmax, fmin=0,
                                                  fmax=np.inf, n_fft=n_fft)
            fourier_power_per_sample = np.abs(data_csd_fourier.data[0, 0]) *\
                sfreq / data_csd_fourier.n_fft
            assert_almost_equal(signal_power_per_sample,
                                fourier_power_per_sample, delta=0.003)

        # Power per sample should not depend on number of tapers
        for n_tapers in [1, 2, 3, 5]:
            for add_n_fft in [30, 0, 30]:
                mt_bandwidth = sfreq / float(n_samples) * (n_tapers + 1)
                data_csd_mt = compute_epochs_csd(epochs_sin, mode='multitaper',
                                                 tmin=None, tmax=tmax, fmin=0,
                                                 fmax=np.inf,
                                                 mt_bandwidth=mt_bandwidth,
                                                 n_fft=n_fft)
                mt_power_per_sample = np.abs(data_csd_mt.data[0, 0]) *\
                    sfreq / data_csd_mt.n_fft
                # The estimate of power gets worse for small time windows when
                # more tapers are used
                if n_tapers == 5 and tmax == 0.2:
                    delta = 0.05
                else:
                    delta = 0.004
                assert_almost_equal(signal_power_per_sample,
                                    mt_power_per_sample, delta=delta)
Exemple #4
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,
                                                  surf_ori=True)
        forward_vol = mne.read_forward_solution(fname_fwd_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()

    # Computing the data and noise cross-spectral density matrices
    if compute_csds:
        data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=0.045,
                                      tmax=None, fmin=8, fmax=12,
                                      mt_bandwidth=72.72)
        noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=None,
                                       tmax=0.0, fmin=8, fmax=12,
                                       mt_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
Exemple #5
0
def read_data():
    """Read in data used in tests
    """
    label = mne.read_label(fname_label)
    events = mne.read_events(fname_event)[:10]
    raw = mne.fiff.Raw(fname_raw, preload=False)
    forward = mne.read_forward_solution(fname_fwd)
    forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True)
    forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True,
                                              surf_ori=True)
    forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True)

    event_id, tmin, tmax = 1, -0.11, 0.15

    # 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.fiff.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()

    # Computing the data and noise cross-spectral density matrices
    data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=0.04,
                                  tmax=None, fmin=8, fmax=12)
    noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=None,
                                   tmax=0.0, fmin=8, fmax=12)

    return raw, epochs, evoked, data_csd, noise_csd, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol
# Then set FFTs length for each frequency range.
# Should be a power of 2 to be faster.
n_ffts = [256, 128, 128, 128]

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating noise cross-spectral density from empty room noise for each
# frequency bin and the corresponding time window length. To calculate noise
# from the baseline period in the data, change epochs_noise to epochs
noise_csds = []
for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts):
    noise_csd = compute_epochs_csd(epochs_noise,
                                   mode='fourier',
                                   fmin=freq_bin[0],
                                   fmax=freq_bin[1],
                                   fsum=True,
                                   tmin=-win_length,
                                   tmax=0,
                                   n_fft=n_fft)
    noise_csds.append(noise_csd)

# Computing DICS solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_dics(epochs,
               forward,
               noise_csds,
               tmin,
               tmax,
               tstep,
               win_lengths,
               freq_bins=freq_bins,
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 DICS_inverse(fn_epo, event_id=1,event='LLst', ctmin=0.05, ctmax=0.25, fmin=4, fmax=8, 
                  min_subject='fsaverage'):
    """
    Inverse evokes into source space using DICS method.
    ----------
    fn_epo : epochs of raw data.
    event_id: event id related with epochs.
    ctmin: the min time for computing CSD
    ctmax: the max time for computing CSD
    fmin: min value of the interest frequency band
    fmax: max value of the interest frequency band 
    min_subject: the subject for the common brain space.
    save_forward: Whether save the forward solution or not.
    """
    from mne import Epochs, pick_types
    from mne.io import Raw
    from mne.event import make_fixed_length_events
    fnlist = get_files_from_list(fn_epo)
    # loop across all filenames
    for fname in fnlist:
        meg_path = os.path.split(fname)[0]
        name = os.path.basename(fname)
        stc_name = name[:name.rfind('-epo.fif')] 
        subject = name.split('_')[0]
        subject_path = subjects_dir + '/%s' %subject
        min_dir = subjects_dir + '/%s' %min_subject
        fn_trans = meg_path + '/%s-trans.fif' % subject
        fn_src = subject_path + '/bem/%s-ico-5-src.fif' % subject
        fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject
        # Make sure the target path is exist
        stc_path = min_dir + '/DICS_ROIs/%s' % subject
        set_directory(stc_path)
        # Read the MNI source space
        epochs = mne.read_epochs(fname)
        tmin = epochs.times.min()
        tmax = epochs.times.max()
        fn_empty = meg_path + '/%s_empty,nr-raw.fif' % subject
        raw_noise = Raw(fn_empty, preload=True)
        epochs.info['bads'] = raw_noise.info['bads']
        picks_noise = pick_types(raw_noise.info, meg='mag', exclude='bads')
        events_noise = make_fixed_length_events(raw_noise, event_id, duration=1.)
        epochs_noise = Epochs(raw_noise, events_noise, event_id, tmin,
                                tmax, proj=True, picks=picks_noise,
                                baseline=None, preload=True, reject=None)
        # Make sure the number of noise epochs is the same as data epochs
        epochs_noise = epochs_noise[:len(epochs.events)]
        evoked = epochs.average()
        forward = mne.make_forward_solution(epochs.info, trans=fn_trans,
                                            src=fn_src, bem=fn_bem,
                                            fname=None, meg=True, eeg=False,
                                            mindist=5.0, n_jobs=2,
                                            overwrite=True)
        forward = mne.convert_forward_solution(forward, surf_ori=True)
        from mne.time_frequency import compute_epochs_csd
        from mne.beamformer import dics
        data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, 
                                      fmin=fmin, fmax=fmax)

        noise_csd = compute_epochs_csd(epochs_noise, mode='multitaper', tmin=ctmin, tmax=ctmax,
                                           fmin=fmin, fmax=fmax)
                
        stc = dics(evoked, forward, noise_csd, data_csd)
        from mne import morph_data
        stc_morph = morph_data(subject, min_subject, stc, grade=5, smooth=5)
        stc_morph.save(stc_path + '/%s_%d_%d' % (event, fmin, fmax), ftype='stc')
                    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, surf_ori=True)

# 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
data_csd = compute_epochs_csd(epochs,
                              mode='multitaper',
                              tmin=0.04,
                              tmax=0.15,
                              fmin=6,
                              fmax=10)
noise_csd = compute_epochs_csd(epochs,
                               mode='multitaper',
                               tmin=-0.11,
                               tmax=0.0,
                               fmin=6,
                               fmax=10)

evoked = epochs.average()

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

plt.figure()
        roi_pretty = roi.split('/')[-1].split('+')[0]
    # right labels are normally in the second index
    if avg_label[0] is not None:
        label = avg_label[0].morph(subject_to=s)
    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):
Exemple #11
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 = 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))
    print(stcs[0].shape)
    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 apply_inverse(fn_epo, event='LLst',ctmin=0.05, ctmax=0.25, nctmin=-0.2, nctmax=0,
                  fmin=4, fmax=8, min_subject='fsaverage', STCs=False):
    """
    Inverse evokes into source space using DICS method.
    ----------
    fn_epo : epochs of raw data.
    event_id: event id related with epochs.
    ctmin: the min time for computing CSD
    ctmax: the max time for computing CSD
    fmin: min value of the interest frequency band
    fmax: max value of the interest frequency band 
    min_subject: the subject for the common brain space.
    STCs: bool, make STCs of epochs.
    """
    from mne import Epochs, pick_types
    from mne.io import Raw
    from mne.event import make_fixed_length_events
    fnlist = get_files_from_list(fn_epo)
    # loop across all filenames
    for fname in fnlist:
        subjects_dir = os.environ['SUBJECTS_DIR']
        # extract the subject infromation from the file name
        meg_path = os.path.split(fname)[0]
        name = os.path.basename(fname)
        stc_name = name[:name.rfind('-epo.fif')] 
        subject = name.split('_')[0]
        subject_path = subjects_dir + '/%s' %subject
        min_dir = subjects_dir + '/%s' %min_subject
        fn_trans = meg_path + '/%s-trans.fif' % subject
        fn_src = subject_path + '/bem/%s-ico-4-src.fif' % subject
        fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject
        # Make sure the target path is exist
        stc_path = min_dir + '/DICS_ROIs/%s' % subject
        set_directory(stc_path)
        # Read the MNI source space
        epochs = mne.read_epochs(fname)
        evoked = epochs.average()
        forward = mne.make_forward_solution(epochs.info, trans=fn_trans,
                                            src=fn_src, bem=fn_bem,
                                            fname=None, meg=True, eeg=False,
                                            mindist=5.0, n_jobs=2,
                                            overwrite=True)
        forward = mne.convert_forward_solution(forward, surf_ori=True)
        from mne.time_frequency import compute_epochs_csd
        from mne.beamformer import dics
        data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, 
                                      fmin=fmin, fmax=fmax)

        noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=nctmin, tmax=nctmax,
                                           fmin=fmin, fmax=fmax)
                
        stc = dics(evoked, forward, noise_csd, data_csd)
        from mne import morph_data
        stc_morph = morph_data(subject, min_subject, stc, grade=4, smooth=4)
        stc_morph.save(stc_path + '/%s_%d_%d' % (stc_name, fmin, fmax), ftype='stc')
        if STCs == True:
            stcs_path = stc_path + '/STCs-%s/' %event
            reset_directory(stcs_path)
            stcs = dics(epochs, forward, noise_csd, data_csd)
            s = 0
            while s < len(stcs):
                stc_morph = mne.morph_data(subject, min_subject, stcs[s], grade=4, smooth=4)
                stc_morph.save(stcs_path + '/trial_%s'
                                % (str(s)), ftype='stc')
                s = s + 1
Exemple #13
0
    if avg_label[0] is not None:
        label = avg_label[0].morph(subject_to=s)
    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
Exemple #14
0
# Setting time windows, please note tmin stretches over the baseline, which is
# selected to be as long as the longest time window. This enables a smooth and
# accurate localization of activity in time
tmin = -0.3  # s
tmax = 0.5  # s
tstep = 0.05  # s

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating noise cross-spectral density from empty room noise for each
# frequency bin and the corresponding time window length. To calculate noise
# from the baseline period in the data, change epochs_noise to epochs
noise_csds = []
for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts):
    noise_csd = compute_epochs_csd(epochs_noise, mode='fourier',
                                   fmin=freq_bin[0], fmax=freq_bin[1],
                                   fsum=True, tmin=tmin,
                                   tmax=tmin + win_length, n_fft=n_fft)
    noise_csds.append(noise_csd)

# Computing DICS solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               n_ffts=n_ffts, reg=0.001, label=label)

# Plotting source spectrogram for source with maximum activity
plot_source_spectrogram(stcs, freq_bins, source_index=None, colorbar=True)
    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)
Exemple #16
0
def estimate_beamformer(epochs,
                        fname_forward_sol,
                        noise_cov_mat=None,
                        method="DICS",
                        show=True):
    """"Estimates source localization for the given data set using beamformer."""

    # read forward operator
    forward_sol = mne.read_forward_solution(fname_forward_sol, surf_ori=True)

    if method == "DICS":
        print ">>>> performing source localization using DICS beamformer..."
        # Computing the data and noise cross-spectral density matrices
        data_csds = compute_epochs_csd(epochs,
                                       mode='fourier',
                                       tmin=0.04,
                                       tmax=0.15,
                                       fmin=5,
                                       fmax=20)

        noise_csds = compute_epochs_csd(epochs,
                                        mode='fourier',
                                        tmin=-0.11,
                                        tmax=-0.0,
                                        fmin=5,
                                        fmax=20)
        pdb.set_trace()
        # Compute DICS spatial filter and estimate source power
        src_loc = beam.dics(epochs.average(), forward_sol, noise_csds,
                            data_csds)

        # for showing results
        fmin = 0.5
        fmid = 3.0
        fmax = 5.0

    else:
        print ">>>> performing source localization using LCMV beamformer..."

        if noise_cov_mat is None:
            print "To use LCMV beamformer the noise-covariance matrix keyword must be set."
            sys.exit()

        evoked = epochs.average()
        noise_cov_mat = mne.cov.regularize(noise_cov_mat,
                                           evoked.info,
                                           mag=0.05,
                                           proj=True)

        data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)

        src_loc = beam.lcmv(evoked,
                            forward_sol,
                            noise_cov_mat,
                            data_cov,
                            reg=0.01,
                            pick_ori=None)
        # for showing results
        fmin = 0.01
        fmid = 0.5
        fmax = 1.0

    # show results if desired
    if show is not None:
        subjects_dir = os.environ.get('SUBJECTS_DIR')
        brain = src_loc.plot(surface='inflated',
                             hemi='both',
                             subjects_dir=subjects_dir,
                             config_opts={'cortex': 'bone'},
                             time_viewer=True,
                             fmin=fmin,
                             fmid=fmid,
                             fmax=fmax)
# 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, surf_ori=True)

# 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
data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=0.04, tmax=0.15,
                              fmin=6, fmax=10)
noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=-0.11, tmax=0.0,
                               fmin=6, fmax=10)

evoked = epochs.average()

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

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)
plt.xlabel('Time (ms)')
plt.ylabel('DICS value')
plt.title('DICS time course of the 30 largest sources.')
def estimate_beamformer(epochs,
                        fname_forward_sol,
                        noise_cov_mat=None,
                        method="DICS",
                        show=True):
    """"Estimates source localization for the given data set using beamformer."""

    # read forward operator
    forward_sol = mne.read_forward_solution(fname_forward_sol, surf_ori=True)

    if method == "DICS":
        print ">>>> performing source localization using DICS beamformer..."
        # Computing the data and noise cross-spectral density matrices
        data_csds = compute_epochs_csd(epochs,
                                       mode='fourier',
                                       tmin=0.04,
                                       tmax=0.15,
                                       fmin=5,
                                       fmax=20)

        noise_csds = compute_epochs_csd(epochs,
                                        mode='fourier',
                                        tmin=-0.11,
                                        tmax=-0.0,
                                        fmin=5,
                                        fmax=20)
        pdb.set_trace()
        # Compute DICS spatial filter and estimate source power
        src_loc = beam.dics(epochs.average(),
                            forward_sol,
                            noise_csds,
                            data_csds)

        # for showing results
        fmin = 0.5; fmid = 3.0; fmax = 5.0

    else:
        print ">>>> performing source localization using LCMV beamformer..."

        if noise_cov_mat is None:
            print "To use LCMV beamformer the noise-covariance matrix keyword must be set."
            sys.exit()

        evoked = epochs.average()
        noise_cov_mat = mne.cov.regularize(noise_cov_mat,
                                           evoked.info,
                                           mag=0.05,
                                           proj=True)

        data_cov = mne.compute_covariance(epochs,
                                          tmin=0.04,
                                          tmax=0.15)

        src_loc = beam.lcmv(evoked,
                            forward_sol,
                            noise_cov_mat,
                            data_cov,
                            reg=0.01,
                            pick_ori=None)
        # for showing results
        fmin = 0.01; fmid = 0.5; fmax = 1.0


    # show results if desired
    if show is not None:
        subjects_dir = os.environ.get('SUBJECTS_DIR')
        brain = src_loc.plot(surface='inflated',
                             hemi='both',
                             subjects_dir=subjects_dir,
                             config_opts={'cortex':'bone'},
                             time_viewer=True,
                             fmin=fmin,
                             fmid=fmid,
                             fmax=fmax)
               pick_ori='max-power')
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    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],
                    preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12))
evoked = epochs.average()

# Read forward operator
forward = mne.read_forward_solution(fname_fwd, surf_ori=True)

# 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
# As fsum is False compute_epochs_csd returns a list of CrossSpectralDensity
# instances than can then be passed to dics_source_power
data_csds = compute_epochs_csd(epochs,
                               mode='multitaper',
                               tmin=0.04,
                               tmax=0.15,
                               fmin=30,
                               fmax=50,
                               fsum=False)
noise_csds = compute_epochs_csd(epochs,
                                mode='multitaper',
                                tmin=-0.11,
                                tmax=-0.001,
                                fmin=30,
                                fmax=50,
                                fsum=False)

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

# Plot source power separately for each frequency of interest
Exemple #21
0
def test_compute_epochs_csd():
    """Test computing cross-spectral density from epochs
    """
    epochs, epochs_sin = _get_data()
    # Check that wrong parameters are recognized
    assert_raises(ValueError, compute_epochs_csd, epochs, mode='notamode')
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=20.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0.15, tmax=0.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0, tmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=10, tmax=11)

    data_csd_mt = compute_epochs_csd(epochs, mode='multitaper', fmin=8,
                                     fmax=12, tmin=0.04, tmax=0.15)
    data_csd_fourier = compute_epochs_csd(epochs, mode='fourier', fmin=8,
                                          fmax=12, tmin=0.04, tmax=0.15)

    # Check shape of the CSD matrix
    n_chan = len(data_csd_mt.ch_names)
    assert_equal(data_csd_mt.data.shape, (n_chan, n_chan))
    assert_equal(data_csd_fourier.data.shape, (n_chan, n_chan))

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(data_csd_mt.data).T.conj(),
                       np.triu(data_csd_mt.data))
    assert_array_equal(np.tril(data_csd_fourier.data).T.conj(),
                       np.triu(data_csd_fourier.data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    power, _ = induced_power(epochs.get_data(), epochs.info['sfreq'], [10],
                             n_cycles=0.6)
    power = np.mean(power, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = data_csd_mt.data.diagonal().argmax()
    max_ch_fourier = data_csd_fourier.data.diagonal().argmax()
    assert_equal(max_ch_mt, max_ch_power)
    assert_equal(max_ch_fourier, max_ch_power)

    # Maximum CSD should occur for specific channel
    ch_csd_mt = [np.abs(data_csd_mt.data[max_ch_power][i])
                 if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = [np.abs(data_csd_fourier.data[max_ch_power][i])
                      if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert_equal(max_ch_csd_mt, max_ch_csd_fourier)

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    csd_fsum = compute_epochs_csd(epochs, mode='fourier', fmin=8, fmax=20,
                                  fsum=True)
    csds = compute_epochs_csd(epochs, mode='fourier', fmin=8, fmax=20,
                              fsum=False)
    freqs = [csd.frequencies[0] for csd in csds]

    csd_sum = np.zeros_like(csd_fsum.data)
    for csd in csds:
        csd_sum += csd.data

    assert(len(csds) == 2)
    assert(len(csd_fsum.frequencies) == 2)
    assert_array_equal(csd_fsum.frequencies, freqs)
    assert_array_equal(csd_fsum.data, csd_sum)
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, surf_ori=True)

# 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
# As fsum is False compute_epochs_csd returns a list of CrossSpectralDensity
# instances than can then be passed to dics_source_power
data_csds = compute_epochs_csd(epochs, mode='multitaper', tmin=0.04, tmax=0.15,
                               fmin=15, fmax=30, fsum=False)
noise_csds = compute_epochs_csd(epochs, mode='multitaper', tmin=-0.11,
                                tmax=-0.001, fmin=15, fmax=30, fsum=False)

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

clim = dict(kind='value', lims=[1.6, 1.9, 2.2])
for i, csd in enumerate(data_csds):
    message = 'DICS source power at %0.1f Hz' % csd.frequencies[0]
    brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir,
                     time_label=message, figure=i, clim=clim, transparent=True)
    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.frequencies[0])