def gen_ras_to_head_trans(head_to_mri_t, t1_img): # RAS -> VOXEL ras_to_vox_t = Transform(fro='ras', to='mri_voxel', trans=np.linalg.inv(t1_img.header.get_vox2ras())) # VOXEL -> MRI vox_to_mri_t = Transform(fro='mri_voxel', to='mri', trans=t1_img.header.get_vox2ras_tkr()) # MRI -> HEAD mri_to_head_t = invert_transform(head_to_mri_t) # Now we have generated all the required transformations # to go from RAS to MNE Head coordinates. Let's combine # the transforms into a single transform. This requires # two calls to `combine_transforms()`. # RAS -> MRI ras_to_mri_t = combine_transforms(ras_to_vox_t, vox_to_mri_t, fro='ras', to='mri') # RAS -> HEAD ras_to_head_t = combine_transforms(ras_to_mri_t, mri_to_head_t, fro='ras', to='head') return ras_to_head_t
def convert_aseg_head_to_MNI(labels_aseg, mri_head_t, sbj, sbj_dir): import mne import numpy as np from mne.transforms import apply_trans, invert_transform ROI_aseg_MNI_coords = list() ROI_aseg_name = list() ROI_aseg_color = list() # get the MRI (surface RAS) -> head matrix head_mri_t = invert_transform(mri_head_t) # head->MRI (surface RAS) for label in labels_aseg: print(('sub structure {} \n'.format(label.name))) # before we go from head to MRI (surface RAS) aseg_coo = label.pos aseg_coo_MRI_RAS = apply_trans(head_mri_t, aseg_coo) coo_MNI, _ = mne.aseg_vertex_to_mni(aseg_coo_MRI_RAS * 1000, sbj, sbj_dir) ROI_aseg_MNI_coords.append(coo_MNI) ROI_aseg_name.append(label.name) ROI_aseg_color.append(label.color) nvert_ROI = [len(vn) for vn in ROI_aseg_MNI_coords] nvert_src = [l.pos.shape[0] for l in labels_aseg] if np.sum(nvert_ROI) != np.sum(nvert_src): raise RuntimeError('number of vol ssrc space vertices must be equal to \ the total number of ROI vertices') ROI_MNI = dict(ROI_aseg_name=ROI_aseg_name, ROI_aseg_MNI_coords=ROI_aseg_MNI_coords, ROI_aseg_color=ROI_aseg_color) return ROI_MNI
def test_get_mri_head_t(): """Test converting '-trans.txt' to '-trans.fif'""" trans = read_trans(fname) trans = invert_transform(trans) # starts out as head->MRI, so invert trans_2 = _get_mri_head_t_from_trans_file(fname_trans) assert_equal(trans["from"], trans_2["from"]) assert_equal(trans["to"], trans_2["to"]) assert_allclose(trans["trans"], trans_2["trans"], rtol=1e-5, atol=1e-5)
def test_get_trans(): """Test converting '-trans.txt' to '-trans.fif'""" trans = read_trans(fname) trans = invert_transform(trans) # starts out as head->MRI, so invert trans_2 = _get_trans(fname_trans)[0] assert_equal(trans['from'], trans_2['from']) assert_equal(trans['to'], trans_2['to']) assert_allclose(trans['trans'], trans_2['trans'], rtol=1e-5, atol=1e-5)
def test_combine(): """Test combining transforms """ trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans["from"], trans["from"]) assert_raises(RuntimeError, combine_transforms, trans, inv, trans["to"], trans["from"]) assert_raises(RuntimeError, combine_transforms, trans, inv, trans["from"], trans["to"]) assert_raises(RuntimeError, combine_transforms, trans, trans, trans["from"], trans["to"])
def _prepare_trans(info, trans, coord_frame='head'): head_mri_t = _ensure_trans(trans, 'head', 'mri') dev_head_t = info['dev_head_t'] del trans # Figure out our transformations if coord_frame == 'meg': head_trans = invert_transform(dev_head_t) meg_trans = Transform('meg', 'meg') mri_trans = invert_transform( combine_transforms(dev_head_t, head_mri_t, 'meg', 'mri')) elif coord_frame == 'mri': head_trans = head_mri_t meg_trans = combine_transforms(dev_head_t, head_mri_t, 'meg', 'mri') mri_trans = Transform('mri', 'mri') else: # coord_frame == 'head' head_trans = Transform('head', 'head') meg_trans = info['dev_head_t'] mri_trans = invert_transform(head_mri_t) return head_trans, meg_trans, mri_trans
def test_combine(): """Test combining transforms.""" trans = read_trans(fname) inv = invert_transform(trans) combine_transforms(trans, inv, trans['from'], trans['from']) pytest.raises(RuntimeError, combine_transforms, trans, inv, trans['to'], trans['from']) pytest.raises(RuntimeError, combine_transforms, trans, inv, trans['from'], trans['to']) pytest.raises(RuntimeError, combine_transforms, trans, trans, trans['from'], trans['to'])
def _make_forward(eeg_leadfield, ch_names, info, src, trans_fname): fwd = eeg_leadfield.array().astype(np.float32).T fwd = _to_forward_dict(fwd, ch_names) picks = mne.pick_channels(info['ch_names'], ch_names) fwd['info'] = mne.pick_info(info, picks) fwd['info']['mri_file'] = trans_fname fwd['info']['mri_id'] = fwd['info']['file_id'] fwd['mri_head_t'] = invert_transform(mne.read_trans(trans_fname)) fwd['info']['mri_head_t'] = fwd['mri_head_t'] fwd['info']['meas_file'] = "" fwd['src'] = src fwd['surf_ori'] = False return fwd
def test_orientation_max_power(bias_params_fixed, bias_params_free, weight_norm, lower, upper, lower_ori, upper_ori, real_filter): """Test orientation selection for bias for max-power DICS.""" # we simulate data for the fixed orientation forward and beamform using # the free orientation forward, and check the orientation match at the end evoked, _, noise_cov, data_cov, want = bias_params_fixed noise_csd = _cov_as_csd(noise_cov, evoked.info) data_csd = _cov_as_csd(data_cov, evoked.info) del data_cov, noise_cov fwd = bias_params_free[1] filters = make_dics(evoked.info, fwd, data_csd, 0.05, noise_csd, pick_ori='max-power', weight_norm=weight_norm, depth=None, real_filter=real_filter) loc = np.abs(apply_dics(evoked, filters).data) ori = filters['max_power_ori'][0] assert ori.shape == (246, 3) loc = np.abs(loc) # Compute the percentage of sources for which there is no loc bias: max_idx = np.argmax(loc, axis=0) mask = want == max_idx # ones that localized properly perc = mask.mean() * 100 assert lower <= perc <= upper # Compute the dot products of our forward normals and # assert we get some hopefully reasonable agreement assert fwd['coord_frame'] == FIFF.FIFFV_COORD_HEAD nn = np.concatenate( [s['nn'][v] for s, v in zip(fwd['src'], filters['vertices'])]) nn = nn[want] nn = apply_trans(invert_transform(fwd['mri_head_t']), nn, move=False) assert_allclose(np.linalg.norm(nn, axis=1), 1, atol=1e-6) assert_allclose(np.linalg.norm(ori, axis=1), 1, atol=1e-12) dots = np.abs((nn[mask] * ori[mask]).sum(-1)) assert_array_less(dots, 1) assert_array_less(0, dots) got = np.mean(dots) assert lower_ori < got < upper_ori
def test_transforms(): """ Test transformations """ bti_trans = (0.0, 0.02, 0.11) bti_dev_t = Transform("ctf_meg", "meg", _get_bti_dev_t(0.0, bti_trans)) for pdf, config, hs in zip(pdf_fnames, config_fnames, hs_fnames): raw = read_raw_bti(pdf, config, hs) dev_ctf_t = raw.info["dev_ctf_t"] dev_head_t_old = raw.info["dev_head_t"] ctf_head_t = raw.info["ctf_head_t"] # 1) get BTI->Neuromag bti_dev_t = Transform("ctf_meg", "meg", _get_bti_dev_t(0.0, bti_trans)) # 2) get Neuromag->BTI head t = combine_transforms(invert_transform(bti_dev_t), dev_ctf_t, "meg", "ctf_head") # 3) get Neuromag->head dev_head_t_new = combine_transforms(t, ctf_head_t, "meg", "head") assert_array_equal(dev_head_t_new["trans"], dev_head_t_old["trans"])
def test_transforms(): """Test transformations.""" bti_trans = (0.0, 0.02, 0.11) bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans)) for pdf, config, hs, in zip(pdf_fnames, config_fnames, hs_fnames): raw = read_raw_bti(pdf, config, hs, preload=False) dev_ctf_t = raw.info['dev_ctf_t'] dev_head_t_old = raw.info['dev_head_t'] ctf_head_t = raw.info['ctf_head_t'] # 1) get BTI->Neuromag bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans)) # 2) get Neuromag->BTI head t = combine_transforms(invert_transform(bti_dev_t), dev_ctf_t, 'meg', 'ctf_head') # 3) get Neuromag->head dev_head_t_new = combine_transforms(t, ctf_head_t, 'meg', 'head') assert_array_equal(dev_head_t_new['trans'], dev_head_t_old['trans'])
def gen_ras_to_head_trans(head_to_mri_t, t1_img): mri_to_head_t = invert_transform(head_to_mri_t) # RAS <> VOXEL ras_to_vox_t = Transform(fro='ras', to='mri_voxel', trans=np.linalg.inv(t1_img.header.get_vox2ras())) # trans=t1_img.header.get_ras2vox()) vox_to_mri_t = Transform(fro='mri_voxel', to='mri', trans=t1_img.header.get_vox2ras_tkr()) # RAS <> MRI ras_to_mri_t = combine_transforms(ras_to_vox_t, vox_to_mri_t, fro='ras', to='mri') ras_to_head_t = combine_transforms(ras_to_mri_t, mri_to_head_t, fro='ras', to='head') return ras_to_head_t
def test_orientation_max_power(bias_params_fixed, bias_params_free, reg, weight_norm, use_cov, depth, lower, upper, lower_ori, upper_ori): """Test orientation selection for bias for max-power LCMV.""" # we simulate data for the fixed orientation forward and beamform using # the free orientation forward, and check the orientation match at the end evoked, _, noise_cov, data_cov, want = bias_params_fixed fwd = bias_params_free[1] if not use_cov: evoked.pick_types(meg='grad') noise_cov = None filters = make_lcmv(evoked.info, fwd, data_cov, reg, noise_cov, pick_ori='max-power', weight_norm=weight_norm, depth=depth) loc = apply_lcmv(evoked, filters).data ori = filters['max_power_ori'] assert ori.shape == (246, 3) loc = np.abs(loc) # Compute the percentage of sources for which there is no loc bias: max_idx = np.argmax(loc, axis=0) mask = want == max_idx # ones that localized properly perc = mask.mean() * 100 assert lower <= perc <= upper # Compute the dot products of our forward normals and assert fwd['coord_frame'] == FIFF.FIFFV_COORD_HEAD nn = np.concatenate( [s['nn'][v] for s, v in zip(fwd['src'], filters['vertices'])]) nn = nn[want] nn = apply_trans(invert_transform(fwd['mri_head_t']), nn, move=False) assert_allclose(np.linalg.norm(nn, axis=1), 1, atol=1e-6) assert_allclose(np.linalg.norm(ori, axis=1), 1, atol=1e-12) dots = np.abs((nn[mask] * ori[mask]).sum(-1)) assert_array_less(dots, 1) assert_array_less(0, dots) got = np.mean(dots) assert lower_ori < got < upper_ori
def test_head_to_mni(): """Test conversion of aseg vertices to MNI coordinates.""" # obtained using freeview coords = np.array([[22.52, 11.24, 17.72], [22.52, 5.46, 21.58], [16.10, 5.46, 22.23], [21.24, 8.36, 22.23]]) xfm = _read_talxfm('sample', subjects_dir) coords_MNI = apply_trans(xfm['trans'], coords) trans = read_trans(trans_fname) # head->MRI (surface RAS) mri_head_t = invert_transform(trans) # MRI (surface RAS)->head matrix # obtained from sample_audvis-meg-oct-6-mixed-fwd.fif coo_right_amygdala = np.array([[0.01745682, 0.02665809, 0.03281873], [0.01014125, 0.02496262, 0.04233755], [0.01713642, 0.02505193, 0.04258181], [0.01720631, 0.03073877, 0.03850075]]) coords_MNI_2 = head_to_mni(coo_right_amygdala, 'sample', mri_head_t, subjects_dir) # less than 1mm error assert_allclose(coords_MNI, coords_MNI_2, atol=10.0)
def select_vertices_in_sensor_range(inst, dist, info=None, picks=None, trans=None, indices=False, verbose=None): """Find vertices within given distance to a sensor. Parameters ---------- inst : instance of Forward | instance of SourceSpaces The object to select vertices from. dist : float The minimum distance between a vertex and the nearest sensor. All vertices for which the distance to the nearest sensor exceeds this limit are discarded. info : instance of Info | None The info structure that contains information about the channels. Only needs to be specified if the object to select vertices from does is an instance of SourceSpaces. picks : array-like of int | None Indices of sensors to include in the search for the nearest sensor. If ``None``, the default, only MEG channels are used. trans : str | instance of Transform | None Either the full path to the head<->MRI transform ``*-trans.fif`` file produced during coregistration, or the Transformation itself. If trans is None, an identity matrix is assumed. Only needed when ``inst`` is a source space in MRI coordinates. indices: False | True If ``True``, return vertex indices instead of vertex numbers. Defaults to ``False``. verbose : bool | str | int | None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- vertices : pair of lists | list of int Either a list of vertex numbers for the left and right hemisphere (if ``indices==False``) or a single list with vertex indices. See Also -------- restrict_forward_to_vertices : restrict Forward to the given vertices restrict_src_to_vertices : restrict SourceSpaces to the given vertices """ if isinstance(inst, Forward): info = inst['info'] src = inst['src'] elif isinstance(inst, SourceSpaces): src = inst if info is None: raise ValueError('You need to specify an Info object with ' 'information about the channels.') # Load the head<->MRI transform if necessary if src[0]['coord_frame'] == FIFF.FIFFV_COORD_MRI: if trans is None: raise ValueError('Source space is in MRI coordinates, but no ' 'head<->MRI transform was given. Please specify ' 'the full path to the appropriate *-trans.fif ' 'file as the "trans" parameter.') if isinstance(trans, string_types): trans = read_trans(trans, return_all=True) for trans in trans: # we got at least 1 try: trans = _ensure_trans(trans, 'head', 'mri') except Exception as exp: pass else: break else: raise exp src_trans = invert_transform(_ensure_trans(trans, 'head', 'mri')) print('Transform!') else: src_trans = Transform('head', 'head') # Identity transform dev_to_head = _ensure_trans(info['dev_head_t'], 'meg', 'head') if picks is None: picks = pick_types(info, meg=True) if len(picks) > 0: logger.info('Using MEG channels') else: logger.info('Using EEG channels') picks = pick_types(info, eeg=True) src_pos = np.vstack([ apply_trans(src_trans, s['rr'][s['inuse'].astype(np.bool)]) for s in src ]) sensor_pos = [] for ch in picks: # MEG channels are in device coordinates, translate them to head if channel_type(info, ch) in ['mag', 'grad']: sensor_pos.append( apply_trans(dev_to_head, info['chs'][ch]['loc'][:3])) else: sensor_pos.append(info['chs'][ch]['loc'][:3]) sensor_pos = np.array(sensor_pos) # Find vertices that are within range of a sensor. We use a KD-tree for # speed. logger.info('Finding vertices within sensor range...') tree = cKDTree(sensor_pos) distances, _ = tree.query(src_pos, distance_upper_bound=dist) # Vertices out of range are flagged as np.inf src_sel = np.isfinite(distances) logger.info('[done]') if indices: return np.flatnonzero(src_sel) else: n_lh_verts = src[0]['nuse'] lh_sel, rh_sel = src_sel[:n_lh_verts], src_sel[n_lh_verts:] vert_lh = src[0]['vertno'][lh_sel] vert_rh = src[1]['vertno'][rh_sel] return [vert_lh, vert_rh]
def get_sensor_pos_from_fwd(inst, info=None, picks=None, trans=None): from mne import SourceSpaces, Forward from mne.io.constants import FIFF from six import string_types from mne.transforms import read_trans, _ensure_trans, invert_transform, Transform, apply_trans from mne.io.pick import channel_type, pick_types if isinstance(inst, Forward): info = inst['info'] src = inst['src'] elif isinstance(inst, SourceSpaces): src = inst if info is None: raise ValueError('You need to specify an Info object with ' 'information about the channels.') # Load the head<->MRI transform if necessary if src[0]['coord_frame'] == FIFF.FIFFV_COORD_MRI: if trans is None: raise ValueError('Source space is in MRI coordinates, but no ' 'head<->MRI transform was given. Please specify ' 'the full path to the appropriate *-trans.fif ' 'file as the "trans" parameter.') if isinstance(trans, string_types): trans = read_trans(trans, return_all=True) for trans in trans: # we got at least 1 try: trans = _ensure_trans(trans, 'head', 'mri') except Exception as exp: pass else: break else: raise exp src_trans = invert_transform(_ensure_trans(trans, 'head', 'mri')) print('Transform!') else: src_trans = Transform('head', 'head') # Identity transform dev_to_head = _ensure_trans(info['dev_head_t'], 'meg', 'head') if picks is None: picks = pick_types(info, meg=True) if len(picks) > 0: print('Using MEG channels') else: print('Using EEG channels') picks = pick_types(info, eeg=True) sensor_pos = [] for ch in picks: # MEG channels are in device coordinates, translate them to head if channel_type(info, ch) in ['mag', 'grad']: sensor_pos.append( apply_trans(dev_to_head, info['chs'][ch]['loc'][:3])) else: sensor_pos.append(info['chs'][ch]['loc'][:3]) sensor_pos = np.array(sensor_pos) return sensor_pos
def test_coreg_model(): """Test CoregModel.""" from mne.gui._coreg_gui import CoregModel tempdir = _TempDir() trans_dst = op.join(tempdir, 'test-trans.fif') model = CoregModel() pytest.raises(RuntimeError, model.save_trans, 'blah.fif') model.mri.subjects_dir = subjects_dir model.mri.subject = 'sample' assert not model.mri.fid_ok model.mri.lpa = [[-0.06, 0, 0]] model.mri.nasion = [[0, 0.05, 0]] model.mri.rpa = [[0.08, 0, 0]] assert (model.mri.fid_ok) model.hsp.file = raw_path assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4) assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4) assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4) assert model.has_lpa_data assert model.has_nasion_data assert model.has_rpa_data assert len(model.hsp.eeg_points) > 1 assert len(model.mri.bem_low_res.surf.rr) == 2562 assert len(model.mri.bem_high_res.surf.rr) == 267122 lpa_distance = model.lpa_distance nasion_distance = model.nasion_distance rpa_distance = model.rpa_distance avg_point_distance = np.mean(model.point_distance) model.nasion_weight = 1. model.fit_fiducials(0) old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2 new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 + model.nasion_distance ** 2) assert new_x < old_x model.fit_icp(0) new_dist = np.mean(model.point_distance) assert new_dist < avg_point_distance model.save_trans(trans_dst) trans = mne.read_trans(trans_dst) assert_allclose(trans['trans'], model.head_mri_t) # test restoring trans x, y, z = 100, 200, 50 rot_x, rot_y, rot_z = np.rad2deg([1.5, 0.1, -1.2]) model.trans_x = x model.trans_y = y model.trans_z = z model.rot_x = rot_x model.rot_y = rot_y model.rot_z = rot_z trans = model.mri_head_t model.reset_traits(["trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z"]) assert_equal(model.trans_x, 0) model.set_trans(trans) assert_array_almost_equal(model.trans_x, x) assert_array_almost_equal(model.trans_y, y) assert_array_almost_equal(model.trans_z, z) assert_array_almost_equal(model.rot_x, rot_x) assert_array_almost_equal(model.rot_y, rot_y) assert_array_almost_equal(model.rot_z, rot_z) # info assert (isinstance(model.fid_eval_str, str)) assert (isinstance(model.points_eval_str, str)) # scaling job assert not model.can_prepare_bem_model model.n_scale_params = 1 assert (model.can_prepare_bem_model) model.prepare_bem_model = True sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \ model.get_scaling_job('sample2', False) assert_equal(sdir, subjects_dir) assert_equal(sfrom, 'sample') assert_equal(sto, 'sample2') assert_allclose(scale, model.parameters[6:9]) assert_equal(skip_fiducials, False) # find BEM files bems = set() for fname in os.listdir(op.join(subjects_dir, 'sample', 'bem')): match = re.match(r'sample-(.+-bem)\.fif', fname) if match: bems.add(match.group(1)) assert_equal(set(bemsol), bems) model.prepare_bem_model = False sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \ model.get_scaling_job('sample2', True) assert_equal(bemsol, []) assert (skip_fiducials) model.load_trans(fname_trans) model.save_trans(trans_dst) trans = mne.read_trans(trans_dst) assert_allclose(trans['trans'], model.head_mri_t) assert_allclose(invert_transform(trans)['trans'][:3, 3] * 1000., [model.trans_x, model.trans_y, model.trans_z])
def plot_visualize_mft_sources(fwdmag, stcdata, tmin, tstep, subject, subjects_dir): ''' Plot the MFT sources at time point of peak. ''' print "##### Attempting to plot:" # cf. decoding/plot_decoding_spatio_temporal_source.py vertices = [s['vertno'] for s in fwdmag['src']] if len(vertices) == 1: vertices = [ fwdmag['src'][0]['vertno'] [fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] <= -0.], fwdmag['src'][0]['vertno'][ fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] > -0.] ] stc_feat = SourceEstimate(stcdata, vertices=vertices, tmin=-0.2, tstep=tstep, subject=subject) for hemi in ['lh', 'rh']: brain = stc_feat.plot(surface='white', hemi=hemi, subjects_dir=subjects_dir, transparent=True, clim='auto') brain.show_view('lateral') # use peak getter to move visualization to the time point of the peak tmin = 0.095 tmax = 0.10 print "Restricting peak search to [%fs, %fs]" % (tmin, tmax) if hemi == 'both': vertno_max, time_idx = stc_feat.get_peak(hemi='rh', time_as_index=True, tmin=tmin, tmax=tmax) else: vertno_max, time_idx = stc_feat.get_peak(hemi=hemi, time_as_index=True, tmin=tmin, tmax=tmax) if hemi == 'lh': comax = fwdmag['src'][0]['rr'][vertno_max] print "hemi=%s: vertno_max=%d, time_idx=%d fwdmag['src'][0]['rr'][vertno_max] = " %\ (hemi, vertno_max, time_idx), comax elif len(fwdmag['src']) > 1: comax = fwdmag['src'][1]['rr'][vertno_max] print "hemi=%s: vertno_max=%d, time_idx=%d fwdmag['src'][1]['rr'][vertno_max] = " %\ (hemi, vertno_max, time_idx), comax print "hemi=%s: setting time_idx=%d" % (hemi, time_idx) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi=hemi, color='blue', scale_factor=0.6) offsets = np.append([0], [s['nuse'] for s in fwdmag['src']]) if hemi == 'lh': ifoci = [ np.nonzero([ stcdata[0:offsets[1], time_idx] >= 0.25 * np.max(stcdata[:, time_idx]) ][0]) ] vfoci = fwdmag['src'][0]['vertno'][ifoci[0][0]] cfoci = fwdmag['src'][0]['rr'][vfoci] print "Coords of %d sel. vfoci: " % cfoci.shape[0] print cfoci print "vfoci: " print vfoci print "brain.geo['lh'].coords[vfoci] : " print brain.geo['lh'].coords[vfoci] elif len(fwdmag['src']) > 1: ifoci = [ np.nonzero([ stcdata[offsets[1]:, time_idx] >= 0.25 * np.max(stcdata[:, time_idx]) ][0]) ] vfoci = fwdmag['src'][1]['vertno'][ifoci[0][0]] cfoci = fwdmag['src'][1]['rr'][vfoci] print "Coords of %d sel. vfoci: " % cfoci.shape[0] print cfoci print "vfoci: " print vfoci print "brain.geo['rh'].coords[vfoci] : " print brain.geo['rh'].coords[vfoci] mrfoci = np.zeros(cfoci.shape) invmri_head_t = invert_transform(fwdmag['info']['mri_head_t']) mrfoci = apply_trans(invmri_head_t['trans'], cfoci, move=True) print "mrfoci: " print mrfoci # Just some blops: bloblist = np.zeros((300, 3)) for i in xrange(100): bloblist[i, 0] = float(i) bloblist[i + 100, 1] = float(i) bloblist[i + 200, 2] = float(i) mrblobs = apply_trans(invmri_head_t['trans'], bloblist, move=True) brain.save_image('testfig_map_%s.png' % hemi) brain.close()
import mne from _make_perturbed_forward import make_pert_forward_solution, make_pert_forward_dipole from mne.datasets import sample import numpy as np # noqa from mne.transforms import (_ensure_trans, transform_surface_to, apply_trans, _get_trans, invert_transform, _print_coord_trans, _coord_frame_name, Transform) # local_data_path = 'C:\MEG\Local_mne_data' data_path = sample.data_path() # local copy of mne sample data raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif' subjects_dir = data_path + '/subjects' subject = 'sample' trans = data_path + '\MEG\sample/sample_audvis_raw-trans.fif' mri_head_t, trans = _get_trans(trans) head_mri_t = invert_transform(mri_head_t) cov = mne.read_cov(cov_fname) info = mne.io.read_info(raw_fname) def fit_dips(min_rad, max_rad, nn, sphere, perts, sourcenorm): testsources = dict(rr=[], nn=[]) nsources = max_rad - min_rad + 1 vertices = np.zeros((nsources, 1)) for i in range(min_rad, max_rad + 1): ex, ey, ez = sourcenorm[0], sourcenorm[1], sourcenorm[2] source = [.001*i*ex, .001*i*ey, .001*i*ez] normal = [nn[0], nn[1], nn[2]] testsources['rr'].append(source) testsources['nn'].append(normal) vertices[i - min_rad] = i
def test_get_trans(): """Test converting '-trans.txt' to '-trans.fif'.""" trans = read_trans(fname) trans = invert_transform(trans) # starts out as head->MRI, so invert trans_2 = _get_trans(fname_trans)[0] assert trans.__eq__(trans_2, atol=1e-5)
def plot_visualize_mft_sources(fwdmag, stcdata, tmin, tstep, subject, subjects_dir): ''' Plot the MFT sources at time point of peak. ''' print "##### Attempting to plot:" # cf. decoding/plot_decoding_spatio_temporal_source.py vertices = [s['vertno'] for s in fwdmag['src']] if len(vertices) == 1: vertices = [fwdmag['src'][0]['vertno'][fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] <= -0.], fwdmag['src'][0]['vertno'][fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] > -0.]] stc_feat = SourceEstimate(stcdata, vertices=vertices, tmin=-0.2, tstep=tstep, subject=subject) for hemi in ['lh', 'rh']: brain = stc_feat.plot(surface='white', hemi=hemi, subjects_dir=subjects_dir, transparent=True, clim='auto') brain.show_view('lateral') # use peak getter to move visualization to the time point of the peak tmin = 0.095 tmax = 0.10 print "Restricting peak search to [%fs, %fs]" % (tmin, tmax) if hemi == 'both': vertno_max, time_idx = stc_feat.get_peak(hemi='rh', time_as_index=True, tmin=tmin, tmax=tmax) else: vertno_max, time_idx = stc_feat.get_peak(hemi=hemi, time_as_index=True, tmin=tmin, tmax=tmax) if hemi == 'lh': comax = fwdmag['src'][0]['rr'][vertno_max] print "hemi=%s: vertno_max=%d, time_idx=%d fwdmag['src'][0]['rr'][vertno_max] = " %\ (hemi, vertno_max, time_idx), comax elif len(fwdmag['src']) > 1: comax = fwdmag['src'][1]['rr'][vertno_max] print "hemi=%s: vertno_max=%d, time_idx=%d fwdmag['src'][1]['rr'][vertno_max] = " %\ (hemi, vertno_max, time_idx), comax print "hemi=%s: setting time_idx=%d" % (hemi, time_idx) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi=hemi, color='blue', scale_factor=0.6) offsets = np.append([0], [s['nuse'] for s in fwdmag['src']]) if hemi == 'lh': ifoci = [np.nonzero([stcdata[0:offsets[1],time_idx]>=0.25*np.max(stcdata[:,time_idx])][0])] vfoci = fwdmag['src'][0]['vertno'][ifoci[0][0]] cfoci = fwdmag['src'][0]['rr'][vfoci] print "Coords of %d sel. vfoci: " % cfoci.shape[0] print cfoci print "vfoci: " print vfoci print "brain.geo['lh'].coords[vfoci] : " print brain.geo['lh'].coords[vfoci] elif len(fwdmag['src']) > 1: ifoci = [np.nonzero([stcdata[offsets[1]:,time_idx]>=0.25*np.max(stcdata[:,time_idx])][0])] vfoci = fwdmag['src'][1]['vertno'][ifoci[0][0]] cfoci = fwdmag['src'][1]['rr'][vfoci] print "Coords of %d sel. vfoci: " % cfoci.shape[0] print cfoci print "vfoci: " print vfoci print "brain.geo['rh'].coords[vfoci] : " print brain.geo['rh'].coords[vfoci] mrfoci = np.zeros(cfoci.shape) invmri_head_t = invert_transform(fwdmag['info']['mri_head_t']) mrfoci = apply_trans(invmri_head_t['trans'],cfoci, move=True) print "mrfoci: " print mrfoci # Just some blops: bloblist = np.zeros((300,3)) for i in xrange(100): bloblist[i,0] = float(i) bloblist[i+100,1] = float(i) bloblist[i+200,2] = float(i) mrblobs = apply_trans(invmri_head_t['trans'], bloblist, move=True) brain.save_image('testfig_map_%s.png' % hemi) brain.close()
def plot_evoked(widget, state, fwd_path, subject, info, ras_to_head_t, exact_solution, bem_path=None, head_to_mri_t=None, fwd_lookup_table=None, t1_img=None): if fwd_lookup_table is None: raise ValueError('Must prodive fwd_lookup_table') dipole_pos = (state['dipole_pos']['x'], state['dipole_pos']['y'], state['dipole_pos']['z']) dipole_ori = (state['dipole_ori']['x'], state['dipole_ori']['y'], state['dipole_ori']['z']) # dipole_pos = np.array(dipole_pos).reshape(1, 3) # dipole_pos = apply_trans(trans=ras_to_head_t, pts=dipole_pos) # dipole_pos /= 1000 # dipole_ori = np.array(dipole_ori).reshape(1, 3) # dipole_ori = apply_trans(trans=ras_to_head_t, pts=dipole_ori, move=False) # dipole_ori /= 1000 # dipole_ori /= np.linalg.norm(dipole_ori) # dipole_pos = np.array(dipole_pos).reshape(1, 3).round(3) # dipole_ori = np.array(dipole_ori).reshape(1, 3).round(3) dipole_pos_ras = np.array(dipole_pos).reshape(1, 3) dipole_pos_vox = apply_trans(t1_img.header.get_ras2vox(), dipole_pos_ras) dipole_pos_mri = apply_trans(t1_img.header.get_vox2ras_tkr(), dipole_pos_vox) dipole_pos_mri_m = dipole_pos_mri / 1000. dipole_pos_head = apply_trans(invert_transform(head_to_mri_t), dipole_pos_mri_m) dipole_pos = dipole_pos_head dipole_ori_ras = np.array(dipole_ori).reshape(1, 3) dipole_ori_vox = apply_trans(t1_img.header.get_ras2vox(), dipole_ori_ras, move=False) dipole_ori_mri = apply_trans(t1_img.header.get_vox2ras_tkr(), dipole_ori_vox, move=False) dipole_ori_mri_m = dipole_ori_mri / 1000. dipole_ori_head = apply_trans(invert_transform(head_to_mri_t), dipole_ori_mri_m, move=False) dipole_ori = dipole_ori_head dipole_ori /= np.linalg.norm(dipole_ori) dipole_amplitude = state['dipole_amplitude'] if exact_solution: if (bem_path).exists(): print(f'\nUsing existing BEM solution: {bem_path}\n') else: print('Retrieving BEM solution from GitHub.') try: download_bem_from_github(data_path=bem_path.parent, subject=subject, overwrite=False) except RuntimeError as e: msg = (f'Failed to retrieve the BEM solution. ' f'The error was: {e}\n') raise RuntimeError(msg) bem = mne.read_bem_solution(bem_path) fwd = gen_forward_solution(pos=dipole_pos, bem=bem, info=info, trans=head_to_mri_t) else: # Retrieve the dipole pos closest to the one we have a pre-calculated # fwd for. pos_head_grid = create_head_grid(info=info) dipole_pos_for_fwd = (find_closest(pos_head_grid[0], dipole_pos[0, 0]), find_closest(pos_head_grid[1], dipole_pos[0, 1]), find_closest(pos_head_grid[2], dipole_pos[0, 2])) print(f'Requested calculations for dipole located at:\n' f' x={dipole_pos[0, 0]}, y={dipole_pos[0, 1]}, ' f'z={dipole_pos[0, 2]} [m, MNE Head]\n' f'Using a forward solution for the following location:\n' f' x={dipole_pos_for_fwd[0]}, y={dipole_pos_for_fwd[1]}, ' f'z={dipole_pos_for_fwd[2]} [m, MNE Head]') fwd_fname = (f'{subject}-' f'{dipole_pos_for_fwd[0]:.3f}-' f'{dipole_pos_for_fwd[1]:.3f}-' f'{dipole_pos_for_fwd[2]:.3f}-fwd.fif') if (fwd_path / fwd_fname).exists(): print(f'\nUsing existing forward solution: {fwd_fname}\n') elif not fwd_lookup_table.loc[str(dipole_pos_for_fwd[0]), str(dipole_pos_for_fwd[1]), str(dipole_pos_for_fwd[2])].iloc[0]: msg = ('No pre-calculated foward solution available for this ' 'dipole. Please select a dipole origin clearly inside the ' 'brain.') print(msg) return else: print('Retrieving forward solution from GitHub.\n\n') try: download_fwd_from_github(fwd_path=fwd_path, subject=subject, dipole_pos=dipole_pos_for_fwd) except RuntimeError as e: msg = (f'Failed to retrieve pre-calculated forward solution. ' f'The error was: {e}\n\n' f'Please try again with another dipole origin inside ' f'the brain.') raise RuntimeError(msg) fwd = mne.read_forward_solution(fwd_path / fwd_fname) del fwd_fname, pos_head_grid, dipole_pos_for_fwd evoked = gen_evoked(fwd=fwd, dipole_ori=dipole_ori, dipole_amplitude=dipole_amplitude, info=info) for ch_type, fig in widget['topomap_fig'].items(): ax_topomap = fig.axes[0] ax_colorbar = fig.axes[1] ax_topomap.clear() ax_colorbar.clear() ax_topomap.set_aspect('equal') if ch_type == 'eeg': outlines = 'head' else: outlines = 'skirt' evoked.plot_topomap(ch_type=ch_type, colorbar=False, outlines=outlines, times=evoked.times[-1], show=False, axes=ax_topomap) ax_topomap.set_title(None) # ax_topomap.format_coord = _create_format_coord('topomap') cb = fig.colorbar(ax_topomap.images[-1], cax=ax_colorbar, orientation='horizontal') if ch_type == 'mag': label = 'fT' elif ch_type == 'grad': label = 'fT/cm' elif ch_type == 'eeg': label = 'µV' # Scale the topomap to approx. the same size as the MEG topomaps. mag_topomap_ax = widget['topomap_fig']['mag'].axes[0] ax_topomap.set_xlim(np.array(mag_topomap_ax.get_xlim()) * 1.05) ax_topomap.set_ylim(np.array(mag_topomap_ax.get_ylim()) * 1.05) cb.set_label(label, fontweight='bold') fig.canvas.draw()
def test_get_trans(): """Test converting '-trans.txt' to '-trans.fif'""" trans = read_trans(fname) trans = invert_transform(trans) # starts out as head->MRI, so invert trans_2 = _get_trans(fname_trans)[0] assert trans.__eq__(trans_2, atol=1e-5)
def test_coreg_model(): """Test CoregModel.""" from mne.gui._coreg_gui import CoregModel tempdir = _TempDir() trans_dst = op.join(tempdir, 'test-trans.fif') model = CoregModel() pytest.raises(RuntimeError, model.save_trans, 'blah.fif') model.mri.subjects_dir = subjects_dir model.mri.subject = 'sample' assert not model.mri.fid_ok model.mri.lpa = [[-0.06, 0, 0]] model.mri.nasion = [[0, 0.05, 0]] model.mri.rpa = [[0.08, 0, 0]] assert (model.mri.fid_ok) model.hsp.file = raw_path assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4) assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4) assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4) assert model.has_lpa_data assert model.has_nasion_data assert model.has_rpa_data assert len(model.hsp.eeg_points) > 1 assert len(model.mri.bem_low_res.surf.rr) == 2562 assert len(model.mri.bem_high_res.surf.rr) == 267122 lpa_distance = model.lpa_distance nasion_distance = model.nasion_distance rpa_distance = model.rpa_distance avg_point_distance = np.mean(model.point_distance) model.nasion_weight = 1. model.fit_fiducials(0) old_x = lpa_distance**2 + rpa_distance**2 + nasion_distance**2 new_x = (model.lpa_distance**2 + model.rpa_distance**2 + model.nasion_distance**2) assert new_x < old_x model.fit_icp(0) new_dist = np.mean(model.point_distance) assert new_dist < avg_point_distance model.save_trans(trans_dst) trans = mne.read_trans(trans_dst) assert_allclose(trans['trans'], model.head_mri_t) # test restoring trans x, y, z = 100, 200, 50 rot_x, rot_y, rot_z = np.rad2deg([1.5, 0.1, -1.2]) model.trans_x = x model.trans_y = y model.trans_z = z model.rot_x = rot_x model.rot_y = rot_y model.rot_z = rot_z trans = model.mri_head_t model.reset_traits( ["trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z"]) assert_equal(model.trans_x, 0) model.set_trans(trans) assert_array_almost_equal(model.trans_x, x) assert_array_almost_equal(model.trans_y, y) assert_array_almost_equal(model.trans_z, z) assert_array_almost_equal(model.rot_x, rot_x) assert_array_almost_equal(model.rot_y, rot_y) assert_array_almost_equal(model.rot_z, rot_z) # info assert (isinstance(model.fid_eval_str, str)) assert (isinstance(model.points_eval_str, str)) # scaling job assert not model.can_prepare_bem_model model.n_scale_params = 1 assert (model.can_prepare_bem_model) model.prepare_bem_model = True sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \ model.get_scaling_job('sample2', False) assert_equal(sdir, subjects_dir) assert_equal(sfrom, 'sample') assert_equal(sto, 'sample2') assert_allclose(scale, model.parameters[6:9]) assert_equal(skip_fiducials, False) # find BEM files bems = set() for fname in os.listdir(op.join(subjects_dir, 'sample', 'bem')): match = re.match(r'sample-(.+-bem)\.fif', fname) if match: bems.add(match.group(1)) assert_equal(set(bemsol), bems) model.prepare_bem_model = False sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \ model.get_scaling_job('sample2', True) assert_equal(bemsol, []) assert (skip_fiducials) model.load_trans(fname_trans) model.save_trans(trans_dst) trans = mne.read_trans(trans_dst) assert_allclose(trans['trans'], model.head_mri_t) assert_allclose( invert_transform(trans)['trans'][:3, 3] * 1000., [model.trans_x, model.trans_y, model.trans_z])
def test_scale_mri_xfm(tmp_path, few_surfaces, subjects_dir_tmp_few): """Test scale_mri transforms and MRI scaling.""" # scale fsaverage tempdir = str(subjects_dir_tmp_few) sample_dir = subjects_dir_tmp_few / 'sample' subject_to = 'flachkopf' spacing = 'oct2' for subject_from in ('fsaverage', 'sample'): if subject_from == 'fsaverage': scale = 1. # single dim else: scale = [0.9, 2, .8] # separate src_from_fname = op.join(tempdir, subject_from, 'bem', '%s-%s-src.fif' % (subject_from, spacing)) src_from = mne.setup_source_space(subject_from, spacing, subjects_dir=tempdir, add_dist=False) write_source_spaces(src_from_fname, src_from) vertices_from = np.concatenate([s['vertno'] for s in src_from]) assert len(vertices_from) == 36 hemis = ([0] * len(src_from[0]['vertno']) + [1] * len(src_from[0]['vertno'])) mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from, subjects_dir=tempdir) if subject_from == 'fsaverage': # identity transform source_rr = np.concatenate( [s['rr'][s['vertno']] for s in src_from]) * 1e3 assert_allclose(mni_from, source_rr) if subject_from == 'fsaverage': overwrite = skip_fiducials = False else: with pytest.raises(IOError, match='No fiducials file'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir) skip_fiducials = True with pytest.raises(IOError, match='already exists'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, skip_fiducials=skip_fiducials) overwrite = True if subject_from == 'sample': # support for not needing all surf files os.remove(op.join(sample_dir, 'surf', 'lh.curv')) scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, verbose='debug', overwrite=overwrite, skip_fiducials=skip_fiducials) if subject_from == 'fsaverage': assert _is_mri_subject(subject_to, tempdir), "Scaling failed" src_to_fname = op.join(tempdir, subject_to, 'bem', '%s-%s-src.fif' % (subject_to, spacing)) assert op.exists(src_to_fname), "Source space was not scaled" # Check MRI scaling fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz') assert op.exists(fname_mri), "MRI was not scaled" # Check MNI transform src = mne.read_source_spaces(src_to_fname) vertices = np.concatenate([s['vertno'] for s in src]) assert_array_equal(vertices, vertices_from) mni = mne.vertex_to_mni(vertices, hemis, subject_to, subjects_dir=tempdir) assert_allclose(mni, mni_from, atol=1e-3) # 0.001 mm # Check head_to_mni (the `trans` here does not really matter) trans = rotation(0.001, 0.002, 0.003) @ translation(0.01, 0.02, 0.03) trans = Transform('head', 'mri', trans) pos_head_from = np.random.RandomState(0).randn(4, 3) pos_mni_from = mne.head_to_mni(pos_head_from, subject_from, trans, tempdir) pos_mri_from = apply_trans(trans, pos_head_from) pos_mri = pos_mri_from * scale pos_head = apply_trans(invert_transform(trans), pos_mri) pos_mni = mne.head_to_mni(pos_head, subject_to, trans, tempdir) assert_allclose(pos_mni, pos_mni_from, atol=1e-3)
def plot_visualize_mft_sources(fwdmag, stcdata, tmin, tstep, subject, subjects_dir): """ Plot the MFT sources at time point of peak. Parameters ---------- fwdmag: forward solution stcdata: stc with ||cdv|| (point sequence as in fwdmag['source_rr']) tmin, tstep, subject: passed to mne.SourceEstimate() """ print("##### Attempting to plot:") # cf. decoding/plot_decoding_spatio_temporal_source.py vertices = [s['vertno'] for s in fwdmag['src']] if len(vertices) == 1: vertices = [ fwdmag['src'][0]['vertno'] [fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] <= -0.], fwdmag['src'][0]['vertno'][ fwdmag['src'][0]['rr'][fwdmag['src'][0]['vertno']][:, 0] > -0.] ] elif len(vertices) > 2: warnings.warn( 'plot_visualize_mft_sources(): Cannot handle more than two sources spaces' ) return stc_feat = SourceEstimate(stcdata, vertices=vertices, tmin=tmin, tstep=tstep, subject=subject) itmaxsum = np.argmax(np.sum(stcdata, axis=0)) twmin = tmin + tstep * float(itmaxsum - stcdata.shape[1] / 20) twmax = tmin + tstep * float(itmaxsum + stcdata.shape[1] / 20) for ihemi, hemi in enumerate(['lh', 'rh', 'both']): brain = stc_feat.plot(surface='white', hemi=hemi, subjects_dir=subjects_dir, transparent=True, clim='auto') # use peak getter to move visualization to the time point of the peak print("Restricting peak search to [%fs, %fs]" % (twmin, twmax)) if hemi == 'both': brain.show_view('parietal') vertno_max, time_idx = stc_feat.get_peak(hemi=None, time_as_index=True, tmin=twmin, tmax=twmax) else: brain.show_view('lateral') vertno_max, time_idx = stc_feat.get_peak(hemi=hemi, time_as_index=True, tmin=twmin, tmax=twmax) print("hemi=%s: setting time_idx=%d" % (hemi, time_idx)) brain.set_data_time_index(time_idx) if hemi == 'lh' or hemi == 'rh': # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi=hemi, color='blue', scale_factor=0.6) if len(fwdmag['src']) > ihemi: fwds = fwdmag['src'][ihemi] comax = fwds['rr'][vertno_max] print("hemi=%s: vertno_max=%d, time_idx=%d fwdmag['src'][%d]['rr'][vertno_max] = " % \ (hemi, vertno_max, time_idx, ihemi), comax) offsets = np.append([0], [s['nuse'] for s in fwdmag['src']]) if hemi == 'lh': ifoci = [ np.nonzero([ stcdata[0:offsets[1], time_idx] >= 0.25 * np.max(stcdata[:, time_idx]) ][0]) ] elif len(fwdmag['src']) > 1: ifoci = [ np.nonzero([ stcdata[offsets[1]:, time_idx] >= 0.25 * np.max(stcdata[:, time_idx]) ][0]) ] vfoci = fwds['vertno'][ifoci[0][0]] cfoci = fwds['rr'][vfoci] print("Coords of %d sel. vfoci: " % cfoci.shape[0]) print(cfoci) print("vfoci: ") print(vfoci) print("brain.geo[%s].coords[vfoci] : " % hemi) print(brain.geo[hemi].coords[vfoci]) mrfoci = np.zeros(cfoci.shape) invmri_head_t = invert_transform(fwdmag['info']['mri_head_t']) mrfoci = apply_trans(invmri_head_t['trans'], cfoci, move=True) print("mrfoci: ") print(mrfoci) # Just some blops along the coordinate axis: # This will not yield reasonable results w an inflated brain. # bloblist = np.zeros((300,3)) # for i in xrange(100): # bloblist[i,0] = float(i) # bloblist[i+100,1] = float(i) # bloblist[i+200,2] = float(i) # mrblobs = apply_trans(invmri_head_t['trans'], bloblist, move=True) # brain.add_foci(mrblobs, coords_as_verts=False, hemi=hemi, color='yellow', scale_factor=0.3) brain.save_image('testfig_map_%s.png' % hemi) brain.close()