def calc_labels_avg(target_subject, hemi, atlas, fmri_fname, res_dir, cwd, overwrite=True, output_txt_fname='', output_sum_fname='', ret_files_name=False, **kargs): def get_labels_names(line): label_name = line.split()[4] label_nums = utils.find_num_in_str(label_name) label_num = label_nums[-1] if len(label_nums) > 0 else '' if label_num != '': name_len = label_name.find('_{}'.format(label_num)) + len(str(label_num)) + 1 label_name = '{}-{}'.format(label_name[:name_len], hemi) return label_name if output_txt_fname == '': output_txt_fname = op.join(res_dir, '{}_{}_{}.txt'.format(utils.namebase(fmri_fname), atlas, hemi)) if output_sum_fname == '': output_sum_fname = op.join(res_dir, '{}_{}_{}.sum'.format(utils.namebase(fmri_fname), atlas, hemi)) if not op.isfile(output_txt_fname) or not op.isfile(output_sum_fname) or overwrite: print('Running mri_segstats on {} ({})'.format(fmri_fname, utils.file_modification_time(fmri_fname))) utils.partial_run_script(locals(), cwd=cwd)(mri_segstats) if not op.isfile(output_txt_fname): raise Exception('The output file was not created!') labels_data = np.genfromtxt(output_txt_fname).T labels_names = utils.read_list_from_file(output_sum_fname, get_labels_names, 'rb') if ret_files_name: return labels_data, labels_names, output_txt_fname, output_sum_fname else: return labels_data, labels_names
def _morph_electrodes_parallel(p): subjects, subject_to, subjects_dir, mmvt_dir, output_fname, overwrite, print_only = p bad_subjects, good_subjects = [], [] for subject_from in subjects: electrodes_to_morph_file_name = 'electrodes_to_morph' morphed_electrodes_file_name = 'electrodes_morph_to_{}'.format( subject_to) output_fname = op.join(mmvt_dir, subject_from, 'electrodes', '{}.txt'.format(morphed_electrodes_file_name)) if op.isfile(output_fname) and not overwrite: print('{} electrode were already morphed to {}'.format( subject_from, subject_to)) continue if subject_to == 'fsaverage': subject_to = 'cvs_avg35_inMNI152' rs = utils.partial_run_script(locals(), print_only=print_only) if subject_to == 'cvs_avg35_inMNI152': rs(apply_morph_mni) else: rs(apply_morph) if op.isfile(output_fname): print('{}: electrodes file was morphed successfuly! -> {}'.format( subject_from, output_fname)) else: print('{}: Couldn\'t morph the electrodes file!'.format( subject_from))
def warp_buckner_atlas(subject, subjects_dir, bunker_atlas_fname, wrap_map_fname, print_only=False, **kargs): norm_fname = op.join(subjects_dir, subject, 'mri', 'norm.mgz') if not op.isfile(norm_fname): print("Error in warp_buckner_atlas, can't find the file {}".format( norm_fname)) return False trans_fname = op.join(subjects_dir, subject, 'mri', 'transforms', 'talairach.m3z') if not op.isfile(trans_fname): print("Error in warp_buckner_atlas, can't find the file {}".format( trans_fname)) return False wrap_map_name = op.basename(wrap_map_fname) # todo: check why we need to chage directory here current_dir = os.getcwd() os.chdir(op.join(subjects_dir, subject, 'mri')) rs = utils.partial_run_script(locals(), print_only=print_only) rs(warp_buckner_atlas_cmd) os.chdir(current_dir) if not op.isfile(wrap_map_fname): raise Exception('Error in warp_buckner_atlas!') else: print('warp_buckner_atlas output fname: {}'.format(wrap_map_fname)) return True
def create_annotation_file(subject, atlas, subjects_dir='', freesurfer_home='', overwrite_annot_file=True, print_only=False): ''' Creates the annot file by using the freesurfer mris_ca_label function Parameters ---------- subject: subject name atlas: One of the three atlases included with freesurfer: Possible values are aparc.DKTatlas40, aparc.a2009s or aparc https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation subjects_dir: subjects dir. If empty, get it from the environ freesurfer_home: freesurfer home. If empty, get it from the environ overwrite_annot_file: If False and the annot file already exist, the function return True. If True, the function delete first the annot files if exist. print_only: If True, the function will just prints the command without executing it Returns ------- True if the new annot files exist ''' atlas_types = {'aparc': 'curvature.buckner40.filled.desikan_killiany', 'aparc.a2009s': 'destrieux.simple.2009-07-28', 'aparc.DKTatlas40': 'DKTatlas40'} atlas_type = atlas_types[atlas] check_env_var('FREESURFER_HOME', freesurfer_home) check_env_var('SUBJECTS_DIR', subjects_dir) annot_files_exist = True for hemi in ['rh','lh']: annot_fname = op.join(subjects_dir, subject, 'label', '{}.{}.annot'.format(hemi, atlas)) if overwrite_annot_file and op.isfile(annot_fname): os.remove(annot_fname) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mris_ca_label) annot_files_exist = annot_files_exist and op.isfile(annot_fname) return annot_files_exist
def aseg_to_srf(subject, subjects_dir, output_fol, region_id, mask_fname, norm_fname, overwrite_subcortical_objs=False): ret = True tmp_fol = op.join(subjects_dir, subject, 'tmp', utils.rand_letters(6)) utils.make_dir(tmp_fol) rs = utils.partial_run_script(locals()) output_fname = op.join(output_fol, '{}.srf'.format(region_id)) tmp_output_fname = op.join(tmp_fol, '{}.asc'.format(region_id)) if overwrite_subcortical_objs: utils.remove_file(output_fname) try: rs(mri_pretess) rs(mri_tessellate) rs(mris_smooth) rs(mris_convert) if op.isfile(tmp_output_fname): shutil.move(tmp_output_fname, output_fname) shutil.rmtree(tmp_fol) else: ret = False except: print('Error in aseg_to_srf! subject: {}'.format(subject)) print(traceback.format_exc()) ret = False return ret
def create_seghead(subject, subjects_dir=None, print_only=False, **kargs): if subjects_dir is None: subjects_dir = utils.get_link_dir(utils.get_links_dir(), 'subjects', 'SUBJECTS_DIR') os.environ['SUBJECTS_DIR'] = subjects_dir rs = utils.partial_run_script(locals(), print_only=print_only) rs(mkheadsurf)
def check_cbf_to_t1_registeration(subject, site, scan_rescan, print_only=False): subject_fol = op.join(HOME_FOL, site, subject, scan_rescan) subject_fs_fol = op.join(FS_ROOT, get_subject_fs_folder(subject, scan_rescan)) orig_fname = op.join(subject_fs_fol, 'mri', 'orig.mgz') control_fname = op.join(subject_fol, 'Control.nii') lta_fname = op.join(subject_fol, 'control_to_T1.lta') lh_white = op.join(subject_fs_fol, 'surf', 'lh.white') rh_white = op.join(subject_fs_fol, 'surf', 'rh.white') cmd = 'freeview -transform-volume -viewport cor -v "{orig_fname}":visible=0:name=orig.mgz ' + \ '"{control_fname}":name=Control.nii:reg="{lta_fname}" --surface ' + \ '"{lh_white}":edgecolor=yellow --surface "{rh_white}":edgecolor=yellow' utils.partial_run_script(locals(), print_only=print_only)(cmd)
def combine_images(fol, movie_name, frame_rate=10, start_number=-1, images_prefix='', images_format='', images_type='', ffmpeg_cmd='ffmpeg', movie_name_full_path=False, debug=False, copy_files=False, **kwargs): images_type, images_prefix, images_format, images_format_len, start_number = find_images_props( fol, start_number, images_prefix, images_format, images_type) if movie_name == '' and images_prefix != '': movie_name = images_prefix elif movie_name == '': movie_name = 'output_video' org_fol = fol if utils.is_windows() or copy_files: fol = change_frames_names(fol, images_prefix, images_type, images_format_len) images_prefix = op.join(fol, images_prefix) if not movie_name_full_path: movie_name = op.join(fol, movie_name) combine_images_cmd = '{ffmpeg_cmd} -framerate {frame_rate} ' if start_number != 1: # You might want to use a static ffmpeg if your ffmepg version doesn't support the start_number flag, like: # ffmpeg_cmd = '~/space1/Downloads/ffmpeg-git-static/ffmpeg' combine_images_cmd += '-start_number {start_number} ' # Not working in windows: # combine_images_cmd += '-pattern_type glob -i "*.{images_type}" ' combine_images_cmd += '-i {images_prefix}{images_format}.{images_type} ' # http://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2 combine_images_cmd += '-vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" ' combine_images_cmd += '-c:v libx264 -r 30 -pix_fmt yuv420p {movie_name}.mp4' if debug: combine_images_cmd += ' -loglevel debug' rs = utils.partial_run_script(locals()) rs(combine_images_cmd) with open(op.join(org_fol, 'combine_images_cmd.txt'), 'w') as f: f.write(combine_images_cmd.format(**locals())) return '{}.mp4'.format(movie_name)
def combine_images(fol, movie_name, frame_rate=10, start_number=-1, images_prefix='', images_format='', images_type='', ffmpeg_cmd='ffmpeg', **kwargs): if images_type == '': images_types = set([utils.file_type(image) for image in glob.glob(op.join(fol, '{}*.*'.format(images_prefix)))]) for opt_type in ['png', 'jpg', 'bmp', 'gif']: if opt_type in images_types: images_type = opt_type print('Images type is {}'.format(images_type)) break if images_type == '': raise Exception("Can't find the images type!") images = glob.glob(op.join(fol, '{}*.{}'.format(images_prefix, images_type))) image_nb = utils.namebase(images[0]) number = utils.read_numbers_rx(image_nb)[0] if images_prefix == '': images_prefix = image_nb[:-len(number)] if images_format == '': images_format = '%0{}d'.format(len(number)) if start_number == -1: start_number = min([int(utils.namebase(image)[len(images_prefix):]) for image in images]) images_prefix = op.join(fol, images_prefix) movie_name = op.join(fol, movie_name) combine_images_cmd = '{ffmpeg_cmd} -framerate {frame_rate} ' if start_number > 1: # You might want to use a static ffmpeg if your ffmepg version doesn't support the start_number flag, like: # ffmpeg_cmd = '~/space1/Downloads/ffmpeg-git-static/ffmpeg' combine_images_cmd += '-start_number {start_number} ' combine_images_cmd += '-i {images_prefix}{images_format}.{images_type} ' # http://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2 combine_images_cmd += '-vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" ' combine_images_cmd += '-c:v libx264 -r 30 -pix_fmt yuv420p {movie_name}.mp4' rs = utils.partial_run_script(locals()) rs(combine_images_cmd)
def create_aparc_aseg_file(subject, atlas, subjects_dir, overwrite_aseg_file=False, print_only=False, **kargs): if not utils.both_hemi_files_exist( op.join(subjects_dir, subject, 'label', '{}.{}.annot'.format( '{hemi}', atlas))): print('No annot file was found for {}!'.format(atlas)) return False, '' # The atlas var need to be in the locals for the APARC2ASEG call aparc_aseg_file = '{}+aseg.mgz'.format(atlas) mri_file_fol = op.join(subjects_dir, subject, 'label') aparc_aseg_fname = op.join(mri_file_fol, aparc_aseg_file) rs = utils.partial_run_script(locals(), print_only=print_only, cwd=mri_file_fol) if not op.isfile(aparc_aseg_fname) or overwrite_aseg_file: now = time.time() rs(mri_aparc2aseg) if op.isfile(aparc_aseg_fname) and op.getmtime(aparc_aseg_fname) > now: return True, aparc_aseg_fname else: print('Failed to create {}'.format(aparc_aseg_fname)) return False, '' return True, aparc_aseg_fname
def flat_brain(subject, hemi, subjects_dir, print_only=False): # mris_flatten lh.inflated.patch lh.flat.patch surf_dir = op.join(subjects_dir, subject, 'surf') rs = utils.partial_run_script(locals(), cwd=surf_dir, print_only=print_only) rs(mris_flatten) return op.join(surf_dir, '{}.flat.patch'.format(hemi))
def flat_brain(subject, hemi, subjects_dir, print_only=False, **kargs): # mris_flatten lh.inflated.patch lh.flat.patch surf_dir = op.join(subjects_dir, subject, 'surf') rs = utils.partial_run_script(locals(), cwd=surf_dir, print_only=print_only) rs(mris_flatten) return get_flat_patch_fname(subject, hemi, subjects_dir)
def robust_register(subject, subjects_dir, source_fname, target_fname, output_fname, lta_name, cost_function='nmi', print_only=False, **kargs): xfms_dir = op.join(subjects_dir, subject, 'mri', 'transforms') utils.make_dir(xfms_dir) lta_fname = op.join(xfms_dir, lta_name) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mri_robust_register) return True if print_only else op.isfile(lta_fname)
def _mri_cvs_register_parallel(p): subjects, subject_to, subjects_dir, overwrite, print_only = p for subject_from in subjects: if overwrite and not print_only: utils.delete_folder_files( op.join(subjects_dir, subject_from, 'mri_cvs_register_to_{}'.format(subject_to))) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mri_cvs_register)
def transform_mni_to_subject(subject, subjects_dir, mni305_sig_file, subject_sig_file, print_only=False, **kargs): rs = utils.partial_run_script(locals(), print_only=print_only) rs(mni305_to_subject_reg) rs(mni305_to_subject)
def mask_to_srf(atlas_fol, region, hemi, colin_norm_fname): os.chdir(atlas_fol) rs = utils.partial_run_script(locals()) # rs(MRI_PRETESS) rs(MRI_TESSELLATE) rs(MRIS_SMOOTH) rs(MRIS_CONVERT) shutil.move(op.join(atlas_fol, 'tmp', '{}_{}.asc'.format(region, hemi)), op.join(atlas_fol, 'tmp', '{}_{}.srf'.format(region, hemi)))
def project_pet_volume_data(subject, volume_fname, hemi, output_fname=None, projfrac=0.5, print_only=False): temp_output = output_fname is None if output_fname is None: output_fname = mktemp(prefix="pysurfer-v2s", suffix='.mgz') rs = utils.partial_run_script(locals(), print_only=print_only) rs(mri_vol2surf_pet) surf_data = read_scalar_data(output_fname) if temp_output: os.remove(output_fname) return surf_data
def project_pet_volume_data(subject, volume_fname, hemi, output_fname=None, projfrac=0.5, print_only=False, **kargs): temp_output = output_fname is None if output_fname is None: output_fname = mktemp(prefix="pysurfer-v2s", suffix='.mgz') rs = utils.partial_run_script(locals(), print_only=print_only) rs(mri_vol2surf_pet) surf_data = read_scalar_data(output_fname) if temp_output: os.remove(output_fname) return surf_data
def transform_mni_to_subject(subject, subjects_dir, volue_fol, volume_fname='sig.mgz', subject_contrast_file_name='sig_subject.mgz', print_only=False): mni305_sig_file = os.path.join(volue_fol, volume_fname) subject_sig_file = os.path.join(volue_fol, subject_contrast_file_name) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mni305_to_subject_reg) rs(mni305_to_subject) subject_fol = op.join(subjects_dir, subject, 'mmvt') utils.make_dir(subject_fol) shutil.move(op.join(utils.get_parent_fol(), 'mn305_to_{}.dat'.format(subject)), op.join(subject_fol, 'mn305_to_{}.dat'.format(subject)))
def vol2vol(subject, source_volume_fname, target_volume_fname, output_volume_fname, cwd=None, print_only=False): if source_volume_fname != target_volume_fname: rs = utils.partial_run_script(locals(), cwd=cwd, print_only=print_only) rs(mri_vol2vol) if not op.isfile(output_volume_fname): raise Exception('vol2vol: Target file was not created!')
def surf2surf(source_subject, target_subject, hemi, source_fname, target_fname, cwd=None, print_only=False): if source_subject != target_subject: rs = utils.partial_run_script(locals(), cwd=cwd, print_only=print_only) rs(mri_surf2surf) if not op.isfile(target_fname): raise Exception('surf2surf: Target file was not created!')
def robust_register_to_template(subjects, template_system, subjects_dir, vox2vox=False, print_only=False): subject_to = 'fsaverage5' if template_system == 'ras' else 'colin27' if template_system == 'mni' else template_system for subject_from in subjects: cmd = mri_robust_register lta_name = 't1_to_{}'.format(subject_to) if vox2vox: cmd += ' --vox2vox' lta_name += '_vox2vox' rs = utils.partial_run_script(locals(), print_only=print_only) rs(cmd)
def transform_mni_to_subject(subject, subjects_dir, volue_fol, volume_fname='sig.mgz', subject_contrast_file_name='sig_subject.mgz', print_only=False): mni305_sig_file = os.path.join(volue_fol, volume_fname) subject_sig_file = os.path.join(volue_fol, subject_contrast_file_name) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mni305_to_subject_reg) rs(mni305_to_subject) subject_fol = op.join(subjects_dir, subject, 'mmvt') utils.make_dir(subject_fol) shutil.move( op.join(utils.get_parent_fol(), 'mn305_to_{}.dat'.format(subject)), op.join(subject_fol, 'mn305_to_{}.dat'.format(subject)))
def aseg_to_srf(subject, subjects_dir, output_fol, region_id, lookup, mask_fname, norm_fname, overwrite_subcortical_objs=False, **kargs): from src.utils import geometry_utils as gu ret = True tmp_fol = op.join(subjects_dir, subject, 'tmp', utils.rand_letters(6)) utils.make_dir(tmp_fol) rs = utils.partial_run_script(locals()) # output_fname = op.join(output_fol, '{}.srf'.format(region_id)) # tmp_output_fname = op.join(tmp_fol, '{}.asc'.format(region_id)) # if overwrite_subcortical_objs: # utils.remove_file(output_fname) try: rs(mri_pretess) rs(mri_tessellate) rs(mris_smooth) fs_file = op.join(tmp_fol, '{}_smooth'.format(region_id)) verts, faces = gu.read_surface(fs_file) # verts, faces = nib_fs.read_geometry(fs_file) num = int(op.basename(fs_file).split('_')[0]) if num not in lookup: print('Error in the subcorticals lookup table!') return False new_name = lookup.get(num, '') utils.write_ply_file(verts, faces, op.join(output_fol, '{}.ply'.format(new_name)), True) # mris_convert = 'mris_convert {tmp_fol}/{region_id}_smooth {tmp_fol}/{region_id}.asc' # rs(mris_convert) # if op.isfile(tmp_output_fname): # shutil.move(tmp_output_fname, output_fname) if op.isdir(tmp_fol): shutil.rmtree(tmp_fol) else: ret = False except: print('Error in aseg_to_srf! subject: {}'.format(subject)) print(traceback.format_exc()) ret = False return ret
def morph_t1(subjects, template_system, subjects_dir, print_only=False): subject_to = 'fsaverage5' if template_system == 'ras' else 'colin27' if template_system == 'mni' else template_system for subject in subjects: if not op.isfile( op.join(subjects_dir, subject, 'mri_cvs_register_to_colin27', 'final_CVSmorph_tocolin27.m3z')): print( f'The m3z morph matrix does not exist for subject {subject}!') continue output_fname = op.join(subjects_dir, subject, 'mri', 'T1_to_colin_csv_register.mgz') if not op.isfile(output_fname): rs = utils.partial_run_script(locals(), print_only=print_only) rs(mri_vol2vol) print( f'freeview -v {subjects_dir}/colin27/mri/T1.mgz {subjects_dir}/{subject}/mri/T1_to_colin_csv_register.mgz' )
def combine_images(fol, movie_name, frame_rate=10, start_number=-1, images_prefix='', images_format='', images_type='', ffmpeg_cmd='ffmpeg', **kwargs): if images_type == '': images_types = set([ utils.file_type(image) for image in glob.glob(op.join(fol, '{}*.*'.format(images_prefix))) ]) for opt_type in ['png', 'jpg', 'bmp', 'gif']: if opt_type in images_types: images_type = opt_type print('Images type is {}'.format(images_type)) break if images_type == '': raise Exception("Can't find the images type!") images = glob.glob( op.join(fol, '{}*.{}'.format(images_prefix, images_type))) image_nb = utils.namebase(images[0]) number = utils.read_numbers_rx(image_nb)[0] if images_prefix == '': images_prefix = image_nb[:-len(number)] if images_format == '': images_format = '%0{}d'.format(len(number)) if start_number == -1: start_number = min([ int(utils.namebase(image)[len(images_prefix):]) for image in images ]) images_prefix = op.join(fol, images_prefix) movie_name = op.join(fol, movie_name) combine_images_cmd = '{ffmpeg_cmd} -framerate {frame_rate} ' if start_number > 1: # You might want to use a static ffmpeg if your ffmepg version doesn't support the start_number flag, like: # ffmpeg_cmd = '~/space1/Downloads/ffmpeg-git-static/ffmpeg' combine_images_cmd += '-start_number {start_number} ' combine_images_cmd += '-i {images_prefix}{images_format}.{images_type} ' # http://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2 combine_images_cmd += '-vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" ' combine_images_cmd += '-c:v libx264 -r 30 -pix_fmt yuv420p {movie_name}.mp4' rs = utils.partial_run_script(locals()) rs(combine_images_cmd)
def warp_buckner_atlas(subject, subjects_dir, bunker_atlas_fname, wrap_map_fname, print_only=False): norm_fname = op.join(subjects_dir, subject, 'mri', 'norm.mgz') if not op.isfile(norm_fname): print("Error in warp_buckner_atlas, can't find the file {}".format(norm_fname)) return False trans_fname = op.join(subjects_dir, subject, 'mri', 'transforms', 'talairach.m3z') if not op.isfile(trans_fname): print("Error in warp_buckner_atlas, can't find the file {}".format(trans_fname)) return False wrap_map_name = op.basename(wrap_map_fname) rs = utils.partial_run_script(locals(), print_only=print_only) rs(warp_buckner_atlas_cmd) if not op.isfile(wrap_map_fname): raise Exception('Error in warp_buckner_atlas!') else: print('warp_buckner_atlas output fname: {}'.format(wrap_map_fname)) return True
def create_annotation_file(subject, atlas, subjects_dir='', freesurfer_home='', overwrite_annot_file=True, print_only=False, **kargs): ''' Creates the annot file by using the freesurfer mris_ca_label function Parameters ---------- subject: subject name atlas: One of the three atlases included with freesurfer: Possible values are aparc.DKTatlas, aparc.a2009s or aparc https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation subjects_dir: subjects dir. If empty, get it from the environ freesurfer_home: freesurfer home. If empty, get it from the environ overwrite_annot_file: If False and the annot file already exist, the function return True. If True, the function delete first the annot files if exist. print_only: If True, the function will just prints the command without executing it Returns ------- True if the new annot files exist ''' atlas_types = { 'aparc': 'curvature.buckner40.filled.desikan_killiany', 'aparc.a2009s': 'destrieux.simple.2009-07-28', 'aparc.DKTatlas': 'DKTatlas', 'aparc.DKTatlas40': 'DKTatlas40' } atlas_type = atlas_types[atlas] check_env_var('FREESURFER_HOME', freesurfer_home) check_env_var('SUBJECTS_DIR', subjects_dir) annot_files_exist = True for hemi in ['rh', 'lh']: annot_fname = op.join(subjects_dir, subject, 'label', '{}.{}.annot'.format(hemi, atlas)) if overwrite_annot_file and op.isfile(annot_fname): os.remove(annot_fname) rs = utils.partial_run_script(locals(), print_only=print_only) rs(mris_ca_label) annot_files_exist = annot_files_exist and op.isfile(annot_fname) return annot_files_exist
def _mri_cvs_register_parallel(p): subjects, subject_to, subjects_dir, overwrite, print_only = p for subject_from in subjects: # output_fname = op.join(SUBJECTS_DIR, subject_from, 'mri_cvs_register_to_colin27', 'combined_tocolin27_elreg_afteraseg-norm.tm3d') # if op.isfile(output_fname) and not overwrite: # print('Already done for {}'.format(subject_from)) # continue # else: # print('Running mri_cvs_register for {}'.format(subject_from)) if overwrite and not print_only: utils.delete_folder_files( op.join(subjects_dir, subject_from, 'mri_cvs_register_to_{}'.format(subject_to))) rs = utils.partial_run_script(locals(), print_only=print_only) if subject_to == 'fsaverage': rs(mri_cvs_register_mni) else: rs(mri_cvs_register)
def _morph_electrodes_parallel(p): subjects, subject_to, subjects_dir, overwrite, print_only = p bad_subjects, good_subjects = [], [] for subject_from in subjects: output_fname = op.join(subjects_dir, subject_from, 'electrodes', f'stim_electrodes_to_{subject_to}.txt') if op.isfile(output_fname) and not overwrite: continue rs = utils.partial_run_script(locals(), print_only=print_only) rs(applyMorph) ret = op.isfile(output_fname) if not ret: bad_subjects.append(subject_from) else: good_subjects.append(subject_from) print('good subjects: {}'.format(good_subjects)) print('bad subjects: {}'.format(bad_subjects))
def calc_volume_fractions(subject, subject_fol, scan_rescan, overwrite=False, print_only=False, check_if_should_run=False, verbose=True): reg_fname = op.join(subject_fol, 'control_to_T1.lta') output_fname = op.join(subject_fol, 'CBF') output_mgz_fname = op.join(subject_fol, 'CBF.cortex.mgz') do_run, ret = cics_checks([reg_fname], [output_fname], subject_fol, check_if_should_run, overwrite, verbose) if not do_run: return ret set_subject(subject, scan_rescan) rs = utils.partial_run_script(locals(), print_only=print_only) # mri_compute_volume_fractions_reg = 'mri_compute_volume_fractions --o "{output_fname}" --reg "{reg_fname}"' rs(mri_compute_volume_fractions_reg) return output_exists()
def create_aparc_aseg_file(subject, args): #atlas, print_only=False, overwrite=False, check_mgz_values=False): necessary_files = {'surf': ['lh.white', 'rh.white'], 'mri': ['ribbon.mgz']} utils.check_for_necessary_files(necessary_files, op.join(SUBJECTS_DIR, subject)) # The atlas var need to be in the locals for the APARC2ASEG call atlas = args.atlas rs = utils.partial_run_script(locals(), print_only=False) aparc_aseg_file = '{}+aseg.mgz'.format(args.atlas) mri_file_fol = op.join(SUBJECTS_DIR, subject, 'mri') mri_file = op.join(mri_file_fol, aparc_aseg_file) blender_file = op.join(MMVT_DIR, subject, 'freeview', aparc_aseg_file) if not op.isfile(blender_file) or args.overwrite_aseg_file: current_dir = op.dirname(op.realpath(__file__)) os.chdir(mri_file_fol) now = time.time() rs(APARC2ASEG) if op.isfile(mri_file) and op.getmtime(mri_file) > now: shutil.copyfile(mri_file, blender_file) else: print('Failed to create {}'.format(mri_file)) os.chdir(current_dir)
def recon_all_clin(args): # python -m src.preproc.examples.anatomy -s nmr01426 -f recon_all_clin --clin_fol clin_6966926 --dicoms_fol Prisma_fit-67026-20200618-141203-000586 import os for subject, clin_fol, dicoms_fol in zip(args.subject, args.clin_fol, args.dicoms_fol): clin_full_fol = utils.make_dir( op.join(args.clin_root, clin_fol, 'mne_dicom')) memprage_fols = glob.glob(op.join(clin_full_fol, '*MEMPRAGE*')) print('mne_organize_dicom output fol: {}'.format(clin_full_fol)) if len(memprage_fols) > 0: ret = au.is_true( input( 'It seems like you already have memprage folders, are you sure you want to rerun?' )) if not ret: continue utils.delete_folder_files(clin_full_fol) fs_dir = utils.make_dir(op.join(args.fs_root, subject)) print('FreeSurfer output fol: {}'.format(fs_dir)) dicoms_full_path = op.join(args.dicoms_root, dicoms_fol) if not op.isdir(dicoms_full_path): print('{} does not exist!'.format(dicoms_full_path)) continue rs = utils.partial_run_script(locals(), print_only=args.print_only) os.chdir(clin_full_fol) rs('mne_organize_dicom {dicoms_full_path}') anat.recon_all(subject, clin_full_fol, overwrite=True, subjects_dir=args.fs_root, print_only=False, n_jobs=args.n_jobs) args = anat.read_cmd_args( dict( subject=subject, function='all,create_skull_surfaces', remote_subject_dir=op.join(args.fs_root, subject), n_jobs=args.n_jobs, )) pu.run_on_subjects(args, anat.main)
def register_aseg_to_cbf(subject, subject_fol, scan_rescan, overwrite=False, print_only=True, check_if_should_run=False, verbose=True): lta_fname = op.join(subject_fol, 'control_to_T1.lta') source_fname = op.join(FS_ROOT, get_subject_fs_folder(subject, scan_rescan), 'mri', 'aparc+aseg.mgz') output_fname = op.join(subject_fol, 'aparc+aseg_cbf.mgz') do_run, ret = cics_checks([lta_fname, source_fname], [output_fname], subject_fol, check_if_should_run, overwrite, verbose) if not do_run: return ret subject = set_subject(subject, scan_rescan) rs = utils.partial_run_script(locals(), print_only=print_only) # 'mri_convert -ait "{lta_fname}" "{source_fname}" "{output_fname}"' rs(register_using_inverse_lta) return op.isfile(output_fname)
def register_cbf_to_t1(subject, subject_fol, scan_rescan, overwrite=False, print_only=False, check_if_should_run=False, verbose=True): output_fname = op.join(subject_fol, 'Control_to_T1.nii') lta_fname = op.join(subject_fol, 'control_to_T1.lta') source_fname = op.join(subject_fol, 'Control.nii') target_fname = op.join(FS_ROOT, get_subject_fs_folder(subject, scan_rescan), 'mri', 'T1.mgz') do_run, ret = cics_checks([source_fname, target_fname], [output_fname, lta_fname], subject_fol, check_if_should_run, overwrite, verbose) if not do_run: return ret set_subject(subject, scan_rescan) rs = utils.partial_run_script(locals(), print_only=print_only) # bbregister --s {subject} --mov "{source_fname}" --lta "{lta_fname}" --t1 --o "{output_fname}" rs(bbregister) return all([op.isfile(fname) for fname in [output_fname, lta_fname]])
def create_aparc_aseg_file( subject, args ): #atlas, print_only=False, overwrite=False, check_mgz_values=False): necessary_files = {'surf': ['lh.white', 'rh.white'], 'mri': ['ribbon.mgz']} utils.check_for_necessary_files(necessary_files, op.join(SUBJECTS_DIR, subject)) # The atlas var need to be in the locals for the APARC2ASEG call atlas = args.atlas rs = utils.partial_run_script(locals(), print_only=False) aparc_aseg_file = '{}+aseg.mgz'.format(args.atlas) mri_file_fol = op.join(SUBJECTS_DIR, subject, 'mri') mri_file = op.join(mri_file_fol, aparc_aseg_file) blender_file = op.join(BLENDER_ROOT_DIR, subject, 'freeview', aparc_aseg_file) if not op.isfile(blender_file) or args.overwrite_aseg_file: current_dir = op.dirname(op.realpath(__file__)) os.chdir(mri_file_fol) now = time.time() rs(APARC2ASEG) if op.isfile(mri_file) and op.getmtime(mri_file) > now: shutil.copyfile(mri_file, blender_file) else: print('Failed to create {}'.format(mri_file)) os.chdir(current_dir)
def warp_buckner_atlas(subject, subjects_dir, bunker_atlas_fname, wrap_map_fname, print_only=False): norm_fname = op.join(subjects_dir, subject, 'mri', 'norm.mgz') if not op.isfile(norm_fname): print("Error in warp_buckner_atlas, can't find the file {}".format( norm_fname)) return False trans_fname = op.join(subjects_dir, subject, 'mri', 'transforms', 'talairach.m3z') if not op.isfile(trans_fname): print("Error in warp_buckner_atlas, can't find the file {}".format( trans_fname)) return False wrap_map_name = op.basename(wrap_map_fname) rs = utils.partial_run_script(locals(), print_only=print_only) rs(warp_buckner_atlas_cmd) if not op.isfile(wrap_map_fname): raise Exception('Error in warp_buckner_atlas!') else: print('warp_buckner_atlas output fname: {}'.format(wrap_map_fname)) return True