本文整理汇总了Python中mne.io.RawArray类的典型用法代码示例。如果您正苦于以下问题:Python RawArray类的具体用法?Python RawArray怎么用?Python RawArray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RawArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_proj_raw_duration
def test_proj_raw_duration(duration, sfreq):
"""Test equivalence of `duration` options."""
n_ch, n_dim = 30, 3
rng = np.random.RandomState(0)
signals = rng.randn(n_dim, 10000)
mixing = rng.randn(n_ch, n_dim) + [0, 1, 2]
data = np.dot(mixing, signals)
raw = RawArray(data, create_info(n_ch, sfreq, 'eeg'))
raw.set_eeg_reference(projection=True)
n_eff = int(round(raw.info['sfreq'] * duration))
# crop to an even "duration" number of epochs
stop = ((len(raw.times) // n_eff) * n_eff - 1) / raw.info['sfreq']
raw.crop(0, stop)
proj_def = compute_proj_raw(raw, n_eeg=n_dim)
proj_dur = compute_proj_raw(raw, duration=duration, n_eeg=n_dim)
proj_none = compute_proj_raw(raw, duration=None, n_eeg=n_dim)
assert len(proj_dur) == len(proj_none) == len(proj_def) == n_dim
# proj_def is not in here because it does not necessarily evenly divide
# the signal length:
for pu, pn in zip(proj_dur, proj_none):
assert_allclose(pu['data']['data'], pn['data']['data'])
# but we can test it here since it should still be a small subspace angle:
for proj in (proj_dur, proj_none, proj_def):
computed = np.concatenate([p['data']['data'] for p in proj], 0)
angle = np.rad2deg(linalg.subspace_angles(computed.T, mixing)[0])
assert angle < 1e-5
示例2: test_apply_function_verbose
def test_apply_function_verbose():
"""Test apply function verbosity
"""
n_chan = 2
n_times = 3
ch_names = [str(ii) for ii in range(n_chan)]
raw = RawArray(np.zeros((n_chan, n_times)),
create_info(ch_names, 1., 'mag'))
# test return types in both code paths (parallel / 1 job)
assert_raises(TypeError, raw.apply_function, bad_1,
None, None, 1)
assert_raises(ValueError, raw.apply_function, bad_2,
None, None, 1)
assert_raises(TypeError, raw.apply_function, bad_1,
None, None, 2)
assert_raises(ValueError, raw.apply_function, bad_2,
None, None, 2)
# check our arguments
tempdir = _TempDir()
test_name = op.join(tempdir, 'test.log')
set_log_file(test_name)
try:
raw.apply_function(printer, None, None, 1, verbose=False)
with open(test_name) as fid:
assert_equal(len(fid.readlines()), 0)
raw.apply_function(printer, None, None, 1, verbose=True)
with open(test_name) as fid:
assert_equal(len(fid.readlines()), n_chan)
finally:
set_log_file(None)
示例3: write_mnefiff
def write_mnefiff(data, filename):
"""Export data to MNE using FIFF format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (include '.mat')
Notes
-----
It cannot store data larger than 2 GB.
The data is assumed to have only EEG electrodes.
It overwrites a file if it exists.
"""
from mne import create_info, set_log_level
from mne.io import RawArray
set_log_level(WARNING)
TRIAL = 0
info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] *
data.number_of('chan')[TRIAL])
UNITS = 1e-6 # mne wants data in uV
fiff = RawArray(data.data[0] * UNITS, info)
if data.attr['chan']:
fiff.set_channel_positions(data.attr['chan'].return_xyz(),
data.attr['chan'].return_label())
fiff.save(filename, overwrite=True)
示例4: _raw_annot
def _raw_annot(meas_date, orig_time):
info = create_info(ch_names=10, sfreq=10.)
raw = RawArray(data=np.empty((10, 10)), info=info, first_samp=10)
raw.info['meas_date'] = meas_date
annot = Annotations([.5], [.2], ['dummy'], orig_time)
raw.set_annotations(annotations=annot)
return raw
示例5: test_annotation_property_deprecation_warning
def test_annotation_property_deprecation_warning():
"""Test that assigning annotations warns and nowhere else."""
with pytest.warns(None) as w:
raw = RawArray(np.random.rand(1, 1), create_info(1, 1))
assert len(w) is 0
with pytest.warns(DeprecationWarning, match='by assignment is deprecated'):
raw.annotations = None
示例6: test_filter_picks
def test_filter_picks():
"""Test filtering default channel picks"""
ch_types = ['mag', 'grad', 'eeg', 'seeg', 'misc', 'stim']
info = create_info(ch_names=ch_types, ch_types=ch_types, sfreq=256)
raw = RawArray(data=np.zeros((len(ch_types), 1000)), info=info)
# -- Deal with meg mag grad exception
ch_types = ('misc', 'stim', 'meg', 'eeg', 'seeg')
# -- Filter data channels
for ch_type in ('mag', 'grad', 'eeg', 'seeg'):
picks = dict((ch, ch == ch_type) for ch in ch_types)
picks['meg'] = ch_type if ch_type in ('mag', 'grad') else False
raw_ = raw.pick_types(copy=True, **picks)
# Avoid RuntimeWarning due to Attenuation
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw_.filter(10, 30)
assert_true(len(w) == 1)
# -- Error if no data channel
for ch_type in ('misc', 'stim'):
picks = dict((ch, ch == ch_type) for ch in ch_types)
raw_ = raw.pick_types(copy=True, **picks)
assert_raises(RuntimeError, raw_.filter, 10, 30)
示例7: test_chunk_duration
def test_chunk_duration():
"""Test chunk_duration."""
# create dummy raw
raw = RawArray(data=np.empty([10, 10], dtype=np.float64),
info=create_info(ch_names=10, sfreq=1.),
first_samp=0)
raw.info['meas_date'] = 0
raw.set_annotations(Annotations(description='foo', onset=[0],
duration=[10], orig_time=None))
# expected_events = [[0, 0, 1], [0, 0, 1], [1, 0, 1], [1, 0, 1], ..
# [9, 0, 1], [9, 0, 1]]
expected_events = np.atleast_2d(np.repeat(range(10), repeats=2)).T
expected_events = np.insert(expected_events, 1, 0, axis=1)
expected_events = np.insert(expected_events, 2, 1, axis=1)
events, events_id = events_from_annotations(raw, chunk_duration=.5,
use_rounding=False)
assert_array_equal(events, expected_events)
# test chunk durations that do not fit equally in annotation duration
expected_events = np.zeros((3, 3))
expected_events[:, -1] = 1
expected_events[:, 0] = np.arange(0, 9, step=3)
events, events_id = events_from_annotations(raw, chunk_duration=3.)
assert_array_equal(events, expected_events)
示例8: test_resample_raw
def test_resample_raw():
"""Test resampling using RawArray."""
x = np.zeros((1, 1001))
sfreq = 2048.
raw = RawArray(x, create_info(1, sfreq, 'eeg'))
raw.resample(128, npad=10)
data = raw.get_data()
assert data.shape == (1, 63)
示例9: raw_factory
def raw_factory(meas_date):
raw = RawArray(data=np.empty((10, 10)),
info=create_info(ch_names=10, sfreq=10., ),
first_samp=10)
raw.info['meas_date'] = meas_date
raw.set_annotations(annotations=Annotations(onset=[.5],
duration=[.2],
description='dummy',
orig_time=None))
return raw
示例10: test_time_as_index_ref
def test_time_as_index_ref(offset, origin):
"""Test indexing of raw times."""
meas_date = 1
info = create_info(ch_names=10, sfreq=10.)
raw = RawArray(data=np.empty((10, 10)), info=info, first_samp=10)
raw.info['meas_date'] = meas_date
relative_times = raw.times
inds = raw.time_as_index(relative_times + offset,
use_rounding=True,
origin=origin)
assert_array_equal(inds, np.arange(raw.n_times))
示例11: test_mark_flat
def test_mark_flat(first_samp):
"""Test marking flat segments."""
# Test if ECG analysis will work on data that is not preloaded
n_ch, n_times = 11, 1000
data = np.random.RandomState(0).randn(n_ch, n_times)
assert not (np.diff(data, axis=-1) == 0).any() # nothing flat at first
info = create_info(n_ch, 1000., 'eeg')
info['meas_date'] = (1, 2)
# test first_samp != for gh-6295
raw = RawArray(data, info, first_samp=first_samp)
raw.info['bads'] = [raw.ch_names[-1]]
#
# First make a channel flat the whole time
#
raw_0 = raw.copy()
raw_0._data[0] = 0.
for kwargs, bads, want_times in [
# Anything < 1 will mark spatially
(dict(bad_percent=100.), [], 0),
(dict(bad_percent=99.9), [raw.ch_names[0]], n_times),
(dict(), [raw.ch_names[0]], n_times)]: # default (1)
raw_time = mark_flat(raw_0.copy(), verbose='debug', **kwargs)
want_bads = raw.info['bads'] + bads
assert raw_time.info['bads'] == want_bads
n_good_times = raw_time.get_data(reject_by_annotation='omit').shape[1]
assert n_good_times == want_times
#
# Now make a channel flat for 20% of the time points
#
raw_0 = raw.copy()
n_good_times = int(round(0.8 * n_times))
raw_0._data[0, n_good_times:] = 0.
threshold = 100 * (n_times - n_good_times) / n_times
for kwargs, bads, want_times in [
# Should change behavior at bad_percent=20
(dict(bad_percent=100), [], n_good_times),
(dict(bad_percent=threshold), [], n_good_times),
(dict(bad_percent=threshold - 1e-5), [raw.ch_names[0]], n_times),
(dict(), [raw.ch_names[0]], n_times)]:
raw_time = mark_flat(raw_0.copy(), verbose='debug', **kwargs)
want_bads = raw.info['bads'] + bads
assert raw_time.info['bads'] == want_bads
n_good_times = raw_time.get_data(reject_by_annotation='omit').shape[1]
assert n_good_times == want_times
with pytest.raises(TypeError, match='must be an instance of BaseRaw'):
mark_flat(0.)
with pytest.raises(ValueError, match='not convert string to float'):
mark_flat(raw, 'x')
示例12: test_picks_by_channels
def test_picks_by_channels():
"""Test creating pick_lists."""
rng = np.random.RandomState(909)
test_data = rng.random_sample((4, 2000))
ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
ch_types = ['grad', 'mag', 'mag', 'eeg']
sfreq = 250.0
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
_assert_channel_types(info)
raw = RawArray(test_data, info)
pick_list = _picks_by_type(raw.info)
assert_equal(len(pick_list), 3)
assert_equal(pick_list[0][0], 'mag')
pick_list2 = _picks_by_type(raw.info, meg_combined=False)
assert_equal(len(pick_list), len(pick_list2))
assert_equal(pick_list2[0][0], 'mag')
pick_list2 = _picks_by_type(raw.info, meg_combined=True)
assert_equal(len(pick_list), len(pick_list2) + 1)
assert_equal(pick_list2[0][0], 'meg')
test_data = rng.random_sample((4, 2000))
ch_names = ['MEG %03d' % i for i in [1, 2, 3, 4]]
ch_types = ['mag', 'mag', 'mag', 'mag']
sfreq = 250.0
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
raw = RawArray(test_data, info)
# This acts as a set, not an order
assert_array_equal(pick_channels(info['ch_names'], ['MEG 002', 'MEG 001']),
[0, 1])
# Make sure checks for list input work.
pytest.raises(ValueError, pick_channels, ch_names, 'MEG 001')
pytest.raises(ValueError, pick_channels, ch_names, ['MEG 001'], 'hi')
pick_list = _picks_by_type(raw.info)
assert_equal(len(pick_list), 1)
assert_equal(pick_list[0][0], 'mag')
pick_list2 = _picks_by_type(raw.info, meg_combined=True)
assert_equal(len(pick_list), len(pick_list2))
assert_equal(pick_list2[0][0], 'mag')
# pick_types type check
pytest.raises(ValueError, raw.pick_types, eeg='string')
# duplicate check
names = ['MEG 002', 'MEG 002']
assert len(pick_channels(raw.info['ch_names'], names)) == 1
assert len(raw.copy().pick_channels(names)[0][0]) == 1
示例13: test_annotations
def test_annotations():
"""Test annotation class."""
raw = read_raw_fif(fif_fname)
onset = np.array(range(10))
duration = np.ones(10)
description = np.repeat('test', 10)
dt = datetime.utcnow()
meas_date = raw.info['meas_date']
# Test time shifts.
for orig_time in [None, dt, meas_date[0], meas_date]:
annot = Annotations(onset, duration, description, orig_time)
assert_raises(ValueError, Annotations, onset, duration, description[:9])
assert_raises(ValueError, Annotations, [onset, 1], duration, description)
assert_raises(ValueError, Annotations, onset, [duration, 1], description)
# Test combining annotations with concatenate_raws
raw2 = raw.copy()
orig_time = (meas_date[0] + meas_date[1] * 0.000001 +
raw2.first_samp / raw2.info['sfreq'])
annot = Annotations(onset, duration, description, orig_time)
raw2.annotations = annot
assert_array_equal(raw2.annotations.onset, onset)
concatenate_raws([raw, raw2])
assert_array_almost_equal(onset + 20., raw.annotations.onset, decimal=2)
assert_array_equal(annot.duration, raw.annotations.duration)
assert_array_equal(raw.annotations.description, np.repeat('test', 10))
# Test combining with RawArray and orig_times
data = np.random.randn(2, 1000) * 10e-12
sfreq = 100.
info = create_info(ch_names=['MEG1', 'MEG2'], ch_types=['grad'] * 2,
sfreq=sfreq)
info['meas_date'] = 0
raws = []
for i, fs in enumerate([1000, 100, 12]):
raw = RawArray(data.copy(), info, first_samp=fs)
ants = Annotations([1., 2.], [.5, .5], 'x', fs / sfreq)
raw.annotations = ants
raws.append(raw)
raw = concatenate_raws(raws)
assert_array_equal(raw.annotations.onset, [1., 2., 11., 12., 21., 22.])
raw.annotations.delete(2)
assert_array_equal(raw.annotations.onset, [1., 2., 12., 21., 22.])
raw.annotations.append(5, 1.5, 'y')
assert_array_equal(raw.annotations.onset, [1., 2., 12., 21., 22., 5])
assert_array_equal(raw.annotations.duration, [.5, .5, .5, .5, .5, 1.5])
assert_array_equal(raw.annotations.description, ['x', 'x', 'x', 'x', 'x',
'y'])
示例14: test_date_none
def test_date_none(tmpdir):
"""Test that DATE_NONE is used properly."""
# Regression test for gh-5908
n_chans = 139
n_samps = 20
data = np.random.random_sample((n_chans, n_samps))
ch_names = ['E{}'.format(x) for x in range(n_chans)]
ch_types = ['eeg'] * n_chans
info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=2048)
assert info['meas_date'] is None
raw = RawArray(data=data, info=info)
fname = op.join(str(tmpdir), 'test-raw.fif')
raw.save(fname)
raw_read = read_raw_fif(fname, preload=True)
assert raw_read.info['meas_date'] is None
示例15: test_crop
def test_crop():
"""Test cropping raw files
"""
# split a concatenated file to test a difficult case
raw = concatenate_raws([Raw(f) for f in [fif_fname, fif_fname]])
split_size = 10. # in seconds
sfreq = raw.info['sfreq']
nsamp = (raw.last_samp - raw.first_samp + 1)
# do an annoying case (off-by-one splitting)
tmins = np.r_[1., np.round(np.arange(0., nsamp - 1, split_size * sfreq))]
tmins = np.sort(tmins)
tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1]))
tmaxs /= sfreq
tmins /= sfreq
raws = [None] * len(tmins)
for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)):
raws[ri] = raw.copy().crop(tmin, tmax, copy=False)
all_raw_2 = concatenate_raws(raws, preload=False)
assert_equal(raw.first_samp, all_raw_2.first_samp)
assert_equal(raw.last_samp, all_raw_2.last_samp)
assert_array_equal(raw[:, :][0], all_raw_2[:, :][0])
tmins = np.round(np.arange(0., nsamp - 1, split_size * sfreq))
tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1]))
tmaxs /= sfreq
tmins /= sfreq
# going in revere order so the last fname is the first file (need it later)
raws = [None] * len(tmins)
for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)):
raws[ri] = raw.copy().crop(tmin, tmax, copy=False)
# test concatenation of split file
all_raw_1 = concatenate_raws(raws, preload=False)
all_raw_2 = raw.copy().crop(0, None, copy=False)
for ar in [all_raw_1, all_raw_2]:
assert_equal(raw.first_samp, ar.first_samp)
assert_equal(raw.last_samp, ar.last_samp)
assert_array_equal(raw[:, :][0], ar[:, :][0])
# test shape consistency of cropped raw
data = np.zeros((1, 1002001))
info = create_info(1, 1000)
raw = RawArray(data, info)
for tmin in range(0, 1001, 100):
raw1 = raw.copy().crop(tmin=tmin, tmax=tmin + 2, copy=False)
assert_equal(raw1[:][0].shape, (1, 2001))