Пример #1
0
    def construct(self, data=None):
        """
        Construct this component
        """
        assert data is None  # because I don't know why it's an argument
        generate_debug_messages \
            = __debug__ and logger.isEnabledFor(logging.DEBUG)
        if self._constructed is True:  #pragma:nocover
            return

        if generate_debug_messages:  #pragma:nocover
            logger.debug("Constructing SOSConstraint %s", self.name)
        timer = ConstructionTimer(self)
        self._constructed = True

        if self._rule is None:
            if self._sosSet is None and self.is_indexed():
                if generate_debug_messages:  #pragma:nocover
                    logger.debug(
                        "  Cannot construct " + self.name +
                        ".  No rule is defined and no SOS sets are defined.")
            else:
                if not self.is_indexed():
                    if self._sosSet is None:
                        if getattr(self._sosVars.index_set(), 'ordered',
                                   False):
                            _sosSet = {None: list(self._sosVars.index_set())}
                        else:
                            _sosSet = {None: set(self._sosVars.index_set())}
                    else:
                        _sosSet = {None: self._sosSet}
                else:
                    _sosSet = self._sosSet

                for index, sosSet in six.iteritems(_sosSet):
                    if generate_debug_messages:  #pragma:nocover
                        logger.debug("  Constructing " + self.name +
                                     " index " + str(index))

                    if self._sosLevel == 2:
                        #
                        # Check that the sets are ordered.
                        #
                        ordered = False
                        if type(
                                sosSet
                        ) is list or sosSet is UnindexedComponent_set or len(
                                sosSet) == 1:
                            ordered = True
                        if hasattr(sosSet, 'ordered') and sosSet.ordered:
                            ordered = True
                        if type(sosSet) is _IndexedOrderedSetData:
                            ordered = True
                        if not ordered:
                            raise ValueError(
                                "Cannot define a SOS over an unordered index.")

                    variables = [self._sosVars[idx] for idx in sosSet]
                    if self._sosWeights is not None:
                        weights = [self._sosWeights[idx] for idx in sosSet]
                    else:
                        weights = None

                    self.add(index, variables, weights)
        else:
            _self_rule = self._rule
            _self_parent = self._parent()
            for index in self._index:
                try:
                    tmp = apply_indexed_rule(self, _self_rule, _self_parent,
                                             index)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "sos constraint %s with index %s:\n%s: %s" %
                        (self.name, str(index), type(err).__name__, err))
                    raise
                if tmp is None:
                    raise ValueError(
                        "SOSConstraint rule returned None instead of SOSConstraint.Skip for index %s"
                        % str(index))
                if type(tmp) is tuple:
                    if tmp is SOSConstraint.Skip:
                        continue
                    # tmp is a tuple of variables, weights
                    self.add(index, tmp[0], tmp[1])
                else:
                    # tmp is a list of variables
                    self.add(index, tmp)
        timer.report()
Пример #2
0
    def construct(self, data=None):
        """
        Initialize this component.

        A parameter is constructed using the initial data or
        the data loaded from an external source.  We first
        set all the values based on self._rule, and then
        allow the data dictionary to overwrite anything.

        Note that we allow an undefined Param value to be
        constructed.  We throw an exception if a user tries
        to use an uninitialized Param.
        """
        if __debug__ and logger.isEnabledFor(logging.DEBUG):  #pragma:nocover
            logger.debug("Constructing Param, name=%s, from data=%s" %
                         (self.name, str(data)))
        #
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        #
        # If the default value is a simple type, we check it versus
        # the domain.
        #
        val = self._default_val
        if val is not _NotValid \
                and type(val) in native_types \
                and val not in self.domain:
            raise ValueError(
                "Default value (%s) is not valid for Param %s domain %s" %
                (str(val), self.name, self.domain.name))
        #
        # Flag that we are in the "during construction" phase
        #
        self._constructed = None
        #
        # Step #1: initialize data from rule value
        #
        if self._rule is not _NotValid:
            self._initialize_from(self._rule)
        #
        # Step #2: allow any user-specified (external) data to override
        # the initialization
        #
        if data is not None:
            try:
                for key, val in iteritems(data):
                    self._setitem_when_not_present(self._validate_index(key),
                                                   val)
            except Exception:
                msg = sys.exc_info()[1]
                if type(data) is not dict:
                    raise ValueError(
                        "Attempting to initialize parameter=%s with data=%s.\n"
                        "\tData type is not a dictionary, and a dictionary is "
                        "expected." % (self.name, str(data)))
                else:
                    raise RuntimeError(
                        "Failed to set value for param=%s, index=%s, value=%s."
                        "\n\tsource error message=%s" %
                        (self.name, str(key), str(val), str(msg)))
        #
        # Flag that things are fully constructed now (and changing an
        # inmutable Param is now an exception).
        #
        self._constructed = True

        # populate all other indices with default data
        # (avoids calling _set_contains on self._index at runtime)
        if self._dense_initialize:
            self.to_dense_data()
        timer.report()