def test_subject_info(): """Test reading subject information """ raw = Raw(fif_fname) raw.crop(0, 1) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = [ 'id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand' ] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[key] = val raw.info['subject_info'] = subject_info out_fname = op.join(tempdir, 'test_subj_info_raw.fif') raw.save(out_fname, overwrite=True) raw_read = Raw(out_fname) for key in keys: assert_equal(subject_info[key], raw_read.info['subject_info'][key]) raw_read.anonymize() assert_true(raw_read.info.get('subject_info') is None) out_fname_anon = op.join(tempdir, 'test_subj_info_anon_raw.fif') raw_read.save(out_fname_anon, overwrite=True) raw_read = Raw(out_fname_anon) assert_true(raw_read.info.get('subject_info') is None)
def test_read_segment(): """Test writing raw kit files when preload is False """ raw1 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<', preload=False) raw1_file = op.join(tempdir, 'raw1.fif') raw1.save(raw1_file, buffer_size_sec=.1, overwrite=True) raw2 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<', preload=True) raw2_file = op.join(tempdir, 'raw2.fif') raw2.save(raw2_file, buffer_size_sec=.1, overwrite=True) raw1 = Raw(raw1_file, preload=True) raw2 = Raw(raw2_file, preload=True) assert_array_equal(raw1._data, raw2._data) raw3 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<', preload=True) assert_array_almost_equal(raw1._data, raw3._data)
def test_preload_modify(): """ Test preloading and modifying data """ for preload in [False, True, 'memmap.dat']: raw = Raw(fif_fname, preload=preload) nsamp = raw.last_samp - raw.first_samp + 1 picks = pick_types(raw.info, meg='grad') data = np.random.randn(len(picks), nsamp / 2) try: raw[picks, :nsamp / 2] = data except RuntimeError as err: if not preload: continue else: raise err tmp_fname = 'raw.fif' raw.save(tmp_fname) raw_new = Raw(tmp_fname) data_new, _ = raw_new[picks, :nsamp / 2] assert_array_almost_equal(data, data_new)
def test_preload_modify(): """ Test preloading and modifying data """ for preload in [False, True, 'memmap.dat']: raw = Raw(fif_fname, preload=preload) nsamp = raw.last_samp - raw.first_samp + 1 picks = pick_types(raw.info, meg='grad', exclude='bads') data = np.random.randn(len(picks), nsamp / 2) try: raw[picks, :nsamp / 2] = data except RuntimeError as err: if not preload: continue else: raise err tmp_fname = op.join(tempdir, 'raw.fif') raw.save(tmp_fname, overwrite=True) raw_new = Raw(tmp_fname) data_new, _ = raw_new[picks, :nsamp / 2] assert_allclose(data, data_new)
def test_read_segment(): """Test writing raw edf files when preload is False """ raw1 = read_raw_edf(edf_path, stim_channel=139, preload=False) raw1_file = op.join(tempdir, 'raw1.fif') raw1.save(raw1_file, overwrite=True, buffer_size_sec=1) raw11 = Raw(raw1_file, preload=True) data1, times1 = raw1[:139, :] data11, times11 = raw11[:139, :] assert_array_almost_equal(data1, data11, 10) assert_array_almost_equal(times1, times11) assert_equal(sorted(raw1.info.keys()), sorted(raw11.info.keys())) raw2 = read_raw_edf(edf_path, stim_channel=139, preload=True) raw2_file = op.join(tempdir, 'raw2.fif') raw2.save(raw2_file, overwrite=True) data2, times2 = raw2[:139, :] assert_array_equal(data1, data2) assert_array_equal(times1, times2) raw1 = Raw(raw1_file, preload=True) raw2 = Raw(raw2_file, preload=True) assert_array_equal(raw1._data, raw2._data) # test the _read_segment function by only loading some of the data raw1 = read_raw_edf(edf_path, preload=False) raw2 = read_raw_edf(edf_path, preload=True) # select some random range of data to compare data1, times1 = raw1[:, 345:417] data2, times2 = raw2[:, 345:417] assert_array_equal(data1, data2) assert_array_equal(times1, times2)
def test_pick_channels_mixin(): """Test channel-picking functionality """ # preload is True raw = Raw(fif_fname, preload=True) ch_names = raw.ch_names[:3] ch_names_orig = raw.ch_names dummy = raw.pick_channels(ch_names, copy=True) # copy is True assert_equal(ch_names, dummy.ch_names) assert_equal(ch_names_orig, raw.ch_names) assert_equal(len(ch_names_orig), raw._data.shape[0]) raw.pick_channels(ch_names, copy=False) # copy is False assert_equal(ch_names, raw.ch_names) assert_equal(len(ch_names), len(raw.cals)) assert_equal(len(ch_names), raw._data.shape[0]) # preload is False raw = Raw(fif_fname, preload=False) ch_names = raw.ch_names[:3] ch_names_orig = raw.ch_names dummy = raw.pick_channels(ch_names, copy=True) # copy is True assert_equal(ch_names, dummy.ch_names) assert_equal(ch_names_orig, raw.ch_names) raw.pick_channels(ch_names, copy=False) # copy is False assert_equal(ch_names, raw.ch_names) assert_equal(len(ch_names), len(raw.cals))
def test_raw_to_nitime(): """ Test nitime export """ raw = Raw(fif_fname, preload=True) picks_meg = pick_types(raw.info, meg=True, exclude='bads') picks = picks_meg[:4] raw_ts = raw.to_nitime(picks=picks) assert_true(raw_ts.data.shape[0] == len(picks)) raw = Raw(fif_fname, preload=False) picks_meg = pick_types(raw.info, meg=True, exclude='bads') picks = picks_meg[:4] raw_ts = raw.to_nitime(picks=picks) assert_true(raw_ts.data.shape[0] == len(picks)) raw = Raw(fif_fname, preload=True) picks_meg = pick_types(raw.info, meg=True, exclude='bads') picks = picks_meg[:4] raw_ts = raw.to_nitime(picks=picks, copy=False) assert_true(raw_ts.data.shape[0] == len(picks)) raw = Raw(fif_fname, preload=False) picks_meg = pick_types(raw.info, meg=True, exclude='bads') picks = picks_meg[:4] raw_ts = raw.to_nitime(picks=picks, copy=False) assert_true(raw_ts.data.shape[0] == len(picks))
def test_raw(): """ Test bti conversion to Raw object """ for pdf, config, hs, exported in zip(pdf_fnames, config_fnames, hs_fnames, exported_fnames): # rx = 2 if 'linux' in pdf else 0 assert_raises(ValueError, read_raw_bti, pdf, 'eggs') assert_raises(ValueError, read_raw_bti, pdf, config, 'spam') if op.exists(tmp_raw_fname): os.remove(tmp_raw_fname) with Raw(exported, preload=True) as ex: with read_raw_bti(pdf, config, hs) as ra: assert_equal(ex.ch_names[:NCH], ra.ch_names[:NCH]) assert_array_almost_equal(ex.info['dev_head_t']['trans'], ra.info['dev_head_t']['trans'], 7) dig1, dig2 = [np.array([d['r'] for d in r_.info['dig']]) for r_ in ra, ex] assert_array_equal(dig1, dig2) coil1, coil2 = [np.concatenate([d['coil_trans'].flatten() for d in r_.info['chs'][:NCH]]) for r_ in ra, ex] assert_array_almost_equal(coil1, coil2, 7) loc1, loc2 = [np.concatenate([d['loc'].flatten() for d in r_.info['chs'][:NCH]]) for r_ in ra, ex] assert_array_equal(loc1, loc2) assert_array_equal(ra._data[:NCH], ex._data[:NCH]) assert_array_equal(ra.cals[:NCH], ex.cals[:NCH]) ra.save(tmp_raw_fname) with Raw(tmp_raw_fname) as r: print r os.remove(tmp_raw_fname)
def test_read_segment(): """Test writing raw kit files when preload is False """ raw1 = kit.read_raw_kit(input_fname=op.join(data_dir, 'test.sqd'), mrk_fname=op.join(data_dir, 'test_mrk.sqd'), elp_fname=op.join(data_dir, 'test_elp.txt'), hsp_fname=op.join(data_dir, 'test_hsp.txt'), sns_fname=op.join(data_dir, 'sns.txt'), stim=range(167, 159, -1), preload=False) raw1_file = op.join(tempdir, 'raw1.fif') raw1.save(raw1_file, buffer_size_sec=.1, overwrite=True) raw2 = kit.read_raw_kit(input_fname=op.join(data_dir, 'test.sqd'), mrk_fname=op.join(data_dir, 'test_mrk.sqd'), elp_fname=op.join(data_dir, 'test_elp.txt'), hsp_fname=op.join(data_dir, 'test_hsp.txt'), sns_fname=op.join(data_dir, 'sns.txt'), stim=range(167, 159, -1), preload=True) raw2_file = op.join(tempdir, 'raw2.fif') raw2.save(raw2_file, buffer_size_sec=.1, overwrite=True) raw1 = Raw(raw1_file, preload=True) raw2 = Raw(raw2_file, preload=True) assert_array_equal(raw1._data, raw2._data) raw3 = kit.read_raw_kit(input_fname=op.join(data_dir, 'test.sqd'), mrk_fname=op.join(data_dir, 'test_mrk.sqd'), elp_fname=op.join(data_dir, 'test_elp.txt'), hsp_fname=op.join(data_dir, 'test_hsp.txt'), sns_fname=op.join(data_dir, 'sns.txt'), stim=range(167, 159, -1), preload=True) assert_array_almost_equal(raw1._data, raw3._data)
def test_copy_append(): """Test raw copying and appending combinations """ raw = Raw(fif_fname, preload=True).copy() raw_full = Raw(fif_fname) raw_full.append(raw) data = raw_full[:, :][0] assert_true(data.shape[1] == 2 * raw._data.shape[1])
def test_proj(): """Test SSP proj operations """ for proj_active in [True, False]: raw = Raw(fif_fname, preload=False, proj_active=proj_active) assert_true(all(p['active'] == proj_active for p in raw.info['projs'])) data, times = raw[0:2, :] data1, times1 = raw[0:2] assert_array_equal(data, data1) assert_array_equal(times, times1) # test adding / deleting proj if proj_active: assert_raises(ValueError, raw.add_proj, [], {'remove_existing': True}) assert_raises(ValueError, raw.del_proj, 0) else: projs = deepcopy(raw.info['projs']) n_proj = len(raw.info['projs']) raw.del_proj(0) assert_true(len(raw.info['projs']) == n_proj - 1) raw.add_proj(projs, remove_existing=False) assert_true(len(raw.info['projs']) == 2 * n_proj - 1) raw.add_proj(projs, remove_existing=True) assert_true(len(raw.info['projs']) == n_proj) # test apply_proj() with and without preload for preload in [True, False]: raw = Raw(fif_fname, preload=preload, proj_active=False) data, times = raw[:, 0:2] raw.apply_projector() data_proj_1 = np.dot(raw._projector, data) # load the file again without proj raw = Raw(fif_fname, preload=preload, proj_active=False) # write the file with proj. activated, make sure proj has been applied raw.save('raw.fif', proj_active=True) raw2 = Raw('raw.fif', proj_active=False) data_proj_2, _ = raw2[:, 0:2] assert_array_almost_equal(data_proj_1, data_proj_2) assert_true(all(p['active'] for p in raw2.info['projs'])) # read orig file with proj. active raw2 = Raw(fif_fname, preload=preload, proj_active=True) data_proj_2, _ = raw2[:, 0:2] assert_array_almost_equal(data_proj_1, data_proj_2) assert_true(all(p['active'] for p in raw2.info['projs'])) # test that apply_projector works raw.apply_projector() data_proj_2, _ = raw[:, 0:2] assert_array_almost_equal(data_proj_1, data_proj_2) assert_array_almost_equal(data_proj_2, np.dot(raw._projector, data_proj_2))
def test_resample(): """Test resample (with I/O and multiple files) """ raw = Raw(fif_fname, preload=True).crop(0, 3, False) raw_resamp = raw.copy() sfreq = raw.info['sfreq'] # test parallel on upsample raw_resamp.resample(sfreq * 2, n_jobs=2) assert_true(raw_resamp.n_times == len(raw_resamp._times)) raw_resamp.save(op.join(tempdir, 'raw_resamp.fif')) raw_resamp = Raw(op.join(tempdir, 'raw_resamp.fif'), preload=True) assert_true(sfreq == raw_resamp.info['sfreq'] / 2) assert_true(raw.n_times == raw_resamp.n_times / 2) assert_true(raw_resamp._data.shape[1] == raw_resamp.n_times) assert_true(raw._data.shape[0] == raw_resamp._data.shape[0]) # test non-parallel on downsample raw_resamp.resample(sfreq, n_jobs=1) assert_true(raw_resamp.info['sfreq'] == sfreq) assert_true(raw._data.shape == raw_resamp._data.shape) assert_true(raw.first_samp == raw_resamp.first_samp) assert_true(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'])
def test_rank_estimation(): """Test raw rank estimation """ raw = Raw(fif_fname) n_meg = len(pick_types(raw.info, meg=True, eeg=False, exclude='bads')) n_eeg = len(pick_types(raw.info, meg=False, eeg=True, exclude='bads')) raw = Raw(fif_fname, preload=True) assert_array_equal(raw.estimate_rank(), n_meg + n_eeg) raw = Raw(fif_fname, preload=False) raw.apply_proj() n_proj = len(raw.info['projs']) assert_array_equal(raw.estimate_rank(tstart=10, tstop=20), n_meg + n_eeg - n_proj)
def test_raw_copy(): """ Test Raw copy""" raw = Raw(fif_fname, preload=True) data, _ = raw[:, :] copied = raw.copy() copied_data, _ = copied[:, :] assert_array_equal(data, copied_data) assert_equal(sorted(raw.__dict__.keys()), sorted(copied.__dict__.keys())) raw = Raw(fif_fname, preload=False) data, _ = raw[:, :] copied = raw.copy() copied_data, _ = copied[:, :] assert_array_equal(data, copied_data) assert_equal(sorted(raw.__dict__.keys()), sorted(copied.__dict__.keys()))
def test_cov_estimation_on_raw_segment(): """Test estimation from raw on continuous recordings (typically empty room) """ raw = Raw(raw_fname, preload=False) cov = compute_raw_data_covariance(raw) cov_mne = read_cov(erm_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') < 1e-4) # test IO when computation done in Python cov.save(op.join(tempdir, 'test-cov.fif')) # test saving cov_read = read_cov(op.join(tempdir, 'test-cov.fif')) assert_true(cov_read.ch_names == cov.ch_names) assert_true(cov_read.nfree == cov.nfree) assert_array_almost_equal(cov.data, cov_read.data) # test with a subset of channels picks = pick_channels(raw.ch_names, include=raw.ch_names[:5]) cov = compute_raw_data_covariance(raw, picks=picks) assert_true(cov_mne.ch_names[:5] == cov.ch_names) assert_true( linalg.norm(cov.data - cov_mne.data[picks][:, picks], ord='fro') / linalg.norm(cov.data, ord='fro') < 1e-4) # make sure we get a warning with too short a segment raw_2 = raw.crop(0, 1) with warnings.catch_warnings(record=True) as w: cov = compute_raw_data_covariance(raw_2) assert_true(len(w) == 1)
def test_set_eeg_reference(): """ Test rereference eeg data""" raw = Raw(fif_fname, preload=True) # Rereference raw data by creating a copy of original data reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'], copy=True) # Separate EEG channels from other channel types picks_eeg = pick_types(raw.info, meg=False, eeg=True, exclude='bads') picks_other = pick_types(raw.info, meg=True, eeg=False, eog=True, stim=True, exclude='bads') # Get the raw EEG data and other channel data raw_eeg_data = raw[picks_eeg][0] raw_other_data = raw[picks_other][0] # Get the rereferenced EEG data and channel other reref_eeg_data = reref[picks_eeg][0] unref_eeg_data = reref_eeg_data + ref_data # Undo rereferencing of EEG channels reref_other_data = reref[picks_other][0] # Check that both EEG data and other data is the same assert_array_equal(raw_eeg_data, unref_eeg_data) assert_array_equal(raw_other_data, reref_other_data) # Test that data is modified in place when copy=False reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'], copy=False) assert_true(raw is reref)
def test_data(): """Test reading raw kit files """ raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim=list(range(167, 159, -1)), slope='+', stimthresh=1, preload=True) print(repr(raw_py)) # Binary file only stores the sensor channels py_picks = pick_types(raw_py.info, exclude='bads') raw_bin = op.join(data_dir, 'test_bin.fif') raw_bin = Raw(raw_bin, preload=True) bin_picks = pick_types(raw_bin.info, stim=True, exclude='bads') data_bin, _ = raw_bin[bin_picks] data_py, _ = raw_py[py_picks] # this .mat was generated using the Yokogawa MEG Reader data_Ykgw = op.join(data_dir, 'test_Ykgw.mat') data_Ykgw = scipy.io.loadmat(data_Ykgw)['data'] data_Ykgw = data_Ykgw[py_picks] assert_array_almost_equal(data_py, data_Ykgw) py_picks = pick_types(raw_py.info, stim=True, ref_meg=False, exclude='bads') data_py, _ = raw_py[py_picks] assert_array_almost_equal(data_py, data_bin)
def test_stim_elim(): """Test eliminate stim artifact""" raw = Raw(raw_fname, preload=True) events = read_events(event_fname) event_idx = np.where(events[:, 2] == 1)[0][0] tidx = events[event_idx, 0] - raw.first_samp raw = eliminate_stim_artifact(raw, events, event_id=1, tmin=-0.005, tmax=0.01, mode='linear') data, times = raw[:, tidx - 3:tidx + 5] diff_data0 = np.diff(data[0]) diff_data0 -= np.mean(diff_data0) assert_array_almost_equal(diff_data0, np.zeros(len(diff_data0))) raw = eliminate_stim_artifact(raw, events, event_id=1, tmin=-0.005, tmax=0.01, mode='window') data, times = raw[:, tidx:tidx + 1] assert_true(np.all(data) == 0.)
def test_filter(): """ Test filtering and Raw.apply_function interface """ raw = Raw(fif_fname, preload=True) picks_meg = pick_types(raw.info, meg=True) picks = picks_meg[:4] raw_lp = deepcopy(raw) raw_lp.filter(0., 4.0, picks=picks, n_jobs=2) raw_hp = deepcopy(raw) raw_lp.filter(8.0, None, picks=picks, n_jobs=2) raw_bp = deepcopy(raw) raw_bp.filter(4.0, 8.0, picks=picks) data, _ = raw[picks, :] lp_data, _ = raw_lp[picks, :] hp_data, _ = raw_hp[picks, :] bp_data, _ = raw_bp[picks, :] assert_array_almost_equal(data, lp_data + hp_data + bp_data) # 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)
def test_raw_index_as_time(): """ Test index as time conversion""" raw = Raw(fif_fname, preload=True) t0 = raw.index_as_time([0], True)[0] t1 = raw.index_as_time([100], False)[0] t2 = raw.index_as_time([100], True)[0] assert_true((t2 - t1) == t0)
def test_brainvision_data(): """Test reading raw Brain Vision files """ raw_py = read_raw_brainvision(vhdr_path, elp_path, elp_names, preload=True) picks = pick_types(raw_py.info, meg=False, eeg=True, exclude='bads') data_py, times_py = raw_py[picks] print(raw_py) # to test repr print(raw_py.info) # to test Info repr # compare with a file that was generated using MNE-C raw_bin = Raw(eeg_bin, preload=True) picks = pick_types(raw_py.info, meg=False, eeg=True, exclude='bads') data_bin, times_bin = raw_bin[picks] assert_array_almost_equal(data_py, data_bin) assert_array_almost_equal(times_py, times_bin) # Make sure EOG channels are marked correctly raw_py = read_raw_brainvision(vhdr_path, elp_path, elp_names, eog=eog, preload=True) for ch in raw_py.info['chs']: if ch['ch_name'] in eog: assert_equal(ch['kind'], FIFF.FIFFV_EOG_CH) elif ch['ch_name'] in elp_names: assert_equal(ch['kind'], FIFF.FIFFV_EEG_CH) elif ch['ch_name'] == 'STI 014': assert_equal(ch['kind'], FIFF.FIFFV_STIM_CH) else: raise RuntimeError("Unknown Channel: %s" % ch['ch_name'])
def test_data(): """Test reading raw kit files """ raw_py = kit.read_raw_kit(input_fname=op.join(data_dir, 'test.sqd'), mrk_fname=op.join(data_dir, 'test_mrk.sqd'), elp_fname=op.join(data_dir, 'test_elp.txt'), hsp_fname=op.join(data_dir, 'test_hsp.txt'), sns_fname=op.join(data_dir, 'sns.txt'), stim=range(167, 159, -1), stimthresh=1, preload=True) # Binary file only stores the sensor channels py_picks = pick_types(raw_py.info, exclude='bads') raw_bin = op.join(data_dir, 'test_bin.fif') raw_bin = Raw(raw_bin, preload=True) bin_picks = pick_types(raw_bin.info, stim=True, exclude='bads') data_bin, _ = raw_bin[bin_picks] data_py, _ = raw_py[py_picks] # this .mat was generated using the Yokogawa MEG Reader data_Ykgw = op.join(data_dir, 'test_Ykgw.mat') data_Ykgw = scipy.io.loadmat(data_Ykgw)['data'] data_Ykgw = data_Ykgw[py_picks] assert_array_almost_equal(data_py, data_Ykgw) py_picks = pick_types(raw_py.info, stim=True, exclude='bads') data_py, _ = raw_py[py_picks] assert_array_almost_equal(data_py, data_bin)
def test_compute_proj_epochs(): """Test SSP computation on epochs""" event_id, tmin, tmax = 1, -0.2, 0.3 raw = Raw(raw_fname, preload=True) events = read_events(event_fname) bad_ch = 'MEG 2443' picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, exclude=[]) epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=None, proj=False) evoked = epochs.average() projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1) write_proj(op.join(tempdir, 'proj.fif.gz'), projs) for p_fname in [proj_fname, proj_gz_fname, op.join(tempdir, 'proj.fif.gz')]: projs2 = read_proj(p_fname) assert_true(len(projs) == len(projs2)) for p1, p2 in zip(projs, projs2): assert_true(p1['desc'] == p2['desc']) assert_true(p1['data']['col_names'] == p2['data']['col_names']) assert_true(p1['active'] == p2['active']) # compare with sign invariance p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0]) p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0]) if bad_ch in p1['data']['col_names']: bad = p1['data']['col_names'].index('MEG 2443') mask = np.ones(p1_data.size, dtype=np.bool) mask[bad] = False p1_data = p1_data[:, mask] p2_data = p2_data[:, mask] corr = np.corrcoef(p1_data, p2_data)[0, 1] assert_array_almost_equal(corr, 1.0, 5) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them epochs.info['projs'] += projs evoked = epochs.average() evoked.save(op.join(tempdir, 'foo.fif')) projs = read_proj(proj_fname) projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0) assert_true(len(projs_evoked) == 2) # XXX : test something # test parallelization projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=2) projs = activate_proj(projs) proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[]) assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)
def _get_data(): # Read raw data raw = Raw(raw_fname) raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set picks picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False, exclude='bads') # Read several epochs event_id, tmin, tmax = 1, -0.2, 0.5 events = mne.read_events(event_fname)[0:100] epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12)) # Create an epochs object with one epoch and one channel of artificial data event_id, tmin, tmax = 1, 0.0, 1.0 epochs_sin = mne.Epochs(raw, events[0:5], event_id, tmin, tmax, proj=True, picks=[0], baseline=(None, 0), preload=True, reject=dict(grad=4000e-13)) freq = 10 epochs_sin._data = np.sin(2 * np.pi * freq * epochs_sin.times)[None, None, :] return epochs, epochs_sin
def test_ch_loc(): """Test raw kit loc """ raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<') raw_bin = Raw(op.join(data_dir, 'test_bin.fif')) ch_py = raw_py._sqd_params['sensor_locs'][:, :5] # ch locs stored as m, not mm ch_py[:, :3] *= 1e3 ch_sns = read_sns(op.join(data_dir, 'sns.txt')) assert_array_almost_equal(ch_py, ch_sns, 2) assert_array_almost_equal(raw_py.info['dev_head_t']['trans'], raw_bin.info['dev_head_t']['trans'], 4) for py_ch, bin_ch in zip(raw_py.info['chs'], raw_bin.info['chs']): if bin_ch['ch_name'].startswith('MEG'): # the stored ch locs have more precision than the sns.txt assert_array_almost_equal(py_ch['loc'], bin_ch['loc'], decimal=2) assert_array_almost_equal(py_ch['coil_trans'], bin_ch['coil_trans'], decimal=2) # test when more than one marker file provided mrks = [mrk_path, mrk2_path, mrk3_path] _ = read_raw_kit(sqd_path, mrks, elp_path, hsp_path, preload=False)
def runICA(subjectID): jumpAmplitudes = dict(grad=400e-12, mag=6e-12) subject = 'dh{:#02d}a'.format(subjectID) subjectPath = data_path + '/MEG_mc_hp004/' + subject + '/block' for block in ['1', '2']: outfilename = subjectPath + block + '_ica.fif' raw_fname = subjectPath + block + '.fif' if os.path.exists(raw_fname): raw = Raw(raw_fname, preload=True) raw.info['bads'] = badChanLibrary[subjectID][int(block)] MEG_channels = mne.fiff.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False) ica = ICA(n_components=0.99, n_pca_components=64, max_pca_components=100, noise_cov=None, random_state=17259) # decompose sources for raw data ica.fit(raw, picks=MEG_channels, reject=jumpAmplitudes, tstep=1.0) # Save ICA results for diagnosis and reconstruction ica.save(outfilename) else: print(raw_fname + ' does not exist. Skipping ICA.')
def test_compute_proj_raw(): """Test SSP computation on raw""" # Test that the raw projectors work raw_time = 2.5 # Do shorter amount for speed raw = Raw(raw_fname, preload=True).crop(0, raw_time, False) for ii in (0.25, 0.5, 1, 2): with warnings.catch_warnings(True) as w: projs = compute_proj_raw(raw, duration=ii - 0.1, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) assert_true(len(w) == 1) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them raw.info['projs'] += projs raw.save(op.join(tempdir, 'foo_%d_raw.fif' % ii), overwrite=True) # Test that purely continuous (no duration) raw projection works with warnings.catch_warnings(True) as w: projs = compute_proj_raw(raw, duration=None, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) assert_true(len(w) == 1) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them raw.info['projs'] += projs raw.save(op.join(tempdir, 'foo_rawproj_continuous_raw.fif')) # test resampled-data projector, upsampling instead of downsampling # here to save an extra filtering (raw would have to be LP'ed to be equiv) raw_resamp = cp.deepcopy(raw) raw_resamp.resample(raw.info['sfreq'] * 2, n_jobs=2) with warnings.catch_warnings(True) as w: projs = compute_proj_raw(raw_resamp, duration=None, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) projs = activate_proj(projs) proj_new, _, _ = make_projector(projs, raw.ch_names, bads=[]) assert_array_almost_equal(proj_new, proj, 4) # test with bads raw.load_bad_channels(bads_fname) # adds 2 bad mag channels with warnings.catch_warnings(True) as w: projs = compute_proj_raw(raw, n_grad=0, n_mag=0, n_eeg=1) # test that bad channels can be excluded proj, nproj, U = make_projector(projs, raw.ch_names, bads=raw.ch_names) assert_array_almost_equal(proj, np.eye(len(raw.ch_names)))
def compensate_mne(fname, grad): tmp_fname = op.join(tempdir, 'mne_ctf_test_raw.fif') cmd = [ 'mne_process_raw', '--raw', fname, '--save', tmp_fname, '--grad', str(grad), '--projoff', '--filteroff' ] run_subprocess(cmd) return Raw(tmp_fname, preload=True)
def test_find_ecg(): """Test find ECG peaks""" raw = Raw(raw_fname) events, ch_ECG, average_pulse = find_ecg_events(raw, event_id=999, ch_name='MEG 1531') n_events = len(events) _, times = raw[0, :] assert_true(55 < average_pulse < 60)
def test_compensation(): """Test compensation """ raw = Raw(ctf_comp_fname, compensation=None) comp1 = make_compensator(raw.info, 3, 1, exclude_comp_chs=False) assert_true(comp1.shape == (340, 340)) comp2 = make_compensator(raw.info, 3, 1, exclude_comp_chs=True) assert_true(comp2.shape == (311, 340))