def main(): ''' Warp input image using the input velocity field at different scales. The scales are integrated by considering input field as a SVF and using either forward Euler or scaling and squaring. ''' #executables work_dir = "/user/bkhanal/home/works/" svf_exp = work_dir + "tools/svfExponential/SVFExponential" warp_img = work_dir + "AdLemModel/build/src/WarpImage" combine_imgs = work_dir + "tools/combineImages/build/combineImages" ext = '.nii.gz' #inputs ops = get_input_options() in_img = ops.inFile in_vel = ops.velFile scale = ops.firstScale num = 1 out_img_pref = ops.outPref + 'WarpedScale' out_4D = '%sWarped4D%sSteps%s' % (ops.outPref, ops.numOfScales, ext) # Make sure that out_img_pref string is not the starting string of out_4D. # Because I delete individual files with out_img_pref*ext !! if ops.interp == 'bspline': interp_ops = ('--interpolator %s --order %s' % (ops.interp, ops.bspline_order)) else: interp_ops = '--interpolator %s' % (ops.interp) while num <= ops.numOfScales: out_vel = '%svelScaled%s%s' % (ops.outPref, scale, ext) out_img = '%s%s%s' % (out_img_pref, num, ext) #create vel field from in_vel cmd = ('%s -s %s -e %s -i %s -o %s' % (svf_exp, scale, ops.compScheme, in_vel, out_vel)) bu.print_and_execute(cmd) #create warped Image from in_img using out_vel created with svf_exp cmd = ( '%s --inImage %s --displacementImage %s ' '--outImage %s --invert %s %s' % (warp_img, in_img, out_vel, out_img, ops.invertField, interp_ops)) bu.print_and_execute(cmd) #Delete vel field bu.print_and_execute('rm ' + out_vel + '\n') #Go to next file num += 1 scale += ops.stepSize #combine images: ops: numOfScales imageType imageBaseFileName out_imgFileName cmd = ('%s %s %s %s %s' % (combine_imgs, ops.numOfScales, ext, out_img_pref, out_4D)) bu.print_and_execute(cmd) #delete individual warped images: if ops.save_only_4D: bu.print_and_execute('rm %s*%s' % (out_img_pref, ext))
def crop_by_mask(dim, in_img, out_img, label_mask_img, label='1', padRadius='0'): ''' Run Ants ExtractRegionFromImageByMask command ''' crop = '%s/ExtractRegionFromImageByMask %s' % (ants_dir, dim) cmd = ('%s %s %s %s %s %s' % (crop, in_img, out_img, label_mask_img, label, padRadius)) bu.print_and_execute(cmd) return
def main(): """ Runs the script. Run with -h to see options. """ ops = get_input_options() adlem_dir = os.getenv('ADLEM_DIR') run_adlem = 'python ' + op.join(adlem_dir, 'scripts/runAdLemModel.py') if adlem_dir is None: raise ValueError('environment variable ADLEM_DIR not set.') adlem_ops = bu.get_lines_as_list(ops.ops_file, '#') sim_ids = bu.get_lines_as_list(ops.simdir_list, '#') for sim_id in sim_ids: cmd = ('%s %s %s\n' % (run_adlem, sim_id, ' '.join(adlem_ops))) if ops.print_only: print cmd else: bu.print_and_execute(cmd) tm.sleep(0.1)
def atrophy_map_from_img(ops): ''' Create atrophy map from input image. ''' if not ops.crop_mask and not ops.uniform_regional_means: cmd = 'cp %s %s' % (ops.atrophy_img, ops.out_atrophy) return in_atrophy = ops.atrophy_img if ops.crop_mask: crop_by_mask(3, in_atrophy, ops.out_atrophy, ops.crop_mask, padRadius=ops.crop_pad_rad) in_atrophy = ops.out_atrophy if ops.uniform_regional_means: cmd = ('%s -t %s -i %s -l %s -u %s' % (uniformize_regionally, ops.uniformize_labels, in_atrophy, ops.seg_for_uniformize, ops.out_atrophy)) if ops.start_from_atrophy_img: cmd += ' -s' bu.print_and_execute(cmd) return
def atrophy_map_from_tables(ops): ''' Create atrophy map from input tables and the input segmentation image. Returns created output atrophy image filename. ''' # Now create atrophy map: The first atrophy table is used to create while # the subsequent ones modify the one created with the first one. cmd_pref = ('%s -l %s -o %s -t ' % (img_from_label_img, ops.seg_for_atrophy, ops.out_atrophy)) tables = ops.atrophy_tables.split(',') # files separated by comma # print('list of tables: ') # print tables cmd = cmd_pref + tables[0] if ops.atrophy_img: cmd += ' -m ' + ops.out_atrophy bu.print_and_execute(cmd) for table in tables[ 1:]: # from the remaining tables modify the output file cmd = cmd_pref + table if not ops.atrohy_img: cmd += ' -m ' + ops.out_atrophy bu.print_and_execute(cmd) tm.sleep(0.2) # wait cmd to write file before writing another one. return ops.out_atrophy
def main(): """ Runs the script. Run with -h to see options. """ ops = get_input_options() adlem_dir = os.getenv('ADLEM_DIR') if adlem_dir is None: raise ValueError('environment variable ADLEM_DIR not set.') res_dir = op.join(adlem_dir, 'results/patients') paste_img = op.join(adlem_dir, 'build/src/pasteImageToBiggerImage') lines = bu.get_lines_as_list(ops.imgs_simIds, '#') for line in lines: rb, sim_id = line.split()[0], line.split()[1] cropped_sf = op.join(res_dir, sim_id, ops.sim_img) pasted_sf = op.join(res_dir, sim_id, ops.pasted_img) crop_mask = op.join(res_dir, sim_id, ops.crop_mask) if op.exists(cropped_sf) and op.exists(rb) and op.exists(crop_mask): if not op.exists(pasted_sf) or ops.overwrite: cmd = ('%s %s %s %s %s\n\n' % (paste_img, cropped_sf, rb, crop_mask, pasted_sf)) if ops.print_only: print cmd else: bu.print_and_execute(cmd) tm.sleep(0.1)
def main(): ''' Extract 3D images from a 4D image and then extract one selected slice from each of these 3D images and combine them as a gif. ''' ops = get_input_options() #split 4d image to get all the 3D images: tmp3d_basename, file_ext = 'tmp3DImage', '.nii.gz' cmd = 'ImageMath 4 %s%s TimeSeriesDisassemble %s' % ( tmp3d_basename, file_ext, ops.in_img) bu.print_and_execute(cmd) #ImageMath 4 tmp3DImage.nii.gz TimeSeriesDisassemble ops.in_img #convert (from ImageMagick) #Executables that must exist: #ImageMath extract_slice = "/home/bkhanal/works/tools/marcoSliceExtractor/myImgSliceExtractor" axis = ops.slice_axis num = 0 #print('number of time steps: %s \n' % (str(ops.total_tpts))) while num < ops.total_tpts: #outputs/results of the executables index = str(num+100) #ImageMath extracted slice names start from 100. tmp3DImage = '%s%s%s' % (tmp3d_basename, index, file_ext) tmp2DImage = 'slice%s.png' % (index,) cmd = '%s %s %s %s %s' % ( extract_slice, tmp3DImage, axis, ops.slice_num, tmp2DImage) bu.print_and_execute(cmd, False) # Rotate the image for proper orientation. if ops.rotate is None: cmd = 'convert -rotate 180 %s %s' % (tmp2DImage, tmp2DImage) else: cmd = 'convert -rotate %s %s %s' % (ops.rotate, tmp2DImage, tmp2DImage) bu.print_and_execute(cmd, False) if ops.crop: cmd = 'convert %s -crop %s +repage %s' % (tmp2DImage, ops.crop, tmp2DImage) bu.print_and_execute(cmd, False) # Write time-point info if ops.time_unit is not None: if ops.time_step is not None: tpt = float(num) * ops.time_step else: tpt = num cmd = ('convert %s -gravity SouthWest -fill orange -pointsize 12 ' '-annotate +0+0 "%s %s" %s' % ( tmp2DImage, str(tpt), ops.time_unit, tmp2DImage)) bu.print_and_execute(cmd, False) #Delete individual 3D files. bu.print_and_execute('rm ' + tmp3DImage, False) #Go to next file num += 1 #Now make the animation and delete individual 2D slices: cmd = 'convert slice1*.png -resize %s -set delay %s %s' % ( ops.resize, ops.delay, ops.out_gif) bu.print_and_execute(cmd) bu.print_and_execute('rm slice1*.png', False)
def main(): """ Run the model adlem for a given patient, segmentation mask, atrophy map and [optional DTI].""" work_dir = os.getenv('ADLEM_DIR') if work_dir is None: raise ValueError('environment variable ADLEM_DIR not set.') ops = get_input_options() if ops.in_new_cluster: target = op.join(work_dir, 'buildNewNef/src/simul_atrophy') else: target = op.join(work_dir, 'build/src/simul_atrophy') res_dir = op.join(work_dir, 'results/patients', ops.patient) in_img = op.join(res_dir, ops.in_img) atrophy = op.join(res_dir, ops.atrophy) in_seg = op.join(res_dir, ops.in_seg) res_path = res_dir + '/' #due to stupid limitation in my AdLem code # where it concatenates simply the -resPath argument with the file prefix. with open(ops.petsc_op_file, 'r') as fil: # Get all lines in the file that does not start with '#' # into a list petsc_ops = [line.strip() for line in fil if not line.startswith('#')] optional_args, bool_args = [], [] if ops.no_lame_in_rhs: bool_args.append('--no_lame_in_rhs') if ops.div12pt_stencil: bool_args.append('--div12pt_stencil') if ops.relax_ic_in_csf: bool_args.append('--relax_ic_in_csf') if ops.relax_ic_coeff is not None: optional_args.append('-relax_ic_coeff ' + ops.relax_ic_coeff) if ops.zero_vel_at_falx: bool_args.append('--zero_vel_at_falx') elif ops.sliding_at_falx: bool_args.append('--sliding_at_falx') if ops.falx_zero_vel_dir is None: raise ValueError('Must provide -falx_zero_vel_dir when using ' '--sliding_at_falx') optional_args.append('-falx_zero_vel_dir ' + ops.falx_zero_vel_dir) if ops.invert_field_to_warp: bool_args.append('--invert_field_to_warp') if ops.mu_file is not None: optional_args.append('-muFile ' + ops.mu_file) if ops.use_dti: bool_args.append('--useTensorLambda') optional_args.append('-lambdaFile ' + op.join(res_dir, ops.in_dti)) if ops.wrt_press: bool_args.append('--writePressure') if ops.wrt_force: bool_args.append('--writeForce') if ops.wrt_residual: bool_args.append('--writeResidual') cmd = ('%s -parameters %s -boundary_condition %s -atrophyFile %s ' '-maskFile %s -imageFile %s -numOfTimeSteps %s -resPath %s ' '-resultsFilenamesPrefix %s %s' % (target, ops.lame_paras, ops.boundary_condition, atrophy, in_seg, in_img, ops.time_steps, res_path, ops.res_prefix, ' '.join(bool_args + optional_args + petsc_ops))) if ops.in_legacy_cluster: cluster_mpi = '/opt/openmpi-gcc/current/bin/mpiexec ' cmd = bu.sophia_nef_pbs_setting(False) + cluster_mpi + cmd job_name = '%sSteps%s' % (ops.res_prefix, ops.time_steps) #print cmd if ops.queue_walltime: queue, _, walltime = ops.queue_walltime.partition(',') else: queue, walltime = 'parlong', '12:00:00' if ops.procs_mem: procs, _, mem = ops.procs_mem.partition(',') else: procs, mem = 'nodes=3:xeon:ppn=20', 'mem=540gb' bu.qsub_job( name=job_name, queue=queue, walltime=walltime, procs=procs, mem=mem, #procs='nodes=4:xeon:ppn=20', mem='mem=720gb', #procs='nodes=5:xeon:ppn=20', mem='mem=900gb', dest_dir=res_dir, cmd=cmd) elif ops.in_new_cluster: cluster_mpi = '/opt/openmpi/gcc/current/bin/mpiexec ' cmd = bu.sophia_nef_pbs_setting(True) + cluster_mpi + cmd job_name = '%sSteps%s' % (ops.res_prefix, ops.time_steps) if not ops.res: ops.res = '/nodes=6/core=24,walltime=01:30:00' # if not ops.prop: # ops.prop = '"cputype=\'xeon\'"' bu.oarsub_job(ops.res, ops.prop, res_dir, job_name, cmd) else: #print cmd bu.print_and_execute(cmd)