diff --git a/AutoWorkup/BRAINSTools/ANTSWrapper.py b/AutoWorkup/BRAINSTools/ANTSWrapper.py new file mode 100644 index 00000000..185c8a46 --- /dev/null +++ b/AutoWorkup/BRAINSTools/ANTSWrapper.py @@ -0,0 +1,91 @@ +#! /usr/bin/env python +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +""" + +Program: PINC/nipype/Wrappers/ants.py +Date: Tue Jan 3 10:47:45 2012 +Author: David Welch, dmwelch@NOSPAM.uiowa.edu # +Purpose: Wrap a Bash script to interface ANTS with Nipype + +Requirements: <<< Interface specifications >>> + +$ ANTS_wrapper.sh + + where the script implicitly generates three output files: + Affine.txt + Warp.nii.gz + InverseWarp.nii.gz + + +""" +from nipype.interfaces.base import ( File, TraitedSpec, Interface, CommandLineInputSpec, CommandLine, traits ) + +### Node Interface +class ANTSWrapperInputSpec( TraitedSpec ): + fixed_T1_image = File( desc = "T1 Fixed Volume", exists = True, mandatory = True) + fixed_T2_image = File( desc = "T2 Fixed Volume", exists = True, mandatory = True) + moving_T1_image = File( desc = "T1 Moving Volume", exists = True, mandatory = True) + moving_T2_image = File( desc = "T2 Moving Volume", exists = True, mandatory = True) + prefix_desc = "Output volume prefix for Affine.txt, Warp.nii.gz, and InverseWarp.nii.gz" + output_prefix = traits.Str( desc = prefix_desc, exists = True, mandatory = False, + default_value = "./ANTS_") + +class ANTSWrapperOutputSpec(TraitedSpec): + output_affine = File( desc = "Affine Transform Text File") + output_warp = File( desc = "Warped Output Volume") + output_invwarp = File( desc = "Inverse Warp Output Volume") + +class ANTSWrapper(Interface): + input_spec = ANTSWrapperInputSpec + output_spec = ANTSWrapperOutputSpec + + def _list_outputs(self): + """ + The ANTS package implicitly outputs three files based on the prefix given at the commandline: + {prefix}Affine.txt, {prefix}Warp.nii.gz, and {prefix}InverseWarp.nii.gz. This function exposes + them for subsequent nodes. + """ + from os.path import abspath + outputs = self.output_spec().get() + outputs['output_affine'] = abspath( self.inputs.output_prefix + 'Affine.txt') + outputs['output_warp'] = abspath( self.inputs.output_prefix + 'Warp.nii.gz') + outputs['output_invwarp'] = abspath( self.inputs.output_prefix + 'InverseWarp.nii.gz') + return outputs + +### CommandLine +class ANTSWrapperCLInputSpec(CommandLineInputSpec): + fixed_T1_image = File(desc="T1 Fixed Volume", exists=True, mandatory=True, position=0, argstr="%s" ) + fixed_T2_image = File(desc="T2 Fixed Volume", exists=True, mandatory=True, position=1, argstr="%s" ) + moving_T1_image = File(desc="T1 Moving Volume", exists=True, mandatory=True, position=2, argstr="%s" ) + moving_T2_image = File(desc="T2 Moving Volume", exists=True, mandatory=True, position=3, argstr="%s" ) + prefix_desc = "Output volume prefix for Affine.txt, Warp.nii.gz, and InverseWarp.nii.gz" + output_prefix = traits.Str(desc=prefix_desc, exists=True, mandatory=False, position=4, argstr="%s", + default_value="./ANTS_" ) + +class ANTSWrapperCLOutputSpec(CommandLineInputSpec): + output_affine = File( desc = "Affine Transform Text File", exists = True, mandatory = False) + output_warp = File( desc = "Warped Output Volume", exists = True, mandatory = True ) + output_invwarp = File( desc = "Inverse Warp Output Volume", exists = True, mandatory = False) + +class ANTSWrapper(CommandLine): + _cmd = 'ANTS_wrapper.sh' + input_spec = ANTSWrapperCLInputSpec + output_spec = ANTSWrapperCLOutputSpec + + def _list_outputs(self): + """ + The ANTS package implicitly outputs three files based on the prefix given at the commandline: + {prefix}Affine.txt, {prefix}Warp.nii.gz, and {prefix}InverseWarp.nii.gz. This function exposes + them for subsequent nodes. + """ + from os.path import abspath + outputs = self.output_spec().get() + outputs['output_affine'] = abspath( self.inputs.output_prefix + 'Affine.txt') + outputs['output_warp'] = abspath( self.inputs.output_prefix + 'Warp.nii.gz') + outputs['output_invwarp'] = abspath( self.inputs.output_prefix + 'InverseWarp.nii.gz') + return outputs + +if __name__ == '__main__': + ants = ANTSWrapper(sys.argv) + ants.run() diff --git a/AutoWorkup/BRAINSTools/BRAINSABC.py b/AutoWorkup/BRAINSTools/BRAINSABC.py new file mode 100644 index 00000000..13b2f29c --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSABC.py @@ -0,0 +1,73 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSABCInputSpec(CommandLineInputSpec): + inputVolumes = InputMultiPath(File(exists=True), argstr = "--inputVolumes %s...") + atlasDefinition = File( exists = True,argstr = "--atlasDefinition %s") + inputVolumeTypes = InputMultiPath(traits.Str, sep = ",",argstr = "--inputVolumeTypes %s") + outputDir = traits.Either(traits.Bool, Directory(), hash_files = False,argstr = "--outputDir %s") + atlasToSubjectTransformType = traits.Enum("ID","Rigid","Affine","BSpline", argstr = "--atlasToSubjectTransformType %s") + atlasToSubjectTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--atlasToSubjectTransform %s") + atlasToSubjectInitialTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--atlasToSubjectInitialTransform %s") + subjectIntermodeTransformType = traits.Enum("ID","Rigid","Affine","BSpline", argstr = "--subjectIntermodeTransformType %s") + outputVolumes = traits.Either(traits.Bool, InputMultiPath(File(),), hash_files = False,argstr = "--outputVolumes %s...") + outputLabels = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputLabels %s") + outputDirtyLabels = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputDirtyLabels %s") + posteriorTemplate = traits.Str( argstr = "--posteriorTemplate %s") + outputFormat = traits.Enum("NIFTI","Meta","Nrrd", argstr = "--outputFormat %s") + resamplerInterpolatorType = traits.Enum("BSpline","NearestNeighbor","WindowedSinc","Linear","ResampleInPlace","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + maxIterations = traits.Int( argstr = "--maxIterations %d") + medianFilterSize = InputMultiPath(traits.Int, sep = ",",argstr = "--medianFilterSize %s") + filterIteration = traits.Int( argstr = "--filterIteration %d") + filterTimeStep = traits.Float( argstr = "--filterTimeStep %f") + filterMethod = traits.Enum("None","CurvatureFlow","GradientAnisotropicDiffusion","Median", argstr = "--filterMethod %s") + maxBiasDegree = traits.Int( argstr = "--maxBiasDegree %d") + atlasWarpingOff = traits.Bool( argstr = "--atlasWarpingOff ") + gridSize = InputMultiPath(traits.Int, sep = ",",argstr = "--gridSize %s") + defaultSuffix = traits.Str( argstr = "--defaultSuffix %s") + implicitOutputs = traits.Either(traits.Bool, InputMultiPath(File(),), hash_files = False,argstr = "--implicitOutputs %s...") + debuglevel = traits.Int( argstr = "--debuglevel %d") + writeLess = traits.Bool( argstr = "--writeLess ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSABCOutputSpec(TraitedSpec): + outputDir = Directory( exists = True) + atlasToSubjectTransform = File( exists = True) + atlasToSubjectInitialTransform = File( exists = True) + outputVolumes = OutputMultiPath(File(exists=True), exists = True) + outputLabels = File( exists = True) + outputDirtyLabels = File( exists = True) + implicitOutputs = OutputMultiPath(File(exists=True), exists = True) + + +class BRAINSABC(CommandLine): + + input_spec = BRAINSABCInputSpec + output_spec = BRAINSABCOutputSpec + _cmd = " BRAINSABC " + _outputs_filenames = {'outputLabels':'outputLabels.nii.gz','atlasToSubjectTransform':'atlasToSubjectTransform.mat','atlasToSubjectInitialTransform':'atlasToSubjectInitialTransform.mat','outputDirtyLabels':'outputDirtyLabels.nii.gz','outputVolumes':'outputVolumes.nii.gz','outputDir':'outputDir','implicitOutputs':'implicitOutputs.nii.gz'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSABC, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSAlignMSP.py b/AutoWorkup/BRAINSTools/BRAINSAlignMSP.py new file mode 100644 index 00000000..35858be8 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSAlignMSP.py @@ -0,0 +1,53 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSAlignMSPInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + resampleMSP = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--OutputresampleMSP %s") + verbose = traits.Bool( argstr = "--verbose ") + resultsDir = traits.Either(traits.Bool, Directory(), hash_files = False,argstr = "--resultsDir %s") + writedebuggingImagesLevel = traits.Int( argstr = "--writedebuggingImagesLevel %d") + mspQualityLevel = traits.Int( argstr = "--mspQualityLevel %d") + rescaleIntensities = traits.Bool( argstr = "--rescaleIntensities ") + trimRescaledIntensities = traits.Float( argstr = "--trimRescaledIntensities %f") + rescaleIntensitiesOutputRange = InputMultiPath(traits.Int, sep = ",",argstr = "--rescaleIntensitiesOutputRange %s") + backgroundFillValueString = traits.Str( argstr = "--BackgroundFillValue %s") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSAlignMSPOutputSpec(TraitedSpec): + resampleMSP = File( exists = True) + resultsDir = Directory( exists = True) + + +class BRAINSAlignMSP(CommandLine): + + input_spec = BRAINSAlignMSPInputSpec + output_spec = BRAINSAlignMSPOutputSpec + _cmd = " BRAINSAlignMSP " + _outputs_filenames = {'resampleMSP':'resampleMSP.nii','resultsDir':'resultsDir'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSAlignMSP, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSClipInferior.py b/AutoWorkup/BRAINSTools/BRAINSClipInferior.py new file mode 100644 index 00000000..b305680a --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSClipInferior.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSClipInferiorInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + acLowerBound = traits.Float( argstr = "--acLowerBound %f") + backgroundFillValueString = traits.Str( argstr = "--BackgroundFillValue %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSClipInferiorOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class BRAINSClipInferior(CommandLine): + + input_spec = BRAINSClipInferiorInputSpec + output_spec = BRAINSClipInferiorOutputSpec + _cmd = " BRAINSClipInferior " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSClipInferior, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSConstellationDetector.py b/AutoWorkup/BRAINSTools/BRAINSConstellationDetector.py new file mode 100644 index 00000000..1d44c293 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSConstellationDetector.py @@ -0,0 +1,91 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSConstellationDetectorInputSpec(CommandLineInputSpec): + houghEyeDetectorMode = traits.Int( argstr = "--houghEyeDetectorMode %d") + inputTemplateModel = File( exists = True,argstr = "--inputTemplateModel %s") + llsModel = File( exists = True,argstr = "--LLSModel %s") + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + outputResampledVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputResampledVolume %s") + outputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransform %s") + outputLandmarksInInputSpace = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputLandmarksInInputSpace %s") + outputLandmarksInACPCAlignedSpace = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputLandmarksInACPCAlignedSpace %s") + outputLandmarkWeights = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputLandmarkWeights %s") + inputLandmarksPaired = File( exists = True,argstr = "--inputLandmarksPaired %s") + outputLandmarksPaired = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputLandmarksPaired %s") + outputMRML = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputMRML %s") + outputVerificationScript = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVerificationScript %s") + mspQualityLevel = traits.Int( argstr = "--mspQualityLevel %d") + otsuPercentileThreshold = traits.Float( argstr = "--otsuPercentileThreshold %f") + acLowerBound = traits.Float( argstr = "--acLowerBound %f") + cutOutHeadInOutputVolume = traits.Bool( argstr = "--cutOutHeadInOutputVolume ") + outputUntransformedClippedVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputUntransformedClippedVolume %s") + rescaleIntensities = traits.Bool( argstr = "--rescaleIntensities ") + trimRescaledIntensities = traits.Float( argstr = "--trimRescaledIntensities %f") + rescaleIntensitiesOutputRange = InputMultiPath(traits.Int, sep = ",",argstr = "--rescaleIntensitiesOutputRange %s") + backgroundFillValueString = traits.Str( argstr = "--BackgroundFillValue %s") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + forceACPoint = InputMultiPath(traits.Float, sep = ",",argstr = "--forceACPoint %s") + forcePCPoint = InputMultiPath(traits.Float, sep = ",",argstr = "--forcePCPoint %s") + forceVN4Point = InputMultiPath(traits.Float, sep = ",",argstr = "--forceVN4Point %s") + forceRPPoint = InputMultiPath(traits.Float, sep = ",",argstr = "--forceRPPoint %s") + inputLandmarksEMSP = File( exists = True,argstr = "--inputLandmarksEMSP %s") + forceHoughEyeDetectorReportFailure = traits.Bool( argstr = "--forceHoughEyeDetectorReportFailure ") + radiusMPJ = traits.Float( argstr = "--rmpj %f") + radiusAC = traits.Float( argstr = "--rac %f") + radiusPC = traits.Float( argstr = "--rpc %f") + radiusVN4 = traits.Float( argstr = "--rVN4 %f") + debug = traits.Bool( argstr = "--debug ") + verbose = traits.Bool( argstr = "--verbose ") + writeBranded2DImage = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--writeBranded2DImage %s") + resultsDir = traits.Either(traits.Bool, Directory(), hash_files = False,argstr = "--resultsDir %s") + writedebuggingImagesLevel = traits.Int( argstr = "--writedebuggingImagesLevel %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSConstellationDetectorOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + outputResampledVolume = File( exists = True) + outputTransform = File( exists = True) + outputLandmarksInInputSpace = File( exists = True) + outputLandmarksInACPCAlignedSpace = File( exists = True) + outputLandmarkWeights = File( exists = True) + outputLandmarksPaired = File( exists = True) + outputMRML = File( exists = True) + outputVerificationScript = File( exists = True) + outputUntransformedClippedVolume = File( exists = True) + writeBranded2DImage = File( exists = True) + resultsDir = Directory( exists = True) + + +class BRAINSConstellationDetector(CommandLine): + + input_spec = BRAINSConstellationDetectorInputSpec + output_spec = BRAINSConstellationDetectorOutputSpec + _cmd = " BRAINSConstellationDetector " + _outputs_filenames = {'outputVolume':'outputVolume.nii.gz','outputResampledVolume':'outputResampledVolume.nii.gz','outputMRML':'outputMRML.mrml','outputLandmarksPaired':'outputLandmarksPaired.fcsv','resultsDir':'resultsDir','outputTransform':'outputTransform.mat','writeBranded2DImage':'writeBranded2DImage.png','outputLandmarksInACPCAlignedSpace':'outputLandmarksInACPCAlignedSpace.fcsv','outputLandmarksInInputSpace':'outputLandmarksInInputSpace.fcsv','outputLandmarkWeights':'outputLandmarkWeights.wts','outputUntransformedClippedVolume':'outputUntransformedClippedVolume.nii.gz','outputVerificationScript':'outputVerificationScript.sh'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSConstellationDetector, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSConstellationModeler.py b/AutoWorkup/BRAINSTools/BRAINSConstellationModeler.py new file mode 100644 index 00000000..63b9cd42 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSConstellationModeler.py @@ -0,0 +1,54 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSConstellationModelerInputSpec(CommandLineInputSpec): + verbose = traits.Bool( argstr = "--verbose ") + inputTrainingList = File( exists = True,argstr = "--inputTrainingList %s") + outputModel = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputModel %s") + saveOptimizedLandmarks = traits.Bool( argstr = "--saveOptimizedLandmarks ") + optimizedLandmarksFilenameExtender = traits.Str( argstr = "--optimizedLandmarksFilenameExtender %s") + resultsDir = traits.Either(traits.Bool, Directory(), hash_files = False,argstr = "--resultsDir %s") + mspQualityLevel = traits.Int( argstr = "--mspQualityLevel %d") + rescaleIntensities = traits.Bool( argstr = "--rescaleIntensities ") + trimRescaledIntensities = traits.Float( argstr = "--trimRescaledIntensities %f") + rescaleIntensitiesOutputRange = InputMultiPath(traits.Int, sep = ",",argstr = "--rescaleIntensitiesOutputRange %s") + backgroundFillValueString = traits.Str( argstr = "--BackgroundFillValue %s") + writedebuggingImagesLevel = traits.Int( argstr = "--writedebuggingImagesLevel %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSConstellationModelerOutputSpec(TraitedSpec): + outputModel = File( exists = True) + resultsDir = Directory( exists = True) + + +class BRAINSConstellationModeler(CommandLine): + + input_spec = BRAINSConstellationModelerInputSpec + output_spec = BRAINSConstellationModelerOutputSpec + _cmd = " BRAINSConstellationModeler " + _outputs_filenames = {'outputModel':'outputModel.mdl','resultsDir':'resultsDir'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSConstellationModeler, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSCut.py b/AutoWorkup/BRAINSTools/BRAINSCut.py new file mode 100644 index 00000000..406abd3b --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSCut.py @@ -0,0 +1,53 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSCutInputSpec(CommandLineInputSpec): + netConfiguration = File( exists = True,argstr = "--netConfiguration %s") + trainModelStartIndex = traits.Int( argstr = "--trainModelStartIndex %d") + verbose = traits.Int( argstr = "--verbose %d") + multiStructureThreshold = traits.Bool( argstr = "--multiStructureThreshold ") + histogramEqualization = traits.Bool( argstr = "--histogramEqualization ") + computeSSEOn = traits.Bool( argstr = "--computeSSEOn ") + generateProbability = traits.Bool( argstr = "--generateProbability ") + createVectors = traits.Bool( argstr = "--createVectors ") + trainModel = traits.Bool( argstr = "--trainModel ") + applyModel = traits.Bool( argstr = "--applyModel ") + validate = traits.Bool( argstr = "--validate ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + implicitOutputs = traits.Either(traits.Bool, InputMultiPath(File(),), hash_files = False,argstr = "--implicitOutputs %s...") + + +class BRAINSCutOutputSpec(TraitedSpec): + implicitOutputs = OutputMultiPath(File(exists=True), exists = True) + + +class BRAINSCut(CommandLine): + + input_spec = BRAINSCutInputSpec + output_spec = BRAINSCutOutputSpec + _cmd = " BRAINSCut " + _outputs_filenames = {'implicitOutputs':'implicitOutputs.nii.gz'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSCut, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSDemonWarp.py b/AutoWorkup/BRAINSTools/BRAINSDemonWarp.py new file mode 100644 index 00000000..e487320f --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSDemonWarp.py @@ -0,0 +1,82 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSDemonWarpInputSpec(CommandLineInputSpec): + movingVolume = File( exists = True,argstr = "--movingVolume %s") + fixedVolume = File( exists = True,argstr = "--fixedVolume %s") + inputPixelType = traits.Enum("float","short","ushort","int","uchar", argstr = "--inputPixelType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum("float","short","ushort","int","uchar", argstr = "--outputPixelType %s") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + registrationFilterType = traits.Enum("Demons","FastSymmetricForces","Diffeomorphic", argstr = "--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( argstr = "--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( argstr = "--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath(traits.Int, sep = ",",argstr = "--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath(traits.Int, sep = ",",argstr = "--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, sep = ",",argstr = "--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( argstr = "--histogramMatch ") + numberOfHistogramBins = traits.Int( argstr = "--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( argstr = "--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath(traits.Int, sep = ",",argstr = "--medianFilterSize %s") + initializeWithDisplacementField = File( exists = True,argstr = "--initializeWithDisplacementField %s") + initializeWithTransform = File( exists = True,argstr = "--initializeWithTransform %s") + maskProcessingMode = traits.Enum("NOMASK","ROIAUTO","ROI","BOBF", argstr = "--maskProcessingMode %s") + fixedBinaryVolume = File( exists = True,argstr = "--fixedBinaryVolume %s") + movingBinaryVolume = File( exists = True,argstr = "--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( argstr = "--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( argstr = "--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( argstr = "--backgroundFillValue %d") + seedForBOBF = InputMultiPath(traits.Int, sep = ",",argstr = "--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath(traits.Int, sep = ",",argstr = "--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( argstr = "--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath(traits.Int, sep = ",",argstr = "--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( argstr = "--outputNormalized ") + outputDebug = traits.Bool( argstr = "--outputDebug ") + gradientType = traits.Enum("0","1","2", argstr = "--gradient_type %s") + smoothingUp = traits.Float( argstr = "--upFieldSmoothing %f") + maxStepLength = traits.Float( argstr = "--max_step_length %f") + turnOffDiffeomorph = traits.Bool( argstr = "--use_vanilla_dem ") + UseDebugImageViewer = traits.Bool( argstr = "--gui ") + PromptAfterImageSend = traits.Bool( argstr = "--promptUser ") + numberOfBCHApproximationTerms = traits.Int( argstr = "--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSDemonWarpOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + outputDisplacementFieldVolume = File( exists = True) + outputCheckerboardVolume = File( exists = True) + + +class BRAINSDemonWarp(CommandLine): + + input_spec = BRAINSDemonWarpInputSpec + output_spec = BRAINSDemonWarpOutputSpec + _cmd = " BRAINSDemonWarp " + _outputs_filenames = {'outputVolume':'outputVolume.nii','outputCheckerboardVolume':'outputCheckerboardVolume.nii','outputDisplacementFieldVolume':'outputDisplacementFieldVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSDemonWarp, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSFit.py b/AutoWorkup/BRAINSTools/BRAINSFit.py new file mode 100644 index 00000000..f1009f9f --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSFit.py @@ -0,0 +1,107 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSFitInputSpec(CommandLineInputSpec): + fixedVolume = File( exists = True,argstr = "--fixedVolume %s") + movingVolume = File( exists = True,argstr = "--movingVolume %s") + bsplineTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--bsplineTransform %s") + linearTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--linearTransform %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + initialTransform = File( exists = True,argstr = "--initialTransform %s") + initializeTransformMode = traits.Enum("Off","useMomentsAlign","useCenterOfHeadAlign","useGeometryAlign","useCenterOfROIAlign", argstr = "--initializeTransformMode %s") + useRigid = traits.Bool( argstr = "--useRigid ") + useScaleVersor3D = traits.Bool( argstr = "--useScaleVersor3D ") + useScaleSkewVersor3D = traits.Bool( argstr = "--useScaleSkewVersor3D ") + useAffine = traits.Bool( argstr = "--useAffine ") + useBSpline = traits.Bool( argstr = "--useBSpline ") + useComposite = traits.Bool( argstr = "--useComposite ") + numberOfSamples = traits.Int( argstr = "--numberOfSamples %d") + splineGridSize = InputMultiPath(traits.Int, sep = ",",argstr = "--splineGridSize %s") + numberOfIterations = InputMultiPath(traits.Int, sep = ",",argstr = "--numberOfIterations %s") + maskProcessingMode = traits.Enum("NOMASK","ROIAUTO","ROI", argstr = "--maskProcessingMode %s") + fixedBinaryVolume = File( exists = True,argstr = "--fixedBinaryVolume %s") + movingBinaryVolume = File( exists = True,argstr = "--movingBinaryVolume %s") + outputFixedVolumeROI = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputFixedVolumeROI %s") + outputMovingVolumeROI = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputMovingVolumeROI %s") + outputVolumePixelType = traits.Enum("float","short","ushort","int","uint","uchar", argstr = "--outputVolumePixelType %s") + backgroundFillValue = traits.Float( argstr = "--backgroundFillValue %f") + maskInferiorCutOffFromCenter = traits.Float( argstr = "--maskInferiorCutOffFromCenter %f") + scaleOutputValues = traits.Bool( argstr = "--scaleOutputValues ") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + minimumStepLength = InputMultiPath(traits.Float, sep = ",",argstr = "--minimumStepLength %s") + translationScale = traits.Float( argstr = "--translationScale %f") + reproportionScale = traits.Float( argstr = "--reproportionScale %f") + skewScale = traits.Float( argstr = "--skewScale %f") + maxBSplineDisplacement = traits.Float( argstr = "--maxBSplineDisplacement %f") + histogramMatch = traits.Bool( argstr = "--histogramMatch ") + numberOfHistogramBins = traits.Int( argstr = "--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( argstr = "--numberOfMatchPoints %d") + strippedOutputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--strippedOutputTransform %s") + transformType = InputMultiPath(traits.Str, sep = ",",argstr = "--transformType %s") + outputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransform %s") + fixedVolumeTimeIndex = traits.Int( argstr = "--fixedVolumeTimeIndex %d") + movingVolumeTimeIndex = traits.Int( argstr = "--movingVolumeTimeIndex %d") + medianFilterSize = InputMultiPath(traits.Int, sep = ",",argstr = "--medianFilterSize %s") + removeIntensityOutliers = traits.Float( argstr = "--removeIntensityOutliers %f") + useCachingOfBSplineWeightsMode = traits.Enum("ON","OFF", argstr = "--useCachingOfBSplineWeightsMode %s") + useExplicitPDFDerivativesMode = traits.Enum("AUTO","ON","OFF", argstr = "--useExplicitPDFDerivativesMode %s") + ROIAutoDilateSize = traits.Float( argstr = "--ROIAutoDilateSize %f") + ROIAutoClosingSize = traits.Float( argstr = "--ROIAutoClosingSize %f") + relaxationFactor = traits.Float( argstr = "--relaxationFactor %f") + maximumStepLength = traits.Float( argstr = "--maximumStepLength %f") + failureExitCode = traits.Int( argstr = "--failureExitCode %d") + writeTransformOnFailure = traits.Bool( argstr = "--writeTransformOnFailure ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + forceMINumberOfThreads = traits.Int( argstr = "--forceMINumberOfThreads %d") + debugLevel = traits.Int( argstr = "--debugLevel %d") + costFunctionConvergenceFactor = traits.Float( argstr = "--costFunctionConvergenceFactor %f") + projectedGradientTolerance = traits.Float( argstr = "--projectedGradientTolerance %f") + UseDebugImageViewer = traits.Bool( argstr = "--gui ") + PromptAfterImageSend = traits.Bool( argstr = "--promptUser ") + useMomentsAlign = traits.Bool( argstr = "--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ") + useGeometryAlign = traits.Bool( argstr = "--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ") + useCenterOfHeadAlign = traits.Bool( argstr = "--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ") + permitParameterVariation = InputMultiPath(traits.Int, sep = ",",argstr = "--permitParameterVariation %s") + costMetric = traits.Enum("MMI","MSE","NC","MC", argstr = "--costMetric %s") + + +class BRAINSFitOutputSpec(TraitedSpec): + bsplineTransform = File( exists = True) + linearTransform = File( exists = True) + outputVolume = File( exists = True) + outputFixedVolumeROI = File( exists = True) + outputMovingVolumeROI = File( exists = True) + strippedOutputTransform = File( exists = True) + outputTransform = File( exists = True) + + +class BRAINSFit(CommandLine): + + input_spec = BRAINSFitInputSpec + output_spec = BRAINSFitOutputSpec + _cmd = " BRAINSFit " + _outputs_filenames = {'outputVolume':'outputVolume.nii','bsplineTransform':'bsplineTransform.mat','outputTransform':'outputTransform.mat','outputFixedVolumeROI':'outputFixedVolumeROI.nii','strippedOutputTransform':'strippedOutputTransform.mat','outputMovingVolumeROI':'outputMovingVolumeROI.nii','linearTransform':'linearTransform.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSFit, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSInitializedControlPoints.py b/AutoWorkup/BRAINSTools/BRAINSInitializedControlPoints.py new file mode 100644 index 00000000..e9de3ce6 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSInitializedControlPoints.py @@ -0,0 +1,46 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSInitializedControlPointsInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + splineGridSize = InputMultiPath(traits.Int, sep = ",",argstr = "--splineGridSize %s") + permuteOrder = InputMultiPath(traits.Int, sep = ",",argstr = "--permuteOrder %s") + outputLandmarksFile = traits.Str( argstr = "--outputLandmarksFile %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSInitializedControlPointsOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class BRAINSInitializedControlPoints(CommandLine): + + input_spec = BRAINSInitializedControlPointsInputSpec + output_spec = BRAINSInitializedControlPointsOutputSpec + _cmd = " BRAINSInitializedControlPoints " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSInitializedControlPoints, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSLandmarkInitializer.py b/AutoWorkup/BRAINSTools/BRAINSLandmarkInitializer.py new file mode 100644 index 00000000..6c4d85c3 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSLandmarkInitializer.py @@ -0,0 +1,44 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSLandmarkInitializerInputSpec(CommandLineInputSpec): + inputFixedLandmarkFilename = File( exists = True,argstr = "--inputFixedLandmarkFilename %s") + inputMovingLandmarkFilename = File( exists = True,argstr = "--inputMovingLandmarkFilename %s") + inputWeightFilename = File( exists = True,argstr = "--inputWeightFilename %s") + outputTransformFilename = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransformFilename %s") + + +class BRAINSLandmarkInitializerOutputSpec(TraitedSpec): + outputTransformFilename = File( exists = True) + + +class BRAINSLandmarkInitializer(CommandLine): + + input_spec = BRAINSLandmarkInitializerInputSpec + output_spec = BRAINSLandmarkInitializerOutputSpec + _cmd = " BRAINSLandmarkInitializer " + _outputs_filenames = {'outputTransformFilename':'outputTransformFilename'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSLandmarkInitializer, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSLinearModelerEPCA.py b/AutoWorkup/BRAINSTools/BRAINSLinearModelerEPCA.py new file mode 100644 index 00000000..2c583ebb --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSLinearModelerEPCA.py @@ -0,0 +1,42 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSLinearModelerEPCAInputSpec(CommandLineInputSpec): + inputTrainingList = File( exists = True,argstr = "--inputTrainingList %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSLinearModelerEPCAOutputSpec(TraitedSpec): + pass + + +class BRAINSLinearModelerEPCA(CommandLine): + + input_spec = BRAINSLinearModelerEPCAInputSpec + output_spec = BRAINSLinearModelerEPCAOutputSpec + _cmd = " BRAINSLinearModelerEPCA " + _outputs_filenames = {} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSLinearModelerEPCA, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSLmkTransform.py b/AutoWorkup/BRAINSTools/BRAINSLmkTransform.py new file mode 100644 index 00000000..0604adf4 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSLmkTransform.py @@ -0,0 +1,48 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSLmkTransformInputSpec(CommandLineInputSpec): + inputMovingLandmarks = File( exists = True,argstr = "--inputMovingLandmarks %s") + inputFixedLandmarks = File( exists = True,argstr = "--inputFixedLandmarks %s") + outputAffineTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputAffineTransform %s") + inputMovingVolume = File( exists = True,argstr = "--inputMovingVolume %s") + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + outputResampledVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputResampledVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSLmkTransformOutputSpec(TraitedSpec): + outputAffineTransform = File( exists = True) + outputResampledVolume = File( exists = True) + + +class BRAINSLmkTransform(CommandLine): + + input_spec = BRAINSLmkTransformInputSpec + output_spec = BRAINSLmkTransformOutputSpec + _cmd = " BRAINSLmkTransform " + _outputs_filenames = {'outputResampledVolume':'outputResampledVolume.nii','outputAffineTransform':'outputAffineTransform.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSLmkTransform, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSMultiModeSegment.py b/AutoWorkup/BRAINSTools/BRAINSMultiModeSegment.py new file mode 100644 index 00000000..3742a6c2 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSMultiModeSegment.py @@ -0,0 +1,48 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSMultiModeSegmentInputSpec(CommandLineInputSpec): + inputVolumes = InputMultiPath(File(exists=True), argstr = "--inputVolumes %s...") + inputMaskVolume = File( exists = True,argstr = "--inputMaskVolume %s") + outputROIMaskVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputROIMaskVolume %s") + outputClippedVolumeROI = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputClippedVolumeROI %s") + lowerThreshold = InputMultiPath(traits.Float, sep = ",",argstr = "--lowerThreshold %s") + upperThreshold = InputMultiPath(traits.Float, sep = ",",argstr = "--upperThreshold %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSMultiModeSegmentOutputSpec(TraitedSpec): + outputROIMaskVolume = File( exists = True) + outputClippedVolumeROI = File( exists = True) + + +class BRAINSMultiModeSegment(CommandLine): + + input_spec = BRAINSMultiModeSegmentInputSpec + output_spec = BRAINSMultiModeSegmentOutputSpec + _cmd = " BRAINSMultiModeSegment " + _outputs_filenames = {'outputROIMaskVolume':'outputROIMaskVolume.nii','outputClippedVolumeROI':'outputClippedVolumeROI.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSMultiModeSegment, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSMush.py b/AutoWorkup/BRAINSTools/BRAINSMush.py new file mode 100644 index 00000000..90f9f0f1 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSMush.py @@ -0,0 +1,58 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSMushInputSpec(CommandLineInputSpec): + inputFirstVolume = File( exists = True,argstr = "--inputFirstVolume %s") + inputSecondVolume = File( exists = True,argstr = "--inputSecondVolume %s") + inputMaskVolume = File( exists = True,argstr = "--inputMaskVolume %s") + outputWeightsFile = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputWeightsFile %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + outputMask = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputMask %s") + seed = InputMultiPath(traits.Int, sep = ",",argstr = "--seed %s") + desiredMean = traits.Float( argstr = "--desiredMean %f") + desiredVariance = traits.Float( argstr = "--desiredVariance %f") + lowerThresholdFactorPre = traits.Float( argstr = "--lowerThresholdFactorPre %f") + upperThresholdFactorPre = traits.Float( argstr = "--upperThresholdFactorPre %f") + lowerThresholdFactor = traits.Float( argstr = "--lowerThresholdFactor %f") + upperThresholdFactor = traits.Float( argstr = "--upperThresholdFactor %f") + boundingBoxSize = InputMultiPath(traits.Int, sep = ",",argstr = "--boundingBoxSize %s") + boundingBoxStart = InputMultiPath(traits.Int, sep = ",",argstr = "--boundingBoxStart %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSMushOutputSpec(TraitedSpec): + outputWeightsFile = File( exists = True) + outputVolume = File( exists = True) + outputMask = File( exists = True) + + +class BRAINSMush(CommandLine): + + input_spec = BRAINSMushInputSpec + output_spec = BRAINSMushOutputSpec + _cmd = " BRAINSMush " + _outputs_filenames = {'outputMask':'outputMask.nii.gz','outputWeightsFile':'outputWeightsFile.txt','outputVolume':'outputVolume.nii.gz'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSMush, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSROIAuto.py b/AutoWorkup/BRAINSTools/BRAINSROIAuto.py new file mode 100644 index 00000000..befb0123 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSROIAuto.py @@ -0,0 +1,52 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSROIAutoInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputROIMaskVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputROIMaskVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + maskOutput = traits.Bool( argstr = "--maskOutput ") + cropOutput = traits.Bool( argstr = "--cropOutput ") + otsuPercentileThreshold = traits.Float( argstr = "--otsuPercentileThreshold %f") + thresholdCorrectionFactor = traits.Float( argstr = "--thresholdCorrectionFactor %f") + closingSize = traits.Float( argstr = "--closingSize %f") + ROIAutoDilateSize = traits.Float( argstr = "--ROIAutoDilateSize %f") + outputVolumePixelType = traits.Enum("float","short","ushort","int","uint","uchar", argstr = "--outputVolumePixelType %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSROIAutoOutputSpec(TraitedSpec): + outputROIMaskVolume = File( exists = True) + outputVolume = File( exists = True) + + +class BRAINSROIAuto(CommandLine): + + input_spec = BRAINSROIAutoInputSpec + output_spec = BRAINSROIAutoOutputSpec + _cmd = " BRAINSROIAuto " + _outputs_filenames = {'outputVolume':'outputVolume.nii','outputROIMaskVolume':'outputROIMaskVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSROIAuto, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSResample.py b/AutoWorkup/BRAINSTools/BRAINSResample.py new file mode 100644 index 00000000..409a78cf --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSResample.py @@ -0,0 +1,51 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSResampleInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + referenceVolume = File( exists = True,argstr = "--referenceVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + pixelType = traits.Enum("float","short","ushort","int","uint","uchar","binary", argstr = "--pixelType %s") + deformationVolume = File( exists = True,argstr = "--deformationVolume %s") + warpTransform = File( exists = True,argstr = "--warpTransform %s") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + inverseTransform = traits.Bool( argstr = "--inverseTransform ") + defaultValue = traits.Float( argstr = "--defaultValue %f") + gridSpacing = InputMultiPath(traits.Int, sep = ",",argstr = "--gridSpacing %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSResampleOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class BRAINSResample(CommandLine): + + input_spec = BRAINSResampleInputSpec + output_spec = BRAINSResampleOutputSpec + _cmd = " BRAINSResample " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSResample, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/BRAINSTrimForegroundInDirection.py b/AutoWorkup/BRAINSTools/BRAINSTrimForegroundInDirection.py new file mode 100644 index 00000000..c8ddf481 --- /dev/null +++ b/AutoWorkup/BRAINSTools/BRAINSTrimForegroundInDirection.py @@ -0,0 +1,48 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class BRAINSTrimForegroundInDirectionInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + directionCode = traits.Int( argstr = "--directionCode %d") + otsuPercentileThreshold = traits.Float( argstr = "--otsuPercentileThreshold %f") + closingSize = traits.Int( argstr = "--closingSize %d") + headSizeLimit = traits.Float( argstr = "--headSizeLimit %f") + backgroundFillValueString = traits.Str( argstr = "--BackgroundFillValue %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class BRAINSTrimForegroundInDirectionOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class BRAINSTrimForegroundInDirection(CommandLine): + + input_spec = BRAINSTrimForegroundInDirectionInputSpec + output_spec = BRAINSTrimForegroundInDirectionOutputSpec + _cmd = " BRAINSTrimForegroundInDirection " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(BRAINSTrimForegroundInDirection, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/ESLR.py b/AutoWorkup/BRAINSTools/ESLR.py new file mode 100644 index 00000000..541e167b --- /dev/null +++ b/AutoWorkup/BRAINSTools/ESLR.py @@ -0,0 +1,49 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class ESLRInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + low = traits.Int( argstr = "--low %d") + high = traits.Int( argstr = "--high %d") + closingSize = traits.Int( argstr = "--closingSize %d") + openingSize = traits.Int( argstr = "--openingSize %d") + safetySize = traits.Int( argstr = "--safetySize %d") + preserveOutside = traits.Bool( argstr = "--preserveOutside ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class ESLROutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class ESLR(CommandLine): + + input_spec = ESLRInputSpec + output_spec = ESLROutputSpec + _cmd = " ESLR " + _outputs_filenames = {'outputVolume':'outputVolume.nii.gz'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(ESLR, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/GenerateLabelMapFromProbabilityMap.py b/AutoWorkup/BRAINSTools/GenerateLabelMapFromProbabilityMap.py new file mode 100644 index 00000000..8874cd4b --- /dev/null +++ b/AutoWorkup/BRAINSTools/GenerateLabelMapFromProbabilityMap.py @@ -0,0 +1,43 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class GenerateLabelMapFromProbabilityMapInputSpec(CommandLineInputSpec): + inputVolumes = InputMultiPath(File(exists=True), argstr = "--inputVolumes %s...") + outputLabelVolume = File( exists = True,argstr = "--outputLabelVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class GenerateLabelMapFromProbabilityMapOutputSpec(TraitedSpec): + pass + + +class GenerateLabelMapFromProbabilityMap(CommandLine): + + input_spec = GenerateLabelMapFromProbabilityMapInputSpec + output_spec = GenerateLabelMapFromProbabilityMapOutputSpec + _cmd = " GenerateLabelMapFromProbabilityMap " + _outputs_filenames = {} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(GenerateLabelMapFromProbabilityMap, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/GenerateSummedGradientImage.py b/AutoWorkup/BRAINSTools/GenerateSummedGradientImage.py new file mode 100644 index 00000000..7bbf59a9 --- /dev/null +++ b/AutoWorkup/BRAINSTools/GenerateSummedGradientImage.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class GenerateSummedGradientImageInputSpec(CommandLineInputSpec): + inputVolume1 = File( exists = True,argstr = "--inputVolume1 %s") + inputVolume2 = File( exists = True,argstr = "--inputVolume2 %s") + outputFileName = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputFileName %s") + MaximumGradient = traits.Bool( argstr = "--MaximumGradient ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class GenerateSummedGradientImageOutputSpec(TraitedSpec): + outputFileName = File( exists = True) + + +class GenerateSummedGradientImage(CommandLine): + + input_spec = GenerateSummedGradientImageInputSpec + output_spec = GenerateSummedGradientImageOutputSpec + _cmd = " GenerateSummedGradientImage " + _outputs_filenames = {'outputFileName':'outputFileName'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(GenerateSummedGradientImage, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/GradientAnisotropicDiffusionImageFilter.py b/AutoWorkup/BRAINSTools/GradientAnisotropicDiffusionImageFilter.py new file mode 100644 index 00000000..e88e93c8 --- /dev/null +++ b/AutoWorkup/BRAINSTools/GradientAnisotropicDiffusionImageFilter.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class GradientAnisotropicDiffusionImageFilterInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + numberOfIterations = traits.Int( argstr = "--numberOfIterations %d") + timeStep = traits.Float( argstr = "--timeStep %f") + conductance = traits.Float( argstr = "--conductance %f") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + + +class GradientAnisotropicDiffusionImageFilterOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class GradientAnisotropicDiffusionImageFilter(CommandLine): + + input_spec = GradientAnisotropicDiffusionImageFilterInputSpec + output_spec = GradientAnisotropicDiffusionImageFilterOutputSpec + _cmd = " GradientAnisotropicDiffusionImageFilter " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(GradientAnisotropicDiffusionImageFilter, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/VBRAINSDemonWarp.py b/AutoWorkup/BRAINSTools/VBRAINSDemonWarp.py new file mode 100644 index 00000000..0068bfe9 --- /dev/null +++ b/AutoWorkup/BRAINSTools/VBRAINSDemonWarp.py @@ -0,0 +1,83 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class VBRAINSDemonWarpInputSpec(CommandLineInputSpec): + movingVolume = InputMultiPath(File(exists=True), argstr = "--movingVolume %s...") + fixedVolume = InputMultiPath(File(exists=True), argstr = "--fixedVolume %s...") + inputPixelType = traits.Enum("float","short","ushort","int","uchar", argstr = "--inputPixelType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum("float","short","ushort","int","uchar", argstr = "--outputPixelType %s") + interpolationMode = traits.Enum("NearestNeighbor","Linear","ResampleInPlace","BSpline","WindowedSinc","Hamming","Cosine","Welch","Lanczos","Blackman", argstr = "--interpolationMode %s") + registrationFilterType = traits.Enum("Demons","FastSymmetricForces","Diffeomorphic","LogDemons","SymmetricLogDemons", argstr = "--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( argstr = "--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( argstr = "--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath(traits.Int, sep = ",",argstr = "--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath(traits.Int, sep = ",",argstr = "--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, sep = ",",argstr = "--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( argstr = "--histogramMatch ") + numberOfHistogramBins = traits.Int( argstr = "--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( argstr = "--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath(traits.Int, sep = ",",argstr = "--medianFilterSize %s") + initializeWithDisplacementField = File( exists = True,argstr = "--initializeWithDisplacementField %s") + initializeWithTransform = File( exists = True,argstr = "--initializeWithTransform %s") + makeBOBF = traits.Bool( argstr = "--makeBOBF ") + fixedBinaryVolume = File( exists = True,argstr = "--fixedBinaryVolume %s") + movingBinaryVolume = File( exists = True,argstr = "--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( argstr = "--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( argstr = "--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( argstr = "--backgroundFillValue %d") + seedForBOBF = InputMultiPath(traits.Int, sep = ",",argstr = "--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath(traits.Int, sep = ",",argstr = "--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( argstr = "--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath(traits.Int, sep = ",",argstr = "--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( argstr = "--outputNormalized ") + outputDebug = traits.Bool( argstr = "--outputDebug ") + weightFactors = InputMultiPath(traits.Float, sep = ",",argstr = "--weightFactors %s") + gradientType = traits.Enum("0","1","2", argstr = "--gradient_type %s") + smoothingUp = traits.Float( argstr = "--upFieldSmoothing %f") + maxStepLength = traits.Float( argstr = "--max_step_length %f") + turnOffDiffeomorph = traits.Bool( argstr = "--use_vanilla_dem ") + UseDebugImageViewer = traits.Bool( argstr = "--gui ") + PromptAfterImageSend = traits.Bool( argstr = "--promptUser ") + numberOfBCHApproximationTerms = traits.Int( argstr = "--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class VBRAINSDemonWarpOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + outputDisplacementFieldVolume = File( exists = True) + outputCheckerboardVolume = File( exists = True) + + +class VBRAINSDemonWarp(CommandLine): + + input_spec = VBRAINSDemonWarpInputSpec + output_spec = VBRAINSDemonWarpOutputSpec + _cmd = " VBRAINSDemonWarp " + _outputs_filenames = {'outputVolume':'outputVolume.nii','outputCheckerboardVolume':'outputCheckerboardVolume.nii','outputDisplacementFieldVolume':'outputDisplacementFieldVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(VBRAINSDemonWarp, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/WarpAllAtlas.py b/AutoWorkup/BRAINSTools/WarpAllAtlas.py new file mode 100644 index 00000000..94f990c1 --- /dev/null +++ b/AutoWorkup/BRAINSTools/WarpAllAtlas.py @@ -0,0 +1,108 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +""" + +Program: PINC/nipype/Wrappers/warpImageMultiTransform.py +Date: Tue Jan 3 13:35:44 2012 +Author: David Welch, dmwelch@NOSPAM.uiowa.edu # +Purpose: Wrap a Bash script to interface with Nipype + +Requirements: <<< Interface specifications >>> + +$ WarpAllAtlas_wrapper.sh + + +""" +from nipype.utils.filemanip import fname_presuffix +from nipype.interfaces.base import ( File, Directory, TraitedSpec, Interface, CommandLineInputSpec, CommandLine, + traits, isdefined ) + +def _gen_fname(self, basename, cwd=None, prefix=None): + """Generate a filename based on the given parameters. + + The filename will take the form: cwd/basename. + + Parameters + ---------- + basename : str + Filename to base the new filename on. + cwd : str + Path to prefix to the new filename. (default is os.getcwd()) + prefix : str + Prefix to add to the `basename`. (defaults is '' ) + + Returns + ------- + fname : str + New filename based on given parameters. + + """ + + if basename == '': + msg = 'Unable to generate filename for command %s. ' % self.cmd + msg += 'basename is not set!' + raise ValueError(msg) + if cwd is None: + cwd = os.getcwd() + if prefix is None: + prefix = '' + fname = fname_presuffix(basename, prefix = prefix, + use_ext = False, newpath = cwd) + return fname + + +### Node Interface +class WarpAllAtlasInputSpec( TraitedSpec ): + affine_transform = File( desc = "Affine Transform file", exists = True, mandatory = True) + deformation_field = File( desc = "Deformation Field file", exists = True, mandatory = True) + reference_image = File( desc = "Moving Reference Volume", exists = True, mandatory = True) + moving_atlas = File( desc = "Warped Volume path/filename", exists = True, mandatory = False ) + +class WarpAllAtlasOutputSpec(TraitedSpec): + deformed_atlas = File( desc = "Warped Volume path/filename", exists = True ) + +class WarpAllAtlas(Interface): + input_spec = WarpAllAtlasInputSpec + output_spec = WarpAllAtlasOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs['deformed_atlas'] = self.inputs.moving_atlas + if not isdefined(outputs["deformed_atlas"]) and isdefined(self.inputs.affine_transform): + outputs['deformed_atlas'] = _gen_fname( self.inputs.affine_transform , + suffix = "_WIMT", + use_ext = False) + return outputs + + +### CommandLine +class WarpAllAtlasCLInputSpec(CommandLineInputSpec): + affine_transform = File(desc="Affine Transform file", exists=True, mandatory=True, position=0, argstr="%s") + deformation_field = File(desc="Deformation Field file", exists=True, mandatory=True, position=1, argstr="%s") + reference_image = File(desc="Moving Reference Volume", exists=True, mandatory=True, position=2, argstr="%s") + moving_atlas = Directory(desc="Warped Volume path/filename", exists=True, mandatory=True, position=3, argstr="%s") + deformed_atlas = Directory(desc = "Warped Volume", mandatory=True, position=4, argstr="%s") + #, default_value="./Warp_Image_Multi_Transform_Output.nii.gz") + pass + +class WarpAllAtlasCLOutputSpec(CommandLineInputSpec): + deformed_atlas = Directory(desc = "Output Warped Volume", mandatory=True, argstr="%s") + pass + +class WarpAllAtlas(CommandLine): + _cmd = 'WarpAllAtlas_wrapper.sh' + input_spec = WarpAllAtlasCLInputSpec + output_spec = WarpAllAtlasCLOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs['deformed_atlas'] = self.inputs.deformed_atlas + if not isdefined(outputs["deformed_atlas"]) and isdefined(self.inputs.affine_transform): + outputs['deformed_atlas'] = _gen_fname( self.inputs.affine_transform , + suffix = "_WIMT", + use_ext = False) + return outputs + +if __name__ == '__main__': + warp = WarpAllAtlas(sys.argv) + warp.run() diff --git a/AutoWorkup/BRAINSTools/__init__.py b/AutoWorkup/BRAINSTools/__init__.py new file mode 100644 index 00000000..d38ba66d --- /dev/null +++ b/AutoWorkup/BRAINSTools/__init__.py @@ -0,0 +1,39 @@ +from BRAINSFit import BRAINSFit +from BRAINSABC import BRAINSABC +from BRAINSCut import BRAINSCut +from BRAINSAlignMSP import BRAINSAlignMSP +from BRAINSClipInferior import BRAINSClipInferior +from BRAINSConstellationDetector import BRAINSConstellationDetector +from BRAINSConstellationModeler import BRAINSConstellationModeler +from BRAINSLandmarkInitializer import BRAINSLandmarkInitializer +from BRAINSDemonWarp import BRAINSDemonWarp +from BRAINSMush import BRAINSMush +from BRAINSInitializedControlPoints import BRAINSInitializedControlPoints +from BRAINSLinearModelerEPCA import BRAINSLinearModelerEPCA +from BRAINSLmkTransform import BRAINSLmkTransform +from BRAINSMultiModeSegment import BRAINSMultiModeSegment +from BRAINSROIAuto import BRAINSROIAuto +from BRAINSResample import BRAINSResample +from BRAINSTrimForegroundInDirection import BRAINSTrimForegroundInDirection +from ESLR import ESLR +from GenerateLabelMapFromProbabilityMap import GenerateLabelMapFromProbabilityMap +from VBRAINSDemonWarp import VBRAINSDemonWarp +from extractNrrdVectorIndex import extractNrrdVectorIndex +from gtractAnisotropyMap import gtractAnisotropyMap +from gtractAverageBvalues import gtractAverageBvalues +from gtractClipAnisotropy import gtractClipAnisotropy +from gtractCoRegAnatomy import gtractCoRegAnatomy +from gtractConcatDwi import gtractConcatDwi +from gtractCopyImageOrientation import gtractCopyImageOrientation +from gtractCoregBvalues import gtractCoregBvalues +from gtractCostFastMarching import gtractCostFastMarching +from gtractImageConformity import gtractImageConformity +from gtractInvertBSplineTransform import gtractInvertBSplineTransform +from gtractInvertRigidTransform import gtractInvertRigidTransform +from gtractResampleAnisotropy import gtractResampleAnisotropy +from gtractResampleB0 import gtractResampleB0 +from gtractResampleCodeImage import gtractResampleCodeImage +from gtractResampleDWIInPlace import gtractResampleDWIInPlace +from gtractTensor import gtractTensor +from GradientAnisotropicDiffusionImageFilter import GradientAnisotropicDiffusionImageFilter +from GenerateSummedGradientImage import GenerateSummedGradientImage diff --git a/AutoWorkup/BRAINSTools/extractNrrdVectorIndex.py b/AutoWorkup/BRAINSTools/extractNrrdVectorIndex.py new file mode 100644 index 00000000..0488169f --- /dev/null +++ b/AutoWorkup/BRAINSTools/extractNrrdVectorIndex.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class extractNrrdVectorIndexInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + vectorIndex = traits.Int( argstr = "--vectorIndex %d") + setImageOrientation = traits.Enum("AsAcquired","Axial","Coronal","Sagittal", argstr = "--setImageOrientation %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class extractNrrdVectorIndexOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class extractNrrdVectorIndex(CommandLine): + + input_spec = extractNrrdVectorIndexInputSpec + output_spec = extractNrrdVectorIndexOutputSpec + _cmd = " extractNrrdVectorIndex " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(extractNrrdVectorIndex, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractAnisotropyMap.py b/AutoWorkup/BRAINSTools/gtractAnisotropyMap.py new file mode 100644 index 00000000..0d0e1378 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractAnisotropyMap.py @@ -0,0 +1,44 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractAnisotropyMapInputSpec(CommandLineInputSpec): + inputTensorVolume = File( exists = True,argstr = "--inputTensorVolume %s") + anisotropyType = traits.Enum("ADC","FA","RA","VR","AD","RD","LI", argstr = "--anisotropyType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractAnisotropyMapOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractAnisotropyMap(CommandLine): + + input_spec = gtractAnisotropyMapInputSpec + output_spec = gtractAnisotropyMapOutputSpec + _cmd = " gtractAnisotropyMap " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractAnisotropyMap, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractAverageBvalues.py b/AutoWorkup/BRAINSTools/gtractAverageBvalues.py new file mode 100644 index 00000000..c28827b3 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractAverageBvalues.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractAverageBvaluesInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + directionsTolerance = traits.Float( argstr = "--directionsTolerance %f") + averageB0only = traits.Bool( argstr = "--averageB0only ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractAverageBvaluesOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractAverageBvalues(CommandLine): + + input_spec = gtractAverageBvaluesInputSpec + output_spec = gtractAverageBvaluesOutputSpec + _cmd = " gtractAverageBvalues " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractAverageBvalues, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractClipAnisotropy.py b/AutoWorkup/BRAINSTools/gtractClipAnisotropy.py new file mode 100644 index 00000000..27bb814d --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractClipAnisotropy.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractClipAnisotropyInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + clipFirstSlice = traits.Bool( argstr = "--clipFirstSlice ") + clipLastSlice = traits.Bool( argstr = "--clipLastSlice ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractClipAnisotropyOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractClipAnisotropy(CommandLine): + + input_spec = gtractClipAnisotropyInputSpec + output_spec = gtractClipAnisotropyOutputSpec + _cmd = " gtractClipAnisotropy " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractClipAnisotropy, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractCoRegAnatomy.py b/AutoWorkup/BRAINSTools/gtractCoRegAnatomy.py new file mode 100644 index 00000000..1f499cf2 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractCoRegAnatomy.py @@ -0,0 +1,63 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractCoRegAnatomyInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + inputAnatomicalVolume = File( exists = True,argstr = "--inputAnatomicalVolume %s") + vectorIndex = traits.Int( argstr = "--vectorIndex %d") + inputRigidTransform = File( exists = True,argstr = "--inputRigidTransform %s") + outputTransformName = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransformName %s") + transformType = traits.Enum("Rigid","Bspline", argstr = "--transformType %s") + numberOfIterations = traits.Int( argstr = "--numberOfIterations %d") + gridSize = InputMultiPath(traits.Int, sep = ",",argstr = "--gridSize %s") + borderSize = traits.Int( argstr = "--borderSize %d") + numberOfHistogramBins = traits.Int( argstr = "--numberOfHistogramBins %d") + spatialScale = traits.Int( argstr = "--spatialScale %d") + convergence = traits.Float( argstr = "--convergence %f") + gradientTolerance = traits.Float( argstr = "--gradientTolerance %f") + maxBSplineDisplacement = traits.Float( argstr = "--maxBSplineDisplacement %f") + maximumStepSize = traits.Float( argstr = "--maximumStepSize %f") + minimumStepSize = traits.Float( argstr = "--minimumStepSize %f") + translationScale = traits.Float( argstr = "--translationScale %f") + relaxationFactor = traits.Float( argstr = "--relaxationFactor %f") + numberOfSamples = traits.Int( argstr = "--numberOfSamples %d") + useMomentsAlign = traits.Bool( argstr = "--useMomentsAlign ") + useGeometryAlign = traits.Bool( argstr = "--useGeometryAlign ") + useCenterOfHeadAlign = traits.Bool( argstr = "--useCenterOfHeadAlign ") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractCoRegAnatomyOutputSpec(TraitedSpec): + outputTransformName = File( exists = True) + + +class gtractCoRegAnatomy(CommandLine): + + input_spec = gtractCoRegAnatomyInputSpec + output_spec = gtractCoRegAnatomyOutputSpec + _cmd = " gtractCoRegAnatomy " + _outputs_filenames = {'outputTransformName':'outputTransformName.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractCoRegAnatomy, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractConcatDwi.py b/AutoWorkup/BRAINSTools/gtractConcatDwi.py new file mode 100644 index 00000000..ed62f1bd --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractConcatDwi.py @@ -0,0 +1,43 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractConcatDwiInputSpec(CommandLineInputSpec): + inputVolume = InputMultiPath(File(exists=True), argstr = "--inputVolume %s...") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractConcatDwiOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractConcatDwi(CommandLine): + + input_spec = gtractConcatDwiInputSpec + output_spec = gtractConcatDwiOutputSpec + _cmd = " gtractConcatDwi " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractConcatDwi, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractCopyImageOrientation.py b/AutoWorkup/BRAINSTools/gtractCopyImageOrientation.py new file mode 100644 index 00000000..d1910bc4 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractCopyImageOrientation.py @@ -0,0 +1,44 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractCopyImageOrientationInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractCopyImageOrientationOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractCopyImageOrientation(CommandLine): + + input_spec = gtractCopyImageOrientationInputSpec + output_spec = gtractCopyImageOrientationOutputSpec + _cmd = " gtractCopyImageOrientation " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractCopyImageOrientation, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractCoregBvalues.py b/AutoWorkup/BRAINSTools/gtractCoregBvalues.py new file mode 100644 index 00000000..835e5609 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractCoregBvalues.py @@ -0,0 +1,56 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractCoregBvaluesInputSpec(CommandLineInputSpec): + movingVolume = File( exists = True,argstr = "--movingVolume %s") + fixedVolume = File( exists = True,argstr = "--fixedVolume %s") + fixedVolumeIndex = traits.Int( argstr = "--fixedVolumeIndex %d") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + outputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransform %s") + eddyCurrentCorrection = traits.Bool( argstr = "--eddyCurrentCorrection ") + numberOfIterations = traits.Int( argstr = "--numberOfIterations %d") + numberOfSpatialSamples = traits.Int( argstr = "--numberOfSpatialSamples %d") + relaxationFactor = traits.Float( argstr = "--relaxationFactor %f") + maximumStepSize = traits.Float( argstr = "--maximumStepSize %f") + minimumStepSize = traits.Float( argstr = "--minimumStepSize %f") + spatialScale = traits.Float( argstr = "--spatialScale %f") + registerB0Only = traits.Bool( argstr = "--registerB0Only ") + debugLevel = traits.Int( argstr = "--debugLevel %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractCoregBvaluesOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + outputTransform = File( exists = True) + + +class gtractCoregBvalues(CommandLine): + + input_spec = gtractCoregBvaluesInputSpec + output_spec = gtractCoregBvaluesOutputSpec + _cmd = " gtractCoregBvalues " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd','outputTransform':'outputTransform.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractCoregBvalues, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractCostFastMarching.py b/AutoWorkup/BRAINSTools/gtractCostFastMarching.py new file mode 100644 index 00000000..b14b83fd --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractCostFastMarching.py @@ -0,0 +1,51 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractCostFastMarchingInputSpec(CommandLineInputSpec): + inputTensorVolume = File( exists = True,argstr = "--inputTensorVolume %s") + inputAnisotropyVolume = File( exists = True,argstr = "--inputAnisotropyVolume %s") + inputStartingSeedsLabelMapVolume = File( exists = True,argstr = "--inputStartingSeedsLabelMapVolume %s") + startingSeedsLabel = traits.Int( argstr = "--startingSeedsLabel %d") + outputCostVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputCostVolume %s") + outputSpeedVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputSpeedVolume %s") + anisotropyWeight = traits.Float( argstr = "--anisotropyWeight %f") + stoppingValue = traits.Float( argstr = "--stoppingValue %f") + seedThreshold = traits.Float( argstr = "--seedThreshold %f") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractCostFastMarchingOutputSpec(TraitedSpec): + outputCostVolume = File( exists = True) + outputSpeedVolume = File( exists = True) + + +class gtractCostFastMarching(CommandLine): + + input_spec = gtractCostFastMarchingInputSpec + output_spec = gtractCostFastMarchingOutputSpec + _cmd = " gtractCostFastMarching " + _outputs_filenames = {'outputCostVolume':'outputCostVolume.nrrd','outputSpeedVolume':'outputSpeedVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractCostFastMarching, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractImageConformity.py b/AutoWorkup/BRAINSTools/gtractImageConformity.py new file mode 100644 index 00000000..52b3af57 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractImageConformity.py @@ -0,0 +1,44 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractImageConformityInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractImageConformityOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractImageConformity(CommandLine): + + input_spec = gtractImageConformityInputSpec + output_spec = gtractImageConformityOutputSpec + _cmd = " gtractImageConformity " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractImageConformity, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractInvertBSplineTransform.py b/AutoWorkup/BRAINSTools/gtractInvertBSplineTransform.py new file mode 100644 index 00000000..2eb3105b --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractInvertBSplineTransform.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractInvertBSplineTransformInputSpec(CommandLineInputSpec): + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + inputTransform = File( exists = True,argstr = "--inputTransform %s") + outputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransform %s") + landmarkDensity = InputMultiPath(traits.Int, sep = ",",argstr = "--landmarkDensity %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractInvertBSplineTransformOutputSpec(TraitedSpec): + outputTransform = File( exists = True) + + +class gtractInvertBSplineTransform(CommandLine): + + input_spec = gtractInvertBSplineTransformInputSpec + output_spec = gtractInvertBSplineTransformOutputSpec + _cmd = " gtractInvertBSplineTransform " + _outputs_filenames = {'outputTransform':'outputTransform.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractInvertBSplineTransform, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractInvertDeformationField.py b/AutoWorkup/BRAINSTools/gtractInvertDeformationField.py new file mode 100644 index 00000000..fdb9360f --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractInvertDeformationField.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractInvertDeformationFieldInputSpec(CommandLineInputSpec): + baseImage = File( exists = True,argstr = "--baseImage %s") + deformationImage = File( exists = True,argstr = "--deformationImage %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + subsamplingFactor = traits.Int( argstr = "--subsamplingFactor %d") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractInvertDeformationFieldOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractInvertDeformationField(CommandLine): + + input_spec = gtractInvertDeformationFieldInputSpec + output_spec = gtractInvertDeformationFieldOutputSpec + _cmd = " gtractInvertDeformationField " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractInvertDeformationField, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractInvertRigidTransform.py b/AutoWorkup/BRAINSTools/gtractInvertRigidTransform.py new file mode 100644 index 00000000..34ee9936 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractInvertRigidTransform.py @@ -0,0 +1,43 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractInvertRigidTransformInputSpec(CommandLineInputSpec): + inputTransform = File( exists = True,argstr = "--inputTransform %s") + outputTransform = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputTransform %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractInvertRigidTransformOutputSpec(TraitedSpec): + outputTransform = File( exists = True) + + +class gtractInvertRigidTransform(CommandLine): + + input_spec = gtractInvertRigidTransformInputSpec + output_spec = gtractInvertRigidTransformOutputSpec + _cmd = " gtractInvertRigidTransform " + _outputs_filenames = {'outputTransform':'outputTransform.mat'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractInvertRigidTransform, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractResampleAnisotropy.py b/AutoWorkup/BRAINSTools/gtractResampleAnisotropy.py new file mode 100644 index 00000000..ce32f95d --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractResampleAnisotropy.py @@ -0,0 +1,46 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractResampleAnisotropyInputSpec(CommandLineInputSpec): + inputAnisotropyVolume = File( exists = True,argstr = "--inputAnisotropyVolume %s") + inputAnatomicalVolume = File( exists = True,argstr = "--inputAnatomicalVolume %s") + inputTransform = File( exists = True,argstr = "--inputTransform %s") + transformType = traits.Enum("Rigid","B-Spline", argstr = "--transformType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractResampleAnisotropyOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractResampleAnisotropy(CommandLine): + + input_spec = gtractResampleAnisotropyInputSpec + output_spec = gtractResampleAnisotropyOutputSpec + _cmd = " gtractResampleAnisotropy " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractResampleAnisotropy, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractResampleB0.py b/AutoWorkup/BRAINSTools/gtractResampleB0.py new file mode 100644 index 00000000..4bb9944a --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractResampleB0.py @@ -0,0 +1,47 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractResampleB0InputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + inputAnatomicalVolume = File( exists = True,argstr = "--inputAnatomicalVolume %s") + inputTransform = File( exists = True,argstr = "--inputTransform %s") + vectorIndex = traits.Int( argstr = "--vectorIndex %d") + transformType = traits.Enum("Rigid","B-Spline", argstr = "--transformType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractResampleB0OutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractResampleB0(CommandLine): + + input_spec = gtractResampleB0InputSpec + output_spec = gtractResampleB0OutputSpec + _cmd = " gtractResampleB0 " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractResampleB0, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractResampleCodeImage.py b/AutoWorkup/BRAINSTools/gtractResampleCodeImage.py new file mode 100644 index 00000000..1493794f --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractResampleCodeImage.py @@ -0,0 +1,46 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractResampleCodeImageInputSpec(CommandLineInputSpec): + inputCodeVolume = File( exists = True,argstr = "--inputCodeVolume %s") + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + inputTransform = File( exists = True,argstr = "--inputTransform %s") + transformType = traits.Enum("Rigid","Affine","B-Spline","Inverse-B-Spline","None", argstr = "--transformType %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractResampleCodeImageOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractResampleCodeImage(CommandLine): + + input_spec = gtractResampleCodeImageInputSpec + output_spec = gtractResampleCodeImageOutputSpec + _cmd = " gtractResampleCodeImage " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractResampleCodeImage, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractResampleDWIInPlace.py b/AutoWorkup/BRAINSTools/gtractResampleDWIInPlace.py new file mode 100644 index 00000000..a005187f --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractResampleDWIInPlace.py @@ -0,0 +1,45 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractResampleDWIInPlaceInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + inputTransform = File( exists = True,argstr = "--inputTransform %s") + debugLevel = traits.Int( argstr = "--debugLevel %d") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractResampleDWIInPlaceOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractResampleDWIInPlace(CommandLine): + + input_spec = gtractResampleDWIInPlaceInputSpec + output_spec = gtractResampleDWIInPlaceOutputSpec + _cmd = " gtractResampleDWIInPlace " + _outputs_filenames = {'outputVolume':'outputVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractResampleDWIInPlace, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractTensor.py b/AutoWorkup/BRAINSTools/gtractTensor.py new file mode 100644 index 00000000..dc8f331d --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractTensor.py @@ -0,0 +1,52 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractTensorInputSpec(CommandLineInputSpec): + inputVolume = File( exists = True,argstr = "--inputVolume %s") + outputVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputVolume %s") + medianFilterSize = InputMultiPath(traits.Int, sep = ",",argstr = "--medianFilterSize %s") + maskProcessingMode = traits.Enum("NOMASK","ROIAUTO","ROI", argstr = "--maskProcessingMode %s") + maskVolume = File( exists = True,argstr = "--maskVolume %s") + backgroundSuppressingThreshold = traits.Int( argstr = "--backgroundSuppressingThreshold %d") + resampleIsotropic = traits.Bool( argstr = "--resampleIsotropic ") + voxelSize = traits.Float( argstr = "--size %f") + b0Index = traits.Int( argstr = "--b0Index %d") + applyMeasurementFrame = traits.Bool( argstr = "--applyMeasurementFrame ") + ignoreIndex = InputMultiPath(traits.Int, sep = ",",argstr = "--ignoreIndex %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractTensorOutputSpec(TraitedSpec): + outputVolume = File( exists = True) + + +class gtractTensor(CommandLine): + + input_spec = gtractTensorInputSpec + output_spec = gtractTensorOutputSpec + _cmd = " gtractTensor " + _outputs_filenames = {'outputVolume':'outputVolume.nrrd'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractTensor, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/BRAINSTools/gtractTransformToDeformationField.py b/AutoWorkup/BRAINSTools/gtractTransformToDeformationField.py new file mode 100644 index 00000000..0e7a71e8 --- /dev/null +++ b/AutoWorkup/BRAINSTools/gtractTransformToDeformationField.py @@ -0,0 +1,44 @@ +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os + +class gtractTransformToDeformationFieldInputSpec(CommandLineInputSpec): + inputTransform = File( exists = True,argstr = "--inputTransform %s") + inputReferenceVolume = File( exists = True,argstr = "--inputReferenceVolume %s") + outputDeformationFieldVolume = traits.Either(traits.Bool, File(), hash_files = False,argstr = "--outputDeformationFieldVolume %s") + numberOfThreads = traits.Int( argstr = "--numberOfThreads %d") + + +class gtractTransformToDeformationFieldOutputSpec(TraitedSpec): + outputDeformationFieldVolume = File( exists = True) + + +class gtractTransformToDeformationField(CommandLine): + + input_spec = gtractTransformToDeformationFieldInputSpec + output_spec = gtractTransformToDeformationFieldOutputSpec + _cmd = " gtractTransformToDeformationField " + _outputs_filenames = {'outputDeformationFieldVolume':'outputDeformationFieldVolume.nii'} + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(gtractTransformToDeformationField, self)._format_arg(name, spec, value) + diff --git a/AutoWorkup/README b/AutoWorkup/README new file mode 100644 index 00000000..c558dca2 --- /dev/null +++ b/AutoWorkup/README @@ -0,0 +1,13 @@ +Inital version of BRAINS AutoWorkup built on Nipype. +Currently very rough, use at your own risk! + +To use the code, build BRAINSTools with ITKv4 on. + +Then install the nipype version in the BRAINSia github account. + +The file Template.config should be copied and modified to define the +experiment that should be run. + +python baw_exp.py -processingLevel 2 -ExperimentConfig Template.config -pe IPL_ENVIRONMENT + + diff --git a/AutoWorkup/Template.config b/AutoWorkup/Template.config new file mode 100644 index 00000000..50aa2049 --- /dev/null +++ b/AutoWorkup/Template.config @@ -0,0 +1,30 @@ +# The configuration file consists of sections, led by a [section] header and followed by name: value entries, +# with continuations in the style of RFC 822 (see section 3.1.1, ?~@~\LONG HEADER FIELDS"); +# +# time python baw_exp.py -processingLevel 2 -ExperimentConfig Template.config -pe IPL_ENVIRONMENT +# +# The intent of this configuraiton file is to define all the information needed to completely run an experiment. +# +[EXPERIMENT_DATA] +# A formatted csv file decribing the data sets one per line +# 'PROJECT,SUBJ,SESSION,"[T1_1.nii.gz,T1_2.nii.gz]","[T2_1.nii.gz]"' +SESSION_DB=subject_db.csv +# The desired output directory for this experiment +EXPERIMENTNAME=B4AUTO.test + +[IPL_ENVIRONMENT] +# Where to find BRAINSTools +BRAINSTOOLS_PATH=/Users/johnsonhj/src/BSA-Darwin-clang +# Where SimpleITK, required nipype, and other non-standard python packages reside +PYTHON_AUX_PATHS=/Users/johnsonhj/local/python-site-packages:/Users/johnsonhj/local/python-site-packages/lib/python2.7/site-packages +# Paths that need to be configured to find tools needed to run this workflow +PROGRAM_PATHS=%(BRAINSTOOLS_PATH)s/lib:%(BRAINSTOOLS_PATH)s/bin +# The path to the reference atlas spact to be used in this analysis by all BRAINSTools +ATLASPATH=%(BRAINSTOOLS_PATH)s/ReferenceAtlas-build/Atlas/Atlas_20120104 +# The path to the model files to be used by BCD. +BCDMODELPATH=%(BRAINSTOOLS_PATH)s/BRAINSTools-build/ExternalData/TestData +# The prefix to add to all image files in the $(SESSION_DB) to account +# for different file system mount points +MOUNTPREFIX="" +# The base directory where all experiments of this type go +BASEOUTPUTDIR=/scratch/BRAINSAutoWorkUpTest/ diff --git a/AutoWorkup/WorkupT1T2.py b/AutoWorkup/WorkupT1T2.py new file mode 100644 index 00000000..76e921b5 --- /dev/null +++ b/AutoWorkup/WorkupT1T2.py @@ -0,0 +1,775 @@ +#!/usr/bin/python +################################################################################# +## Program: BRAINS (Brain Research: Analysis of Images, Networks, and Systems) +## Language: Python +## +## Author: Hans J. Johnson +## +## This software is distributed WITHOUT ANY WARRANTY; without even +## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +## PURPOSE. See the above copyright notices for more information. +## +################################################################################# + +import os +import csv +import sys +import string +import argparse +#"""Import necessary modules from nipype.""" +#from nipype.utils.config import config +#config.set('logging', 'log_to_file', 'false') +#config.set_log_dir(os.getcwd()) +#--config.set('logging', 'workflow_level', 'DEBUG') +#--config.set('logging', 'interface_level', 'DEBUG') +#--config.set('execution','remove_unnecessary_outputs','false') + +from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory +from nipype.interfaces.base import traits, isdefined, BaseInterface +from nipype.interfaces.utility import Merge, Split, Function, Rename, IdentityInterface +import nipype.interfaces.io as nio # Data i/o +import nipype.pipeline.engine as pe # pypeline engine +from nipype.interfaces.freesurfer import ReconAll + +from nipype.utils.misc import package_check +#package_check('nipype', '5.4', 'tutorial1') ## HACK: Check nipype version +package_check('numpy', '1.3', 'tutorial1') +package_check('scipy', '0.7', 'tutorial1') +package_check('networkx', '1.0', 'tutorial1') +package_check('IPython', '0.10', 'tutorial1') + +from BRAINSTools.BRAINSConstellationDetector import * +from BRAINSTools.BRAINSABC import * +from BRAINSTools.BRAINSDemonWarp import * +from BRAINSTools.BRAINSFit import * +from BRAINSTools.BRAINSMush import * +from BRAINSTools.BRAINSResample import * +from BRAINSTools.BRAINSROIAuto import * +from BRAINSTools.BRAINSLandmarkInitializer import * +from BRAINSTools.BRAINSCut import * +from BRAINSTools.GradientAnisotropicDiffusionImageFilter import * +from BRAINSTools.GenerateSummedGradientImage import * +from BRAINSTools.ANTSWrapper import * +#from BRAINSTools.WarpImageMultiTransform import * +#from BRAINSTools.WarpAllAtlas import * + +####################### HACK: Needed to make some global variables for quick +####################### processing needs +#Generate by running a file system list "ls -1 $AtlasDir *.nii.gz *.xml *.fcsv *.wgts" +atlas_file_list="AtlasPVDefinition.xml ALLPVAIR.nii.gz ALLPVBASALTISSUE.nii.gz ALLPVCRBLGM.nii.gz ALLPVCRBLWM.nii.gz ALLPVCSF.nii.gz ALLPVNOTCSF.nii.gz ALLPVNOTGM.nii.gz ALLPVNOTVB.nii.gz ALLPVNOTWM.nii.gz ALLPVSURFGM.nii.gz ALLPVVB.nii.gz ALLPVWM.nii.gz avg_t1.nii.gz avg_t2.nii.gz tempNOTVBBOX.nii.gz template_ABC_lables.nii.gz template_WMPM2_labels.nii.gz template_WMPM2_labels.txt template_brain.nii.gz template_cerebellum.nii.gz template_class.nii.gz template_headregion.nii.gz template_leftHemisphere.nii.gz template_nac_lables.nii.gz template_nac_lables.txt template_rightHemisphere.nii.gz template_t1.nii.gz template_t1_clipped.nii.gz template_t2.nii.gz template_t2_clipped.nii.gz template_ventricles.nii.gz probabilityMaps/l_caudate_ProbabilityMap.nii.gz probabilityMaps/r_caudate_ProbabilityMap.nii.gz probabilityMaps/l_hippocampus_ProbabilityMap.nii.gz probabilityMaps/r_hippocampus_ProbabilityMap.nii.gz probabilityMaps/l_putamen_ProbabilityMap.nii.gz probabilityMaps/r_putamen_ProbabilityMap.nii.gz probabilityMaps/l_thalamus_ProbabilityMap.nii.gz probabilityMaps/r_thalamus_ProbabilityMap.nii.gz spatialImages/phi.nii.gz spatialImages/rho.nii.gz spatialImages/theta.nii.gz" +atlas_file_names=atlas_file_list.split(' ') +atlas_file_names=["AtlasPVDefinition.xml","ALLPVAIR.nii.gz", + "ALLPVBASALTISSUE.nii.gz","ALLPVCRBLGM.nii.gz", + "ALLPVCRBLWM.nii.gz","ALLPVCSF.nii.gz","ALLPVNOTCSF.nii.gz", + "ALLPVNOTGM.nii.gz","ALLPVNOTVB.nii.gz","ALLPVNOTWM.nii.gz", + "ALLPVSURFGM.nii.gz","ALLPVVB.nii.gz","ALLPVWM.nii.gz", + "avg_t1.nii.gz","avg_t2.nii.gz","tempNOTVBBOX.nii.gz", + "template_ABC_lables.nii.gz","template_WMPM2_labels.nii.gz", + "template_WMPM2_labels.txt","template_brain.nii.gz", + "template_cerebellum.nii.gz","template_class.nii.gz", + "template_headregion.nii.gz","template_leftHemisphere.nii.gz", + "template_nac_lables.nii.gz","template_nac_lables.txt", + "template_rightHemisphere.nii.gz","template_t1.nii.gz", + "template_t1_clipped.nii.gz","template_t2.nii.gz", + "template_t2_clipped.nii.gz","template_ventricles.nii.gz", + "template_landmarks.fcsv","template_landmark_weights.csv", +"probabilityMaps/l_caudate_ProbabilityMap.nii.gz", +"probabilityMaps/r_caudate_ProbabilityMap.nii.gz", +"probabilityMaps/l_hippocampus_ProbabilityMap.nii.gz", +"probabilityMaps/r_hippocampus_ProbabilityMap.nii.gz", +"probabilityMaps/l_putamen_ProbabilityMap.nii.gz", +"probabilityMaps/r_putamen_ProbabilityMap.nii.gz", +"probabilityMaps/l_thalamus_ProbabilityMap.nii.gz", +"probabilityMaps/r_thalamus_ProbabilityMap.nii.gz", +"spatialImages/phi.nii.gz", +"spatialImages/rho.nii.gz", +"spatialImages/theta.nii.gz" + ] + + +## Remove filename extensions for images, but replace . with _ for other file types +atlas_file_keys=[os.path.basename(fn).replace('.nii.gz','').replace('.','_') for fn in atlas_file_names] +atlas_outputs_filename_match = dict(zip(atlas_file_keys,atlas_file_names)) + + +############################################################################# +############################################################################# +## Utility functions for the pipeline +############################################################################# +############################################################################# +def get_first_T1_and_T2(in_files,T1_count): + ''' + Returns the first T1 and T2 file in in_files, based on offset in T1_count. + ''' + return in_files[0],in_files[T1_count] + +def GetExtensionlessBaseName(filename): + ''' + Get the filename without the extension. Works for .ext and .ext.gz + ''' + import os + currBaseName = os.path.basename(filename) + currExt = os.path.splitext(currBaseName)[1] + currBaseName = os.path.splitext(currBaseName)[0] + if currExt == ".gz": + currBaseName = os.path.splitext(currBaseName)[0] + currExt = os.path.splitext(currBaseName)[1] + return currBaseName + + +def MakeAtlasNode(atlasDirectory): + BAtlas = pe.Node(interface=nio.DataGrabber(outfields=atlas_file_keys), + name='BAtlas') + BAtlas.inputs.base_directory = atlasDirectory + BAtlas.inputs.template = '*' + ## Prefix every filename with atlasDirectory + atlas_search_paths=['{0}'.format(fn) for fn in atlas_file_names] + BAtlas.inputs.field_template = dict(zip(atlas_file_keys,atlas_search_paths)) + ## Give 'atlasDirectory' as the substitution argument + atlas_template_args_match=[ [[]] for i in atlas_file_keys ] ##build a list of proper lenght with repeated entries + BAtlas.inputs.template_args = dict(zip(atlas_file_keys,atlas_template_args_match)) + return BAtlas + +def create_BRAINSCut_XML(rho,phi,theta,model, + r_probabilityMap,l_probabilityMap, + atlasT1,atlasBrain, + subjT1,subjT2, + subjT1GAD,subjT2GAD,subjSGGAD,subjBrain, + atlasToSubj, + output_dir): + import re + import os + print "*"*80 + print rho + print phi + print theta + print model + print r_probabilityMap + print l_probabilityMap + structure = re.search("r_(\w+)_ProbabilityMap",os.path.basename(r_probabilityMap)).group(1) + + ## The model file name is auto-generated, and needs to be split apart here + basemodel =re.search("(.*{structure}Model.*\.txt)(00[0-9]*)".format(structure=structure),model).group(1) + EpochIterations=re.search("(.*{structure}Model.*\.txt)(00[0-9]*)".format(structure=structure),model).group(2) + EpochIterations.lstrip('0') + + ## HACK: Needed to make neural networks easier to use. This information should be embeded in the model file. + HiddenNodeDict={'caudate':"14",'putamen':"20",'hippocampus':"20",'thalamus':"14"} + + print "^^"*80 + print "^^"*80 + print "^^"*80 + print "^^"*80 + print basemodel + print EpochIterations + NumberOfHiddenNodes=HiddenNodeDict[structure] + + EXTRA_FLAGS="" + if structure in [ 'putamen','hippocampus']: + EXTRA_FLAGS=""" + + """ + + XMLSTRING=""" + + + + + + + + + + {EXTRA_FLAGS} + + + + + + + + + + + + + + + + + + +""".format(structure=structure,rho=rho,phi=phi,theta=theta, + basemodel=basemodel,EpochIterations=EpochIterations,NumberOfHiddenNodes=NumberOfHiddenNodes, + r_probabilityMap=r_probabilityMap,l_probabilityMap=l_probabilityMap, + atlasT1=atlasT1,atlasBrain=atlasBrain, + subjT1=subjT1,subjT2=subjT2, + subjT1GAD=subjT1GAD,subjT2GAD=subjT2GAD,subjSGGAD=subjSGGAD,subjBrain=subjBrain, + EXTRA_FLAGS=EXTRA_FLAGS, + atlasToSubj=atlasToSubj, + output_dir=output_dir) + + if not os.path.exists(output_dir): + os.mkdir(output_dir) + #xml_filename = os.path.join(output_dir,'%s.xml' % structure) + xml_filename = '%s.xml' % structure + xml_file = open(xml_filename,'w') + #xml_file.write(etree.tostring(xml_output, pretty_print=True)) + xml_file.write(XMLSTRING) + xml_file.close() + + r_struct_fname="{output_dir}/r_{structure}_seg.nii.gz".format(output_dir=output_dir,structure=structure) + l_struct_fname="{output_dir}/l_{structure}_seg.nii.gz".format(output_dir=output_dir,structure=structure) + return os.path.realpath(xml_filename), [ r_struct_fname, l_struct_fname ] + + +def get_list_element( nestedList, index ): + return nestedList[index] + +class AutoVivification(dict): + """Implementation of perl's autovivification feature.""" + def __getitem__(self, item): + try: + return dict.__getitem__(self, item) + except KeyError: + value = self[item] = type(self)() + return value + +def getFirstT1(uid, dbfile): + from cPickle import load + with open(dbfile) as fp: + db = load(fp) + print("uid:= {0}, dbfile: {1}".format(uid,dbfile)) + print("result:= {0}".format(db[uid]["T1s"])) + return db[uid]["T1s"][0] + +def getT1s(uid, dbfile): + from cPickle import load + with open(dbfile) as fp: + db = load(fp) + #print("uid:= {0}, dbfile: {1}".format(uid,dbfile)) + #print("result:= {0}".format(db[uid]["T1s"])) + return db[uid]["T1s"] + +def getT1sLength(uid, dbfile): + from cPickle import load + with open(dbfile) as fp: + db = load(fp) + #print("uid:= {0}, dbfile: {1}".format(uid,dbfile)) + #print("result:= {0}".format(db[uid]["T1s"])) + return len(db[uid]["T1s"]) + +def getT2s(uid, dbfile): + from cPickle import load + with open(dbfile) as fp: + db = load(fp) + #print("uid:= {0}, dbfile: {1}".format(uid,dbfile)) + #print("result:= {0}".format(db[uid]["T1s"])) + return db[uid]["T2s"] + +def getT1sT2s(uid, dbfile,altT1): + from cPickle import load + with open(dbfile) as fp: + db = load(fp) + #print("uid:= {0}, dbfile: {1}".format(uid,dbfile)) + #print("result:= {0}".format(db[uid]["T1s"])) + temp=db[uid]["T1s"] + temp.append(db[uid]["T2s"]) + temp[0]=altT1 + return temp + + + + +########################################################################### +########################################################################### +########################################################################### +########################################################################### +########################################################################### +########################################################################### +## WorkupT1T2 is the main workflow to be run +########################################################################### +########################################################################### +########################################################################### +########################################################################### +########################################################################### +def WorkupT1T2(processingLevel,mountPrefix,ExperimentBaseDirectory, subject_data_file, atlas_fname_wpath, BCD_model_path, + InterpolationMode="Linear", Mode=10,DwiList=[] ): + processingLevel=int(processingLevel) + """ + Run autoworkup on all subjects data defined in the subject_data_file + + This is the main function to call when processing a data set with T1 & T2 + data. ExperimentBaseDirectory is the base of the directory to place results, T1Images & T2Images + are the lists of images to be used in the auto-workup. atlas_fname_wpath is + the path and filename of the atlas to use. + """ + subjData=csv.reader(open(subject_data_file,'rb'), delimiter=',', quotechar='"') + myDB=dict() + multiLevel=AutoVivification() + for row in subjData: + currDict=dict() + validEntry=True + if len(row) == 5: + site=row[0] + subj=row[1] + session=row[2] + T1s=eval(row[3]) + T2s=eval(row[4]) + fullT1s=[ mountPrefix+i for i in T1s] + fullT2s=[ mountPrefix+i for i in T2s] + currDict['T1s']=fullT1s + currDict['T2s']=fullT2s + currDict['site']=site + currDict['subj']=subj + if len(fullT1s) < 1: + print("Invalid Entry! {0}".format(currDict)) + validEntry=False + if len(fullT2s) < 1: + print("Invalid Entry! {0}".format(currDict)) + validEntry=False + for i in fullT1s: + if not os.path.exists(i): + print("Missing File: {0}".format(i)) + validEntry=False + for i in fullT2s: + if not os.path.exists(i): + print("Missing File: {0}".format(i)) + validEntry=False + + if validEntry == True: + myDB[session]=currDict + UNIQUE_ID=site+"_"+subj+"_"+session + multiLevel[UNIQUE_ID]=currDict + from cPickle import dump + dump(multiLevel, open('db.tmp','w')) + + ########### PIPELINE INITIALIZATION ############# + baw200 = pe.Workflow(name="BAW_20120104_workflow") + baw200.config['execution'] = { + 'plugin':'Linear', + #'stop_on_first_crash':'true', + 'stop_on_first_crash':'false', + 'stop_on_first_rerun': 'false', + 'hash_method': 'timestamp', + 'single_thread_matlab':'true', + 'remove_unnecessary_outputs':'false', + 'use_relative_paths':'false', + 'remove_node_directories':'false', + 'local_hash_check':'true' + } + #'job_finished_timeout':3700 + baw200.config['logging'] = { + 'workflow_level':'DEBUG', + 'filemanip_level':'DEBUG', + 'interface_level':'DEBUG', + 'log_directory': ExperimentBaseDirectory + } + baw200.base_dir = ExperimentBaseDirectory + + """TODO: Determine if we want to pass subjectID and scanID, always require full + paths, get them from the output path, or something else. + """ + siteSource = pe.Node(interface=IdentityInterface(fields=['uid']),name='99_siteSource') + siteSource.iterables = ('uid', multiLevel.keys() ) + + BAtlas = MakeAtlasNode(atlas_fname_wpath) ## Call function to create node + + ######################################################## + # Run ACPC Detect on first T1 Image - Base Image + ######################################################## + BCD = pe.Node(interface=BRAINSConstellationDetector(), name="01_BCD") + ## Use program default BCD.inputs.inputTemplateModel = T1ACPCModelFile + ##BCD.inputs.outputVolume = "BCD_OUT" + "_ACPC_InPlace.nii.gz" #$# T1AcpcImageList + BCD.inputs.outputTransform = "BCD" + "_Original2ACPC_transform.mat" + BCD.inputs.outputResampledVolume = "BCD" + "_ACPC.nii.gz" + BCD.inputs.outputLandmarksInInputSpace = "BCD" + "_Original.fcsv" + BCD.inputs.outputLandmarksInACPCAlignedSpace = "BCD" + "_ACPC_Landmarks.fcsv" + BCD.inputs.outputMRML = "BCD" + "_ACPC_Scene.mrml" + BCD.inputs.interpolationMode = InterpolationMode + BCD.inputs.houghEyeDetectorMode = 1 # Look for dark eyes like on a T1 image, 0=Look for bright eyes like in a T2 image + BCD.inputs.acLowerBound = 80.0 # Chop the data set 80mm below the AC PC point. + BCD.inputs.llsModel = os.path.join(BCD_model_path,'LLSModel-2ndVersion.hdf5') + BCD.inputs.inputTemplateModel = os.path.join(BCD_model_path,'T1-2ndVersion.mdl') + + # Entries below are of the form: + baw200.connect( [ (siteSource, BCD, [(('uid', getFirstT1, os.path.join(os.getcwd(), 'db.tmp') ), 'inputVolume')] ), ]) + + if processingLevel > 0: + ######################################################## + # Run BLI atlas_to_subject + ######################################################## + BLI = pe.Node(interface=BRAINSLandmarkInitializer(), name="05_BLI") + BLI.inputs.outputTransformFilename = "landmarkInitializer_atlas_to_subject_transform.mat" + + baw200.connect([ + (BCD,BLI,[('outputLandmarksInACPCAlignedSpace','inputFixedLandmarkFilename')]), + ]) + baw200.connect([ + (BAtlas,BLI,[('template_landmarks_fcsv','inputMovingLandmarkFilename')]), + (BAtlas,BLI,[('template_landmark_weights_csv','inputWeightFilename')]) + ]) + + if processingLevel > 0: + ######################################################## + # Run BLI subject_to_atlas + ######################################################## + BLI2Atlas = pe.Node(interface=BRAINSLandmarkInitializer(), name="05_BLI2Atlas") + BLI2Atlas.inputs.outputTransformFilename = "landmarkInitializer_subject_to_atlas_transform.mat" + + baw200.connect([ + (BCD,BLI2Atlas,[('outputLandmarksInInputSpace','inputMovingLandmarkFilename')]), + ]) + baw200.connect([ + (BAtlas,BLI2Atlas,[('template_landmarks_fcsv','inputFixedLandmarkFilename')]), + (BAtlas,BLI2Atlas,[('template_landmark_weights_csv','inputWeightFilename')]) + ]) + Resample2Atlas=pe.Node(interface=BRAINSResample(),name="05_Resample2Atlas") + Resample2Atlas.inputs.interpolationMode = "Linear" + Resample2Atlas.inputs.outputVolume = "subject2atlas.nii.gz" + + baw200.connect( [ (siteSource, Resample2Atlas, [(('uid', getFirstT1, os.path.join(os.getcwd(), 'db.tmp') ), 'inputVolume')] ), ]) + baw200.connect(BLI2Atlas,'outputTransformFilename',Resample2Atlas,'warpTransform') + baw200.connect(BAtlas,'template_t1',Resample2Atlas,'referenceVolume') + + if processingLevel > 1: + ######################################################## + # Run BABC on Multi-modal images + ######################################################## + def MakeOneFileList(T1List,T2List,altT1): + """ This funciton uses altT1 for the first T1, and the append the rest of the T1's and T2's """ + imagePathList=list() + imagePathList.append(altT1) + for i in T1List[1:]: + imagePathList.append(i) + for i in T2List[0:]: + imagePathList.append(i) + return imagePathList + makeImagePathList = pe.Node( Function(function=MakeOneFileList, input_names = ['T1List','T2List','altT1'], output_names = ['imagePathList']), run_without_submitting=True, name="99_makeImagePathList") + baw200.connect( [ (siteSource, makeImagePathList, [(('uid', getT1s, os.path.join(os.getcwd(), 'db.tmp') ), 'T1List')] ), ]) + baw200.connect( [ (siteSource, makeImagePathList, [(('uid', getT2s, os.path.join(os.getcwd(), 'db.tmp') ), 'T2List')] ), ]) + # -- Standard mode to make 256^3 images + baw200.connect( BCD, 'outputResampledVolume', makeImagePathList, 'altT1' ) + + def MakeOneFileTypeList(T1List,T2List): + input_types = ["T1"]*len(T1List) + input_types.extend( ["T2"]*len(T2List) ) + return ",".join(input_types) + makeImageTypeList = pe.Node( Function(function=MakeOneFileTypeList, input_names = ['T1List','T2List'], output_names = ['imageTypeList']), run_without_submitting=True, name="99_makeImageTypeList") + + baw200.connect( [ (siteSource, makeImageTypeList, [(('uid', getT1s, os.path.join(os.getcwd(), 'db.tmp') ), 'T1List')] ), ]) + baw200.connect( [ (siteSource, makeImageTypeList, [(('uid', getT2s, os.path.join(os.getcwd(), 'db.tmp') ), 'T2List')] ), ]) + + def MakeOutFileList(T1List,T2List): + def GetExtBaseName(filename): + ''' + Get the filename without the extension. Works for .ext and .ext.gz + ''' + import os + currBaseName = os.path.basename(filename) + currExt = os.path.splitext(currBaseName)[1] + currBaseName = os.path.splitext(currBaseName)[0] + if currExt == ".gz": + currBaseName = os.path.splitext(currBaseName)[0] + currExt = os.path.splitext(currBaseName)[1] + return currBaseName + all_files=T1List + all_files.extend(T2List) + out_corrected_names=[] + for i in all_files: + out_name=GetExtBaseName(i)+"_corrected.nii.gz" + out_corrected_names.append(out_name) + return out_corrected_names + makeOutImageList = pe.Node( Function(function=MakeOutFileList, input_names = ['T1List','T2List'], output_names = ['outImageList']), run_without_submitting=True, name="99_makeOutImageList") + baw200.connect( [ (siteSource, makeOutImageList, [(('uid', getT1s, os.path.join(os.getcwd(), 'db.tmp') ), 'T1List')] ), ]) + baw200.connect( [ (siteSource, makeOutImageList, [(('uid', getT2s, os.path.join(os.getcwd(), 'db.tmp') ), 'T2List')] ), ]) + + BABC= pe.Node(interface=BRAINSABC(), name="11_BABC") + baw200.connect(makeImagePathList,'imagePathList',BABC,'inputVolumes') + baw200.connect(makeImageTypeList,'imageTypeList',BABC,'inputVolumeTypes') + baw200.connect(makeOutImageList,'outImageList',BABC,'outputVolumes') + BABC.inputs.debuglevel = 0 + BABC.inputs.maxIterations = 3 + BABC.inputs.maxBiasDegree = 4 + BABC.inputs.filterIteration = 3 + BABC.inputs.filterMethod = 'GradientAnisotropicDiffusion' + BABC.inputs.gridSize = [28,20,24] + BABC.inputs.outputFormat = "NIFTI" + BABC.inputs.outputLabels = "brain_label_seg.nii.gz" + BABC.inputs.outputDirtyLabels = "volume_label_seg.nii.gz" + BABC.inputs.posteriorTemplate = "POSTERIOR_%s.nii.gz" + BABC.inputs.atlasToSubjectTransform = "atlas_to_subject.mat" + BABC.inputs.implicitOutputs = ['t1_average_BRAINSABC.nii.gz', 't2_average_BRAINSABC.nii.gz'] + + BABC.inputs.resamplerInterpolatorType = InterpolationMode + ## + BABC.inputs.outputDir = './' + + baw200.connect(BAtlas,'AtlasPVDefinition_xml',BABC,'atlasDefinition') + + baw200.connect(BLI,'outputTransformFilename',BABC,'atlasToSubjectInitialTransform') + """ + Get the first T1 and T2 corrected images from BABC + """ + bfc_files = pe.Node(Function(input_names=['in_files','T1_count'], + output_names=['t1_corrected','t2_corrected'], + function=get_first_T1_and_T2), name='99_bfc_files') + + baw200.connect( [ (siteSource, bfc_files, [(('uid', getT1sLength, os.path.join(os.getcwd(), 'db.tmp') ), 'T1_count')] ), ]) + baw200.connect(BABC,'outputVolumes',bfc_files,'in_files') + + """ + ResampleNACLabels + """ + ResampleAtlasNACLabels=pe.Node(interface=BRAINSResample(),name="13_ResampleAtlasNACLabels") + ResampleAtlasNACLabels.inputs.interpolationMode = "NearestNeighbor" + ResampleAtlasNACLabels.inputs.outputVolume = "atlasToSubjectNACLabels.nii.gz" + + baw200.connect(BABC,'atlasToSubjectTransform',ResampleAtlasNACLabels,'warpTransform') + baw200.connect(bfc_files,'t1_corrected',ResampleAtlasNACLabels,'referenceVolume') + baw200.connect(BAtlas,'template_nac_lables',ResampleAtlasNACLabels,'inputVolume') + + """ + BRAINSMush + """ + BMUSH=pe.Node(interface=BRAINSMush(),name="15_BMUSH") + BMUSH.inputs.outputVolume = "MushImage.nii.gz" + BMUSH.inputs.outputMask = "MushMask.nii.gz" + BMUSH.inputs.lowerThresholdFactor = 1.2 + BMUSH.inputs.upperThresholdFactor = 0.55 + + baw200.connect(bfc_files,'t1_corrected',BMUSH,'inputFirstVolume') + baw200.connect(bfc_files,'t2_corrected',BMUSH,'inputSecondVolume') + baw200.connect(BABC,'outputLabels',BMUSH,'inputMaskVolume') + + """ + BRAINSROIAuto + """ + BROI = pe.Node(interface=BRAINSROIAuto(), name="17_BRAINSROIAuto") + BROI.inputs.closingSize=12 + BROI.inputs.otsuPercentileThreshold=0.01 + BROI.inputs.thresholdCorrectionFactor=1.0 + BROI.inputs.outputROIMaskVolume = "temproiAuto_t1_ACPC_corrected_BRAINSABC.nii.gz" + baw200.connect(bfc_files,'t1_corrected',BROI,'inputVolume') + + """ + Split the implicit outputs of BABC + """ + SplitAvgBABC = pe.Node(Function(input_names=['in_files','T1_count'], output_names=['avgBABCT1','avgBABCT2'], + function = get_first_T1_and_T2), run_without_submitting=True, name="99_SplitAvgBABC") + SplitAvgBABC.inputs.T1_count = 1 ## There is only 1 average T1 image. + + baw200.connect(BABC,'implicitOutputs',SplitAvgBABC,'in_files') + + + """ + Gradient Anistropic Diffusion images for BRAINSCut + """ + GADT1=pe.Node(interface=GradientAnisotropicDiffusionImageFilter(),name="27_GADT1") + GADT1.inputs.timeStep = 0.025 + GADT1.inputs.conductance = 1 + GADT1.inputs.numberOfIterations = 5 + GADT1.inputs.outputVolume = "GADT1.nii.gz" + + baw200.connect(SplitAvgBABC,'avgBABCT1',GADT1,'inputVolume') + + GADT2=pe.Node(interface=GradientAnisotropicDiffusionImageFilter(),name="27_GADT2") + GADT2.inputs.timeStep = 0.025 + GADT2.inputs.conductance = 1 + GADT2.inputs.numberOfIterations = 5 + GADT2.inputs.outputVolume = "GADT2.nii.gz" + + def printFullPath(outFileFullPath): + print("="*80) + print("="*80) + print("="*80) + print("="*80) + print("{0}".format(outFileFullPath)) + return outFileFullPath + printOutImage = pe.Node( Function(function=printFullPath, input_names = ['outFileFullPath'], output_names = ['genoutFileFullPath']), run_without_submitting=True, name="99_printOutImage") + baw200.connect( GADT2, 'outputVolume', printOutImage, 'outFileFullPath' ) + + baw200.connect(SplitAvgBABC,'avgBABCT2',GADT2,'inputVolume') + + """ + Sum the gradient images for BRAINSCut + """ + SGI=pe.Node(interface=GenerateSummedGradientImage(),name="27_SGI") + SGI.inputs.outputFileName = "SummedGradImage.nii.gz" + + baw200.connect(GADT1,'outputVolume',SGI,'inputVolume1') + baw200.connect(GADT2,'outputVolume',SGI,'inputVolume2') + + if processingLevel > 1: + """ + Load the BRAINSCut models & probabiity maps. + """ + BCM_outputs = ['phi','rho','theta', + 'r_probabilityMaps','l_probabilityMaps', + 'models'] + BCM_Models = pe.Node(interface=nio.DataGrabber(input_names=['structures'], + outfields=BCM_outputs), + name='10_BCM_Models') + BCM_Models.inputs.base_directory = atlas_fname_wpath + BCM_Models.inputs.template_args['phi'] = [['spatialImages','phi','nii.gz']] + BCM_Models.inputs.template_args['rho'] = [['spatialImages','rho','nii.gz']] + BCM_Models.inputs.template_args['theta'] = [['spatialImages','theta','nii.gz']] + BCM_Models.inputs.template_args['r_probabilityMaps'] = [['structures']] + BCM_Models.inputs.template_args['l_probabilityMaps'] = [['structures']] + BCM_Models.inputs.template_args['models'] = [['structures']] + + BRAINSCut_structures = ['caudate','thalamus','putamen','hippocampus'] + #BRAINSCut_structures = ['caudate','thalamus'] + BCM_Models.iterables = ( 'structures', BRAINSCut_structures ) + BCM_Models.inputs.template = '%s/%s.%s' + BCM_Models.inputs.field_template = dict( + r_probabilityMaps='probabilityMaps/r_%s_ProbabilityMap.nii.gz', + l_probabilityMaps='probabilityMaps/l_%s_ProbabilityMap.nii.gz', + models='modelFiles/%sModel*', + ) + + """ + The xml creation and BRAINSCut need to be their own mini-pipeline that gets + executed once for each of the structures in BRAINSCut_structures. This can be + accomplished with a map node and a new pipeline. + """ + """ + Create xml file for BRAINSCut + """ + + + BFitAtlasToSubject = pe.Node(interface=BRAINSFit(),name="30_BFitAtlasToSubject") + BFitAtlasToSubject.inputs.costMetric="MMI" + BFitAtlasToSubject.inputs.maskProcessingMode="ROI" + BFitAtlasToSubject.inputs.numberOfSamples=100000 + BFitAtlasToSubject.inputs.numberOfIterations=[1500,1500] + BFitAtlasToSubject.inputs.numberOfHistogramBins=50 + BFitAtlasToSubject.inputs.maximumStepLength=0.2 + BFitAtlasToSubject.inputs.minimumStepLength=[0.005,0.005] + BFitAtlasToSubject.inputs.transformType= ["Affine","BSpline"] + BFitAtlasToSubject.inputs.maxBSplineDisplacement= 7 + BFitAtlasToSubject.inputs.maskInferiorCutOffFromCenter=65 + BFitAtlasToSubject.inputs.splineGridSize=[28,20,24] + BFitAtlasToSubject.inputs.outputVolume="Trial_Initializer_Output.nii.gz" + BFitAtlasToSubject.inputs.outputTransform="Trial_Initializer_Output.mat" + baw200.connect(SplitAvgBABC,'avgBABCT1',BFitAtlasToSubject,'fixedVolume') + baw200.connect(BABC,'outputLabels',BFitAtlasToSubject,'fixedBinaryVolume') + baw200.connect(BAtlas,'template_t1',BFitAtlasToSubject,'movingVolume') + baw200.connect(BAtlas,'template_brain',BFitAtlasToSubject,'movingBinaryVolume') + baw200.connect(BLI,'outputTransformFilename',BFitAtlasToSubject,'initialTransform') + + CreateBRAINSCutXML = pe.Node(Function(input_names=['rho','phi','theta', + 'model', + 'r_probabilityMap', + 'l_probabilityMap', + 'atlasT1','atlasBrain', + 'subjT1','subjT2', + 'subjT1GAD','subjT2GAD', + 'subjSGGAD','subjBrain', + 'atlasToSubj','output_dir'], + output_names=['xml_filename','rl_structure_filename_list'], + function = create_BRAINSCut_XML), + overwrite = True, + name="CreateBRAINSCutXML") + + ## HACK Makde better directory + CreateBRAINSCutXML.inputs.output_dir = "." #os.path.join(baw200.base_dir, "BRAINSCut_output") + baw200.connect(BCM_Models,'models',CreateBRAINSCutXML,'model') + baw200.connect(BCM_Models,'rho',CreateBRAINSCutXML,'rho') + baw200.connect(BCM_Models,'phi',CreateBRAINSCutXML,'phi') + baw200.connect(BCM_Models,'theta',CreateBRAINSCutXML,'theta') + baw200.connect(BCM_Models,'r_probabilityMaps',CreateBRAINSCutXML,'r_probabilityMap') + baw200.connect(BCM_Models,'l_probabilityMaps',CreateBRAINSCutXML,'l_probabilityMap') + baw200.connect(BAtlas,'template_t1',CreateBRAINSCutXML,'atlasT1') + baw200.connect(BAtlas,'template_brain',CreateBRAINSCutXML,'atlasBrain') + baw200.connect(SplitAvgBABC,'avgBABCT1',CreateBRAINSCutXML,'subjT1') + baw200.connect(SplitAvgBABC,'avgBABCT2',CreateBRAINSCutXML,'subjT2') + baw200.connect(GADT1,'outputVolume',CreateBRAINSCutXML,'subjT1GAD') + baw200.connect(GADT2,'outputVolume',CreateBRAINSCutXML,'subjT2GAD') + baw200.connect(SGI,'outputFileName',CreateBRAINSCutXML,'subjSGGAD') + baw200.connect(BABC,'outputLabels',CreateBRAINSCutXML,'subjBrain') + baw200.connect(BFitAtlasToSubject,'outputTransform',CreateBRAINSCutXML,'atlasToSubj') + #CreateBRAINSCutXML.inputs.atlasToSubj = "INTERNAL_REGISTER.mat" + #baw200.connect(BABC,'atlasToSubjectTransform',CreateBRAINSCutXML,'atlasToSubj') + + if 1 == 1: + """ + BRAINSCut + """ + BRAINSCUT = pe.Node(interface=BRAINSCut(),name="BRAINSCUT", + input_names=['netConfiguration'], + output_names=['implicitOutputs']) + BRAINSCUT.inputs.applyModel = True + baw200.connect(CreateBRAINSCutXML,'xml_filename',BRAINSCUT,'netConfiguration') + baw200.connect(CreateBRAINSCutXML,'rl_structure_filename_list',BRAINSCUT,'implicitOutputs') + + """ + BRAINSTalairach + Not implemented yet. + """ + + ## Make deformed Atlas image space + if processingLevel > 2: + print(""" + Run ANTS Registration at processingLevel={0} + """.format(processingLevel) ) + ComputeAtlasToSubjectTransform = pe.Node(interface=ANTSWrapper(), name="19_ComputeAtlasToSubjectTransform") + ComputeAtlasToSubjectTransform.inputs.output_prefix = "ANTS_" + + baw200.connect( SplitAvgBABC,'avgBABCT1',ComputeAtlasToSubjectTransform,"fixed_T1_image") + baw200.connect( SplitAvgBABC,'avgBABCT2',ComputeAtlasToSubjectTransform,"fixed_T2_image") + baw200.connect( BAtlas,'template_t1', ComputeAtlasToSubjectTransform,"moving_T1_image") + baw200.connect( BAtlas,'template_t1', ComputeAtlasToSubjectTransform,"moving_T2_image") + + WarpAtlas = pe.Node(interface=WarpAllAtlas(), name = "19_WarpAtlas") + WarpAtlas.inputs.moving_atlas = atlas_fname_wpath + WarpAtlas.inputs.deformed_atlas = "./" + baw200.connect( ComputeAtlasToSubjectTransform,'output_affine', WarpAtlas,"affine_transform") + baw200.connect( ComputeAtlasToSubjectTransform,'output_warp', WarpAtlas,"deformation_field") + baw200.connect( SplitAvgBABC,'avgBABCT1', WarpAtlas, 'reference_image') + + if processingLevel > 3: + print(""" + Run Freesurfer ReconAll at processingLevel={0} + """.format(processingLevel) ) + subj_id = os.path.basename(os.path.dirname(os.path.dirname(baw200.base_dir))) + scan_id = os.path.basename(os.path.dirname(baw200.base_dir)) + reconall = pe.Node(interface=ReconAll(),name="41_FS510") + reconall.inputs.subject_id = subj_id+'_'+scan_id + reconall.inputs.directive = 'all' + reconall.inputs.subjects_dir = '.' + baw200.connect(SplitAvgBABC,'avgBABCT1',reconall,'T1_files') + else: + print "Skipping freesurfer" + + return baw200 + diff --git a/AutoWorkup/baw_exp.py b/AutoWorkup/baw_exp.py new file mode 100644 index 00000000..7d4a718f --- /dev/null +++ b/AutoWorkup/baw_exp.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +################################################################################# +## Program: BRAINS (Brain Research: Analysis of Images, Networks, and Systems) +## Language: Python +## +## Author: Hans J. Johnson +## +## This software is distributed WITHOUT ANY WARRANTY; without even +## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +## PURPOSE. See the above copyright notices for more information. +## +################################################################################# +import sys + +############################################################################## +def get_global_sge_script(pythonPathsList,binPathsList): + """This is a wrapper script for running commands on an SGE cluster +so that all the python modules and commands are pathed properly""" + PYTHONPATH=":".join(pythonPathsList) + BASE_BUILDS=":".join(binPathsList) + GLOBAL_SGE_SCRIPT="""#!/bin/bash +echo "STARTED at: $(date +'%F-%T')" +echo "Ran on: $(hostname)" +export PATH={BINPATH} +export PYTHONPATH={PYTHONPATH} +echo "With PYTHONPATH={PYTHONPATH}" +echo "With PATH={BINPATH}" +## NOTE: nipype inserts the actaul commands that need running below this section. +""".format(PYTHONPATH=PYTHONPATH,BINPATH=BASE_BUILDS) + return GLOBAL_SGE_SCRIPT + +def main(argv=None): + import argparse + import ConfigParser + import os + import csv + import string + + if argv == None: + argv = sys.argv + + # Create and parse input arguments + parser = argparse.ArgumentParser(description='Runs a mini version of BRAINSAutoWorkup') + group = parser.add_argument_group('Required') + group.add_argument('-pe', action="store", dest='processingEnvironment', required=True, + help='The name of the processing environment to use from the config file') + group.add_argument('-ExperimentConfig', action="store", dest='ExperimentConfig', required=True, + help='The path to the file that describes the entire experiment') + parser.add_argument('--version', action='version', version='%(prog)s 1.0') + group.add_argument('-processingLevel', action="store", dest='processingLevel', required=False, + help='How much processing should be done, 1=basic, 2= include ABC, 3= include ANTS, 4= include Freesurfer', + default=2) + #parser.add_argument('-v', action='store_false', dest='verbose', default=True, + # help='If not present, prints the locations') + input_arguments = parser.parse_args() + + + expConfig = ConfigParser.ConfigParser() + expConfig.read(input_arguments.ExperimentConfig) + + # Experiment specific information + session_db=expConfig.get('EXPERIMENT_DATA','SESSION_DB') + ExperimentName=expConfig.get('EXPERIMENT_DATA','EXPERIMENTNAME') + + # Platform specific information + # Prepend the python search paths + PYTHON_AUX_PATHS=expConfig.get(input_arguments.processingEnvironment,'PYTHON_AUX_PATHS') + PYTHON_AUX_PATHS=PYTHON_AUX_PATHS.split(';') + PYTHON_AUX_PATHS.extend(sys.path) + sys.path=PYTHON_AUX_PATHS + # Prepend the shell environment search paths + PROGRAM_PATHS=expConfig.get(input_arguments.processingEnvironment,'PROGRAM_PATHS') + PROGRAM_PATHS=PROGRAM_PATHS.split(';') + PROGRAM_PATHS.extend(os.environ['PATH'].split(':')) + os.environ['PATH']=':'.join(PROGRAM_PATHS) + # Define platform specific output write paths + mountPrefix=expConfig.get(input_arguments.processingEnvironment,'MOUNTPREFIX') + BASEOUTPUTDIR=expConfig.get(input_arguments.processingEnvironment,'BASEOUTPUTDIR') + FULL_EXPERIMENT_OUTPUTDIR=os.path.join(BASEOUTPUTDIR,ExperimentName) + if not os.path.exists(FULL_EXPERIMENT_OUTPUTDIR): + os.makedirs(FULL_EXPERIMENT_OUTPUTDIR) + ExperimentBaseDirectory=os.path.realpath(os.path.join(BASEOUTPUTDIR,ExperimentName)) + # Define workup common reference data sets + ATLASPATH=expConfig.get(input_arguments.processingEnvironment,'ATLASPATH') + BCDMODELPATH=expConfig.get(input_arguments.processingEnvironment,'BCDMODELPATH') + + import WorkupT1T2 ## NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified + baw200=WorkupT1T2.WorkupT1T2(input_arguments.processingLevel, mountPrefix, + ExperimentBaseDirectory, + session_db, + ATLASPATH, + BCDMODELPATH) + + print "Start Processing" + ## Create the shell wrapper script for ensuring that all jobs running on remote hosts from SGE + # have the same environment as the job submission host. + JOB_SCRIPT=get_global_sge_script(sys.path,PROGRAM_PATHS) + #baw200.run(plugin='SGE', plugin_args=dict(template=JOB_SCRIPT,qsub_args="-S /bin/bash -q OSX -pe smp1 2-4 -o /dev/null -e /dev/null ")) + #baw200.run(plugin='MultiProc', plugin_args={'n_procs' : 4}) + #baw200.run(plugin='MultiProc', plugin_args={'n_procs' : 12}) + #baw200.run(plugin='SGE', plugin_args=dict(template=JOB_SCRIPT,qsub_args="-S /bin/bash -q all.q -pe smp1 2-4 -o /dev/null -e /dev/null ")) + baw200.run() + baw200.write_graph() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/AutoWorkup/generate_classes.py b/AutoWorkup/generate_classes.py new file mode 100644 index 00000000..f50737d6 --- /dev/null +++ b/AutoWorkup/generate_classes.py @@ -0,0 +1,235 @@ +import xml.dom.minidom +import subprocess +import os +import warnings +from nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits, + TraitedSpec, File, StdOutCommandLine, + StdOutCommandLineInputSpec, isdefined) + + +def generate_all_classes(modules_list = [], launcher=[], exec_dir='', outdir='./'): + """ modules_list contains all the SEM compliant tools that should have wrappers created for them. + launcher containtains the command line prefix wrapper arugments needed to prepare + a proper environment for each of the modules. + """ + outdir=outdir.strip('/')+'/' ## ensure that outdir has exactly 1 trailing '/' + init_imports = "" + for module in modules_list: + module_python_filename="%s.py"%module + print("="*80) + print("Generating Definition for module {0} in {1}".format(module,module_python_filename)) + print("^"*80) + code = generate_class(module,launcher) + f = open(outdir+module_python_filename, "w") + f.write(code) + f.close() + init_imports += "from %s import %s\n"%(module,module) + f = open(outdir+"__init__.py", "w") + f.write(init_imports) + f.close() + + +def generate_class(module,launcher): + dom = _grab_xml(module,launcher) + inputTraits = [] + outputTraits = [] + outputs_filenames = {} + + #self._outputs_nodes = [] + + for paramGroup in dom.getElementsByTagName("parameters"): + for param in paramGroup.childNodes: + if param.nodeName in ['label', 'description', '#text', '#comment']: + continue + traitsParams = {} + + name = param.getElementsByTagName('name')[0].firstChild.nodeValue + name = name.lstrip().rstrip() + + longFlagNode = param.getElementsByTagName('longflag') + if longFlagNode: + ## Prefer to use longFlag as name if it is given, rather than the parameter name + longFlagName = longFlagNode[0].firstChild.nodeValue + ## SEM automatically strips prefixed "--" or "-" from from xml before processing + ## we need to replicate that behavior here The following + ## two nodes in xml have the same behavior in the program + ## --test + ## test + longFlagName = longFlagName.lstrip(" -").rstrip(" ") + traitsParams["argstr"] = "--" + longFlagName + " " + else: + traitsParams["argstr"] = "--" + name + " " + + argsDict = {'directory': '%s', 'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s", 'integer-enumeration' : '%s'} + + if param.nodeName.endswith('-vector'): + traitsParams["argstr"] += "%s" + else: + traitsParams["argstr"] += argsDict[param.nodeName] + + index = param.getElementsByTagName('index') + if index: + traitsParams["position"] = index[0].firstChild.nodeValue + + desc = param.getElementsByTagName('description') + if index: + traitsParams["desc"] = desc[0].firstChild.nodeValue + + name = param.getElementsByTagName('name')[0].firstChild.nodeValue + + typesDict = {'integer': "traits.Int", 'double': "traits.Float", + 'float': "traits.Float", 'image': "File", + 'transform': "File", 'boolean': "traits.Bool", + 'string': "traits.Str", 'file':"File", + 'directory': "Directory"} + + if param.nodeName.endswith('-enumeration'): + type = "traits.Enum" + values = ['"%s"'%el.firstChild.nodeValue for el in param.getElementsByTagName('element')] + elif param.nodeName.endswith('-vector'): + type = "InputMultiPath" + if param.nodeName in ['file', 'directory', 'image', 'transform']: + values = ["%s(exists=True)"%typesDict[param.nodeName.replace('-vector','')]] + else: + values = [typesDict[param.nodeName.replace('-vector','')]] + traitsParams["sep"] = ',' + elif param.getAttribute('multiple') == "true": + type = "InputMultiPath" + if param.nodeName in ['file', 'directory', 'image', 'transform']: + values = ["%s(exists=True)"%typesDict[param.nodeName]] + else: + values = [typesDict[param.nodeName]] + traitsParams["argstr"] += "..." + else: + values = [] + type = typesDict[param.nodeName] + + if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output': + traitsParams["hash_files"] = False + inputTraits.append("%s = traits.Either(traits.Bool, %s(%s), %s)"%(name, + type, + _parse_values(values).replace("exists=True",""), + _parse_params(traitsParams))) + traitsParams["exists"] = True + traitsParams.pop("argstr") + traitsParams.pop("hash_files") + outputTraits.append("%s = %s(%s %s)"%(name, type.replace("Input", "Output"), _parse_values(values), _parse_params(traitsParams))) + + outputs_filenames[name] = gen_filename_from_param(param) + else: + if param.nodeName in ['file', 'directory', 'image', 'transform'] and type not in ["InputMultiPath", "traits.List"]: + traitsParams["exists"] = True + + inputTraits.append("%s = %s(%s %s)"%(name, type, _parse_values(values), _parse_params(traitsParams))) + + input_spec_code = "class " + module + "InputSpec(CommandLineInputSpec):\n" + for trait in inputTraits: + input_spec_code += " " + trait + "\n" + + output_spec_code = "class " + module + "OutputSpec(TraitedSpec):\n" + if len(outputTraits) > 0: + for trait in outputTraits: + output_spec_code += " " + trait + "\n" + else: + output_spec_code += " pass\n" + + output_filenames_code = "_outputs_filenames = {" + output_filenames_code += ",".join(["'%s':'%s'"%(key,value) for key,value in outputs_filenames.iteritems()]) + output_filenames_code += "}" + + + input_spec_code += "\n\n" + output_spec_code += "\n\n" + + imports = """from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath +import os\n\n""" + + template = """class %name%(CommandLine): + + input_spec = %name%InputSpec + output_spec = %name%OutputSpec + _cmd = "%launcher% %name% " + %output_filenames_code% + + def _list_outputs(self): + outputs = self.output_spec().get() + for name in outputs.keys(): + coresponding_input = getattr(self.inputs, name) + if isdefined(coresponding_input): + if isinstance(coresponding_input, bool) and coresponding_input == True: + outputs[name] = os.path.abspath(self._outputs_filenames[name]) + else: + if isinstance(coresponding_input, list): + outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] + else: + outputs[name] = os.path.abspath(coresponding_input) + return outputs + + def _format_arg(self, name, spec, value): + if name in self._outputs_filenames.keys(): + if isinstance(value, bool): + if value == True: + value = os.path.abspath(self._outputs_filenames[name]) + else: + return "" + return super(%name%, self)._format_arg(name, spec, value)\n\n""" + + + main_class = template.replace("%name%", module).replace("%output_filenames_code%", output_filenames_code).replace("%launcher%"," ".join(launcher)) + + return imports + input_spec_code + output_spec_code + main_class + +def _grab_xml(module,launcher): +# cmd = CommandLine(command = "Slicer3", args="--launch %s --xml"%module) +# ret = cmd.run() + command_list=launcher[:] ## force copy to preserve original + command_list.extend([module, "--xml"]) + final_command=" ".join(command_list) + xmlReturnValue = subprocess.Popen(final_command, stdout=subprocess.PIPE, shell=True).communicate()[0] + return xml.dom.minidom.parseString(xmlReturnValue) +# if ret.runtime.returncode == 0: +# return xml.dom.minidom.parseString(ret.runtime.stdout) +# else: +# raise Exception(cmd.cmdline + " failed:\n%s"%ret.runtime.stderr) +def _parse_params(params): + list = [] + for key, value in params.iteritems(): + if isinstance(value, str) or isinstance(value, unicode): + list.append('%s = "%s"'%(key, value)) + else: + list.append('%s = %s'%(key, value)) + + return ",".join(list) + +def _parse_values(values): + values = ['%s'%value for value in values] + if len(values) > 0: + retstr = ",".join(values) + "," + else: + retstr = "" + return retstr + +def gen_filename_from_param(param): + base = param.getElementsByTagName('name')[0].firstChild.nodeValue + fileExtensions = param.getAttribute("fileExtensions") + if fileExtensions: + ## It is possible that multiple file extensions can be specified in a + ## comma separated list, This will extract just the first extension + firstFileExtension=fileExtensions.split(',')[0] + ext = firstFileExtension + else: + ext = {'image': '.nii', 'transform': '.mat', 'file': '', 'directory': ''}[param.nodeName] + return base + ext + +if __name__ == "__main__": + ## NOTE: For now either the launcher needs to be found on the default path, or + ## every tool in the modules list must be found on the default path + ## AND calling the module with --xml must be supported and compliant. + modules_list = ['BRAINSFit', 'BRAINSResample', 'BRAINSDemonWarp', 'BRAINSROIAuto'] + ## SlicerExecutionModel compliant tools that are usually statically built, and don't need the Slicer3 --launcher + #generate_all_classes(modules_list=modules_list,launcher=[]) + ## Tools compliant with SlicerExecutionModel called from the Slicer environment (for shared lib compatibility) + launcher=['Slicer3','--launch'] + generate_all_classes(modules_list=modules_list, launcher=launcher ) + #generate_all_classes(modules_list=['BRAINSABC'], launcher=[] ) + diff --git a/AutoWorkup/install_python_tools.sh b/AutoWorkup/install_python_tools.sh new file mode 100644 index 00000000..31e78c49 --- /dev/null +++ b/AutoWorkup/install_python_tools.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +mkdir ./python_install_stuff +cd ./python_install_stuff + +export INSTALL_DIR=~/local/python-site-packages +export PYTHONPATH=${INSTALL_DIR} +export THIS_DIR=$(pwd) + +## On 10.7.3 the gcc compiler is not reliable, use clang +export CC=/usr/bin/clang +export CXX=/usr/bin/clang++ + +if [ 0 -eq 1 ]; then +git clone http://github.com/numpy/numpy.git numpy +cd ${THIS_DIR}/numpy +python setup.py install --prefix=${INSTALL_DIR} +fi + +if [ 0 -eq 1 ]; then +git clone http://github.com/scipy/scipy.git scipy +cd ${THIS_DIR}/scipy +python setup.py install --prefix=${INSTALL_DIR} +fi + +for required_package in nibabel networkx nipype; do + easy_install --install-dir=${INSTALL_DIR} ${required_package} +done + +#git clone git://github.com/nipy/nipype.git nipype +#cd ${THIS_DIR}/nipype +#python setup.py install --prefix=${INSTALL_DIR} + + diff --git a/AutoWorkup/subject_db.csv b/AutoWorkup/subject_db.csv new file mode 100644 index 00000000..1db3206c --- /dev/null +++ b/AutoWorkup/subject_db.csv @@ -0,0 +1,2 @@ +MYPROJ,SUBJ_0001,SESSION_01,"['/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T1_1.nii.gz']","['/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T2_1.nii.gz','/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T2_2.nii.gz']" +MYPROJ,SUBJ_0001,SESSION_01,"['/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T1_1.nii.gz']","['/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T2_1.nii.gz','/scratch/MYPROJ/SUBJ_0001/SESSION_01/ANONRAW/T2_2.nii.gz']"