def set_bet(self): bet = fsl.BET() bet.inputs.in_file = self.field_mag bet.inputs.out_file = ( f"{os.path.dirname(self.field_mag)}/field_mag_brain.nii.gz" ) return bet
def bet_T1(self, **kwargs): pipeline = self.create_pipeline( name='BET_T1', inputs=[DatasetSpec('t1', nifti_gz_format)], outputs=[ DatasetSpec('betted_T1', nifti_gz_format), DatasetSpec('betted_T1_mask', nifti_gz_format) ], desc=("python implementation of BET"), version=1, citations=[fsl_cite], **kwargs) bias = pipeline.create_node(interface=ants.N4BiasFieldCorrection(), name='n4_bias_correction', requirements=[ants19_req], wall_time=60, memory=12000) pipeline.connect_input('t1', bias, 'input_image') bet = pipeline.create_node(fsl.BET(frac=0.15, reduce_bias=True), name='bet', requirements=[fsl5_req], memory=8000, wall_time=45) pipeline.connect(bias, 'output_image', bet, 'in_file') pipeline.connect_output('betted_T1', bet, 'out_file') pipeline.connect_output('betted_T1_mask', bet, 'mask_file') return pipeline
def _prepare_coregistration(item, input_dir, tmp_dir): """Prepare coregistering by generating the mean b0's and the corresponding masks. Args: item (str): the item basename to prepare input_dir (str): the input directory in which the items reside tmp_dir (str): the output dir. The output is: - basename_b0s.nii.gz - basename_mean_b0s.nii.gz - basename_mask.nii.gz (the skull stripped image) - basename_mask_mask.nii.gz (the binary mask). """ dwi = os.path.join(input_dir, item + '.nii.gz') bvec = os.path.join(input_dir, item + '.bvec') bval = os.path.join(input_dir, item + '.bval') b0_file = os.path.join(tmp_dir, item + '_b0s.nii.gz') mean_b0_file = os.path.join(tmp_dir, item + '_mean_b0s.nii.gz') masked_file = os.path.join(tmp_dir, item + '_mask.nii.gz') write_unweighted(dwi, bvec, bval, b0_file) create_mean_volumes(b0_file, mean_b0_file) bet = pe.Node(fsl.BET(frac=0.35, mask=True, robust=True, in_file=mean_b0_file, out_file=masked_file), name='bet') bet.run()
def _run_interface_pbr(self, runtime): #insert workflow here: import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import nipype.interfaces.freesurfer as fs import nipype.interfaces.io as nio bet = pe.MapNode(interface=fsl.BET(), name = 'bet', iterfield=['frac']) bet.inputs.in_file = #define in_file right here bet.inputs.frac = [0.7, 0.5, 0.3] fast = pe.MapNode(interface=fsl.FAST(), name='fast', iterfield=['in_files']) ss = pe.MapNode(interface=fs.SegStats(), name='ss', iterfield=['segmentation_file']) ds = pe.Node(interface=nio.DataSink(), name="ds", iterfield=['in_files']) ds.inputs.base_directory = #define the output here workflow = pe.Workflow(name='ute_flow') workflow.base_dir = '.' workflow.connect([(bet, fast, [('out_file', 'in_files')]), (fast, ss,[('mixeltype', 'segmentation_file')]), (ss, ds, [('avgwf_file', 'in_files')])]) workflow.run() """print(self.inputs)""" #this was used for checking if the workflow was being triggered and run #vi inserted into ucsf server side ute.py return runtime
def build_nodes(self): # BET - Skullstrip anatomical Image self.bet_anat = Node(fsl.BET(frac=0.5, robust=True, output_type='NIFTI_GZ'), name="bet_anat") # image segmentation self.segmentation = Node(fsl.FAST(output_type='NIFTI_GZ'), name='segmentation') # threshold WM probability image self.threshold = Node(fsl.Threshold(thresh=0.5, args='-bin', output_type='NIFTI_GZ'), name='threshold') # flirt - pre-alignment of images self.coreg_pre = Node(fsl.FLIRT(dof=6, output_type='NIFTI_GZ'), name='coreg_pre') # co-reg self.coreg_mi = Node(fsl.FLIRT(bins=640, cost_func='bbr', interp='spline', searchr_x=[-180, 180], searchr_y=[-180, 180], searchr_z=[-180, 180], dof=6, output_type='NIFTI_GZ'), name='coreg_mi') # apply warp map to images self.applywarp = Node(fsl.preprocess.ApplyXFM(apply_xfm=True, output_type='NIFTI_GZ'), name='applywarp') # Apply coregistration warp to mean file self.applywarp_mean = Node(fsl.FLIRT(interp='spline',output_type='NIFTI_GZ'), name="applywarp_mean")
def bet_T1(self, **name_maps): pipeline = self.new_pipeline( name='BET_T1', name_maps=name_maps, desc=("Brain extraction pipeline using FSL's BET"), citations=[fsl_cite]) bias = pipeline.add('n4_bias_correction', ants.N4BiasFieldCorrection(), inputs={'input_image': ('t1', nifti_gz_format)}, requirements=[ants_req.v('1.9')], wall_time=60, mem_gb=12) pipeline.add('bet', fsl.BET(frac=0.15, reduce_bias=True, output_type='NIFTI_GZ'), inputs={'in_file': (bias, 'output_image')}, outputs={ 'betted_T1': ('out_file', nifti_gz_format), 'betted_T1_mask': ('mask_file', nifti_gz_format) }, requirements=[fsl_req.v('5.0.8')], mem_gb=8, wall_time=45) return pipeline
def ssn4(p): print(p, patients[p]) patient_dir = basedir + patients[p] + '/' os.chdir(patient_dir) #n4 bias correction n4 = N4BiasFieldCorrection(output_image= 'FLAIR_n4.nii') n4.inputs.input_image = 'FLAIR.nii' n4.inputs.n_iterations = [20,20,10,5] n4.run() n4 = N4BiasFieldCorrection(output_image= 'T2_n4.nii') n4.inputs.input_image = 'T2.nii' n4.inputs.n_iterations = [20,20,10,5] n4.run() n4 = N4BiasFieldCorrection(output_image= 'T1_n4.nii') n4.inputs.input_image = 'T1.nii' n4.inputs.n_iterations = [20,20,10,5] n4.run() n4 = N4BiasFieldCorrection(output_image= 'T1post_n4.nii') n4.inputs.input_image = 'T1post.nii' n4.inputs.n_iterations = [20,20,10,5] n4.run() #skullstripping mybet = fsl.BET() result = mybet.run(in_file='FLAIR_n4.nii', out_file='FLAIR_ss_n4.nii', frac=0.4, output_type = 'NIFTI') result = mybet.run(in_file='T2_n4.nii', out_file='T2_ss_n4.nii', frac=0.3, output_type = 'NIFTI') result = mybet.run(in_file='T1_n4.nii', out_file='T1_ss_n4.nii', frac=0.5, output_type = 'NIFTI') result = mybet.run(in_file='T1post_n4.nii', out_file='T1post_ss_n4.nii', frac=0.5, output_type = 'NIFTI')
def _bet_brain_extraction_pipeline(self, **name_maps): """ Generates a whole brain mask using FSL's BET command. """ pipeline = self.new_pipeline( name='brain_extraction', name_maps=name_maps, desc="Generate brain mask from mr_scan", citations=[fsl_cite, bet_cite, bet2_cite]) # Create mask node bet = pipeline.add( "bet", fsl.BET( mask=True, output_type='NIFTI_GZ', frac=self.parameter('bet_f_threshold'), vertical_gradient=self.parameter('bet_g_threshold')), inputs={ 'in_file': ('mag_preproc', nifti_gz_format)}, outputs={ 'brain': ('out_file', nifti_gz_format), 'brain_mask': ('mask_file', nifti_gz_format)}, requirements=[fsl_req.v('5.0.9')]) # Set either robust or reduce bias if self.branch('bet_robust'): bet.inputs.robust = True else: bet.inputs.reduce_bias = self.parameter('bet_reduce_bias') return pipeline
def bet_T1(self, **name_maps): pipeline = self.new_pipeline(name='BET_T1', name_maps=name_maps, desc=("python implementation of BET"), references=[fsl_cite]) bias = pipeline.add('n4_bias_correction', ants.N4BiasFieldCorrection(), inputs={'input_image': ('t1', nifti_gz_format)}, requirements=[ants_req.v('1.9')], wall_time=60, mem_gb=12) pipeline.add('bet', fsl.BET(frac=0.15, reduce_bias=True), connections={'in_file': (bias, 'output_image')}, outputs={ 'out_file': ('betted_T1', nifti_gz_format), 'mask_file': ('betted_T1_mask', nifti_gz_format) }, requirements=[fsl_req.v('5.0.8')], mem_gb=8, wall_time=45) return pipeline
def __init__(self, in_file='path', **options): from nipype.interfaces import fsl btr = fsl.BET() btr.inputs.in_file = in_file for ef in options: setattr(btr.inputs, ef, options[ef]) self.res = btr.run()
def _fsl_bet_brain_extraction_pipeline(self, in_file, **kwargs): """ Generates a whole brain mask using FSL's BET command. """ pipeline = self.create_pipeline( name='brain_extraction', inputs=[DatasetSpec(in_file, nifti_gz_format)], outputs=[ DatasetSpec('brain', nifti_gz_format), DatasetSpec('brain_mask', nifti_gz_format) ], desc="Generate brain mask from mr_scan", version=1, citations=[fsl_cite, bet_cite, bet2_cite], **kwargs) # Create mask node bet = pipeline.create_node(interface=fsl.BET(), name="bet", requirements=[fsl509_req]) bet.inputs.mask = True bet.inputs.output_type = 'NIFTI_GZ' if self.parameter('bet_robust'): bet.inputs.robust = True if self.parameter('bet_reduce_bias'): bet.inputs.reduce_bias = True bet.inputs.frac = self.parameter('bet_f_threshold') bet.inputs.vertical_gradient = self.parameter('bet_g_threshold') # Connect inputs/outputs pipeline.connect_input(in_file, bet, 'in_file') pipeline.connect_output('brain', bet, 'out_file') pipeline.connect_output('brain_mask', bet, 'mask_file') return pipeline
def bet_T2s(self, **options): pipeline = self.new_pipeline( name='BET_T2s', inputs=[FilesetSpec('t2s', nifti_gz_format), FilesetSpec('t2s_last_echo', nifti_gz_format)], outputs=[FilesetSpec('betted_T2s', nifti_gz_format), FilesetSpec('betted_T2s_mask', nifti_gz_format), FilesetSpec('betted_T2s_last_echo', nifti_gz_format)], desc=("python implementation of BET"), default_options={}, citations=[fsl_cite], options=options) bet = pipeline.create_node( fsl.BET(frac=0.1, mask=True), name='bet', requirements=[fsl_req.v('5.0.8')], mem_gb=8, wall_time=45) pipeline.connect_input('t2s', bet, 'in_file') pipeline.connect_output('betted_T2s', bet, 'out_file') pipeline.connect_output('betted_T2s_mask', bet, 'mask_file') maths = pipeline.create_node( fsl.utils.ImageMaths(suffix='_BET_brain', op_string='-mas'), name='mask', requirements=[fsl_req.v('5.0.8')], mem_gb=16, wall_time=5) pipeline.connect_input('t2s_last_echo', maths, 'in_file') pipeline.connect(bet, 'mask_file', maths, 'in_file2') pipeline.connect_output('betted_T2s_last_echo', maths, 'out_file') return pipeline
def applyBET(input_file, frac, radius, vertical_gradient): # scale Nifti data by factor 10 fslPath = scaleBy10(input_file, inv=False) # extract brain output_file = os.path.join( os.path.dirname(input_file), os.path.basename(input_file).split('.')[0]) + 'Bet.nii.gz' maskFile = os.path.join( os.path.dirname(input_file), os.path.basename(input_file).split('.')[0]) + 'Bet_mask.nii.gz' myBet = fsl.BET(in_file=fslPath, out_file=output_file, frac=frac, radius=radius, vertical_gradient=vertical_gradient, robust=True, mask=True) print(myBet.cmdline) myBet.run() os.remove(fslPath) # unscale result data by factor 10ˆ(-1) output_file = scaleBy10(output_file, inv=True) maskFile = scaleBy10(maskFile, inv=True) return output_file, maskFile
def remove_bias(name='bias_correct'): """ This workflow estimates a single multiplicative bias field from the averaged *b0* image, as suggested in [Jeurissen2014]_. .. admonition:: References .. [Jeurissen2014] Jeurissen B. et al., `Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data <http://dx.doi.org/10.1016/j.neuroimage.2014.07.061>`_.squeue NeuroImage (2014). doi: 10.1016/j.neuroimage.2014.07.061 Example ------- >>> from nipype.workflows.dmri.fsl.artifacts import remove_bias >>> bias = remove_bias() >>> bias.inputs.inputnode.in_file = 'epi.nii' >>> bias.inputs.inputnode.in_bval = 'diffusion.bval' >>> bias.inputs.inputnode.in_mask = 'mask.nii' >>> bias.run() # doctest: +SKIP """ import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe import nipype.interfaces.fsl as fsl import nipype.interfaces.ants as ants inputnode = pe.Node(niu.IdentityInterface( fields=['in_file']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(fields=['out_file', 'b0_mask']), name='outputnode') get_b0 = pe.Node(fsl.ExtractROI(t_min=0, t_size=1), name='get_b0') mask_b0 = pe.Node(fsl.BET(frac=0.3, mask=True, robust=True), name='mask_b0') n4 = pe.Node(ants.N4BiasFieldCorrection( dimension=3, save_bias=True, bspline_fitting_distance=600), name='Bias_b0') split = pe.Node(fsl.Split(dimension='t'), name='SplitDWIs') mult = pe.MapNode(fsl.MultiImageMaths(op_string='-div %s'), iterfield=['in_file'], name='RemoveBiasOfDWIs') thres = pe.MapNode(fsl.Threshold(thresh=0.0), iterfield=['in_file'], name='RemoveNegative') merge = pe.Node(fsl.utils.Merge(dimension='t'), name='MergeDWIs') wf = pe.Workflow(name=name) wf.connect([ (inputnode, get_b0, [('in_file', 'in_file')]), (get_b0, n4, [('roi_file', 'input_image')]), (get_b0, mask_b0, [('roi_file', 'in_file')]), (mask_b0, n4, [('mask_file', 'mask_image')]), (inputnode, split, [('in_file', 'in_file')]), (n4, mult, [('bias_image', 'operand_files')]), (split, mult, [('out_files', 'in_file')]), (mult, thres, [('out_file', 'in_file')]), (thres, merge, [('out_file', 'in_files')]), (merge, outputnode, [('merged_file', 'out_file')]), (mask_b0, outputnode, [('mask_file', 'b0_mask')]) ]) return wf
def do_Brain_Skull_Extraction(infile, maskfile, skullfile, outfile, fraction): # Doing Brain Extraction ''' Parameters ---------- infile : str path containing the input image. maskfile : str path to save the mask after brain extraction. skullfile : str path to save the skull after brain extraction. outfile : str path to save the image after brain extraction (BET tool from FSL is used). fraction : float fraction that controls extent of brain extraction (lower value removes more outer brain). Returns ------- an image which is the brain extracted version of input image a binary image which is the mask for extracted brain another binary image which is the mask for the skull ''' print('doing brain and skull extraction for', infile) btr = fsl.BET() btr.inputs.in_file = infile btr.inputs.frac = fraction btr.inputs.robust = True btr.inputs.out_file = outfile btr.inputs.mask = True btr.inputs.skull = True btr.inputs.output_type = 'NIFTI' btr.run() os.rename(maskfile[0:-9] + '_mask.nii', maskfile) os.rename(skullfile[0:-10] + '_skull.nii', skullfile) print('brain and skull extraction completed', outfile, skullfile, '\n')
def extractBrainRegion(baselineNiifilename, niiBrainFilename='', niiBrainMaskFilename=''): # start skull stripping to get the brain region using FSL's bet tool if niiBrainFilename == '': f = baselineNiifilename.find('.') niiBrainFilename = baselineNiifilename[0:f] + '_brain.nii.gz' niiBrainMaskFilename = baselineNiifilename[0:f] + '_brain_mask.nii.gz' fslBet = fsl.BET() fslBet.inputs.in_file = baselineNiifilename fslBet.inputs.out_file = niiBrainFilename fslBet.inputs.mask = True fslBet.inputs.mesh = True fslBet.inputs.outline = True #fslBet.inputs.reduce_bias = True # takes alot of time to clean the neck fslBet.inputs.vertical_gradient = 0.1 # vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top fslBet.inputs.frac = 0.2 # fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates betInterface = fslBet.run() #cmd: bet CURRENT_RAW_2012.nii.gz mask.nii -o -m -f 0.2 -g 0.1 -R -S -B niiMask = nib.load(niiBrainMaskFilename) brainMask = niiMask.get_data() return brainMask
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 extraction_node(config: dict, **kwargs): ''' Parses config file to return desired brain extraction method. Parameters ---------- config : dict PALS config file kwargs Keyword arguments to send to brain extraction method. Returns ------- MapNode ''' # Get extraction type extract_type = config['Analysis']['BrainExtractionMethod'] if (not config['Analysis']['BrainExtraction']): # No brain extraction; in-> out n = MapNode(Function(function=infile_to_outfile, input_names='in_file', output_names='out_file'), name='extract_skip', iterfield='in_file') return n elif (extract_type.lower() == 'bet'): n = MapNode(fsl.BET(**kwargs), name='extraction_bet', iterfield='in_file') return n else: raise (NotImplementedError( f'Extraction method {extract_type} not implemented.'))
def create_dwi_preprocess_pipeline(name="preprocess"): inputnode = pe.Node(interface=util.IdentityInterface(fields=['dwi']), name="inputnode") preprocess = pe.Workflow(name=name) """ extract the volume with b=0 (nodif_brain) """ fslroi = pe.Node(interface=fsl.ExtractROI(), name='fslroi') fslroi.inputs.t_min = 0 fslroi.inputs.t_size = 1 """ create a brain mask from the nodif_brain """ bet = pe.Node(interface=fsl.BET(), name='bet') bet.inputs.mask = True bet.inputs.frac = 0.34 """ correct the diffusion weighted images for eddy_currents """ eddycorrect = create_eddy_correct_pipeline("eddycorrect") eddycorrect.inputs.inputnode.ref_num = 0 preprocess.connect([ (inputnode, fslroi, [('dwi', 'in_file')]), (inputnode, eddycorrect, [('dwi', 'inputnode.in_file')]), (fslroi, bet, [('roi_file', 'in_file')]), ]) return preprocess
def fsl_brain_connector(wf, cfg, strat_pool, pipe_num, opt): inputnode_bet = pe.Node(util.IdentityInterface(fields=[ 'frac', 'mask_boolean', 'mesh_boolean', 'outline', 'padding', 'radius', 'reduce_bias', 'remove_eyes', 'robust', 'skull', 'surfaces', 'threshold', 'vertical_gradient' ]), name=f'BET_options_{pipe_num}') anat_skullstrip = pe.Node(interface=fsl.BET(), name=f'anat_BET_skullstrip_{pipe_num}') anat_skullstrip.inputs.output_type = 'NIFTI_GZ' inputnode_bet.inputs.set( frac=cfg.anatomical_preproc['brain_extraction']['FSL-BET']['frac'], mask_boolean=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['mask_boolean'], mesh_boolean=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['mesh_boolean'], outline=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['outline'], padding=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['padding'], radius=cfg.anatomical_preproc['brain_extraction']['FSL-BET']['radius'], reduce_bias=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['reduce_bias'], remove_eyes=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['remove_eyes'], robust=cfg.anatomical_preproc['brain_extraction']['FSL-BET']['robust'], skull=cfg.anatomical_preproc['brain_extraction']['FSL-BET']['skull'], surfaces=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['surfaces'], threshold=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['threshold'], vertical_gradient=cfg.anatomical_preproc['brain_extraction']['FSL-BET'] ['vertical_gradient'], ) node, out = strat_pool.get_data( ['desc-preproc_T1w', 'desc-reorient_T1w', 'T1w']) wf.connect(node, out, anat_skullstrip, 'in_file') wf.connect([(inputnode_bet, anat_skullstrip, [ ('frac', 'frac'), ('mask_boolean', 'mask'), ('mesh_boolean', 'mesh'), ('outline', 'outline'), ('padding', 'padding'), ('radius', 'radius'), ('reduce_bias', 'reduce_bias'), ('remove_eyes', 'remove_eyes'), ('robust', 'robust'), ('skull', 'skull'), ('surfaces', 'surfaces'), ('threshold', 'threshold'), ('vertical_gradient', 'vertical_gradient'), ])]) outputs = {'space-T1w_desc-brain_mask': (anat_skullstrip, 'mask_file')} return (wf, outputs)
def skull_strip_dwi_files(dwi_files, out_dir, force_run = True): """ Apply BET to a list of dwi files """ skull_strip_dir = os.path.join(out_dir, 'maskDWI') logger.info("Creating skull strip directory '{}'".format(skull_strip_dir)) make_dir_safe(skull_strip_dir) skull_stripped_files = [] bet = fsl.BET() bet.inputs.frac = 0.30 bet.inputs.vertical_gradient = 0.30 bet.inputs.output_type = 'NIFTI' for i, dwi_file in enumerate(dwi_files): bet.inputs.in_file = dwi_file bet.inputs.out_file = os.path.join(skull_strip_dir, "flirt-{num:02d}-masked.nii".format(num = i+1)) skull_stripped_files.append(bet.inputs.out_file) if not os.path.isfile(bet.inputs.out_file) or force_run: bet.run() return skull_stripped_files
def headmsk_wf(name='HeadMaskWorkflow', use_bet=True): """ Computes a head mask as in [Mortamet2009]_. .. workflow:: from mriqc.workflows.anatomical import headmsk_wf wf = headmsk_wf() """ has_dipy = False try: from dipy.denoise import nlmeans # noqa has_dipy = True except ImportError: pass workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file', 'in_segm']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(fields=['out_file']), name='outputnode') if use_bet or not has_dipy: # Alternative for when dipy is not installed bet = pe.Node(fsl.BET(surfaces=True), name='fsl_bet') workflow.connect([ (inputnode, bet, [('in_file', 'in_file')]), (bet, outputnode, [('outskin_mask_file', 'out_file')]) ]) else: from nipype.interfaces.dipy import Denoise enhance = pe.Node(niu.Function( input_names=['in_file'], output_names=['out_file'], function=_enhance), name='Enhance') estsnr = pe.Node(niu.Function( input_names=['in_file', 'seg_file'], output_names=['out_snr'], function=_estimate_snr), name='EstimateSNR') denoise = pe.Node(Denoise(), name='Denoise') gradient = pe.Node(niu.Function( input_names=['in_file', 'snr'], output_names=['out_file'], function=image_gradient), name='Grad') thresh = pe.Node(niu.Function( input_names=['in_file', 'in_segm'], output_names=['out_file'], function=gradient_threshold), name='GradientThreshold') workflow.connect([ (inputnode, estsnr, [('in_file', 'in_file'), ('in_segm', 'seg_file')]), (estsnr, denoise, [('out_snr', 'snr')]), (inputnode, enhance, [('in_file', 'in_file')]), (enhance, denoise, [('out_file', 'in_file')]), (estsnr, gradient, [('out_snr', 'snr')]), (denoise, gradient, [('out_file', 'in_file')]), (inputnode, thresh, [('in_segm', 'in_segm')]), (gradient, thresh, [('out_file', 'in_file')]), (thresh, outputnode, [('out_file', 'out_file')]) ]) return workflow
def bet_brain_extract(in_file: Path, out_file: Path = None): """ Perform brain extraction using FSL's BET. Arguments: in_file {Path} -- [Path to input nifti image] Keyword Arguments: out_file {Path} -- [Path to output nifti image] (default: {None}) Returns: bet [nipype.interfaces.fsl.preprocess.BET] -- [nipype's implementation of FSL's bet] """ in_file = Path(in_file) img = nib.load(in_file) functional = img.ndim > 3 # check if input is 4D (fmri/dti) if not out_file: f_name = Path( in_file.parent / Path(in_file.stem).stem ) # clear .nii.gz and .nii out_file = Path(f"{f_name}_brain{FSLOUTTYPE}") mask_file = Path(f"{f_name}_brain_mask{FSLOUTTYPE}") else: f_name = Path(out_file.parent / Path(out_file.stem).stem) mask_file = Path(f"{f_name}_mask{FSLOUTTYPE}") # initiate fsl bet = fsl.BET() bet.inputs.in_file = in_file bet.inputs.out_file = out_file bet.inputs.mask = True bet.mask_file = mask_file if functional: bet.inputs.functional = True # perform bet on all frames else: bet.inputs.robust = True # better outcome for structural images return bet, out_file
def __init__(self, settings): # call base constructor super().__init__(settings) # define input/output node self.set_input(['refimg', 'T1_skullstrip']) self.set_output(['affine_func_2_anat', 'warp_func_2_anat']) # define datasink substitutions self.set_subs([ ('_calc_calc_calc_calc_calc', ''), ('_roi', '_reference'), ('_unwarped_Warped', '_unwarped'), ('_masked_calc', '_skullstrip'), ('_Warped', '_anat'), ]) # Skullstrip the EPI image self.epi_skullstrip = Node(fsl.BET(), name='epi_skullstrip') self.epi_automask = Node(afni.Automask(args='-overwrite', outputtype='NIFTI_GZ'), name='epi_automask') self.epi_3dcalc = Node(afni.Calc(expr='c*or(a,b)', overwrite=True, outputtype='NIFTI_GZ'), name='epi_3dcalc') # create the output name for the registration self.create_prefix = Node(Function(input_names=['filename'], output_names=['basename'], function=get_prefix), name='create_prefix') # align func to anat self.align_func_2_anat = Node(ants.Registration( num_threads=settings['num_threads'], collapse_output_transforms=False, initial_moving_transform_com=1, write_composite_transform=True, initialize_transforms_per_stage=True, transforms=['Rigid', 'Affine'], transform_parameters=[(0.1, ), (0.1, )], metric=['MI', 'MI'], metric_weight=[1, 1], radius_or_number_of_bins=[32, 32], sampling_strategy=['Regular', 'Regular'], sampling_percentage=[0.25, 0.25], convergence_threshold=[1.e-6, 1.e-8], convergence_window_size=[10, 10], smoothing_sigmas=[[3, 2, 1, 0], [2, 1, 0]], sigma_units=['vox', 'vox'], shrink_factors=[[8, 4, 2, 1], [4, 2, 1]], number_of_iterations=[[1000, 500, 250, 100], [500, 250, 100]], use_estimate_learning_rate_once=[False, True], use_histogram_matching=False, verbose=True, output_warped_image=True), name='align_func_2_anat') self.align_func_2_anat.n_procs = settings['num_threads']
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 segment_fslFAST(population, workspace_dir): count = 0 #subject = population[subject_index] for subject in population: count += 1 print '========================================================================================' print '%s- Runnning FSL FAST Segmentation on subject %s_%s' % ( count, subject[0:10], workspace_dir[-1]) print '' # define subject directory and anatomical file path subject_dir = os.path.join(workspace_dir, subject[0:4]) anatomical_dir = os.path.join(subject_dir, 'anatomical_original') anatomical_file = os.path.join(anatomical_dir, 'ANATOMICAL.nii') # check if the file exists if os.path.isfile( os.path.join( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST', 'fslFAST_seg_2.nii.gz'))): print 'Brain already segmented......... moving on' else: # define destination directory for spm segmentation outputs try: os.makedirs( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) except OSError: out_dir = str( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) out_dir = str( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) # running bet print '..... Running Brain Extraction' os.chdir(out_dir) btr = fsl.BET() btr.inputs.in_file = anatomical_file btr.inputs.frac = 0.7 btr.run() # run FSL FAST segmentation print '..... Running FSL FAST Segmentation ' os.chdir(out_dir) seg = fsl.FAST() seg.inputs.in_files = os.path.join(out_dir, 'ANATOMICAL_brain.nii.gz') seg.inputs.out_basename = 'fslFAST' seg.inputs.segments = True seg.inputs.probability_maps = True seg.run() print '========================================================================================'
def qsm_de_pipeline(self, **kwargs): # @UnusedVariable @IgnorePep8 """ Process dual echo data for QSM (TE=[7.38, 22.14]) NB: Default values come from the STI-Suite """ pipeline = self.create_pipeline( name='qsmrecon', inputs=[DatasetSpec('coils', directory_format)], # TODO should this be primary? outputs=[ DatasetSpec('qsm', nifti_gz_format), DatasetSpec('tissue_phase', nifti_gz_format), DatasetSpec('tissue_mask', nifti_gz_format), DatasetSpec('qsm_mask', nifti_gz_format) ], desc="Resolve QSM from t2star coils", citations=[sti_cites, fsl_cite, matlab_cite], version=1, **kwargs) # Prepare and reformat SWI_COILS prepare = pipeline.create_node(interface=Prepare(), name='prepare', requirements=[matlab2015_req], wall_time=30, memory=16000) # Brain Mask mask = pipeline.create_node(interface=fsl.BET(), name='bet', requirements=[fsl5_req], wall_time=30, memory=8000) mask.inputs.reduce_bias = True mask.inputs.output_type = 'NIFTI_GZ' mask.inputs.frac = 0.3 mask.inputs.mask = True # Phase and QSM for dual echo qsmrecon = pipeline.create_node(interface=STI_DE(), name='qsmrecon', requirements=[matlab2015_req], wall_time=600, memory=24000) # Connect inputs/outputs pipeline.connect_input('coils', prepare, 'in_dir') pipeline.connect_output('qsm_mask', mask, 'mask_file') pipeline.connect_output('qsm', qsmrecon, 'qsm') pipeline.connect_output('tissue_phase', qsmrecon, 'tissue_phase') pipeline.connect_output('tissue_mask', qsmrecon, 'tissue_mask') pipeline.connect(prepare, 'out_file', mask, 'in_file') pipeline.connect(mask, 'mask_file', qsmrecon, 'mask_file') pipeline.connect(prepare, 'out_dir', qsmrecon, 'in_dir') return pipeline
def create_2lvl_rand(name="group_randomize", mask=None, iters=5000): 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", "group", "regressors" ]), name='inputspec') model = pe.Node(fsl.MultipleRegressDesign(), name='l2model') wk.connect(inputspec, 'contrasts', model, "contrasts") wk.connect(inputspec, 'regressors', model, "regressors") wk.connect(inputspec, 'group', model, 'groups') mergecopes = pe.Node(fsl.Merge(dimension='t'), name='merge_copes') rand = pe.Node(fsl.Randomise(base_name='TwoSampleT', raw_stats_imgs=True, tfce=True, num_perm=iters), name='randomize') wk.connect(inputspec, 'copes', mergecopes, 'in_files') wk.connect(model, 'design_mat', rand, 'design_mat') wk.connect(model, 'design_con', rand, 'tcon') wk.connect(mergecopes, 'merged_file', rand, 'in_file') wk.connect(model, 'design_grp', rand, 'x_block_labels') if mask == None: 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', rand, 'mask') else: wk.connect(inputspec, 'template', rand, 'mask') outputspec = pe.Node(niu.IdentityInterface(fields=[ 'f_corrected_p_files', 'f_p_files', 'fstat_files', 't_corrected_p_files', 't_p_files', 'tstat_file', 'mask' ]), name='outputspec') wk.connect(rand, 'f_corrected_p_files', outputspec, 'f_corrected_p_files') wk.connect(rand, 'f_p_files', outputspec, 'f_p_files') wk.connect(rand, 'fstat_files', outputspec, 'fstat_files') wk.connect(rand, 't_corrected_p_files', outputspec, 't_corrected_p_files') wk.connect(rand, 't_p_files', outputspec, 't_p_files') wk.connect(rand, 'tstat_files', outputspec, 'tstat_file') if mask == None: wk.connect(bet, 'mask_file', outputspec, 'mask') else: wk.connect(inputspec, 'template', outputspec, 'mask') return wk
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 create_bbregister_workflow(name="bbregister", contrast_type="t2", partial_brain=False, init_with="fsl"): """Find a linear transformation to align the EPI file with the anatomy.""" in_fields = ["subject_id", "timeseries"] if partial_brain: in_fields.append("whole_brain_template") inputnode = Node(IdentityInterface(in_fields), "inputs") # Take the mean over time to get a target volume meanvol = MapNode(fsl.MeanImage(), "in_file", "meanvol") # Do a rough skullstrip using BET skullstrip = MapNode(fsl.BET(), "in_file", "bet") # Estimate the registration to Freesurfer conformed space func2anat = MapNode( fs.BBRegister(contrast_type=contrast_type, init=init_with, epi_mask=True, registered_file=True, out_reg_file="func2anat_tkreg.dat", out_fsl_file="func2anat_flirt.mat"), "source_file", "func2anat") # Make an image for quality control on the registration report = MapNode(CoregReport(), "in_file", "coreg_report") # Define the workflow outputs outputnode = Node(IdentityInterface(["tkreg_mat", "flirt_mat", "report"]), "outputs") bbregister = Workflow(name=name) # Connect the registration bbregister.connect([ (inputnode, func2anat, [("subject_id", "subject_id")]), (inputnode, report, [("subject_id", "subject_id")]), (inputnode, meanvol, [("timeseries", "in_file")]), (meanvol, skullstrip, [("out_file", "in_file")]), (skullstrip, func2anat, [("out_file", "source_file")]), (func2anat, report, [("registered_file", "in_file")]), (func2anat, outputnode, [("out_reg_file", "tkreg_mat")]), (func2anat, outputnode, [("out_fsl_file", "flirt_mat")]), (report, outputnode, [("out_file", "report")]), ]) # Possibly connect the full_fov image if partial_brain: bbregister.connect([ (inputnode, func2anat, [("whole_brain_template", "intermediate_file")]), ]) return bbregister