def afni_unifize(in_file, write_dir=None, out_file=None, caching=False, terminal_output='allatonce', verbose=True, environ=None, copy_geometry=False, **unifize_kwargs): if write_dir is None: write_dir = os.path.dirname(in_file) if environ is None: environ = {'AFNI_DECONFLICT': 'OVERWRITE'} if caching: memory = Memory(write_dir) copy_geom = memory.cache(fsl.CopyGeom) unifize = memory.cache(afni.Unifize) copy = memory.cache(afni.Copy) unifize.interface().set_default_terminal_output(terminal_output) copy.interface().set_default_terminal_output(terminal_output) else: copy_geom = fsl.CopyGeom(terminal_output=terminal_output).run unifize = afni.Unifize(terminal_output=terminal_output).run copy = afni.Copy(terminal_output=terminal_output).run if out_file is None: out_file = fname_presuffix(in_file, suffix='_unifized', newpath=write_dir) if copy_geometry: unifized_file = fname_presuffix(in_file, suffix='_unifized_rough_geom', newpath=write_dir) else: unifized_file = out_file out_unifize = unifize(in_file=in_file, out_file=unifized_file, environ=environ, quiet=not (verbose), **unifize_kwargs) if copy_geometry: out_copy = copy(in_file=out_unifize.outputs.out_file, out_file=out_file, environ=environ) out_copy_geom = copy_geom(dest_file=out_copy.outputs.out_file, in_file=in_file) return out_file
def test_copy(): input_map = dict( args=dict(argstr='%s', ), environ=dict(usedefault=True, ), ignore_exception=dict(usedefault=True, ), in_file=dict( argstr='%s', mandatory=True, ), out_file=dict(argstr='%s', ), outputtype=dict(), ) instance = afni.Copy() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(instance.inputs.traits()[key], metakey), value
def ants_n4(in_file, write_dir=None, caching=False, terminal_output='allatonce', environ=None, copy_geometry=True): if write_dir is None: write_dir = os.path.dirname(in_file) if environ is None: environ = {'AFNI_DECONFLICT': 'OVERWRITE'} if caching: memory = Memory(write_dir) bias_correct = memory.cache(ants.N4BiasFieldCorrection) copy = memory.cache(afni.Copy) copy_geom = memory.cache(fsl.CopyGeom) bias_correct.interface().set_default_terminal_output(terminal_output) copy.interface().set_default_terminal_output(terminal_output) else: bias_correct = ants.N4BiasFieldCorrection( terminal_output=terminal_output).run copy = afni.Copy(terminal_output=terminal_output).run copy_geom = fsl.CopyGeom(terminal_output=terminal_output).run unbiased_file = fname_presuffix(in_file, suffix='_n4', newpath=write_dir) if copy_geometry: output_image = fname_presuffix(in_file, suffix='_n4_rough_geom', newpath=write_dir) else: output_image = unbiased_file out_bias_correct = bias_correct( input_image=in_file, shrink_factor=_compute_n4_max_shrink(in_file), output_image=output_image) if copy_geometry: out_copy = copy(in_file=out_bias_correct.outputs.output_image, out_file=unbiased_file, environ=environ) out_copy_geom = copy_geom(dest_file=out_copy.outputs.out_file, in_file=in_file) return unbiased_file
def copy(self, in_file, out_file=None, suffix=None): if out_file is None and suffix is None: suffix = "copy" in_file, out_file = self.FuncHandler(in_file, out_file, suffix) copy3d = afni.Copy() #https://nipype.readthedocs.io/en/latest/interfaces/generated/interfaces.afni/utils.html#copy copy3d.inputs.in_file = in_file copy3d.inputs.out_file = out_file copy3d.inputs.verbose = self._is_verbose #copy3d.inputs.num_threads = cpu_count() copy3d.run() #remove temp files if type(in_file) == models.BIDSImageFile: in_file = os.path.join(self._output_dir, in_file.filename) if "_desc-temp" in in_file: os.remove(in_file)
def _delete_orientation(in_file, write_dir=None, min_zoom=.1, caching=False, verbose=True): if write_dir is None: write_dir = os.path.dirname(in_file) if verbose: terminal_output = 'stream' else: terminal_output = 'none' if caching: memory = Memory(write_dir) copy = memory.cache(afni.Copy) refit = memory.cache(afni.Refit) center_mass = memory.cache(afni.CenterMass) for step in [copy, refit]: step.interface().set_default_terminal_output(terminal_output) else: copy = afni.Copy(terminal_output=terminal_output).run refit = afni.Refit(terminal_output=terminal_output).run center_mass = afni.CenterMass().run out_copy = copy(in_file=in_file, out_file=fname_presuffix(in_file, newpath=write_dir)) zooms = nibabel.load(in_file).header.get_zooms()[:3] out_refit = refit(in_file=out_copy.outputs.out_file, xyzscale=min_zoom / min(zooms)) out_center_mass = center_mass(in_file=out_refit.outputs.out_file, cm_file=fname_presuffix(in_file, suffix='.txt', use_ext=False, newpath=write_dir), set_cm=(0, 0, 0)) return out_center_mass.outputs.out_file
# use_estimate_learning_rate_once = [False, False], # use_histogram_matching = [False, True], # number_of_iterations = [[300], [500,250]], # collapse_output_transforms = True, # winsorize_lower_quantile = 0.05, # winsorize_upper_quantile = 0.95, # args = '--float', # num_threads = 1, # initial_moving_transform_com = True, # ), name='coreg') # # preproc_func.connect([(selectfiles, coreg, [('struct','fixed_image')]), # (median, coreg, [('median_file','moving_image')]) # ]) make_nii = Node(afni.Copy(outputtype='NIFTI', out_file='func_moco.nii'), name="make_nii") preproc_func.connect([(moco, make_nii, [('out_file', 'in_file')])]) make_nii_mask = Node(afni.Copy(outputtype='NIFTI', out_file='func_mask.nii'), name="make_nii_mask") preproc_func.connect([(selectfiles, make_nii_mask, [('mask', 'in_file')])]) def makebase(scan, out_dir): return out_dir + scan + '/' # Sink relevant files func_sink = Node(nio.DataSink(parameterization=False), name='func_sink') preproc_func.connect([
bias_correct_t1_fs_nucorrect = ni_engine.Node( ni_fs.MNIBiasCorrection(), name='bias_correct_t1_fs_nucorrect') bias_correct_t1_ants_n4 = ni_engine.Node(ni_ants.N4BiasFieldCorrection(), name='bias_correct_t1_ants_n4') segment_t1_ants_atropos = ni_engine.Node(ni_ants.Atropos( number_of_tissue_classes=3, initialization='KMeans', save_posteriors=True), name='segment_t1_ants_atropos') # TODO: Break out masking as separate workflow? # TODO: Separate WM mask # TODO: Binarize WM mask (may not be strictly necessary) # TODO: Mask T1 with WM mask # TODO: Mask FLAIR with WM mask copy_t1 = ni_engine.Node(ni_afni.Copy(outputtype='NIFTI_GZ'), name='copy_t1') # Manually defined lists for now site_top_list = ('Amst', ) site_bot_list = ('GE3T', ) if DEBUG is True: sub_list = ('100', ) else: sub_list = ('100', '101', '102') # Infosource infosource = ni_engine.Node( ni_util.IdentityInterface(fields=['site_top', 'site_bot', 'subject_id']), name="infosource") infosource.iterables = [('site_top', site_top_list),
def _realign(func_filename, write_dir, caching=False, terminal_output='allatonce', environ=None): if environ is None: environ = {'AFNI_DECONFLICT': 'OVERWRITE'} if caching: memory = Memory(write_dir) clip_level = memory.cache(afni.ClipLevel) threshold = memory.cache(fsl.Threshold) volreg = memory.cache(afni.Volreg) allineate = memory.cache(afni.Allineate) copy = memory.cache(afni.Copy) copy_geom = memory.cache(fsl.CopyGeom) tstat = memory.cache(afni.TStat) for step in [threshold, volreg, allineate, tstat, copy, copy_geom]: step.interface().set_default_terminal_output(terminal_output) else: clip_level = afni.ClipLevel().run threshold = fsl.Threshold(terminal_output=terminal_output).run volreg = afni.Volreg(terminal_output=terminal_output).run allineate = afni.Allineate(terminal_output=terminal_output).run copy = afni.Copy(terminal_output=terminal_output).run copy_geom = fsl.CopyGeom(terminal_output=terminal_output).run tstat = afni.TStat(terminal_output=terminal_output).run out_clip_level = clip_level(in_file=func_filename) out_threshold = threshold(in_file=func_filename, thresh=out_clip_level.outputs.clip_val, out_file=fname_presuffix(func_filename, suffix='_thresholded', newpath=write_dir)) thresholded_filename = out_threshold.outputs.out_file out_volreg = volreg( # XXX dfile not saved in_file=thresholded_filename, out_file=fname_presuffix(thresholded_filename, suffix='_volreg', newpath=write_dir), environ=environ, oned_file=fname_presuffix(thresholded_filename, suffix='_volreg.1Dfile.1D', use_ext=False, newpath=write_dir), oned_matrix_save=fname_presuffix(thresholded_filename, suffix='_volreg.aff12.1D', use_ext=False, newpath=write_dir)) # Apply the registration to the whole head out_allineate = allineate(in_file=func_filename, master=func_filename, in_matrix=out_volreg.outputs.oned_matrix_save, out_file=fname_presuffix(func_filename, suffix='_volreg', newpath=write_dir), environ=environ) # 3dAllineate removes the obliquity. This is not a good way to readd it as # removes motion correction info in the header if it were an AFNI file...as # it happens it's NIfTI which does not store that so irrelevant! out_copy = copy(in_file=out_allineate.outputs.out_file, out_file=fname_presuffix(out_allineate.outputs.out_file, suffix='_oblique', newpath=write_dir), environ=environ) out_copy_geom = copy_geom(dest_file=out_copy.outputs.out_file, in_file=out_volreg.outputs.out_file) oblique_allineated_filename = out_copy_geom.outputs.out_file # Create a (hopefully) nice mean image for use in the registration out_tstat = tstat(in_file=oblique_allineated_filename, args='-mean', out_file=fname_presuffix(oblique_allineated_filename, suffix='_tstat', newpath=write_dir), environ=environ) # Remove intermediate outputs if not caching: for output_file in [ thresholded_filename, out_volreg.outputs.oned_matrix_save, out_volreg.outputs.out_file, out_volreg.outputs.md1d_file, out_allineate.outputs.out_file ]: os.remove(output_file) return (oblique_allineated_filename, out_tstat.outputs.out_file, out_volreg.outputs.oned_file)
def compute_morpho_brain_mask(head_file, brain_volume, write_dir=None, unifize=True, caching=False, verbose=True, terminal_output='allatonce', **unifize_kwargs): """ Parameters ---------- brain_volume : int Volume of the brain in mm3 used for brain extraction. Typically 400 for mouse and 1800 for rat. unifize : bool, optional If True, brain mask is computed using RATS Mathematical Morphology. Otherwise, a histogram-based brain segmentation is used. caching : bool, optional Wether or not to use caching. unifize_kwargs : dict, optional Is passed to nipype.interfaces.afni.Unifize. Returns ------- path to brain extracted image. Notes ----- RATS tool is used for brain extraction and has to be cited. For more information, see `RATS <http://www.iibi.uiowa.edu/content/rats-overview/>`_ """ if write_dir is None: write_dir = os.path.dirname(head_file) if interfaces.Info().version() is None: raise ValueError('Can not locate Rats') environ = {'AFNI_DECONFLICT': 'OVERWRITE'} if caching: memory = Memory(write_dir) clip_level = memory.cache(afni.ClipLevel) compute_mask = memory.cache(interfaces.MathMorphoMask) compute_mask.interface().set_default_terminal_output(terminal_output) copy = memory.cache(afni.Copy) copy.interface().set_default_terminal_output(terminal_output) copy_geom = memory.cache(fsl.CopyGeom) else: clip_level = afni.ClipLevel().run compute_mask = interfaces.MathMorphoMask( terminal_output=terminal_output).run copy = afni.Copy(terminal_output=terminal_output).run copy_geom = fsl.CopyGeom(terminal_output=terminal_output).run if unifize: unifization_options = [ '{}_{}'.format(k, v) for (k, v) in unifize_kwargs.items() ] suffix = 'unifized_' + '_'.join(unifization_options) file_to_mask = afni_unifize(head_file, write_dir, out_file=fname_presuffix( head_file, suffix=suffix, newpath=write_dir), caching=caching, terminal_output=terminal_output, verbose=verbose, environ=environ, **unifize_kwargs) else: file_to_mask = head_file out_clip_level = clip_level(in_file=file_to_mask) out_compute_mask = compute_mask( in_file=file_to_mask, out_file=fname_presuffix(file_to_mask, suffix='_rats_brain_mask', newpath=write_dir), volume_threshold=brain_volume, intensity_threshold=int(out_clip_level.outputs.clip_val)) # RATS sometimes slightly modifies the affine same_geom = _check_same_geometry(out_compute_mask.outputs.out_file, head_file) if not same_geom: mask_file = fname_presuffix(out_compute_mask.outputs.out_file, suffix='_rough_geom', newpath=write_dir) out_copy = copy(in_file=out_compute_mask.outputs.out_file, out_file=mask_file, environ=environ) _ = copy_geom(dest_file=out_copy.outputs.out_file, in_file=head_file) else: mask_file = out_compute_mask.outputs.out_file # Remove intermediate output if not caching and unifize: os.remove(file_to_mask) if not same_geom: os.remove(out_compute_mask.outputs.out_file) return mask_file
def fix_obliquity(to_fix_filename, reference_filename, caching=False, caching_dir=None, overwrite=False, verbose=True, environ=None): if caching_dir is None: caching_dir = os.getcwd() if caching: memory = Memory(caching_dir) if verbose: terminal_output = 'allatonce' else: terminal_output = 'none' if environ is None: if caching: environ = {} else: environ = {'AFNI_DECONFLICT': 'OVERWRITE'} if caching: copy = memory.cache(afni.Copy) refit = memory.cache(afni.Refit) copy.interface().set_default_terminal_output(terminal_output) refit.interface().set_default_terminal_output(terminal_output) else: copy = afni.Copy(terminal_output=terminal_output).run refit = afni.Refit(terminal_output=terminal_output).run tmp_folder = os.path.join(caching_dir, 'tmp') if not os.path.isdir(tmp_folder): os.makedirs(tmp_folder) reference_basename = os.path.basename(reference_filename) orig_reference_filename = fname_presuffix(os.path.join( tmp_folder, reference_basename), suffix='+orig.BRIK', use_ext=False) out_copy_oblique = copy(in_file=reference_filename, out_file=orig_reference_filename, environ=environ) orig_reference_filename = out_copy_oblique.outputs.out_file to_fix_basename = os.path.basename(to_fix_filename) orig_to_fix_filename = fname_presuffix(os.path.join( tmp_folder, to_fix_basename), suffix='+orig.BRIK', use_ext=False) out_copy = copy(in_file=to_fix_filename, out_file=orig_to_fix_filename, environ=environ) orig_to_fix_filename = out_copy.outputs.out_file out_refit = refit(in_file=orig_to_fix_filename, atrcopy=(orig_reference_filename, 'IJK_TO_DICOM_REAL')) out_copy = copy(in_file=out_refit.outputs.out_file, out_file=fname_presuffix(to_fix_filename, suffix='_oblique'), environ=environ) if not caching: shutil.rmtree(tmp_folder) return out_copy.outputs.out_file