def make_dipole_projectors(info, pos, ori, bem, trans, verbose=None): """Make dipole projectors. Parameters ---------- info : instance of Info The measurement info. pos : ndarray, shape (n_dip, 3) The dipole positions. ori : ndarray, shape (n_dip, 3) The dipole orientations. bem : instance of ConductorModel The conductor model to use. trans : instance of Transform The mri-to-head transformation. %(verbose)s Returns ------- projs : list of Projection The projectors. """ pos = np.atleast_2d(pos).astype(float) ori = np.atleast_2d(ori).astype(float) if pos.shape[1] != 3 or pos.shape != ori.shape: raise ValueError('pos and ori must be 2D, the same shape, and have ' f'last dimension 3, got {pos.shape} and {ori.shape}') dip = Dipole(pos=pos, ori=ori, amplitude=np.ones(pos.shape[0]), gof=np.ones(pos.shape[0]), times=np.arange(pos.shape[0])) info = pick_info(info, pick_types(info, meg=True, eeg=True, exclude=())) fwd, _ = make_forward_dipole(dip, bem, info, trans) assert fwd['sol']['data'].shape[1] == pos.shape[0] projs = list() for kind in ('meg', 'eeg'): kwargs = dict(meg=False, eeg=False, exclude=()) kwargs.update({kind: True}) picks = pick_types(info, **kwargs) if len(picks) > 0: ch_names = [info['ch_names'][pick] for pick in picks] projs.extend([ Projection(data=dict(data=p[np.newaxis, picks], row_names=None, nrow=1, col_names=list(ch_names), ncol=len(ch_names)), kind=FIFF.FIFFV_PROJ_ITEM_DIP_FIX, explained_var=None, active=False, desc=f'Dipole #{pi}') for pi, p in enumerate(fwd['sol']['data'].T, 1) ]) return projs
def test_io_dipoles(): """Test IO for .dip files """ tempdir = _TempDir() out_fname = op.join(tempdir, 'temp.dip') with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') times, pos, amplitude, ori, gof = read_dip(fname_dip) assert_true(len(w) >= 1) assert_true(pos.shape[1] == 3) assert_true(ori.shape[1] == 3) assert_true(len(times) == len(pos)) assert_true(len(times) == gof.size) assert_true(len(times) == amplitude.size) dipole = Dipole(times, pos, amplitude, ori, gof, 'ALL') print(dipole) # test repr dipole.save(out_fname) dipole_new = read_dipole(out_fname) _compare_dipoles(dipole, dipole_new)
def test_simulate_calculate_chpi_positions(): """Test calculation of cHPI positions with simulated data.""" # Read info dict from raw FIF file info = read_info(raw_fname) # Tune the info structure chpi_channel = u'STI201' ncoil = len(info['hpi_results'][0]['order']) coil_freq = 10 + np.arange(ncoil) * 5 hpi_subsystem = { 'event_channel': chpi_channel, 'hpi_coils': [{ 'event_bits': np.array([256, 0, 256, 256], dtype=np.int32) }, { 'event_bits': np.array([512, 0, 512, 512], dtype=np.int32) }, { 'event_bits': np.array([1024, 0, 1024, 1024], dtype=np.int32) }, { 'event_bits': np.array([2048, 0, 2048, 2048], dtype=np.int32) }], 'ncoil': ncoil } info['hpi_subsystem'] = hpi_subsystem for l, freq in enumerate(coil_freq): info['hpi_meas'][0]['hpi_coils'][l]['coil_freq'] = freq picks = pick_types(info, meg=True, stim=True, eeg=False, exclude=[]) info['sfreq'] = 100. # this will speed it up a lot info = pick_info(info, picks) info['chs'][info['ch_names'].index('STI 001')]['ch_name'] = 'STI201' info._update_redundant() info['projs'] = [] info_trans = info['dev_head_t']['trans'].copy() dev_head_pos_ini = np.concatenate( [rot_to_quat(info_trans[:3, :3]), info_trans[:3, 3]]) ez = np.array([0, 0, 1]) # Unit vector in z-direction of head coordinates # Define some constants duration = 30 # Time / s # Quotient of head position sampling frequency # and raw sampling frequency head_pos_sfreq_quotient = 0.1 # Round number of head positions to the next integer S = int(duration / (info['sfreq'] * head_pos_sfreq_quotient)) dz = 0.001 # Shift in z-direction is 0.1mm for each step dev_head_pos = np.zeros((S, 10)) dev_head_pos[:, 0] = np.arange(S) * info['sfreq'] * head_pos_sfreq_quotient dev_head_pos[:, 1:4] = dev_head_pos_ini[:3] dev_head_pos[:, 4:7] = dev_head_pos_ini[3:] + \ np.outer(np.arange(S) * dz, ez) dev_head_pos[:, 7] = 1.0 # cm/s dev_head_pos[:, 9] = 100 * dz / (info['sfreq'] * head_pos_sfreq_quotient) # Round number of samples to the next integer raw_data = np.zeros((len(picks), int(duration * info['sfreq'] + 0.5))) raw = RawArray(raw_data, info) dip = Dipole(np.array([0.0, 0.1, 0.2]), np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), np.array([1e-9, 1e-9, 1e-9]), np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), np.array([1.0, 1.0, 1.0]), 'dip') sphere = make_sphere_model('auto', 'auto', info=info, relative_radii=(1.0, 0.9), sigmas=(0.33, 0.3)) fwd, stc = make_forward_dipole(dip, sphere, info) stc.resample(info['sfreq']) raw = simulate_raw(raw, stc, None, fwd['src'], sphere, cov=None, blink=False, ecg=False, chpi=True, head_pos=dev_head_pos, mindist=1.0, interp='zero', verbose=None) quats = _calculate_chpi_positions( raw, t_step_min=raw.info['sfreq'] * head_pos_sfreq_quotient, t_step_max=raw.info['sfreq'] * head_pos_sfreq_quotient, t_window=1.0) _assert_quats(quats, dev_head_pos, dist_tol=0.001, angle_tol=1.)
def test_brain_init(renderer_pyvistaqt, tmp_path, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(ValueError, match='.*hemi.*Allowed values.*'): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(ValueError, match='.*view.*Allowed values.*'): Brain(hemi='lh', surf=surf, views='foo', **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) with pytest.raises(FileNotFoundError, match=r'lh\.whatever'): Brain(subject_id, 'lh', 'whatever') with pytest.raises(ValueError, match='`surf` cannot be seghead'): Brain(hemi='lh', surf='seghead', **kwargs) with pytest.raises(ValueError, match='RGB argument'): Brain('sample', cortex='badcolor') Brain(subject_id, hemi=None, surf=None) # test no surfaces renderer_pyvistaqt.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) assert 'data' not in brain._actors with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='Invalid.*hemi.*Allowed'): brain._check_hemi(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh', ) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) assert len(brain._actors['data']) == 4 brain.remove_data() assert 'data' not in brain._actors # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add head and skull brain.add_head(color='red', alpha=0.1) brain.remove_head() brain.add_skull(outer=True, color='green', alpha=0.1) brain.remove_skull() # add volume labels brain.add_volume_labels(aseg='aseg', labels=('Brain-Stem', 'Left-Hippocampus', 'Left-Amygdala')) brain.remove_volume_labels() # add sensors info = read_info(fname_raw_testing) brain.add_sensors(info, trans=fname_trans) for kind in ('meg', 'eeg', 'fnirs', 'ecog', 'seeg', 'dbs', 'helmet'): brain.remove_sensors(kind) brain.add_sensors(info, trans=fname_trans) brain.remove_sensors() info['chs'][0]['coord_frame'] = 99 with pytest.raises(RuntimeError, match='must be "meg", "head" or "mri"'): brain.add_sensors(info, trans=fname_trans) # add dipole dip = Dipole(times=[0], pos=[[-0.06439933, 0.00733009, 0.06280205]], amplitude=[3e-8], ori=[[0, 1, 0]], gof=50) brain.add_dipole(dip, fname_trans, colors='blue', scales=5, alpha=0.5) brain.remove_dipole() with pytest.raises(ValueError, match='The number of colors'): brain.add_dipole(dip, fname_trans, colors=['red', 'blue']) with pytest.raises(ValueError, match='The number of scales'): brain.add_dipole(dip, fname_trans, scales=[1, 2]) fwd = read_forward_solution(fname_fwd) brain.add_forward(fwd, fname_trans, alpha=0.5, scale=10) brain.remove_forward() # fake incorrect coordinate frame fwd['coord_frame'] = 99 with pytest.raises(RuntimeError, match='must be "head" or "mri"'): brain.add_forward(fwd, fname_trans) fwd['coord_frame'] = 2003 with pytest.raises(RuntimeError, match='must be "head" or "mri"'): brain.add_forward(fwd, fname_trans) # add text brain.add_text(x=0, y=0, text='foo') with pytest.raises(ValueError, match='already exists'): brain.add_text(x=0, y=0, text='foo') brain.remove_text('foo') brain.add_text(x=0, y=0, text='foo') brain.remove_text() brain.close() # add annotation annots = [ 'aparc', op.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot') ] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) view_args = dict(roll=1, distance=500, focalpoint=(1e-5, 1e-5, 1e-5)) cam = brain._renderer.figure.plotter.camera previous_roll = cam.GetRoll() brain.show_view(**view_args) assert_allclose(cam.GetFocalPoint(), view_args["focalpoint"]) assert_allclose(cam.GetDistance(), view_args["distance"]) assert_allclose(cam.GetRoll(), previous_roll + view_args["roll"]) del view_args # image and screenshot fname = op.join(str(tmp_path), 'test.png') assert not op.isfile(fname) brain.save_image(fname) assert op.isfile(fname) fp = np.array( brain._renderer.figure.plotter.renderer.ComputeVisiblePropBounds()) fp = (fp[1::2] + fp[::2]) * 0.5 azimuth, elevation = 180., 90. for view_args in (dict(azimuth=azimuth, elevation=elevation, focalpoint='auto'), dict(view='lateral', hemi='lh')): brain.show_view(**view_args) assert_allclose(brain._renderer.figure._azimuth, azimuth) assert_allclose(brain._renderer.figure._elevation, elevation) assert_allclose(cam.GetFocalPoint(), fp) del view_args img = brain.screenshot(mode='rgba') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 4]) assert_allclose(img.shape, want_size) brain.close()