• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mne.find_events函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mne.find_events函数的典型用法代码示例。如果您正苦于以下问题:Python find_events函数的具体用法?Python find_events怎么用?Python find_events使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了find_events函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_gdf_data

def test_gdf_data():
    """Test reading raw GDF 1.x files."""
    with warnings.catch_warnings(record=True):  # interpolate / overlap events
        raw = read_raw_edf(gdf1_path + '.gdf', eog=None,
                           misc=None, preload=True, stim_channel='auto')
    picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
    data, _ = raw[picks]

    # this .npy was generated using the official biosig python package
    raw_biosig = np.load(gdf1_path + '_biosig.npy')
    raw_biosig = raw_biosig * 1e-6  # data are stored in microvolts
    data_biosig = raw_biosig[picks]

    # Assert data are almost equal
    assert_array_almost_equal(data, data_biosig, 8)

    # Test for stim channel
    events = find_events(raw, shortest_event=1)
    # The events are overlapping.
    assert_array_equal(events[:, 0], raw._raw_extras[0]['events'][1][::2])

    # Test events are encoded to stim channel.
    events = find_events(raw)
    evs = raw.find_edf_events()
    assert_true(all([event in evs[1] for event in events[:, 0]]))
开发者ID:HSMin,项目名称:mne-python,代码行数:25,代码来源:test_gdf.py


示例2: test_raw_events

def test_raw_events():
    """Test creating stim channel from raw SQD file."""
    def evts(a, b, c, d, e, f=None):
        out = [[269, a, b], [281, b, c], [1552, c, d], [1564, d, e]]
        if f is not None:
            out.append([2000, e, f])
        return out

    raw = read_raw_kit(sqd_path)
    assert_array_equal(find_events(raw, output='step', consecutive=True),
                       evts(255, 254, 255, 254, 255, 0))

    raw = read_raw_kit(sqd_path, slope='+')
    assert_array_equal(find_events(raw, output='step', consecutive=True),
                       evts(0, 1, 0, 1, 0))

    raw = read_raw_kit(sqd_path, stim='<', slope='+')
    assert_array_equal(find_events(raw, output='step', consecutive=True),
                       evts(0, 128, 0, 128, 0))

    raw = read_raw_kit(sqd_path, stim='<', slope='+', stim_code='channel')
    assert_array_equal(find_events(raw, output='step', consecutive=True),
                       evts(0, 160, 0, 160, 0))

    raw = read_raw_kit(sqd_path, stim=range(160, 162), slope='+',
                       stim_code='channel')
    assert_array_equal(find_events(raw, output='step', consecutive=True),
                       evts(0, 160, 0, 160, 0))
开发者ID:HSMin,项目名称:mne-python,代码行数:28,代码来源:test_kit.py


示例3: test_kit2fiff_model

def test_kit2fiff_model():
    """Test CombineMarkersModel Traits Model"""
    from mne.gui._kit2fiff_gui import Kit2FiffModel

    model = Kit2FiffModel()
    assert_false(model.can_save)
    model.markers.mrk1.file = mrk_pre_path
    model.markers.mrk2.file = mrk_post_path
    model.sqd_file = sqd_path
    model.hsp_file = hsp_path
    assert_false(model.can_save)
    model.fid_file = fid_path

    # export raw
    assert_true(model.can_save)
    raw_out = model.get_raw()
    raw_out.save(tgt_fname)
    raw = Raw(tgt_fname)

    # Compare exported raw with the original binary conversion
    raw_bin = Raw(fif_path)
    trans_bin = raw.info['dev_head_t']['trans']
    assert_equal(raw_bin.info.keys(), raw.info.keys())
    trans_transform = raw_bin.info['dev_head_t']['trans']
    assert_allclose(trans_transform, trans_bin, 0.1)

    # Averaging markers
    model.markers.mrk3.method = "Average"
    trans_avg = model.dev_head_trans
    assert_false(np.all(trans_avg == trans_transform))
    assert_allclose(trans_avg, trans_bin, 0.1)

    # Test exclusion of one marker
    model.markers.mrk3.method = "Transform"
    model.use_mrk = [1, 2, 3, 4]
    assert_false(np.all(model.dev_head_trans == trans_transform))
    assert_false(np.all(model.dev_head_trans == trans_avg))
    assert_false(np.all(model.dev_head_trans == np.eye(4)))

    # test setting stim channels
    model.stim_slope = '+'
    events_bin = mne.find_events(raw_bin, stim_channel='STI 014')

    model.stim_chs = '<'
    raw = model.get_raw()
    events = mne.find_events(raw, stim_channel='STI 014')
    assert_array_equal(events, events_bin)

    events_rev = events_bin.copy()
    events_rev[:, 2] = 1
    model.stim_chs = '>'
    raw = model.get_raw()
    events = mne.find_events(raw, stim_channel='STI 014')
    assert_array_equal(events, events_rev)

    model.stim_chs = 'man'
    model.stim_chs_manual = list(range(167, 159, -1))
    raw = model.get_raw()
    events = mne.find_events(raw, stim_channel='STI 014')
    assert_array_equal(events, events_bin)
开发者ID:dengemann,项目名称:mne-python,代码行数:60,代码来源:test_kit2fiff_gui.py


示例4: test_gdf_data

def test_gdf_data():
    """Test reading raw GDF 1.x files."""
    with pytest.warns(RuntimeWarning, match='Overlapping events'):
        raw = read_raw_edf(gdf1_path + '.gdf', eog=None,
                           misc=None, preload=True, stim_channel='auto')
    picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
    data, _ = raw[picks]

    # this .npy was generated using the official biosig python package
    raw_biosig = np.load(gdf1_path + '_biosig.npy')
    raw_biosig = raw_biosig * 1e-6  # data are stored in microvolts
    data_biosig = raw_biosig[picks]

    # Assert data are almost equal
    assert_array_almost_equal(data, data_biosig, 8)

    # Test for stim channel
    events = find_events(raw, shortest_event=1)
    # The events are overlapping.
    assert_array_equal(events[:, 0], raw._raw_extras[0]['events'][1][::2])

    # Test events are encoded to stim channel.
    events = find_events(raw)
    evs = raw.find_edf_events()
    assert (all([event in evs[1] for event in events[:, 0]]))

    # gh-5604
    assert raw.info['meas_date'] == DATE_NONE
    with pytest.warns(RuntimeWarning, match='Overlapping events'):
        _test_raw_reader(read_raw_edf, input_fname=gdf1_path + '.gdf',
                         eog=None, misc=None, stim_channel='auto')
开发者ID:jhouck,项目名称:mne-python,代码行数:31,代码来源:test_gdf.py


示例5: _assert_iter_sim

def _assert_iter_sim(raw_sim, raw_new, new_event_id):
    events = find_events(raw_sim, initial_event=True)
    events_tuple = find_events(raw_new, initial_event=True)
    assert_array_equal(events_tuple[:, :2], events[:, :2])
    assert_array_equal(events_tuple[:, 2], new_event_id)
    data_sim = raw_sim[:-1][0]
    data_new = raw_new[:-1][0]
    assert_array_equal(data_new, data_sim)
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:8,代码来源:test_raw.py


示例6: test_fix_stim

def test_fix_stim():
    """Test fixing stim STI016 for Neuromag."""
    raw = read_raw_fif(raw_fname, preload=True)
    # 32768 (016) + 3 (002+001) bits gets incorrectly coded during acquisition
    raw._data[raw.ch_names.index('STI 014'), :3] = [0, -32765, 0]
    with pytest.warns(RuntimeWarning, match='STI016'):
        events = find_events(raw, 'STI 014')
    assert_array_equal(events[0], [raw.first_samp + 1, 0, 32765])
    events = find_events(raw, 'STI 014', uint_cast=True)
    assert_array_equal(events[0], [raw.first_samp + 1, 0, 32771])
开发者ID:kambysese,项目名称:mne-python,代码行数:10,代码来源:test_event.py


示例7: test_fix_stim

def test_fix_stim():
    """Test fixing stim STI016 for Neuromag."""
    raw = read_raw_fif(raw_fname, preload=True)
    # 32768 (016) + 3 (002+001) bits gets incorrectly coded during acquisition
    raw._data[raw.ch_names.index('STI 014'), :3] = [0, -32765, 0]
    with warnings.catch_warnings(record=True) as w:
        events = find_events(raw, 'STI 014')
    assert_true(len(w) >= 1)
    assert_true(any('STI016' in str(ww.message) for ww in w))
    assert_array_equal(events[0], [raw.first_samp + 1, 0, 32765])
    events = find_events(raw, 'STI 014', uint_cast=True)
    assert_array_equal(events[0], [raw.first_samp + 1, 0, 32771])
开发者ID:deep-introspection,项目名称:mne-python,代码行数:12,代码来源:test_event.py


示例8: test_events

def test_events():
    """Test reading and modifying events"""
    tempdir = _TempDir()
    raw = read_raw_brainvision(vhdr_path, eog=eog, preload=True)

    # check that events are read and stim channel is synthesized correcly
    events = raw.get_brainvision_events()
    assert_array_equal(
        events,
        [
            [487, 1, 253],
            [497, 1, 255],
            [1770, 1, 254],
            [1780, 1, 255],
            [3253, 1, 254],
            [3263, 1, 255],
            [4936, 1, 253],
            [4946, 1, 255],
            [6620, 1, 254],
            [6630, 1, 255],
        ],
    )

    mne_events = mne.find_events(raw, stim_channel="STI 014")
    assert_array_equal(events[:, [0, 2]], mne_events[:, [0, 2]])

    # modify events and check that stim channel is updated
    index = events[:, 2] == 255
    events = events[index]
    raw.set_brainvision_events(events)
    mne_events = mne.find_events(raw, stim_channel="STI 014")
    assert_array_equal(events[:, [0, 2]], mne_events[:, [0, 2]])

    # remove events
    nchan = raw.info["nchan"]
    ch_name = raw.info["chs"][-2]["ch_name"]
    events = np.empty((0, 3))
    raw.set_brainvision_events(events)
    assert_equal(raw.info["nchan"], nchan - 1)
    assert_equal(len(raw._data), nchan - 1)
    assert_equal(raw.info["chs"][-1]["ch_name"], ch_name)
    fname = op.join(tempdir, "evt_raw.fif")
    raw.save(fname)

    # add events back in
    events = [[10, 1, 2]]
    raw.set_brainvision_events(events)
    assert_equal(raw.info["nchan"], nchan)
    assert_equal(len(raw._data), nchan)
    assert_equal(raw.info["chs"][-1]["ch_name"], "STI 014")
开发者ID:agramfort,项目名称:mne-python,代码行数:50,代码来源:test_brainvision.py


示例9: load_raw

    def load_raw(self, filename=None, mark_bads=True):

        if filename is None:
            filename = op.join(self.ptp_dir, '%s_%s-raw.fif' %(self.subject, self.experiment))
        print "Loading raw data from file %s" %filename
        raw = mne.io.read_raw_fif(filename, preload=True, verbose=False)
        event_check = mne.find_events(raw=raw, stim_channel='STI 014', min_duration=0.002, verbose=False)
        exp_event_check = event_check[np.in1d(event_check[:,2], self.trigger_scheme.values())]
        print len(event_check), "total events found."
        print len(exp_event_check), "events found with experiment-relevant triggers."

        if mark_bads:
            bad_file = glob.glob(self.processed_files + '*bad_channels.txt')
            if len(bad_file) == 0:
                print "No bad channels file found."
            elif len(bad_file) > 1:
                raise RuntimeError("Two or more bad channels files were found")
            else:
                bads = [i.strip() for i in open(bad_file[0]).readlines()]
                raw.info['bads'] += bads
                print "Marking the following channels as bad: " + str(bads)

        self.add_preprocessing_notes("Raw data loaded from file %s" %filename)
        for bad in raw.info['bads']:
            self.add_preprocessing_notes("%s marked as bad channel." %bad)

        self.raw_unfiltered = raw

        return raw
开发者ID:reddigari,项目名称:MNE-Python_PreprocessingMEG,代码行数:29,代码来源:MnePreproc.py


示例10: test_find_events

def test_find_events():
    """Test find events in raw file
    """
    events = mne.read_events(fname)
    raw = mne.fiff.Raw(raw_fname)
    events2 = mne.find_events(raw)
    assert_array_almost_equal(events, events2)
开发者ID:emilyruzich,项目名称:mne-python,代码行数:7,代码来源:test_event.py


示例11: test_ransac

def test_ransac():
    """Some basic tests for ransac."""

    event_id = {'Visual/Left': 3}
    tmin, tmax = -0.2, 0.5

    events = mne.find_events(raw)
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=(None, 0), decim=8,
                        reject=None, preload=True)
    # normal case
    picks = mne.pick_types(epochs.info, meg='mag', eeg=False, stim=False,
                           eog=False, exclude=[])

    ransac = Ransac(picks=picks)
    epochs_clean = ransac.fit_transform(epochs)
    assert_true(len(epochs_clean) == len(epochs))
    # Pass numpy instead of epochs
    X = epochs.get_data()
    assert_raises(AttributeError, ransac.fit, X)
    #
    # should not contain both channel types
    picks = mne.pick_types(epochs.info, meg=True, eeg=False, stim=False,
                           eog=False, exclude=[])
    ransac = Ransac(picks=picks)
    assert_raises(ValueError, ransac.fit, epochs)
    #
    # should not contain other channel types.
    picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=True,
                           eog=False, exclude=[])
    ransac = Ransac(picks=picks)
    assert_raises(ValueError, ransac.fit, epochs)
开发者ID:autoreject,项目名称:autoreject,代码行数:32,代码来源:test_ransac.py


示例12: test_tfr_with_inverse_operator

def test_tfr_with_inverse_operator():
    """Test time freq with MNE inverse computation"""

    tmin, tmax, event_id = -0.2, 0.5, 1

    # Setup for reading the raw data
    raw = io.Raw(fname_data)
    events = find_events(raw, stim_channel='STI 014')
    inverse_operator = read_inverse_operator(fname_inv)
    inv = prepare_inverse_operator(inverse_operator, nave=1,
                                   lambda2=1. / 9., method="dSPM")

    raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

    # picks MEG gradiometers
    picks = pick_types(raw.info, meg=True, eeg=False, eog=True,
                       stim=False, exclude='bads')

    # Load condition 1
    event_id = 1
    events3 = events[:3]  # take 3 events to keep the computation time low
    epochs = Epochs(raw, events3, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)

    # Compute a source estimate per frequency band
    bands = dict(alpha=[10, 10])
    label = read_label(fname_label)

    stcs = source_band_induced_power(epochs, inv, bands,
                                     n_cycles=2, use_fft=False, pca=True,
                                     label=label, prepared=True)

    stc = stcs['alpha']
    assert_true(len(stcs) == len(list(bands.keys())))
    assert_true(np.all(stc.data > 0))
    assert_array_almost_equal(stc.times, epochs.times)

    stcs_no_pca = source_band_induced_power(epochs, inv, bands,
                                            n_cycles=2, use_fft=False,
                                            pca=False, label=label,
                                            prepared=True)

    assert_array_almost_equal(stcs['alpha'].data, stcs_no_pca['alpha'].data)

    # Compute a source estimate per frequency band
    epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)

    frequencies = np.arange(7, 30, 2)  # define frequencies of interest
    power, phase_lock = source_induced_power(epochs, inv,
                                             frequencies, label,
                                             baseline=(-0.1, 0),
                                             baseline_mode='percent',
                                             n_cycles=2, n_jobs=1,
                                             prepared=True)
    assert_true(np.all(phase_lock > 0))
    assert_true(np.all(phase_lock <= 1))
    assert_true(np.max(power) > 10)
开发者ID:BushraR,项目名称:mne-python,代码行数:60,代码来源:test_time_frequency.py


示例13: merge_trial_and_audio_onsets

def merge_trial_and_audio_onsets(raw, use_audio_onsets=True, inplace=True, stim_channel='STI 014', verbose=None):
    events = mne.find_events(raw, stim_channel='STI 014', shortest_event=0)

    merged = list()
    last_trial_event = None
    for i, event in enumerate(events):
        etype = event[2]
        if etype < 1000 or etype == 1111: # trial or noise onset
            if use_audio_onsets and events[i+1][2] == 1000: # followed by audio onset
                onset = events[i+1][0]
                merged.append([onset, 0, etype])
                if verbose:
                    log.debug('merged {} + {} = {}'.format(event, events[i+1], merged[-1]))
            else:
                # either we are not interested in audio onsets or there is none
                merged.append(event)
                if verbose:
                    log.debug('kept {}'.format(merged[-1]))
        # audio onsets (etype == 1000) are not copied
        if etype > 1111: # other events (keystrokes)
            merged.append(event)
            if verbose:
                log.debug('kept other {}'.format(merged[-1]))

    merged = np.asarray(merged, dtype=int)

    if inplace:
        stim_id = raw.ch_names.index(stim_channel)
        raw._data[stim_id,:].fill(0)     # delete data in stim channel
        raw.add_events(merged)

    return merged
开发者ID:Qi0116,项目名称:deepthought,代码行数:32,代码来源:events.py


示例14: make_events_files

def make_events_files(sub_id, session):
    """ This function read in a fiff file and write out a event file
    """

    # SETUP AND LOAD FILES ####
    # name with subject id & session
    fname = "sub_%d_%s" % (sub_id, session)

    # load the raw fif
    print '\nLoading raw file'
    raw = fiff.Raw(fname + "_tsss_mc_autobad.fif", preload=False)

    # EPOCHS ####
    events = mne.find_events(raw, stim_channel="STI101")
    events_classic = []
    events_interupt = []
    for i in range(len(events)):
        if i > 0:
            if events[i, 2] == 1 and events[i - 1, 2] == 1:
                events_classic.append(i)
            elif events[i, 2] == 1 and events[i - 1, 2] == 2:
                events_interupt.append(i)
   
    if len(events_classic) > 0:
        outname = "sub_%d_%s.eve" % (sub_id, session)
        mne.write_events(outname, events[events_classic])

    if len(events_interupt) is not 0:
        outname_classic = "sub_%d_%s_%s.eve" % (sub_id, session, "classic")
        outname_interrupt = "sub_%d_%s_%s.eve" % (sub_id, session, "interrupt")

        mne.write_events(outname_classic, events[events_classic])
        mne.write_events(outname_interrupt, events[events_interupt])
开发者ID:MadsJensen,项目名称:readiness_scripts,代码行数:33,代码来源:preprocessing_functions.py


示例15: test_io_egi

def test_io_egi():
    """Test importing EGI simple binary files"""
    # test default
    tempdir = _TempDir()
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always', category=RuntimeWarning)
        raw = read_raw_egi(egi_fname, include=None)
        assert_true('RawEGI' in repr(raw))
        raw.load_data()  # currently does nothing
        assert_equal(len(w), 1)
        assert_true(w[0].category == RuntimeWarning)
        msg = 'Did not find any event code with more than one event.'
        assert_true(msg in '%s' % w[0].message)

    include = ['TRSP', 'XXX1']
    raw = read_raw_egi(egi_fname, include=include)
    repr(raw)
    repr(raw.info)

    assert_equal('eeg' in raw, True)
    out_fname = op.join(tempdir, 'test_egi_raw.fif')
    raw.save(out_fname)

    raw2 = Raw(out_fname, preload=True)
    data1, times1 = raw[:10, :]
    data2, times2 = raw2[:10, :]
    assert_array_almost_equal(data1, data2, 9)
    assert_array_almost_equal(times1, times2)

    eeg_chan = [c for c in raw.ch_names if 'EEG' in c]
    assert_equal(len(eeg_chan), 256)
    picks = pick_types(raw.info, eeg=True)
    assert_equal(len(picks), 256)
    assert_equal('STI 014' in raw.ch_names, True)

    events = find_events(raw, stim_channel='STI 014')
    assert_equal(len(events), 2)  # ground truth
    assert_equal(np.unique(events[:, 1])[0], 0)
    assert_true(np.unique(events[:, 0])[0] != 0)
    assert_true(np.unique(events[:, 2])[0] != 0)
    triggers = np.array([[0, 1, 1, 0], [0, 0, 1, 0]])

    # test trigger functionality
    assert_raises(RuntimeError, _combine_triggers, triggers, None)
    triggers = np.array([[0, 1, 0, 0], [0, 0, 1, 0]])
    events_ids = [12, 24]
    new_trigger = _combine_triggers(triggers, events_ids)
    assert_array_equal(np.unique(new_trigger), np.unique([0, 12, 24]))

    assert_raises(ValueError, read_raw_egi, egi_fname,
                  include=['Foo'])
    assert_raises(ValueError, read_raw_egi, egi_fname,
                  exclude=['Bar'])
    for ii, k in enumerate(include, 1):
        assert_true(k in raw.event_id)
        assert_true(raw.event_id[k] == ii)

    # Make sure concatenation works
    raw_concat = concatenate_raws([raw.copy(), raw])
    assert_equal(raw_concat.n_times, 2 * raw.n_times)
开发者ID:jasmainak,项目名称:mne-python,代码行数:60,代码来源:test_egi.py


示例16: test_gdf2_data

def test_gdf2_data():
    """Test reading raw GDF 2.x files."""
    raw = read_raw_edf(gdf2_path + '.gdf', eog=None, misc=None, preload=True)

    picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
    data, _ = raw[picks]

    # This .mat was generated using the official biosig matlab package
    mat = sio.loadmat(gdf2_path + '_biosig.mat')
    data_biosig = mat['dat'] * 1e-6  # data are stored in microvolts
    data_biosig = data_biosig[picks]

    # Assert data are almost equal
    assert_array_almost_equal(data, data_biosig, 8)

    # Find events
    events = find_events(raw, verbose=1)
    events[:, 2] >>= 8  # last 8 bits are system events in biosemi files
    assert_equal(events.shape[0], 2)  # 2 events in file
    assert_array_equal(events[:, 2], [20, 28])

    # gh-5604
    assert raw.info['meas_date'] == DATE_NONE
    _test_raw_reader(read_raw_edf, input_fname=gdf2_path + '.gdf',
                     eog=None, misc=None)
开发者ID:kambysese,项目名称:mne-python,代码行数:25,代码来源:test_gdf.py


示例17: hilbert_process

def hilbert_process(raw, bands, return_evoked=False):
    """Make hilbert transform of raw data and epoch it.

    Parameters
    ----------

    raw : ???
        The raw data to be transformed.
    bands : dict
        Dictionary with frequencies to calculate. Shape "band": [low, high]
    return_evoked : bool
        If true, an evoked data set will be returned, if False epochs will be
        returned.

    Returns
    -------
    Epochs if return_evoked is False. These are complex number!
    if return_evoked is True, an evoked object is returned. This does only
    have the envelope.
    """
    tmin, tmax = -2, 2
    event_id = {'voluntary': 243, 'involuntary': 219}
    picks = mne.pick_types(
        raw.info, meg=False, eeg=True, stim=False, exclude='bads')
    events = mne.find_events(raw)
    results_dict = {}

    for band in bands.keys():
        raw_tmp = raw.copy()
        raw_tmp.filter(bands[band][0], bands[band][1])

        if return_evoked:
            evokeds = []
            raw_tmp.apply_hilbert(picks=picks, envelope=True)
            epochs = mne.Epochs(
                raw_tmp,
                events,
                event_id,
                tmin,
                tmax,
                picks=picks,
                baseline=(None, -1.8),
                reject=reject)
            for cond in epochs.event_id.keys():
                evokeds.append(epochs[cond].average())
            results_dict[band] = evokeds
        else:
            raw_tmp.apply_hilbert(picks=picks, envelope=False)
            epochs = mne.Epochs(
                raw_tmp,
                events,
                event_id,
                tmin,
                tmax,
                picks=picks,
                baseline=None,
                reject=reject)
            results_dict[band] = epochs

    return results_dict
开发者ID:MadsJensen,项目名称:agency_connectivity,代码行数:60,代码来源:preprocessing.py


示例18: test_cov_estimation_with_triggers

def test_cov_estimation_with_triggers():
    """Test estimation from raw with triggers
    """
    events = find_events(raw)
    event_ids = [1, 2, 3, 4]
    reject = dict(grad=10000e-13, mag=4e-12, eeg=80e-6, eog=150e-6)

    # cov with merged events and keep_sample_mean=True
    events_merged = merge_events(events, event_ids, 1234)
    epochs = Epochs(raw, events_merged, 1234, tmin=-0.2, tmax=0,
                    baseline=(-0.2, -0.1), proj=True,
                    reject=reject, preload=True)

    cov = compute_covariance(epochs, keep_sample_mean=True)
    cov_mne = read_cov(cov_km_fname)
    assert_true(cov_mne.ch_names == cov.ch_names)
    assert_true((linalg.norm(cov.data - cov_mne.data, ord='fro')
            / linalg.norm(cov.data, ord='fro')) < 0.005)

    # Test with tmin and tmax (different but not too much)
    cov_tmin_tmax = compute_covariance(epochs, tmin=-0.19, tmax=-0.01)
    assert_true(np.all(cov.data != cov_tmin_tmax.data))
    assert_true((linalg.norm(cov.data - cov_tmin_tmax.data, ord='fro')
            / linalg.norm(cov_tmin_tmax.data, ord='fro')) < 0.05)

    # cov using a list of epochs and keep_sample_mean=True
    epochs = [Epochs(raw, events, ev_id, tmin=-0.2, tmax=0,
              baseline=(-0.2, -0.1), proj=True, reject=reject)
              for ev_id in event_ids]

    cov2 = compute_covariance(epochs, keep_sample_mean=True)
    assert_array_almost_equal(cov.data, cov2.data)
    assert_true(cov.ch_names == cov2.ch_names)

    # cov with keep_sample_mean=False using a list of epochs
    cov = compute_covariance(epochs, keep_sample_mean=False)
    cov_mne = read_cov(cov_fname)
    assert_true(cov_mne.ch_names == cov.ch_names)
    assert_true((linalg.norm(cov.data - cov_mne.data, ord='fro')
            / linalg.norm(cov.data, ord='fro')) < 0.005)

    # test IO when computation done in Python
    cov.save('test-cov.fif')  # test saving
    cov_read = read_cov('test-cov.fif')
    assert_true(cov_read.ch_names == cov.ch_names)
    assert_true(cov_read.nfree == cov.nfree)
    assert_true((linalg.norm(cov.data - cov_read.data, ord='fro')
            / linalg.norm(cov.data, ord='fro')) < 1e-5)

    # cov with list of epochs with different projectors
    epochs = [Epochs(raw, events[:4], event_ids[0], tmin=-0.2, tmax=0,
              baseline=(-0.2, -0.1), proj=True, reject=reject),
              Epochs(raw, events[:4], event_ids[0], tmin=-0.2, tmax=0,
              baseline=(-0.2, -0.1), proj=False, reject=reject)]
    # these should fail
    assert_raises(ValueError, compute_covariance, epochs)
    assert_raises(ValueError, compute_covariance, epochs, projs=None)
    # these should work, but won't be equal to above
    cov = compute_covariance(epochs, projs=epochs[0].info['projs'])
    cov = compute_covariance(epochs, projs=[])
开发者ID:starzynski,项目名称:mne-python,代码行数:60,代码来源:test_cov.py


示例19: test_epochs_vector_inverse

def test_epochs_vector_inverse():
    """Test vector inverse consistency between evoked and epochs."""
    raw = read_raw_fif(fname_raw)
    events = find_events(raw, stim_channel='STI 014')[:2]
    reject = dict(grad=2000e-13, mag=4e-12, eog=150e-6)

    epochs = Epochs(raw, events, None, 0, 0.01, baseline=None,
                    reject=reject, preload=True)

    assert_equal(len(epochs), 2)

    evoked = epochs.average(picks=range(len(epochs.ch_names)))

    inv = read_inverse_operator(fname_inv)

    method = "MNE"
    snr = 3.
    lambda2 = 1. / snr ** 2

    stcs_epo = apply_inverse_epochs(epochs, inv, lambda2, method=method,
                                    pick_ori='vector', return_generator=False)
    stc_epo = np.mean(stcs_epo)

    stc_evo = apply_inverse(evoked, inv, lambda2, method=method,
                            pick_ori='vector')

    assert_allclose(stc_epo.data, stc_evo.data, rtol=1e-9, atol=0)
开发者ID:teonbrooks,项目名称:mne-python,代码行数:27,代码来源:test_source_estimate.py


示例20: load_raw_from_blocknums

    def load_raw_from_blocknums(self,block_ns=['1']):
        """
        block_ns:       list of strings, corresponding to number of raw files to combine
        """

        raws = []

        # loads each of the raw blocks - assumes file is called _01_raw.fif, _02_raw.fif...
        for blockn in block_ns:
            raw_oneblock = self.ptp_dir + self.subj_code + '_0%s_raw.fif' % blockn
            raw = mne.io.Raw(raw_oneblock, preload=True, verbose=False)

            # make sure all have the same name of the trigger line, and same bad channels marked (i.e., none)
            raw.info['ch_names'][0] = 'STI 014'
            raw.info['bads'] = []

            # check number of events in each raw
            event_check = mne.find_events(raw=raw, stim_channel='STI 014', min_duration=0.002, verbose=False)
            print len(event_check), "events found for raw_0%s" % blockn

            self.add_preprocessing_notes( "%s events found for raw_0%s" % (str(len(event_check)), str(blockn)) )

            # append raws together
            raws.append(raw)

        # put all the raws together into one object
        for number in map(int,block_ns)[:-1]:
            raws[0].append(raws[number])
            raw = raws[0]

        # save the unfiltered raw to the class
        self.raw_unfiltered = raw

        return self.raw_unfiltered
开发者ID:reddigari,项目名称:MNE-Python_PreprocessingMEG,代码行数:34,代码来源:MnePreproc.py



注:本文中的mne.find_events函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mne.fit_dipole函数代码示例发布时间:2022-05-27
下一篇:
Python mne.extract_label_time_course函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap