Пример #1
0
def test_lcmv():
    """Test LCMV with evoked data and single trials
    """
    event_id, tmin, tmax = 1, -0.1, 0.15

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

    # Set up pick list: EEG + MEG - bad channels (modify to your needs)
    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()

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov, evoked.info,
                                   mag=0.05, grad=0.05, eeg=0.1, proj=True)

    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

    stc_pow = np.sum(stc.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc.data[idx]
    tmax = stc.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.1)
    assert_true(2. < np.max(max_stc) < 3.)

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True,
                                              surf_ori=True)
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)

    epochs.drop_bad_epochs()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stc.data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)
Пример #2
0
def test_lcmv():
    """Test LCMV
    """
    event_id, tmin, tmax = 1, -0.2, 0.2

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

    # Set up pick list: EEG + MEG - bad channels (modify to your needs)
    left_temporal_channels = mne.read_selection('Left-temporal')
    picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude=raw.info['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))
    evoked = epochs.average()

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov, evoked.info,
                                   mag=0.05, grad=0.05, eeg=0.1, proj=True)

    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

    stc_pow = np.sum(stc.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc.data[idx]
    tmax = stc.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.1)
    assert_true(2. < np.max(max_stc) < 3.)
def run_lcmv(subject_id):
    subject = "sub%03d" % subject_id
    print("processing subject: %s" % subject)
    data_path = op.join(meg_dir, subject)

    fname_epo = op.join(data_path,
                        '%s_highpass-%sHz-epo.fif' % (subject, l_freq))
    fname_ave = op.join(data_path,
                        '%s_highpass-%sHz-ave.fif' % (subject, l_freq))
    fname_cov = op.join(data_path,
                        '%s_highpass-%sHz-cov.fif' % (subject, l_freq))
    fname_fwd = op.join(data_path,
                        '%s-meg-eeg-%s-fwd.fif' % (subject, spacing))

    epochs = mne.read_epochs(fname_epo, preload=False)
    data_cov = mne.compute_covariance(epochs[['face', 'scrambled']],
                                      tmin=0.03,
                                      tmax=0.3,
                                      method='shrunk')
    evoked = mne.read_evokeds(fname_ave, condition='contrast')
    noise_cov = mne.read_cov(fname_cov)
    forward = mne.read_forward_solution(fname_fwd)
    forward = mne.convert_forward_solution(forward, surf_ori=True)
    stc = abs(
        lcmv(evoked,
             forward,
             noise_cov,
             data_cov,
             pick_ori='max-power',
             max_ori_out='signed'))
    stc.save(
        op.join(data_path,
                'mne_LCMV_inverse_highpass-%sHz-contrast' % (l_freq, )))
Пример #4
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked,
                   fwd,
                   noise_cov,
                   data_cov,
                   reg=0.01,
                   max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105, tmax)
        assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked,
                              forward_surf_ori,
                              noise_cov,
                              data_cov,
                              reg=0.01,
                              pick_ori="normal",
                              max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.04 < tmax < 0.11, tmax)
            assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked,
                             fwd,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             pick_ori="max-power",
                             max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.08 < tmax < 0.11, tmax)
        assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc))

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label,
                                                     fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())

        # Test NAI weight normalization:
        stc_nai = lcmv(evoked,
                       fwd,
                       noise_cov=noise_cov,
                       data_cov=data_cov,
                       reg=0.01,
                       pick_ori='max-power',
                       weight_norm='nai',
                       max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None,
                                        pos=15.,
                                        mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None,
                                        mindist=5.0,
                                        exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info,
                                           trans=None,
                                           src=src,
                                           bem=sphere,
                                           eeg=False,
                                           meg=True)

    # Test that we get an error is not reducing rank
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  fwd_sphere,
                  noise_cov,
                  data_cov,
                  reg=0.1,
                  weight_norm='unit-noise-gain',
                  pick_ori="max-power",
                  reduce_rank=False)

    # Now let's reduce it
    stc_sphere = lcmv(evoked,
                      fwd_sphere,
                      noise_cov,
                      data_cov,
                      reg=0.1,
                      weight_norm='unit-noise-gain',
                      pick_ori="max-power",
                      reduce_rank=True,
                      max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    assert_true(0.08 < tmax < 0.11, tmax)
    assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if missing of data covariance matrix is detected
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=noise_cov,
                  data_cov=None,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=None,
                  data_cov=data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_surf_ori,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal",
                  weight_norm='nai')
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori=None,
                  weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throw
    # an error
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  weight_norm=None,
                  max_ori_out='signed')

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[:-1])
    filters = make_lcmv(evoked.info,
                        forward_vol,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    assert_raises(ValueError,
                  apply_lcmv,
                  evoked_ch,
                  filters,
                  max_ori_out='signed')

    # Test if non-matching SSP projection is detected in application of filter
    raw_proj = deepcopy(raw)
    raw_proj.del_proj()
    assert_raises(ValueError,
                  apply_lcmv_raw,
                  raw_proj,
                  filters,
                  max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  pick_ori=None,
                  weight_norm='nai',
                  reduce_rank=True,
                  max_ori_out='signed')
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_surf_ori,
                  noise_cov,
                  data_cov,
                  pick_ori='normal',
                  weight_norm='nai',
                  reduce_rank=True,
                  max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs,
                       forward_fixed,
                       noise_cov,
                       data_cov,
                       reg=0.01,
                       max_ori_out='signed')
    stcs_ = lcmv_epochs(epochs,
                        forward_fixed,
                        noise_cov,
                        data_cov,
                        reg=0.01,
                        return_generator=True,
                        max_ori_out='signed')
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked,
                     forward_fixed,
                     noise_cov,
                     data_cov,
                     reg=0.01,
                     max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs,
                             forward_fixed,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             label=label,
                             max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #5
0
                    preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()

forward = mne.read_forward_solution(fname_fwd)

noise_cov = mne.read_cov(fname_cov)
noise_cov = mne.cov.regularize(noise_cov,
                               evoked.info,
                               mag=0.05,
                               grad=0.05,
                               eeg=0.1,
                               proj=True)

data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume(
    'lcmv_inverse.nii.gz', stc, forward['src'],
    mri_resolution=False)  # True for full MRI resolution

# plot result (one slice)
pl.close('all')
data = img.get_data()
coronal_slice = data[:, 10, :, 60]
Пример #6
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)
noise_cov = mne.read_cov(fname_cov)
noise_cov = mne.cov.regularize(noise_cov, evoked.info,
                               mag=0.05, grad=0.05, eeg=0.1, proj=True)

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

plt.close('all')

pick_oris = [None, 'normal', 'max-power']
names = ['free', 'normal', 'max-power']
descriptions = ['Free orientation', 'Normal orientation', 'Max-power '
                'orientation']
colors = ['b', 'k', 'r']

for pick_ori, name, desc, color in zip(pick_oris, names, descriptions, colors):
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01,
               pick_ori=pick_ori)

    # View activation time-series
    label = mne.read_label(fname_label)
    stc_label = stc.in_label(label)
    plt.plot(1e3 * stc_label.times, np.mean(stc_label.data, axis=0), color,
             hold=True, label=desc)

plt.xlabel('Time (ms)')
plt.ylabel('LCMV value')
plt.ylim(-0.8, 2.2)
plt.title('LCMV in %s' % label_name)
plt.legend()
plt.show()
Пример #8
0
def test_lcmv():
    """Test LCMV with evoked data and single trials
    """
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01)

        if fwd is forward:
            assert_true(isinstance(stc, SourceEstimate))
        else:
            assert_true(isinstance(stc, VolSourceEstimate))

        stc_pow = np.sum(stc.data, axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105)
        assert_true(1.9 < np.max(max_stc) < 3.)

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov,
                              reg=0.01, pick_ori="normal")

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.09 < tmax < 0.11)
            assert_true(1. < np.max(max_stc) < 2.)

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01,
                             pick_ori="max-power")
        stc_pow = np.sum(stc_max_power.data, axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc_max_power.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.1)
        assert_true(2. < np.max(max_stc) < 3.)

        # Maximum output source power orientation results should be similar to
        # free orientation results
        assert_true((stc_max_power.data - stc.data < 0.5).all())

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="max-power")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad_epochs()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov,
                             reg=0.01, label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #9
0
picks = pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                   exclude=raw.info['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))
evoked = epochs.average()

forward = mne.read_forward_solution(fname_fwd)

noise_cov = mne.read_cov(fname_cov)
noise_cov = mne.cov.regularize(noise_cov, evoked.info,
                               mag=0.05, grad=0.05, eeg=0.1, proj=True)

data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

# Save result in stc files
stc.save('lcmv')

###############################################################################
# View activation time-series
data, times, _ = mne.label_time_courses(fname_label, "lcmv-lh.stc")
pl.close('all')
pl.plot(1e3 * times, np.mean(data, axis=0))
pl.xlabel('time (ms)')
pl.ylabel('LCMV value')
pl.title('LCMV in %s' % label_name)
pl.show()
Пример #10
0
def test_lcmv():
    """Test LCMV with evoked data and single trials
    """
    event_id, tmin, tmax = 1, -0.1, 0.15

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

    # Set up pick list: EEG + MEG - bad channels (modify to your needs)
    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()

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov, evoked.info,
                                   mag=0.05, grad=0.05, eeg=0.1, proj=True)

    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

    stc_pow = np.sum(stc.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc.data[idx]
    tmax = stc.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.1)
    assert_true(2. < np.max(max_stc) < 3.)

    # Test picking normal orientation
    stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01,
                      pick_ori="normal")

    stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_normal.data[idx]
    tmax = stc_normal.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.11)
    assert_true(1. < np.max(max_stc) < 2.)

    # The amplitude of normal orientation results should always be smaller than
    # free orientation results
    assert_true((np.abs(stc_normal.data) <= stc.data).all())

    # Test picking source orientation maximizing output source power
    stc_max_power = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01,
                         pick_ori="max-power")

    stc_pow = np.sum(stc_max_power.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_max_power.data[idx]
    tmax = stc.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.1)
    assert_true(2. < np.max(max_stc) < 3.)

    # Maximum output source power orientation results should be similar to free
    # orientation results
    assert_true((stc_max_power.data - stc.data < 0.5).all())

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="max-power")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, stcs_.next().data)

    epochs.drop_bad_epochs()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stc.data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov,
                             reg=0.01, label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #11
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked,
                   fwd,
                   noise_cov,
                   data_cov,
                   reg=0.01,
                   max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105, tmax)
        assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked,
                              forward_surf_ori,
                              noise_cov,
                              data_cov,
                              reg=0.01,
                              pick_ori="normal")
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.04 < tmax < 0.11, tmax)
            assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked,
                             fwd,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             pick_ori="max-power",
                             max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.08 < tmax < 0.11, tmax)
        assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc))

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label,
                                                     fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())

        # Test NAI weight normalization:
        stc_nai = lcmv(evoked,
                       fwd,
                       noise_cov=noise_cov,
                       data_cov=data_cov,
                       reg=0.01,
                       pick_ori='max-power',
                       weight_norm='nai',
                       max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if missing of data covariance matrix is detected
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=noise_cov,
                  data_cov=None,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov=None,
                  data_cov=data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  max_ori_out='signed')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_surf_ori,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal",
                  weight_norm='nai')
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori=None,
                  weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throw
    # an error
    assert_raises(NotImplementedError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power",
                  weight_norm=None,
                  max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs,
                        forward_fixed,
                        noise_cov,
                        data_cov,
                        reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs,
                             forward_fixed,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #12
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)
Пример #13
0
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    baseline=(None, 0), preload=True, proj=proj,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()

forward = mne.read_forward_solution(fname_fwd)

# Read regularized noise covariance and compute regularized data covariance
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0, method='shrunk')
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
                                  method='shrunk')

# Run free orientation (vector) beamformer. Source orientation can be
# restricted by setting pick_ori to 'max-power' (or 'normal' but only when
# using a surface-based source space)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.05, pick_ori=None)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('lcmv_inverse.nii.gz', stc,
                             forward['src'], mri_resolution=False)

t1_fname = data_path + '/subjects/sample/mri/T1.mgz'

# Plotting with nilearn ######################################################
plot_stat_map(index_img(img, 61), t1_fname, threshold=0.8,
              title='LCMV (t=%.1f s.)' % stc.times[61])
Пример #14
0
def test_lcmv():
    """Test LCMV with evoked data and single trials
    """
    event_id, tmin, tmax = 1, -0.1, 0.15

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

    # Set up pick list: EEG + MEG - bad channels (modify to your needs)
    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()

    noise_cov = mne.read_cov(fname_cov)
    noise_cov = mne.cov.regularize(noise_cov,
                                   evoked.info,
                                   mag=0.05,
                                   grad=0.05,
                                   eeg=0.1,
                                   proj=True)

    data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01)

    stc_pow = np.sum(stc.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc.data[idx]
    tmax = stc.times[np.argmax(max_stc)]

    assert_true(0.09 < tmax < 0.1)
    assert_true(2. < np.max(max_stc) < 3.)

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    forward_fixed = mne.read_forward_solution(fname_fwd,
                                              force_fixed=True,
                                              surf_ori=True)
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs,
                        forward_fixed,
                        noise_cov,
                        data_cov,
                        reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, stcs_.next().data)

    epochs.drop_bad_epochs()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stc.data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs,
                             forward_fixed,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #15
0
def SourceReconstruction(condnames, ListSubj):

    #ipython --pylab
    import mne
    from mne.minimum_norm import apply_inverse, make_inverse_operator
    from mne.beamformer import lcmv
    import os
    os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON')

    os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri'
    os.environ['MNE_ROOT'] = '/neurospin/local/mne'

    wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"
    #wdir = "/media/bgauthie/Seagate Backup Plus Drive/TMP_MEG_SOURCE/MEG/"

    for i in range(len(ListSubj)):

        # open a text logfile
        logfile = open(wdir + ListSubj[i] + "/mne_python/logfile_preproc.txt",
                       "w")

        # load covariance matrices
        fname_fwd_eeg = (wdir + ListSubj[i] +
                         "/mne_python/run3_ico-5_eegonly_-fwd.fif")
        fname_fwd_meg = (wdir + ListSubj[i] +
                         "/mne_python/run3_ico-5_megonly_-fwd.fif")
        fname_fwd_meeg = (wdir + ListSubj[i] +
                          "/mne_python/run3_ico-5_meeg_-fwd.fif")

        fname_noisecov1 = (wdir + ListSubj[i] + "/mne_python/MEGnoisecov_" +
                           condnames + "_" + ListSubj[i] + "-cov.fif")
        fname_noisecov2 = (wdir + ListSubj[i] + "/mne_python/EEGnoisecov_" +
                           condnames + "_" + ListSubj[i] + "-cov.fif")
        fname_noisecov3 = (wdir + ListSubj[i] + "/mne_python/MEEGnoisecov_" +
                           condnames + "_" + ListSubj[i] + "-cov.fif")

        fname_datacov1 = (wdir + ListSubj[i] + "/mne_python/MEGdatacov_" +
                          condnames + "_" + ListSubj[i] + "-cov.fif")
        fname_datacov2 = (wdir + ListSubj[i] + "/mne_python/EEGdatacov_" +
                          condnames + "_" + ListSubj[i] + "-cov.fif")
        fname_datacov3 = (wdir + ListSubj[i] + "/mne_python/MEEGdatacov_" +
                          condnames + "_" + ListSubj[i] + "-cov.fif")

        forward_meg = mne.read_forward_solution(fname_fwd_meg, surf_ori=True)
        forward_eeg = mne.read_forward_solution(fname_fwd_eeg, surf_ori=True)
        forward_meeg = mne.read_forward_solution(fname_fwd_meeg, surf_ori=True)

        fname_ave_meg = (wdir + ListSubj[i] + "/mne_python/MEG_" + condnames +
                         "_" + ListSubj[i] + "-ave.fif")
        fname_ave_eeg = (wdir + ListSubj[i] + "/mne_python/EEG_" + condnames +
                         "_" + ListSubj[i] + "-ave.fif")
        fname_ave_meeg = (wdir + ListSubj[i] + "/mne_python/MEEG_" +
                          condnames + "_" + ListSubj[i] + "-ave.fif")

        NOISE_COV1_meg = mne.read_cov(fname_noisecov1)
        NOISE_COV1_eeg = mne.read_cov(fname_noisecov2)
        NOISE_COV1_meeg = mne.read_cov(fname_noisecov3)

        DATA_COV1_meg = mne.read_cov(fname_datacov1)
        DATA_COV1_eeg = mne.read_cov(fname_datacov2)
        DATA_COV1_meeg = mne.read_cov(fname_datacov3)

        # load evoked
        evokedcond1_meg = mne.read_evokeds(fname_ave_meg,
                                           condition=0,
                                           baseline=(-0.2, 0))
        evokedcond1_eeg = mne.read_evokeds(fname_ave_eeg,
                                           condition=0,
                                           baseline=(-0.2, 0))
        evokedcond1_meeg = mne.read_evokeds(fname_ave_meeg,
                                            condition=0,
                                            baseline=(-0.2, 0))

        inverse_operator1_meg = make_inverse_operator(evokedcond1_meg.info,
                                                      forward_meg,
                                                      NOISE_COV1_meg,
                                                      loose=0.2,
                                                      depth=0.8)
        inverse_operator1_eeg = make_inverse_operator(evokedcond1_eeg.info,
                                                      forward_eeg,
                                                      NOISE_COV1_eeg,
                                                      loose=0.2,
                                                      depth=0.8)
        inverse_operator1_meeg = make_inverse_operator(evokedcond1_meeg.info,
                                                       forward_meeg,
                                                       NOISE_COV1_meeg,
                                                       loose=0.2,
                                                       depth=0.8)

        #################################################################################################################################
        # dSPM solution #
        #################################################################################################################################
        snr = 3.0
        lambda2 = 1.0 / snr**2

        # MEG source reconstruction
        stccond1_meg = apply_inverse(evokedcond1_meg,
                                     inverse_operator1_meg,
                                     lambda2,
                                     method='dSPM',
                                     pick_ori=None)
        stccond1_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" +
                          ListSubj[i] + "_" + condnames +
                          "_pick_oriNone_dSPMinverse_ico-5-fwd.fif")
        stccond1norm_meg = apply_inverse(evokedcond1_meg,
                                         inverse_operator1_meg,
                                         lambda2,
                                         method='dSPM',
                                         pick_ori="normal")
        stccond1norm_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" +
                              ListSubj[i] + "_" + condnames +
                              "_pick_orinormal_dSPMinverse_ico-5-fwd.fif")

        stc_fsaverage_cond1_meg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                 stccond1_meg)
        stc_fsaverage_cond1_meg.save(
            wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1norm_meg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                     stccond1norm_meg)
        stc_fsaverage_cond1norm_meg.save(
            wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("MEG dSPM source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        # EEG source reconstruction
        stccond1_eeg = apply_inverse(evokedcond1_eeg,
                                     inverse_operator1_eeg,
                                     lambda2,
                                     method='dSPM',
                                     pick_ori=None)
        stccond1_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" +
                          ListSubj[i] + "_" + condnames +
                          "_pick_oriNone_dSPMinverse_ico-5-fwd.fif")
        stccond1norm_eeg = apply_inverse(evokedcond1_eeg,
                                         inverse_operator1_eeg,
                                         lambda2,
                                         method='dSPM',
                                         pick_ori="normal")
        stccond1norm_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" +
                              ListSubj[i] + "_" + condnames +
                              "_pick_orinormal_dSPMinverse_ico-5-fwd.fif")

        stc_fsaverage_cond1_eeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                 stccond1_eeg)
        stc_fsaverage_cond1_eeg.save(
            wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1bis_eeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                    stccond1norm_eeg)
        stc_fsaverage_cond1bis_eeg.save(
            wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("EEG dSPM source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        # MEEG source reconstruction
        stccond1_meeg = apply_inverse(evokedcond1_meeg,
                                      inverse_operator1_meeg,
                                      lambda2,
                                      method='dSPM',
                                      pick_ori=None)
        stccond1_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" +
                           ListSubj[i] + "_" + condnames +
                           "_pick_oriNone_dSPMinverse_ico-5-fwd.fif")
        stccond1norm_meeg = apply_inverse(evokedcond1_meeg,
                                          inverse_operator1_meeg,
                                          lambda2,
                                          method='dSPM',
                                          pick_ori="normal")
        stccond1norm_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" +
                               ListSubj[i] + "_" + condnames +
                               "_pick_orinormal_dSPMinverse_ico-5-fwd.fif")

        stc_fsaverage_cond1_meeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                  stccond1_meeg)
        stc_fsaverage_cond1_meeg.save(
            wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_dSPMinverse_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1bis_meeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                     stccond1norm_meeg)
        stc_fsaverage_cond1bis_meeg.save(
            wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_dSPMinverse_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("MEEG dSPM source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        #################################################################################################################################
        # LCMV Beamformer #
        #################################################################################################################################
        # MEG source reconstruction
        stccond1_meg = lcmv(evokedcond1_meg,
                            forward_meg,
                            NOISE_COV1_meg,
                            DATA_COV1_meg,
                            reg=0.01,
                            pick_ori=None)
        stccond1_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" +
                          ListSubj[i] + "_" + condnames +
                          "_pick_oriNone_LCMV_ico-5-fwd.fif")
        stccond1norm_meg = lcmv(evokedcond1_meg,
                                forward_meg,
                                NOISE_COV1_meg,
                                DATA_COV1_meg,
                                reg=0.01,
                                pick_ori="normal")
        stccond1norm_meg.save(wdir + ListSubj[i] + "/mne_python/MEG_" +
                              ListSubj[i] + "_" + condnames +
                              "_pick_orinormal_LCMV_ico-5-fwd.fif")

        stc_fsaverage_cond1_meg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                 stccond1_meg)
        stc_fsaverage_cond1_meg.save(
            wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1norm_meg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                     stccond1norm_meg)
        stc_fsaverage_cond1norm_meg.save(
            wdir + ListSubj[i] + "/mne_python/MEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("MEG LCMV source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        # EEG source reconstruction
        stccond1_eeg = lcmv(evokedcond1_eeg,
                            forward_eeg,
                            NOISE_COV1_eeg,
                            DATA_COV1_eeg,
                            reg=0.01,
                            pick_ori=None)
        stccond1_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" +
                          ListSubj[i] + "_" + condnames +
                          "_pick_oriNone_LCMV_ico-5-fwd.fif")
        stccond1norm_eeg = lcmv(evokedcond1_eeg,
                                forward_eeg,
                                NOISE_COV1_eeg,
                                DATA_COV1_eeg,
                                reg=0.01,
                                pick_ori="normal")
        stccond1norm_eeg.save(wdir + ListSubj[i] + "/mne_python/EEG_" +
                              ListSubj[i] + "_" + condnames +
                              "_pick_orinormal_LCMV_ico-5-fwd.fif")

        stc_fsaverage_cond1_eeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                 stccond1_eeg)
        stc_fsaverage_cond1_eeg.save(
            wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1norm_eeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                     stccond1norm_eeg)
        stc_fsaverage_cond1norm_eeg.save(
            wdir + ListSubj[i] + "/mne_python/EEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("EEG dSPM source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        # MEEG source reconstruction
        stccond1_meeg = lcmv(evokedcond1_meeg,
                             forward_meeg,
                             NOISE_COV1_meeg,
                             DATA_COV1_meeg,
                             reg=0.01,
                             pick_ori=None)
        stccond1_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" +
                           ListSubj[i] + "_" + condnames +
                           "_pick_oriNone_LCMV_ico-5-fwd.fif")
        stccond1norm_meeg = lcmv(evokedcond1_meeg,
                                 forward_meeg,
                                 NOISE_COV1_meeg,
                                 DATA_COV1_meeg,
                                 reg=0.01,
                                 pick_ori="normal")
        stccond1norm_meeg.save(wdir + ListSubj[i] + "/mne_python/MEEG_" +
                               ListSubj[i] + "_" + condnames +
                               "_pick_orinormal_LCMV_ico-5-fwd.fif")

        stc_fsaverage_cond1_meeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                  stccond1_meeg)
        stc_fsaverage_cond1_meeg.save(
            wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" +
            condnames + "_pick_oriNone_LCMV_ico-5-fwd-fsaverage.fif")
        stc_fsaverage_cond1norm_meeg = mne.morph_data(ListSubj[i], 'fsaverage',
                                                      stccond1norm_meeg)
        stc_fsaverage_cond1norm_meeg.save(
            wdir + ListSubj[i] + "/mne_python/MEEG_" + ListSubj[i] + "_" +
            condnames + "_pick_orinormal_LCMV_ico-5-fwd-fsaverage.fif")

        logfile.write("" "\n")
        logfile.write("processing subject " + ListSubj[i] + "\n")
        logfile.write("MEEG dSPM source reconstruction: orinone & orinormal " +
                      "\n")
        logfile.write("Morphing on fsaverage " + "\n")
        logfile.write("" "\n")

        logfile.close()
Пример #16
0
                                  method='shrunk')

plt.close('all')

pick_oris = [None, 'normal', 'max-power']
names = ['free', 'normal', 'max-power']
descriptions = [
    'Free orientation', 'Normal orientation', 'Max-power '
    'orientation'
]
colors = ['b', 'k', 'r']

for pick_ori, name, desc, color in zip(pick_oris, names, descriptions, colors):
    stc = lcmv(evoked,
               forward,
               noise_cov,
               data_cov,
               reg=0.01,
               pick_ori=pick_ori)

    # View activation time-series
    label = mne.read_label(fname_label)
    stc_label = stc.in_label(label)
    plt.plot(1e3 * stc_label.times,
             np.mean(stc_label.data, axis=0),
             color,
             hold=True,
             label=desc)

plt.xlabel('Time (ms)')
plt.ylabel('LCMV value')
plt.ylim(-0.8, 2.2)
Пример #17
0
    fname = out_dir + '%s_%s_dSPM_base_clean' % (subj, conds[c])
    stc.save(fname)
    stc = apply_inverse(evoked_ds[c], inv_blank, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to,
                                     morph_mat)
    fname = out_dir + '%s_%s_dSPM_blank_clean' % (subj, conds[c])
    stc.save(fname)

    # the next estimate is LCMV beamformer in time
    data_cov = mne.compute_covariance(epochs_ds[conds[c]],
                                      tmin=0,
                                      tmax=None,
                                      method='shrunk')
    stc = lcmv(evoked_ds[c],
               forward,
               cov_blank,
               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_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])
Пример #18
0
def SourceReconstructionv4(condarray,condrenames,ListSubj,modality,Method,covmatsource):
#
#    condarray = (('EtPre','EtPre'),('EtPast','EtFut'))
#    condrenames = ('NoProjT','ProjT')
#    ListSubj  = ('jm100109',)
#    modality  = 'MEG'
#    Method    = 'dSPM'
#    covmatsource = 'EV'

    import mne
    from mne.minimum_norm import apply_inverse, make_inverse_operator
    from mne.beamformer import lcmv
    import os

    os.chdir('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/SCRIPTS/MNE_PYTHON')
    os.environ['SUBJECTS_DIR'] = '/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri'
    os.environ['MNE_ROOT'] = '/neurospin/local/mne'

    wdir = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/"

    for c in range(len(condarray)):
        for i in range(len(ListSubj)):

            # which modality?
            if modality == 'MEG':
                megtag=True  
                eegtag=False
                fname_fwd  = (wdir+ListSubj[i]+"/mne_python/run3_ico5_megonly_icacorr_-fwd.fif") 
            elif modality == 'EEG':
                megtag=False  
                eegtag=True
                fname_fwd  = (wdir+ListSubj[i]+"/mne_python/run3_ico5_eegonly_icacorr_-fwd.fif") 
            elif modality == 'MEEG':
                megtag=True  
                eegtag=True
                fname_fwd = (wdir+ListSubj[i]+"/mne_python/run3_ico5_meeg_icacorr_-fwd.fif")

            # load noise covariance matrice
            fname_noisecov    = (wdir+ListSubj[i]+"/mne_python/COVMATS/"+modality+"_noisecov_icacorr_"+ covmatsource +"_"+ ListSubj[i] +"-cov.fif")
            NOISE_COV1        = mne.read_cov(fname_noisecov)
            
            # concatenate epochs if several conditions
            if len(condarray[c]) == 1:
                condnames = []
                condnames = condarray[c][0]
                # load MEEG epochs, then pick    
                fname_epochs      = (wdir+ListSubj[i]+"/mne_python/EPOCHS/MEEG_epochs_icacorr_" +condnames+ '_' + ListSubj[i]+"-epo.fif")          
                epochs            = mne.read_epochs(fname_epochs)
                picks = mne.pick_types(epochs.info, meg=megtag,  eeg=eegtag, stim=False , eog=False)
                # compute evoked
                evokedcond1       = epochs.average(picks = picks)
                forward           = mne.read_forward_solution(fname_fwd ,surf_ori=True)
                inverse_operator1 = make_inverse_operator(evokedcond1.info,  forward, NOISE_COV1,  loose=0.2, depth=0.8)
                
            elif len(condarray[c]) > 1:
                epochlist = []
                for ca in range(len(condarray[c])):
                    condnames = []
                    condnames = condarray[c][ca]
                    # load MEEG epochs, then pick    
                    fname_epochs      = (wdir+ListSubj[i]+"/mne_python/EPOCHS/MEEG_epochs_icacorr_" +condnames+ '_' + ListSubj[i]+"-epo.fif")          
                    epochs            = mne.read_epochs(fname_epochs)
                    picks = mne.pick_types(epochs.info, meg=megtag,  eeg=eegtag, stim=False , eog=False)
                    epochlist.append(epochs)
                epochs = []
                epochs = mne.epochs.concatenate_epochs(epochlist)
                    
            # compute evoked
            evokedcond1       = epochs.average(picks = picks)
            forward           = mne.read_forward_solution(fname_fwd ,surf_ori=True)
            inverse_operator1 = make_inverse_operator(evokedcond1.info,  forward, NOISE_COV1,  loose=0.2, depth=0.8)
                    
            
            if Method == 'LCMV':
                fname_datacov     = (wdir+ListSubj[i]+"/mne_python/COVMATS/"+modality+"datacov_"+condnames[c]+"_"+ListSubj[i]+"-cov.fif")
                DATA_COV1         = mne.read_cov(fname_datacov)

    ###############################
    # dSPM/ MNE/ sLORETA solution #
    ###############################

        if Method == 'dSPM' or Method == 'MNE' or Method == 'sLORETA':

    	    snr = 3.0
    	    lambda2 = 1.0 / snr **2
    	
	    # MEG source reconstruction
    	    stccond1     = apply_inverse(evokedcond1, inverse_operator1, lambda2,method = Method, pick_ori= None)
    	    stccond1.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd.fif")

    	    stccond1norm = apply_inverse(evokedcond1, inverse_operator1, lambda2,method =Method, pick_ori= "normal")
    	    stccond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd.fif")

            # morphing to fsaverage
    	    stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1,smooth = 20)
    	    stc_fsaverage_cond1.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd-fsaverage.fif")

    	    stc_fsaverage_cond1norm = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm,smooth = 20)
    	    stc_fsaverage_cond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/IcaCorr_"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd-fsaverage.fif")
    
    ###################
    # LCMV Beamformer #
    ###################

        elif Method == 'LCMV':

            # MEG source reconstruction    
            stccond1 = lcmv(evokedcond1, forward, NOISE_COV1,DATA_COV1, reg=0.01,pick_ori= None)
            stccond1.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd.fif")

            stccond1norm = lcmv(evokedcond1, forward, NOISE_COV1,DATA_COV1, reg=0.01,pick_ori= "normal")
            stccond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd.fif")

            # morphing to fsaverage
            stc_fsaverage_cond1 = mne.morph_data(ListSubj[i], 'fsaverage', stccond1,smooth = 20)
            stc_fsaverage_cond1.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_oriNone_"+Method+"_ico-5-fwd-fsaverage.fif") 

            stc_fsaverage_cond1norm = mne.morph_data(ListSubj[i], 'fsaverage', stccond1norm,smooth = 20)
            stc_fsaverage_cond1norm.save(wdir+ListSubj[i]+"/mne_python/STCS/"+modality+"_"+ListSubj[i]+"_"+condrenames[c]+"_pick_orinormal_"+Method+"_ico-5-fwd-fsaverage.fif")   
Пример #19
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01,
                   max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105, tmax)
        assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked, forward_surf_ori, noise_cov,
                              data_cov, reg=0.01, pick_ori="normal",
                              max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.04 < tmax < 0.11, tmax)
            assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01,
                             pick_ori="max-power", max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.08 < tmax < 0.11, tmax)
        assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc))

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label, fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())

        # Test NAI weight normalization:
        stc_nai = lcmv(evoked, fwd, noise_cov=noise_cov, data_cov=data_cov,
                       reg=0.01, pick_ori='max-power', weight_norm='nai',
                       max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0, exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info, trans=None, src=src,
                                           bem=sphere, eeg=False, meg=True)

    # Test that we get an error is not reducing rank
    assert_raises(ValueError, lcmv, evoked, fwd_sphere, noise_cov, data_cov,
                  reg=0.1, weight_norm='unit-noise-gain', pick_ori="max-power",
                  reduce_rank=False)

    # Now let's reduce it
    stc_sphere = lcmv(evoked, fwd_sphere, noise_cov, data_cov, reg=0.1,
                      weight_norm='unit-noise-gain', pick_ori="max-power",
                      reduce_rank=True, max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    assert_true(0.08 < tmax < 0.11, tmax)
    assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")
    assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov,
                  reg=0.01, pick_ori="max-power", max_ori_out='signed')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov,
                  reg=0.01, pick_ori="normal")

    # Test if missing of data covariance matrix is detected
    assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=noise_cov,
                  data_cov=None, reg=0.01, pick_ori="max-power",
                  max_ori_out='signed')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=None,
                  data_cov=data_cov, reg=0.01, pick_ori="max-power",
                  max_ori_out='signed')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori,
                  noise_cov, data_cov, reg=0.01, pick_ori="normal",
                  weight_norm='nai')
    assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov,
                  data_cov, reg=0.01, pick_ori=None, weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throw
    # an error
    assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov,
                  data_cov, reg=0.01, pick_ori="max-power", weight_norm=None,
                  max_ori_out='signed')

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    assert_raises(ValueError, apply_lcmv, evoked_ch, filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    raw_proj = deepcopy(raw)
    raw_proj.del_proj()
    assert_raises(ValueError, apply_lcmv_raw, raw_proj, filters,
                  max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov,
                  data_cov, pick_ori=None, weight_norm='nai', reduce_rank=True,
                  max_ori_out='signed')
    assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori,
                  noise_cov, data_cov, pick_ori='normal', weight_norm='nai',
                  reduce_rank=True, max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov,
                       reg=0.01, max_ori_out='signed')
    stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov,
                        reg=0.01, return_generator=True,
                        max_ori_out='signed')
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01,
                     max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov,
                             reg=0.01, label=label, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #20
0
    # start with the simplest method, MNE + dSPM
    stc = apply_inverse(evoked_ds[c], inv_base, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    fname = out_dir + '%s_%s_dSPM_base_clean' % (subj, conds[c])
    stc.save(fname)
    stc = apply_inverse(evoked_ds[c], inv_blank, lambda2, method)
    stc = mne.morph_data_precomputed(subj, 'fsaverage', stc,
                                     vertices_to, morph_mat)
    fname = out_dir + '%s_%s_dSPM_blank_clean' % (subj, conds[c])
    stc.save(fname)

    # the next estimate is LCMV beamformer in time
    data_cov = mne.compute_covariance(epochs_ds[conds[c]], tmin=0, tmax=None,
                                      method='shrunk')
    stc = lcmv(evoked_ds[c], forward, cov_blank, 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_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,
Пример #21
0
                                  tmin=0.04,
                                  tmax=0.15,
                                  method='shrunk')

# Run free orientation (vector) beamformer with weight normalization (neural
# activity index, NAI). Providing a noise covariance matrix enables whitening
# of the data and forward solution. Source orientation is optimized by
# setting pick_ori to 'max-power'.
# weight_norm can also be set to 'unit-noise-gain'. Source orientation can also
# be 'normal' (but only when using a surface-based source space) or None,
# which computes a vector beamfomer. Note, however, that not all combinations
# of orientation selection and weight normalization are implemented yet.
stc = lcmv(evoked,
           forward,
           noise_cov,
           data_cov,
           reg=0.05,
           pick_ori='max-power',
           weight_norm='nai',
           max_ori_out='signed')

# take absolute values for plotting
stc.data[:, :] = np.abs(stc.data)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('lcmv_inverse.nii.gz',
                             stc,
Пример #22
0
def test_lcmv():
    """Test LCMV with evoked data and single trials
    """
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01)

        if fwd is forward:
            assert_true(isinstance(stc, SourceEstimate))
        else:
            assert_true(isinstance(stc, VolSourceEstimate))

        stc_pow = np.sum(stc.data, axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.105)
        assert_true(1.9 < np.max(max_stc) < 3.)

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            stc_normal = lcmv(evoked,
                              forward_surf_ori,
                              noise_cov,
                              data_cov,
                              reg=0.01,
                              pick_ori="normal")

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert_true(0.09 < tmax < 0.11)
            assert_true(1. < np.max(max_stc) < 2.)

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert_true((np.abs(stc_normal.data) <= stc.data).all())

        # Test picking source orientation maximizing output source power
        stc_max_power = lcmv(evoked,
                             fwd,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             pick_ori="max-power")
        stc_pow = np.sum(stc_max_power.data, axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc_max_power.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert_true(0.09 < tmax < 0.1)
        assert_true(2. < np.max(max_stc) < 3.)

        # Maximum output source power orientation results should be similar to
        # free orientation results
        assert_true((stc_max_power.data - stc.data < 0.5).all())

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_fixed,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="max-power")

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Test if volume forward operator is detected when picking normal
    # orientation
    assert_raises(ValueError,
                  lcmv,
                  evoked,
                  forward_vol,
                  noise_cov,
                  data_cov,
                  reg=0.01,
                  pick_ori="normal")

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01)
    stcs_ = lcmv_epochs(epochs,
                        forward_fixed,
                        noise_cov,
                        data_cov,
                        reg=0.01,
                        return_generator=True)
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad_epochs()
    assert_true(len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01)
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    stcs_label = lcmv_epochs(epochs,
                             forward_fixed,
                             noise_cov,
                             data_cov,
                             reg=0.01,
                             label=label)

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Пример #23
0
###############################################################################
# Run beamformers and look at maximum outputs

pick_oris = [None, 'normal', 'max-power']
names = ['free', 'normal', 'max-power']
descriptions = ['Free orientation, voxel: %i', 'Normal orientation, voxel: %i',
                'Max-power orientation, voxel: %i']
colors = ['b', 'k', 'r']

fig, ax = plt.subplots(1)
max_voxs = list()
for pick_ori, name, desc, color in zip(pick_oris, names, descriptions, colors):
    # compute unit-noise-gain beamformer with whitening of the leadfield and
    # data (enabled by passing a noise covariance matrix)
    stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.05,
               pick_ori=pick_ori, weight_norm='unit-noise-gain',
               max_ori_out='signed')

    # View activation time-series in maximum voxel at 100 ms:
    time_idx = stc.time_as_index(0.1)
    max_idx = np.argmax(stc.data[:, time_idx])
    # we know these are all left hemi, so we can just use vertices[0]
    max_voxs.append(stc.vertices[0][max_idx])
    ax.plot(stc.times, stc.data[max_idx, :], color, label=desc % max_idx)

ax.set(xlabel='Time (ms)', ylabel='LCMV value', ylim=(-0.8, 2.2),
       title='LCMV in maximum voxel')
ax.legend()
mne.viz.utils.plt_show()

###############################################################################