def test_io_inverse_operator(): """Test IO of inverse_operator """ tempdir = _TempDir() inverse_operator = read_inverse_operator(fname_inv) x = repr(inverse_operator) assert_true(x) assert_true(isinstance(inverse_operator['noise_cov'], Covariance)) # just do one example for .gz, as it should generalize _compare_io(inverse_operator, '.gz') # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') inv_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_inverse_operator(inv_badname, inverse_operator) read_inverse_operator(inv_badname) assert_naming(w, 'test_inverse.py', 2) # make sure we can write and read inv_fname = op.join(tempdir, 'test-inv.fif') args = (10, 1. / 9., 'dSPM') inv_prep = prepare_inverse_operator(inverse_operator, *args) write_inverse_operator(inv_fname, inv_prep) inv_read = read_inverse_operator(inv_fname) _compare(inverse_operator, inv_read) inv_read_prep = prepare_inverse_operator(inv_read, *args) _compare(inv_prep, inv_read_prep) inv_prep_prep = prepare_inverse_operator(inv_prep, *args) _compare(inv_prep, inv_prep_prep)
def test_io_events(): """Test IO for events """ tempdir = _TempDir() # Test binary fif IO events = read_events(fname) # Use as the gold standard write_events(op.join(tempdir, 'events-eve.fif'), events) events2 = read_events(op.join(tempdir, 'events-eve.fif')) assert_array_almost_equal(events, events2) # Test binary fif.gz IO events2 = read_events(fname_gz) # Use as the gold standard assert_array_almost_equal(events, events2) write_events(op.join(tempdir, 'events-eve.fif.gz'), events2) events2 = read_events(op.join(tempdir, 'events-eve.fif.gz')) assert_array_almost_equal(events, events2) # Test new format text file IO write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) events2 = read_events(fname_txt_mpr) assert_array_almost_equal(events, events2) # Test old format text file IO events2 = read_events(fname_old_txt) assert_array_almost_equal(events, events2) write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) # Test event selection a = read_events(op.join(tempdir, 'events-eve.fif'), include=1) b = read_events(op.join(tempdir, 'events-eve.fif'), include=[1]) c = read_events(op.join(tempdir, 'events-eve.fif'), exclude=[2, 3, 4, 5, 32]) d = read_events(op.join(tempdir, 'events-eve.fif'), include=1, exclude=[2, 3]) assert_array_equal(a, b) assert_array_equal(a, c) assert_array_equal(a, d) # Test binary file IO for 1 event events = read_events(fname_1) # Use as the new gold standard write_events(op.join(tempdir, 'events-eve.fif'), events) events2 = read_events(op.join(tempdir, 'events-eve.fif')) assert_array_almost_equal(events, events2) # Test text file IO for 1 event write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fname2 = op.join(tempdir, 'test-bad-name.fif') write_events(fname2, events) read_events(fname2) assert_naming(w, 'test_event.py', 2)
def test_io_trans(): """Test reading and writing of trans files """ tempdir = _TempDir() os.mkdir(op.join(tempdir, 'sample')) assert_raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir) trans0 = read_trans(fname) fname1 = op.join(tempdir, 'sample', 'test-trans.fif') write_trans(fname1, trans0) assert_true(fname1 == _find_trans('sample', subjects_dir=tempdir)) trans1 = read_trans(fname1) # check all properties assert_true(trans0['from'] == trans1['from']) assert_true(trans0['to'] == trans1['to']) assert_array_equal(trans0['trans'], trans1['trans']) # check reading non -trans.fif files assert_raises(IOError, read_trans, fname_eve) # check warning on bad filenames with warnings.catch_warnings(record=True) as w: fname2 = op.join(tempdir, 'trans-test-bad-name.fif') write_trans(fname2, trans0) assert_naming(w, 'test_transforms.py', 1)
def test_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args""" tempdir = _TempDir() ave = read_evokeds(fname, 0) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave) ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0] # This not being assert_array_equal due to windows rounding assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first) assert_true(repr(ave)) # test compressed i/o ave2 = read_evokeds(fname_gz, 0) assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8)) # test str access condition = 'Left Auditory' assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr') assert_raises(ValueError, read_evokeds, fname, condition, kind='standard_error') ave3 = read_evokeds(fname, condition) assert_array_almost_equal(ave.data, ave3.data, 19) # test read_evokeds and write_evokeds aves1 = read_evokeds(fname)[1::2] aves2 = read_evokeds(fname, [1, 3]) aves3 = read_evokeds(fname, ['Right Auditory', 'Right visual']) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1) aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.fif')) for aves in [aves2, aves3, aves4]: for [av1, av2] in zip(aves1, aves): assert_array_almost_equal(av1.data, av2.data) assert_array_almost_equal(av1.times, av2.times) assert_equal(av1.nave, av2.nave) assert_equal(av1.kind, av2.kind) assert_equal(av1._aspect_kind, av2._aspect_kind) assert_equal(av1.last, av2.last) assert_equal(av1.first, av2.first) assert_equal(av1.comment, av2.comment) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fname2 = op.join(tempdir, 'test-bad-name.fif') write_evokeds(fname2, ave) read_evokeds(fname2) assert_naming(w, 'test_evoked.py', 2) # constructor assert_raises(TypeError, Evoked, fname)
def test_io_trans(): """Test reading and writing of trans files """ tempdir = _TempDir() os.mkdir(op.join(tempdir, 'sample')) assert_raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir) trans0 = read_trans(fname) fname1 = op.join(tempdir, 'sample', 'test-trans.fif') trans0.save(fname1) assert_true(fname1 == _find_trans('sample', subjects_dir=tempdir)) trans1 = read_trans(fname1) # check all properties assert_true(trans0['from'] == trans1['from']) assert_true(trans0['to'] == trans1['to']) assert_array_equal(trans0['trans'], trans1['trans']) # check reading non -trans.fif files assert_raises(IOError, read_trans, fname_eve) # check warning on bad filenames with warnings.catch_warnings(record=True) as w: fname2 = op.join(tempdir, 'trans-test-bad-name.fif') write_trans(fname2, trans0) assert_naming(w, 'test_transforms.py', 1)
def test_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args """ tempdir = _TempDir() ave = read_evokeds(fname, 0) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave) ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0] # This not being assert_array_equal due to windows rounding assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first) assert_true(repr(ave)) # test compressed i/o ave2 = read_evokeds(fname_gz, 0) assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8)) # test str access condition = 'Left Auditory' assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr') assert_raises(ValueError, read_evokeds, fname, condition, kind='standard_error') ave3 = read_evokeds(fname, condition) assert_array_almost_equal(ave.data, ave3.data, 19) # test read_evokeds and write_evokeds aves1 = read_evokeds(fname)[1::2] aves2 = read_evokeds(fname, [1, 3]) aves3 = read_evokeds(fname, ['Right Auditory', 'Right visual']) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1) aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.fif')) for aves in [aves2, aves3, aves4]: for [av1, av2] in zip(aves1, aves): assert_array_almost_equal(av1.data, av2.data) assert_array_almost_equal(av1.times, av2.times) assert_equal(av1.nave, av2.nave) assert_equal(av1.kind, av2.kind) assert_equal(av1._aspect_kind, av2._aspect_kind) assert_equal(av1.last, av2.last) assert_equal(av1.first, av2.first) assert_equal(av1.comment, av2.comment) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fname2 = op.join(tempdir, 'test-bad-name.fif') write_evokeds(fname2, ave) read_evokeds(fname2) assert_naming(w, 'test_evoked.py', 2) # constructor assert_raises(TypeError, Evoked, fname)
def test_write_source_space(): """Test reading and writing of source spaces.""" tempdir = _TempDir() src0 = read_source_spaces(fname, patch_stats=False) write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0) src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), patch_stats=False) _compare_source_spaces(src0, src1) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') src_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_source_spaces(src_badname, src0) read_source_spaces(src_badname) assert_naming(w, 'test_source_space.py', 2)
def test_io_forward(): """Test IO for forward solutions """ temp_dir = _TempDir() # do extensive tests with MEEG + grad n_channels, n_src = 366, 108 fwd = read_forward_solution(fname_meeg_grad) assert_true(isinstance(fwd, Forward)) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd['sol']['row_names']), n_channels) fname_temp = op.join(temp_dir, 'test-fwd.fif') write_forward_solution(fname_temp, fwd, overwrite=True) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) fwd_read = read_forward_solution(fname_temp, surf_ori=True) leadfield = fwd_read['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd_read['sol']['row_names']), n_channels) assert_equal(len(fwd_read['info']['chs']), n_channels) assert_true('dev_head_t' in fwd_read['info']) assert_true('mri_head_t' in fwd_read) assert_array_almost_equal(fwd['sol']['data'], fwd_read['sol']['data']) fwd = read_forward_solution(fname_meeg_grad, force_fixed=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src / 3)) assert_equal(len(fwd['sol']['row_names']), n_channels) assert_equal(len(fwd['info']['chs']), n_channels) assert_true('dev_head_t' in fwd['info']) assert_true('mri_head_t' in fwd) assert_true(fwd['surf_ori']) # test warnings on bad filenames fwd = read_forward_solution(fname_meeg_grad) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fwd_badname = op.join(temp_dir, 'test-bad-name.fif.gz') write_forward_solution(fwd_badname, fwd) read_forward_solution(fwd_badname) assert_naming(w, 'test_forward.py', 2) fwd = read_forward_solution(fname_meeg) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) compare_forwards(fwd, fwd_read)
def test_io_forward(): """Test IO for forward solutions """ temp_dir = _TempDir() # do extensive tests with MEEG + grad n_channels, n_src = 366, 108 fwd = read_forward_solution(fname_meeg_grad) assert_true(isinstance(fwd, Forward)) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) leadfield = fwd["sol"]["data"] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd["sol"]["row_names"]), n_channels) fname_temp = op.join(temp_dir, "test-fwd.fif") write_forward_solution(fname_temp, fwd, overwrite=True) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) fwd_read = read_forward_solution(fname_temp, surf_ori=True) leadfield = fwd_read["sol"]["data"] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd_read["sol"]["row_names"]), n_channels) assert_equal(len(fwd_read["info"]["chs"]), n_channels) assert_true("dev_head_t" in fwd_read["info"]) assert_true("mri_head_t" in fwd_read) assert_array_almost_equal(fwd["sol"]["data"], fwd_read["sol"]["data"]) fwd = read_forward_solution(fname_meeg_grad, force_fixed=True) leadfield = fwd["sol"]["data"] assert_equal(leadfield.shape, (n_channels, n_src / 3)) assert_equal(len(fwd["sol"]["row_names"]), n_channels) assert_equal(len(fwd["info"]["chs"]), n_channels) assert_true("dev_head_t" in fwd["info"]) assert_true("mri_head_t" in fwd) assert_true(fwd["surf_ori"]) # test warnings on bad filenames fwd = read_forward_solution(fname_meeg_grad) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") fwd_badname = op.join(temp_dir, "test-bad-name.fif.gz") write_forward_solution(fwd_badname, fwd) read_forward_solution(fwd_badname) assert_naming(w, "test_forward.py", 2) fwd = read_forward_solution(fname_meeg) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) compare_forwards(fwd, fwd_read)
def test_io_cov(): """Test IO for noise covariance matrices """ tempdir = _TempDir() cov = read_cov(cov_fname) cov['method'] = 'empirical' cov['loglik'] = -np.inf cov.save(op.join(tempdir, 'test-cov.fif')) cov2 = read_cov(op.join(tempdir, 'test-cov.fif')) assert_array_almost_equal(cov.data, cov2.data) assert_equal(cov['method'], cov2['method']) assert_equal(cov['loglik'], cov2['loglik']) assert_true('Covariance' in repr(cov)) cov2 = read_cov(cov_gz_fname) assert_array_almost_equal(cov.data, cov2.data) cov2.save(op.join(tempdir, 'test-cov.fif.gz')) cov2 = read_cov(op.join(tempdir, 'test-cov.fif.gz')) assert_array_almost_equal(cov.data, cov2.data) cov['bads'] = ['EEG 039'] cov_sel = pick_channels_cov(cov, exclude=cov['bads']) assert_true(cov_sel['dim'] == (len(cov['data']) - len(cov['bads']))) assert_true(cov_sel['data'].shape == (cov_sel['dim'], cov_sel['dim'])) cov_sel.save(op.join(tempdir, 'test-cov.fif')) cov2 = read_cov(cov_gz_fname) assert_array_almost_equal(cov.data, cov2.data) cov2.save(op.join(tempdir, 'test-cov.fif.gz')) cov2 = read_cov(op.join(tempdir, 'test-cov.fif.gz')) assert_array_almost_equal(cov.data, cov2.data) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') cov_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_cov(cov_badname, cov) read_cov(cov_badname) assert_naming(w, 'test_cov.py', 2)
def test_io_cov(): """Test IO for noise covariance matrices.""" tempdir = _TempDir() cov = read_cov(cov_fname) cov["method"] = "empirical" cov["loglik"] = -np.inf cov.save(op.join(tempdir, "test-cov.fif")) cov2 = read_cov(op.join(tempdir, "test-cov.fif")) assert_array_almost_equal(cov.data, cov2.data) assert_equal(cov["method"], cov2["method"]) assert_equal(cov["loglik"], cov2["loglik"]) assert_true("Covariance" in repr(cov)) cov2 = read_cov(cov_gz_fname) assert_array_almost_equal(cov.data, cov2.data) cov2.save(op.join(tempdir, "test-cov.fif.gz")) cov2 = read_cov(op.join(tempdir, "test-cov.fif.gz")) assert_array_almost_equal(cov.data, cov2.data) cov["bads"] = ["EEG 039"] cov_sel = pick_channels_cov(cov, exclude=cov["bads"]) assert_true(cov_sel["dim"] == (len(cov["data"]) - len(cov["bads"]))) assert_true(cov_sel["data"].shape == (cov_sel["dim"], cov_sel["dim"])) cov_sel.save(op.join(tempdir, "test-cov.fif")) cov2 = read_cov(cov_gz_fname) assert_array_almost_equal(cov.data, cov2.data) cov2.save(op.join(tempdir, "test-cov.fif.gz")) cov2 = read_cov(op.join(tempdir, "test-cov.fif.gz")) assert_array_almost_equal(cov.data, cov2.data) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") cov_badname = op.join(tempdir, "test-bad-name.fif.gz") write_cov(cov_badname, cov) read_cov(cov_badname) assert_naming(w, "test_cov.py", 2)
def test_io_raw(): """Test IO for raw data (Neuromag + CTF + gz) """ tempdir = _TempDir() # test unicode io for chars in [b'\xc3\xa4\xc3\xb6\xc3\xa9', b'a']: with Raw(fif_fname) as r: assert_true('Raw' in repr(r)) assert_true(op.basename(fif_fname) in repr(r)) desc1 = r.info['description'] = chars.decode('utf-8') temp_file = op.join(tempdir, 'raw.fif') r.save(temp_file, overwrite=True) with Raw(temp_file) as r2: desc2 = r2.info['description'] assert_equal(desc1, desc2) # Let's construct a simple test for IO first raw = Raw(fif_fname).crop(0, 3.5) raw.load_data() # put in some data that we know the values of data = rng.randn(raw._data.shape[0], raw._data.shape[1]) raw._data[:, :] = data # save it somewhere fname = op.join(tempdir, 'test_copy_raw.fif') raw.save(fname, buffer_size_sec=1.0) # read it in, make sure the whole thing matches raw = Raw(fname) assert_allclose(data, raw[:, :][0], rtol=1e-6, atol=1e-20) # let's read portions across the 1-sec tag boundary, too inds = raw.time_as_index([1.75, 2.25]) sl = slice(inds[0], inds[1]) assert_allclose(data[:, sl], raw[:, sl][0], rtol=1e-6, atol=1e-20) # now let's do some real I/O fnames_in = [fif_fname, test_fif_gz_fname, ctf_fname] fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif'] for fname_in, fname_out in zip(fnames_in, fnames_out): fname_out = op.join(tempdir, fname_out) raw = Raw(fname_in) nchan = raw.info['nchan'] ch_names = raw.info['ch_names'] meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == 'M'] n_channels = 100 meg_channels_idx = meg_channels_idx[:n_channels] start, stop = raw.time_as_index([0, 5]) data, times = raw[meg_channels_idx, start:(stop + 1)] meg_ch_names = [ch_names[k] for k in meg_channels_idx] # Set up pick list: MEG + STI 014 - bad channels include = ['STI 014'] include += meg_ch_names picks = pick_types(raw.info, meg=True, eeg=False, stim=True, misc=True, ref_meg=True, include=include, exclude='bads') # Writing with drop_small_buffer True raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True, overwrite=True) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(times2.max() <= 3) # Writing raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_equal(len(raw.info['dig']), 146) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_allclose(data, data2, rtol=1e-6, atol=1e-20) assert_allclose(times, times2) assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5) # check transformations for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']: if raw.info[trans] is None: assert_true(raw2.info[trans] is None) else: assert_array_equal(raw.info[trans]['trans'], raw2.info[trans]['trans']) # check transformation 'from' and 'to' if trans.startswith('dev'): from_id = FIFF.FIFFV_COORD_DEVICE else: from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD if trans[4:8] == 'head': to_id = FIFF.FIFFV_COORD_HEAD else: to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD for raw_ in [raw, raw2]: assert_equal(raw_.info[trans]['from'], from_id) assert_equal(raw_.info[trans]['to'], to_id) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r']) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") raw_badname = op.join(tempdir, 'test-bad-name.fif.gz') raw.save(raw_badname) Raw(raw_badname) assert_naming(w, 'test_raw_fiff.py', 2)
def test_io_events(): """Test IO for events.""" tempdir = _TempDir() # Test binary fif IO events = read_events(fname) # Use as the gold standard write_events(op.join(tempdir, 'events-eve.fif'), events) events2 = read_events(op.join(tempdir, 'events-eve.fif')) assert_array_almost_equal(events, events2) # Test binary fif.gz IO events2 = read_events(fname_gz) # Use as the gold standard assert_array_almost_equal(events, events2) write_events(op.join(tempdir, 'events-eve.fif.gz'), events2) events2 = read_events(op.join(tempdir, 'events-eve.fif.gz')) assert_array_almost_equal(events, events2) # Test new format text file IO write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') events2 = read_events(fname_txt_mpr, mask=0, mask_type='not_and') assert_true(sum('first row of' in str(ww.message) for ww in w) == 1) assert_array_almost_equal(events, events2) # Test old format text file IO events2 = read_events(fname_old_txt) assert_array_almost_equal(events, events2) write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) # Test event selection a = read_events(op.join(tempdir, 'events-eve.fif'), include=1) b = read_events(op.join(tempdir, 'events-eve.fif'), include=[1]) c = read_events(op.join(tempdir, 'events-eve.fif'), exclude=[2, 3, 4, 5, 32]) d = read_events(op.join(tempdir, 'events-eve.fif'), include=1, exclude=[2, 3]) assert_array_equal(a, b) assert_array_equal(a, c) assert_array_equal(a, d) # test reading file with mask=None events2 = events.copy() events2[:, -1] = range(events2.shape[0]) write_events(op.join(tempdir, 'events-eve.fif'), events2) events3 = read_events(op.join(tempdir, 'events-eve.fif'), mask=None) assert_array_almost_equal(events2, events3) # Test binary file IO for 1 event events = read_events(fname_1) # Use as the new gold standard write_events(op.join(tempdir, 'events-eve.fif'), events) events2 = read_events(op.join(tempdir, 'events-eve.fif')) assert_array_almost_equal(events, events2) # Test text file IO for 1 event write_events(op.join(tempdir, 'events.eve'), events) events2 = read_events(op.join(tempdir, 'events.eve')) assert_array_almost_equal(events, events2) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fname2 = op.join(tempdir, 'test-bad-name.fif') write_events(fname2, events) read_events(fname2) assert_naming(w, 'test_event.py', 2)
def test_ica_additional(method): """Test additional ICA functionality.""" _skip_check_picard(method) import matplotlib.pyplot as plt tempdir = _TempDir() stop2 = 500 raw = read_raw_fif(raw_fname).crop(1.5, stop).load_data() raw.annotations = Annotations([0.5], [0.5], ['BAD']) # XXX This breaks the tests :( # raw.info['bads'] = [raw.ch_names[1]] test_cov = read_cov(test_cov_name) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') epochs = Epochs(raw, events, None, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs.decimate(3, verbose='error') assert len(epochs) == 4 # test if n_components=None works ica = ICA(n_components=None, max_pca_components=None, n_pca_components=None, random_state=0, method=method, max_iter=1) with warnings.catch_warnings(record=True): ica.fit(epochs) # for testing eog functionality picks2 = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=True, exclude='bads') epochs_eog = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks2, baseline=(None, 0), preload=True) test_cov2 = test_cov.copy() ica = ICA(noise_cov=test_cov2, n_components=3, max_pca_components=4, n_pca_components=4, method=method) assert_true(ica.info is None) with warnings.catch_warnings(record=True): ica.fit(raw, picks[:5]) assert_true(isinstance(ica.info, Info)) assert_true(ica.n_components_ < 5) ica = ICA(n_components=3, max_pca_components=4, method=method, n_pca_components=4, random_state=0) assert_raises(RuntimeError, ica.save, '') with warnings.catch_warnings(record=True): ica.fit(raw, picks=[1, 2, 3, 4, 5], start=start, stop=stop2) # check passing a ch_name to find_bads_ecg with warnings.catch_warnings(record=True): # filter length _, scores_1 = ica.find_bads_ecg(raw) _, scores_2 = ica.find_bads_ecg(raw, raw.ch_names[1]) assert_false(scores_1[0] == scores_2[0]) # test corrmap ica2 = ica.copy() ica3 = ica.copy() corrmap([ica, ica2], (0, 0), threshold='auto', label='blinks', plot=True, ch_type="mag") corrmap([ica, ica2], (0, 0), threshold=2, plot=False, show=False) assert_true(ica.labels_["blinks"] == ica2.labels_["blinks"]) assert_true(0 in ica.labels_["blinks"]) # test retrieval of component maps as arrays components = ica.get_components() template = components[:, 0] EvokedArray(components, ica.info, tmin=0.).plot_topomap([0], time_unit='s') corrmap([ica, ica3], template, threshold='auto', label='blinks', plot=True, ch_type="mag") assert_true(ica2.labels_["blinks"] == ica3.labels_["blinks"]) plt.close('all') # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ica_badname = op.join(op.dirname(tempdir), 'test-bad-name.fif.gz') ica.save(ica_badname) read_ica(ica_badname) assert_naming(w, 'test_ica.py', 2) # test decim ica = ICA(n_components=3, max_pca_components=4, n_pca_components=4, method=method, max_iter=1) raw_ = raw.copy() for _ in range(3): raw_.append(raw_) n_samples = raw_._data.shape[1] with warnings.catch_warnings(record=True): ica.fit(raw, picks=None, decim=3) assert_true(raw_._data.shape[1], n_samples) # test expl var ica = ICA(n_components=1.0, max_pca_components=4, n_pca_components=4, method=method, max_iter=1) with warnings.catch_warnings(record=True): ica.fit(raw, picks=None, decim=3) assert_true(ica.n_components_ == 4) ica_var = _ica_explained_variance(ica, raw, normalize=True) assert_true(np.all(ica_var[:-1] >= ica_var[1:])) # test ica sorting ica.exclude = [0] ica.labels_ = dict(blink=[0], think=[1]) ica_sorted = _sort_components(ica, [3, 2, 1, 0], copy=True) assert_equal(ica_sorted.exclude, [3]) assert_equal(ica_sorted.labels_, dict(blink=[3], think=[2])) # epochs extraction from raw fit assert_raises(RuntimeError, ica.get_sources, epochs) # test reading and writing test_ica_fname = op.join(op.dirname(tempdir), 'test-ica.fif') for cov in (None, test_cov): ica = ICA(noise_cov=cov, n_components=2, max_pca_components=4, n_pca_components=4, method=method, max_iter=1) with warnings.catch_warnings(record=True): # ICA does not converge ica.fit(raw, picks=picks, start=start, stop=stop2) sources = ica.get_sources(epochs).get_data() assert_true(ica.mixing_matrix_.shape == (2, 2)) assert_true(ica.unmixing_matrix_.shape == (2, 2)) assert_true(ica.pca_components_.shape == (4, len(picks))) assert_true(sources.shape[1] == ica.n_components_) for exclude in [[], [0]]: ica.exclude = exclude ica.labels_ = {'foo': [0]} ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) assert_true(ica.exclude == ica_read.exclude) assert_equal(ica.labels_, ica_read.labels_) ica.exclude = [] ica.apply(raw, exclude=[1]) assert_true(ica.exclude == []) ica.exclude = [0, 1] ica.apply(raw, exclude=[1]) assert_true(ica.exclude == [0, 1]) ica_raw = ica.get_sources(raw) assert_true( ica.exclude == [ica_raw.ch_names.index(e) for e in ica_raw.info['bads']]) # test filtering d1 = ica_raw._data[0].copy() ica_raw.filter(4, 20, fir_design='firwin2') assert_equal(ica_raw.info['lowpass'], 20.) assert_equal(ica_raw.info['highpass'], 4.) assert_true((d1 != ica_raw._data[0]).any()) d1 = ica_raw._data[0].copy() ica_raw.notch_filter([10], trans_bandwidth=10, fir_design='firwin') assert_true((d1 != ica_raw._data[0]).any()) ica.n_pca_components = 2 ica.method = 'fake' ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) assert_true(ica.n_pca_components == ica_read.n_pca_components) assert_equal(ica.method, ica_read.method) assert_equal(ica.labels_, ica_read.labels_) # check type consistency attrs = ('mixing_matrix_ unmixing_matrix_ pca_components_ ' 'pca_explained_variance_ pre_whitener_') def f(x, y): return getattr(x, y).dtype for attr in attrs.split(): assert_equal(f(ica_read, attr), f(ica, attr)) ica.n_pca_components = 4 ica_read.n_pca_components = 4 ica.exclude = [] ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) for attr in [ 'mixing_matrix_', 'unmixing_matrix_', 'pca_components_', 'pca_mean_', 'pca_explained_variance_', 'pre_whitener_' ]: assert_array_almost_equal(getattr(ica, attr), getattr(ica_read, attr)) assert_true(ica.ch_names == ica_read.ch_names) assert_true(isinstance(ica_read.info, Info)) sources = ica.get_sources(raw)[:, :][0] sources2 = ica_read.get_sources(raw)[:, :][0] assert_array_almost_equal(sources, sources2) _raw1 = ica.apply(raw, exclude=[1]) _raw2 = ica_read.apply(raw, exclude=[1]) assert_array_almost_equal(_raw1[:, :][0], _raw2[:, :][0]) os.remove(test_ica_fname) # check score funcs for name, func in get_score_funcs().items(): if name in score_funcs_unsuited: continue scores = ica.score_sources(raw, target='EOG 061', score_func=func, start=0, stop=10) assert_true(ica.n_components_ == len(scores)) # check univariate stats scores = ica.score_sources(raw, score_func=stats.skew) # check exception handling assert_raises(ValueError, ica.score_sources, raw, target=np.arange(1)) params = [] params += [(None, -1, slice(2), [0, 1])] # variance, kurtosis params params += [(None, 'MEG 1531')] # ECG / EOG channel params for idx, ch_name in product(*params): ica.detect_artifacts(raw, start_find=0, stop_find=50, ecg_ch=ch_name, eog_ch=ch_name, skew_criterion=idx, var_criterion=idx, kurt_criterion=idx) evoked = epochs.average() evoked_data = evoked.data.copy() raw_data = raw[:][0].copy() epochs_data = epochs.get_data().copy() with warnings.catch_warnings(record=True): idx, scores = ica.find_bads_ecg(raw, method='ctps') assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_ecg(raw, method='correlation') assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_eog(raw) assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_ecg(epochs, method='ctps') assert_equal(len(scores), ica.n_components_) assert_raises(ValueError, ica.find_bads_ecg, epochs.average(), method='ctps') assert_raises(ValueError, ica.find_bads_ecg, raw, method='crazy-coupling') idx, scores = ica.find_bads_eog(raw) assert_equal(len(scores), ica.n_components_) raw.info['chs'][raw.ch_names.index('EOG 061') - 1]['kind'] = 202 idx, scores = ica.find_bads_eog(raw) assert_true(isinstance(scores, list)) assert_equal(len(scores[0]), ica.n_components_) idx, scores = ica.find_bads_eog(evoked, ch_name='MEG 1441') assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_ecg(evoked, method='correlation') assert_equal(len(scores), ica.n_components_) assert_array_equal(raw_data, raw[:][0]) assert_array_equal(epochs_data, epochs.get_data()) assert_array_equal(evoked_data, evoked.data) # check score funcs for name, func in get_score_funcs().items(): if name in score_funcs_unsuited: continue scores = ica.score_sources(epochs_eog, target='EOG 061', score_func=func) assert_true(ica.n_components_ == len(scores)) # check univariate stats scores = ica.score_sources(epochs, score_func=stats.skew) # check exception handling assert_raises(ValueError, ica.score_sources, epochs, target=np.arange(1)) # ecg functionality ecg_scores = ica.score_sources(raw, target='MEG 1531', score_func='pearsonr') with warnings.catch_warnings(record=True): # filter attenuation warning ecg_events = ica_find_ecg_events(raw, sources[np.abs(ecg_scores).argmax()]) assert_true(ecg_events.ndim == 2) # eog functionality eog_scores = ica.score_sources(raw, target='EOG 061', score_func='pearsonr') with warnings.catch_warnings(record=True): # filter attenuation warning eog_events = ica_find_eog_events(raw, sources[np.abs(eog_scores).argmax()]) assert_true(eog_events.ndim == 2) # Test ica fiff export ica_raw = ica.get_sources(raw, start=0, stop=100) assert_true(ica_raw.last_samp - ica_raw.first_samp == 100) assert_equal(len(ica_raw._filenames), 1) # API consistency ica_chans = [ch for ch in ica_raw.ch_names if 'ICA' in ch] assert_true(ica.n_components_ == len(ica_chans)) test_ica_fname = op.join(op.abspath(op.curdir), 'test-ica_raw.fif') ica.n_components = np.int32(ica.n_components) ica_raw.save(test_ica_fname, overwrite=True) ica_raw2 = read_raw_fif(test_ica_fname, preload=True) assert_allclose(ica_raw._data, ica_raw2._data, rtol=1e-5, atol=1e-4) ica_raw2.close() os.remove(test_ica_fname) # Test ica epochs export ica_epochs = ica.get_sources(epochs) assert_true(ica_epochs.events.shape == epochs.events.shape) ica_chans = [ch for ch in ica_epochs.ch_names if 'ICA' in ch] assert_true(ica.n_components_ == len(ica_chans)) assert_true(ica.n_components_ == ica_epochs.get_data().shape[1]) assert_true(ica_epochs._raw is None) assert_true(ica_epochs.preload is True) # test float n pca components ica.pca_explained_variance_ = np.array([0.2] * 5) ica.n_components_ = 0 for ncomps, expected in [[0.3, 1], [0.9, 4], [1, 1]]: ncomps_ = ica._check_n_pca_components(ncomps) assert_true(ncomps_ == expected) ica = ICA(method=method) with warnings.catch_warnings(record=True) as w: # convergence and filter ica.fit(raw, picks=picks[:5]) ica.find_bads_ecg(raw) ica.find_bads_eog(epochs, ch_name='MEG 0121') assert_array_equal(raw_data, raw[:][0]) raw.drop_channels(['MEG 0122']) with warnings.catch_warnings(record=True): # filter length assert_raises(RuntimeError, ica.find_bads_eog, raw) assert_raises(RuntimeError, ica.find_bads_ecg, raw)
def test_compute_proj_epochs(): """Test SSP computation on epochs""" tempdir = _TempDir() 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, 'test-proj.fif.gz'), projs) for p_fname in [proj_fname, proj_gz_fname, op.join(tempdir, 'test-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) if p2['explained_var']: assert_array_almost_equal(p1['explained_var'], p2['explained_var']) # 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-ave.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, desc_prefix='foobar') assert_true(all('foobar' in x['desc'] for x in projs)) projs = activate_proj(projs) proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[]) assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16) # test warnings on bad filenames clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') proj_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_proj(proj_badname, projs) read_proj(proj_badname) assert_naming(w, 'test_proj.py', 2)
def test_ica_additional(): """Test additional ICA functionality""" tempdir = _TempDir() stop2 = 500 raw = Raw(raw_fname).crop(1.5, stop, False) raw.load_data() picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') test_cov = read_cov(test_cov_name) events = read_events(event_name) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) # test if n_components=None works with warnings.catch_warnings(record=True): ica = ICA(n_components=None, max_pca_components=None, n_pca_components=None, random_state=0) ica.fit(epochs, picks=picks, decim=3) # for testing eog functionality picks2 = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=True, exclude='bads') epochs_eog = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks2, baseline=(None, 0), preload=True) test_cov2 = test_cov.copy() ica = ICA(noise_cov=test_cov2, n_components=3, max_pca_components=4, n_pca_components=4) assert_true(ica.info is None) with warnings.catch_warnings(record=True): ica.fit(raw, picks[:5]) assert_true(isinstance(ica.info, Info)) assert_true(ica.n_components_ < 5) ica = ICA(n_components=3, max_pca_components=4, n_pca_components=4) assert_raises(RuntimeError, ica.save, '') with warnings.catch_warnings(record=True): ica.fit(raw, picks=[1, 2, 3, 4, 5], start=start, stop=stop2) # test corrmap ica2 = ica.copy() corrmap([ica, ica2], (0, 0), threshold='auto', label='blinks', plot=True, ch_type="mag") corrmap([ica, ica2], (0, 0), threshold=2, plot=False, show=False) assert_true(ica.labels_["blinks"] == ica2.labels_["blinks"]) assert_true(0 in ica.labels_["blinks"]) plt.close('all') # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ica_badname = op.join(op.dirname(tempdir), 'test-bad-name.fif.gz') ica.save(ica_badname) read_ica(ica_badname) assert_naming(w, 'test_ica.py', 2) # test decim ica = ICA(n_components=3, max_pca_components=4, n_pca_components=4) raw_ = raw.copy() for _ in range(3): raw_.append(raw_) n_samples = raw_._data.shape[1] with warnings.catch_warnings(record=True): ica.fit(raw, picks=None, decim=3) assert_true(raw_._data.shape[1], n_samples) # test expl var ica = ICA(n_components=1.0, max_pca_components=4, n_pca_components=4) with warnings.catch_warnings(record=True): ica.fit(raw, picks=None, decim=3) assert_true(ica.n_components_ == 4) # epochs extraction from raw fit assert_raises(RuntimeError, ica.get_sources, epochs) # test reading and writing test_ica_fname = op.join(op.dirname(tempdir), 'test-ica.fif') for cov in (None, test_cov): ica = ICA(noise_cov=cov, n_components=2, max_pca_components=4, n_pca_components=4) with warnings.catch_warnings(record=True): # ICA does not converge ica.fit(raw, picks=picks, start=start, stop=stop2) sources = ica.get_sources(epochs).get_data() assert_true(ica.mixing_matrix_.shape == (2, 2)) assert_true(ica.unmixing_matrix_.shape == (2, 2)) assert_true(ica.pca_components_.shape == (4, len(picks))) assert_true(sources.shape[1] == ica.n_components_) for exclude in [[], [0]]: ica.exclude = [0] ica.labels_ = {'foo': [0]} ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) assert_true(ica.exclude == ica_read.exclude) assert_equal(ica.labels_, ica_read.labels_) ica.exclude = [] ica.apply(raw, exclude=[1]) assert_true(ica.exclude == []) ica.exclude = [0, 1] ica.apply(raw, exclude=[1]) assert_true(ica.exclude == [0, 1]) ica_raw = ica.get_sources(raw) assert_true(ica.exclude == [ica_raw.ch_names.index(e) for e in ica_raw.info['bads']]) # test filtering d1 = ica_raw._data[0].copy() with warnings.catch_warnings(record=True): # dB warning ica_raw.filter(4, 20) assert_true((d1 != ica_raw._data[0]).any()) d1 = ica_raw._data[0].copy() with warnings.catch_warnings(record=True): # dB warning ica_raw.notch_filter([10]) assert_true((d1 != ica_raw._data[0]).any()) ica.n_pca_components = 2 ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) assert_true(ica.n_pca_components == ica_read.n_pca_components) # check type consistency attrs = ('mixing_matrix_ unmixing_matrix_ pca_components_ ' 'pca_explained_variance_ _pre_whitener') def f(x, y): return getattr(x, y).dtype for attr in attrs.split(): assert_equal(f(ica_read, attr), f(ica, attr)) ica.n_pca_components = 4 ica_read.n_pca_components = 4 ica.exclude = [] ica.save(test_ica_fname) ica_read = read_ica(test_ica_fname) for attr in ['mixing_matrix_', 'unmixing_matrix_', 'pca_components_', 'pca_mean_', 'pca_explained_variance_', '_pre_whitener']: assert_array_almost_equal(getattr(ica, attr), getattr(ica_read, attr)) assert_true(ica.ch_names == ica_read.ch_names) assert_true(isinstance(ica_read.info, Info)) sources = ica.get_sources(raw)[:, :][0] sources2 = ica_read.get_sources(raw)[:, :][0] assert_array_almost_equal(sources, sources2) _raw1 = ica.apply(raw, exclude=[1]) _raw2 = ica_read.apply(raw, exclude=[1]) assert_array_almost_equal(_raw1[:, :][0], _raw2[:, :][0]) os.remove(test_ica_fname) # check scrore funcs for name, func in get_score_funcs().items(): if name in score_funcs_unsuited: continue scores = ica.score_sources(raw, target='EOG 061', score_func=func, start=0, stop=10) assert_true(ica.n_components_ == len(scores)) # check univariate stats scores = ica.score_sources(raw, score_func=stats.skew) # check exception handling assert_raises(ValueError, ica.score_sources, raw, target=np.arange(1)) params = [] params += [(None, -1, slice(2), [0, 1])] # varicance, kurtosis idx params params += [(None, 'MEG 1531')] # ECG / EOG channel params for idx, ch_name in product(*params): ica.detect_artifacts(raw, start_find=0, stop_find=50, ecg_ch=ch_name, eog_ch=ch_name, skew_criterion=idx, var_criterion=idx, kurt_criterion=idx) with warnings.catch_warnings(record=True): idx, scores = ica.find_bads_ecg(raw, method='ctps') assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_ecg(raw, method='correlation') assert_equal(len(scores), ica.n_components_) idx, scores = ica.find_bads_ecg(epochs, method='ctps') assert_equal(len(scores), ica.n_components_) assert_raises(ValueError, ica.find_bads_ecg, epochs.average(), method='ctps') assert_raises(ValueError, ica.find_bads_ecg, raw, method='crazy-coupling') idx, scores = ica.find_bads_eog(raw) assert_equal(len(scores), ica.n_components_) raw.info['chs'][raw.ch_names.index('EOG 061') - 1]['kind'] = 202 idx, scores = ica.find_bads_eog(raw) assert_true(isinstance(scores, list)) assert_equal(len(scores[0]), ica.n_components_) # check score funcs for name, func in get_score_funcs().items(): if name in score_funcs_unsuited: continue scores = ica.score_sources(epochs_eog, target='EOG 061', score_func=func) assert_true(ica.n_components_ == len(scores)) # check univariate stats scores = ica.score_sources(epochs, score_func=stats.skew) # check exception handling assert_raises(ValueError, ica.score_sources, epochs, target=np.arange(1)) # ecg functionality ecg_scores = ica.score_sources(raw, target='MEG 1531', score_func='pearsonr') with warnings.catch_warnings(record=True): # filter attenuation warning ecg_events = ica_find_ecg_events(raw, sources[np.abs(ecg_scores).argmax()]) assert_true(ecg_events.ndim == 2) # eog functionality eog_scores = ica.score_sources(raw, target='EOG 061', score_func='pearsonr') with warnings.catch_warnings(record=True): # filter attenuation warning eog_events = ica_find_eog_events(raw, sources[np.abs(eog_scores).argmax()]) assert_true(eog_events.ndim == 2) # Test ica fiff export ica_raw = ica.get_sources(raw, start=0, stop=100) assert_true(ica_raw.last_samp - ica_raw.first_samp == 100) assert_true(len(ica_raw._filenames) == 0) # API consistency ica_chans = [ch for ch in ica_raw.ch_names if 'ICA' in ch] assert_true(ica.n_components_ == len(ica_chans)) test_ica_fname = op.join(op.abspath(op.curdir), 'test-ica_raw.fif') ica.n_components = np.int32(ica.n_components) ica_raw.save(test_ica_fname, overwrite=True) ica_raw2 = Raw(test_ica_fname, preload=True) assert_allclose(ica_raw._data, ica_raw2._data, rtol=1e-5, atol=1e-4) ica_raw2.close() os.remove(test_ica_fname) # Test ica epochs export ica_epochs = ica.get_sources(epochs) assert_true(ica_epochs.events.shape == epochs.events.shape) ica_chans = [ch for ch in ica_epochs.ch_names if 'ICA' in ch] assert_true(ica.n_components_ == len(ica_chans)) assert_true(ica.n_components_ == ica_epochs.get_data().shape[1]) assert_true(ica_epochs._raw is None) assert_true(ica_epochs.preload is True) # test float n pca components ica.pca_explained_variance_ = np.array([0.2] * 5) ica.n_components_ = 0 for ncomps, expected in [[0.3, 1], [0.9, 4], [1, 1]]: ncomps_ = ica._check_n_pca_components(ncomps) assert_true(ncomps_ == expected)
def test_io_raw(): """Test IO for raw data (Neuromag + CTF + gz) """ tempdir = _TempDir() # test unicode io for chars in [b'\xc3\xa4\xc3\xb6\xc3\xa9', b'a']: with Raw(fif_fname) as r: assert_true('Raw' in repr(r)) assert_true(op.basename(fif_fname) in repr(r)) desc1 = r.info['description'] = chars.decode('utf-8') temp_file = op.join(tempdir, 'raw.fif') r.save(temp_file, overwrite=True) with Raw(temp_file) as r2: desc2 = r2.info['description'] assert_equal(desc1, desc2) # Let's construct a simple test for IO first raw = Raw(fif_fname).crop(0, 3.5, False) raw.load_data() # put in some data that we know the values of data = rng.randn(raw._data.shape[0], raw._data.shape[1]) raw._data[:, :] = data # save it somewhere fname = op.join(tempdir, 'test_copy_raw.fif') raw.save(fname, buffer_size_sec=1.0) # read it in, make sure the whole thing matches raw = Raw(fname) assert_allclose(data, raw[:, :][0], rtol=1e-6, atol=1e-20) # let's read portions across the 1-sec tag boundary, too inds = raw.time_as_index([1.75, 2.25]) sl = slice(inds[0], inds[1]) assert_allclose(data[:, sl], raw[:, sl][0], rtol=1e-6, atol=1e-20) # now let's do some real I/O fnames_in = [fif_fname, test_fif_gz_fname, ctf_fname] fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif'] for fname_in, fname_out in zip(fnames_in, fnames_out): fname_out = op.join(tempdir, fname_out) raw = Raw(fname_in) nchan = raw.info['nchan'] ch_names = raw.info['ch_names'] meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == 'M'] n_channels = 100 meg_channels_idx = meg_channels_idx[:n_channels] start, stop = raw.time_as_index([0, 5]) data, times = raw[meg_channels_idx, start:(stop + 1)] meg_ch_names = [ch_names[k] for k in meg_channels_idx] # Set up pick list: MEG + STI 014 - bad channels include = ['STI 014'] include += meg_ch_names picks = pick_types(raw.info, meg=True, eeg=False, stim=True, misc=True, ref_meg=True, include=include, exclude='bads') # Writing with drop_small_buffer True raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True, overwrite=True) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_true(times2.max() <= 3) # Writing raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_equal(len(raw.info['dig']), 146) raw2 = Raw(fname_out) sel = pick_channels(raw2.ch_names, meg_ch_names) data2, times2 = raw2[sel, :] assert_allclose(data, data2, rtol=1e-6, atol=1e-20) assert_allclose(times, times2) assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5) # check transformations for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']: if raw.info[trans] is None: assert_true(raw2.info[trans] is None) else: assert_array_equal(raw.info[trans]['trans'], raw2.info[trans]['trans']) # check transformation 'from' and 'to' if trans.startswith('dev'): from_id = FIFF.FIFFV_COORD_DEVICE else: from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD if trans[4:8] == 'head': to_id = FIFF.FIFFV_COORD_HEAD else: to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD for raw_ in [raw, raw2]: assert_equal(raw_.info[trans]['from'], from_id) assert_equal(raw_.info[trans]['to'], to_id) if fname_in == fif_fname or fname_in == fif_fname + '.gz': assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r']) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") raw_badname = op.join(tempdir, 'test-bad-name.fif.gz') raw.save(raw_badname) Raw(raw_badname) assert_naming(w, 'test_raw_fiff.py', 2)
def test_io_forward(): """Test IO for forward solutions """ temp_dir = _TempDir() # do extensive tests with MEEG + grad n_channels, n_src = 366, 108 fwd = read_forward_solution(fname_meeg_grad) assert_true(isinstance(fwd, Forward)) fwd = read_forward_solution(fname_meeg_grad) fwd = convert_forward_solution(fwd, surf_ori=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd['sol']['row_names']), n_channels) fname_temp = op.join(temp_dir, 'test-fwd.fif') write_forward_solution(fname_temp, fwd, overwrite=True) fwd = read_forward_solution(fname_meeg_grad) fwd = convert_forward_solution(fwd, surf_ori=True) fwd_read = read_forward_solution(fname_temp) fwd_read = convert_forward_solution(fwd_read, surf_ori=True) leadfield = fwd_read['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd_read['sol']['row_names']), n_channels) assert_equal(len(fwd_read['info']['chs']), n_channels) assert_true('dev_head_t' in fwd_read['info']) assert_true('mri_head_t' in fwd_read) assert_array_almost_equal(fwd['sol']['data'], fwd_read['sol']['data']) fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=False) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) fwd_read = convert_forward_solution(fwd_read, surf_ori=True, force_fixed=True, use_cps=False) assert_true(repr(fwd_read)) assert_true(isinstance(fwd_read, Forward)) assert_true(is_fixed_orient(fwd_read)) compare_forwards(fwd, fwd_read) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, 1494 / 3)) assert_equal(len(fwd['sol']['row_names']), n_channels) assert_equal(len(fwd['info']['chs']), n_channels) assert_true('dev_head_t' in fwd['info']) assert_true('mri_head_t' in fwd) assert_true(fwd['surf_ori']) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) fwd_read = convert_forward_solution(fwd_read, surf_ori=True, force_fixed=True, use_cps=True) assert_true(repr(fwd_read)) assert_true(isinstance(fwd_read, Forward)) assert_true(is_fixed_orient(fwd_read)) compare_forwards(fwd, fwd_read) fwd = read_forward_solution(fname_meeg_grad) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src / 3)) assert_equal(len(fwd['sol']['row_names']), n_channels) assert_equal(len(fwd['info']['chs']), n_channels) assert_true('dev_head_t' in fwd['info']) assert_true('mri_head_t' in fwd) assert_true(fwd['surf_ori']) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) fwd_read = convert_forward_solution(fwd_read, surf_ori=True, force_fixed=True, use_cps=True) assert_true(repr(fwd_read)) assert_true(isinstance(fwd_read, Forward)) assert_true(is_fixed_orient(fwd_read)) compare_forwards(fwd, fwd_read) # test warnings on bad filenames fwd = read_forward_solution(fname_meeg_grad) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fwd_badname = op.join(temp_dir, 'test-bad-name.fif.gz') write_forward_solution(fwd_badname, fwd) read_forward_solution(fwd_badname) assert_naming(w, 'test_forward.py', 2) fwd = read_forward_solution(fname_meeg) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) compare_forwards(fwd, fwd_read)