def test_cov_ctf(): """Test basic cov computation on ctf data with/without compensation.""" raw = read_raw_ctf(ctf_fname).crop(0., 2.).load_data() events = make_fixed_length_events(raw, 99999) assert len(events) == 2 ch_names = [ raw.info['ch_names'][pick] for pick in pick_types(raw.info, meg=True, eeg=False, ref_meg=False) ] for comp in [0, 1]: raw.apply_gradient_compensation(comp) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) with pytest.warns(RuntimeWarning, match='Too few samples'): noise_cov = compute_covariance(epochs, tmax=0., method=['empirical']) prepare_noise_cov(noise_cov, raw.info, ch_names) raw.apply_gradient_compensation(0) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) with pytest.warns(RuntimeWarning, match='Too few samples'): noise_cov = compute_covariance(epochs, tmax=0., method=['empirical']) raw.apply_gradient_compensation(1) # TODO This next call in principle should fail. prepare_noise_cov(noise_cov, raw.info, ch_names) # make sure comps matrices was not removed from raw assert raw.info['comps'], 'Comps matrices removed'
def test_cov_ctf(): """Test basic cov computation on ctf data with/without compensation.""" raw = read_raw_ctf(ctf_fname).crop(0., 2.).load_data() events = make_fixed_length_events(raw, 99999) assert len(events) == 2 ch_names = [raw.info['ch_names'][pick] for pick in pick_types(raw.info, meg=True, eeg=False, ref_meg=False)] for comp in [0, 1]: raw.apply_gradient_compensation(comp) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) with pytest.warns(RuntimeWarning, match='Too few samples'): noise_cov = compute_covariance(epochs, tmax=0., method=['empirical']) prepare_noise_cov(noise_cov, raw.info, ch_names) raw.apply_gradient_compensation(0) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) with pytest.warns(RuntimeWarning, match='Too few samples'): noise_cov = compute_covariance(epochs, tmax=0., method=['empirical']) raw.apply_gradient_compensation(1) # TODO This next call in principle should fail. prepare_noise_cov(noise_cov, raw.info, ch_names) # make sure comps matrices was not removed from raw assert raw.info['comps'], 'Comps matrices removed'
def test_cov_ctf(): """Test basic cov computation on ctf data with/without compensation.""" raw = read_raw_ctf(ctf_fname, preload=True) events = make_fixed_length_events(raw, 99999) ch_names = [ raw.info['ch_names'][pick] for pick in pick_types(raw.info, meg=True, eeg=False, ref_meg=False) ] for comp in [0, 1]: raw.apply_gradient_compensation(comp) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) noise_cov = compute_covariance(epochs, tmax=0., method=['shrunk']) prepare_noise_cov(noise_cov, raw.info, ch_names) raw.apply_gradient_compensation(0) epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True) noise_cov = compute_covariance(epochs, tmax=0., method=['shrunk']) raw.apply_gradient_compensation(1) # TODO This next call in principle should fail. prepare_noise_cov(noise_cov, raw.info, ch_names) # make sure comps matrices was not removed from raw if not raw.info['comps']: raise RuntimeError('Comps matrices removed')
def test_cov_order(): """Test covariance ordering.""" raw = read_raw_fif(raw_fname) raw.set_eeg_reference(projection=True) info = raw.info # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error') # big reordering cov_reorder = cov.copy() order = np.random.RandomState(0).permutation(np.arange(len(cov.ch_names))) cov_reorder['names'] = [cov['names'][ii] for ii in order] cov_reorder['data'] = cov['data'][order][:, order] # Make sure we did this properly _assert_reorder(cov_reorder, cov, order) # Now check some functions that should get the same result for both # regularize with pytest.raises(ValueError, match='rank, if str'): regularize(cov, info, rank='foo') with pytest.raises(TypeError, match='rank must be'): regularize(cov, info, rank=False) with pytest.raises(TypeError, match='rank must be'): regularize(cov, info, rank=1.) cov_reg = regularize(cov, info, rank='full') cov_reg_reorder = regularize(cov_reorder, info, rank='full') _assert_reorder(cov_reg_reorder, cov_reg, order) # prepare_noise_cov cov_prep = prepare_noise_cov(cov, info, ch_names) cov_prep_reorder = prepare_noise_cov(cov, info, ch_names) _assert_reorder(cov_prep, cov_prep_reorder, order=np.arange(len(cov_prep['names']))) # compute_whitener whitener, w_ch_names, n_nzero = compute_whitener( cov, info, return_rank=True) assert whitener.shape[0] == whitener.shape[1] whitener_2, w_ch_names_2, n_nzero_2 = compute_whitener( cov_reorder, info, return_rank=True) assert_array_equal(w_ch_names_2, w_ch_names) assert_allclose(whitener_2, whitener, rtol=1e-6) assert n_nzero == n_nzero_2 # with pca assert n_nzero < whitener.shape[0] whitener_pca, w_ch_names_pca, n_nzero_pca = compute_whitener( cov, info, pca=True, return_rank=True) assert_array_equal(w_ch_names_pca, w_ch_names) assert n_nzero_pca == n_nzero assert whitener_pca.shape == (n_nzero_pca, len(w_ch_names)) # whiten_evoked evoked = read_evokeds(ave_fname)[0] evoked_white = whiten_evoked(evoked, cov) evoked_white_2 = whiten_evoked(evoked, cov_reorder) assert_allclose(evoked_white_2.data, evoked_white.data, atol=1e-7)
def test_cov_order(): """Test covariance ordering.""" raw = read_raw_fif(raw_fname) raw.set_eeg_reference(projection=True) info = raw.info # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error') # big reordering cov_reorder = cov.copy() order = np.random.RandomState(0).permutation(np.arange(len(cov.ch_names))) cov_reorder['names'] = [cov['names'][ii] for ii in order] cov_reorder['data'] = cov['data'][order][:, order] # Make sure we did this properly _assert_reorder(cov_reorder, cov, order) # Now check some functions that should get the same result for both # regularize with pytest.raises(ValueError, match='rank, if str'): regularize(cov, info, rank='foo') with pytest.raises(TypeError, match='rank must be'): regularize(cov, info, rank=False) with pytest.raises(TypeError, match='rank must be'): regularize(cov, info, rank=1.) cov_reg = regularize(cov, info, rank='full') cov_reg_reorder = regularize(cov_reorder, info, rank='full') _assert_reorder(cov_reg_reorder, cov_reg, order) # prepare_noise_cov cov_prep = prepare_noise_cov(cov, info, ch_names) cov_prep_reorder = prepare_noise_cov(cov, info, ch_names) _assert_reorder(cov_prep, cov_prep_reorder, order=np.arange(len(cov_prep['names']))) # compute_whitener whitener, w_ch_names, n_nzero = compute_whitener( cov, info, return_rank=True) assert whitener.shape[0] == whitener.shape[1] whitener_2, w_ch_names_2, n_nzero_2 = compute_whitener( cov_reorder, info, return_rank=True) assert_array_equal(w_ch_names_2, w_ch_names) assert_allclose(whitener_2, whitener) assert n_nzero == n_nzero_2 # with pca assert n_nzero < whitener.shape[0] whitener_pca, w_ch_names_pca, n_nzero_pca = compute_whitener( cov, info, pca=True, return_rank=True) assert_array_equal(w_ch_names_pca, w_ch_names) assert n_nzero_pca == n_nzero assert whitener_pca.shape == (n_nzero_pca, len(w_ch_names)) # whiten_evoked evoked = read_evokeds(ave_fname)[0] evoked_white = whiten_evoked(evoked, cov) evoked_white_2 = whiten_evoked(evoked, cov_reorder) assert_allclose(evoked_white_2.data, evoked_white.data)
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info["bads"] += ["MEG 0113"] ch_names = [info["ch_names"][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose="error")
def test_cov_order(): """Test covariance ordering""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) with warnings.catch_warnings(record=True): # no avg ref present prepare_noise_cov(cov, info, ch_names, verbose='error')
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [ info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True) ] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error')
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [ info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True) ] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error') # big reordering cov_reorder = cov.copy() order = np.random.RandomState(0).permutation(np.arange(len(cov.ch_names))) cov_reorder['names'] = [cov['names'][ii] for ii in order] cov_reorder['data'] = cov['data'][order][:, order] # Make sure we did this properly _assert_reorder(cov_reorder, cov, order) # Now check some functions that should get the same result for both # regularize cov_reg = regularize(cov, info) cov_reg_reorder = regularize(cov_reorder, info) _assert_reorder(cov_reg_reorder, cov_reg, order) # prepare_noise_cov cov_prep = prepare_noise_cov(cov, info, ch_names) cov_prep_reorder = prepare_noise_cov(cov, info, ch_names) _assert_reorder(cov_prep, cov_prep_reorder, order=np.arange(len(cov_prep['names']))) # compute_whitener whitener, w_ch_names = compute_whitener(cov, info) whitener_2, w_ch_names_2 = compute_whitener(cov_reorder, info) assert_array_equal(w_ch_names_2, w_ch_names) assert_allclose(whitener_2, whitener) # whiten_evoked evoked = read_evokeds(ave_fname)[0] evoked_white = whiten_evoked(evoked, cov) evoked_white_2 = whiten_evoked(evoked, cov_reorder) assert_allclose(evoked_white_2.data, evoked_white.data)
def test_cov_order(): """Test covariance ordering.""" info = read_info(raw_fname) # add MEG channel with low enough index number to affect EEG if # order is incorrect info['bads'] += ['MEG 0113'] ch_names = [info['ch_names'][pick] for pick in pick_types(info, meg=False, eeg=True)] cov = read_cov(cov_fname) # no avg ref present warning prepare_noise_cov(cov, info, ch_names, verbose='error') # big reordering cov_reorder = cov.copy() order = np.random.RandomState(0).permutation(np.arange(len(cov.ch_names))) cov_reorder['names'] = [cov['names'][ii] for ii in order] cov_reorder['data'] = cov['data'][order][:, order] # Make sure we did this properly _assert_reorder(cov_reorder, cov, order) # Now check some functions that should get the same result for both # regularize cov_reg = regularize(cov, info) cov_reg_reorder = regularize(cov_reorder, info) _assert_reorder(cov_reg_reorder, cov_reg, order) # prepare_noise_cov cov_prep = prepare_noise_cov(cov, info, ch_names) cov_prep_reorder = prepare_noise_cov(cov, info, ch_names) _assert_reorder(cov_prep, cov_prep_reorder, order=np.arange(len(cov_prep['names']))) # compute_whitener whitener, w_ch_names = compute_whitener(cov, info) whitener_2, w_ch_names_2 = compute_whitener(cov_reorder, info) assert_array_equal(w_ch_names_2, w_ch_names) assert_allclose(whitener_2, whitener) # whiten_evoked evoked = read_evokeds(ave_fname)[0] evoked_white = whiten_evoked(evoked, cov) evoked_white_2 = whiten_evoked(evoked, cov_reorder) assert_allclose(evoked_white_2.data, evoked_white.data)
def mSSP_make_whitener(noise_cov, info, pca=False, rank=None, verbose=None): """get whitening matrix from covariance matrix ripped from mne.minimum_norm.inverse._prepare_forward I still don't understand this - doesn't seem to work e.g. whitener.dot(noise_cov.data).dot(whitener) is not near to identity """ ch_names = [ c['ch_name'] for c in info['chs'] if ((c['ch_name'] not in info['bads'] and c['ch_name'] not in noise_cov['bads']) and (c['ch_name'] in noise_cov.ch_names)) ] if not len(info['bads']) == len(noise_cov['bads']) or \ not all(b in noise_cov['bads'] for b in info['bads']): logger.info('info["bads"] and noise_cov["bads"] do not match, ' 'excluding bad channels from both') n_chan = len(ch_names) logger.info("Computing whitener with %d channels." % n_chan) # # Handle noise cov # noise_cov = prepare_noise_cov(noise_cov, info, ch_names, rank) # Omit the zeroes due to projection eig = noise_cov['eig'] nzero = (eig > 0) n_nzero = sum(nzero) if pca: # Rows of eigvec are the eigenvectors whitener = noise_cov['eigvec'][nzero] / np.sqrt(eig[nzero])[:, None] logger.info('Reducing data rank to %d' % n_nzero) else: whitener = np.zeros((n_chan, n_chan), dtype=np.float) whitener[nzero, nzero] = 1.0 / np.sqrt(eig[nzero]) # Rows of eigvec are the eigenvectors whitener = np.dot(whitener, noise_cov['eigvec']) logger.info('Total rank is %d' % n_nzero) return whitener, noise_cov, n_nzero
def test_rank(): """Test cov rank estimation.""" # Test that our rank estimation works properly on a simple case evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=False) cov = read_cov(cov_fname) ch_names = [ ch for ch in evoked.info['ch_names'] if '053' not in ch and ch.startswith('EEG') ] cov = prepare_noise_cov(cov, evoked.info, ch_names, None) assert_equal(cov['eig'][0], 0.) # avg projector should set this to zero assert_true((cov['eig'][1:] > 0).all()) # all else should be > 0 # Now do some more comprehensive tests raw_sample = read_raw_fif(raw_fname) raw_sss = read_raw_fif(hp_fif_fname) raw_sss.add_proj(compute_proj_raw(raw_sss)) cov_sample = compute_raw_covariance(raw_sample) cov_sample_proj = compute_raw_covariance(raw_sample.copy().apply_proj()) cov_sss = compute_raw_covariance(raw_sss) cov_sss_proj = compute_raw_covariance(raw_sss.copy().apply_proj()) picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True) picks_all_sss = pick_types(raw_sss.info, meg=True, eeg=True) info_sample = pick_info(raw_sample.info, picks_all_sample) picks_stack_sample = [('eeg', pick_types(info_sample, meg=False, eeg=True))] picks_stack_sample += [('meg', pick_types(info_sample, meg=True))] picks_stack_sample += [('all', pick_types(info_sample, meg=True, eeg=True))] info_sss = pick_info(raw_sss.info, picks_all_sss) picks_stack_somato = [('eeg', pick_types(info_sss, meg=False, eeg=True))] picks_stack_somato += [('meg', pick_types(info_sss, meg=True))] picks_stack_somato += [('all', pick_types(info_sss, meg=True, eeg=True))] iter_tests = list( itt.product( [(cov_sample, picks_stack_sample, info_sample), (cov_sample_proj, picks_stack_sample, info_sample), (cov_sss, picks_stack_somato, info_sss), (cov_sss_proj, picks_stack_somato, info_sss)], # sss [dict(mag=1e15, grad=1e13, eeg=1e6)])) for (cov, picks_list, this_info), scalings in iter_tests: for ch_type, picks in picks_list: this_very_info = pick_info(this_info, picks) # compute subset of projs this_projs = [ c['active'] and len( set(c['data']['col_names']).intersection( set(this_very_info['ch_names']))) > 0 for c in cov['projs'] ] n_projs = sum(this_projs) # count channel types ch_types = [ channel_type(this_very_info, idx) for idx in range(len(picks)) ] n_eeg, n_mag, n_grad = [ ch_types.count(k) for k in ['eeg', 'mag', 'grad'] ] n_meg = n_mag + n_grad if ch_type in ('all', 'eeg'): n_projs_eeg = 1 else: n_projs_eeg = 0 # check sss if len(this_very_info['proc_history']) > 0: mf = this_very_info['proc_history'][0]['max_info'] n_free = _get_sss_rank(mf) if 'mag' not in ch_types and 'grad' not in ch_types: n_free = 0 # - n_projs XXX clarify expected_rank = n_free + n_eeg if n_projs > 0 and ch_type in ('all', 'eeg'): expected_rank -= n_projs_eeg else: expected_rank = n_meg + n_eeg - n_projs C = cov['data'][np.ix_(picks, picks)] est_rank = _estimate_rank_meeg_cov(C, this_very_info, scalings=scalings) assert_equal(expected_rank, est_rank)
def test_cov_rank_estimation(rank_method, proj, meg): """Test cov rank estimation.""" # Test that our rank estimation works properly on a simple case evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=False) cov = read_cov(cov_fname) ch_names = [ ch for ch in evoked.info['ch_names'] if '053' not in ch and ch.startswith('EEG') ] cov = prepare_noise_cov(cov, evoked.info, ch_names, None) assert cov['eig'][0] <= 1e-25 # avg projector should set this to zero assert (cov['eig'][1:] > 1e-16).all() # all else should be > 0 # Now do some more comprehensive tests raw_sample = read_raw_fif(raw_fname) assert not _has_eeg_average_ref_proj(raw_sample.info['projs']) raw_sss = read_raw_fif(hp_fif_fname) assert not _has_eeg_average_ref_proj(raw_sss.info['projs']) raw_sss.add_proj(compute_proj_raw(raw_sss, meg=meg)) cov_sample = compute_raw_covariance(raw_sample) cov_sample_proj = compute_raw_covariance(raw_sample.copy().apply_proj()) cov_sss = compute_raw_covariance(raw_sss) cov_sss_proj = compute_raw_covariance(raw_sss.copy().apply_proj()) picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True) picks_all_sss = pick_types(raw_sss.info, meg=True, eeg=True) info_sample = pick_info(raw_sample.info, picks_all_sample) picks_stack_sample = [('eeg', pick_types(info_sample, meg=False, eeg=True))] picks_stack_sample += [('meg', pick_types(info_sample, meg=True))] picks_stack_sample += [('all', pick_types(info_sample, meg=True, eeg=True))] info_sss = pick_info(raw_sss.info, picks_all_sss) picks_stack_somato = [('eeg', pick_types(info_sss, meg=False, eeg=True))] picks_stack_somato += [('meg', pick_types(info_sss, meg=True))] picks_stack_somato += [('all', pick_types(info_sss, meg=True, eeg=True))] iter_tests = list( itt.product( [(cov_sample, picks_stack_sample, info_sample), (cov_sample_proj, picks_stack_sample, info_sample), (cov_sss, picks_stack_somato, info_sss), (cov_sss_proj, picks_stack_somato, info_sss)], # sss [dict(mag=1e15, grad=1e13, eeg=1e6)], )) for (cov, picks_list, iter_info), scalings in iter_tests: rank = compute_rank(cov, rank_method, scalings, iter_info, proj=proj) rank['all'] = sum(rank.values()) for ch_type, picks in picks_list: this_info = pick_info(iter_info, picks) # compute subset of projs, active and inactive n_projs_applied = sum(proj['active'] and len( set(proj['data']['col_names']) & set(this_info['ch_names'])) > 0 for proj in cov['projs']) n_projs_info = sum( len( set(proj['data']['col_names']) & set(this_info['ch_names'])) > 0 for proj in this_info['projs']) # count channel types ch_types = _get_channel_types(this_info) n_eeg, n_mag, n_grad = [ ch_types.count(k) for k in ['eeg', 'mag', 'grad'] ] n_meg = n_mag + n_grad has_sss = (n_meg > 0 and len(this_info['proc_history']) > 0) if has_sss: n_meg = _get_rank_sss(this_info) expected_rank = n_meg + n_eeg if rank_method is None: if meg == 'combined' or not has_sss: if proj: expected_rank -= n_projs_info else: expected_rank -= n_projs_applied else: # XXX for now it just uses the total count assert rank_method == 'info' if proj: expected_rank -= n_projs_info assert rank[ch_type] == expected_rank
def test_rank(): """Test cov rank estimation.""" # Test that our rank estimation works properly on a simple case evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=False) cov = read_cov(cov_fname) ch_names = [ch for ch in evoked.info['ch_names'] if '053' not in ch and ch.startswith('EEG')] cov = prepare_noise_cov(cov, evoked.info, ch_names, None) assert_equal(cov['eig'][0], 0.) # avg projector should set this to zero assert_true((cov['eig'][1:] > 0).all()) # all else should be > 0 # Now do some more comprehensive tests raw_sample = read_raw_fif(raw_fname) raw_sss = read_raw_fif(hp_fif_fname) raw_sss.add_proj(compute_proj_raw(raw_sss)) cov_sample = compute_raw_covariance(raw_sample) cov_sample_proj = compute_raw_covariance( raw_sample.copy().apply_proj()) cov_sss = compute_raw_covariance(raw_sss) cov_sss_proj = compute_raw_covariance( raw_sss.copy().apply_proj()) picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True) picks_all_sss = pick_types(raw_sss.info, meg=True, eeg=True) info_sample = pick_info(raw_sample.info, picks_all_sample) picks_stack_sample = [('eeg', pick_types(info_sample, meg=False, eeg=True))] picks_stack_sample += [('meg', pick_types(info_sample, meg=True))] picks_stack_sample += [('all', pick_types(info_sample, meg=True, eeg=True))] info_sss = pick_info(raw_sss.info, picks_all_sss) picks_stack_somato = [('eeg', pick_types(info_sss, meg=False, eeg=True))] picks_stack_somato += [('meg', pick_types(info_sss, meg=True))] picks_stack_somato += [('all', pick_types(info_sss, meg=True, eeg=True))] iter_tests = list(itt.product( [(cov_sample, picks_stack_sample, info_sample), (cov_sample_proj, picks_stack_sample, info_sample), (cov_sss, picks_stack_somato, info_sss), (cov_sss_proj, picks_stack_somato, info_sss)], # sss [dict(mag=1e15, grad=1e13, eeg=1e6)] )) for (cov, picks_list, this_info), scalings in iter_tests: for ch_type, picks in picks_list: this_very_info = pick_info(this_info, picks) # compute subset of projs this_projs = [c['active'] and len(set(c['data']['col_names']) .intersection(set(this_very_info['ch_names']))) > 0 for c in cov['projs']] n_projs = sum(this_projs) # count channel types ch_types = [channel_type(this_very_info, idx) for idx in range(len(picks))] n_eeg, n_mag, n_grad = [ch_types.count(k) for k in ['eeg', 'mag', 'grad']] n_meg = n_mag + n_grad if ch_type in ('all', 'eeg'): n_projs_eeg = 1 else: n_projs_eeg = 0 # check sss if len(this_very_info['proc_history']) > 0: mf = this_very_info['proc_history'][0]['max_info'] n_free = _get_sss_rank(mf) if 'mag' not in ch_types and 'grad' not in ch_types: n_free = 0 # - n_projs XXX clarify expected_rank = n_free + n_eeg if n_projs > 0 and ch_type in ('all', 'eeg'): expected_rank -= n_projs_eeg else: expected_rank = n_meg + n_eeg - n_projs C = cov['data'][np.ix_(picks, picks)] est_rank = _estimate_rank_meeg_cov(C, this_very_info, scalings=scalings) assert_equal(expected_rank, est_rank)
def mSSP_make_beamformer(cov, topos, regpars): """Make beamformer estimator given covariance matrix and topography(ies) inclulde MLE depending on covmat Parameters ---------- cov : instance of Covariance matrix Covariance matrix for beamformer, assumed to be regularised. topos : instance of Evoked One beamformer per topography will be computed, with this toography as target. regpars : float or dict of float regularisation parameters for covariance matrices (per channel type) if float, one regpar for all channel types if dict, needs entries for all channel types in cov ('mag', 'grad', 'eeg') Returns ------- spatfilt: Evoked spatial filters as topographies.""" # evoked object to contain spatial filters spatfilt = copy.deepcopy(topos) # make sure covariance matrix and topos agree in channels # assumes noise_cov has at least the channels of topos ch_names = topos.ch_names # channel indices for different channel types ch_idx = mSSP_get_channel_types(ch_names) print "Preparing covariance matrix" cov = prepare_noise_cov(cov, info=topos.info, ch_names=ch_names, rank=None) # noise covariance matrix as np.array cov_mat = cov.data print "Getting sub-matrices for channel types" cov_dict = {} if ch_idx['mag']: cov_dict['mag'] = cov_mat[np.ix_(ch_idx['mag'], ch_idx['mag'])] if ch_idx['grad']: cov_dict['grad'] = cov_mat[np.ix_(ch_idx['grad'], ch_idx['grad'])] if ch_idx['eeg']: cov_dict['eeg'] = cov_mat[np.ix_(ch_idx['eeg'], ch_idx['eeg'])] ### if using whitener-approach (not happy with it): # cov_inv_dict = {} # if ch_idx['mag']: # chs = [ch_names[idx] for idx in ch_idx['mag']] # cov_now = pick_channels_cov(cov, include=chs) # [cov_inv_now, _, _] = mSSP_make_whitener(cov_now, topos.info, rank=None) # cov_inv_dict['mag'] = cov_inv_now # if ch_idx['grad']: # chs = [ch_names[idx] for idx in ch_idx['grad']] # cov_now = pick_channels_cov(cov, include=chs) # [cov_inv_now, _, _] = mSSP_make_whitener(cov_now, topos.info, rank=None) # cov_inv_dict['grad'] = cov_inv_now # if ch_idx['eeg']: # chs = [ch_names[idx] for idx in ch_idx['eeg']] # cov_now = pick_channels_cov(cov, include=chs) # [cov_inv_now, _, _] = mSSP_make_whitener(cov_now, topos.info, rank=None) # cov_inv_dict['eeg'] = cov_inv_now print "Computing spatial filters" sf_dict = {} # spatial filters per channel type for ch_type in cov_dict: print ch_type topo_now = topos.data[ch_idx[ch_type], :] [n_c, n_t] = topo_now.shape sf_dict[ch_type] = np.zeros([n_c, n_t]) # # take square of whitener for beamformer # cov_dict_inv = cov_inv_dict[ch_type].dot(cov_inv_dict[ch_type]) # (pseudo)invert covariance matrix # cov_dict_inv = pinv(cov_dict[ch_type]) # using eigenvalue truncation # cov_dict_inv = mSSP_invert_SVD_trunc(cov_dict[ch_type], n_comp=30) # using Tikhonov regularisation if type(regpars) == dict: # if reg params specified per channel type regpar = regpars[ch_type] else: # if only one reg param specified: use for all channel types regpar = regpars cov_dict_inv = mSSP_invert_square_Tikhonov(cov_dict[ch_type], regpar=regpar) for tt in range(n_t): targ = topo_now[:, tt] denom = targ.T.dot(cov_dict_inv).dot(targ) sf_dict[ch_type][:, tt] = cov_dict_inv.dot(targ) / denom spatfilt.data[ch_idx[ch_type], :] = sf_dict[ch_type] return spatfilt
def test_cov_rank_estimation(rank_method, proj, meg): """Test cov rank estimation.""" # Test that our rank estimation works properly on a simple case evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=False) cov = read_cov(cov_fname) ch_names = [ch for ch in evoked.info['ch_names'] if '053' not in ch and ch.startswith('EEG')] cov = prepare_noise_cov(cov, evoked.info, ch_names, None) assert cov['eig'][0] <= 1e-25 # avg projector should set this to zero assert (cov['eig'][1:] > 1e-16).all() # all else should be > 0 # Now do some more comprehensive tests raw_sample = read_raw_fif(raw_fname) assert not _has_eeg_average_ref_proj(raw_sample.info['projs']) raw_sss = read_raw_fif(hp_fif_fname) assert not _has_eeg_average_ref_proj(raw_sss.info['projs']) raw_sss.add_proj(compute_proj_raw(raw_sss, meg=meg)) cov_sample = compute_raw_covariance(raw_sample) cov_sample_proj = compute_raw_covariance(raw_sample.copy().apply_proj()) cov_sss = compute_raw_covariance(raw_sss) cov_sss_proj = compute_raw_covariance(raw_sss.copy().apply_proj()) picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True) picks_all_sss = pick_types(raw_sss.info, meg=True, eeg=True) info_sample = pick_info(raw_sample.info, picks_all_sample) picks_stack_sample = [('eeg', pick_types(info_sample, meg=False, eeg=True))] picks_stack_sample += [('meg', pick_types(info_sample, meg=True))] picks_stack_sample += [('all', pick_types(info_sample, meg=True, eeg=True))] info_sss = pick_info(raw_sss.info, picks_all_sss) picks_stack_somato = [('eeg', pick_types(info_sss, meg=False, eeg=True))] picks_stack_somato += [('meg', pick_types(info_sss, meg=True))] picks_stack_somato += [('all', pick_types(info_sss, meg=True, eeg=True))] iter_tests = list(itt.product( [(cov_sample, picks_stack_sample, info_sample), (cov_sample_proj, picks_stack_sample, info_sample), (cov_sss, picks_stack_somato, info_sss), (cov_sss_proj, picks_stack_somato, info_sss)], # sss [dict(mag=1e15, grad=1e13, eeg=1e6)], )) for (cov, picks_list, iter_info), scalings in iter_tests: rank = compute_rank(cov, rank_method, scalings, iter_info, proj=proj) rank['all'] = sum(rank.values()) for ch_type, picks in picks_list: this_info = pick_info(iter_info, picks) # compute subset of projs, active and inactive n_projs_applied = sum(proj['active'] and len(set(proj['data']['col_names']) & set(this_info['ch_names'])) > 0 for proj in cov['projs']) n_projs_info = sum(len(set(proj['data']['col_names']) & set(this_info['ch_names'])) > 0 for proj in this_info['projs']) # count channel types ch_types = [channel_type(this_info, idx) for idx in range(len(picks))] n_eeg, n_mag, n_grad = [ch_types.count(k) for k in ['eeg', 'mag', 'grad']] n_meg = n_mag + n_grad has_sss = (n_meg > 0 and len(this_info['proc_history']) > 0) if has_sss: n_meg = _get_rank_sss(this_info) expected_rank = n_meg + n_eeg if rank_method is None: if meg == 'combined' or not has_sss: if proj: expected_rank -= n_projs_info else: expected_rank -= n_projs_applied else: # XXX for now it just uses the total count assert rank_method == 'info' if proj: expected_rank -= n_projs_info assert rank[ch_type] == expected_rank