def create_mni2diff_transforms(bedpostx_dir): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe ####Custom inputs#### try: FSLDIR = os.environ['FSLDIR'] except NameError: print('FSLDIR environment variable not set!') merged_f_samples_path = bedpostx_dir + '/merged_f1samples.nii.gz' ####Custom inputs#### print('\nCreating MNI-diffusion space transforms...\n') input_MNI = FSLDIR + '/data/standard/MNI152_T1_1mm_brain.nii.gz' out_aff = bedpostx_dir + '/xfms/MNI2diff_affine.nii.gz' ##Create transform matrix between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = merged_f_samples_path flirt.inputs.in_file = input_MNI flirt.inputs.out_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.inputs.out_file = '/tmp/out_flirt.nii.gz' flirt.run() ##Apply transform between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = merged_f_samples_path flirt.inputs.in_file = input_MNI flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.inputs.out_file = out_aff flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.run() return out_aff
def _apply_coregistration(item, reference_item, input_dir, tmp_dir, output_dir): """Coregisters all items to the reference item. The reference item is skipped in the list of items. Args: item (str): the items base_name to register to the reference item reference_item (str): the name of the reference item in the items list input_dir (str): the input directory in which the items reside tmp_dir (str): the working dir. Outputs reference volume and reference matrix """ reference_mean_b0 = os.path.join(tmp_dir, reference_item + '_mask.nii.gz') reference_dwi = os.path.join(input_dir, reference_item + '.nii.gz') input_mean_b0 = os.path.join(tmp_dir, item + '_mask.nii.gz') input_dwi = os.path.join(input_dir, item + '.nii.gz') out_b0_vol = os.path.join(tmp_dir, item + '_to_' + reference_item + '_mean_b0.nii.gz') out_img = os.path.join(output_dir, item + '.nii.gz') out_mat = os.path.join(tmp_dir, item + '_to_' + reference_item + '_mean_b0.mat') flirt_b0 = pe.Node(fsl.FLIRT(in_file=input_mean_b0, reference=reference_mean_b0, out_file=out_b0_vol, out_matrix_file=out_mat, dof=6), name='flirt_b0') flirt_b0.run() flirt_apply = pe.Node(fsl.FLIRT(in_file=input_dwi, reference=reference_dwi, out_file=out_img, in_matrix_file=out_mat, apply_xfm=True), name='flirt') flirt_apply.run()
def epi_normalize(name='epi_normalize'): inputnode = pe.Node( utility.IdentityInterface( fields=['fmri_mean','t1','t1_to_mni','t1_mask']), name='inputspec') outputnode = pe.Node( utility.IdentityInterface( fields=['epi2t1_warp','coregistered_fmri_mean','epi2mni_warp', 't1_to_epi_warp','epi_mask']), name='outputspec') n_spm_coregister = pe.Node( spm.Coregister(jobtype='estimate'), name='spm_coregister') # n_epi2mni = pe.Node( # spm.preprocess.ApplyDeformations( # reference_volume='/coconut/applis/src/spm8_x64/toolbox/Seg/TPM.nii'), # name='epi2mni') n_flirt_epi2t1 = pe.Node( fsl.FLIRT(out_matrix_file='flirt_epi2t1.mat', out_file='%s_flirt', cost='normmi', # as in fcon1000 preproc, why?? searchr_x=[-10,10],searchr_y=[-10,10],searchr_z=[-10,10], dof=6), name='flirt_epi2t1') n_t1_to_epi = pe.Node( fsl.ConvertXFM(invert_xfm=True), name='t1_to_epi') n_mask_to_epi = pe.Node( fsl.FLIRT(interp='nearestneighbour', out_file='%s_epi', apply_xfm=True,), name='mask_to_epi') w=pe.Workflow(name=name) w.connect([ # (inputnode,n_spm_coregister,[('fmri_mean','source'), # ('t1','target')]), (inputnode,n_flirt_epi2t1,[('t1','reference')]), # (n_spm_coregister,n_epi2mni,[('coregistered_source','in_files')]), # (inputnode,n_epi2mni,[('t1_to_mni','deformation_field')]), (inputnode,n_flirt_epi2t1,[('fmri_mean','in_file')]), (n_flirt_epi2t1,outputnode,[('out_matrix_file','epi2t1_warp')]), (n_flirt_epi2t1,n_t1_to_epi,[('out_matrix_file','in_file')]), (n_t1_to_epi,outputnode,[('out_file','t1_to_epi_warp')]), (inputnode,n_mask_to_epi,[('fmri_mean','reference'), ('t1_mask','in_file')]), (n_t1_to_epi, n_mask_to_epi,[('out_file','in_matrix_file')]), (n_mask_to_epi, outputnode, [('out_file','epi_mask')]) # (n_spm_coregister,outputnode,[('coregistered_source', # 'coregistered_fmri_mean')]), ]) return w
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 quick_transform(c): import nipype.pipeline.engine as pe import nipype.interfaces.io as nio import nipype.interfaces.fsl as fsl wf = pe.Workflow(name='flirt_transform') sink = pe.Node(nio.DataSink(),name='sinker') sink.inputs.base_directory = c.sink_dir if c.create_transform: datagrabber = c.datagrabber_create.create_dataflow() infosource = datagrabber.get_node('subject_id_iterable') xform = pe.MapNode(fsl.FLIRT(interp=c.interpolation),name='flirt',iterfield=['in_file']) wf.connect(xform,'out_matrix_file',sink,'%s.@outmatfile'%c.name) elif c.apply_transform: datagrabber = c.datagrabber_apply.create_dataflow() infosource = datagrabber.get_node('subject_id_iterable') xform = pe.MapNode(fsl.FLIRT(interp=c.interpolation,apply_xfm=True),name='flirt',iterfield=['in_file']) wf.connect(datagrabber,'datagrabber.reg_mat',xform,'in_matrix_file') else: raise Exception("Need to either create or apply a flirt transform!!") wf.connect(datagrabber,'datagrabber.inputs',xform,'in_file') wf.connect(datagrabber,'datagrabber.template',xform,'reference') wf.connect(infosource,'subject_id',sink,'container') wf.connect(xform,'out_file',sink,'%s.@outfile'%c.name) subs = lambda sub_id: [('_subject_id_%s'%sub_id,'')]+[('_flirt%d'%i,'') for i in range(20)] wf.connect(infosource,('subject_id', subs),sink,'substitutions') return wf
def mni2bold(bold, anat, standard, mask, workdir): """ Use fsl.FLIRT to transform a mask from MNI to subject space """ os.makedirs(workdir) # bold to anat bold2anat = fsl.FLIRT(dof=6, no_clamp=True, in_file=bold, reference=anat, out_matrix_file=join(workdir, 'bold2anat.txt'), out_file=join(workdir, 'bold2anat.nii.gz')) bold2anat.run() # anat to mni anat2mni = fsl.FLIRT(dof=12, in_file=anat, reference=standard, out_matrix_file=join(workdir, 'anat2mni.txt'), out_file=join(workdir, sub, run, '%s_%s_anat2mni.nii.gz' % (sub, run))) anat2mni.run() # concatinate matrices concat = ConvertXFM(concat_xfm=True, in_file2=join(workdir, sub, run, '%s_%s_bold2anat.txt' % (sub, run)), in_file=join(workdir, sub, run, '%s_%s_anat2mni.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run))) concat.run() # inverse transmatrix inverse = ConvertXFM(in_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)), invert_xfm=True) inverse.run() # apply to mask mni2bold = fsl.FLIRT( interp='nearestneighbour', apply_xfm=True, in_matrix_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)), in_file=join(mask), reference=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'), out_file=join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run))) mni2bold.run() mask_subjspace = join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run)) # return path of created mask return mask_subjspace
def mask2subjspace(sub, run, data_basedir, workdir, mask): """ Use fsl.FLIRT to transform roi mask from MNI to subject space (without brain extraction). """ from nipype.interfaces import fsl from nipype.interfaces.fsl.utils import ConvertXFM from os.path import join import os os.makedirs(join(workdir, sub, run)) # bold to anat bold2anat = fsl.FLIRT( dof=6, no_clamp=True, in_file=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'), reference=join(data_basedir, sub, 'anatomy', 'highres001.nii.gz'), out_matrix_file=join(workdir, sub, run, '%s_%s_bold2anat.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_bold2anat.nii.gz' % (sub, run))) bold2anat.run() # anat to mni anat2mni = fsl.FLIRT( dof=12, interp='nearestneighbour', in_file=join(data_basedir, sub, 'anatomy', 'highres001.nii.gz'), reference='/usr/share/fsl/5.0//data/standard/MNI152_T1_2mm_brain.nii.gz', out_matrix_file=join(workdir, sub, run, '%s_%s_anat2mni.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_anat2mni.nii.gz' % (sub, run))) anat2mni.run() # concatinate matrices concat = ConvertXFM( concat_xfm=True, in_file2=join(workdir, sub, run, '%s_%s_bold2anat.txt' % (sub, run)), in_file=join(workdir, sub, run, '%s_%s_anat2mni.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run))) concat.run() # inverse transmatrix inverse = ConvertXFM( in_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run)), out_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)), invert_xfm=True) inverse.run() # apply to mask mni2bold = fsl.FLIRT( interp='nearestneighbour', apply_xfm=True, in_matrix_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)), in_file=join(mask), reference=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'), out_file=join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run))) mni2bold.run() mask_subjspace = join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run)) # return path of created mask return mask_subjspace
def epi_unwrap(name='epi_unwrap'): inputnode = pe.Node( utility.IdentityInterface( fields=['fieldmap', 'fieldmap_mask', 'fieldmap_to_epi', 'epi_file','epi_reference', 'echo_time','echo_spacing','unwarp_direction']), name='inputspec') outputnode = pe.Node( utility.IdentityInterface( fields=['unwarped_epi','voxel_shift_map']), name='outputspec') n_fieldmap_to_epi = pe.Node( fsl.FLIRT(apply_xfm=True, no_resample_blur=True), name='fieldmap_to_epi') n_mask_to_epi = pe.Node( fsl.FLIRT(apply_xfm=True, interp='nearestneighbour'), name='mask_to_epi') n_epi_voxelshiftmap = pe.Node( fsl.FUGUE(shift_out_file='vsm_epi.nii.gz',), name='epi_voxelshiftmap') n_unwarp_epi = pe.Node( fsl.FUGUE(), name='unwarp_epi') w=pe.Workflow(name=name) w.connect([ (inputnode, n_fieldmap_to_epi, [ ('fieldmap_to_epi','in_matrix_file'), ('fieldmap','in_file'), ('epi_reference','reference'),]), (inputnode, n_mask_to_epi, [ ('fieldmap_to_epi','in_matrix_file'), ('fieldmap_mask','in_file'), ('epi_reference','reference'),]), (n_fieldmap_to_epi,n_epi_voxelshiftmap,[('out_file','fmap_in_file')]), (n_mask_to_epi, n_epi_voxelshiftmap, [('out_file','mask_file')]), (inputnode, n_epi_voxelshiftmap,[ ('epi_reference','in_file'), ('unwarp_direction','unwarp_direction'), ('echo_spacing','dwell_time')]), (n_mask_to_epi, n_unwarp_epi, [('out_file','mask_file')]), (n_epi_voxelshiftmap,n_unwarp_epi,[('shift_out_file','shift_in_file')]), (inputnode,n_unwarp_epi,[ ('epi_file','in_file'),]), ]) return w
def linear_registration_( self ): """Linear registration. First part in the study template creation. Estimation of the registration parameters of GM to grey matter standard template.""" try: # # # # Retrieve the GM tissue prior avg152T1_gray = "" if os.environ.get('FSLDIR'): avg152T1_gray = os.path.join( os.environ.get('FSLDIR'), "data","standard","tissuepriors", "avg152T1_gray.hdr" ) else: raise Exception( "$FSLDIR env variable is not setup on your system" ) # # Loop on the tasks while True: # get the item item = self.queue_[0].get() # registration estimation flt = fsl.FLIRT() flt.inputs.in_file = os.path.join( self.maps_dir_, item ) flt.inputs.reference = avg152T1_gray flt.inputs.out_file = os.path.join( self.template_dir_, "%s_li_MNI.nii.gz"%item[:-7] ) flt.inputs.out_matrix_file = os.path.join( self.template_dir_, "%s_li_MNI.mat"%item[:-7] ) flt.inputs.dof = 12 res = flt.run() # apply registration flt = fsl.FLIRT() flt.inputs.in_file = os.path.join( self.maps_dir_, item ) flt.inputs.reference = avg152T1_gray flt.inputs.out_file = os.path.join( self.template_dir_, "%s_li_MNI.nii.gz"%item[:-7] ) flt.inputs.in_matrix_file = os.path.join( self.template_dir_, "%s_li_MNI.mat"%item[:-7] ) flt.inputs.out_matrix_file = os.path.join( self.template_dir_, "%s_li_MNI_apply.mat"%item[:-7] ) flt.inputs.apply_xfm = True flt.inputs.dof = 12 res = flt.run() # lock and add the file singlelock.acquire() self.linear_MNI_.append( flt.inputs.out_file ) singlelock.release() # job is done self.queue_[0].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 flirt_registration(self, keepfiles=False): """ """ def _ssos(data): """Squared sum of squares from multichannel complex data""" ssos = np.sqrt(np.mean(np.absolute(data), axis=self.rcvrdim)) return ssos # make workdir if does not exist if not os.path.exists(self.workdir): os.makedirs(self.workdir) # make 6d nifti data for flirt affine transform img_6d = vj.util.make_6d(self.imgspace) # making niftis img_out = self.workdir + '/composer_img_main' ref_out = self.workdir + '/composer_ref_main' flirt_out = self.workdir + '/composer_flirtout' full = self.workdir + '/composer_6d_img' writer = vj.io.NiftiWriter(_ssos(self.imgspace), self.procpar,\ input_space='local',\ output_space='scanner') writer.write(img_out) writer = vj.io.NiftiWriter(_ssos(self.imgspace_ref), self.procpar_ref,\ input_space='local',\ output_space='scanner') writer.write(ref_out) writer = vj.io.NiftiWriter(img_6d, self.procpar_ref,\ input_space='local',\ output_space='scanner') writer.write(full) # registering by combined magnitude FSL FLIRT flirt = fsl.FLIRT() flirt.inputs.in_file = img_out + '.nii.gz' flirt.inputs.reference = ref_out + '.nii.gz' flirt.inputs.out_file = flirt_out + '.nii.gz' flirt.inputs.out_matrix_file = 'composer_invol2refvolmat' print(flirt.cmdline) res = flirt.run() # applying the resulting transform to full data flirt = fsl.FLIRT() flirt.inputs.in_file = img_out + '.nii.gz' flirt.inputs.reference = ref_out + '.nii.gz' flirt.inputs.out_file = flirt_out + '.nii.gz' flirt.inputs.out_matrix_file = 'composer_invol2refvolmat' print(flirt.cmdline) vj.io.NiftiReader(flirt_out + '.nii.gz') # loading result nifti rdr = vj.io.NiftiReader(flirt_out + '.nii.gz')
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 mask2pe( pe, anat, mnimask, workdir, standard='/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz' ): """ Compute new 2-step projection for a masn from mni to 3D parameter space (and apply it). """ # create transformation matrix from mni to anatomical mni2anat = fsl.FLIRT(dof=12, interp='trilinear', in_file=standard, reference=anat, out_file=join(workdir, 'mni2anat.nii.gz'), out_matrix_file=join(workdir, 'mni2anat.txt')) mni2anat.run() # anat to parameter estimate map (3D statistical volume) anat2pe = fsl.FLIRT(dof=6, interp='trilinear', in_file=anat, reference=pe, out_file=join(workdir, 'anat2pe.nii.gz'), out_matrix_file=join(workdir, 'anat2pe.txt')) anat2pe.run() # concatinate matrices concat = ConvertXFM(concat_xfm=True, in_file2=join(workdir, 'mni2anat.txt'), in_file=join(workdir, 'anat2pe.txt'), out_file=join(workdir, 'mni2pe.txt')) concat.run() # set path to output file outfile = join(workdir, 'mask2pe.nii.gz') # apply transformation to mask image mni2pe = fsl.FLIRT(interp='nearestneighbour', apply_xfm=True, in_matrix_file=join(workdir, 'mni2pe.txt'), out_matrix_file=join(workdir, 'mask2pe.txt'), in_file=mnimask, reference=pe, out_file=outfile) mni2pe.run() # return path to transformed result return outfile
def init_fsl(self, in_file: str, ref: str, out_file: str, out_mat: str): ax = fsl.FLIRT() ax.inputs.in_file = in_file ax.inputs.reference = ref ax.inputs.out_file = out_file ax.inputs.out_matrix_file = out_mat return ax
def create_workflow(): workflow = Workflow( name='transform_manual_mask') inputs = Node(IdentityInterface(fields=[ 'subject_id', 'session_id', 'refsubject_id', 'ref_funcmask', 'ref_func', 'funcs', ]), name='in') # Find the transformation matrix func_ref -> func # First find transform from func to manualmask's ref func # first take the median (flirt functionality has changed and no longer automatically takes the first volume when given 4D files) median_func = MapNode( interface=fsl.maths.MedianImage(dimension="T"), name='median_func', iterfield=('in_file'), ) findtrans = MapNode(fsl.FLIRT(), iterfield=['in_file'], name='findtrans' ) # Invert the matrix transform invert = MapNode(fsl.ConvertXFM(invert_xfm=True), name='invert', iterfield=['in_file'], ) workflow.connect(findtrans, 'out_matrix_file', invert, 'in_file') # Transform the manualmask to be aligned with func funcreg = MapNode(ApplyXFMRefName(), name='funcreg', iterfield=['in_matrix_file', 'reference'], ) workflow.connect(inputs, 'funcs', median_func, 'in_file') workflow.connect(median_func, 'out_file', findtrans, 'in_file') workflow.connect(inputs, 'ref_func', findtrans, 'reference') workflow.connect(invert, 'out_file', funcreg, 'in_matrix_file') workflow.connect(inputs, 'ref_func', funcreg, 'in_file') workflow.connect(inputs, 'funcs', funcreg, 'reference') return workflow
def reg_parcels2diff(dwi_dir, seeds_dir): import re import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe 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') seeds_list = [i for i in os.listdir(seeds_dir) if '.nii' in i] def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [atoi(c) for c in re.split('(\d+)', text)] seeds_list.sort(key=natural_keys) i = 0 for parcel in seeds_list: out_file = "%s%s%s%s" % (seeds_dir, '/region_', str(i), '_diff.nii.gz') flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = dwi_infile flirt.inputs.in_file = "%s%s%s" % (seeds_dir, '/', parcel) flirt.inputs.out_file = out_file flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = "%s%s" % (dwi_dir, '/xfms/MNI2diff.mat') flirt.run() i = i + 1 seeds_list = [i for i in os.listdir(seeds_dir) if 'diff.nii' in i] return seeds_list
def autorotate( template, in_file='structural.nii', ): """Multi-rotation-state transformation start. This allows the registration to commence with the best rotational fit, and may help if the orientation of the data is malformed with respect to the header. Parameters ---------- template : string Full path to template data. in_file : string Name of input NIfTI file with data which is to be transformed. Returns ------- flt_res : Path names of output_file, out_log, and out_matrix_file (affine transformation). """ flt = fsl.FLIRT(bins=640, cost_func='mutualinfo') flt.inputs.in_file = in_file flt.inputs.reference = template flt.inputs.output_type = "NIFTI_GZ" flt.inputs.dof = 6 flt.input.searchr_x = [-180, 180] flt.input.searchr_y = [-180, 180] flt.input.searchr_z = [-180, 180] flt.input.force_scaling = True flt.cmdline flt_res = flt.run() return flt_res
def epi_sbref_registration(name='EPI_SBrefRegistration'): workflow = pe.Workflow(name=name) inputnode = pe.Node( niu.IdentityInterface(fields=['epi_brain', 'sbref_brain']), name='inputnode') outputnode = pe.Node( niu.IdentityInterface(fields=['epi_registered', 'out_mat']), name='outputnode') mean = pe.Node(fsl.MeanImage(dimension='T'), name='EPImean') inu = pe.Node(ants.N4BiasFieldCorrection(dimension=3), name='EPImeanBias') epi_sbref = pe.Node(fsl.FLIRT(dof=6, out_matrix_file='init.mat'), name='EPI2SBRefRegistration') epi_split = pe.Node(fsl.Split(dimension='t'), name='EPIsplit') epi_xfm = pe.MapNode(fsl.ApplyXfm(), name='EPIapplyxfm', iterfield=['in_file']) epi_merge = pe.Node(fsl.Merge(dimension='t'), name='EPImergeback') workflow.connect([ (inputnode, epi_split, [('epi_brain', 'in_file')]), (inputnode, epi_sbref, [('sbref_brain', 'reference')]), (inputnode, epi_xfm, [('sbref_brain', 'reference')]), (inputnode, mean, [('epi_brain', 'in_file')]), (mean, inu, [('out_file', 'input_image')]), (inu, epi_sbref, [('output_image', 'in_file')]), (epi_split, epi_xfm, [('out_files', 'in_file')]), (epi_sbref, epi_xfm, [('out_matrix_file', 'in_matrix_file')]), (epi_xfm, epi_merge, [('out_file', 'in_files')]), (epi_sbref, outputnode, [('out_matrix_file', 'out_mat')]), (epi_merge, outputnode, [('merged_file', 'epi_registered')]) ]) return workflow
def apply_xfm_node(config: dict, **kwargs): ''' Parses config file to return desired apply_xfm node. Parameters ---------- config : dict PALS config file kwargs Keyword arguments to send to registration method. Returns ------- MapNode ''' if (not config['Analysis']['Registration']): # No registration; no xfm to apply. n = MapNode(Function(function=infile_to_outfile, input_names=['in_file', 'in_matrix_file'], output_names='out_file'), name='transformation_skip', iterfield=['in_file', 'in_matrix_file']) else: n = MapNode(fsl.FLIRT(apply_xfm=True, reference=config['Registration']['reference']), name='transformation_flirt', iterfield=['in_file', 'in_matrix_file']) return n
def registration_node(config: dict, **kwargs): ''' Parses config file to return desired registration method. Parameters ---------- config : dict PALS config file kwargs Keyword arguments to send to registration method. Returns ------- MapNode ''' # Get registration method reg_method = config['Analysis']['RegistrationMethod'] if (not config['Analysis']['Registration']): # No registration; in -> out n = MapNode(Function(function=reg_no_reg, input_names=['in_file'], output_names=['out_file', 'out_matrix_file']), name='registration_identity', iterfield='in_file') elif (reg_method.lower() == 'flirt'): # Use FLIRT n = MapNode(fsl.FLIRT(), name='registration_flirt', iterfield='in_file') for k, v in kwargs.items(): setattr(n.inputs, k, v) else: raise (NotImplementedError( f'Registration method {reg_method} not implemented.')) return n
def registration(in_file, out_file, reference): fsl.FSLCommand.set_default_output_type('NIFTI') flt = fsl.FLIRT(bins=640, cost_func='mutualinfo') flt.inputs.in_file = in_file flt.inputs.out_file = out_file flt.inputs.reference = reference result = flt.run()
def fsl_realign_opt(name='fsl_realign_opt'): inputnode = pe.Node( utility.IdentityInterface( fields=['fmri','reference','mask']), name='inputspec') n_flirt_epi2t1 = pe.Node( fsl.FLIRT(out_matrix_file='flirt_epi2t1.mat', cost='normmi', # as in fcon1000 preproc, why?? searchr_x=[-10,10],searchr_y=[-10,10],searchr_z=[-10,10], dof=6), name='flirt_epi2t1') n_mcflirt_spline = pe.Node( fsl.MCFLIRT(interpolation='spline', ref_vol=0, save_plots=True, save_rms=True, save_mats=True, stats_imgs=True, dof=6), name='mcflirt_spline') w=pe.Workflow(name=name) w.connect([ (inputnode,n_flirt_epi2t1,[('fmri','in_file'), ('reference','reference')]), (inputnode,n_mcflirt_spline,[('fmri','in_file'),]), (n_flirt_epi2t1,n_mcflirt_spline,[('out_matrix_file','init')]) ]) return w
def func2mni_wf(): mni_skull_2mm = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm.nii.gz' mni_brain_2mm = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz' flow = Workflow('func2mni_nonlinear') inputnode = Node(util.IdentityInterface(fields=['func_image', 'reference_image', 'func2anat_affine', 'anat2mni_warp']),name = 'inputnode') outputnode = Node(util.IdentityInterface(fields=['func2mni_2mm', 'func2mni_4mm']),name = 'outputnode') applywarp = Node(fsl.ApplyWarp(), name = 'apply_warp',) applywarp.inputs.ref_file = mni_brain_2mm flirt4mm = Node(fsl.FLIRT(), name = 'resample_4mm') flirt4mm.inputs.reference = mni_brain_2mm flirt4mm.inputs.apply_isoxfm = 4.0 flow.connect(inputnode, 'func_image' , applywarp, 'in_file') flow.connect(inputnode, 'anat2mni_warp' , applywarp, 'field_file') flow.connect(inputnode, 'func2anat_affine' , applywarp, 'premat') flow.connect(applywarp, 'out_file' , flirt4mm, 'in_file') flow.connect(applywarp, 'out_file' , outputnode, 'func2mni_2mm') flow.connect(flirt4mm, 'out_file' , outputnode, 'func2mni_4mm') return flow
def register_dwi_files_to_super_b0(dwi_files, super_b0 , out_dir, force_run = True): """ Register list of dwi files to super b0 (both paths) """ processed_files = [] registered_dir = os.path.join(out_dir, 'registered_dwi_files') logger.info("Creaging dwi directory {}".format(registered_dir)) make_dir_safe(registered_dir) flirt = fsl.FLIRT() flirt.inputs.reference = super_b0 flirt.inputs.interp = 'sinc' flirt.inputs.sinc_width = 7 flirt.inputs.sinc_window = 'blackman' flirt.inputs.no_search = False flirt.inputs.verbose = 1 flirt.inputs.padding_size = 1 flirt.inputs.output_type = 'NIFTI' for i, dwi_file in enumerate(dwi_files): flirt.inputs.in_file = dwi_file flirt.inputs.out_file = os.path.join(registered_dir, "flirt-{num:02d}.nii".format(num = i+1)) processed_files.append(flirt.inputs.out_file) flirt.inputs.out_matrix_file = os.path.join(registered_dir, "flirt-{num:02d}.txt".format(num = i+1)) if not os.path.isfile(flirt.inputs.out_matrix_file) or force_run: flirt.run() return processed_files
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 linear_registration( in_file: Path, ref: Path, out_file: Path, out_mat: Path = None, coregister: bool = False, ): """ Wrap inputs into FSL's FLIRT interface for linear registraions. Parameters ---------- in_file : Path Path to "moving" file ref : Path Path to reference file out_file : Path Path to output registered file coregister : bool, optional Indicating whether it's a within-subject registration, by default False """ if not out_mat: in_name = in_file.name.split(".")[0] ref_name = ref.name.split(".")[0] out_mat = out_file.parent / f"{in_name}-{ref_name}_affine.mat" flt = fsl.FLIRT() flt.inputs.in_file = in_file flt.inputs.reference = ref flt.inputs.out_file = out_file if coregister: flt.inputs.cost = "mutualinfo" flt.inputs.out_matrix_file = out_mat return flt
def FLIRT(self, in_file: str, ref: str, out_dir: str, type: int): """ FLIRT linear transformation @param in_file: image to be transformed @param ref: image to transform into @param out_dir: directory for outputs @param type: 0 for highres2lowres, 1 for atlasHighres2highres, 2 for atlasLabels2highres @return: """ flt = fsl.FLIRT() flt.inputs.in_file = in_file flt.inputs.reference = ref flt.inputs.bins = 256 flt.inputs.cost = "corratio" flt.inputs.searchr_x = [-90, 90] flt.inputs.searchr_y = [-90, 90] flt.inputs.searchr_z = [-90, 90] flt.inputs.dof = 12 flt.inputs.interp = "trilinear" if type == 0: flt.inputs.out_file = f"{out_dir}/Highres2Lowres_linear.nii" flt.inputs.out_matrix_file = f"{out_dir}/Highres2Lowres_linear.mat" print("Running linear transformation from Highres to Lowres:") elif type == 1: flt.inputs.out_file = f"{out_dir}/HighresAtlas2Highres_linear.nii" flt.inputs.out_matrix_file = f"{out_dir}/HighresAtlas2Highres_linear.mat" print("Running linear transformation from Atlas to Highres:") elif type == 2: flt.inputs.out_file = f"{out_dir}/LabelsAtlas2Highres_linear.nii" flt.inputs.out_matrix_file = f"{out_dir}/LabelsAtlas2Highres_linear.mat" print("Running linear transformation from Atlas to Highres:") flt.inputs.output_type = "NIFTI" print(flt.cmdline) flt.run() return flt.inputs.out_matrix_file
def reg_parcels2diff(bedpostx_dir): import re import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe merged_f_samples_path = bedpostx_dir + '/merged_f1samples.nii.gz' volumes_dir = bedpostx_dir + '/volumes' volumes_list = [i for i in os.listdir(volumes_dir) if '.nii' in i] def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [atoi(c) for c in re.split('(\d+)', text)] volumes_list.sort(key=natural_keys) i = 0 for parcel in volumes_list: out_file = volumes_dir + '/region_' + str(i) + '_diff.nii.gz' flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = merged_f_samples_path flirt.inputs.in_file = volumes_dir + '/' + parcel flirt.inputs.out_file = out_file flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.run() i = i + 1 volumes_list = [i for i in os.listdir(volumes_dir) if 'diff.nii' in i] return volumes_list
def create_eddy_correct_pipeline(name='eddy_correct'): """ .. deprecated:: 0.9.3 Use :func:`nipype.workflows.dmri.preprocess.epi.ecc_pipeline` instead. Creates a pipeline that replaces eddy_correct script in FSL. It takes a series of diffusion weighted images and linearly co-registers them to one reference image. No rotation of the B-matrix is performed, so this pipeline should be executed after the motion correction pipeline. Example ------- >>> nipype_eddycorrect = create_eddy_correct_pipeline('nipype_eddycorrect') >>> nipype_eddycorrect.inputs.inputnode.in_file = 'diffusion.nii' >>> nipype_eddycorrect.inputs.inputnode.ref_num = 0 >>> nipype_eddycorrect.run() # doctest: +SKIP Inputs:: inputnode.in_file inputnode.ref_num Outputs:: outputnode.eddy_corrected """ warnings.warn( ('This workflow is deprecated from v.1.0.0, use ' 'nipype.workflows.dmri.preprocess.epi.ecc_pipeline instead'), DeprecationWarning) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file', 'ref_num']), name='inputnode') pipeline = pe.Workflow(name=name) split = pe.Node(fsl.Split(dimension='t'), name='split') pick_ref = pe.Node(niu.Select(), name='pick_ref') coregistration = pe.MapNode(fsl.FLIRT(no_search=True, padding_size=1, interp='trilinear'), name='coregistration', iterfield=['in_file']) merge = pe.Node(fsl.Merge(dimension='t'), name='merge') outputnode = pe.Node(niu.IdentityInterface(fields=['eddy_corrected']), name='outputnode') pipeline.connect([(inputnode, split, [('in_file', 'in_file')]), (split, pick_ref, [('out_files', 'inlist')]), (inputnode, pick_ref, [('ref_num', 'index')]), (split, coregistration, [('out_files', 'in_file')]), (pick_ref, coregistration, [('out', 'reference')]), (coregistration, merge, [('out_file', 'in_files')]), (merge, outputnode, [('merged_file', 'eddy_corrected')]) ]) return pipeline
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 test_nonlinear_register(): from ..registration import create_nonlinear_register from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.interfaces.fsl as fsl ## necessary inputs ## -input_brain ## -input_skull ## -reference_brain ## -reference_skull ## -fnirt_config ## -fnirt_warp_res ## input_brain anat_bet_file = '/home/data/Projects/nuisance_reliability_paper/working_dir_CPAC_order/resting_preproc/anatpreproc/_session_id_NYU_TRT_session1_subject_id_sub05676/anat_skullstrip/mprage_anonymized_RPI_3dT.nii.gz' ## input_skull ## reference_brain mni_file = '/usr/share/fsl/4.1/data/standard/MNI152_T1_3mm_brain.nii.gz' ## reference_skull ## fnirt_config fnirt_config = 'T1_2_MNI152_3mm' ## fnirt_warp_res fnirt_warp_res = None #?? what is this for?: func_file = '/home/data/Projects/nuisance_reliability_paper/working_dir_CPAC_order/resting_preproc/nuisance_preproc/_session_id_NYU_TRT_session1_subject_id_sub05676/_csf_threshold_0.4/_gm_threshold_0.2/_wm_threshold_0.66/_run_scrubbing_False/_nc_5/_selector_6.7/regress_nuisance/mapflow/_regress_nuisance0/residual.nii.gz' mni_workflow = pe.Workflow(name='mni_workflow') linear_reg = pe.Node(interface=fsl.FLIRT(), name='linear_reg_0') linear_reg.inputs.cost = 'corratio' linear_reg.inputs.dof = 6 linear_reg.inputs.interp = 'nearestneighbour' linear_reg.inputs.in_file = func_file linear_reg.inputs.reference = anat_bet_file #T1 to MNI Node c = create_nonlinear_register() c.inputs.inputspec.input = anat_bet_file c.inputs.inputspec.reference = '/usr/share/fsl/4.1/data/standard/MNI152_T1_3mm_brain.nii.gz' c.inputs.inputspec.fnirt_config = 'T1_2_MNI152_3mm' #EPI to MNI warp Node mni_warp = pe.Node(interface=fsl.ApplyWarp(), name='mni_warp') mni_warp.inputs.ref_file = '/usr/share/fsl/4.1/data/standard/MNI152_T1_3mm_brain.nii.gz' mni_warp.inputs.in_file = func_file mni_workflow.connect(c, 'outputspec.nonlinear_xfm', mni_warp, 'field_file') mni_workflow.connect(linear_reg, 'out_matrix_file', mni_warp, 'premat') mni_workflow.base_dir = './' mni_workflow.run()