Пример #1
0
def test_make_inverse_operator_fixed():
    """Test MNE inverse computation with fixed orientation"""
    # XXX : should be fixed and not skipped
    raise nose.SkipTest("XFailed Test")

    evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0))
    fwd_op = read_forward_solution(fname_fwd, force_fixed=True)
    inv_op = make_inverse_operator(evoked.info,
                                   fwd_op,
                                   noise_cov,
                                   depth=0.8,
                                   loose=None)

    assert_array_almost_equal(inverse_operator_fixed['depth_prior']['data'],
                              inv_op['depth_prior']['data'])
    assert_equal(inverse_operator_fixed['orient_prior'],
                 inv_op['orient_prior'])
    assert_array_almost_equal(inverse_operator_fixed['source_cov']['data'],
                              inv_op['source_cov']['data'])

    stc_fixed = apply_inverse(evoked, inverse_operator_fixed, lambda2, "dSPM")
    my_stc = apply_inverse(evoked, inv_op, lambda2, "dSPM")

    assert_equal(stc_fixed.times, my_stc.times)
    assert_array_almost_equal(stc_fixed.data, my_stc.data, 2)
Пример #2
0
def test_gamma_map():
    """Test Gamma MAP inverse"""
    forward = read_forward_solution(fname_fwd, force_fixed=False,
                                    surf_ori=True)
    evoked = fiff.Evoked(fname_evoked, setno=0, baseline=(None, 0))
    evoked.crop(tmin=0, tmax=0.3)

    cov = read_cov(fname_cov)
    cov = mne.cov.regularize(cov, evoked.info)

    alpha = 0.2
    stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                    xyz_same_gamma=True, update_mode=1)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 96397)

    stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                    xyz_same_gamma=False, update_mode=1)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 82010)

    # force fixed orientation
    stc, res = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                         xyz_same_gamma=False, update_mode=2,
                         loose=None, return_residual=True)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 83398)

    assert_array_almost_equal(evoked.times, res.times)
Пример #3
0
def test_apply_inverse_operator():
    """Test MNE inverse computation

    With and without precomputed inverse operator.
    """
    evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0))

    stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE")
    assert_true(stc.data.min() > 0)
    assert_true(stc.data.max() < 10e-10)
    assert_true(stc.data.mean() > 1e-11)

    stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA")
    assert_true(stc.data.min() > 0)
    assert_true(stc.data.max() < 9.0)
    assert_true(stc.data.mean() > 0.1)

    stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM")
    assert_true(stc.data.min() > 0)
    assert_true(stc.data.max() < 35)
    assert_true(stc.data.mean() > 0.1)

    # Test MNE inverse computation starting from forward operator
    evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0))
    fwd_op = read_forward_solution(fname_fwd, surf_ori=True)

    my_inv_op = make_inverse_operator(evoked.info,
                                      fwd_op,
                                      noise_cov,
                                      loose=0.2,
                                      depth=0.8)
    write_inverse_operator('test-inv.fif', my_inv_op)
    read_my_inv_op = read_inverse_operator('test-inv.fif')
    _compare(my_inv_op, read_my_inv_op)

    my_stc = apply_inverse(evoked, my_inv_op, lambda2, "dSPM")

    assert_true('dev_head_t' in my_inv_op['info'])
    assert_true('mri_head_t' in my_inv_op)

    assert_equal(stc.times, my_stc.times)
    assert_array_almost_equal(stc.data, my_stc.data, 2)
Пример #4
0
def test_inverse_operator_volume():
    """Test MNE inverse computation on volume source space"""
    evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0))
    inverse_operator_vol = read_inverse_operator(fname_vol_inv)
    stc = apply_inverse(evoked, inverse_operator_vol, lambda2, "dSPM")
    stc.save('tmp-vl.stc')
    stc2 = read_source_estimate('tmp-vl.stc')
    assert_true(np.all(stc.data > 0))
    assert_true(np.all(stc.data < 35))
    assert_array_almost_equal(stc.data, stc2.data)
    assert_array_almost_equal(stc.times, stc2.times)
Пример #5
0
def test_comparision_with_c():
    """Test of average obtained vs C code
    """
    c_evoked = fiff.Evoked(evoked_nf_name, setno=0)
    epochs = Epochs(raw, events, event_id, tmin, tmax,
                    baseline=None, preload=True,
                    reject=None, flat=None)
    evoked = epochs.average()
    sel = fiff.pick_channels(c_evoked.ch_names, evoked.ch_names)
    evoked_data = evoked.data
    c_evoked_data = c_evoked.data[sel]

    assert_true(evoked.nave == c_evoked.nave)
    assert_array_almost_equal(evoked_data, c_evoked_data, 10)
    assert_array_almost_equal(evoked.times, c_evoked.times, 12)
Пример #6
0
from numpy.testing import assert_array_almost_equal

import mne
from mne.datasets import sample
from mne import fiff, read_cov, read_forward_solution
from mne.inverse_sparse import gamma_map

data_path = sample.data_path()
fname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_fwd = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis-eeg-oct-6-fwd.fif')


forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True)
evoked = fiff.Evoked(fname_evoked, setno=0, baseline=(None, 0))
evoked.crop(tmin=0, tmax=0.3)

cov = read_cov(fname_cov)
cov = mne.cov.regularize(cov, evoked.info)


def test_gamma_map():
    """Test Gamma MAP inverse"""

    alpha = 0.2
    stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5,
                    xyz_same_gamma=True, update_mode=1)
    idx = np.argmax(np.sum(stc.data ** 2, axis=1))
    assert_true(np.concatenate(stc.vertno)[idx] == 96397)
Пример #7
0
def equalizeTriggers(subjID):

    os.chdir("/cluster/kuperberg/SemPrMM/MEG/data/" + subjID)

    expList = ['ATLLoc', 'MaskedMM', 'BaleenLP', 'BaleenHP', 'AXCPT']
    runDict = {
        'ATLLoc': [''],
        'MaskedMM': ['Run1', 'Run2'],
        'BaleenLP': ['Run1', 'Run2', 'Run3', 'Run4'],
        'BaleenHP': ['Run1', 'Run2', 'Run3', 'Run4'],
        'AXCPT': ['Run1', 'Run2']
    }

    codeGroupDict = {'AXCPT': ['AXCPT_prime', 'AXCPT_target']}

    codeDict = {'AXCPT_prime': ['5', '6'], 'AXCPT_target': ['1', '2', '3']}
    minDict = {}

    if subjID == 'ya3':
        runDict['AXCPT'] = ['Run1']
    if (subjID == 'ya1' or subjID == 'ya2' or subjID == 'ya4'
            or subjID == 'ya7' or subjID == 'ya8' or subjID == 'ya16'):
        runDict['AXCPT'] = ''

    #########################
    ##EQUALIZE TRIGGER COUNTS###
    print '----equalize triggers'
    for exp in expList:
        for codeGroup in codeGroupDict[exp]:
            evMin = 9999
            for code in codeDict[codeGroup]:
                print int(code) - 1
                aveName = '/cluster/kuperberg/SemPrMM/MEG/data/%s/ave_projon/%s_%s_All-ave.fif' % (
                    subjID, subjID, exp)
                print aveName
                evoked = fiff.Evoked(aveName,
                                     setno=int(code) - 1)  #needs revision
                print evoked.nave
                if int(evoked.nave) < evMin:
                    evMin = int(evoked.nave)
            minDict[codeGroup] = evMin
            print codeGroup, evMin, minDict[codeGroup]

        for run in runDict[exp]:
            inFile = 'eve/' + subjID + '_' + exp + run + 'Mod.eve'
            outFile = 'eve/' + subjID + '_' + exp + run + 'Mod-testeq.eve'  #when finalized, this should probably be ModRejEq.eve, and later scripts changed
            print inFile
            if os.path.exists(inFile):
                data = readInput.readTable(inFile)

                firstRow = data[0]
                firstSample = firstRow[0]
                firstTime = firstRow[1]

                flag = ''

                for row in data:
                    trigger = row[3]
                    time = row[1]

                writeOutput.writeTable(outFile, data)
Пример #8
0
#
# License: BSD (3-clause)

print __doc__

import matplotlib.pyplot as plt
from mne import fiff
from mne.datasets import sample

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

# Reading evoked data
evoked = fiff.Evoked(fname,
                     setno='Left Auditory',
                     baseline=(None, 0),
                     proj=True)

picks = fiff.pick_channels(ch_names=evoked.info['ch_names'],
                           include="MEG 2332",
                           exclude="bad")

# Create subplots
f, axarr = plt.subplots(3)
evoked.plot(exclude=[],
            picks=picks,
            axes=axarr[0],
            titles=dict(grad='Before time shifting'))

# Apply relative time-shift of 500 ms
evoked.shift_time(0.5, relative=True)
Пример #9
0
font = {
 'weight' : 'bold',
 'size'   : 12}
pl.rc('font', **font)
#figure(num=None, figsize=(16, 6), dpi=80, facecolor='w', edgecolor='k') # you could use this to change the size of the figure

                       
               
for c in range(2):
        
                ##get the data
                file = data_path + prefixList[c] +'-ave.fif'
                ##file = data_path + args.prefix1 +'-ave.fif'
                print file
                print 'set ',condList[c]
                evoked = fiff.Evoked(file,setno=condList[c],baseline=(-100,0),proj=False)
                times=evoked.times*1000
                print channelList
				
                for chan in channelList: 
						if chan == 'CZ':
							pl.subplot(3,3,2)
							pl.title("CZ")
                            ##pl.title(1.0, 1.0, 'FZ', fontsize='medium', verticalalignment='top')						
						elif chan == 'CPZ':
							pl.subplot(3,3,5)
							pl.title("CPZ")
							##pl.title(1.0, 1.0, 'CZ', fontsize='medium', verticalalignment='top')
							
						elif chan == 'PZ':
							pl.subplot(3,3,8)
Пример #10
0
def test_mxne_inverse():
    """Test (TF-)MxNE inverse computation"""
    # Handling forward solution
    evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0))

    # Read noise covariance matrix
    cov = read_cov(fname_cov)

    # Handling average file
    setno = 0
    loose = None
    depth = 0.9

    evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0))
    evoked.crop(tmin=-0.1, tmax=0.4)

    evoked_l21 = copy.deepcopy(evoked)
    evoked_l21.crop(tmin=0.08, tmax=0.1)
    label = read_label(fname_label)
    weights_min = 0.5
    forward = read_forward_solution(fname_fwd,
                                    force_fixed=False,
                                    surf_ori=True)

    # Reduce source space to make test computation faster
    inverse_operator = make_inverse_operator(evoked.info,
                                             forward,
                                             cov,
                                             loose=loose,
                                             depth=depth,
                                             fixed=True)
    stc_dspm = apply_inverse(evoked_l21,
                             inverse_operator,
                             lambda2=1. / 9.,
                             method='dSPM')
    stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0
    stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1.

    # MxNE tests
    alpha = 60  # spatial regularization parameter

    stc_prox = mixed_norm(evoked_l21,
                          forward,
                          cov,
                          alpha,
                          loose=None,
                          depth=0.9,
                          maxit=1000,
                          tol=1e-8,
                          active_set_size=10,
                          solver='prox')
    stc_cd = mixed_norm(evoked_l21,
                        forward,
                        cov,
                        alpha,
                        loose=None,
                        depth=0.9,
                        maxit=1000,
                        tol=1e-8,
                        active_set_size=10,
                        solver='cd')
    assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5)
    assert_array_almost_equal(stc_prox.data, stc_cd.data, 5)
    assert_true(stc_prox.vertno[1][0] in label.vertices)
    assert_true(stc_cd.vertno[1][0] in label.vertices)

    stc, _ = mixed_norm(evoked_l21,
                        forward,
                        cov,
                        alpha,
                        loose=None,
                        depth=depth,
                        maxit=500,
                        tol=1e-4,
                        active_set_size=10,
                        weights=stc_dspm,
                        weights_min=weights_min,
                        return_residual=True)

    assert_array_almost_equal(stc.times, evoked_l21.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)

    # Do with TF-MxNE for test memory savings
    alpha_space = 60.  # spatial regularization parameter
    alpha_time = 1.  # temporal regularization parameter

    stc, _ = tf_mixed_norm(evoked,
                           forward,
                           cov,
                           alpha_space,
                           alpha_time,
                           loose=loose,
                           depth=depth,
                           maxit=100,
                           tol=1e-4,
                           tstep=4,
                           wsize=16,
                           window=0.1,
                           weights=stc_dspm,
                           weights_min=weights_min,
                           return_residual=True)

    assert_array_almost_equal(stc.times, evoked.times, 5)
    assert_true(stc.vertno[1][0] in label.vertices)
Пример #11
0
from mne.datasets import sample
from mne.label import read_label
from mne import fiff, read_cov, read_forward_solution
from mne.mixed_norm.inverse import mixed_norm

examples_folder = op.join(op.dirname(__file__), '..', '..', '..', 'examples')
data_path = sample.data_path(examples_folder)
fname_data = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_fwd = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis-meg-oct-6-fwd.fif')
label = 'Aud-rh'
fname_label = op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label)

evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0))

# Read noise covariance matrix
cov = read_cov(fname_cov)

# Handling average file
setno = 0
loose = None

evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0))
evoked.crop(tmin=0.08, tmax=0.12)

# Handling forward solution
forward = read_forward_solution(fname_fwd, force_fixed=True)
label = read_label(fname_label)
Пример #12
0
def _get_evoked():
    evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0))
    evoked.crop(0, 0.2)
    return evoked
"""
# Author: Denis Engemann <d.engemann@fz-juelichde>
#         Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

print(__doc__)

from mne import fiff
from mne.datasets import sample
from nitime.viz import plot_tseries
import matplotlib.pyplot as plt


data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

# Reading
evoked = fiff.Evoked(fname, setno=0, baseline=(None, 0), proj=True)

# Pick channels to view
picks = fiff.pick_types(evoked.info, meg='grad', eeg=False, exclude='bads')

evoked_ts = evoked.to_nitime(picks=picks)

plot_tseries(evoked_ts)

plt.show()
Пример #14
0
parser = argparse.ArgumentParser(description='Get input')
parser.add_argument('prefix1', type=str)
parser.add_argument('prefix2', type=str)
parser.add_argument('set1', type=int)
parser.add_argument('set2', type=int)
parser.add_argument('sensor', type=int)
parser.add_argument('label1', type=str)
parser.add_argument('label2', type=str)

args = parser.parse_args()

data_path = '/cluster/kuperberg/SemPrMM/MEG/results/sensor_level/ga_fif/'

file1 = data_path + args.prefix1 + '-ave.fif'
evoked1 = fiff.Evoked(file1, setno=args.set1, baseline=(-100, 0), proj=False)
data1 = evoked1.data
wave1 = data1[args.sensor][:] * scalingFactor
print args.sensor

times = evoked1.times * 1000

file2 = data_path + args.prefix2 + '-ave.fif'
evoked2 = fiff.Evoked(file2, setno=args.set2, baseline=(-100, 0), proj=False)
data2 = evoked2.data
wave2 = data2[args.sensor][:] * scalingFactor

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

font = {'weight': 'bold', 'size': 16}
Пример #15
0
                            sub
                    ) > 3:  ##This makes the tabbing pretty for the table; different for longer subject names
                        beg = '%s\t' % sub
                    else:
                        beg = '%s\t\t' % sub
                subjLine.append(beg)
                if k == 'ATLLoc':
                    aveName = '/%s/kuperberg/SemPrMM/MEG/data/%s/ave_projon/%s_%s-ave.fif' % (
                        pre, sub, sub, k)
                else:
                    aveName = '/%s/kuperberg/SemPrMM/MEG/data/%s/ave_projon/%s_%s_All_ecgeog1-ave.fif' % (
                        pre, sub, sub, k)
                count = 0
                results = beg
                for code in codes:
                    evoked = fiff.Evoked(aveName, setno=count)
                    count = count + 1
                    results = results + '\t\t' + str(
                        '%.2f' % (float(evoked.nave) / v[sub][code][1]))
                    print results
                subject_lines.append(results)
                print sub, subject_lines
            #write out dat for each paradigm
            f = open(fname, 'w')
            f.write(code_line + '\n')
            f.write('\n'.join(subject_lines))
            f.close()
            print("Saved combined table to %s" % fname)
            make_lingua(fname)
    pass