Beispiel #1
0
    def test_clone_trait(self):
        """ Method to test trait clone from string description.
        """
        # Test first to build trait description from nipype traits and then
        # to instanciate the trait
        to_test_fields = {
            "timing_units": "traits.Enum(('secs', 'scans'))",
            "bases": ("traits.Dict(traits.Enum(('hrf', 'fourier', "
                      "'fourier_han', 'gamma', 'fir')), traits.Any())"),
            "mask_image": "traits.File(Undefined)",
            "microtime_onset": "traits.Float()",
            "mask_threshold": ("traits.Either(traits.Enum(('-Inf',)), "
                               "traits.Float())")
        }
        i = spm.Level1Design()
        for field, result in six.iteritems(to_test_fields):

            # Test to build the trait expression
            trait = i.inputs.trait(field)
            expression = build_expression(trait)
            self.assertEqual(expression, result)

            # Try to clone the trait
            trait = eval_trait(expression)()
            self.assertEqual(build_expression(trait), result)

        to_test_fields = {
            "contrasts": (
                "traits.List(traits.Either(traits.Tuple(traits.Str(), "
                "traits.Enum(('T',)), traits.List(traits.Str()), "
                "traits.List(traits.Float())), traits.Tuple(traits.Str(), "
                "traits.Enum(('T',)), traits.List(traits.Str()), "
                "traits.List(traits.Float()), traits.List(traits.Float())), "
                "traits.Tuple(traits.Str(), traits.Enum(('F',)), "
                "traits.List(traits.Either(traits.Tuple(traits.Str(), "
                "traits.Enum(('T',)), traits.List(traits.Str()), "
                "traits.List(traits.Float())), traits.Tuple(traits.Str(), "
                "traits.Enum(('T',)), traits.List(traits.Str()), "
                "traits.List(traits.Float()), traits.List(traits.Float())"
                "))))))"),
            "use_derivs": "traits.Bool()"
        }
        i = spm.EstimateContrast()
        for field, result in six.iteritems(to_test_fields):

            # Test to build the trait expression
            trait = i.inputs.trait(field)
            expression = build_expression(trait)
            self.assertEqual(expression, result)

            # Try to clone the trait
            trait = eval_trait(expression)()
            self.assertEqual(build_expression(trait), result)

        # Test to clone some traits
        trait_description = ["Float", "Int"]
        handler = clone_trait(trait_description)
        trait = handler.as_ctrait()
        self.assertEqual(trait_description, trait_ids(trait))
Beispiel #2
0
    def sync_process_output_traits(process_instance, name, value):
        """ Event handler function to update the process instance outputs

        This callback is only called when an input process instance trait is
        modified.

        Parameters
        ----------
        process_instance: process instance (mandatory)
            the process instance that contain the nipype interface we want
            to update.
        name: str (mandatory)
            the name of the trait we want to update.
        value: type (manndatory)
            the old trait value
        """
        # Get all the input traits
        input_traits = process_instance.traits(output=False)

        # Try to update all the output process instance traits values when
        # a process instance input trait is modified.
        if name in input_traits:

            # Try to set all the process instance output traits values from
            # the nipype autocompleted traits values
            try:
                nipype_outputs = (process_instance.
                                  _nipype_interface._list_outputs())

                # Synchronize traits: check file existance
                for out_name, out_value in nipype_outputs.iteritems():

                    # Get trait type
                    trait_type = trait_ids(
                        process_instance._nipype_interface.output_spec().
                        trait(out_name))

                    # Set the output process trait value
                    # If we have a file check that the file exists before
                    # setting the new value
                    if (trait_type[0] is not "File" or
                       os.path.isfile(repr(out_value))):

                        process_instance.set_parameter(
                            "_" + out_name, out_value)

            # If we can't update the output process instance traits values,
            # print a logging debug message.
            except Exception:
                ex_type, ex, tb = sys.exc_info()
                logger.debug(
                    "Something wrong in the nipype output trait "
                    "synchronization:\n\n\tError: {0} - {1}\n"
                    "\tTraceback:\n{2}".format(
                        ex_type, ex, "".join(traceback.format_tb(tb))))
Beispiel #3
0
    def onCreateViewerClicked(self):
        """ Event to create the viewer
        """
        # Get the viewer node and process
        viewer_node = self.pipeline.nodes[self.viewer_node_name]
        viewer_process = viewer_node.process

        # Propagate the parameters to the input viewer node
        # And check if the viewer is active (ie dependencies
        # are specified -> corresponding process have run)
        is_viewer_active = True
        for plug_name, plug in six.iteritems(viewer_node.plugs):

            if plug_name in ["nodes_activation", "selection_changed"]:
                continue

            # Since it is a viewer node we normally have only inputs
            for (source_node_name, source_plug_name, source_node, source_plug,
                 weak_link) in plug.links_from:

                # Get the source plug value and source trait
                source_plug_value = getattr(source_node.process,
                                            source_plug_name)
                source_trait = source_node.process.trait(source_plug_name)

                # Check if the viewer is active:
                # 1) the source_plug_value has been set
                if source_plug_value == source_trait.handler.default_value:
                    is_viewer_active = False
                    break
                # 2) if the plug is a file, the file exists
                str_description = trait_ids(source_trait)
                if (len(str_description) == 1 and str_description[0] == "File"
                        and not os.path.isfile(source_plug_value)):

                    is_viewer_active = False
                    break

                # Update destination trait
                setattr(viewer_process, plug_name, source_plug_value)

            # Just stop the iterations if the status of the viewer
            # is alreadu known
            if not is_viewer_active:
                break

        # Execute the viewer process using the defined study configuration
        if is_viewer_active:
            soma.subprocess.Popen(viewer_process.get_commandline())
            # self.study_config.run(viewer_process)
        else:
            logging.error("The viewer is not active yet, maybe "
                          "because the processings steps have not run or are "
                          "not finished.")
    def sync_process_output_traits(process_instance, name, value):
        """ Event handler function to update the process instance outputs

        This callback is only called when an input process instance trait is
        modified.

        Parameters
        ----------
        process_instance: process instance (mandatory)
            the process instance that contain the nipype interface we want
            to update.
        name: str (mandatory)
            the name of the trait we want to update.
        value: type (manndatory)
            the old trait value
        """
        # Get all the input traits
        input_traits = process_instance.traits(output=False)

        # Try to update all the output process instance traits values when
        # a process instance input trait is modified or when the dedicated
        # 'synchronize' trait value is modified
        if name in input_traits or name == "synchronize":

            # Try to set all the process instance output traits values from
            # the nipype autocompleted traits values
            try:
                nipype_outputs = (
                    process_instance._nipype_interface._list_outputs())

                # Synchronize traits: check file existance
                for out_name, out_value in six.iteritems(nipype_outputs):

                    # Get trait type
                    trait_type = trait_ids(
                        process_instance._nipype_interface.output_spec().trait(
                            out_name))

                    # Set the output process trait value
                    process_instance.set_parameter("_" + out_name, out_value)

            # If we can't update the output process instance traits values,
            # print a logging debug message.
            except Exception:
                ex_type, ex, tb = sys.exc_info()
                logger.debug("Something wrong in the nipype output trait "
                             "synchronization:\n\n\tError: {0} - {1}\n"
                             "\tTraceback:\n{2}".format(
                                 ex_type, ex,
                                 "".join(traceback.format_tb(tb))))
Beispiel #5
0
    def _list_outputs(self):
        """ Method to list all the interface outputs.

        Returns
        -------
        outputs: dict
            all the interface outputs
        """
        # Get the outputs from the nipype method
        outputs = self._list_outputs_core()

        # Modify the output paths
        corrected_outputs = {}
        for trait_name, trait_value in outputs.iteritems():
            trait_desc = trait_ids(self.output_spec().trait(trait_name))
            if len(trait_desc) != 1:
                raise ValueError("Do not deal for the moment with Either "
                                 "nipype output traits.")
            corrected_outputs[trait_name] = self._modify_path(
                trait_value, trait_desc[0].split("_"))
        return corrected_outputs
Beispiel #6
0
    def test_clone_trait(self):
        """ Method to test trait clone from string description.
        """
        # Test first to build trait description from nipype traits and then
        # to instanciate the trait
        to_test_fields = {
            "timing_units":
            "traits.Enum(('secs', 'scans'))",
            "bases": ("traits.Dict(traits.Enum(('hrf', 'fourier', "
                      "'fourier_han', 'gamma', 'fir')), traits.Any())"),
            "mask_image":
            "traits.File(Undefined)",
            "microtime_onset":
            "traits.Float()",
            "mask_threshold": ("traits.Either(traits.Enum(('-Inf',)), "
                               "traits.Float())")
        }
        i = spm.Level1Design()
        for field, result in six.iteritems(to_test_fields):

            # Test to build the trait expression
            trait = i.inputs.trait(field)
            expression = build_expression(trait)
            self.assertEqual(expression, result)

            # Try to clone the trait
            trait = eval_trait(expression)()
            self.assertEqual(build_expression(trait), result)

        to_test_fields = {
            "contrasts":
            ("traits.List(traits.Either(traits.Tuple(traits.Str(), "
             "traits.Enum(('T',)), traits.List(traits.Str()), "
             "traits.List(traits.Float())), traits.Tuple(traits.Str(), "
             "traits.Enum(('T',)), traits.List(traits.Str()), "
             "traits.List(traits.Float()), traits.List(traits.Float())), "
             "traits.Tuple(traits.Str(), traits.Enum(('F',)), "
             "traits.List(traits.Either(traits.Tuple(traits.Str(), "
             "traits.Enum(('T',)), traits.List(traits.Str()), "
             "traits.List(traits.Float())), traits.Tuple(traits.Str(), "
             "traits.Enum(('T',)), traits.List(traits.Str()), "
             "traits.List(traits.Float()), traits.List(traits.Float())"
             "))))))"),
            "use_derivs":
            "traits.Bool()"
        }
        i = spm.EstimateContrast()
        for field, result in six.iteritems(to_test_fields):

            # Test to build the trait expression
            trait = i.inputs.trait(field)
            expression = build_expression(trait)
            self.assertEqual(expression, result)

            # Try to clone the trait
            trait = eval_trait(expression)()
            self.assertEqual(build_expression(trait), result)

        # Test to clone some traits
        trait_description = ["Float", "Int"]
        handler = clone_trait(trait_description)
        trait = handler.as_ctrait()
        self.assertEqual(trait_description, trait_ids(trait))
Beispiel #7
0
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Create the widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: str (mandatory)
            the default control value, here the enum values
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: QComboBox,
            associated label: QLabel)
        """
        # Create the widget that will be used to select a value
        widget = Qt.QWidget(parent)

        # we have a combobox for the trait type, and one of the control types
        # implementations depending on it

        layout = Qt.QVBoxLayout()
        widget.setLayout(layout)
        widget.type_combo = Qt.QComboBox()
        hlayout = Qt.QHBoxLayout()
        #layout.addLayout(hlayout)
        lwidget = Qt.QWidget()
        lwidget.setLayout(hlayout)
        hlayout.addWidget(Qt.QLabel('Compound type:'))
        hlayout.addWidget(widget.type_combo)
        widget.header_widget = lwidget
        widget.user_data = user_data

        # get compound types
        types = trait_ids(trait)
        for t in types:
            widget.type_combo.addItem(t)
        widget.type_combo.setCurrentIndex(0)

        widget.compound_widget = None
        widget.trait = trait  # we need to access it later
        widget.trait_name = control_name
        widget.compound_label = None

        type_id = CompoundControlWidget.type_id_for(trait.handler.handlers,
                                                    control_value)
        widget.current_type_id = type_id
        widget.type_combo.setCurrentIndex(type_id)

        CompoundControlWidget.create_compound_widget(widget)

        widget.type_combo.currentIndexChanged.connect(
            partial(CompoundControlWidget.change_type_index, widget))

        # Add a parameter to tell us if the widget is optional
        widget.optional = trait.optional

        # Create the label associated with the enum widget
        control_label = trait.label
        if control_label is None:
            control_label = control_name
        if label_class is None:
            label_class = Qt.QLabel
        if control_label is not None:
            label = (label_class(control_label, parent), lwidget)
        else:
            label = lwidget

        return (widget, label)