当前位置: 首页>>代码示例>>Python>>正文


Python Raw.preload_data方法代码示例

本文整理汇总了Python中mne.io.Raw.preload_data方法的典型用法代码示例。如果您正苦于以下问题:Python Raw.preload_data方法的具体用法?Python Raw.preload_data怎么用?Python Raw.preload_data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mne.io.Raw的用法示例。


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

示例1: test_compute_proj_eog

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_compute_proj_eog():
    """Test computation of EOG SSP projectors"""
    raw = Raw(raw_fname).crop(0, 10, False)
    raw.preload_data()
    for average in [False, True]:
        n_projs_init = len(raw.info['projs'])
        projs, events = compute_proj_eog(raw, n_mag=2, n_grad=2, n_eeg=2,
                                         bads=['MEG 2443'], average=average,
                                         avg_ref=True, no_proj=False,
                                         l_freq=None, h_freq=None,
                                         reject=None, tmax=dur_use)
        assert_true(len(projs) == (7 + n_projs_init))
        assert_true(np.abs(events.shape[0] -
                    np.sum(np.less(eog_times, dur_use))) <= 1)
        # XXX: better tests

        # This will throw a warning b/c simplefilter('always')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            projs, events = compute_proj_eog(raw, n_mag=2, n_grad=2, n_eeg=2,
                                             average=average, bads=[],
                                             avg_ref=True, no_proj=False,
                                             l_freq=None, h_freq=None,
                                             tmax=dur_use)
            assert_equal(len(w), 1)
        assert_equal(projs, None)
开发者ID:rajul,项目名称:mne-python,代码行数:28,代码来源:test_ssp.py

示例2: test_memmap

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_memmap():
    fname='ec_rest_before_tsss_mc_rsl.fif'
    raw = Raw(fname, preload=False)
    raw.preload_data() #  data becomes numpy.float64
    data_shape = raw._data.shape

    tmpdir = mkdtemp(dir='/Users/cjb/tmp')
    mmap_fname = opj(tmpdir, 'raw_data.dat')

    fp = np.memmap(mmap_fname, dtype='float64', mode='w+',
                   shape=data_shape)

    print('Contents of raw._data:')
    print(raw._data[0][:10])
    print('Contents of memmap:')
    print(fp[0][:10])

    fp[:] = raw._data[:]
    print('Contents of memmap after assignment:')
    print(fp[0][:10])

    # delete numpy array and the memmap writer
    del raw._data
    del fp

    raw._data = np.memmap(mmap_fname, dtype='float64', mode='r+',
                          shape=data_shape)
    print('Contents of raw._data after loading from memmap:')
    print(raw._data[0][:10])


    raw.filter(None,40)
    print('Contents of raw._data after filtering:')
    print(raw._data[0][:10])
开发者ID:cjayb,项目名称:memory_profiling,代码行数:36,代码来源:np_memmap_raw.py

示例3: test_compute_proj_ecg

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_compute_proj_ecg():
    """Test computation of ECG SSP projectors"""
    raw = Raw(raw_fname).crop(0, 10, False)
    raw.preload_data()
    for average in [False, True]:
        # For speed, let's not filter here (must also not reject then)
        projs, events = compute_proj_ecg(raw, n_mag=2, n_grad=2, n_eeg=2,
                                         ch_name='MEG 1531', bads=['MEG 2443'],
                                         average=average, avg_ref=True,
                                         no_proj=True, l_freq=None,
                                         h_freq=None, reject=None,
                                         tmax=dur_use, qrs_threshold=0.5)
        assert_true(len(projs) == 7)
        # heart rate at least 0.5 Hz, but less than 3 Hz
        assert_true(events.shape[0] > 0.5 * dur_use and
                    events.shape[0] < 3 * dur_use)
        # XXX: better tests

        # without setting a bad channel, this should throw a warning
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            projs, events = compute_proj_ecg(raw, n_mag=2, n_grad=2, n_eeg=2,
                                             ch_name='MEG 1531', bads=[],
                                             average=average, avg_ref=True,
                                             no_proj=True, l_freq=None,
                                             h_freq=None, tmax=dur_use)
            assert_equal(len(w), 1)
        assert_equal(projs, None)
开发者ID:rajul,项目名称:mne-python,代码行数:30,代码来源:test_ssp.py

示例4: manual_filter

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def manual_filter():
    fname='ec_rest_before_tsss_mc_rsl.fif'
    raw = Raw(fname, preload=False)
    raw.preload_data() #  data becomes numpy.float64
    _mmap_raw(raw)

    copy = False  # filter in-place
    zero_phase = True
    n_jobs = 1
    picks = pick_types(raw.info, exclude=[], meg=True)

    x = raw._data  # pointer?

    Fs = 1000.
    Fp = 20.
    Fstop = 21.
    filter_length='10s'

    print('x.shape before prepping:', x.shape)
    h_fft, n_h, n_edge, orig_shape = _do_prep(Fs, Fp, Fstop, x, copy, picks,
                                              filter_length, zero_phase)
    print('x.shape after prepping:', x.shape)

    print('Before filtering:')
    print(x[0][:10])
    for p in picks:
        mangle_x(x[p])
        # _1d_overlap_filter(x[p], h_fft, n_h, n_edge, zero_phase,
        #                           dict(use_cuda=False))
    #x.shape = orig_shape
    print('After filtering:')
    print(x[0][:10])

    print('Data type:', raw._data[0][:5])
    print(type(raw._data))
开发者ID:cjayb,项目名称:memory_profiling,代码行数:37,代码来源:manual_filter_raw_mmap.py

示例5: test_resample

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_resample():
    """Test resample (with I/O and multiple files)
    """
    tempdir = _TempDir()
    raw = Raw(fif_fname).crop(0, 3, False)
    raw.preload_data()
    raw_resamp = raw.copy()
    sfreq = raw.info['sfreq']
    # test parallel on upsample
    raw_resamp.resample(sfreq * 2, n_jobs=2)
    assert_equal(raw_resamp.n_times, len(raw_resamp.times))
    raw_resamp.save(op.join(tempdir, 'raw_resamp-raw.fif'))
    raw_resamp = Raw(op.join(tempdir, 'raw_resamp-raw.fif'), preload=True)
    assert_equal(sfreq, raw_resamp.info['sfreq'] / 2)
    assert_equal(raw.n_times, raw_resamp.n_times / 2)
    assert_equal(raw_resamp._data.shape[1], raw_resamp.n_times)
    assert_equal(raw._data.shape[0], raw_resamp._data.shape[0])
    # test non-parallel on downsample
    raw_resamp.resample(sfreq, n_jobs=1)
    assert_equal(raw_resamp.info['sfreq'], sfreq)
    assert_equal(raw._data.shape, raw_resamp._data.shape)
    assert_equal(raw.first_samp, raw_resamp.first_samp)
    assert_equal(raw.last_samp, raw.last_samp)
    # upsampling then downsampling doubles resampling error, but this still
    # works (hooray). Note that the stim channels had to be sub-sampled
    # without filtering to be accurately preserved
    # note we have to treat MEG and EEG+STIM channels differently (tols)
    assert_allclose(raw._data[:306, 200:-200],
                    raw_resamp._data[:306, 200:-200],
                    rtol=1e-2, atol=1e-12)
    assert_allclose(raw._data[306:, 200:-200],
                    raw_resamp._data[306:, 200:-200],
                    rtol=1e-2, atol=1e-7)

    # now check multiple file support w/resampling, as order of operations
    # (concat, resample) should not affect our data
    raw1 = raw.copy()
    raw2 = raw.copy()
    raw3 = raw.copy()
    raw4 = raw.copy()
    raw1 = concatenate_raws([raw1, raw2])
    raw1.resample(10)
    raw3.resample(10)
    raw4.resample(10)
    raw3 = concatenate_raws([raw3, raw4])
    assert_array_equal(raw1._data, raw3._data)
    assert_array_equal(raw1._first_samps, raw3._first_samps)
    assert_array_equal(raw1._last_samps, raw3._last_samps)
    assert_array_equal(raw1._raw_lengths, raw3._raw_lengths)
    assert_equal(raw1.first_samp, raw3.first_samp)
    assert_equal(raw1.last_samp, raw3.last_samp)
    assert_equal(raw1.info['sfreq'], raw3.info['sfreq'])
开发者ID:Odingod,项目名称:mne-python,代码行数:54,代码来源:test_raw.py

示例6: filter_raw

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def filter_raw():
    fname='ec_rest_before_tsss_mc_rsl.fif'

    raw = Raw(fname, preload=False)
    raw.preload_data() #  data becomes numpy.float64
    raw.filter(None, 40, n_jobs=4)
    del raw

    fname='ec_rest_after_tsss_mc_rsl.fif'
    raw2 = Raw(fname, preload=False)
    raw2.preload_data() #  data becomes numpy.float64
    raw2.filter(None, 40, n_jobs=4)
    del raw2
开发者ID:cjayb,项目名称:memory_profiling,代码行数:15,代码来源:memprof_raw_filter.py

示例7: test_hash_raw

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_hash_raw():
    """Test hashing raw objects
    """
    raw = read_raw_fif(fif_fname)
    assert_raises(RuntimeError, raw.__hash__)
    raw = Raw(fif_fname).crop(0, 0.5, False)
    raw.preload_data()
    raw_2 = Raw(fif_fname).crop(0, 0.5, False)
    raw_2.preload_data()
    assert_equal(hash(raw), hash(raw_2))
    # do NOT use assert_equal here, failing output is terrible
    assert_equal(pickle.dumps(raw), pickle.dumps(raw_2))

    raw_2._data[0, 0] -= 1
    assert_not_equal(hash(raw), hash(raw_2))
开发者ID:rkmaddox,项目名称:mne-python,代码行数:17,代码来源:test_raw.py

示例8: test_maxwell_filter_additional

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_maxwell_filter_additional():
    """Test processing of Maxwell filtered data"""

    # TODO: Future tests integrate with mne/io/tests/test_proc_history

    # Load testing data (raw, SSS std origin, SSS non-standard origin)
    data_path = op.join(testing.data_path(download=False))

    file_name = 'test_move_anon'

    raw_fname = op.join(data_path, 'SSS', file_name + '_raw.fif')

    with warnings.catch_warnings(record=True):  # maxshield
        # Use 2.0 seconds of data to get stable cov. estimate
        raw = Raw(raw_fname, preload=False, proj=False,
                  allow_maxshield=True).crop(0., 2., False)

    # Get MEG channels, compute Maxwell filtered data
    raw.preload_data()
    raw.pick_types(meg=True, eeg=False)
    int_order, ext_order = 8, 3
    raw_sss = maxwell.maxwell_filter(raw, int_order=int_order,
                                     ext_order=ext_order)

    # Test io on processed data
    tempdir = _TempDir()
    test_outname = op.join(tempdir, 'test_raw_sss.fif')
    raw_sss.save(test_outname)
    raw_sss_loaded = Raw(test_outname, preload=True, proj=False,
                         allow_maxshield=True)

    # Some numerical imprecision since save uses 'single' fmt
    assert_allclose(raw_sss_loaded._data[:, :], raw_sss._data[:, :],
                    rtol=1e-6, atol=1e-20)

    # Test rank of covariance matrices for raw and SSS processed data
    cov_raw = compute_raw_data_covariance(raw)
    cov_sss = compute_raw_data_covariance(raw_sss)

    scalings = None
    cov_raw_rank = _estimate_rank_meeg_cov(cov_raw['data'], raw.info, scalings)
    cov_sss_rank = _estimate_rank_meeg_cov(cov_sss['data'], raw_sss.info,
                                           scalings)

    assert_equal(cov_raw_rank, raw.info['nchan'])
    assert_equal(cov_sss_rank, maxwell.get_num_moments(int_order, 0))
开发者ID:rajul,项目名称:mne-python,代码行数:48,代码来源:test_maxwell.py

示例9: test_preload_memmap

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_preload_memmap():
    tmpdir = mkdtemp(dir="/Users/cjb/tmp")
    mmap_fname = opj(tmpdir, "raw_data.dat")

    # fname='ec_rest_before_tsss_mc_rsl.fif'
    data_path = sample.data_path(download=False)
    fname = data_path + "/MEG/sample/sample_audvis_raw.fif"

    raw = Raw(fname, preload=False)
    # """This function actually preloads the data"""
    # data_buffer = mmap_fname
    # raw._data = raw._read_segment(data_buffer=data_buffer)[0]
    # assert len(raw._data) == raw.info['nchan']
    # raw.preload = True
    # raw.close()
    raw.preload_data(data_buffer=mmap_fname)
    data_shape = raw._data.shape

    print("Contents of raw._data after reading from fif:")
    print(type(raw._data))
    print(raw._data[100][:5])

    del raw._data
    raw._data = np.memmap(mmap_fname, dtype="float64", mode="c", shape=data_shape)

    print("Contents of raw._data after RE-loading:")
    print(type(raw._data))
    print(raw._data[100][:5])

    raw.filter(None, 40)
    print("Contents of raw._data after filtering:")
    print(type(raw._data))
    print(raw._data[100][:5])

    # PROBLEM: Now the filtered data are IN MEMORY, but as a memmap
    # What if I'd like to continue from here using it as an ndarray?

    del raw._data

    rmtree(tmpdir, ignore_errors=True)
开发者ID:cjayb,项目名称:memory_profiling,代码行数:42,代码来源:mne_preload_raw.py

示例10: test_compute_proj_parallel

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_compute_proj_parallel():
    """Test computation of ExG projectors using parallelization"""
    raw_0 = Raw(raw_fname).crop(0, 10, False)
    raw_0.preload_data()
    raw = raw_0.copy()
    projs, _ = compute_proj_eog(raw, n_mag=2, n_grad=2, n_eeg=2,
                                bads=['MEG 2443'], average=False,
                                avg_ref=True, no_proj=False, n_jobs=1,
                                l_freq=None, h_freq=None, reject=None,
                                tmax=dur_use)
    raw_2 = raw_0.copy()
    projs_2, _ = compute_proj_eog(raw_2, n_mag=2, n_grad=2, n_eeg=2,
                                  bads=['MEG 2443'], average=False,
                                  avg_ref=True, no_proj=False, n_jobs=2,
                                  l_freq=None, h_freq=None, reject=None,
                                  tmax=dur_use)
    projs = activate_proj(projs)
    projs_2 = activate_proj(projs_2)
    projs, _, _ = make_projector(projs, raw_2.info['ch_names'],
                                 bads=['MEG 2443'])
    projs_2, _, _ = make_projector(projs_2, raw_2.info['ch_names'],
                                   bads=['MEG 2443'])
    assert_array_almost_equal(projs, projs_2, 10)
开发者ID:rajul,项目名称:mne-python,代码行数:25,代码来源:test_ssp.py

示例11: test_bads_reconstruction

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_bads_reconstruction():
    """Test reconstruction of channels marked as bad"""

    with warnings.catch_warnings(record=True):  # maxshield, naming
        sss_bench = Raw(sss_bad_recon_fname, preload=True, proj=False,
                        allow_maxshield=True)

    raw_fname = op.join(data_path, 'SSS', 'test_move_anon_raw.fif')

    with warnings.catch_warnings(record=True):  # maxshield
        raw = Raw(raw_fname, preload=False, proj=False,
                  allow_maxshield=True).crop(0., 1., False)

    raw.preload_data()

    # Set 30 random bad MEG channels (20 grad, 10 mag)
    bads = ['MEG0912', 'MEG1722', 'MEG2213', 'MEG0132', 'MEG1312', 'MEG0432',
            'MEG2433', 'MEG1022', 'MEG0442', 'MEG2332', 'MEG0633', 'MEG1043',
            'MEG1713', 'MEG0422', 'MEG0932', 'MEG1622', 'MEG1343', 'MEG0943',
            'MEG0643', 'MEG0143', 'MEG2142', 'MEG0813', 'MEG2143', 'MEG1323',
            'MEG0522', 'MEG1123', 'MEG0423', 'MEG2122', 'MEG2532', 'MEG0812']
    raw.info['bads'] = bads

    # Compute Maxwell filtered data
    raw_sss = maxwell.maxwell_filter(raw)
    meg_chs = pick_types(raw_sss.info)

    # Some numerical imprecision since save uses 'single' fmt
    assert_allclose(raw_sss._data[meg_chs, :], sss_bench._data[meg_chs, :],
                    rtol=1e-12, atol=1e-4, err_msg='Maxwell filtered data '
                    'with reconstructed bads is incorrect.')

    # Confirm SNR is above 1000
    bench_rms = np.sqrt(np.mean(raw_sss._data[meg_chs, :] ** 2, axis=1))
    error = raw_sss._data[meg_chs, :] - sss_bench._data[meg_chs, :]
    error_rms = np.sqrt(np.mean(error ** 2, axis=1))
    assert_true(np.mean(bench_rms / error_rms) >= 1000, 'SNR < 1000')
开发者ID:harvest15,项目名称:mne-python,代码行数:39,代码来源:test_maxwell.py

示例12: test_multiple_files

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_multiple_files():
    """Test loading multiple files simultaneously
    """
    # split file
    tempdir = _TempDir()
    raw = Raw(fif_fname)
    raw.preload_data()
    raw.preload_data()  # test no operation
    raw = raw.crop(0, 10)
    split_size = 3.  # in seconds
    sfreq = raw.info['sfreq']
    nsamp = (raw.last_samp - raw.first_samp)
    tmins = np.round(np.arange(0., nsamp, split_size * sfreq))
    tmaxs = np.concatenate((tmins[1:] - 1, [nsamp]))
    tmaxs /= sfreq
    tmins /= sfreq
    assert_equal(raw.n_times, len(raw._times))

    # going in reverse order so the last fname is the first file (need later)
    raws = [None] * len(tmins)
    for ri in range(len(tmins) - 1, -1, -1):
        fname = op.join(tempdir, 'test_raw_split-%d_raw.fif' % ri)
        raw.save(fname, tmin=tmins[ri], tmax=tmaxs[ri])
        raws[ri] = Raw(fname)
    events = [find_events(r, stim_channel='STI 014') for r in raws]
    last_samps = [r.last_samp for r in raws]
    first_samps = [r.first_samp for r in raws]

    # test concatenation of split file
    assert_raises(ValueError, concatenate_raws, raws, True, events[1:])
    all_raw_1, events1 = concatenate_raws(raws, preload=False,
                                          events_list=events)
    assert_true(raw.first_samp == all_raw_1.first_samp)
    assert_true(raw.last_samp == all_raw_1.last_samp)
    assert_allclose(raw[:, :][0], all_raw_1[:, :][0])
    raws[0] = Raw(fname)
    all_raw_2 = concatenate_raws(raws, preload=True)
    assert_allclose(raw[:, :][0], all_raw_2[:, :][0])

    # test proper event treatment for split files
    events2 = concatenate_events(events, first_samps, last_samps)
    events3 = find_events(all_raw_2, stim_channel='STI 014')
    assert_array_equal(events1, events2)
    assert_array_equal(events1, events3)

    # test various methods of combining files
    raw = Raw(fif_fname, preload=True)
    n_times = len(raw._times)
    # make sure that all our data match
    times = list(range(0, 2 * n_times, 999))
    # add potentially problematic points
    times.extend([n_times - 1, n_times, 2 * n_times - 1])

    raw_combo0 = Raw([fif_fname, fif_fname], preload=True)
    _compare_combo(raw, raw_combo0, times, n_times)
    raw_combo = Raw([fif_fname, fif_fname], preload=False)
    _compare_combo(raw, raw_combo, times, n_times)
    raw_combo = Raw([fif_fname, fif_fname], preload='memmap8.dat')
    _compare_combo(raw, raw_combo, times, n_times)
    assert_raises(ValueError, Raw, [fif_fname, ctf_fname])
    assert_raises(ValueError, Raw, [fif_fname, fif_bad_marked_fname])
    assert_true(raw[:, :][0].shape[1] * 2 == raw_combo0[:, :][0].shape[1])
    assert_true(raw_combo0[:, :][0].shape[1] == len(raw_combo0._times))

    # with all data preloaded, result should be preloaded
    raw_combo = Raw(fif_fname, preload=True)
    raw_combo.append(Raw(fif_fname, preload=True))
    assert_true(raw_combo.preload is True)
    assert_true(len(raw_combo._times) == raw_combo._data.shape[1])
    _compare_combo(raw, raw_combo, times, n_times)

    # with any data not preloaded, don't set result as preloaded
    raw_combo = concatenate_raws([Raw(fif_fname, preload=True),
                                  Raw(fif_fname, preload=False)])
    assert_true(raw_combo.preload is False)
    assert_array_equal(find_events(raw_combo, stim_channel='STI 014'),
                       find_events(raw_combo0, stim_channel='STI 014'))
    _compare_combo(raw, raw_combo, times, n_times)

    # user should be able to force data to be preloaded upon concat
    raw_combo = concatenate_raws([Raw(fif_fname, preload=False),
                                  Raw(fif_fname, preload=True)],
                                 preload=True)
    assert_true(raw_combo.preload is True)
    _compare_combo(raw, raw_combo, times, n_times)

    raw_combo = concatenate_raws([Raw(fif_fname, preload=False),
                                  Raw(fif_fname, preload=True)],
                                 preload='memmap3.dat')
    _compare_combo(raw, raw_combo, times, n_times)

    raw_combo = concatenate_raws([Raw(fif_fname, preload=True),
                                  Raw(fif_fname, preload=True)],
                                 preload='memmap4.dat')
    _compare_combo(raw, raw_combo, times, n_times)

    raw_combo = concatenate_raws([Raw(fif_fname, preload=False),
                                  Raw(fif_fname, preload=False)],
                                 preload='memmap5.dat')
    _compare_combo(raw, raw_combo, times, n_times)
#.........这里部分代码省略.........
开发者ID:pombreda,项目名称:mne-python,代码行数:103,代码来源:test_raw.py

示例13: test_resample

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_resample():
    """Test resample (with I/O and multiple files)
    """
    tempdir = _TempDir()
    raw = Raw(fif_fname).crop(0, 3, False)
    raw.preload_data()
    raw_resamp = raw.copy()
    sfreq = raw.info['sfreq']
    # test parallel on upsample
    raw_resamp.resample(sfreq * 2, n_jobs=2)
    assert_equal(raw_resamp.n_times, len(raw_resamp.times))
    raw_resamp.save(op.join(tempdir, 'raw_resamp-raw.fif'))
    raw_resamp = Raw(op.join(tempdir, 'raw_resamp-raw.fif'), preload=True)
    assert_equal(sfreq, raw_resamp.info['sfreq'] / 2)
    assert_equal(raw.n_times, raw_resamp.n_times / 2)
    assert_equal(raw_resamp._data.shape[1], raw_resamp.n_times)
    assert_equal(raw._data.shape[0], raw_resamp._data.shape[0])
    # test non-parallel on downsample
    raw_resamp.resample(sfreq, n_jobs=1)
    assert_equal(raw_resamp.info['sfreq'], sfreq)
    assert_equal(raw._data.shape, raw_resamp._data.shape)
    assert_equal(raw.first_samp, raw_resamp.first_samp)
    assert_equal(raw.last_samp, raw.last_samp)
    # upsampling then downsampling doubles resampling error, but this still
    # works (hooray). Note that the stim channels had to be sub-sampled
    # without filtering to be accurately preserved
    # note we have to treat MEG and EEG+STIM channels differently (tols)
    assert_allclose(raw._data[:306, 200:-200],
                    raw_resamp._data[:306, 200:-200],
                    rtol=1e-2, atol=1e-12)
    assert_allclose(raw._data[306:, 200:-200],
                    raw_resamp._data[306:, 200:-200],
                    rtol=1e-2, atol=1e-7)

    # now check multiple file support w/resampling, as order of operations
    # (concat, resample) should not affect our data
    raw1 = raw.copy()
    raw2 = raw.copy()
    raw3 = raw.copy()
    raw4 = raw.copy()
    raw1 = concatenate_raws([raw1, raw2])
    raw1.resample(10.)
    raw3.resample(10.)
    raw4.resample(10.)
    raw3 = concatenate_raws([raw3, raw4])
    assert_array_equal(raw1._data, raw3._data)
    assert_array_equal(raw1._first_samps, raw3._first_samps)
    assert_array_equal(raw1._last_samps, raw3._last_samps)
    assert_array_equal(raw1._raw_lengths, raw3._raw_lengths)
    assert_equal(raw1.first_samp, raw3.first_samp)
    assert_equal(raw1.last_samp, raw3.last_samp)
    assert_equal(raw1.info['sfreq'], raw3.info['sfreq'])

    # test resampling of stim channel

    # basic decimation
    stim = [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
    assert_allclose(raw.resample(8.)._data,
                    [[1, 1, 0, 0, 1, 1, 0, 0]])

    # decimation of multiple stim channels
    raw = RawArray(2 * [stim], create_info(2, len(stim), 2 * ['stim']))
    assert_allclose(raw.resample(8.)._data,
                    [[1, 1, 0, 0, 1, 1, 0, 0],
                     [1, 1, 0, 0, 1, 1, 0, 0]])

    # decimation that could potentially drop events if the decimation is
    # done naively
    stim = [0, 0, 0, 1, 1, 0, 0, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
    assert_allclose(raw.resample(4.)._data,
                    [[0, 1, 1, 0]])

    # two events are merged in this case (warning)
    stim = [0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        raw.resample(8.)
        assert_true(len(w) == 1)

    # events are dropped in this case (warning)
    stim = [0, 1, 1, 0, 0, 1, 1, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        raw.resample(4.)
        assert_true(len(w) == 1)

    # test resampling events: this should no longer give a warning
    stim = [0, 1, 1, 0, 0, 1, 1, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
    events = find_events(raw)
    raw, events = raw.resample(4., events=events)
    assert_equal(events, np.array([[0, 0, 1], [2, 0, 1]]))

    # test copy flag
    stim = [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
    raw = RawArray([stim], create_info(1, len(stim), ['stim']))
#.........这里部分代码省略.........
开发者ID:rkmaddox,项目名称:mne-python,代码行数:103,代码来源:test_raw.py

示例14: test_filter

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_filter():
    """Test filtering (FIR and IIR) and Raw.apply_function interface
    """
    raw = Raw(fif_fname).crop(0, 7, False)
    raw.preload_data()
    sig_dec = 11
    sig_dec_notch = 12
    sig_dec_notch_fit = 12
    picks_meg = pick_types(raw.info, meg=True, exclude='bads')
    picks = picks_meg[:4]

    raw_lp = raw.copy()
    raw_lp.filter(0., 4.0 - 0.25, picks=picks, n_jobs=2)

    raw_hp = raw.copy()
    raw_hp.filter(8.0 + 0.25, None, picks=picks, n_jobs=2)

    raw_bp = raw.copy()
    raw_bp.filter(4.0 + 0.25, 8.0 - 0.25, picks=picks)

    raw_bs = raw.copy()
    raw_bs.filter(8.0 + 0.25, 4.0 - 0.25, picks=picks, n_jobs=2)

    data, _ = raw[picks, :]

    lp_data, _ = raw_lp[picks, :]
    hp_data, _ = raw_hp[picks, :]
    bp_data, _ = raw_bp[picks, :]
    bs_data, _ = raw_bs[picks, :]

    assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec)
    assert_array_almost_equal(data, bp_data + bs_data, sig_dec)

    raw_lp_iir = raw.copy()
    raw_lp_iir.filter(0., 4.0, picks=picks, n_jobs=2, method='iir')
    raw_hp_iir = raw.copy()
    raw_hp_iir.filter(8.0, None, picks=picks, n_jobs=2, method='iir')
    raw_bp_iir = raw.copy()
    raw_bp_iir.filter(4.0, 8.0, picks=picks, method='iir')
    lp_data_iir, _ = raw_lp_iir[picks, :]
    hp_data_iir, _ = raw_hp_iir[picks, :]
    bp_data_iir, _ = raw_bp_iir[picks, :]
    summation = lp_data_iir + hp_data_iir + bp_data_iir
    assert_array_almost_equal(data[:, 100:-100], summation[:, 100:-100],
                              sig_dec)

    # make sure we didn't touch other channels
    data, _ = raw[picks_meg[4:], :]
    bp_data, _ = raw_bp[picks_meg[4:], :]
    assert_array_equal(data, bp_data)
    bp_data_iir, _ = raw_bp_iir[picks_meg[4:], :]
    assert_array_equal(data, bp_data_iir)

    # do a very simple check on line filtering
    raw_bs = raw.copy()
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        raw_bs.filter(60.0 + 0.5, 60.0 - 0.5, picks=picks, n_jobs=2)
        data_bs, _ = raw_bs[picks, :]
        raw_notch = raw.copy()
        raw_notch.notch_filter(60.0, picks=picks, n_jobs=2, method='fft')
    data_notch, _ = raw_notch[picks, :]
    assert_array_almost_equal(data_bs, data_notch, sig_dec_notch)

    # now use the sinusoidal fitting
    raw_notch = raw.copy()
    raw_notch.notch_filter(None, picks=picks, n_jobs=2, method='spectrum_fit')
    data_notch, _ = raw_notch[picks, :]
    data, _ = raw[picks, :]
    assert_array_almost_equal(data, data_notch, sig_dec_notch_fit)
开发者ID:rkmaddox,项目名称:mne-python,代码行数:72,代码来源:test_raw.py

示例15: test_maxwell_filter

# 需要导入模块: from mne.io import Raw [as 别名]
# 或者: from mne.io.Raw import preload_data [as 别名]
def test_maxwell_filter():
    """Test multipolar moment and Maxwell filter"""

    # TODO: Future tests integrate with mne/io/tests/test_proc_history

    # Load testing data (raw, SSS std origin, SSS non-standard origin)
    with warnings.catch_warnings(record=True):  # maxshield
        raw = Raw(raw_fname, preload=False, proj=False,
                  allow_maxshield=True).crop(0., 1., False)
    raw.preload_data()
    with warnings.catch_warnings(record=True):  # maxshield, naming
        sss_std = Raw(sss_std_fname, preload=True, proj=False,
                      allow_maxshield=True)
        sss_nonStd = Raw(sss_nonstd_fname, preload=True, proj=False,
                         allow_maxshield=True)
        raw_err = Raw(raw_fname, preload=False, proj=True,
                      allow_maxshield=True).crop(0., 0.1, False)
    assert_raises(RuntimeError, maxwell.maxwell_filter, raw_err)

    # Create coils
    all_coils, meg_info = maxwell._make_coils(raw.info)
    picks = [raw.info['ch_names'].index(ch) for ch in [coil['chname']
                                                       for coil in all_coils]]
    coils = [all_coils[ci] for ci in picks]
    ncoils = len(coils)

    int_order, ext_order = 8, 3
    n_int_bases = int_order ** 2 + 2 * int_order
    n_ext_bases = ext_order ** 2 + 2 * ext_order
    nbases = n_int_bases + n_ext_bases

    # Check number of bases computed correctly
    assert_equal(maxwell.get_num_moments(int_order, ext_order), nbases)

    # Check multipolar moment basis set
    S_in, S_out = maxwell._sss_basis(origin=np.array([0, 0, 40]), coils=coils,
                                     int_order=int_order, ext_order=ext_order)
    assert_equal(S_in.shape, (ncoils, n_int_bases), 'S_in has incorrect shape')
    assert_equal(S_out.shape, (ncoils, n_ext_bases),
                 'S_out has incorrect shape')

    # Check normalization
    assert_allclose(np.sum(S_in ** 2, axis=0), np.ones((S_in.shape[1])),
                    rtol=1e-12, err_msg='S_in normalization error')
    assert_allclose(np.sum(S_out ** 2, axis=0), np.ones((S_out.shape[1])),
                    rtol=1e-12, err_msg='S_out normalization error')

    # Test sss computation at the standard head origin
    raw_sss = maxwell.maxwell_filter(raw, origin=[0., 0., 40.],
                                     int_order=int_order, ext_order=ext_order)

    assert_array_almost_equal(raw_sss._data[picks, :], sss_std._data[picks, :],
                              decimal=11, err_msg='Maxwell filtered data at '
                              'standard origin incorrect.')

    # Confirm SNR is above 100
    bench_rms = np.sqrt(np.mean(sss_std._data[picks, :] ** 2, axis=1))
    error = raw_sss._data[picks, :] - sss_std._data[picks, :]
    error_rms = np.sqrt(np.mean(error ** 2, axis=1))
    assert_true(np.mean(bench_rms / error_rms) > 1000, 'SNR < 1000')

    # Test sss computation at non-standard head origin
    raw_sss = maxwell.maxwell_filter(raw, origin=[0., 20., 20.],
                                     int_order=int_order, ext_order=ext_order)
    assert_array_almost_equal(raw_sss._data[picks, :],
                              sss_nonStd._data[picks, :], decimal=11,
                              err_msg='Maxwell filtered data at non-std '
                              'origin incorrect.')
    # Confirm SNR is above 100
    bench_rms = np.sqrt(np.mean(sss_nonStd._data[picks, :] ** 2, axis=1))
    error = raw_sss._data[picks, :] - sss_nonStd._data[picks, :]
    error_rms = np.sqrt(np.mean(error ** 2, axis=1))
    assert_true(np.mean(bench_rms / error_rms) > 1000, 'SNR < 1000')

    # Check against SSS functions from proc_history
    sss_info = raw_sss.info['proc_history'][0]['max_info']
    assert_equal(maxwell.get_num_moments(int_order, 0),
                 proc_history._get_sss_rank(sss_info))
开发者ID:emmanuelkalunga,项目名称:mne-python,代码行数:80,代码来源:test_maxwell.py


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