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 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(record=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(record=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(record=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(record=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 test_compute_proj_raw(): """Test SSP computation on raw.""" tempdir = _TempDir() # Test that the raw projectors work raw_time = 2.5 # Do shorter amount for speed raw = read_raw_fif(raw_fname).crop(0, raw_time) raw.load_data() for ii in (0.25, 0.5, 1, 2): with pytest.warns(RuntimeWarning, match='Too few samples'): projs = compute_proj_raw(raw, duration=ii - 0.1, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert nproj == 2 assert 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 pytest.warns(RuntimeWarning, match='Too few samples'): projs = compute_proj_raw(raw, duration=None, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert nproj == 2 assert 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, npad='auto') 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 pytest.warns(RuntimeWarning, match='Too few samples'): 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 _prepare_beamformer_input(info, forward, label, picks, pick_ori): """Input preparation common for all beamformer functions. Check input values, prepare channel list and gain matrix. For documentation of parameters, please refer to _apply_lcmv. """ is_free_ori = forward['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI if pick_ori in ['normal', 'max-power'] and not is_free_ori: raise ValueError('Normal or max-power orientation can only be picked ' 'when a forward operator with free orientation is ' 'used.') if pick_ori == 'normal' and not forward['surf_ori']: # XXX eventually this could just call convert_forward_solution raise ValueError('Normal orientation can only be picked when a ' 'forward operator oriented in surface coordinates is ' 'used.') if pick_ori == 'normal' and not forward['src'][0]['type'] == 'surf': raise ValueError('Normal orientation can only be picked when a ' 'forward operator with a surface-based source space ' 'is used.') # Restrict forward solution to selected channels info_ch_names = [ch['ch_name'] for ch in info['chs']] ch_names = [info_ch_names[k] for k in picks] fwd_ch_names = forward['sol']['row_names'] # Keep channels in forward present in info: fwd_ch_names = [ch for ch in fwd_ch_names if ch in info_ch_names] # This line takes ~48 milliseconds on kernprof # forward = pick_channels_forward(forward, fwd_ch_names, verbose='ERROR') picks_forward = [fwd_ch_names.index(ch) for ch in ch_names] # Get gain matrix (forward operator) if label is not None: vertno, src_sel = label_src_vertno_sel(label, forward['src']) if is_free_ori: src_sel = 3 * src_sel src_sel = np.c_[src_sel, src_sel + 1, src_sel + 2] src_sel = src_sel.ravel() G = forward['sol']['data'][:, src_sel] else: vertno = _get_vertno(forward['src']) G = forward['sol']['data'] # Apply SSPs proj, ncomp, _ = make_projector(info['projs'], fwd_ch_names) if info['projs']: G = np.dot(proj, G) # Pick after applying the projections G = G[picks_forward] proj = proj[np.ix_(picks_forward, picks_forward)] return is_free_ori, ch_names, proj, vertno, G
def test_compute_proj_parallel(): """Test computation of ExG projectors using parallelization""" raw_0 = Raw(raw_fname).crop(0, 10, copy=False) raw_0.load_data() raw = raw_0.copy() projs, _ = compute_proj_eog(raw, n_mag=2, n_grad=2, n_eeg=2, bads=['MEG 2443'], average=False, avg_ref=True, no_proj=False, n_jobs=1, l_freq=None, h_freq=None, reject=None, tmax=dur_use, filter_length=6000) raw_2 = raw_0.copy() projs_2, _ = compute_proj_eog(raw_2, n_mag=2, n_grad=2, n_eeg=2, bads=['MEG 2443'], average=False, avg_ref=True, no_proj=False, n_jobs=2, l_freq=None, h_freq=None, reject=None, tmax=dur_use, filter_length=6000) projs = activate_proj(projs) projs_2 = activate_proj(projs_2) projs, _, _ = make_projector(projs, raw_2.info['ch_names'], bads=['MEG 2443']) projs_2, _, _ = make_projector(projs_2, raw_2.info['ch_names'], bads=['MEG 2443']) assert_array_almost_equal(projs, projs_2, 10)
def test_compute_proj_parallel(short_raw): """Test computation of ExG projectors using parallelization.""" short_raw = short_raw.copy().pick(('eeg', 'eog')).resample(100) raw = short_raw.copy() with pytest.warns(RuntimeWarning, match='Attenuation'): projs, _ = compute_proj_eog(raw, n_eeg=2, bads=raw.ch_names[1:2], average=False, avg_ref=True, no_proj=False, n_jobs=1, l_freq=None, h_freq=None, reject=None, tmax=dur_use, filter_length=100) raw_2 = short_raw.copy() with pytest.warns(RuntimeWarning, match='Attenuation'): projs_2, _ = compute_proj_eog(raw_2, n_eeg=2, bads=raw.ch_names[1:2], average=False, avg_ref=True, no_proj=False, n_jobs=2, l_freq=None, h_freq=None, reject=None, tmax=dur_use, filter_length=100) projs = activate_proj(projs) projs_2 = activate_proj(projs_2) projs, _, _ = make_projector(projs, raw_2.info['ch_names'], bads=['MEG 2443']) projs_2, _, _ = make_projector(projs_2, raw_2.info['ch_names'], bads=['MEG 2443']) assert_array_almost_equal(projs, projs_2, 10)
def test_compute_proj_parallel(): """Test computation of ExG projectors using parallelization""" raw_0 = Raw(raw_fname).crop(0, 10, copy=False) raw_0.load_data() raw = raw_0.copy() projs, _ = compute_proj_eog(raw, n_mag=2, n_grad=2, n_eeg=2, bads=['MEG 2443'], average=False, avg_ref=True, no_proj=False, n_jobs=1, l_freq=None, h_freq=None, reject=None, tmax=dur_use) raw_2 = raw_0.copy() projs_2, _ = compute_proj_eog(raw_2, n_mag=2, n_grad=2, n_eeg=2, bads=['MEG 2443'], average=False, avg_ref=True, no_proj=False, n_jobs=2, l_freq=None, h_freq=None, reject=None, tmax=dur_use) projs = activate_proj(projs) projs_2 = activate_proj(projs_2) projs, _, _ = make_projector(projs, raw_2.info['ch_names'], bads=['MEG 2443']) projs_2, _, _ = make_projector(projs_2, raw_2.info['ch_names'], bads=['MEG 2443']) assert_array_almost_equal(projs, projs_2, 10)
def test_inverse_residual(evoked): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) evoked = evoked.pick_types() inv = read_inverse_operator(fname_inv_fixed_depth) fwd = read_forward_solution(fname_fwd) pick_channels_forward(fwd, evoked.ch_names, copy=False) fwd = convert_forward_solution(fwd, force_fixed=True, surf_ori=True) matcher = re.compile(r'.* ([0-9]?[0-9]?[0-9]?\.[0-9])% variance.*') for method in ('MNE', 'dSPM', 'sLORETA'): with catch_logging() as log: stc, residual = apply_inverse(evoked, inv, method=method, return_residual=True, verbose=True) log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert 45 < match < 50 if method == 'MNE': # must be first! recon = apply_forward(fwd, stc, evoked.info) proj_op = make_projector(evoked.info['projs'], evoked.ch_names)[0] recon.data[:] = np.dot(proj_op, recon.data) residual_fwd = evoked.copy() residual_fwd.data -= recon.data corr = np.corrcoef(residual_fwd.data.ravel(), residual.data.ravel())[0, 1] assert corr > 0.999 with catch_logging() as log: _, residual = apply_inverse(evoked, inv, 0., 'MNE', return_residual=True, verbose=True) log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert match == 100. assert_array_less(np.abs(residual.data), 1e-15) # Degenerate: we don't have the right representation for eLORETA for this with pytest.raises(ValueError, match='eLORETA does not .* support .*'): apply_inverse(evoked, inv, method="eLORETA", return_residual=True)
def test_inverse_residual(evoked, method): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) evoked = evoked.pick_types(meg=True) inv = read_inverse_operator(fname_inv_fixed_depth) fwd = read_forward_solution(fname_fwd) pick_channels_forward(fwd, evoked.ch_names, copy=False) fwd = convert_forward_solution(fwd, force_fixed=True, surf_ori=True) matcher = re.compile(r'.* ([0-9]?[0-9]?[0-9]?\.[0-9])% variance.*') # make it complex to ensure we handle it properly evoked.data = 1j * evoked.data with catch_logging() as log: stc, residual = apply_inverse( evoked, inv, method=method, return_residual=True, verbose=True) # revert the complex-ification (except STC, allow that to be complex still) assert_array_equal(residual.data.real, 0) residual.data = (-1j * residual.data).real evoked.data = (-1j * evoked.data).real # continue testing log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert 45 < match < 50 if method not in ('dSPM', 'sLORETA'): # revert effects of STC being forced to be complex recon = apply_forward(fwd, stc, evoked.info) recon.data = (-1j * recon.data).real proj_op = make_projector(evoked.info['projs'], evoked.ch_names)[0] recon.data[:] = np.dot(proj_op, recon.data) residual_fwd = evoked.copy() residual_fwd.data -= recon.data corr = np.corrcoef(residual_fwd.data.ravel(), residual.data.ravel())[0, 1] assert corr > 0.999 if method != 'sLORETA': # XXX divide by zero error with catch_logging() as log: _, residual = apply_inverse( evoked, inv, 0., method, return_residual=True, verbose=True) log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert match == 100. assert_array_less(np.abs(residual.data), 1e-15)
def test_inverse_residual(): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) evoked = _get_evoked().pick_types() inv = read_inverse_operator(fname_inv_fixed_depth) fwd = read_forward_solution(fname_fwd) fwd = convert_forward_solution(fwd, force_fixed=True, surf_ori=True) fwd = pick_channels_forward(fwd, evoked.ch_names) matcher = re.compile(r'.* ([0-9]?[0-9]?[0-9]?\.[0-9])% variance.*') for method in ('MNE', 'dSPM', 'sLORETA'): with catch_logging() as log: stc, residual = apply_inverse( evoked, inv, method=method, return_residual=True, verbose=True) log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert 45 < match < 50 if method == 'MNE': # must be first! recon = apply_forward(fwd, stc, evoked.info) proj_op = make_projector(evoked.info['projs'], evoked.ch_names)[0] recon.data[:] = np.dot(proj_op, recon.data) residual_fwd = evoked.copy() residual_fwd.data -= recon.data corr = np.corrcoef(residual_fwd.data.ravel(), residual.data.ravel())[0, 1] assert corr > 0.999 with catch_logging() as log: _, residual = apply_inverse( evoked, inv, 0., 'MNE', return_residual=True, verbose=True) log = log.getvalue() match = matcher.match(log.replace('\n', ' ')) assert match is not None match = float(match.group(1)) assert match == 100. assert_array_less(np.abs(residual.data), 1e-15) # Degenerate: we don't have the right representation for eLORETA for this with pytest.raises(ValueError, match='eLORETA does not .* support .*'): apply_inverse(evoked, inv, method="eLORETA", return_residual=True)
def test_compute_proj_epochs(tmp_path): """Test SSP computation on epochs.""" tempdir = str(tmp_path) event_id, tmin, tmax = 1, -0.2, 0.3 raw = read_raw_fif(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 len(projs) == len(projs2) for p1, p2 in zip(projs, projs2): assert p1['desc'] == p2['desc'] assert p1['data']['col_names'] == p2['data']['col_names'] assert 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=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 nproj == 2 assert U.shape[1] == 2 # test that you can save them with epochs.info._unlock(): 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 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=1, desc_prefix='foobar') assert 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 proj_badname = op.join(tempdir, 'test-bad-name.fif.gz') with pytest.warns(RuntimeWarning, match='-proj.fif'): write_proj(proj_badname, projs) with pytest.warns(RuntimeWarning, match='-proj.fif'): read_proj(proj_badname) # bad inputs fname = op.join(tempdir, 'out-proj.fif') with pytest.raises(TypeError, match='projs'): write_proj(fname, 'foo') with pytest.raises(TypeError, match=r'projs\[0\] must be .*'): write_proj(fname, ['foo'])
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_compute_proj_epochs(): """Test SSP computation on epochs.""" tempdir = _TempDir() event_id, tmin, tmax = 1, -0.2, 0.3 raw = read_raw_fif(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 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_compute_proj_epochs(): """Test SSP computation on epochs.""" tempdir = _TempDir() event_id, tmin, tmax = 1, -0.2, 0.3 raw = read_raw_fif(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 len(projs) == len(projs2) for p1, p2 in zip(projs, projs2): assert p1['desc'] == p2['desc'] assert p1['data']['col_names'] == p2['data']['col_names'] assert 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 nproj == 2 assert 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 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=1, desc_prefix='foobar') assert 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 proj_badname = op.join(tempdir, 'test-bad-name.fif.gz') with pytest.warns(RuntimeWarning, match='-proj.fif'): write_proj(proj_badname, projs) with pytest.warns(RuntimeWarning, match='-proj.fif'): read_proj(proj_badname)