def test_long_names(): """Test long name support.""" info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., verbose='error') data = np.empty((2, 1000)) raw = RawArray(data, info) assert raw.ch_names == ['a' * 13 + '-0', 'a' * 13 + '-1'] info = create_info(['a' * 16] * 11, 1000., verbose='error') data = np.empty((11, 1000)) raw = RawArray(data, info) assert raw.ch_names == ['a' * 12 + '-%s' % ii for ii in range(11)]
def test_array_copy(): """Test copying during construction.""" info = create_info(1, 1000.) data = np.empty((1, 1000)) # 'auto' (default) raw = RawArray(data, info) assert raw._data is data assert raw.info is not info raw = RawArray(data.astype(np.float32), info) assert raw._data is not data assert raw.info is not info # 'info' (more restrictive) raw = RawArray(data, info, copy='info') assert raw._data is data assert raw.info is not info with pytest.raises(ValueError, match="data copying was not .* copy='info"): RawArray(data.astype(np.float32), info, copy='info') # 'data' raw = RawArray(data, info, copy='data') assert raw._data is not data assert raw.info is info # 'both' raw = RawArray(data, info, copy='both') assert raw._data is not data assert raw.info is not info raw = RawArray(data.astype(np.float32), info, copy='both') assert raw._data is not data assert raw.info is not info # None raw = RawArray(data, info, copy=None) assert raw._data is data assert raw.info is info with pytest.raises(ValueError, match='data copying was not .* copy=None'): RawArray(data.astype(np.float32), info, copy=None)
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) 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) # Make sure checks for list input work. assert_raises(ValueError, pick_channels, ch_names, 'MEG 001') assert_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')
def to_fif(self): import mne print('have mne %r, version %r', mne, mne.__version__) from mne.io.array import RawArray try: from mne.io.meas_info import create_info except ImportError: from mne.io.array import create_info print('reading data') data, _ = self.read_data() types = ['eeg' for _ in data] print('creating info') info = create_info(self.chnm, self.srate, ['eeg' for _ in data]) print('creating raw') raw = RawArray(data, info) return raw
def test_pick_seeg(): names = 'A1 A2 Fz O OTp1 OTp2 OTp3'.split() types = 'mag mag eeg eeg seeg seeg seeg'.split() info = create_info(names, 1024., types) idx = channel_indices_by_type(info) assert_array_equal(idx['mag'], [0, 1]) assert_array_equal(idx['eeg'], [2, 3]) assert_array_equal(idx['seeg'], [4, 5, 6]) assert_array_equal(pick_types(info, meg=False, seeg=True), [4, 5, 6]) for i, t in enumerate(types): assert_equal(channel_type(info, i), types[i]) raw = RawArray(zeros((len(names), 10)), info) events = array([[1, 0, 0], [2, 0, 0]]).astype('d') epochs = Epochs(raw, events, {'event': 0}, -1e-5, 1e-5) evoked = epochs.average(pick_types(epochs.info, meg=True, seeg=True)) e_seeg = pick_types_evoked(evoked, meg=False, seeg=True) for l, r in zip(e_seeg.ch_names, names[4:]): assert_equal(l, r)
def test_long_names(): """Test long name support.""" info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., verbose='error') data = np.empty((2, 1000)) raw = RawArray(data, info) assert raw.ch_names == ['a' * 15 + 'b', 'a' * 16] # and a way to get the old behavior raw.rename_channels({k: k[:13] for k in raw.ch_names}, allow_duplicates=True, verbose='error') assert raw.ch_names == ['a' * 13 + '-0', 'a' * 13 + '-1'] info = create_info(['a' * 16] * 11, 1000., verbose='error') data = np.empty((11, 1000)) raw = RawArray(data, info) assert raw.ch_names == ['a' * 16 + '-%s' % ii for ii in range(11)]
def test_array_raw(): """Test creating raw from array.""" import matplotlib.pyplot as plt # creating raw = read_raw_fif(fif_fname).crop(2, 5) data, times = raw[:, :] sfreq = raw.info['sfreq'] ch_names = [(ch[4:] if 'STI' not in ch else ch) for ch in raw.info['ch_names']] # change them, why not # del raw types = list() for ci in range(101): types.extend(('grad', 'grad', 'mag')) types.extend(['ecog', 'seeg', 'hbo']) # really 3 meg channels types.extend(['stim'] * 9) types.extend(['eeg'] * 60) # wrong length pytest.raises(ValueError, create_info, ch_names, sfreq, types) # bad entry types.append('foo') pytest.raises(KeyError, create_info, ch_names, sfreq, types) types[-1] = 'eog' # default type info = create_info(ch_names, sfreq) assert_equal(info['chs'][0]['kind'], _kind_dict['misc'][0]) # use real types info = create_info(ch_names, sfreq, types) raw2 = _test_raw_reader(RawArray, test_preloading=False, data=data, info=info, first_samp=2 * data.shape[1]) data2, times2 = raw2[:, :] assert_allclose(data, data2) assert_allclose(times, times2) assert ('RawArray' in repr(raw2)) pytest.raises(TypeError, RawArray, info, data) # filtering picks = pick_types(raw2.info, misc=True, exclude='bads')[:4] assert_equal(len(picks), 4) raw_lp = raw2.copy() kwargs = dict(fir_design='firwin', picks=picks) raw_lp.filter(None, 4.0, h_trans_bandwidth=4., n_jobs=2, **kwargs) raw_hp = raw2.copy() raw_hp.filter(16.0, None, l_trans_bandwidth=4., n_jobs=2, **kwargs) raw_bp = raw2.copy() raw_bp.filter(8.0, 12.0, l_trans_bandwidth=4., h_trans_bandwidth=4., **kwargs) raw_bs = raw2.copy() raw_bs.filter(16.0, 4.0, l_trans_bandwidth=4., h_trans_bandwidth=4., n_jobs=2, **kwargs) data, _ = raw2[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] bs_data, _ = raw_bs[picks, :] sig_dec = 15 assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec) assert_array_almost_equal(data, bp_data + bs_data, sig_dec) # plotting raw2.plot() raw2.plot_psd(tmax=np.inf, average=True, n_fft=1024, spatial_colors=False) plt.close('all') # epoching events = find_events(raw2, stim_channel='STI 014') events[:, 2] = 1 assert (len(events) > 2) epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True) epochs.plot_drop_log() epochs.plot() evoked = epochs.average() evoked.plot(time_unit='s') assert_equal(evoked.nave, len(events) - 1) plt.close('all') # complex data rng = np.random.RandomState(0) data = rng.randn(1, 100) + 1j * rng.randn(1, 100) raw = RawArray(data, create_info(1, 1000., 'eeg')) assert_allclose(raw._data, data) # Using digital montage to give MNI electrode coordinates n_elec = 10 ts_size = 10000 Fs = 512. elec_labels = [str(i) for i in range(n_elec)] elec_coords = np.random.randint(60, size=(n_elec, 3)).tolist() electrode = np.random.rand(n_elec, ts_size) dig_ch_pos = dict(zip(elec_labels, elec_coords)) mon = channels.DigMontage(dig_ch_pos=dig_ch_pos) info = create_info(elec_labels, Fs, 'ecog', montage=mon) raw = RawArray(electrode, info) raw.plot_psd(average=False) # looking for inexistent layout raw.plot_psd_topo()
def test_array_raw(): """Test creating raw from array """ tempdir = _TempDir() # creating raw = Raw(fif_fname).crop(2, 5, copy=False) data, times = raw[:, :] sfreq = raw.info['sfreq'] ch_names = [(ch[4:] if 'STI' not in ch else ch) for ch in raw.info['ch_names']] # change them, why not # del raw types = list() for ci in range(102): types.extend(('grad', 'grad', 'mag')) types.extend(['stim'] * 9) types.extend(['eeg'] * 60) # wrong length assert_raises(ValueError, create_info, ch_names, sfreq, types) # bad entry types.append('foo') assert_raises(KeyError, create_info, ch_names, sfreq, types) types[-1] = 'eog' # default type info = create_info(ch_names, sfreq) assert_equal(info['chs'][0]['kind'], _kind_dict['misc'][0]) # use real types info = create_info(ch_names, sfreq, types) raw2 = RawArray(data, info) data2, times2 = raw2[:, :] assert_allclose(data, data2) assert_allclose(times, times2) # Make sure concatenation works raw_concat = concatenate_raws([raw2.copy(), raw2]) assert_equal(raw_concat.n_times, 2 * raw2.n_times) assert_true('RawArray' in repr(raw2)) # saving temp_fname = op.join(tempdir, 'raw.fif') raw2.save(temp_fname) raw3 = Raw(temp_fname) data3, times3 = raw3[:, :] assert_allclose(data, data3) assert_allclose(times, times3) # filtering picks = pick_types(raw2.info, misc=True, exclude='bads')[:4] assert_equal(len(picks), 4) raw_lp = raw2.copy() with warnings.catch_warnings(record=True): raw_lp.filter(0., 4.0 - 0.25, picks=picks, n_jobs=2) raw_hp = raw2.copy() with warnings.catch_warnings(record=True): raw_hp.filter(8.0 + 0.25, None, picks=picks, n_jobs=2) raw_bp = raw2.copy() with warnings.catch_warnings(record=True): raw_bp.filter(4.0 + 0.25, 8.0 - 0.25, picks=picks) raw_bs = raw2.copy() with warnings.catch_warnings(record=True): raw_bs.filter(8.0 + 0.25, 4.0 - 0.25, picks=picks, n_jobs=2) data, _ = raw2[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] bs_data, _ = raw_bs[picks, :] sig_dec = 11 assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec) assert_array_almost_equal(data, bp_data + bs_data, sig_dec) # plotting raw2.plot() raw2.plot_psd() # epoching events = find_events(raw2, stim_channel='STI 014') events[:, 2] = 1 assert_true(len(events) > 2) epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True) epochs.plot_drop_log() epochs.plot() evoked = epochs.average() evoked.plot()
def test_array_raw(): """Test creating raw from array """ import matplotlib.pyplot as plt tempdir = _TempDir() # creating raw = Raw(fif_fname).crop(2, 5, copy=False) data, times = raw[:, :] sfreq = raw.info['sfreq'] ch_names = [(ch[4:] if 'STI' not in ch else ch) for ch in raw.info['ch_names']] # change them, why not # del raw types = list() for ci in range(102): types.extend(('grad', 'grad', 'mag')) types.extend(['stim'] * 9) types.extend(['eeg'] * 60) # wrong length assert_raises(ValueError, create_info, ch_names, sfreq, types) # bad entry types.append('foo') assert_raises(KeyError, create_info, ch_names, sfreq, types) types[-1] = 'eog' # default type info = create_info(ch_names, sfreq) assert_equal(info['chs'][0]['kind'], _kind_dict['misc'][0]) # use real types info = create_info(ch_names, sfreq, types) raw2 = RawArray(data, info) data2, times2 = raw2[:, :] assert_allclose(data, data2) assert_allclose(times, times2) # Make sure concatenation works raw_concat = concatenate_raws([raw2.copy(), raw2]) assert_equal(raw_concat.n_times, 2 * raw2.n_times) assert_true('RawArray' in repr(raw2)) # saving temp_fname = op.join(tempdir, 'raw.fif') raw2.save(temp_fname) raw3 = Raw(temp_fname) data3, times3 = raw3[:, :] assert_allclose(data, data3) assert_allclose(times, times3) # filtering picks = pick_types(raw2.info, misc=True, exclude='bads')[:4] assert_equal(len(picks), 4) raw_lp = raw2.copy() with warnings.catch_warnings(record=True): raw_lp.filter(0., 4.0 - 0.25, picks=picks, n_jobs=2) raw_hp = raw2.copy() with warnings.catch_warnings(record=True): raw_hp.filter(8.0 + 0.25, None, picks=picks, n_jobs=2) raw_bp = raw2.copy() with warnings.catch_warnings(record=True): raw_bp.filter(4.0 + 0.25, 8.0 - 0.25, picks=picks) raw_bs = raw2.copy() with warnings.catch_warnings(record=True): raw_bs.filter(8.0 + 0.25, 4.0 - 0.25, picks=picks, n_jobs=2) data, _ = raw2[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] bs_data, _ = raw_bs[picks, :] sig_dec = 11 assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec) assert_array_almost_equal(data, bp_data + bs_data, sig_dec) # plotting raw2.plot() raw2.plot_psd() plt.close('all') # epoching events = find_events(raw2, stim_channel='STI 014') events[:, 2] = 1 assert_true(len(events) > 2) epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True) epochs.plot_drop_log() with warnings.catch_warnings(record=True): # deprecation warnings.simplefilter('always') epochs.plot() evoked = epochs.average() evoked.plot() plt.close('all')
def test_array_raw(): """Test creating raw from array.""" import matplotlib.pyplot as plt # creating raw = read_raw_fif(fif_fname).crop(2, 5) data, times = raw[:, :] sfreq = raw.info['sfreq'] ch_names = [(ch[4:] if 'STI' not in ch else ch) for ch in raw.info['ch_names']] # change them, why not # del raw types = list() for ci in range(101): types.extend(('grad', 'grad', 'mag')) types.extend(['ecog', 'seeg', 'hbo']) # really 3 meg channels types.extend(['stim'] * 9) types.extend(['eeg'] * 60) # wrong length assert_raises(ValueError, create_info, ch_names, sfreq, types) # bad entry types.append('foo') assert_raises(KeyError, create_info, ch_names, sfreq, types) types[-1] = 'eog' # default type info = create_info(ch_names, sfreq) assert_equal(info['chs'][0]['kind'], _kind_dict['misc'][0]) # use real types info = create_info(ch_names, sfreq, types) raw2 = _test_raw_reader(RawArray, test_preloading=False, data=data, info=info, first_samp=2 * data.shape[1]) data2, times2 = raw2[:, :] assert_allclose(data, data2) assert_allclose(times, times2) assert_true('RawArray' in repr(raw2)) assert_raises(TypeError, RawArray, info, data) # filtering picks = pick_types(raw2.info, misc=True, exclude='bads')[:4] assert_equal(len(picks), 4) raw_lp = raw2.copy() kwargs = dict(fir_design='firwin', picks=picks) raw_lp.filter(None, 4.0, h_trans_bandwidth=4., n_jobs=2, **kwargs) raw_hp = raw2.copy() raw_hp.filter(16.0, None, l_trans_bandwidth=4., n_jobs=2, **kwargs) raw_bp = raw2.copy() raw_bp.filter(8.0, 12.0, l_trans_bandwidth=4., h_trans_bandwidth=4., **kwargs) raw_bs = raw2.copy() raw_bs.filter(16.0, 4.0, l_trans_bandwidth=4., h_trans_bandwidth=4., n_jobs=2, **kwargs) data, _ = raw2[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] bs_data, _ = raw_bs[picks, :] sig_dec = 15 assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec) assert_array_almost_equal(data, bp_data + bs_data, sig_dec) # plotting raw2.plot() raw2.plot_psd(tmax=np.inf, average=True, n_fft=1024, spatial_colors=False) plt.close('all') # epoching events = find_events(raw2, stim_channel='STI 014') events[:, 2] = 1 assert_true(len(events) > 2) epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True) epochs.plot_drop_log() epochs.plot() evoked = epochs.average() evoked.plot(time_unit='s') assert_equal(evoked.nave, len(events) - 1) plt.close('all') # complex data rng = np.random.RandomState(0) data = rng.randn(1, 100) + 1j * rng.randn(1, 100) raw = RawArray(data, create_info(1, 1000., 'eeg')) assert_allclose(raw._data, data) # Using digital montage to give MNI electrode coordinates n_elec = 10 ts_size = 10000 Fs = 512. elec_labels = [str(i) for i in range(n_elec)] elec_coords = np.random.randint(60, size=(n_elec, 3)).tolist() electrode = np.random.rand(n_elec, ts_size) dig_ch_pos = dict(zip(elec_labels, elec_coords)) mon = channels.DigMontage(dig_ch_pos=dig_ch_pos) info = create_info(elec_labels, Fs, 'ecog', montage=mon) raw = RawArray(electrode, info) raw.plot_psd(average=False) # looking for inexistent layout raw.plot_psd_topo()
def test_array_raw(): """Test creating raw from array """ import matplotlib.pyplot as plt # creating raw = read_raw_fif(fif_fname, add_eeg_ref=False).crop(2, 5) data, times = raw[:, :] sfreq = raw.info['sfreq'] ch_names = [(ch[4:] if 'STI' not in ch else ch) for ch in raw.info['ch_names']] # change them, why not # del raw types = list() for ci in range(101): types.extend(('grad', 'grad', 'mag')) types.extend(['ecog', 'seeg', 'hbo']) # really 3 meg channels types.extend(['stim'] * 9) types.extend(['eeg'] * 60) # wrong length assert_raises(ValueError, create_info, ch_names, sfreq, types) # bad entry types.append('foo') assert_raises(KeyError, create_info, ch_names, sfreq, types) types[-1] = 'eog' # default type info = create_info(ch_names, sfreq) assert_equal(info['chs'][0]['kind'], _kind_dict['misc'][0]) # use real types info = create_info(ch_names, sfreq, types) raw2 = _test_raw_reader(RawArray, test_preloading=False, data=data, info=info, first_samp=2 * data.shape[1]) data2, times2 = raw2[:, :] assert_allclose(data, data2) assert_allclose(times, times2) assert_true('RawArray' in repr(raw2)) assert_raises(TypeError, RawArray, info, data) # filtering picks = pick_types(raw2.info, misc=True, exclude='bads')[:4] assert_equal(len(picks), 4) raw_lp = raw2.copy() raw_lp.filter(None, 4.0, h_trans_bandwidth=4., filter_length='auto', picks=picks, n_jobs=2, phase='zero', fir_window='hamming') raw_hp = raw2.copy() raw_hp.filter(16.0, None, l_trans_bandwidth=4., filter_length='auto', picks=picks, n_jobs=2, phase='zero', fir_window='hamming') raw_bp = raw2.copy() raw_bp.filter(8.0, 12.0, l_trans_bandwidth=4., h_trans_bandwidth=4., filter_length='auto', picks=picks, phase='zero', fir_window='hamming') raw_bs = raw2.copy() raw_bs.filter(16.0, 4.0, l_trans_bandwidth=4., h_trans_bandwidth=4., filter_length='auto', picks=picks, n_jobs=2, phase='zero', fir_window='hamming') data, _ = raw2[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] bs_data, _ = raw_bs[picks, :] sig_dec = 15 assert_array_almost_equal(data, lp_data + bp_data + hp_data, sig_dec) assert_array_almost_equal(data, bp_data + bs_data, sig_dec) # plotting raw2.plot() raw2.plot_psd() plt.close('all') # epoching events = find_events(raw2, stim_channel='STI 014') events[:, 2] = 1 assert_true(len(events) > 2) epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True, add_eeg_ref=False) epochs.plot_drop_log() epochs.plot() evoked = epochs.average() evoked.plot() assert_equal(evoked.nave, len(events) - 1) plt.close('all') # complex data rng = np.random.RandomState(0) data = rng.randn(1, 100) + 1j * rng.randn(1, 100) raw = RawArray(data, create_info(1, 1000., 'eeg')) assert_allclose(raw._data, data)
assert all(ch0['sampling_rate'] == ch['sampling_rate'] for ch in channels) assert all(ch0['data'].shape == ch['data'].shape for ch in channels) sfreq = ch0['sampling_rate'] nsamp = ch0['data'].shape[0] nchan = len(channels) LOG.info('received %d channels, %dk samples @ %.3f Hz', nchan, nsamp/1000, sfreq) LOG.info('data array will required %.3fMB of memory', (nsamp * nchan) * 4 / 2**20.0) LOG.info('building data array, labels & types') data = np.zeros((nchan, nsamp), np.float32) labels = [] types = [] for i, chan in enumerate(channels): label = chan['name'] # bipolar case if chan['ref']: label += '-' + chan['ref'] LOG.debug('channel %03d %r%s', i, label, ' bipolar' if chan['ref'] else '') data[i] = chan['data'] labels.append(label) types.append('eeg') LOG.info('building mne raw instance...') info = create_info(labels, sfreq, types) raw = RawArray(data, info) LOG.info('%r', raw) raw.save(filename) LOG.info('saved %r', filename) LOG.info('done in %.3f s', time.time() - tic)