def check_ply_files(subject): ply_subject = op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial.ply') npz_subject = op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial.npz') ply_blender = op.join(MMVT_DIR, subject, 'surf', '{}.pial.ply') npz_blender = op.join(MMVT_DIR, subject, 'surf', '{}.pial.npz') ok = True for hemi in HEMIS: # print('reading {}'.format(ply_subject.format(hemi))) verts1, faces1 = utils.read_ply_file(ply_subject.format(hemi), npz_subject.format(hemi)) # print('reading {}'.format(ply_blender.format(hemi))) verts2, faces2 = utils.read_ply_file(ply_blender.format(hemi), npz_blender.format(hemi)) print('vertices: ply: {}, blender: {}'.format(verts1.shape[0], verts2.shape[0])) print('faces: ply: {}, blender: {}'.format(faces1.shape[0], faces2.shape[0])) ok = ok and verts1.shape[0] == verts2.shape[0] and faces1.shape[0]==faces2.shape[0] return ok
def check_ply_files(subject): ply_subject = op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial.ply') npz_subject = op.join(SUBJECTS_DIR, subject, 'mmvt', '{}.pial.npz') ply_blender = op.join(MMVT_DIR, subject, '{}.pial.ply') npz_blender = op.join(MMVT_DIR, subject, '{}.pial.npz') ok = True for hemi in HEMIS: # print('reading {}'.format(ply_subject.format(hemi))) verts1, faces1 = utils.read_ply_file(ply_subject.format(hemi), npz_subject.format(hemi)) # print('reading {}'.format(ply_blender.format(hemi))) verts2, faces2 = utils.read_ply_file(ply_blender.format(hemi), npz_blender.format(hemi)) print('vertices: ply: {}, blender: {}'.format(verts1.shape[0], verts2.shape[0])) print('faces: ply: {}, blender: {}'.format(faces1.shape[0], faces2.shape[0])) ok = ok and verts1.shape[0] == verts2.shape[0] and faces1.shape[0]==faces2.shape[0] return ok
def _save_fmri_colors(subject, hemi, x, threshold, output_file='', verts=None, surf_name='pial'): if verts is None: # Try to read the hemi ply file to check if the vertices number is correct ply_file = op.join(SUBJECTS_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_name)) if op.isfile(ply_file): verts, _ = utils.read_ply_file(ply_file) if len(x) != verts.shape[0]: raise Exception( "fMRI contrast map and the hemi doens't have the same vertices number!" ) else: print("No ply file, Can't check the vertices number") colors = utils.arr_to_colors_two_colors_maps(x, cm_big='YlOrRd', cm_small='PuBu', threshold=threshold, default_val=1) colors = np.hstack((x.reshape((len(x), 1)), colors)) if output_file != '': op.join(BLENDER_ROOT_DIR, subject, 'fmri_{}.npy'.format(hemi)) print('Saving {}'.format(output_file)) np.save(output_file, colors)
def init_clusters(subject, contrast_name, input_fol): input_fname = op.join(input_fol, 'fmri_{}_{}.npy'.format(contrast_name, '{hemi}')) contrast_per_hemi, verts_per_hemi = {}, {} for hemi in utils.HEMIS: fmri_fname = input_fname.format(hemi=hemi) if utils.file_type(input_fname) == 'npy': x = np.load(fmri_fname) contrast_per_hemi[hemi] = x[:, 0] else: # try nibabel x = nib.load(fmri_fname) contrast_per_hemi[hemi] = x.get_data().ravel() pial_npz_fname = op.join(BLENDER_ROOT_DIR, subject, '{}.pial.npz'.format(hemi)) if not op.isfile(pial_npz_fname): print('No pial npz file (), creating one'.format(pial_npz_fname)) verts, faces = utils.read_ply_file( op.join(BLENDER_ROOT_DIR, subject, '{}.pial.ply'.format(hemi))) np.savez(pial_npz_fname[:-4], verts=verts, faces=faces) d = np.load(pial_npz_fname) verts_per_hemi[hemi] = d['verts'] connectivity_fname = op.join(BLENDER_ROOT_DIR, subject, 'spatial_connectivity.pkl') if not op.isfile(connectivity_fname): from src.preproc import anatomy_preproc anatomy_preproc.create_spatial_connectivity(subject) connectivity_per_hemi = utils.load(connectivity_fname) return contrast_per_hemi, connectivity_per_hemi, verts_per_hemi
def calc_faces_verts_dic(subject, atlas, overwrite=False): # hemis_plus = HEMIS + ['cortex'] ply_files = [op.join(MMVT_DIR, subject, 'surf', '{}.pial.npz'.format(hemi)) for hemi in utils.HEMIS] out_files = [op.join(MMVT_DIR, subject, 'faces_verts_{}.npy'.format(hemi)) for hemi in utils.HEMIS] subcortical_plys = glob.glob(op.join(MMVT_DIR, subject, 'subcortical', '*.ply')) errors = {} if len(subcortical_plys) > 0: faces_verts_dic_fnames = [op.join(MMVT_DIR, subject, 'subcortical', '{}_faces_verts.npy'.format( utils.namebase(ply))) for ply in subcortical_plys] ply_files.extend(subcortical_plys) out_files.extend(faces_verts_dic_fnames) for hemi in utils.HEMIS: labels_plys = glob.glob(op.join(MMVT_DIR, subject, '{}.pial.{}'.format(atlas, hemi), '*.ply')) if len(labels_plys) > 0: faces_verts_dic_fnames = [op.join(MMVT_DIR, subject, '{}.pial.{}'.format(atlas, hemi), '{}_faces_verts.npy'.format( utils.namebase(ply))) for ply in labels_plys] ply_files.extend(labels_plys) out_files.extend(faces_verts_dic_fnames) for ply_file, out_file in zip(ply_files, out_files): if not overwrite and op.isfile(out_file): # print('{} already exist.'.format(out_file)) continue # ply_file = op.join(SUBJECTS_DIR, subject,'surf', '{}.pial.ply'.format(hemi)) # print('preparing a lookup table for {}'.format(ply_file)) verts, faces = utils.read_ply_file(ply_file) errors = utils.calc_ply_faces_verts(verts, faces, out_file, overwrite, utils.namebase(ply_file), errors) if len(errors) > 0: for k, message in errors.items(): print('{}: {}'.format(k, message)) return len(errors) == 0
def freesurfer_surface_to_blender_surface(subject, hemi='both', overwrite=False): for hemi in utils.get_hemis(hemi): utils.make_dir(op.join(MMVT_DIR, subject, 'surf')) for surf_type in ['inflated', 'pial']: surf_name = op.join(SUBJECTS_DIR, subject, 'surf', '{}.{}'.format(hemi, surf_type)) surf_wavefront_name = '{}.asc'.format(surf_name) surf_new_name = '{}.srf'.format(surf_name) hemi_ply_fname = '{}.ply'.format(surf_name) mmvt_hemi_ply_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_type)) mmvt_hemi_npz_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.npz'.format(hemi, surf_type)) if overwrite or not op.isfile(mmvt_hemi_ply_fname) and not op.isfile(mmvt_hemi_npz_fname): print('{} {}: convert srf to asc'.format(hemi, surf_type)) utils.run_script('mris_convert {} {}'.format(surf_name, surf_wavefront_name)) os.rename(surf_wavefront_name, surf_new_name) print('{} {}: convert asc to ply'.format(hemi, surf_type)) convert_hemis_srf_to_ply(subject, hemi, surf_type) if op.isfile(mmvt_hemi_ply_fname): os.remove(mmvt_hemi_ply_fname) shutil.copy(hemi_ply_fname, mmvt_hemi_ply_fname) ply_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_type)) if not op.isfile(mmvt_hemi_npz_fname): verts, faces = utils.read_ply_file(ply_fname) np.savez(mmvt_hemi_npz_fname, verts=verts, faces=faces) return utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.pial.ply')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.pial.npz')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.inflated.ply')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.inflated.npz'))
def init_clusters(subject, contrast_name, input_fol): input_fname = op.join(input_fol, 'fmri_{}_{}.npy'.format(contrast_name, '{hemi}')) contrast_per_hemi, verts_per_hemi = {}, {} for hemi in utils.HEMIS: fmri_fname = input_fname.format(hemi=hemi) if utils.file_type(input_fname) == 'npy': x = np.load(fmri_fname) contrast_per_hemi[hemi] = x[:, 0] else: # try nibabel x = nib.load(fmri_fname) contrast_per_hemi[hemi] = x.get_data().ravel() pial_npz_fname = op.join(BLENDER_ROOT_DIR, subject, '{}.pial.npz'.format(hemi)) if not op.isfile(pial_npz_fname): print('No pial npz file (), creating one'.format(pial_npz_fname)) verts, faces = utils.read_ply_file(op.join(BLENDER_ROOT_DIR, subject, '{}.pial.ply'.format(hemi))) np.savez(pial_npz_fname[:-4], verts=verts, faces=faces) d = np.load(pial_npz_fname) verts_per_hemi[hemi] = d['verts'] connectivity_fname = op.join(BLENDER_ROOT_DIR, subject, 'spatial_connectivity.pkl') if not op.isfile(connectivity_fname): from src.preproc import anatomy_preproc anatomy_preproc.create_spatial_connectivity(subject) connectivity_per_hemi = utils.load(connectivity_fname) return contrast_per_hemi, connectivity_per_hemi, verts_per_hemi
def transform_to_another_subject(subject, region, subjects_dir): colin27_xfm = tu.get_talxfm('colin27', subjects_dir) xfm = tu.get_talxfm('colin27', subjects_dir) for hemi in ['lh', 'rh']: verts, faces = utils.read_ply_file(op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi))) verts = tu.apply_trans(colin27_xfm, verts) verts = tu.apply_trans(np.linalg.inv(xfm), verts) utils.write_ply_file(verts, faces, op.join(MMVT_DIR, subject, 'subcortical', '{}_{}.ply'.format(region, hemi)))
def transform_to_another_subject(subject, region, subjects_dir): import mne.source_space import mne.transforms colin27_xfm = mne.source_space._read_talxfm('colin27', subjects_dir, 'nibabel') xfm = mne.source_space._read_talxfm(subject, subjects_dir, 'nibabel') for hemi in ['lh', 'rh']: verts, faces = utils.read_ply_file(op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi))) verts = apply_trans(colin27_xfm['trans'], verts) verts = apply_trans(np.linalg.inv(xfm['trans']), verts) utils.write_ply_file(verts, faces, op.join(MMVT_DIR, subject, 'subcortical', '{}_{}.ply'.format(region, hemi)))
def convert_and_rename_subcortical_files(subject, fol, new_fol, lookup): obj_files = glob.glob(op.join(fol, '*.srf')) utils.delete_folder_files(new_fol) for obj_file in obj_files: num = int(op.basename(obj_file)[:-4].split('_')[-1]) new_name = lookup.get(num, '') if new_name != '': utils.srf2ply(obj_file, op.join(new_fol, '{}.ply'.format(new_name))) verts, faces = utils.read_ply_file(op.join(new_fol, '{}.ply'.format(new_name))) np.savez(op.join(new_fol, '{}.npz'.format(new_name)), verts=verts, faces=faces) copy_subcorticals_to_blender(new_fol, subject)
def convert_and_rename_subcortical_files(subject, fol, new_fol, lookup, mmvt_subcorticals_fol_name='subcortical'): obj_files = glob.glob(op.join(fol, '*.srf')) utils.delete_folder_files(new_fol) for obj_file in obj_files: num = int(op.basename(obj_file)[:-4].split('_')[-1]) new_name = lookup.get(num, '') if new_name != '': utils.srf2ply(obj_file, op.join(new_fol, '{}.ply'.format(new_name))) verts, faces = utils.read_ply_file(op.join(new_fol, '{}.ply'.format(new_name))) np.savez(op.join(new_fol, '{}.npz'.format(new_name)), verts=verts, faces=faces) copy_subcorticals_to_mmvt(new_fol, subject, mmvt_subcorticals_fol_name)
def create_faces_verts(subject): skull_fol = op.join(MMVT_DIR, subject, 'skull') errors = {} for skull_surf in ['inner_skull', 'outer_skull']: ply_fname = op.join(skull_fol, '{}.ply'.format(skull_surf)) verts, faces = utils.read_ply_file(ply_fname) faces_verts_fname = op.join(skull_fol, 'faces_verts_{}.npy'.format(skull_surf)) errors = utils.calc_ply_faces_verts(verts, faces, faces_verts_fname, False, utils.namebase(ply_fname), errors) if len(errors) > 0: for k, message in errors.items(): print('{}: {}'.format(k, message))
def convert_and_rename_subcortical_files(subject, fol, new_fol, lookup): obj_files = glob.glob(op.join(fol, '*.srf')) utils.delete_folder_files(new_fol) for obj_file in obj_files: num = int(op.basename(obj_file)[:-4].split('_')[-1]) new_name = lookup.get(num, '') if new_name != '': utils.srf2ply(obj_file, op.join(new_fol, '{}.ply'.format(new_name))) verts, faces = utils.read_ply_file(op.join(new_fol, '{}.ply'.format(new_name))) np.savez(op.join(new_fol, '{}.npz'.format(new_name)), verts=verts, faces=faces) blender_fol = op.join(MMVT_DIR, subject, 'subcortical') if op.isdir(blender_fol): shutil.rmtree(blender_fol) shutil.copytree(new_fol, blender_fol)
def calculate_subcorticals_activity(subject, volume_file, subcortical_codes_file='', aseg_stats_file_name='', method='max', k_points=100, do_plot=False): x = nib.load(volume_file) x_data = x.get_data() if do_plot: fig = plt.figure() ax = Axes3D(fig) sig_subs = [] if subcortical_codes_file != '': subcortical_codes = np.genfromtxt(subcortical_codes_file, dtype=str, delimiter=',') seg_labels = map(str, subcortical_codes[:, 0]) elif aseg_stats_file_name != '': aseg_stats = np.genfromtxt(aseg_stats_file_name, dtype=str, delimiter=',', skip_header=1) seg_labels = map(str, aseg_stats[:, 0]) else: raise Exception('No segmentation file!') # Find the segmentation file aseg_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'aseg.mgz') aseg = nib.load(aseg_fname) aseg_hdr = aseg.get_header() out_folder = op.join(SUBJECTS_DIR, subject, 'subcortical_fmri_activity') if not op.isdir(out_folder): os.mkdir(out_folder) sub_cortical_generator = utils.sub_cortical_voxels_generator(aseg, seg_labels, 5, False, FREE_SURFER_HOME) for pts, seg_name, seg_id in sub_cortical_generator: print(seg_name) verts, _ = utils.read_ply_file(op.join(SUBJECTS_DIR, subject, 'subcortical', '{}.ply'.format(seg_name))) vals = np.array([x_data[i, j, k] for i, j, k in pts]) is_sig = np.max(np.abs(vals)) >= 2 print(seg_name, seg_id, np.mean(vals), is_sig) pts = utils.transform_voxels_to_RAS(aseg_hdr, pts) # plot_points(verts,pts) verts_vals = calc_vert_vals(verts, pts, vals, method=method, k_points=k_points) print('verts vals: {}+-{}'.format(verts_vals.mean(), verts_vals.std())) if sum(abs(verts_vals)>2) > 0: sig_subs.append(seg_name) verts_colors = utils.arr_to_colors_two_colors_maps(verts_vals, threshold=2) verts_data = np.hstack((np.reshape(verts_vals, (len(verts_vals), 1)), verts_colors)) np.save(op.join(out_folder, seg_name), verts_data) if do_plot: plot_points(verts, colors=verts_colors, fig_name=seg_name, ax=ax) # print(pts) utils.rmtree(op.join(BLENDER_ROOT_DIR, subject, 'subcortical_fmri_activity')) shutil.copytree(out_folder, op.join(BLENDER_ROOT_DIR, subject, 'subcortical_fmri_activity')) if do_plot: plt.savefig('/home/noam/subjects/mri/mg78/subcortical_fmri_activity/figures/brain.jpg') plt.show()
def calc_faces_verts_dic(subject, atlas, overwrite=False): # hemis_plus = HEMIS + ['cortex'] ply_files = [op.join(MMVT_DIR, subject, 'surf', '{}.pial.npz'.format(hemi)) for hemi in utils.HEMIS] out_files = [op.join(MMVT_DIR, subject, 'faces_verts_{}.npy'.format(hemi)) for hemi in utils.HEMIS] subcortical_plys = glob.glob(op.join(MMVT_DIR, subject, 'subcortical', '*.ply')) errors = [] if len(subcortical_plys) > 0: faces_verts_dic_fnames = [op.join(MMVT_DIR, subject, 'subcortical', '{}_faces_verts.npy'.format( utils.namebase(ply))) for ply in subcortical_plys] ply_files.extend(subcortical_plys) out_files.extend(faces_verts_dic_fnames) for hemi in utils.HEMIS: labels_plys = glob.glob(op.join(MMVT_DIR, subject, '{}.pial.{}'.format(atlas, hemi), '*.ply')) if len(labels_plys) > 0: faces_verts_dic_fnames = [op.join(MMVT_DIR, subject, '{}.pial.{}'.format(atlas, hemi), '{}_faces_verts.npy'.format( utils.namebase(ply))) for ply in labels_plys] ply_files.extend(labels_plys) out_files.extend(faces_verts_dic_fnames) for ply_file, out_file in zip(ply_files, out_files): if not overwrite and op.isfile(out_file): # print('{} already exist.'.format(out_file)) continue # ply_file = op.join(SUBJECTS_DIR, subject,'surf', '{}.pial.ply'.format(hemi)) # print('preparing a lookup table for {}'.format(ply_file)) verts, faces = utils.read_ply_file(ply_file) _faces = faces.ravel() print('{}: verts: {}, faces: {}, faces ravel: {}'.format(utils.namebase(ply_file), verts.shape[0], faces.shape[0], len(_faces))) faces_arg_sort = np.argsort(_faces) faces_sort = np.sort(_faces) faces_count = Counter(faces_sort) max_len = max([v for v in faces_count.values()]) lookup = np.ones((verts.shape[0], max_len)) * -1 diff = np.diff(faces_sort) n = 0 for ind, (k, v) in enumerate(zip(faces_sort, faces_arg_sort)): lookup[k, n] = v n = 0 if ind < len(diff) and diff[ind] > 0 else n+1 # print('writing {}'.format(out_file)) np.save(out_file, lookup.astype(np.int)) print('{} max lookup val: {}'.format(utils.namebase(ply_file), int(np.max(lookup)))) if len(_faces) != int(np.max(lookup)) + 1: errors[utils.namebase(ply_file)] = 'Wrong values in lookup table! ' + \ 'faces ravel: {}, max looup val: {}'.format(len(_faces), int(np.max(lookup))) if len(errors) > 0: for k, message in errors.items(): print('{}: {}'.format(k, message)) return len(errors) == 0
def _save_fmri_colors(subject, hemi, x, threshold, output_file='', verts=None, surf_name='pial'): if verts is None: # Try to read the hemi ply file to check if the vertices number is correct ply_file = op.join(SUBJECTS_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_name)) if op.isfile(ply_file): verts, _ = utils.read_ply_file(ply_file) if len(x) != verts.shape[0]: raise Exception("fMRI contrast map and the hemi doens't have the same vertices number!") else: print("No ply file, Can't check the vertices number") colors = utils.arr_to_colors_two_colors_maps(x, cm_big='YlOrRd', cm_small='PuBu', threshold=threshold, default_val=1) colors = np.hstack((x.reshape((len(x), 1)), colors)) if output_file != '': op.join(BLENDER_ROOT_DIR, subject, 'fmri_{}.npy'.format(hemi)) print('Saving {}'.format(output_file)) np.save(output_file, colors)
def load_surf(subject, mmvt_dir, subjects_dir): verts = {} for hemi in HEMIS: if op.isfile( op.join(mmvt_dir, subject, 'surf', '{}.pial.npz'.format(hemi))): hemi_verts, _ = utils.read_pial(subject, mmvt_dir, hemi) elif op.isfile( op.join(subjects_dir, subject, 'surf', '{}.pial.ply'.format(hemi))): hemis_verts, _ = utils.read_ply_file( op.join(subjects_dir, subject, 'surf', '{}.pial.ply'.format(hemi))) else: print("Can't find {} pial ply/npz files!".format(hemi)) return False verts[hemi] = hemi_verts return verts
def convert_perecelated_cortex(subject, aparc_name, surf_type='pial', overwrite_ply_files=False, hemi='both'): lookup = {} for hemi in utils.get_hemis(hemi): lookup[hemi] = create_labels_lookup(subject, hemi, aparc_name) if len(lookup[hemi]) == 0: continue srf_fol = op.join(SUBJECTS_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi)) ply_fol = op.join(SUBJECTS_DIR, subject,'{}_{}_{}_ply'.format(aparc_name, surf_type, hemi)) blender_fol = op.join(MMVT_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi)) utils.convert_srf_files_to_ply(srf_fol, overwrite_ply_files) rename_cortical(lookup, srf_fol, ply_fol) if surf_type == 'inflated': for ply_fname in glob.glob(op.join(ply_fol, '*.ply')): verts, faces = utils.read_ply_file(ply_fname) verts_offset = 5.5 if hemi == 'rh' else -5.5 verts[:, 0] = verts[:, 0] + verts_offset utils.write_ply_file(verts, faces, ply_fname) utils.rmtree(blender_fol) shutil.copytree(ply_fol, blender_fol) return lookup
def freesurfer_surface_to_blender_surface(subject, hemi='both', overwrite=False): # verts, faces = {}, {} for hemi in utils.get_hemis(hemi): utils.make_dir(op.join(MMVT_DIR, subject, 'surf')) for surf_type in ['inflated', 'pial']: surf_name = op.join(SUBJECTS_DIR, subject, 'surf', '{}.{}'.format(hemi, surf_type)) surf_wavefront_name = '{}.asc'.format(surf_name) surf_new_name = '{}.srf'.format(surf_name) hemi_ply_fname = '{}.ply'.format(surf_name) mmvt_hemi_ply_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_type)) mmvt_hemi_npz_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.npz'.format(hemi, surf_type)) if overwrite or not op.isfile(mmvt_hemi_ply_fname) and not op.isfile(mmvt_hemi_npz_fname): print('{}: convert srf to asc'.format(hemi)) utils.run_script('mris_convert {} {}'.format(surf_name, surf_wavefront_name)) os.rename(surf_wavefront_name, surf_new_name) print('{}: convert asc to ply'.format(hemi)) convert_hemis_srf_to_ply(subject, hemi, surf_type) # if surf_type == 'inflated': # verts, faces = utils.read_ply_file(hemi_ply_fname) # verts_offset = 5.5 if hemi == 'rh' else -5.5 # verts[:, 0] = verts[:, 0] + verts_offset # utils.write_ply_file(verts, faces, '{}_offset.ply'.format(surf_name)) if op.isfile(mmvt_hemi_ply_fname): os.remove(mmvt_hemi_ply_fname) shutil.copy(hemi_ply_fname, mmvt_hemi_ply_fname) ply_fname = op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surf_type)) if not op.isfile(mmvt_hemi_npz_fname): verts, faces = utils.read_ply_file(ply_fname) np.savez(mmvt_hemi_npz_fname, verts=verts, faces=faces) # verts[hemi], faces[hemi] = utils.read_ply_file(mmvt_hemi_npz_fname) # if not op.isfile(op.join(MMVT_DIR, subject, 'cortex.pial.npz')): # faces['rh'] += np.max(faces['lh']) + 1 # verts_cortex = np.vstack((verts['lh'], verts['rh'])) # faces_cortex = np.vstack((faces['lh'], faces['rh'])) # utils.write_ply_file(verts_cortex, faces_cortex, op.join(MMVT_DIR, subject, 'cortex.pial.ply')) # np.savez(op.join(MMVT_DIR, subject, 'cortex.pial.npz'), verts=verts_cortex, faces=faces_cortex) return utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.pial.ply')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.pial.npz')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.inflated.ply')) and \ utils.both_hemi_files_exist(op.join(MMVT_DIR, subject, 'surf', '{hemi}.inflated.npz'))
def calc_faces_verts_dic(subject, overwrite=False): ply_files = [op.join(SUBJECTS_DIR, subject,'surf', '{}.pial.ply'.format(hemi)) for hemi in HEMIS] out_files = [op.join(MMVT_DIR, subject, 'faces_verts_{}.npy'.format(hemi)) for hemi in HEMIS] subcortical_plys = glob.glob(op.join(MMVT_DIR, subject, 'subcortical', '*.ply')) errors = [] if len(subcortical_plys) > 0: faces_verts_dic_fnames = [op.join(MMVT_DIR, subject, 'subcortical', '{}_faces_verts.npy'.format( utils.namebase(ply))) for ply in subcortical_plys] ply_files.extend(subcortical_plys) out_files.extend(faces_verts_dic_fnames) for ply_file, out_file in zip(ply_files, out_files): if not overwrite and op.isfile(out_file): # print('{} already exist.'.format(out_file)) continue # ply_file = op.join(SUBJECTS_DIR, subject,'surf', '{}.pial.ply'.format(hemi)) # print('preparing a lookup table for {}'.format(ply_file)) verts, faces = utils.read_ply_file(ply_file) _faces = faces.ravel() print('{}: verts: {}, faces: {}, faces ravel: {}'.format(utils.namebase(ply_file), verts.shape[0], faces.shape[0], len(_faces))) faces_arg_sort = np.argsort(_faces) faces_sort = np.sort(_faces) faces_count = Counter(faces_sort) max_len = max([v for v in faces_count.values()]) lookup = np.ones((verts.shape[0], max_len)) * -1 diff = np.diff(faces_sort) n = 0 for ind, (k, v) in enumerate(zip(faces_sort, faces_arg_sort)): lookup[k, n] = v n = 0 if ind<len(diff) and diff[ind] > 0 else n+1 # print('writing {}'.format(out_file)) np.save(out_file, lookup.astype(np.int)) print('{} max lookup val: {}'.format(utils.namebase(ply_file), int(np.max(lookup)))) if len(_faces) != int(np.max(lookup)) + 1: errors[utils.namebase(ply_file)] = 'Wrong values in lookup table! ' + \ 'faces ravel: {}, max looup val: {}'.format(len(_faces), int(np.max(lookup))) if len(errors) > 0: for k, message in errors.items(): print('{}: {}'.format(k, message)) return len(errors) == 0
def freesurfer_surface_to_blender_surface(subject, hemi='both', overwrite=False): for hemi in utils.get_hemis(hemi): surf_name = op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial'.format(hemi)) surf_wavefront_name = '{}.asc'.format(surf_name) surf_new_name = '{}.srf'.format(surf_name) hemi_ply_fname = '{}.ply'.format(surf_name) mmvt_hemi_ply_fname = op.join(MMVT_DIR, subject, '{}.pial.ply'.format(hemi)) if overwrite or not op.isfile(hemi_ply_fname): print('{}: convert srf to asc'.format(hemi)) utils.run_script('mris_convert {} {}'.format(surf_name, surf_wavefront_name)) os.rename(surf_wavefront_name, surf_new_name) print('{}: convert asc to ply'.format(hemi)) convert_hemis_srf_to_ply(subject, hemi) for hemi in utils.get_hemis(hemi): if not op.isfile(mmvt_hemi_ply_fname): shutil.copy(hemi_ply_fname, mmvt_hemi_ply_fname) ply_fname = op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial.ply'.format(hemi)) verts, faces = utils.read_ply_file(ply_fname) np.savez(op.join(SUBJECTS_DIR, subject, 'mmvt', '{}.pial'.format(hemi)), verts=verts, faces=faces) shutil.copyfile(op.join(SUBJECTS_DIR, subject, 'mmvt', '{}.pial.npz'.format(hemi)), op.join(MMVT_DIR, subject, '{}.pial.npz'.format(hemi))) return utils.both_hemi_files_exist(op.join(SUBJECTS_DIR, subject, 'surf', '{hemi}.pial.ply'))
def calculate_subcorticals_activity(subject, volume_file, subcortical_codes_file='', aseg_stats_file_name='', method='max', k_points=100, do_plot=False): x = nib.load(volume_file) x_data = x.get_data() if do_plot: fig = plt.figure() ax = Axes3D(fig) sig_subs = [] if subcortical_codes_file != '': subcortical_codes = np.genfromtxt(subcortical_codes_file, dtype=str, delimiter=',') seg_labels = map(str, subcortical_codes[:, 0]) elif aseg_stats_file_name != '': aseg_stats = np.genfromtxt(aseg_stats_file_name, dtype=str, delimiter=',', skip_header=1) seg_labels = map(str, aseg_stats[:, 0]) else: raise Exception('No segmentation file!') # Find the segmentation file aseg_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'aseg.mgz') aseg = nib.load(aseg_fname) aseg_hdr = aseg.get_header() out_folder = op.join(SUBJECTS_DIR, subject, 'subcortical_fmri_activity') if not op.isdir(out_folder): os.mkdir(out_folder) sub_cortical_generator = utils.sub_cortical_voxels_generator( aseg, seg_labels, 5, False, FREE_SURFER_HOME) for pts, seg_name, seg_id in sub_cortical_generator: print(seg_name) verts, _ = utils.read_ply_file( op.join(SUBJECTS_DIR, subject, 'subcortical', '{}.ply'.format(seg_name))) vals = np.array([x_data[i, j, k] for i, j, k in pts]) is_sig = np.max(np.abs(vals)) >= 2 print(seg_name, seg_id, np.mean(vals), is_sig) pts = utils.transform_voxels_to_RAS(aseg_hdr, pts) # plot_points(verts,pts) verts_vals = calc_vert_vals(verts, pts, vals, method=method, k_points=k_points) print('verts vals: {}+-{}'.format(verts_vals.mean(), verts_vals.std())) if sum(abs(verts_vals) > 2) > 0: sig_subs.append(seg_name) verts_colors = utils.arr_to_colors_two_colors_maps(verts_vals, threshold=2) verts_data = np.hstack( (np.reshape(verts_vals, (len(verts_vals), 1)), verts_colors)) np.save(op.join(out_folder, seg_name), verts_data) if do_plot: plot_points(verts, colors=verts_colors, fig_name=seg_name, ax=ax) # print(pts) utils.rmtree( op.join(BLENDER_ROOT_DIR, subject, 'subcortical_fmri_activity')) shutil.copytree( out_folder, op.join(BLENDER_ROOT_DIR, subject, 'subcortical_fmri_activity')) if do_plot: plt.savefig( '/home/noam/subjects/mri/mg78/subcortical_fmri_activity/figures/brain.jpg' ) plt.show()
def recreate_mesh_faces_verts(subject, ply_fname): verts, faces = utils.read_ply_file(ply_fname) faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_faces_verts.npy') utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname, True, utils.namebase(faces_verts_out_fname))
def parcelate(subject, atlas, hemi, surface_type, vertices_labels_ids_lookup=None, overwrite_vertices_labels_lookup=False): output_fol = op.join(MMVT_DIR, subject, 'labels', '{}.{}.{}'.format(atlas, surface_type, hemi)) utils.make_dir(output_fol) vtx, fac = utils.read_ply_file( op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surface_type))) if vertices_labels_ids_lookup is None or overwrite_vertices_labels_lookup: vertices_labels_ids_lookup = lu.create_vertices_labels_lookup( subject, atlas, True, overwrite_vertices_labels_lookup)[hemi] labels = lu.read_labels(subject, SUBJECTS_DIR, atlas, hemi=hemi) if 'unknown-{}'.format(hemi) not in [l.name for l in labels]: labels.append(lu.Label([], name='unknown-{}'.format(hemi), hemi=hemi)) nV = vtx.shape[0] nF = fac.shape[0] nL = len(labels) # print('The number of unique labels is {}'.format(nL)) vtxL = [[] for _ in range(nL)] facL = [[] for _ in range(nL)] now = time.time() for f in range(nF): utils.time_to_go(now, f, nF, runs_num_to_print=50000) # Current face & labels Cfac = fac[f] Cidx = [vertices_labels_ids_lookup[vert_ind] for vert_ind in Cfac] # Depending on how many vertices of the current face # are in different labels, behave differently # nuCidx = len(np.unique(Cidx)) # if nuCidx == 1: # If all vertices share same label # same_label = utils.all_items_equall(Cidx) # if same_label: if Cidx[0] == Cidx[1] == Cidx[2]: # Add the current face to the list of faces of the # respective label, and don't create new faces facL[Cidx[0]] += [Cfac.tolist()] else: # If 2 or 3 vertices are in different labels # Create 3 new vertices at the midpoints of the 3 edges vtxCfac = vtx[Cfac] vtxnew = (vtxCfac + vtxCfac[[1, 2, 0]]) / 2 vtx = np.concatenate((vtx, vtxnew)) # Define 4 new faces, with care preserve normals (all CCW) facnew = [[Cfac[0], nV, nV + 2], [nV, Cfac[1], nV + 1], [nV + 2, nV + 1, Cfac[2]], [nV, nV + 1, nV + 2]] # Update nV for the next loop nV = vtx.shape[0] # Add the new faces to their respective labels facL[Cidx[0]] += [facnew[0]] facL[Cidx[1]] += [facnew[1]] facL[Cidx[2]] += [facnew[2]] freq_Cidx = mode(Cidx) facL[freq_Cidx] += [facnew[3]] # central face # Having defined new faces and assigned all faces to labels, now # select the vertices and redefine faces to use the new vertex indices # Also, create the file for the indices # fidx = fopen(sprintf('%s.index.csv', srfprefix), 'w'); # params = [] # for lab in range(nL): # facL_lab = facL[lab] # facL_lab_flat = utils.list_flatten(facL_lab) # vidx = list(set(facL_lab_flat)) # vtxL_lab = vtx[vidx] # params.append((facL_lab, vtxL_lab, vidx, nV, labels[lab].name, hemi, output_fol)) # utils.run_parallel(writing_ply_files_parallel, params, njobs=n_jobs) # ret = True for lab in range(nL): ret = ret and writing_ply_files(subject, surface_type, lab, facL[lab], vtx, vtxL, labels, hemi, output_fol) return ret