def test_stc_mpl(): """Test plotting source estimates with matplotlib.""" sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.ones((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') with pytest.warns(RuntimeWarning, match='not included'): stc.plot(subjects_dir=subjects_dir, time_unit='s', views='ven', hemi='rh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='oct1', initial_time=0.001, colormap='Reds') fig = stc.plot(subjects_dir=subjects_dir, time_unit='ms', views='dor', hemi='lh', smoothing_steps=2, subject='sample', backend='matplotlib', spacing='ico2', time_viewer=True, colormap='mne') time_viewer = fig.time_viewer _fake_click(time_viewer, time_viewer.axes[0], (0.5, 0.5)) # change t time_viewer.canvas.key_press_event('ctrl+right') time_viewer.canvas.key_press_event('left') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, hemi='both', subject='sample', backend='matplotlib') pytest.raises(ValueError, stc.plot, subjects_dir=subjects_dir, time_unit='ss', subject='sample', backend='matplotlib') plt.close('all')
def test_simulate_raw_bem(): """Test simulation of raw data with BEM.""" raw, src, stc, trans, sphere = _get_data() src = setup_source_space('sample', 'oct1', subjects_dir=subjects_dir) for s in src: s['nuse'] = 3 s['vertno'] = src[1]['vertno'][:3] s['inuse'].fill(0) s['inuse'][s['vertno']] = 1 # use different / more complete STC here vertices = [s['vertno'] for s in src] stc = SourceEstimate(np.eye(sum(len(v) for v in vertices)), vertices, 0, 1. / raw.info['sfreq']) raw_sim_sph = simulate_raw(raw, stc, trans, src, sphere, cov=None) raw_sim_bem = simulate_raw(raw, stc, trans, src, bem_fname, cov=None, n_jobs=2) # some components (especially radial) might not match that well, # so just make sure that most components have high correlation assert_array_equal(raw_sim_sph.ch_names, raw_sim_bem.ch_names) picks = pick_types(raw.info, meg=True, eeg=True) n_ch = len(picks) corr = np.corrcoef(raw_sim_sph[picks][0], raw_sim_bem[picks][0]) assert_array_equal(corr.shape, (2 * n_ch, 2 * n_ch)) med_corr = np.median(np.diag(corr[:n_ch, -n_ch:])) assert med_corr > 0.65 # do some round-trip localization for s in src: transform_surface_to(s, 'head', trans) locs = np.concatenate([s['rr'][s['vertno']] for s in src]) tmax = (len(locs) - 1) / raw.info['sfreq'] cov = make_ad_hoc_cov(raw.info) # The tolerance for the BEM is surprisingly high (28) but I get the same # result when using MNE-C and Xfit, even when using a proper 5120 BEM :( for use_raw, bem, tol in ((raw_sim_sph, sphere, 2), (raw_sim_bem, bem_fname, 31)): events = find_events(use_raw, 'STI 014') assert len(locs) == 6 evoked = Epochs(use_raw, events, 1, 0, tmax, baseline=None).average() assert len(evoked.times) == len(locs) fits = fit_dipole(evoked, cov, bem, trans, min_dist=1.)[0].pos diffs = np.sqrt(np.sum((locs - fits)**2, axis=-1)) * 1000 med_diff = np.median(diffs) assert med_diff < tol, '%s: %s' % (bem, med_diff)
def test_process_clim_plot(renderer_interactive, brain_gc): """Test functionality for determining control points with stc.plot.""" sample_src = read_source_spaces(src_fname) kwargs = dict(subjects_dir=subjects_dir, smoothing_steps=1, time_viewer=False, show_traces=False) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.random.RandomState(0).rand((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') # Test for simple use cases brain = stc.plot(**kwargs) assert brain.data['center'] is None brain.close() brain = stc.plot(clim=dict(pos_lims=(10, 50, 90)), **kwargs) assert brain.data['center'] == 0. brain.close() stc.plot(colormap='hot', clim='auto', **kwargs) stc.plot(colormap='mne', clim='auto', **kwargs) stc.plot(clim=dict(kind='value', lims=(10, 50, 90)), figure=99, **kwargs) pytest.raises(TypeError, stc.plot, clim='auto', figure=[0], **kwargs) # Test for correct clim values with pytest.raises(ValueError, match='monotonically'): stc.plot(clim=dict(kind='value', pos_lims=[0, 1, 0]), **kwargs) with pytest.raises(ValueError, match=r'.*must be \(3,\)'): stc.plot(colormap='mne', clim=dict(pos_lims=(5, 10, 15, 20)), **kwargs) with pytest.raises(ValueError, match="'value', 'values', and 'percent'"): stc.plot(clim=dict(pos_lims=(5, 10, 15), kind='foo'), **kwargs) with pytest.raises(ValueError, match='must be "auto" or dict'): stc.plot(colormap='mne', clim='foo', **kwargs) with pytest.raises(TypeError, match='must be an instance of'): plot_source_estimates('foo', clim='auto', **kwargs) with pytest.raises(ValueError, match='hemi'): stc.plot(hemi='foo', clim='auto', **kwargs) with pytest.raises(ValueError, match='Exactly one'): stc.plot(clim=dict(lims=[0, 1, 2], pos_lims=[0, 1, 2], kind='value'), **kwargs) # Test handling of degenerate data: thresholded maps stc._data.fill(0.) with pytest.warns(RuntimeWarning, match='All data were zero'): plot_source_estimates(stc, **kwargs)
def test_to_data_frame_index(index): """Test index creation in stc Pandas exporter.""" n_vert, n_times = 10, 5 vertices = [np.arange(n_vert, dtype=np.int), np.empty(0, dtype=np.int)] data = rng.randn(n_vert, n_times) stc = SourceEstimate(data, vertices=vertices, tmin=0, tstep=1, subject='sample') df = stc.to_data_frame(index=index) # test index setting if not isinstance(index, list): index = [index] assert (df.index.names == index) # test that non-indexed data were present as columns non_index = list(set(['time', 'subject']) - set(index)) if len(non_index): assert all(np.in1d(non_index, df.columns))
def test_single_hemi(hemi, renderer_interactive_pyvistaqt, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close()
def test_brain_timeviewer(renderer_interactive): """Test _TimeViewer primitives.""" sample_src = read_source_spaces(src_fname) # dense version vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(np.random.rand(stc_size // 20) * stc_size).astype(int)] = \ np.random.RandomState(0).rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1) fmin = stc.data.min() fmax = stc.data.max() brain_data = _Brain(subject_id, 'split', surf, size=300, subjects_dir=subjects_dir) for hemi in ['lh', 'rh']: hemi_idx = 0 if hemi == 'lh' else 1 data = getattr(stc, hemi + '_data') vertices = stc.vertices[hemi_idx] brain_data.add_data(data, fmin=fmin, hemi=hemi, fmax=fmax, colormap='hot', vertices=vertices, colorbar=True) time_viewer = _TimeViewer(brain_data) time_viewer.time_call(value=0) time_viewer.orientation_call(value='lat', update_widget=True) time_viewer.orientation_call(value='medial', update_widget=True) time_viewer.smoothing_call(value=1) time_viewer.fmin_call(value=12.0) time_viewer.fmax_call(value=4.0) time_viewer.fmid_call(value=6.0) time_viewer.fmid_call(value=4.0) time_viewer.fscale_call(value=1.1) time_viewer.toggle_interface() time_viewer.playback_speed_call(value=0.1) time_viewer.toggle_playback() time_viewer.apply_auto_scaling() time_viewer.restore_user_scaling() link_viewer = _LinkViewer([brain_data]) link_viewer.set_time_point(value=0) link_viewer.set_playback_speed(value=0.1) link_viewer.toggle_playback()
def test_apply_forward(): """Test projection of source space data to sensor space.""" start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) assert isinstance(fwd, Forward) vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) gain_sum = np.sum(fwd['sol']['data'], axis=1) # Evoked evoked = read_evokeds(fname_evoked, condition=0) evoked.pick_types(meg=True) with pytest.warns(RuntimeWarning, match='only .* positive values'): evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop) data = evoked.data times = evoked.times # do some tests assert_array_almost_equal(evoked.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) assert_array_almost_equal(times[0], t_start) assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq) # Raw with pytest.warns(RuntimeWarning, match='only .* positive values'): raw_proj = apply_forward_raw(fwd, stc, evoked.info, start=start, stop=stop) data, times = raw_proj[:, :] # do some tests assert_array_almost_equal(raw_proj.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) atol = 1. / sfreq assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol) assert_allclose(raw_proj.last_samp / sfreq, t_start + (n_times - 1) / sfreq, atol=atol)
def test_apply_forward(): """Test projection of source space data to sensor space """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) assert_true(isinstance(fwd, Forward)) vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) gain_sum = np.sum(fwd['sol']['data'], axis=1) # Evoked with warnings.catch_warnings(record=True) as w: evoked = read_evokeds(fname_evoked, condition=0) evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop) assert_equal(len(w), 2) data = evoked.data times = evoked.times # do some tests assert_array_almost_equal(evoked.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) assert_array_almost_equal(times[0], t_start) assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq) # Raw raw = Raw(fname_raw) raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop) data, times = raw_proj[:, :] # do some tests assert_array_almost_equal(raw_proj.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) atol = 1. / sfreq assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol) assert_allclose(raw_proj.last_samp / sfreq, t_start + (n_times - 1) / sfreq, atol=atol)
def test_plot_source_spectrogram(): """Test plotting of source spectrogram.""" sample_src = read_source_spaces(op.join(subjects_dir, 'sample', 'bem', 'sample-oct-6-src.fif')) # dense version vertices = [s['vertno'] for s in sample_src] n_times = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.ones((n_verts, n_times)) stc = SourceEstimate(stc_data, vertices, 1, 1) plot_source_spectrogram([stc, stc], [[1, 2], [3, 4]]) assert_raises(ValueError, plot_source_spectrogram, [], []) assert_raises(ValueError, plot_source_spectrogram, [stc, stc], [[1, 2], [3, 4]], tmin=0) assert_raises(ValueError, plot_source_spectrogram, [stc, stc], [[1, 2], [3, 4]], tmax=7)
def test_accuracy(): """Test dipole fitting to sub-mm accuracy.""" evoked = read_evokeds(fname_evo)[0].crop( 0., 0., ) evoked.pick_types(meg=True, eeg=False) evoked.pick_channels([c for c in evoked.ch_names[::4]]) for rad, perc_90 in zip((0.09, None), (0.002, 0.004)): bem = make_sphere_model('auto', rad, evoked.info, relative_radii=(0.999, 0.998, 0.997, 0.995)) src = read_source_spaces(fname_src) fwd = make_forward_solution(evoked.info, None, src, bem) fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=True) vertices = [src[0]['vertno'], src[1]['vertno']] n_vertices = sum(len(v) for v in vertices) amp = 10e-9 data = np.eye(n_vertices + 1)[:n_vertices] data[-1, -1] = 1. data *= amp stc = SourceEstimate(data, vertices, 0., 1e-3, 'sample') evoked.info.normalize_proj() sim = simulate_evoked(fwd, stc, evoked.info, cov=None, nave=np.inf) cov = make_ad_hoc_cov(evoked.info) dip = fit_dipole(sim, cov, bem, min_dist=0.001)[0] ds = [] for vi in range(n_vertices): if vi < len(vertices[0]): hi = 0 vertno = vi else: hi = 1 vertno = vi - len(vertices[0]) vertno = src[hi]['vertno'][vertno] rr = src[hi]['rr'][vertno] d = np.sqrt(np.sum((rr - dip.pos[vi])**2)) ds.append(d) # make sure that our median is sub-mm and the large majority are very # close (we expect some to be off by a bit e.g. because they are # radial) assert ((np.percentile(ds, [50, 90]) < [0.0005, perc_90]).all())
def test_to_data_frame(): """Test stc Pandas exporter.""" n_vert, n_times = 10, 5 vertices = [np.arange(n_vert, dtype=np.int), np.empty(0, dtype=np.int)] data = rng.randn(n_vert, n_times) stc_surf = SourceEstimate(data, vertices=vertices, tmin=0, tstep=1, subject='sample') stc_vol = VolSourceEstimate(data, vertices=vertices[0], tmin=0, tstep=1, subject='sample') for stc in [stc_surf, stc_vol]: df = stc.to_data_frame() # test data preservation (first 2 dataframe elements are subj & time) assert_array_equal(df.values.T[2:], stc.data) # test long format df_long = stc.to_data_frame(long_format=True) assert(len(df_long) == stc.data.size) expected = ('subject', 'time', 'source', 'value') assert set(expected) == set(df_long.columns)
def test_limits_to_control_points(): """Test functionality for determining control points.""" sample_src = read_source_spaces(src_fname) kwargs = dict(subjects_dir=subjects_dir, smoothing_steps=1) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.random.RandomState(0).rand((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') # Test for simple use cases mlab = _import_mlab() stc.plot(**kwargs) stc.plot(clim=dict(pos_lims=(10, 50, 90)), **kwargs) stc.plot(colormap='hot', clim='auto', **kwargs) stc.plot(colormap='mne', clim='auto', **kwargs) figs = [mlab.figure(), mlab.figure()] stc.plot(clim=dict(kind='value', lims=(10, 50, 90)), figure=99, **kwargs) pytest.raises(ValueError, stc.plot, clim='auto', figure=figs, **kwargs) # Test for correct clim values with pytest.raises(ValueError, match='monotonically'): stc.plot(clim=dict(kind='value', pos_lims=[0, 1, 0]), **kwargs) with pytest.raises(ValueError, match=r'.*must be \(3,\)'): stc.plot(colormap='mne', clim=dict(pos_lims=(5, 10, 15, 20)), **kwargs) with pytest.raises(ValueError, match="'value', 'values' and 'percent'"): stc.plot(clim=dict(pos_lims=(5, 10, 15), kind='foo'), **kwargs) with pytest.raises(ValueError, match='must be "auto" or dict'): stc.plot(colormap='mne', clim='foo', **kwargs) with pytest.raises(TypeError, match='must be an instance of'): plot_source_estimates('foo', clim='auto', **kwargs) with pytest.raises(ValueError, match='hemi'): stc.plot(hemi='foo', clim='auto', **kwargs) with pytest.raises(ValueError, match='Exactly one'): stc.plot(clim=dict(lims=[0, 1, 2], pos_lims=[0, 1, 2], kind='value'), **kwargs) # Test handling of degenerate data: thresholded maps stc._data.fill(0.) with pytest.warns(RuntimeWarning, match='All data were zero'): plot_source_estimates(stc, **kwargs) mlab.close(all=True)
def test_to_data_frame(): """Test stc Pandas exporter""" n_vert, n_times = 10, 5 vertices = [np.arange(n_vert, dtype=np.int), np.empty(0, dtype=np.int)] data = rng.randn(n_vert, n_times) stc_surf = SourceEstimate(data, vertices=vertices, tmin=0, tstep=1, subject='sample') stc_vol = VolSourceEstimate(data, vertices=vertices[0], tmin=0, tstep=1, subject='sample') for stc in [stc_surf, stc_vol]: assert_raises(ValueError, stc.to_data_frame, index=['foo', 'bar']) for ncat, ind in zip([1, 0], ['time', ['subject', 'time']]): df = stc.to_data_frame(index=ind) assert_true(df.index.names == ind if isinstance(ind, list) else [ind]) assert_array_equal(df.values.T[ncat:], stc.data) # test that non-indexed data were present as categorial variables assert_true(all([c in ['time', 'subject'] for c in df.reset_index().columns][:2]))
def test_simulate_round_trip(): """Test simulate_raw round trip calculations.""" # Check a diagonal round-trip raw, src, stc, trans, sphere = _get_data() raw.pick_types(meg=True, stim=True) bem = read_bem_solution(bem_1_fname) old_bem = bem.copy() old_src = src.copy() old_trans = trans.copy() fwd = make_forward_solution(raw.info, trans, src, bem) # no omissions assert (sum(len(s['vertno']) for s in src) == sum(len(s['vertno']) for s in fwd['src']) == 36) # make sure things were not modified assert ( old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) data = np.eye(fwd['nsource']) raw.crop(0, (len(data) - 1) / raw.info['sfreq']) stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0, 1. / raw.info['sfreq']) for use_cps in (False, True): this_raw = simulate_raw(raw, stc, trans, src, bem, cov=None, use_cps=use_cps) this_raw.pick_types(meg=True, eeg=True) assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0] ['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) this_fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=use_cps) assert_allclose(this_raw[:][0], this_fwd['sol']['data'], atol=1e-12, rtol=1e-6)
def _get_psf_ctf(resmat, src, idx, func='psf', norm=False): """Get point-spread (PSFs) or cross-talk (CTFs) functions for vertices. Parameters ---------- resmat : array, shape (n_dipoles, n_dipoles) Forward Operator. src : Source Space Source space used to compute resolution matrix. idx : list of int Vertex indices for which PSFs or CTFs to produce. func : str ('psf' | 'ctf') Whether to produce PSFs or CTFs. Defaults to psf. norm : bool Whether to normalise to maximum across all PSFs and CTFs (default: False) Returns ------- stc: instance of SourceEstimate PSFs or CTFs as an stc object. """ # vertices used in forward and inverse operator vertno_lh = src[0]['vertno'] vertno_rh = src[1]['vertno'] vertno = [vertno_lh, vertno_rh] # in everything below indices refer to columns if func == 'ctf': resmat = resmat.T # column of resolution matrix funcs = resmat[:, idx] if norm: maxval = np.abs(funcs).max() funcs = funcs / maxval # convert to source estimate stc = SourceEstimate(funcs, vertno, tmin=0., tstep=1.) return stc
def test_sparse_morph(): """Test sparse morphing.""" rng = np.random.RandomState(0) vertices_fs = [np.sort(rng.permutation(np.arange(10242))[:4]), np.sort(rng.permutation(np.arange(10242))[:6])] data = rng.randn(10, 1) stc_fs = SourceEstimate(data, vertices_fs, 1, 1, 'fsaverage') spheres_fs = [mne.read_surface(op.join( subjects_dir, 'fsaverage', 'surf', '%s.sphere.reg' % hemi))[0] for hemi in ('lh', 'rh')] spheres_sample = [mne.read_surface(op.join( subjects_dir, 'sample', 'surf', '%s.sphere.reg' % hemi))[0] for hemi in ('lh', 'rh')] morph_fs_sample = compute_source_morph( stc_fs, 'fsaverage', 'sample', sparse=True, spacing=None, subjects_dir=subjects_dir) stc_sample = morph_fs_sample.apply(stc_fs) offset = 0 orders = list() for v1, s1, v2, s2 in zip(stc_fs.vertices, spheres_fs, stc_sample.vertices, spheres_sample): dists = cdist(s1[v1], s2[v2]) order = np.argmin(dists, axis=-1) assert_array_less(dists[np.arange(len(order)), order], 1.5) # mm orders.append(order + offset) offset += len(order) assert_allclose(stc_fs.data, stc_sample.data[np.concatenate(orders)]) # Return morph_sample_fs = compute_source_morph( stc_sample, 'sample', 'fsaverage', sparse=True, spacing=None, subjects_dir=subjects_dir) stc_fs_return = morph_sample_fs.apply(stc_sample) offset = 0 orders = list() for v1, s, v2 in zip(stc_fs.vertices, spheres_fs, stc_fs_return.vertices): dists = cdist(s[v1], s[v2]) order = np.argmin(dists, axis=-1) assert_array_less(dists[np.arange(len(order)), order], 1.5) # mm orders.append(order + offset) offset += len(order) assert_allclose(stc_fs.data, stc_fs_return.data[np.concatenate(orders)])
def test_plot_volume_source_estimates_morph(): """Test interactive plotting of volume source estimates with morph.""" forward = read_forward_solution(fwd_fname) sample_src = forward['src'] vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) n_time = 2 data = np.random.RandomState(0).rand(n_verts, n_time) stc = VolSourceEstimate(data, vertices, 1, 1) sample_src[0]['subject_his_id'] = 'sample' # old src morph = compute_source_morph(sample_src, 'sample', 'fsaverage', zooms=5, subjects_dir=subjects_dir) initial_pos = (-0.05, -0.01, -0.006) # sometimes get scalars/index warning with _record_warnings(): with catch_logging() as log: stc.plot(morph, subjects_dir=subjects_dir, mode='glass_brain', initial_pos=initial_pos, verbose=True) log = log.getvalue() assert 't = 1.000 s' in log assert '(-52.0, -8.0, -7.0) mm' in log with pytest.raises(ValueError, match='Allowed values are'): stc.plot(sample_src, 'sample', subjects_dir, mode='abcd') vertices.append([]) surface_stc = SourceEstimate(data, vertices, 1, 1) with pytest.raises(TypeError, match='an instance of VolSourceEstimate'): plot_volume_source_estimates(surface_stc, sample_src, 'sample', subjects_dir) with pytest.raises(ValueError, match='Negative colormap limits'): stc.plot(sample_src, 'sample', subjects_dir, clim=dict(lims=[-1, 2, 3], kind='value'))
def _export_to_stc(inv_op, subject=None): if not hasattr(inv_op, 'pmap'): raise AttributeError('Run the inversion algorithm first!!') pmaps = inv_op.pmap fwd = inv_op.forward est_n_dips = inv_op.est_n_dips vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] nv_tot = fwd['nsource'] pmap_tot = np.zeros([len(pmaps), nv_tot]) for it, bl in enumerate(pmaps): if est_n_dips[it] > 0: pmap_tot[it] = np.sum(bl, axis=0) tmin = 1 stc = SourceEstimate(data=pmap_tot.T, vertices=vertno, tmin=tmin, tstep=1, subject=subject) return stc
def test_link_brains(renderer): """Test plotting linked brains.""" if renderer.get_3d_backend() == "mayavi": pytest.skip() # Skip PySurfer.TimeViewer elif renderer.get_3d_backend() == "pyvista": # Widgets are not available offscreen import pyvista orig_offscreen = pyvista.OFF_SCREEN pyvista.OFF_SCREEN = False # Disable testing to allow interactive window renderer.MNE_3D_BACKEND_TESTING = False with pytest.raises(ValueError, match='is empty'): link_brains([]) with pytest.raises(TypeError, match='type is Brain'): link_brains('foo') sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(np.random.rand(stc_size // 20) * stc_size).astype(int)] = \ np.random.RandomState(0).rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1) colormap = 'mne_analyze' brain = plot_source_estimates(stc, 'sample', colormap=colormap, background=(1, 1, 0), subjects_dir=subjects_dir, colorbar=True, clim='auto') link_brains(brain) if renderer.get_3d_backend() == "pyvista": pyvista.OFF_SCREEN = orig_offscreen
def get_fsaverage_label_operator(parc='aparc.a2009s', remove_bads=True, combine_medial=False, return_labels=False, subjects_dir=None, verbose=None): """Get a label operator matrix for fsaverage.""" subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) src = read_source_spaces(op.join( subjects_dir, 'fsaverage', 'bem', 'fsaverage-5-src.fif'), verbose=False) fs_vertices = [np.arange(10242), np.arange(10242)] assert all(np.array_equal(a['vertno'], b) for a, b in zip(src, fs_vertices)) labels = read_labels_from_annot('fsaverage', parc) # Remove bad labels if remove_bads: bads = get_fsaverage_medial_vertices(False) bads = dict(lh=bads[0], rh=bads[1]) assert all(b.size > 1 for b in bads.values()) labels = [label for label in labels if np.in1d(label.vertices, bads[label.hemi]).mean() < 0.8] del bads if combine_medial: labels = combine_medial_labels(labels) offsets = dict(lh=0, rh=10242) rev_op = np.zeros((20484, len(labels))) for li, label in enumerate(labels): if isinstance(label, BiHemiLabel): use_labels = [label.lh, label.rh] else: use_labels = [label] for ll in use_labels: rev_op[ll.get_vertices_used() + offsets[ll.hemi], li:li + 1] = 1. # every src vertex is in exactly one label, except medial wall verts # assert (rev_op.sum(-1) == 1).sum() label_op = SourceEstimate(np.eye(20484), fs_vertices, 0, 1) label_op = label_op.extract_label_time_course(labels, src) out = (label_op, rev_op) if return_labels: out += (labels,) return out
def test_plot_volume_source_estimates(): """Test interactive plotting of volume source estimates.""" forward = read_forward_solution(fwd_fname) sample_src = forward['src'] vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) n_time = 2 data = np.random.RandomState(0).rand(n_verts, n_time) vol_stc = VolSourceEstimate(data, vertices, 1, 1) vol_vec_stc = VolVectorSourceEstimate( np.tile(vol_stc.data[:, np.newaxis], (1, 3, 1)), vol_stc.vertices, 0, 1) for mode, stc in zip(['glass_brain', 'stat_map'], (vol_stc, vol_vec_stc)): with pytest.warns(None): # sometimes get scalars/index warning fig = stc.plot(sample_src, subject='sample', subjects_dir=subjects_dir, mode=mode) # [ax_time, ax_y, ax_x, ax_z] for ax_idx in [0, 2, 3, 4]: _fake_click(fig, fig.axes[ax_idx], (0.3, 0.5)) fig.canvas.key_press_event('left') fig.canvas.key_press_event('shift+right') with pytest.raises(ValueError, match='must be one of'): vol_stc.plot(sample_src, 'sample', subjects_dir, mode='abcd') vertices.append([]) surface_stc = SourceEstimate(data, vertices, 1, 1) with pytest.raises(ValueError, match='Only Vol'): plot_volume_source_estimates(surface_stc, sample_src, 'sample', subjects_dir) with pytest.raises(ValueError, match='Negative colormap limits'): vol_stc.plot(sample_src, 'sample', subjects_dir, clim=dict(lims=[-1, 2, 3], kind='value'))
def get_Tpermutation_distribution(dat_all, nperm, timeAll, labels): time_start = timeAll[0][0] time_end = timeAll[-1][1] dat = dat_all[:, :, int(time_start * 1000) + 100:int(time_end * 1000) + 100] # permuta the data and calculate the largest sumed p values for each permutation across labels highest_permutation_values = [] sign = np.ones((dat.shape[0], )) sign[:np.int32(np.round(len(sign) / 2.))] = -1 for index in range(nperm): #to permute the conditions print("permution: " + str(index)) sign = np.random.permutation(sign) dat_perm = sign * np.transpose(dat, [1, 2, 0]) stats_perm, pval_perm = ttest_1samp(dat_perm, 0, axis=2) stc_perm = SourceEstimate( -np.log10(pval_perm), vertices=[np.arange(10242), np.arange(10242)], tmin=time_start, tstep=1 / 1000., subject='fsaverage') means_of_thresholded_timewinds_labels = [] for time1, time2 in timeAll: stc_perm_timewind = stc_perm.copy().crop(time1, time2) for label in labels: label_fname = op.join( '/autofs/cluster/kuperberg/nonconMM/MEG/MNE/250Labels', label + '.label') label_name = mne.read_label(label_fname, subject='fsaverage', color='r') stc_label_perm = stc_perm_timewind.in_label(label_name) stc_label_perm = threshold_by_pvalue(stc_label_perm, 2) means_of_thresholded_timewinds_labels.append( stc_label_perm.data.mean()) highest_permutation_values.append( max(means_of_thresholded_timewinds_labels)) return highest_permutation_values
def to_stc(self, subject=None): """Export results in .stc file Parameters ---------- file_name : str Path and name of the file to be saved fwd : dict Forward structure from which the lead-field matrix and the source space were been extracted it_in and it_fin : int First and last iteration to be saved subject : str Name of the subject """ if 'SourceEstimate' not in dir(): from mne import SourceEstimate if not hasattr(self, 'blob'): raise AttributeError('Run filter first!!') # TODO: fwd is already saved in _sasmc blobs = self.blob fwd = self.forward vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] nv_tot = fwd['nsource'] blob_tot = np.array([np.sum(bl, axis=0) for bl in blobs[1:]]) # I don't store first iteration which is always empty tmin = 1 stc = SourceEstimate(data=blob_tot.T, vertices=vertno, tmin=tmin, tstep=1, subject=subject) return stc
def tiny(tmp_path): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' (tmp_path / subject).mkdir() subject_dir = tmp_path / subject (subject_dir / 'surf').mkdir() surf_dir = subject_dir / 'surf' rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir / 'lh.curv', 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir / 'lh.white', rr, tris) write_surface(surf_dir / 'rh.white', rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmp_path, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio
def test_extract_label_time_course(): """Test extraction of label time courses from stc """ n_stcs = 3 n_times = 50 src = read_inverse_operator(fname_inv)['src'] vertices = [src[0]['vertno'], src[1]['vertno']] n_verts = len(vertices[0]) + len(vertices[1]) # get some labels labels_lh = read_labels_from_annot('sample', hemi='lh', subjects_dir=subjects_dir) labels_rh = read_labels_from_annot('sample', hemi='rh', subjects_dir=subjects_dir) labels = list() labels.extend(labels_lh[:5]) labels.extend(labels_rh[:4]) n_labels = len(labels) label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) label_maxs = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times)) # compute the mean with sign flip label_means_flipped = np.zeros_like(label_means) for i, label in enumerate(labels): label_means_flipped[i] = i * np.mean(label_sign_flip(label, src)) # generate some stc's with known data stcs = list() for i in range(n_stcs): data = np.zeros((n_verts, n_times)) # set the value of the stc within each label for j, label in enumerate(labels): if label.hemi == 'lh': idx = np.intersect1d(vertices[0], label.vertices) idx = np.searchsorted(vertices[0], idx) elif label.hemi == 'rh': idx = np.intersect1d(vertices[1], label.vertices) idx = len(vertices[0]) + np.searchsorted(vertices[1], idx) data[idx] = label_means[j] this_stc = SourceEstimate(data, vertices, 0, 1) stcs.append(this_stc) # test some invalid inputs assert_raises(ValueError, extract_label_time_course, stcs, labels, src, mode='notamode') # have an empty label empty_label = labels[0].copy() empty_label.vertices += 1000000 assert_raises(ValueError, extract_label_time_course, stcs, empty_label, src, mode='mean') # but this works: tc = extract_label_time_course(stcs, empty_label, src, mode='mean', allow_empty=True) for arr in tc: assert_true(arr.shape == (1, n_times)) assert_array_equal(arr, np.zeros((1, n_times))) # test the different modes modes = ['mean', 'mean_flip', 'pca_flip', 'max'] for mode in modes: label_tc = extract_label_time_course(stcs, labels, src, mode=mode) label_tc_method = [ stc.extract_label_time_course(labels, src, mode=mode) for stc in stcs ] assert_true(len(label_tc) == n_stcs) assert_true(len(label_tc_method) == n_stcs) for tc1, tc2 in zip(label_tc, label_tc_method): assert_true(tc1.shape == (n_labels, n_times)) assert_true(tc2.shape == (n_labels, n_times)) assert_true(np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16)) if mode == 'mean': assert_array_almost_equal(tc1, label_means) if mode == 'mean_flip': assert_array_almost_equal(tc1, label_means_flipped) if mode == 'max': assert_array_almost_equal(tc1, label_maxs) # test label with very few vertices (check SVD conditionals) label = Label(vertices=src[0]['vertno'][:2], hemi='lh') x = label_sign_flip(label, src) assert_true(len(x) == 2) label = Label(vertices=[], hemi='lh') x = label_sign_flip(label, src) assert_true(x.size == 0)
def _fake_stc(n_time=10): verts = [np.arange(10), np.arange(90)] return SourceEstimate(np.random.rand(100, n_time), verts, 0, 1e-1, 'foo')
def test_morphed_source_space_return(): """Test returning a morphed source space to the original subject.""" # let's create some random data on fsaverage data = rng.randn(20484, 1) tmin, tstep = 0, 1. src_fs = read_source_spaces(fname_fs) stc_fs = SourceEstimate(data, [s['vertno'] for s in src_fs], tmin, tstep, 'fsaverage') n_verts_fs = sum(len(s['vertno']) for s in src_fs) # Create our morph source space src_morph = morph_source_spaces(src_fs, 'sample', subjects_dir=subjects_dir) n_verts_sample = sum(len(s['vertno']) for s in src_morph) assert n_verts_fs == n_verts_sample # Morph the data over using standard methods stc_morph = compute_source_morph(src_fs, 'fsaverage', 'sample', spacing=[s['vertno'] for s in src_morph], smooth=1, subjects_dir=subjects_dir, warn=False).apply(stc_fs) assert stc_morph.data.shape[0] == n_verts_sample # We can now pretend like this was real data we got e.g. from an inverse. # To be complete, let's remove some vertices keeps = [ np.sort(rng.permutation(np.arange(len(v)))[:len(v) - 10]) for v in stc_morph.vertices ] stc_morph = SourceEstimate( np.concatenate([ stc_morph.lh_data[keeps[0]], stc_morph.rh_data[keeps[1]] ]), [v[k] for v, k in zip(stc_morph.vertices, keeps)], tmin, tstep, 'sample') # Return it to the original subject stc_morph_return = stc_morph.to_original_src(src_fs, subjects_dir=subjects_dir) # This should fail (has too many verts in SourceMorph) with pytest.warns(RuntimeWarning, match='vertices not included'): morph = compute_source_morph(src_morph, subject_from='sample', spacing=stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='vertices do not match'): morph.apply(stc_morph) # Compare to the original data with pytest.warns(RuntimeWarning, match='vertices not included'): stc_morph_morph = compute_source_morph( src=stc_morph, subject_from='sample', spacing=stc_morph_return.vertices, smooth=1, subjects_dir=subjects_dir).apply(stc_morph) assert_equal(stc_morph_return.subject, stc_morph_morph.subject) for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Explicitly test having two vertices map to the same target vertex. We # simulate this by having two vertices be at the same position. src_fs2 = src_fs.copy() vert1, vert2 = src_fs2[0]['vertno'][:2] src_fs2[0]['rr'][vert1] = src_fs2[0]['rr'][vert2] stc_morph_return = stc_morph.to_original_src(src_fs2, subjects_dir=subjects_dir) # test to_original_src method result equality for ii in range(2): assert_array_equal(stc_morph_return.vertices[ii], stc_morph_morph.vertices[ii]) # These will not match perfectly because morphing pushes data around corr = np.corrcoef(stc_morph_return.data[:, 0], stc_morph_morph.data[:, 0])[0, 1] assert corr > 0.99, corr # Degenerate cases stc_morph.subject = None # no .subject provided pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='fsaverage', subjects_dir=subjects_dir) stc_morph.subject = 'sample' del src_fs[0]['subject_his_id'] # no name in src_fsaverage pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'fsaverage' # name mismatch pytest.raises(ValueError, stc_morph.to_original_src, src_fs, subject_orig='foo', subjects_dir=subjects_dir) src_fs[0]['subject_his_id'] = 'sample' src = read_source_spaces(fname) # wrong source space pytest.raises(RuntimeError, stc_morph.to_original_src, src, subjects_dir=subjects_dir)
def test_simulate_round_trip(raw_data): """Test simulate_raw round trip calculations.""" # Check a diagonal round-trip raw, src, stc, trans, sphere = raw_data raw.pick_types(meg=True, stim=True) bem = read_bem_solution(bem_1_fname) old_bem = bem.copy() old_src = src.copy() old_trans = trans.copy() fwd = make_forward_solution(raw.info, trans, src, bem) # no omissions assert (sum(len(s['vertno']) for s in src) == sum(len(s['vertno']) for s in fwd['src']) == 36) # make sure things were not modified assert ( old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0]['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) data = np.eye(fwd['nsource']) raw.crop(0, (len(data) - 1) / raw.info['sfreq']) stc = SourceEstimate(data, [s['vertno'] for s in fwd['src']], 0, 1. / raw.info['sfreq']) for use_fwd in (None, fwd): if use_fwd is None: use_trans, use_src, use_bem = trans, src, bem else: use_trans = use_src = use_bem = None with pytest.deprecated_call(): this_raw = simulate_raw(raw, stc, use_trans, use_src, use_bem, cov=None, forward=use_fwd) this_raw.pick_types(meg=True, eeg=True) assert (old_bem['surfs'][0]['coord_frame'] == bem['surfs'][0] ['coord_frame']) assert trans == old_trans _compare_source_spaces(src, old_src) this_fwd = convert_forward_solution(fwd, force_fixed=True) assert_allclose(this_raw[:][0], this_fwd['sol']['data'], atol=1e-12, rtol=1e-6) with pytest.raises(ValueError, match='If forward is not None then'): simulate_raw(raw.info, stc, trans, src, bem, forward=fwd) # Not iterable with pytest.raises(TypeError, match='SourceEstimate, tuple, or iterable'): simulate_raw(raw.info, 0., trans, src, bem, None) # STC with a source that `src` does not have assert 0 not in src[0]['vertno'] vertices = [[0, fwd['src'][0]['vertno'][0]], []] stc_bad = SourceEstimate(data[:2], vertices, 0, 1. / raw.info['sfreq']) with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, trans, src, bem) assert 0 not in fwd['src'][0]['vertno'] with pytest.warns(RuntimeWarning, match='1 of 2 SourceEstimate vertices'): simulate_raw(raw.info, stc_bad, None, None, None, forward=fwd) # dev_head_t mismatch fwd['info']['dev_head_t']['trans'][0, 0] = 1. with pytest.raises(ValueError, match='dev_head_t.*does not match'): simulate_raw(raw.info, stc, None, None, None, forward=fwd)
def test_limits_to_control_points(): """Test functionality for determing control points.""" sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.random.RandomState(0).rand((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') # Test for simple use cases mlab = _import_mlab() stc.plot(subjects_dir=subjects_dir) stc.plot(clim=dict(pos_lims=(10, 50, 90)), subjects_dir=subjects_dir) stc.plot(clim=dict(kind='value', lims=(10, 50, 90)), figure=99, subjects_dir=subjects_dir) stc.plot(colormap='hot', clim='auto', subjects_dir=subjects_dir) stc.plot(colormap='mne', clim='auto', subjects_dir=subjects_dir) figs = [mlab.figure(), mlab.figure()] assert_raises(ValueError, stc.plot, clim='auto', figure=figs, subjects_dir=subjects_dir) # Test both types of incorrect limits key (lims/pos_lims) assert_raises(KeyError, plot_source_estimates, stc, colormap='mne', clim=dict(kind='value', lims=(5, 10, 15)), subjects_dir=subjects_dir) assert_raises(KeyError, plot_source_estimates, stc, colormap='hot', clim=dict(kind='value', pos_lims=(5, 10, 15)), subjects_dir=subjects_dir) # Test for correct clim values assert_raises(ValueError, stc.plot, clim=dict(kind='value', pos_lims=[0, 1, 0]), subjects_dir=subjects_dir) assert_raises(ValueError, stc.plot, colormap='mne', clim=dict(pos_lims=(5, 10, 15, 20)), subjects_dir=subjects_dir) assert_raises(ValueError, stc.plot, clim=dict(pos_lims=(5, 10, 15), kind='foo'), subjects_dir=subjects_dir) assert_raises(ValueError, stc.plot, colormap='mne', clim='foo', subjects_dir=subjects_dir) assert_raises(ValueError, stc.plot, clim=(5, 10, 15), subjects_dir=subjects_dir) assert_raises(ValueError, plot_source_estimates, 'foo', clim='auto', subjects_dir=subjects_dir) assert_raises(ValueError, stc.plot, hemi='foo', clim='auto', subjects_dir=subjects_dir) # Test handling of degenerate data stc.plot(clim=dict(kind='value', lims=[0, 0, 1]), subjects_dir=subjects_dir) # ok with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # thresholded maps stc._data.fill(1.) plot_source_estimates(stc, subjects_dir=subjects_dir, time_unit='s') assert_equal(len(w), 0) stc._data[0].fill(0.) plot_source_estimates(stc, subjects_dir=subjects_dir, time_unit='s') assert_equal(len(w), 0) stc._data.fill(0.) plot_source_estimates(stc, subjects_dir=subjects_dir, time_unit='s') assert_equal(len(w), 1) mlab.close(all=True)
def test_dipole_fitting(): """Test dipole fitting.""" amp = 100e-9 tempdir = _TempDir() rng = np.random.RandomState(0) fname_dtemp = op.join(tempdir, 'test.dip') fname_sim = op.join(tempdir, 'test-ave.fif') fwd = convert_forward_solution(read_forward_solution(fname_fwd), surf_ori=False, force_fixed=True, use_cps=True) evoked = read_evokeds(fname_evo)[0] cov = read_cov(fname_cov) n_per_hemi = 5 vertices = [ np.sort(rng.permutation(s['vertno'])[:n_per_hemi]) for s in fwd['src'] ] nv = sum(len(v) for v in vertices) stc = SourceEstimate(amp * np.eye(nv), vertices, 0, 0.001) evoked = simulate_evoked(fwd, stc, evoked.info, cov, nave=evoked.nave, random_state=rng) # For speed, let's use a subset of channels (strange but works) picks = np.sort( np.concatenate([ pick_types(evoked.info, meg=True, eeg=False)[::2], pick_types(evoked.info, meg=False, eeg=True)[::2] ])) evoked.pick_channels([evoked.ch_names[p] for p in picks]) evoked.add_proj(make_eeg_average_ref_proj(evoked.info)) write_evokeds(fname_sim, evoked) # Run MNE-C version run_subprocess([ 'mne_dipole_fit', '--meas', fname_sim, '--meg', '--eeg', '--noise', fname_cov, '--dip', fname_dtemp, '--mri', fname_fwd, '--reg', '0', '--tmin', '0', ]) dip_c = read_dipole(fname_dtemp) # Run mne-python version sphere = make_sphere_model(head_radius=0.1) with pytest.warns(RuntimeWarning, match='projection'): dip, residuals = fit_dipole(evoked, cov, sphere, fname_fwd) # Sanity check: do our residuals have less power than orig data? data_rms = np.sqrt(np.sum(evoked.data**2, axis=0)) resi_rms = np.sqrt(np.sum(residuals**2, axis=0)) assert (data_rms > resi_rms * 0.95).all(), \ '%s (factor: %s)' % ((data_rms / resi_rms).min(), 0.95) # Compare to original points transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t']) transform_surface_to(fwd['src'][1], 'head', fwd['mri_head_t']) assert_equal(fwd['src'][0]['coord_frame'], FIFF.FIFFV_COORD_HEAD) src_rr = np.concatenate([s['rr'][v] for s, v in zip(fwd['src'], vertices)], axis=0) src_nn = np.concatenate([s['nn'][v] for s, v in zip(fwd['src'], vertices)], axis=0) # MNE-C skips the last "time" point :( out = dip.crop(dip_c.times[0], dip_c.times[-1]) assert (dip is out) src_rr, src_nn = src_rr[:-1], src_nn[:-1] # check that we did about as well corrs, dists, gc_dists, amp_errs, gofs = [], [], [], [], [] for d in (dip_c, dip): new = d.pos diffs = new - src_rr corrs += [np.corrcoef(src_rr.ravel(), new.ravel())[0, 1]] dists += [np.sqrt(np.mean(np.sum(diffs * diffs, axis=1)))] gc_dists += [ 180 / np.pi * np.mean(np.arccos(np.sum(src_nn * d.ori, axis=1))) ] amp_errs += [np.sqrt(np.mean((amp - d.amplitude)**2))] gofs += [np.mean(d.gof)] if os.getenv('TRAVIS', 'false').lower() == 'true' and \ 'OPENBLAS_NUM_THREADS' in os.environ: # XXX possibly some OpenBLAS numerical differences make # things slightly worse for us factor = 0.7 else: factor = 0.8 assert dists[0] / factor >= dists[1], 'dists: %s' % dists assert corrs[0] * factor <= corrs[1], 'corrs: %s' % corrs assert gc_dists[0] / factor >= gc_dists[1] * 0.8, \ 'gc-dists (ori): %s' % gc_dists assert amp_errs[0] / factor >= amp_errs[1],\ 'amplitude errors: %s' % amp_errs # This one is weird because our cov/sim/picking is weird assert gofs[0] * factor <= gofs[1] * 2, 'gof: %s' % gofs