def realign(file_to_realign): print "running motion correction" realign = spm.Realign() realign.inputs.in_files = file_to_realign realign.inputs.register_to_mean = False #realign.inputs.out_prefix = 'spm_corr_' res = realign.run() parameters = res.outputs.realignment_parameters if not isinstance(parameters, list): parameters = [parameters] par_file = parameters out_file = [] if isinstance(res.outputs.realigned_files, list): for rf in res.outputs.realigned_files: res = fsl.ImageMaths(in_file=rf, out_file=rf, output_type='NIFTI', op_string='-nan').run() out_file.append(res.outputs.out_file) else: res2 = fsl.ImageMaths(in_file=res.outputs.realigned_files, out_file=res.outputs.realigned_files, output_type='NIFTI', op_string='-nan').run() out_file.append(res2.outputs.out_file) return out_file, par_file
def create_CT_skin_seg_wf(name="skin_wf"): workflow = pe.Workflow(name=name) inputnode = pe.Node(interface=util.IdentityInterface(fields=["CT"]), name="inputnode") outputnode = pe.Node( interface=util.IdentityInterface(fields=["skin_mask"]), name="outputnode") init_high_thresh = 150 skin_low = -705 skin_high = -8 step1_remove_high_val = pe.Node(interface=fsl.ImageMaths(), name="step1_remove_high_val") step1_remove_high_val.inputs.op_string = "-uthr %f -fmedian" % init_high_thresh step2_seg_skin = pe.Node(interface=fsl.ImageMaths(), name="step2_seg_skin") step2_seg_skin.inputs.op_string = "-thr %f -uthr %f" % (skin_low, skin_high) workflow.connect([(inputnode, step1_remove_high_val, [("CT", "in_file")])]) workflow.connect([(step1_remove_high_val, step2_seg_skin, [("out_file", "in_file")])]) workflow.connect([(step2_seg_skin, outputnode, [("out_file", "skin_mask")]) ]) return workflow
def make_mask_map(clf, out_file, data): import tempfile folder = tempfile.mkdtemp() data = list(data) (masks, num) = zip(*clf.masklist) for (n, v) in enumerate(data): fsl.ImageMaths(in_file=masks[n], op_string=' -add ' + str(v) + ' -thr ' + str(v + 0.001), out_file=folder + '/' + str(n) + '.nii.gz' ).run() fsl.ImageMaths(in_file=folder + '/0.nii.gz', op_string=' -add ' + folder + '/1', out_file=folder + '/ongoing.nii.gz').run() if clf.mask_num > 1: for n in range(2, clf.mask_num): fsl.ImageMaths(in_file=folder + '/ongoing.nii.gz', op_string=' -add ' + folder + '/' + str(n), out_file=folder + '/ongoing.nii.gz').run() fsl.ImageMaths(in_file=folder + '/ongoing.nii.gz', op_string=' -sub 1' + ' -thr 0', out_file=out_file).run() print "Made" + out_file
def create_tbss_1_preproc(name='tbss_1_preproc'): """Preprocess FA data for TBSS: erodes a little and zero end slicers and creates masks(for use in FLIRT & FNIRT from FSL). A pipeline that does the same as tbss_1_preproc script in FSL Example -------- >>>tbss1 = tbss.create_tbss_1_preproc(name='tbss1') >>>tbss1.run() Inputs:: inputnode.fa_list Outputs:: outputnode.fa_list outputnode.mask_list """ # Define the inputnode inputnode = pe.Node(interface = util.IdentityInterface(fields=["fa_list"]), name="inputnode") # Prep the FA images prepfa = pe.MapNode(fsl.ImageMaths(suffix="_prep"), name="prepfa", iterfield=['in_file','op_string']) # Slicer slicer = pe.MapNode(fsl.Slicer(all_axial = True, image_width=1280), name='slicer', iterfield=['in_file']) # Create a mask getmask = pe.MapNode(fsl.ImageMaths(op_string="-bin", suffix="_mask"), name="getmask", iterfield=['in_file']) # Define the tbss1 workflow tbss1 = pe.Workflow(name="tbss1") tbss1.connect([ (inputnode, prepfa, [("fa_list", "in_file")]), (inputnode, prepfa, [(("fa_list", tbss1_op_string), "op_string")]), (prepfa, getmask, [("out_file", "in_file")]), (prepfa, slicer,[('out_file', 'in_file')]), ]) # Define the outputnode outputnode = pe.Node(interface = util.IdentityInterface(fields=["fa_list", "mask_list"]), name="outputnode") tbss1.connect([ (prepfa, outputnode, [("out_file", "fa_list")]), (getmask, outputnode, [("out_file","mask_list")]), ]) return tbss1
def create_nonbrain_meansignal(name='nonbrain_meansignal'): nonbrain_meansignal = Workflow(name=name) inputspec = Node(utility.IdentityInterface(fields=['func_file']), name='inputspec') # Split raw 4D functional image into 3D niftis split_image = Node(fsl.Split(dimension='t', output_type='NIFTI'), name='split_image') # Create a brain mask for each of the 3D images brain_mask = MapNode(fsl.BET(frac=0.3, mask=True, no_output=True, robust=True), iterfield=['in_file'], name='brain_mask') # Merge the 3D masks into a 4D nifti (producing a separate mask per volume) merge_mask = Node(fsl.Merge(dimension='t'), name='merge_mask') # Reverse the 4D brain mask, to produce a 4D non brain mask reverse_mask = Node(fsl.ImageMaths(op_string='-sub 1 -mul -1'), name='reverse_mask') # Apply the mask on the raw functional data apply_mask = Node(fsl.ImageMaths(), name='apply_mask') # Highpass filter the non brain image highpass = create_highpass_filter(name='highpass') # Extract the mean signal from the non brain image mean_signal = Node(fsl.ImageMeants(), name='mean_signal') outputspec = Node(utility.IdentityInterface(fields=['nonbrain_regressor']), name='outputspec') nonbrain_meansignal.connect(inputspec, 'func_file', split_image, 'in_file') nonbrain_meansignal.connect(split_image, 'out_files', brain_mask, 'in_file') nonbrain_meansignal.connect(brain_mask, 'mask_file', merge_mask, 'in_files') nonbrain_meansignal.connect(merge_mask, 'merged_file', reverse_mask, 'in_file') nonbrain_meansignal.connect(reverse_mask, 'out_file', apply_mask, 'mask_file') nonbrain_meansignal.connect(inputspec, 'func_file', apply_mask, 'in_file') nonbrain_meansignal.connect(apply_mask, 'out_file', highpass, 'inputspec.in_file') nonbrain_meansignal.connect(highpass, 'outputspec.filtered_file', mean_signal, 'in_file') nonbrain_meansignal.connect(mean_signal, 'out_file', outputspec, 'nonbrain_regressor') return nonbrain_meansignal
def reg_coords2diff(coords, dwi_dir, node_size, seeds_dir): try: FSLDIR = os.environ['FSLDIR'] except KeyError: print('FSLDIR environment variable not set!') import nipype.interfaces.fsl as fsl merged_f_samples_path = "%s%s" % (dwi_dir, '/merged_f1samples.nii.gz') if os.path.exists(merged_f_samples_path) is True: dwi_infile = merged_f_samples_path else: dwi_infile = "%s%s" % (dwi_dir, '/dwi.nii.gz') # #print(coords) # # Grow spheres at ROI for coord in coords[0]: X = coord[0] Y = coord[1] Z = coord[2] out_file1 = "%s%s%s%s%s%s%s%s" % (seeds_dir, '/roi_point_', str(X), '_', str(Y), '_', str(Z), '.nii.gz') args = "%s%s%s%s%s%s%s" % ('-mul 0 -add 1 -roi ', str(X), ' 1 ', str(Y), ' 1 ', str(Z), ' 1 0 1') maths = fsl.ImageMaths(in_file=FSLDIR + '/data/standard/MNI152_T1_1mm_brain.nii.gz', op_string=args, out_file=out_file1) os.system(maths.cmdline + ' -odt float') out_file2 = "%s%s%s%s%s%s%s%s" % (seeds_dir, '/region_', str(X), '_', str(Y), '_', str(Z), '.nii.gz') args = "%s%s%s" % ('-kernel sphere ', str(node_size), ' -fmean -bin') maths = fsl.ImageMaths(in_file=out_file1, op_string=args, out_file=out_file2) os.system(maths.cmdline + ' -odt float') # Map ROIs from Standard Space to diffusion Space: # Applying xfm and input matrix to transform ROI's between diff and MNI using FLIRT out_file_diff = "%s%s" % (out_file2.split('.nii')[0], '.nii.gz') cmd = "flirt -in {} -init {} -ref {} -out {} -omat {} -interp trilinear -cost mutualinfo -applyxfm -dof 12 -searchrx -180 180 -searchry -180 180 -searchrz -180 180" cmd_run = cmd.format(out_file2, "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat'), dwi_infile, out_file_diff, '/tmp/out_flirt.mat') os.system(cmd_run) args = '-bin' maths = fsl.ImageMaths(in_file=out_file_diff, op_string=args, out_file=out_file_diff) os.system(maths.cmdline) done_nodes = True return done_nodes
def participant_workflow(args): fsl.FSLCommand.set_default_output_type('NIFTI_GZ') inbidslayout = BIDSLayout(args.input_dataset, validate=not args.skip_validation) outbidslayout = utils.get_BIDSLayout_with_conf(args.output_folder, validate=False) wf = pe.Workflow(name='participant') if not args.debug_io: qformfiles = ['model', 'model_brain_mask', 'atlas'] if args.subcortical: qformfiles.extend([ 'subcortical_model', 'subcortical_model_brain_mask', 'subcortical_atlas' ]) if args.intracranial_volume: qformfiles.append('intracranial_mask') qformwf = forceqform_workflow(qformfiles, args.max_shear_angle) for qformfile in qformfiles: setattr(qformwf.inputs.inputspec, qformfile, getattr(args, qformfile)) t1inputspec = qformfiles + ['model_brain'] maskmodel = pe.Node(fsl.ImageMaths(), 'maskmodel') wf.connect([(qformwf, maskmodel, [('outputspec.model', 'in_file'), ('outputspec.model_brain_mask', 'mask_file')])]) if args.subcortical: masksubcortmodel = pe.Node(fsl.ImageMaths(), 'masksubcortmodel') wf.connect([(qformwf, masksubcortmodel, [ ('outputspec.subcortical_model', 'in_file'), ('outputspec.subcortical_model_brain_mask', 'mask_file') ])]) t1inputspec.append('subcortical_model_brain') else: t1inputspec = [] for T1_scan, T1_entities in _get_scans( inbidslayout, args.bids_filter, subject_list=args.participant_labels): tmpwf = t1_workflow(T1_scan, T1_entities, outbidslayout, args, t1inputspec) if not args.debug_io: for qformfile in qformfiles: wf.connect(qformwf, f'outputspec.{qformfile}', tmpwf, f'inputspec.{qformfile}') wf.connect(maskmodel, 'out_file', tmpwf, 'inputspec.model_brain') if args.subcortical: wf.connect(masksubcortmodel, 'out_file', tmpwf, 'inputspec.subcortical_model_brain') else: wf.add_nodes([tmpwf]) _update_workdir(wf, args.working_directory) if args.resource_input_file is not None: _set_resource_data(wf, args.resource_input_file) return wf
def coreg_vent_CSF_to_diff(dwi_dir, csf_loc, mni_csf_loc): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe print('\nTransforming CSF mask to diffusion space...') merged_f_samples_path = "%s%s" % (dwi_dir, '/merged_f1samples.nii.gz') if os.path.exists(merged_f_samples_path) is True: dwi_infile = merged_f_samples_path else: dwi_infile = "%s%s" % (dwi_dir, '/dwi.nii.gz') csf_mask_diff_out = "%s%s" % (dwi_dir, '/csf_diff.nii.gz') flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = dwi_infile flirt.inputs.in_file = csf_loc flirt.inputs.out_file = csf_mask_diff_out flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.in_matrix_file = "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat') flirt.inputs.apply_xfm = True flirt.run() vent_mask_diff_out = dwi_dir + '/ventricle_diff.nii.gz' flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = dwi_infile flirt.inputs.in_file = mni_csf_loc flirt.inputs.out_file = vent_mask_diff_out flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.in_matrix_file = "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat') flirt.inputs.apply_xfm = True flirt.run() # Mask CSF with MNI ventricle mask print('Masking CSF with ventricle mask...') vent_csf_diff_out = "%s%s" % (dwi_dir, '/vent_csf_diff.nii.gz') args = "%s%s" % ('-mas ', vent_mask_diff_out) maths = fsl.ImageMaths(in_file=csf_mask_diff_out, op_string=args, out_file=vent_csf_diff_out) os.system(maths.cmdline) print('Eroding and binarizing CSF mask...') # Erode CSF mask out_file_final = "%s%s" % (vent_csf_diff_out.split('.nii.gz')[0], '_ero.nii.gz') args = '-ero -bin' maths = fsl.ImageMaths(in_file=vent_csf_diff_out, op_string=args, out_file=out_file_final) os.system(maths.cmdline) return out_file_final
def init_temporalfilter_wf(temporal_filter_width, repetition_time, name="temporalfilter"): """ create a workflow for temporal filtering of functional data based on gaussian smoothing implemented by FSLMATHS :param temporal_filter_width: width of the remporal filter in seconds :param repetition_time: repetition time of the input volume :param name: workflow name (Default value = "temporalfilter") """ # the workflow workflow = pe.Workflow(name=name) # only input is the bold image to be filtered inputnode = pe.Node(niu.IdentityInterface(fields=["bold_file", ""]), name="inputnode") # only output is the filtered bold image outputnode = pe.Node(niu.IdentityInterface(fields=["filtered_file"]), name="outputnode") # prepare operand string for FSLMATHS highpass_operand = "-bptf %.10f -1" % \ (temporal_filter_width / (2.0 * repetition_time)) # node that calls FSLMATHS to actually do the temporal filtering highpass = pe.Node(interface=fsl.ImageMaths(op_string=highpass_operand, suffix="_tempfilt"), name="highpass") # temporal filtering also demeans the image, which is not desired. Therefore, # we add the mean of the original image back in. meanfunc = pe.Node(interface=fsl.ImageMaths(op_string="-Tmean", suffix="_mean"), name="meanfunc") addmean = pe.Node(interface=fsl.BinaryMaths(operation="add"), name="addmean") workflow.connect([(inputnode, highpass, [("bold_file", "in_file")]), (inputnode, meanfunc, [("bold_file", "in_file")]), (highpass, addmean, [("out_file", "in_file")]), (meanfunc, addmean, [("out_file", "operand_file")]), (addmean, outputnode, [("out_file", "filtered_file")])]) return workflow
def get_norm_wf(name="norm_wf"): wf = Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['t1w', 't1w_brain']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['t1w_2_MNI_mat', 't1w_2_MNI_warp', 't1w_MNIspace']), name='outputnode') # otherwise fnirt is trying to write to the sourcedata dir t1w_dummy = pe.Node(fsl.ImageMaths(), name="t1w_dummy") wf.connect(inputnode, "t1w", t1w_dummy, "in_file") t1w_2_MNI_flirt = pe.Node(fsl.FLIRT(dof=12), name='t1w_2_MNI_flirt') t1w_2_MNI_flirt.inputs.reference = fsl.Info.standard_image( 'MNI152_T1_1mm_brain.nii.gz') wf.connect(inputnode, 't1w_brain', t1w_2_MNI_flirt, 'in_file') wf.connect(t1w_2_MNI_flirt, 'out_matrix_file', outputnode, 't1w_2_MNI_mat') # 2. CALC. WARP STRUCT -> MNI with FNIRT # cf. wrt. 2mm # https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind1311&L=FSL&P=R86108&1=FSL&9=A&J=on&d=No+Match%3BMatch%3BMatches&z=4 t1w_2_MNI_fnirt = pe.Node(fsl.FNIRT(), name='t1w_2_MNI_fnirt') t1w_2_MNI_fnirt.inputs.config_file = 'T1_2_MNI152_2mm' t1w_2_MNI_fnirt.inputs.ref_file = fsl.Info.standard_image( 'MNI152_T1_2mm.nii.gz') t1w_2_MNI_fnirt.inputs.field_file = True t1w_2_MNI_fnirt.plugin_args = {'submit_specs': 'request_memory = 4000'} wf.connect(t1w_dummy, 'out_file', t1w_2_MNI_fnirt, 'in_file') wf.connect(t1w_2_MNI_flirt, 'out_matrix_file', t1w_2_MNI_fnirt, 'affine_file') wf.connect(t1w_2_MNI_fnirt, 'field_file', outputnode, 't1w_2_MNI_warp') wf.connect(t1w_2_MNI_fnirt, 'warped_file', outputnode, 't1w_MNIspace') return wf
def coreg_mask_to_diff(dwi_dir, mask): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe print('\nTransforming custom waypoint mask to diffusion space...') merged_f_samples_path = "%s%s" % (dwi_dir, '/merged_f1samples.nii.gz') if os.path.exists(merged_f_samples_path) is True: dwi_infile = merged_f_samples_path else: dwi_infile = "%s%s" % (dwi_dir, '/dwi.nii.gz') out_file = "%s%s" % (dwi_dir, '/mask_custom_diff.nii.gz') flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = dwi_infile flirt.inputs.in_file = mask flirt.inputs.out_file = out_file flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.in_matrix_file = "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat') flirt.inputs.apply_xfm = True flirt.run() args = '-bin' maths = fsl.ImageMaths(in_file=out_file, op_string=args, out_file=out_file) print('\nBinarizing custom mask...') os.system(maths.cmdline) return out_file
def create_bet_mask_from_dwi(name, do_realignment=True): wf = Workflow(name=name) inputnode = Node(interface=IdentityInterface(fields=["dwi", "bvec", "bval"]), name="inputnode") b0s = Node(DwiextractB0(), "b0s") wf.connect(inputnode, "dwi", b0s, "in_file") wf.connect(inputnode, "bvec", b0s, "bvec") wf.connect(inputnode, "bval", b0s, "bval") meanb0 = Node(fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), name="meanb0") wf.connect(b0s, "out_file", meanb0, "in_file") mcflirt = Node(fsl.MCFLIRT(), "mcflirt") bet = Node(fsl.BET(), "bet") bet.inputs.frac = 0.3 bet.inputs.robust = True bet.inputs.mask = True if do_realignment: wf.connect(meanb0, "out_file", mcflirt, "in_file") wf.connect(mcflirt, "out_file", bet, "in_file") else: wf.connect(meanb0, "out_file", bet, "in_file") outputnode = Node(interface=IdentityInterface(fields=["mask_file"]), name="outputnode") wf.connect(bet, "mask_file", outputnode, "mask_file") return wf
def main(): ## Parsing Arguments # # usage = "usage: %prog [options] arg1 arg2" parser = argparse.ArgumentParser(prog='cenc_freesurfer') parser.add_argument("--brainmask", help="Freesurfer brainmask.nii.gz", default='brainmask.nii.gz') parser.add_argument("--aseg", help="Aseg", default='aseg.nii.gz') parser.add_argument("--out", help="Aseg", default='mask.nii.gz') inArgs = parser.parse_args() # Create final brain mask brainmask = inArgs.brainmask aseg = inArgs.aseg mask = inArgs.out maths = fsl.ImageMaths(in_file=brainmask, op_string='-bin -kernel box 12 -ero -add ' + aseg + ' -bin -kernel box 9 -dilM -kernel box 7 -ero', out_file=mask) print maths.cmdline maths.run()
def gen_anat_segs(anat_loc): # # Custom inputs# # try: FSLDIR = os.environ['FSLDIR'] except KeyError: print('FSLDIR environment variable not set!') import nipype.interfaces.fsl as fsl #import nibabel as nib #from nilearn.image import resample_img from nipype.interfaces.fsl import ExtractROI print( '\nSegmenting anatomical image to create White Matter and Ventricular CSF masks for contraining the tractography...' ) # Create MNI ventricle mask print('Creating MNI space ventricle mask...') anat_dir = os.path.dirname(anat_loc) lvent_out_file = "%s%s" % (anat_dir, '/LVentricle.nii.gz') rvent_out_file = "%s%s" % (anat_dir, '/RVentricle.nii.gz') MNI_atlas = "%s%s" % ( FSLDIR, '/data/atlases/HarvardOxford/HarvardOxford-sub-prob-1mm.nii.gz') fslroi1 = ExtractROI(in_file=MNI_atlas, roi_file=lvent_out_file, t_min=2, t_size=1) os.system(fslroi1.cmdline) fslroi2 = ExtractROI(in_file=MNI_atlas, roi_file=rvent_out_file, t_min=13, t_size=1) os.system(fslroi2.cmdline) mni_csf_loc = anat_dir + '/VentricleMask.nii.gz' args = "%s%s%s" % ('-add ', rvent_out_file, ' -thr 0.1 -bin -dilF') maths = fsl.ImageMaths(in_file=lvent_out_file, op_string=args, out_file=mni_csf_loc) os.system(maths.cmdline) # Segment anatomical (should be in MNI space) print('Segmenting anatomical image using FAST...') fastr = fsl.FAST() fastr.inputs.in_files = anat_loc fastr.inputs.img_type = 1 fastr.run() old_file_csf = "%s%s" % (anat_loc.split('.nii.gz')[0], '_pve_0.nii.gz') new_file_csf = "%s%s" % (anat_dir, '/CSF.nii.gz') old_file_wm = "%s%s" % (anat_loc.split('.nii.gz')[0], '_pve_2.nii.gz') new_file_wm = "%s%s" % (anat_dir, '/WM.nii.gz') os.rename(old_file_csf, new_file_csf) os.rename(old_file_wm, new_file_wm) # Reslice to 1x1x1mm voxels #img=nib.load(anat_loc) #vox_sz = img.affine[0][0] #targ_aff = img.affine/(np.array([[int(abs(vox_sz)),1,1,1],[1,int(abs(vox_sz)),1,1],[1,1,int(abs(vox_sz)),1],[1,1,1,1]])) #new_file_csf_res = resample_img(new_file_csf, target_affine=targ_aff) #new_file_wm_res = resample_img(new_file_wm, target_affine=targ_aff) #nib.save(new_file_csf_res, new_file_csf) #nib.save(new_file_wm_res, new_file_wm) return new_file_csf, mni_csf_loc, new_file_wm
def create_mgzconvert_pipeline(name='mgzconvert'): # workflow mgzconvert = Workflow(name='mgzconvert') # inputnode inputnode = Node( util.IdentityInterface(fields=['fs_subjects_dir', 'fs_subject_id']), name='inputnode') # outputnode outputnode = Node(util.IdentityInterface(fields=[ 'anat_head', 'anat_brain', 'anat_brain_mask', 'wmseg', 'wmedge' ]), name='outputnode') # import files from freesurfer fs_import = Node(interface=nio.FreeSurferSource(), name='fs_import') # convert Freesurfer T1 file to nifti head_convert = Node(fs.MRIConvert(out_type='niigz', out_file='T1.nii.gz'), name='head_convert') # create brainmask from aparc+aseg with single dilation def get_aparc_aseg(files): for name in files: if 'aparc+aseg' in name: return name # create brain by converting only freesurfer output brain_convert = Node(fs.MRIConvert(out_type='niigz', out_file='brain.nii.gz'), name='brain_convert') brain_binarize = Node(fsl.ImageMaths(op_string='-bin -fillh', out_file='T1_brain_mask.nii.gz'), name='brain_binarize') # cortical and cerebellar white matter volumes to construct wm edge # [lh cerebral wm, lh cerebellar wm, rh cerebral wm, rh cerebellar wm, brain stem] wmseg = Node(fs.Binarize(out_type='nii.gz', match=[2, 7, 41, 46, 16], binary_file='T1_brain_wmseg.nii.gz'), name='wmseg') # make edge from wmseg to visualize coregistration quality edge = Node(fsl.ApplyMask(args='-edge -bin', out_file='T1_brain_wmedge.nii.gz'), name='edge') # connections mgzconvert.connect([ (inputnode, fs_import, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id')]), (fs_import, head_convert, [('T1', 'in_file')]), (fs_import, wmseg, [(('aparc_aseg', get_aparc_aseg), 'in_file')]), (fs_import, brain_convert, [('brainmask', 'in_file')]), (wmseg, edge, [('binary_file', 'in_file'), ('binary_file', 'mask_file')]), (head_convert, outputnode, [('out_file', 'anat_head')]), (brain_convert, outputnode, [('out_file', 'anat_brain')]), (brain_convert, brain_binarize, [('out_file', 'in_file')]), (brain_binarize, outputnode, [('out_file', 'anat_brain_mask')]), (wmseg, outputnode, [('binary_file', 'wmseg')]), (edge, outputnode, [('out_file', 'wmedge')]) ]) return mgzconvert
def create_templates_2func_workflow(threshold=0.5, name='templates_2func_workflow'): templates_2func_workflow = Workflow(name=name) # Input Node inputspec = Node(utility.IdentityInterface(fields=[ 'func_file', 'premat', 'warp', 'templates', ]), name='inputspec') # Get the overal EPI to MNI warp func_2mni_warp = Node(fsl.ConvertWarp(), name='func_2mni_warp') func_2mni_warp.inputs.reference = fsl.Info.standard_image( 'MNI152_T1_2mm.nii.gz') # Calculate the inverse warp mni_2func_warp = Node(fsl.InvWarp(), name='mni_2func_warp') # Transform MNI templates to EPI space templates_2func_apply = MapNode(fsl.ApplyWarp(), iterfield=['in_file'], name='templates_2func_apply') # Threshold templates templates_threshold = MapNode( fsl.ImageMaths(op_string='-thr {0} -bin'.format(threshold)), iterfield=['in_file'], name='templates_threshold') # Output Node outputspec = Node(utility.IdentityInterface( fields=['templates_2func_files', 'func_2mni_warp']), name='outputspec') # Connect the workflow nodes templates_2func_workflow.connect(inputspec, 'premat', func_2mni_warp, 'premat') templates_2func_workflow.connect(inputspec, 'warp', func_2mni_warp, 'warp1') templates_2func_workflow.connect(inputspec, 'func_file', mni_2func_warp, 'reference') templates_2func_workflow.connect(func_2mni_warp, 'out_file', mni_2func_warp, 'warp') templates_2func_workflow.connect(inputspec, 'templates', templates_2func_apply, 'in_file') templates_2func_workflow.connect(inputspec, 'func_file', templates_2func_apply, 'ref_file') templates_2func_workflow.connect(mni_2func_warp, 'inverse_warp', templates_2func_apply, 'field_file') templates_2func_workflow.connect(templates_2func_apply, 'out_file', templates_threshold, 'in_file') templates_2func_workflow.connect(func_2mni_warp, 'out_file', outputspec, 'func_2mni_warp') templates_2func_workflow.connect(templates_threshold, 'out_file', outputspec, 'templates_2func_files') return templates_2func_workflow
def copes1_2_anat_func(fixed, cope1_10Hz_r1, cope1_10Hz_r2, cope1_10Hz_r3, func_2_anat_trans_10Hz_r1, func_2_anat_trans_10Hz_r2, func_2_anat_trans_10Hz_r3, mask_brain): import os import re import nipype.interfaces.ants as ants import nipype.interfaces.fsl as fsl cwd = os.getcwd() copes1 = [cope1_10Hz_r1, cope1_10Hz_r2, cope1_10Hz_r3] trans = [ func_2_anat_trans_10Hz_r1, func_2_anat_trans_10Hz_r2, func_2_anat_trans_10Hz_r3 ] copes1_2_anat = [] FEtdof_t1_2_anat = [] for i in range(len(copes1)): moving = copes1[i] transform = trans[i] ants_apply = ants.ApplyTransforms() ants_apply.inputs.dimension = 3 ants_apply.inputs.input_image = moving ants_apply.inputs.reference_image = fixed ants_apply.inputs.transforms = transform ants_apply.inputs.output_image = 'cope1_2_anat_10Hz_r{0}.nii.gz'.format( i + 1) ants_apply.run() copes1_2_anat.append( os.path.abspath('cope1_2_anat_10Hz_r{0}.nii.gz'.format(i + 1))) dof = fsl.ImageMaths() dof.inputs.in_file = 'cope1_2_anat_10Hz_r{0}.nii.gz'.format(i + 1) dof.inputs.op_string = '-mul 0 -add 147 -mas' dof.inputs.in_file2 = mask_brain dof.inputs.out_file = 'FEtdof_t1_2_anat_10Hz_r{0}.nii.gz'.format(i + 1) dof.run() FEtdof_t1_2_anat.append( os.path.abspath('FEtdof_t1_2_anat_10Hz_r{0}.nii.gz'.format(i + 1))) merge = fsl.Merge() merge.inputs.dimension = 't' merge.inputs.in_files = copes1_2_anat merge.inputs.merged_file = 'copes1_2_anat_10Hz.nii.gz' merge.run() merge.inputs.in_files = FEtdof_t1_2_anat merge.inputs.merged_file = 'dofs_t1_2_anat_10Hz.nii.gz' merge.run() copes1_2_anat = os.path.abspath('copes1_2_anat_10Hz.nii.gz') dofs_t1_2_anat = os.path.abspath('dofs_t1_2_anat_10Hz.nii.gz') return copes1_2_anat, dofs_t1_2_anat
def create_2lvl(name="group"): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import nipype.interfaces.utility as niu wk = pe.Workflow(name=name) inputspec = pe.Node(niu.IdentityInterface(fields=['copes','varcopes', 'template', "contrasts", "regressors"]),name='inputspec') model = pe.Node(fsl.MultipleRegressDesign(),name='l2model') #wk.connect(inputspec,('copes',get_len),model,'num_copes') wk.connect(inputspec, 'contrasts', model, "contrasts") wk.connect(inputspec, 'regressors', model, "regressors") mergecopes = pe.Node(fsl.Merge(dimension='t'),name='merge_copes') mergevarcopes = pe.Node(fsl.Merge(dimension='t'),name='merge_varcopes') flame = pe.Node(fsl.FLAMEO(run_mode='ols'),name='flameo') wk.connect(inputspec,'copes',mergecopes,'in_files') wk.connect(inputspec,'varcopes',mergevarcopes,'in_files') wk.connect(model,'design_mat',flame,'design_file') wk.connect(model,'design_con',flame, 't_con_file') wk.connect(mergecopes, 'merged_file', flame, 'cope_file') wk.connect(mergevarcopes,'merged_file',flame,'var_cope_file') wk.connect(model,'design_grp',flame,'cov_split_file') bet = pe.Node(fsl.BET(mask=True,frac=0.3),name="template_brainmask") wk.connect(inputspec,'template',bet,'in_file') wk.connect(bet,'mask_file',flame,'mask_file') outputspec = pe.Node(niu.IdentityInterface(fields=['zstat','tstat','cope', 'varcope','mrefvars', 'pes','res4d','mask', 'tdof','weights','pstat']), name='outputspec') wk.connect(flame,'copes',outputspec,'cope') wk.connect(flame,'var_copes',outputspec,'varcope') wk.connect(flame,'mrefvars',outputspec,'mrefvars') wk.connect(flame,'pes',outputspec,'pes') wk.connect(flame,'res4d',outputspec,'res4d') wk.connect(flame,'weights',outputspec,'weights') wk.connect(flame,'zstats',outputspec,'zstat') wk.connect(flame,'tstats',outputspec,'tstat') wk.connect(flame,'tdof',outputspec,'tdof') wk.connect(bet,'mask_file',outputspec,'mask') ztopval = pe.MapNode(interface=fsl.ImageMaths(op_string='-ztop', suffix='_pval'), name='z2pval', iterfield=['in_file']) wk.connect(flame,'zstats',ztopval,'in_file') wk.connect(ztopval,'out_file',outputspec,'pstat') return wk
def coreg_vent_CSF_to_diff(dwi_dir, csf_loc, mni_csf_loc): import nipype.interfaces.fsl as fsl print('\nTransforming CSF mask to diffusion space...') merged_f_samples_path = "%s%s" % (dwi_dir, '/merged_f1samples.nii.gz') if os.path.exists(merged_f_samples_path) is True: dwi_infile = merged_f_samples_path else: dwi_infile = "%s%s" % (dwi_dir, '/dwi.nii.gz') csf_mask_diff_out = "%s%s" % (dwi_dir, '/csf_diff.nii.gz') vent_mask_diff_out = dwi_dir + '/ventricle_diff.nii.gz' # Create transform matrix between diff and MNI using FLIRT to get CSF in diff space cmd = "flirt -in {} -init {} -ref {} -out {} -omat {} -interp trilinear -cost mutualinfo -applyxfm -dof 12 -searchrx -180 180 -searchry -180 180 -searchrz -180 180" cmd_run = cmd.format(csf_loc, "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat'), dwi_infile, csf_mask_diff_out, '/tmp/out_flirt.mat') os.system(cmd_run) # Apply transform between diff and MNI using FLIRT to get ventricles in diff space cmd = "flirt -in {} -init {} -ref {} -out {} -omat {} -interp trilinear -cost mutualinfo -applyxfm -dof 12 -searchrx -180 180 -searchry -180 180 -searchrz -180 180" cmd_run = cmd.format(mni_csf_loc, "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat'), dwi_infile, vent_mask_diff_out, '/tmp/out_flirt.mat') os.system(cmd_run) # Mask CSF with MNI ventricle mask print('Masking CSF with ventricle mask...') vent_csf_diff_out = "%s%s" % (dwi_dir, '/vent_csf_diff.nii.gz') args = "%s%s" % ('-mas ', vent_mask_diff_out) maths = fsl.ImageMaths(in_file=csf_mask_diff_out, op_string=args, out_file=vent_csf_diff_out) os.system(maths.cmdline) print('Eroding and binarizing CSF mask...') # Erode CSF mask out_file_final = "%s%s" % (vent_csf_diff_out.split('.nii.gz')[0], '_ero.nii.gz') args = '-ero -bin' maths = fsl.ImageMaths(in_file=vent_csf_diff_out, op_string=args, out_file=out_file_final) os.system(maths.cmdline) return out_file_final
def create_highpass_filter(cutoff=100, name='highpass'): highpass = Workflow(name=name) inputspec = Node(utility.IdentityInterface(fields=['in_file']), name='inputspec') # calculate sigma def calculate_sigma(in_file, cutoff): import subprocess output = subprocess.check_output(['fslinfo', in_file]).decode().split("\n") for out in output: if out.startswith("pixdim4"): sigma = cutoff / (2 * float(out.lstrip("pixdim4"))) return '-bptf %.10f -1' % sigma getsigma = Node(utility.Function(function=calculate_sigma, input_names=['in_file', 'cutoff'], output_names=['op_string']), name='getsigma') getsigma.inputs.cutoff = cutoff # save mean meanfunc = Node(fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), name='meanfunc') # filter data filter_ = Node(fsl.ImageMaths(suffix='_tempfilt'), name='filter') # restore mean addmean = Node(fsl.BinaryMaths(operation='add'), name='addmean') outputspec = Node(utility.IdentityInterface(fields=['filtered_file']), name='outputspec') highpass.connect(inputspec, 'in_file', filter_, 'in_file') highpass.connect(inputspec, 'in_file', getsigma, 'in_file') highpass.connect(getsigma, 'op_string', filter_, 'op_string') highpass.connect(inputspec, 'in_file', meanfunc, 'in_file') highpass.connect(filter_, 'out_file', addmean, 'in_file') highpass.connect(meanfunc, 'out_file', addmean, 'operand_file') highpass.connect(addmean, 'out_file', outputspec, 'filtered_file') return highpass
def coreg_vent_CSF_to_diff(nodif_brain_mask_path, bedpostx_dir, csf_loc, mni_csf_loc): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe csf_mask_diff_out = bedpostx_dir + '/csf_diff.nii.gz' flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = nodif_brain_mask_path flirt.inputs.in_file = csf_loc flirt.inputs.out_file = csf_mask_diff_out flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.inputs.apply_xfm = True flirt.run() vent_mask_diff_out = bedpostx_dir + '/ventricle_diff.nii.gz' flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = nodif_brain_mask_path flirt.inputs.in_file = mni_csf_loc flirt.inputs.out_file = vent_mask_diff_out flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.inputs.apply_xfm = True flirt.run() ##Mask CSF with MNI ventricle mask print('Masking CSF with ventricle mask...') vent_csf_diff_out = bedpostx_dir + '/vent_csf_diff.nii.gz' args = '-mas ' + vent_mask_diff_out maths = fsl.ImageMaths(in_file=csf_mask_diff_out, op_string=args, out_file=vent_csf_diff_out) os.system(maths.cmdline) print('Eroding CSF mask...') ##Erode CSF mask out_file_final = vent_csf_diff_out.split('.nii.gz')[0] + '_ero.nii.gz' args = '-ero -bin' maths = fsl.ImageMaths(in_file=vent_csf_diff_out, op_string=args, out_file=out_file_final) os.system(maths.cmdline) return out_file_final
def average_template_( self, Template_4D, List, Template ): """Merge the list in a 4D image; average the 4D imge in a 3D image; flip the image and and average the flipped and unflipped iamges.""" try: # # # merge tissues in a 4D file merger = fsl.Merge() merger.inputs.in_files = List merger.inputs.dimension = 't' merger.inputs.output_type = 'NIFTI_GZ' merger.inputs.merged_file = Template_4D merger.run() # average over frames maths = fsl.ImageMaths( in_file = Template_4D, op_string = '-Tmean', out_file = Template ) maths.run(); # Flip the frames swap = fsl.SwapDimensions() swap.inputs.in_file = Template swap.inputs.new_dims = ("-x","y","z") swap.inputs.out_file = "%s_flipped.nii.gz"%Template[:-7] swap.run() # average the frames maths = fsl.ImageMaths( in_file = Template, op_string = '-add %s -div 2'%Template[:-7], out_file = Template ) maths.run(); # # except Exception as inst: print inst _log.error(inst) quit(-1) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) quit(-1) except: print "Unexpected error:", sys.exc_info()[0] quit(-1)
def generate_common_mask(inputs): mask_list = [] for subj in inputs: mask = os.path.join(OUTPUT, 'stage1', 'mask_idc_' + subj + '.nii.gz') mask_list.append(mask) allFile = os.path.join(OUTPUT, 'stage1', 'maskALL.nii.gz') cmd_out = os.path.join(OUTPUT, 'stage1', 'stage1_maskall_idc_' + subj + '.out') fslmerge = fsl.Merge(dimension='t', terminal_output='stream',in_files=mask_list, merged_file=allFile, output_type='NIFTI_GZ') write_cmd_out(fslmerge.cmdline, cmd_out) fslmerge.run() oFile = os.path.join(OUTPUT, 'stage1', 'mask.nii.gz') fslmaths = fsl.ImageMaths(in_file=allFile, op_string='-Tmin', out_file=oFile) fslmaths.run()
def dual_reg_mask(subj): iFile = os.path.join(os.path.dirname(self.indir), subj, 'idc_' + subj + self.featdir_sfix, self.ff_data_name) oFile = os.path.join(self.outdir, 'stage1', 'mask_idc_' + subj + '.nii.gz') self.mask_list.append(oFile) fslmaths = fsl.ImageMaths(in_file=iFile, op_string='-Tstd -bin', out_file=oFile, output_type='NIFTI_GZ', out_data_type='char') fslmaths.run()
def create_anat_noise_roi_workflow(SinkTag="func_preproc", wf_name="create_noise_roi"): """ Creates an anatomical noise ROI for use with compcor inputs are awaited from the (BBR-based) func2anat registration and are already transformed to functional space Tamas Spisak 2018 """ import os import nipype import nipype.pipeline as pe import nipype.interfaces.utility as utility import nipype.interfaces.fsl as fsl import PUMI.utils.globals as globals # Basic interface class generates identity mappings inputspec = pe.Node( utility.IdentityInterface(fields=['wm_mask', 'ventricle_mask']), name='inputspec') # Basic interface class generates identity mappings outputspec = pe.Node(utility.IdentityInterface(fields=['noise_roi']), name='outputspec') SinkDir = os.path.abspath(globals._SinkDir_ + "/" + SinkTag) if not os.path.exists(SinkDir): os.makedirs(SinkDir) wf = nipype.Workflow(wf_name) # erode WM mask in functional space erode_mask = pe.MapNode(fsl.ErodeImage(), iterfield=['in_file'], name="erode_wm_mask") wf.connect(inputspec, 'wm_mask', erode_mask, 'in_file') # add ventricle and eroded WM masks add_masks = pe.MapNode(fsl.ImageMaths(op_string=' -add'), iterfield=['in_file', 'in_file2'], name="addimgs") wf.connect(inputspec, 'ventricle_mask', add_masks, 'in_file') wf.connect(erode_mask, 'out_file', add_masks, 'in_file2') wf.connect(add_masks, 'out_file', outputspec, 'noise_roi') return wf
def generate_mask(subj, **kwargs): iFile = os.path.join(os.path.dirname(INPUT), subj, feat_pfix + subj + feat_sfix, ff_data_name) if not os.path.exists(iFile): print 'Cannot locate input file....must exit' print 'input file: ', iFile print 'Please ensure that subject has the input file, or adjust the subject list to remove them.' sys.exit(0) oFile = os.path.join(OUTPUT, 'stage1', 'mask_idc_' + subj + '.nii.gz') if os.path.exists(oFile): return cmd_out = os.path.join(OUTPUT, 'stage1', 'stage1_masking_idc_' + subj + '.out') fslmaths = fsl.ImageMaths(in_file=iFile, op_string= '-Tstd -bin', out_file=oFile, output_type='NIFTI_GZ', out_data_type='char') write_cmd_out(fslmaths.cmdline, cmd_out) fslmaths.run()
def warp_CBF_map( self, CBF_dir, CBF_list ): """Apply warp to the CBF map and smooth.""" try: # # # # create the pool of threads for i in range( self.procs_ ): t = threading.Thread( target = self.CBF_modulation_, args=[CBF_dir] ) t.daemon = True t.start() # Stack the items for item in CBF_list: self.queue_CBF_.put(item) # block until all tasks are done self.queue_CBF_.join() # # 4D image with modulated CBF CBF_modulated_template_4D = os.path.join(self.ana_dir_, "CBF_modulated_template_4D.nii.gz") # merger = fsl.Merge() merger.inputs.in_files = self.CBF_modulated_template_ merger.inputs.dimension = 't' merger.inputs.output_type = 'NIFTI_GZ' merger.inputs.merged_file = CBF_modulated_template_4D merger.run() # # Smooth the 4D image for sigma in [2, 3, 4]: CBF_mod_smooth_4D = os.path.join(self.ana_dir_, "CBF_modulated_template_4D_%s_sigma.nii.gz"%sigma) # maths = fsl.ImageMaths() maths.inputs.in_file = CBF_modulated_template_4D maths.inputs.op_string = "-fmean -kernel gauss %s"%sigma maths.inputs.out_file = CBF_mod_smooth_4D maths.run() # # except Exception as inst: print inst _log.error(inst) quit(-1) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) quit(-1) except: print "Unexpected error:", sys.exc_info()[0] quit(-1)
def func_preprocess(name='func_preproc'): ''' Method to preprocess functional data after warping to anatomical space. Accomplished after one step Distortion Correction, Motion Correction and Boundary based linear registration to anatomical space. Precodure includes: # 1- skull strip # 2- Normalize the image intensity values. # 3- Calculate Mean of Skull stripped image # 4- Create brain mask from Normalized data. ''' # Define Workflow flow = Workflow(name=name) inputnode = Node(util.IdentityInterface(fields=['func_in']), name='inputnode') outputnode = Node(util.IdentityInterface( fields=['func_preproc', 'func_preproc_mean', 'func_preproc_mask']), name='outputnode') # 2- Normalize the image intensity values. norm = Node(interface=fsl.ImageMaths(), name='func_normalized') norm.inputs.op_string = '-ing 1000' norm.out_data_type = 'float' norm.output_type = 'NIFTI' # 4- Create brain mask from Normalized data. mask = Node(interface=fsl.BET(), name='func_preprocessed') mask.inputs.functional = True mask.inputs.mask = True mask.inputs.frac = 0.5 mask.inputs.vertical_gradient = 0 mask.inputs.threshold = True # 3- Calculate Mean of Skull stripped image mean = Node(interface=preprocess.TStat(), name='func_preprocessed_mean') mean.inputs.options = '-mean' mean.inputs.outputtype = 'NIFTI' flow.connect(inputnode, 'func_in', norm, 'in_file') flow.connect(norm, 'out_file', mask, 'in_file') flow.connect(norm, 'out_file', mean, 'in_file') flow.connect(mask, 'out_file', outputnode, 'func_preproc') flow.connect(mask, 'mask_file', outputnode, 'func_preproc_mask') flow.connect(mean, 'out_file', outputnode, 'func_preproc_mean') return flow
def CBF_modulation_( self, CBF_dir ): """CBF applyed GM Modulation.""" try: # # # Loop on the tasks while True: # get the item item = self.queue_CBF_.get() # find the corresponding GM GM_warp_coeff = "%s_non_li_template_coeff.nii.gz"%(item[4:-7]) GM_warp_jac = "%s_non_li_template_jac.nii.gz"%(item[4:-7]) # apply the GM warp aw = fsl.ApplyWarp() aw.inputs.in_file = os.path.join(CBF_dir, item ) aw.inputs.ref_file = self.template_ aw.inputs.out_file = os.path.join( self.template_dir_, "%s_non_li_template_warped.nii.gz"%item[:-7] ) aw.inputs.field_file = os.path.join( self.template_dir_, GM_warp_coeff ) res = aw.run() # Modulate with the GM jacobian maths = fsl.ImageMaths() maths.inputs.in_file = os.path.join(self.template_dir_, "%s_non_li_template_warped.nii.gz"%item[:-7]) maths.inputs.op_string = '-mul %s'%( os.path.join(self.template_dir_, GM_warp_jac) ) maths.inputs.out_file = os.path.join( self.template_dir_, "%s_modulated.nii.gz"%item[:-7] ) maths.inputs.out_data_type = "float" maths.run(); # lock and add the file singlelock.acquire() self.CBF_warped_template_.append( aw.inputs.out_file ) self.CBF_modulated_template_.append( maths.inputs.out_file ) singlelock.release() # job is done self.queue_CBF_.task_done() # # except Exception as inst: print inst _log.error(inst) quit(-1) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) quit(-1) except: print "Unexpected error:", sys.exc_info()[0] quit(-1)
def normalize_image(nifti_input_file): #from nipype.interfaces.fsl import ImageStats from nipype.interfaces import fsl """ This will take an image and scale it so the mean intensity is 100 ....""" stats = fsl.ImageStats(in_file=nifti_input_file, op_string='-R') stats_results = stats.run() ### so the -R flag outputs the min and max robust intensity value # print stats_results.outputs[1] # So this gets messy quickly... normalize_image = fsl.ImageMaths(in_file=nifti_input_file, op_string=' -div ' + str(stats_results.outputs.out_stat[1]) + ' -mul 1000') run_image_norm = normalize_image.run() return run_image_norm.outputs.out_file