def calc_shifted_vox2tk_ras(region_fname, colin_T1_fname): region_vox2ras = tu.get_vox2ras(region_fname) zero_in_ras = utils.apply_trans(region_vox2ras, [[0, 0, 0]]) zero_in_T1_voxels = utils.apply_trans(np.linalg.inv(tu.get_vox2ras(colin_T1_fname)), zero_in_ras) zero_in_T1_tk_ras = utils.apply_trans(tu.get_vox2ras_tkr(colin_T1_fname), zero_in_T1_voxels) voxels_sizes = [abs(v) for v in np.diag(region_vox2ras)[:-1]] shifted_vox2tk_ras = get_shifted_vox2tk_ras(zero_in_T1_tk_ras[0], voxels_sizes) return shifted_vox2tk_ras
def calc_shifted_vox2tk_ras(region_fname, colin_T1_fname): region_vox2ras = tu.get_vox2ras(region_fname) zero_in_ras = utils.apply_trans(region_vox2ras, [[0, 0, 0]]) zero_in_T1_voxels = utils.apply_trans(np.linalg.inv(tu.get_vox2ras(colin_T1_fname)), zero_in_ras) zero_in_T1_tk_ras = utils.apply_trans(tu.get_vox2ras_tkr(colin_T1_fname), zero_in_T1_voxels) voxels_sizes = [abs(v) for v in np.diag(region_vox2ras)[:-1]] shifted_vox2tk_ras = get_shifted_vox2tk_ras(zero_in_T1_tk_ras[0], voxels_sizes) return shifted_vox2tk_ras
def convert_coordinates(subject, xyz, modality, coordinates_system): point = np.array(list(map(float, xyz.split(',')))) trans = get_modality_trans_file(subject, modality) if trans is None: return None if coordinates_system == 'tk_ras': vox = utils.apply_trans(trans.ras_tkr2vox, point).astype(np.int) print('T1: {}'.format(vox)) elif coordinates_system == 'vox': vox = point return vox
def get_t1_vertices_data(subject): trans_fname = op.join(MMVT_DIR, subject, 't1_trans.npz') trans_dict = utils.Bag(np.load(trans_fname)) ras_tkr2vox = np.linalg.inv(trans_dict.vox2ras_tkr) pial_verts = utils.load_surf(subject, MMVT_DIR, SUBJECTS_DIR) t1_data, t1_header = anat.get_data_and_header(subject, 'brainmask.mgz') for hemi in utils.HEMIS: output_fname = op.join(MMVT_DIR, subject, 'surf', 'T1-{}.npy'.format(hemi)) verts = pial_verts[hemi] t1_surf_hemi = np.zeros((len(verts))) hemi_pial_voxels = np.rint(utils.apply_trans(ras_tkr2vox, verts)).astype(int) for vert_ind, t1_vox in zip(range(len(verts)), hemi_pial_voxels): t1_surf_hemi[vert_ind] = t1_data[tuple(t1_vox)] np.save(output_fname, t1_surf_hemi)
def create_surf(subject, subcortical_code, subcortical_name): aseg = nib.load(op.join(SUBJECTS_DIR, subject, 'mri', 'aseg.mgz')).get_data() t1_header = nib.load(op.join(SUBJECTS_DIR, subject, 'mri', 'T1.mgz')).header aseg[aseg != subcortical_code] = 255 aseg[aseg == subcortical_code] = 10 aseg = np.array(aseg, dtype=np.float) aseg_smooth = scipy.ndimage.gaussian_filter(aseg, sigma=1) verts_vox, faces, _, _ = measure.marching_cubes(aseg_smooth, 100) # Doesn't seem to fix the normals directions that should be out... faces = measure.correct_mesh_orientation(aseg_smooth, verts_vox, faces) verts = utils.apply_trans(t1_header.get_vox2ras_tkr(), verts_vox) fol = utils.make_dir(op.join(MMVT_DIR, subject, 'subcortical_test')) ply_file_name = op.join(fol, '{}.ply'.format(subcortical_name)) utils.write_ply_file(verts, faces, ply_file_name, False)
def load(): import sys # print(sys.argv) if len(sys.argv) == 6: mri_fname = sys.argv[1] x, y, z = map(float, sys.argv[2:5]) print(x, y, z) if sys.argv[5] == 'load': open_slicer(mri_fname, x, y, z) elif sys.argv[5] == 'update': update_slicer(x, y, z) else: # open_slicer('/home/noam/mmvt/mg78/freeview/orig.mgz', 0.9862712 , -45.62893867, 12.2588706) # subject = 'nmr00979' # subject = '100307' subject = 'mg102' trans_fname = op.join(MMVT_DIR, subject, 't1_trans.npz') d = utils.Bag(np.load(trans_fname)) ras_tkr2vox = np.linalg.inv(d.vox2ras_tkr) mri_fname = op.join(MMVT_DIR, subject, 'freeview', 'T1.mgz') ct_fname = op.join(MMVT_DIR, subject, 'freeview', 'ct.mgz') # ct_fname = op.join(MMVT_DIR, subject, 'freeview', 'ct_nas.nii.gz') # x, y, z = 0.9862712 , -45.62893867, 12.2588706 # x, y, z = 125, 151, 68 point = np.array([-2.3, 1.1, 2.2]) * 10 x, y, z = utils.apply_trans(ras_tkr2vox, point).astype(np.int) # x, y, z = 151, 106, 139 # x, y, z = 166, 118, 113 p = [133, 122, 84] p = [112.29232267212728, 125, 63.956603631432188] open_slicer(ct_fname, *p) # ct_header = nib.load(ct_fname).get_header() # ct_vox2ras_tkr = ct_header.get_vox2ras_tkr() # ct_ras_tkr2vox = np.linalg.inv(ct_vox2ras_tkr) # ct_x, ct_y, ct_z = utils.apply_trans(ct_ras_tkr2vox, point).astype(np.int) # save_slices(subject, mri_fname, x, y, z, 'mri') # save_slices(subject, ct_fname, 128, 139, 110, 'ct') # print('Error! Should send the mri fname, x, y and z') print('asdf')
def calc_subcorticals_pos(subject, aseg_data, lut): output_fname = op.join(MMVT_DIR, subject, 'subcorticals_pos.npz') if op.isfile(output_fname): d = np.load(output_fname) return d['pos'], list(d['names']) subject_header = nib.load(op.join(SUBJECTS_DIR, subject, 'mri', 'T1.mgz')).header # codes_file = op.join(MMVT_DIR, 'sub_cortical_codes.txt') # subcortical_lookup = np.genfromtxt(codes_file, dtype=str, delimiter=',') aseg_unique_vals = np.unique(aseg_data) subcortical_lookup = [(label, index) for label, index in zip(lut['label'], lut['index']) if index < 1000 and label not in WHITES and label != 'Unknown' and index in aseg_unique_vals] subs_pos = np.zeros((len(subcortical_lookup), 3)) for sub_ind, (sub_name, sub_code) in enumerate(subcortical_lookup): t1_inds = np.where(aseg_data == int(sub_code)) center_vox = np.array(t1_inds).mean(axis=1) subs_pos[sub_ind] = utils.apply_trans(subject_header.get_vox2ras_tkr(), center_vox) names = [name for name, index in subcortical_lookup] np.savez(output_fname, pos=subs_pos, names=names) return subs_pos, names
def calc_elas(subject, template, specific_elecs_names=[], bipolar=False, atlas='aparc.DKTatlas', error_radius=3, elc_length=4, print_warnings=False, overwrite=False, n_jobs=1): fol = utils.make_dir( op.join(MMVT_DIR, subject, 'electrodes', 'ela_morphed')) elecs_names, elecs_pos, elecs_dists, elecs_types, elecs_oris, excludes = get_electrodes_info( subject, atlas, bipolar, n_jobs) specific_elecs_names = specific_elecs_names if len( specific_elecs_names) > 0 else elecs_names elecs_info = [(elec_name, elec_pos, elec_dist, elec_type, elec_ori) for elec_name, elec_pos, elec_dist, elec_type, elec_ori in \ zip(elecs_names, elecs_pos, elecs_dists, elecs_types, elecs_oris) if elec_name in specific_elecs_names] (labels_vertices, regions_center_of_mass, regions_names, aseg_data, lut, pia_verts) = init(subject, atlas, n_jobs) atlas = utils.fix_atlas_name(subject, atlas, SUBJECTS_DIR) if not utils.both_hemi_files_exist( op.join(SUBJECTS_DIR, template, 'label', '{}.{}.annot'.format( '{hemi}', atlas))): raise Exception('No {} atlas for {}!'.format(atlas, template)) else: template_atlas = atlas (template_labels_vertices, template_regions_center_of_mass, template_regions_names, template_aseg_data, lut, template_pia_verts) = init(template, template_atlas, n_jobs) len_lh_pia = len(pia_verts['lh']) template_len_lh_pia = len(template_pia_verts['lh']) template_header = nib.load(op.join(SUBJECTS_DIR, template, 'mri', 'T1.mgz')).header epsilon = 0 max_run_num = 1000 parallel = True for elec_name, elec_pos, elec_dist, elec_type, elec_ori in elecs_info: elec_output_fname = op.join(fol, '{}_ela_morphed.npz'.format(elec_name)) if op.isfile(elec_output_fname) and not overwrite: d = np.load(elec_output_fname) print('{}: err: {}, new_pos={}'.format(elec_name, d['err'], d['pos'])) continue elec_labeling = calc_ela(subject, bipolar, elec_name, elec_pos, elec_type, elec_ori, elec_dist, labels_vertices, aseg_data, lut, pia_verts, len_lh_pia, excludes, error_radius, elc_length, print_warnings, overwrite, n_jobs) print('subject_ela:') print_ela(elec_labeling) elec_labeling_no_whites = calc_elec_labeling_no_white(elec_labeling) template_elec_pos = calc_prob_pos(elec_labeling_no_whites, template_regions_center_of_mass, template_regions_names) subject_prob_pos_in_template_space = template_elec_pos.copy() template_elec_vox = np.rint( utils.apply_trans(np.linalg.inv(template_header.get_vox2ras_tkr()), template_elec_pos).astype(int)) elec_labeling_template = calc_ela( template, bipolar, elec_name, template_elec_pos, elec_type, elec_ori, elec_dist, template_labels_vertices, template_aseg_data, lut, template_pia_verts, template_len_lh_pia, excludes, error_radius, elc_length, print_warnings, overwrite, n_jobs) err = comp_elecs_labeling(elec_labeling_template, template_regions_center_of_mass, template_regions_names, subject_prob_pos_in_template_space) run_num = 0 stop_gradient = False print(err) while not stop_gradient and err > epsilon and run_num < max_run_num: dxyzs = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)] if parallel: new_template_elec_pos_arr = [ utils.apply_trans(template_header.get_vox2ras_tkr(), template_elec_vox + dxyz) for dxyz in dxyzs ] params = [ (template, bipolar, elec_name, new_template_elec_pos, elec_type, elec_ori, elec_dist, template_labels_vertices, template_aseg_data, lut, template_pia_verts, template_len_lh_pia, elec_labeling_no_whites, regions_center_of_mass, regions_names, template_regions_center_of_mass, template_regions_names, subject_prob_pos_in_template_space, excludes, error_radius, elc_length, overwrite) for new_template_elec_pos in new_template_elec_pos_arr ] results = utils.run_parallel(_parallel_calc_ela_err, params, len(dxyzs) if n_jobs > 1 else 1) errs = [res[1] for res in results] ind = np.argmin(errs) new_template_pos = new_template_elec_pos_arr[ind] best_ela = results[ind][0] regions, new_probs = norm_probs( calc_elec_labeling_no_white(best_ela)) print([ '{} ({}) '.format(r, p) for r, p in zip(regions, new_probs) ]) min_err = errs[ind] if min_err >= err: stop_gradient = True else: err = min_err else: for dxyz in dxyzs: new_template_elec_pos = utils.apply_trans( template_header.get_vox2ras_tkr(), template_elec_vox + dxyz) elec_labeling_template = calc_ela( template, bipolar, elec_name, new_template_elec_pos, elec_type, elec_ori, elec_dist, template_labels_vertices, template_aseg_data, lut, template_pia_verts, template_len_lh_pia, excludes, error_radius, elc_length, print_warnings, overwrite, n_jobs) new_err = comp_elecs_labeling( elec_labeling_template, template_regions_center_of_mass, template_regions_names, subject_prob_pos_in_template_space) if new_err < err: new_template_pos = new_template_elec_pos err = new_err break else: stop_gradient = True print('*** {}){} ***'.format(run_num + 1, err)) print_ela(elec_labeling_template) run_num += 1 template_elec_vox = np.rint( utils.apply_trans( np.linalg.inv(template_header.get_vox2ras_tkr()), new_template_pos).astype(int)) if stop_gradient: print('Stop gradient!!!') print('subject_ela:') print_ela(elec_labeling) print('template ela:') print_ela(elec_labeling_template) print('Save output to {}'.format(elec_output_fname)) np.savez(elec_output_fname, pos=new_template_pos, name=elec_name, err=err)
else: # open_slicer('/home/noam/mmvt/mg78/freeview/orig.mgz', 0.9862712 , -45.62893867, 12.2588706) # subject = 'nmr00979' # subject = '100307' subject = 'mg102' trans_fname = op.join(MMVT_DIR, subject, 't1_trans.npz') d = utils.Bag(np.load(trans_fname)) ras_tkr2vox = np.linalg.inv(d.vox2ras_tkr) mri_fname = op.join(MMVT_DIR, subject, 'freeview', 'T1.mgz') ct_fname = op.join(MMVT_DIR, subject, 'freeview', 'ct.mgz') # ct_fname = op.join(MMVT_DIR, subject, 'freeview', 'ct_nas.nii.gz') # x, y, z = 0.9862712 , -45.62893867, 12.2588706 # x, y, z = 125, 151, 68 point = np.array([-2.3, 1.1, 2.2]) * 10 x, y, z = utils.apply_trans(ras_tkr2vox, point).astype(np.int) # x, y, z = 151, 106, 139 # x, y, z = 166, 118, 113 p = [133, 122, 84] p = [112.29232267212728, 125, 63.956603631432188] open_slicer(ct_fname, *p) # ct_header = nib.load(ct_fname).get_header() # ct_vox2ras_tkr = ct_header.get_vox2ras_tkr() # ct_ras_tkr2vox = np.linalg.inv(ct_vox2ras_tkr) # ct_x, ct_y, ct_z = utils.apply_trans(ct_ras_tkr2vox, point).astype(np.int) # save_slices(subject, mri_fname, x, y, z, 'mri') # save_slices(subject, ct_fname, 128, 139, 110, 'ct') # print('Error! Should send the mri fname, x, y and z')