本文整理汇总了Python中nipype.interfaces.traits_extension.isdefined函数的典型用法代码示例。如果您正苦于以下问题:Python isdefined函数的具体用法?Python isdefined怎么用?Python isdefined使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isdefined函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_sorteddict
def _get_sorteddict(self, object, dictwithhash=False, hash_method=None, hash_files=True):
if isinstance(object, dict):
out = {}
for key, val in sorted(object.items()):
if isdefined(val):
out[key] = self._get_sorteddict(val, dictwithhash, hash_method=hash_method, hash_files=hash_files)
elif isinstance(object, (list, tuple)):
out = []
for val in object:
if isdefined(val):
out.append(self._get_sorteddict(val, dictwithhash, hash_method=hash_method, hash_files=hash_files))
if isinstance(object, tuple):
out = tuple(out)
else:
if isdefined(object):
if hash_files and isinstance(object, str) and os.path.isfile(object):
if hash_method == None:
hash_method = config.get("execution", "hash_method")
if hash_method.lower() == "timestamp":
hash = hash_timestamp(object)
elif hash_method.lower() == "content":
hash = hash_infile(object)
else:
raise Exception("Unknown hash method: %s" % hash_method)
if dictwithhash:
out = (object, hash)
else:
out = hash
elif isinstance(object, float):
out = "%.10f" % object
else:
out = object
return out
示例2: _format_arg
def _format_arg(self, opt, spec, val):
if opt == 'moving_image_mask':
return '--masks [ %s, %s ]' % (self.inputs.fixed_image_mask, self.inputs.moving_image_mask)
elif opt == 'transforms':
return self._formatRegistration()
elif opt == 'initial_moving_transform':
if self.inputs.invert_initial_moving_transform:
return '--initial-moving-transform [ %s, 1 ]' % self.inputs.initial_moving_transform
else:
return '--initial-moving-transform [ %s, 0 ]' % self.inputs.initial_moving_transform
elif opt == 'interpolation':
# TODO: handle multilabel, gaussian, and bspline options
return '--interpolation %s' % self.inputs.interpolation
elif opt == 'output_transform_prefix':
if isdefined(self.inputs.output_inverse_warped_image) and self.inputs.output_inverse_warped_image:
return '--output [ %s, %s, %s ]' % (self.inputs.output_transform_prefix, self.inputs.output_warped_image, self.inputs.output_inverse_warped_image)
elif isdefined(self.inputs.output_warped_image) and self.inputs.output_warped_image:
return '--output [ %s, %s ]' % (self.inputs.output_transform_prefix, self.inputs.output_warped_image)
else:
return '--output %s' % self.inputs.output_transform_prefix
elif opt == 'winsorize_upper_quantile' or opt == 'winsorize_lower_quantile':
if not self._quantilesDone:
return self._formatWinsorizeImageIntensities()
return '' # Must return something for argstr!
elif opt == 'collapse_linear_transforms_to_fixed_image_header':
return self._formatCollapseLinearTransformsToFixedImageHeader()
return super(Registration, self)._format_arg(opt, spec, val)
示例3: _formatRegistration
def _formatRegistration(self):
retval = []
for ii in range(len(self.inputs.transforms)):
retval.append('--transform %s' % (self._formatTransform(ii)))
for metric in self._formatMetric(ii):
retval.append('--metric %s' % metric)
retval.append('--convergence %s' % self._formatConvergence(ii))
if isdefined(self.inputs.sigma_units):
retval.append('--smoothing-sigmas %s%s' %
(self._antsJoinList(self.inputs.smoothing_sigmas[
ii]),
self.inputs.sigma_units[ii]))
else:
retval.append('--smoothing-sigmas %s' %
self._antsJoinList(self.inputs.smoothing_sigmas[ii]))
retval.append('--shrink-factors %s' %
self._antsJoinList(self.inputs.shrink_factors[ii]))
if isdefined(self.inputs.use_estimate_learning_rate_once):
retval.append('--use-estimate-learning-rate-once %d' %
self.inputs.use_estimate_learning_rate_once[ii])
if isdefined(self.inputs.use_histogram_matching):
# use_histogram_matching is either a common flag for all transforms
# or a list of transform-specific flags
if isinstance(self.inputs.use_histogram_matching, bool):
histval = self.inputs.use_histogram_matching
else:
histval = self.inputs.use_histogram_matching[ii]
retval.append('--use-histogram-matching %d' % histval)
return " ".join(retval)
示例4: _clean_container
def _clean_container(self, object, undefinedval=None, skipundefined=False):
"""Convert a traited obejct into a pure python representation.
"""
if isinstance(object, TraitDictObject) or isinstance(object, dict):
out = {}
for key, val in object.items():
if isdefined(val):
out[key] = self._clean_container(val, undefinedval)
else:
if not skipundefined:
out[key] = undefinedval
elif isinstance(object, TraitListObject) or isinstance(object, list) or isinstance(object, tuple):
out = []
for val in object:
if isdefined(val):
out.append(self._clean_container(val, undefinedval))
else:
if not skipundefined:
out.append(undefinedval)
else:
out.append(None)
if isinstance(object, tuple):
out = tuple(out)
else:
if isdefined(object):
out = object
else:
if not skipundefined:
out = undefinedval
return out
示例5: _list_outputs
def _list_outputs(self):
outputs = self._outputs().get()
outputs["forward_transforms"] = []
outputs["forward_invert_flags"] = []
outputs["reverse_transforms"] = []
outputs["reverse_invert_flags"] = []
if not self.inputs.collapse_output_transforms:
transformCount = 0
if isdefined(self.inputs.initial_moving_transform):
outputs["forward_transforms"].append(self.inputs.initial_moving_transform)
outputs["forward_invert_flags"].append(self.inputs.invert_initial_moving_transform)
outputs["reverse_transforms"].insert(0, self.inputs.initial_moving_transform)
outputs["reverse_invert_flags"].insert(0, not self.inputs.invert_initial_moving_transform) # Prepend
transformCount += 1
elif isdefined(self.inputs.initial_moving_transform_com):
# forwardFileName, _ = self._outputFileNames(self.inputs.output_transform_prefix,
# transformCount,
# 'Initial')
# outputs['forward_transforms'].append(forwardFileName)
transformCount += 1
for count in range(len(self.inputs.transforms)):
forwardFileName, forwardInverseMode = self._outputFileNames(
self.inputs.output_transform_prefix, transformCount, self.inputs.transforms[count]
)
reverseFileName, reverseInverseMode = self._outputFileNames(
self.inputs.output_transform_prefix, transformCount, self.inputs.transforms[count], True
)
outputs["forward_transforms"].append(os.path.abspath(forwardFileName))
outputs["forward_invert_flags"].append(forwardInverseMode)
outputs["reverse_transforms"].insert(0, os.path.abspath(reverseFileName))
outputs["reverse_invert_flags"].insert(0, reverseInverseMode)
transformCount += 1
else:
transformCount = 0
for transform in ["GenericAffine", "SyN"]: # Only files returned by collapse_output_transforms
forwardFileName, forwardInverseMode = self._outputFileNames(
self.inputs.output_transform_prefix, transformCount, transform
)
reverseFileName, reverseInverseMode = self._outputFileNames(
self.inputs.output_transform_prefix, transformCount, transform, True
)
outputs["forward_transforms"].append(os.path.abspath(forwardFileName))
outputs["forward_invert_flags"].append(forwardInverseMode)
outputs["reverse_transforms"].append(os.path.abspath(reverseFileName))
outputs["reverse_invert_flags"].append(reverseInverseMode)
transformCount += 1
if self.inputs.write_composite_transform:
fileName = self.inputs.output_transform_prefix + "Composite.h5"
outputs["composite_transform"] = [os.path.abspath(fileName)]
fileName = self.inputs.output_transform_prefix + "InverseComposite.h5"
outputs["inverse_composite_transform"] = [os.path.abspath(fileName)]
out_filename = self._get_outputfilenames(inverse=False)
inv_out_filename = self._get_outputfilenames(inverse=True)
if out_filename:
outputs["warped_image"] = os.path.abspath(out_filename)
if inv_out_filename:
outputs["inverse_warped_image"] = os.path.abspath(inv_out_filename)
return outputs
示例6: _format_arg
def _format_arg(self, name, spec, value):
if name == 'use_histogram_matching':
if isdefined(self.inputs.use_histogram_matching):
return spec.argstr % {False: '0', True: '1'}[value]
elif name == 'precision_type':
if isdefined(self.inputs.precision_type):
return spec.argstr % {'float': 'f', 'double': 'd'}[value]
return super(RegistrationSynQuick, self)._format_arg(name, spec, value)
示例7: _parse_stdout
def _parse_stdout(self, stdout):
import re
import os
files = []
reoriented_files = []
reoriented_and_cropped_files = []
bvecs = []
bvals = []
skip = False
last_added_file = None
for line in stdout.split("\n"):
if not skip:
file = None
if line.startswith("Saving "):
file = line[len("Saving "):]
elif line.startswith("GZip..."):
#for gzipped outpus files are not absolute
if isdefined(self.inputs.output_dir):
output_dir = self.inputs.output_dir
else:
output_dir = self._gen_filename('output_dir')
file = os.path.abspath(os.path.join(output_dir,
line[len("GZip..."):]))
elif line.startswith("Number of diffusion directions "):
if last_added_file:
base, filename, ext = split_filename(last_added_file)
bvecs.append(os.path.join(base,filename + ".bvec"))
bvals.append(os.path.join(base,filename + ".bval"))
elif re.search('.*->(.*)', line):
val = re.search('.*->(.*)', line)
val = val.groups()[0]
if isdefined(self.inputs.output_dir):
output_dir = self.inputs.output_dir
else:
output_dir = self._gen_filename('output_dir')
val = os.path.join(output_dir, val)
file = val
if file:
if last_added_file and os.path.exists(file) and not last_added_file in file:
files.append(file)
last_added_file = file
continue
if line.startswith("Reorienting as "):
reoriented_files.append(line[len("Reorienting as "):])
skip = True
continue
elif line.startswith("Cropping NIfTI/Analyze image "):
base, filename = os.path.split(line[len("Cropping NIfTI/Analyze image "):])
filename = "c" + filename
reoriented_and_cropped_files.append(os.path.join(base, filename))
skip = True
continue
skip = False
return files, reoriented_files, reoriented_and_cropped_files, bvecs, bvals
示例8: _check_xor
def _check_xor(self, spec, name, value):
""" check if mutually exclusive inputs are satisfied
"""
if spec.xor:
values = [isdefined(getattr(self.inputs, field)) for field in spec.xor]
if not any(values) and not isdefined(value):
msg = "%s requires a value for one of the inputs '%s'. " \
"For a list of required inputs, see %s.help()" % \
(self.__class__.__name__, ', '.join(spec.xor),
self.__class__.__name__)
raise ValueError(msg)
示例9: _check_requires
def _check_requires(self, spec, name, value):
""" check if required inputs are satisfied
"""
if spec.requires:
values = [not isdefined(getattr(self.inputs, field)) for field in spec.requires]
if any(values) and isdefined(value):
msg = "%s requires a value for input '%s' because one of %s is set. " \
"For a list of required inputs, see %s.help()" % \
(self.__class__.__name__, name,
', '.join(spec.requires), self.__class__.__name__)
raise ValueError(msg)
示例10: _formatRegistration
def _formatRegistration(self):
retval = []
for ii in range(len(self.inputs.transforms)):
retval.append('--transform %s' % (self._formatTransform(ii)))
retval.append('--metric %s' % self._formatMetric(ii))
retval.append('--convergence %s' % self._formatConvergence(ii))
retval.append('--smoothing-sigmas %s' % self._antsJoinList(self.inputs.smoothing_sigmas[ii]))
retval.append('--shrink-factors %s' % self._antsJoinList(self.inputs.shrink_factors[ii]))
if isdefined(self.inputs.use_estimate_learning_rate_once):
retval.append('--use-estimate-learning-rate-once %d' % self.inputs.use_estimate_learning_rate_once[ii])
if isdefined(self.inputs.use_histogram_matching):
retval.append('--use-histogram-matching %d' % self.inputs.use_histogram_matching[ii])
return " ".join(retval)
示例11: _formatMetric
def _formatMetric(self, index):
"""
Format the antsRegistration -m metric argument(s).
Parameters
----------
index: the stage index
"""
# The common fixed image.
fixed = self.inputs.fixed_image[0]
# The common moving image.
moving = self.inputs.moving_image[0]
# The metric name input for the current stage.
name_input = self.inputs.metric[index]
# The stage-specific input dictionary.
stage_inputs = dict(
metric=name_input,
weight=self.inputs.metric_weight[index],
radius_or_bins=self.inputs.radius_or_number_of_bins[index],
optional=self.inputs.radius_or_number_of_bins[index]
)
# The optional sampling strategy and percentage.
if (isdefined(self.inputs.sampling_strategy) and self.inputs.sampling_strategy):
sampling_strategy = self.inputs.sampling_strategy[index]
if sampling_strategy:
stage_inputs['sampling_strategy'] = sampling_strategy
sampling_percentage = self.inputs.sampling_percentage
if (isdefined(self.inputs.sampling_percentage) and self.inputs.sampling_percentage):
sampling_percentage = self.inputs.sampling_percentage[index]
if sampling_percentage:
stage_inputs['sampling_percentage'] = sampling_percentage
# Make a list of metric specifications, one per -m command line
# argument for the current stage.
# If there are multiple inputs for this stage, then convert the
# dictionary of list inputs into a list of metric specifications.
# Otherwise, make a singleton list of the metric specification
# from the non-list inputs.
if isinstance(name_input, list):
items = stage_inputs.items()
indexes = range(0, len(name_input))
# dict-comprehension only works with python 2.7 and up
#specs = [{k: v[i] for k, v in items} for i in indexes]
specs = [dict([(k, v[i]) for k, v in items]) for i in indexes]
else:
specs = [stage_inputs]
# Format the --metric command line metric arguments, one per
# specification.
return [self._formatMetricArgument(fixed, moving, **spec) for spec in specs]
示例12: _xor_warn
def _xor_warn(self, obj, name, old, new):
""" Generates warnings for xor traits
"""
if isdefined(new):
trait_spec = self.traits()[name]
# for each xor, set to default_value
for trait_name in trait_spec.xor:
if trait_name == name:
# skip ourself
continue
if isdefined(getattr(self, trait_name)):
self.trait_set(trait_change_notify=False, **{'%s' % name: Undefined})
msg = 'Input "%s" is mutually exclusive with input "%s", ' \
'which is already set' \
% (name, trait_name)
raise IOError(msg)
示例13: _check_mandatory_inputs
def _check_mandatory_inputs(self):
""" Raises an exception if a mandatory input is Undefined
"""
for name, spec in self.inputs.traits(mandatory=True).items():
value = getattr(self.inputs, name)
self._check_xor(spec, name, value)
if not isdefined(value) and spec.xor is None:
msg = "%s requires a value for input '%s'. " \
"For a list of required inputs, see %s.help()" % \
(self.__class__.__name__, name, self.__class__.__name__)
raise ValueError(msg)
if isdefined(value):
self._check_requires(spec, name, value)
for name, spec in self.inputs.traits(mandatory=None,
transient=None).items():
self._check_requires(spec, name, getattr(self.inputs, name))
示例14: fname_presuffix
def fname_presuffix(fname, prefix='', suffix='', newpath=None, use_ext=True):
"""Manipulates path and name of input filename
Parameters
----------
fname : string
A filename (may or may not include path)
prefix : string
Characters to prepend to the filename
suffix : string
Characters to append to the filename
newpath : string
Path to replace the path of the input fname
use_ext : boolean
If True (default), appends the extension of the original file
to the output name.
Returns
-------
Absolute path of the modified filename
>>> from nipype.utils.filemanip import fname_presuffix
>>> fname = 'foo.nii.gz'
>>> fname_presuffix(fname,'pre','post','/tmp')
'/tmp/prefoopost.nii.gz'
"""
pth, fname, ext = split_filename(fname)
if not use_ext:
ext = ''
if newpath and isdefined(newpath):
pth = os.path.abspath(newpath)
return os.path.join(pth, prefix+fname+suffix+ext)
示例15: run
def run(self, **inputs):
"""Execute this interface.
This interface will not raise an exception if runtime.returncode is
non-zero.
Parameters
----------
inputs : allows the interface settings to be updated
Returns
-------
results : an InterfaceResult object containing a copy of the instance
that was executed, provenance information and, if successful, results
"""
self.inputs.set(**inputs)
self._check_mandatory_inputs()
interface = self.__class__
# initialize provenance tracking
env = deepcopy(os.environ.data)
runtime = Bunch(cwd=os.getcwd(),
returncode=None,
duration=None,
environ=env,
hostname=gethostname())
t = time()
try:
runtime = self._run_interface(runtime)
runtime.duration = time() - t
results = InterfaceResult(interface, runtime,
inputs=self.inputs.get_traitsfree())
results.outputs = self.aggregate_outputs(results.runtime)
except Exception, e:
if len(e.args) == 0:
e.args = ("")
message = "\nInterface %s failed to run." % self.__class__.__name__
if config.has_option('logging', 'interface_level') and config.get('logging', 'interface_level').lower() == 'debug':
inputs_str = "Inputs:" + str(self.inputs) + "\n"
else:
inputs_str = ''
if len(e.args) == 1 and isinstance(e.args[0], str):
e.args = (e.args[0] + " ".join([message, inputs_str]),)
else:
e.args += (message, )
if inputs_str != '':
e.args += (inputs_str, )
#exception raising inhibition for special cases
if hasattr(self.inputs, 'ignore_exception') and \
isdefined(self.inputs.ignore_exception) and \
self.inputs.ignore_exception:
import traceback
runtime.traceback = traceback.format_exc()
runtime.traceback_args = e.args
return InterfaceResult(interface, runtime)
else:
raise