Ejemplo n.º 1
0
    def _run_interface(self, runtime):
        # Create function handle
        if self.as_module: 
            import importlib 
            pieces = self.inputs.function_str.split('.') 
            module = '.'.join(pieces[:-1]) 
            function = pieces[-1] 
            try: 
                function_handle = getattr(importlib.import_module(module), function) 
            except ImportError: 
                raise RuntimeError('Could not import module: %s' % self.inputs.function_str) 
        else: 
            function_handle = create_function_from_source(self.inputs.function_str, 
                                                          self.imports) 

        # Get function args
        args = {}
        for name in self._input_names:
            value = getattr(self.inputs, name)
            if isdefined(value):
                args[name] = value

        out = function_handle(**args)
        if len(self._output_names) == 1:
            self._out[self._output_names[0]] = out
        else:
            if isinstance(out, tuple) and \
                    (len(out) != len(self._output_names)):
                raise RuntimeError('Mismatch in number of expected outputs')

            else:
                for idx, name in enumerate(self._output_names):
                    self._out[name] = out[idx]

        return runtime
Ejemplo n.º 2
0
    def _set_function_string(self, obj, name, old, new):
        if name == 'function_str':
            self.inputs.function_str_hash = ''

            if self.as_module:
                module = inspect.getmodule(new).__name__
                full_name = "%s.%s" % (module, new.__name__)
                self.inputs.function_str = full_name
                self.inputs.function_str_hash = hashlib.md5(
                    getsource(new)).hexdigest()
            elif hasattr(new, '__call__'):
                function_source = getsource(new)
                fninfo = new.__code__
            elif isinstance(new, (str, bytes)):
                function_source = new
                fninfo = create_function_from_source(new,
                                                     self.imports).__code__

            self.inputs.trait_set(trait_change_notify=False,
                                  **{'%s' % name: function_source})

            # Update input traits
            input_names = fninfo.co_varnames[:fninfo.co_argcount]
            new_names = set(input_names) - set(self._input_names)
            add_traits(self.inputs, list(new_names))
            self._input_names.extend(new_names)
Ejemplo n.º 3
0
    def _run_interface(self, runtime):
        # Create function handle
        if self.as_module: 
            import importlib 
            pieces = self.inputs.function_str.split('.') 
            module = '.'.join(pieces[:-1]) 
            function = pieces[-1] 
            try: 
                function_handle = getattr(importlib.import_module(module), function) 
            except ImportError: 
                raise RuntimeError('Could not import module: %s' % self.inputs.function_str) 
        else: 
            function_handle = create_function_from_source(self.inputs.function_str, 
                                                          self.imports) 

        # Get function args
        args = {}
        for name in self._input_names:
            value = getattr(self.inputs, name)
            if isdefined(value):
                args[name] = value

        out = function_handle(**args)
        if len(self._output_names) == 1:
            self._out[self._output_names[0]] = out
        else:
            if isinstance(out, tuple) and \
                    (len(out) != len(self._output_names)):
                raise RuntimeError('Mismatch in number of expected outputs')

            else:
                for idx, name in enumerate(self._output_names):
                    self._out[name] = out[idx]

        return runtime
Ejemplo n.º 4
0
def test_func_to_str():
    def func1(x):
        return x**2

    # Should be ok with both functions!
    for f in _func1, func1:
        f_src = getsource(f)
        f_recreated = create_function_from_source(f_src)
        assert f(2.3) == f_recreated(2.3)
Ejemplo n.º 5
0
 def _set_function_string(self, obj, name, old, new):
     if name == 'function_str':
         if self.as_module:
             module = inspect.getmodule(new).__name__
             full_name = "%s.%s" % (module, new.__name__)
             self.inputs.function_str = full_name
         elif hasattr(new, '__call__'):
             function_source = getsource(new)
             fninfo = new.__code__
         elif isinstance(new, (str, bytes)):
             function_source = new
             fninfo = create_function_from_source(new,
                                                  self.imports).__code__
         self.inputs.trait_set(
             trait_change_notify=False, **{
                 '%s' % name: function_source
             })
         # Update input traits
         input_names = fninfo.co_varnames[:fninfo.co_argcount]
         new_names = set(input_names) - set(self._input_names)
         add_traits(self.inputs, list(new_names))
         self._input_names.extend(new_names)
Ejemplo n.º 6
0
def test_func_print_py2():
    wrapped_func = create_function_from_source(getsource(_print_statement))
    assert wrapped_func()
Ejemplo n.º 7
0
def test_func_string():
    def is_string():
        return isinstance('string', str)

    wrapped_func = create_function_from_source(getsource(is_string))
    assert is_string() == wrapped_func()
Ejemplo n.º 8
0
def test_func_to_str_err():
    bad_src = "obbledygobbledygook"
    with pytest.raises(RuntimeError): create_function_from_source(bad_src)
Ejemplo n.º 9
0
    def __init__(self,
                 input_names=None,
                 output_names='out',
                 function=None,
                 imports=None,
                 as_module=False,
                 **inputs):
        """

        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 : callable
            callable python object. must be able to execute in an
            isolated namespace (possibly in concert with the ``imports``
            parameter)
        imports : list of strings
            list of import statements that allow the function to execute
            in an otherwise empty namespace
        """

        super(Function, self).__init__(**inputs)
        if function:
            if as_module:
                module = inspect.getmodule(function).__name__
                full_name = "%s.%s" % (module, function.__name__)
                self.inputs.function_str = full_name
            elif hasattr(function, '__call__'):
                try:
                    self.inputs.function_str = getsource(function)
                except IOError:
                    raise Exception('Interface Function does not accept '
                                    'function objects defined interactively '
                                    'in a python session')
                else:
                    if input_names is None:
                        fninfo = function.__code__
            elif isinstance(function, (str, bytes)):
                self.inputs.function_str = function
                if input_names is None:
                    fninfo = create_function_from_source(function,
                                                         imports).__code__
            else:
                raise Exception('Unknown type of function')
            if input_names is None:
                input_names = fninfo.co_varnames[:fninfo.co_argcount]

        self.as_module = as_module
        self.inputs.on_trait_change(self._set_function_string, 'function_str')
        self._input_names = ensure_list(input_names)
        self._output_names = ensure_list(output_names)
        add_traits(self.inputs, [name for name in self._input_names])
        self.imports = imports
        self._out = {}
        for name in self._output_names:
            self._out[name] = None
Ejemplo n.º 10
0
def test_func_print_py2():
    wrapped_func = create_function_from_source(getsource(_print_statement))
    assert wrapped_func()
Ejemplo n.º 11
0
def test_func_string():
    def is_string():
        return isinstance('string', str)

    wrapped_func = create_function_from_source(getsource(is_string))
    assert is_string() == wrapped_func()
Ejemplo n.º 12
0
def test_func_to_str_err():
    bad_src = "obbledygobbledygook"
    with pytest.raises(RuntimeError):
        create_function_from_source(bad_src)
Ejemplo n.º 13
0
def Nipype1topydratask(interface):
    import pydra
    from pydra.engine.task import ShellCommandTask
    from nipype.utils.functions import create_function_from_source
    from nipype.interfaces import utility as niu
    from nipype.interfaces import base as bs
    from nipype.pipeline import engine as pe

    if not isinstance(interface, pe.Node):
        # Set the Node name
        if isinstance(interface, bs.CommandLine):
            node_name = interface.cmd
        elif isinstance(interface, niu.Function):
            node_name = interface.fullname
        else:
            node_name = interface.__class__.__name__

        # Make a Node
        interface = pe.Node(
            interface,
            name=node_name,
        )

    # Function interface case
    if isinstance(interface.interface, niu.Function):
        # Get inputs
        ins = interface.inputs
        interface_dict = ins.get()
        building_blocks = interface_dict.keys()
        input_vars = []
        for element in building_blocks:
            if element == 'function_str':
                niu_function = interface_dict[element]
            else:
                input_vars.append(element)
            if element == 'imports':
                niu_imports = interface_dict[element]
            else:
                niu_imports = None

        # Get outputs
        outs = interface.outputs
        interface_dict = outs.get()
        building_blocks = interface_dict.keys()
        output_vars = []
        for element in building_blocks:
            output_vars.append(element)
        return pydra.mark.task(
            create_function_from_source(niu_function, imports=niu_imports))

    elif isinstance(interface.interface, bs.SimpleInterface):
        # Get inputs
        ins = interface.inputs
        interface_dict = ins.get()
        building_blocks = interface_dict.keys()
        input_vars = []
        for element in building_blocks:
            input_vars.append(element)
            # if element == 'imports':
            #     niu_imports = interface_dict[element]
            # else:
            #     niu_imports = None
        niu_function = interface.interface._run_interface.__func__

        # Get outputs
        outs = interface.outputs
        interface_dict = outs.get()
        building_blocks = interface_dict.keys()
        output_vars = []
        for element in building_blocks:
            output_vars.append(element)
        #return pydra.mark.task(create_function_from_source(niu_function, imports=niu_imports))
        return pydra.mark.task(niu_function)

    # Commandline interface case
    elif isinstance(interface.interface, bs.CommandLine):
        cmdline = interface.interface.cmdline.split(' ')
        sct = ShellCommandTask(name=interface.name, executable=cmdline)
        return sct
Ejemplo n.º 14
0
    def __init__(self,
                 input_names=None,
                 output_names='out',
                 function=None,
                 imports=None,
                 as_module=False,
                 **inputs):
        """

        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 : callable
            callable python object. must be able to execute in an
            isolated namespace (possibly in concert with the ``imports``
            parameter)
        imports : list of strings
            list of import statements that allow the function to execute
            in an otherwise empty namespace
        """

        super(Function, self).__init__(**inputs)
        if function:
            if as_module:
                module = inspect.getmodule(function).__name__
                full_name = "%s.%s" % (module, function.__name__)
                self.inputs.function_str = full_name
            elif hasattr(function, '__call__'):
                try:
                    self.inputs.function_str = getsource(function)
                except IOError:
                    raise Exception('Interface Function does not accept '
                                    'function objects defined interactively '
                                    'in a python session')
                else:
                    if input_names is None:
                        fninfo = function.__code__
            elif isinstance(function, (str, bytes)):
                self.inputs.function_str = function
                if input_names is None:
                    fninfo = create_function_from_source(function,
                                                         imports).__code__
            else:
                raise Exception('Unknown type of function')
            if input_names is None:
                input_names = fninfo.co_varnames[:fninfo.co_argcount]

        self.as_module = as_module
        self.inputs.on_trait_change(self._set_function_string, 'function_str')
        self._input_names = ensure_list(input_names)
        self._output_names = ensure_list(output_names)
        add_traits(self.inputs, [name for name in self._input_names])
        self.imports = imports
        self._out = {}
        for name in self._output_names:
            self._out[name] = None