Exemple #1
0
def test_sensitivity_maps():
    """Test sensitivity map computation"""
    fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)
    proj_eog = read_proj(eog_fname)
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data
        stc = sensitivity_map(fwd, projs=None, ch_type=ch_type,
                              mode='free', exclude='bads')
        assert_array_almost_equal(stc.data, w, decim)
        assert_true(stc.subject == 'sample')
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='fixed',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'mag':
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='ratio',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'eeg':
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ['radiality', 'angle', 'remaining', 'dampening']
            ends = ['4-lh', '5-lh', '6-lh', '7-lh']
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd, projs=proj_eog, mode=mode,
                                      ch_type=ch_type, exclude='bads')
                assert_array_almost_equal(stc.data, w, decim)
def plot_forward(fwd, sbj_id, sbj_dir):
    import mne
    import matplotlib.pyplot as plt
    
    leadfield = fwd['sol']['data']
    print 'Leadfield size : %d x %d' % leadfield.shape
    grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
    mag_map  = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
    picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)
    
    fig, axes = plt.subplots(1, 1, figsize=(10, 8), sharex=True)
    fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
    im = axes.imshow(leadfield[picks_meg, :500], origin='lower', aspect='auto', cmap='RdBu_r')
    axes.set_title('meg'.upper())
    axes.set_xlabel('sources')
    axes.set_ylabel('sensors')
    plt.colorbar(im, ax=axes, cmap='RdBu_r')
    plt.show()
    plt.figure()
    plt.hist([grad_map.data.ravel(), mag_map.data.ravel()], bins=20, label=['Gradiometers', 'Magnetometers'], 
              color=['c', 'b'])
    plt.legend()
    plt.title('Normal orientation sensitivity')
    plt.xlabel('sensitivity')
    plt.ylabel('count')
    plt.show()
    
    grad_map.plot(subject=sbj_id, time_label='Gradiometer sensitivity', subjects_dir=sbj_dir, clim='auto')
Exemple #3
0
def test_sensitivity_maps():
    """Test sensitivity map computation"""
    fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        proj_eog = read_proj(eog_fname)
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data
        stc = sensitivity_map(fwd,
                              projs=None,
                              ch_type=ch_type,
                              mode='free',
                              exclude='bads')
        assert_array_almost_equal(stc.data, w, decim)
        assert_true(stc.subject == 'sample')
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data
            stc = sensitivity_map(fwd,
                                  projs=None,
                                  mode='fixed',
                                  ch_type=ch_type,
                                  exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'mag':
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data
            stc = sensitivity_map(fwd,
                                  projs=None,
                                  mode='ratio',
                                  ch_type=ch_type,
                                  exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'eeg':
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ['radiality', 'angle', 'remaining', 'dampening']
            ends = ['4-lh', '5-lh', '6-lh', '7-lh']
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd,
                                      projs=proj_eog,
                                      mode=mode,
                                      ch_type=ch_type,
                                      exclude='bads')
                assert_array_almost_equal(stc.data, w, decim)

    # test corner case for EEG
    stc = sensitivity_map(fwd,
                          projs=[make_eeg_average_ref_proj(fwd['info'])],
                          ch_type='eeg',
                          exclude='bads')
Exemple #4
0
def test_sensitivity_maps():
    """Test sensitivity map computation."""
    fwd = read_forward_solution(fwd_fname)
    fwd = convert_forward_solution(fwd, surf_ori=True)
    projs = read_proj(eog_fname)
    projs.extend(read_proj(ecg_fname))
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data
        stc = sensitivity_map(fwd,
                              projs=None,
                              ch_type=ch_type,
                              mode='free',
                              exclude='bads')
        assert_array_almost_equal(stc.data, w, decim)
        assert stc.subject == 'sample'
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data
            stc = sensitivity_map(fwd,
                                  projs=None,
                                  mode='fixed',
                                  ch_type=ch_type,
                                  exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'mag':
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data
            stc = sensitivity_map(fwd,
                                  projs=None,
                                  mode='ratio',
                                  ch_type=ch_type,
                                  exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'eeg':
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ['radiality', 'angle', 'remaining', 'dampening']
            ends = ['4-lh', '5-lh', '6-lh', '7-lh']
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd,
                                      projs=projs,
                                      mode=mode,
                                      ch_type=ch_type,
                                      exclude='bads')
                assert_array_almost_equal(stc.data, w, decim)

    # test corner case for EEG
    stc = sensitivity_map(fwd,
                          projs=[make_eeg_average_ref_proj(fwd['info'])],
                          ch_type='eeg',
                          exclude='bads')
    # test corner case for projs being passed but no valid ones (#3135)
    pytest.raises(ValueError, sensitivity_map, fwd, projs=None, mode='angle')
    pytest.raises(RuntimeError, sensitivity_map, fwd, projs=[], mode='angle')
    # test volume source space
    fname = op.join(sample_path, 'sample_audvis_trunc-meg-vol-7-fwd.fif')
    fwd = read_forward_solution(fname)
    sensitivity_map(fwd)
Exemple #5
0
def test_sensitivity_maps():
    """Test sensitivity map computation"""
    fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)
    projs = None
    proj_eog = read_proj(eog_fname)
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w_lh = mne.read_w(sensmap_fname % (ch_type, 'lh'))
        w_rh = mne.read_w(sensmap_fname % (ch_type, 'rh'))
        w = np.r_[w_lh['data'], w_rh['data']]
        stc = sensitivity_map(fwd, projs=projs, ch_type=ch_type,
                              mode='free', exclude='bads')
        assert_array_almost_equal(stc.data.ravel(), w, decim)
        assert_true(stc.subject == 'sample')
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed
            w_lh = mne.read_w(sensmap_fname % (ch_type, '2-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '2-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=projs, mode='fixed',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data.ravel(), w, decim)
        if ch_type == 'mag':
            # ratio
            w_lh = mne.read_w(sensmap_fname % (ch_type, '3-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '3-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=projs, mode='ratio',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data.ravel(), w, decim)
        if ch_type == 'eeg':
            # radiality (4)
            w_lh = mne.read_w(sensmap_fname % (ch_type, '4-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '4-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=projs, mode='radiality',
                                  ch_type=ch_type, exclude='bads')
            # angle (5)
            w_lh = mne.read_w(sensmap_fname % (ch_type, '5-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '5-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=proj_eog, mode='angle',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data.ravel(), w, decim)
            # remaining (6)
            w_lh = mne.read_w(sensmap_fname % (ch_type, '6-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '6-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=proj_eog, mode='remaining',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data.ravel(), w, decim)
            # dampening (7)
            w_lh = mne.read_w(sensmap_fname % (ch_type, '7-lh'))
            w_rh = mne.read_w(sensmap_fname % (ch_type, '7-rh'))
            w = np.r_[w_lh['data'], w_rh['data']]
            stc = sensitivity_map(fwd, projs=proj_eog, mode='dampening',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data.ravel(), w, decim)
def run():

    args = sys.argv
    if len(args) <= 1:
        print 'Usage: run_anatomy_tutorial.sh <sample data directory>'
        return

    sample_dir = args[1]
    subjects_dir = join(sample_dir, 'subjects')
    meg_dir = join(sample_dir, 'MEG', 'sample')

    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['MEG_DIR'] = meg_dir

    subject = 'sample'

    bem = join(subjects_dir, subject, 'bem', 'sample-5120-bem-sol.fif')
    mri = join(subjects_dir, subject, 'mri', 'T1.mgz')
    fname = join(subjects_dir, subject, 'bem', 'volume-7mm-src.fif')
    src = setup_volume_source_space(subject,
                                    fname=fname,
                                    pos=7,
                                    mri=mri,
                                    bem=bem,
                                    overwrite=True,
                                    subjects_dir=subjects_dir)

    ###############################################################################
    # Compute forward solution a.k.a. lead field

    raw = mne.io.Raw(join(meg_dir, 'sample_audvis_raw.fif'))
    fwd_fname = join(meg_dir, 'sample_audvis-meg-vol-7-fwd.fif')
    trans = join(meg_dir, 'sample_audvis_raw-trans.fif')
    # for MEG only
    fwd = make_forward_solution(raw.info,
                                trans=trans,
                                src=src,
                                bem=bem,
                                fname=fwd_fname,
                                meg=True,
                                eeg=False,
                                overwrite=True)

    # Make a sensitivity map
    smap = mne.sensitivity_map(fwd, ch_type='grad', mode='free')
    smap.save(join(meg_dir, 'sample_audvis-grad-vol-7-fwd-sensmap'), ftype='w')

    ###############################################################################
    # Compute MNE inverse operators
    #
    # Note: The MEG/EEG forward solution could be used for all
    #
    noise_cov = mne.read_cov(join(meg_dir, 'sample_audvis-cov.fif'))
    inv = make_inverse_operator(raw.info, fwd, noise_cov)
    fname = join(meg_dir, 'sample_audvis-meg-vol-7-meg-inv.fif')
    write_inverse_operator(fname, inv)
Exemple #7
0
def plot_sensitivity_maps(sub, ch_types):
    fwd = sub.load_forward()

    for ch_type in ch_types:
        sens_map = mne.sensitivity_map(fwd, ch_type=ch_type, mode='fixed')
        brain = sens_map.plot(title=f'{ch_type}-Sensitivity for {sub.name}',
                              subjects_dir=sub.subjects_dir,
                              clim=dict(lims=[0, 50, 100]))

        plot_save(sub, 'sensitivity', trial=ch_type, brain=brain)
def run():

    args = sys.argv
    if len(args) <= 1:
        print 'Usage: run_anatomy_tutorial.sh <sample data directory>'
        return

    sample_dir = args[1]
    subjects_dir = join(sample_dir, 'subjects')
    meg_dir = join(sample_dir, 'MEG', 'sample')

    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['MEG_DIR'] = meg_dir

    subject = 'sample'

    bem = join(subjects_dir, subject, 'bem', 'sample-5120-bem-sol.fif')
    mri = join(subjects_dir, subject, 'mri', 'T1.mgz')
    fname = join(subjects_dir, subject, 'bem', 'volume-7mm-src.fif')
    src = setup_volume_source_space(subject, fname=fname, pos=7, mri=mri,
                                    bem=bem, overwrite=True,
                                    subjects_dir=subjects_dir)

###############################################################################
    # Compute forward solution a.k.a. lead field

    raw = mne.io.Raw(join(meg_dir, 'sample_audvis_raw.fif'))
    fwd_fname = join(meg_dir, 'sample_audvis-meg-vol-7-fwd.fif')
    trans = join(meg_dir, 'sample_audvis_raw-trans.fif')
    # for MEG only
    fwd = make_forward_solution(raw.info, trans=trans, src=src, bem=bem,
                                fname=fwd_fname, meg=True, eeg=False,
                                overwrite=True)

    # Make a sensitivity map
    smap = mne.sensitivity_map(fwd, ch_type='grad', mode='free')
    smap.save(join(meg_dir, 'sample_audvis-grad-vol-7-fwd-sensmap'), ftype='w')

###############################################################################
    # Compute MNE inverse operators
    #
    # Note: The MEG/EEG forward solution could be used for all
    #
    noise_cov = mne.read_cov(join(meg_dir, 'sample_audvis-cov.fif'))
    inv = make_inverse_operator(raw.info, fwd, noise_cov)
    fname = join(meg_dir, 'sample_audvis-meg-vol-7-meg-inv.fif')
    write_inverse_operator(fname, inv)
Exemple #9
0
def test_sensitivity_maps():
    """Test sensitivity map computation."""
    fwd = mne.read_forward_solution(fwd_fname)
    fwd = mne.convert_forward_solution(fwd, surf_ori=True)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        projs = read_proj(eog_fname)
        projs.extend(read_proj(ecg_fname))
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data
        stc = sensitivity_map(fwd, projs=None, ch_type=ch_type,
                              mode='free', exclude='bads')
        assert_array_almost_equal(stc.data, w, decim)
        assert_true(stc.subject == 'sample')
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='fixed',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'mag':
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='ratio',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'eeg':
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ['radiality', 'angle', 'remaining', 'dampening']
            ends = ['4-lh', '5-lh', '6-lh', '7-lh']
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd, projs=projs, mode=mode,
                                      ch_type=ch_type, exclude='bads')
                assert_array_almost_equal(stc.data, w, decim)

    # test corner case for EEG
    stc = sensitivity_map(fwd, projs=[make_eeg_average_ref_proj(fwd['info'])],
                          ch_type='eeg', exclude='bads')
    # test corner case for projs being passed but no valid ones (#3135)
    assert_raises(ValueError, sensitivity_map, fwd, projs=None, mode='angle')
    assert_raises(RuntimeError, sensitivity_map, fwd, projs=[], mode='angle')
    # test volume source space
    fname = op.join(sample_path, 'sample_audvis_trunc-meg-vol-7-fwd.fif')
    fwd = mne.read_forward_solution(fname)
    sensitivity_map(fwd)
def plot_sensitivity_map(fwd_sol,
                         subject,
                         fname_leadfield_plot,
                         fname_sensitvity_plot):
    """Estimates and plots sensitivity map of forward solution."""

    # estimate lead field
    leadfield = fwd_sol['sol']['data']

    pp = PdfPages(fname_leadfield_plot)

    # plot leadfield
    plt.matshow(leadfield[:, :500])
    plt.xlabel('sources')
    plt.ylabel('sensors')
    plt.title('Lead field matrix (500 dipoles only)')
    pp.savefig()
    plt.close()


    # estimate sensitivity map for magnetometer
    mag_map = mne.sensitivity_map(fwd_sol, ch_type='mag', mode='fixed')

    # plot histogram of sensitivity
    plt.hist(mag_map.data.ravel(),
                   bins=20,
                   label='Magnetometers')
    plt.legend()
    plt.title('Normal orientation sensitivity')
    pp.savefig()
    plt.close()
    pp.close()

    subjects_dir = os.environ.get('SUBJECTS_DIR')
    brain = mag_map.plot(subject=subject,
                         time_label='Magnetometer sensitivity',
                         subjects_dir=subjects_dir,
                         fmin=0.1,
                         fmid=0.5,
                         fmax=0.9,
                         smoothing_steps=7)

    brain.save_montage(fname_sensitvity_plot)
    brain.close()
Exemple #11
0
def test_sensitivity_maps():
    """Test sensitivity map computation."""
    fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        projs = read_proj(eog_fname)
        projs.extend(read_proj(ecg_fname))
    decim = 6
    for ch_type in ["eeg", "grad", "mag"]:
        w = read_source_estimate(sensmap_fname % (ch_type, "lh")).data
        stc = sensitivity_map(fwd, projs=None, ch_type=ch_type, mode="free", exclude="bads")
        assert_array_almost_equal(stc.data, w, decim)
        assert_true(stc.subject == "sample")
        # let's just make sure the others run
        if ch_type == "grad":
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, "2-lh")).data
            stc = sensitivity_map(fwd, projs=None, mode="fixed", ch_type=ch_type, exclude="bads")
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == "mag":
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, "3-lh")).data
            stc = sensitivity_map(fwd, projs=None, mode="ratio", ch_type=ch_type, exclude="bads")
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == "eeg":
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ["radiality", "angle", "remaining", "dampening"]
            ends = ["4-lh", "5-lh", "6-lh", "7-lh"]
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd, projs=projs, mode=mode, ch_type=ch_type, exclude="bads")
                assert_array_almost_equal(stc.data, w, decim)

    # test corner case for EEG
    stc = sensitivity_map(fwd, projs=[make_eeg_average_ref_proj(fwd["info"])], ch_type="eeg", exclude="bads")
    # test corner case for projs being passed but no valid ones (#3135)
    assert_raises(ValueError, sensitivity_map, fwd, projs=None, mode="angle")
    assert_raises(RuntimeError, sensitivity_map, fwd, projs=[], mode="angle")
    # test volume source space
    fname = op.join(sample_path, "sample_audvis_trunc-meg-vol-7-fwd.fif")
    fwd = mne.read_forward_solution(fname)
    sensitivity_map(fwd)
Exemple #12
0
def plot_sensitivity_map(fwd_sol, subject, fname_leadfield_plot,
                         fname_sensitvity_plot):
    """Estimates and plots sensitivity map of forward solution."""

    # estimate lead field
    leadfield = fwd_sol['sol']['data']

    pp = PdfPages(fname_leadfield_plot)

    # plot leadfield
    plt.matshow(leadfield[:, :500])
    plt.xlabel('sources')
    plt.ylabel('sensors')
    plt.title('Lead field matrix (500 dipoles only)')
    pp.savefig()
    plt.close()

    # estimate sensitivity map for magnetometer
    mag_map = mne.sensitivity_map(fwd_sol, ch_type='mag', mode='fixed')

    # plot histogram of sensitivity
    plt.hist(mag_map.data.ravel(), bins=20, label='Magnetometers')
    plt.legend()
    plt.title('Normal orientation sensitivity')
    pp.savefig()
    plt.close()
    pp.close()

    subjects_dir = os.environ.get('SUBJECTS_DIR')
    brain = mag_map.plot(subject=subject,
                         time_label='Magnetometer sensitivity',
                         subjects_dir=subjects_dir,
                         fmin=0.1,
                         fmid=0.5,
                         fmax=0.9,
                         smoothing_steps=7)

    brain.save_montage(fname_sensitvity_plot)
    brain.close()
raw = mne.io.read_raw_edf(raw_fname, preload=True)


# Clean channel names to be able to use a standard 1005 montage
ch_names = [c.replace('.', '') for c in raw.ch_names]
raw.rename_channels({old: new for old, new in zip(raw.ch_names, ch_names)})

# Read and set the EEG electrode locations
montage = mne.channels.read_montage('standard_1005', ch_names=raw.ch_names,
                                    transform=True)

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
mne.viz.plot_alignment(
    raw.info, src=src, eeg=['original', 'projected'], trans=trans, dig=True)

##############################################################################
# Setup source space and compute forward
# --------------------------------------

fwd = mne.make_forward_solution(raw.info, trans=trans, src=src,
                                bem=bem, eeg=True, mindist=5.0, n_jobs=1)
print(fwd)

# for illustration purposes use fwd to compute the sensitivity map
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')
eeg_map.plot(time_label='EEG sensitivity', subjects_dir=subjects_dir,
             clim=dict(lims=[5, 50, 100]))
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

subjects_dir = data_path + '/subjects'
fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'

fwd = read_forward_solution(fname)

projs = read_proj(ecg_fname)
# take only one projection per channel type
projs = projs[::2]

# Compute sensitivity map
ssp_ecg_map = sensitivity_map(fwd, ch_type='grad', projs=projs, mode='angle')

###############################################################################
# Show sensitivity map

plt.hist(ssp_ecg_map.data.ravel())
plt.show()

args = dict(clim=dict(kind='value', lims=(0.2, 0.6, 1.)),
            smoothing_steps=7,
            hemi='rh',
            subjects_dir=subjects_dir)
ssp_ecg_map.plot(subject='sample', time_label='ECG SSP sensitivity', **args)
bems = mne.make_bem_model(subject, conductivity=(0.3,),
                          subjects_dir=subjects_dir,
                          ico=None)  # ico = None for morphed SP.
bem_sol = mne.make_bem_solution(bems)
bem_sol['surfs'][0]['coord_frame'] = 5

##############################################################################
# Now we can read the channels that we want to map to the cortical locations.
# Then we can compute the forward solution.

info = hcp.read_info(subject=subject, hcp_path=hcp_path, data_type='rest',
                     run_index=0)

picks = mne.pick_types(info, meg=True, ref_meg=False)
info = mne.pick_info(info, picks)

fwd = mne.make_forward_solution(info, trans=head_mri_t, bem=bem_sol,
                                src=src_subject)
mag_map = mne.sensitivity_map(
    fwd, projs=None, ch_type='mag', mode='fixed', exclude=[], verbose=None)

##############################################################################
# we display sensitivity map on the original surface with little smoothing
# and admire the expected curvature-driven sensitivity pattern.

mag_map = mag_map.to_original_src(src_fsaverage, subjects_dir=subjects_dir)
mag_map.plot(subject='fsaverage', subjects_dir=subjects_dir,
             clim=dict(kind='percent', lims=[0, 50, 99]),
             smoothing_steps=2)
Exemple #16
0
    for run in runs:
        fwds.append(
            mne.read_forward_solution(
                "{dir}nc_{sub}_{run}_{spacing}-fwd.fif".format(
                    dir=proc_dir, sub=v, run=run, spacing=spacing)))
    avg_fwd = mne.average_forward_solutions(fwds)
    del fwds
    mne.write_forward_solution("{dir}nc_{sub}_{spacing}-fwd.fif".format(
        dir=proc_dir, sub=v, spacing=spacing),
                               avg_fwd,
                               overwrite=True)
    avg_fwd = mne.read_forward_solution(
        "{dir}nc_{sub}_{spacing}-fwd.fif".format(dir=proc_dir,
                                                 sub=v,
                                                 spacing=spacing))
    sen = mne.sensitivity_map(avg_fwd, ch_type="mag", mode="fixed")
    m_to_fs = mne.compute_source_morph(sen,
                                       subject_from=k,
                                       subject_to="fsaverage",
                                       spacing=int(spacing[-1]),
                                       subjects_dir=subjects_dir,
                                       smooth=None)
    sen = m_to_fs.apply(sen)
    sens.append(sen)
    sen.save("{dir}nc_{sub}_{sp}_sens".format(dir=proc_dir, sub=v, sp=spacing))

sen = sens[0].copy()
for s in sens[1:]:
    sen.data += s.data
sen.data /= len(sens)
sen.data[sen.data < thresh] = 0
Exemple #17
0
def run():

    args = sys.argv
    if len(args) <= 1:
        print 'Usage: run_meg_tutorial.sh <sample data directory>'
        return

    sample_dir = args[1]
    subjects_dir = join(sample_dir, 'subjects')
    meg_dir = join(sample_dir, 'MEG', 'sample')

    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['MEG_DIR'] = meg_dir

    subject = 'sample'

    src = setup_source_space(subject,
                             fname=True,
                             spacing='oct6',
                             n_jobs=2,
                             overwrite=True)

    # If one wanted to use other source spaces, these types of options are
    # available
    src_fsaverage = setup_source_space('fsaverage',
                                       fname=True,
                                       spacing='ico5',
                                       n_jobs=2,
                                       overwrite=True,
                                       add_dist=False)
    morph_source_spaces(src_fsaverage, subject_to='sample')
    setup_source_space(subject,
                       fname=True,
                       spacing='all',
                       overwrite=True,
                       n_jobs=2,
                       add_dist=False)

    # Add distances to source space (if desired, takes a long time)
    bem_dir = join(subjects_dir, join('sample', 'bem'))
    os.rename(join(bem_dir, 'sample-oct-6-src.fif'),
              join(bem_dir, 'sample-oct-6-orig-src.fif'))
    new_src = add_source_space_distances(src, dist_limit=0.007)
    new_src.save(join(bem_dir, 'sample-oct-6-src.fif'))

    # Preprocessing
    raw = mne.io.Raw(join(meg_dir, 'sample_audvis_raw.fif'), preload=True)
    raw.info['bads'] = ['MEG 2443', 'EEG 053']
    reject = dict(grad=3000e-13, mag=4000e-15, eeg=100e-6)
    ecg_proj, _ = mne.preprocessing.compute_proj_ecg(raw,
                                                     l_freq=1,
                                                     h_freq=100,
                                                     ch_name='MEG 1531',
                                                     reject=reject)

    eog_proj, _ = mne.preprocessing.compute_proj_eog(raw,
                                                     l_freq=1,
                                                     h_freq=35,
                                                     reject=reject,
                                                     no_proj=True)

    events = mne.find_events(raw)
    mne.write_events(join(meg_dir, 'sample_audvis_raw-eve.fif'), events)
    event_id = [1, 2, 3, 4]
    tmin, tmax = -0.2, 0.5
    picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=True, eog=True)

    # Average with no filter
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks)
    evoked = epochs.average()
    evoked.save(join(meg_dir, 'sample_audvis-no-filter-ave.fif'))

    raw.filter(l_freq=None, h_freq=40)
    raw_resampled = raw.resample(150)
    raw_resampled.save(join(meg_dir, 'sample_audvis_filt-0-40_raw.fif'),
                       overwrite=True)

    raw.add_proj(ecg_proj)
    raw.add_proj(eog_proj)

    resampled_events = mne.find_events(raw_resampled)
    mne.write_events(join(meg_dir, 'sample_audvis_filt-0-40_raw-eve.fif'),
                     resampled_events)

    # Average with filter
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks)
    evoked = epochs.average()
    evoked.save(join(meg_dir, 'sample_audvis-ave.fif'))

    # Compute the noise covariance matrix
    noise_cov = mne.compute_raw_data_covariance(raw, picks=picks)
    noise_cov.save(join(meg_dir, 'audvis.cov'))

    # Compute the empty-room noise covariance matrix
    ernoise_raw = mne.io.Raw(join(meg_dir, 'ernoise_raw.fif'), preload=True)
    ernoise_raw.info['bads'] = ['MEG 2443']
    ernoise_raw.filter(l_freq=None, h_freq=40)
    picks = mne.pick_types(ernoise_raw.info,
                           meg=True,
                           eeg=True,
                           stim=True,
                           eog=True)
    ernoise_cov = mne.compute_raw_data_covariance(ernoise_raw, picks=picks)
    ernoise_cov.save(join(meg_dir, 'ernoise.cov'))

    ###############################################################################
    # Compute forward solution a.k.a. lead field
    trans = join(meg_dir, 'sample_audvis_raw-trans.fif')
    bem = join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif')
    # for MEG only
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-fwd.fif')
    fwd_meg = mne.make_forward_solution(raw.info,
                                        trans,
                                        src,
                                        bem,
                                        fname=fname,
                                        meg=True,
                                        eeg=False,
                                        mindist=5.0,
                                        n_jobs=2,
                                        overwrite=True)

    # for EEG only
    bem = join(subjects_dir, 'sample', 'bem',
               'sample-5120-5120-5120-bem-sol.fif')
    fname = join(meg_dir, 'sample_audvis-eeg-oct-6-fwd.fif')
    fwd_eeg = mne.make_forward_solution(raw.info,
                                        trans,
                                        src,
                                        bem,
                                        fname=fname,
                                        meg=False,
                                        eeg=True,
                                        mindist=5.0,
                                        n_jobs=2,
                                        overwrite=True)

    # for both EEG and MEG
    fname = join(meg_dir, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
    fwd = mne.make_forward_solution(raw.info,
                                    trans,
                                    src,
                                    bem,
                                    fname=fname,
                                    meg=True,
                                    eeg=True,
                                    mindist=5.0,
                                    n_jobs=2,
                                    overwrite=True)

    # Create various sensitivity maps
    grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='free')
    grad_map.save(join(meg_dir, 'sample_audvis-grad-oct-6-fwd-sensmap'),
                  ftype='w')
    mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='free')
    mag_map.save(join(meg_dir, 'sample_audvis-mag-oct-6-fwd-sensmap'),
                 ftype='w')
    eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='free')
    eeg_map.save(join(meg_dir, 'sample_audvis-eeg-oct-6-fwd-sensmap'),
                 ftype='w')
    grad_map2 = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
    grad_map2.save(join(meg_dir, 'sample_audvis-grad-oct-6-fwd-sensmap-2'),
                   ftype='w')
    mag_map2 = mne.sensitivity_map(fwd, ch_type='mag', mode='ratio')
    mag_map2.save(join(meg_dir, 'sample_audvis-mag-oct-6-fwd-sensmap-3'),
                  ftype='w')

    # Compute some with the EOG + ECG projectors
    projs = ecg_proj + eog_proj + raw.info['projs']
    for map_type in ['radiality', 'angle', 'remaining', 'dampening']:
        eeg_map = mne.sensitivity_map(fwd,
                                      projs=projs,
                                      ch_type='eeg',
                                      mode=map_type)
        eeg_map.save(
            join(meg_dir, 'sample_audvis-eeg-oct-6-fwd-sensmap-' + map_type))


###############################################################################
# Compute MNE inverse operators
#
# Note: The MEG/EEG forward solution could be used for all
#
    inv_meg = make_inverse_operator(raw.info, fwd_meg, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-inv.fif')
    write_inverse_operator(fname, inv_meg)

    inv_eeg = make_inverse_operator(raw.info, fwd_eeg, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-eeg-oct-6-eeg-inv.fif')
    write_inverse_operator(fname, inv_eeg)

    inv = make_inverse_operator(raw.info, fwd, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-eeg-oct-6-meg-eeg-inv.fif')
    write_inverse_operator(fname, inv)

    # inverse operator with fixed orientation (for testing). Not implemented
    #inv_fixed = make_inverse_operator(raw.info, fwd_meg, noise_cov,
    #                                  depth=None, fixed=True)
    #fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif')
    #write_inverse_operator(fname, inv_fixed)

    # produce two with diagonal noise (for testing)
    diag = noise_cov.as_diag()
    inv_meg_diag = make_inverse_operator(raw.info, fwd_meg, diag, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
    write_inverse_operator(fname, inv_meg_diag)

    inv_eeg_diag = make_inverse_operator(raw.info, fwd, diag, loose=0.2)
    fname = join(meg_dir,
                 'sample_audvis-meg-eeg-oct-6-meg-eeg-diagnoise-inv.fif')
    write_inverse_operator(fname, inv_eeg_diag)

    # Produce stc files
    evoked.crop(0, 0.25)
    stc_meg = apply_inverse(evoked, inv_meg, method='MNE')
    stc_meg.save(join(meg_dir, 'sample_audvis-meg'))
    stc_eeg = apply_inverse(evoked, inv_eeg, method='MNE')
    stc_eeg.save(join(meg_dir, 'sample_audvis-eeg'))
    stc = apply_inverse(evoked, inv, method='MNE')
    stc.save(join(meg_dir, 'sample_audvis-meg-eeg'))

    # let's also morph to fsaverage
    stc_to = stc_meg.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-meg'))
    stc_to = stc_eeg.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-eeg'))
    stc_to = stc.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-meg-eeg'))

    ###############################################################################
    # Do one dipole fitting
    evoked = evoked.pick_types(meg=True, eeg=False)
    evoked.crop(0.04, 0.095)
    bem = join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif')
    dip, _ = mne.fit_dipole(evoked, noise_cov, bem, trans)
    dip.save(join(meg_dir, 'sample_audvis_set1.dip'))
bem = subjects_dir + '0001/bem/0001-inner_skull-bem-sol.fif'


# Note that forward solutions can also be read with read_forward_solution
fwd = mne.make_forward_solution(raw_fname, trans, src, bem,
                                fname="0001-fwd.fif", meg=True, eeg=False,
                                mindist=5.0,
                                n_jobs=n_jobs, overwrite=True)

# convert to surface orientation for better visualization
fwd = mne.convert_forward_solution(fwd, surf_ori=True)
leadfield = fwd['sol']['data']

print("Leadfield size : %d x %d" % leadfield.shape)

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')

###############################################################################
# Show gain matrix a.k.a. leadfield matrix with sensitivity map

picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)

fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
for ax, picks, ch_type in zip(axes, [picks_meg], ['meg']):
    im = ax.imshow(leadfield[picks, :], origin='lower', aspect='auto',
                   cmap='RdBu_r')
    ax.set_title(ch_type.upper())
    ax.set_xlabel('sources')
    ax.set_ylabel('sensors')
Exemple #19
0
# Then we can compute the forward solution.

info = hcp.read_info(subject=subject,
                     hcp_path=hcp_path,
                     data_type='rest',
                     run_index=0)

picks = mne.pick_types(info, meg=True, ref_meg=False)
info = mne.pick_info(info, picks)

fwd = mne.make_forward_solution(info,
                                trans=head_mri_t,
                                bem=bem_sol,
                                src=src_subject)
mag_map = mne.sensitivity_map(fwd,
                              projs=None,
                              ch_type='mag',
                              mode='fixed',
                              exclude=[],
                              verbose=None)

##############################################################################
# we display sensitivity map on the original surface with little smoothing
# and admire the expected curvature-driven sensitivity pattern.

mag_map = mag_map.to_original_src(src_fsaverage, subjects_dir=subjects_dir)
mag_map.plot(subject='fsaverage',
             subjects_dir=subjects_dir,
             clim=dict(kind='percent', lims=[0, 50, 99]),
             smoothing_steps=2)
def run():

    args = sys.argv
    if len(args) <= 1:
        print 'Usage: run_meg_tutorial.sh <sample data directory>'
        return

    sample_dir = args[1]
    subjects_dir = join(sample_dir, 'subjects')
    meg_dir = join(sample_dir, 'MEG', 'sample')

    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['MEG_DIR'] = meg_dir

    subject = 'sample'

    src = setup_source_space(subject, fname=True, spacing='oct6', n_jobs=2,
                             overwrite=True)

    # If one wanted to use other source spaces, these types of options are
    # available
    src_fsaverage = setup_source_space('fsaverage', fname=True, spacing='ico5',
                                       n_jobs=2, overwrite=True,
                                       add_dist=False)
    morph_source_spaces(src_fsaverage, subject_to='sample')
    setup_source_space(subject, fname=True, spacing='all', overwrite=True,
                       n_jobs=2, add_dist=False)

    # Add distances to source space (if desired, takes a long time)
    bem_dir = join(subjects_dir, join('sample', 'bem'))
    os.rename(join(bem_dir, 'sample-oct-6-src.fif'),
              join(bem_dir, 'sample-oct-6-orig-src.fif'))
    new_src = add_source_space_distances(src, dist_limit=0.007)
    new_src.save(join(bem_dir, 'sample-oct-6-src.fif'))

    # Preprocessing
    raw = mne.io.Raw(join(meg_dir, 'sample_audvis_raw.fif'), preload=True)
    raw.info['bads'] = ['MEG 2443', 'EEG 053']
    reject = dict(grad=3000e-13, mag=4000e-15, eeg=100e-6)
    ecg_proj, _ = mne.preprocessing.compute_proj_ecg(raw, l_freq=1, h_freq=100,
                                                     ch_name='MEG 1531',
                                                     reject=reject)

    eog_proj, _ = mne.preprocessing.compute_proj_eog(raw, l_freq=1, h_freq=35,
                                                     reject=reject,
                                                     no_proj=True)

    events = mne.find_events(raw)
    mne.write_events(join(meg_dir, 'sample_audvis_raw-eve.fif'), events)
    event_id = [1, 2, 3, 4]
    tmin, tmax = -0.2, 0.5
    picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=True, eog=True)

    # Average with no filter
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks)
    evoked = epochs.average()
    evoked.save(join(meg_dir, 'sample_audvis-no-filter-ave.fif'))

    raw.filter(l_freq=None, h_freq=40)
    raw_resampled = raw.resample(150)
    raw_resampled.save(join(meg_dir, 'sample_audvis_filt-0-40_raw.fif'),
                       overwrite=True)

    raw.add_proj(ecg_proj)
    raw.add_proj(eog_proj)

    resampled_events = mne.find_events(raw_resampled)
    mne.write_events(join(meg_dir, 'sample_audvis_filt-0-40_raw-eve.fif'),
                     resampled_events)

    # Average with filter
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks)
    evoked = epochs.average()
    evoked.save(join(meg_dir, 'sample_audvis-ave.fif'))

    # Compute the noise covariance matrix
    noise_cov = mne.compute_raw_data_covariance(raw, picks=picks)
    noise_cov.save(join(meg_dir, 'audvis.cov'))

    # Compute the empty-room noise covariance matrix
    ernoise_raw = mne.io.Raw(join(meg_dir, 'ernoise_raw.fif'), preload=True)
    ernoise_raw.info['bads'] = ['MEG 2443']
    ernoise_raw.filter(l_freq=None, h_freq=40)
    picks = mne.pick_types(ernoise_raw.info, meg=True, eeg=True, stim=True,
                           eog=True)
    ernoise_cov = mne.compute_raw_data_covariance(ernoise_raw, picks=picks)
    ernoise_cov.save(join(meg_dir, 'ernoise.cov'))

###############################################################################
    # Compute forward solution a.k.a. lead field
    trans = join(meg_dir, 'sample_audvis_raw-trans.fif')
    bem = join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif')
    # for MEG only
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-fwd.fif')
    fwd_meg = mne.make_forward_solution(raw.info, trans, src, bem,
                                        fname=fname, meg=True, eeg=False,
                                        mindist=5.0, n_jobs=2, overwrite=True)

    # for EEG only
    bem = join(subjects_dir, 'sample', 'bem',
               'sample-5120-5120-5120-bem-sol.fif')
    fname = join(meg_dir, 'sample_audvis-eeg-oct-6-fwd.fif')
    fwd_eeg = mne.make_forward_solution(raw.info, trans, src, bem,
                                        fname=fname, meg=False, eeg=True,
                                        mindist=5.0, n_jobs=2, overwrite=True)

    # for both EEG and MEG
    fname = join(meg_dir, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
    fwd = mne.make_forward_solution(raw.info, trans, src, bem,
                                    fname=fname, meg=True, eeg=True,
                                    mindist=5.0, n_jobs=2, overwrite=True)

    # Create various sensitivity maps
    grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='free')
    grad_map.save(join(meg_dir, 'sample_audvis-grad-oct-6-fwd-sensmap'),
                  ftype='w')
    mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='free')
    mag_map.save(join(meg_dir, 'sample_audvis-mag-oct-6-fwd-sensmap'),
                 ftype='w')
    eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='free')
    eeg_map.save(join(meg_dir, 'sample_audvis-eeg-oct-6-fwd-sensmap'),
                 ftype='w')
    grad_map2 = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
    grad_map2.save(join(meg_dir, 'sample_audvis-grad-oct-6-fwd-sensmap-2'),
                   ftype='w')
    mag_map2 = mne.sensitivity_map(fwd, ch_type='mag', mode='ratio')
    mag_map2.save(join(meg_dir, 'sample_audvis-mag-oct-6-fwd-sensmap-3'),
                  ftype='w')

    # Compute some with the EOG + ECG projectors
    projs = ecg_proj + eog_proj + raw.info['projs']
    for map_type in ['radiality', 'angle', 'remaining', 'dampening']:
        eeg_map = mne.sensitivity_map(fwd, projs=projs, ch_type='eeg',
                                      mode=map_type)
        eeg_map.save(join(meg_dir,
                          'sample_audvis-eeg-oct-6-fwd-sensmap-' + map_type))

###############################################################################
    # Compute MNE inverse operators
    #
    # Note: The MEG/EEG forward solution could be used for all
    #
    inv_meg = make_inverse_operator(raw.info, fwd_meg, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-inv.fif')
    write_inverse_operator(fname, inv_meg)

    inv_eeg = make_inverse_operator(raw.info, fwd_eeg, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-eeg-oct-6-eeg-inv.fif')
    write_inverse_operator(fname, inv_eeg)

    inv = make_inverse_operator(raw.info, fwd, noise_cov, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-eeg-oct-6-meg-eeg-inv.fif')
    write_inverse_operator(fname, inv)

    # inverse operator with fixed orientation (for testing). Not implemented
    #inv_fixed = make_inverse_operator(raw.info, fwd_meg, noise_cov,
    #                                  depth=None, fixed=True)
    #fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif')
    #write_inverse_operator(fname, inv_fixed)

    # produce two with diagonal noise (for testing)
    diag = noise_cov.as_diag()
    inv_meg_diag = make_inverse_operator(raw.info, fwd_meg, diag, loose=0.2)
    fname = join(meg_dir, 'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
    write_inverse_operator(fname, inv_meg_diag)

    inv_eeg_diag = make_inverse_operator(raw.info, fwd, diag, loose=0.2)
    fname = join(meg_dir,
                 'sample_audvis-meg-eeg-oct-6-meg-eeg-diagnoise-inv.fif')
    write_inverse_operator(fname, inv_eeg_diag)

    # Produce stc files
    evoked.crop(0, 0.25)
    stc_meg = apply_inverse(evoked, inv_meg, method='MNE')
    stc_meg.save(join(meg_dir, 'sample_audvis-meg'))
    stc_eeg = apply_inverse(evoked, inv_eeg, method='MNE')
    stc_eeg.save(join(meg_dir, 'sample_audvis-eeg'))
    stc = apply_inverse(evoked, inv, method='MNE')
    stc.save(join(meg_dir, 'sample_audvis-meg-eeg'))

    # let's also morph to fsaverage
    stc_to = stc_meg.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-meg'))
    stc_to = stc_eeg.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-eeg'))
    stc_to = stc.morph('fsaverage', grade=3, smooth=12)
    stc_to.save(join(meg_dir, 'fsaverage_audvis-meg-eeg'))

###############################################################################
    # Do one dipole fitting
    evoked = evoked.pick_types(meg=True, eeg=False)
    evoked.crop(0.04, 0.095)
    bem = join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif')
    dip, _ = mne.fit_dipole(evoked, noise_cov, bem, trans)
    dip.save(join(meg_dir, 'sample_audvis_set1.dip'))
import matplotlib.pyplot as plt

from mne import read_forward_solution, read_proj, sensitivity_map
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

subjects_dir = data_path + '/subjects'
fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'

fwd = read_forward_solution(fname, surf_ori=True)
projs = read_proj(ecg_fname)
projs = projs[3:][::2]  # take only one projection per channel type

# Compute sensitivity map
ssp_ecg_map = sensitivity_map(fwd, ch_type='grad', projs=projs, mode='angle')

###############################################################################
# Show sensitivity map

plt.hist(ssp_ecg_map.data.ravel())
plt.show()

args = dict(clim=dict(kind='value', lims=(0.2, 0.6, 1.)), smoothing_steps=7,
            hemi='rh', subjects_dir=subjects_dir)
ssp_ecg_map.plot(subject='sample', time_label='ECG SSP sensitivity', **args)
Exemple #22
0
            eeg=False,  # exclude EEG channels
            mindist=5.0,  # ignore sources <= 5mm from inner skull
            n_jobs=1)  # number of jobs to run in parallel

        mne.write_forward_solution(fwd_fname, fwd, overwrite=True)

    if operations_to_apply['LeadfieldMatrix']:
        fwd = mne.convert_forward_solution(fwd, surf_ori=True)
        leadfield = fwd['sol']['data']
        print(
            "Leadfield size : %d sensors x %d dipoles" %
            leadfield.shape)  ## three times the number of vertices -- x, y, z

        # Compute sensitivity maps for gradiometers
        sens_map = mne.sensitivity_map(fwd,
                                       ch_type=str(SensorType),
                                       mode='fixed')

        # # Show gain matrix a.k.a. leadfield matrix with sensitivy map
        picks = mne.pick_types(fwd['info'], meg=str(SensorType), eeg=False)

        im = plt.imshow(leadfield[picks, :500],
                        origin='lower',
                        aspect='auto',
                        cmap='RdBu_r')
        plt.xlabel('sources')
        plt.ylabel('sensors')
        plt.title('Lead field matrix for Gradiometers', fontsize=14)
        plt.colorbar(cmap='RdBu_r')

        plt.figure()
# Get relevant channel information
info = mne.io.read_info(raw_fname)
info = mne.pick_info(info, mne.pick_types(info, meg=True, eeg=False,
                                          exclude=[]))

# Morph fsaverage's source space to sample
src_fs = mne.read_source_spaces(fname_src_fs)
src_morph = mne.morph_source_spaces(src_fs, subject_to='sample',
                                    subjects_dir=subjects_dir)

# Compute the forward with our morphed source space
fwd = mne.make_forward_solution(info, trans=fname_trans,
                                src=src_morph, bem=fname_bem)
# fwd = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True)
mag_map = mne.sensitivity_map(fwd, ch_type='mag')

# Return this SourceEstimate (on sample's surfaces) to fsaverage's surfaces
mag_map_fs = mag_map.to_original_src(src_fs, subjects_dir=subjects_dir)

# Plot the result, which tracks the sulcal-gyral folding
# outliers may occur, we'll place the cutoff at 99 percent.
kwargs = dict(clim=dict(kind='percent', lims=[0, 50, 99]),
              # no smoothing, let's see the dipoles on the cortex.
              smoothing_steps=1, hemi='rh', views=['lat'])

# Now note that the dipoles on fsaverage are almost equidistant while
# morphing will distribute the dipoles unevenly across the given subject's
# cortical surface to achieve the closest approximation to the average brain.
# Our testing code suggests a correlation of higher than 0.99.
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')

# Get relevant channel information
info = mne.io.read_info(raw_fname)
info = mne.pick_info(info, mne.pick_types(info, meg=True, eeg=False,
                                          exclude=[]))

# Morph fsaverage's source space to sample
src_fs = mne.read_source_spaces(fname_src_fs)
src_morph = mne.morph_source_spaces(src_fs, subject_to='sample',
                                    subjects_dir=subjects_dir)

# Compute the forward with our morphed source space
fwd = mne.make_forward_solution(info, trans=fname_trans,
                                src=src_morph, bem=fname_bem)
mag_map = mne.sensitivity_map(fwd, ch_type='mag')

# Return this SourceEstimate (on sample's surfaces) to fsaverage's surfaces
mag_map_fs = mag_map.to_original_src(src_fs, subjects_dir=subjects_dir)

# Plot the result, which tracks the sulcal-gyral folding
# outliers may occur, we'll place the cutoff at 99 percent.
kwargs = dict(clim=dict(kind='percent', lims=[0, 50, 99]),
              # no smoothing, let's see the dipoles on the cortex.
              smoothing_steps=1, hemi='rh', views=['lat'])

# Now note that the dipoles on fsaverage are almost equidistant while
# morphing will distribute the dipoles unevenly across the given subject's
# cortical surface to achieve the closest approximation to the average brain.
# Our testing code suggests a correlation of higher than 0.99.
                                src=src,
                                bem=bem,
                                fname=None,
                                meg=True,
                                eeg=True,
                                mindist=5.0,
                                n_jobs=2,
                                overwrite=True)

# convert to surface orientation for better visualization
fwd = mne.convert_forward_solution(fwd, surf_ori=True)
leadfield = fwd['sol']['data']

print("Leadfield size : %d x %d" % leadfield.shape)

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')

###############################################################################
# Show gain matrix a.k.a. leadfield matrix with sensitivity map

picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)
picks_eeg = mne.pick_types(fwd['info'], meg=False, eeg=True)

fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
for ax, picks, ch_type in zip(axes, [picks_meg, picks_eeg], ['meg', 'eeg']):
    im = ax.imshow(leadfield[picks, :500],
                   origin='lower',
                   aspect='auto',
print __doc__

import mne
from mne.datasets import sample

data_path = sample.data_path()

fname = data_path + "/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif"
subjects_dir = data_path + "/subjects"

fwd = mne.read_forward_solution(fname, surf_ori=True)
leadfield = fwd["sol"]["data"]

print "Leadfield size : %d x %d" % leadfield.shape

grad_map = mne.sensitivity_map(fwd, ch_type="grad", mode="fixed")
mag_map = mne.sensitivity_map(fwd, ch_type="mag", mode="fixed")
eeg_map = mne.sensitivity_map(fwd, ch_type="eeg", mode="fixed")

###############################################################################
# Show gain matrix a.k.a. leadfield matrix with sensitivy map

import pylab as pl

pl.matshow(leadfield[:, :500])
pl.xlabel("sources")
pl.ylabel("sensors")
pl.title("Lead field matrix (500 dipoles only)")

pl.figure()
pl.hist(
Exemple #27
0
                                    transform=True)

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
mne.viz.plot_alignment(raw.info,
                       src=src,
                       eeg=['original', 'projected'],
                       trans=trans,
                       dig=True)

##############################################################################
# Setup source space and compute forward
# --------------------------------------

fwd = mne.make_forward_solution(raw.info,
                                trans=trans,
                                src=src,
                                bem=bem,
                                eeg=True,
                                mindist=5.0,
                                n_jobs=1)
print(fwd)

# for illustration purposes use fwd to compute the sensitivity map
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')
eeg_map.plot(time_label='EEG sensitivity',
             subjects_dir=subjects_dir,
             clim=dict(lims=[5, 50, 100]))
def run_evoked(subject_id):
    subject = "sub%03d" % subject_id
    print("processing subject: %s" % subject)
    in_path = op.join(data_path, "EEG_Process")
    evo_path = op.join(data_path, "EEG_Evoked")
    for run in range(1, 2):
        fname = op.join(in_path, 'sub_%03d_raw-epo.fif' % (subject_id, ))
        epochs = mne.read_epochs(fname, preload=True)

        #compute covariance for later on (inverse solution)
        fname_cov = op.join(evo_path,
                            "sub_%03d_LSF_HSF-cov.fif" % (subject_id, ))
        cv = KFold(3, random_state=97)  # make sure cv is deterministic
        cov = mne.compute_covariance(epochs,
                                     tmax=-0.01,
                                     method='shrunk',
                                     cv=cv)
        cov.save(fname_cov)
        mne.viz.plot_cov(cov, epochs.info)

        #general: HSF vs LSF
        evoked_LSF = epochs['LSF'].average()
        evoked_HSF = epochs['HSF'].average()
        contrast = mne.combine_evoked([evoked_HSF, evoked_LSF],
                                      weights=[1, -1])
        #name the conditions
        # Simplify comment
        evoked_LSF.comment = 'evoked_LSF'
        evoked_HSF.comment = 'evoked_HSF'
        contrast.comment = 'contrast'

        #contrast.plot(picks=('Oz'), window_title='CONTRAST')

        #plot
        #evoked_LSF.plot(picks=['Oz'], window_title='evoked, condition LSF, electrode Oz')
        #evoked_HSF.plot(picks=['Oz'], window_title='evoked, condition HSF, electrode Oz')

        fname_evo = op.join(evo_path,
                            "sub_%03d_LSF_HSF-ave.fif" % (subject_id, ))
        mne.evoked.write_evokeds(fname_evo, [evoked_LSF, evoked_HSF, contrast])

        #compute forward solution for later on (inverse solution)
        fname_fwd = op.join(evo_path,
                            "sub_%03d_LSF_HSF-fwd.fif" % (subject_id, ))
        info = mne.io.read_info(fname_evo)
        fwd = mne.make_forward_solution(info=info,
                                        trans=trans,
                                        src=src,
                                        bem=bem,
                                        eeg=True,
                                        mindist=5.0,
                                        n_jobs=1)
        print(fwd)
        leadfield = fwd['sol']['data']
        print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)
        mne.write_forward_solution(fname_fwd, fwd, overwrite=True)

        # for illustration purposes use fwd to compute the sensitivity map
        eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')
        eeg_map.plot(time_label='EEG sensitivity LSF',
                     clim=dict(lims=[5, 50, 100]))