Example #1
0
def test_evoked_resample():
    """Test for resampling of evoked data
    """
    # upsample, write it out, read it in
    ave = read_evoked(fname, 0)
    sfreq_normal = ave.info['sfreq']
    ave.resample(2 * sfreq_normal)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)
    ave_up = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    # compare it to the original
    ave_normal = read_evoked(fname, 0)

    # and compare the original to the downsampled upsampled version
    ave_new = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_new.resample(sfreq_normal)

    assert_array_almost_equal(ave_normal.data, ave_new.data, 2)
    assert_array_almost_equal(ave_normal.times, ave_new.times)
    assert_equal(ave_normal.nave, ave_new.nave)
    assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)
    assert_equal(ave_normal.kind, ave_new.kind)
    assert_equal(ave_normal.last, ave_new.last)
    assert_equal(ave_normal.first, ave_new.first)

    # for the above to work, the upsampling just about had to, but
    # we'll add a couple extra checks anyway
    assert_true(len(ave_up.times) == 2 * len(ave_normal.times))
    assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
Example #2
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evoked(fname, 0)

    write_evoked(op.join(tempdir, 'evoked.fif'), ave)
    ave2 = read_evoked(op.join(tempdir, 'evoked.fif'))

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evoked(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    setno = 'Left Auditory'
    assert_raises(ValueError, read_evoked, fname, setno, kind='stderr')
    assert_raises(ValueError, read_evoked, fname, setno, kind='standard_error')
    ave3 = read_evoked(fname, setno)
    assert_array_almost_equal(ave.data, ave3.data, 19)
Example #3
0
def test_evoked_standard_error():
    """Test calculation and read/write of standard error
    """
    epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0))
    evoked = [epochs.average(), epochs.standard_error()]
    fiff.write_evoked(op.join(tempdir, 'evoked.fif'), evoked)
    evoked2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1])
    evoked3 = [read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown'),
               read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown',
                           kind='standard_error')]
    for evoked_new in [evoked2, evoked3]:
        assert_true(evoked_new[0]._aspect_kind ==
                    fiff.FIFF.FIFFV_ASPECT_AVERAGE)
        assert_true(evoked_new[0].kind == 'average')
        assert_true(evoked_new[1]._aspect_kind ==
                    fiff.FIFF.FIFFV_ASPECT_STD_ERR)
        assert_true(evoked_new[1].kind == 'standard_error')
        for ave, ave2 in zip(evoked, evoked_new):
            assert_array_almost_equal(ave.data, ave2.data)
            assert_array_almost_equal(ave.times, ave2.times)
            assert_equal(ave.nave, ave2.nave)
            assert_equal(ave._aspect_kind, ave2._aspect_kind)
            assert_equal(ave.kind, ave2.kind)
            assert_equal(ave.last, ave2.last)
            assert_equal(ave.first, ave2.first)
Example #4
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evokeds(fname, 0)

    write_evokeds(op.join(tempdir, 'evoked.fif'), ave)
    ave2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0]

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evokeds(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    condition = 'Left Auditory'
    assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')
    assert_raises(ValueError,
                  read_evokeds,
                  fname,
                  condition,
                  kind='standard_error')
    ave3 = read_evokeds(fname, condition)
    assert_array_almost_equal(ave.data, ave3.data, 19)

    # test deprecation warning for read_evoked and write_evoked
    # XXX should be deleted for 0.9 release
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        ave = read_evoked(fname, setno=0)
        assert_true(w[0].category == DeprecationWarning)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        write_evoked(op.join(tempdir, 'evoked.fif'), ave)
        assert_true(w[0].category == DeprecationWarning)

    # test read_evokeds and write_evokeds
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves1 = read_evokeds(fname)
    aves2 = read_evokeds(fname, [0, 1, 2, 3])
    aves3 = read_evokeds(fname, types)
    write_evokeds(op.join(tempdir, 'evoked.fif'), aves1)
    aves4 = read_evokeds(op.join(tempdir, 'evoked.fif'))
    for aves in [aves2, aves3, aves4]:
        for [av1, av2] in zip(aves1, aves):
            assert_array_almost_equal(av1.data, av2.data)
            assert_array_almost_equal(av1.times, av2.times)
            assert_equal(av1.nave, av2.nave)
            assert_equal(av1.kind, av2.kind)
            assert_equal(av1._aspect_kind, av2._aspect_kind)
            assert_equal(av1.last, av2.last)
            assert_equal(av1.first, av2.first)
            assert_equal(av1.comment, av2.comment)
Example #5
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evoked(fname, 0)

    write_evoked(op.join(tempdir, 'evoked.fif'), ave)
    ave2 = read_evoked(op.join(tempdir, 'evoked.fif'))

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evoked(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    setno = 'Left Auditory'
    assert_raises(ValueError, read_evoked, fname, setno, kind='stderr')
    assert_raises(ValueError, read_evoked, fname, setno, kind='standard_error')
    ave3 = read_evoked(fname, setno)
    assert_array_almost_equal(ave.data, ave3.data, 19)
Example #6
0
def test_evoked_resample():
    """Test for resampling of evoked data
    """
    # upsample, write it out, read it in
    ave = read_evoked(fname, 0)
    sfreq_normal = ave.info['sfreq']
    ave.resample(2 * sfreq_normal)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)
    ave_up = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    # compare it to the original
    ave_normal = read_evoked(fname, 0)

    # and compare the original to the downsampled upsampled version
    ave_new = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_new.resample(sfreq_normal)

    assert_array_almost_equal(ave_normal.data, ave_new.data, 2)
    assert_array_almost_equal(ave_normal.times, ave_new.times)
    assert_equal(ave_normal.nave, ave_new.nave)
    assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)
    assert_equal(ave_normal.kind, ave_new.kind)
    assert_equal(ave_normal.last, ave_new.last)
    assert_equal(ave_normal.first, ave_new.first)

    # for the above to work, the upsampling just about had to, but
    # we'll add a couple extra checks anyway
    assert_true(len(ave_up.times) == 2 * len(ave_normal.times))
    assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
Example #7
0
def test_evoked_standard_error():
    """Test calculation and read/write of standard error
    """
    epochs = Epochs(raw,
                    events[:4],
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=(None, 0))
    evoked = [epochs.average(), epochs.standard_error()]
    fiff.write_evoked(op.join(tempdir, 'evoked.fif'), evoked)
    evoked2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1])
    evoked3 = [
        read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown'),
        read_evoked(op.join(tempdir, 'evoked.fif'),
                    'Unknown',
                    kind='standard_error')
    ]
    for evoked_new in [evoked2, evoked3]:
        assert_true(
            evoked_new[0]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE)
        assert_true(evoked_new[0].kind == 'average')
        assert_true(
            evoked_new[1]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR)
        assert_true(evoked_new[1].kind == 'standard_error')
        for ave, ave2 in zip(evoked, evoked_new):
            assert_array_almost_equal(ave.data, ave2.data)
            assert_array_almost_equal(ave.times, ave2.times)
            assert_equal(ave.nave, ave2.nave)
            assert_equal(ave._aspect_kind, ave2._aspect_kind)
            assert_equal(ave.kind, ave2.kind)
            assert_equal(ave.last, ave2.last)
            assert_equal(ave.first, ave2.first)
Example #8
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz) with integer and str args
    """
    ave = read_evokeds(fname, 0)

    write_evokeds(op.join(tempdir, 'evoked.fif'), ave)
    ave2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0]

    # This not being assert_array_equal due to windows rounding
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave._aspect_kind, ave2._aspect_kind)
    assert_equal(ave.kind, ave2.kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evokeds(fname_gz, 0)
    assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))

    # test str access
    condition = 'Left Auditory'
    assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')
    assert_raises(ValueError, read_evokeds, fname, condition,
                  kind='standard_error')
    ave3 = read_evokeds(fname, condition)
    assert_array_almost_equal(ave.data, ave3.data, 19)

    # test deprecation warning for read_evoked and write_evoked
    # XXX should be deleted for 0.9 release
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        ave = read_evoked(fname, setno=0)
        assert_true(w[0].category == DeprecationWarning)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        write_evoked(op.join(tempdir, 'evoked.fif'), ave)
        assert_true(w[0].category == DeprecationWarning)

    # test read_evokeds and write_evokeds
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves1 = read_evokeds(fname)
    aves2 = read_evokeds(fname, [0, 1, 2, 3])
    aves3 = read_evokeds(fname, types)
    write_evokeds(op.join(tempdir, 'evoked.fif'), aves1)
    aves4 = read_evokeds(op.join(tempdir, 'evoked.fif'))
    for aves in [aves2, aves3, aves4]:
        for [av1, av2] in zip(aves1, aves):
            assert_array_almost_equal(av1.data, av2.data)
            assert_array_almost_equal(av1.times, av2.times)
            assert_equal(av1.nave, av2.nave)
            assert_equal(av1.kind, av2.kind)
            assert_equal(av1._aspect_kind, av2._aspect_kind)
            assert_equal(av1.last, av2.last)
            assert_equal(av1.first, av2.first)
            assert_equal(av1.comment, av2.comment)
Example #9
0
def test_io_multi_evoked():
    """Test IO for multiple evoked datasets
    """
    aves = read_evoked(fname, [0, 1, 2, 3])
    write_evoked('evoked.fif', aves)
    aves2 = read_evoked('evoked.fif', [0, 1, 2, 3])
    for [ave, ave2] in zip(aves, aves2):
        assert_array_almost_equal(ave.data, ave2.data)
        assert_array_almost_equal(ave.times, ave2.times)
        assert_equal(ave.nave, ave2.nave)
        assert_equal(ave.aspect_kind, ave2.aspect_kind)
        assert_equal(ave.last, ave2.last)
        assert_equal(ave.first, ave2.first)
Example #10
0
def test_io_evoked():
    """Test IO for evoked data
    """
    ave = read_evoked(fname)

    ave.crop(tmin=0)

    write_evoked('evoked.fif', ave)
    ave2 = read_evoked('evoked.fif')

    assert_array_almost_equal(ave.data, ave2.data)
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave.aspect_kind, ave2.aspect_kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)
Example #11
0
def test_evoked_standard_error():
    """Test calculation and read/write of standard error
    """
    epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0))
    evoked = [epochs.average(), epochs.standard_error()]
    fiff.write_evoked('evoked.fif', evoked)
    evoked2 = fiff.read_evoked('evoked.fif', [0, 1])
    assert_true(evoked2[0].aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE)
    assert_true(evoked2[1].aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR)
    for ave, ave2 in zip(evoked, evoked2):
        assert_array_almost_equal(ave.data, ave2.data)
        assert_array_almost_equal(ave.times, ave2.times)
        assert_equal(ave.nave, ave2.nave)
        assert_equal(ave.aspect_kind, ave2.aspect_kind)
        assert_equal(ave.last, ave2.last)
        assert_equal(ave.first, ave2.first)
Example #12
0
def test_io_multi_evoked():
    """Test IO for multiple evoked datasets
    """
    aves = read_evoked(fname, [0, 1, 2, 3])
    write_evoked(op.join(tempdir, 'evoked.fif'), aves)
    aves2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1, 2, 3])
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves3 = read_evoked(op.join(tempdir, 'evoked.fif'), types)
    for aves_new in [aves2, aves3]:
        for [ave, ave_new] in zip(aves, aves_new):
            assert_array_almost_equal(ave.data, ave_new.data)
            assert_array_almost_equal(ave.times, ave_new.times)
            assert_equal(ave.nave, ave_new.nave)
            assert_equal(ave.kind, ave_new.kind)
            assert_equal(ave._aspect_kind, ave_new._aspect_kind)
            assert_equal(ave.last, ave_new.last)
            assert_equal(ave.first, ave_new.first)
    # this should throw an error since there are mulitple datasets
    assert_raises(ValueError, read_evoked, fname)
Example #13
0
def test_io_multi_evoked():
    """Test IO for multiple evoked datasets
    """
    aves = read_evoked(fname, [0, 1, 2, 3])
    write_evoked(op.join(tempdir, 'evoked.fif'), aves)
    aves2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1, 2, 3])
    types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']
    aves3 = read_evoked(op.join(tempdir, 'evoked.fif'), types)
    for aves_new in [aves2, aves3]:
        for [ave, ave_new] in zip(aves, aves_new):
            assert_array_almost_equal(ave.data, ave_new.data)
            assert_array_almost_equal(ave.times, ave_new.times)
            assert_equal(ave.nave, ave_new.nave)
            assert_equal(ave.kind, ave_new.kind)
            assert_equal(ave._aspect_kind, ave_new._aspect_kind)
            assert_equal(ave.last, ave_new.last)
            assert_equal(ave.first, ave_new.first)
    # this should throw an error since there are mulitple datasets
    assert_raises(ValueError, read_evoked, fname)
Example #14
0
def test_io_evoked():
    """Test IO for evoked data (fif + gz)
    """
    ave = read_evoked(fname)

    ave.crop(tmin=0)

    write_evoked('evoked.fif', ave)
    ave2 = read_evoked('evoked.fif')

    assert_array_almost_equal(ave.data, ave2.data)
    assert_array_almost_equal(ave.times, ave2.times)
    assert_equal(ave.nave, ave2.nave)
    assert_equal(ave.aspect_kind, ave2.aspect_kind)
    assert_equal(ave.last, ave2.last)
    assert_equal(ave.first, ave2.first)

    # test compressed i/o
    ave2 = read_evoked(fname_gz)
    ave2.crop(tmin=0)
    assert_array_equal(ave.data, ave2.data)
Example #15
0
def test_shift_time_evoked():
    """ Test for shifting of time scale
    """
    # Shift backward
    ave = read_evoked(fname, 0)
    ave.shift_time(-0.1, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)

    # Shift forward twice the amount
    ave_bshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_bshift.shift_time(0.2, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave_bshift)

    # Shift backward again
    ave_fshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_fshift.shift_time(-0.1, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave_fshift)

    ave_normal = read_evoked(fname, 0)
    ave_relative = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    assert_true(np.allclose(ave_normal.data, ave_relative.data,
                            atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)

    assert_equal(ave_normal.last, ave_relative.last)
    assert_equal(ave_normal.first, ave_relative.first)

    # Absolute time shift
    ave = read_evoked(fname, 0)
    ave.shift_time(-0.3, relative=False)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)

    ave_absolute = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    assert_true(np.allclose(ave_normal.data, ave_absolute.data,
                            atol=1e-16, rtol=1e-3))
    assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
Example #16
0
def test_shift_time_evoked():
    """ Test for shifting of time scale
    """
    # Shift backward
    ave = read_evoked(fname, 0)
    ave.shift_time(-0.1, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)

    # Shift forward twice the amount
    ave_bshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_bshift.shift_time(0.2, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave_bshift)

    # Shift backward again
    ave_fshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0)
    ave_fshift.shift_time(-0.1, relative=True)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave_fshift)

    ave_normal = read_evoked(fname, 0)
    ave_relative = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    assert_true(
        np.allclose(ave_normal.data, ave_relative.data, atol=1e-16, rtol=1e-3))
    assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)

    assert_equal(ave_normal.last, ave_relative.last)
    assert_equal(ave_normal.first, ave_relative.first)

    # Absolute time shift
    ave = read_evoked(fname, 0)
    ave.shift_time(-0.3, relative=False)
    write_evoked(op.join(tempdir, 'evoked.fif'), ave)

    ave_absolute = read_evoked(op.join(tempdir, 'evoked.fif'), 0)

    assert_true(
        np.allclose(ave_normal.data, ave_absolute.data, atol=1e-16, rtol=1e-3))
    assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
Example #17
0
        fiff.Raw.filter(raw, l_freq = hp_cutoff, h_freq = lp_cutoff)
        
        ##Pick all channels 
        picks = []
        for i in range(raw.info['nchan']):
            picks.append(i)
            
        ##Read Epochs and compute Evoked :) 
        print 'Reading Epochs from raw file...'
        epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline = (None,0), picks = picks, proj = True, name = condName, preload = True, flat = dict(mag = magFlat, grad= gradFlat), reject=dict(mag=magRej, grad=gradRej))
        print epochs
        evoked = [epochs[cond].average(picks =picks) for cond in event_id]
        
        ##Write Evoked 
        print 'Writing Evoked data to -ave.fif file...' 
        fiff.write_evoked(data_path + '/ave_projon/'+subjID+'_' + par + run +'-ave.fif', evoked)
        evokedRuns.append(evoked)
        print 'Completed! See ave.fif result in folder', data_path + '/ave_projon/'

##Show the Result - Plotting the evoked data
#mne.viz.plot_evoked(evoked, exclude = [])

#print len(evokedRuns)

##Make the Final Grand average of all the runs
runData = []
runNave = []
newEvokeds = []
newEvoked = copy.deepcopy(evoked)
count = 0 
numCond = len(newEvoked)
Example #18
0
    for i in range(raw_ssp.info['nchan']):
        picks.append(i)

    ###Read epochs
    epochs = mne.Epochs(raw_ssp, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0),add_eeg_ref=avgRefVal, proj=projVal,reject=dict(eeg=eegRej,mag=magRej,grad=gradRej),flat=dict(mag=magFlat, grad=gradFlat))
    print epochs    
    evokeds = [epochs[cond].average(picks=picks) for cond in event_id]

    ###Add the 120 conditions for BaleenHP
    if exp == 'BaleenHP':
        evoked_Rel = evokeds[4]+evokeds[5]
        evoked_Unrel = evokeds[6]+evokeds[7]
        evokeds.append(evoked_Rel)
        evokeds.append(evoked_Unrel)

    fiff.write_evoked(data_path + 'ave_projon/'+args.subj+'_'+exp+evRun+'-ave.fif',evokeds)
    evokedRuns.append(evokeds)




##############################
############Make grand-average
runData = []
runNave = []
newEvoked = copy.deepcopy(evokedRuns[0])
print newEvoked
count = 0
numCond = len(newEvoked)

for c in range(numCond):
Example #19
0
def mnepy_avg(subjID,run):
    import mne
    from mne import fiff
    from mne import viz
    #from mne.viz import evoked
    import argparse
    import copy
    import numpy
    
    #######Get Input ##
    print subjID

    
    ########Analysis Parameters##

    
    ###Projection and Average Reference and Filtering
    projVal = True
    avgRefVal = False
    hp_cutoff = 0.7
    lp_cutoff = 40 
    event_id = 2
    #######Experiment specific parameters 
    ###TimeWindow
    tmin = 0
    tmax = 2.0 ##float(cc.epMax[eve])
    
    if run == 'CRM':
        tmax = 1.0 
    elif run == 'DFNAM':
        tmax = 2.0
    ########Artifact rejection parameters
    ###General
    gradRej = 2000e-13
    magRej = 3000e-15
    magFlat = 1e-14
    gradFlat = 1000e-15
    ####################################
    #######Compute averages for each run 
# #   evoked=[]
#    if subjID == 'EP2':
#        runs = ['run1', 'run2', 'run3']
    
    evokedRuns =[]
#    for run in runs:
        ###Event file suffix 
    eveSuffix = '.eve' 
    eve_file = run + eveSuffix #eve + eveSuffix 
    print "You have chosen the event file " + eve_file
    ##Setup Subject Speciifc Information
    data_path = '/home/custine/MEG/data/epi_conn/' +subjID
    event_file = data_path + '/eve/' + eve_file
    print event_file
    
    raw_file = data_path + '/' + run +'_raw.fif' ##Change this suffix if you are using SSP 
    avgLog_file = data_path + '/logs/' +run+ '_py-ave.log'
    print raw_file, avgLog_file
#        
    ##Setup Reading fiff data structure
    print 'Reading Raw data... '
    raw = fiff.Raw(raw_file, preload = True)
    events = mne.read_events(event_file)
    #print events
    
    mne.set_log_file(fname = avgLog_file, overwrite = True)
    
    ##Filter raw data 
    fiff.Raw.filter(raw, l_freq = hp_cutoff, h_freq = lp_cutoff)
    
    #Pick all channels 
    picks = []
    for i in range(raw.info['nchan']):
        picks.append(i)
        
    ##Read Epochs and compute Evoked :) 
    print 'Reading Epochs from evoked file...'
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline = (None,0), proj = True, picks = picks, preload = True, flat = dict(mag = magFlat, grad= gradFlat), reject=dict(mag=magRej, grad=gradRej))
    print epochs
    evoked = [epochs.average(picks =None)]
    #    #        epochs.plot()
    
    ##Write Evoked 
    print 'Writing Evoked data to -ave.fif file...' 
    fiff.write_evoked(data_path + '/ave_projon/' + run +'-noise-ave.fif', evoked)
    evokedRuns.append(evoked)
    print 'Completed! See ave.fif result in folder', data_path + '/ave_projon/'
#
##    #        ###############################################################################
##    #        #Show the Result - Plotting the evoked data
##    #        mne.viz.evoked.plot_evoked(evoked, exclude = [])
#    
    print len(evokedRuns)
Example #20
0
picks = fiff.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=True,
                        include=include, exclude='bads')
# Read epochs
epochs = mne.Epochs(raw, events, event_ids, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(eeg=80e-6, eog=150e-6))
# Let's equalize the trial counts in each condition
epochs.equalize_event_counts(['AudL', 'AudR', 'VisL', 'VisR'], copy=False)
# Now let's combine some conditions
combine_event_ids(epochs, ['AudL', 'AudR'], {'Auditory': 12}, copy=False)
combine_event_ids(epochs, ['VisL', 'VisR'], {'Visual': 34}, copy=False)

# average epochs and get Evoked datasets
evokeds = [epochs[cond].average() for cond in ['Auditory', 'Visual']]

# save evoked data to disk
fiff.write_evoked('sample_auditory_and_visual_eeg-ave.fif', evokeds)

###############################################################################
# View evoked response
import matplotlib.pyplot as plt
plt.clf()
ax = plt.subplot(2, 1, 1)
evokeds[0].plot(axes=ax)
plt.title('EEG evoked potential, auditory trials')
plt.ylabel('Potential (uV)')
ax = plt.subplot(2, 1, 2)
evokeds[1].plot(axes=ax)
plt.title('EEG evoked potential, visual trials')
plt.ylabel('Potential (uV)')
plt.show()
    mne.epochs.equalize_epoch_counts([epochsAPrime, epochsBPrime],
                                     method="mintime")

    print "Epochs after equalising"
    print epochsAPrime
    print epochsBPrime

    ###Averaging Epochs#######
    evokedAPrime = epochsAPrime.average(picks=picks)
    evokedBPrime = epochsBPrime.average(picks=picks)
    for ep in [evokedAPrime, evokedBPrime]:
        evokeds.append(ep)

    ###Computing Evoked Potentials#######
    fiff.write_evoked(
        data_path + '/' + ave_dest + '/' + args.subj + '_' + expName + evRun +
        '-equalisedPri-ave.fif', evokeds)
    evokedRuns.append(evokeds)

#######################################
##########Make grand-average###########
runData = []
runNave = []
newEvoked = copy.deepcopy(evokedRuns[0])
count = 0
numCond = len(newEvoked)

for c in range(numCond):
    for evRun in evokedRuns:
        runData.append(evRun[c].data)
        runNave.append(evRun[c].nave)
    print "Epochs After equalising"
    print epochsAX
    print epochsBX
    print epochsAY
    print epochsBY
   
    ###Averaging Epochs#######
    evokedAY =epochsAY.average(picks = picks)
    evokedBX =epochsBX.average(picks = picks)
    evokedBY =epochsBY.average(picks = picks)
    evokedAX =epochsAX.average(picks = picks)
    for ep in [evokedAY, evokedBX, evokedBY, evokedAX]:
           evokeds.append(ep)

    fiff.write_evoked(data_path +'/' + ave_dest +'/'+ args.subj+'_'+expName+evRun+'-equalisedTar-ave.fif',evokeds)
    evokedRuns.append(evokeds)

##
####################################
############Make grand-average######
runData = []
runNave = []
newEvoked = copy.deepcopy(evokedRuns[0])
#print newEvoked
count = 0
numCond = len(newEvoked)

for c in range(numCond):
    for evRun in evokedRuns:
        runData.append(evRun[c].data)
Example #23
0
def mnepy_avg(subjID, sessID, eve, ssp_type):
    import mne
    from mne import fiff
    from mne import viz
    from mne.viz import evoked
    import argparse
    import condCodes as cc
    import copy
    import numpy
    
    #######Get Input ##
    print subjID
    print sessID
    print eve
    data_path = '/home/custine/MEG/data/krns_kr3/' +subjID+'/'+sessID
    if ssp_type == 'run':
        raw_data_path = '/home/custine/MEG/data/krns_kr3/' +subjID+'/'+sessID
        runSuffix = '_raw.fif'
    elif ssp_type == 'ecg' or ssp_type == 'eog':
        raw_data_path = '/home/custine/MEG/data/krns_kr3/' +subjID+'/'+sessID + '/ssp/mne'
        runSuffix = '_clean_' + ssp_type + '_raw.fif'
    ########Analysis Parameters##
    ###Event file suffix 
    eveSuffix = '-Triggers.eve' 
    eve_file = eve + eveSuffix #eve + eveSuffix 
    print "You have chosen the event file " + eve_file
    
    ###Projection and Average Reference and Filtering
    projVal = True
    avgRefVal = False
    hp_cutoff = 0.7
    lp_cutoff = 50 
    #######Experiment specific parameters 
    ###EventLabels and Runs
    runs = cc.runDict[eve] ##TESTING################################################
    print runs
    labelList = cc.condLabels[eve]
    event_id = {}
    condName = {}
    for row in labelList:
        event_id[row[1]] = int(row[0])
        condName[row[1]] = row[1]
    print event_id 
    ###TimeWindow
    tmin = -.5
    tmax = float(cc.epMax[eve])
#    tmax = 3.00 #4Words Category 
    ########Artifact rejection parameters
    ###General
    gradRej = 4000e-13
    magRej = 4000e-12
    magFlat = 1e-14
    gradFlat = 1000e-15
    ####################################
    ######Compute averages for each run 
    evoked=[]
    
    evokedRuns =[]
    for runID in runs:
            print runID
            ##Setup Subject Speciifc Information
            
            event_file = data_path + '/eve/triggers/' + subjID + '_'+ sessID +'_'+runID +'_' + eve_file
            print event_file
            
            raw_file = raw_data_path + '/' + subjID + '_' + sessID+ '_' + runID + runSuffix ##Change this suffix if you are using SSP ##_clean_ecg_
            avgLog_file = data_path + '/ave_projon/logs/' +subjID + '_' + sessID+ '_'+runID + '_'+eve+'_' + ssp_type +'-ave.log'
            print raw_file, avgLog_file
            
            ##Setup Reading fiff data structure
            print 'Reading Raw data... '
            raw = fiff.Raw(raw_file, preload = True)
            events = mne.read_events(event_file)
            print events
            
            mne.set_log_file(fname = avgLog_file, overwrite = True)
            
            ##Filter raw data 
            fiff.Raw.filter(raw, l_freq = hp_cutoff, h_freq = lp_cutoff)
            
            ##Pick all channels 
            picks = []
            for i in range(raw.info['nchan']):
                picks.append(i)
                
            ##Read Epochs and compute Evoked :) 
            print 'Reading Epochs from evoked raw file...'
            epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline = (-0.5,0), picks = picks, proj = True, name = condName, preload = True, flat = dict(mag = magFlat, grad= gradFlat), reject=dict(mag=magRej, grad=gradRej))
            print epochs
            evoked = [epochs[cond].average(picks =picks) for cond in event_id]
#    #        epochs.plot()
            
            ##Write Evoked 
            print 'Writing Evoked data to -ave.fif file...' 
            fiff.write_evoked(data_path + '/ave_projon/' + subjID+'_' + sessID+'_'+runID+'_' + eve +'_' + ssp_type+'-ave.fif', evoked)
            evokedRuns.append(evoked)
            print 'Completed! See ave.fif result in folder', data_path + '/ave_projon/'

            ###############################################################################
            ##Show the Result - Plotting the evoked data
            #mne.viz.evoked.plot_evoked(evoked, exclude = [])
    
    print len(evokedRuns)
    
    ##Make the Final Grand average of all the runs
    runData = []
    runNave = []

    newEvoked = copy.deepcopy(evoked)
    print newEvoked
    numCond = len(newEvoked)
    print 'Length', numCond
    for c in range(numCond):
        for evRun in evokedRuns:
            runData.append(evRun[c].data)
            runNave.append(evRun[c].nave)
        print 'Jane Here', c, runNave    
        gaveData = numpy.mean(runData,0)
        gaveNave = numpy.sum(runNave)
        print 'Sum', sum(runNave)
    
        newEvoked[c].data = gaveData
        newEvoked[c].nave = gaveNave
        
#        runData = []
#        runNave = []
    print newEvoked[0].nave
    
    ##Write Grand average Evoked     
    fiff.write_evoked(data_path + '/ave_projon/'+subjID+'_' + sessID+'_' + eve +'_' + ssp_type+'_All-ave.fif', newEvoked)