desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initializes outputs'
@classmethod def _outputs(cls):
raise NotImplementedError
'Execute the command.'
def run(self):
raise NotImplementedError
'Called to populate outputs'
def aggregate_outputs(self, runtime=None, needed_outputs=None):
raise NotImplementedError
'List expected outputs'
def _list_outputs(self):
raise NotImplementedError
'Provides information about file inputs to copy or link to cwd. Necessary for pipeline operation'
def _get_filecopy_info(self):
raise NotImplementedError
'Prints class help'
@classmethod def help(cls, returnhelp=False):
if cls.__doc__: docstring = (trim(cls.__doc__).split(u'\n') + [u'']) else: docstring = [u''] allhelp = u'\n'.join(((((((docstring + cls._inputs_help()) + [u'']) + cls._outputs_help()) + [u'']) + cls._refs_help()) + [u''])) if returnhelp: return allhelp else: print(all...
'Prints interface references.'
@classmethod def _refs_help(cls):
if (not cls.references_): return [] helpstr = [u'References::'] for r in cls.references_: helpstr += [u'{}'.format(r[u'entry'])] return helpstr
'Prints description for input parameters'
@classmethod def _inputs_help(cls):
helpstr = [u'Inputs::'] inputs = cls.input_spec() if (len(list(inputs.traits(transient=None).items())) == 0): helpstr += [u'', u' DCTB None'] return helpstr manhelpstr = [u'', u' DCTB [Mandatory]'] mandatory_items = inputs.traits(mandatory=True) for (name, spec) in sorted(mandato...
'Prints description for output parameters'
@classmethod def _outputs_help(cls):
helpstr = [u'Outputs::', u''] if cls.output_spec: outputs = cls.output_spec() for (name, spec) in sorted(outputs.traits(transient=None).items()): helpstr += cls._get_trait_desc(outputs, name, spec) if (len(helpstr) == 2): helpstr += [u' DCTB None'] return helpstr
'Returns a bunch containing output fields for the class'
def _outputs(self):
outputs = None if self.output_spec: outputs = self.output_spec() return outputs
'Provides information about file inputs to copy or link to cwd. Necessary for pipeline operation'
@classmethod def _get_filecopy_info(cls):
info = [] if (cls.input_spec is None): return info metadata = dict(copyfile=(lambda t: (t is not None))) for (name, spec) in sorted(cls.input_spec().traits(**metadata).items()): info.append(dict(key=name, copy=spec.copyfile)) return info
'check if required inputs are satisfied'
def _check_requires(self, spec, name, value):
if spec.requires: values = [(not isdefined(getattr(self.inputs, field))) for field in spec.requires] if (any(values) and isdefined(value)): msg = (u"%s requires a value for input '%s' because one of %s is set. For a list of required i...
'check if mutually exclusive inputs are satisfied'
def _check_xor(self, spec, name, value):
if spec.xor: values = [isdefined(getattr(self.inputs, field)) for field in spec.xor] if ((not any(values)) and (not isdefined(value))): msg = (u"%s requires a value for one of the inputs '%s'. For a list of required inputs, see %s.help()...
'Raises an exception if a mandatory input is Undefined'
def _check_mandatory_inputs(self):
for (name, spec) in list(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 = (u"%s requires a value for input '%s'. For a list of...
'Raises an exception on version mismatch'
def _check_version_requirements(self, trait_object, raise_exception=True):
unavailable_traits = [] check = dict(min_ver=(lambda t: (t is not None))) names = trait_object.trait_names(**check) if (names and self.version): version = LooseVersion(str(self.version)) for name in names: min_ver = LooseVersion(str(trait_object.traits()[name].min_ver)) ...
'Core function that executes interface'
def _run_interface(self, runtime):
raise NotImplementedError
'Add the interface references to the duecredit citations'
def _duecredit_cite(self):
for r in self.references_: r[u'path'] = self.__module__ due.cite(**r)
'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'
def run(self, **inputs):
self.inputs.trait_set(**inputs) self._check_mandatory_inputs() self._check_version_requirements(self.inputs) interface = self.__class__ self._duecredit_cite() env = deepcopy(dict(os.environ)) runtime = Bunch(cwd=os.getcwd(), returncode=None, duration=None, environ=env, startTime=dt.isoformat...
'List the expected outputs'
def _list_outputs(self):
if self.output_spec: raise NotImplementedError else: return None
'Collate expected outputs and check for existence'
def aggregate_outputs(self, runtime=None, needed_outputs=None):
predicted_outputs = self._list_outputs() outputs = self._outputs() if predicted_outputs: _unavailable_outputs = [] if outputs: _unavailable_outputs = self._check_version_requirements(self._outputs()) for (key, val) in list(predicted_outputs.items()): if (neede...
'A convenient way to load pre-set inputs from a JSON file.'
def load_inputs_from_json(self, json_file, overwrite=True):
with open(json_file) as fhandle: inputs_dict = json.load(fhandle) def_inputs = [] if (not overwrite): def_inputs = list(self.inputs.get_traitsfree().keys()) new_inputs = list((set(list(inputs_dict.keys())) - set(def_inputs))) for key in new_inputs: if hasattr(self.inputs, key...
'A convenient way to save current inputs to a JSON file.'
def save_inputs_to_json(self, json_file):
inputs = self.inputs.get_traitsfree() iflogger.debug(u'saving inputs {}', inputs) with open(json_file, (u'w' if PY3 else u'wb')) as fhandle: json.dump(inputs, fhandle, indent=4, ensure_ascii=False)
'Pass-through for file descriptor.'
def fileno(self):
return self._impl.fileno()
'Read from the file descriptor. If \'drain\' set, read until EOF.'
def read(self, drain=0):
while (self._read(drain) is not None): if (not drain): break
'Read from the file descriptor'
def _read(self, drain):
fd = self.fileno() buf = os.read(fd, 4096).decode(self.default_encoding) if ((not buf) and (not self._buf)): return None if (u'\n' not in buf): if (not drain): self._buf += buf return [] buf = (self._buf + buf) if (u'\n' in buf): (tmp, rest) = buf....
'Set the default terminal output for CommandLine Interfaces. This method is used to set default terminal output for CommandLine Interfaces. However, setting this will not update the output type for any existing instances. For these, assign the <instance>.inputs.terminal_output.'
@classmethod def set_default_terminal_output(cls, output_type):
if (output_type in [u'stream', u'allatonce', u'file', u'none']): cls._terminal_output = output_type else: raise AttributeError((u'Invalid terminal output_type: %s' % output_type))
'sets base command, immutable'
@property def cmd(self):
return self._cmd
'`command` plus any arguments (args) validates arguments and generates command line'
@property def cmdline(self):
self._check_mandatory_inputs() allargs = self._parse_inputs() allargs.insert(0, self.cmd) return u' '.join(allargs)
'Execute command via subprocess Parameters runtime : passed by the run function Returns runtime : updated runtime information adds stdout, stderr, merged, cmdline, dependencies, command_path'
def _run_interface(self, runtime, correct_return_codes=(0,)):
setattr(runtime, u'stdout', None) setattr(runtime, u'stderr', None) setattr(runtime, u'cmdline', self.cmdline) out_environ = self._get_environ() runtime.environ.update(out_environ) executable_name = self.cmd.split()[0] (exist_val, cmd_path) = _exists_in_path(executable_name, runtime.environ)...
'A helper function for _parse_inputs Formats a trait containing argstr metadata'
def _format_arg(self, name, trait_spec, value):
argstr = trait_spec.argstr iflogger.debug((u'%s_%s' % (name, str(value)))) if (trait_spec.is_trait_type(traits.Bool) and (u'%' not in argstr)): if value: return argstr else: return None elif (trait_spec.is_trait_type(traits.List) or (trait_spec.is_trait_type(trait...
'Parse all inputs using the ``argstr`` format string in the Trait. Any inputs that are assigned (not the default_value) are formatted to be added to the command line. Returns all_args : list A list of all inputs formatted for the command line.'
def _parse_inputs(self, skip=None):
all_args = [] initial_args = {} final_args = {} metadata = dict(argstr=(lambda t: (t is not None))) for (name, spec) in sorted(self.inputs.traits(**metadata).items()): if (skip and (name in skip)): continue value = getattr(self.inputs, name) if spec.name_source: ...
'Adds \'mpiexec\' to begining of command'
@property def cmdline(self):
result = [] if self.inputs.use_mpi: result.append(u'mpiexec') if self.inputs.n_procs: result.append((u'-n %d' % self.inputs.n_procs)) result.append(super(MpiCommandLine, self).cmdline) return u' '.join(result)
'validate and process inputs into useful form. Returns a list of nilearn maskers and the list of corresponding label names.'
def _process_inputs(self):
import nilearn.input_data as nl import nilearn.image as nli label_data = nli.concat_imgs(self.inputs.label_files) maskers = [] if (np.amax(label_data.get_data()) > 1): n_labels = np.amax(label_data.get_data()) maskers.append(nl.NiftiLabelsMasker(label_data)) else: n_label...
'takes a 3-dimensional numpy array and an affine, returns the equivalent 4th dimensional nifti file'
def _4d(self, array, affine):
return nb.Nifti1Image(array[:, :, :, np.newaxis], affine)
'Parameters input_names: single str or list or None names corresponding to function inputs if ``None``, derive input names from function argument names output_names: single str or list names corresponding to function outputs (default: \'out\'). if list of length > 1, has to match the number of outputs function : callab...
def __init__(self, input_names=None, output_names=u'out', function=None, imports=None, **inputs):
super(Function, self).__init__(**inputs) if function: if hasattr(function, u'__call__'): try: self.inputs.function_str = getsource(function) except IOError: raise Exception(u'Interface Function does not accept function objects ...
''
def __init__(self, filename):
import threading self._filename = filename self._size = float(os.path.getsize(filename)) self._seen_so_far = 0 self._lock = threading.Lock()
''
def __call__(self, bytes_amount):
import sys with self._lock: self._seen_so_far += bytes_amount if (self._size != 0): percentage = ((self._seen_so_far // self._size) * 100) else: percentage = 0 progress_str = (u'%d / %d (%.2f%%)\r' % (self._seen_so_far, self._size, percentage)) ...
'Parameters infields : list of str Indicates the input fields to be dynamically created'
def __init__(self, infields=None, force_run=True, **kwargs):
super(DataSink, self).__init__(**kwargs) undefined_traits = {} self._infields = infields if infields: for key in infields: self.inputs.add_trait(key, traits.Any) self.inputs._outputs[key] = Undefined undefined_traits[key] = Undefined self.inputs.trait_set(...
'Method to see if the datasink\'s base directory specifies an S3 bucket path; if it does, it parses the path for the bucket name in the form \'s3://bucket_name/...\' and returns it Parameters Returns s3_flag : boolean flag indicating whether the base_directory contained an S3 bucket path bucket_name : string name of th...
def _check_s3_base_dir(self):
s3_str = u's3://' bucket_name = u'<N/A>' base_directory = self.inputs.base_directory if (not isdefined(base_directory)): s3_flag = False return (s3_flag, bucket_name) if base_directory.lower().startswith(s3_str): base_dir_sp = base_directory.split(u'/') base_dir_sp[0]...
'Method to return AWS access key id and secret access key using credentials found in a local file. Parameters self : nipype.interfaces.io.DataSink self for instance method Returns aws_access_key_id : string string of the AWS access key ID aws_secret_access_key : string string of the AWS secret access key'
def _return_aws_keys(self):
import os creds_path = self.inputs.creds_path if (creds_path and os.path.exists(creds_path)): with open(creds_path, u'r') as creds_in: row1 = creds_in.readline() row2 = creds_in.readline() if (u'User Name' in row1): aws_access_key_id = row2.split(u',')[...
'Method to return a bucket object which can be used to interact with an AWS S3 bucket using credentials found in a local file. Parameters self : nipype.interfaces.io.DataSink self for instance method bucket_name : string string corresponding to the name of the bucket on S3 Returns bucket : boto3.resources.factory.s3.Bu...
def _fetch_bucket(self, bucket_name):
import logging try: import boto3 import botocore except ImportError as exc: err_msg = u'Boto3 package is not installed - install boto3 and try again.' raise Exception(err_msg) creds_path = self.inputs.creds_path iflogger = logging.getLogg...
'Method to upload outputs to S3 bucket instead of on local disk'
def _upload_to_s3(self, bucket, src, dst):
import hashlib import logging import os from botocore.exceptions import ClientError iflogger = logging.getLogger(u'interface') s3_str = u's3://' s3_prefix = (s3_str + bucket.name) if dst.lower().startswith(s3_str): dst_sp = dst.split(u'/') dst_sp[0] = dst_sp[0].lower() ...
'Execute this module.'
def _list_outputs(self):
iflogger = logging.getLogger(u'interface') outputs = self.output_spec().get() out_files = [] use_hardlink = str2bool(config.get(u'execution', u'try_hard_link_datasink')) if isdefined(self.inputs.local_copy): outdir = self.inputs.local_copy else: outdir = self.inputs.base_director...
'Parameters infields : list of str Indicates the input fields to be dynamically created outfields: list of str Indicates output fields to be dynamically created See class examples for usage'
def __init__(self, infields=None, outfields=None, **kwargs):
if (not outfields): outfields = [u'outfiles'] super(S3DataGrabber, self).__init__(**kwargs) undefined_traits = {} self._infields = infields self._outfields = outfields if infields: for key in infields: self.inputs.add_trait(key, traits.Any) undefined_trait...
'S3 specific: Downloads relevant files to a local folder specified Using traits.Any instead out OutputMultiPath till add_trait bug is fixed.'
def _add_output_traits(self, base):
return add_traits(base, list(self.inputs.template_args.keys()))
'Parameters infields : list of str Indicates the input fields to be dynamically created outfields: list of str Indicates output fields to be dynamically created See class examples for usage'
def __init__(self, infields=None, outfields=None, **kwargs):
if (not outfields): outfields = [u'outfiles'] super(DataGrabber, self).__init__(**kwargs) undefined_traits = {} self._infields = infields self._outfields = outfields if infields: for key in infields: self.inputs.add_trait(key, traits.Any) undefined_traits[...
'Using traits.Any instead out OutputMultiPath till add_trait bug is fixed.'
def _add_output_traits(self, base):
return add_traits(base, list(self.inputs.template_args.keys()))
'Create an instance with specific input fields. Parameters templates : dictionary Mapping from string keys to string template values. The keys become output fields on the interface. The templates should use {}-formatting syntax, where the names in curly braces become inputs fields on the interface. Format strings can a...
def __init__(self, templates, **kwargs):
super(SelectFiles, self).__init__(**kwargs) infields = [] for (name, template) in list(templates.items()): for (_, field_name, _, _) in string.Formatter().parse(template): if (field_name is not None): field_name = re.match(u'\\w+', field_name).group() if (...
'Add the dynamic output fields'
def _add_output_traits(self, base):
return add_traits(base, list(self._templates.keys()))
'Find the files and expose them as interface outputs.'
def _list_outputs(self):
outputs = {} info = dict([(k, v) for (k, v) in list(self.inputs.__dict__.items()) if (k in self._infields)]) force_lists = self.inputs.force_lists if isinstance(force_lists, bool): force_lists = (self._outfields if force_lists else []) bad_fields = (set(force_lists) - set(self._outfields)) ...
'Parameters infields : list of str Indicates the input fields to be dynamically created outfields: list of str Indicates output fields to be dynamically created See class examples for usage'
def __init__(self, infields=None, outfields=None, **kwargs):
super(XNATSource, self).__init__(**kwargs) undefined_traits = {} self._infields = infields if infields: for key in infields: self.inputs.add_trait(key, traits.Any) undefined_traits[key] = Undefined self.inputs.query_template_args[u'outfiles'] = [infields] if o...
'Using traits.Any instead out OutputMultiPath till add_trait bug is fixed.'
def _add_output_traits(self, base):
return add_traits(base, list(self.inputs.query_template_args.keys()))
'Execute this module.'
def _list_outputs(self):
cache_dir = (self.inputs.cache_dir or tempfile.gettempdir()) if self.inputs.config: xnat = pyxnat.Interface(config=self.inputs.config) else: xnat = pyxnat.Interface(self.inputs.server, self.inputs.user, self.inputs.pwd, cache_dir) if self.inputs.share: subject_id = self.inputs.su...
'Execute this module.'
def _list_outputs(self):
conn = sqlite3.connect(self.inputs.database_file, check_same_thread=False) c = conn.cursor() c.execute((((((u'INSERT OR REPLACE INTO %s (' % self.inputs.table_name) + u','.join(self._input_names)) + u') VALUES (') + u','.join(([u'?'] * len(self._input_names)))) + u')'), [getattr(self.in...
'Execute this module.'
def _list_outputs(self):
import MySQLdb if isdefined(self.inputs.config): conn = MySQLdb.connect(db=self.inputs.database_name, read_default_file=self.inputs.config) else: conn = MySQLdb.connect(host=self.inputs.host, user=self.inputs.username, passwd=self.inputs.password, db=self.inputs.database_name) c = conn.c...
'Parameters infields : list of str Indicates the input fields to be dynamically created outfields: list of str Indicates output fields to be dynamically created See class examples for usage'
def __init__(self, infields=None, outfields=None, **kwargs):
try: paramiko except NameError: warn(u'The library paramiko needs to be installed for this module to run.') if (not outfields): outfields = [u'outfiles'] kwargs = kwargs.copy() kwargs[u'infields'] = infields kwargs[u'outfields'] = outfield...
'Method to instantiate TestRuntimeProfiler Parameters self : TestRuntimeProfile'
def setup_class(self):
self.num_gb = 1.0 self.num_threads = 2 self.mem_err_gb = 0.3
'Function to collect a range of runtime stats'
def _collect_range_runtime_stats(self, num_threads):
import json import numpy as np import pandas as pd ram_gb_range = 10.0 ram_gb_step = 0.25 dict_list = [] for num_gb in np.arange(0.25, (ram_gb_range + ram_gb_step), ram_gb_step): (cmd_start_str, cmd_fin_str) = self._run_cmdline_workflow(num_gb, num_threads) cmd_start_ts = jso...
'Function to run the use_resources cmdline script in a nipype workflow and return the runtime stats recorded by the profiler Parameters self : TestRuntimeProfile Returns finish_str : string a json-compatible dictionary string containing the runtime statistics of the nipype node that used system resources'
def _run_cmdline_workflow(self, num_gb, num_threads):
import logging import os import shutil import tempfile import nipype.pipeline.engine as pe import nipype.interfaces.utility as util from nipype.pipeline.plugins.callback_log import log_nodes_cb base_dir = tempfile.mkdtemp() log_file = os.path.join(base_dir, u'callback.log') logge...
'Function to run the use_resources() function in a nipype workflow and return the runtime stats recorded by the profiler Parameters self : TestRuntimeProfile Returns finish_str : string a json-compatible dictionary string containing the runtime statistics of the nipype node that used system resources'
def _run_function_workflow(self, num_gb, num_threads):
import logging import os import shutil import tempfile import nipype.pipeline.engine as pe import nipype.interfaces.utility as util from nipype.pipeline.plugins.callback_log import log_nodes_cb base_dir = tempfile.mkdtemp() log_file = os.path.join(base_dir, u'callback.log') logge...
'Test runtime profiler correctly records workflow RAM/CPUs consumption from a cmdline function'
@pytest.mark.skipif((run_profile == False), reason=skip_profile_msg) def test_cmdline_profiling(self):
import json import numpy as np num_gb = self.num_gb num_threads = self.num_threads (start_str, finish_str) = self._run_cmdline_workflow(num_gb, num_threads) node_stats = json.loads(finish_str) runtime_gb = float(node_stats[u'runtime_memory_gb']) runtime_threads = int(node_stats[u'runtime...
'Test runtime profiler correctly records workflow RAM/CPUs consumption from a python function'
@pytest.mark.skipif(True, reason=u'https://github.com/nipy/nipype/issues/1663') @pytest.mark.skipif((run_profile == False), reason=skip_profile_msg) def test_function_profiling(self):
import json import numpy as np num_gb = self.num_gb num_threads = self.num_threads (start_str, finish_str) = self._run_function_workflow(num_gb, num_threads) node_stats = json.loads(finish_str) runtime_gb = float(node_stats[u'runtime_memory_gb']) runtime_threads = int(node_stats[u'runtim...
'Test a node using the SignalExtraction interface. Unlike interface.run(), node.run() checks the traits'
def test_signal_extr_traits_valid(self):
node = pe.Node(iface.SignalExtraction(in_file=os.path.abspath(self.filenames['in_file']), label_files=os.path.abspath(self.filenames['label_files']), class_labels=self.labels, incl_shared_variance=False), name='SignalExtraction') node.run()
'Convenience method for converting input arrays [1,2,3] to commandline format \'1x2x3\''
@staticmethod def _format_xarray(val):
return u'x'.join([str(x) for x in val])
'Set the default number of threads for ITK calls This method is used to set the default number of ITK threads for all the ANTS interfaces. However, setting this will not update the output type for any existing instances. For these, assign the <instance>.inputs.num_threads'
@classmethod def set_default_num_threads(cls, num_threads):
cls._num_threads = num_threads
'Format the antsRegistration -m metric argument(s). Parameters index: the stage index'
def _format_metric(self, index):
name_input = self.inputs.metric[index] stage_inputs = dict(fixed_image=self.inputs.fixed_image[0], moving_image=self.inputs.moving_image[0], 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...
'Copy header from input image to an output image'
def _copy_header(self, fname):
import nibabel as nb in_img = nb.load(self.inputs.input_image) out_img = nb.load(fname, mmap=False) new_img = out_img.__class__(out_img.get_data(), in_img.affine, in_img.header) new_img.set_data_dtype(out_img.get_data_dtype()) new_img.to_filename(fname)
'initializes interface to matlab (default \'matlab -nodesktop -nosplash\')'
def __init__(self, matlab_cmd=None, **inputs):
super(MatlabCommand, self).__init__(**inputs) if (matlab_cmd and isdefined(matlab_cmd)): self._cmd = matlab_cmd elif self._default_matlab_cmd: self._cmd = self._default_matlab_cmd if (self._default_mfile and (not isdefined(self.inputs.mfile))): self.inputs.mfile = self._default_m...
'Set the default MATLAB command line for MATLAB classes. This method is used to set values for all MATLAB subclasses. However, setting this will not update the output type for any existing instances. For these, assign the <instance>.inputs.matlab_cmd.'
@classmethod def set_default_matlab_cmd(cls, matlab_cmd):
cls._default_matlab_cmd = matlab_cmd
'Set the default MATLAB script file format for MATLAB classes. This method is used to set values for all MATLAB subclasses. However, setting this will not update the output type for any existing instances. For these, assign the <instance>.inputs.mfile.'
@classmethod def set_default_mfile(cls, mfile):
cls._default_mfile = mfile
'Set the default MATLAB paths for MATLAB classes. This method is used to set values for all MATLAB subclasses. However, setting this will not update the output type for any existing instances. For these, assign the <instance>.inputs.paths.'
@classmethod def set_default_paths(cls, paths):
cls._default_paths = paths
'Generates commands and, if mfile specified, writes it to disk.'
def _gen_matlab_command(self, argstr, script_lines):
cwd = os.getcwd() mfile = (self.inputs.mfile or self.inputs.uses_mcr) paths = [] if isdefined(self.inputs.paths): paths = self.inputs.paths prescript = self.inputs.prescript postscript = self.inputs.postscript if mfile: prescript.insert(0, u"fprintf(1,'Executing %s at ...
'Check for minc version on the system Parameters None Returns version : dict Version number as dict or None if MINC not found'
@staticmethod def version():
try: clout = CommandLine(command=u'mincinfo', args=u'-version', terminal_output=u'allatonce').run() except IOError: return None out = clout.runtime.stdout def read_program_version(s): if (u'program' in s): return s.split(u':')[1].strip() return None def re...
'A number of the command line options expect precisely one or two files.'
def _parse_inputs(self):
nr_input_files = len(self.inputs.input_files) for n in self.input_spec.bool_or_const_traits: t = self.inputs.__getattribute__(n) if isdefined(t): if isinstance(t, bool): if (nr_input_files != 2): raise ValueError((u'Due to the %s option...
'Generate a filename based on the given parameters. The filename will take the form: cwd/basename<suffix><ext>. If change_ext is True, it will use the extentions specified in <instance>intputs.output_type. Parameters basename : str Filename to base the new filename on. cwd : str Path to prefix to the new filename. (def...
def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=u'.nii.gz'):
if (basename == u''): msg = (u'Unable to generate filename for command %s. ' % self.cmd) msg += u'basename is not set!' raise ValueError(msg) if (cwd is None): cwd = os.getcwd() if change_ext: if suffix: suffix = u''.join((suf...
'Init method calling super. No version to be checked.'
def __init__(self, **inputs):
super(NiftyFitCommand, self).__init__(**inputs)
'Rewrite the cmdline to write options in text_file.'
@property def cmdline(self):
argv = super(RegAverage, self).cmdline reg_average_cmd = os.path.join(os.getcwd(), u'reg_average_cmd') with open(reg_average_cmd, u'w') as f: f.write(argv) return (u'%s --cmd_file %s' % (self.cmd, reg_average_cmd))
'Returns the path to the SPM directory in the Matlab path If path not found, returns None. Parameters matlab_cmd: str Sets the default matlab command. If None, the value of the environment variable SPMMCRCMD will be used if set and use_mcr is True or the environment variable FORCE_SPMMCR is set. If one of FORCE_SPMMCR ...
@staticmethod def version(matlab_cmd=None, paths=None, use_mcr=None):
if (use_mcr or (u'FORCE_SPMMCR' in os.environ)): use_mcr = True if (matlab_cmd is None): try: matlab_cmd = os.environ[u'SPMMCRCMD'] except KeyError: pass if (matlab_cmd is None): try: matlab_cmd = os.environ[u'MATLABCMD'...
'Executes the SPM function using MATLAB.'
def _run_interface(self, runtime):
self.mlab.inputs.script = self._make_matlab_command(deepcopy(self._parse_inputs())) results = self.mlab.run() runtime.returncode = results.runtime.returncode if self.mlab.inputs.uses_mcr: if (u'Skipped' in results.runtime.stdout): self.raise_exception(runtime) runtime.stdout = re...
'Determine the expected outputs based on inputs.'
def _list_outputs(self):
raise NotImplementedError
'Convert input to appropriate format for SPM.'
def _format_arg(self, opt, spec, val):
if spec.is_trait_type(traits.Bool): return int(val) else: return val
'Encloses a dict representation within hierarchical lists. In order to create an appropriate SPM job structure, a Python dict storing the job needs to be modified so that each dict embedded in dict needs to be enclosed as a list element. Examples >>> a = SPMCommand()._reformat_dict_for_savemat(dict(a=1, ... ...
def _reformat_dict_for_savemat(self, contents):
newdict = {} try: for (key, value) in list(contents.items()): if isinstance(value, dict): if value: newdict[key] = self._reformat_dict_for_savemat(value) else: newdict[key] = value return [newdict] except TypeError: ...
'Recursive function to generate spm job specification as a string Parameters prefix : string A string that needs to get contents : dict A non-tuple Python structure containing spm job information gets converted to an appropriate sequence of matlab commands.'
def _generate_job(self, prefix=u'', contents=None):
jobstring = u'' if (contents is None): return jobstring if isinstance(contents, list): for (i, value) in enumerate(contents): if prefix.endswith(u')'): newprefix = (u'%s,%d)' % (prefix[:(-1)], (i + 1))) else: newprefix = (u'%s(%d)' % (p...
'Generates a mfile to build job structure Parameters contents : list a list of dicts generated by _parse_inputs in each subclass cwd : string default os.getcwd() Returns mscript : string contents of a script called by matlab'
def _make_matlab_command(self, contents, postscript=None):
cwd = os.getcwd() mscript = u"\n %% Generated by nipype.interfaces.spm\n if isempty(which('spm')),\n throw(MException('SPMCheck:NotFound', 'SPM not in matlab path'));\n ...
'Trait handles neuroimaging files. Parameters types : list Strings of file format types accepted compressed : boolean Indicates whether the file format can compressed'
def __init__(self, value=u'', filter=None, auto_set=False, entries=0, exists=False, types=[u'nifti1', u'nifti2'], allow_compressed=False, **metadata):
self.types = types self.allow_compressed = allow_compressed super(ImageFileSPM, self).__init__(value, filter, auto_set, entries, exists, types, allow_compressed, **metadata)
'makes filename to hold inverse transform if not specified'
def _make_inv_file(self):
invmat = fname_presuffix(self.inputs.mat, prefix=u'inverse_') return invmat
'makes name for matfile if doesn exist'
def _make_mat_file(self):
(pth, mv, _) = split_filename(self.inputs.moving) (_, tgt, _) = split_filename(self.inputs.target) mat = os.path.join(pth, (u'%s_to_%s.mat' % (mv, tgt))) return mat
'checks for SPM, generates script'
def _make_matlab_command(self, _):
if (not isdefined(self.inputs.mat)): self.inputs.mat = self._make_mat_file() if (not isdefined(self.inputs.invmat)): self.inputs.invmat = self._make_inv_file() script = (u"\n target = '%s';\n moving = '%s';\n ...
'checks for SPM, generates script'
def _make_matlab_command(self, _):
outputs = self._list_outputs() self.inputs.out_file = outputs[u'out_file'] script = (u"\n infile = '%s';\n outfile = '%s'\n transform = load('%s');\n\n V = spm_...
'generates script'
def _make_matlab_command(self, _):
if (not isdefined(self.inputs.out_file)): self.inputs.out_file = fname_presuffix(self.inputs.in_file, prefix=u'r') script = (u"\n flags.mean = 0;\n flags.which = 1;\n flags.mask = 0;\n ...
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'in_files'): return scans_for_fnames(filename_to_list(val)) if (opt == u'target'): return scans_for_fname(filename_to_list(val)) if (opt == u'deformation'): return np.array([list_to_filename(val)], dtype=object) if (opt == u'deformation_field'): return np.arra...
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'in_files'): return scans_for_fnames(filename_to_list(val)) if (opt == u'target'): return scans_for_fname(filename_to_list(val)) if (opt == u'deformation'): return np.array([list_to_filename(val)], dtype=object) if (opt == u'deformation_field'): return np.arra...
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'in_files'): return np.array(val, dtype=object) if (opt == u'output_dir'): return np.array([val], dtype=object) if (opt == u'output_dir'): return os.path.abspath(val) if (opt == u'icedims'): if val: return 1 return 0 return super(DicomI...
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'in_files'): return scans_for_fnames(filename_to_list(val), keep4d=False, separate_sessions=True) return super(SliceTiming, self)._format_arg(opt, spec, val)
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'in_files'): if (self.inputs.jobtype == u'write'): separate_sessions = False else: separate_sessions = True return scans_for_fnames(val, keep4d=False, separate_sessions=separate_sessions) return super(Realign, self)._format_arg(opt, spec, val)
'validate spm realign options if set to None ignore'
def _parse_inputs(self):
einputs = super(Realign, self)._parse_inputs() return [{(u'%s' % self.inputs.jobtype): einputs[0]}]
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if ((opt == u'target') or ((opt == u'source') and (self.inputs.jobtype != u'write'))): return scans_for_fnames(filename_to_list(val), keep4d=True) if (opt == u'apply_to_files'): return np.array(filename_to_list(val), dtype=object) if ((opt == u'source') and (self.inputs.jobtype == u'write'))...
'validate spm coregister options if set to None ignore'
def _parse_inputs(self):
if (self.inputs.jobtype == u'write'): einputs = super(Coregister, self)._parse_inputs(skip=(u'jobtype', u'apply_to_files')) else: einputs = super(Coregister, self)._parse_inputs(skip=u'jobtype') jobtype = self.inputs.jobtype return [{(u'%s' % jobtype): einputs[0]}]
'Convert input to appropriate format for spm'
def _format_arg(self, opt, spec, val):
if (opt == u'template'): return scans_for_fname(filename_to_list(val)) if (opt == u'source'): return scans_for_fname(filename_to_list(val)) if (opt == u'apply_to_files'): return scans_for_fnames(filename_to_list(val)) if (opt == u'parameter_file'): return np.array([list_t...
'Validate spm normalize options if set to None ignore'
def _parse_inputs(self):
einputs = super(Normalize, self)._parse_inputs(skip=(u'jobtype', u'apply_to_files')) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.source): inputfiles.extend(self.inputs.source) einputs[0][u'subj'][u'resam...